"use strict";
const debug_1 = require('./debug');
const debug = debug_1.default('pnpm:run_script');
const path = require('path');
const byline = require('byline');
const spawn = require('cross-spawn');
const PATH = require('path-name');
function runScript(command, args, opts) {
    opts = Object.assign({ log: (() => { }) }, opts);
    args = args || [];
    const log = opts.log;
    const script = `${command}${args.length ? ' ' + args.join(' ') : ''}`;
    if (script)
        debug('runscript', script);
    if (!command)
        return Promise.resolve();
    return new Promise((resolve, reject) => {
        const proc = spawn(command, args, {
            cwd: opts.cwd,
            env: createEnv(opts.cwd)
        });
        log('stdout', '$ ' + script);
        proc.on('error', reject);
        byline(proc.stdout).on('data', (line) => log('stdout', line));
        byline(proc.stderr).on('data', (line) => log('stderr', line));
        proc.on('close', (code) => {
            if (code > 0)
                return reject(new Error('Exit code ' + code));
            return resolve();
        });
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = runScript;
function sync(command, args, opts) {
    opts = Object.assign({}, opts);
    return spawn.sync(command, args, Object.assign({}, opts, {
        env: createEnv(opts.cwd)
    }));
}
exports.sync = sync;
function createEnv(cwd) {
    const env = Object.create(process.env);
    env[PATH] = [
        path.join(cwd, 'node_modules', '.bin'),
        path.dirname(process.execPath),
        process.env[PATH]
    ].join(path.delimiter);
    env['NODE_PRESERVE_SYMLINKS'] = '1';
    return env;
}
//# sourceMappingURL=runScript.js.map