Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/future.
Something went wrong. Try again.
future from.ts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268import 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<T, TReturn = T, TNext = unknown>( operation: PromiseLike<T>,): ReturnType<typeof fromPromise<T>>;export function from<T, TReturn = T, TNext = unknown>( operation: ReadableStream<T>,): ReturnType<typeof fromStream<T>>;export function from<T, TReturn = T, TNext = unknown>( operation: AsyncIterable<T> | Iterable<T | PromiseLike<T>>,): ReturnType<typeof fromIterable<T, TReturn>>;export function from<T, TReturn = T, TNext = unknown>( operation: Iterable<T | PromiseLike<T>>,): ReturnType<typeof fromBuiltinIterable<T>>;export function from<T, TReturn = T, TNext = unknown>( operation: | AsyncIterator<T, TReturn, TNext> | Iterator<T | PromiseLike<T>, TReturn | PromiseLike<TReturn>, TNext>,): ReturnType<typeof fromIterator<T, TReturn>>;export function from<T, TReturn = T, TNext = unknown>( operation: FutureFromOperation<T, TReturn, TNext>,): ReturnType<typeof fromOperation<T, TReturn, TNext>>;export function from<T, TReturn = T, TNext = unknown>( operation: Future<T, TReturn, TNext>,): Future<T, TReturn, TNext>;export function from<T, TReturn = T, TNext = unknown>( operation: T,): ReturnType<typeof of<T>>;export function from<T, TReturn = T, TNext = unknown>( operation: | FutureFromOperation<T, TReturn, TNext> | Future<T, TReturn, TNext> | ReadableStream<T> | AsyncIterable<T> | Iterable<T | PromiseLike<T>> | Iterator<T | PromiseLike<T>, TReturn | PromiseLike<TReturn>, TNext> | PromiseLike<T> | T,) { // Handle Future instances directly if (is(operation)) { return operation as Future<T, TReturn, TNext>; }
// 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<T, TReturn, TNext>); }
return of(operation);}
export function of<T>(value: T): Future<T, T> { return new Future<T, T>(async function* (_, stack) { const disposable = useDisposableStack(value, stack); yield disposable; return disposable; });}
export function fromPromise<T>(promise: PromiseLike<T>): Future<T, T> { return new Future<T, T>(async function* (_, stack) { const disposable = useDisposableStack(promise, stack); yield disposable; return disposable; });}
export function fromOperation<T, TReturn = T, TNext = unknown>( operation: FutureFromOperation<T, TReturn, TNext>,): Future<T, TReturn, TNext> { return new Future<T, TReturn, TNext>( 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<T | PromiseLike<T>>; return result as TReturn; }
// Handle promise-like result or single value yield result; return result as TReturn; }, );}
export function fromIterable<T, TReturn = T>( iterable: AsyncIterable<T> | Iterable<T | PromiseLike<T>>,): Future<T, TReturn> { return new Future<T, TReturn>(async function* (_, stack) { const disposable = useDisposableStack(iterable, stack); return yield* disposable; });}
export function fromBuiltinIterable<T>( iterable: Iterable<T | PromiseLike<T>>,): Future<T, Iterable<T | PromiseLike<T>>> { return new Future<T, Iterable<T | PromiseLike<T>>>(async function* (_, stack) { const disposable = useDisposableStack(iterable, stack); yield* disposable; return disposable; });}
export function fromIterator<T, TReturn = T, TNext = unknown>( iterator: | AsyncIterator<T, TReturn, TNext> | Iterator<T | PromiseLike<T>, TReturn | PromiseLike<TReturn>, TNext>,): Future<T, TReturn> { return new Future<T, TReturn, TNext>(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<Uint8Array>({ * 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<T>(stream: ReadableStream<T>): Future<T, undefined> { return new Future<T, undefined>(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<T, TReturn = unknown, TNext = unknown>( value: unknown,): value is Future<T, TReturn, TNext> { return value instanceof Future;}