"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 core_loggers_1 = require("@pnpm/core-loggers");
const mkdirp = require("mkdirp-promise");
const fs = require("mz/fs");
const path = require("path");
const symlinkDir = require("symlink-dir");
const DEP_TYPE_BY_DEPS_FIELD_NAME = {
    dependencies: 'prod',
    devDependencies: 'dev',
    optionalDependencies: 'optional',
};
function linkToModules(opts) {
    return __awaiter(this, void 0, void 0, function* () {
        // `opts.destModulesDir` may be a non-existent `node_modules` dir
        // so `fs.realpath` would throw.
        // Even though `symlinkDir` creates the dir if it doesn't exist,
        // our dir may include an ancestor dir which is symlinked,
        // so we create it if it doesn't exist, and then find its realpath.
        let destModulesDirReal;
        try {
            destModulesDirReal = yield fs.realpath(opts.destModulesDir);
        }
        catch (err) {
            if (err.code === 'ENOENT') {
                yield mkdirp(opts.destModulesDir);
                destModulesDirReal = yield fs.realpath(opts.destModulesDir);
            }
            else {
                throw err;
            }
        }
        const packageDirReal = yield fs.realpath(opts.packageDir);
        const dest = path.join(destModulesDirReal, opts.alias);
        const { reused } = yield symlinkDir(packageDirReal, dest);
        if (reused)
            return; // if the link was already present, don't log
        core_loggers_1.rootLogger.debug({
            added: {
                dependencyType: opts.saveType && DEP_TYPE_BY_DEPS_FIELD_NAME[opts.saveType],
                linkedFrom: packageDirReal,
                name: opts.alias,
                realName: opts.name,
                version: opts.version,
            },
            prefix: opts.prefix,
        });
    });
}
exports.default = linkToModules;
//# sourceMappingURL=linkToModules.js.map