"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_promise_1 = require("child-process-promise");
const path_1 = require("path");
const semver_1 = require("semver");
const fs_extra_1 = require("fs-extra");
const ramda_1 = require("ramda");
const npm = require.resolve('npm');
const env = ramda_1.dissoc('PUPPETEER_SKIP_CHROMIUM_DOWNLOAD', process.env);
const options = {
    cwd: path_1.join(__dirname, '../../../'),
    env,
};
function lazyRequire({ moduleName, repo }, { unsafe } = { unsafe: false }) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const modulePath = require.resolve(moduleName);
            const currentVersion = require(`${moduleName}/package.json`).version;
            const repoVersion = repo && repo.match(/[#](.*)$/);
            const targetVersion = repoVersion && repoVersion[1];
            if (targetVersion && semver_1.gt(targetVersion, currentVersion)) {
                return installModule(moduleName, repo, unsafe);
            }
            return require(modulePath).default;
        }
        catch (_a) {
            return installModule(moduleName, repo);
        }
    });
}
function installModule(moduleName, repo, unsafe) {
    return __awaiter(this, void 0, void 0, function* () {
        const commandParameters = [
            'install',
            '-g',
            repo !== null && repo !== void 0 ? repo : moduleName,
            ...(unsafe ? [] : ['--unsafe-perm']),
        ];
        yield child_process_promise_1.fork(npm, commandParameters, options);
        yield child_process_promise_1.fork(npm, ['link', moduleName], options);
        return require(yield resolveModulePath(moduleName)).default;
    });
}
function resolveModulePath(moduleName) {
    return __awaiter(this, void 0, void 0, function* () {
        const moduleFolder = path_1.join(options.cwd, 'node_modules', moduleName);
        const modulePackage = yield fs_extra_1.readJSON(path_1.join(moduleFolder, 'package.json'));
        return path_1.join(moduleFolder, modulePackage.main);
    });
}
exports.default = lazyRequire;
//# sourceMappingURL=lazyRequire.js.map