"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pipeWebResponseToNode = exports.readJsonBody = exports.writeJson = void 0;
const stream_1 = require("stream");
const MAX_BODY_SIZE = 10 * 1024 * 1024;
function writeJson(res, statusCode, payload) {
    res.writeHead(statusCode, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(payload));
}
exports.writeJson = writeJson;
function readJsonBody(req) {
    return new Promise((resolve, reject) => {
        const chunks = [];
        let total = 0;
        let settled = false;
        const resolveOnce = (payload) => {
            if (!settled) {
                settled = true;
                resolve(payload);
            }
        };
        const rejectOnce = (error) => {
            if (!settled) {
                settled = true;
                reject(error);
            }
        };
        req.on('data', (chunk) => {
            total += chunk.length;
            if (total > MAX_BODY_SIZE) {
                req.pause();
                rejectOnce(new Error('Request body too large (max 10MB)'));
                return;
            }
            chunks.push(chunk);
        });
        req.on('end', () => {
            const raw = Buffer.concat(chunks).toString('utf8').trim();
            if (!raw) {
                resolveOnce({});
                return;
            }
            try {
                resolveOnce(JSON.parse(raw));
            }
            catch {
                rejectOnce(new Error('Invalid JSON in request body'));
            }
        });
        req.on('error', (error) => {
            rejectOnce(error instanceof Error ? error : new Error(String(error)));
        });
    });
}
exports.readJsonBody = readJsonBody;
async function pipeWebResponseToNode(response, res) {
    res.statusCode = response.status;
    response.headers.forEach((value, key) => {
        res.setHeader(key, value);
    });
    if (!response.body) {
        res.end();
        return;
    }
    const nodeStream = stream_1.Readable.fromWeb(response.body);
    await new Promise((resolve, reject) => {
        nodeStream.on('error', reject);
        nodeStream.on('end', resolve);
        nodeStream.pipe(res);
    });
}
exports.pipeWebResponseToNode = pipeWebResponseToNode;
//# sourceMappingURL=http-helpers.js.map