"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPackageFile = extractPackageFile;
const tslib_1 = require("tslib");
const upath_1 = require("upath");
const logger_1 = require("../../../logger");
const array_1 = require("../../../util/array");
const schema_utils_1 = require("../../../util/schema-utils");
const bazelrc = tslib_1.__importStar(require("./bazelrc"));
const parser_1 = require("./parser");
const maven_1 = require("./parser/maven");
const rules_1 = require("./rules");
const rules = tslib_1.__importStar(require("./rules"));
async function extractPackageFile(content, packageFile) {
    try {
        const records = (0, parser_1.parse)(content);
        const pfc = await extractBazelPfc(records, packageFile);
        const mavenDeps = extractMavenDeps(records);
        if (mavenDeps.length) {
            pfc.deps.push(...mavenDeps);
        }
        return pfc.deps.length ? pfc : null;
    }
    catch (err) {
        logger_1.logger.debug({ err, packageFile }, 'Failed to parse bazel module file.');
        return null;
    }
}
async function extractBazelPfc(records, packageFile) {
    const pfc = (0, schema_utils_1.LooseArray)(rules_1.RuleToBazelModulePackageDep)
        .transform(rules.toPackageDependencies)
        .transform((deps) => ({ deps }))
        .parse(records);
    const registryUrls = (await bazelrc.read((0, upath_1.dirname)(packageFile)))
        // Ignore any entries for custom configurations
        .filter((ce) => ce.config === undefined)
        .map((ce) => ce.getOption('registry')?.value)
        .filter(array_1.isNotNullOrUndefined);
    if (registryUrls.length) {
        pfc.registryUrls = registryUrls;
    }
    return pfc;
}
function extractMavenDeps(records) {
    return (0, schema_utils_1.LooseArray)(maven_1.RuleToMavenPackageDep)
        .transform(maven_1.fillRegistryUrls)
        .parse(records);
}
//# sourceMappingURL=extract.js.map