"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("@pnpm/logger");
const pkgid_to_filename_1 = require("@pnpm/pkgid-to-filename");
const common_tags_1 = require("common-tags");
const crypto = require("crypto");
const path = require("path");
const R = require("ramda");
const semver = require("semver");
const nodeIdUtils_1 = require("../nodeIdUtils");
function default_1(pkgGraph, rootNodeIdsByAlias, 
// only the top dependencies that were already installed
// to avoid warnings about unresolved peer dependencies
topParents, independentLeaves, nodeModules) {
    const pkgsByName = Object.assign(R.fromPairs(topParents.map((parent) => [
        parent.name,
        {
            depth: 0,
            version: parent.version,
        },
    ])), toPkgByName(R.keys(rootNodeIdsByAlias).map((alias) => ({ alias, nodeId: rootNodeIdsByAlias[alias], node: pkgGraph[rootNodeIdsByAlias[alias]] }))));
    const absolutePathsByNodeId = {};
    const depGraph = {};
    resolvePeersOfChildren(rootNodeIdsByAlias, pkgsByName, {
        absolutePathsByNodeId,
        depGraph,
        independentLeaves,
        nodeModules,
        pkgGraph,
        purePkgs: new Set(),
    });
    R.values(depGraph).forEach((node) => {
        node.children = R.keys(node.children).reduce((acc, alias) => {
            acc[alias] = absolutePathsByNodeId[node.children[alias]];
            return acc;
        }, {});
    });
    return {
        depGraph,
        rootAbsolutePathsByAlias: R.keys(rootNodeIdsByAlias).reduce((rootAbsolutePathsByAlias, alias) => {
            rootAbsolutePathsByAlias[alias] = absolutePathsByNodeId[rootNodeIdsByAlias[alias]];
            return rootAbsolutePathsByAlias;
        }, {}),
    };
}
exports.default = default_1;
function resolvePeersOfNode(nodeId, parentParentPkgs, ctx) {
    const node = ctx.pkgGraph[nodeId];
    if (ctx.purePkgs.has(node.pkg.id) && ctx.depGraph[node.pkg.id].depth <= node.depth) {
        ctx.absolutePathsByNodeId[nodeId] = node.pkg.id;
        return {};
    }
    const children = typeof node.children === 'function' ? node.children() : node.children;
    const parentPkgs = R.isEmpty(children)
        ? parentParentPkgs
        : Object.assign({}, parentParentPkgs, toPkgByName(R.keys(children).map((alias) => ({ alias, nodeId: children[alias], node: ctx.pkgGraph[children[alias]] }))));
    const unknownResolvedPeersOfChildren = resolvePeersOfChildren(children, parentPkgs, ctx);
    const resolvedPeers = R.isEmpty(node.pkg.peerDependencies)
        ? {}
        : resolvePeers(nodeId, node, parentPkgs, ctx.pkgGraph);
    const allResolvedPeers = Object.assign(unknownResolvedPeersOfChildren, resolvedPeers);
    let modules;
    let absolutePath;
    const localLocation = path.join(ctx.nodeModules, `.${pkgid_to_filename_1.default(node.pkg.id)}`);
    if (R.isEmpty(allResolvedPeers)) {
        modules = path.join(localLocation, 'node_modules');
        absolutePath = node.pkg.id;
        if (R.isEmpty(node.pkg.peerDependencies)) {
            ctx.purePkgs.add(node.pkg.id);
        }
    }
    else {
        const peersFolder = createPeersFolderName(R.keys(allResolvedPeers).map((alias) => ({
            name: alias,
            version: ctx.pkgGraph[allResolvedPeers[alias]].pkg.version,
        })));
        modules = path.join(localLocation, peersFolder, 'node_modules');
        absolutePath = `${node.pkg.id}/${peersFolder}`;
    }
    ctx.absolutePathsByNodeId[nodeId] = absolutePath;
    if (!ctx.depGraph[absolutePath] || ctx.depGraph[absolutePath].depth > node.depth) {
        const independent = ctx.independentLeaves && R.isEmpty(node.children) && R.isEmpty(node.pkg.peerDependencies);
        const centralLocation = node.pkg.engineCache || path.join(node.pkg.path, 'node_modules', node.pkg.name);
        const peripheralLocation = !independent
            ? path.join(modules, node.pkg.name)
            : centralLocation;
        ctx.depGraph[absolutePath] = {
            absolutePath,
            additionalInfo: node.pkg.additionalInfo,
            centralLocation,
            children: Object.assign(children, resolvedPeers),
            depth: node.depth,
            dev: node.pkg.dev,
            fetchingFiles: node.pkg.fetchingFiles,
            fetchingRawManifest: node.pkg.fetchingRawManifest,
            hasBin: node.pkg.hasBin,
            hasBundledDependencies: node.pkg.hasBundledDependencies,
            id: node.pkg.id,
            independent,
            installable: node.installable,
            isBuilt: !!node.pkg.engineCache,
            modules,
            name: node.pkg.name,
            optional: node.pkg.optional,
            optionalDependencies: node.pkg.optionalDependencies,
            peripheralLocation,
            prepare: node.pkg.prepare,
            prod: node.pkg.prod,
            requiresBuild: node.pkg.requiresBuild,
            resolution: node.pkg.resolution,
            version: node.pkg.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(nodeId, node, parentPkgs, pkgGraph) {
    const resolvedPeers = {};
    for (const peerName in node.pkg.peerDependencies) { // tslint:disable-line:forin
        const peerVersionRange = node.pkg.peerDependencies[peerName];
        const resolved = parentPkgs[peerName];
        if (!resolved || resolved.nodeId && !pkgGraph[resolved.nodeId].installable) {
            const friendlyPath = nodeIdToFriendlyPath(nodeId, pkgGraph);
            logger_1.default.warn(common_tags_1.oneLine `
        ${friendlyPath ? `${friendlyPath}: ` : ''}${packageFriendlyId(node.pkg)}
        requires a peer of ${peerName}@${peerVersionRange} but none was installed.`);
            continue;
        }
        if (!semver.satisfies(resolved.version, peerVersionRange)) {
            const friendlyPath = nodeIdToFriendlyPath(nodeId, pkgGraph);
            logger_1.default.warn(common_tags_1.oneLine `
        ${friendlyPath ? `${friendlyPath}: ` : ''}${packageFriendlyId(node.pkg)}
        requires a peer of ${peerName}@${peerVersionRange} but version ${resolved.version} was installed.`);
        }
        if (resolved.depth === 0 || resolved.depth === node.depth + 1) {
            // if the resolved package is a top dependency
            // or the peer dependency is resolved from a regular dependency of the package
            // then there is no need to link it in
            continue;
        }
        if (resolved && resolved.nodeId)
            resolvedPeers[peerName] = resolved.nodeId;
    }
    return resolvedPeers;
}
function packageFriendlyId(pkg) {
    return `${pkg.name}@${pkg.version}`;
}
function nodeIdToFriendlyPath(nodeId, pkgGraph) {
    const parts = nodeIdUtils_1.splitNodeId(nodeId).slice(2, -2);
    return R.tail(R.scan((prevNodeId, pkgId) => nodeIdUtils_1.createNodeId(prevNodeId, pkgId), nodeIdUtils_1.ROOT_NODE_ID, parts))
        .map((nid) => pkgGraph[nid].pkg.name)
        .join(' > ');
}
function toPkgByName(nodes) {
    const pkgsByName = {};
    for (const node of nodes) {
        pkgsByName[node.alias] = {
            depth: node.node.depth,
            nodeId: node.nodeId,
            version: node.node.pkg.version,
        };
    }
    return pkgsByName;
}
function createPeersFolderName(peers) {
    const folderName = peers.map((peer) => `${peer.name.replace('/', '!')}@${peer.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