"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_loggers_1 = require("@pnpm/core-loggers");
const filter_shrinkwrap_1 = require("@pnpm/filter-shrinkwrap");
const lifecycle_1 = require("@pnpm/lifecycle");
const link_bins_1 = require("@pnpm/link-bins");
const logger_1 = require("@pnpm/logger");
const modules_cleaner_1 = require("@pnpm/modules-cleaner");
const modules_yaml_1 = require("@pnpm/modules-yaml");
const pkgid_to_filename_1 = require("@pnpm/pkgid-to-filename");
const read_package_json_1 = require("@pnpm/read-package-json");
const shamefully_flatten_1 = require("@pnpm/shamefully-flatten");
const shrinkwrap_file_1 = require("@pnpm/shrinkwrap-file");
const shrinkwrap_utils_1 = require("@pnpm/shrinkwrap-utils");
const symlink_dependency_1 = require("@pnpm/symlink-dependency");
const utils_1 = require("@pnpm/utils");
const dp = require("dependency-path");
const pLimit = require("p-limit");
const path = require("path");
const R = require("ramda");
const constants_1 = require("./constants");
const runDependenciesScripts_1 = require("./runDependenciesScripts");
exports.default = async (opts) => {
    const reporter = opts.reporter;
    if (reporter) {
        logger_1.streamParser.on('data', reporter);
    }
    const shrinkwrapDirectory = opts.shrinkwrapDirectory;
    const wantedShrinkwrap = opts.wantedShrinkwrap || await shrinkwrap_file_1.readWanted(shrinkwrapDirectory, { ignoreIncompatible: false });
    if (!wantedShrinkwrap) {
        throw new Error('Headless installation requires a shrinkwrap.yaml file');
    }
    const currentShrinkwrap = opts.currentShrinkwrap || await shrinkwrap_file_1.readCurrent(shrinkwrapDirectory, { ignoreIncompatible: false });
    const virtualStoreDir = await utils_1.realNodeModulesDir(shrinkwrapDirectory);
    for (const importer of opts.importers) {
        if (!shrinkwrap_utils_1.satisfiesPackageJson(wantedShrinkwrap, importer.pkg, importer.id)) {
            const err = new Error('Cannot install with "frozen-shrinkwrap" because shrinkwrap.yaml is not up-to-date with ' +
                path.relative(opts.shrinkwrapDirectory, path.join(importer.prefix, 'package.json')));
            err['code'] = 'ERR_PNPM_OUTDATED_SHRINKWRAP'; // tslint:disable-line
            throw err;
        }
    }
    const scriptsOpts = {
        optional: false,
        rawNpmConfig: opts.rawNpmConfig,
        stdio: opts.ownLifecycleHooksStdio || 'inherit',
        unsafePerm: opts.unsafePerm || false,
    };
    if (!opts.ignoreScripts) {
        await lifecycle_1.runLifecycleHooksConcurrently(['preinstall'], opts.importers, opts.childConcurrency || 5, scriptsOpts);
    }
    const skipped = opts.skipped || new Set();
    const filterOpts = {
        include: opts.include,
        registries: opts.registries,
        skipped,
    };
    if (currentShrinkwrap) {
        await modules_cleaner_1.prune({
            dryRun: false,
            importers: opts.importers,
            newShrinkwrap: filter_shrinkwrap_1.default(wantedShrinkwrap, filterOpts),
            oldShrinkwrap: currentShrinkwrap,
            pruneStore: opts.pruneStore,
            registries: opts.registries,
            shrinkwrapDirectory,
            storeController: opts.storeController,
            virtualStoreDir,
        });
    }
    else {
        core_loggers_1.statsLogger.debug({
            prefix: shrinkwrapDirectory,
            removed: 0,
        });
    }
    core_loggers_1.stageLogger.debug({
        prefix: opts.shrinkwrapDirectory,
        stage: 'importing_started',
    });
    const filteredShrinkwrap = filter_shrinkwrap_1.filterByImportersAndEngine(wantedShrinkwrap, opts.importers.map((importer) => importer.id), Object.assign({}, filterOpts, { currentEngine: opts.currentEngine, engineStrict: opts.engineStrict, failOnMissingDependencies: true, includeIncompatiblePackages: opts.force === true, prefix: shrinkwrapDirectory }));
    const res = await shrinkwrapToDepGraph(filteredShrinkwrap, opts.force ? null : currentShrinkwrap, Object.assign({}, opts, { importerIds: opts.importers.map((importer) => importer.id), prefix: shrinkwrapDirectory, skipped,
        virtualStoreDir }));
    const depGraph = res.graph;
    core_loggers_1.statsLogger.debug({
        added: Object.keys(depGraph).length,
        prefix: shrinkwrapDirectory,
    });
    await Promise.all([
        linkAllModules(depGraph, { optional: opts.include.optionalDependencies }),
        linkAllPkgs(opts.storeController, R.values(depGraph), opts),
    ]);
    core_loggers_1.stageLogger.debug({
        prefix: opts.shrinkwrapDirectory,
        stage: 'importing_done',
    });
    function warn(message) {
        logger_1.default.warn({
            message,
            prefix: shrinkwrapDirectory,
        });
    }
    await linkAllBins(depGraph, { optional: opts.include.optionalDependencies, warn });
    await Promise.all(opts.importers.map(async (importer) => {
        if (importer.shamefullyFlatten) {
            importer.hoistedAliases = await shamefully_flatten_1.shamefullyFlattenByShrinkwrap(filteredShrinkwrap, importer.id, {
                getIndependentPackageLocation: opts.independentLeaves
                    ? async (packageId, packageName) => {
                        const { directory } = await opts.storeController.getPackageLocation(packageId, packageName, {
                            importerPrefix: opts.shrinkwrapDirectory,
                            targetEngine: opts.sideEffectsCacheRead && constants_1.ENGINE_NAME || undefined,
                        });
                        return directory;
                    }
                    : undefined,
                modulesDir: importer.modulesDir,
                prefix: opts.shrinkwrapDirectory,
                registries: opts.registries,
                virtualStoreDir,
            });
        }
        else {
            importer.hoistedAliases = {};
        }
    }));
    await Promise.all(opts.importers.map(async (importer) => {
        await linkRootPackages(filteredShrinkwrap, {
            importerId: importer.id,
            importerModulesDir: importer.modulesDir,
            prefix: importer.prefix,
            registries: opts.registries,
            rootDependencies: res.directDependenciesByImporterId[importer.id],
        });
        const bin = path.join(importer.modulesDir, '.bin');
        await link_bins_1.default(importer.modulesDir, bin, { warn });
        // Even though headless installation will never update the package.json
        // this needs to be logged because otherwise install summary won't be printed
        core_loggers_1.packageJsonLogger.debug({
            prefix: importer.prefix,
            updated: importer.pkg,
        });
    }));
    if (currentShrinkwrap && !R.equals(opts.importers.map((importer) => importer.id).sort(), Object.keys(filteredShrinkwrap.importers).sort())) {
        Object.assign(filteredShrinkwrap.packages, currentShrinkwrap.packages);
    }
    await shrinkwrap_file_1.writeCurrentOnly(shrinkwrapDirectory, filteredShrinkwrap);
    if (opts.ignoreScripts) {
        for (const importer of opts.importers) {
            if (opts.ignoreScripts && importer.pkg && importer.pkg.scripts &&
                (importer.pkg.scripts.preinstall || importer.pkg.scripts.prepublish ||
                    importer.pkg.scripts.install ||
                    importer.pkg.scripts.postinstall ||
                    importer.pkg.scripts.prepare)) {
                opts.pendingBuilds.push(importer.id);
            }
        }
        // we can use concat here because we always only append new packages, which are guaranteed to not be there by definition
        opts.pendingBuilds = opts.pendingBuilds
            .concat(R.values(depGraph)
            .filter((node) => node.requiresBuild)
            .map((node) => node.relDepPath));
    }
    await modules_yaml_1.write(virtualStoreDir, {
        importers: opts.importers.reduce((acc, importer) => {
            acc[importer.id] = {
                hoistedAliases: importer.hoistedAliases,
                shamefullyFlatten: importer.shamefullyFlatten,
            };
            return acc;
        }, {}),
        included: opts.include,
        independentLeaves: !!opts.independentLeaves,
        layoutVersion: constants_1.LAYOUT_VERSION,
        packageManager: `${opts.packageManager.name}@${opts.packageManager.version}`,
        pendingBuilds: opts.pendingBuilds,
        registries: opts.registries,
        skipped: Array.from(skipped),
        store: opts.store,
    });
    if (!opts.ignoreScripts) {
        for (const importer of opts.importers) {
            await runDependenciesScripts_1.default(depGraph, R.values(res.directDependenciesByImporterId[importer.id]).filter((loc) => depGraph[loc]), {
                childConcurrency: opts.childConcurrency,
                prefix: importer.prefix,
                rawNpmConfig: opts.rawNpmConfig,
                rootNodeModulesDir: importer.modulesDir,
                sideEffectsCacheWrite: opts.sideEffectsCacheWrite,
                storeController: opts.storeController,
                unsafePerm: opts.unsafePerm,
                userAgent: opts.userAgent,
            });
        }
    }
    // waiting till package requests are finished
    await Promise.all(R.values(depGraph).map((depNode) => depNode.finishing));
    core_loggers_1.summaryLogger.debug({ prefix: opts.shrinkwrapDirectory });
    await opts.storeController.close();
    if (!opts.ignoreScripts) {
        await lifecycle_1.runLifecycleHooksConcurrently(['install', 'postinstall', 'prepublish', 'prepare'], opts.importers, opts.childConcurrency || 5, scriptsOpts);
    }
    if (reporter) {
        logger_1.streamParser.removeListener('data', reporter);
    }
};
async function linkRootPackages(shr, opts) {
    const shrImporter = shr.importers[opts.importerId];
    const allDeps = Object.assign({}, shrImporter.devDependencies, shrImporter.dependencies, shrImporter.optionalDependencies);
    return Promise.all(R.keys(allDeps)
        .map(async (alias) => {
        if (allDeps[alias].startsWith('link:')) {
            const isDev = shrImporter.devDependencies && shrImporter.devDependencies[alias];
            const isOptional = shrImporter.optionalDependencies && shrImporter.optionalDependencies[alias];
            const packageDir = path.join(opts.prefix, allDeps[alias].substr(5));
            const linkedPackage = await read_package_json_1.fromDir(packageDir);
            await symlink_dependency_1.symlinkDirectRootDependency(packageDir, opts.importerModulesDir, alias, {
                fromDependenciesField: isDev && 'devDependencies' ||
                    isOptional && 'optionalDependencies' ||
                    'dependencies',
                linkedPackage,
                prefix: opts.prefix,
            });
            return;
        }
        const depPath = dp.refToAbsolute(allDeps[alias], alias, opts.registries);
        const peripheralLocation = opts.rootDependencies[alias];
        // Skipping linked packages
        if (!peripheralLocation) {
            return;
        }
        if ((await symlink_dependency_1.default(peripheralLocation, opts.importerModulesDir, alias)).reused) {
            return;
        }
        const isDev = shrImporter.devDependencies && shrImporter.devDependencies[alias];
        const isOptional = shrImporter.optionalDependencies && shrImporter.optionalDependencies[alias];
        const relDepPath = dp.refToRelative(allDeps[alias], alias);
        if (relDepPath === null)
            return;
        const pkgSnapshot = shr.packages && shr.packages[relDepPath];
        if (!pkgSnapshot)
            return; // this won't ever happen. Just making typescript happy
        const pkgId = pkgSnapshot.id || depPath;
        const pkgInfo = shrinkwrap_utils_1.nameVerFromPkgSnapshot(relDepPath, pkgSnapshot);
        core_loggers_1.rootLogger.debug({
            added: {
                dependencyType: isDev && 'dev' || isOptional && 'optional' || 'prod',
                id: pkgId,
                // latest: opts.outdatedPkgs[pkg.id],
                name: alias,
                realName: pkgInfo.name,
                version: pkgInfo.version,
            },
            prefix: opts.prefix,
        });
    }));
}
async function shrinkwrapToDepGraph(shr, currentShrinkwrap, opts) {
    const currentPackages = currentShrinkwrap && currentShrinkwrap.packages || {};
    const graph = {};
    let directDependenciesByImporterId = {};
    if (shr.packages) {
        const pkgSnapshotByLocation = {};
        for (const relDepPath of R.keys(shr.packages)) {
            if (currentPackages[relDepPath] && R.equals(currentPackages[relDepPath].dependencies, shr.packages[relDepPath].dependencies) &&
                R.equals(currentPackages[relDepPath].optionalDependencies, shr.packages[relDepPath].optionalDependencies)) {
                continue;
            }
            const depPath = dp.resolve(opts.registries, relDepPath);
            const pkgSnapshot = shr.packages[relDepPath];
            const resolution = shrinkwrap_utils_1.pkgSnapshotToResolution(relDepPath, pkgSnapshot, opts.registries);
            // TODO: optimize. This info can be already returned by pkgSnapshotToResolution()
            const pkgName = shrinkwrap_utils_1.nameVerFromPkgSnapshot(relDepPath, pkgSnapshot).name;
            const packageId = pkgSnapshot.id || depPath;
            core_loggers_1.progressLogger.debug({
                packageId,
                requester: opts.shrinkwrapDirectory,
                status: 'resolved',
            });
            let fetchResponse = opts.storeController.fetchPackage({
                force: false,
                pkgId: packageId,
                prefix: opts.prefix,
                resolution,
                verifyStoreIntegrity: opts.verifyStoreIntegrity,
            });
            if (fetchResponse instanceof Promise)
                fetchResponse = await fetchResponse;
            fetchResponse.fetchingFiles // tslint:disable-line
                .then((fetchResult) => {
                core_loggers_1.progressLogger.debug({
                    packageId,
                    requester: opts.shrinkwrapDirectory,
                    status: fetchResult.fromStore
                        ? 'found_in_store' : 'fetched',
                });
            });
            const pkgLocation = await opts.storeController.getPackageLocation(packageId, pkgName, {
                importerPrefix: opts.shrinkwrapDirectory,
                targetEngine: opts.sideEffectsCacheRead && !opts.force && constants_1.ENGINE_NAME || undefined,
            });
            const modules = path.join(opts.virtualStoreDir, `.${pkgid_to_filename_1.default(depPath, opts.shrinkwrapDirectory)}`, 'node_modules');
            const independent = opts.independentLeaves && shrinkwrap_utils_1.packageIsIndependent(pkgSnapshot);
            const peripheralLocation = !independent
                ? path.join(modules, pkgName)
                : pkgLocation.directory;
            graph[peripheralLocation] = {
                centralLocation: pkgLocation.directory,
                children: {},
                fetchingFiles: fetchResponse.fetchingFiles,
                finishing: fetchResponse.finishing,
                hasBin: pkgSnapshot.hasBin === true,
                hasBundledDependencies: !!pkgSnapshot.bundledDependencies,
                independent,
                isBuilt: pkgLocation.isBuilt,
                modules,
                optional: !!pkgSnapshot.optional,
                optionalDependencies: new Set(R.keys(pkgSnapshot.optionalDependencies)),
                peripheralLocation,
                pkgId: packageId,
                prepare: pkgSnapshot.prepare === true,
                relDepPath,
                requiresBuild: pkgSnapshot.requiresBuild === true,
            };
            pkgSnapshotByLocation[peripheralLocation] = pkgSnapshot;
        }
        const ctx = {
            force: opts.force,
            graph,
            independentLeaves: opts.independentLeaves,
            pkgSnapshotsByRelDepPaths: shr.packages,
            prefix: opts.prefix,
            registries: opts.registries,
            shrinkwrapDirectory: opts.shrinkwrapDirectory,
            sideEffectsCacheRead: opts.sideEffectsCacheRead,
            skipped: opts.skipped,
            store: opts.store,
            storeController: opts.storeController,
            virtualStoreDir: opts.virtualStoreDir,
        };
        for (const peripheralLocation of R.keys(graph)) {
            const pkgSnapshot = pkgSnapshotByLocation[peripheralLocation];
            const allDeps = Object.assign({}, pkgSnapshot.dependencies, pkgSnapshot.optionalDependencies);
            graph[peripheralLocation].children = await getChildrenPaths(ctx, allDeps);
        }
        for (const importerId of opts.importerIds) {
            const shrImporter = shr.importers[importerId];
            const rootDeps = Object.assign({}, shrImporter.devDependencies, shrImporter.dependencies, shrImporter.optionalDependencies);
            directDependenciesByImporterId[importerId] = await getChildrenPaths(ctx, rootDeps);
        }
    }
    return { graph, directDependenciesByImporterId };
}
async function getChildrenPaths(ctx, allDeps) {
    const children = {};
    for (const alias of R.keys(allDeps)) {
        const childDepPath = dp.refToAbsolute(allDeps[alias], alias, ctx.registries);
        if (childDepPath === null) {
            children[alias] = path.resolve(ctx.prefix, allDeps[alias].substr(5));
            continue;
        }
        const childRelDepPath = dp.refToRelative(allDeps[alias], alias);
        const childPkgSnapshot = ctx.pkgSnapshotsByRelDepPaths[childRelDepPath];
        if (ctx.graph[childDepPath]) {
            children[alias] = ctx.graph[childDepPath].peripheralLocation;
        }
        else if (ctx.independentLeaves && shrinkwrap_utils_1.packageIsIndependent(childPkgSnapshot)) {
            const pkgId = childPkgSnapshot.id || childDepPath;
            const pkgName = shrinkwrap_utils_1.nameVerFromPkgSnapshot(childRelDepPath, childPkgSnapshot).name;
            const pkgLocation = await ctx.storeController.getPackageLocation(pkgId, pkgName, {
                importerPrefix: ctx.shrinkwrapDirectory,
                targetEngine: ctx.sideEffectsCacheRead && !ctx.force && constants_1.ENGINE_NAME || undefined,
            });
            children[alias] = pkgLocation.directory;
        }
        else if (childPkgSnapshot) {
            const pkgName = shrinkwrap_utils_1.nameVerFromPkgSnapshot(childRelDepPath, childPkgSnapshot).name;
            children[alias] = path.join(ctx.virtualStoreDir, `.${pkgid_to_filename_1.default(childDepPath, ctx.shrinkwrapDirectory)}`, 'node_modules', pkgName);
        }
        else if (allDeps[alias].indexOf('file:') === 0) {
            children[alias] = path.resolve(ctx.prefix, allDeps[alias].substr(5));
        }
        else if (!ctx.skipped.has(childRelDepPath)) {
            throw new Error(`${childRelDepPath} not found in shrinkwrap.yaml`);
        }
    }
    return children;
}
const limitLinking = pLimit(16);
async function linkAllPkgs(storeController, depNodes, opts) {
    return Promise.all(depNodes.map(async (depNode) => {
        const filesResponse = await depNode.fetchingFiles;
        if (depNode.independent)
            return;
        return storeController.importPackage(depNode.centralLocation, depNode.peripheralLocation, {
            filesResponse,
            force: opts.force,
        });
    }));
}
async function linkAllBins(depGraph, opts) {
    return Promise.all(R.values(depGraph)
        .map((depNode) => limitLinking(async () => {
        const childrenToLink = opts.optional
            ? depNode.children
            : R.keys(depNode.children)
                .reduce((nonOptionalChildren, childAlias) => {
                if (!depNode.optionalDependencies.has(childAlias)) {
                    nonOptionalChildren[childAlias] = depNode.children[childAlias];
                }
                return nonOptionalChildren;
            }, {});
        const binPath = path.join(depNode.peripheralLocation, 'node_modules', '.bin');
        const pkgSnapshots = R.props(R.values(childrenToLink), depGraph);
        if (pkgSnapshots.indexOf(undefined) !== -1) { // tslint:disable-line
            await link_bins_1.default(depNode.modules, binPath, { warn: opts.warn });
        }
        else {
            const pkgs = await Promise.all(pkgSnapshots
                .filter((dep) => dep.hasBin)
                .map(async (dep) => ({
                location: dep.peripheralLocation,
                manifest: await read_package_json_1.fromDir(dep.peripheralLocation),
            })));
            await link_bins_1.linkBinsOfPackages(pkgs, binPath, { warn: opts.warn });
        }
        // link also the bundled dependencies` bins
        if (depNode.hasBundledDependencies) {
            const bundledModules = path.join(depNode.peripheralLocation, 'node_modules');
            await link_bins_1.default(bundledModules, binPath, { warn: opts.warn });
        }
    })));
}
async function linkAllModules(depGraph, opts) {
    return Promise.all(R.values(depGraph)
        .filter((depNode) => !depNode.independent)
        .map((depNode) => limitLinking(async () => {
        const childrenToLink = opts.optional
            ? depNode.children
            : R.keys(depNode.children)
                .reduce((nonOptionalChildren, childAlias) => {
                if (!depNode.optionalDependencies.has(childAlias)) {
                    nonOptionalChildren[childAlias] = depNode.children[childAlias];
                }
                return nonOptionalChildren;
            }, {});
        await Promise.all(R.keys(childrenToLink)
            .map(async (alias) => {
            // if (!pkg.installable && pkg.optional) return
            await symlink_dependency_1.default(childrenToLink[alias], depNode.modules, alias);
        }));
    })));
}
//# sourceMappingURL=index.js.map