"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const error_1 = require("@pnpm/error");
const logger_1 = require("@pnpm/logger");
const pkgid_to_filename_1 = require("@pnpm/pkgid-to-filename");
const resolve_dependencies_1 = require("@pnpm/resolve-dependencies");
const common_tags_1 = require("common-tags");
const crypto = require("crypto");
const importFrom = require("import-from");
const path = require("path");
const R = require("ramda");
const semver = require("semver");
function default_1(opts) {
    const depGraph = {};
    const pathsByNodeId = {};
    for (const { directNodeIdsByAlias, topParents, rootDir } of opts.projects) {
        const pkgsByName = Object.assign(R.fromPairs(topParents.map(({ name, version }) => [
            name,
            {
                depth: 0,
                version,
            },
        ])), toPkgByName(Object
            .keys(directNodeIdsByAlias)
            .map((alias) => ({
            alias,
            node: opts.dependenciesTree[directNodeIdsByAlias[alias]],
            nodeId: directNodeIdsByAlias[alias],
        }))));
        resolvePeersOfChildren(directNodeIdsByAlias, pkgsByName, {
            dependenciesTree: opts.dependenciesTree,
            depGraph,
            lockfileDir: opts.lockfileDir,
            pathsByNodeId,
            purePkgs: new Set(),
            rootDir,
            strictPeerDependencies: opts.strictPeerDependencies,
            virtualStoreDir: opts.virtualStoreDir,
        });
    }
    R.values(depGraph).forEach((node) => {
        node.children = R.keys(node.children).reduce((acc, alias) => {
            var _a;
            acc[alias] = (_a = pathsByNodeId[node.children[alias]]) !== null && _a !== void 0 ? _a : node.children[alias];
            return acc;
        }, {});
    });
    const projectsDirectPathsByAlias = {};
    for (const { directNodeIdsByAlias, id } of opts.projects) {
        projectsDirectPathsByAlias[id] = R.keys(directNodeIdsByAlias).reduce((rootPathsByAlias, alias) => {
            rootPathsByAlias[alias] = pathsByNodeId[directNodeIdsByAlias[alias]];
            return rootPathsByAlias;
        }, {});
    }
    return {
        depGraph,
        projectsDirectPathsByAlias,
    };
}
exports.default = default_1;
function resolvePeersOfNode(nodeId, parentParentPkgs, ctx) {
    const node = ctx.dependenciesTree[nodeId];
    if (node.depth === -1)
        return {};
    const resolvedPackage = node.resolvedPackage;
    if (ctx.purePkgs.has(resolvedPackage.depPath) && ctx.depGraph[resolvedPackage.depPath].depth <= node.depth) {
        ctx.pathsByNodeId[nodeId] = resolvedPackage.depPath;
        return {};
    }
    const children = typeof node.children === 'function' ? node.children() : node.children;
    const parentPkgs = R.isEmpty(children)
        ? parentParentPkgs
        : {
            ...parentParentPkgs,
            ...toPkgByName(Object.keys(children).map((alias) => ({
                alias,
                node: ctx.dependenciesTree[children[alias]],
                nodeId: children[alias],
            }))),
        };
    const unknownResolvedPeersOfChildren = resolvePeersOfChildren(children, parentPkgs, ctx);
    const resolvedPeers = R.isEmpty(resolvedPackage.peerDependencies)
        ? {}
        : resolvePeers({
            currentDepth: node.depth,
            dependenciesTree: ctx.dependenciesTree,
            nodeId,
            parentPkgs,
            resolvedPackage,
            rootDir: ctx.rootDir,
            strictPeerDependencies: ctx.strictPeerDependencies,
        });
    const allResolvedPeers = Object.assign(unknownResolvedPeersOfChildren, resolvedPeers);
    let modules;
    let depPath;
    const localLocation = path.join(ctx.virtualStoreDir, pkgid_to_filename_1.default(resolvedPackage.depPath, ctx.lockfileDir));
    const isPure = R.isEmpty(allResolvedPeers);
    if (isPure) {
        modules = path.join(localLocation, 'node_modules');
        depPath = resolvedPackage.depPath;
        if (R.isEmpty(resolvedPackage.peerDependencies)) {
            ctx.purePkgs.add(resolvedPackage.depPath);
        }
    }
    else {
        const peersFolderSuffix = createPeersFolderSuffix(Object.keys(allResolvedPeers).map((alias) => ({
            name: alias,
            version: ctx.dependenciesTree[allResolvedPeers[alias]].resolvedPackage.version,
        })));
        modules = path.join(`${localLocation}${peersFolderSuffix}`, 'node_modules');
        depPath = `${resolvedPackage.depPath}${peersFolderSuffix}`;
    }
    ctx.pathsByNodeId[nodeId] = depPath;
    if (!ctx.depGraph[depPath] || ctx.depGraph[depPath].depth > node.depth) {
        const dir = path.join(modules, resolvedPackage.name);
        const unknownPeers = Object.keys(unknownResolvedPeersOfChildren);
        if (unknownPeers.length) {
            if (!resolvedPackage.additionalInfo.peerDependencies) {
                resolvedPackage.additionalInfo.peerDependencies = {};
            }
            for (const unknownPeer of unknownPeers) {
                if (!resolvedPackage.additionalInfo.peerDependencies[unknownPeer]) {
                    resolvedPackage.additionalInfo.peerDependencies[unknownPeer] = '*';
                }
            }
        }
        ctx.depGraph[depPath] = {
            additionalInfo: resolvedPackage.additionalInfo,
            children: Object.assign(children, resolvedPeers),
            depPath,
            depth: node.depth,
            dev: resolvedPackage.dev,
            dir,
            fetchingBundledManifest: resolvedPackage.fetchingBundledManifest,
            fetchingFiles: resolvedPackage.fetchingFiles,
            filesIndexFile: resolvedPackage.filesIndexFile,
            hasBin: resolvedPackage.hasBin,
            hasBundledDependencies: resolvedPackage.hasBundledDependencies,
            installable: node.installable,
            isPure,
            modules,
            name: resolvedPackage.name,
            optional: resolvedPackage.optional,
            optionalDependencies: resolvedPackage.optionalDependencies,
            packageId: resolvedPackage.id,
            prepare: resolvedPackage.prepare,
            prod: resolvedPackage.prod,
            requiresBuild: resolvedPackage.requiresBuild,
            resolution: resolvedPackage.resolution,
            version: resolvedPackage.version,
        };
    }
    return allResolvedPeers;
}
function resolvePeersOfChildren(children, parentPkgs, ctx) {
    const allResolvedPeers = {};
    for (const childNodeId of R.values(children)) {
        Object.assign(allResolvedPeers, resolvePeersOfNode(childNodeId, parentPkgs, ctx));
    }
    const unknownResolvedPeersOfChildren = R.keys(allResolvedPeers)
        .filter((alias) => !children[alias])
        .reduce((acc, peer) => {
        acc[peer] = allResolvedPeers[peer];
        return acc;
    }, {});
    return unknownResolvedPeersOfChildren;
}
function resolvePeers(ctx) {
    var _a, _b;
    const resolvedPeers = {};
    for (const peerName in ctx.resolvedPackage.peerDependencies) { // tslint:disable-line:forin
        const peerVersionRange = ctx.resolvedPackage.peerDependencies[peerName];
        let resolved = ctx.parentPkgs[peerName];
        if (!resolved || resolved.nodeId && !ctx.dependenciesTree[resolved.nodeId].installable) {
            try {
                const { version } = importFrom(ctx.rootDir, `${peerName}/package.json`);
                resolved = {
                    depth: -1,
                    version,
                };
            }
            catch (err) {
                if (((_b = (_a = ctx.resolvedPackage.additionalInfo.peerDependenciesMeta) === null || _a === void 0 ? void 0 : _a[peerName]) === null || _b === void 0 ? void 0 : _b.optional) === true) {
                    continue;
                }
                const friendlyPath = nodeIdToFriendlyPath(ctx.nodeId, ctx.dependenciesTree);
                const message = common_tags_1.oneLine `
          ${friendlyPath ? `${friendlyPath}: ` : ''}${packageFriendlyId(ctx.resolvedPackage)}
          requires a peer of ${peerName}@${peerVersionRange} but none was installed.`;
                if (ctx.strictPeerDependencies) {
                    throw new error_1.default('MISSING_PEER_DEPENDENCY', message);
                }
                logger_1.default.warn({
                    message,
                    prefix: ctx.rootDir,
                });
                continue;
            }
        }
        if (!semver.satisfies(resolved.version, peerVersionRange)) {
            const friendlyPath = nodeIdToFriendlyPath(ctx.nodeId, ctx.dependenciesTree);
            const message = common_tags_1.oneLine `
        ${friendlyPath ? `${friendlyPath}: ` : ''}${packageFriendlyId(ctx.resolvedPackage)}
        requires a peer of ${peerName}@${peerVersionRange} but version ${resolved.version} was installed.`;
            if (ctx.strictPeerDependencies) {
                throw new error_1.default('INVALID_PEER_DEPENDENCY', message);
            }
            logger_1.default.warn({
                message,
                prefix: ctx.rootDir,
            });
        }
        if (resolved.depth === ctx.currentDepth + 1) {
            // if the resolved package is a regular dependency of the package
            // then there is no need to link it in
            continue;
        }
        if (resolved === null || resolved === void 0 ? void 0 : resolved.nodeId)
            resolvedPeers[peerName] = resolved.nodeId;
    }
    return resolvedPeers;
}
function packageFriendlyId(manifest) {
    return `${manifest.name}@${manifest.version}`;
}
function nodeIdToFriendlyPath(nodeId, dependenciesTree) {
    const parts = resolve_dependencies_1.splitNodeId(nodeId).slice(0, -1);
    const result = R.scan((prevNodeId, pkgId) => resolve_dependencies_1.createNodeId(prevNodeId, pkgId), '>', parts)
        .slice(2)
        .map((nid) => dependenciesTree[nid].resolvedPackage.name)
        .join(' > ');
    return result;
}
function toPkgByName(nodes) {
    const pkgsByName = {};
    for (const { alias, node, nodeId } of nodes) {
        pkgsByName[alias] = {
            depth: node.depth,
            nodeId,
            version: node.resolvedPackage.version,
        };
    }
    return pkgsByName;
}
function createPeersFolderSuffix(peers) {
    const folderName = peers.map(({ name, version }) => `${name.replace('/', '+')}@${version}`).sort().join('+');
    // We don't want the folder name to get too long.
    // Otherwise, an ENAMETOOLONG error might happen.
    // see: https://github.com/pnpm/pnpm/issues/977
    //
    // A bigger limit might be fine but the md5 hash will be 32 symbols,
    // so for consistency's sake, we go with 32.
    if (folderName.length > 32) {
        return `_${crypto.createHash('md5').update(folderName).digest('hex')}`;
    }
    return `_${folderName}`;
}
//# sourceMappingURL=resolvePeers.js.map