wasm-rquickjs-cli 0.5.1

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
import { Buffer } from "buffer";

async function dumpResponse(response) {
    console.log(`Response from ${response.url}: ${response.status} ${response.statusText} (ok=${response.ok})`);
    console.log(`Headers:`);
    for (const [name, value] of response.headers.entries()) {
        console.log(`  ${name}: ${value}`);
    }

    const data = await response.json();
    console.log(`Body: ${JSON.stringify(data)}`);
}

export async function postJsonAndGet(port) {
    console.log("fetch test 1");
    const response1 = await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "foo",
            body: "bar",
            userId: 1
        })
    });

    const response2 = await fetch(`http://localhost:${port}/todos/0`);

    await dumpResponse(response1);
    await dumpResponse(response2);
}

export async function postAndGetAsArrayBuffer(port) {
    console.log("fetch test 2");

    await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "foo",
            body: "bar",
            userId: 1
        })
    });

    const response = await fetch(`http://localhost:${port}/todos/0`);
    const data = await response.arrayBuffer();
    console.log(`Response body as ArrayBuffer:`, data);
}

export async function streamingResponseBody(port) {
    console.log("fetch test 3");
    const response = await fetch(`http://localhost:${port}/todos-stream`);
    for await (const chunk of response.body) {
        // Do something with each "chunk"
        console.log(`Received chunk: ${chunk}`);
    }
}

export async function pipeResponseBodyToRequest(port) {
    console.log("fetch test 4");
    const response1 = await fetch(`http://localhost:${port}/todos-stream`);
    const response2 = await fetch(`http://localhost:${port}/echo`, {
        method: "POST",
        body: response1.body
    });

    await dumpResponse(response2);
}

export async function pipeBufferedResponseBodyToRequest(port) {
    console.log("fetch test 4 (buffered)");
    const response1 = await fetch(`http://localhost:${port}/todos-stream`);

    let body1 = await response1.bytes();

    const response2 = await fetch(`http://localhost:${port}/echo`, {
        method: "POST",
        body: body1
    });

    await dumpResponse(response2);
}

export async function concurrentPostAndGet(port) {
    async function test(i) {
        let response1 = await fetch(`http://localhost:${port}/todos`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                title: `title_${i}`,
                body: `body_${i}`,
                userId: 1
            })
        });
        let response1Json = await response1.json()

        let response2 = await fetch(`http://localhost:${port}/todos/${response1Json.id}`);
        let response2Json = await response2.json();
        console.log(response2.status, JSON.stringify(response2Json));
    }

    let promises = [];
    for (let i = 0; i < 5; i++) {
        promises.push(test(i));
    }

    await Promise.all(promises);
}

class SlowRequestBodySource {
    #interval

    constructor(body) {
        this.body = body;
    }

    start(controller) {
        console.log(`Starting request body stream`);
        this.#interval = setInterval(() => {
            const next = this.body.slice(0, 2);
            this.body = this.body.slice(2);
            if (next.length === 0) {
                console.log(`Closing request body stream`);
                controller.close();
                clearInterval(this.#interval);
            } else {
                console.log(`Enqueuing chunk: ${next}`);
                controller.enqueue(next);
            }
        }, 100);
    }

    cancel() {
        console.log(`Cancelling request body stream`);
        clearInterval(this.#interval);
    }
}

export async function postWithSlowStreamingBody(port) {
    let body = new Uint8Array([123, 34, 116, 105, 116, 108, 101, 34, 58, 34, 102, 111, 111, 34, 44, 34, 98, 111, 100, 121, 34, 58, 34, 98, 97, 114, 34, 44, 34, 117, 115, 101, 114, 73, 100, 34, 58, 49, 125]);
    const stream = new ReadableStream(new SlowRequestBodySource(body));
    const response = await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: stream
    });
    await dumpResponse(response);
}

export async function blobOperations() {
    const blob = new Blob(['hello, world'])

    const text = await blob.text();
    console.log(`Blob text: ${text}`);

    const array = await blob.arrayBuffer();
    console.log(`Blob array buffer length: ${array.byteLength}`);
    console.log(`Blob array buffer: ${array}`);

    for await (let chunk of blob.stream()) {
        console.log(`Blob stream chunk: ${chunk}`);
    }

    let body = new Uint8Array([123, 34, 116, 105, 116, 108, 101, 34, 58, 34, 102, 111, 111, 34, 44, 34, 98, 111, 100, 121, 34, 58, 34, 98, 97, 114, 34, 44, 34, 117, 115, 101, 114, 73, 100, 34, 58, 49, 125]);
    const stream = new ReadableStream(new SlowRequestBodySource(body));
    const formData = new FormData()
    formData.append('f1', new File(['abc'], 'hello-world.txt'))
    formData.append('f2', {
        size: 123,
        type: '',
        name: 'cat-video.mp4',
        stream() {
            return stream
        },
        [Symbol.toStringTag]: 'File'
    });

    console.log(`FormData keys: ${JSON.stringify([...formData.keys()])}`);
    for (const pair of formData.entries()) {
        console.log(pair[0], JSON.stringify(pair[1]));
    }

    console.log("done");
}

export async function postWithBlobBody(port) {
    let body = new Uint8Array([123, 34, 116, 105, 116, 108, 101, 34, 58, 34, 102, 111, 111, 34, 44, 34, 98, 111, 100, 121, 34, 58, 34, 98, 97, 114, 34, 44, 34, 117, 115, 101, 114, 73, 100, 34, 58, 49, 125]);
    const blob = new Blob([body], {type: "application/json"});
    const response = await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        body: blob
    });
    await dumpResponse(response);
}

