"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 getContext_1 = require("./getContext");
const extendOptions_1 = require("./extendOptions");
const lock_1 = require("./lock");
const removeOrphanPkgs_1 = require("./removeOrphanPkgs");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const logger_1 = require("@pnpm/logger");
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 extendOptions_1.default(maybeOpts);
        const ctx = yield getContext_1.default(opts);
        if (opts.lock === false) {
            yield run();
        }
        else {
            yield lock_1.default(ctx.storePath, run, { stale: opts.lockStaleDuration, locks: opts.locks });
        }
        if (reporter) {
            logger_1.streamParser.removeListener('data', reporter);
        }
        function run() {
            return __awaiter(this, void 0, void 0, function* () {
                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 removeOrphanPkgs_1.default({
                    oldShrinkwrap: ctx.currentShrinkwrap,
                    newShrinkwrap: prunedShr,
                    prefix: ctx.root,
                    store: ctx.storePath,
                    storeIndex: ctx.storeIndex,
                    pruneStore: true,
                    bin: opts.bin,
                });
            });
        }
    });
}
exports.prune = prune;
//# sourceMappingURL=prune.js.map