"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Endpoint = void 0;
exports.fetchJSONFile = fetchJSONFile;
exports.getPresetFromEndpoint = getPresetFromEndpoint;
exports.getPreset = getPreset;
const tslib_1 = require("tslib");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const logger_1 = require("../../../logger");
const external_host_error_1 = require("../../../types/errors/external-host-error");
const gitlab_1 = require("../../../util/http/gitlab");
const util_1 = require("../util");
const gitlabApi = new gitlab_1.GitlabHttp();
exports.Endpoint = 'https://gitlab.com/api/v4/';
async function getDefaultBranchName(urlEncodedPkgName, endpoint) {
    const res = await gitlabApi.getJson(`${endpoint}projects/${urlEncodedPkgName}`);
    return res.body.default_branch ?? 'master'; // should never happen, but we keep this to ensure the current behavior
}
async function fetchJSONFile(repo, fileName, endpoint, tag) {
    let url = endpoint;
    let ref = '';
    let res;
    try {
        const urlEncodedRepo = encodeURIComponent(repo);
        const urlEncodedPkgName = encodeURIComponent(fileName);
        if (is_1.default.nonEmptyString(tag)) {
            ref = `?ref=${tag}`;
        }
        else {
            const defaultBranchName = await getDefaultBranchName(urlEncodedRepo, endpoint);
            ref = `?ref=${defaultBranchName}`;
        }
        url += `projects/${urlEncodedRepo}/repository/files/${urlEncodedPkgName}/raw${ref}`;
        logger_1.logger.trace({ url }, `Preset URL`);
        res = await gitlabApi.get(url);
    }
    catch (err) {
        if (err instanceof external_host_error_1.ExternalHostError) {
            throw err;
        }
        logger_1.logger.debug(`Preset file ${fileName} not found in ${repo}`);
        throw new Error(util_1.PRESET_DEP_NOT_FOUND);
    }
    return (0, util_1.parsePreset)(res.body, fileName);
}
function getPresetFromEndpoint(repo, presetName, presetPath, endpoint = exports.Endpoint, tag) {
    return (0, util_1.fetchPreset)({
        repo,
        filePreset: presetName,
        presetPath,
        endpoint,
        tag,
        fetch: fetchJSONFile,
    });
}
function getPreset({ repo, presetPath, presetName = 'default', tag = undefined, }) {
    return getPresetFromEndpoint(repo, presetName, presetPath, exports.Endpoint, tag);
}
//# sourceMappingURL=index.js.map