export async function postFormDataWithFiles(port) {
    let body = new Uint8Array([123, 34, 116, 105, 116, 108, 101, 34, 58, 34, 102, 111, 111, 34, 44, 34, 98, 111, 100, 121, 34, 58, 34, 98, 97, 114, 34, 44, 34, 117, 115, 101, 114, 73, 100, 34, 58, 49, 125]);
    const stream = new ReadableStream(new SlowRequestBodySource(body));
    const formData = new FormData()
    formData.append('f1', new File(['abc'], 'hello-world.txt'))
    formData.append('f2', {
        size: 123,
        type: '',
        name: 'cat-video.mp4',
        stream() {
            return stream
        },
        [Symbol.toStringTag]: 'File'
    });
    const response = await fetch(`http://localhost:${port}/echo-form`, {method: 'POST', body: formData});
    await dumpResponse(response);
}


export async function fetchWithRequestObject(port) {
    console.log("fetch test 10");
    const request1 = new Request(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "foo",
            body: "bar",
            userId: 1
        })
    });
    const response1 = await fetch(request1);

    const request2 = new Request(`http://localhost:${port}/todos/0`);
    const response2 = await fetch(request2);

    await dumpResponse(response1);
    await dumpResponse(response2);
}

export async function postWithDataViewBody(port) {
    console.log("fetch test 11 (DataView)");

    // Create a DataView from an ArrayBuffer containing JSON data
    const buffer = new ArrayBuffer(39);
    const view = new DataView(buffer);
    const jsonData = JSON.stringify({title: "foo", body: "bar", userId: 1});

    // Fill the DataView with the JSON string bytes
    for (let i = 0; i < jsonData.length; i++) {
        view.setUint8(i, jsonData.charCodeAt(i));
    }

    // Send the DataView as a request body
    const response = await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: view
    });

    await dumpResponse(response);
}

export async function postWithUrlSearchParams(port) {
    console.log("fetch test 12 (URLSearchParams)");

    // Create URLSearchParams with form data
    const params = new URLSearchParams();
    params.append('title', 'foo');
    params.append('body', 'bar');
    params.append('userId', '1');

    console.log(`URLSearchParams toString: ${params.toString()}`);

    // Send URLSearchParams as request body
    const response = await fetch(`http://localhost:${port}/form-echo`, {
        method: "POST",
        body: params
    });

    await dumpResponse(response);
}

export async function requestWithUrlSearchParams(port) {
    console.log("fetch test 13 (URLSearchParams in Request)");

    // Create URLSearchParams
    const params = new URLSearchParams();
    params.append('name', 'John');
    params.append('email', 'john@example.com');

    // Create a Request with URLSearchParams body
    const request = new Request(`http://localhost:${port}/form-echo`, {
        method: "POST",
        body: params
    });

    console.log(`Request body used: ${request.bodyUsed}`);

    // Use the request in fetch
    const response = await fetch(request);

    await dumpResponse(response);
}

export async function fetchWithReferrer(port) {
    console.log("fetch test 14 (referrer with fetch)");

    // Test 1: default referrer with default policy (about:client should not send header)
    console.log("Test 1: default referrer");
    const response1 = await fetch(`http://localhost:${port}/echo-referer`, {
        method: "POST"
    });
    const data1 = await response1.json();
    console.log(`Test 1 referer sent: '${data1.referer}'`);

    // Test 2: custom referrer with default policy (strict-origin-when-cross-origin)
    // Since this is same-origin, it should send the full referrer URL
    console.log("Test 2: custom referrer");
    const response2 = await fetch(`http://localhost:${port}/echo-referer`, {
        method: "POST",
        referrer: `http://localhost:${port}/source`
    });
    const data2 = await response2.json();
    console.log(`Test 2 referer sent: '${data2.referer}'`);

    // Test 3: empty referrer (explicitly omit header)
    console.log("Test 3: empty referrer");
    const response3 = await fetch(`http://localhost:${port}/echo-referer`, {
        method: "POST",
        referrer: ""
    });
    const data3 = await response3.json();
    console.log(`Test 3 referer sent: '${data3.referer}'`);
}

export async function fetchWithReferrerPolicy(port) {
    console.log("fetch test 15 (referrerPolicy with fetch)");

    const baseUrl = `http://localhost:${port}`;
    const sourceUrl = `${baseUrl}/source`;

    // Test 1: no-referrer policy (should never send Referer header)
    console.log("Test 1: no-referrer policy");
    const response1 = await fetch(`${baseUrl}/echo-referer`, {
        method: "POST",
        referrer: sourceUrl,
        referrerPolicy: "no-referrer"
    });
    const data1 = await response1.json();
    console.log(`Test 1 referer sent: '${data1.referer}'`);

    // Test 2: origin policy (should send origin only)
    console.log("Test 2: origin policy");
    const response2 = await fetch(`${baseUrl}/echo-referer`, {
        method: "POST",
        referrer: sourceUrl,
        referrerPolicy: "origin"
    });
    const data2 = await response2.json();
    console.log(`Test 2 referer sent: '${data2.referer}'`);

    // Test 3: origin-when-cross-origin (same-origin, so sends full)
    console.log("Test 3: origin-when-cross-origin policy (same-origin)");
    const response3 = await fetch(`${baseUrl}/echo-referer`, {
        method: "POST",
        referrer: sourceUrl,
        referrerPolicy: "origin-when-cross-origin"
    });
    const data3 = await response3.json();
    console.log(`Test 3 referer sent: '${data3.referer}'`);

    // Test 4: strict-origin-when-cross-origin (default, same-origin sends full)
    console.log("Test 4: strict-origin-when-cross-origin policy (default)");
    const response4 = await fetch(`${baseUrl}/echo-referer`, {
        method: "POST",
        referrer: sourceUrl,
        referrerPolicy: "strict-origin-when-cross-origin"
    });
    const data4 = await response4.json();
    console.log(`Test 4 referer sent: '${data4.referer}'`);
}

