"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.spawnPromise = void 0;
/* eslint-disable no-console */
const node_child_process_1 = require("node:child_process");
const console_log_colors_1 = require("console-log-colors");
const spawnPromise = (path, args, options) => new Promise((resolve, reject) => {
    const all = [];
    const { logCommand = true, throwOnFail = false, logData = true, logError = true } = options ?? {};
    const cd = (0, node_child_process_1.spawn)(path, args, options);
    const pid = cd.pid;
    cd.stdout.on("data", (data) => {
        data = data.toString("utf8");
        all.push(data);
    });
    cd.stderr.on("data", (data) => {
        data = data.toString("utf8");
        all.push(console_log_colors_1.color.red(data));
    });
    cd.on("error", (error) => {
        const errorText = console_log_colors_1.color.red(error.stack ?? error.toString());
        all.push(error.stack ?? error.toString());
        if (logData || logError) {
            console.error(errorText);
        }
        reject(error);
    });
    cd.on("close", (status) => {
        if (status > 0) {
            if (logError) {
                console.error(all);
            }
            if (throwOnFail) {
                reject(new Error(all.join("\n")));
                return;
            }
        }
        if (logCommand) {
            if (options.cwd) {
                console.log(`Spawn: ${path} in ${options.cwd} ${JSON.stringify(args, undefined, 2)}`);
            }
            else {
                console.log(`Spawn: ${path} ${JSON.stringify(args, undefined, 2)}`);
            }
            if (logData) {
                console.log(all.join("\n"));
            }
        }
        resolve({
            get all() {
                return all.join("\n");
            },
            pid,
            status
        });
    });
});
exports.spawnPromise = spawnPromise;
//# sourceMappingURL=spawnPromise.js.map