"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 dp = require("dependency-path");
const path = require("path");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const modulesController_1 = require("../fs/modulesController");
const getSaveType_1 = require("../getSaveType");
const removeDeps_1 = require("../removeDeps");
const removeTopDependency_1 = require("../removeTopDependency");
const safeIsInnerLink_1 = require("../safeIsInnerLink");
const extendUninstallOptions_1 = require("./extendUninstallOptions");
const getContext_1 = require("./getContext");
const install_1 = require("./install");
const lock_1 = require("./lock");
const removeOrphanPkgs_1 = require("./removeOrphanPkgs");
const shrinkwrapsEqual_1 = require("./shrinkwrapsEqual");
function uninstall(pkgsToUninstall, 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 extendUninstallOptions_1.default(maybeOpts);
        if (opts.lock) {
            yield lock_1.default(opts.prefix, _uninstall, { stale: opts.lockStaleDuration, locks: opts.locks });
        }
        else {
            yield _uninstall();
        }
        if (reporter) {
            logger_1.streamParser.removeListener('data', reporter);
        }
        function _uninstall() {
            return __awaiter(this, void 0, void 0, function* () {
                const ctx = yield getContext_1.default(opts);
                if (!ctx.pkg) {
                    throw new Error('No package.json found - cannot uninstall');
                }
                return uninstallInContext(pkgsToUninstall, ctx, opts);
            });
        }
    });
}
exports.default = uninstall;
function uninstallInContext(pkgsToUninstall, ctx, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const makePartialCurrentShrinkwrap = !shrinkwrapsEqual_1.default(ctx.currentShrinkwrap, ctx.wantedShrinkwrap);
        const pkgJsonPath = path.join(ctx.root, 'package.json');
        const saveType = getSaveType_1.default(opts);
        const pkg = yield removeDeps_1.default(pkgJsonPath, pkgsToUninstall, saveType);
        const newShr = pnpm_shrinkwrap_1.prune(ctx.wantedShrinkwrap, pkg);
        const removedPkgIds = yield removeOrphanPkgs_1.default({
            bin: opts.bin,
            hoistedAliases: ctx.hoistedAliases,
            newShrinkwrap: newShr,
            oldShrinkwrap: ctx.currentShrinkwrap,
            prefix: ctx.root,
            shamefullyFlatten: opts.shamefullyFlatten,
            storeController: opts.storeController,
        });
        ctx.pendingBuilds = ctx.pendingBuilds.filter((pkgId) => !removedPkgIds.has(dp.resolve(newShr.registry, pkgId)));
        yield opts.storeController.close();
        const currentShrinkwrap = makePartialCurrentShrinkwrap
            ? pnpm_shrinkwrap_1.prune(ctx.currentShrinkwrap, pkg)
            : newShr;
        if (opts.shrinkwrap) {
            yield pnpm_shrinkwrap_1.write(ctx.root, newShr, currentShrinkwrap);
        }
        else {
            yield pnpm_shrinkwrap_1.writeCurrentOnly(ctx.root, currentShrinkwrap);
        }
        yield modulesController_1.save(path.join(ctx.root, 'node_modules'), {
            hoistedAliases: ctx.hoistedAliases,
            independentLeaves: opts.independentLeaves,
            layoutVersion: modulesController_1.LAYOUT_VERSION,
            packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`,
            pendingBuilds: ctx.pendingBuilds,
            shamefullyFlatten: opts.shamefullyFlatten,
            skipped: Array.from(ctx.skipped).filter((pkgId) => !removedPkgIds.has(pkgId)),
            store: ctx.storePath,
        });
        yield removeOuterLinks(pkgsToUninstall, path.join(ctx.root, 'node_modules'), {
            bin: opts.bin,
            storePath: ctx.storePath,
        });
        if (opts.shamefullyFlatten) {
            yield install_1.installPkgs(currentShrinkwrap.specifiers, Object.assign({}, opts, { lock: false, reinstallForFlatten: true, update: false }));
        }
        logger_1.default('summary').info();
    });
}
exports.uninstallInContext = uninstallInContext;
function removeOuterLinks(pkgsToUninstall, modules, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        // These packages are not in package.json, they were just linked in not installed
        for (const pkgToUninstall of pkgsToUninstall) {
            if ((yield safeIsInnerLink_1.default(modules, pkgToUninstall, opts)) !== true) {
                yield removeTopDependency_1.default({
                    dev: false,
                    name: pkgToUninstall,
                    optional: false,
                }, {
                    bin: opts.bin,
                    modules,
                });
            }
        }
    });
}
//# sourceMappingURL=uninstall.js.map