export async function fetchWithCredentials(port) {
    console.log("fetch test 16 (credentials option with fetch)");

    const baseUrl = `http://localhost:${port}`;

    // Test 1: credentials "omit" (should not send any credentials headers and should filter Set-Cookie)
    console.log("Test 1: credentials 'omit'");
    const request1 = new Request(`${baseUrl}/echo-credentials`, {
        method: "POST",
        credentials: "omit",
        headers: {
            "Authorization": "Bearer test-token",
            "Cookie": "session=test-session-id"
        }
    });
    console.log(`Request 1 credentials: '${request1.credentials}'`);
    const response1 = await fetch(request1);
    const data1 = await response1.json();
    console.log(`Test 1 authorization: '${data1.authorization}', cookie: '${data1.cookie}'`);
    const setCookie1 = response1.headers.get('set-cookie');
    console.log(`Test 1 set-cookie: '${setCookie1 || ''}'`);

    // Test 2: credentials "same-origin" (default, should send credentials for same-origin and preserve Set-Cookie)
    console.log("Test 2: credentials 'same-origin'");
    const request2 = new Request(`${baseUrl}/echo-credentials`, {
        method: "POST",
        credentials: "same-origin",
        headers: {
            "Authorization": "Bearer test-token",
            "Cookie": "session=test-session-id"
        }
    });
    console.log(`Request 2 credentials: '${request2.credentials}'`);
    const response2 = await fetch(request2);
    const data2 = await response2.json();
    console.log(`Test 2 authorization: '${data2.authorization}', cookie: '${data2.cookie}'`);
    const setCookie2 = response2.headers.get('set-cookie');
    console.log(`Test 2 set-cookie: '${setCookie2 || ''}'`);

    // Test 3: credentials "include" (should send credentials for all requests and preserve Set-Cookie)
    console.log("Test 3: credentials 'include'");
    const request3 = new Request(`${baseUrl}/echo-credentials`, {
        method: "POST",
        credentials: "include",
        headers: {
            "Authorization": "Bearer test-token",
            "Cookie": "session=test-session-id"
        }
    });
    console.log(`Request 3 credentials: '${request3.credentials}'`);
    const response3 = await fetch(request3);
    const data3 = await response3.json();
    console.log(`Test 3 authorization: '${data3.authorization}', cookie: '${data3.cookie}'`);
    const setCookie3 = response3.headers.get('set-cookie');
    console.log(`Test 3 set-cookie: '${setCookie3 || ''}'`);
}

export async function redirectFollow(port) {
    console.log("fetch test 17 (redirect: follow)");
    const response = await fetch(`http://localhost:${port}/redirect-to?url=/todos&status=302`);
    console.log(`Status: ${response.status}`);
    console.log(`Redirected: ${response.redirected}`);
    if (response.status === 200 && response.redirected) {
        console.log("Redirect followed successfully");
    } else {
        console.log("Redirect failed");
    }
    await dumpResponse(response);
}

export async function redirectManual(port) {
    console.log("fetch test 18 (redirect: manual)");
    const response = await fetch(`http://localhost:${port}/redirect-to?url=/todos&status=302`, {
        redirect: 'manual'
    });
    console.log(`Status: ${response.status}`);
    console.log(`Redirected: ${response.redirected}`);
    if (response.status === 0 && !response.redirected) {
        console.log("Manual redirect handled correctly");
    } else {
        console.log("Manual redirect failed");
    }
}

export async function redirectError(port) {
    console.log("fetch test 19 (redirect: error)");
    try {
        await fetch(`http://localhost:${port}/redirect-to?url=/todos&status=302`, {
            redirect: 'error'
        });
        console.log("Error: Should have thrown exception");
    } catch (e) {
        console.log("Caught expected error for redirect: error");
    }
}

export async function redirectLoop(port) {
    console.log("fetch test 20 (redirect loop)");
    try {
        await fetch(`http://localhost:${port}/redirect-loop`);
        console.log("Error: Should have thrown exception for loop");
    } catch (e) {
        console.log("Caught expected error for loop");
    }
}

export async function postWithRedirect(port) {
    console.log("fetch test 21 (redirect with body)");
    const blob = new Blob(["hello world"], {type: "text/plain"});

    // Redirect using 307 to preserve POST and body
    const target = `/echo`;
    const response = await fetch(`http://localhost:${port}/redirect-to?url=${target}&status=307`, {
        method: 'POST',
        body: blob,
        redirect: 'follow'
    });

    console.log(`Status: ${response.status}`);
    console.log(`Redirected: ${response.redirected}`);

    const text = await response.text();
    console.log(`Body: ${text}`);
}

