"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.persist = exports.toJSON = exports.toBuffer = void 0;
const stream_1 = require("stream");
const general = __importStar(require("./general"));
async function toBuffer(stream) {
    return new Promise((resolve, reject) => {
        let ended = false;
        const chunks = [];
        stream.on('data', onData);
        stream.on('end', onEnd);
        stream.on('error', onEnd);
        stream.on('aborted', onAbort);
        stream.on('pause', onPause);
        stream.on('close', onCleanup);
        function onData(chunk) {
            chunks.push(chunk);
        }
        function onEnd(err) {
            if (err)
                return reject(err);
            ended = true;
            resolve(Buffer.concat(chunks));
        }
        function onAbort() {
            if (!ended)
                reject(new Error('Cannot collect message data due to it being closed before ended'));
        }
        function onPause() {
            stream.resume();
        }
        function onCleanup() {
            stream.off('data', onData);
            stream.off('end', onEnd);
            stream.off('error', onEnd);
            stream.off('aborted', onAbort);
            stream.off('pause', onPause);
            stream.off('close', onCleanup);
        }
    });
}
exports.toBuffer = toBuffer;
async function toJSON(stream) {
    const buffer = await toBuffer(stream);
    return JSON.parse(buffer.toString('utf8'));
}
exports.toJSON = toJSON;
function persist(stream) {
    const clone = stream.pipe(new stream_1.PassThrough());
    let buffer;
    clone.pipe = general.wrap(clone.pipe.bind(clone), (pipe, destination, options) => {
        if (!buffer) {
            buffer = toBuffer(clone);
            return pipe(destination, options);
        }
        buffer.then(buffer => {
            destination.write(buffer);
            if ((options === null || options === void 0 ? void 0 : options.end) !== false)
                destination.end();
        });
        return destination;
    });
    return clone;
}
exports.persist = persist;
