"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrbDatasource = void 0;
const tslib_1 = require("tslib");
const logger_1 = require("../../../logger");
const decorator_1 = require("../../../util/cache/package/decorator");
const datasource_1 = require("../datasource");
const MAX_VERSIONS = 100;
const query = `
query($packageName: String!, $maxVersions: Int!) {
  orb(name: $packageName) {
    name,
    homeUrl,
    isPrivate,
    versions(count: $maxVersions) {
      version,
      createdAt
    }
  }
}
`;
class OrbDatasource extends datasource_1.Datasource {
    static id = 'orb';
    constructor() {
        super(OrbDatasource.id);
    }
    customRegistrySupport = false;
    defaultRegistryUrls = ['https://circleci.com/'];
    releaseTimestampSupport = true;
    releaseTimestampNote = 'The release timestamp is determined from the `createdAt` field in the results.';
    async getReleases({ packageName, registryUrl, }) {
        // istanbul ignore if
        if (!registryUrl) {
            return null;
        }
        const url = `${registryUrl}graphql-unstable`;
        const body = {
            query,
            variables: { packageName, maxVersions: MAX_VERSIONS },
        };
        const res = (await this.http.postJson(url, {
            body,
        })).body;
        if (!res?.data?.orb) {
            logger_1.logger.debug({ res }, `Failed to look up orb ${packageName}`);
            return null;
        }
        const { orb } = res.data;
        // Simplify response before caching and returning
        const homepage = orb.homeUrl?.length
            ? orb.homeUrl
            : `https://circleci.com/developer/orbs/orb/${packageName}`;
        const releases = orb.versions.map(({ version, createdAt }) => ({
            version,
            releaseTimestamp: createdAt ?? null,
        }));
        const dep = { homepage, isPrivate: !!orb.isPrivate, releases };
        logger_1.logger.trace({ dep }, 'dep');
        return dep;
    }
}
exports.OrbDatasource = OrbDatasource;
tslib_1.__decorate([
    (0, decorator_1.cache)({
        namespace: `datasource-${OrbDatasource.id}`,
        key: ({ packageName }) => packageName,
    })
], OrbDatasource.prototype, "getReleases", null);
//# sourceMappingURL=index.js.map