export async function responseCloneBasic(port) {
    console.log("fetch test 22 (response clone - basic)");

    // First POST to create a todo
    await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "clone test",
            body: "test body",
            userId: 1
        })
    });

    const response = await fetch(`http://localhost:${port}/todos/0`);

    console.log(`Original status: ${response.status}`);
    console.log(`Original ok: ${response.ok}`);

    try {
        const cloned = response.clone();
        console.log(`Cloned status: ${cloned.status}`);
        console.log(`Cloned ok: ${cloned.ok}`);

        // Read body from cloned response
        const clonedData = await cloned.json();
        console.log(`Cloned body id: ${clonedData.id}`);

        // Original response body can still be read
        const originalData = await response.json();
        console.log(`Original body id: ${originalData.id}`);

        if (originalData.id === clonedData.id &&
            cloned.status === response.status &&
            cloned.ok === response.ok
        ) {
            console.log("Basic clone test passed");
        }
    } catch (e) {
        console.log("Clone error:", e.message);
    }
}

export async function responseCloneStreamingBody(port) {
    console.log("fetch test 23 (response clone - streaming body)");
    const response = await fetch(`http://localhost:${port}/todos-stream`);

    console.log(`Original status: ${response.status}`);

    const lockedReader = response.body.getReader();
    const cloneRejectedWhileLocked = cloneThrows(response);
    lockedReader.releaseLock();
    const cloned = response.clone();
    const buffered = response.clone();

    console.log(`Cloned status: ${cloned.status}`);

    const consume = async (body) => {
        const data = [];
        for await (const chunk of body) {
            for (const byte of chunk) {
                data.push(byte);
            }
        }
        return new Uint8Array(data);
    };

    // Clones must tee the native stream: both readers are deliberately active together.
    const [clonedBytes, originalBytes, bufferedBytes] = await Promise.all([
        consume(cloned.body),
        consume(response.body),
        buffered.arrayBuffer().then(buffer => new Uint8Array(buffer)),
    ]);

    console.log(`Cloned body: ${clonedBytes}`);
    console.log(`Original body: ${originalBytes}`);

    if (cloneRejectedWhileLocked
        && Buffer.compare(clonedBytes, originalBytes) === 0
        && Buffer.compare(originalBytes, bufferedBytes) === 0) {
        console.log("Streaming clone test passed");
    }
}

export async function responseCloneReuseBodies(port) {
    console.log("fetch test 24 (response clone - reuse bodies)");

    // First POST to create a todo
    await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "reuse bodies test",
            body: "test body",
            userId: 1
        })
    });

    const response = await fetch(`http://localhost:${port}/todos/0`);

    try {
        const clone1 = response.clone();
        const clone2 = response.clone();

        // Start all consumers before awaiting any one of them. The shared native reader must
        // wake the other clone consumers as buffered chunks become available.
        const [originalBody, clone1Body, clone2Body] = await Promise.all([
            response.json(),
            clone1.json(),
            clone2.json(),
        ]);

        console.log(`Original id: ${originalBody.id}`);
        console.log(`Clone1 id: ${clone1Body.id}`);
        console.log(`Clone2 id: ${clone2Body.id}`);

        if (originalBody.id === clone1Body.id && clone1Body.id === clone2Body.id) {
            console.log("All clones have matching bodies");
        }
    } catch (e) {
        console.log("Clone reuse bodies error:", e.message);
    }
}

export async function responseCloneHeaders(port) {
    console.log("fetch test 25 (response clone - headers preservation)");

    // First POST to create a todo
    await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "headers test",
            body: "test body",
            userId: 1
        })
    });

    const response = await fetch(`http://localhost:${port}/todos/0`);

    try {
        const originalContentType = response.headers.get("content-type");
        const cloned = response.clone();
        const clonedContentType = cloned.headers.get("content-type");

        console.log(`Original content-type: ${originalContentType}`);
        console.log(`Cloned content-type: ${clonedContentType}`);

        // Consume both
        await response.text();
        await cloned.text();

        if (originalContentType === clonedContentType) {
            console.log("Headers preserved in clone");
        }
    } catch (e) {
        console.log("Clone headers error:", e.message);
    }
}

export async function responseFormData(port) {
    console.log("response-form-data test");

    const response = await fetch(`http://localhost:${port}/form-response`);
    console.log(`Response status: ${response.status}`);
    console.log(`Response Content-Type: ${response.headers.get('Content-Type')}`);

    // Parse the form data from the response
    const responseFormData = await response.formData();
    console.log(`Parsed FormData entries:`);
    for (const [name, value] of responseFormData.entries()) {
        if (value instanceof File) {
            const content = await value.text();
            console.log(`  ${name}: File(${value.name}, size=${content.length}, type=${value.type})`);
        } else {
            console.log(`  ${name}: ${value}`);
        }
    }

    console.log("response-form-data test completed");
}

export async function headersIterator(port) {
    console.log("fetch test 26 (Headers iterator)");

    const response = await fetch(`http://localhost:${port}/todos/0`);
    
    // Test Symbol.iterator on response headers
    console.log("Testing Headers Symbol.iterator:");
    let iteratorCount = 0;
    for (const [name, value] of response.headers) {
        console.log(`  Header: ${name} = ${value}`);
        iteratorCount++;
    }
    console.log(`Total headers via Symbol.iterator: ${iteratorCount}`);

    // Verify it matches entries()
    let entriesCount = 0;
    for (const [name, value] of response.headers.entries()) {
        entriesCount++;
    }
    console.log(`Total headers via entries(): ${entriesCount}`);
    
    if (iteratorCount === entriesCount) {
        console.log("Symbol.iterator test passed");
    } else {
        console.log("Symbol.iterator test FAILED");
    }
}

