"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.iterateStream = iterateStream;
async function* iterateStream(stream) {
    const contents = [];
    let resolveDataPromise = null;
    const onData = (data) => {
        contents.push(data);
        if (resolveDataPromise) {
            resolveDataPromise();
            resolveDataPromise = null;
        }
    };
    stream.on("data", onData);
    let ended = false;
    const onEnd = () => {
        ended = true;
        if (resolveDataPromise) {
            resolveDataPromise();
            resolveDataPromise = null;
        }
    };
    stream.on("end", onEnd);
    let error = false;
    const onError = (err) => {
        error = err;
        if (resolveDataPromise) {
            resolveDataPromise();
            resolveDataPromise = null;
        }
    };
    stream.on("error", onError);
    try {
        while (!ended || contents.length > 0) {
            if (contents.length === 0) {
                stream.resume();
                await new Promise(resolve => {
                    resolveDataPromise = resolve;
                });
            }
            else {
                stream.pause();
                const data = contents.shift();
                yield data;
            }
            if (error) {
                throw error;
            }
        }
    }
    finally {
        // Clean up listeners
        stream.removeListener("data", onData);
        stream.removeListener("end", onEnd);
        stream.removeListener("error", onError);
    }
}
