"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 logger_1 = require("@pnpm/logger");
const utils_1 = require("@pnpm/utils");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const extendPruneOptions_1 = require("./extendPruneOptions");
const getContext_1 = require("./getContext");
const install_1 = require("./install");
function prune(maybeOpts) {
    return __awaiter(this, void 0, void 0, function* () {
        const reporter = maybeOpts && maybeOpts.reporter;
        if (reporter) {
            logger_1.streamParser.on('data', reporter);
        }
        const opts = yield extendPruneOptions_1.default(maybeOpts);
        const ctx = yield getContext_1.default(opts);
        if (!ctx.pkg) {
            throw new Error('No package.json found - cannot prune');
        }
        const pkg = {
            dependencies: opts.production ? ctx.pkg.dependencies : {},
            devDependencies: opts.development ? ctx.pkg.devDependencies : {},
            optionalDependencies: opts.optional ? ctx.pkg.optionalDependencies : {},
        };
        const prunedShr = pnpm_shrinkwrap_1.prune(ctx.wantedShrinkwrap, pkg);
        yield utils_1.removeOrphanPackages({
            bin: opts.bin,
            hoistedAliases: ctx.hoistedAliases,
            newShrinkwrap: prunedShr,
            oldShrinkwrap: ctx.currentShrinkwrap,
            prefix: ctx.root,
            pruneStore: true,
            shamefullyFlatten: opts.shamefullyFlatten,
            storeController: opts.storeController,
        });
        if (opts.shamefullyFlatten) {
            yield install_1.installPkgs(prunedShr.specifiers, Object.assign({}, opts, { lock: false, reinstallForFlatten: true, update: false }));
        }
        if (reporter) {
            logger_1.streamParser.removeListener('data', reporter);
        }
    });
}
exports.prune = prune;
//# sourceMappingURL=prune.js.map