"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JenkinsPluginsDatasource = void 0;
const tslib_1 = require("tslib");
const logger_1 = require("../../../logger");
const decorator_1 = require("../../../util/cache/package/decorator");
const clone_1 = require("../../../util/clone");
const url_1 = require("../../../util/url");
const datasource_1 = require("../datasource");
class JenkinsPluginsDatasource extends datasource_1.Datasource {
    static id = 'jenkins-plugins';
    constructor() {
        super(JenkinsPluginsDatasource.id);
    }
    customRegistrySupport = true;
    defaultRegistryUrls = ['https://updates.jenkins.io'];
    registryStrategy = 'hunt';
    static packageInfoPath = 'current/update-center.actual.json';
    static packageVersionsPath = 'current/plugin-versions.json';
    releaseTimestampSupport = true;
    releaseTimestampNote = 'The releaseTimestamp is determined from the `releaseTimestamp` or `buildDate` field in the results.';
    sourceUrlSupport = 'package';
    sourceUrlNote = 'The source URL is determined from the `scm` field in the results.';
    async getReleases({ packageName, registryUrl, }) {
        // istanbul ignore if
        if (!registryUrl) {
            return null;
        }
        const updateSiteUrl = (0, url_1.ensureTrailingSlash)(registryUrl);
        const plugins = await this.getJenkinsPluginInfo(updateSiteUrl);
        const plugin = plugins[packageName];
        if (!plugin) {
            return null;
        }
        const result = (0, clone_1.clone)(plugin);
        const versions = await this.getJenkinsPluginVersions(updateSiteUrl);
        const releases = versions[packageName];
        result.releases = releases ? (0, clone_1.clone)(releases) : [];
        return result;
    }
    async getJenkinsPluginInfo(updateSiteUrl) {
        const { plugins } = await this.getJenkinsUpdateCenterResponse(`${updateSiteUrl}${JenkinsPluginsDatasource.packageInfoPath}`);
        const info = {};
        for (const name of Object.keys(plugins ?? [])) {
            info[name] = {
                releases: [], // releases
                sourceUrl: plugins[name]?.scm,
            };
        }
        return info;
    }
    async getJenkinsPluginVersions(updateSiteUrl) {
        const { plugins } = await this.getJenkinsUpdateCenterResponse(`${updateSiteUrl}${JenkinsPluginsDatasource.packageVersionsPath}`);
        const versions = {};
        for (const name of Object.keys(plugins ?? [])) {
            versions[name] = Object.keys(plugins[name]).map((version) => {
                const downloadUrl = plugins[name][version]?.url;
                const buildDate = plugins[name][version]?.buildDate;
                const releaseTimestamp = plugins[name][version]?.releaseTimestamp ??
                    (buildDate ? new Date(`${buildDate} UTC`).toISOString() : null);
                const jenkins = plugins[name][version]?.requiredCore;
                const constraints = jenkins ? { jenkins: [`>=${jenkins}`] } : undefined;
                return {
                    version,
                    downloadUrl,
                    releaseTimestamp,
                    ...(constraints && { constraints }),
                };
            });
        }
        return versions;
    }
    async getJenkinsUpdateCenterResponse(url) {
        let response;
        try {
            logger_1.logger.debug(`jenkins-plugins: Fetching Jenkins plugins from ${url}`);
            const startTime = Date.now();
            response = (await this.http.getJson(url)).body;
            const durationMs = Math.round(Date.now() - startTime);
            logger_1.logger.debug({ durationMs }, `jenkins-plugins: Fetched Jenkins plugins from ${url}`);
        }
        catch (err) /* istanbul ignore next */ {
            this.handleGenericErrors(err);
        }
        return response;
    }
}
exports.JenkinsPluginsDatasource = JenkinsPluginsDatasource;
tslib_1.__decorate([
    (0, decorator_1.cache)({
        namespace: `datasource-${JenkinsPluginsDatasource.id}`,
        key: 'info',
        ttlMinutes: 1440,
    })
], JenkinsPluginsDatasource.prototype, "getJenkinsPluginInfo", null);
tslib_1.__decorate([
    (0, decorator_1.cache)({
        namespace: `datasource-${JenkinsPluginsDatasource.id}`,
        key: 'versions',
    })
], JenkinsPluginsDatasource.prototype, "getJenkinsPluginVersions", null);
//# sourceMappingURL=index.js.map