Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1613 lines (1481 loc) · 73.8 KB
/
Copy pathbackground.js
File metadata and controls
1613 lines (1481 loc) · 73.8 KB
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
const api = typeof browser !== "undefined" && browser.runtime ? browser : chrome;
const GRAPHQL_URL = "https://api.github.com/graphql";
// Session storage lives in memory only and is not offered everywhere, so it is used when it is there.
const sessionStore = api.storage.session || null;
async function getSettings() {
const stored = await api.storage.local.get(["token", "fields", "ageEnabled", "ageUnit"]);
return {
token: (stored.token || "").trim(),
fields: parseFields(stored.fields),
ageEnabled: stored.ageEnabled === true,
ageUnit: stored.ageUnit || "months"
};
}
// pulls: [{owner, repo, number}] -> { "owner/repo!number": { association, bot, login, fork, additions, deletions, files, mergeState, draft } }
async function fetchPullRequests(pulls) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const byRepo = new Map();
for (const it of pulls) {
const key = `${it.owner}/${it.repo}`;
if (!byRepo.has(key)) byRepo.set(key, { owner: it.owner, repo: it.repo, numbers: new Set() });
byRepo.get(key).numbers.add(Number(it.number));
}
const parts = [];
let r = 0;
for (const { owner, repo, numbers } of byRepo.values()) {
const items = [...numbers].map((n) => `p${n}: pullRequest(number: ${n}) { number isDraft authorAssociation author { __typename login } isCrossRepository additions deletions changedFiles mergeStateStatus }`);
parts.push(`r${r++}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(repo)}) { nameWithOwner ${items.join("\n")} }`);
}
const data = await graphql(token, `{ ${parts.join("\n")} }`, { partial: true });
const result = {};
for (const repoNode of Object.values(data)) {
if (!repoNode || !repoNode.nameWithOwner) continue;
for (const [alias, pr] of Object.entries(repoNode)) {
if (!alias.startsWith("p") || !pr || typeof pr !== "object") continue;
result[`${repoNode.nameWithOwner}!${pr.number}`] = {
association: pr.authorAssociation || "NONE",
bot: Boolean(pr.author && pr.author.__typename === "Bot"),
login: pr.author ? pr.author.login : null,
fork: Boolean(pr.isCrossRepository),
additions: pr.additions, deletions: pr.deletions, files: pr.changedFiles,
mergeState: pr.mergeStateStatus || "UNKNOWN",
draft: Boolean(pr.isDraft)
};
}
}
return { pulls: result };
}
function parseFields(raw) {
return String(raw || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
}
// At most this many requests are out at once, however many tabs and chunks ask: a big project table sends
// many chunks together, and GitHub's secondary limits answer a burst with a refusal.
const MAX_CONCURRENT = 3;
let activeRequests = 0;
const waitingRequests = [];
function takeSlot() {
return new Promise((resolve) => {
const go = () => { activeRequests++; resolve(); };
if (activeRequests < MAX_CONCURRENT) go();
else waitingRequests.push(go);
});
}
function freeSlot() {
activeRequests--;
const next = waitingRequests.shift();
if (next) next();
}
// When GitHub says to wait, nothing is sent with that token until then: the answer would be the same refusal,
// and asking again is what makes a secondary limit last longer. Another token is not held back.
let blocked = { token: "", until: 0 };
const DEFAULT_WAIT_MS = 60 * 1000;
const MAX_WAIT_MS = 60 * 60 * 1000;
function waitWords(ms) {
const seconds = Math.max(1, Math.ceil(ms / 1000));
if (seconds < 90) return `${seconds} second${seconds === 1 ? "" : "s"}`;
const minutes = Math.ceil(seconds / 60);
return `${minutes} minutes`;
}
function rateLimitError(ms) {
return new Error(`GitHub rate limit reached. Try again in ${waitWords(ms)}.`);
}
// How long GitHub asks to wait, from its headers: `Retry-After` for the secondary limit, the reset time
// when the hourly allowance is used up, or a minute when it only says no.
function waitFrom(res) {
const retry = Number(res.headers.get("retry-after"));
if (Number.isFinite(retry) && retry > 0) return Math.min(retry * 1000, MAX_WAIT_MS);
const reset = Number(res.headers.get("x-ratelimit-reset"));
if (res.headers.get("x-ratelimit-remaining") === "0" && Number.isFinite(reset) && reset > 0) {
return Math.min(Math.max(reset * 1000 - Date.now(), 1000), MAX_WAIT_MS);
}
return DEFAULT_WAIT_MS;
}
async function graphql(token, query, { partial = false, errors = null } = {}) {
if (blocked.token === token && Date.now() < blocked.until) throw rateLimitError(blocked.until - Date.now());
await takeSlot();
let res;
try {
res = await fetch(GRAPHQL_URL, {
method: "POST",
headers: {
Authorization: `bearer ${token}`,
"Content-Type": "application/json",
"User-Agent": "github-issue-toolkit"
},
body: JSON.stringify({ query })
});
} finally {
freeSlot();
}
if (res.status === 401) {
throw new Error("Token rejected by GitHub (401). Check it in the extension options.");
}
// A 403 is a rate limit only when GitHub says how long to wait; otherwise it is a missing permission.
const limited = res.status === 429
|| (res.status === 403 && (res.headers.get("retry-after") || res.headers.get("x-ratelimit-remaining") === "0"));
if (limited) {
const wait = waitFrom(res);
blocked = { token, until: Date.now() + wait };
throw rateLimitError(wait);
}
if (!res.ok) {
throw new Error(`GitHub API responded with HTTP ${res.status}`);
}
const json = await res.json();
// The hourly allowance of GraphQL runs out as a normal answer that carries an error of this type.
if (json.errors && json.errors.some((e) => e && e.type === "RATE_LIMITED")) {
const wait = waitFrom(res);
blocked = { token, until: Date.now() + wait };
throw rateLimitError(wait);
}
// A caller that wants the reasons for the parts that failed passes a list to collect them in.
if (json.errors && errors) errors.push(...json.errors.map((e) => e.message));
if (json.errors && (!json.data || !partial)) {
throw new Error(json.errors.map((e) => e.message).join("; "));
}
return json.data || {};
}
// `withOptions` also asks for the options a single-select field defines, which gives the kanban board its
// column order. Not every GitHub deployment knows that selection, so the caller falls back to asking without it.
function fieldValueFragment(withOptions) {
return `
issueFieldValues(first: 30) {
nodes {
__typename
... on IssueFieldSingleSelectValue { name color field { ... on IssueFieldSingleSelect { id name ${withOptions ? "options { id name color }" : ""} } } }
... on IssueFieldMultiSelectValue { value field { ... on IssueFieldMultiSelect { name } } }
... on IssueFieldTextValue { value field { ... on IssueFieldText { name } } }
... on IssueFieldNumberValue { value field { ... on IssueFieldNumber { name } } }
... on IssueFieldDateValue { value field { ... on IssueFieldDate { name } } }
}
}`;
}
const FIELD_VALUE_FRAGMENT = fieldValueFragment(false);
// One field value as the content script wants it: the field name, the value as text, its colour, and,
// for a single select, the options of the field in the order the organization defined them.
function fieldValue(node) {
const fieldName = node.field && node.field.name;
if (!fieldName) return null;
const value = node.__typename === "IssueFieldSingleSelectValue" ? node.name : node.value;
if (value === null || value === undefined || value === "") return null;
const options = node.field && Array.isArray(node.field.options)
? node.field.options.map((o) => ({ id: o.id, name: o.name, color: o.color || "GRAY" }))
: null;
return {
field: fieldName,
fieldId: (node.field && node.field.id) || null,
value: String(value),
color: node.color || "GRAY",
kind: node.__typename.replace(/^IssueField|Value$/g, "").toLowerCase(),
options
};
}
const LABEL_FRAGMENT = "labels(first: 30) { nodes { name color } }";
// A `label:` entry in the field list shows matching labels: `label:area/*` every label starting with `area/`,
// `label:bug` only that one. The entry itself stands in as the field name, so it keeps its place in the order.
function labelPatterns(fields) {
return fields
.filter((f) => /^label:/i.test(f))
.map((f) => ({ field: f, pattern: f.slice(6).trim().toLowerCase() }));
}
// A label matched by two entries, `label:area/*` and `label:area/ui`, is shown once, at the first one.
function labelValues(node, patterns) {
const values = [];
const seen = new Set();
for (const { field, pattern } of patterns) {
for (const label of (node.labels && node.labels.nodes) || []) {
if (!label) continue;
const name = label.name.toLowerCase();
const hit = pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern;
if (!hit || seen.has(name)) continue;
seen.add(name);
values.push({ field, value: label.name, color: labelColor(label.color), kind: "label" });
}
}
return values;
}
// Labels carry any hex colour while badges only know GitHub's named ones, so take the nearest hue.
function labelColor(hex) {
const [r, g, b] = [0, 2, 4].map((i) => parseInt(String(hex).slice(i, i + 2), 16) / 255);
if ([r, g, b].some(Number.isNaN)) return "GRAY";
const max = Math.max(r, g, b);
const d = max - Math.min(r, g, b);
if (d < 0.15) return "GRAY";
const hue = 60 * (max === r ? ((g - b) / d + 6) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4);
if (hue < 15 || hue >= 345) return "RED";
if (hue < 40) return "ORANGE";
if (hue < 70) return "YELLOW";
if (hue < 170) return "GREEN";
if (hue < 245) return "BLUE";
if (hue < 290) return "PURPLE";
return "PINK";
}
async function fetchFieldValues(issues) {
const { token, fields, ageEnabled } = await getSettings();
if (!token) {
return { error: "NO_TOKEN" };
}
// Field badges are optional: with nothing to show there is nothing to ask GitHub.
if (!fields.length && !ageEnabled) {
return { values: {}, created: {}, fields };
}
const byRepo = new Map();
for (const it of issues) {
const key = `${it.owner}/${it.repo}`;
if (!byRepo.has(key)) byRepo.set(key, { owner: it.owner, repo: it.repo, numbers: new Set() });
byRepo.get(key).numbers.add(Number(it.number));
}
// A field list holding only `label:` entries reads no field values, so it works without issue fields too.
const patterns = labelPatterns(fields);
const withFields = fields.length > patterns.length;
const repoParts = [];
let r = 0;
for (const { owner, repo, numbers } of byRepo.values()) {
const issueParts = [...numbers].map(
(n) => `i${n}: issue(number: ${n}) { number createdAt ${withFields ? FIELD_VALUE_FRAGMENT : ""} ${patterns.length ? LABEL_FRAGMENT : ""} }`
);
repoParts.push(
`r${r++}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(repo)}) { nameWithOwner ${issueParts.join("\n")} }`
);
}
// partial: a single missing issue (deleted, transferred, no access) must not fail the whole page.
const data = await graphql(token, `{ ${repoParts.join("\n")} }`, { partial: true });
const wanted = new Set(fields.map((f) => f.toLowerCase()));
const result = {};
const created = {};
for (const repoNode of Object.values(data)) {
if (!repoNode || !repoNode.nameWithOwner) continue;
for (const [alias, issueNode] of Object.entries(repoNode)) {
if (!alias.startsWith("i") || !issueNode || typeof issueNode !== "object") continue;
const key = `${repoNode.nameWithOwner}#${issueNode.number}`;
if (issueNode.createdAt) created[key] = issueNode.createdAt;
const values = [];
for (const node of (issueNode.issueFieldValues && issueNode.issueFieldValues.nodes) || []) {
const v = fieldValue(node);
if (!v || !wanted.has(v.field.toLowerCase())) continue;
values.push({ field: v.field, value: v.value, color: v.color });
}
values.push(...labelValues(issueNode, patterns));
values.sort((a, b) => fields.findIndex((f) => f.toLowerCase() === a.field.toLowerCase())
- fields.findIndex((f) => f.toLowerCase() === b.field.toLowerCase()));
result[key] = values;
}
}
return { values: result, created, fields };
}
// ---------------------------------------------------------------------------
// Answers shared by every tab. A tab keeps what it read for as long as it is open, but a new tab or a reload
// starts empty, so what was read about a person is also kept here, in memory only: the worker holds it, and
// session storage carries it over the worker's idle stops. It is gone when the browser closes, and when the
// token changes, since another token may be allowed to see other things.
// ---------------------------------------------------------------------------
const SHARED_PREFIX = "shared:";
const sharedAnswers = new Map(); // key -> { at, value }
const sharedPending = new Map(); // key -> promise of a read that is under way
async function sharedLookup(keys) {
const found = new Map();
const missing = [];
for (const key of keys) {
const hit = sharedAnswers.get(key);
if (hit) found.set(key, hit);
else missing.push(key);
}
if (missing.length && sessionStore) {
const stored = await sessionStore.get(missing.map((key) => SHARED_PREFIX + key)).catch(() => ({}));
for (const key of missing) {
const hit = stored[SHARED_PREFIX + key];
if (hit && typeof hit.at === "number") {
sharedAnswers.set(key, hit);
found.set(key, hit);
}
}
}
return found;
}
function sharedStore(entries) {
const stored = {};
for (const [key, entry] of entries) {
sharedAnswers.set(key, entry);
stored[SHARED_PREFIX + key] = entry;
}
if (sessionStore && entries.length) sessionStore.set(stored).catch(() => {});
}
async function sharedForget() {
sharedAnswers.clear();
sharedPending.clear();
if (!sessionStore) return;
const all = await sessionStore.get(null).catch(() => ({}));
const keys = Object.keys(all).filter((key) => key.startsWith(SHARED_PREFIX));
if (keys.length) sessionStore.remove(keys).catch(() => {});
}
// One read for a key, shared by every tab asking at the same time and kept for `ttl`. `keep` says whether an
// answer is whole enough to be kept; `force` reads again, which the refresh button asks for. The answer
// carries `at`, when it was read, so a card can say how old it is.
async function sharedRead(key, ttl, load, keep, force) {
if (!force) {
const hit = (await sharedLookup([key])).get(key);
if (hit && Date.now() - hit.at < ttl) return { ...hit.value, at: hit.at };
if (sharedPending.has(key)) return sharedPending.get(key);
}
const request = load().then((value) => {
const at = Date.now();
if (value && !value.error && keep(value)) sharedStore([[key, { at, value }]]);
return value && !value.error ? { ...value, at } : value;
});
const own = request.finally(() => { if (sharedPending.get(key) === own) sharedPending.delete(key); });
sharedPending.set(key, own);
return own;
}
// ---------------------------------------------------------------------------
// Contributor load: who one person is to a repository and what they already hold in its organization
// ---------------------------------------------------------------------------
// Who the token belongs to, so the button can skip the reader's own name. Held for the life of the
// worker and read again after it restarts, which is cheap enough not to need storing.
let viewerLogin = null;
async function viewer() {
if (viewerLogin !== null) return viewerLogin;
const { token } = await getSettings();
if (!token) return "";
const data = await graphql(token, "{ viewer { login } }").catch(() => null);
viewerLogin = (data && data.viewer && data.viewer.login) || "";
return viewerLogin;
}
const LOAD_ISSUE_SAMPLE = 25;
const LOAD_PULL_SAMPLE = 50;
// A count from a search, or null when that part of the answer did not come back.
function searchCount(node) {
return node && Number.isFinite(node.issueCount) ? node.issueCount : null;
}
// One request per person answers everything the card shows: the counts for the repository and for the
// whole organization, and the open work with the pull request that closes each issue, which GraphQL
// knows, so the card can say which of the assigned issues is already being worked on instead of
// guessing from closing keywords in the body.
async function fetchContributorLoad(ref) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const org = String((ref && ref.org) || "").trim();
const repo = String((ref && ref.repo) || "").trim();
const login = String((ref && ref.login) || "").trim();
if (!org || !repo || !login) return { error: "An organization, a repository and a login are all needed." };
const count = (alias, scope, terms) => `${alias}: search(query: ${JSON.stringify(`${scope} ${terms}`)}, type: ISSUE, first: 1) { issueCount }`;
const here = `repo:${org}/${repo}`;
const all = `org:${org}`;
const author = `author:${login}`;
const assignee = `assignee:${login}`;
const assigned = JSON.stringify(`${all} is:issue is:open ${assignee}`);
const pulls = JSON.stringify(`${all} is:pr is:open ${author}`);
const data = await graphql(token, `{
assigned: search(query: ${assigned}, type: ISSUE, first: ${LOAD_ISSUE_SAMPLE}) {
issueCount
nodes { ... on Issue { number title url repository { nameWithOwner } } }
}
pulls: search(query: ${pulls}, type: ISSUE, first: ${LOAD_PULL_SAMPLE}) {
issueCount
nodes {
... on PullRequest {
number url authorAssociation
closingIssuesReferences(first: 10) { nodes { number repository { nameWithOwner } } }
}
}
}
member: user(login: ${JSON.stringify(login)}) { organization(login: ${JSON.stringify(org)}) { login } }
${count("mergedHere", here, `is:pr is:merged ${author}`)}
${count("mergedAll", all, `is:pr is:merged ${author}`)}
${count("openHere", here, `is:pr is:open ${author}`)}
${count("closedHere", here, `is:pr is:closed is:unmerged ${author}`)}
${count("closedAll", all, `is:pr is:closed is:unmerged ${author}`)}
${count("assignedHere", here, `is:issue is:open ${assignee}`)}
${count("doneHere", here, `is:issue is:closed reason:completed ${assignee}`)}
${count("doneAll", all, `is:issue is:closed reason:completed ${assignee}`)}
}`, { partial: true });
// A member of the organization is one GitHub shows as such to this token, or one whose own pull requests
// in the organization GitHub marks as made by a member or an owner.
let member = Boolean(data.member && data.member.organization);
const closes = new Map();
for (const pull of (data.pulls && data.pulls.nodes) || []) {
if (!pull) continue;
if (pull.authorAssociation === "MEMBER" || pull.authorAssociation === "OWNER") member = true;
for (const issue of (pull.closingIssuesReferences && pull.closingIssuesReferences.nodes) || []) {
if (!issue || !issue.repository) continue;
const key = `${issue.repository.nameWithOwner}#${issue.number}`;
if (!closes.has(key)) closes.set(key, { number: pull.number, url: pull.url });
}
}
const items = [];
for (const issue of (data.assigned && data.assigned.nodes) || []) {
if (!issue || !issue.repository) continue;
const key = `${issue.repository.nameWithOwner}#${issue.number}`;
items.push({
key,
repo: issue.repository.nameWithOwner.split("/")[1] || issue.repository.nameWithOwner,
number: issue.number,
title: issue.title,
url: issue.url,
pull: closes.get(key) || null
});
}
return {
member,
merged: { repo: searchCount(data.mergedHere), org: searchCount(data.mergedAll) },
open: { repo: searchCount(data.openHere), org: searchCount(data.pulls) },
closed: { repo: searchCount(data.closedHere), org: searchCount(data.closedAll) },
assigned: { repo: searchCount(data.assignedHere), org: searchCount(data.assigned) },
done: { repo: searchCount(data.doneHere), org: searchCount(data.doneAll) },
items
};
}
// What one person has done in one organization, for the panel on their profile. One request: counts of the
// pull requests they have open and merged, those they reviewed, the issues they opened and are
// assigned, what they commented on, whether they belong to the organization, their open pull requests and
// the open issues assigned to them.
const PROFILE_OPEN_SAMPLE = 20;
async function fetchOrgActivity(ref) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const org = String((ref && ref.org) || "").trim();
const login = String((ref && ref.login) || "").trim();
if (!org || !login) return { error: "An organization and a login are both needed." };
const count = (alias, terms) => `${alias}: search(query: ${JSON.stringify(`org:${org} ${terms}`)}, type: ISSUE, first: 1) { issueCount }`;
const data = await graphql(token, `{
member: user(login: ${JSON.stringify(login)}) { organization(login: ${JSON.stringify(org)}) { login } }
${count("merged", `is:pr is:merged author:${login}`)}
${count("open", `is:pr is:open author:${login}`)}
${count("issues", `is:issue author:${login}`)}
${count("issuesOpen", `is:issue is:open author:${login}`)}
${count("reviewed", `is:pr reviewed-by:${login} -author:${login}`)}
${count("commented", `commenter:${login} -author:${login}`)}
${count("assignedOpen", `is:issue is:open assignee:${login}`)}
openIssues: search(query: ${JSON.stringify(`org:${org} is:issue is:open assignee:${login} sort:updated-desc`)}, type: ISSUE, first: ${PROFILE_OPEN_SAMPLE}) {
nodes { ... on Issue { number title url repository { name } } }
}
openWork: search(query: ${JSON.stringify(`org:${org} is:pr is:open author:${login} sort:updated-desc`)}, type: ISSUE, first: ${PROFILE_OPEN_SAMPLE}) {
nodes { ... on PullRequest { number title url isDraft repository { name } } }
}
}`, { partial: true });
const openWork = ((data.openWork && data.openWork.nodes) || []).filter(Boolean).map((pull) => ({
repo: pull.repository ? pull.repository.name : "",
number: pull.number,
title: pull.title,
url: pull.url,
draft: Boolean(pull.isDraft)
}));
const openIssues = ((data.openIssues && data.openIssues.nodes) || []).filter(Boolean).map((issue) => ({
repo: issue.repository ? issue.repository.name : "",
number: issue.number,
title: issue.title,
url: issue.url
}));
return {
member: Boolean(data.member && data.member.organization),
merged: searchCount(data.merged),
open: searchCount(data.open),
issues: searchCount(data.issues),
issuesOpen: searchCount(data.issuesOpen),
reviewed: searchCount(data.reviewed),
commented: searchCount(data.commented),
assignedOpen: searchCount(data.assignedOpen),
openWork,
openIssues
};
}
// Assignment requests: the comments of an issue, to find the ones asking to be assigned, and the action that
// marks comments as outdated, which is GitHub's own Hide, Outdated.
// ---------------------------------------------------------------------------
const ASSIGN_PAGES = 3;
const ASSIGN_BODY_KEPT = 1500;
async function fetchIssueComments(ref) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const owner = String((ref && ref.owner) || "").trim();
const repo = String((ref && ref.repo) || "").trim();
const number = Number(ref && ref.number);
if (!owner || !repo || !Number.isInteger(number)) return { error: "An owner, a repository and an issue number are all needed." };
let after = null;
let assignees = [];
let author = "";
let isPrivate = false;
const comments = [];
let more = false;
for (let page = 0; page < ASSIGN_PAGES; page++) {
const cursor = after ? `, after: ${JSON.stringify(after)}` : "";
const data = await graphql(token, `{
repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(repo)}) {
isPrivate
issue(number: ${number}) {
author { login }
assignees(first: 20) { nodes { login } }
comments(first: 100${cursor}) {
pageInfo { hasNextPage endCursor }
nodes { id url body createdAt isMinimized viewerCanMinimize author { login } }
}
}
}
}`);
const issue = data.repository && data.repository.issue;
if (!issue) return { error: "That issue could not be read." };
isPrivate = Boolean(data.repository.isPrivate);
author = (issue.author && issue.author.login) || "";
assignees = ((issue.assignees && issue.assignees.nodes) || []).filter(Boolean).map((u) => u.login);
for (const node of issue.comments.nodes || []) {
if (!node) continue;
comments.push({
id: node.id,
url: node.url,
author: (node.author && node.author.login) || "",
// Only the start is kept, the length is kept whole: long comments are discussion, not requests.
body: String(node.body || "").slice(0, ASSIGN_BODY_KEPT),
length: String(node.body || "").length,
createdAt: node.createdAt,
hidden: Boolean(node.isMinimized),
canHide: Boolean(node.viewerCanMinimize)
});
}
more = issue.comments.pageInfo.hasNextPage;
if (!more) break;
after = issue.comments.pageInfo.endCursor;
}
return { author, assignees, comments, more, isPrivate };
}
// Marks comments as outdated, or brings them back. This writes to GitHub, and only ever for the ids it is given
// after the person has confirmed them.
async function setCommentsHidden(ids, hide) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const list = [...new Set((ids || []).map(String))].slice(0, 100);
if (!list.length) return { error: "No comments were chosen." };
const done = {};
const reasons = [];
for (let i = 0; i < list.length; i += 20) {
const chunk = list.slice(i, i + 20);
const mutations = chunk.map((id, n) => hide
? `h${n}: minimizeComment(input: {subjectId: ${JSON.stringify(id)}, classifier: OUTDATED}) { minimizedComment { isMinimized } }`
: `h${n}: unminimizeComment(input: {subjectId: ${JSON.stringify(id)}}) { unminimizedComment { isMinimized } }`).join("\n");
const data = await graphql(token, `mutation { ${mutations} }`, { partial: true, errors: reasons });
chunk.forEach((id, n) => { done[id] = Boolean(data[`h${n}`]); });
}
const failed = list.filter((id) => !done[id]).length;
return { done, failed, reason: failed ? (reasons[0] || "GitHub refused.") : "" };
}
// ---------------------------------------------------------------------------
// Related work on a pull request: the issues it closes, what its description says it is related to, the other
// pull requests on the same issues, and what mentions it. One request for the pull request and one that
// resolves what its description names.
// ---------------------------------------------------------------------------
// The words GitHub itself links with, and the ones people use to say a change belongs with another: the closing
// keywords, then the rest. A reference with none of them is still listed, as a mention.
const RELATION_CLOSING = ["closes", "closed", "close", "fixes", "fixed", "fix", "resolves", "resolved", "resolve"];
const RELATION_OTHER = [
"counterpart of", "counterpart to", "counterpart in", "counterpart for", "counterpart",
"related to", "relates to", "relating to", "related", "part of", "follow-up to", "follow-up of", "follow up to", "follow up of", "followup to", "followup of", "follow-up", "follow up", "followup",
"backport of", "backports", "backported from", "backport", "port of", "ported from", "forward port of", "cherry-pick of", "cherry-picked from", "cherry pick of", "mirror of", "mirrors", "mirrored from",
"continuation of", "continues", "continue", "depends on", "depended on", "blocked by", "blocks", "supersedes", "superseded by", "replaces", "replaced by", "duplicate of", "duplicates", "split from", "split out of", "extracted from",
"reverts", "revert of", "see also", "see", "refs", "ref", "references", "reference", "towards", "toward", "addresses", "address", "companion of", "companion to", "companion", "sibling of", "sibling", "paired with", "pairs with", "other half of", "same as", "similar to", "alternative to", "instead of", "in favor of", "in favour of", "upstream", "downstream", "tracked in", "tracked by", "tracking", "epic", "parent", "child of", "sub-task of", "subtask of"
];
const RELATION_MAX_REFS = 40;
const RELATION_SIBLINGS_KEPT = 8;
// A bare #12 with no relation word before it is as likely to be step 12 or iteration 12 as an issue, so a number
// this small only counts when a word says it is a reference.
const RELATION_BARE_MIN = 100;
function relationEscape(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/ /g, "[\\s-]+");
}
// What the description of a pull request names: each reference once, with the relation word just before it.
function parseRelations(text, home) {
const clean = String(text || "")
.replace(/<!--[\s\S]*?-->/g, " ")
.replace(/```[\s\S]*?```/g, " ")
.replace(/`[^`\n]*`/g, " ");
const refs = [];
const seen = new Set();
const refPattern = /https?:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/(?:issues|pull)\/(\d+)(?![\w/])|(?<![\w/&])([\w.-]+)\/([\w.-]+)#(\d+)\b|(?<![\w/&#])#(\d{1,7})\b/g;
const words = [...RELATION_CLOSING.map((w) => [w, "closes"]), ...RELATION_OTHER.map((w) => [w, "related"])];
words.sort((a, b) => b[0].length - a[0].length);
const wordPattern = new RegExp(`(?:^|[^\\w])(${words.map((w) => relationEscape(w[0])).join("|")})\\b((?:[\\s:,&()\\-*_>]|\\band\\b|\\bor\\b|\\bthe\\b|\\bissues?\\b|\\bprs?\\b|\\bpull requests?\\b|\\bof\\b|\\bto\\b|\\bin\\b|\\bwith\\b|\\bfor\\b|#|\\d+|[\\w.-]+\\/[\\w.-]+#\\d+|https?:\\/\\/\\S+)*)$`, "i");
let m;
while ((m = refPattern.exec(clean))) {
let owner = home.owner;
let repo = home.repo;
let number;
if (m[1]) { owner = m[1]; repo = m[2]; number = Number(m[3]); }
else if (m[4]) { owner = m[4]; repo = m[5]; number = Number(m[6]); }
else number = Number(m[7]);
const key = `${owner}/${repo}#${number}`.toLowerCase();
if (seen.has(key) || (owner.toLowerCase() === home.owner.toLowerCase() && repo.toLowerCase() === home.repo.toLowerCase() && number === home.number)) continue;
seen.add(key);
// The words in front of it on the same line.
const lineStart = clean.lastIndexOf("\n", m.index) + 1;
const before = clean.slice(lineStart, m.index).slice(-160);
const found = wordPattern.exec(before);
let kind = "mention";
let word = "";
if (found) {
const lower = found[1].toLowerCase().replace(/[\s-]+/g, " ");
const hit = words.find((w) => w[0].replace(/[\s-]+/g, " ") === lower);
kind = hit ? hit[1] : "related";
word = lower;
}
if (kind === "mention" && m[7] && number < RELATION_BARE_MIN) continue;
refs.push({ owner, repo, number, kind, word });
if (refs.length >= RELATION_MAX_REFS) break;
}
return refs;
}
function relationNode(node, extra) {
if (!node || !node.number) return null;
const repo = node.repository && node.repository.nameWithOwner ? node.repository.nameWithOwner : "";
const [owner, name] = repo.split("/");
return {
type: node.__typename === "PullRequest" || node.merged !== undefined ? "pull" : "issue",
owner: owner || "",
repo: name || "",
number: node.number,
title: node.title || "",
state: node.state || "",
merged: Boolean(node.merged),
draft: Boolean(node.isDraft),
url: node.url || "",
...extra
};
}
const RELATION_ITEM_FIELDS = "number title state url repository { nameWithOwner }";
const RELATION_PULL_FIELDS = `${RELATION_ITEM_FIELDS} merged isDraft`;
const RELATION_ISSUE_EXTRAS = `
closedByPullRequestsReferences(first: 10, includeClosedPrs: true) { nodes { __typename ${RELATION_PULL_FIELDS} } }
timelineItems(first: 20, itemTypes: [CROSS_REFERENCED_EVENT]) { nodes { ... on CrossReferencedEvent { source { __typename ... on PullRequest { ${RELATION_PULL_FIELDS} } } } } }`;
async function fetchPullRelations(ref) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const owner = String((ref && ref.owner) || "").trim();
const repo = String((ref && ref.repo) || "").trim();
const number = Number(ref && ref.number);
if (!owner || !repo || !Number.isInteger(number)) return { error: "An owner, a repository and a pull request number are all needed." };
const data = await graphql(token, `{
repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(repo)}) {
pullRequest(number: ${number}) {
title body state merged isDraft author { login }
closingIssuesReferences(first: 30) { nodes { __typename ${RELATION_ITEM_FIELDS} ${RELATION_ISSUE_EXTRAS} } }
timelineItems(first: 60, itemTypes: [CROSS_REFERENCED_EVENT]) { nodes { ... on CrossReferencedEvent { source { __typename ... on PullRequest { ${RELATION_PULL_FIELDS} } ... on Issue { ${RELATION_ITEM_FIELDS} } } } } }
}
}
}`);
const pull = data.repository && data.repository.pullRequest;
if (!pull) return { error: "That pull request could not be read." };
const items = new Map();
const home = `${owner}/${repo}#${number}`.toLowerCase();
const keyOf = (item) => `${item.owner}/${item.repo}#${item.number}`.toLowerCase();
const add = (item) => {
if (!item || keyOf(item) === home) return false;
if (items.has(keyOf(item))) return false;
items.set(keyOf(item), item);
return true;
};
const sources = []; // the issues whose other pull requests are worth listing
for (const node of (pull.closingIssuesReferences && pull.closingIssuesReferences.nodes) || []) {
const item = relationNode(node, { type: "issue", group: "closes", word: "closes" });
if (add(item)) sources.push({ item, node });
}
// What the description and the title name, resolved in one request.
const named = parseRelations(`${pull.title}\n${pull.body || ""}`, { owner, repo, number }).filter((r) => !items.has(`${r.owner}/${r.repo}#${r.number}`.toLowerCase()));
if (named.length) {
const query = `{
${named.map((r, i) => `r${i}: repository(owner: ${JSON.stringify(r.owner)}, name: ${JSON.stringify(r.repo)}) { issueOrPullRequest(number: ${r.number}) { __typename ... on Issue { ${RELATION_ITEM_FIELDS} ${RELATION_ISSUE_EXTRAS} } ... on PullRequest { ${RELATION_PULL_FIELDS} } } }`).join("\n")}
}`;
const resolved = await graphql(token, query, { partial: true });
named.forEach((r, i) => {
const node = resolved[`r${i}`] && resolved[`r${i}`].issueOrPullRequest;
if (!node) return;
const group = r.kind === "closes" ? "closes" : (r.kind === "related" ? "related" : "mentions");
const item = relationNode(node, { type: node.__typename === "PullRequest" ? "pull" : "issue", group, word: r.word });
// Only what the description closes or is related to leads to other pull requests; a passing mention does not.
if (add(item) && item.type === "issue" && group !== "mentions") sources.push({ item, node });
});
}
// The other pull requests on those issues: the ones that close them, and the ones that mention them.
for (const { item, node } of sources) {
const pulls = [];
for (const p of (node.closedByPullRequestsReferences && node.closedByPullRequestsReferences.nodes) || []) pulls.push(relationNode(p, { type: "pull", via: item }));
for (const event of (node.timelineItems && node.timelineItems.nodes) || []) {
if (event && event.source && event.source.__typename === "PullRequest") pulls.push(relationNode(event.source, { type: "pull", via: item }));
}
// The ones still going first, then the most recent.
pulls.sort((a, b) => (b ? Number(b.state === "OPEN") : 0) - (a ? Number(a.state === "OPEN") : 0) || (b ? b.number : 0) - (a ? a.number : 0));
let kept = 0;
for (const p of pulls) {
if (!p || kept >= RELATION_SIBLINGS_KEPT) continue;
if (add({ ...p, group: "siblings", via: `${item.owner}/${item.repo}#${item.number}`, viaNumber: item.number, viaRepo: `${item.owner}/${item.repo}` })) kept++;
}
}
// What mentions this pull request.
let mentioned = 0;
for (const event of (pull.timelineItems && pull.timelineItems.nodes) || []) {
if (!event || !event.source || mentioned >= 20) continue;
const item = relationNode(event.source, { type: event.source.__typename === "PullRequest" ? "pull" : "issue", group: "mentioned" });
if (add(item)) mentioned++;
}
return {
title: pull.title,
state: pull.state,
merged: Boolean(pull.merged),
draft: Boolean(pull.isDraft),
items: [...items.values()].map((item) => {
const { via, ...rest } = item;
return typeof via === "string" ? { ...rest, via } : rest;
})
};
}
// ---------------------------------------------------------------------------
// Whether each of a list of people belongs to an organization, for the mark that shows at once. One
// lookup per person goes in a shared request, so a long thread costs a handful of requests rather than
// one for every name. A person GitHub cannot find, a bot for example, comes back as null.
const MEMBER_CHUNK = 40;
const MEMBER_MAX = 200;
// Belonging to an organization changes rarely, so an answer stays good for hours and is shared by every tab.
const MEMBER_TTL_MS = 6 * 60 * 60 * 1000;
async function fetchMembers(ref) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const org = String((ref && ref.org) || "").trim();
const logins = [...new Set(((ref && ref.logins) || []).map((l) => String(l).trim()).filter(Boolean))].slice(0, MEMBER_MAX);
if (!org || !logins.length) return { error: "An organization and at least one login are needed." };
const keyOf = (login) => `member:${org.toLowerCase()}/${login.toLowerCase()}`;
const members = {};
const known = await sharedLookup(logins.map(keyOf));
const missing = [];
for (const login of logins) {
const hit = known.get(keyOf(login));
if (hit && Date.now() - hit.at < MEMBER_TTL_MS) members[login] = hit.value;
else missing.push(login);
}
for (let i = 0; i < missing.length; i += MEMBER_CHUNK) {
const chunk = missing.slice(i, i + MEMBER_CHUNK);
const lookups = chunk.map((login, n) => `m${n}: user(login: ${JSON.stringify(login)}) { organization(login: ${JSON.stringify(org)}) { login } }`).join("\n");
const data = await graphql(token, `{ ${lookups} }`, { partial: true });
const at = Date.now();
const answered = [];
chunk.forEach((login, n) => {
const node = data[`m${n}`];
members[login] = node ? Boolean(node.organization) : null;
// Someone GitHub could not find may be found later, so only a clear yes or no is kept.
if (members[login] !== null) answered.push([keyOf(login), { at, value: members[login] }]);
});
sharedStore(answered);
}
return { members };
}
// ---------------------------------------------------------------------------
// Address bar search: `@gh <shortcut> <words>`, each shortcut a kind of item and GitHub qualifiers
// ---------------------------------------------------------------------------
// Used until the settings page saves a list of its own, so the keyword works right after installing.
const DEFAULT_SHORTCUTS = [
{ name: "repo", icon: "📦", kind: "repo", query: "" },
{ name: "pr", icon: "🔀", kind: "pr", query: "is:open" }
];
const SEARCH_KINDS = {
repo: { label: "Repositories", type: "repositories", qualifier: "" },
issue: { label: "Issues", type: "issues", qualifier: "is:issue" },
pr: { label: "Pull requests", type: "pullrequests", qualifier: "is:pr" }
};
const SEARCH_LIMIT = 8;
const OWNER_REPOS_TTL_MS = 10 * 60 * 1000;
const OWNER_REPOS_PAGES = 5;
const OPEN_SETTINGS = "github-issue-toolkit:settings";
// Chrome reads suggestion descriptions as XML with a few highlight tags; Firefox shows them as typed.
const RICH_SUGGESTIONS = !api.runtime.getURL("").startsWith("moz-extension:");
async function searchSettings() {
const stored = await api.storage.local.get(["token", "searchShortcuts", "searchDefault"]);
const saved = Array.isArray(stored.searchShortcuts)
? stored.searchShortcuts.filter((s) => s && s.name && SEARCH_KINDS[s.kind])
: [];
const shortcuts = saved.length ? saved : DEFAULT_SHORTCUTS;
const wanted = String(stored.searchDefault || "").toLowerCase();
return {
token: (stored.token || "").trim(),
shortcuts,
fallback: shortcuts.find((s) => s.name.toLowerCase() === wanted) || shortcuts[0]
};
}
// The first word picks a shortcut when it is one's name; otherwise the whole text goes to the default.
function parseSearch(text, shortcuts, fallback) {
const trimmed = String(text || "").trim();
const [first, ...rest] = trimmed.split(/\s+/);
const named = first && shortcuts.find((s) => s.name.toLowerCase() === first.toLowerCase());
if (named) return { shortcut: named, words: rest.join(" "), named: true };
return { shortcut: fallback, words: trimmed, named: false };
}
function searchQuery(shortcut, words) {
return [words, shortcut.query, SEARCH_KINDS[shortcut.kind].qualifier].filter(Boolean).join(" ").trim();
}
function searchPageUrl(shortcut, words) {
const query = searchQuery(shortcut, words);
if (!query) return "https://github.com/search";
return `https://github.com/search?q=${encodeURIComponent(query)}&type=${SEARCH_KINDS[shortcut.kind].type}`;
}
// Chrome refuses the whole list when one description is not valid XML, so the characters XML does not
// allow, which issue titles do carry now and then, are dropped before escaping.
const NOT_XML = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
function escapeXml(text) {
return String(text).replace(NOT_XML, "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
}
// parts: [[text, tag]], the tag being match, dim, url or nothing.
function describe(parts) {
return parts
.filter(([text]) => text)
.map(([text, tag]) => (RICH_SUGGESTIONS && tag ? `<${tag}>${escapeXml(text)}</${tag}>` : RICH_SUGGESTIONS ? escapeXml(text) : text))
.join(" ");
}
function shortcutSummary(shortcut, fallback) {
const kind = SEARCH_KINDS[shortcut.kind].label;
return `${shortcut.query ? `${kind} in ${shortcut.query}` : kind}${shortcut === fallback ? " (default)" : ""}`;
}
// Every repository of an owner, newest push first, kept for ten minutes: GitHub search matches whole
// words only, so `app` finds `webapp` through this list and not through search. The worker is stopped
// after a short idle time, so the list is also kept in session storage, which lives in memory only.
const ownerRepoCache = new Map();
function fresh(entry) {
return entry && Date.now() - entry.at < OWNER_REPOS_TTL_MS;
}
// The list when it is already known, without waiting: what each keystroke can show at once.
function cachedRepos(owner) {
const hit = ownerRepoCache.get(owner.toLowerCase());
return fresh(hit) && hit.list ? hit.list : null;
}
async function readOwnerRepos(token, owner) {
const storeKey = `repoList:${owner.toLowerCase()}`;
const stored = sessionStore ? (await sessionStore.get(storeKey))[storeKey] : null;
if (fresh(stored)) return stored;
const list = [];
let cursor = null;
for (let page = 0; page < OWNER_REPOS_PAGES; page++) {
const data = await graphql(token, `{ o: repositoryOwner(login: ${JSON.stringify(owner)}) {
repositories(first: 100, orderBy: { field: PUSHED_AT, direction: DESC }${cursor ? `, after: ${JSON.stringify(cursor)}` : ""}) {
pageInfo { hasNextPage endCursor }
nodes { nameWithOwner description url pushedAt }
}
} }`);
const connection = data.o && data.o.repositories;
if (!connection) break;
list.push(...(connection.nodes || []).filter(Boolean));
if (!connection.pageInfo || !connection.pageInfo.hasNextPage) break;
cursor = connection.pageInfo.endCursor;
}
const entry = { at: Date.now(), list };
if (sessionStore) sessionStore.set({ [storeKey]: entry }).catch(() => {});
return entry;
}
function ownerRepos(token, owner) {
const key = owner.toLowerCase();
const hit = ownerRepoCache.get(key);
if (fresh(hit)) return hit.repos;
const repos = readOwnerRepos(token, owner).then((entry) => {
ownerRepoCache.set(key, { at: entry.at, repos, list: entry.list });
return entry.list;
});
ownerRepoCache.set(key, { at: Date.now(), repos });
// A failed read is not kept, so the next keystroke asks again.
repos.catch(() => ownerRepoCache.delete(key));
return repos;
}
function repoOwners(shortcut) {
return [...shortcut.query.matchAll(/(?:^|\s)(?:org|user):(\S+)/g)].map((m) => m[1]);
}
const NO_MATCH = 4;
// Lower is better: the name itself, then a name that starts with the words, then one where they start a
// part of it (`kafka` in `plugin-kafka`), then anywhere in it. Words with a slash are matched against
// `owner/name`, and several words read as one name, `plugin kafka` as `plugin-kafka`.
function repoRank(repo, needle) {
if (!needle) return 0;
const full = repo.nameWithOwner.toLowerCase();
const name = needle.includes("/") ? full : full.slice(full.indexOf("/") + 1);
if (name === needle) return 0;
if (name.startsWith(needle)) return 1;
const at = name.indexOf(needle);
if (at > 0 && /[-_./]/.test(name[at - 1])) return 2;
return at >= 0 ? 3 : NO_MATCH;
}
// Best rank first, then the shorter name, which is the closer one, then the order the repositories came
// in: the most recently pushed first for the owner's list, followed by GitHub search's own order.
// With no words there is nothing to be close to, so the list keeps that order, newest push first.
// GitHub search also matches descriptions, so its results are kept even when the name does not match.
function rankRepos(repos, words, { keepSearched = false } = {}) {
const needle = words.trim().toLowerCase().replace(/\s+/g, "-");
return repos
.map((repo, order) => ({ repo, order, rank: repoRank(repo, needle), length: needle ? repo.nameWithOwner.length : 0 }))
.filter((r) => r.rank < NO_MATCH || (keepSearched && r.repo.searched))
.sort((a, b) => a.rank - b.rank || a.length - b.length || a.order - b.order)
.map((r) => r.repo);
}
// A search still unanswered after this long is reported as such, instead of leaving the old rows in place.
const SEARCH_TIMEOUT_MS = 10 * 1000;
function timedGraphql(token, query) {
let timer;
return Promise.race([