"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CdnJsDatasource = void 0;
const zod_1 = require("zod");
const logger_1 = require("../../../logger");
const external_host_error_1 = require("../../../types/errors/external-host-error");
const result_1 = require("../../../util/result");
const datasource_1 = require("../datasource");
const schema_1 = require("../schema");
const Homepage = zod_1.z.string().optional().catch(undefined);
const Repository = zod_1.z
    .object({
    type: zod_1.z.literal('git'),
    url: zod_1.z.string(),
})
    .transform(({ url }) => url)
    .optional()
    .catch(undefined);
const Assets = zod_1.z.array(zod_1.z.object({
    version: zod_1.z.string(),
    files: zod_1.z.string().array(),
    sri: zod_1.z.record(zod_1.z.string()).optional(),
}));
class CdnJsDatasource extends datasource_1.Datasource {
    static id = 'cdnjs';
    constructor() {
        super(CdnJsDatasource.id);
    }
    customRegistrySupport = false;
    defaultRegistryUrls = ['https://api.cdnjs.com/'];
    caching = true;
    async getReleases(config) {
        const result = result_1.Result.wrap(schema_1.ReleasesConfig.safeParse(config))
            .transform(({ packageName, registryUrl }) => {
            const [library] = packageName.split('/');
            const assetName = packageName.replace(`${library}/`, '');
            const url = `${registryUrl}libraries/${library}?fields=homepage,repository,assets`;
            const schema = zod_1.z.object({
                homepage: Homepage,
                repository: Repository,
                assets: Assets.transform((assets) => assets
                    .filter(({ files }) => files.includes(assetName))
                    .map(({ version, sri }) => {
                    const res = { version };
                    const newDigest = sri?.[assetName];
                    if (newDigest) {
                        res.newDigest = newDigest;
                    }
                    return res;
                })),
            });
            return this.http.getJsonSafe(url, schema);
        })
            .transform(({ assets, homepage, repository }) => {
            const releases = assets;
            const res = { releases };
            if (homepage) {
                res.homepage = homepage;
            }
            if (repository) {
                res.sourceUrl = repository;
            }
            return res;
        });
        const { val, err } = await result.unwrap();
        if (err instanceof zod_1.ZodError) {
            logger_1.logger.debug({ err }, 'cdnjs: validation error');
            return null;
        }
        if (err) {
            this.handleGenericErrors(err);
        }
        return val;
    }
    handleHttpErrors(err) {
        if (err.response?.statusCode !== 404) {
            throw new external_host_error_1.ExternalHostError(err);
        }
    }
}
exports.CdnJsDatasource = CdnJsDatasource;
//# sourceMappingURL=index.js.map