"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pipeIterableToSink = pipeIterableToSink;
exports.collect = collect;
const shared_1 = require("../../stream/shared.js");
const event_utils_1 = require("../../stream/internal/event-utils.js");
const type_guards_1 = require("../../stream/internal/type-guards.js");
async function pipeIterableToSink(iterable, sink) {
    if ((0, type_guards_1.isWritableStream)(sink)) {
        const writer = sink.getWriter();
        try {
            for await (const chunk of iterable) {
                await writer.write(chunk);
            }
            await writer.close();
        }
        finally {
            try {
                writer.releaseLock();
            }
            catch {
                // Ignore
            }
        }
        return;
    }
    // Node-style Writable
    for await (const chunk of iterable) {
        const ok = sink.write(chunk);
        if (ok === false && typeof sink.once === "function") {
            await (0, event_utils_1.onceEvent)(sink, "drain");
        }
    }
    if (typeof sink.end === "function") {
        sink.end();
    }
    if (typeof sink.once === "function") {
        await Promise.race([(0, event_utils_1.onceEvent)(sink, "finish"), (0, event_utils_1.onceEvent)(sink, "close")]);
    }
}
async function collect(iterable) {
    const chunks = [];
    let total = 0;
    for await (const chunk of iterable) {
        chunks.push(chunk);
        total += chunk.length;
    }
    return (0, shared_1.concatUint8Arrays)(chunks, total);
}
