"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_1 = require("@pnpm/lifecycle");
const logger_1 = require("@pnpm/logger");
const modules_yaml_1 = require("@pnpm/modules-yaml");
const utils_1 = require("@pnpm/utils");
const npa = require("@zkochan/npm-package-arg");
const dp = require("dependency-path");
const graphSequencer = require("graph-sequencer");
const pLimit = require("p-limit");
const path = require("path");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const R = require("ramda");
const semver = require("semver");
const constants_1 = require("../constants");
const extendRebuildOptions_1 = require("./extendRebuildOptions");
const getContext_1 = require("./getContext");
function findPackages(packages, searched) {
    return R.keys(packages)
        .filter((relativeDepPath) => {
        const pkgShr = packages[relativeDepPath];
        const pkgInfo = pnpm_shrinkwrap_1.nameVerFromPkgSnapshot(relativeDepPath, pkgShr);
        if (!pkgInfo.name) {
            logger_1.default.warn(`Skipping ${relativeDepPath} because cannot get the package name from shrinkwrap.yaml.
          Try to run run \`pnpm update --depth 100\` to create a new shrinkwrap.yaml with all the necessary info.`);
            return false;
        }
        return matches(searched, pkgInfo);
    });
}
// TODO: move this logic to separate package as this is also used in dependencies-hierarchy
function matches(searched, pkg) {
    return searched.some((searchedPkg) => {
        if (typeof searchedPkg === 'string') {
            return pkg.name === searchedPkg;
        }
        return searchedPkg.name === pkg.name && !!pkg.version &&
            semver.satisfies(pkg.version, searchedPkg.range);
    });
}
function rebuildPkgs(pkgSpecs, 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 extendRebuildOptions_1.default(maybeOpts);
        const ctx = yield getContext_1.default(opts);
        const modules = yield utils_1.realNodeModulesDir(opts.prefix);
        if (!ctx.currentShrinkwrap || !ctx.currentShrinkwrap.packages)
            return;
        const packages = ctx.currentShrinkwrap.packages;
        const searched = pkgSpecs.map((arg) => {
            const parsed = npa(arg);
            if (parsed.raw === parsed.name) {
                return parsed.name;
            }
            if (parsed.type !== 'version' && parsed.type !== 'range') {
                throw new Error(`Invalid argument - ${arg}. Rebuild can only select by version or range`);
            }
            return {
                name: parsed.name,
                range: parsed.fetchSpec,
            };
        });
        const pkgs = findPackages(packages, searched);
        yield _rebuild(new Set(pkgs), modules, ctx.currentShrinkwrap, opts);
    });
}
exports.rebuildPkgs = rebuildPkgs;
function rebuild(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 extendRebuildOptions_1.default(maybeOpts);
        const ctx = yield getContext_1.default(opts);
        const modules = yield utils_1.realNodeModulesDir(opts.prefix);
        let idsToRebuild = [];
        if (opts.pending) {
            idsToRebuild = ctx.pendingBuilds;
        }
        else if (ctx.currentShrinkwrap && ctx.currentShrinkwrap.packages) {
            idsToRebuild = R.keys(ctx.currentShrinkwrap.packages);
        }
        else {
            return;
        }
        yield _rebuild(new Set(idsToRebuild), modules, ctx.currentShrinkwrap, opts);
        yield modules_yaml_1.write(path.join(ctx.root, 'node_modules'), {
            hoistedAliases: ctx.hoistedAliases,
            independentLeaves: opts.independentLeaves,
            layoutVersion: constants_1.LAYOUT_VERSION,
            packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`,
            pendingBuilds: [],
            shamefullyFlatten: opts.shamefullyFlatten,
            skipped: Array.from(ctx.skipped),
            store: ctx.storePath,
        });
    });
}
exports.rebuild = rebuild;
function getSubgraphToBuild(pkgSnapshots, entryNodes, nodesToBuildAndTransitive, walked, opts) {
    let currentShouldBeBuilt = false;
    for (const depPath of entryNodes) {
        if (nodesToBuildAndTransitive.has(depPath)) {
            currentShouldBeBuilt = true;
        }
        if (walked.has(depPath))
            continue;
        walked.add(depPath);
        const pkgSnapshot = pkgSnapshots[depPath];
        if (!pkgSnapshot && depPath.startsWith('link:'))
            continue;
        const nextEntryNodes = R.toPairs(Object.assign({}, pkgSnapshot.dependencies, (opts.optional && pkgSnapshot.optionalDependencies || {}))).map((pair) => dp.refToRelative(pair[1], pair[0]));
        const childShouldBeBuilt = getSubgraphToBuild(pkgSnapshots, nextEntryNodes, nodesToBuildAndTransitive, walked, opts)
            || opts.pkgsToRebuild.has(depPath);
        if (childShouldBeBuilt) {
            nodesToBuildAndTransitive.add(depPath);
            currentShouldBeBuilt = true;
        }
    }
    return currentShouldBeBuilt;
}
function _rebuild(pkgsToRebuild, modules, shr, opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const limitChild = pLimit(opts.childConcurrency);
        const graph = new Map();
        const pkgSnapshots = shr.packages || {};
        const relDepPaths = R.keys(pkgSnapshots);
        const entryNodes = R.toPairs(Object.assign({}, (opts.development && shr.devDependencies || {}), (opts.production && shr.dependencies || {}), (opts.optional && shr.optionalDependencies || {}))).map((pair) => dp.refToRelative(pair[1], pair[0]));
        const nodesToBuildAndTransitive = new Set();
        getSubgraphToBuild(pkgSnapshots, entryNodes, nodesToBuildAndTransitive, new Set(), { optional: opts.optional === true, pkgsToRebuild });
        const nodesToBuildAndTransitiveArray = Array.from(nodesToBuildAndTransitive);
        for (const relDepPath of nodesToBuildAndTransitiveArray) {
            const pkgSnapshot = pkgSnapshots[relDepPath];
            graph.set(relDepPath, R.toPairs(Object.assign({}, pkgSnapshot.dependencies, pkgSnapshot.optionalDependencies))
                .map((pair) => dp.refToRelative(pair[1], pair[0]))
                .filter((childRelDepPath) => nodesToBuildAndTransitive.has(childRelDepPath)));
        }
        const graphSequencerResult = graphSequencer({
            graph,
            groups: [nodesToBuildAndTransitiveArray],
        });
        const chunks = graphSequencerResult.chunks;
        for (const chunk of chunks) {
            yield Promise.all(chunk
                .filter((relDepPath) => pkgsToRebuild.has(relDepPath))
                .map((relDepPath) => {
                const pkgSnapshot = pkgSnapshots[relDepPath];
                return limitChild(() => __awaiter(this, void 0, void 0, function* () {
                    const depAbsolutePath = dp.resolve(shr.registry, relDepPath);
                    const pkgInfo = pnpm_shrinkwrap_1.nameVerFromPkgSnapshot(relDepPath, pkgSnapshot);
                    try {
                        yield lifecycle_1.runPostinstallHooks({
                            depPath: depAbsolutePath,
                            pkgRoot: path.join(modules, `.${depAbsolutePath}`, 'node_modules', pkgInfo.name),
                            prepare: pkgSnapshot.prepare,
                            rawNpmConfig: opts.rawNpmConfig,
                            rootNodeModulesDir: opts.prefix,
                            unsafePerm: opts.unsafePerm || false,
                        });
                    }
                    catch (err) {
                        if (pkgSnapshot.optional) {
                            // TODO: add parents field to the log
                            utils_1.skippedOptionalDependencyLogger.debug({
                                details: err.toString(),
                                package: {
                                    id: pkgSnapshot.id || depAbsolutePath,
                                    name: pkgInfo.name,
                                    version: pkgInfo.version,
                                },
                                reason: 'build_failure',
                            });
                            return;
                        }
                        throw err;
                    }
                }));
            }));
        }
    });
}
//# sourceMappingURL=rebuild.js.map