"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 findUp = require("find-up");
const path = require("path");
const pathAbsolute = require("path-absolute");
const R = require("ramda");
const supi_1 = require("supi");
const constants_1 = require("../constants");
const createStoreController_1 = require("../createStoreController");
const findWorkspacePackages_1 = require("../findWorkspacePackages");
exports.default = (input, opts) => __awaiter(this, void 0, void 0, function* () {
    const cwd = opts && opts.prefix || process.cwd();
    const store = yield createStoreController_1.default(opts);
    const linkOpts = Object.assign(opts, {
        store: store.path,
        storeController: store.ctrl,
    });
    // pnpm link
    if (!input || !input.length) {
        yield supi_1.linkToGlobal(cwd, linkOpts);
        return;
    }
    const [pkgPaths, pkgNames] = R.partition((inp) => inp.startsWith('.'), input);
    if (pkgNames.length) {
        const workspaceManifestLocation = yield findUp(constants_1.WORKSPACE_MANIFEST_FILENAME);
        let globalPkgNames;
        if (workspaceManifestLocation) {
            const workspaceRoot = path.dirname(workspaceManifestLocation);
            const pkgs = yield findWorkspacePackages_1.default(workspaceRoot);
            const pkgsFoundInWorkspace = pkgs.filter((pkg) => pkgNames.indexOf(pkg.manifest.name) !== -1);
            pkgsFoundInWorkspace.forEach((pkgFromWorkspace) => pkgPaths.push(pkgFromWorkspace.path));
            if (pkgsFoundInWorkspace.length && !linkOpts.saveDev && !linkOpts.saveProd && !linkOpts.saveOptional) {
                linkOpts.saveProd = true;
            }
            globalPkgNames = pkgNames.filter((pkgName) => !pkgsFoundInWorkspace.some((pkgFromWorkspace) => pkgFromWorkspace.manifest.name === pkgName));
        }
        else {
            globalPkgNames = pkgNames;
        }
        const globalPkgPath = pathAbsolute(opts.globalPrefix);
        globalPkgNames.forEach((pkgName) => pkgPaths.push(path.join(globalPkgPath, 'node_modules', pkgName)));
    }
    yield supi_1.link(pkgPaths, path.join(cwd, 'node_modules'), linkOpts);
});
//# sourceMappingURL=link.js.map