"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const lifecycle = require("npm-lifecycle");
const path = require("path");
const exists = require("path-exists");
const readPackageJsonCB = require("read-package-json");
const promisify = require("util.promisify");
const logger_1 = require("./logger");
const readPackageJson = promisify(readPackageJsonCB);
function noop() { } // tslint:disable-line:no-empty
function runPostinstallHooks(opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const pkg = yield readPackageJson(path.join(opts.pkgRoot, 'package.json'));
        const scripts = pkg && pkg.scripts || {};
        if (!scripts.install) {
            yield checkBindingGyp(opts.pkgRoot, scripts);
        }
        if (scripts.preinstall) {
            yield runLifecycleHook('preinstall', pkg, opts);
        }
        if (scripts.install) {
            yield runLifecycleHook('install', pkg, opts);
        }
        if (scripts.postinstall) {
            yield runLifecycleHook('postinstall', pkg, opts);
        }
        return !!scripts.preinstall || !!scripts.install || !!scripts.postinstall;
    });
}
exports.runPostinstallHooks = runPostinstallHooks;
function runLifecycleHook(stage, pkg, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        return lifecycle(pkg, stage, opts.pkgRoot, {
            config: opts.rawNpmConfig,
            dir: opts.rootNodeModulesDir,
            log: {
                clearProgress: noop,
                info: noop,
                level: opts.stdio === 'inherit' ? undefined : 'silent',
                pause: noop,
                resume: noop,
                showProgress: noop,
                silly: npmLog,
                verbose: npmLog,
                warn: noop,
            },
            stdio: opts.stdio || 'pipe',
            unsafePerm: opts.unsafePerm,
        });
        function npmLog(prefix, logid, stdtype, line) {
            switch (stdtype) {
                case 'stdout':
                    logger_1.lifecycleLogger.info({
                        line: line.toString(),
                        pkgId: opts.pkgId,
                        script: stage,
                    });
                    return;
                case 'stderr':
                    logger_1.lifecycleLogger.error({
                        line: line.toString(),
                        pkgId: opts.pkgId,
                        script: stage,
                    });
                    return;
                case 'Returned: code:':
                    if (opts.stdio === 'inherit') {
                        // Preventing the pnpm reporter from overriding the project's script output
                        return;
                    }
                    const code = arguments[3];
                    logger_1.lifecycleLogger[code === 0 ? 'info' : 'error']({
                        exitCode: code,
                        pkgId: opts.pkgId,
                        script: stage,
                    });
                    return;
            }
        }
    });
}
exports.default = runLifecycleHook;
/**
 * Run node-gyp when binding.gyp is available. Only do this when there's no
 * `install` script (see `npm help scripts`).
 */
function checkBindingGyp(root, scripts) {
    return __awaiter(this, void 0, void 0, function* () {
        if (yield exists(path.join(root, 'binding.gyp'))) {
            scripts['install'] = 'node-gyp rebuild'; // tslint:disable-line:no-string-literal
        }
    });
}
//# sourceMappingURL=index.js.map