-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
2424 lines (2038 loc) · 82.3 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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
javascript:/* eslint-disable-line no-unused-labels *//*
* # NgSlackLinkifier vX.Y.Z-VERSION
*
* ## What it does
*
* **It converts...**
*
* - Markdown-like links (of the form `[some text](/some/url)`) to actual links.
*
* - URLs to GitHub commits to short links. E.g.:
* - `https://github.com/angular/angular/commit/a1b2c3d4e5` --> `angular@a1b2c3d4e5`
* - `https://github.com/angular/angular-cli/commit/b2c3d4e5f6` --> `angular-cli@b2c3d4e5f6`
* - `https://github.com/not-angular/some-lib/commit/c3d4e5f` --> `not-angular/some-lib@c3d4e5f`
*
* - GitHub commits of the format `[<owner>/]<repo>@<sha>` to links. If omitted `<owner>` defaults to `angular`. In
* order for commits to be recognized at least the first 7 characters of the SHA must be provided. E.g.:
* - `angular@a1b2c3d` or `angular/angular@a1b2c3d` -->
* `[angular@a1b2c3d](https://github.com/angular/angular/commit/a1b2c3d)`
* - `angular-cli@b2c3d4e5f6` or `angular/angular-cli@b2c3d4e5f6` -->
* `[`angular-cli@b2c3d4e`](https://github.com/angular/angular-cli/commit/b2c3d4e5f6)`
* - `not-angular/some-lib@c3d4e5f6` -->
* `[not-angular/some-lib@c3d4e5f](https://github.com/not-angular/some-lib/commit/c3d4e5f6)`
*
* - URLs to GitHub issues/PRs to short links. E.g.:
* - `https://github.com/angular/angular/issues/12345` --> `#12345`
* - `https://github.com/angular/angular-cli/pull/23456` --> `angular-cli#23456`
* - `https://github.com/not-angular/some-lib/pull/34567` --> `not-angular/some-lib@#34567`
*
* - GitHub issues/PRs of the format `[[<owner>/]<repo>]#<issue-or-pr>` to links. If omitted `<owner>` and `<repo>`
* default to `angular`. E.g.:
* - `#12345` or `angular#12345` or `angular/angular#12345` -->
* `[#12345](https://github.com/angular/angular/issues/12345)`
* - `angular-cli#23456` or `angular/angular-cli#23456` -->
* `[angular-cli#23456](https://github.com/angular/angular-cli/issues/23456)`
* - `not-angular/some-lib#34567` -->
* [not-angular/some-lib#34567](https://github.com/not-angular/some-lib/issues/34567)`
*
* - URLs to Jira-like issues for `angular-team` to short links. (Recognizes the format `XYZ-<number>`.) E.g.:
* - `https://angular-team.atlassian.net/browse/FW-12345` --> `FW-12345`
* - `https://angular-team.atlassian.net/browse/TOOL-23456` --> `TOOL-23456`
* - `https://angular-team.atlassian.net/browse/COMP-34567` --> `COMP-34567`
*
* - Jira-like issues for `angular-team` to links. (Recognizes the format `XYZ-<number>`.) E.g.:
* - `FW-12345` --> `[FW-12345](https://angular-team.atlassian.net/browse/FW-12345)`
* - `TOOL-23456` --> `[TOOL-23456](https://angular-team.atlassian.net/browse/TOOL-23456)`
* - `COMP-34567` --> `[COMP-34567](https://angular-team.atlassian.net/browse/COMP-34567)`
*
* **It shows...**
*
* - Popups with basic info (title, description, author, state, labels), when hovering over links to GitHub issues/PRs.
*
* ---
* **Note:**
* Currently, GitHub URLs are recognized if they end in the GitHub issue/PR number.
* E.g. `.../issues/12345` is recongized, but `.../issues/12345/files` or `.../issues/12345#issuecomment-67890` isn't.
*/
((window, document) => {'use strict';
/* Constants */
const NAME = 'NgSlackLinkifier';
const VERSION = 'X.Y.Z-VERSION';
const CLASS_GITHUB_COMMIT_LINK = 'nsl-github-commit';
const CLASS_GITHUB_ISSUE_LINK = 'nsl-github-issue';
const CLASS_JIRA_LINK = 'nsl-jira';
const CLASS_PROCESSED = 'nsl-processed';
const CLASS_POST_PROCESSED = 'nsl-post-processed';
/* Helpers */
const hasOwnProperty = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
/*
* Encoded entities must not appear as is in the source code, because the browser may automatically decode them, when
* the script is used as a bookmarklet. Since minification may concatenate strings and replace constants, the `%`
* symbol of encoded entities are further encoded as `{{P}}` and decoded at runtime.
*/
const perc = input => input.replace(/\{\{P}}/g, '%');
/* Classes */
class AbstractInfoProvider {
static get TOKEN_NAME() { return this._notImplemented(); }
static get TOKEN_DESCRIPTION_HTML() { return this._notImplemented(); }
static validateToken(token) {
if (!token || (typeof token !== 'string')) {
throw new Error(`Empty or invalid token (${typeof token}: ${token}). Please, provide a non-empty string.`);
}
}
constructor() {
this._cacheMaxAge = 60000;
this._cache = new Map();
this.setToken(null);
}
cleanUp() {
this.setToken(null);
this._cache.clear();
}
hasToken() { return this._token !== undefined; }
requiresToken() { return this._notImplemented(); }
setToken(token) {
this._token = token || undefined;
this._headers = this._token && this._generateHeaders(this._token);
}
_generateHeaders(token) { this._notImplemented(token); }
_getErrorConstructorExtending(BaseConstructor) {
const provider = this;
return class extends BaseConstructor {
get provider() { return provider; }
};
}
_getErrorForResponse(res) { this._notImplemented(res); }
_getFromCache(url) {
if (!this._cache.has(url)) return undefined;
const {date, response} = this._cache.get(url);
if ((Date.now() - date) > this._cacheMaxAge) {
this._cache.delete(url);
return undefined;
}
return response;
}
async _getJson(url) {
let responsePromise = this._getFromCache(url);
if (!responsePromise) {
responsePromise = window.fetch(url, {headers: {Accept: 'application/json', ...this._headers}}).
then(async res => res.ok ?
{data: await res.json(), headers: res.headers} :
Promise.reject(await this._getErrorForResponse(res))).
catch(err => {
if (this._getFromCache(url) === responsePromise) this._cache.delete(url);
throw err;
});
this._cache.set(url, {date: Date.now(), response: responsePromise});
}
return responsePromise;
}
_notImplemented() { throw new Error('Not implemented.'); }
_wrapError(err, message) {
const ErrorConstructor = (err instanceof Error) ? err.constructor : Error;
return new ErrorConstructor(`${message}\n${err.message || err}`);
}
}
class AbstractInvalidTokenError extends Error {
get provider() { throw new Error('Not implemented.'); }
}
class CleaningUpMarkerError extends Error {
constructor() { super('Cleaning up.'); }
}
class Deferred {
constructor() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
class GithubUtils extends AbstractInfoProvider {
static get TOKEN_NAME() { return 'GitHub access token'; }
static get TOKEN_DESCRIPTION_HTML() {
const tokenName = this.TOKEN_NAME;
const tokenUrl = 'https://github.com/settings/tokens/new';
return `
<p>
A ${tokenName} can be used to make authenticated requests to GitHub's API, when retrieving info for links to
issues and PRs. Authenticated requests have a much higher limit for requests per hour (at the time of writing
5000 vs 60 for anonymous requests).
</p>
<p>
To create a ${tokenName} visit: <a href="${tokenUrl}?description=${NAME}" target="_blank">${tokenUrl}</a>
<i>(no scopes required)</i>
</p>
`;
}
constructor() {
super();
this._baseUrl = 'https://api.github.com/repos';
this._rateLimitResetTime = 0;
}
async getCommitInfo(owner, repo, commit) {
try {
const url = `${this._baseUrl}/${owner}/${repo}/commits/${commit}`;
const {data} = await this._getJson(url);
const {files, stats} = this._extractFileInfo(data.files);
return {
sha: data.sha,
message: data.commit.message,
author: this._extractUserInfo(data.author),
committer: data.commiter && this._extractUserInfo(data.committer),
authorDate: new Date(data.commit.author.date),
committerDate: new Date(data.commit.committer.date),
stats: data.stats,
files,
filesUrl: data.html_url,
/*
* GitHub seems to send the first 300 files, but there is no direct way to tell whether there are more files.
* Try to infer that by comparing the total changes in `data.stats` and in `data.files`.
*/
hasMoreFiles: data.stats.total !== stats.total,
};
} catch (err) {
throw this._wrapError(err, `Error getting GitHub info for ${owner}/${repo}@${commit}:`);
}
}
async getIssueInfo(owner, repo, number) {
try {
const url = `${this._baseUrl}/${owner}/${repo}/issues/${number}`;
const {data} = await this._getJson(url);
const isPr = hasOwnProperty(data, 'pull_request');
let prInfo = null;
if (isPr) {
const prFilesUrl = `${this._baseUrl}/${owner}/${repo}/pulls/${number}/files?per_page=50`;
const {headers, data: rawFiles} = await this._getJson(prFilesUrl);
const {files, stats} = this._extractFileInfo(rawFiles);
prInfo = {
stats,
files,
filesUrl: `${data.html_url}/files`,
hasMoreFiles: headers.has('link'),
};
}
return {
number: data.number,
title: data.title,
description: data.body.trim(),
author: this._extractUserInfo(data.user),
state: data.state,
labels: data.labels.map(l => l.name).sort(),
isPr,
prInfo,
};
} catch (err) {
throw this._wrapError(err, `Error getting GitHub info for ${owner}/${repo}#${number}:`);
}
}
async getLatestTag(owner, repo) {
try {
/* Tags are listed in reverse order. */
const url = `${this._baseUrl}/${owner}/${repo}/tags?per_page=1`;
const {data} = await this._getJson(url);
return data[0];
} catch (err) {
throw this._wrapError(err, `Error getting latest GitHub tag ${owner}/${repo}:`);
}
}
requiresToken() {
return !this.hasToken() && (this._rateLimitResetTime > Date.now()) &&
`Anonymous rate-limit reached (until ${new Date(this._rateLimitResetTime).toLocaleString()})`;
}
_extractFileInfo(rawFiles) {
const stats = {total: 0, additions: 0, deletions: 0};
const files = rawFiles.map(f => {
const fileStats = {
total: f.changes,
additions: f.additions,
deletions: f.deletions,
};
stats.total += fileStats.total;
stats.additions += fileStats.additions;
stats.deletions += fileStats.deletions;
return {
filename: f.filename,
patch: (f.patch === undefined) ? null : f.patch,
status: f.status,
stats: fileStats,
};
});
return {files, stats};
}
_extractUserInfo(user) {
return {
avatar: user.avatar_url,
username: user.login,
url: user.html_url,
};
}
_generateHeaders(token) {
return {Authorization: `token ${token}`};
}
async _getErrorForResponse(res) {
let ErrorConstructor = Error;
const data = await res.json();
let message = data.message || JSON.stringify(data);
switch (res.status) {
case 401:
if (this.hasToken()) ErrorConstructor = this._getErrorConstructorExtending(AbstractInvalidTokenError);
break;
case 403:
if (res.headers.get('X-RateLimit-Remaining') === '0') {
const limit = res.headers.get('X-RateLimit-Limit');
const reset = new Date(res.headers.get('X-RateLimit-Reset') * 1000);
this._rateLimitResetTime = reset.getTime();
message = `0/${limit} API requests remaining until ${reset.toLocaleString()}.\n${message}`;
}
break;
}
return new ErrorConstructor(`${res.status} (${res.statusText}) - ${message}`);
}
}
class InMemoryStorage {
/* An in-memory implementation of the `Storage` interface. */
get length() { return this._keys().length; }
constructor() {
this._resetItems();
}
clear() {
this._resetItems();
}
getItem(key) {
return this._has(key) ? this._items[key] : null;
}
key(index) {
const keys = this._keys();
return (index < keys.length) ? keys[index] : null;
}
removeItem(key) {
delete this._items[key];
}
setItem(key, value) {
this._items[key] = `${value}`;
}
_has(key) {
return Object.prototype.hasOwnProperty.call(this._items, key);
}
_keys() {
return Object.keys(this._items);
}
_resetItems() {
this._items = Object.create(null);
}
}
class JiraUtils extends AbstractInfoProvider {
static get TOKEN_NAME() { return 'Jira e-mail and access token'; }
static get TOKEN_DESCRIPTION_HTML() {
const tokenName = this.TOKEN_NAME;
const tokenUrl = 'https://id.atlassian.com/manage/api-tokens';
const corsAnywhereLink =
'<a href="https://cors-anywhere.herokuapp.com/" target="_blank">https://cors-anywhere.herokuapp.com/</a>';
return `
<p>
A ${tokenName} is required in order to retrieve info for links to Jira issues. Unauthenticated requests are
<b>not supported</b> by Jira's API, so you will not be able to see any info without providing a ${tokenName}.
</p>
<p>To create a Jira access token visit: <a href="${tokenUrl}" target="_blank">${tokenUrl}</a></p>
<br />
<p style="
background-color: rgba(255, 0, 0, 0.1);
border: 2px solid gray;
border-radius: 6px;
color: red;
padding: 7px;
">
<b>WARNING:</b><br />
Currently, all requests to Jira's API are sent through ${corsAnywhereLink} in order to work around CORS
restrictions. There will, hopefully, be a better solution in the future, but for now <b>do not</b> provide a
${tokenName}, unless you understand and feel comfortable with the implications of sending the requests
(including your encoded ${tokenName}) through ${corsAnywhereLink}.
</p>
<br />
<p>
<b>IMPORTANT:</b><br />
Enter the ${tokenName} in the field below in the format <code><email>:<access-token></code> (e.g.
<code>[email protected]:My4cc3ssT0k3n</code>).
</p>
`;
}
static validateToken(token) {
super.validateToken(token);
if (!/^[^:]+@[^:]+:./.test(token)) {
const hiddenToken = token.replace(/\w/g, '*');
throw new Error(
`Invalid token format (${hiddenToken}). ` +
'Please, provide the token in the form `<email>:<access-token>` (e.g. `[email protected]:My4cc3ssT0k3n`).');
}
}
constructor() {
super();
this._baseUrl = 'https://angular-team.atlassian.net/rest/api/3';
/*
* Prepend `https://cors-anywhere.herokuapp.com/` to the URL to work around CORS restrictions.
* TODO(gkalpak): Implement a more secure alternative.
*/
this._baseUrl = `https://cors-anywhere.herokuapp.com/${this._baseUrl}`;
this._customFields = {
PrLink: 'customfield_10135',
};
}
async getIssueInfo(number) {
try {
const url = `${this._baseUrl}/issue/${number}?` +
'expand=renderedFields&' +
'fields=assignee,description,fixVersions,issuelinks,issuetype,project,reporter,status,summary,' +
this._customFields.PrLink;
const {data} = await this._getJson(url);
return {
number: data.key,
type: data.fields.issuetype.name,
title: data.fields.summary,
description: data.renderedFields.description.trim(),
reporter: this._extractUserInfo(data.fields.reporter),
assignee: data.fields.assignee && this._extractUserInfo(data.fields.assignee),
status: this._extractStatusInfo(data.fields.status),
project: data.fields.project.name,
fixVersions: data.fields.fixVersions.map(x => x.name).sort(),
prLink: data.fields[this._customFields.PrLink],
issueLinks: data.fields.issuelinks.
map(x => this._extractIssueLinkInfo(x)).
sort((a, b) => this._sortIssueLinks(a, b)),
};
} catch (err) {
throw this._wrapError(err, `Error getting Jira info for ${number}:`);
}
}
requiresToken() { return !this.hasToken() && 'Unauthenticated requests are not supported.'; }
_extractIssueLinkInfo(link) {
const isInward = hasOwnProperty(link, 'inwardIssue');
const otherIssue = isInward ? link.inwardIssue : link.outwardIssue;
return {
type: isInward ? link.type.inward : link.type.outward,
otherIssue: {
number: otherIssue.key,
url: `https://angular-team.atlassian.net/browse/${otherIssue.key}`,
title: otherIssue.fields.summary,
status: this._extractStatusInfo(otherIssue.fields.status),
},
};
}
_extractStatusInfo(status) {
return {
name: status.name,
color: status.statusCategory.colorName,
};
}
_extractUserInfo(user) {
return {
avatar: user.avatarUrls['32x32'],
username: user.name,
name: user.displayName,
url: `https://angular-team.atlassian.net/people/${user.accountId}`,
};
}
_generateHeaders(token) { return {Authorization: `Basic ${window.btoa(token)}`}; }
async _getErrorForResponse(res) {
let ErrorConstructor = Error;
const data = res.headers.get('Content-Type').includes('application/json') ?
await res.json() :
(await res.text()).trim();
const message = !Array.isArray(data.errorMessages) ?
JSON.stringify(data) : (data.errorMessages.length === 1) ?
data.errorMessages[0] :
['Errors:', ...data.errorMessages.map(e => ` - ${e}`)].join('\n');
switch (res.status) {
case 401:
if (this.hasToken()) ErrorConstructor = this._getErrorConstructorExtending(AbstractInvalidTokenError);
break;
}
return new ErrorConstructor(`${res.status} (${res.statusText}) - ${message}`);
}
_sortIssueLinks(l1, l2) {
return (l1.type < l2.type) ?
-1 : (l1.type > l2.type) ?
+1 : (l1.otherIssue.number < l2.otherIssue.number) ?
-1 :
+1;
}
}
class Linkifier {
constructor(postProcessNode = () => undefined) {
this._postProcessNode = postProcessNode;
this._observer = new MutationObserver(mutations =>
mutations.forEach(m =>
/* Delay processing to allow Slack complete it's own DOM manipulation (e.g. converting URLs to links). */
m.addedNodes && setTimeout(() => this.processAll(m.addedNodes), 500)));
this._regexps = {
githubCommitShortRe: /(?:([\w.-]+)\/)?([\w.-]+)@([A-Fa-f\d]{7,})\b/,
githubCommitUrlRe: /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/commit\/([A-Fa-f\d]{7,})$/,
githubCommitUrlRedirRe:
/* eslint-disable-next-line max-len */
new RegExp(perc('^https://slack-redir\\.net/link\\?url=https{{P}}3A{{P}}2F{{P}}2Fgithub\\.com{{P}}2F([\\w.-]+){{P}}2F([\\w.-]+){{P}}2Fcommit{{P}}2F([A-Fa-f\\d]{7,})$')),
githubIssueShortRe: /(?:(?:([\w.-]+)\/)?([\w.-]+))?#(\d+)\b/,
githubIssueUrlRe: /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/(?:issues|pull)\/(\d+)$/,
githubIssueUrlRedirRe:
/* eslint-disable-next-line max-len */
new RegExp(perc('^https://slack-redir\\.net/link\\?url=https{{P}}3A{{P}}2F{{P}}2Fgithub\\.com{{P}}2F([\\w.-]+){{P}}2F([\\w.-]+){{P}}2F(?:issues|pull){{P}}2F(\\d+)$')),
jiraIssueShortRe: /(?<!https:\/\/angular-team\.atlassian\.net\/browse\/)\b([A-Z]+-\d+)\b/,
jiraIssueUrlRe: /^https:\/\/angular-team\.atlassian\.net\/browse\/([A-Z]+-\d+)$/,
jiraIssueUrlRedirRe:
/* eslint-disable-next-line max-len */
new RegExp(perc('^https://slack-redir\\.net/link\\?url=https{{P}}3A{{P}}2F{{P}}2Fangular-team\\.atlassian\\.net{{P}}2Fbrowse{{P}}2F([A-Z]+-\\d+)$')),
mdLinkRe: /\[([^[\]]+|[^[]*(?:\[[^\]]+][^[]*)*)]\($/,
};
}
cleanUp() {
this._observer.disconnect();
}
observe(elem) {
this._observer.observe(elem, {childList: true, subtree: true});
}
processAll(nodes, forcePostProcess = false) {
/*
* - `.c-message__body`: Normal messages.
* - `.c-message_attachment__body`: Attachments (e.g. posted by GeekBot in #fw-standup).
* - `.c-message_kit__text`: Thread messages.
* - `.p-rich_text_block`: Messages with rich-text support (whatever that is that differentiates them from regular
* messages).
*/
const selectors = '.c-message__body, .c-message_attachment__body, .c-message_kit__text, .p-rich_text_block';
const processedParents = new Set();
nodes.forEach(n => {
if (processedParents.has(n.parentNode)) return;
const isAncestorOfInterest = n.closest ?
n.closest(selectors) :
(n.parentNode && n.parentNode.closest(selectors));
if (isAncestorOfInterest) {
/* A child of a message body element was added. */
this._processNode(n.parentNode, forcePostProcess);
} else if (n.querySelectorAll) {
/* An element that might contain message bodies was added. */
n.querySelectorAll(selectors).forEach(n => this._processNode(n, forcePostProcess));
}
});
}
_acceptNodeInTextNodeWalker(node) {
return (node.parentNode &&
(node.parentNode.nodeName !== 'A') &&
(!node.parentNode.parentNode || (node.parentNode.parentNode.nodeName !== 'A'))) ?
NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
_getEffectiveSiblingTextNode(node, nextSibling) {
/*
* Normally, we would use `previousSibling/nextSibling`. In some cases, however, the effective sibling text nodes
* may be wrapped in `<b>` and/or `<i>` elements. We "unwrap" these to get to the actual text node.
*/
const ignorableTags = ['B', 'I'];
const canIgnore = elem =>
ignorableTags.includes(elem.tagName) &&
((elem.childNodes.length === 1) ||
(elem.childElementCount === 1) &&
(elem.textContent.trim() === elem.firstElementChild.textContent.trim()));
const siblingProp = nextSibling ? 'nextSibling' : 'previousSibling';
let sibling = node[siblingProp];
if (!sibling) {
while (canIgnore(node.parentNode)) {
node = node.parentNode;
}
sibling = node[siblingProp];
}
if (sibling) {
while (canIgnore(sibling)) {
sibling = sibling.firstElementChild || sibling.firstChild;
}
}
return (sibling && (sibling.nodeType === Node.TEXT_NODE)) ? sibling : null;
}
_processNode(node, forcePostProcess) {
const processedNodes = new Set([
...this._processNodeMdLinks(node),
...this._processNodeGithubCommits(node),
...this._processNodeGithubIssues(node),
...this._processNodeJira(node),
]);
processedNodes.forEach(n => n.classList.add(CLASS_PROCESSED));
if (forcePostProcess || processedNodes.size) this._postProcessNode(node);
}
/* Process GitHub-like commits. */
_processNodeGithubCommits(node) {
const processedNodes = new Set();
const {githubCommitShortRe, githubCommitUrlRe, githubCommitUrlRedirRe} = this._regexps;
const acceptNode = x => this._acceptNodeInTextNodeWalker(x);
const treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, {acceptNode}, false);
let t;
while ((t = treeWalker.nextNode())) {
const textMatch = githubCommitShortRe.exec(t.textContent);
if (textMatch) {
const [, owner = 'angular', repo = 'angular', commit] = textMatch;
const url = `https://github.com/${owner}/${repo}/commit/${commit}`;
const link = Object.assign(document.createElement('a'), {
href: url,
target: '_blank',
textContent: url,
});
const trailingText = document.createTextNode(t.textContent.slice(textMatch.index + textMatch[0].length));
t.textContent = t.textContent.slice(0, textMatch.index);
t.after(link);
link.after(trailingText);
processedNodes.add(link);
}
}
node.querySelectorAll(`a:not(.${CLASS_PROCESSED})`).forEach(link => {
const hrefMatch = githubCommitUrlRe.exec(link.href) || githubCommitUrlRedirRe.exec(link.href);
if (hrefMatch) {
const [, owner, repo, commit] = hrefMatch;
link.classList.add(CLASS_GITHUB_COMMIT_LINK);
link.dataset.nslOwner = owner;
link.dataset.nslRepo = repo;
link.dataset.nslCommit = commit;
processedNodes.add(link);
}
const htmlMatch = githubCommitUrlRe.exec(link.innerHTML);
if (htmlMatch) {
const [, owner, repo, commit] = htmlMatch;
const repoSlug = `${(owner === 'angular') ? '' : `${owner}/`}${repo}`;
link.innerHTML = `<b>${repoSlug}@${commit.slice(0, 7)}</b>`;
processedNodes.add(link);
}
});
return processedNodes;
}
/* Process GitHub-like issues/PRs. */
_processNodeGithubIssues(node) {
const processedNodes = new Set();
const {githubIssueShortRe, githubIssueUrlRe, githubIssueUrlRedirRe} = this._regexps;
const acceptNode = x => this._acceptNodeInTextNodeWalker(x);
const treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, {acceptNode}, false);
let t;
while ((t = treeWalker.nextNode())) {
const textMatch = githubIssueShortRe.exec(t.textContent);
if (textMatch) {
const [, owner = 'angular', repo = 'angular', issue] = textMatch;
const url = `https://github.com/${owner}/${repo}/issues/${issue}`;
const link = Object.assign(document.createElement('a'), {
href: url,
target: '_blank',
textContent: url,
});
const trailingText = document.createTextNode(t.textContent.slice(textMatch.index + textMatch[0].length));
t.textContent = t.textContent.slice(0, textMatch.index);
t.after(link);
link.after(trailingText);
processedNodes.add(link);
}
}
node.querySelectorAll(`a:not(.${CLASS_PROCESSED})`).forEach(link => {
const hrefMatch = githubIssueUrlRe.exec(link.href) || githubIssueUrlRedirRe.exec(link.href);
if (hrefMatch) {
const [, owner, repo, issue] = hrefMatch;
link.classList.add(CLASS_GITHUB_ISSUE_LINK);
link.dataset.nslOwner = owner;
link.dataset.nslRepo = repo;
link.dataset.nslNumber = issue;
processedNodes.add(link);
}
const htmlMatch = githubIssueUrlRe.exec(link.innerHTML);
if (htmlMatch) {
const [, owner, repo, issue] = htmlMatch;
const isOwnerNg = owner === 'angular';
const isRepoNg = repo === 'angular';
const repoSlug = `${isOwnerNg ? '' : `${owner}/`}${(isOwnerNg && isRepoNg) ? '' : repo}`;
link.innerHTML = `<b>${repoSlug}#${issue}</b>`;
processedNodes.add(link);
}
});
return processedNodes;
}
/* Process Jira-like issues. */
_processNodeJira(node) {
const processedNodes = new Set();
const {jiraIssueShortRe, jiraIssueUrlRe, jiraIssueUrlRedirRe} = this._regexps;
const acceptNode = x => this._acceptNodeInTextNodeWalker(x);
const treeWalker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, {acceptNode}, false);
let t;
while ((t = treeWalker.nextNode())) {
const textMatch = jiraIssueShortRe.exec(t.textContent);
if (textMatch) {
const url = `https://angular-team.atlassian.net/browse/${textMatch[1]}`;
const link = Object.assign(document.createElement('a'), {
href: url,
target: '_blank',
textContent: url,
});
const trailingText = document.createTextNode(t.textContent.slice(textMatch.index + textMatch[0].length));
t.textContent = t.textContent.slice(0, textMatch.index);
t.after(link);
link.after(trailingText);
processedNodes.add(link);
}
}
node.querySelectorAll(`a:not(.${CLASS_PROCESSED})`).forEach(link => {
const hrefMatch = jiraIssueUrlRe.exec(link.href) || jiraIssueUrlRedirRe.exec(link.href);
if (hrefMatch) {
link.classList.add(CLASS_JIRA_LINK);
link.dataset.nslNumber = hrefMatch[1];
processedNodes.add(link);
}
const htmlMatch = jiraIssueUrlRe.exec(link.innerHTML);
if (htmlMatch) {
link.innerHTML = `<b>${htmlMatch[1]}</b>`;
processedNodes.add(link);
}
});
return processedNodes;
}
/* Process markdown-like links. */
_processNodeMdLinks(node) {
const processedNodes = new Set();
const {mdLinkRe} = this._regexps;
node.querySelectorAll(`a:not(.${CLASS_PROCESSED})`).forEach(link => {
const prev = this._getEffectiveSiblingTextNode(link, false);
const prevMatch = prev && mdLinkRe.exec(prev.textContent);
const next = prevMatch && this._getEffectiveSiblingTextNode(link, true);
const nextMatch = next ?
/^\)/.exec(next.textContent) :
/* Truncated link in message attachment (e.g. by GeekBot). Requires special handling. */
(link.lastChild && (link.lastChild.textContent === '…'));
if (nextMatch) {
link.childNodes.forEach(n => n.textContent = '');
link.appendChild(Object.assign(document.createElement('b'), {textContent: prevMatch[1]}));
prev.textContent = prev.textContent.slice(0, -prevMatch[0].length);
if (next) {
next.textContent = next.textContent.slice(nextMatch[0].length);
} else {
/*
* Special handling: Prevent Slack to update the link's text content,
* when expanding/collapsing the message attachment.
*/
const originalAppendChild = link.appendChild;
link.appendChild = n => originalAppendChild.call(link, Object.assign(n, {textContent: ''}));
}
processedNodes.add(link);
}
});
return processedNodes;
}
}
class LogUtils {
constructor(prefix) {
this._prefix = `[${prefix}]`;
}
cleanUp() { /* Nothing to clean up. */ }
log(...args) {
console.log(this._prefix, ...args);
}
warn(...args) {
console.warn(this._prefix, ...args);
}
error(...args) {
console.error(this._prefix, ...args);
}
}
class Program {
constructor() {
this._KEYS = new Map([
[GithubUtils, 1],
[JiraUtils, 2],
]);
this._cleanUpables = [
this._logUtils = new LogUtils(`${NAME} v${VERSION}`),
this._storageUtils = new StorageUtils(NAME),
/*
* NOTE:
* The idea (for now) is to just make it difficult for someone to make sense of encrypted values they might get
* access to. E.g. those values could be stored on `window.localStorage` or `window.sessionStorage` and it won't
* be possible for someone to get to the underlying data without knowing about this code here.
*/
this._secretUtils = new SecretUtils('$NgSl@ckL1nk1fy$'),
this._linkifier = new Linkifier(node => this._addListeners(node)),
this._uiUtils = new UiUtils(),
this._ghUtils = new GithubUtils(),
this._jiraUtils = new JiraUtils(),
this._updateUtils = new UpdateUtils(this._ghUtils),
];
this._cleanUpFns = [
() => this._destroyedDeferred.reject(new CleaningUpMarkerError()),
];
this._destroyedDeferred = new Deferred();
}
cleanUp() {
this._logUtils.log('Uninstalling...');
while (this._cleanUpables.length || this._cleanUpFns.length) {
while (this._cleanUpables.length) this._cleanUpables.shift().cleanUp();
while (this._cleanUpFns.length) this._cleanUpFns.shift()();
}
this._logUtils.log('Uninstalled.');
}
async main() {
try {
if (window.__ngSlackLinkifyCleanUp) window.__ngSlackLinkifyCleanUp();
window.__ngSlackLinkifyCleanUp = () => {
this.cleanUp();
window.__ngSlackLinkifyCleanUp = null;
};
this._logUtils.log('Installing...');
this._ghUtils.setToken(await this._getStoredTokenFor(GithubUtils));
this._jiraUtils.setToken(await this._getStoredTokenFor(JiraUtils));
const root = this._getRootElement();
this._linkifier.processAll([root], true);
this._linkifier.observe(root);
this._postInstall();
this._logUtils.log('Installed.');
} catch (err) {
this._onError(err);
} finally {
/* Even if installation failed, check for updates so that we can recover from a broken version. */
this._schedule(() => this._checkForUpdate(), 10000);
}
}
_addListeners(node) {
const processedNodes = new Set();
node.querySelectorAll(`.${CLASS_GITHUB_COMMIT_LINK}:not(.${CLASS_POST_PROCESSED})`).forEach(link => {
processedNodes.add(link);
this._addListenersForLink(link, data => this._getPopupContentForGithubCommit(data));
});
node.querySelectorAll(`.${CLASS_GITHUB_ISSUE_LINK}:not(.${CLASS_POST_PROCESSED})`).forEach(link => {
processedNodes.add(link);
this._addListenersForLink(link, data => this._getPopupContentForGithubIssue(data));
});
node.querySelectorAll(`.${CLASS_JIRA_LINK}:not(.${CLASS_POST_PROCESSED})`).forEach(link => {
processedNodes.add(link);
this._addListenersForLink(link, data => this._getPopupContentForJira(data));
});
processedNodes.forEach(n => {
n.classList.add(CLASS_POST_PROCESSED);
this._cleanUpFns.push(() => n.classList.remove(CLASS_POST_PROCESSED));
});
}
_addListenersForLink(link, getPopupContent) {
const linkStyle = link.style;
const linkData = link.dataset;
const cursorStyle = 'help';
let interactionId = 0;
const onMouseenter = async evt => {
try {
const id = interactionId;