export async function headersConstructorIterator(port) {
    console.log("fetch test 27 (Headers constructor iterator)");

    // Create Headers from object
    const headers1 = new Headers({
        'x-custom-1': 'value1',
        'x-custom-2': 'value2',
        'x-custom-3': 'value3'
    });

    // Test iteration via Symbol.iterator
    console.log("Testing Headers constructor with for-of loop:");
    let count1 = 0;
    for (const [name, value] of headers1) {
        console.log(`  Header: ${name} = ${value}`);
        count1++;
    }
    console.log(`Total headers from for-of loop: ${count1}`);

    // Test with entries()
    let count2 = 0;
    for (const [name, value] of headers1.entries()) {
        count2++;
    }
    console.log(`Total headers from entries(): ${count2}`);

    if (count1 === count2 && count1 === 3) {
        console.log("Headers constructor iterator test passed");
    } else {
        console.log("Headers constructor iterator test FAILED");
    }
}

export async function fetchWithUrlObject(port) {
    console.log("fetch test 28 (URL object parameter)");
    
    // First POST to create a todo
    await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "url_object_test",
            body: "test body",
            userId: 1
        })
    });
    
    const url = new URL(`http://localhost:${port}/todos/0`);
    const response = await fetch(url);

    console.log(`URL object test: status=${response.status}`);
    assert_eq(response.status, 200);
    
    const data = await response.json();
    console.log(`URL object fetch successful: ${JSON.stringify(data)}`);
}

export async function postWithUrlObject(port) {
    console.log("fetch test 29 (POST with URL object)");
    const url = new URL(`http://localhost:${port}/todos`);
    const response = await fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "url_object_test",
            body: "testing URL object parameter",
            userId: 1
        })
    });

    console.log(`POST with URL object: status=${response.status}`);
    assert_eq(response.status, 201);
    
    const data = await response.json();
    console.log(`POST with URL object successful: title=${data.title}`);
}

export async function fetchUrlObjectWithQueryParams(port) {
    console.log("fetch test 30 (URL object with query parameters)");
    const url = new URL(`http://localhost:${port}/todos`);
    url.searchParams.append('_limit', '1');
    url.searchParams.append('_sort', 'id');
    
    const response = await fetch(url);
    console.log(`URL with query params: status=${response.status}`);
    assert_eq(response.status, 200);
    
    const data = await response.json();
    console.log(`Fetched ${Array.isArray(data) ? data.length : 1} item(s) with URL query params`);
}

export async function requestBodyGetReaderAfterAccess(port) {
    console.log("fetch test 31 (Request body getReader after body access)");
    
    // Create a request with a body
    const request = new Request(`http://localhost:${port}/echo`, {
        method: "POST",
        body: "test body content"
    });
    
    // First, access request.body and store it (but don't consume it)
    const storedBody = request.body;
    console.log(`Stored body reference: ${storedBody !== null ? 'exists' : 'null'}`);
    
    // Now try to use getReader on the original request's body
    // This should work and NOT give a "body already consumed" error
    const reader = request.body.getReader();
    console.log(`Got reader from request.body`);
    
    // Read the body content
    let chunks = [];
    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        chunks.push(value);
    }
    
    // Combine chunks and decode
    const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
    const combined = new Uint8Array(totalLength);
    let offset = 0;
    for (const chunk of chunks) {
        combined.set(chunk, offset);
        offset += chunk.length;
    }
    
    const bodyText = new TextDecoder().decode(combined);
    console.log(`Body content: ${bodyText}`);
    
    assert_eq(bodyText, "test body content");
    console.log("Request body getReader after access test passed");
}

export async function responseBodyGetReaderAfterAccess(port) {
    console.log("fetch test 32 (Response body getReader after body access - TanStack AI pattern)");
    
    // First POST to create a todo so we have something to GET
    await fetch(`http://localhost:${port}/todos`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: "test",
            body: "test body",
            userId: 1
        })
    });
    
    // Fetch a response (simulating what TanStack AI does)
    const response = await fetch(`http://localhost:${port}/todos/0`);
    
    // This is the TanStack AI pattern that fails:
    // 1. First, access response.body and store it (but don't consume it)
    const storedBody = response.body;
    console.log(`Stored body reference: ${storedBody !== null ? 'exists' : 'null'}`);
    
    // 2. Now try to use getReader on the original response's body
    // This should work and NOT give a "body already consumed" error
    // TanStack AI does: const reader = response.body?.getReader()
    const reader = response.body.getReader();
    console.log(`Got reader from response.body`);
    
    // 3. Read the body content (like TanStack AI's readStreamLines)
    let chunks = [];
    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        chunks.push(value);
    }
    
    // Combine chunks and decode
    const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
    const combined = new Uint8Array(totalLength);
    let offset = 0;
    for (const chunk of chunks) {
        combined.set(chunk, offset);
        offset += chunk.length;
    }
    
    const bodyText = new TextDecoder().decode(combined);
    console.log(`Body content: ${bodyText}`);
    
    // Verify we got valid JSON
    const parsed = JSON.parse(bodyText);
    console.log(`Parsed id: ${parsed.id}`);
    
    console.log("Response body getReader after access test passed");
}

function assert_eq(a, b) {
    if (a !== b) {
        throw new Error(`Assertion failed: ${a} !== ${b}`);
    }
}

