"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NpmConfigRepo = void 0;
const tslib_1 = require("tslib");
const fs = require("fs");
const path = require("path");
const ini = require("ini");
const _ = require("lodash");
/** Cruds npm config files (npmrc and package.json) */
class NpmConfigRepo {
    constructor(_projectRoot) {
        this._projectRoot = _projectRoot;
    }
    /** NOTE: Returns an empty object if the file doesnt exist.
     * @param scrubIdentities Removes any auth tokens or scopes from the config object.
     */
    loadNpmrc(absolutePathName, scrubIdentities = false) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    let npmrc = {};
                    if (fs.existsSync(absolutePathName)) {
                        let content = fs.readFileSync(absolutePathName, { encoding: "utf-8" }).trim();
                        npmrc = ini.parse(content);
                        if (scrubIdentities) {
                            npmrc = this.scrubRegistriesFrom(npmrc);
                        }
                    }
                    resolve(npmrc);
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Writes the given npmrc object to the given path, using the ini lib to encode it. */
    saveNpmrc(npmrc, absolutePathName) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    let targetFolder = path.dirname(absolutePathName);
                    if (!fs.existsSync(targetFolder)) {
                        fs.mkdirSync(targetFolder, { recursive: true });
                    }
                    fs.writeFileSync(absolutePathName, ini.encode(npmrc));
                    resolve();
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Removes any auth tokens or scopes from the config object. */
    scrubRegistriesFrom(npmrc) {
        // properties ending with ":_authToken"
        let cleaned = _.omitBy(npmrc, (v, k) => k.match(/.*\:_authToken$/));
        // properties starting with "@scope:"
        cleaned = _.omitBy(cleaned, (v, k) => k.match(/^@[\w\d\._-]+\:/));
        return cleaned;
    }
}
exports.NpmConfigRepo = NpmConfigRepo;
//# sourceMappingURL=npm-config-repo.js.map