"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractDepFromFragment = exports.coerceFragmentToTarget = exports.supportedRulesRegex = void 0;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const logger_1 = require("../../../../logger");
const regex_1 = require("../../../../util/regex");
const docker_1 = require("./docker");
const git_1 = require("./git");
const go_1 = require("./go");
const http_1 = require("./http");
const dependencyExtractorRegistry = {
    git_repository: git_1.gitDependency,
    go_repository: go_1.goDependency,
    http_archive: http_1.httpDependency,
    http_file: http_1.httpDependency,
    container_pull: docker_1.dockerDependency,
};
const supportedRules = Object.keys(dependencyExtractorRegistry);
exports.supportedRulesRegex = (0, regex_1.regEx)(`^${supportedRules.join('|')}$`);
function isTarget(x) {
    return is_1.default.string(x.name) && is_1.default.string(x.rule);
}
function coerceFragmentToTarget(fragment) {
    if (fragment.type === 'record') {
        const { children } = fragment;
        const target = {};
        for (const [key, value] of Object.entries(children)) {
            if (value.type === 'array') {
                const values = value.children
                    .filter((x) => x.type === 'string')
                    .map((x) => x.value);
                target[key] = values;
            }
            else if (value.type === 'string') {
                target[key] = value.value;
            }
        }
        if (isTarget(target)) {
            return target;
        }
    }
    return null;
}
exports.coerceFragmentToTarget = coerceFragmentToTarget;
function extractDepFromFragment(fragment) {
    const target = coerceFragmentToTarget(fragment);
    if (!target) {
        return null;
    }
    const dependencyExtractor = dependencyExtractorRegistry[target.rule];
    if (!dependencyExtractor) {
        logger_1.logger.debug(`Bazel dependency extractor function not found for ${target.rule}`);
        return null;
    }
    return dependencyExtractor(target);
}
exports.extractDepFromFragment = extractDepFromFragment;
//# sourceMappingURL=index.js.map