Repository navigation
Expand file tree
/
Copy pathgm_download_test.js
More file actions
1483 lines (1410 loc) · 53.7 KB
/
Copy pathgm_download_test.js
File metadata and controls
1483 lines (1410 loc) · 53.7 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
// ==UserScript==
// @name GM_download / GM.download Test Harness
// @namespace tm-gmdl-test
// @version 0.2.0
// @description Comprehensive in-page tests for GM_download / GM.download — covers downloadMode native/browser, url types (string / blob / Blob obj), callbacks, abort, conflictAction, and edge cases.
// @author you
// @match *://*/*?GM_DOWNLOAD_TEST_SC
// @grant GM_download
// @grant GM.download
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_info
// @require https://cdn.jsdelivr.net/gh/scriptscat/scriptcat@36ab4ce5ff23c820a32cd13ac5a04d8834ab4d82/example/tests/lib/sctest.js
// @connect httpbingo.org
// @connect raw.githubusercontent.com
// @connect cdn.jsdelivr.net
// @connect ipv4.download.thinkbroadband.com
// @connect nonexistent-domain-abcxyz.test
// @noframes
// ==/UserScript==
/*
WHAT THIS DOES
--------------
- Builds an in-page test runner panel for GM_download / GM.download.
- Drives a battery of tests covering options, callbacks, modes, url forms, and edge paths.
- Every download actually writes a file to disk; all files go under a
user-configurable sub-folder (default: "scriptcat-gmdl-tests/") so cleanup
is one rm -rf away.
WHAT IT COVERS
--------------
Auto:
✓ GM_download(url, name) — string form
✓ GM_download({ ... }) — options-object form
✓ GM.download({ ... }) — promise form (resolve / reject)
✓ downloadMode "native" — sc default: SW xhr fetch then chrome.downloads
✓ downloadMode "browser" — chrome.downloads only, no xhr
✓ url types: http(s) string, blob: URL, data: URL, Blob object, File object
✓ conflictAction: uniquify / overwrite
✓ onprogress / onload / onerror / ontimeout
✓ abort() before connect, abort() during, abort() after onload
✓ headers (passed through to xhr in native mode)
✓ edge: bad url, empty url, 404, blocked host (@connect missing)
Manual (verdict-driven — human clicks Mark Pass/Fail/Skip; auto-skips after a timeout
so a forgotten test can never hang the runner):
• saveAs: true — dialog appears, user saves
• saveAs: true — user cancels → must NOT trigger onerror (the bug evaluated above)
• native + handle.abort() while downloading → no onload, no onerror after abort
• browser mode + cancel from chrome://downloads → must arrive as onload (save_cancelled),
NOT onerror (this is the regression the download.ts fix guards against)
• visual content check — open the file, confirm contents match
Why two cancel tests, not one?
In `downloadMode: "native"` the Service Worker fetches the whole file via xhr
BEFORE chrome.downloads sees anything, so chrome://downloads never shows a
real in-progress entry — you can't cancel it from there in time. So:
- native mode → test handle.abort() instead
- browser mode → test the chrome://downloads Cancel button (real timing)
HOW TO USE
----------
1. Install in ScriptCat / Tampermonkey. Grant all listed permissions.
2. Open any page whose URL matches *?GM_DOWNLOAD_TEST_SC
(e.g. https://example.com/?GM_DOWNLOAD_TEST_SC)
3. The panel appears bottom-right. Click "Run Auto" to start.
4. Files land in your downloads folder under the prefix shown in the panel.
Click "Set prefix" to change it. Click "Clear log" to reset counts.
*/
const enableTool = true;
(function () {
"use strict";
if (!enableTool) return;
let reportSession = null;
// ---------- Tiny DOM helper ----------
function h(tag, props = {}, ...children) {
const el = document.createElement(tag);
Object.entries(props).forEach(([k, v]) => {
if (k === "style" && typeof v === "object") Object.assign(el.style, v);
else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);
else el[k] = v;
});
for (const c of children) el.append(c && c.nodeType ? c : document.createTextNode(String(c)));
return el;
}
function escapeHtml(s) {
return String(s).replace(
/[&<>"']/g,
(m) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[m]
);
}
function fmtMs(ms) {
return ms < 1000 ? `${ms | 0}ms` : `${(ms / 1000).toFixed(2)}s`;
}
// ---------- Settings (persisted) ----------
// Prefix is the sub-folder under the user's Downloads dir. Trailing slash auto-appended.
function getPrefix() {
let p = "";
try {
p = (typeof GM_getValue === "function" ? GM_getValue("dl_prefix", "") : "") || "";
} catch {
/* ignore */
}
if (!p) p = "scriptcat-gmdl-tests/";
if (!p.endsWith("/")) p += "/";
return p;
}
function setPrefix(p) {
try {
if (typeof GM_setValue === "function") GM_setValue("dl_prefix", p);
} catch {
/* ignore */
}
}
// Each test gets a unique tail so re-runs don't collide unless we explicitly
// want them to (the conflictAction "overwrite" test reuses a fixed name).
const RUN_TAG =
Date.now().toString(36) +
"-" +
Math.floor(Math.random() * 36 ** 4)
.toString(36)
.padStart(4, "0");
function nameFor(label, ext = "bin") {
return getPrefix() + RUN_TAG + "-" + label.replace(/[^a-zA-Z0-9_-]+/g, "_") + "." + ext;
}
// ---------- A small dataset built once, reused everywhere ----------
// 1x1 transparent PNG (67 bytes).
const PNG_BYTES = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0a, 0x49,
0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, 0xae, 0xb4, 0xfa, 0x77,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
const PNG_BLOB = new Blob([PNG_BYTES], { type: "image/png" });
const TEXT_BLOB = new Blob(["hello from GM_download test harness"], { type: "text/plain" });
// File extends Blob; useful to verify the URL-object branch handles File too.
const TEXT_FILE = new File([TEXT_BLOB], "ignored-by-api.txt", { type: "text/plain" });
// httpbingo deterministic endpoint — returns N random bytes.
const HB = "https://httpbingo.org";
// ---------- Panel ----------
const panel = h(
"div",
{
id: "gmdl-test-panel",
style: {
position: "fixed",
bottom: "12px",
right: "12px",
width: "520px",
maxHeight: "78vh",
overflow: "auto",
zIndex: 2147483647,
background: "#111",
color: "#f5f5f5",
font: "13px/1.4 system-ui, -apple-system, Segoe UI, Roboto, sans-serif",
borderRadius: "10px",
boxShadow: "0 12px 30px rgba(0,0,0,.4)",
border: "1px solid #333",
},
},
h(
"div",
{
style: {
position: "sticky",
top: 0,
background: "#181818",
padding: "10px 12px",
borderBottom: "1px solid #333",
display: "flex",
alignItems: "center",
gap: "8px",
},
},
h(
"div",
{ style: { flex: "1 1 auto" } },
h(
"div",
{ style: { fontWeight: "600" } },
`GM_download Test Harness ${(typeof GM_info === "object" && GM_info.script && GM_info.script.version) || ""}`
),
h(
"div",
{
style: {
display: "flex",
flexDirection: "row",
gap: "10px",
marginTop: "2px",
opacity: 0.85,
flexWrap: "wrap",
},
},
h(
"div",
{ style: { fontWeight: "400" } },
`${(typeof GM_info === "object" && GM_info.scriptHandler) || "?"} ${(typeof GM_info === "object" && GM_info.version) || ""}`
),
h("div", { id: "counts", style: { marginLeft: "auto" } }, "…")
)
),
h("button", { id: "start", style: btnStyle() }, "Run Auto"),
h("button", { id: "clear", style: btnStyle("#444") }, "Clear log")
),
h(
"div",
{ id: "status", style: { padding: "6px 12px", borderBottom: "1px solid #222", opacity: 0.9 } },
"Status: idle"
),
// Settings strip.
h(
"div",
{
style: {
padding: "6px 12px",
borderBottom: "1px solid #222",
display: "flex",
gap: "8px",
alignItems: "center",
flexWrap: "wrap",
},
},
h("span", { style: { opacity: 0.8 } }, "Download prefix:"),
h("code", { id: "prefix", style: { background: "#222", padding: "2px 6px", borderRadius: "4px" } }, getPrefix()),
h("button", { id: "setPrefix", style: btnStyle("#444") }, "Set prefix"),
h("span", { style: { opacity: 0.6, marginLeft: "auto", fontSize: "11.5px" } }, `RunTag: ${RUN_TAG}`)
),
// Manual section.
h(
"details",
{ id: "manualWrap", open: false, style: { padding: "0 12px 8px", borderBottom: "1px solid #222" } },
h(
"summary",
{ style: { padding: "6px 0", cursor: "pointer", userSelect: "none" } },
"Manual tests (require human)"
),
h(
"div",
{ id: "manualHint", style: { fontSize: "12px", opacity: 0.75, margin: "4px 0 6px" } },
"Each manual test waits for your verdict. Read the instructions in the log, perform the action, then click Mark Pass or Mark Fail. Skip ends the test without a verdict."
),
h("div", { id: "manualButtons", style: { display: "flex", flexWrap: "wrap", gap: "6px", marginTop: "4px" } })
),
// Awaiting bar — shown only while a manual test is in flight.
h(
"div",
{
id: "awaitingWrap",
style: { padding: "8px 12px", borderBottom: "1px solid #222", display: "none", background: "#1a1408" },
},
h(
"div",
{ style: { display: "flex", alignItems: "center", gap: "8px", flexWrap: "wrap" } },
h(
"div",
{ style: { flex: "1 1 auto" } },
h("div", { style: { fontWeight: "600", color: "#fbbf24" } }, "⏳ Awaiting your action"),
h("div", { id: "awaitingLabel", style: { fontSize: "12px", opacity: 0.85, marginTop: "2px" } }, "")
),
h(
"div",
{ id: "awaitingTimer", style: { fontSize: "12px", opacity: 0.85, fontFamily: "ui-monospace, monospace" } },
""
),
// Optional in-flight action button (e.g. "🛑 Abort download"); tests register a handler via showAwaitingAction().
h("button", { id: "awaitingAction", style: { ...btnStyle("#0ea5e9"), display: "none" } }, ""),
h("button", { id: "awaitingPass", style: btnStyle("#16a34a") }, "✓ Mark Pass"),
h("button", { id: "awaitingFail", style: btnStyle("#dc2626") }, "✗ Mark Fail"),
h("button", { id: "awaitingSkip", style: btnStyle("#475569") }, "Skip")
)
),
// Queue.
h(
"details",
{ id: "queueWrap", open: false, style: { padding: "0 12px 6px", borderBottom: "1px solid #222" } },
h("summary", { style: { padding: "6px 0", cursor: "pointer", userSelect: "none" } }, "Pending auto tests"),
h(
"div",
{
id: "queue",
style: {
fontFamily: "ui-monospace, SFMono-Regular, Consolas, monospace",
whiteSpace: "pre-wrap",
opacity: 0.8,
},
},
"(none)"
)
),
// Live progress for currently running test.
h(
"div",
{ id: "progressWrap", style: { padding: "6px 12px", borderBottom: "1px solid #222", display: "none" } },
h("div", { id: "progressLabel", style: { fontSize: "12px", opacity: 0.8, marginBottom: "4px" } }, ""),
h(
"div",
{ style: { background: "#222", height: "6px", borderRadius: "3px", overflow: "hidden" } },
h("div", {
id: "progressBar",
style: { background: "#2a6df1", height: "100%", width: "0%", transition: "width .15s" },
})
)
),
h("div", { id: "log", style: { padding: "10px 12px" } })
);
document.documentElement.appendChild(panel);
function btnStyle(bg) {
return {
background: bg || "#2a6df1",
color: "white",
border: "0",
padding: "6px 10px",
borderRadius: "6px",
cursor: "pointer",
font: "inherit",
};
}
const $log = panel.querySelector("#log");
const $counts = panel.querySelector("#counts");
const $status = panel.querySelector("#status");
const $queue = panel.querySelector("#queue");
const $prefix = panel.querySelector("#prefix");
const $progressWrap = panel.querySelector("#progressWrap");
const $progressLabel = panel.querySelector("#progressLabel");
const $progressBar = panel.querySelector("#progressBar");
const $manualButtons = panel.querySelector("#manualButtons");
const $awaitingWrap = panel.querySelector("#awaitingWrap");
const $awaitingLabel = panel.querySelector("#awaitingLabel");
const $awaitingTimer = panel.querySelector("#awaitingTimer");
const $awaitingPass = panel.querySelector("#awaitingPass");
const $awaitingFail = panel.querySelector("#awaitingFail");
const $awaitingSkip = panel.querySelector("#awaitingSkip");
const $awaitingAction = panel.querySelector("#awaitingAction");
panel.querySelector("#clear").addEventListener("click", () => {
$log.textContent = "";
state.pass = state.fail = state.warn = state.info = state.skip = state.manual = 0;
setCounts();
setStatus("idle");
setQueue([]);
hideProgress();
});
panel.querySelector("#start").addEventListener("click", () => runAuto());
panel.querySelector("#setPrefix").addEventListener("click", () => {
const cur = getPrefix();
const next = prompt("Download sub-folder (under Downloads). Trailing slash optional.", cur);
if (next == null) return;
setPrefix(next.trim() || "scriptcat-gmdl-tests/");
$prefix.textContent = getPrefix();
logLine(`Prefix set to <code>${escapeHtml(getPrefix())}</code>`);
});
function logLine(html, cls = "") {
const line = h("div", { style: { padding: "6px 0", borderBottom: "1px dashed #2a2a2a" } });
line.innerHTML = html;
if (cls) line.className = cls;
$log.prepend(line);
}
// ---------- Counters & status ----------
const state = { pass: 0, fail: 0, warn: 0, info: 0, skip: 0, manual: 0 };
function setCounts() {
$counts.textContent = `PASS ${state.pass} FAIL ${state.fail} WARN ${state.warn} INFO ${state.info} SKIP ${state.skip} MANUAL ${state.manual}`;
}
setCounts();
function setStatus(text) {
$status.textContent = `Status: ${text}`;
}
function setQueue(items) {
$queue.textContent = items.length ? items.map((t, i) => `${i + 1}. ${t}`).join("\n") : "(none)";
}
function pass(msg) {
state.pass++;
setCounts();
logLine(`✅ ${escapeHtml(msg)}`);
}
function fail(msg, extra) {
state.fail++;
setCounts();
logLine(
`❌ ${escapeHtml(msg)}${extra ? `<pre style="white-space:pre-wrap;color:#bbb;margin:.5em 0 0">${escapeHtml(extra)}</pre>` : ""}`,
"fail"
);
}
function skip(msg) {
state.skip++;
setCounts();
logLine(`⏭️ ${escapeHtml(msg)}`);
}
function newReportSession() {
return SCTest.createReportSession({ name: "GM_download / GM.download", reporter: "panel" });
}
function reportVerdict(session, result, status, detail, name) {
if (!result) return session.record({ category: "GM_download", name, status, detail });
return session.update(result, status, { detail: detail || result.detail, manualVerdict: status });
}
function showProgress(label) {
$progressWrap.style.display = "";
$progressLabel.textContent = label;
$progressBar.style.width = "0%";
}
function updateProgress(loaded, total) {
if (total > 0) {
$progressBar.style.width = Math.min(100, Math.round((loaded / total) * 100)) + "%";
} else {
// Unknown total — fake an indeterminate bar that creeps up.
const cur = parseFloat($progressBar.style.width) || 0;
$progressBar.style.width = Math.min(95, cur + 5) + "%";
}
}
function hideProgress() {
$progressWrap.style.display = "none";
$progressBar.style.width = "0%";
}
// ---------- Assertion helpers ----------
function assertEq(a, b, msg) {
if (a !== b)
throw new Error(
msg ? `${msg}: expected ${JSON.stringify(b)}, got ${JSON.stringify(a)}` : `expected ${b}, got ${a}`
);
}
function assertTrue(cond, msg) {
if (!cond) throw new Error(msg || "assertTrue failed");
}
function withTimeout(p, ms, label) {
return new Promise((resolve, reject) => {
let done = false;
const t = setTimeout(() => {
if (done) return;
done = true;
reject(new Error(`timed out after ${ms}ms: ${label || ""}`));
}, ms);
p.then(
(v) => {
if (done) return;
done = true;
clearTimeout(t);
resolve(v);
},
(e) => {
if (done) return;
done = true;
clearTimeout(t);
reject(e);
}
);
});
}
// ---------- Awaiting bar (manual-test verdict UI) ----------
// The manual tests can't be "asserted" purely from JS — the contract often is
// "user sees a dialog, picks Cancel, the script doesn't crash". So we hand the
// verdict back to the human via Pass/Fail/Skip buttons. To avoid the runner
// hanging forever if the human disappears, every manual test runs under a
// countdown that auto-skips when it hits zero.
let _verdictResolve = null;
let _verdictTimerId = null;
let _verdictDeadline = 0;
function showAwaiting(label, deadlineSecs) {
$awaitingLabel.innerHTML = label; // caller controls HTML, we trust it
$awaitingWrap.style.display = "";
_verdictDeadline = performance.now() + deadlineSecs * 1000;
tickAwaitingTimer();
if (_verdictTimerId) clearInterval(_verdictTimerId);
_verdictTimerId = setInterval(tickAwaitingTimer, 250);
}
function tickAwaitingTimer() {
const remaining = Math.max(0, Math.ceil((_verdictDeadline - performance.now()) / 1000));
$awaitingTimer.textContent = `auto-skip in ${remaining}s`;
if (remaining === 0) {
// Time's up — auto-skip so the runner doesn't hang.
resolveVerdict({ verdict: "skip", reason: "timed out waiting for verdict" });
}
}
function hideAwaiting() {
$awaitingWrap.style.display = "none";
$awaitingLabel.innerHTML = "";
$awaitingTimer.textContent = "";
if (_verdictTimerId) {
clearInterval(_verdictTimerId);
_verdictTimerId = null;
}
// Tear down any registered action button so it doesn't leak into the next test.
$awaitingAction.style.display = "none";
$awaitingAction.textContent = "";
$awaitingAction.onclick = null;
}
function resolveVerdict(v) {
if (!_verdictResolve) return;
const r = _verdictResolve;
_verdictResolve = null;
hideAwaiting();
r(v);
}
$awaitingPass.addEventListener("click", () => resolveVerdict({ verdict: "pass" }));
$awaitingFail.addEventListener("click", () => {
const reason = prompt("Why did this fail? (optional)", "") || "marked failed by user";
resolveVerdict({ verdict: "fail", reason });
});
$awaitingSkip.addEventListener("click", () => resolveVerdict({ verdict: "skip", reason: "skipped by user" }));
/**
* Wait for the human to give a verdict via the awaiting bar.
* @param {string} promptHtml HTML shown in the awaiting bar (be careful — trusted source).
* @param {number} [deadlineSecs=120] Auto-skip after this many seconds of no input.
* @returns {Promise<{verdict: "pass"|"fail"|"skip", reason?: string}>}
*/
function awaitVerdict(promptHtml, deadlineSecs = 120) {
return new Promise((resolve) => {
_verdictResolve = resolve;
showAwaiting(promptHtml, deadlineSecs);
});
}
/**
* Register an in-flight action button on the awaiting bar.
* Use to expose things like "🛑 Abort download" while we wait for a verdict.
* The button auto-hides when the verdict resolves (or the next showAwaiting() is called).
* @param {string} label Button text.
* @param {() => void} onClick Click handler. Stays attached until the bar hides.
*/
function showAwaitingAction(label, onClick) {
$awaitingAction.textContent = label;
$awaitingAction.style.display = "";
$awaitingAction.onclick = (ev) => {
ev.preventDefault();
try {
onClick();
} catch (e) {
console.error("awaiting action handler threw:", e);
}
};
}
// ---------- GM_download wrappers ----------
/**
* Call GM_download with the callback-based API and turn it into a promise.
* Resolves on onload (or save_cancelled — TM's behavior), rejects on onerror/ontimeout.
* Captures all progress events.
*
* Returns: { promise, handle, progress[] }
* - promise: { kind: "load"|"save_cancelled", data } / rejection
* - handle.abort(): abort the download
* - progress: array of onprogress callback args, in order received
*/
function gmDownloadCb(details) {
const progress = [];
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
let saveCancelled = false;
const opts = {
...details,
onprogress(p) {
progress.push(p);
try {
details.onprogress && details.onprogress(p);
} catch {}
updateProgress(p.loaded ?? p.done ?? 0, p.total ?? p.totalSize ?? -1);
},
onload(data) {
try {
details.onload && details.onload(data);
} catch {}
resolve({ kind: saveCancelled ? "save_cancelled" : "load", data });
},
onerror(err) {
try {
details.onerror && details.onerror(err);
} catch {}
reject({ kind: "error", err });
},
ontimeout(err) {
try {
details.ontimeout && details.ontimeout(err);
} catch {}
reject({ kind: "timeout", err });
},
};
// GM_download returns { abort } in both TM and SC.
const handle = GM_download(opts);
return {
promise,
handle,
progress,
_markSaveCancelled() {
saveCancelled = true;
},
};
}
/**
* Call GM.download (promise form). Returns the Promise itself plus the abort handle.
* Also collects onprogress events.
*/
function gmDownloadPromise(details) {
const progress = [];
const opts = {
...details,
onprogress(p) {
progress.push(p);
try {
details.onprogress && details.onprogress(p);
} catch {}
updateProgress(p.loaded ?? p.done ?? 0, p.total ?? p.totalSize ?? -1);
},
};
const ret = GM.download(opts);
return { promise: ret, abort: ret && ret.abort, progress };
}
// ---------- The auto test suite ----------
// Each entry: { name, manual?: boolean, run: async () => void }
const tests = [];
function autoTest(name, run) {
tests.push({ name, manual: false, run });
}
function manualTest(name, run) {
tests.push({ name, manual: true, run });
}
// 1) sanity: APIs exist
autoTest("APIs exist (GM_download / GM.download)", async () => {
assertEq(typeof GM_download, "function", "GM_download must be a function");
assertTrue(typeof GM !== "undefined" && typeof GM.download === "function", "GM.download must exist");
});
// 2) string-form: GM_download(url, name) — passes through to the options form
autoTest("GM_download(url, name) — string form", async () => {
const name = nameFor("string-form", "txt");
const blobUrl = URL.createObjectURL(TEXT_BLOB);
try {
const result = await withTimeout(
new Promise((resolve, reject) => {
// String form has no callbacks, so we can only check that it does not throw
// synchronously and returns an object with abort(). The actual download is
// observed by the user.
let h;
try {
h = GM_download(blobUrl, name);
} catch (e) {
return reject(e);
}
assertTrue(h && typeof h.abort === "function", "handle.abort must be a function");
// Wait briefly to give the SW a chance to dispatch the download.
setTimeout(() => resolve({ handle: h }), 800);
}),
5000,
"string-form"
);
assertTrue(!!result, "completed");
} finally {
URL.revokeObjectURL(blobUrl);
}
});
// 3) options-form with onload
autoTest("GM_download({...}) — options form, blob: URL", async () => {
const name = nameFor("options-blob-url", "png");
const blobUrl = URL.createObjectURL(PNG_BLOB);
try {
const { promise } = gmDownloadCb({
url: blobUrl,
name,
conflictAction: "uniquify",
});
const r = await withTimeout(promise, 10000, "blob: URL download");
assertEq(r.kind, "load", "onload should fire");
} finally {
URL.revokeObjectURL(blobUrl);
}
});
// 4) Blob object as url — should be converted to data: URL or blob URL
autoTest("GM_download with Blob object as url", async () => {
const name = nameFor("blob-object", "png");
const { promise } = gmDownloadCb({
url: PNG_BLOB,
name,
});
const r = await withTimeout(promise, 10000, "Blob object download");
assertEq(r.kind, "load", "onload should fire");
});
// 5) File object as url — File extends Blob, should also work
autoTest("GM_download with File object as url", async () => {
const name = nameFor("file-object", "txt");
const { promise } = gmDownloadCb({
url: TEXT_FILE,
name,
});
const r = await withTimeout(promise, 10000, "File object download");
assertEq(r.kind, "load", "onload should fire");
});
// 6) data: URL
autoTest("GM_download with data: URL", async () => {
const name = nameFor("data-url", "txt");
const dataUrl = "data:text/plain;charset=utf-8,hello%20from%20data%20url";
const { promise } = gmDownloadCb({
url: dataUrl,
name,
});
const r = await withTimeout(promise, 10000, "data: URL download");
assertEq(r.kind, "load", "onload should fire");
});
// 7) GM.download promise form
autoTest("GM.download promise resolves on success", async () => {
const name = nameFor("promise-form", "txt");
const { promise } = gmDownloadPromise({
url: URL.createObjectURL(TEXT_BLOB),
name,
});
const r = await withTimeout(promise, 10000, "GM.download promise");
assertTrue(r && typeof r === "object", "should resolve to an object");
});
// 8) native mode — uses SW fetch xhr, multiple onprogress events expected
autoTest("downloadMode 'native' — xhr fetch, onprogress fires", async () => {
const name = nameFor("mode-native", "bin");
const t0 = performance.now();
const r = await withTimeout(
new Promise((resolve, reject) => {
const h = GM_download({
url: `${HB}/bytes/4096`,
name,
downloadMode: "native",
onprogress(p) {
/* captured in wrapper too, but native mode emits >=1 */
},
onload: resolve,
onerror: reject,
ontimeout: reject,
});
// Don't keep the handle around — but ensure abort exists.
if (!h || typeof h.abort !== "function") reject(new Error("handle.abort missing"));
}),
20000,
"native mode"
);
assertTrue(!!r, "onload received");
// Sanity bound: 4KB shouldn't take 20s on any sane net.
assertTrue(performance.now() - t0 < 20000, "completed in time");
});
// 9) browser mode — chrome.downloads only
autoTest("downloadMode 'browser' — direct chrome.downloads", async () => {
const name = nameFor("mode-browser", "bin");
const r = await withTimeout(
new Promise((resolve, reject) => {
GM_download({
url: `${HB}/bytes/2048`,
name,
downloadMode: "browser",
onload: resolve,
onerror: reject,
ontimeout: reject,
});
}),
20000,
"browser mode"
);
assertTrue(!!r, "onload received");
});
// 10) onprogress structure (native mode)
autoTest("onprogress event shape (native mode)", async () => {
const name = nameFor("progress-shape", "bin");
const progresses = [];
await withTimeout(
new Promise((resolve, reject) => {
GM_download({
url: `${HB}/bytes/1024`,
name,
downloadMode: "native",
onprogress(p) {
progresses.push(p);
},
onload: resolve,
onerror: reject,
});
}),
20000,
"progress shape"
);
assertTrue(progresses.length > 0, "got at least one progress event");
const last = progresses[progresses.length - 1];
assertTrue("loaded" in last, "progress has loaded");
assertTrue("total" in last, "progress has total");
assertTrue(last.mode === "native" || last.mode === "browser", `mode field present, got ${last.mode}`);
});
// 11) conflictAction "overwrite" — second download to the same name should replace
autoTest("conflictAction 'overwrite' — second write replaces", async () => {
// Note: we intentionally do NOT include RUN_TAG so the second run targets
// the same path. uniquify would otherwise produce filename(1), filename(2)...
const fixedName = getPrefix() + "overwrite-target.txt";
const a = await withTimeout(
new Promise((resolve, reject) => {
GM_download({
url: URL.createObjectURL(new Blob(["v1"])),
name: fixedName,
conflictAction: "overwrite",
onload: resolve,
onerror: reject,
});
}),
10000,
"overwrite #1"
);
assertTrue(!!a, "first write succeeded");
const b = await withTimeout(
new Promise((resolve, reject) => {
GM_download({
url: URL.createObjectURL(new Blob(["v2"])),
name: fixedName,
conflictAction: "overwrite",
onload: resolve,
onerror: reject,
});
}),
10000,
"overwrite #2"
);
assertTrue(!!b, "second write succeeded (overwrite)");
skip(`(visual check) ${fixedName} should now contain "v2"`);
});
// 12) conflictAction "uniquify" — second download gets " (1)" suffix
autoTest("conflictAction 'uniquify' — second write gets suffix", async () => {
const fixedName = getPrefix() + "uniquify-target.txt";
await withTimeout(
new Promise((resolve, reject) => {
GM_download({
url: URL.createObjectURL(new Blob(["v1"])),
name: fixedName,
conflictAction: "uniquify",
onload: resolve,
onerror: reject,
});
}),
10000,
"uniquify #1"
);
await withTimeout(
new Promise((resolve, reject) => {
GM_download({
url: URL.createObjectURL(new Blob(["v2"])),
name: fixedName,
conflictAction: "uniquify",
onload: resolve,
onerror: reject,
});
}),
10000,
"uniquify #2"
);
skip(`(visual check) you should see both uniquify-target.txt and uniquify-target (1).txt`);
});
// 13) headers honored in native mode — httpbingo /headers echoes request headers
autoTest("headers passed to backend xhr (native mode)", async () => {
// We can't easily inspect what hit the server because the response is
// streamed to disk. So instead: ask /headers, which RESPONDS with the headers
// we sent. Then read that file back via fetch from a blob-URL... no, files
// on disk are not addressable. Cheap alternative: just verify the download
// succeeded with custom headers attached and didn't error.
const name = nameFor("headers-passthrough", "json");
const r = await withTimeout(
new Promise((resolve, reject) => {
GM_download({
url: `${HB}/headers`,
name,
downloadMode: "native",
headers: { "X-Custom-Probe": "scriptcat-gmdl-test" },
onload: resolve,
onerror: reject,
});
}),
20000,
"headers passthrough"
);
assertTrue(!!r, "onload received");
skip(`(visual check) open ${name} — X-Custom-Probe should be echoed in the body`);
});
// 14) abort() immediately — should not produce a file
autoTest("abort() immediately — no onload, no onerror reached", async () => {
const name = nameFor("abort-immediate", "bin");
let onloadCalled = false,
onerrorCalled = false;
const h = GM_download({
url: `${HB}/bytes/65536`,
name,
downloadMode: "native",
onload() {
onloadCalled = true;
},
onerror() {
onerrorCalled = true;
},
});
h.abort();
// Give the system 1.5s to (not) call any callbacks.
await new Promise((r) => setTimeout(r, 1500));
assertEq(onloadCalled, false, "onload should not fire after immediate abort");
// Note: onerror may still fire in some impls — we accept either no-call or a
// generic error. The important contract is: no successful onload.
if (onerrorCalled) {
skip("onerror fired post-abort (implementation choice, not a failure)");
}
});
// 15) abort() after onload — should be a no-op, no exceptions
autoTest("abort() after onload — safe no-op", async () => {
const name = nameFor("abort-after-load", "txt");
let handle;
await withTimeout(
new Promise((resolve, reject) => {
handle = GM_download({
url: URL.createObjectURL(TEXT_BLOB),
name,
onload: resolve,
onerror: reject,
});
}),
10000,
"abort-after-load"
);
try {
handle.abort();
} catch (e) {
throw new Error("abort() after onload threw: " + e);
}
});
// 16) blocked host: missing @connect — should hit onerror (native mode)
autoTest("blocked host (missing @connect) — onerror", async () => {
const name = nameFor("blocked-host", "bin");
let onloadCalled = false;
let errSeen = null;
await new Promise((resolve) => {
GM_download({
url: "https://blocked-host-not-in-connect.example/",
name,
downloadMode: "native",
onload() {
onloadCalled = true;
resolve();
},
onerror(e) {
errSeen = e || true;
resolve();
},
});
// Safety timeout
setTimeout(resolve, 8000);
});
assertEq(onloadCalled, false, "onload must NOT fire");
assertTrue(!!errSeen, "onerror should fire");
});
// 17) bad URL string — onerror or thrown
autoTest("invalid URL — onerror (no crash)", async () => {
const name = nameFor("bad-url", "bin");
let onloadCalled = false,
errSeen = null,
threw = null;
try {