/** * Utility helpers connect Observable pipelines with Web Streams and foreign * operator ecosystems. * * Most application code will use these indirectly through `pipe()`, * `fromStreamPair()`, or `fromObservableOperator()`. They live here so the * adapter logic stays reusable and the public helpers stay small. * * @module */ import type { ObservableInteropInputLike, ObservableOperatorInterop, ObservableOperatorInteropOptions, TransformFunctionOptions, StreamPair, TransformStreamOptions, } from "./_types.ts"; import type { CreateOperatorOptions, Operator } from "./_types.ts"; import { ObservableError } from "../error.ts"; import { Observable } from "../observable.ts"; /** * Returns `true` when operator options provide a `TransformStream` factory. */ export function isTransformStreamOptions( options: CreateOperatorOptions, ): options is TransformStreamOptions { return "stream" in options; } /** * Returns `true` when operator options provide a custom transform callback. */ export function isTransformFunctionOptions( options: CreateOperatorOptions, ): options is TransformFunctionOptions { return "transform" in options; } /** * Applies one operator to a stream and converts setup failures into injected * error values. */ export function applyOperator( input: ReadableStream, // deno-lint-ignore no-explicit-any operator: Operator, { message = `pipe:operator` } = {}, ): ReadableStream { try { const result = operator(input); return result; } catch (err) { return input.pipeThrough(injectError(err, message)); } } /** * Converts an iterable or async iterable into a `ReadableStream`. */ export function toStream( iterable: Iterable | AsyncIterable, ): ReadableStream { // Check if it's an async iterable const isAsync = typeof (iterable as AsyncIterable)[Symbol.asyncIterator] === "function"; return new ReadableStream({ async start(controller) { try { if (isAsync) { for await (const item of iterable as AsyncIterable) { controller.enqueue(item); } } else { for (const item of iterable as Iterable) { controller.enqueue(item); } } try { controller.close(); } catch { // Downstream may already be closed or errored. } } catch (err) { try { controller.enqueue(ObservableError.from(err, "toStream")); controller.close(); } catch { // If downstream is already unavailable, the original failure has // already decided the stream outcome. Do not surface a second error. } } }, }); } /** * Adapts a readable/writable stream pair into an Observable operator. * * Some platform transforms, such as `CompressionStream`, expose a writable side * and a readable side without being created through this library's operator * builders. This helper turns that pair into a normal `Operator` so it can be * used inside `pipe()` like any built-in operator. * * A fresh pair is created for each operator application. That preserves the * cold semantics of the surrounding Observable pipeline and avoids reusing a * consumed stream pair across subscriptions. * * @typeParam TIn - Chunk type written into the pair * @typeParam TOut - Chunk type read from the pair * @param createPair - Factory that returns a fresh readable/writable pair * @returns An operator that pipes input through the created pair * * @example * ```ts * const gzip = fromStreamPair( * () => new CompressionStream('gzip') * ); * ``` */ export function fromStreamPair( createPair: () => StreamPair, ): Operator { return (source) => source.pipeThrough(createPair()); } /** * Wraps a `ReadableStream` as an Observable so foreign Observable-style * operators can subscribe to it directly. * * This avoids first converting the stream into an async-iterable Observable via * `Observable.from()`, which would add an extra adaptation layer before the * foreign operator even starts running. */ export function streamAsObservable(stream: ReadableStream): Observable { return new Observable((observer) => { const reader = stream.getReader(); let cancelled = false; void (async () => { try { while (!cancelled && !observer.closed) { const { done, value } = await reader.read(); if (done) { break; } observer.next(value); } if (!cancelled && !observer.closed) { observer.complete(); } } catch (err) { if (!cancelled && !observer.closed) { observer.error(err); } } finally { try { reader.releaseLock(); } catch { // Releasing the reader is best-effort during teardown. } } })(); return () => { cancelled = true; void reader.cancel(); }; }); } /** * Returns true when a value exposes a direct `subscribe()` method. * * Many Observable libraries return subscribable objects that are usable without * first going through this library's `Observable.from()`. Detecting that shape * lets interop stay direct for outputs such as RxJS Observables. */ function hasSubscribe( input: ObservableInteropInputLike | unknown, ): input is { subscribe(observer: { next?(value: T): void; error?(error: unknown): void; complete?(): void; }): { unsubscribe?(): void } | void; } { return typeof input === "object" && input !== null && typeof (input as { subscribe?: unknown }).subscribe === "function"; } /** * Subscribes to an Observable-like output and exposes it as a ReadableStream. * * Foreign operators are allowed to return either a normal `Observable.from()` * input or a direct subscribable from another Observable implementation. * Converting the result with a direct subscription avoids the extra * async-generator and stream layers that `pull(...)+toStream()` would add. * * If the foreign subscribable throws during subscription setup, this bridge * converts that failure into an `ObservableError` value so downstream * consumers see the same buffered-error behavior as the rest of this library. */ export function observableInputToStream( input: ObservableInteropInputLike, errorContext: string, ): ReadableStream { let subscription: { unsubscribe?(): void } | void; let settled = false; return new ReadableStream({ start(controller) { const source = hasSubscribe(input) ? input : Observable.from(input); try { const startedSubscription = source.subscribe({ next(value) { try { controller.enqueue(value); } catch { // Downstream cancellation already decided the stream outcome. } }, error(error) { settled = true; try { controller.enqueue(ObservableError.from(error, errorContext)); controller.close(); } catch { // Downstream cancellation already decided the stream outcome. } finally { subscription = undefined; } }, complete() { settled = true; try { controller.close(); } catch { // Downstream cancellation already decided the stream outcome. } finally { subscription = undefined; } }, }); subscription = settled ? undefined : startedSubscription; } catch (error) { settled = true; try { controller.enqueue(ObservableError.from(error, errorContext)); controller.close(); } catch { // Downstream cancellation already decided the stream outcome. } finally { subscription = undefined; } } }, cancel() { subscription?.unsubscribe?.(); subscription = undefined; }, }); } /** * Adapts a foreign Observable-style operator into a stream operator. * * Libraries such as RxJS model operators as functions from one Observable-like * source to another Observable-like result. This helper bridges that shape into * this library's `Operator` contract by: * * 1. wrapping the input stream as an Observable-like source * 2. calling the foreign operator * 3. converting the resulting Observable-like output back into a stream * * The result keeps this library's buffered error behavior by converting the * foreign output into a `ReadableStream` that enqueues wrapped * `ObservableError` values instead of failing the readable side outright. * That includes synchronous setup failures when the foreign subscribable * throws from its `subscribe()` implementation. * * @typeParam TIn - Value type accepted by the foreign operator * @typeParam TOut - Value type produced by the foreign operator * @param operator - Foreign operator function to adapt * @returns An operator compatible with this library's `pipe()` * * @example * ```ts * const foreignTakeOne = fromObservableOperator((source) => * rxTake(1)(source) * , { sourceAdapter: (source) => rxFrom(source) }); * ``` */ export function fromObservableOperator>( operator: ObservableOperatorInterop, options?: ObservableOperatorInteropOptions, ): Operator { return (source) => { const observableSource = streamAsObservable(source); const foreignSource = options?.sourceAdapter ? options.sourceAdapter(observableSource) : observableSource as unknown as TSource; const output = operator(foreignSource) as ObservableInteropInputLike; return observableInputToStream( output, options?.errorContext ?? "operator:fromObservableOperator:output", ); }; } /** * Creates a TransformStream that injects an error at the start and passes through all original data. * * ## What this does * Think of this as creating a "tee" in your stream pipeline where an error gets injected at the * beginning, but all your original data continues to flow through unchanged. It's like adding * a warning sign at the start of a conveyor belt while keeping everything else moving. * * ## Why you need this * When operator setup fails, you want to signal the error but not lose all your data. This creates * a transform that does exactly that - it marks the problem but preserves your stream's content. * * ## How it works * The transform immediately outputs the error when the stream starts, then passes every chunk * from the source unchanged. Your downstream consumers see the error first, then all the data. * * ## When to use this * - **Operator setup failures**: When building an operator fails but the source data is still valid * - **Warning injection**: When you want to flag a problem but continue processing * - **Error preservation**: When you need both error information and data preservation * * ## What the output looks like * ```typescript * // Original stream: [1, 2, 3, 4, 5] * // After error injection: [ObservableError("setup failed"), 1, 2, 3, 4, 5] * // The error appears first, then all original data flows through * ``` * * @param error The error to inject at the start of the stream * @param context Context string for error reporting (where it happened) * * @returns A TransformStream that injects the error and passes through data * * @example * ```typescript * // Handle operator setup failure * function createSafeOperator( * operatorBuilder: () => Operator, * context: string * ): Operator { * return (source: ReadableStream) => { * try { * return operatorBuilder()(source); * } catch (err) { * return source.pipeThrough( * createErrorInjectionTransform(err, context) * ); * } * }; * } * ``` * * @example * ```typescript * // Add warning to stream without breaking it * const warningStream = dataStream.pipeThrough( * createErrorInjectionTransform( * new Error("Data quality issue detected"), * "data-validation" * ) * ); * * // Consumers will see: [Error, ...originalData] * ``` */ export function injectError( error?: Error | Error[] | unknown | unknown[], context?: string, value?: unknown, ): TransformStream { return new TransformStream({ start(controller) { // Inject the error as the first item in the stream controller.enqueue(ObservableError.from(error, context, value)); }, }); }