ponyfill.es6.mjs
169 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
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
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
/**
* web-streams-polyfill v3.2.1
*/
/// <reference lib="es2015.symbol" />
const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
Symbol :
description => `Symbol(${description})`;
/// <reference lib="dom" />
function noop() {
return undefined;
}
function getGlobals() {
if (typeof self !== 'undefined') {
return self;
}
else if (typeof window !== 'undefined') {
return window;
}
else if (typeof global !== 'undefined') {
return global;
}
return undefined;
}
const globals = getGlobals();
function typeIsObject(x) {
return (typeof x === 'object' && x !== null) || typeof x === 'function';
}
const rethrowAssertionErrorRejection = noop;
const originalPromise = Promise;
const originalPromiseThen = Promise.prototype.then;
const originalPromiseResolve = Promise.resolve.bind(originalPromise);
const originalPromiseReject = Promise.reject.bind(originalPromise);
function newPromise(executor) {
return new originalPromise(executor);
}
function promiseResolvedWith(value) {
return originalPromiseResolve(value);
}
function promiseRejectedWith(reason) {
return originalPromiseReject(reason);
}
function PerformPromiseThen(promise, onFulfilled, onRejected) {
// There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
// approximation.
return originalPromiseThen.call(promise, onFulfilled, onRejected);
}
function uponPromise(promise, onFulfilled, onRejected) {
PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
}
function uponFulfillment(promise, onFulfilled) {
uponPromise(promise, onFulfilled);
}
function uponRejection(promise, onRejected) {
uponPromise(promise, undefined, onRejected);
}
function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
}
function setPromiseIsHandledToTrue(promise) {
PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
}
const queueMicrotask = (() => {
const globalQueueMicrotask = globals && globals.queueMicrotask;
if (typeof globalQueueMicrotask === 'function') {
return globalQueueMicrotask;
}
const resolvedPromise = promiseResolvedWith(undefined);
return (fn) => PerformPromiseThen(resolvedPromise, fn);
})();
function reflectCall(F, V, args) {
if (typeof F !== 'function') {
throw new TypeError('Argument is not a function');
}
return Function.prototype.apply.call(F, V, args);
}
function promiseCall(F, V, args) {
try {
return promiseResolvedWith(reflectCall(F, V, args));
}
catch (value) {
return promiseRejectedWith(value);
}
}
// Original from Chromium
// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
const QUEUE_MAX_ARRAY_SIZE = 16384;
/**
* Simple queue structure.
*
* Avoids scalability issues with using a packed array directly by using
* multiple arrays in a linked list and keeping the array size bounded.
*/
class SimpleQueue {
constructor() {
this._cursor = 0;
this._size = 0;
// _front and _back are always defined.
this._front = {
_elements: [],
_next: undefined
};
this._back = this._front;
// The cursor is used to avoid calling Array.shift().
// It contains the index of the front element of the array inside the
// front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
this._cursor = 0;
// When there is only one node, size === elements.length - cursor.
this._size = 0;
}
get length() {
return this._size;
}
// For exception safety, this method is structured in order:
// 1. Read state
// 2. Calculate required state mutations
// 3. Perform state mutations
push(element) {
const oldBack = this._back;
let newBack = oldBack;
if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
newBack = {
_elements: [],
_next: undefined
};
}
// push() is the mutation most likely to throw an exception, so it
// goes first.
oldBack._elements.push(element);
if (newBack !== oldBack) {
this._back = newBack;
oldBack._next = newBack;
}
++this._size;
}
// Like push(), shift() follows the read -> calculate -> mutate pattern for
// exception safety.
shift() { // must not be called on an empty queue
const oldFront = this._front;
let newFront = oldFront;
const oldCursor = this._cursor;
let newCursor = oldCursor + 1;
const elements = oldFront._elements;
const element = elements[oldCursor];
if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
newFront = oldFront._next;
newCursor = 0;
}
// No mutations before this point.
--this._size;
this._cursor = newCursor;
if (oldFront !== newFront) {
this._front = newFront;
}
// Permit shifted element to be garbage collected.
elements[oldCursor] = undefined;
return element;
}
// The tricky thing about forEach() is that it can be called
// re-entrantly. The queue may be mutated inside the callback. It is easy to
// see that push() within the callback has no negative effects since the end
// of the queue is checked for on every iteration. If shift() is called
// repeatedly within the callback then the next iteration may return an
// element that has been removed. In this case the callback will be called
// with undefined values until we either "catch up" with elements that still
// exist or reach the back of the queue.
forEach(callback) {
let i = this._cursor;
let node = this._front;
let elements = node._elements;
while (i !== elements.length || node._next !== undefined) {
if (i === elements.length) {
node = node._next;
elements = node._elements;
i = 0;
if (elements.length === 0) {
break;
}
}
callback(elements[i]);
++i;
}
}
// Return the element that would be returned if shift() was called now,
// without modifying the queue.
peek() { // must not be called on an empty queue
const front = this._front;
const cursor = this._cursor;
return front._elements[cursor];
}
}
function ReadableStreamReaderGenericInitialize(reader, stream) {
reader._ownerReadableStream = stream;
stream._reader = reader;
if (stream._state === 'readable') {
defaultReaderClosedPromiseInitialize(reader);
}
else if (stream._state === 'closed') {
defaultReaderClosedPromiseInitializeAsResolved(reader);
}
else {
defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
}
}
// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
// check.
function ReadableStreamReaderGenericCancel(reader, reason) {
const stream = reader._ownerReadableStream;
return ReadableStreamCancel(stream, reason);
}
function ReadableStreamReaderGenericRelease(reader) {
if (reader._ownerReadableStream._state === 'readable') {
defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
}
else {
defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
}
reader._ownerReadableStream._reader = undefined;
reader._ownerReadableStream = undefined;
}
// Helper functions for the readers.
function readerLockException(name) {
return new TypeError('Cannot ' + name + ' a stream using a released reader');
}
// Helper functions for the ReadableStreamDefaultReader.
function defaultReaderClosedPromiseInitialize(reader) {
reader._closedPromise = newPromise((resolve, reject) => {
reader._closedPromise_resolve = resolve;
reader._closedPromise_reject = reject;
});
}
function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
defaultReaderClosedPromiseInitialize(reader);
defaultReaderClosedPromiseReject(reader, reason);
}
function defaultReaderClosedPromiseInitializeAsResolved(reader) {
defaultReaderClosedPromiseInitialize(reader);
defaultReaderClosedPromiseResolve(reader);
}
function defaultReaderClosedPromiseReject(reader, reason) {
if (reader._closedPromise_reject === undefined) {
return;
}
setPromiseIsHandledToTrue(reader._closedPromise);
reader._closedPromise_reject(reason);
reader._closedPromise_resolve = undefined;
reader._closedPromise_reject = undefined;
}
function defaultReaderClosedPromiseResetToRejected(reader, reason) {
defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
}
function defaultReaderClosedPromiseResolve(reader) {
if (reader._closedPromise_resolve === undefined) {
return;
}
reader._closedPromise_resolve(undefined);
reader._closedPromise_resolve = undefined;
reader._closedPromise_reject = undefined;
}
const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
const PullSteps = SymbolPolyfill('[[PullSteps]]');
/// <reference lib="es2015.core" />
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
const NumberIsFinite = Number.isFinite || function (x) {
return typeof x === 'number' && isFinite(x);
};
/// <reference lib="es2015.core" />
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
const MathTrunc = Math.trunc || function (v) {
return v < 0 ? Math.ceil(v) : Math.floor(v);
};
// https://heycam.github.io/webidl/#idl-dictionaries
function isDictionary(x) {
return typeof x === 'object' || typeof x === 'function';
}
function assertDictionary(obj, context) {
if (obj !== undefined && !isDictionary(obj)) {
throw new TypeError(`${context} is not an object.`);
}
}
// https://heycam.github.io/webidl/#idl-callback-functions
function assertFunction(x, context) {
if (typeof x !== 'function') {
throw new TypeError(`${context} is not a function.`);
}
}
// https://heycam.github.io/webidl/#idl-object
function isObject(x) {
return (typeof x === 'object' && x !== null) || typeof x === 'function';
}
function assertObject(x, context) {
if (!isObject(x)) {
throw new TypeError(`${context} is not an object.`);
}
}
function assertRequiredArgument(x, position, context) {
if (x === undefined) {
throw new TypeError(`Parameter ${position} is required in '${context}'.`);
}
}
function assertRequiredField(x, field, context) {
if (x === undefined) {
throw new TypeError(`${field} is required in '${context}'.`);
}
}
// https://heycam.github.io/webidl/#idl-unrestricted-double
function convertUnrestrictedDouble(value) {
return Number(value);
}
function censorNegativeZero(x) {
return x === 0 ? 0 : x;
}
function integerPart(x) {
return censorNegativeZero(MathTrunc(x));
}
// https://heycam.github.io/webidl/#idl-unsigned-long-long
function convertUnsignedLongLongWithEnforceRange(value, context) {
const lowerBound = 0;
const upperBound = Number.MAX_SAFE_INTEGER;
let x = Number(value);
x = censorNegativeZero(x);
if (!NumberIsFinite(x)) {
throw new TypeError(`${context} is not a finite number`);
}
x = integerPart(x);
if (x < lowerBound || x > upperBound) {
throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
}
if (!NumberIsFinite(x) || x === 0) {
return 0;
}
// TODO Use BigInt if supported?
// let xBigInt = BigInt(integerPart(x));
// xBigInt = BigInt.asUintN(64, xBigInt);
// return Number(xBigInt);
return x;
}
function assertReadableStream(x, context) {
if (!IsReadableStream(x)) {
throw new TypeError(`${context} is not a ReadableStream.`);
}
}
// Abstract operations for the ReadableStream.
function AcquireReadableStreamDefaultReader(stream) {
return new ReadableStreamDefaultReader(stream);
}
// ReadableStream API exposed for controllers.
function ReadableStreamAddReadRequest(stream, readRequest) {
stream._reader._readRequests.push(readRequest);
}
function ReadableStreamFulfillReadRequest(stream, chunk, done) {
const reader = stream._reader;
const readRequest = reader._readRequests.shift();
if (done) {
readRequest._closeSteps();
}
else {
readRequest._chunkSteps(chunk);
}
}
function ReadableStreamGetNumReadRequests(stream) {
return stream._reader._readRequests.length;
}
function ReadableStreamHasDefaultReader(stream) {
const reader = stream._reader;
if (reader === undefined) {
return false;
}
if (!IsReadableStreamDefaultReader(reader)) {
return false;
}
return true;
}
/**
* A default reader vended by a {@link ReadableStream}.
*
* @public
*/
class ReadableStreamDefaultReader {
constructor(stream) {
assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
assertReadableStream(stream, 'First parameter');
if (IsReadableStreamLocked(stream)) {
throw new TypeError('This stream has already been locked for exclusive reading by another reader');
}
ReadableStreamReaderGenericInitialize(this, stream);
this._readRequests = new SimpleQueue();
}
/**
* Returns a promise that will be fulfilled when the stream becomes closed,
* or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
*/
get closed() {
if (!IsReadableStreamDefaultReader(this)) {
return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
}
return this._closedPromise;
}
/**
* If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
*/
cancel(reason = undefined) {
if (!IsReadableStreamDefaultReader(this)) {
return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
}
if (this._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('cancel'));
}
return ReadableStreamReaderGenericCancel(this, reason);
}
/**
* Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
*
* If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
*/
read() {
if (!IsReadableStreamDefaultReader(this)) {
return promiseRejectedWith(defaultReaderBrandCheckException('read'));
}
if (this._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('read from'));
}
let resolvePromise;
let rejectPromise;
const promise = newPromise((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
const readRequest = {
_chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
_closeSteps: () => resolvePromise({ value: undefined, done: true }),
_errorSteps: e => rejectPromise(e)
};
ReadableStreamDefaultReaderRead(this, readRequest);
return promise;
}
/**
* Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
* If the associated stream is errored when the lock is released, the reader will appear errored in the same way
* from now on; otherwise, the reader will appear closed.
*
* A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
* the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
* do so will throw a `TypeError` and leave the reader locked to the stream.
*/
releaseLock() {
if (!IsReadableStreamDefaultReader(this)) {
throw defaultReaderBrandCheckException('releaseLock');
}
if (this._ownerReadableStream === undefined) {
return;
}
if (this._readRequests.length > 0) {
throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
}
ReadableStreamReaderGenericRelease(this);
}
}
Object.defineProperties(ReadableStreamDefaultReader.prototype, {
cancel: { enumerable: true },
read: { enumerable: true },
releaseLock: { enumerable: true },
closed: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableStreamDefaultReader',
configurable: true
});
}
// Abstract operations for the readers.
function IsReadableStreamDefaultReader(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
return false;
}
return x instanceof ReadableStreamDefaultReader;
}
function ReadableStreamDefaultReaderRead(reader, readRequest) {
const stream = reader._ownerReadableStream;
stream._disturbed = true;
if (stream._state === 'closed') {
readRequest._closeSteps();
}
else if (stream._state === 'errored') {
readRequest._errorSteps(stream._storedError);
}
else {
stream._readableStreamController[PullSteps](readRequest);
}
}
// Helper functions for the ReadableStreamDefaultReader.
function defaultReaderBrandCheckException(name) {
return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
}
/// <reference lib="es2018.asynciterable" />
let AsyncIteratorPrototype;
if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
// We're running inside a ES2018+ environment, but we're compiling to an older syntax.
// We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.
AsyncIteratorPrototype = {
// 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
// https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator
[SymbolPolyfill.asyncIterator]() {
return this;
}
};
Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });
}
/// <reference lib="es2018.asynciterable" />
class ReadableStreamAsyncIteratorImpl {
constructor(reader, preventCancel) {
this._ongoingPromise = undefined;
this._isFinished = false;
this._reader = reader;
this._preventCancel = preventCancel;
}
next() {
const nextSteps = () => this._nextSteps();
this._ongoingPromise = this._ongoingPromise ?
transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
nextSteps();
return this._ongoingPromise;
}
return(value) {
const returnSteps = () => this._returnSteps(value);
return this._ongoingPromise ?
transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
returnSteps();
}
_nextSteps() {
if (this._isFinished) {
return Promise.resolve({ value: undefined, done: true });
}
const reader = this._reader;
if (reader._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('iterate'));
}
let resolvePromise;
let rejectPromise;
const promise = newPromise((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
const readRequest = {
_chunkSteps: chunk => {
this._ongoingPromise = undefined;
// This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
// FIXME Is this a bug in the specification, or in the test?
queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
},
_closeSteps: () => {
this._ongoingPromise = undefined;
this._isFinished = true;
ReadableStreamReaderGenericRelease(reader);
resolvePromise({ value: undefined, done: true });
},
_errorSteps: reason => {
this._ongoingPromise = undefined;
this._isFinished = true;
ReadableStreamReaderGenericRelease(reader);
rejectPromise(reason);
}
};
ReadableStreamDefaultReaderRead(reader, readRequest);
return promise;
}
_returnSteps(value) {
if (this._isFinished) {
return Promise.resolve({ value, done: true });
}
this._isFinished = true;
const reader = this._reader;
if (reader._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('finish iterating'));
}
if (!this._preventCancel) {
const result = ReadableStreamReaderGenericCancel(reader, value);
ReadableStreamReaderGenericRelease(reader);
return transformPromiseWith(result, () => ({ value, done: true }));
}
ReadableStreamReaderGenericRelease(reader);
return promiseResolvedWith({ value, done: true });
}
}
const ReadableStreamAsyncIteratorPrototype = {
next() {
if (!IsReadableStreamAsyncIterator(this)) {
return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
}
return this._asyncIteratorImpl.next();
},
return(value) {
if (!IsReadableStreamAsyncIterator(this)) {
return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
}
return this._asyncIteratorImpl.return(value);
}
};
if (AsyncIteratorPrototype !== undefined) {
Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
}
// Abstract operations for the ReadableStream.
function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
const reader = AcquireReadableStreamDefaultReader(stream);
const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
iterator._asyncIteratorImpl = impl;
return iterator;
}
function IsReadableStreamAsyncIterator(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
return false;
}
try {
// noinspection SuspiciousTypeOfGuard
return x._asyncIteratorImpl instanceof
ReadableStreamAsyncIteratorImpl;
}
catch (_a) {
return false;
}
}
// Helper functions for the ReadableStream.
function streamAsyncIteratorBrandCheckException(name) {
return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
}
/// <reference lib="es2015.core" />
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
const NumberIsNaN = Number.isNaN || function (x) {
// eslint-disable-next-line no-self-compare
return x !== x;
};
function CreateArrayFromList(elements) {
// We use arrays to represent lists, so this is basically a no-op.
// Do a slice though just in case we happen to depend on the unique-ness.
return elements.slice();
}
function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
}
// Not implemented correctly
function TransferArrayBuffer(O) {
return O;
}
// Not implemented correctly
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function IsDetachedBuffer(O) {
return false;
}
function ArrayBufferSlice(buffer, begin, end) {
// ArrayBuffer.prototype.slice is not available on IE10
// https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
if (buffer.slice) {
return buffer.slice(begin, end);
}
const length = end - begin;
const slice = new ArrayBuffer(length);
CopyDataBlockBytes(slice, 0, buffer, begin, length);
return slice;
}
function IsNonNegativeNumber(v) {
if (typeof v !== 'number') {
return false;
}
if (NumberIsNaN(v)) {
return false;
}
if (v < 0) {
return false;
}
return true;
}
function CloneAsUint8Array(O) {
const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
return new Uint8Array(buffer);
}
function DequeueValue(container) {
const pair = container._queue.shift();
container._queueTotalSize -= pair.size;
if (container._queueTotalSize < 0) {
container._queueTotalSize = 0;
}
return pair.value;
}
function EnqueueValueWithSize(container, value, size) {
if (!IsNonNegativeNumber(size) || size === Infinity) {
throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
}
container._queue.push({ value, size });
container._queueTotalSize += size;
}
function PeekQueueValue(container) {
const pair = container._queue.peek();
return pair.value;
}
function ResetQueue(container) {
container._queue = new SimpleQueue();
container._queueTotalSize = 0;
}
/**
* A pull-into request in a {@link ReadableByteStreamController}.
*
* @public
*/
class ReadableStreamBYOBRequest {
constructor() {
throw new TypeError('Illegal constructor');
}
/**
* Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
*/
get view() {
if (!IsReadableStreamBYOBRequest(this)) {
throw byobRequestBrandCheckException('view');
}
return this._view;
}
respond(bytesWritten) {
if (!IsReadableStreamBYOBRequest(this)) {
throw byobRequestBrandCheckException('respond');
}
assertRequiredArgument(bytesWritten, 1, 'respond');
bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
if (this._associatedReadableByteStreamController === undefined) {
throw new TypeError('This BYOB request has been invalidated');
}
if (IsDetachedBuffer(this._view.buffer)) ;
ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
}
respondWithNewView(view) {
if (!IsReadableStreamBYOBRequest(this)) {
throw byobRequestBrandCheckException('respondWithNewView');
}
assertRequiredArgument(view, 1, 'respondWithNewView');
if (!ArrayBuffer.isView(view)) {
throw new TypeError('You can only respond with array buffer views');
}
if (this._associatedReadableByteStreamController === undefined) {
throw new TypeError('This BYOB request has been invalidated');
}
if (IsDetachedBuffer(view.buffer)) ;
ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
}
}
Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
respond: { enumerable: true },
respondWithNewView: { enumerable: true },
view: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableStreamBYOBRequest',
configurable: true
});
}
/**
* Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
*
* @public
*/
class ReadableByteStreamController {
constructor() {
throw new TypeError('Illegal constructor');
}
/**
* Returns the current BYOB pull request, or `null` if there isn't one.
*/
get byobRequest() {
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('byobRequest');
}
return ReadableByteStreamControllerGetBYOBRequest(this);
}
/**
* Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
* over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
*/
get desiredSize() {
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('desiredSize');
}
return ReadableByteStreamControllerGetDesiredSize(this);
}
/**
* Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
* the stream, but once those are read, the stream will become closed.
*/
close() {
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('close');
}
if (this._closeRequested) {
throw new TypeError('The stream has already been closed; do not close it again!');
}
const state = this._controlledReadableByteStream._state;
if (state !== 'readable') {
throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
}
ReadableByteStreamControllerClose(this);
}
enqueue(chunk) {
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('enqueue');
}
assertRequiredArgument(chunk, 1, 'enqueue');
if (!ArrayBuffer.isView(chunk)) {
throw new TypeError('chunk must be an array buffer view');
}
if (chunk.byteLength === 0) {
throw new TypeError('chunk must have non-zero byteLength');
}
if (chunk.buffer.byteLength === 0) {
throw new TypeError(`chunk's buffer must have non-zero byteLength`);
}
if (this._closeRequested) {
throw new TypeError('stream is closed or draining');
}
const state = this._controlledReadableByteStream._state;
if (state !== 'readable') {
throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
}
ReadableByteStreamControllerEnqueue(this, chunk);
}
/**
* Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
*/
error(e = undefined) {
if (!IsReadableByteStreamController(this)) {
throw byteStreamControllerBrandCheckException('error');
}
ReadableByteStreamControllerError(this, e);
}
/** @internal */
[CancelSteps](reason) {
ReadableByteStreamControllerClearPendingPullIntos(this);
ResetQueue(this);
const result = this._cancelAlgorithm(reason);
ReadableByteStreamControllerClearAlgorithms(this);
return result;
}
/** @internal */
[PullSteps](readRequest) {
const stream = this._controlledReadableByteStream;
if (this._queueTotalSize > 0) {
const entry = this._queue.shift();
this._queueTotalSize -= entry.byteLength;
ReadableByteStreamControllerHandleQueueDrain(this);
const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
readRequest._chunkSteps(view);
return;
}
const autoAllocateChunkSize = this._autoAllocateChunkSize;
if (autoAllocateChunkSize !== undefined) {
let buffer;
try {
buffer = new ArrayBuffer(autoAllocateChunkSize);
}
catch (bufferE) {
readRequest._errorSteps(bufferE);
return;
}
const pullIntoDescriptor = {
buffer,
bufferByteLength: autoAllocateChunkSize,
byteOffset: 0,
byteLength: autoAllocateChunkSize,
bytesFilled: 0,
elementSize: 1,
viewConstructor: Uint8Array,
readerType: 'default'
};
this._pendingPullIntos.push(pullIntoDescriptor);
}
ReadableStreamAddReadRequest(stream, readRequest);
ReadableByteStreamControllerCallPullIfNeeded(this);
}
}
Object.defineProperties(ReadableByteStreamController.prototype, {
close: { enumerable: true },
enqueue: { enumerable: true },
error: { enumerable: true },
byobRequest: { enumerable: true },
desiredSize: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableByteStreamController',
configurable: true
});
}
// Abstract operations for the ReadableByteStreamController.
function IsReadableByteStreamController(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
return false;
}
return x instanceof ReadableByteStreamController;
}
function IsReadableStreamBYOBRequest(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
return false;
}
return x instanceof ReadableStreamBYOBRequest;
}
function ReadableByteStreamControllerCallPullIfNeeded(controller) {
const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
if (!shouldPull) {
return;
}
if (controller._pulling) {
controller._pullAgain = true;
return;
}
controller._pulling = true;
// TODO: Test controller argument
const pullPromise = controller._pullAlgorithm();
uponPromise(pullPromise, () => {
controller._pulling = false;
if (controller._pullAgain) {
controller._pullAgain = false;
ReadableByteStreamControllerCallPullIfNeeded(controller);
}
}, e => {
ReadableByteStreamControllerError(controller, e);
});
}
function ReadableByteStreamControllerClearPendingPullIntos(controller) {
ReadableByteStreamControllerInvalidateBYOBRequest(controller);
controller._pendingPullIntos = new SimpleQueue();
}
function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
let done = false;
if (stream._state === 'closed') {
done = true;
}
const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
if (pullIntoDescriptor.readerType === 'default') {
ReadableStreamFulfillReadRequest(stream, filledView, done);
}
else {
ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
}
}
function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
const bytesFilled = pullIntoDescriptor.bytesFilled;
const elementSize = pullIntoDescriptor.elementSize;
return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
}
function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
controller._queue.push({ buffer, byteOffset, byteLength });
controller._queueTotalSize += byteLength;
}
function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
const elementSize = pullIntoDescriptor.elementSize;
const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
let totalBytesToCopyRemaining = maxBytesToCopy;
let ready = false;
if (maxAlignedBytes > currentAlignedBytes) {
totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
ready = true;
}
const queue = controller._queue;
while (totalBytesToCopyRemaining > 0) {
const headOfQueue = queue.peek();
const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
if (headOfQueue.byteLength === bytesToCopy) {
queue.shift();
}
else {
headOfQueue.byteOffset += bytesToCopy;
headOfQueue.byteLength -= bytesToCopy;
}
controller._queueTotalSize -= bytesToCopy;
ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
totalBytesToCopyRemaining -= bytesToCopy;
}
return ready;
}
function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
pullIntoDescriptor.bytesFilled += size;
}
function ReadableByteStreamControllerHandleQueueDrain(controller) {
if (controller._queueTotalSize === 0 && controller._closeRequested) {
ReadableByteStreamControllerClearAlgorithms(controller);
ReadableStreamClose(controller._controlledReadableByteStream);
}
else {
ReadableByteStreamControllerCallPullIfNeeded(controller);
}
}
function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
if (controller._byobRequest === null) {
return;
}
controller._byobRequest._associatedReadableByteStreamController = undefined;
controller._byobRequest._view = null;
controller._byobRequest = null;
}
function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
while (controller._pendingPullIntos.length > 0) {
if (controller._queueTotalSize === 0) {
return;
}
const pullIntoDescriptor = controller._pendingPullIntos.peek();
if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
ReadableByteStreamControllerShiftPendingPullInto(controller);
ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
}
}
}
function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
const stream = controller._controlledReadableByteStream;
let elementSize = 1;
if (view.constructor !== DataView) {
elementSize = view.constructor.BYTES_PER_ELEMENT;
}
const ctor = view.constructor;
// try {
const buffer = TransferArrayBuffer(view.buffer);
// } catch (e) {
// readIntoRequest._errorSteps(e);
// return;
// }
const pullIntoDescriptor = {
buffer,
bufferByteLength: buffer.byteLength,
byteOffset: view.byteOffset,
byteLength: view.byteLength,
bytesFilled: 0,
elementSize,
viewConstructor: ctor,
readerType: 'byob'
};
if (controller._pendingPullIntos.length > 0) {
controller._pendingPullIntos.push(pullIntoDescriptor);
// No ReadableByteStreamControllerCallPullIfNeeded() call since:
// - No change happens on desiredSize
// - The source has already been notified of that there's at least 1 pending read(view)
ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
return;
}
if (stream._state === 'closed') {
const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
readIntoRequest._closeSteps(emptyView);
return;
}
if (controller._queueTotalSize > 0) {
if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
ReadableByteStreamControllerHandleQueueDrain(controller);
readIntoRequest._chunkSteps(filledView);
return;
}
if (controller._closeRequested) {
const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
ReadableByteStreamControllerError(controller, e);
readIntoRequest._errorSteps(e);
return;
}
}
controller._pendingPullIntos.push(pullIntoDescriptor);
ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
ReadableByteStreamControllerCallPullIfNeeded(controller);
}
function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
const stream = controller._controlledReadableByteStream;
if (ReadableStreamHasBYOBReader(stream)) {
while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
}
}
}
function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
return;
}
ReadableByteStreamControllerShiftPendingPullInto(controller);
const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
if (remainderSize > 0) {
const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);
ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
}
pullIntoDescriptor.bytesFilled -= remainderSize;
ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
}
function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
const firstDescriptor = controller._pendingPullIntos.peek();
ReadableByteStreamControllerInvalidateBYOBRequest(controller);
const state = controller._controlledReadableByteStream._state;
if (state === 'closed') {
ReadableByteStreamControllerRespondInClosedState(controller);
}
else {
ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
}
ReadableByteStreamControllerCallPullIfNeeded(controller);
}
function ReadableByteStreamControllerShiftPendingPullInto(controller) {
const descriptor = controller._pendingPullIntos.shift();
return descriptor;
}
function ReadableByteStreamControllerShouldCallPull(controller) {
const stream = controller._controlledReadableByteStream;
if (stream._state !== 'readable') {
return false;
}
if (controller._closeRequested) {
return false;
}
if (!controller._started) {
return false;
}
if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
return true;
}
if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
return true;
}
const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
if (desiredSize > 0) {
return true;
}
return false;
}
function ReadableByteStreamControllerClearAlgorithms(controller) {
controller._pullAlgorithm = undefined;
controller._cancelAlgorithm = undefined;
}
// A client of ReadableByteStreamController may use these functions directly to bypass state check.
function ReadableByteStreamControllerClose(controller) {
const stream = controller._controlledReadableByteStream;
if (controller._closeRequested || stream._state !== 'readable') {
return;
}
if (controller._queueTotalSize > 0) {
controller._closeRequested = true;
return;
}
if (controller._pendingPullIntos.length > 0) {
const firstPendingPullInto = controller._pendingPullIntos.peek();
if (firstPendingPullInto.bytesFilled > 0) {
const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
ReadableByteStreamControllerError(controller, e);
throw e;
}
}
ReadableByteStreamControllerClearAlgorithms(controller);
ReadableStreamClose(stream);
}
function ReadableByteStreamControllerEnqueue(controller, chunk) {
const stream = controller._controlledReadableByteStream;
if (controller._closeRequested || stream._state !== 'readable') {
return;
}
const buffer = chunk.buffer;
const byteOffset = chunk.byteOffset;
const byteLength = chunk.byteLength;
const transferredBuffer = TransferArrayBuffer(buffer);
if (controller._pendingPullIntos.length > 0) {
const firstPendingPullInto = controller._pendingPullIntos.peek();
if (IsDetachedBuffer(firstPendingPullInto.buffer)) ;
firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
}
ReadableByteStreamControllerInvalidateBYOBRequest(controller);
if (ReadableStreamHasDefaultReader(stream)) {
if (ReadableStreamGetNumReadRequests(stream) === 0) {
ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
}
else {
if (controller._pendingPullIntos.length > 0) {
ReadableByteStreamControllerShiftPendingPullInto(controller);
}
const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
ReadableStreamFulfillReadRequest(stream, transferredView, false);
}
}
else if (ReadableStreamHasBYOBReader(stream)) {
// TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
}
else {
ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
}
ReadableByteStreamControllerCallPullIfNeeded(controller);
}
function ReadableByteStreamControllerError(controller, e) {
const stream = controller._controlledReadableByteStream;
if (stream._state !== 'readable') {
return;
}
ReadableByteStreamControllerClearPendingPullIntos(controller);
ResetQueue(controller);
ReadableByteStreamControllerClearAlgorithms(controller);
ReadableStreamError(stream, e);
}
function ReadableByteStreamControllerGetBYOBRequest(controller) {
if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
const firstDescriptor = controller._pendingPullIntos.peek();
const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
controller._byobRequest = byobRequest;
}
return controller._byobRequest;
}
function ReadableByteStreamControllerGetDesiredSize(controller) {
const state = controller._controlledReadableByteStream._state;
if (state === 'errored') {
return null;
}
if (state === 'closed') {
return 0;
}
return controller._strategyHWM - controller._queueTotalSize;
}
function ReadableByteStreamControllerRespond(controller, bytesWritten) {
const firstDescriptor = controller._pendingPullIntos.peek();
const state = controller._controlledReadableByteStream._state;
if (state === 'closed') {
if (bytesWritten !== 0) {
throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
}
}
else {
if (bytesWritten === 0) {
throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');
}
if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
throw new RangeError('bytesWritten out of range');
}
}
firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
}
function ReadableByteStreamControllerRespondWithNewView(controller, view) {
const firstDescriptor = controller._pendingPullIntos.peek();
const state = controller._controlledReadableByteStream._state;
if (state === 'closed') {
if (view.byteLength !== 0) {
throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream');
}
}
else {
if (view.byteLength === 0) {
throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream');
}
}
if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
throw new RangeError('The region specified by view does not match byobRequest');
}
if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {
throw new RangeError('The buffer of view has different capacity than byobRequest');
}
if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {
throw new RangeError('The region specified by view is larger than byobRequest');
}
const viewByteLength = view.byteLength;
firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
}
function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
controller._controlledReadableByteStream = stream;
controller._pullAgain = false;
controller._pulling = false;
controller._byobRequest = null;
// Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
controller._queue = controller._queueTotalSize = undefined;
ResetQueue(controller);
controller._closeRequested = false;
controller._started = false;
controller._strategyHWM = highWaterMark;
controller._pullAlgorithm = pullAlgorithm;
controller._cancelAlgorithm = cancelAlgorithm;
controller._autoAllocateChunkSize = autoAllocateChunkSize;
controller._pendingPullIntos = new SimpleQueue();
stream._readableStreamController = controller;
const startResult = startAlgorithm();
uponPromise(promiseResolvedWith(startResult), () => {
controller._started = true;
ReadableByteStreamControllerCallPullIfNeeded(controller);
}, r => {
ReadableByteStreamControllerError(controller, r);
});
}
function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
const controller = Object.create(ReadableByteStreamController.prototype);
let startAlgorithm = () => undefined;
let pullAlgorithm = () => promiseResolvedWith(undefined);
let cancelAlgorithm = () => promiseResolvedWith(undefined);
if (underlyingByteSource.start !== undefined) {
startAlgorithm = () => underlyingByteSource.start(controller);
}
if (underlyingByteSource.pull !== undefined) {
pullAlgorithm = () => underlyingByteSource.pull(controller);
}
if (underlyingByteSource.cancel !== undefined) {
cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
}
const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
if (autoAllocateChunkSize === 0) {
throw new TypeError('autoAllocateChunkSize must be greater than 0');
}
SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
}
function SetUpReadableStreamBYOBRequest(request, controller, view) {
request._associatedReadableByteStreamController = controller;
request._view = view;
}
// Helper functions for the ReadableStreamBYOBRequest.
function byobRequestBrandCheckException(name) {
return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
}
// Helper functions for the ReadableByteStreamController.
function byteStreamControllerBrandCheckException(name) {
return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
}
// Abstract operations for the ReadableStream.
function AcquireReadableStreamBYOBReader(stream) {
return new ReadableStreamBYOBReader(stream);
}
// ReadableStream API exposed for controllers.
function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
stream._reader._readIntoRequests.push(readIntoRequest);
}
function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
const reader = stream._reader;
const readIntoRequest = reader._readIntoRequests.shift();
if (done) {
readIntoRequest._closeSteps(chunk);
}
else {
readIntoRequest._chunkSteps(chunk);
}
}
function ReadableStreamGetNumReadIntoRequests(stream) {
return stream._reader._readIntoRequests.length;
}
function ReadableStreamHasBYOBReader(stream) {
const reader = stream._reader;
if (reader === undefined) {
return false;
}
if (!IsReadableStreamBYOBReader(reader)) {
return false;
}
return true;
}
/**
* A BYOB reader vended by a {@link ReadableStream}.
*
* @public
*/
class ReadableStreamBYOBReader {
constructor(stream) {
assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
assertReadableStream(stream, 'First parameter');
if (IsReadableStreamLocked(stream)) {
throw new TypeError('This stream has already been locked for exclusive reading by another reader');
}
if (!IsReadableByteStreamController(stream._readableStreamController)) {
throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
'source');
}
ReadableStreamReaderGenericInitialize(this, stream);
this._readIntoRequests = new SimpleQueue();
}
/**
* Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
* the reader's lock is released before the stream finishes closing.
*/
get closed() {
if (!IsReadableStreamBYOBReader(this)) {
return promiseRejectedWith(byobReaderBrandCheckException('closed'));
}
return this._closedPromise;
}
/**
* If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
*/
cancel(reason = undefined) {
if (!IsReadableStreamBYOBReader(this)) {
return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
}
if (this._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('cancel'));
}
return ReadableStreamReaderGenericCancel(this, reason);
}
/**
* Attempts to reads bytes into view, and returns a promise resolved with the result.
*
* If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
*/
read(view) {
if (!IsReadableStreamBYOBReader(this)) {
return promiseRejectedWith(byobReaderBrandCheckException('read'));
}
if (!ArrayBuffer.isView(view)) {
return promiseRejectedWith(new TypeError('view must be an array buffer view'));
}
if (view.byteLength === 0) {
return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
}
if (view.buffer.byteLength === 0) {
return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
}
if (IsDetachedBuffer(view.buffer)) ;
if (this._ownerReadableStream === undefined) {
return promiseRejectedWith(readerLockException('read from'));
}
let resolvePromise;
let rejectPromise;
const promise = newPromise((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
const readIntoRequest = {
_chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
_closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
_errorSteps: e => rejectPromise(e)
};
ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
return promise;
}
/**
* Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
* If the associated stream is errored when the lock is released, the reader will appear errored in the same way
* from now on; otherwise, the reader will appear closed.
*
* A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
* the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
* do so will throw a `TypeError` and leave the reader locked to the stream.
*/
releaseLock() {
if (!IsReadableStreamBYOBReader(this)) {
throw byobReaderBrandCheckException('releaseLock');
}
if (this._ownerReadableStream === undefined) {
return;
}
if (this._readIntoRequests.length > 0) {
throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
}
ReadableStreamReaderGenericRelease(this);
}
}
Object.defineProperties(ReadableStreamBYOBReader.prototype, {
cancel: { enumerable: true },
read: { enumerable: true },
releaseLock: { enumerable: true },
closed: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableStreamBYOBReader',
configurable: true
});
}
// Abstract operations for the readers.
function IsReadableStreamBYOBReader(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
return false;
}
return x instanceof ReadableStreamBYOBReader;
}
function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
const stream = reader._ownerReadableStream;
stream._disturbed = true;
if (stream._state === 'errored') {
readIntoRequest._errorSteps(stream._storedError);
}
else {
ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
}
}
// Helper functions for the ReadableStreamBYOBReader.
function byobReaderBrandCheckException(name) {
return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
}
function ExtractHighWaterMark(strategy, defaultHWM) {
const { highWaterMark } = strategy;
if (highWaterMark === undefined) {
return defaultHWM;
}
if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
throw new RangeError('Invalid highWaterMark');
}
return highWaterMark;
}
function ExtractSizeAlgorithm(strategy) {
const { size } = strategy;
if (!size) {
return () => 1;
}
return size;
}
function convertQueuingStrategy(init, context) {
assertDictionary(init, context);
const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
const size = init === null || init === void 0 ? void 0 : init.size;
return {
highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
};
}
function convertQueuingStrategySize(fn, context) {
assertFunction(fn, context);
return chunk => convertUnrestrictedDouble(fn(chunk));
}
function convertUnderlyingSink(original, context) {
assertDictionary(original, context);
const abort = original === null || original === void 0 ? void 0 : original.abort;
const close = original === null || original === void 0 ? void 0 : original.close;
const start = original === null || original === void 0 ? void 0 : original.start;
const type = original === null || original === void 0 ? void 0 : original.type;
const write = original === null || original === void 0 ? void 0 : original.write;
return {
abort: abort === undefined ?
undefined :
convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
close: close === undefined ?
undefined :
convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
start: start === undefined ?
undefined :
convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
write: write === undefined ?
undefined :
convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
type
};
}
function convertUnderlyingSinkAbortCallback(fn, original, context) {
assertFunction(fn, context);
return (reason) => promiseCall(fn, original, [reason]);
}
function convertUnderlyingSinkCloseCallback(fn, original, context) {
assertFunction(fn, context);
return () => promiseCall(fn, original, []);
}
function convertUnderlyingSinkStartCallback(fn, original, context) {
assertFunction(fn, context);
return (controller) => reflectCall(fn, original, [controller]);
}
function convertUnderlyingSinkWriteCallback(fn, original, context) {
assertFunction(fn, context);
return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
}
function assertWritableStream(x, context) {
if (!IsWritableStream(x)) {
throw new TypeError(`${context} is not a WritableStream.`);
}
}
function isAbortSignal(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
try {
return typeof value.aborted === 'boolean';
}
catch (_a) {
// AbortSignal.prototype.aborted throws if its brand check fails
return false;
}
}
const supportsAbortController = typeof AbortController === 'function';
/**
* Construct a new AbortController, if supported by the platform.
*
* @internal
*/
function createAbortController() {
if (supportsAbortController) {
return new AbortController();
}
return undefined;
}
/**
* A writable stream represents a destination for data, into which you can write.
*
* @public
*/
class WritableStream {
constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
if (rawUnderlyingSink === undefined) {
rawUnderlyingSink = null;
}
else {
assertObject(rawUnderlyingSink, 'First parameter');
}
const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
InitializeWritableStream(this);
const type = underlyingSink.type;
if (type !== undefined) {
throw new RangeError('Invalid type is specified');
}
const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
const highWaterMark = ExtractHighWaterMark(strategy, 1);
SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
}
/**
* Returns whether or not the writable stream is locked to a writer.
*/
get locked() {
if (!IsWritableStream(this)) {
throw streamBrandCheckException$2('locked');
}
return IsWritableStreamLocked(this);
}
/**
* Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
* immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
* mechanism of the underlying sink.
*
* The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
* that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
* the stream) if the stream is currently locked.
*/
abort(reason = undefined) {
if (!IsWritableStream(this)) {
return promiseRejectedWith(streamBrandCheckException$2('abort'));
}
if (IsWritableStreamLocked(this)) {
return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
}
return WritableStreamAbort(this, reason);
}
/**
* Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
* close behavior. During this time any further attempts to write will fail (without erroring the stream).
*
* The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
* successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
* a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
*/
close() {
if (!IsWritableStream(this)) {
return promiseRejectedWith(streamBrandCheckException$2('close'));
}
if (IsWritableStreamLocked(this)) {
return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
}
if (WritableStreamCloseQueuedOrInFlight(this)) {
return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
}
return WritableStreamClose(this);
}
/**
* Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
* is locked, no other writer can be acquired until this one is released.
*
* This functionality is especially useful for creating abstractions that desire the ability to write to a stream
* without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
* the same time, which would cause the resulting written data to be unpredictable and probably useless.
*/
getWriter() {
if (!IsWritableStream(this)) {
throw streamBrandCheckException$2('getWriter');
}
return AcquireWritableStreamDefaultWriter(this);
}
}
Object.defineProperties(WritableStream.prototype, {
abort: { enumerable: true },
close: { enumerable: true },
getWriter: { enumerable: true },
locked: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
value: 'WritableStream',
configurable: true
});
}
// Abstract operations for the WritableStream.
function AcquireWritableStreamDefaultWriter(stream) {
return new WritableStreamDefaultWriter(stream);
}
// Throws if and only if startAlgorithm throws.
function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
const stream = Object.create(WritableStream.prototype);
InitializeWritableStream(stream);
const controller = Object.create(WritableStreamDefaultController.prototype);
SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
return stream;
}
function InitializeWritableStream(stream) {
stream._state = 'writable';
// The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
// 'erroring' or 'errored'. May be set to an undefined value.
stream._storedError = undefined;
stream._writer = undefined;
// Initialize to undefined first because the constructor of the controller checks this
// variable to validate the caller.
stream._writableStreamController = undefined;
// This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
// producer without waiting for the queued writes to finish.
stream._writeRequests = new SimpleQueue();
// Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
// them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
stream._inFlightWriteRequest = undefined;
// The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
// has been detached.
stream._closeRequest = undefined;
// Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
// from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
stream._inFlightCloseRequest = undefined;
// The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
stream._pendingAbortRequest = undefined;
// The backpressure signal set by the controller.
stream._backpressure = false;
}
function IsWritableStream(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
return false;
}
return x instanceof WritableStream;
}
function IsWritableStreamLocked(stream) {
if (stream._writer === undefined) {
return false;
}
return true;
}
function WritableStreamAbort(stream, reason) {
var _a;
if (stream._state === 'closed' || stream._state === 'errored') {
return promiseResolvedWith(undefined);
}
stream._writableStreamController._abortReason = reason;
(_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort();
// TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
// but it doesn't know that signaling abort runs author code that might have changed the state.
// Widen the type again by casting to WritableStreamState.
const state = stream._state;
if (state === 'closed' || state === 'errored') {
return promiseResolvedWith(undefined);
}
if (stream._pendingAbortRequest !== undefined) {
return stream._pendingAbortRequest._promise;
}
let wasAlreadyErroring = false;
if (state === 'erroring') {
wasAlreadyErroring = true;
// reason will not be used, so don't keep a reference to it.
reason = undefined;
}
const promise = newPromise((resolve, reject) => {
stream._pendingAbortRequest = {
_promise: undefined,
_resolve: resolve,
_reject: reject,
_reason: reason,
_wasAlreadyErroring: wasAlreadyErroring
};
});
stream._pendingAbortRequest._promise = promise;
if (!wasAlreadyErroring) {
WritableStreamStartErroring(stream, reason);
}
return promise;
}
function WritableStreamClose(stream) {
const state = stream._state;
if (state === 'closed' || state === 'errored') {
return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
}
const promise = newPromise((resolve, reject) => {
const closeRequest = {
_resolve: resolve,
_reject: reject
};
stream._closeRequest = closeRequest;
});
const writer = stream._writer;
if (writer !== undefined && stream._backpressure && state === 'writable') {
defaultWriterReadyPromiseResolve(writer);
}
WritableStreamDefaultControllerClose(stream._writableStreamController);
return promise;
}
// WritableStream API exposed for controllers.
function WritableStreamAddWriteRequest(stream) {
const promise = newPromise((resolve, reject) => {
const writeRequest = {
_resolve: resolve,
_reject: reject
};
stream._writeRequests.push(writeRequest);
});
return promise;
}
function WritableStreamDealWithRejection(stream, error) {
const state = stream._state;
if (state === 'writable') {
WritableStreamStartErroring(stream, error);
return;
}
WritableStreamFinishErroring(stream);
}
function WritableStreamStartErroring(stream, reason) {
const controller = stream._writableStreamController;
stream._state = 'erroring';
stream._storedError = reason;
const writer = stream._writer;
if (writer !== undefined) {
WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
}
if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
WritableStreamFinishErroring(stream);
}
}
function WritableStreamFinishErroring(stream) {
stream._state = 'errored';
stream._writableStreamController[ErrorSteps]();
const storedError = stream._storedError;
stream._writeRequests.forEach(writeRequest => {
writeRequest._reject(storedError);
});
stream._writeRequests = new SimpleQueue();
if (stream._pendingAbortRequest === undefined) {
WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
return;
}
const abortRequest = stream._pendingAbortRequest;
stream._pendingAbortRequest = undefined;
if (abortRequest._wasAlreadyErroring) {
abortRequest._reject(storedError);
WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
return;
}
const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
uponPromise(promise, () => {
abortRequest._resolve();
WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
}, (reason) => {
abortRequest._reject(reason);
WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
});
}
function WritableStreamFinishInFlightWrite(stream) {
stream._inFlightWriteRequest._resolve(undefined);
stream._inFlightWriteRequest = undefined;
}
function WritableStreamFinishInFlightWriteWithError(stream, error) {
stream._inFlightWriteRequest._reject(error);
stream._inFlightWriteRequest = undefined;
WritableStreamDealWithRejection(stream, error);
}
function WritableStreamFinishInFlightClose(stream) {
stream._inFlightCloseRequest._resolve(undefined);
stream._inFlightCloseRequest = undefined;
const state = stream._state;
if (state === 'erroring') {
// The error was too late to do anything, so it is ignored.
stream._storedError = undefined;
if (stream._pendingAbortRequest !== undefined) {
stream._pendingAbortRequest._resolve();
stream._pendingAbortRequest = undefined;
}
}
stream._state = 'closed';
const writer = stream._writer;
if (writer !== undefined) {
defaultWriterClosedPromiseResolve(writer);
}
}
function WritableStreamFinishInFlightCloseWithError(stream, error) {
stream._inFlightCloseRequest._reject(error);
stream._inFlightCloseRequest = undefined;
// Never execute sink abort() after sink close().
if (stream._pendingAbortRequest !== undefined) {
stream._pendingAbortRequest._reject(error);
stream._pendingAbortRequest = undefined;
}
WritableStreamDealWithRejection(stream, error);
}
// TODO(ricea): Fix alphabetical order.
function WritableStreamCloseQueuedOrInFlight(stream) {
if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
return false;
}
return true;
}
function WritableStreamHasOperationMarkedInFlight(stream) {
if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
return false;
}
return true;
}
function WritableStreamMarkCloseRequestInFlight(stream) {
stream._inFlightCloseRequest = stream._closeRequest;
stream._closeRequest = undefined;
}
function WritableStreamMarkFirstWriteRequestInFlight(stream) {
stream._inFlightWriteRequest = stream._writeRequests.shift();
}
function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
if (stream._closeRequest !== undefined) {
stream._closeRequest._reject(stream._storedError);
stream._closeRequest = undefined;
}
const writer = stream._writer;
if (writer !== undefined) {
defaultWriterClosedPromiseReject(writer, stream._storedError);
}
}
function WritableStreamUpdateBackpressure(stream, backpressure) {
const writer = stream._writer;
if (writer !== undefined && backpressure !== stream._backpressure) {
if (backpressure) {
defaultWriterReadyPromiseReset(writer);
}
else {
defaultWriterReadyPromiseResolve(writer);
}
}
stream._backpressure = backpressure;
}
/**
* A default writer vended by a {@link WritableStream}.
*
* @public
*/
class WritableStreamDefaultWriter {
constructor(stream) {
assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
assertWritableStream(stream, 'First parameter');
if (IsWritableStreamLocked(stream)) {
throw new TypeError('This stream has already been locked for exclusive writing by another writer');
}
this._ownerWritableStream = stream;
stream._writer = this;
const state = stream._state;
if (state === 'writable') {
if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
defaultWriterReadyPromiseInitialize(this);
}
else {
defaultWriterReadyPromiseInitializeAsResolved(this);
}
defaultWriterClosedPromiseInitialize(this);
}
else if (state === 'erroring') {
defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
defaultWriterClosedPromiseInitialize(this);
}
else if (state === 'closed') {
defaultWriterReadyPromiseInitializeAsResolved(this);
defaultWriterClosedPromiseInitializeAsResolved(this);
}
else {
const storedError = stream._storedError;
defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
}
}
/**
* Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
* the writer’s lock is released before the stream finishes closing.
*/
get closed() {
if (!IsWritableStreamDefaultWriter(this)) {
return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
}
return this._closedPromise;
}
/**
* Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
* A producer can use this information to determine the right amount of data to write.
*
* It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
* queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
* the writer’s lock is released.
*/
get desiredSize() {
if (!IsWritableStreamDefaultWriter(this)) {
throw defaultWriterBrandCheckException('desiredSize');
}
if (this._ownerWritableStream === undefined) {
throw defaultWriterLockException('desiredSize');
}
return WritableStreamDefaultWriterGetDesiredSize(this);
}
/**
* Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
* from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
* back to zero or below, the getter will return a new promise that stays pending until the next transition.
*
* If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
* rejected.
*/
get ready() {
if (!IsWritableStreamDefaultWriter(this)) {
return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
}
return this._readyPromise;
}
/**
* If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
*/
abort(reason = undefined) {
if (!IsWritableStreamDefaultWriter(this)) {
return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
}
if (this._ownerWritableStream === undefined) {
return promiseRejectedWith(defaultWriterLockException('abort'));
}
return WritableStreamDefaultWriterAbort(this, reason);
}
/**
* If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
*/
close() {
if (!IsWritableStreamDefaultWriter(this)) {
return promiseRejectedWith(defaultWriterBrandCheckException('close'));
}
const stream = this._ownerWritableStream;
if (stream === undefined) {
return promiseRejectedWith(defaultWriterLockException('close'));
}
if (WritableStreamCloseQueuedOrInFlight(stream)) {
return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
}
return WritableStreamDefaultWriterClose(this);
}
/**
* Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
* If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
* now on; otherwise, the writer will appear closed.
*
* Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
* promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
* It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
* other producers from writing in an interleaved manner.
*/
releaseLock() {
if (!IsWritableStreamDefaultWriter(this)) {
throw defaultWriterBrandCheckException('releaseLock');
}
const stream = this._ownerWritableStream;
if (stream === undefined) {
return;
}
WritableStreamDefaultWriterRelease(this);
}
write(chunk = undefined) {
if (!IsWritableStreamDefaultWriter(this)) {
return promiseRejectedWith(defaultWriterBrandCheckException('write'));
}
if (this._ownerWritableStream === undefined) {
return promiseRejectedWith(defaultWriterLockException('write to'));
}
return WritableStreamDefaultWriterWrite(this, chunk);
}
}
Object.defineProperties(WritableStreamDefaultWriter.prototype, {
abort: { enumerable: true },
close: { enumerable: true },
releaseLock: { enumerable: true },
write: { enumerable: true },
closed: { enumerable: true },
desiredSize: { enumerable: true },
ready: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
value: 'WritableStreamDefaultWriter',
configurable: true
});
}
// Abstract operations for the WritableStreamDefaultWriter.
function IsWritableStreamDefaultWriter(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
return false;
}
return x instanceof WritableStreamDefaultWriter;
}
// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
function WritableStreamDefaultWriterAbort(writer, reason) {
const stream = writer._ownerWritableStream;
return WritableStreamAbort(stream, reason);
}
function WritableStreamDefaultWriterClose(writer) {
const stream = writer._ownerWritableStream;
return WritableStreamClose(stream);
}
function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
const stream = writer._ownerWritableStream;
const state = stream._state;
if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
return promiseResolvedWith(undefined);
}
if (state === 'errored') {
return promiseRejectedWith(stream._storedError);
}
return WritableStreamDefaultWriterClose(writer);
}
function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
if (writer._closedPromiseState === 'pending') {
defaultWriterClosedPromiseReject(writer, error);
}
else {
defaultWriterClosedPromiseResetToRejected(writer, error);
}
}
function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
if (writer._readyPromiseState === 'pending') {
defaultWriterReadyPromiseReject(writer, error);
}
else {
defaultWriterReadyPromiseResetToRejected(writer, error);
}
}
function WritableStreamDefaultWriterGetDesiredSize(writer) {
const stream = writer._ownerWritableStream;
const state = stream._state;
if (state === 'errored' || state === 'erroring') {
return null;
}
if (state === 'closed') {
return 0;
}
return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
}
function WritableStreamDefaultWriterRelease(writer) {
const stream = writer._ownerWritableStream;
const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
// The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
// rejected until afterwards. This means that simply testing state will not work.
WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
stream._writer = undefined;
writer._ownerWritableStream = undefined;
}
function WritableStreamDefaultWriterWrite(writer, chunk) {
const stream = writer._ownerWritableStream;
const controller = stream._writableStreamController;
const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
if (stream !== writer._ownerWritableStream) {
return promiseRejectedWith(defaultWriterLockException('write to'));
}
const state = stream._state;
if (state === 'errored') {
return promiseRejectedWith(stream._storedError);
}
if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
}
if (state === 'erroring') {
return promiseRejectedWith(stream._storedError);
}
const promise = WritableStreamAddWriteRequest(stream);
WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
return promise;
}
const closeSentinel = {};
/**
* Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
*
* @public
*/
class WritableStreamDefaultController {
constructor() {
throw new TypeError('Illegal constructor');
}
/**
* The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
*
* @deprecated
* This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
* Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
*/
get abortReason() {
if (!IsWritableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$2('abortReason');
}
return this._abortReason;
}
/**
* An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
*/
get signal() {
if (!IsWritableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$2('signal');
}
if (this._abortController === undefined) {
// Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.
// We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,
// so instead we only implement support for `signal` if we find a global `AbortController` constructor.
throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');
}
return this._abortController.signal;
}
/**
* Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
*
* This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
* sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
* normal lifecycle of interactions with the underlying sink.
*/
error(e = undefined) {
if (!IsWritableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$2('error');
}
const state = this._controlledWritableStream._state;
if (state !== 'writable') {
// The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
// just treat it as a no-op.
return;
}
WritableStreamDefaultControllerError(this, e);
}
/** @internal */
[AbortSteps](reason) {
const result = this._abortAlgorithm(reason);
WritableStreamDefaultControllerClearAlgorithms(this);
return result;
}
/** @internal */
[ErrorSteps]() {
ResetQueue(this);
}
}
Object.defineProperties(WritableStreamDefaultController.prototype, {
abortReason: { enumerable: true },
signal: { enumerable: true },
error: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
value: 'WritableStreamDefaultController',
configurable: true
});
}
// Abstract operations implementing interface required by the WritableStream.
function IsWritableStreamDefaultController(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
return false;
}
return x instanceof WritableStreamDefaultController;
}
function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
controller._controlledWritableStream = stream;
stream._writableStreamController = controller;
// Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
controller._queue = undefined;
controller._queueTotalSize = undefined;
ResetQueue(controller);
controller._abortReason = undefined;
controller._abortController = createAbortController();
controller._started = false;
controller._strategySizeAlgorithm = sizeAlgorithm;
controller._strategyHWM = highWaterMark;
controller._writeAlgorithm = writeAlgorithm;
controller._closeAlgorithm = closeAlgorithm;
controller._abortAlgorithm = abortAlgorithm;
const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
WritableStreamUpdateBackpressure(stream, backpressure);
const startResult = startAlgorithm();
const startPromise = promiseResolvedWith(startResult);
uponPromise(startPromise, () => {
controller._started = true;
WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
}, r => {
controller._started = true;
WritableStreamDealWithRejection(stream, r);
});
}
function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
const controller = Object.create(WritableStreamDefaultController.prototype);
let startAlgorithm = () => undefined;
let writeAlgorithm = () => promiseResolvedWith(undefined);
let closeAlgorithm = () => promiseResolvedWith(undefined);
let abortAlgorithm = () => promiseResolvedWith(undefined);
if (underlyingSink.start !== undefined) {
startAlgorithm = () => underlyingSink.start(controller);
}
if (underlyingSink.write !== undefined) {
writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
}
if (underlyingSink.close !== undefined) {
closeAlgorithm = () => underlyingSink.close();
}
if (underlyingSink.abort !== undefined) {
abortAlgorithm = reason => underlyingSink.abort(reason);
}
SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
}
// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
function WritableStreamDefaultControllerClearAlgorithms(controller) {
controller._writeAlgorithm = undefined;
controller._closeAlgorithm = undefined;
controller._abortAlgorithm = undefined;
controller._strategySizeAlgorithm = undefined;
}
function WritableStreamDefaultControllerClose(controller) {
EnqueueValueWithSize(controller, closeSentinel, 0);
WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
}
function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
try {
return controller._strategySizeAlgorithm(chunk);
}
catch (chunkSizeE) {
WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
return 1;
}
}
function WritableStreamDefaultControllerGetDesiredSize(controller) {
return controller._strategyHWM - controller._queueTotalSize;
}
function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
try {
EnqueueValueWithSize(controller, chunk, chunkSize);
}
catch (enqueueE) {
WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
return;
}
const stream = controller._controlledWritableStream;
if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
WritableStreamUpdateBackpressure(stream, backpressure);
}
WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
}
// Abstract operations for the WritableStreamDefaultController.
function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
const stream = controller._controlledWritableStream;
if (!controller._started) {
return;
}
if (stream._inFlightWriteRequest !== undefined) {
return;
}
const state = stream._state;
if (state === 'erroring') {
WritableStreamFinishErroring(stream);
return;
}
if (controller._queue.length === 0) {
return;
}
const value = PeekQueueValue(controller);
if (value === closeSentinel) {
WritableStreamDefaultControllerProcessClose(controller);
}
else {
WritableStreamDefaultControllerProcessWrite(controller, value);
}
}
function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
if (controller._controlledWritableStream._state === 'writable') {
WritableStreamDefaultControllerError(controller, error);
}
}
function WritableStreamDefaultControllerProcessClose(controller) {
const stream = controller._controlledWritableStream;
WritableStreamMarkCloseRequestInFlight(stream);
DequeueValue(controller);
const sinkClosePromise = controller._closeAlgorithm();
WritableStreamDefaultControllerClearAlgorithms(controller);
uponPromise(sinkClosePromise, () => {
WritableStreamFinishInFlightClose(stream);
}, reason => {
WritableStreamFinishInFlightCloseWithError(stream, reason);
});
}
function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
const stream = controller._controlledWritableStream;
WritableStreamMarkFirstWriteRequestInFlight(stream);
const sinkWritePromise = controller._writeAlgorithm(chunk);
uponPromise(sinkWritePromise, () => {
WritableStreamFinishInFlightWrite(stream);
const state = stream._state;
DequeueValue(controller);
if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
WritableStreamUpdateBackpressure(stream, backpressure);
}
WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
}, reason => {
if (stream._state === 'writable') {
WritableStreamDefaultControllerClearAlgorithms(controller);
}
WritableStreamFinishInFlightWriteWithError(stream, reason);
});
}
function WritableStreamDefaultControllerGetBackpressure(controller) {
const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
return desiredSize <= 0;
}
// A client of WritableStreamDefaultController may use these functions directly to bypass state check.
function WritableStreamDefaultControllerError(controller, error) {
const stream = controller._controlledWritableStream;
WritableStreamDefaultControllerClearAlgorithms(controller);
WritableStreamStartErroring(stream, error);
}
// Helper functions for the WritableStream.
function streamBrandCheckException$2(name) {
return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
}
// Helper functions for the WritableStreamDefaultController.
function defaultControllerBrandCheckException$2(name) {
return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
}
// Helper functions for the WritableStreamDefaultWriter.
function defaultWriterBrandCheckException(name) {
return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
}
function defaultWriterLockException(name) {
return new TypeError('Cannot ' + name + ' a stream using a released writer');
}
function defaultWriterClosedPromiseInitialize(writer) {
writer._closedPromise = newPromise((resolve, reject) => {
writer._closedPromise_resolve = resolve;
writer._closedPromise_reject = reject;
writer._closedPromiseState = 'pending';
});
}
function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
defaultWriterClosedPromiseInitialize(writer);
defaultWriterClosedPromiseReject(writer, reason);
}
function defaultWriterClosedPromiseInitializeAsResolved(writer) {
defaultWriterClosedPromiseInitialize(writer);
defaultWriterClosedPromiseResolve(writer);
}
function defaultWriterClosedPromiseReject(writer, reason) {
if (writer._closedPromise_reject === undefined) {
return;
}
setPromiseIsHandledToTrue(writer._closedPromise);
writer._closedPromise_reject(reason);
writer._closedPromise_resolve = undefined;
writer._closedPromise_reject = undefined;
writer._closedPromiseState = 'rejected';
}
function defaultWriterClosedPromiseResetToRejected(writer, reason) {
defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
}
function defaultWriterClosedPromiseResolve(writer) {
if (writer._closedPromise_resolve === undefined) {
return;
}
writer._closedPromise_resolve(undefined);
writer._closedPromise_resolve = undefined;
writer._closedPromise_reject = undefined;
writer._closedPromiseState = 'resolved';
}
function defaultWriterReadyPromiseInitialize(writer) {
writer._readyPromise = newPromise((resolve, reject) => {
writer._readyPromise_resolve = resolve;
writer._readyPromise_reject = reject;
});
writer._readyPromiseState = 'pending';
}
function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
defaultWriterReadyPromiseInitialize(writer);
defaultWriterReadyPromiseReject(writer, reason);
}
function defaultWriterReadyPromiseInitializeAsResolved(writer) {
defaultWriterReadyPromiseInitialize(writer);
defaultWriterReadyPromiseResolve(writer);
}
function defaultWriterReadyPromiseReject(writer, reason) {
if (writer._readyPromise_reject === undefined) {
return;
}
setPromiseIsHandledToTrue(writer._readyPromise);
writer._readyPromise_reject(reason);
writer._readyPromise_resolve = undefined;
writer._readyPromise_reject = undefined;
writer._readyPromiseState = 'rejected';
}
function defaultWriterReadyPromiseReset(writer) {
defaultWriterReadyPromiseInitialize(writer);
}
function defaultWriterReadyPromiseResetToRejected(writer, reason) {
defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
}
function defaultWriterReadyPromiseResolve(writer) {
if (writer._readyPromise_resolve === undefined) {
return;
}
writer._readyPromise_resolve(undefined);
writer._readyPromise_resolve = undefined;
writer._readyPromise_reject = undefined;
writer._readyPromiseState = 'fulfilled';
}
/// <reference lib="dom" />
const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
/// <reference types="node" />
function isDOMExceptionConstructor(ctor) {
if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
return false;
}
try {
new ctor();
return true;
}
catch (_a) {
return false;
}
}
function createDOMExceptionPolyfill() {
// eslint-disable-next-line no-shadow
const ctor = function DOMException(message, name) {
this.message = message || '';
this.name = name || 'Error';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
};
ctor.prototype = Object.create(Error.prototype);
Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
return ctor;
}
// eslint-disable-next-line no-redeclare
const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
const reader = AcquireReadableStreamDefaultReader(source);
const writer = AcquireWritableStreamDefaultWriter(dest);
source._disturbed = true;
let shuttingDown = false;
// This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
let currentWrite = promiseResolvedWith(undefined);
return newPromise((resolve, reject) => {
let abortAlgorithm;
if (signal !== undefined) {
abortAlgorithm = () => {
const error = new DOMException$1('Aborted', 'AbortError');
const actions = [];
if (!preventAbort) {
actions.push(() => {
if (dest._state === 'writable') {
return WritableStreamAbort(dest, error);
}
return promiseResolvedWith(undefined);
});
}
if (!preventCancel) {
actions.push(() => {
if (source._state === 'readable') {
return ReadableStreamCancel(source, error);
}
return promiseResolvedWith(undefined);
});
}
shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
};
if (signal.aborted) {
abortAlgorithm();
return;
}
signal.addEventListener('abort', abortAlgorithm);
}
// Using reader and writer, read all chunks from this and write them to dest
// - Backpressure must be enforced
// - Shutdown must stop all activity
function pipeLoop() {
return newPromise((resolveLoop, rejectLoop) => {
function next(done) {
if (done) {
resolveLoop();
}
else {
// Use `PerformPromiseThen` instead of `uponPromise` to avoid
// adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
PerformPromiseThen(pipeStep(), next, rejectLoop);
}
}
next(false);
});
}
function pipeStep() {
if (shuttingDown) {
return promiseResolvedWith(true);
}
return PerformPromiseThen(writer._readyPromise, () => {
return newPromise((resolveRead, rejectRead) => {
ReadableStreamDefaultReaderRead(reader, {
_chunkSteps: chunk => {
currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
resolveRead(false);
},
_closeSteps: () => resolveRead(true),
_errorSteps: rejectRead
});
});
});
}
// Errors must be propagated forward
isOrBecomesErrored(source, reader._closedPromise, storedError => {
if (!preventAbort) {
shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
}
else {
shutdown(true, storedError);
}
});
// Errors must be propagated backward
isOrBecomesErrored(dest, writer._closedPromise, storedError => {
if (!preventCancel) {
shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
}
else {
shutdown(true, storedError);
}
});
// Closing must be propagated forward
isOrBecomesClosed(source, reader._closedPromise, () => {
if (!preventClose) {
shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
}
else {
shutdown();
}
});
// Closing must be propagated backward
if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
if (!preventCancel) {
shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
}
else {
shutdown(true, destClosed);
}
}
setPromiseIsHandledToTrue(pipeLoop());
function waitForWritesToFinish() {
// Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
// for that too.
const oldCurrentWrite = currentWrite;
return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
}
function isOrBecomesErrored(stream, promise, action) {
if (stream._state === 'errored') {
action(stream._storedError);
}
else {
uponRejection(promise, action);
}
}
function isOrBecomesClosed(stream, promise, action) {
if (stream._state === 'closed') {
action();
}
else {
uponFulfillment(promise, action);
}
}
function shutdownWithAction(action, originalIsError, originalError) {
if (shuttingDown) {
return;
}
shuttingDown = true;
if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
uponFulfillment(waitForWritesToFinish(), doTheRest);
}
else {
doTheRest();
}
function doTheRest() {
uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
}
}
function shutdown(isError, error) {
if (shuttingDown) {
return;
}
shuttingDown = true;
if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
}
else {
finalize(isError, error);
}
}
function finalize(isError, error) {
WritableStreamDefaultWriterRelease(writer);
ReadableStreamReaderGenericRelease(reader);
if (signal !== undefined) {
signal.removeEventListener('abort', abortAlgorithm);
}
if (isError) {
reject(error);
}
else {
resolve(undefined);
}
}
});
}
/**
* Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
*
* @public
*/
class ReadableStreamDefaultController {
constructor() {
throw new TypeError('Illegal constructor');
}
/**
* Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
* over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
*/
get desiredSize() {
if (!IsReadableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$1('desiredSize');
}
return ReadableStreamDefaultControllerGetDesiredSize(this);
}
/**
* Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
* the stream, but once those are read, the stream will become closed.
*/
close() {
if (!IsReadableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$1('close');
}
if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
throw new TypeError('The stream is not in a state that permits close');
}
ReadableStreamDefaultControllerClose(this);
}
enqueue(chunk = undefined) {
if (!IsReadableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$1('enqueue');
}
if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
throw new TypeError('The stream is not in a state that permits enqueue');
}
return ReadableStreamDefaultControllerEnqueue(this, chunk);
}
/**
* Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
*/
error(e = undefined) {
if (!IsReadableStreamDefaultController(this)) {
throw defaultControllerBrandCheckException$1('error');
}
ReadableStreamDefaultControllerError(this, e);
}
/** @internal */
[CancelSteps](reason) {
ResetQueue(this);
const result = this._cancelAlgorithm(reason);
ReadableStreamDefaultControllerClearAlgorithms(this);
return result;
}
/** @internal */
[PullSteps](readRequest) {
const stream = this._controlledReadableStream;
if (this._queue.length > 0) {
const chunk = DequeueValue(this);
if (this._closeRequested && this._queue.length === 0) {
ReadableStreamDefaultControllerClearAlgorithms(this);
ReadableStreamClose(stream);
}
else {
ReadableStreamDefaultControllerCallPullIfNeeded(this);
}
readRequest._chunkSteps(chunk);
}
else {
ReadableStreamAddReadRequest(stream, readRequest);
ReadableStreamDefaultControllerCallPullIfNeeded(this);
}
}
}
Object.defineProperties(ReadableStreamDefaultController.prototype, {
close: { enumerable: true },
enqueue: { enumerable: true },
error: { enumerable: true },
desiredSize: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableStreamDefaultController',
configurable: true
});
}
// Abstract operations for the ReadableStreamDefaultController.
function IsReadableStreamDefaultController(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
return false;
}
return x instanceof ReadableStreamDefaultController;
}
function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
if (!shouldPull) {
return;
}
if (controller._pulling) {
controller._pullAgain = true;
return;
}
controller._pulling = true;
const pullPromise = controller._pullAlgorithm();
uponPromise(pullPromise, () => {
controller._pulling = false;
if (controller._pullAgain) {
controller._pullAgain = false;
ReadableStreamDefaultControllerCallPullIfNeeded(controller);
}
}, e => {
ReadableStreamDefaultControllerError(controller, e);
});
}
function ReadableStreamDefaultControllerShouldCallPull(controller) {
const stream = controller._controlledReadableStream;
if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
return false;
}
if (!controller._started) {
return false;
}
if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
return true;
}
const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
if (desiredSize > 0) {
return true;
}
return false;
}
function ReadableStreamDefaultControllerClearAlgorithms(controller) {
controller._pullAlgorithm = undefined;
controller._cancelAlgorithm = undefined;
controller._strategySizeAlgorithm = undefined;
}
// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
function ReadableStreamDefaultControllerClose(controller) {
if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
return;
}
const stream = controller._controlledReadableStream;
controller._closeRequested = true;
if (controller._queue.length === 0) {
ReadableStreamDefaultControllerClearAlgorithms(controller);
ReadableStreamClose(stream);
}
}
function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
return;
}
const stream = controller._controlledReadableStream;
if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
ReadableStreamFulfillReadRequest(stream, chunk, false);
}
else {
let chunkSize;
try {
chunkSize = controller._strategySizeAlgorithm(chunk);
}
catch (chunkSizeE) {
ReadableStreamDefaultControllerError(controller, chunkSizeE);
throw chunkSizeE;
}
try {
EnqueueValueWithSize(controller, chunk, chunkSize);
}
catch (enqueueE) {
ReadableStreamDefaultControllerError(controller, enqueueE);
throw enqueueE;
}
}
ReadableStreamDefaultControllerCallPullIfNeeded(controller);
}
function ReadableStreamDefaultControllerError(controller, e) {
const stream = controller._controlledReadableStream;
if (stream._state !== 'readable') {
return;
}
ResetQueue(controller);
ReadableStreamDefaultControllerClearAlgorithms(controller);
ReadableStreamError(stream, e);
}
function ReadableStreamDefaultControllerGetDesiredSize(controller) {
const state = controller._controlledReadableStream._state;
if (state === 'errored') {
return null;
}
if (state === 'closed') {
return 0;
}
return controller._strategyHWM - controller._queueTotalSize;
}
// This is used in the implementation of TransformStream.
function ReadableStreamDefaultControllerHasBackpressure(controller) {
if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
return false;
}
return true;
}
function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
const state = controller._controlledReadableStream._state;
if (!controller._closeRequested && state === 'readable') {
return true;
}
return false;
}
function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
controller._controlledReadableStream = stream;
controller._queue = undefined;
controller._queueTotalSize = undefined;
ResetQueue(controller);
controller._started = false;
controller._closeRequested = false;
controller._pullAgain = false;
controller._pulling = false;
controller._strategySizeAlgorithm = sizeAlgorithm;
controller._strategyHWM = highWaterMark;
controller._pullAlgorithm = pullAlgorithm;
controller._cancelAlgorithm = cancelAlgorithm;
stream._readableStreamController = controller;
const startResult = startAlgorithm();
uponPromise(promiseResolvedWith(startResult), () => {
controller._started = true;
ReadableStreamDefaultControllerCallPullIfNeeded(controller);
}, r => {
ReadableStreamDefaultControllerError(controller, r);
});
}
function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
const controller = Object.create(ReadableStreamDefaultController.prototype);
let startAlgorithm = () => undefined;
let pullAlgorithm = () => promiseResolvedWith(undefined);
let cancelAlgorithm = () => promiseResolvedWith(undefined);
if (underlyingSource.start !== undefined) {
startAlgorithm = () => underlyingSource.start(controller);
}
if (underlyingSource.pull !== undefined) {
pullAlgorithm = () => underlyingSource.pull(controller);
}
if (underlyingSource.cancel !== undefined) {
cancelAlgorithm = reason => underlyingSource.cancel(reason);
}
SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
}
// Helper functions for the ReadableStreamDefaultController.
function defaultControllerBrandCheckException$1(name) {
return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
}
function ReadableStreamTee(stream, cloneForBranch2) {
if (IsReadableByteStreamController(stream._readableStreamController)) {
return ReadableByteStreamTee(stream);
}
return ReadableStreamDefaultTee(stream);
}
function ReadableStreamDefaultTee(stream, cloneForBranch2) {
const reader = AcquireReadableStreamDefaultReader(stream);
let reading = false;
let readAgain = false;
let canceled1 = false;
let canceled2 = false;
let reason1;
let reason2;
let branch1;
let branch2;
let resolveCancelPromise;
const cancelPromise = newPromise(resolve => {
resolveCancelPromise = resolve;
});
function pullAlgorithm() {
if (reading) {
readAgain = true;
return promiseResolvedWith(undefined);
}
reading = true;
const readRequest = {
_chunkSteps: chunk => {
// This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
// reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
// successful synchronously-available reads get ahead of asynchronously-available errors.
queueMicrotask(() => {
readAgain = false;
const chunk1 = chunk;
const chunk2 = chunk;
// There is no way to access the cloning code right now in the reference implementation.
// If we add one then we'll need an implementation for serializable objects.
// if (!canceled2 && cloneForBranch2) {
// chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));
// }
if (!canceled1) {
ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
}
if (!canceled2) {
ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
}
reading = false;
if (readAgain) {
pullAlgorithm();
}
});
},
_closeSteps: () => {
reading = false;
if (!canceled1) {
ReadableStreamDefaultControllerClose(branch1._readableStreamController);
}
if (!canceled2) {
ReadableStreamDefaultControllerClose(branch2._readableStreamController);
}
if (!canceled1 || !canceled2) {
resolveCancelPromise(undefined);
}
},
_errorSteps: () => {
reading = false;
}
};
ReadableStreamDefaultReaderRead(reader, readRequest);
return promiseResolvedWith(undefined);
}
function cancel1Algorithm(reason) {
canceled1 = true;
reason1 = reason;
if (canceled2) {
const compositeReason = CreateArrayFromList([reason1, reason2]);
const cancelResult = ReadableStreamCancel(stream, compositeReason);
resolveCancelPromise(cancelResult);
}
return cancelPromise;
}
function cancel2Algorithm(reason) {
canceled2 = true;
reason2 = reason;
if (canceled1) {
const compositeReason = CreateArrayFromList([reason1, reason2]);
const cancelResult = ReadableStreamCancel(stream, compositeReason);
resolveCancelPromise(cancelResult);
}
return cancelPromise;
}
function startAlgorithm() {
// do nothing
}
branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
uponRejection(reader._closedPromise, (r) => {
ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
if (!canceled1 || !canceled2) {
resolveCancelPromise(undefined);
}
});
return [branch1, branch2];
}
function ReadableByteStreamTee(stream) {
let reader = AcquireReadableStreamDefaultReader(stream);
let reading = false;
let readAgainForBranch1 = false;
let readAgainForBranch2 = false;
let canceled1 = false;
let canceled2 = false;
let reason1;
let reason2;
let branch1;
let branch2;
let resolveCancelPromise;
const cancelPromise = newPromise(resolve => {
resolveCancelPromise = resolve;
});
function forwardReaderError(thisReader) {
uponRejection(thisReader._closedPromise, r => {
if (thisReader !== reader) {
return;
}
ReadableByteStreamControllerError(branch1._readableStreamController, r);
ReadableByteStreamControllerError(branch2._readableStreamController, r);
if (!canceled1 || !canceled2) {
resolveCancelPromise(undefined);
}
});
}
function pullWithDefaultReader() {
if (IsReadableStreamBYOBReader(reader)) {
ReadableStreamReaderGenericRelease(reader);
reader = AcquireReadableStreamDefaultReader(stream);
forwardReaderError(reader);
}
const readRequest = {
_chunkSteps: chunk => {
// This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
// reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
// successful synchronously-available reads get ahead of asynchronously-available errors.
queueMicrotask(() => {
readAgainForBranch1 = false;
readAgainForBranch2 = false;
const chunk1 = chunk;
let chunk2 = chunk;
if (!canceled1 && !canceled2) {
try {
chunk2 = CloneAsUint8Array(chunk);
}
catch (cloneE) {
ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
return;
}
}
if (!canceled1) {
ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
}
if (!canceled2) {
ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
}
reading = false;
if (readAgainForBranch1) {
pull1Algorithm();
}
else if (readAgainForBranch2) {
pull2Algorithm();
}
});
},
_closeSteps: () => {
reading = false;
if (!canceled1) {
ReadableByteStreamControllerClose(branch1._readableStreamController);
}
if (!canceled2) {
ReadableByteStreamControllerClose(branch2._readableStreamController);
}
if (branch1._readableStreamController._pendingPullIntos.length > 0) {
ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
}
if (branch2._readableStreamController._pendingPullIntos.length > 0) {
ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
}
if (!canceled1 || !canceled2) {
resolveCancelPromise(undefined);
}
},
_errorSteps: () => {
reading = false;
}
};
ReadableStreamDefaultReaderRead(reader, readRequest);
}
function pullWithBYOBReader(view, forBranch2) {
if (IsReadableStreamDefaultReader(reader)) {
ReadableStreamReaderGenericRelease(reader);
reader = AcquireReadableStreamBYOBReader(stream);
forwardReaderError(reader);
}
const byobBranch = forBranch2 ? branch2 : branch1;
const otherBranch = forBranch2 ? branch1 : branch2;
const readIntoRequest = {
_chunkSteps: chunk => {
// This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
// reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
// successful synchronously-available reads get ahead of asynchronously-available errors.
queueMicrotask(() => {
readAgainForBranch1 = false;
readAgainForBranch2 = false;
const byobCanceled = forBranch2 ? canceled2 : canceled1;
const otherCanceled = forBranch2 ? canceled1 : canceled2;
if (!otherCanceled) {
let clonedChunk;
try {
clonedChunk = CloneAsUint8Array(chunk);
}
catch (cloneE) {
ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
return;
}
if (!byobCanceled) {
ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
}
ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
}
else if (!byobCanceled) {
ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
}
reading = false;
if (readAgainForBranch1) {
pull1Algorithm();
}
else if (readAgainForBranch2) {
pull2Algorithm();
}
});
},
_closeSteps: chunk => {
reading = false;
const byobCanceled = forBranch2 ? canceled2 : canceled1;
const otherCanceled = forBranch2 ? canceled1 : canceled2;
if (!byobCanceled) {
ReadableByteStreamControllerClose(byobBranch._readableStreamController);
}
if (!otherCanceled) {
ReadableByteStreamControllerClose(otherBranch._readableStreamController);
}
if (chunk !== undefined) {
if (!byobCanceled) {
ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
}
if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
}
}
if (!byobCanceled || !otherCanceled) {
resolveCancelPromise(undefined);
}
},
_errorSteps: () => {
reading = false;
}
};
ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
}
function pull1Algorithm() {
if (reading) {
readAgainForBranch1 = true;
return promiseResolvedWith(undefined);
}
reading = true;
const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
if (byobRequest === null) {
pullWithDefaultReader();
}
else {
pullWithBYOBReader(byobRequest._view, false);
}
return promiseResolvedWith(undefined);
}
function pull2Algorithm() {
if (reading) {
readAgainForBranch2 = true;
return promiseResolvedWith(undefined);
}
reading = true;
const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
if (byobRequest === null) {
pullWithDefaultReader();
}
else {
pullWithBYOBReader(byobRequest._view, true);
}
return promiseResolvedWith(undefined);
}
function cancel1Algorithm(reason) {
canceled1 = true;
reason1 = reason;
if (canceled2) {
const compositeReason = CreateArrayFromList([reason1, reason2]);
const cancelResult = ReadableStreamCancel(stream, compositeReason);
resolveCancelPromise(cancelResult);
}
return cancelPromise;
}
function cancel2Algorithm(reason) {
canceled2 = true;
reason2 = reason;
if (canceled1) {
const compositeReason = CreateArrayFromList([reason1, reason2]);
const cancelResult = ReadableStreamCancel(stream, compositeReason);
resolveCancelPromise(cancelResult);
}
return cancelPromise;
}
function startAlgorithm() {
return;
}
branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
forwardReaderError(reader);
return [branch1, branch2];
}
function convertUnderlyingDefaultOrByteSource(source, context) {
assertDictionary(source, context);
const original = source;
const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
const cancel = original === null || original === void 0 ? void 0 : original.cancel;
const pull = original === null || original === void 0 ? void 0 : original.pull;
const start = original === null || original === void 0 ? void 0 : original.start;
const type = original === null || original === void 0 ? void 0 : original.type;
return {
autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
undefined :
convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
cancel: cancel === undefined ?
undefined :
convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
pull: pull === undefined ?
undefined :
convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
start: start === undefined ?
undefined :
convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
};
}
function convertUnderlyingSourceCancelCallback(fn, original, context) {
assertFunction(fn, context);
return (reason) => promiseCall(fn, original, [reason]);
}
function convertUnderlyingSourcePullCallback(fn, original, context) {
assertFunction(fn, context);
return (controller) => promiseCall(fn, original, [controller]);
}
function convertUnderlyingSourceStartCallback(fn, original, context) {
assertFunction(fn, context);
return (controller) => reflectCall(fn, original, [controller]);
}
function convertReadableStreamType(type, context) {
type = `${type}`;
if (type !== 'bytes') {
throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
}
return type;
}
function convertReaderOptions(options, context) {
assertDictionary(options, context);
const mode = options === null || options === void 0 ? void 0 : options.mode;
return {
mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
};
}
function convertReadableStreamReaderMode(mode, context) {
mode = `${mode}`;
if (mode !== 'byob') {
throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
}
return mode;
}
function convertIteratorOptions(options, context) {
assertDictionary(options, context);
const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
return { preventCancel: Boolean(preventCancel) };
}
function convertPipeOptions(options, context) {
assertDictionary(options, context);
const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
const signal = options === null || options === void 0 ? void 0 : options.signal;
if (signal !== undefined) {
assertAbortSignal(signal, `${context} has member 'signal' that`);
}
return {
preventAbort: Boolean(preventAbort),
preventCancel: Boolean(preventCancel),
preventClose: Boolean(preventClose),
signal
};
}
function assertAbortSignal(signal, context) {
if (!isAbortSignal(signal)) {
throw new TypeError(`${context} is not an AbortSignal.`);
}
}
function convertReadableWritablePair(pair, context) {
assertDictionary(pair, context);
const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
assertRequiredField(readable, 'readable', 'ReadableWritablePair');
assertReadableStream(readable, `${context} has member 'readable' that`);
const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
assertRequiredField(writable, 'writable', 'ReadableWritablePair');
assertWritableStream(writable, `${context} has member 'writable' that`);
return { readable, writable };
}
/**
* A readable stream represents a source of data, from which you can read.
*
* @public
*/
class ReadableStream {
constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
if (rawUnderlyingSource === undefined) {
rawUnderlyingSource = null;
}
else {
assertObject(rawUnderlyingSource, 'First parameter');
}
const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
InitializeReadableStream(this);
if (underlyingSource.type === 'bytes') {
if (strategy.size !== undefined) {
throw new RangeError('The strategy for a byte stream cannot have a size function');
}
const highWaterMark = ExtractHighWaterMark(strategy, 0);
SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
}
else {
const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
const highWaterMark = ExtractHighWaterMark(strategy, 1);
SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
}
}
/**
* Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
*/
get locked() {
if (!IsReadableStream(this)) {
throw streamBrandCheckException$1('locked');
}
return IsReadableStreamLocked(this);
}
/**
* Cancels the stream, signaling a loss of interest in the stream by a consumer.
*
* The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
* method, which might or might not use it.
*/
cancel(reason = undefined) {
if (!IsReadableStream(this)) {
return promiseRejectedWith(streamBrandCheckException$1('cancel'));
}
if (IsReadableStreamLocked(this)) {
return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
}
return ReadableStreamCancel(this, reason);
}
getReader(rawOptions = undefined) {
if (!IsReadableStream(this)) {
throw streamBrandCheckException$1('getReader');
}
const options = convertReaderOptions(rawOptions, 'First parameter');
if (options.mode === undefined) {
return AcquireReadableStreamDefaultReader(this);
}
return AcquireReadableStreamBYOBReader(this);
}
pipeThrough(rawTransform, rawOptions = {}) {
if (!IsReadableStream(this)) {
throw streamBrandCheckException$1('pipeThrough');
}
assertRequiredArgument(rawTransform, 1, 'pipeThrough');
const transform = convertReadableWritablePair(rawTransform, 'First parameter');
const options = convertPipeOptions(rawOptions, 'Second parameter');
if (IsReadableStreamLocked(this)) {
throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
}
if (IsWritableStreamLocked(transform.writable)) {
throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
}
const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
setPromiseIsHandledToTrue(promise);
return transform.readable;
}
pipeTo(destination, rawOptions = {}) {
if (!IsReadableStream(this)) {
return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
}
if (destination === undefined) {
return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
}
if (!IsWritableStream(destination)) {
return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
}
let options;
try {
options = convertPipeOptions(rawOptions, 'Second parameter');
}
catch (e) {
return promiseRejectedWith(e);
}
if (IsReadableStreamLocked(this)) {
return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
}
if (IsWritableStreamLocked(destination)) {
return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
}
return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
}
/**
* Tees this readable stream, returning a two-element array containing the two resulting branches as
* new {@link ReadableStream} instances.
*
* Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
* To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
* propagated to the stream's underlying source.
*
* Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
* this could allow interference between the two branches.
*/
tee() {
if (!IsReadableStream(this)) {
throw streamBrandCheckException$1('tee');
}
const branches = ReadableStreamTee(this);
return CreateArrayFromList(branches);
}
values(rawOptions = undefined) {
if (!IsReadableStream(this)) {
throw streamBrandCheckException$1('values');
}
const options = convertIteratorOptions(rawOptions, 'First parameter');
return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
}
}
Object.defineProperties(ReadableStream.prototype, {
cancel: { enumerable: true },
getReader: { enumerable: true },
pipeThrough: { enumerable: true },
pipeTo: { enumerable: true },
tee: { enumerable: true },
values: { enumerable: true },
locked: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
value: 'ReadableStream',
configurable: true
});
}
if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {
value: ReadableStream.prototype.values,
writable: true,
configurable: true
});
}
// Abstract operations for the ReadableStream.
// Throws if and only if startAlgorithm throws.
function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
const stream = Object.create(ReadableStream.prototype);
InitializeReadableStream(stream);
const controller = Object.create(ReadableStreamDefaultController.prototype);
SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
return stream;
}
// Throws if and only if startAlgorithm throws.
function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
const stream = Object.create(ReadableStream.prototype);
InitializeReadableStream(stream);
const controller = Object.create(ReadableByteStreamController.prototype);
SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);
return stream;
}
function InitializeReadableStream(stream) {
stream._state = 'readable';
stream._reader = undefined;
stream._storedError = undefined;
stream._disturbed = false;
}
function IsReadableStream(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
return false;
}
return x instanceof ReadableStream;
}
function IsReadableStreamLocked(stream) {
if (stream._reader === undefined) {
return false;
}
return true;
}
// ReadableStream API exposed for controllers.
function ReadableStreamCancel(stream, reason) {
stream._disturbed = true;
if (stream._state === 'closed') {
return promiseResolvedWith(undefined);
}
if (stream._state === 'errored') {
return promiseRejectedWith(stream._storedError);
}
ReadableStreamClose(stream);
const reader = stream._reader;
if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
reader._readIntoRequests.forEach(readIntoRequest => {
readIntoRequest._closeSteps(undefined);
});
reader._readIntoRequests = new SimpleQueue();
}
const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
return transformPromiseWith(sourceCancelPromise, noop);
}
function ReadableStreamClose(stream) {
stream._state = 'closed';
const reader = stream._reader;
if (reader === undefined) {
return;
}
defaultReaderClosedPromiseResolve(reader);
if (IsReadableStreamDefaultReader(reader)) {
reader._readRequests.forEach(readRequest => {
readRequest._closeSteps();
});
reader._readRequests = new SimpleQueue();
}
}
function ReadableStreamError(stream, e) {
stream._state = 'errored';
stream._storedError = e;
const reader = stream._reader;
if (reader === undefined) {
return;
}
defaultReaderClosedPromiseReject(reader, e);
if (IsReadableStreamDefaultReader(reader)) {
reader._readRequests.forEach(readRequest => {
readRequest._errorSteps(e);
});
reader._readRequests = new SimpleQueue();
}
else {
reader._readIntoRequests.forEach(readIntoRequest => {
readIntoRequest._errorSteps(e);
});
reader._readIntoRequests = new SimpleQueue();
}
}
// Helper functions for the ReadableStream.
function streamBrandCheckException$1(name) {
return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
}
function convertQueuingStrategyInit(init, context) {
assertDictionary(init, context);
const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
return {
highWaterMark: convertUnrestrictedDouble(highWaterMark)
};
}
// The size function must not have a prototype property nor be a constructor
const byteLengthSizeFunction = (chunk) => {
return chunk.byteLength;
};
try {
Object.defineProperty(byteLengthSizeFunction, 'name', {
value: 'size',
configurable: true
});
}
catch (_a) {
// This property is non-configurable in older browsers, so ignore if this throws.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
}
/**
* A queuing strategy that counts the number of bytes in each chunk.
*
* @public
*/
class ByteLengthQueuingStrategy {
constructor(options) {
assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
options = convertQueuingStrategyInit(options, 'First parameter');
this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
}
/**
* Returns the high water mark provided to the constructor.
*/
get highWaterMark() {
if (!IsByteLengthQueuingStrategy(this)) {
throw byteLengthBrandCheckException('highWaterMark');
}
return this._byteLengthQueuingStrategyHighWaterMark;
}
/**
* Measures the size of `chunk` by returning the value of its `byteLength` property.
*/
get size() {
if (!IsByteLengthQueuingStrategy(this)) {
throw byteLengthBrandCheckException('size');
}
return byteLengthSizeFunction;
}
}
Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
highWaterMark: { enumerable: true },
size: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
value: 'ByteLengthQueuingStrategy',
configurable: true
});
}
// Helper functions for the ByteLengthQueuingStrategy.
function byteLengthBrandCheckException(name) {
return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
}
function IsByteLengthQueuingStrategy(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
return false;
}
return x instanceof ByteLengthQueuingStrategy;
}
// The size function must not have a prototype property nor be a constructor
const countSizeFunction = () => {
return 1;
};
try {
Object.defineProperty(countSizeFunction, 'name', {
value: 'size',
configurable: true
});
}
catch (_a) {
// This property is non-configurable in older browsers, so ignore if this throws.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
}
/**
* A queuing strategy that counts the number of chunks.
*
* @public
*/
class CountQueuingStrategy {
constructor(options) {
assertRequiredArgument(options, 1, 'CountQueuingStrategy');
options = convertQueuingStrategyInit(options, 'First parameter');
this._countQueuingStrategyHighWaterMark = options.highWaterMark;
}
/**
* Returns the high water mark provided to the constructor.
*/
get highWaterMark() {
if (!IsCountQueuingStrategy(this)) {
throw countBrandCheckException('highWaterMark');
}
return this._countQueuingStrategyHighWaterMark;
}
/**
* Measures the size of `chunk` by always returning 1.
* This ensures that the total queue size is a count of the number of chunks in the queue.
*/
get size() {
if (!IsCountQueuingStrategy(this)) {
throw countBrandCheckException('size');
}
return countSizeFunction;
}
}
Object.defineProperties(CountQueuingStrategy.prototype, {
highWaterMark: { enumerable: true },
size: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
value: 'CountQueuingStrategy',
configurable: true
});
}
// Helper functions for the CountQueuingStrategy.
function countBrandCheckException(name) {
return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
}
function IsCountQueuingStrategy(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
return false;
}
return x instanceof CountQueuingStrategy;
}
function convertTransformer(original, context) {
assertDictionary(original, context);
const flush = original === null || original === void 0 ? void 0 : original.flush;
const readableType = original === null || original === void 0 ? void 0 : original.readableType;
const start = original === null || original === void 0 ? void 0 : original.start;
const transform = original === null || original === void 0 ? void 0 : original.transform;
const writableType = original === null || original === void 0 ? void 0 : original.writableType;
return {
flush: flush === undefined ?
undefined :
convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
readableType,
start: start === undefined ?
undefined :
convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
transform: transform === undefined ?
undefined :
convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
writableType
};
}
function convertTransformerFlushCallback(fn, original, context) {
assertFunction(fn, context);
return (controller) => promiseCall(fn, original, [controller]);
}
function convertTransformerStartCallback(fn, original, context) {
assertFunction(fn, context);
return (controller) => reflectCall(fn, original, [controller]);
}
function convertTransformerTransformCallback(fn, original, context) {
assertFunction(fn, context);
return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
}
// Class TransformStream
/**
* A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
* known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
* In a manner specific to the transform stream in question, writes to the writable side result in new data being
* made available for reading from the readable side.
*
* @public
*/
class TransformStream {
constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
if (rawTransformer === undefined) {
rawTransformer = null;
}
const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
const transformer = convertTransformer(rawTransformer, 'First parameter');
if (transformer.readableType !== undefined) {
throw new RangeError('Invalid readableType specified');
}
if (transformer.writableType !== undefined) {
throw new RangeError('Invalid writableType specified');
}
const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
let startPromise_resolve;
const startPromise = newPromise(resolve => {
startPromise_resolve = resolve;
});
InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
if (transformer.start !== undefined) {
startPromise_resolve(transformer.start(this._transformStreamController));
}
else {
startPromise_resolve(undefined);
}
}
/**
* The readable side of the transform stream.
*/
get readable() {
if (!IsTransformStream(this)) {
throw streamBrandCheckException('readable');
}
return this._readable;
}
/**
* The writable side of the transform stream.
*/
get writable() {
if (!IsTransformStream(this)) {
throw streamBrandCheckException('writable');
}
return this._writable;
}
}
Object.defineProperties(TransformStream.prototype, {
readable: { enumerable: true },
writable: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {
value: 'TransformStream',
configurable: true
});
}
function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
function startAlgorithm() {
return startPromise;
}
function writeAlgorithm(chunk) {
return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
}
function abortAlgorithm(reason) {
return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
}
function closeAlgorithm() {
return TransformStreamDefaultSinkCloseAlgorithm(stream);
}
stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
function pullAlgorithm() {
return TransformStreamDefaultSourcePullAlgorithm(stream);
}
function cancelAlgorithm(reason) {
TransformStreamErrorWritableAndUnblockWrite(stream, reason);
return promiseResolvedWith(undefined);
}
stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
// The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
stream._backpressure = undefined;
stream._backpressureChangePromise = undefined;
stream._backpressureChangePromise_resolve = undefined;
TransformStreamSetBackpressure(stream, true);
stream._transformStreamController = undefined;
}
function IsTransformStream(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
return false;
}
return x instanceof TransformStream;
}
// This is a no-op if both sides are already errored.
function TransformStreamError(stream, e) {
ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
TransformStreamErrorWritableAndUnblockWrite(stream, e);
}
function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
if (stream._backpressure) {
// Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
// cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
// _backpressure is set.
TransformStreamSetBackpressure(stream, false);
}
}
function TransformStreamSetBackpressure(stream, backpressure) {
// Passes also when called during construction.
if (stream._backpressureChangePromise !== undefined) {
stream._backpressureChangePromise_resolve();
}
stream._backpressureChangePromise = newPromise(resolve => {
stream._backpressureChangePromise_resolve = resolve;
});
stream._backpressure = backpressure;
}
// Class TransformStreamDefaultController
/**
* Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
*
* @public
*/
class TransformStreamDefaultController {
constructor() {
throw new TypeError('Illegal constructor');
}
/**
* Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
*/
get desiredSize() {
if (!IsTransformStreamDefaultController(this)) {
throw defaultControllerBrandCheckException('desiredSize');
}
const readableController = this._controlledTransformStream._readable._readableStreamController;
return ReadableStreamDefaultControllerGetDesiredSize(readableController);
}
enqueue(chunk = undefined) {
if (!IsTransformStreamDefaultController(this)) {
throw defaultControllerBrandCheckException('enqueue');
}
TransformStreamDefaultControllerEnqueue(this, chunk);
}
/**
* Errors both the readable side and the writable side of the controlled transform stream, making all future
* interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
*/
error(reason = undefined) {
if (!IsTransformStreamDefaultController(this)) {
throw defaultControllerBrandCheckException('error');
}
TransformStreamDefaultControllerError(this, reason);
}
/**
* Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
* transformer only needs to consume a portion of the chunks written to the writable side.
*/
terminate() {
if (!IsTransformStreamDefaultController(this)) {
throw defaultControllerBrandCheckException('terminate');
}
TransformStreamDefaultControllerTerminate(this);
}
}
Object.defineProperties(TransformStreamDefaultController.prototype, {
enqueue: { enumerable: true },
error: { enumerable: true },
terminate: { enumerable: true },
desiredSize: { enumerable: true }
});
if (typeof SymbolPolyfill.toStringTag === 'symbol') {
Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
value: 'TransformStreamDefaultController',
configurable: true
});
}
// Transform Stream Default Controller Abstract Operations
function IsTransformStreamDefaultController(x) {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
return false;
}
return x instanceof TransformStreamDefaultController;
}
function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
controller._controlledTransformStream = stream;
stream._transformStreamController = controller;
controller._transformAlgorithm = transformAlgorithm;
controller._flushAlgorithm = flushAlgorithm;
}
function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
const controller = Object.create(TransformStreamDefaultController.prototype);
let transformAlgorithm = (chunk) => {
try {
TransformStreamDefaultControllerEnqueue(controller, chunk);
return promiseResolvedWith(undefined);
}
catch (transformResultE) {
return promiseRejectedWith(transformResultE);
}
};
let flushAlgorithm = () => promiseResolvedWith(undefined);
if (transformer.transform !== undefined) {
transformAlgorithm = chunk => transformer.transform(chunk, controller);
}
if (transformer.flush !== undefined) {
flushAlgorithm = () => transformer.flush(controller);
}
SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
}
function TransformStreamDefaultControllerClearAlgorithms(controller) {
controller._transformAlgorithm = undefined;
controller._flushAlgorithm = undefined;
}
function TransformStreamDefaultControllerEnqueue(controller, chunk) {
const stream = controller._controlledTransformStream;
const readableController = stream._readable._readableStreamController;
if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
throw new TypeError('Readable side is not in a state that permits enqueue');
}
// We throttle transform invocations based on the backpressure of the ReadableStream, but we still
// accept TransformStreamDefaultControllerEnqueue() calls.
try {
ReadableStreamDefaultControllerEnqueue(readableController, chunk);
}
catch (e) {
// This happens when readableStrategy.size() throws.
TransformStreamErrorWritableAndUnblockWrite(stream, e);
throw stream._readable._storedError;
}
const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
if (backpressure !== stream._backpressure) {
TransformStreamSetBackpressure(stream, true);
}
}
function TransformStreamDefaultControllerError(controller, e) {
TransformStreamError(controller._controlledTransformStream, e);
}
function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
const transformPromise = controller._transformAlgorithm(chunk);
return transformPromiseWith(transformPromise, undefined, r => {
TransformStreamError(controller._controlledTransformStream, r);
throw r;
});
}
function TransformStreamDefaultControllerTerminate(controller) {
const stream = controller._controlledTransformStream;
const readableController = stream._readable._readableStreamController;
ReadableStreamDefaultControllerClose(readableController);
const error = new TypeError('TransformStream terminated');
TransformStreamErrorWritableAndUnblockWrite(stream, error);
}
// TransformStreamDefaultSink Algorithms
function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
const controller = stream._transformStreamController;
if (stream._backpressure) {
const backpressureChangePromise = stream._backpressureChangePromise;
return transformPromiseWith(backpressureChangePromise, () => {
const writable = stream._writable;
const state = writable._state;
if (state === 'erroring') {
throw writable._storedError;
}
return TransformStreamDefaultControllerPerformTransform(controller, chunk);
});
}
return TransformStreamDefaultControllerPerformTransform(controller, chunk);
}
function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
// abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
// errored.
TransformStreamError(stream, reason);
return promiseResolvedWith(undefined);
}
function TransformStreamDefaultSinkCloseAlgorithm(stream) {
// stream._readable cannot change after construction, so caching it across a call to user code is safe.
const readable = stream._readable;
const controller = stream._transformStreamController;
const flushPromise = controller._flushAlgorithm();
TransformStreamDefaultControllerClearAlgorithms(controller);
// Return a promise that is fulfilled with undefined on success.
return transformPromiseWith(flushPromise, () => {
if (readable._state === 'errored') {
throw readable._storedError;
}
ReadableStreamDefaultControllerClose(readable._readableStreamController);
}, r => {
TransformStreamError(stream, r);
throw readable._storedError;
});
}
// TransformStreamDefaultSource Algorithms
function TransformStreamDefaultSourcePullAlgorithm(stream) {
// Invariant. Enforced by the promises returned by start() and pull().
TransformStreamSetBackpressure(stream, false);
// Prevent the next pull() call until there is backpressure.
return stream._backpressureChangePromise;
}
// Helper functions for the TransformStreamDefaultController.
function defaultControllerBrandCheckException(name) {
return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
}
// Helper functions for the TransformStream.
function streamBrandCheckException(name) {
return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
}
export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter };
//# sourceMappingURL=ponyfill.es6.mjs.map