"use strict";
/**
 * Stream Utilities
 *
 * Small, cross-platform helpers built on top of the platform stream
 * implementation selected by `./streams` (Node.js or browser).
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.collect = collect;
exports.text = text;
exports.json = json;
exports.bytes = bytes;
exports.fromString = fromString;
exports.fromJSON = fromJSON;
exports.fromBytes = fromBytes;
exports.transform = transform;
exports.filter = filter;
const streams_1 = require("./streams.js");
const shared_1 = require("./shared.js");
// =============================================================================
// High-Level Stream Consumers
// =============================================================================
async function collect(stream) {
    const result = [];
    for await (const chunk of stream) {
        result.push(chunk);
    }
    return result;
}
async function text(stream) {
    const chunks = [];
    let totalLength = 0;
    for await (const chunk of stream) {
        chunks.push(chunk);
        totalLength += chunk.length;
    }
    if (chunks.length === 1) {
        return (0, shared_1.uint8ArrayToString)(chunks[0]);
    }
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (let i = 0, len = chunks.length; i < len; i++) {
        const c = chunks[i];
        result.set(c, offset);
        offset += c.length;
    }
    return (0, shared_1.uint8ArrayToString)(result);
}
async function json(stream) {
    const str = await text(stream);
    return JSON.parse(str);
}
async function bytes(stream) {
    const chunks = [];
    let totalLength = 0;
    for await (const chunk of stream) {
        chunks.push(chunk);
        totalLength += chunk.length;
    }
    if (chunks.length === 1) {
        return chunks[0];
    }
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (let i = 0, len = chunks.length; i < len; i++) {
        const c = chunks[i];
        result.set(c, offset);
        offset += c.length;
    }
    return result;
}
// =============================================================================
// Stream Factory Helpers
// =============================================================================
function fromString(str) {
    return (0, streams_1.createReadableFromArray)([(0, shared_1.stringToUint8Array)(str)], {
        objectMode: false
    });
}
function fromJSON(data) {
    return fromString(JSON.stringify(data));
}
function fromBytes(data) {
    return (0, streams_1.createReadableFromArray)([data], { objectMode: false });
}
function transform(fn) {
    return (0, streams_1.createTransform)(fn);
}
function filter(predicate) {
    return (0, streams_1.createTransform)(async (chunk) => {
        if (await predicate(chunk)) {
            return chunk;
        }
        return undefined;
    }, { objectMode: true });
}
