|
| 1 | +import {isReadableStream} from 'is-stream'; |
| 2 | + |
| 3 | +export const getAsyncIterable = stream => { |
| 4 | + if (isReadableStream(stream, {checkOpen: false})) { |
| 5 | + return getStreamIterable(stream); |
| 6 | + } |
| 7 | + |
| 8 | + if (typeof stream?.[Symbol.asyncIterator] !== 'function') { |
| 9 | + throw new TypeError('The first argument must be a Readable, a ReadableStream, or an async iterable.'); |
| 10 | + } |
| 11 | + |
| 12 | + return stream; |
| 13 | +}; |
| 14 | + |
| 15 | +// The default iterable for Node.js streams does not allow for multiple readers at once, so we re-implement it |
| 16 | +const getStreamIterable = async function * (stream) { |
| 17 | + if (nodeImports === undefined) { |
| 18 | + await loadNodeImports(); |
| 19 | + } |
| 20 | + |
| 21 | + const controller = new AbortController(); |
| 22 | + const state = {}; |
| 23 | + handleStreamEnd(stream, controller, state); |
| 24 | + |
| 25 | + try { |
| 26 | + for await (const [chunk] of nodeImports.events.on(stream, 'data', { |
| 27 | + signal: controller.signal, |
| 28 | + highWatermark: stream.readableHighWaterMark, |
| 29 | + })) { |
| 30 | + yield chunk; |
| 31 | + } |
| 32 | + } catch (error) { |
| 33 | + // Stream failure, for example due to `stream.destroy(error)` |
| 34 | + if (state.error !== undefined) { |
| 35 | + throw state.error; |
| 36 | + // `error` event directly emitted on stream |
| 37 | + } else if (!controller.signal.aborted) { |
| 38 | + throw error; |
| 39 | + // Otherwise, stream completed successfully |
| 40 | + } |
| 41 | + // The `finally` block also runs when the caller throws, for example due to the `maxBuffer` option |
| 42 | + } finally { |
| 43 | + stream.destroy(); |
| 44 | + } |
| 45 | +}; |
| 46 | + |
| 47 | +const handleStreamEnd = async (stream, controller, state) => { |
| 48 | + try { |
| 49 | + await nodeImports.streamPromises.finished(stream, {cleanup: true, readable: true, writable: false, error: false}); |
| 50 | + } catch (error) { |
| 51 | + state.error = error; |
| 52 | + } finally { |
| 53 | + controller.abort(); |
| 54 | + } |
| 55 | +}; |
| 56 | + |
| 57 | +// Use dynamic imports to support browsers |
| 58 | +const loadNodeImports = async () => { |
| 59 | + const [events, streamPromises] = await Promise.all([ |
| 60 | + import('node:events'), |
| 61 | + import('node:stream/promises'), |
| 62 | + ]); |
| 63 | + nodeImports = {events, streamPromises}; |
| 64 | +}; |
| 65 | + |
| 66 | +let nodeImports; |
0 commit comments