"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 logger_1 = require("@pnpm/logger");
const utils_1 = require("@pnpm/utils");
const normalizeRegistryUrl = require("normalize-registry-url");
const path = require("path");
const pnpm_shrinkwrap_1 = require("pnpm-shrinkwrap");
const pnpmPkgJson_1 = require("../pnpmPkgJson");
function toStrictImporter(shamefullyFlatten, shrinkwrapDirectory, importerOptions) {
    return __awaiter(this, void 0, void 0, function* () {
        const modulesDir = yield utils_1.realNodeModulesDir(importerOptions.prefix);
        const importerId = pnpm_shrinkwrap_1.getImporterId(shrinkwrapDirectory, importerOptions.prefix);
        return {
            bin: importerOptions.bin || path.join(importerOptions.prefix, 'node_modules', '.bin'),
            id: importerId,
            modulesDir,
            prefix: importerOptions.prefix,
            shamefullyFlatten: typeof importerOptions.shamefullyFlatten === 'boolean' ? importerOptions.shamefullyFlatten : shamefullyFlatten,
        };
    });
}
const defaults = (opts) => __awaiter(this, void 0, void 0, function* () {
    const packageManager = opts.packageManager || {
        name: pnpmPkgJson_1.default.name,
        version: pnpmPkgJson_1.default.version,
    };
    return {
        allowNew: true,
        childConcurrency: 5,
        depth: 0,
        engineStrict: false,
        force: false,
        frozenShrinkwrap: false,
        hooks: {},
        ignoreCurrentPrefs: false,
        ignoreScripts: false,
        importers: [{
                bin: opts.bin,
                prefix: opts.prefix || process.cwd(),
            }],
        include: {
            dependencies: true,
            devDependencies: true,
            optionalDependencies: true,
        },
        independentLeaves: false,
        localPackages: {},
        lock: true,
        lockStaleDuration: 5 * 60 * 1000,
        locks: path.join(opts.store, '_locks'),
        nodeVersion: process.version,
        ownLifecycleHooksStdio: 'inherit',
        packageManager,
        preferFrozenShrinkwrap: true,
        pruneStore: false,
        rawNpmConfig: {},
        registry: 'https://registry.npmjs.org/',
        repeatInstallDepth: -1,
        saveDev: false,
        saveExact: false,
        saveOptional: false,
        savePrefix: '^',
        saveProd: false,
        shrinkwrap: true,
        shrinkwrapDirectory: opts.shrinkwrapDirectory || opts.prefix || process.cwd(),
        shrinkwrapOnly: false,
        sideEffectsCache: false,
        sideEffectsCacheReadonly: false,
        store: opts.store,
        storeController: opts.storeController,
        strictPeerDependencies: false,
        tag: 'latest',
        unsafePerm: process.platform === 'win32' ||
            process.platform === 'cygwin' ||
            !(process.getuid && process.setuid &&
                process.getgid && process.setgid) ||
            process.getuid() !== 0,
        update: false,
        userAgent: `${packageManager.name}/${packageManager.version} npm/? node/${process.version} ${process.platform} ${process.arch}`,
        verifyStoreIntegrity: true,
    };
});
exports.default = (opts) => __awaiter(this, void 0, void 0, function* () {
    if (opts) {
        for (const key in opts) {
            if (opts[key] === undefined) {
                delete opts[key];
            }
        }
    }
    const defaultOpts = yield defaults(opts);
    const extendedOpts = Object.assign({}, defaultOpts, opts, { importers: yield Promise.all((opts.importers || defaultOpts.importers)
            .map(toStrictImporter.bind(null, opts.shamefullyFlatten || false, opts.shrinkwrapDirectory || defaultOpts.shrinkwrapDirectory))), store: defaultOpts.store });
    if (!extendedOpts.shrinkwrap && extendedOpts.shrinkwrapOnly) {
        throw new Error('Cannot generate a shrinkwrap.yaml because shrinkwrap is set to false');
    }
    if (extendedOpts.userAgent.startsWith('npm/')) {
        extendedOpts.userAgent = `${extendedOpts.packageManager.name}/${extendedOpts.packageManager.version} ${extendedOpts.userAgent}`;
    }
    extendedOpts.registry = normalizeRegistryUrl(extendedOpts.registry);
    extendedOpts.rawNpmConfig['registry'] = extendedOpts.registry; // tslint:disable-line:no-string-literal
    // if sideEffectsCacheReadonly is true, sideEffectsCache is necessarily true too
    if (extendedOpts.sideEffectsCache && extendedOpts.sideEffectsCacheReadonly) {
        logger_1.default.warn({
            message: "--side-effects-cache-readonly turns on side effects cache too, you don't need to specify both",
            prefix: extendedOpts.shrinkwrapDirectory || process.cwd(),
        });
    }
    extendedOpts.sideEffectsCache = extendedOpts.sideEffectsCache || extendedOpts.sideEffectsCacheReadonly;
    return extendedOpts;
});
//# sourceMappingURL=extendInstallOptions.js.map