// Like graphql-js's internal `mapAsyncIterable` (which it does not export): // returns an async generator of `iterable`'s values passed through `fn`, one // at a time. It closes `iterable` when it finishes, when `fn` throws, or when // the consumer calls `return()`, `throw()`, or `[Symbol.asyncDispose]()` on // it. // // This is a hand-written object rather than an `async function*` so that // closing it reaches `iterable` even if `next()` was never called; calling // `return()` on an async generator that hasn't started doesn't run its body // at all, so nothing would close `iterable`. export function mapAsyncIterable( iterable: AsyncIterable, fn: (value: T) => Promise, ): AsyncGenerator { const iterator = iterable[Symbol.asyncIterator](); const mapped: AsyncGenerator = { [Symbol.asyncIterator]: () => mapped, [Symbol.asyncDispose]: () => mapped.return().then(() => undefined), async next() { const result = await iterator.next(); if (result.done) { return result; } return { done: false, value: await fn(result.value) }; }, async return() { await iterator.return?.(); return { done: true, value: undefined }; }, async throw(error: unknown) { await iterator.return?.(); throw error; }, }; return mapped; }