/** * @module observable-operators * Functional reactive operators for @ibgib/core-gib ObservableWitness instances. */ import { getUUID, extractErrorMsg } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs"; import { IbGib_V1 } from "@ibgib/ts-gib/dist/V1/types.mjs"; import { GIB, ROOT } from "@ibgib/ts-gib/dist/V1/constants.mjs"; import { ObservableWitness, ObservableCmd } from "./observable-types.mjs"; import { ObserverWitness, Observer } from "../observer/observer-types.mjs"; import { fnObs } from "../observer/observer-helper.mjs"; import { SubscriptionWitness } from "../subscription/subscription-types.mjs"; import { WitnessAny } from "../../../witness/witness-types.mjs"; import { isCommand } from "../../../witness/witness-helper.mjs"; import { isObserver } from "../subject/subject-helper.mjs"; /** * Functional transformation operator that takes a source observable and returns a transformed observable. */ export type ObservableOperator = (source: ObservableWitness) => ObservableWitness; /** * Configuration options for creating a custom operator observable. */ export interface CreateOperatorObservableOpts { source: ObservableWitness; operatorName: string; handleNext: (value: TIn, destination: ObserverWitness) => Promise; handleError?: (err: any, destination: ObserverWitness) => Promise; handleComplete?: (destination: ObserverWitness) => Promise; handleUnsubscribe?: () => void; } /** * Helper factory that creates a lazy ObservableWitness wrapping a source ObservableWitness. * Automatically handles subscription lifecycle, error catching, and downstream delegation. */ export function createOperatorObservable( opts: CreateOperatorObservableOpts ): ObservableWitness { const { source, operatorName, handleNext, handleError, handleComplete, handleUnsubscribe } = opts; const opObservable: ObservableWitness = { ib: `witness observable operator ${operatorName}`, gib: GIB, data: { classname: 'OperatorObservableWitness', operator: operatorName, }, rel8ns: {}, get isCompleteOrErrored(): boolean { return source.isCompleteOrErrored; }, get isComplete(): boolean { return source.isComplete; }, get isErrored(): boolean { return source.isErrored; }, async witness(arg: IbGib_V1): Promise { if (isCommand({ ibGib: arg })) { const cmdData = (arg as any).data; if (cmdData?.cmd === ObservableCmd.subscribe) { const observer = (arg as any).ibGibs?.[0]; if (observer) { return (await opObservable.subscribe(observer)) as any; } } } else if (isObserver({ ibGib: arg })) { return (await opObservable.subscribe(arg as any)) as any; } return ROOT; }, async subscribe(observer: WitnessAny | ObserverWitness): Promise { let destObserver: ObserverWitness; if (isObserver({ ibGib: observer })) { destObserver = observer as ObserverWitness; } else { // Adapt plain witness with visitor pattern destObserver = fnObs({ next: async (val: TOut) => { await (observer as WitnessAny).witness(val); } }); } let isUnsubscribed = false; let sourceSubscription: SubscriptionWitness | undefined; sourceSubscription = await source.subscribe(fnObs({ next: async (val: TIn) => { if (isUnsubscribed) return; try { await handleNext(val, destObserver); } catch (err) { if (destObserver.error) { await destObserver.error(err as any); } else { console.error(`[operator:${operatorName}] Error in handleNext: ${extractErrorMsg(err)}`); } } }, error: async (err: any) => { if (isUnsubscribed) return; if (handleError) { try { await handleError(err, destObserver); } catch (hErr) { if (destObserver.error) { await destObserver.error(hErr as any); } } } else if (destObserver.error) { await destObserver.error(err); } }, complete: async () => { if (isUnsubscribed) return; if (handleComplete) { try { await handleComplete(destObserver); } catch (cErr) { if (destObserver.error) { await destObserver.error(cErr as any); } } } else if (destObserver.complete) { await destObserver.complete(); } } })); const subUuid = getUUID(); const subscription: SubscriptionWitness = { ib: `witness subscription Subscription_V1 ${subUuid}`, gib: GIB, data: { uuid: subUuid, classname: 'Subscription_V1', name: `subscription_${operatorName}`, }, rel8ns: {}, witness: async (arg: IbGib_V1) => { if (arg.ib === 'unsubscribe') { await subscription.unsubscribe(); return ROOT; } return ROOT; }, unsubscribe: async () => { if (isUnsubscribed) return; isUnsubscribed = true; if (handleUnsubscribe) { try { handleUnsubscribe(); } catch (uErr) { console.error(`[operator:${operatorName}] Error in handleUnsubscribe: ${extractErrorMsg(uErr)}`); } } if (sourceSubscription) { await sourceSubscription.unsubscribe(); } }, unsubscribed: async () => isUnsubscribed, }; return subscription; } }; return opObservable; } /** * Filters emissions from the source observable by only passing values that satisfy the predicate. * * @param predicate Synchronous or asynchronous filter function returning a boolean. * @returns Operator function. */ export function filterObs( predicate: (value: T) => boolean | Promise ): ObservableOperator { return (source: ObservableWitness): ObservableWitness => { return createOperatorObservable({ source, operatorName: 'filter', handleNext: async (value, destination) => { const passes = await predicate(value); if (passes && destination.next) { await destination.next(value); } } }); }; } /** * Projects each emission from the source observable to a new IbGib representation. * * @param project Synchronous or asynchronous projection function. * @returns Operator function. */ export function mapObs( project: (value: TIn) => TOut | Promise ): ObservableOperator { return (source: ObservableWitness): ObservableWitness => { return createOperatorObservable({ source, operatorName: 'map', handleNext: async (value, destination) => { const projected = await project(value); if (destination.next) { await destination.next(projected); } } }); }; } /** * Delays emission until the specified time in milliseconds has elapsed since the last emission. * Any emissions occurring during the window cancel prior pending emissions. * * @param ms Delay window in milliseconds. * @returns Operator function. */ export function debounceObs( ms: number ): ObservableOperator { return (source: ObservableWitness): ObservableWitness => { let timer: any = null; let lastValue: T | undefined = undefined; return createOperatorObservable({ source, operatorName: `debounce(${ms}ms)`, handleNext: async (value, destination) => { lastValue = value; if (timer) { clearTimeout(timer); } timer = setTimeout(async () => { timer = null; if (lastValue !== undefined && destination.next) { const valToSend = lastValue; lastValue = undefined; await destination.next(valToSend); } }, ms); }, handleComplete: async (destination) => { if (timer) { clearTimeout(timer); timer = null; if (lastValue !== undefined && destination.next) { const valToSend = lastValue; lastValue = undefined; await destination.next(valToSend); } } if (destination.complete) { await destination.complete(); } }, handleUnsubscribe: () => { if (timer) { clearTimeout(timer); timer = null; } lastValue = undefined; } }); }; } /** * Side-effect operator that intercepts values for logging or external notification * without modifying the stream. * * @param action Synchronous or asynchronous side-effect callback. * @returns Operator function. */ export function tapObs( action: (value: T) => void | Promise ): ObservableOperator { return (source: ObservableWitness): ObservableWitness => { return createOperatorObservable({ source, operatorName: 'tap', handleNext: async (value, destination) => { await action(value); if (destination.next) { await destination.next(value); } } }); }; } /** * Composes a series of operators into a single pipeline. */ export function pipeObs( source: ObservableWitness ): ObservableWitness; export function pipeObs( source: ObservableWitness, op1: ObservableOperator ): ObservableWitness; export function pipeObs( source: ObservableWitness, op1: ObservableOperator, op2: ObservableOperator ): ObservableWitness; export function pipeObs( source: ObservableWitness, op1: ObservableOperator, op2: ObservableOperator, op3: ObservableOperator ): ObservableWitness; export function pipeObs( source: ObservableWitness, op1: ObservableOperator, op2: ObservableOperator, op3: ObservableOperator, op4: ObservableOperator ): ObservableWitness; export function pipeObs( source: ObservableWitness, ...operators: Array> ): ObservableWitness { return operators.reduce((acc, op) => op(acc), source); }