/
index.js
262 lines (217 loc) · 6.88 KB
/
index.js
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
const reservedPaths = require('github-reserved-names/reserved-names.json');
const patchDiffRegex = /[.](patch|diff)$/;
const releaseRegex = /^releases[/]tag[/]([^/]+)/;
const labelRegex = /^labels[/]([^/]+)/;
const compareRegex = /^compare[/]([^/]+)/;
const pullRegex = /^pull[/](?<pull>\d+)(?:[/](?<pullPage>[^/]+))?(?:[/](?<pullPartialStart>[\da-f]{40})[.][.](?<pullPartialEnd>[\da-f]{40}))?$/;
const issueRegex = /^issues[/](\d+)$/;
const commitRegex = /^commit[/]([\da-f]{40})$/;
const releaseArchiveRegex = /^archive[/](.+)([.]zip|[.]tar[.]gz)/;
const releaseDownloadRegex = /^releases[/]download[/]([^/]+)[/](.+)/;
const dependentsRegex = /^network[/]dependents[/]?$/;
const dependenciesRegex = /^network[/]dependencies[/]?$/;
const wikiRegex = /^wiki[/](.+)$/;
function styleRevision(revision) {
if (!revision) {
return;
}
revision = revision.replace(patchDiffRegex, '');
if (/^[0-9a-f]{40}$/.test(revision)) {
revision = revision.slice(0, 7);
}
return `<code>${revision}</code>`;
}
function commentIndicator(hash) {
if (hash.startsWith('#issue-') || hash.startsWith('#commitcomment-')) {
return ' (comment)';
}
if (hash.startsWith('#pullrequestreview-') || hash.startsWith('#discussion_r')) {
return ' (review)';
}
return '';
}
// Filter out null values
function joinValues(array, delimiter = '/') {
return array.filter(Boolean).join(delimiter);
}
function shortenURL(href, currentUrl = 'https://github.com') {
if (!href) {
return;
}
currentUrl = new URL(currentUrl);
const currentRepo = currentUrl.pathname.slice(1).split('/', 2).join('/');
/**
* Parse URL
*/
const url = new URL(href);
const {
origin,
pathname,
search,
searchParams,
hash,
} = url;
const pathnameParts = pathname.slice(1).split('/'); // ['user', 'repo', 'pull', '342']
const repoPath = pathnameParts.slice(2).join('/'); // 'pull/342'
const isRaw = [
'https://raw.githubusercontent.com',
'https://cdn.rawgit.com',
'https://rawgit.com',
].includes(origin);
const isRedirection = [
'https://togithub.com', // Renovate
'https://github-redirect.dependabot.com', // Dependabot
].includes(origin);
let [
user,
repo,
type,
revision,
...filePath
] = pathnameParts;
if (isRaw) {
[
user,
repo,
// Raw URLs don't have `blob` here
revision,
...filePath
] = pathnameParts;
type = 'raw';
}
revision = styleRevision(revision);
filePath = filePath.join('/');
const isLocal = origin === currentUrl.origin;
const isThisRepo = (isLocal || isRaw || isRedirection) && currentRepo === `${user}/${repo}`;
const isReserved = reservedPaths.includes(user);
const isDependents = dependentsRegex.test(repoPath);
const isDependencies = dependenciesRegex.test(repoPath);
const [, diffOrPatch] = repoPath.match(patchDiffRegex) || [];
const [, release] = repoPath.match(releaseRegex) || [];
const [, releaseTag, releaseTagExt] = repoPath.match(releaseArchiveRegex) || [];
const [, downloadTag, downloadFilename] = repoPath.match(releaseDownloadRegex) || [];
const [, label] = repoPath.match(labelRegex) || [];
const [, compare] = repoPath.match(compareRegex) || [];
const {pull, pullPage, pullPartialStart, pullPartialEnd} = repoPath.match(pullRegex)?.groups ?? {};
const [, issue] = isRedirection ? repoPath.match(issueRegex) || [] : [];
const [, commit] = isRedirection ? repoPath.match(commitRegex) || [] : [];
const [, wiki] = repoPath.match(wikiRegex) || [];
const isFileOrDir = revision && [
'raw',
'tree',
'blob',
'blame',
'commits',
].includes(type);
const repoUrl = isThisRepo ? '' : `${user}/${repo}`;
/**
* Shorten URL
*/
if (isReserved || pathname === '/' || (!isLocal && !isRaw && !isRedirection)) {
return href
.replace(/^https:[/][/]/, '')
.replace(/^www[.]/, '')
.replace(/[/]$/, '');
}
if (user && !repo) {
return `@${user}${search}${hash}`;
}
if (isFileOrDir) {
const revisioned = joinValues(
[joinValues([repoUrl, revision], '@'), filePath],
'/',
);
const partial = `${revisioned}${search}${hash}`;
if (type !== 'blob' && type !== 'tree') {
return `${partial} (${type})`;
}
return partial;
}
if (diffOrPatch) {
const partial = joinValues([repoUrl, revision], '@');
return `${partial}.${diffOrPatch}${search}${hash}`;
}
if (release) {
const partial = joinValues([repoUrl, `<code>${release}</code>`], '@');
return `${partial}${search}${hash} (release)`;
}
if (releaseTagExt) {
const partial = joinValues([repoUrl, `<code>${releaseTag}</code>`], '@');
return `${partial}${releaseTagExt}${search}${hash}`;
}
if (downloadFilename) {
const partial = joinValues([repoUrl, `<code>${downloadTag}</code>`], '@');
return `${partial} ${downloadFilename}${search}${hash} (download)`;
}
if (label) {
return (
joinValues([repoUrl, decodeURIComponent(label)])
+ `${search}${hash} (label)`
);
}
if (isDependents) {
return `${user}/${repo} (dependents)`;
}
if (isDependencies) {
return `${user}/${repo} (dependencies)`;
}
if (pull) {
if (pullPage === 'files' && pullPartialStart && pullPartialEnd) {
return `<code>${pullPartialStart.slice(0, 8)}..${pullPartialEnd.slice(0, 8)}</code> (#${pull})`;
}
if (pullPage) {
return `${repoUrl}#${pull} (${pullPage})`;
}
}
if (compare) {
const partial = joinValues([repoUrl, revision], '@');
return `${partial}${search}${hash} (compare)`;
}
if (wiki) {
return `Wiki: ${decodeURIComponent((wiki + (hash ? ' (' + hash.slice(1) + ')' : '')).replaceAll('-', ' '))} (${repoUrl})`;
}
// Shorten URLs that would otherwise be natively shortened
if (isRedirection) {
if (issue) {
return `${repoUrl}#${issue}${commentIndicator(hash)}`;
}
if (pull) {
return `${repoUrl}#${pull}${commentIndicator(hash)}`;
}
if (commit) {
return joinValues([repoUrl, `<code>${commit.slice(0, 7)}</code>`], '@') + commentIndicator(hash);
}
}
let query = searchParams.get('q') ?? '';
if (query) {
searchParams.delete('q');
if (pathname.endsWith('/issues')) {
query = query.replace('is:issue', '');
} else if (pathname.endsWith('/pulls')) {
query = query.replace('is:pr', '');
}
query = ` (${query.replaceAll(/\s+/g, ' ').trim()})`;
}
if (searchParams.get('tab') === 'readme-ov-file') {
searchParams.delete('tab');
}
// Drop leading and trailing slash of relative path
return pathname.replaceAll(/^[/]|[/]$/g, '') + url.search + hash + query;
}
function applyToLink(a, currentUrl) {
// Shorten only if the link name hasn't been customized.
// .href automatically adds a / to naked origins so that needs to be tested too
// `trim` makes it compatible with this feature: https://github.com/sindresorhus/refined-github/pull/3085
const url = a.dataset.originalHref ?? a.href;
if (
(url === a.textContent.trim() || url === `${a.textContent}/`)
&& !a.firstElementChild
) {
const shortened = shortenURL(url, currentUrl);
a.innerHTML = shortened;
return true;
}
return false;
}
module.exports = shortenURL;
module.exports.applyToLink = applyToLink;