"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findVersion = exports.getConfiguredRegistries = exports.getDefaultRegistries = exports.readFileAsXmlDocument = void 0;
const tslib_1 = require("tslib");
const upath_1 = tslib_1.__importDefault(require("upath"));
const xmldoc_1 = require("xmldoc");
const logger_1 = require("../../../logger");
const fs_1 = require("../../../util/fs");
const regex_1 = require("../../../util/regex");
const nuget_1 = require("../../datasource/nuget");
async function readFileAsXmlDocument(file) {
    try {
        // TODO #22198
        const doc = new xmldoc_1.XmlDocument((await (0, fs_1.readLocalFile)(file, 'utf8')));
        // don't return empty documents
        return doc?.firstChild ? doc : undefined;
    }
    catch (err) {
        logger_1.logger.debug({ err, file }, `failed to parse file as XML document`);
        return undefined;
    }
}
exports.readFileAsXmlDocument = readFileAsXmlDocument;
/**
 * The default `nuget.org` named registry.
 * @returns the default registry for NuGet
 */
function getDefaultRegistries() {
    return [{ url: nuget_1.nugetOrg, name: 'nuget.org' }];
}
exports.getDefaultRegistries = getDefaultRegistries;
async function getConfiguredRegistries(packageFile) {
    // Valid file names taken from https://github.com/NuGet/NuGet.Client/blob/f64621487c0b454eda4b98af853bf4a528bef72a/src/NuGet.Core/NuGet.Configuration/Settings/Settings.cs#L34
    const nuGetConfigFileNames = ['nuget.config', 'NuGet.config', 'NuGet.Config'];
    // normalize paths, otherwise startsWith can fail because of path delimitter mismatch
    const nuGetConfigPath = await (0, fs_1.findUpLocal)(nuGetConfigFileNames, upath_1.default.dirname(packageFile));
    if (!nuGetConfigPath) {
        return undefined;
    }
    logger_1.logger.debug(`Found NuGet.config at ${nuGetConfigPath}`);
    const nuGetConfig = await readFileAsXmlDocument(nuGetConfigPath);
    if (!nuGetConfig) {
        return undefined;
    }
    const packageSources = nuGetConfig.childNamed('packageSources');
    if (!packageSources) {
        return undefined;
    }
    const packageSourceMapping = nuGetConfig.childNamed('packageSourceMapping');
    const registries = getDefaultRegistries();
    // Map optional source mapped package patterns to default registries
    for (const registry of registries) {
        const sourceMappedPackagePatterns = packageSourceMapping
            ?.childWithAttribute('key', registry.name)
            ?.childrenNamed('package')
            .map((packagePattern) => packagePattern.attr['pattern']);
        registry.sourceMappedPackagePatterns = sourceMappedPackagePatterns;
    }
    for (const child of packageSources.children) {
        if (child.type === 'element') {
            if (child.name === 'clear') {
                logger_1.logger.debug(`clearing registry URLs`);
                registries.length = 0;
            }
            else if (child.name === 'add') {
                const isHttpUrl = (0, regex_1.regEx)(/^https?:\/\//i).test(child.attr.value);
                if (isHttpUrl) {
                    let registryUrl = child.attr.value;
                    if (child.attr.protocolVersion) {
                        registryUrl += `#protocolVersion=${child.attr.protocolVersion}`;
                    }
                    const sourceMappedPackagePatterns = packageSourceMapping
                        ?.childWithAttribute('key', child.attr.key)
                        ?.childrenNamed('package')
                        .map((packagePattern) => packagePattern.attr['pattern']);
                    logger_1.logger.debug({
                        name: child.attr.key,
                        registryUrl,
                        sourceMappedPackagePatterns,
                    }, `Adding registry URL ${registryUrl}`);
                    registries.push({
                        name: child.attr.key,
                        url: registryUrl,
                        sourceMappedPackagePatterns,
                    });
                }
                else {
                    logger_1.logger.debug({ registryUrl: child.attr.value }, 'ignoring local registry URL');
                }
            }
            // child.name === 'remove' not supported
        }
    }
    return registries;
}
exports.getConfiguredRegistries = getConfiguredRegistries;
function findVersion(parsedXml) {
    for (const tag of ['Version', 'VersionPrefix']) {
        for (const l1Elem of parsedXml.childrenNamed('PropertyGroup')) {
            for (const l2Elem of l1Elem.childrenNamed(tag)) {
                return l2Elem;
            }
        }
    }
    return null;
}
exports.findVersion = findVersion;
//# sourceMappingURL=util.js.map