import type { FutureFromOperation } from "./types.ts"; import { useDisposableStack } from "./disposal.ts"; import { isAsyncGenerator, isAsyncIterable, isAsyncIterator, isBuiltinIterable, isGenerator, isIterable, isIterator, isPromiseLike, } from "./_utils.ts"; import { Future } from "./future.ts"; /** * Wraps a value, Promise, iterable, stream, or operation factory in a Future. * * A factory runs when the Future is consumed. It receives an AbortController * and an AsyncDisposableStack. Pass the signal to cancellable I/O and register * only resources whose cleanup belongs to this Future. * * An existing Promise may already be running. Wrapping it does not make its * producer pausable or connect cancellation to that producer. Likewise, an * existing iterator or stream keeps its own consumption state. * * @example * ```typescript * const work = from(async function* (abort) { * yield "requesting"; * const response = await fetch("https://example.com/data.json", { * signal: abort.signal, * }); * if (!response.ok) throw new Error(`HTTP ${response.status}`); * return await response.json(); * }); * * const result = await work.toPromise(); * ``` * * Yield values are intermediate results; the generator's return value is the * final result. Use a factory that creates fresh work when repeat execution is * required. Resetting a wrapper around an existing Promise cannot rerun its I/O. * * @param operation - The input to consume or the factory to invoke. * @returns A Future that exposes the input through the generator contract. */ export function from( operation: PromiseLike, ): ReturnType>; export function from( operation: ReadableStream, ): ReturnType>; export function from( operation: AsyncIterable | Iterable>, ): ReturnType>; export function from( operation: Iterable>, ): ReturnType>; export function from( operation: | AsyncIterator | Iterator, TReturn | PromiseLike, TNext>, ): ReturnType>; export function from( operation: FutureFromOperation, ): ReturnType>; export function from( operation: Future, ): Future; export function from( operation: T, ): ReturnType>; export function from( operation: | FutureFromOperation | Future | ReadableStream | AsyncIterable | Iterable> | Iterator, TReturn | PromiseLike, TNext> | PromiseLike | T, ) { // Handle Future instances directly if (is(operation)) { return operation as Future; } // Handle ReadableStreams (common in web APIs) if (operation instanceof ReadableStream) { return fromStream(operation); } if (isPromiseLike(operation)) { return fromPromise(operation); } if (isAsyncIterator(operation) || isIterator(operation)) { return fromIterator(operation); } // We skip arrays and strings as they are built-in iterables, but never return a value directly, so we await them. if ( (isAsyncIterable(operation) || isIterable(operation)) && !isBuiltinIterable(operation) ) { return fromIterable(operation); } if (isBuiltinIterable(operation)) { return fromBuiltinIterable(operation); } if (typeof operation === "function") { return fromOperation(operation as FutureFromOperation); } return of(operation); } export function of(value: T): Future { return new Future(async function* (_, stack) { const disposable = useDisposableStack(value, stack); yield disposable; return disposable; }); } export function fromPromise(promise: PromiseLike): Future { return new Future(async function* (_, stack) { const disposable = useDisposableStack(promise, stack); yield disposable; return disposable; }); } export function fromOperation( operation: FutureFromOperation, ): Future { return new Future( async function* (abort, stack) { const result = operation(abort, stack); if (isAsyncGenerator(result) || isGenerator(result)) { // Handle async iterable or iterable result return yield* result; } if (isBuiltinIterable(result)) { // Handle built-in iterable result yield* result as Iterable>; return result as TReturn; } // Handle promise-like result or single value yield result; return result as TReturn; }, ); } export function fromIterable( iterable: AsyncIterable | Iterable>, ): Future { return new Future(async function* (_, stack) { const disposable = useDisposableStack(iterable, stack); return yield* disposable; }); } export function fromBuiltinIterable( iterable: Iterable>, ): Future>> { return new Future>>(async function* (_, stack) { const disposable = useDisposableStack(iterable, stack); yield* disposable; return disposable; }); } export function fromIterator( iterator: | AsyncIterator | Iterator, TReturn | PromiseLike, TNext>, ): Future { return new Future(async function* (_, stack) { const _iterator = useDisposableStack(iterator, stack); let iteratorResult = await _iterator.next(); while (!iteratorResult.done) { iteratorResult = await _iterator.next( yield iteratorResult.value ); } return iteratorResult.value; }); } /** * Creates a `Future` from a readable stream. * * This method allows you to process data from a `ReadableStream` as it becomes available, * yielding each chunk of data and providing full control over the stream's lifecycle. * * @param stream - The `ReadableStream` to convert into a `Future`. * @returns A `Future` that yields chunks of data from the stream. * * @example * ```typescript * const response = await fetch('https://api.example.com/large-file'); * const future = Future.fromStream(response.body!); * * for await (const chunk of future) { * console.log(chunk); // Process each chunk of data * } * ``` * * @example * ```typescript * const stream = new ReadableStream({ * pull(controller) { * controller.enqueue(new Uint8Array([1, 2, 3])); * controller.close(); * } * }); * const future = Future.fromStream(stream); * for await (const chunk of future) { * console.log(chunk); // Logs Uint8Array([1, 2, 3]) * } * ``` */ export function fromStream(stream: ReadableStream): Future { return new Future(async function* (_, stack) { const _stream = useDisposableStack(stream, stack); const reader = _stream.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) break; // Yield each chunk of data yield value; } } catch (error) { reader.cancel(error); throw error; } finally { reader.releaseLock(); } return undefined; }); } /** * Creates a new `Future` instance from an async generator function. * @param value - A function that returns an async generator to define the asynchronous task. * @returns A new `Future` instance. */ export function is( value: unknown, ): value is Future { return value instanceof Future; }