"use strict";
/**
 * Copyright: (c) Myia SAS 2026.
 * This file and its contents are licensed under the AGPLv3 License.
 * Please see the LICENSE file at the root of this repository
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.StdoutCaptureSession = void 0;
class StdoutCaptureSession {
    constructor() {
        this.stdoutBuf = [];
        this.stderrBuf = [];
        this.stopped = false;
        // Save the raw property value (not a bound wrapper) so stop() can
        // put back exactly the function that was installed, not an identity
        // copy of it. We restore `this` manually on the forward-call below.
        this.origStdout = process.stdout.write;
        this.origStderr = process.stderr.write;
        process.stdout.write = this.makePatched(this.stdoutBuf, this.origStdout, process.stdout);
        process.stderr.write = this.makePatched(this.stderrBuf, this.origStderr, process.stderr);
    }
    stop() {
        if (this.stopped) {
            return { stdout: this.stdoutBuf, stderr: this.stderrBuf };
        }
        this.stopped = true;
        process.stdout.write = this.origStdout;
        process.stderr.write = this.origStderr;
        return { stdout: this.stdoutBuf, stderr: this.stderrBuf };
    }
    makePatched(buf, orig, target) {
        return function patched(chunk, ...rest) {
            buf.push(StdoutCaptureSession.chunkToString(chunk, rest[0]));
            return Reflect.apply(orig, target, [chunk, ...rest]);
        };
    }
    static chunkToString(chunk, encoding) {
        if (typeof chunk === 'string')
            return chunk;
        if (chunk instanceof Uint8Array) {
            const enc = typeof encoding === 'string' ? encoding : 'utf8';
            return Buffer.from(chunk).toString(enc);
        }
        return String(chunk);
    }
}
exports.StdoutCaptureSession = StdoutCaptureSession;
