"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.startSaving = startSaving;
const console_1 = require("console");
const stream_1 = require("stream");
const path_1 = require("path");
const streamroller_1 = require("streamroller");
function startSaving(baseDir) {
    // Create a file to save combined stdout and stderr output
    const outFileName = `out.log`;
    const stream = new streamroller_1.RollingFileStream((0, path_1.join)(baseDir, outFileName), 10000000, 10);
    // Create a transform stream factory that adds timestamps
    const createTimestampTransform = () => new stream_1.Transform({
        transform(chunk, encoding, callback) {
            try {
                const lines = chunk.toString().split('\n');
                const timestampedLines = lines.map((line) => {
                    if (line.trim()) {
                        const timestamp = new Date().toISOString();
                        return `${timestamp} - ${line}`;
                    }
                    return line;
                });
                callback(null, timestampedLines.join('\n'));
            }
            catch (err) {
                // Swallow any error silently and pass through the original chunk
                callback(null, chunk);
            }
        },
    });
    // Create passthroughs that write to stdout, stderr, and the output file
    const outPass = new stream_1.PassThrough();
    outPass.pipe(process.stdout);
    outPass.pipe(createTimestampTransform()).pipe(stream);
    const errPass = new stream_1.PassThrough();
    errPass.pipe(process.stderr);
    errPass.pipe(createTimestampTransform()).pipe(stream);
    // Monkey patch the global console with a new one that uses our passthroughs
    console = new console_1.Console({ stdout: outPass, stderr: errPass }); // eslint-disable-line no-global-assign
}
//# sourceMappingURL=saveConsoleOutput.js.map