export async function redirectWithFailingStreamBody(port) {
    console.log("fetch test 33 (redirect with failing stream body)");

    // Cover both orderings: an immediate source failure and one that occurs
    // after the server has had time to return the redirect.
    for (const delay of [0, 100]) {
        const stream = new ReadableStream({
            async pull() {
                if (delay > 0) {
                    await new Promise((resolve) => setTimeout(resolve, delay));
                }
                throw new Error(`source body failure ${delay}`);
            }
        });

        let caught = null;
        try {
            await fetch(`http://localhost:${port}/redirect-to?url=/todos&status=302`, {
                method: 'POST',
                body: stream,
                redirect: 'follow'
            });
        } catch (e) {
            caught = e;
        }

        if (caught === null) {
            throw new Error(`Expected delayed=${delay} stream body source error to propagate`);
        }
        if (!String(caught.message).includes(`source body failure ${delay}`)) {
            throw new Error(`Unexpected delayed=${delay} stream body error: ${caught.message}`);
        }
    }
    console.log("Stream body source errors surfaced across redirect orderings: PASSED");
}

export async function redirectWithInfiniteStreamBody(port) {
    console.log("fetch test 34 (redirect with infinite stream body)");

    // An infinite body that keeps producing chunks. Without prompt redirect
    // handling this fetch would never resolve.
    let interval = null;
    const stream = new ReadableStream({
        start(controller) {
            interval = setInterval(() => {
                try {
                    controller.enqueue(new Uint8Array([1, 2, 3, 4]));
                } catch (_) { /* ignore */ }
            }, 50);
        },
        cancel() {
            if (interval !== null) {
                clearInterval(interval);
                interval = null;
            }
            console.log("Infinite stream cancel() invoked");
        }
    });

    const start = Date.now();
    const response = await fetch(`http://localhost:${port}/redirect-to?url=/todos&status=302`, {
        method: 'POST',
        body: stream,
        redirect: 'follow'
    });
    const duration = Date.now() - start;

    console.log(`Status: ${response.status}`);
    console.log(`Redirected: ${response.redirected}`);
    console.log(`Resolved in approximately ${duration}ms`);

    // Stop the timer if cancel didn't get called
    if (interval !== null) {
        clearInterval(interval);
        interval = null;
    }

    // The exact threshold doesn't matter - we just want to be sure we did
    // NOT block waiting for the infinite upload to complete.
    if (duration < 5000) {
        console.log("Redirect handled promptly with infinite upload: PASSED");
    } else {
        console.log(`Redirect with infinite body was too slow: FAILED (${duration}ms)`);
    }
}

export async function fetchFunctionShape() {
    console.log("fetch test 35 (fetch function shape - Node compat)");

    // Mirrors Node's vendored test-fetch.mjs invariants: fetch must be a
    // plain (non-async) function whose prototype is Function.prototype.
    // Node deliberately exposes `fetch` as a plain function (not a method
    // shorthand) so `new fetch(url)` does NOT throw — it simply returns
    // the Promise produced by fetch(url). We match that behavior.
    const asyncFunction = (async function () {}).constructor;
    const isAsync = fetch instanceof asyncFunction;
    const hasFunctionProto = Reflect.getPrototypeOf(fetch) === Reflect.getPrototypeOf(function () {});
    const notAsyncProto = Reflect.getPrototypeOf(fetch) !== Reflect.getPrototypeOf(async function () {});

    console.log(`fetch instanceof AsyncFunction: ${isAsync}`);
    console.log(`fetch has Function.prototype: ${hasFunctionProto}`);
    console.log(`fetch prototype !== AsyncFunction prototype: ${notAsyncProto}`);
    console.log(`Request standard method normalized: ${new Request('data:text/plain,', { method: 'post' }).method === 'POST'}`);
    console.log(`Request custom method preserved: ${new Request('data:text/plain,', { method: 'foo' }).method === 'foo'}`);

    // Verify `new fetch(...)` matches Node behavior: returns a Promise without throwing.
    let newResult = null;
    let newThrew = false;
    try {
        newResult = new fetch("data:text/plain,hello");
    } catch (e) {
        newThrew = true;
        console.log(`Unexpected throw from new fetch: ${e.constructor.name}: ${e.message}`);
    }
    const newReturnedPromise = newResult instanceof Promise;
    console.log(`new fetch threw: ${newThrew}`);
    console.log(`new fetch returned Promise: ${newReturnedPromise}`);

    // Catch the rejection so it doesn't surface as unhandled.
    if (newResult && typeof newResult.catch === 'function') {
        newResult.catch(() => {});
    }

    if (!isAsync && hasFunctionProto && notAsyncProto && !newThrew && newReturnedPromise) {
        console.log("fetch function shape matches Node: PASSED");
    } else {
        console.log("fetch function shape: FAILED");
    }
}

export async function abortReleasesRequest(port) {
    const controller = new AbortController();
    const reason = 'cancelled by test';
    const request = fetch(`http://localhost:${port}/slow-response`, {
        signal: controller.signal,
    });

    await fetch(`http://localhost:${port}/abort-ready`);
    controller.abort(reason);
    try {
        await request;
        return false;
    } catch (error) {
        return error === reason;
    }
}

export async function abortReleasesUpload(port) {
    const controller = new AbortController();
    const reason = 'cancelled upload';
    let cancelled = false;
    const body = new ReadableStream({
        pull() {
            return new Promise(() => {});
        },
        cancel() {
            cancelled = true;
        },
    });
    const request = fetch(`http://localhost:${port}/slow-response`, {
        method: 'POST',
        body,
        signal: controller.signal,
    });
    await fetch(`http://localhost:${port}/abort-ready`);
    controller.abort(reason);
    try {
        await request;
        return false;
    } catch (error) {
        return error === reason && cancelled;
    }
}

