-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.ts
61 lines (54 loc) · 1.62 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { ExternalHostError } from '../../types/errors/external-host-error';
import { Http } from '../../util/http';
import type { GetReleasesConfig, ReleaseResult } from '../types';
export const id = 'cdnjs';
export const registryUrlRestriction = 'fixed';
export const defaultRegistryUrls = ['https://api.cdnjs.com/'];
export const caching = true;
const http = new Http(id);
interface CdnjsAsset {
version: string;
files: string[];
sri?: Record<string, string>;
}
interface CdnjsResponse {
homepage?: string;
repository?: {
type: 'git' | unknown;
url?: string;
};
assets?: CdnjsAsset[];
}
export async function getReleases({
lookupName,
registryUrl,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
// Each library contains multiple assets, so we cache at the library level instead of per-asset
const library = lookupName.split('/')[0];
const url = `${registryUrl}libraries/${library}?fields=homepage,repository,assets`;
try {
const { assets, homepage, repository } = (
await http.getJson<CdnjsResponse>(url)
).body;
if (!assets) {
return null;
}
const assetName = lookupName.replace(`${library}/`, '');
const releases = assets
.filter(({ files }) => files.includes(assetName))
.map(({ version, sri }) => ({ version, newDigest: sri[assetName] }));
const result: ReleaseResult = { releases };
if (homepage) {
result.homepage = homepage;
}
if (repository?.url) {
result.sourceUrl = repository.url;
}
return result;
} catch (err) {
if (err.statusCode !== 404) {
throw new ExternalHostError(err);
}
throw err;
}
}