Repository navigation
Expand file tree
/
Copy pathpr-tracker.html
More file actions
3011 lines (2722 loc) · 132 KB
/
Copy pathpr-tracker.html
File metadata and controls
3011 lines (2722 loc) · 132 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PR Review Tracker</title>
<link rel="icon" href="favicon.svg" />
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; connect-src https://api.github.com; img-src 'self' data:; style-src 'self' 'sha256-9fwgLHt+tTAPFsnNBYKKkvSQWtZMKllTrowwSNXkyP0='; script-src 'self' 'sha256-hhI5CNQxGz4HJyCLWzGqKL72QRFJwxFtRlsQLJ0zAe0='; base-uri 'none'; form-action 'none'" />
<link rel="stylesheet" href="gh-common.css" />
<style>
/* Page-specific. Tokens, shell, buttons, panels, stats, feedback, the
token screen and the Combobox all come from gh-common.css. */
.main { max-width: 93.75rem; }
/* ── Config panel ─────────────────────────────────────────────────── */
/* Every configuration row is the same shape: an uppercase label in a
fixed column, its control in the next. Consistency here is the point -
previously some rows had a label, some had none, and one control lived
outside the panel entirely. */
.cfg-row { display:grid; grid-template-columns:10.5rem minmax(0,1fr); gap:12px; align-items:start; padding:12px 0; border-top:1px solid var(--border); }
.cfg-row:first-child { padding-top:0; border-top:none; }
.cfg-row:last-child { padding-bottom:0; }
.cfg-row > .panel-label { padding-top:9px; }
.cfg-control { min-width:0; display:flex; flex-direction:column; gap:8px; position:relative; }
.cfg-inline { display:flex; flex-wrap:wrap; align-items:center; gap:18px; }
/* Things that act, or that change how the fetched data is displayed. */
.action-bar { display:flex; gap:14px; align-items:center; flex-wrap:wrap; margin-bottom:16px; }
.action-bar .spacer { flex:1 1 auto; }
.action-group { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
/* Split button: the common action on the left, its rarer variants behind
the caret. The variant runs once; it does not become the new default. */
.split-btn { position:relative; display:inline-flex; }
.split-main { border-top-right-radius:0; border-bottom-right-radius:0; }
.split-caret { border-top-left-radius:0; border-bottom-left-radius:0; padding-left:8px; padding-right:8px;
border-left:1px solid rgba(255,255,255,0.3); }
.split-menu { position:absolute; top:calc(100% + 4px); right:0; z-index:9999; min-width:19rem;
background:var(--surface); border:1px solid var(--border); border-radius:var(--radius);
box-shadow:0 10px 30px rgba(0,0,0,0.6); padding:4px; display:none; }
.split-menu.is-open { display:block; }
.split-item { display:block; width:100%; text-align:left; background:transparent; border:none;
border-radius:var(--radius-sm); padding:8px 10px; cursor:pointer;
color:var(--text-soft); font-size:var(--fs-md); font-family:var(--sans); }
.split-item:hover, .split-item.is-active { background:var(--border); color:#fff; }
.split-item .note { display:block; font-size:var(--fs-sm); color:var(--text-mute); margin-top:2px; line-height:1.45; white-space:normal; }
.split-item:hover .note, .split-item.is-active .note { color:var(--text-soft); }
.watch-row { display:grid; grid-template-columns:1fr 1fr 1fr auto; gap:8px; align-items:start; }
.watch-row .cell { display:flex; min-width:0; }
.btn-del { padding:8px 11px; border-radius:7px; border:1px solid var(--border); background:transparent; color:var(--text-faint); font-size:var(--fs-base); cursor:pointer; line-height:1; height:2.2rem; }
.btn-del:hover { color:var(--danger); border-color:#7f1d1d; }
/* Only takes up room when it has something to say. It used to reserve a
line under every repository row whether or not there was a note, which
is most of what looked like dead space between rows. */
.row-note { grid-column:1 / -1; font-size:var(--fs-sm); margin:2px 0 0; display:flex; align-items:center; gap:6px; }
.row-note:empty { display:none; }
.mini-select { padding:6px 26px 6px 10px; border-radius:7px; border:1px solid var(--border); background:var(--surface); color:var(--text-dim); font-size:var(--fs-md); cursor:pointer; appearance:none; -webkit-appearance:none; background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%2364748b'/%3E%3C/svg%3E"); background-repeat:no-repeat; background-position:right 9px center; }
.mini-select:focus { border-color:var(--accent-solid); }
.hint { display:inline-flex; align-items:center; justify-content:center; width:1.2em; height:1.2em; border-radius:50%; border:1px solid var(--border); color:var(--text-faint); font-size:var(--fs-2xs); cursor:help; }
.hint:hover { color:var(--text-dim); border-color:var(--border-hi); }
.range-opt { display:flex; align-items:center; gap:7px; font-size:var(--fs-md); color:var(--text-dim); cursor:pointer; }
.range-opt input[type=radio] { width:0.9em; height:0.9em; cursor:pointer; accent-color:var(--accent-solid); flex-shrink:0; }
.range-opt.is-off { color:var(--text-faint); }
.range-opt input:disabled { opacity:0.5; cursor:not-allowed; }
.opt { display:flex; align-items:center; gap:7px; font-size:var(--fs-md); color:var(--text-dim); }
.opt input[type=checkbox] { width:0.9em; height:0.9em; cursor:pointer; accent-color:var(--accent-solid); }
.opt input[type=text], .opt input[type=number] { padding:6px 9px; border-radius:var(--radius-sm); border:1px solid var(--border); background:var(--bg); color:var(--text); font-size:var(--fs-md); }
.opt input[type=text]:focus, .opt input[type=number]:focus { border-color:var(--accent-solid); }
.opt select { padding:6px 24px 6px 9px; border-radius:var(--radius-sm); border:1px solid var(--border); background:var(--bg); color:var(--text); font-size:var(--fs-md); cursor:pointer; appearance:none; -webkit-appearance:none; background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M0 0l5 6 5-6z' fill='%2364748b'/%3E%3C/svg%3E"); background-repeat:no-repeat; background-position:right 8px center; }
/* Widths that used to sit in style attributes on the markup. */
#opt-baseline { width:18.75rem; }
#opt-days { width:4rem; }
.err-wrap { padding:16px; }
/* ── Toolbar / filters ────────────────────────────────────────────── */
/* Both token fields now sit inside the panel, on the same background. */
.filter-drop { position:absolute; top:calc(100% + 4px); left:0; right:0; z-index:9999; margin:0; padding:0; list-style:none; background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); max-height:15.625rem; overflow-y:auto; box-shadow:0 10px 30px rgba(0,0,0,0.6); display:none; }
.filter-opt { padding:8px 12px; cursor:pointer; font-size:var(--fs-base); color:var(--text-soft); border-bottom:1px solid var(--bg); font-family:var(--mono); }
.filter-opt:last-child { border-bottom:none; }
.filter-opt.active, .filter-opt:hover { background:var(--border); color:#fff; }
.filter-opt-field { color:var(--accent); font-weight:600; }
.filter-chip-field { color:var(--accent); font-weight:600; }
/* ── PR groups / table ────────────────────────────────────────────── */
.group { margin-bottom:18px; }
/* The bar is a click target, but the repository and branch names in it are
text people copy. `user-select:none` on the whole bar made them
unselectable, so it is scoped to the parts that are only decoration. */
.group-head { position:relative; display:flex; align-items:center; gap:10px; padding:10px 14px; background:var(--surface); border:1px solid var(--border); border-radius:10px 10px 0 0; flex-wrap:wrap; cursor:pointer; }
.group-head .group-count, .group-head .group-toggle, .group-head .cutoff-chip { user-select:none; }
.group-progress { font-size:var(--fs-sm); color:var(--accent); font-family:var(--mono); white-space:nowrap; }
.group-bar { position:absolute; left:0; bottom:0; height:2px; background:var(--accent); width:0; transition:width 0.18s linear; border-bottom-left-radius:2px; }
.group-head:hover { background:var(--surface-hi); }
.group-head.collapsed { border-radius:10px; }
.group-toggle { border:none; background:transparent; color:var(--text-mute); cursor:pointer; font-size:var(--fs-sm); padding:0 2px; line-height:1; }
.group-toggle:hover { color:var(--text-soft); }
.stack-mark { color:var(--accent); font-size:var(--fs-md); margin-right:4px; }
.stack-tag { font-size:var(--fs-xs); color:var(--accent); background:rgba(129,140,248,0.10); border:1px solid rgba(129,140,248,0.28); border-radius:999px; padding:1px 7px; font-family:var(--mono); }
.group-title { font-size:var(--fs-base); font-weight:600; color:var(--text-soft); font-family:var(--mono); }
.group-branch { font-size:var(--fs-md); color:var(--accent); font-family:var(--mono); }
.group-count { font-size:var(--fs-sm); color:var(--text-mute); }
.cutoff-chip { font-size:var(--fs-xs); color:var(--accent); background:rgba(129,140,248,0.10); border:1px solid rgba(129,140,248,0.28); border-radius:999px; padding:2px 8px; font-family:var(--mono); }
.trunc-chip { font-size:var(--fs-xs); color:var(--warn); background:rgba(251,191,36,0.10); border:1px solid rgba(251,191,36,0.30); border-radius:999px; padding:2px 8px; font-family:var(--mono); }
.group-body { border:1px solid var(--border); border-top:none; border-radius:0 0 10px 10px; overflow-x:auto; }
table { width:100%; border-collapse:collapse; }
th { text-align:left; font-size:var(--fs-xs); font-weight:700; letter-spacing:0.08em; text-transform:uppercase; color:var(--text-faint); padding:9px 14px; background:var(--surface-alt); border-bottom:1px solid var(--border); white-space:nowrap; }
td { padding:11px 14px; border-bottom:1px solid var(--surface); vertical-align:top; font-size:var(--fs-base); }
tr:last-child td { border-bottom:none; }
tr.pr-row:hover td { background:var(--surface-alt); }
.col-pr { min-width:17.5rem; }
.col-author { width:9.375rem; }
.col-rev { min-width:14.375rem; }
.col-labels { min-width:10.625rem; }
.col-status { width:8.125rem; }
.pr-title { font-size:var(--fs-base); font-weight:500; color:var(--text); text-decoration:none; line-height:1.45; }
.pr-title:hover { color:var(--accent); text-decoration:underline; }
.pr-num { font-family:var(--mono); font-size:var(--fs-sm); color:var(--text-faint); text-decoration:none; }
.pr-num:hover { color:var(--accent); }
.pr-meta { font-size:var(--fs-sm); color:var(--text-faint); margin-top:4px; display:flex; gap:9px; flex-wrap:wrap; align-items:center; }
.draft-tag { font-size:var(--fs-xs); font-weight:700; text-transform:uppercase; letter-spacing:0.05em; color:var(--text-mute); border:1px solid var(--border); border-radius:4px; padding:1px 5px; }
.handle { font-family:var(--mono); font-size:var(--fs-md); color:var(--text-dim); text-decoration:none; }
.handle:hover { color:var(--accent); }
.chips { display:flex; flex-wrap:wrap; gap:5px; }
.chip { display:inline-flex; align-items:center; gap:4px; font-size:var(--fs-sm); padding:2px 8px; border-radius:999px; border:1px solid transparent; font-family:var(--mono); text-decoration:none; max-width:13.125rem; }
.chip:hover { filter:brightness(1.25); }
.chip .ico { font-size:var(--fs-2xs); }
.chip-approved { background:rgba(74,222,128,0.12); color:var(--ok); border-color:rgba(74,222,128,0.3); }
.chip-changes { background:rgba(251,191,36,0.12); color:var(--warn); border-color:rgba(251,191,36,0.3); }
.chip-commented { background:rgba(148,163,184,0.10); color:var(--text-dim); border-color:rgba(148,163,184,0.25); }
.chip-pending { background:transparent; color:var(--text-mute); border-color:var(--border); border-style:dashed; }
.chip-dismissed { background:transparent; color:var(--text-faint); border-color:var(--border); text-decoration:line-through; }
.chip-label { font-family:var(--sans); font-weight:500; }
.rev-group { margin-bottom:5px; }
.rev-group:last-child { margin-bottom:0; }
.status { display:inline-flex; align-items:center; gap:6px; font-size:var(--fs-md); font-weight:600; white-space:nowrap; }
.status .dot { width:0.55em; height:0.55em; border-radius:50%; flex-shrink:0; }
@media (max-width: 51.25em) {
.cfg-row { grid-template-columns:minmax(0,1fr); gap:6px; padding:10px 0; }
.cfg-row > .panel-label { padding-top:0; }
.watch-row { grid-template-columns:1fr 1fr; }
.watch-row .cell:nth-child(3) { grid-column:1 / -1; }
td, th { padding:9px 10px; }
}
</style>
</head>
<body>
<div id="app"></div>
<script src="gh-common.js"></script>
<script>
/* ══════════════════════════════════════════════════════════════════════════
PR Review Tracker
─────────────────
A browser-only replacement for the PR Tracker Google Sheet. Every viewer
supplies their own GitHub token, so repo visibility is enforced by GitHub
itself: a private repo simply 404s for anyone whose token can't read it.
Nothing is ever sent to a server - PR data is fetched live from the GitHub
API and rendered in-page.
Persistence model:
- Token → localStorage (opt-in) or sessionStorage (this tab only).
- Watch list → localStorage, and encodable into the URL hash so a
configuration can be shared as a plain link.
- Reviews of merged PRs → localStorage cache (a merged PR's review
state is frozen, so it never needs re-fetching).
══════════════════════════════════════════════════════════════════════════ */
/* ── Storage keys ─────────────────────────────────────────────────────────
The token keys live in gh-common.js and are shared across dashboards; these
are the tracker's own. All of them are listed in gh-common's OWNED_KEYS so
that "Forget token" clears the cached review data too. */
const CONFIG_KEY = 'gh_pr_tracker_config';
const CACHE_KEY_V1 = 'gh_pr_tracker_review_cache_v1'; // retired: held filtered lists
const REVIEWS_KEY = 'gh_pr_tracker_reviews_v2';
const COMMITS_KEY = 'gh_pr_tracker_commit_dates_v1';
const RESULTS_KEY = 'gh_pr_tracker_results_v1';
const IMPORTED_KEY = 'gh_pr_tracker_imported_hash';
/* ── Defaults ───────────────────────────────────────────────────────────── */
const DEFAULT_CONFIG = {
watches: [], // [{ org, repo, branch }]
range: 'days', // how much merged history: days | baseline | all
mergedDays: 30, // used by the 'days' range
baselineCommit: '', // used by the 'baseline' range
includeStacked: true, // follow PR chains beyond the base branch
hideDrafts: false,
filters: [], // [{ field, value }] - one entry per field
denylist: 'xrplf-ai-reviewer[bot], copilot-pull-request-reviewer[bot], copilot-swe-agent[bot]',
autoRefreshSec: 300, // 0 = manual only
collapsed: {}, // group key -> true (local only, not shared)
};
/* How often the tab may re-poll GitHub. Declared here with the other config
constants because `migrateConfig` snaps to it: it is the set of legal values,
not just the contents of a dropdown. */
const AUTO_INTERVALS = [0, 60, 300, 900, 1800, 3600];
/* The label that marks a PR cleared to land. Fixed rather than configurable:
one convention across the repos we track. */
const READY_LABEL = 'Ready to Merge';
const SHA_RE = /^[0-9a-f]{7,40}$/i;
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
/* Filterable fields. Everything except `title` has a bounded set of values in
the fetched data, so those can be auto-completed. */
const FILTER_FIELDS = ['title', 'author', 'reviewer', 'status', 'label', 'milestone'];
const NO_VALUE = '(none)';
/* How much merged history a watched branch pulls in. One control per row,
because `develop` and a staging branch genuinely want different answers. */
/* How much merged history to pull in. One setting for the whole watch list:
it was per-row, but in practice every row wants the same answer and the
two inputs it depends on were global anyway, which made the pairing
confusing. Open pull requests are always included. */
const RANGES = ['all', 'baseline', 'days'];
const STATUS_META = {
'Draft': { color: '#9fadc0' },
'In Review': { color: '#67e8f9' },
'Changes Requested': { color: '#fbbf24' },
'Approved': { color: '#34d399' },
'Ready to Merge': { color: '#4ade80' },
'Queued': { color: '#818cf8' },
'Merged': { color: '#a78bfa' },
'Reverted': { color: '#f87171' },
};
/* ── App state ────────────────────────────────────────────────────────────
`app` comes from gh-common.js (token, username, orgs, connecting); these are
the fields only this page cares about. */
Object.assign(app, { loading: false, lastRefresh: null, refreshIndex: 0, refreshTotal: 0,
snapshotAt: null });
let config = { ...DEFAULT_CONFIG, watches: [] };
let results = []; // [{ key, org, repo, branch, prs, error, loading }]
const rowUi = []; // per-watch-row DOM refs + generation counters
/* ══════════════════════════════════════════════════════════════════════════
Merged-review cache
A merged PR can't collect new reviews, so its raw review history is frozen
and worth caching across sessions - this is the single most expensive part
of a refresh (one request per PR).
What gets cached is the *raw* review facts, never the derived reviewer
lists. Caching the derived lists means a later change to the ignore list -
or to how reviewer states are resolved - can never reach a merged PR again,
because it is never re-fetched. Storing the inputs and re-deriving on every
render keeps the cache a pure bandwidth optimisation with no effect on what
is displayed.
══════════════════════════════════════════════════════════════════════════ */
let reviewCache = (() => {
try { return JSON.parse(store.get(REVIEWS_KEY) || '{}'); } catch (e) { return {}; }
})();
/* The pre-v2 cache held filtered reviewer objects; drop it. */
try { store.del(CACHE_KEY_V1); } catch (e) { /* ignore */ }
/* Store only what computeReviewers reads, as compact triples. */
function compactReviews(reviews) {
return (reviews || []).map(rv => [
(rv.user && rv.user.login) || '', rv.state || '', rv.submitted_at || '',
]);
}
function expandReviews(rows) {
return (rows || []).map(([login, state, submitted_at]) => ({
user: { login }, state, submitted_at,
}));
}
function cacheGet(key) {
const hit = reviewCache[key];
return Array.isArray(hit) ? hit : null; // ignore any older shape
}
function cacheSet(key, val) { reviewCache[key] = val; }
function cacheFlush() {
const keys = Object.keys(reviewCache);
if (keys.length > 4000) { // keep the store bounded
const trimmed = {};
keys.slice(-3000).forEach(k => { trimmed[k] = reviewCache[k]; });
reviewCache = trimmed;
}
try { store.set(REVIEWS_KEY, JSON.stringify(reviewCache)); } catch (e) { /* non-fatal */ }
}
/* Bots that used to be excluded by default. A stored config (or an older
shareable link) carries whatever the default was when it was written, so an
addition to the default list would never reach anyone who has used the tool
before. Upgrade any denylist that still matches a previous default, leaving
hand-edited ones alone.
Comparison is order- and spacing-insensitive, so reformatting the default
string here can't accidentally strand existing users on an old list. */
const LEGACY_DENYLISTS = [
'xrplf-ai-reviewer[bot]',
'xrplf-ai-reviewer[bot], copilot-pull-request-reviewer[bot]',
];
function normalizeLogins(value) {
return String(value || '')
.split(/[,\n]/).map(s => s.trim().toLowerCase()).filter(Boolean)
.sort().join(',');
}
function migrateDenylist(value) {
const normalized = normalizeLogins(value);
if (!normalized) return value; // deliberately empty
return LEGACY_DENYLISTS.some(l => normalizeLogins(l) === normalized)
? DEFAULT_CONFIG.denylist
: value;
}
/* ══════════════════════════════════════════════════════════════════════════
Config: localStorage + shareable URL hash
══════════════════════════════════════════════════════════════════════════ */
/* Scope values have changed shape once already (they used to be a free-text
"since" field holding a SHA, a date, "all" or "none"). Normalise whatever a
stored config or an older link carries onto the current enum. */
function normalizeScope(value, legacyMode) {
const v = String(value === undefined || value === null ? '' : value).trim().toLowerCase();
if (v === 'all') return 'all';
/* "Open PRs only" is retired; those rows become the plain default. */
if (v === 'none' || v === 'open') return '';
if (RANGES.includes(v)) return v;
if (SHA_RE.test(v) || DATE_RE.test(v)) return 'baseline'; // was a per-row cutoff
switch (legacyMode) { // was a global mode
case 'none': return '';
case 'all': return 'all';
case 'commit': return 'baseline';
case 'days': return 'days';
}
return 'days';
}
function normalizeFilters(list, legacyMilestone) {
const out = [];
const seen = new Set();
const add = (field, value) => {
const f = String(field || '').trim().toLowerCase();
const v = String(value === undefined || value === null ? '' : value).trim();
if (!FILTER_FIELDS.includes(f) || !v || seen.has(f)) return;
seen.add(f);
out.push({ field: f, value: v });
};
(list || []).forEach(item => {
if (Array.isArray(item)) add(item[0], item[1]);
else if (item && typeof item === 'object') add(item.field, item.value);
});
/* The milestone dropdown became a filter chip. */
if (legacyMilestone) add('milestone', legacyMilestone === '\u0000none' ? NO_VALUE : legacyMilestone);
return out;
}
/* A shared link is untrusted input. Owner and repository have a known grammar,
so anything that isn't one is dropped rather than carried into the UI; a git
ref is far more permissive, so it is only stripped of control characters and
bounded. Escaping at the sinks is the real defence - this just stops junk
reaching them in the first place. */
function safeName(v) {
const t = String(v === undefined || v === null ? '' : v).trim();
return isGhName(t) ? t : '';
}
function safeRef(v) {
return String(v === undefined || v === null ? '' : v)
.trim().replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 255);
}
/* Collapse whatever per-row scopes an older config carried into the single
global range: the first row that named a real one wins, and if none did
(everything was "open only", or the config predates scopes) fall back to
the default. */
function collapseRange(r) {
const explicit = normalizeScope(r.range, undefined);
if (r.range !== undefined && RANGES.includes(explicit)) return explicit;
for (const w of (r.watches || [])) {
const v = normalizeScope(w.scope !== undefined ? w.scope : w.since, r.mergedMode);
if (RANGES.includes(v)) return v;
}
return DEFAULT_CONFIG.range;
}
/* Everything a shared link can carry has to be bounded here, because a link is
untrusted input and this is the only gate it passes through. `mergedDays` was
already clamped; the two below were not.
MAX_WATCHES is generous against real use (a dozen rows is a busy board) and
cheap against abuse: each row builds three Comboboxes, and each Combobox holds
its own document-level mousedown listener, so an unbounded list makes every
click on the page run thousands of handlers. */
const MAX_WATCHES = 50;
function migrateConfig(raw) {
const r = raw || {};
return {
watches: (r.watches || []).slice(0, MAX_WATCHES).map(w => ({
org: safeName(w.org), repo: safeName(w.repo), branch: safeRef(w.branch),
})),
range: collapseRange(r),
mergedDays: clampInt(r.mergedDays, 1, 365, DEFAULT_CONFIG.mergedDays),
baselineCommit: typeof r.baselineCommit === 'string' ? r.baselineCommit.trim() : '',
includeStacked: r.includeStacked === undefined ? DEFAULT_CONFIG.includeStacked : !!r.includeStacked,
hideDrafts: !!r.hideDrafts,
filters: normalizeFilters(r.filters, r.milestoneFilter),
denylist: migrateDenylist(typeof r.denylist === 'string' ? r.denylist : DEFAULT_CONFIG.denylist),
/* Snap to an interval the dropdown actually offers. A link asking for
`"ar":1` would otherwise poll GitHub once a second for as long as the
recipient's tab is focused, quietly spending their rate limit. */
autoRefreshSec: AUTO_INTERVALS.includes(Number(r.autoRefreshSec))
? Number(r.autoRefreshSec)
: DEFAULT_CONFIG.autoRefreshSec,
collapsed: (r.collapsed && typeof r.collapsed === 'object') ? { ...r.collapsed } : {},
};
}
/* ══════════════════════════════════════════════════════════════════════════
Last-results snapshot
A cold refresh takes a while, and until now a reload stared at an empty
table for the whole of it. The in-session behaviour was already the right
one - refreshAll() reuses the existing group objects so their rows stay put
while new data is fetched - this just extends that across reloads.
Only the fields the table actually renders are stored: the raw pull request
objects are an order of magnitude larger, and none of the rest is read
again. The snapshot is always replaced by a live fetch on load, so it is a
placeholder, never a source of truth.
══════════════════════════════════════════════════════════════════════════ */
/* Bumped when the fingerprint changed shape: an older snapshot is discarded
as out of date rather than reported as a confusing settings mismatch. */
/* Bump whenever a stored snapshot would be wrong rather than merely old, so it
is discarded instead of being restored and believed.
3: revert detection was rewritten. `revertedFlag` is stored per pull request
and `applyDenylistToResults` derives the Reverted status straight from it
on restore, so a snapshot written by the old matcher would keep showing
its false positives (every "Bump version" marked Reverted because one of
them was) until the first live refresh replaced them.
2: the fingerprint changed shape. */
const SNAPSHOT_VERSION = 3;
const SNAPSHOT_MAX_AGE_MS = 7 * 86400000;
const SNAPSHOT_MAX_BYTES = 2_000_000;
/* Anything that changes what a fetch would return. A snapshot taken under
different settings describes a different question, so it is discarded
rather than shown briefly and corrected. Filters are deliberately absent:
they are applied at render time, so they never invalidate the data. */
function snapshotFingerprint() {
/* The ignore list is deliberately absent: it is applied when the snapshot
is restored, so changing it does not make the stored data wrong. */
return JSON.stringify([
config.range, config.mergedDays, config.baselineCommit, config.includeStacked,
]);
}
function trimPrForSnapshot(pr) {
const out = {
number: pr.number, title: pr.title, html_url: pr.html_url || '',
draft: !!pr.draft, merged_at: pr.merged_at || null,
created_at: pr.created_at || null, updated_at: pr.updated_at || null,
};
if (pr.user && pr.user.login) out.user = { login: pr.user.login };
const labels = (pr.labels || []).map(l => (typeof l === 'string'
? { name: l }
: { name: l.name, color: l.color, description: l.description }));
if (labels.length) out.labels = labels;
if (pr.milestone && pr.milestone.title) out.milestone = { title: pr.milestone.title };
/* The unfiltered lists, not the filtered ones: the ignore list is applied
on restore, so a snapshot stays valid across changes to it. */
if (pr.reviewersAll) out.reviewersAll = pr.reviewersAll;
if (pr.revertedFlag) out.revertedFlag = true;
if (pr.reviewError) out.reviewError = pr.reviewError;
if (pr.stackDepth) { out.stackDepth = pr.stackDepth; out.stackParent = pr.stackParent; }
if (pr.base && pr.base.ref) out.base = { ref: pr.base.ref };
if (pr.auto_merge) {
out.auto_merge = {
merge_method: pr.auto_merge.merge_method,
enabled_by: pr.auto_merge.enabled_by ? { login: pr.auto_merge.enabled_by.login } : null,
};
}
if (pr.mergeQueue) out.mergeQueue = pr.mergeQueue;
return out;
}
/* What happened last time we tried to save or restore, so a failure is
visible instead of the board just quietly loading from scratch. */
let snapshotNote = '';
function snapshotLog(msg) {
snapshotNote = msg;
console.info('[pr-tracker] snapshot: ' + msg);
}
/* localStorage is a few megabytes for the whole origin, shared with the review
cache, and a busy board can exceed it. Rather than silently storing nothing,
give up detail until it fits: merged pull requests are history, the open
ones are what the board is for. */
const SNAPSHOT_MERGED_CAPS = [Infinity, 200, 50, 0];
function saveSnapshot() {
try {
const full = results
.filter(r => !r.error && r.prs && r.prs.length)
.map(r => ({
key: r.key, org: r.org, repo: r.repo, branch: r.branch,
cutoffLabel: r.cutoffLabel || '', stackedCount: r.stackedCount || 0,
truncated: r.truncated || '', mergeQueueError: r.mergeQueueError || '',
prs: r.prs.map(trimPrForSnapshot),
}));
if (!full.length) { store.del(RESULTS_KEY); snapshotLog('nothing to save'); return; }
for (const cap of SNAPSHOT_MERGED_CAPS) {
const groups = full.map(g => {
if (cap === Infinity) return g;
let kept = 0;
return { ...g, prs: g.prs.filter(pr => !pr.merged_at || ++kept <= cap) };
});
const json = JSON.stringify({
v: SNAPSHOT_VERSION, savedAt: Date.now(), fp: snapshotFingerprint(),
mergedCap: cap === Infinity ? null : cap, groups,
});
if (json.length > SNAPSHOT_MAX_BYTES) continue;
if (store.set(RESULTS_KEY, json)) {
const n = groups.reduce((t, g) => t + g.prs.length, 0);
snapshotLog(`saved ${n} pull requests` +
(cap === Infinity ? '' : `, merged history capped at ${cap} per branch to fit`));
return;
}
/* The write did not persist. Free the biggest neighbour and try again
at the same size before shedding any more detail. */
if (cap === SNAPSHOT_MERGED_CAPS[0]) {
console.info('[pr-tracker] storage full; dropping the merged-review cache to make room');
reviewCache = {};
store.del(REVIEWS_KEY);
if (store.set(RESULTS_KEY, json)) { snapshotLog('saved after clearing the review cache'); return; }
}
}
store.del(RESULTS_KEY);
snapshotLog('could not be saved - browser storage is full or blocked');
} catch (e) {
snapshotLog('could not be saved (' + (e && e.message) + ')');
}
}
/* Give up on the stored copy, and throw it away rather than leaving it to be
rejected again on the next load.
A snapshot that cannot be used is not going to become usable, and leaving it
in place has a nasty failure mode: if a later save then fails or has nothing
to write, the same dead blob is re-read and re-rejected on every single load,
so the reason never changes and it looks like saving is broken when the real
problem is that the old copy was never cleared. Deleting here guarantees the
next cycle starts from a clean slate. */
function discardSnapshot(why) {
store.del(RESULTS_KEY);
snapshotLog(why + ' - discarded, the next refresh will save a fresh copy');
return [];
}
function loadSnapshot() {
const raw = store.get(RESULTS_KEY);
if (!raw) { snapshotLog('none stored yet'); return []; }
let payload;
try { payload = JSON.parse(raw); }
catch (e) { return discardSnapshot('stored copy is not readable JSON'); }
/* Three separate reasons, reported separately. They used to share one
"stored copy is from an older version", which is actively misleading when
the truth is a corrupt shape, and gives no way to tell a real version bump
from a structural problem. */
if (!payload || typeof payload !== 'object') {
return discardSnapshot('stored copy is not an object');
}
if (payload.v !== SNAPSHOT_VERSION) {
return discardSnapshot(`stored copy is version ${JSON.stringify(payload.v)}, this build writes version ${SNAPSHOT_VERSION}`);
}
if (!Array.isArray(payload.groups)) {
return discardSnapshot('stored copy has no group list');
}
if (payload.fp !== snapshotFingerprint()) {
return discardSnapshot(`settings changed since it was saved (was ${payload.fp}, now ${snapshotFingerprint()})`);
}
const age = Date.now() - Number(payload.savedAt || 0);
if (!Number.isFinite(age) || age < 0 || age > SNAPSHOT_MAX_AGE_MS) {
return discardSnapshot('stored copy is older than 7 days');
}
/* Keyed to the watch list as it stands now, and in its order, so a row
added or removed since does not resurrect or misplace a group. */
const wanted = new Set(config.watches.filter(w => w.org && w.repo && w.branch)
.map(w => `${w.org}/${w.repo}@${w.branch}`));
const byKey = new Map(payload.groups.map(g => [g.key, g]));
const groups = [...wanted].map(k => byKey.get(k)).filter(Boolean).map(g => ({
key: g.key, org: g.org, repo: g.repo, branch: g.branch,
prs: Array.isArray(g.prs) ? g.prs : [],
cutoffLabel: g.cutoffLabel || '', stackedCount: g.stackedCount || 0,
truncated: g.truncated || '', mergeQueueError: g.mergeQueueError || '',
error: '', loading: false,
}));
if (groups.length) {
app.snapshotAt = new Date(payload.savedAt);
snapshotLog(`restored ${groups.reduce((t, g) => t + g.prs.length, 0)} pull requests from ` +
new Date(payload.savedAt).toLocaleString());
} else {
snapshotLog('stored copy covers none of the repositories currently watched');
}
return groups;
}
/* ══════════════════════════════════════════════════════════════════════════
Config: localStorage + shareable URL hash
══════════════════════════════════════════════════════════════════════════ */
function encodeConfig(cfg) {
const json = JSON.stringify({
w: cfg.watches.map(w => [w.org, w.repo, w.branch]),
rg: cfg.range,
d: cfg.mergedDays,
bc: cfg.baselineCommit,
st: cfg.includeStacked ? 1 : 0,
hd: cfg.hideDrafts ? 1 : 0,
f: cfg.filters.map(f => [f.field, f.value]),
dl: cfg.denylist,
ar: cfg.autoRefreshSec,
});
return b64EncodeUtf8(json).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function decodeConfig(str) {
const o = JSON.parse(b64DecodeUtf8(str.replace(/-/g, '+').replace(/_/g, '/')));
/* `m` (include-merged boolean) predates `mm`, which predates per-row scopes. */
const legacyMode = typeof o.mm === 'string' ? o.mm : (o.m === 0 ? 'none' : undefined);
return migrateConfig({
watches: (o.w || []).map(([org, repo, branch, scope]) => ({ org, repo, branch, since: scope })),
range: o.rg,
mergedMode: legacyMode,
mergedDays: o.d,
baselineCommit: o.bc,
includeStacked: o.st === undefined ? undefined : o.st === 1,
hideDrafts: o.hd === 1,
filters: o.f,
milestoneFilter: o.ms,
denylist: o.dl,
autoRefreshSec: o.ar,
});
}
/* A shared link is an import, not a permanent override.
It used to win on every single load, which meant that once a `#c=` was in
the address bar - and "Copy shareable link" puts one there for the person
sharing it - every later change to the watch list, the range or the ignore
list was written to local storage and then silently thrown away on the next
reload. So the link is adopted once, saved as the stored configuration, and
then got out of the way.
Clearing the hash is the tidy half of that and it is not always allowed:
`history.replaceState` throws on a `file://` page. The marker is what
actually guarantees the link is only ever applied once. */
let importedFromLink = false;
function loadConfig() {
const hash = location.hash.replace(/^#/, '');
const m = /(?:^|&)c=([^&]+)/.exec(hash);
if (m && store.get(IMPORTED_KEY) !== m[1]) {
try {
const cfg = decodeConfig(m[1]);
store.set(CONFIG_KEY, JSON.stringify(cfg));
store.set(IMPORTED_KEY, m[1]);
clearConfigHash();
importedFromLink = true;
return cfg;
} catch (e) { /* unreadable link: fall through to whatever is stored */ }
}
try {
const saved = JSON.parse(store.get(CONFIG_KEY) || 'null');
if (saved) return migrateConfig(saved);
} catch (e) { /* ignore */ }
return migrateConfig({});
}
function clearConfigHash() {
try { history.replaceState(null, '', location.pathname + location.search); }
catch (e) { /* file:// forbids this; the marker above covers us */ }
}
function saveConfig() {
/* Collapsed state is keyed by repo@branch and nothing ever removed an entry,
so rows that were watched once kept their key forever. Prune to what is
actually on the board before writing. */
const live = new Set(config.watches
.filter(w => w.org && w.repo && w.branch)
.map(w => `${w.org}/${w.repo}@${w.branch}`));
Object.keys(config.collapsed).forEach(k => { if (!live.has(k)) delete config.collapsed[k]; });
store.set(CONFIG_KEY, JSON.stringify(config));
}
/* The share link is built at the point it is copied, because the caller also
needs the encoded string itself to mark it as already imported. */
/* ══════════════════════════════════════════════════════════════════════════
Merge cutoff
"Everything merged since the previous release" is the question this tracker
exists to answer, and a release is identified by a commit, not a date. So a
cutoff may be given as a commit SHA, which is resolved to that commit's
date and handed to the Search API as `merged:>`, exactly as the Apps Script
did - GitHub does the filtering server-side rather than us paging through
history.
The cutoff is per watched branch, because the branches want different
answers: `develop` wants "since the release baseline", while a
`staging/N.M.x` branch wants everything that ever landed on it.
══════════════════════════════════════════════════════════════════════════ */
let commitDateCache = (() => {
try { return JSON.parse(store.get(COMMITS_KEY) || '{}'); } catch (e) { return {}; }
})();
async function commitDate(org, repo, sha) {
const key = `${org}/${repo}@${sha.toLowerCase()}`;
if (commitDateCache[key]) return commitDateCache[key]; // commits are immutable
let data;
try {
data = await ghGet(app.token, `/repos/${seg(org)}/${seg(repo)}/commits/${seg(sha)}`);
} catch (e) {
if (e.status === 404) {
throw new Error(`Commit ${sha.slice(0, 10)} isn't in ${org}/${repo}'s history. The baseline applies to every watched repository, so it has to be a commit they all share - otherwise use "Last N days" or "Everything".`);
}
throw e;
}
const iso = (data.commit && ((data.commit.committer && data.commit.committer.date) ||
(data.commit.author && data.commit.author.date))) || null;
if (!iso) throw new Error(`Commit ${sha.slice(0, 10)} returned no date.`);
commitDateCache[key] = iso;
/* Bounded like the review cache is. Commits are immutable so nothing here
goes stale, but a baseline changes every release and the entries would
otherwise accumulate for the life of the browser profile, competing with
the board snapshot for the origin's storage quota. */
const keys = Object.keys(commitDateCache);
if (keys.length > 500) {
const trimmed = {};
keys.slice(-400).forEach(k => { trimmed[k] = commitDateCache[k]; });
commitDateCache = trimmed;
}
try { store.set(COMMITS_KEY, JSON.stringify(commitDateCache)); } catch (e) { /* non-fatal */ }
return iso;
}
/* Returns { iso, op, label } - or { iso: null } for "no merged PRs at all"
/ "all merged PRs", distinguished by `skip`. */
/* Turn the configured range into a merged-PR window. Open pull requests are
always included; this only decides how far back merged history reaches. */
async function resolveScope(watch) {
switch (config.range) {
case 'all':
return { iso: null, label: 'all merged' };
case 'baseline': {
const sha = String(config.baselineCommit || '').trim();
if (!sha) {
throw new Error('No baseline commit set - fill in the SHA next to "Since commit", or pick a different range.');
}
if (!SHA_RE.test(sha)) {
throw new Error(`Baseline "${sha}" isn't a commit SHA.`);
}
const iso = await commitDate(watch.org, watch.repo, sha);
return { iso, op: '>', label: `since ${sha.slice(0, 7)} · ${iso.slice(0, 10)}` };
}
default: {
const iso = new Date(Date.now() - config.mergedDays * 86400000).toISOString().slice(0, 10);
return { iso, op: '>=', label: `merged in last ${config.mergedDays}d` };
}
}
}
/* Requirements 2 and 3 are both conditional on "if it exists" - a
staging/N.M.x branch that hasn't been cut yet is a normal state mid-cycle,
not an error, and deserves to be said out loud rather than shown as an
empty table. */
async function branchExists(org, repo, branch) {
/* One request, always. `/branches/{branch}` takes the ref with its slashes
raw - that is how the endpoint is defined - so `staging/2.5.x` goes on the
path as-is. There used to be a percent-encoded second attempt as a fallback,
which only ever fired for refs containing a slash, which is precisely the
release branches this tool exists for. It doubled the cost of every miss,
and the miss is the expected state for a release branch that has not been
cut yet, so it also doubled the exposure to a stalled request's 30-second
timeout. Encoding the slash makes GitHub look for a branch whose name
literally contains "%2F", so it could never have rescued a real 404. */
try {
await ghGet(app.token, `/repos/${seg(org)}/${seg(repo)}/branches/${branch}`);
return true;
} catch (e) {
if (e.status === 404) return false;
throw e;
}
}
/* ══════════════════════════════════════════════════════════════════════════
Reviewers
Three distinct populations, which the sheet couldn't express:
- submitted a verdict → APPROVED / CHANGES_REQUESTED / DISMISSED
- commented only → engaged, but no verdict
- still invited → `requested_reviewers` (GitHub drops a user from
this list the moment they submit a review, so
it is exactly "hasn't responded yet")
══════════════════════════════════════════════════════════════════════════ */
/* Ignore-list matching is tolerant about the `[bot]` suffix, so both
`copilot-pull-request-reviewer` and `copilot-pull-request-reviewer[bot]`
exclude the same account - the suffix is easy to get wrong by hand, and
getting it wrong silently fails open. */
function normLogin(s) {
return String(s || '').trim().toLowerCase().replace(/\[bot\]$/, '');
}
function makeDenyMatcher(logins) {
const set = new Set([...(logins || [])].map(normLogin).filter(Boolean));
return login => set.has(normLogin(login));
}
/* Returns every reviewer, ignore list not applied. Filtering happens later,
in filterReviewers(), so that editing the ignore list is a pure re-derive
over data already in memory rather than something that needs a refetch. */
function computeReviewers(reviews, pr) {
const authorLogin = (pr.user && pr.user.login || '').toLowerCase();
const sorted = (reviews || []).slice().sort(
(a, b) => new Date(a.submitted_at || 0) - new Date(b.submitted_at || 0)
);
const verdict = new Map(); // login → APPROVED | CHANGES_REQUESTED | DISMISSED
const commented = new Set();
sorted.forEach(rv => {
const login = rv.user && rv.user.login;
if (!login) return;
const lower = login.toLowerCase();
if (lower === authorLogin) return;
if (rv.state === 'PENDING') return; // unsubmitted draft review
if (rv.state === 'COMMENTED') { commented.add(login); return; }
// Latest non-COMMENTED state wins, mirroring GitHub's own PR UI: a
// comment left after an approval must not downgrade the approval.
verdict.set(login, rv.state);
});
const approved = [], changes = [], dismissed = [];
verdict.forEach((state, login) => {
if (state === 'APPROVED') approved.push(login);
else if (state === 'CHANGES_REQUESTED') changes.push(login);
else if (state === 'DISMISSED') dismissed.push(login);
});
const commentedOnly = [...commented].filter(l => !verdict.has(l));
const pending = [];
(pr.requested_reviewers || []).forEach(u => {
if (!u || !u.login) return;
const lower = u.login.toLowerCase();
if (lower === authorLogin || verdict.has(u.login)) return;
pending.push(u.login);
});
(pr.requested_teams || []).forEach(t => {
const name = t && (t.slug || t.name);
if (name) pending.push('@' + name);
});
const byName = (a, b) => a.toLowerCase().localeCompare(b.toLowerCase());
return {
approved: approved.sort(byName),
changes: changes.sort(byName),
commented: commentedOnly.sort(byName),
pending: pending.sort(byName),
dismissed: dismissed.sort(byName),
};
}
/* The ignore list, applied to already-derived reviewer lists. Teams carry an
"@" prefix for display but are matched on their bare slug, the same way they
were when the check lived inside computeReviewers. */
function filterReviewers(all, denySet) {
const isDenied = makeDenyMatcher(denySet);
const keep = l => !isDenied(String(l).replace(/^@/, ''));
const a = all || {};
return {
approved: (a.approved || []).filter(keep),
changes: (a.changes || []).filter(keep),
commented: (a.commented || []).filter(keep),
pending: (a.pending || []).filter(keep),
dismissed: (a.dismissed || []).filter(keep),
};
}
function currentDenySet() {
return new Set(denyList().map(x => x.toLowerCase()));
}
/* Re-apply the ignore list to everything on screen and recompute the statuses
it can change - an approval from an ignored reviewer should stop counting as
an approval. No network: the unfiltered lists are already held per PR. */
function applyDenylistToResults() {
const denySet = currentDenySet();
results.forEach(r => {
(r.prs || []).forEach(pr => {
if (pr.reviewersAll) pr.reviewers = filterReviewers(pr.reviewersAll, denySet);
});
const reverted = new Set((r.prs || []).filter(p => p.revertedFlag).map(p => p.number));
(r.prs || []).forEach(pr => { pr.status = computeStatus(pr, reverted); });
});
}
/* ══════════════════════════════════════════════════════════════════════════
Status + revert detection (ported from the Apps Script)
══════════════════════════════════════════════════════════════════════════ */
function hasLabel(pr, name) {
const target = (name || '').toLowerCase();
if (!target) return false;
return (pr.labels || []).some(l => {
const n = typeof l === 'string' ? l : l.name;
return n && n.toLowerCase() === target;
});
}
/* Only a title that opens with `Revert "` can be a revert, so the quoted subject
is extracted once per candidate rather than a regular expression being built
per (candidate, original) pair. Anchoring at the start also stops a title that
merely mentions another - `Docs: how to Revert "Add retry logic" safely` -
from being read as one.
The trailing `"` is matched greedily so that a subject which itself contains a
quote survives the round trip. */
const REVERT_RE = /^\s*revert\s+"([\s\S]*)"\s*$/i;
/* What a revert title claims to be reverting: the PR number if the reverted
subject carries a squash-merge `(#N)` suffix, and the bare subject either way. */
function revertTarget(pr) {
/* The revert's own squash suffix comes off first: a revert merged by squash is
titled `Revert "Fix thing (#601)" (#602)`, and the closing quote is not the
last character. What is left is `Revert "<subject>"`. */
const m = REVERT_RE.exec(stripPrSuffix(pr.title || ''));
if (!m) return null;
const subject = m[1];
/* Squash merges leave `(#N)` on the subject, which identifies the original
exactly. Merge-commit repositories do not, which is why the subject is kept
as a fallback. */
const num = /\(#(\d+)\)\s*$/.exec(subject);
return { number: num ? Number(num[1]) : null, subject: subject.trim() };
}
/* Which merged pull requests were later reverted.
Matching by number is exact. Matching by subject is not, so it is only used
when that subject is unique among the merged set: repetitive titles ("Bump
version", dependabot updates, "Update changelog") are common, and reverting
one of them used to mark every one of them as Reverted - a directly misleading
signal on a board whose job is saying what actually shipped.
Cost matters here too. This used to compile a regular expression for every
pair, which is up to 250,000 of them at the 500-merge cap, and it runs once
per repository per refresh on the main thread. Two linear passes and a map
lookup do the same work in a fraction of the time. */
function findRevertedNumbers(prs) {
const merged = prs.filter(p => !!p.merged_at);
const out = new Set();
const reverts = [];
const subjectCount = new Map();
merged.forEach(p => {
const t = revertTarget(p);
if (t) reverts.push({ by: p.number, target: t });
const key = String(p.title || '').trim();
if (key) subjectCount.set(key, (subjectCount.get(key) || 0) + 1);
});
if (!reverts.length) return out;
const byNumber = new Map(merged.map(p => [p.number, p]));
const bySubject = new Map();
merged.forEach(p => {
const key = String(p.title || '').trim();
if (key && !bySubject.has(key)) bySubject.set(key, p);
});
reverts.forEach(({ by, target }) => {
if (target.number !== null) {
const hit = byNumber.get(target.number);
/* A PR cannot revert itself; a title quoting its own number is noise. */
if (hit && hit.number !== by) out.add(hit.number);
return;
}
if (subjectCount.get(target.subject) !== 1) return; // ambiguous, so unusable
const hit = bySubject.get(target.subject);