"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 modules_yaml_1 = require("@pnpm/modules-yaml");
const utils_1 = require("@pnpm/utils");
const dp = require("dependency-path");
const path = require("path");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const constants_1 = require("../constants");
const removeDeps_1 = require("../removeDeps");
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 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, {
                locks: opts.locks,
                prefix: opts.prefix,
                stale: opts.lockStaleDuration,
            });
        }
        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.prefix, 'package.json');
        const saveType = utils_1.getSaveType(opts);
        const pkg = yield removeDeps_1.default(pkgJsonPath, pkgsToUninstall, { prefix: opts.prefix, saveType });
        const newShr = pnpm_shrinkwrap_1.prune(ctx.wantedShrinkwrap, pkg, (message) => logger_1.default.warn({ message, prefix: ctx.prefix }));
        const removedPkgIds = yield utils_1.removeOrphanPackages({
            bin: opts.bin,
            hoistedAliases: ctx.hoistedAliases,
            newShrinkwrap: newShr,
            oldShrinkwrap: ctx.currentShrinkwrap,
            prefix: ctx.prefix,
            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, (message) => logger_1.default.warn({ message, prefix: ctx.prefix }))
            : newShr;
        if (opts.shrinkwrap) {
            yield pnpm_shrinkwrap_1.write(ctx.prefix, newShr, currentShrinkwrap);
        }
        else {
            yield pnpm_shrinkwrap_1.writeCurrentOnly(ctx.prefix, currentShrinkwrap);
        }
        yield modules_yaml_1.write(path.join(ctx.prefix, 'node_modules'), {
            hoistedAliases: ctx.hoistedAliases,
            independentLeaves: opts.independentLeaves,
            layoutVersion: constants_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.prefix, 'node_modules'), {
            bin: opts.bin,
            prefix: opts.prefix,
            storePath: ctx.storePath,
        });
        if (opts.shamefullyFlatten) {
            yield install_1.installPkgs(currentShrinkwrap.specifiers, Object.assign({}, opts, { lock: false, reinstallForFlatten: true, update: false }));
        }
        utils_1.summaryLogger.debug({ prefix: opts.prefix });
    });
}
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 utils_1.removeTopDependency({
                    dev: false,
                    name: pkgToUninstall,
                    optional: false,
                }, {
                    bin: opts.bin,
                    modules,
                    prefix: opts.prefix,
                });
            }
        }
    });
}
//# sourceMappingURL=uninstall.js.map