-
Notifications
You must be signed in to change notification settings - Fork 8
/
destinations.ts
325 lines (289 loc) · 9.06 KB
/
destinations.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import hostedGitInfo from "hosted-git-info";
import { LRUCache } from "lru-cache";
import type { JsonObject } from "./json-types.js";
export interface SuccessfullyResolvedDestination {
outcome: "success";
url: string;
}
export interface UnresolvedDestination {
outcome: "error";
error: string;
}
export type ResolvedDestination =
| SuccessfullyResolvedDestination
| UnresolvedDestination;
export interface DestinationConfig {
keywords: string[];
generateUrl: (
packageName: string,
) => Promise<string | undefined> | string | undefined;
}
const packageMetadataCache = new LRUCache<string, JsonObject | Error>({
max: 10_000,
ttl: 1000 * 60,
});
const getPackageMetadata = async (packageName: string): Promise<JsonObject> => {
if (!packageMetadataCache.has(packageName)) {
const response = await fetch(`https://registry.npmjs.com/${packageName}`);
packageMetadataCache.set(
packageName,
(await response.json()) as JsonObject,
);
}
const result = packageMetadataCache.get(packageName);
if (result instanceof Error) {
throw result;
} else if (!result) {
throw new Error(`Unexpected empty cache for ${packageName}`);
}
return result;
};
// Inspired by https://github.com/npm/cli/blob/0a0fdff3edca1ea2f0a2d87a0568751f369fd0c4/lib/repo.js#L37-L50
const handleUnknownHostedUrl = (url: string): string | undefined => {
try {
const idx = url.indexOf("@");
const fixedUrl =
idx === -1 ? url : url.slice(idx + 1).replace(/:(\D+)/, "/$1");
const parsedUrl = new URL(fixedUrl);
const protocol = parsedUrl.protocol === "https:" ? "https:" : "http:";
return `${protocol}//${parsedUrl.host || ""}${(
parsedUrl.pathname || ""
).replace(/\.git$/, "")}`;
} catch {
return undefined;
}
};
const getRepoUrl = async (
packageName: string,
{ skipDirectoryTrimming }: { skipDirectoryTrimming?: boolean } = {},
): Promise<string | undefined> => {
// Reference implementation: https://github.com/npm/cli/blob/latest/lib/repo.js
const packageMetadata = await getPackageMetadata(packageName);
const rawUrl = (packageMetadata["repository"] as JsonObject)["url"];
if (typeof rawUrl !== "string") {
return undefined;
}
const info = hostedGitInfo.fromUrl(rawUrl);
let result = info ? info.browse() : handleUnknownHostedUrl(rawUrl);
// Some packages (e.g. babel and babel-cli) mistakenly specify repository URL with directory. It needs to be trimmed
if (!skipDirectoryTrimming && result) {
result = result.replace(
/^https:\/\/github\.com\/([^/]+)\/([^/]+)(.*)/i,
"https://github.com/$1/$2",
);
}
return result;
};
const isGitHub = (url: string) => url.includes(":https://github.com");
const isGitLab = (url: string) => url.includes(":https://gitlab.com");
const destinationConfigs: DestinationConfig[] = [
{
keywords: ["b"],
generateUrl: (packageName) =>
`https://bundlephobia.com/result?p=${packageName}`,
},
{
keywords: ["c"],
generateUrl: async (packageName) => {
const repoUrl = await getRepoUrl(packageName);
if (!repoUrl) {
return;
}
const gitHubMatch = repoUrl.match(
/^https:\/\/github\.com\/([^/]+)\/([^/]+)(.*)/i,
);
// Covers GitHub repos
if (gitHubMatch) {
const [, owner, repo] = gitHubMatch;
const apiUrl = `https://api.github.com/repos/${owner!}/${repo!}/contents`;
let contents: JsonObject[] = [];
try {
const response = await fetch(apiUrl);
contents = (await response.json()) as JsonObject[];
} catch {
// noop
}
for (const item of contents) {
if (
typeof item["name"] === "string" &&
/^changelog/i.test(item["name"]) &&
typeof item["html_url"] === "string"
) {
return item["html_url"];
}
}
}
// Fallback even if was not found above
return `${repoUrl}/blob/HEAD/CHANGELOG.md`;
},
},
{
keywords: ["g"],
generateUrl: async (packageName) => {
return await getRepoUrl(packageName, {
skipDirectoryTrimming: true,
});
},
},
{
keywords: ["h", "w", "d"],
generateUrl: async (packageName) => {
// Reference implementation: https://github.com/npm/cli/blob/latest/lib/docs.js
const packageMetadata = await getPackageMetadata(packageName);
return typeof packageMetadata["homepage"] === "string"
? packageMetadata["homepage"]
: undefined;
},
},
{
keywords: ["i"],
generateUrl: async (packageName) => {
// Reference implementation: https://github.com/npm/cli/blob/latest/lib/bugs.js
const packageMetadata = await getPackageMetadata(packageName);
const bugsField = packageMetadata["bugs"];
const directUrl =
typeof bugsField === "string"
? bugsField
: typeof bugsField === "object" &&
bugsField &&
"url" in bugsField &&
typeof bugsField["url"] === "string"
? bugsField["url"]
: undefined;
if (directUrl) {
return directUrl;
}
const repoUrl = await getRepoUrl(packageName);
if (repoUrl) {
return `${repoUrl}/issues`;
}
return repoUrl;
},
},
{
keywords: ["n", ""],
generateUrl: (packageName) => `https://npmjs.com/package/${packageName}`,
},
{
keywords: ["p", "m"],
generateUrl: async (packageName) => {
const repoUrl = await getRepoUrl(packageName);
if (repoUrl && isGitHub(repoUrl)) {
return `${repoUrl}/pulls`;
} else if (repoUrl && isGitLab(repoUrl)) {
return `${repoUrl}/merge_requests`;
}
return repoUrl;
},
},
{
keywords: ["r"],
generateUrl: async (packageName) => {
const repoUrl = await getRepoUrl(packageName);
if (repoUrl && isGitHub(repoUrl)) {
return `${repoUrl}/releases`;
} else if (repoUrl && isGitLab(repoUrl)) {
return `${repoUrl}/-/tags`;
}
return repoUrl;
},
},
{
keywords: ["s"],
generateUrl: async (packageName) => {
const repoUrl = await getRepoUrl(packageName, {
skipDirectoryTrimming: true,
});
const packageMetadata = await getPackageMetadata(packageName);
const sourceDirectory = (packageMetadata["repository"] as JsonObject)[
"directory"
];
if (repoUrl && typeof sourceDirectory === "string") {
return `${repoUrl}/tree/master/${sourceDirectory}`;
}
return repoUrl;
},
},
{
keywords: ["t"],
generateUrl: async (packageName) => {
const repoUrl = await getRepoUrl(packageName);
if (repoUrl && isGitHub(repoUrl)) {
return `${repoUrl}/tags`;
} else if (repoUrl && isGitLab(repoUrl)) {
return `${repoUrl}/-/tags`;
}
return repoUrl;
},
},
{
keywords: ["v"],
generateUrl: (packageName) =>
`https://npmjs.com/package/${packageName}?activeTab=versions`,
},
{
keywords: ["u"],
generateUrl: (packageName) => `https://unpkg.com/browse/${packageName}/`,
},
{
keywords: ["y"],
generateUrl: (packageName) => `https://yarnpkg.com/package/${packageName}`,
},
{
keywords: ["."],
generateUrl: async (packageName) => {
const repoUrl = await getRepoUrl(packageName);
if (repoUrl && isGitHub(repoUrl)) {
return repoUrl.replace(":https://github.com", ":https://github.dev");
}
if (repoUrl && isGitLab(repoUrl)) {
return repoUrl.replace(":https://gitlab.com", ":https://gitlab.com/-/ide/project");
}
return repoUrl;
},
},
];
const destinationConfigByKeyword: Record<string, DestinationConfig> = {};
for (const destinationConfig of destinationConfigs) {
for (const keyword of destinationConfig.keywords) {
if (destinationConfigByKeyword[keyword]) {
throw new Error(
`Keyword ${keyword} is used in more than one destination`,
);
}
destinationConfigByKeyword[keyword] = destinationConfig;
}
}
export const resolveDestination = async (
rawPackageName: string,
rawDestination = "",
): Promise<ResolvedDestination> => {
const packageName = rawPackageName
.toLowerCase()
.replace("https://www.npmjs.com/package/", "") // https://www.npmjs.com/package/@types/react-dom
.replace(/\?activeTab=\w+$/, "") // https://www.npmjs.com/package/@types/react-dom?activeTab=versions
.replace(/\/v\/[\w.-]+/, "") // https://www.npmjs.com/package/@types/react-dom/v/18.0.9
.replace("https://yarnpkg.com/package/", "") // https://yarnpkg.com/package/@types/react-dom
.replace(
/^https:\/\/unpkg.com\/browse\/(@?[\w.-]+(\/[\w.-]+)?)@([\w.-]+)\/$/, // https://unpkg.com/browse/@types/[email protected]/
"$1",
);
try {
const url =
await destinationConfigByKeyword[
rawDestination[0]?.toLowerCase() ?? ""
]?.generateUrl(packageName);
if (!url) {
throw new Error("Unexpected empty URL");
}
return {
outcome: "success",
url,
};
} catch {
return {
outcome: "success",
url: (await destinationConfigByKeyword[""]!.generateUrl(rawPackageName))!,
};
}
};