const COMMAND_OUTPUT_EVENT_FLUSH_MS = 80;
const MAX_COMMAND_OUTPUT_EVENT_CHARS = 16 * 1024;
export function createOutputEventCollector(input) {
    const onOutput = input.onOutput;
    const pendingChunks = [];
    let pendingCharCount = 0;
    let sequence = 0;
    let flushTimer;
    const clearFlushTimer = () => {
        if (!flushTimer)
            return;
        clearTimeout(flushTimer);
        flushTimer = undefined;
    };
    const flush = () => {
        if (!onOutput || pendingChunks.length === 0)
            return;
        clearFlushTimer();
        sequence += 1;
        const streams = new Set(pendingChunks.map((chunk) => chunk.stream));
        const stream = streams.size === 1 ? pendingChunks[0]?.stream ?? "mixed" : "mixed";
        const text = pendingChunks.map((chunk) => chunk.text).join("");
        pendingChunks.length = 0;
        pendingCharCount = 0;
        onOutput({
            stream,
            text,
            sequence,
            cwd: input.cwd,
            commandLineCount: input.commandLineCount,
            ...(input.commandFilePath
                ? { commandFilePath: input.commandFilePath }
                : {}),
        });
    };
    return {
        push(stream, text) {
            if (!onOutput || !text)
                return;
            pendingChunks.push({ stream, text });
            pendingCharCount += text.length;
            if (pendingCharCount >= MAX_COMMAND_OUTPUT_EVENT_CHARS) {
                flush();
                return;
            }
            if (!flushTimer) {
                flushTimer = setTimeout(flush, COMMAND_OUTPUT_EVENT_FLUSH_MS);
                flushTimer.unref?.();
            }
        },
        close() {
            flush();
            clearFlushTimer();
        },
    };
}