export async function abortAfterRedirect(port) {
    const controller = new AbortController();
    const reason = 'cancelled redirected request';
    const request = fetch(`http://localhost:${port}/redirect-to-slow`, {
        signal: controller.signal,
    });
    await fetch(`http://localhost:${port}/abort-ready`);
    controller.abort(reason);
    try {
        await request;
        return false;
    } catch (error) {
        return error === reason;
    }
}

export async function abortResponseBody(port) {
    const textController = new AbortController();
    const textResponse = await fetch(`http://localhost:${port}/todos/0`, {
        signal: textController.signal,
    });
    const textReason = new Error('body abort reason');
    textController.abort(textReason);
    let textError;
    try {
        await textResponse.text();
    } catch (error) {
        textError = error;
    }
    if (textError !== textReason) {
        return false;
    }

    const streamController = new AbortController();
    const streamResponse = await fetch(`http://localhost:${port}/todos/0`, {
        signal: streamController.signal,
    });
    const streamReason = new Error('stream abort reason');
    streamController.abort(streamReason);
    let streamError;
    try {
        await streamResponse.body.getReader().read();
    } catch (error) {
        streamError = error;
    }
    return streamError === streamReason;
}

function isAbortError(error) {
    return error instanceof DOMException && error.name === 'AbortError';
}

let retainedResponseBodyController;

async function finishPendingResponseBodyCase(result) {
    // Keep the invocation alive long enough for the host fixture to observe that the body was
    // released by abort/GC, rather than by component teardown after this export returns.
    await new Promise(resolve => setTimeout(resolve, 250));
    return result;
}

