"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsapStream = void 0;
const stream_1 = require("stream");
const cross_1 = require("./cross");
// produces as promises resolve, not sequentially
class AsapStream extends stream_1.Readable {
    promises;
    finished = false;
    constructor(promises) {
        super({ objectMode: true });
        this.promises = promises;
    }
    _read() {
        if (this.finished)
            return;
        this.finished = true;
        void (async () => {
            const pending = [];
            try {
                if ((0, cross_1.isAsyncIterable)(this.promises)) {
                    const iterator = this.promises[Symbol.asyncIterator]();
                    while (true) {
                        const { value, done } = await iterator.next();
                        if (done)
                            break;
                        const promise = Promise.resolve(value);
                        pending.push(promise);
                        promise.then(x => x !== undefined && this.push(x), e => this.emit('error', e));
                    }
                }
                else {
                    for (const p of this.promises) {
                        const promise = Promise.resolve(p);
                        pending.push(promise);
                        promise.then(x => x !== undefined && this.push(x), e => this.emit('error', e));
                    }
                }
                await Promise.allSettled(pending);
                this.push(null);
            }
            catch (e) {
                this.emit('error', e);
                this.push(null);
            }
        })();
    }
}
exports.AsapStream = AsapStream;
