"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveRegistryUrl = exports.loadConfigFromYarnrcYml = exports.loadConfigFromLegacyYarnrc = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const js_yaml_1 = require("js-yaml");
const zod_1 = require("zod");
const logger_1 = require("../../../../logger");
const regex_1 = require("../../../../util/regex");
const YarnrcYmlSchema = zod_1.z.object({
    npmRegistryServer: zod_1.z.string().optional(),
    npmScopes: zod_1.z
        .record(zod_1.z.object({
        npmRegistryServer: zod_1.z.string().optional(),
    }))
        .optional(),
});
const registryRegEx = (0, regex_1.regEx)(/^"?(@(?<scope>[^:]+):)?registry"? "?(?<registryUrl>[^"]+)"?$/gm);
function loadConfigFromLegacyYarnrc(legacyYarnrc) {
    var _a, _b;
    const registryMatches = [...legacyYarnrc.matchAll(registryRegEx)]
        .map((m) => m.groups)
        .filter(is_1.default.truthy);
    const yarnConfig = {};
    for (const registryMatch of registryMatches) {
        if (registryMatch.scope) {
            yarnConfig.npmScopes ?? (yarnConfig.npmScopes = {});
            (_a = yarnConfig.npmScopes)[_b = registryMatch.scope] ?? (_a[_b] = {});
            yarnConfig.npmScopes[registryMatch.scope].npmRegistryServer =
                registryMatch.registryUrl;
        }
        else {
            yarnConfig.npmRegistryServer = registryMatch.registryUrl;
        }
    }
    return yarnConfig;
}
exports.loadConfigFromLegacyYarnrc = loadConfigFromLegacyYarnrc;
function loadConfigFromYarnrcYml(yarnrcYml) {
    try {
        const obj = (0, js_yaml_1.load)(yarnrcYml, {
            json: true,
        });
        if (!obj) {
            // emtpy yaml file
            return null;
        }
        return YarnrcYmlSchema.parse(obj);
    }
    catch (err) {
        logger_1.logger.warn({ yarnrcYml, err }, `Failed to load yarnrc file`);
        return null;
    }
}
exports.loadConfigFromYarnrcYml = loadConfigFromYarnrcYml;
function resolveRegistryUrl(packageName, yarnConfig) {
    if (yarnConfig.npmScopes) {
        for (const scope in yarnConfig.npmScopes) {
            if (packageName.startsWith(`@${scope}/`)) {
                return yarnConfig.npmScopes[scope].npmRegistryServer ?? null;
            }
        }
    }
    if (yarnConfig.npmRegistryServer) {
        return yarnConfig.npmRegistryServer;
    }
    return null;
}
exports.resolveRegistryUrl = resolveRegistryUrl;
//# sourceMappingURL=yarnrc.js.map