export async function abortPendingResponseBody(port, testCase) {
    const url = `http://localhost:${port}/pending-response-body`;

    if (testCase === 0) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        controller.abort();
        try {
            await response.text();
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(
                isAbortError(error) && response.bodyUsed && cloneThrows(response),
            );
        }
    }

    if (testCase === 1) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        const reason = new Error('custom response body abort reason');
        const read = response.text();
        const disturbedImmediately = response.bodyUsed && cloneThrows(response);
        controller.abort(reason);
        try {
            await read;
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(
                disturbedImmediately && response.bodyUsed && error === reason,
            );
        }
    }

    if (testCase === 2) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        const reader = response.body.getReader();
        const first = await reader.read();
        const pendingRead = reader.read();
        controller.abort();
        try {
            await pendingRead;
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(first.done === false
                && new TextDecoder().decode(first.value) === 'first chunk'
                && response.bodyUsed
                && isAbortError(error));
        }
    }

    if (testCase === 3) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        const clone = response.clone();
        const read = clone.text();
        controller.abort();
        try {
            await read;
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(
                clone.bodyUsed && cloneThrows(clone) && isAbortError(error),
            );
        }
    }

    if (testCase === 4) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        const read = response.arrayBuffer();
        const disturbedImmediately = response.bodyUsed && cloneThrows(response);
        controller.abort();
        try {
            await read;
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(
                disturbedImmediately && response.bodyUsed && isAbortError(error),
            );
        }
    }

    if (testCase === 5) {
        const controller = new AbortController();
        retainedResponseBodyController = controller;
        if (retainedResponseBodyController !== controller) return false;
        let response = await fetch(url, {signal: controller.signal});
        response = null;
        gc();
        await Promise.resolve();
        gc();
        return finishPendingResponseBodyCase(true);
    }

    if (testCase === 6) {
        const response = await fetch(`http://localhost:${port}/truncated-response-body`);
        const resolvedAtHead = response.status === 200 && !response.bodyUsed;
        try {
            await response.text();
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(
                resolvedAtHead && response.bodyUsed && cloneThrows(response) && error instanceof Error,
            );
        }
    }

    if (testCase === 7) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        controller.abort(null);
        try {
            await response.text();
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(
                isAbortError(error) && response.bodyUsed && cloneThrows(response),
            );
        }
    }

    if (testCase === 8) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        const read = response.arrayBuffer();
        const disturbedImmediately = response.bodyUsed && cloneThrows(response);
        controller.abort(null);
        try {
            await read;
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(
                disturbedImmediately && response.bodyUsed && isAbortError(error),
            );
        }
    }

    if (testCase === 9) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        const clone = response.clone();
        const reader = response.body.getReader();
        const first = await reader.read();
        const pendingRead = reader.read();
        const pendingClone = clone.text();
        controller.abort(null);
        const [readerResult, cloneResult] = await Promise.allSettled([
            pendingRead,
            pendingClone,
        ]);
        return finishPendingResponseBodyCase(
            first.done === false
            && new TextDecoder().decode(first.value) === 'first chunk'
            && readerResult.status === 'rejected'
            && isAbortError(readerResult.reason)
            && cloneResult.status === 'rejected'
            && isAbortError(cloneResult.reason),
        );
    }

    if (testCase === 10) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        const reader = response.body.getReader();
        const first = await reader.read();
        const reason = 'idle reader abort';
        controller.abort(reason);
        let closedReason;
        try {
            await reader.closed;
            return false;
        } catch (error) {
            closedReason = error;
        }
        return finishPendingResponseBodyCase(
            first.done === false && closedReason === reason,
        );
    }

    if (testCase === 11) {
        const response = await fetch(url);
        const reader = response.body.getReader();
        const first = await reader.read();
        await reader.cancel('consumer stopped');
        return finishPendingResponseBodyCase(first.done === false && response.bodyUsed);
    }

    if (testCase === 12) {
        const response = await fetch(`http://localhost:${port}/empty-response-body`);
        const resolvedAtHead = response.status === 204 && !response.bodyUsed;
        const text = await response.text();
        return finishPendingResponseBodyCase(
            resolvedAtHead && text === '' && response.bodyUsed && cloneThrows(response),
        );
    }

    if (testCase === 13) {
        const response = await fetch(`http://localhost:${port}/clone-response-body`);
        const canceled = response.clone();
        let cancelSettled = false;
        const cancel = canceled.body.cancel('cancel before pull').then(() => {
            cancelSettled = true;
        });
        await Promise.resolve();
        const pendingUntilSurvivorFinishes = !cancelSettled;
        const text = await response.text();
        await cancel;
        return finishPendingResponseBodyCase(
            pendingUntilSurvivorFinishes
            && cancelSettled
            && text === 'first chunksecond chunk',
        );
    }

    if (testCase === 14) {
        const response = await fetch(`http://localhost:${port}/clone-response-body`);
        const canceled = response.clone();
        const reader = canceled.body.getReader();
        const pendingRead = reader.read();
        await Promise.resolve();
        let cancelSettled = false;
        const cancel = reader.cancel('cancel in-flight clone read').then(() => {
            cancelSettled = true;
        });
        await Promise.resolve();
        const pendingUntilSurvivorFinishes = !cancelSettled;
        await pendingRead.catch(() => undefined);
        await new Promise(resolve => setTimeout(resolve, 0));
        const pendingAfterCanceledReadSettled = !cancelSettled;
        const text = await response.text();
        await cancel;
        return finishPendingResponseBodyCase(
            pendingUntilSurvivorFinishes
            && pendingAfterCanceledReadSettled
            && cancelSettled
            && text === 'first chunksecond chunk',
        );
    }

    if (testCase >= 15 && testCase <= 17) {
        const controller = new AbortController();
        const response = await fetch(url, {signal: controller.signal});
        const reason = testCase === 15 ? false : testCase === 16 ? 0 : '';
        const read = response.text();
        controller.abort(reason);
        try {
            await read;
            return false;
        } catch (error) {
            return finishPendingResponseBodyCase(
                isAbortError(error) && response.bodyUsed && cloneThrows(response),
            );
        }
    }

    if (testCase === 18) {
        const response = await fetch(`http://localhost:${port}/clone-race-response-body`);
        const canceled = response.clone();
        const requiresPendingRace =
            typeof response.nativeResponse.makeOpaqueRedirect === 'function';
        const hasRecoveryTestHook =
            typeof canceled.pauseNextBodyReadAfterReadyForTest === 'function';
        const pauseArmed = hasRecoveryTestHook
            ? canceled.pauseNextBodyReadAfterReadyForTest()
            : false;
        const reader = canceled.body.getReader();
        let pendingReadSettled = false;
        const pendingRead = reader.read().finally(() => {
            pendingReadSettled = true;
        });
        await fetch(`http://localhost:${port}/clone-race-release`);
        await Promise.resolve();
        if (requiresPendingRace) {
            await new Promise(resolve => setTimeout(resolve, 10));
        }
        // Preview 3's cancel-safe native read is the race under test. Preview 2 may deliver the
        // available chunk before this continuation, but must still preserve it for the survivor.
        const exercisedTargetRace = !requiresPendingRace || !pendingReadSettled;
        let cancelSettled = false;
        const cancel = reader.cancel('cancel after bytes became available').then(() => {
            cancelSettled = true;
        });
        await pendingRead.catch(() => undefined);
        await new Promise(resolve => setTimeout(resolve, 0));
        const pendingAfterCanceledReadSettled = !cancelSettled;
        const recoveredBytes = hasRecoveryTestHook
            ? response.takeRecoveredBodyReadBytesForTest()
            : 0;
        const text = await response.text();
        await cancel;
        const result =
            (!requiresPendingRace || (hasRecoveryTestHook && pauseArmed))
            && exercisedTargetRace
            && pendingAfterCanceledReadSettled
            && (!requiresPendingRace || recoveredBytes > 0)
            && text === 'first chunksecond chunk';
        if (!result) {
            console.log('clone race diagnostics', JSON.stringify({
                requiresPendingRace,
                hasRecoveryTestHook,
                pauseArmed,
                exercisedTargetRace,
                pendingAfterCanceledReadSettled,
                recoveredBytes,
                text,
            }));
        }
        return finishPendingResponseBodyCase(result);
    }

    if (testCase === 19) {
        const response = await fetch(`http://localhost:${port}/truncated-response-body`);
        const canceled = response.clone();
        response.clone(); // Keep a third branch idle while the shared source errors.
        let cancelSettled = false;
        const cancel = canceled.body.cancel('cancel before shared body error').then(() => {
            cancelSettled = true;
        });
        await Promise.resolve();
        const pendingBeforeError = !cancelSettled;
        try {
            await response.text();
            return false;
        } catch (error) {
            await cancel;
            return finishPendingResponseBodyCase(
                pendingBeforeError && cancelSettled && error instanceof Error,
            );
        }
    }

    if (testCase === 20) {
        let response = await fetch(url);
        const survivor = response;
        let abandoned = response.clone();
        response = null;
        abandoned = null;
        gc();
        await Promise.resolve();
        gc();
        await survivor.body.cancel('cancel after sibling collection');
        return finishPendingResponseBodyCase(true);
    }

    return false;
}

function cloneThrows(response) {
    try {
        response.clone();
        return false;
    } catch (error) {
        return error instanceof TypeError;
    }
}