"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());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NpmController = void 0;
const child_process_promise_1 = require("child-process-promise");
const fs_extra_1 = require("fs-extra");
const path_1 = require("path");
const ramda_1 = require("ramda");
const url_1 = require("url");
const urlJoin = require("url-join");
const npm = require.resolve('npm');
const NPM_RC = '.npmrc';
class NpmController {
    constructor(_a) {
        var { cwd, registry = '', token = '' } = _a, options = __rest(_a, ["cwd", "registry", "token"]);
        const env = ramda_1.compose(ramda_1.mergeLeft({ AUTH_TOKEN: token }), ramda_1.omit(['npm_config_registry', 'npm_config_always_auth']))(process.env);
        this.npmRcPath = path_1.join(cwd, NPM_RC);
        this.registry = registry;
        this.options = Object.assign(Object.assign({}, options), { cwd,
            env });
    }
    install(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { options } = this;
            yield this.runNpm([
                { cmd: 'i', args: ['--package-lock-only', ...args], options },
                { cmd: 'ci', args: [], options },
            ]);
        });
    }
    publish() {
        return __awaiter(this, void 0, void 0, function* () {
            const { options } = this;
            yield this.runNpm([{ cmd: 'publish', args: [], options }]);
        });
    }
    uninstall(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { options } = this;
            yield this.runNpmProcess({ cmd: 'r', args, options });
        });
    }
    runNpm(npmCommands) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.registry) {
                yield this.runNpmWithRc(npmCommands);
            }
            else {
                yield this.runNpmCommands(npmCommands);
            }
        });
    }
    runNpmWithRc(npmCommands) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                yield this.createNpmRc();
                yield this.runNpmCommands(npmCommands);
            }
            finally {
                yield this.removeNpmRc();
            }
        });
    }
    runNpmCommands(npmCommands) {
        return __awaiter(this, void 0, void 0, function* () {
            for (const command of npmCommands) {
                yield this.runNpmProcess(command);
            }
        });
    }
    createNpmRc() {
        const content = this.generateNpmConfig();
        return fs_extra_1.outputFile(this.npmRcPath, content);
    }
    removeNpmRc() {
        return fs_extra_1.remove(this.npmRcPath);
    }
    generateNpmConfig() {
        const { host, pathname } = url_1.parse(this.registry);
        const ewizardjsNamespace = '@ewizardjs';
        const registry = `registry=${this.registry}`;
        const registryWithoutProtocol = urlJoin(host, removeTrailingSlash(pathname));
        return `${ewizardjsNamespace}:${registry}\n${registry}\n//${registryWithoutProtocol}/:always-auth=true\n//${registryWithoutProtocol}/:_authToken=\${AUTH_TOKEN}`;
    }
    runNpmProcess({ cmd, args, options }) {
        return __awaiter(this, void 0, void 0, function* () {
            yield child_process_promise_1.fork(npm, [cmd, ...args], options);
        });
    }
}
exports.NpmController = NpmController;
function removeTrailingSlash(pathname) {
    return pathname.replace(/\/$/, '');
}
//# sourceMappingURL=index.js.map