"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 symlink_dir_1 = require("symlink-dir");
const path = require("path");
const semver = require("semver");
const pnpm_logger_1 = require("pnpm-logger");
function linkPeers(installs) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!installs)
            return;
        const groupedPkgs = {};
        Object.keys(installs).forEach(id => {
            const pkgData = installs[id];
            if (!pkgData.pkg.version)
                return;
            const pkgName = pkgData.pkg.name;
            groupedPkgs[pkgName] = groupedPkgs[pkgName] || {};
            groupedPkgs[pkgName][pkgData.pkg.version] = pkgData;
        });
        return Promise.all(Object.keys(installs).map(id => {
            const pkgData = installs[id];
            const peerDependencies = pkgData.pkg.peerDependencies || {};
            return Promise.all(Object.keys(peerDependencies).map(peerName => {
                const version = semver.maxSatisfying(Object.keys(groupedPkgs[peerName] || {}), peerDependencies[peerName], true);
                if (!version) {
                    pnpm_logger_1.default.warn(`${pkgData.id} requires a peer of ${peerName}@${peerDependencies[peerName]} but none was installed.`);
                    return;
                }
                return symlink_dir_1.default(groupedPkgs[peerName][version].hardlinkedLocation, path.join(pkgData.modules, peerName));
            }));
        }));
    });
}
exports.default = linkPeers;
//# sourceMappingURL=linkPeers.js.map