"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("@pnpm/logger");
const byline = require("byline");
const spawn = require("cross-spawn");
const path = require("path");
const PATH = require("path-name");
const loggers_1 = require("./loggers");
const scriptLogger = logger_1.default('run_script');
function runScript(command, args, opts) {
    opts = Object.assign({ log: (() => { }) }, opts); // tslint:disable-line:no-empty
    args = args || [];
    const script = `${command}${args.length ? ' ' + args.join(' ') : ''}`;
    if (script)
        scriptLogger.debug(`runscript ${script}`);
    if (!command)
        return Promise.resolve();
    return new Promise((resolve, reject) => {
        const proc = spawn(command, args, {
            cwd: opts.cwd,
            env: createEnv(opts),
        });
        const scriptName = args[args.length - 1];
        proc.on('error', reject);
        byline(proc.stdout).on('data', (line) => loggers_1.lifecycleLogger.info({
            line: line.toString(),
            pkgId: opts.pkgId,
            script: scriptName,
        }));
        byline(proc.stderr).on('data', (line) => loggers_1.lifecycleLogger.error({
            line: line.toString(),
            pkgId: opts.pkgId,
            script: scriptName,
        }));
        proc.on('close', (code) => {
            if (code > 0) {
                loggers_1.lifecycleLogger.error({
                    exitCode: code,
                    pkgId: opts.pkgId,
                    script: scriptName,
                });
                return reject(new Error('Exit code ' + code));
            }
            loggers_1.lifecycleLogger.info({
                exitCode: code,
                pkgId: opts.pkgId,
                script: scriptName,
            });
            return resolve();
        });
    });
}
exports.default = runScript;
function createEnv(opts) {
    const env = Object.create(process.env);
    env[PATH] = [
        path.join(opts.cwd, 'node_modules', '.bin'),
        path.dirname(process.execPath),
        process.env[PATH],
    ].join(path.delimiter);
    if (opts.userAgent) {
        env['npm_config_user_agent'] = opts.userAgent; // tslint:disable-line:no-string-literal
    }
    return env;
}
//# sourceMappingURL=runScript.js.map