"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const package_store_1 = require("package-store");
const R = require("ramda");
const semver = require("semver");
const logger_1 = require("@pnpm/logger");
const path = require("path");
const common_tags_1 = require("common-tags");
function default_1(tree, 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,
        {
            version: parent.version,
            depth: 0
        }
    ])), toPkgByName(R.keys(rootNodeIdsByAlias).map(alias => ({ alias, nodeId: rootNodeIdsByAlias[alias], node: tree[rootNodeIdsByAlias[alias]] }))));
    const absolutePathsByNodeId = {};
    const resolvedTree = {};
    resolvePeersOfChildren(rootNodeIdsByAlias, pkgsByName, {
        tree,
        absolutePathsByNodeId,
        resolvedTree,
        independentLeaves,
        nodeModules,
        purePkgs: new Set(),
    });
    R.values(resolvedTree).forEach(node => {
        node.children = R.keys(node.children).reduce((acc, alias) => {
            acc[alias] = absolutePathsByNodeId[node.children[alias]];
            return acc;
        }, {});
    });
    return {
        resolvedTree,
        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.tree[nodeId];
    if (ctx.purePkgs.has(node.pkg.id) && ctx.resolvedTree[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.tree[children[alias]] }))));
    const unknownResolvedPeersOfChildren = resolvePeersOfChildren(children, parentPkgs, ctx, nodeId);
    const resolvedPeers = R.isEmpty(node.pkg.peerDependencies)
        ? {}
        : resolvePeers(nodeId, node, parentPkgs, ctx.tree);
    const allResolvedPeers = Object.assign(unknownResolvedPeersOfChildren, resolvedPeers);
    let modules;
    let absolutePath;
    const localLocation = path.join(ctx.nodeModules, `.${package_store_1.pkgIdToFilename(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.tree[allResolvedPeers[alias]].pkg.version,
        })));
        modules = path.join(localLocation, peersFolder, 'node_modules');
        absolutePath = `${node.pkg.id}/${peersFolder}`;
    }
    ctx.absolutePathsByNodeId[nodeId] = absolutePath;
    if (!ctx.resolvedTree[absolutePath] || ctx.resolvedTree[absolutePath].depth > node.depth) {
        const independent = ctx.independentLeaves && R.isEmpty(node.children) && R.isEmpty(node.pkg.peerDependencies);
        const pathToUnpacked = path.join(node.pkg.path, 'node_modules', node.pkg.name);
        const hardlinkedLocation = !independent
            ? path.join(modules, node.pkg.name)
            : pathToUnpacked;
        ctx.resolvedTree[absolutePath] = {
            name: node.pkg.name,
            version: node.pkg.version,
            hasBundledDependencies: node.pkg.hasBundledDependencies,
            fetchingFiles: node.pkg.fetchingFiles,
            resolution: node.pkg.resolution,
            path: pathToUnpacked,
            modules,
            hardlinkedLocation,
            independent,
            optionalDependencies: node.pkg.optionalDependencies,
            children: Object.assign(children, resolvedPeers),
            depth: node.depth,
            absolutePath,
            prod: node.pkg.prod,
            dev: node.pkg.dev,
            optional: node.pkg.optional,
            id: node.pkg.id,
            installable: node.installable,
            additionalInfo: node.pkg.additionalInfo,
        };
    }
    return allResolvedPeers;
}
function addMany(a, b) {
    for (const el of Array.from(b)) {
        a.add(el);
    }
    return a;
}
function union(a, b) {
    return new Set(Array.from(a).concat(Array.from(b)));
}
function difference(a, b) {
    return new Set(Array.from(a).filter(el => !b.has(el)));
}
function resolvePeersOfChildren(children, parentPkgs, ctx, exceptNodeId) {
    let allResolvedPeers = {};
    for (const childNodeId of R.values(children)) {
        Object.assign(allResolvedPeers, resolvePeersOfNode(childNodeId, parentPkgs, ctx));
    }
    const unknownResolvedPeersOfChildren = R.keys(allResolvedPeers)
        .filter(alias => !children[alias] && allResolvedPeers[alias] !== exceptNodeId)
        .reduce((unknownResolvedPeersOfChildren, peer) => {
        unknownResolvedPeersOfChildren[peer] = allResolvedPeers[peer];
        return unknownResolvedPeersOfChildren;
    }, {});
    return unknownResolvedPeersOfChildren;
}
function resolvePeers(nodeId, node, parentPkgs, tree) {
    const resolvedPeers = {};
    for (const peerName in node.pkg.peerDependencies) {
        const peerVersionRange = node.pkg.peerDependencies[peerName];
        const resolved = parentPkgs[peerName];
        if (!resolved || resolved.nodeId && !tree[resolved.nodeId].installable) {
            const friendlyPath = nodeIdToFriendlyPath(nodeId, tree);
            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, tree);
            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, tree) {
    const parts = nodeId.split(':').slice(2, -2);
    return R.tail(R.scan((prevNodeId, pkgId) => `${prevNodeId}${pkgId}:`, ':/:', parts))
        .map(nodeId => tree[nodeId].pkg.name)
        .join(' > ');
}
function toPkgByName(nodes) {
    const pkgsByName = {};
    for (const node of nodes) {
        pkgsByName[node.alias] = {
            version: node.node.pkg.version,
            nodeId: node.nodeId,
            depth: node.node.depth,
        };
    }
    return pkgsByName;
}
function createPeersFolderName(peers) {
    return peers.map(peer => `${peer.name.replace('/', '!')}@${peer.version}`).sort().join('+');
}
//# sourceMappingURL=resolvePeers.js.map