import child_process from 'child_process';
import { CustomError } from 'ts-custom-error';
export class ChildProcessError extends CustomError {
    constructor(data) {
        super(data.error.message);
        this.data = data;
    }
}
export function exec(list) {
    const command = list[0];
    const args = list.slice(1);
    return new Promise(function (resolve, reject) {
        const child = child_process.spawn(command, args);
        const stdout = [];
        child.stdout.setEncoding('utf-8');
        child.stdout.on('data', data => {
            stdout.push(data);
        });
        const stderr = [];
        child.stderr.setEncoding('utf-8');
        child.stderr.on('data', data => {
            stderr.push(data);
        });
        child.on('error', error => {
            reject(new ChildProcessError({
                error,
                stdout: stdout.join(''),
                stderr: stderr.join(''),
            }));
        });
        child.on('close', () => {
            resolve(stdout.join('').trim() || stderr.join(''));
        });
    });
}
export function spawn(args, onOutput) {
    const command = args.shift();
    return new Promise((res, rej) => {
        const child = child_process.spawn(command, args);
        child.stderr.setEncoding('utf-8');
        let error = false;
        child.stderr.on('data', text => {
            error = true;
            onOutput?.({ form: 'fall', text });
        });
        child.stdout.setEncoding('utf-8');
        child.stdout.on('data', text => {
            onOutput?.({ form: 'rise', text });
        });
        child.on('error', rej);
        child.on('close', () => {
            if (error) {
                rej(new Error(`Process error.`));
            }
            else {
                res(undefined);
            }
        });
    });
}
//# sourceMappingURL=process.js.map