mozjs_sys 0.67.1

System crate for the Mozilla SpiderMonkey JavaScript engine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
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
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "builtin/Stream.h"

#include "js/Stream.h"

#include "gc/Heap.h"
#include "js/ArrayBuffer.h"  // JS::NewArrayBuffer
#include "js/PropertySpec.h"
#include "vm/Interpreter.h"
#include "vm/JSContext.h"
#include "vm/SelfHosting.h"

#include "vm/Compartment-inl.h"
#include "vm/List-inl.h"
#include "vm/NativeObject-inl.h"

using namespace js;

enum ReaderType { ReaderType_Default, ReaderType_BYOB };

template <class T>
bool Is(const HandleValue v) {
  return v.isObject() && v.toObject().is<T>();
}

template <class T>
bool IsMaybeWrapped(const HandleValue v) {
  return v.isObject() && v.toObject().canUnwrapAs<T>();
}

JS::ReadableStreamMode ReadableStream::mode() const {
  ReadableStreamController* controller = this->controller();
  if (controller->is<ReadableStreamDefaultController>()) {
    return JS::ReadableStreamMode::Default;
  }
  return controller->as<ReadableByteStreamController>().hasExternalSource()
             ? JS::ReadableStreamMode::ExternalSource
             : JS::ReadableStreamMode::Byte;
}

/**
 * Returns the stream associated with the given reader.
 */
static MOZ_MUST_USE ReadableStream* UnwrapStreamFromReader(
    JSContext* cx, Handle<ReadableStreamReader*> reader) {
  MOZ_ASSERT(reader->hasStream());
  return UnwrapInternalSlot<ReadableStream>(cx, reader,
                                            ReadableStreamReader::Slot_Stream);
}

/**
 * Returns the reader associated with the given stream.
 *
 * Must only be called on ReadableStreams that already have a reader
 * associated with them.
 *
 * If the reader is a wrapper, it will be unwrapped, so the result might not be
 * an object from the currently active compartment.
 */
static MOZ_MUST_USE ReadableStreamReader* UnwrapReaderFromStream(
    JSContext* cx, Handle<ReadableStream*> stream) {
  return UnwrapInternalSlot<ReadableStreamReader>(cx, stream,
                                                  ReadableStream::Slot_Reader);
}

static MOZ_MUST_USE ReadableStreamReader* UnwrapReaderFromStreamNoThrow(
    ReadableStream* stream) {
  JSObject* readerObj =
      &stream->getFixedSlot(ReadableStream::Slot_Reader).toObject();
  if (IsProxy(readerObj)) {
    if (JS_IsDeadWrapper(readerObj)) {
      return nullptr;
    }

    readerObj = readerObj->maybeUnwrapAs<ReadableStreamReader>();
    if (!readerObj) {
      return nullptr;
    }
  }

  return &readerObj->as<ReadableStreamReader>();
}

constexpr size_t StreamHandlerFunctionSlot_Target = 0;

inline static MOZ_MUST_USE JSFunction* NewHandler(JSContext* cx, Native handler,
                                                  HandleObject target) {
  cx->check(target);

  HandlePropertyName funName = cx->names().empty;
  RootedFunction handlerFun(
      cx, NewNativeFunction(cx, handler, 0, funName,
                            gc::AllocKind::FUNCTION_EXTENDED, GenericObject));
  if (!handlerFun) {
    return nullptr;
  }
  handlerFun->setExtendedSlot(StreamHandlerFunctionSlot_Target,
                              ObjectValue(*target));
  return handlerFun;
}

/**
 * Helper for handler functions that "close over" a value that is always a
 * direct reference to an object of class T, never a wrapper.
 */
template <class T>
inline static MOZ_MUST_USE T* TargetFromHandler(CallArgs& args) {
  JSFunction& func = args.callee().as<JSFunction>();
  return &func.getExtendedSlot(StreamHandlerFunctionSlot_Target)
              .toObject()
              .as<T>();
}

inline static MOZ_MUST_USE bool ResetQueue(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedContainer);

inline static MOZ_MUST_USE bool InvokeOrNoop(JSContext* cx, HandleValue O,
                                             HandlePropertyName P,
                                             HandleValue arg,
                                             MutableHandleValue rval);

static MOZ_MUST_USE JSObject* PromiseRejectedWithPendingError(JSContext* cx) {
  RootedValue exn(cx);
  if (!cx->isExceptionPending() || !GetAndClearException(cx, &exn)) {
    // Uncatchable error. This happens when a slow script is killed or a
    // worker is terminated. Propagate the uncatchable error. This will
    // typically kill off the calling asynchronous process: the caller
    // can't hook its continuation to the new rejected promise.
    return nullptr;
  }
  return PromiseObject::unforgeableReject(cx, exn);
}

static MOZ_MUST_USE bool ReturnPromiseRejectedWithPendingError(
    JSContext* cx, const CallArgs& args) {
  JSObject* promise = PromiseRejectedWithPendingError(cx);
  if (!promise) {
    return false;
  }

  args.rval().setObject(*promise);
  return true;
}

/**
 * Creates a NativeObject to be used as a list and stores it on the given
 * container at the given fixed slot offset.
 */
inline static MOZ_MUST_USE bool SetNewList(
    JSContext* cx, HandleNativeObject unwrappedContainer, uint32_t slot) {
  AutoRealm ar(cx, unwrappedContainer);
  ListObject* list = ListObject::create(cx);
  if (!list) {
    return false;
  }
  unwrappedContainer->setFixedSlot(slot, ObjectValue(*list));
  return true;
}

#if 0  // disable user-defined byte streams

class ByteStreamChunk : public NativeObject
{
  private:
    enum Slots {
        Slot_Buffer = 0,
        Slot_ByteOffset,
        Slot_ByteLength,
        SlotCount
    };

  public:
    static const Class class_;

    ArrayBufferObject* buffer() {
        return &getFixedSlot(Slot_Buffer).toObject().as<ArrayBufferObject>();
    }
    uint32_t byteOffset() { return getFixedSlot(Slot_ByteOffset).toInt32(); }
    void SetByteOffset(uint32_t offset) {
        setFixedSlot(Slot_ByteOffset, Int32Value(offset));
    }
    uint32_t byteLength() { return getFixedSlot(Slot_ByteLength).toInt32(); }
    void SetByteLength(uint32_t length) {
        setFixedSlot(Slot_ByteLength, Int32Value(length));
    }

    static ByteStreamChunk* create(JSContext* cx, HandleObject buffer, uint32_t byteOffset,
                                   uint32_t byteLength)
    {
        Rooted<ByteStreamChunk*> chunk(cx, NewBuiltinClassInstance<ByteStreamChunk>(cx));
        if (!chunk) {
            return nullptr;
        }

        chunk->setFixedSlot(Slot_Buffer, ObjectValue(*buffer));
        chunk->setFixedSlot(Slot_ByteOffset, Int32Value(byteOffset));
        chunk->setFixedSlot(Slot_ByteLength, Int32Value(byteLength));
        return chunk;
    }
};

const Class ByteStreamChunk::class_ = {
    "ByteStreamChunk",
    JSCLASS_HAS_RESERVED_SLOTS(SlotCount)
};

#endif  // user-defined byte streams

class PullIntoDescriptor : public NativeObject {
 private:
  enum Slots {
    Slot_buffer,
    Slot_ByteOffset,
    Slot_ByteLength,
    Slot_BytesFilled,
    Slot_ElementSize,
    Slot_Ctor,
    Slot_ReaderType,
    SlotCount
  };

 public:
  static const Class class_;

  ArrayBufferObject* buffer() {
    return &getFixedSlot(Slot_buffer).toObject().as<ArrayBufferObject>();
  }
  void setBuffer(ArrayBufferObject* buffer) {
    setFixedSlot(Slot_buffer, ObjectValue(*buffer));
  }
  JSObject* ctor() { return getFixedSlot(Slot_Ctor).toObjectOrNull(); }
  uint32_t byteOffset() const {
    return getFixedSlot(Slot_ByteOffset).toInt32();
  }
  uint32_t byteLength() const {
    return getFixedSlot(Slot_ByteLength).toInt32();
  }
  uint32_t bytesFilled() const {
    return getFixedSlot(Slot_BytesFilled).toInt32();
  }
  void setBytesFilled(int32_t bytes) {
    setFixedSlot(Slot_BytesFilled, Int32Value(bytes));
  }
  uint32_t elementSize() const {
    return getFixedSlot(Slot_ElementSize).toInt32();
  }
  uint32_t readerType() const {
    return getFixedSlot(Slot_ReaderType).toInt32();
  }

  static PullIntoDescriptor* create(JSContext* cx,
                                    HandleArrayBufferObject buffer,
                                    uint32_t byteOffset, uint32_t byteLength,
                                    uint32_t bytesFilled, uint32_t elementSize,
                                    HandleObject ctor, uint32_t readerType) {
    Rooted<PullIntoDescriptor*> descriptor(
        cx, NewBuiltinClassInstance<PullIntoDescriptor>(cx));
    if (!descriptor) {
      return nullptr;
    }

    descriptor->setFixedSlot(Slot_buffer, ObjectValue(*buffer));
    descriptor->setFixedSlot(Slot_Ctor, ObjectOrNullValue(ctor));
    descriptor->setFixedSlot(Slot_ByteOffset, Int32Value(byteOffset));
    descriptor->setFixedSlot(Slot_ByteLength, Int32Value(byteLength));
    descriptor->setFixedSlot(Slot_BytesFilled, Int32Value(bytesFilled));
    descriptor->setFixedSlot(Slot_ElementSize, Int32Value(elementSize));
    descriptor->setFixedSlot(Slot_ReaderType, Int32Value(readerType));
    return descriptor;
  }
};

const Class PullIntoDescriptor::class_ = {
    "PullIntoDescriptor", JSCLASS_HAS_RESERVED_SLOTS(SlotCount)};

class QueueEntry : public NativeObject {
 private:
  enum Slots { Slot_Value = 0, Slot_Size, SlotCount };

 public:
  static const Class class_;

  Value value() { return getFixedSlot(Slot_Value); }
  double size() { return getFixedSlot(Slot_Size).toNumber(); }

  static QueueEntry* create(JSContext* cx, HandleValue value, double size) {
    Rooted<QueueEntry*> entry(cx, NewBuiltinClassInstance<QueueEntry>(cx));
    if (!entry) {
      return nullptr;
    }

    entry->setFixedSlot(Slot_Value, value);
    entry->setFixedSlot(Slot_Size, NumberValue(size));

    return entry;
  }
};

const Class QueueEntry::class_ = {"QueueEntry",
                                  JSCLASS_HAS_RESERVED_SLOTS(SlotCount)};

/**
 * TeeState objects implement the local variables in Streams spec 3.3.9
 * ReadableStreamTee, which are accessed by several algorithms.
 */
class TeeState : public NativeObject {
 public:
  /**
   * Memory layout for TeeState instances.
   *
   * The Reason1 and Reason2 slots store opaque values, which might be
   * wrapped objects from other compartments. Since we don't treat them as
   * objects in Streams-specific code, we don't have to worry about that
   * apart from ensuring that the values are properly wrapped before storing
   * them.
   *
   * CancelPromise is always created in TeeState::create below, so is
   * guaranteed to be in the same compartment as the TeeState instance
   * itself.
   *
   * Stream can be from another compartment. It is automatically wrapped
   * before storing it and unwrapped upon retrieval. That means that
   * TeeState consumers need to be able to deal with unwrapped
   * ReadableStream instances from non-current compartments.
   *
   * Branch1 and Branch2 are always created in the same compartment as the
   * TeeState instance, so cannot be from another compartment.
   */
  enum Slots {
    Slot_Flags = 0,
    Slot_Reason1,
    Slot_Reason2,
    Slot_CancelPromise,
    Slot_Stream,
    Slot_Branch1,
    Slot_Branch2,
    SlotCount
  };

 private:
  enum Flags {
    Flag_ClosedOrErrored = 1 << 0,
    Flag_Canceled1 = 1 << 1,
    Flag_Canceled2 = 1 << 2,
    Flag_CloneForBranch2 = 1 << 3,
  };
  uint32_t flags() const { return getFixedSlot(Slot_Flags).toInt32(); }
  void setFlags(uint32_t flags) { setFixedSlot(Slot_Flags, Int32Value(flags)); }

 public:
  static const Class class_;

  bool cloneForBranch2() const { return flags() & Flag_CloneForBranch2; }

  bool closedOrErrored() const { return flags() & Flag_ClosedOrErrored; }
  void setClosedOrErrored() {
    MOZ_ASSERT(!(flags() & Flag_ClosedOrErrored));
    setFlags(flags() | Flag_ClosedOrErrored);
  }

  bool canceled1() const { return flags() & Flag_Canceled1; }
  void setCanceled1(HandleValue reason) {
    MOZ_ASSERT(!(flags() & Flag_Canceled1));
    setFlags(flags() | Flag_Canceled1);
    setFixedSlot(Slot_Reason1, reason);
  }

  bool canceled2() const { return flags() & Flag_Canceled2; }
  void setCanceled2(HandleValue reason) {
    MOZ_ASSERT(!(flags() & Flag_Canceled2));
    setFlags(flags() | Flag_Canceled2);
    setFixedSlot(Slot_Reason2, reason);
  }

  Value reason1() const {
    MOZ_ASSERT(canceled1());
    return getFixedSlot(Slot_Reason1);
  }

  Value reason2() const {
    MOZ_ASSERT(canceled2());
    return getFixedSlot(Slot_Reason2);
  }

  PromiseObject* cancelPromise() {
    return &getFixedSlot(Slot_CancelPromise).toObject().as<PromiseObject>();
  }

  ReadableStreamDefaultController* branch1() {
    ReadableStreamDefaultController* controller =
        &getFixedSlot(Slot_Branch1)
             .toObject()
             .as<ReadableStreamDefaultController>();
    MOZ_ASSERT(controller->isTeeBranch1());
    return controller;
  }
  void setBranch1(ReadableStreamDefaultController* controller) {
    MOZ_ASSERT(controller->isTeeBranch1());
    setFixedSlot(Slot_Branch1, ObjectValue(*controller));
  }

  ReadableStreamDefaultController* branch2() {
    ReadableStreamDefaultController* controller =
        &getFixedSlot(Slot_Branch2)
             .toObject()
             .as<ReadableStreamDefaultController>();
    MOZ_ASSERT(controller->isTeeBranch2());
    return controller;
  }
  void setBranch2(ReadableStreamDefaultController* controller) {
    MOZ_ASSERT(controller->isTeeBranch2());
    setFixedSlot(Slot_Branch2, ObjectValue(*controller));
  }

  static TeeState* create(JSContext* cx,
                          Handle<ReadableStream*> unwrappedStream) {
    Rooted<TeeState*> state(cx, NewBuiltinClassInstance<TeeState>(cx));
    if (!state) {
      return nullptr;
    }

    Rooted<PromiseObject*> cancelPromise(
        cx, PromiseObject::createSkippingExecutor(cx));
    if (!cancelPromise) {
      return nullptr;
    }

    state->setFixedSlot(Slot_Flags, Int32Value(0));
    state->setFixedSlot(Slot_CancelPromise, ObjectValue(*cancelPromise));
    RootedObject wrappedStream(cx, unwrappedStream);
    if (!cx->compartment()->wrap(cx, &wrappedStream)) {
      return nullptr;
    }
    state->setFixedSlot(Slot_Stream, ObjectValue(*wrappedStream));

    return state;
  }
};

const Class TeeState::class_ = {"TeeState",
                                JSCLASS_HAS_RESERVED_SLOTS(SlotCount)};

#define CLASS_SPEC(cls, nCtorArgs, nSlots, specFlags, classFlags, classOps) \
  const ClassSpec cls::classSpec_ = {                                       \
      GenericCreateConstructor<cls::constructor, nCtorArgs,                 \
                               gc::AllocKind::FUNCTION>,                    \
      GenericCreatePrototype<cls>,                                          \
      nullptr,                                                              \
      nullptr,                                                              \
      cls##_methods,                                                        \
      cls##_properties,                                                     \
      nullptr,                                                              \
      specFlags};                                                           \
                                                                            \
  const Class cls::class_ = {#cls,                                          \
                             JSCLASS_HAS_RESERVED_SLOTS(nSlots) |           \
                                 JSCLASS_HAS_CACHED_PROTO(JSProto_##cls) |  \
                                 classFlags,                                \
                             classOps, &cls::classSpec_};                   \
                                                                            \
  const Class cls::protoClass_ = {"object",                                 \
                                  JSCLASS_HAS_CACHED_PROTO(JSProto_##cls),  \
                                  JS_NULL_CLASS_OPS, &cls::classSpec_};

/*** 3.2. Class ReadableStream **********************************************/

static MOZ_MUST_USE bool SetUpExternalReadableByteStreamController(
    JSContext* cx, Handle<ReadableStream*> stream,
    JS::ReadableStreamUnderlyingSource* source);

ReadableStream* ReadableStream::createExternalSourceStream(
    JSContext* cx, JS::ReadableStreamUnderlyingSource* source,
    HandleObject proto /* = nullptr */) {
  Rooted<ReadableStream*> stream(cx, create(cx, proto));
  if (!stream) {
    return nullptr;
  }

  if (!SetUpExternalReadableByteStreamController(cx, stream, source)) {
    return nullptr;
  }

  return stream;
}

static MOZ_MUST_USE bool MakeSizeAlgorithmFromSizeFunction(JSContext* cx,
                                                           HandleValue size);

static MOZ_MUST_USE bool ValidateAndNormalizeHighWaterMark(
    JSContext* cx, HandleValue highWaterMarkVal, double* highWaterMark);

static MOZ_MUST_USE bool
SetUpReadableStreamDefaultControllerFromUnderlyingSource(
    JSContext* cx, Handle<ReadableStream*> stream, HandleValue underlyingSource,
    double highWaterMark, HandleValue sizeAlgorithm);

/**
 * Streams spec, 3.2.3. new ReadableStream(underlyingSource = {}, strategy = {})
 */
bool ReadableStream::constructor(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  if (!ThrowIfNotConstructing(cx, args, "ReadableStream")) {
    return false;
  }

  // Implicit in the spec: argument default values.
  RootedValue underlyingSource(cx, args.get(0));
  if (underlyingSource.isUndefined()) {
    JSObject* emptyObj = NewBuiltinClassInstance<PlainObject>(cx);
    if (!emptyObj) {
      return false;
    }
    underlyingSource = ObjectValue(*emptyObj);
  }

  RootedValue strategy(cx, args.get(1));
  if (strategy.isUndefined()) {
    JSObject* emptyObj = NewBuiltinClassInstance<PlainObject>(cx);
    if (!emptyObj) {
      return false;
    }
    strategy = ObjectValue(*emptyObj);
  }

  // Implicit in the spec: Set this to
  //     OrdinaryCreateFromConstructor(NewTarget, ...).
  // Step 1: Perform ! InitializeReadableStream(this).
  RootedObject proto(cx);
  if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_ReadableStream,
                                          &proto)) {
    return false;
  }
  Rooted<ReadableStream*> stream(cx, ReadableStream::create(cx, proto));
  if (!stream) {
    return false;
  }

  // Step 2: Let size be ? GetV(strategy, "size").
  RootedValue size(cx);
  if (!GetProperty(cx, strategy, cx->names().size, &size)) {
    return false;
  }

  // Step 3: Let highWaterMark be ? GetV(strategy, "highWaterMark").
  RootedValue highWaterMarkVal(cx);
  if (!GetProperty(cx, strategy, cx->names().highWaterMark,
                   &highWaterMarkVal)) {
    return false;
  }

  // Step 4: Let type be ? GetV(underlyingSource, "type").
  RootedValue type(cx);
  if (!GetProperty(cx, underlyingSource, cx->names().type, &type)) {
    return false;
  }

  // Step 5: Let typeString be ? ToString(type).
  RootedString typeString(cx, ToString<CanGC>(cx, type));
  if (!typeString) {
    return false;
  }

  // Step 6: If typeString is "bytes",
  bool equal;
  if (!EqualStrings(cx, typeString, cx->names().bytes, &equal)) {
    return false;
  }
  if (equal) {
    // The rest of step 6 is unimplemented, since we don't support
    // user-defined byte streams yet.
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAM_BYTES_TYPE_NOT_IMPLEMENTED);
    return false;
  }

  // Step 7: Otherwise, if type is undefined,
  if (type.isUndefined()) {
    // Step 7.a: Let sizeAlgorithm be ? MakeSizeAlgorithmFromSizeFunction(size).
    if (!MakeSizeAlgorithmFromSizeFunction(cx, size)) {
      return false;
    }

    // Step 7.b: If highWaterMark is undefined, let highWaterMark be 1.
    double highWaterMark;
    if (highWaterMarkVal.isUndefined()) {
      highWaterMark = 1;
    } else {
      // Step 7.c: Set highWaterMark to ?
      // ValidateAndNormalizeHighWaterMark(highWaterMark).
      if (!ValidateAndNormalizeHighWaterMark(cx, highWaterMarkVal,
                                             &highWaterMark)) {
        return false;
      }
    }

    // Step 7.d: Perform
    //           ? SetUpReadableStreamDefaultControllerFromUnderlyingSource(
    //           this, underlyingSource, highWaterMark, sizeAlgorithm).
    if (!SetUpReadableStreamDefaultControllerFromUnderlyingSource(
            cx, stream, underlyingSource, highWaterMark, size)) {
      return false;
    }

    args.rval().setObject(*stream);
    return true;
  }

  // Step 8: Otherwise, throw a RangeError exception.
  JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                            JSMSG_READABLESTREAM_UNDERLYINGSOURCE_TYPE_WRONG);
  return false;
}

/**
 * Streams spec, 3.2.5.1. get locked
 */
static bool ReadableStream_locked(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1: If ! IsReadableStream(this) is false, throw a TypeError exception.
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapAndTypeCheckThis<ReadableStream>(cx, args, "get locked"));
  if (!unwrappedStream) {
    return false;
  }

  // Step 2: Return ! IsReadableStreamLocked(this).
  args.rval().setBoolean(unwrappedStream->locked());
  return true;
}

static MOZ_MUST_USE JSObject* ReadableStreamCancel(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream, HandleValue reason);

/**
 * Streams spec, 3.2.5.2. cancel ( reason )
 */
static MOZ_MUST_USE bool ReadableStream_cancel(JSContext* cx, unsigned argc,
                                               Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1: If ! IsReadableStream(this) is false, return a promise rejected
  //         with a TypeError exception.
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapAndTypeCheckThis<ReadableStream>(cx, args, "cancel"));
  if (!unwrappedStream) {
    return ReturnPromiseRejectedWithPendingError(cx, args);
  }

  // Step 2: If ! IsReadableStreamLocked(this) is true, return a promise
  //         rejected with a TypeError exception.
  if (unwrappedStream->locked()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAM_LOCKED_METHOD, "cancel");
    return ReturnPromiseRejectedWithPendingError(cx, args);
  }

  // Step 3: Return ! ReadableStreamCancel(this, reason).
  RootedObject cancelPromise(
      cx, ::ReadableStreamCancel(cx, unwrappedStream, args.get(0)));
  if (!cancelPromise) {
    return false;
  }
  args.rval().setObject(*cancelPromise);
  return true;
}

static MOZ_MUST_USE ReadableStreamDefaultReader*
CreateReadableStreamDefaultReader(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream,
    ForAuthorCodeBool forAuthorCode = ForAuthorCodeBool::No,
    HandleObject proto = nullptr);

/**
 * Streams spec, 3.2.5.3. getReader({ mode } = {})
 */
static bool ReadableStream_getReader(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Implicit in the spec: Argument defaults and destructuring.
  RootedValue optionsVal(cx, args.get(0));
  if (optionsVal.isUndefined()) {
    JSObject* emptyObj = NewBuiltinClassInstance<PlainObject>(cx);
    if (!emptyObj) {
      return false;
    }
    optionsVal.setObject(*emptyObj);
  }
  RootedValue modeVal(cx);
  if (!GetProperty(cx, optionsVal, cx->names().mode, &modeVal)) {
    return false;
  }

  // Step 1: If ! IsReadableStream(this) is false, throw a TypeError exception.
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapAndTypeCheckThis<ReadableStream>(cx, args, "getReader"));
  if (!unwrappedStream) {
    return false;
  }

  // Step 2: If mode is undefined, return
  //         ? AcquireReadableStreamDefaultReader(this).
  RootedObject reader(cx);
  if (modeVal.isUndefined()) {
    reader = CreateReadableStreamDefaultReader(cx, unwrappedStream,
                                               ForAuthorCodeBool::Yes);
  } else {
    // Step 3: Set mode to ? ToString(mode) (implicit).
    RootedString mode(cx, ToString<CanGC>(cx, modeVal));
    if (!mode) {
      return false;
    }

    // Step 4: If mode is "byob",
    //         return ? AcquireReadableStreamBYOBReader(this).
    bool equal;
    if (!EqualStrings(cx, mode, cx->names().byob, &equal)) {
      return false;
    }
    if (equal) {
      JS_ReportErrorNumberASCII(
          cx, GetErrorMessage, nullptr,
          JSMSG_READABLESTREAM_BYTES_TYPE_NOT_IMPLEMENTED);
      return false;
    }

    // Step 5: Throw a RangeError exception.
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAM_INVALID_READER_MODE);
    return false;
  }

  // Reordered second part of steps 2 and 4.
  if (!reader) {
    return false;
  }
  args.rval().setObject(*reader);
  return true;
}

// Streams spec, 3.2.5.4.
//      pipeThrough({ writable, readable }, options)
//
// Not implemented.

// Streams spec, 3.2.5.5.
//      pipeTo(dest, { preventClose, preventAbort, preventCancel } = {})
//
// Not implemented.

static MOZ_MUST_USE bool ReadableStreamTee(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream,
    bool cloneForBranch2, MutableHandle<ReadableStream*> branch1,
    MutableHandle<ReadableStream*> branch2);

/**
 * Streams spec, 3.2.5.6. tee()
 */
static bool ReadableStream_tee(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1: If ! IsReadableStream(this) is false, throw a TypeError exception.
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapAndTypeCheckThis<ReadableStream>(cx, args, "tee"));
  if (!unwrappedStream) {
    return false;
  }

  // Step 2: Let branches be ? ReadableStreamTee(this, false).
  Rooted<ReadableStream*> branch1(cx);
  Rooted<ReadableStream*> branch2(cx);
  if (!ReadableStreamTee(cx, unwrappedStream, false, &branch1, &branch2)) {
    return false;
  }

  // Step 3: Return ! CreateArrayFromList(branches).
  RootedNativeObject branches(cx, NewDenseFullyAllocatedArray(cx, 2));
  if (!branches) {
    return false;
  }
  branches->setDenseInitializedLength(2);
  branches->initDenseElement(0, ObjectValue(*branch1));
  branches->initDenseElement(1, ObjectValue(*branch2));

  args.rval().setObject(*branches);
  return true;
}

static const JSFunctionSpec ReadableStream_methods[] = {
    JS_FN("cancel", ReadableStream_cancel, 1, 0),
    JS_FN("getReader", ReadableStream_getReader, 0, 0),
    JS_FN("tee", ReadableStream_tee, 0, 0), JS_FS_END};

static const JSPropertySpec ReadableStream_properties[] = {
    JS_PSG("locked", ReadableStream_locked, 0), JS_PS_END};

CLASS_SPEC(ReadableStream, 0, SlotCount, 0, 0, JS_NULL_CLASS_OPS);

/*** 3.3. General readable stream abstract operations ***********************/

// Streams spec, 3.3.1. AcquireReadableStreamBYOBReader ( stream )
// Always inlined.

// Streams spec, 3.3.2. AcquireReadableStreamDefaultReader ( stream )
// Always inlined. See CreateReadableStreamDefaultReader.

/**
 * Characterizes the family of algorithms, (startAlgorithm, pullAlgorithm,
 * cancelAlgorithm), associated with a readable stream.
 *
 * See the comment on SetUpReadableStreamDefaultController().
 */
enum class SourceAlgorithms {
  Script,
  Tee,
};

static MOZ_MUST_USE bool SetUpReadableStreamDefaultController(
    JSContext* cx, Handle<ReadableStream*> stream, SourceAlgorithms algorithms,
    HandleValue underlyingSource, HandleValue pullMethod,
    HandleValue cancelMethod, double highWaterMark, HandleValue size);

/**
 * Streams spec, 3.3.3. CreateReadableStream (
 *                          startAlgorithm, pullAlgorithm, cancelAlgorithm
 *                          [, highWaterMark [, sizeAlgorithm ] ] )
 *
 * The start/pull/cancelAlgorithm arguments are represented instead as four
 * arguments: sourceAlgorithms, underlyingSource, pullMethod, cancelMethod.
 * See the comment on SetUpReadableStreamDefaultController.
 */
MOZ_MUST_USE ReadableStream* CreateReadableStream(
    JSContext* cx, SourceAlgorithms sourceAlgorithms,
    HandleValue underlyingSource, HandleValue pullMethod = UndefinedHandleValue,
    HandleValue cancelMethod = UndefinedHandleValue, double highWaterMark = 1,
    HandleValue sizeAlgorithm = UndefinedHandleValue,
    HandleObject proto = nullptr) {
  cx->check(underlyingSource, sizeAlgorithm, proto);
  MOZ_ASSERT(sizeAlgorithm.isUndefined() || IsCallable(sizeAlgorithm));

  // Step 1: If highWaterMark was not passed, set it to 1 (implicit).
  // Step 2: If sizeAlgorithm was not passed, set it to an algorithm that
  //         returns 1 (implicit).
  // Step 3: Assert: ! IsNonNegativeNumber(highWaterMark) is true.
  MOZ_ASSERT(highWaterMark >= 0);

  // Step 4: Let stream be ObjectCreate(the original value of ReadableStream's
  //         prototype property).
  // Step 5: Perform ! InitializeReadableStream(stream).
  Rooted<ReadableStream*> stream(cx, ReadableStream::create(cx, proto));
  if (!stream) {
    return nullptr;
  }

  // Step 6: Let controller be ObjectCreate(the original value of
  //         ReadableStreamDefaultController's prototype property).
  // Step 7: Perform ? SetUpReadableStreamDefaultController(stream,
  //         controller, startAlgorithm, pullAlgorithm, cancelAlgorithm,
  //         highWaterMark, sizeAlgorithm).
  if (!SetUpReadableStreamDefaultController(
          cx, stream, sourceAlgorithms, underlyingSource, pullMethod,
          cancelMethod, highWaterMark, sizeAlgorithm)) {
    return nullptr;
  }

  // Step 8: Return stream.
  return stream;
}

// Streams spec, 3.3.4. CreateReadableByteStream (
//                          startAlgorithm, pullAlgorithm, cancelAlgorithm
//                          [, highWaterMark [, autoAllocateChunkSize ] ] )
// Not implemented.

/**
 * Streams spec, 3.3.5. InitializeReadableStream ( stream )
 */
MOZ_MUST_USE /* static */
    ReadableStream*
    ReadableStream::create(JSContext* cx, HandleObject proto /* = nullptr */) {
  // In the spec, InitializeReadableStream is always passed a newly created
  // ReadableStream object. We instead create it here and return it below.
  Rooted<ReadableStream*> stream(
      cx, NewObjectWithClassProto<ReadableStream>(cx, proto));
  if (!stream) {
    return nullptr;
  }

  // Step 1: Set stream.[[state]] to "readable".
  stream->initStateBits(Readable);
  MOZ_ASSERT(stream->readable());

  // Step 2: Set stream.[[reader]] and stream.[[storedError]] to
  //         undefined (implicit).
  MOZ_ASSERT(!stream->hasReader());
  MOZ_ASSERT(stream->storedError().isUndefined());

  // Step 3: Set stream.[[disturbed]] to false (done in step 1).
  MOZ_ASSERT(!stream->disturbed());

  return stream;
}

// Streams spec, 3.3.6. IsReadableStream ( x )
// Using UnwrapAndTypeCheck templates instead.

// Streams spec, 3.3.7. IsReadableStreamDisturbed ( stream )
// Using stream->disturbed() instead.

/**
 * Streams spec, 3.3.8. IsReadableStreamLocked ( stream )
 */
bool ReadableStream::locked() const {
  // Step 1: Assert: ! IsReadableStream(stream) is true (implicit).
  // Step 2: If stream.[[reader]] is undefined, return false.
  // Step 3: Return true.
  // Special-casing for streams with external sources. Those can be locked
  // explicitly via JSAPI, which is indicated by a controller flag.
  // IsReadableStreamLocked is called from the controller's constructor, at
  // which point we can't yet call stream->controller(), but the source also
  // can't be locked yet.
  if (hasController() && controller()->sourceLocked()) {
    return true;
  }
  return hasReader();
}

static MOZ_MUST_USE bool ReadableStreamDefaultControllerClose(
    JSContext* cx,
    Handle<ReadableStreamDefaultController*> unwrappedController);

static MOZ_MUST_USE bool ReadableStreamDefaultControllerEnqueue(
    JSContext* cx, Handle<ReadableStreamDefaultController*> unwrappedController,
    HandleValue chunk);

/**
 * Streams spec, 3.3.9. ReadableStreamTee steps 12.a.i-ix.
 */
static bool TeeReaderReadHandler(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<TeeState*> unwrappedTeeState(cx,
                                      UnwrapCalleeSlot<TeeState>(cx, args, 0));
  HandleValue resultVal = args.get(0);

  // Step i: Assert: Type(result) is Object.
  RootedObject result(cx, &resultVal.toObject());

  // Step ii: Let value be ? Get(result, "value").
  // (This can fail only if `result` was nuked.)
  RootedValue value(cx);
  if (!GetProperty(cx, result, result, cx->names().value, &value)) {
    return false;
  }

  // Step iii: Let done be ? Get(result, "done").
  RootedValue doneVal(cx);
  if (!GetProperty(cx, result, result, cx->names().done, &doneVal)) {
    return false;
  }

  // Step iv: Assert: Type(done) is Boolean.
  bool done = doneVal.toBoolean();

  // Step v: If done is true and closedOrErrored is false,
  if (done && !unwrappedTeeState->closedOrErrored()) {
    // Step v.1: If canceled1 is false,
    if (!unwrappedTeeState->canceled1()) {
      // Step v.1.a: Perform ! ReadableStreamDefaultControllerClose(
      //             branch1.[[readableStreamController]]).
      Rooted<ReadableStreamDefaultController*> unwrappedBranch1(
          cx, unwrappedTeeState->branch1());
      if (!ReadableStreamDefaultControllerClose(cx, unwrappedBranch1)) {
        return false;
      }
    }

    // Step v.2: If teeState.[[canceled2]] is false,
    if (!unwrappedTeeState->canceled2()) {
      // Step v.2.a: Perform ! ReadableStreamDefaultControllerClose(
      //             branch2.[[readableStreamController]]).
      Rooted<ReadableStreamDefaultController*> unwrappedBranch2(
          cx, unwrappedTeeState->branch2());
      if (!ReadableStreamDefaultControllerClose(cx, unwrappedBranch2)) {
        return false;
      }
    }

    // Step v.3: Set closedOrErrored to true.
    unwrappedTeeState->setClosedOrErrored();
  }

  // Step vi: If closedOrErrored is true, return.
  if (unwrappedTeeState->closedOrErrored()) {
    return true;
  }

  // Step vii: Let value1 and value2 be value.
  RootedValue value1(cx, value);
  RootedValue value2(cx, value);

  // Step viii: If canceled2 is false and cloneForBranch2 is true,
  //            set value2 to
  //            ? StructuredDeserialize(? StructuredSerialize(value2),
  //                                    the current Realm Record).
  // We don't yet support any specifications that use cloneForBranch2, and
  // the Streams spec doesn't offer any way for author code to enable it,
  // so it's always false here.
  MOZ_ASSERT(!unwrappedTeeState->cloneForBranch2());

  // Step ix: If canceled1 is false, perform
  //          ? ReadableStreamDefaultControllerEnqueue(
  //                branch1.[[readableStreamController]], value1).
  Rooted<ReadableStreamDefaultController*> unwrappedController(cx);
  if (!unwrappedTeeState->canceled1()) {
    unwrappedController = unwrappedTeeState->branch1();
    if (!ReadableStreamDefaultControllerEnqueue(cx, unwrappedController,
                                                value1)) {
      return false;
    }
  }

  // Step x: If canceled2 is false, perform
  //         ? ReadableStreamDefaultControllerEnqueue(
  //               branch2.[[readableStreamController]], value2).
  if (!unwrappedTeeState->canceled2()) {
    unwrappedController = unwrappedTeeState->branch2();
    if (!ReadableStreamDefaultControllerEnqueue(cx, unwrappedController,
                                                value2)) {
      return false;
    }
  }

  args.rval().setUndefined();
  return true;
}

static MOZ_MUST_USE JSObject* ReadableStreamDefaultReaderRead(
    JSContext* cx, Handle<ReadableStreamDefaultReader*> unwrappedReader);

/**
 * Streams spec, 3.3.9. ReadableStreamTee step 12, "Let pullAlgorithm be the
 * following steps:"
 */
static MOZ_MUST_USE JSObject* ReadableStreamTee_Pull(
    JSContext* cx, Handle<TeeState*> unwrappedTeeState) {
  // Implicit in the spec: Unpack the closed-over variables `stream` and
  // `reader` from the TeeState.
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapInternalSlot<ReadableStream>(cx, unwrappedTeeState,
                                             TeeState::Slot_Stream));
  if (!unwrappedStream) {
    return nullptr;
  }
  Rooted<ReadableStreamReader*> unwrappedReaderObj(
      cx, UnwrapReaderFromStream(cx, unwrappedStream));
  if (!unwrappedReaderObj) {
    return nullptr;
  }
  Rooted<ReadableStreamDefaultReader*> unwrappedReader(
      cx, &unwrappedReaderObj->as<ReadableStreamDefaultReader>());

  // Step 12.a: Return the result of transforming
  // ! ReadableStreamDefaultReaderRead(reader) with a fulfillment handler
  // which takes the argument result and performs the following steps:
  //
  // The steps under 12.a are implemented in TeeReaderReadHandler.
  RootedObject readPromise(
      cx, ::ReadableStreamDefaultReaderRead(cx, unwrappedReader));
  if (!readPromise) {
    return nullptr;
  }

  RootedObject teeState(cx, unwrappedTeeState);
  if (!cx->compartment()->wrap(cx, &teeState)) {
    return nullptr;
  }
  RootedObject onFulfilled(cx, NewHandler(cx, TeeReaderReadHandler, teeState));
  if (!onFulfilled) {
    return nullptr;
  }

  return JS::CallOriginalPromiseThen(cx, readPromise, onFulfilled, nullptr);
}

/**
 * Cancel one branch of a tee'd stream with the given |reason_|.
 *
 * Streams spec, 3.3.9. ReadableStreamTee steps 13 and 14: "Let
 * cancel1Algorithm/cancel2Algorithm be the following steps, taking a reason
 * argument:"
 */
static MOZ_MUST_USE JSObject* ReadableStreamTee_Cancel(
    JSContext* cx, Handle<TeeState*> unwrappedTeeState,
    Handle<ReadableStreamDefaultController*> unwrappedBranch,
    HandleValue reason) {
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapInternalSlot<ReadableStream>(cx, unwrappedTeeState,
                                             TeeState::Slot_Stream));
  if (!unwrappedStream) {
    return nullptr;
  }

  bool bothBranchesCanceled = false;

  // Step 13/14.a: Set canceled1/canceled2 to true.
  // Step 13/14.b: Set reason1/reason2 to reason.
  {
    RootedValue unwrappedReason(cx, reason);
    {
      AutoRealm ar(cx, unwrappedTeeState);
      if (!cx->compartment()->wrap(cx, &unwrappedReason)) {
        return nullptr;
      }
    }
    if (unwrappedBranch->isTeeBranch1()) {
      unwrappedTeeState->setCanceled1(unwrappedReason);
      bothBranchesCanceled = unwrappedTeeState->canceled2();
    } else {
      MOZ_ASSERT(unwrappedBranch->isTeeBranch2());
      unwrappedTeeState->setCanceled2(unwrappedReason);
      bothBranchesCanceled = unwrappedTeeState->canceled1();
    }
  }

  // Step 13/14.c: If canceled2/canceled1 is true,
  if (bothBranchesCanceled) {
    // Step 13/14.c.i: Let compositeReason be
    //                 ! CreateArrayFromList(« reason1, reason2 »).
    RootedNativeObject compositeReason(cx, NewDenseFullyAllocatedArray(cx, 2));
    if (!compositeReason) {
      return nullptr;
    }

    compositeReason->setDenseInitializedLength(2);

    RootedValue reason1(cx, unwrappedTeeState->reason1());
    RootedValue reason2(cx, unwrappedTeeState->reason2());
    if (!cx->compartment()->wrap(cx, &reason1) ||
        !cx->compartment()->wrap(cx, &reason2)) {
      return nullptr;
    }
    compositeReason->initDenseElement(0, reason1);
    compositeReason->initDenseElement(1, reason2);
    RootedValue compositeReasonVal(cx, ObjectValue(*compositeReason));

    // Step 13/14.c.ii: Let cancelResult be
    //                  ! ReadableStreamCancel(stream, compositeReason).
    // In our implementation, this can fail with OOM. The best course then
    // is to reject cancelPromise with an OOM error.
    RootedObject cancelResult(
        cx, ::ReadableStreamCancel(cx, unwrappedStream, compositeReasonVal));
    {
      Rooted<PromiseObject*> cancelPromise(cx,
                                           unwrappedTeeState->cancelPromise());
      AutoRealm ar(cx, cancelPromise);

      if (!cancelResult) {
        // Handle the OOM case mentioned above.
        if (!RejectPromiseWithPendingError(cx, cancelPromise)) {
          return nullptr;
        }
      } else {
        // Step 13/14.c.iii: Resolve cancelPromise with cancelResult.
        RootedValue resultVal(cx, ObjectValue(*cancelResult));
        if (!cx->compartment()->wrap(cx, &resultVal)) {
          return nullptr;
        }
        if (!PromiseObject::resolve(cx, cancelPromise, resultVal)) {
          return nullptr;
        }
      }
    }
  }

  // Step 13/14.d: Return cancelPromise.
  RootedObject cancelPromise(cx, unwrappedTeeState->cancelPromise());
  if (!cx->compartment()->wrap(cx, &cancelPromise)) {
    return nullptr;
  }
  return cancelPromise;
}

static MOZ_MUST_USE bool ReadableStreamControllerError(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController,
    HandleValue e);

/**
 * Streams spec, 3.3.9. step 18:
 * Upon rejection of reader.[[closedPromise]] with reason r,
 */
static bool TeeReaderErroredHandler(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<TeeState*> teeState(cx, TargetFromHandler<TeeState>(args));
  HandleValue reason = args.get(0);

  // Step a: If closedOrErrored is false, then:
  if (!teeState->closedOrErrored()) {
    // Step a.iii: Set closedOrErrored to true.
    // Reordered to ensure that internal errors in the other steps don't
    // leave the teeState in an undefined state.
    teeState->setClosedOrErrored();

    // Step a.i: Perform
    //           ! ReadableStreamDefaultControllerError(
    //               branch1.[[readableStreamController]], r).
    Rooted<ReadableStreamDefaultController*> branch1(cx, teeState->branch1());
    if (!ReadableStreamControllerError(cx, branch1, reason)) {
      return false;
    }

    // Step a.ii: Perform
    //            ! ReadableStreamDefaultControllerError(
    //                branch2.[[readableStreamController]], r).
    Rooted<ReadableStreamDefaultController*> branch2(cx, teeState->branch2());
    if (!ReadableStreamControllerError(cx, branch2, reason)) {
      return false;
    }
  }

  args.rval().setUndefined();
  return true;
}

/**
 * Streams spec, 3.3.9. ReadableStreamTee ( stream, cloneForBranch2 )
 */
static MOZ_MUST_USE bool ReadableStreamTee(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream,
    bool cloneForBranch2, MutableHandle<ReadableStream*> branch1Stream,
    MutableHandle<ReadableStream*> branch2Stream) {
  // Step 1: Assert: ! IsReadableStream(stream) is true (implicit).
  // Step 2: Assert: Type(cloneForBranch2) is Boolean (implicit).

  // Step 3: Let reader be ? AcquireReadableStreamDefaultReader(stream).
  Rooted<ReadableStreamDefaultReader*> reader(
      cx, CreateReadableStreamDefaultReader(cx, unwrappedStream));
  if (!reader) {
    return false;
  }

  // Several algorithms close over the variables initialized in the next few
  // steps, so we allocate them in an object, the TeeState. The algorithms
  // also close over `stream` and `reader`, so TeeState gets a reference to
  // the stream.
  //
  // Step 4: Let closedOrErrored be false.
  // Step 5: Let canceled1 be false.
  // Step 6: Let canceled2 be false.
  // Step 7: Let reason1 be undefined.
  // Step 8: Let reason2 be undefined.
  // Step 9: Let branch1 be undefined.
  // Step 10: Let branch2 be undefined.
  // Step 11: Let cancelPromise be a new promise.
  Rooted<TeeState*> teeState(cx, TeeState::create(cx, unwrappedStream));
  if (!teeState) {
    return false;
  }

  // Step 12: Let pullAlgorithm be the following steps: [...]
  // Step 13: Let cancel1Algorithm be the following steps: [...]
  // Step 14: Let cancel2Algorithm be the following steps: [...]
  // Step 15: Let startAlgorithm be an algorithm that returns undefined.
  //
  // Implicit. Our implementation does not use objects to represent
  // [[pullAlgorithm]], [[cancelAlgorithm]], and so on. Instead, we decide
  // which one to perform based on class checks. For example, our
  // implementation of ReadableStreamControllerCallPullIfNeeded checks
  // whether the stream's underlyingSource is a TeeState object.

  // Step 16: Set branch1 to
  //          ! CreateReadableStream(startAlgorithm, pullAlgorithm,
  //                                 cancel1Algorithm).
  RootedValue underlyingSource(cx, ObjectValue(*teeState));
  branch1Stream.set(
      CreateReadableStream(cx, SourceAlgorithms::Tee, underlyingSource));
  if (!branch1Stream) {
    return false;
  }

  Rooted<ReadableStreamDefaultController*> branch1(cx);
  branch1 = &branch1Stream->controller()->as<ReadableStreamDefaultController>();
  branch1->setTeeBranch1();
  teeState->setBranch1(branch1);

  // Step 17: Set branch2 to
  //          ! CreateReadableStream(startAlgorithm, pullAlgorithm,
  //                                 cancel2Algorithm).
  branch2Stream.set(
      CreateReadableStream(cx, SourceAlgorithms::Tee, underlyingSource));
  if (!branch2Stream) {
    return false;
  }

  Rooted<ReadableStreamDefaultController*> branch2(cx);
  branch2 = &branch2Stream->controller()->as<ReadableStreamDefaultController>();
  branch2->setTeeBranch2();
  teeState->setBranch2(branch2);

  // Step 18: Upon rejection of reader.[[closedPromise]] with reason r, [...]
  RootedObject closedPromise(cx, reader->closedPromise());

  RootedObject onRejected(cx,
                          NewHandler(cx, TeeReaderErroredHandler, teeState));
  if (!onRejected) {
    return false;
  }

  if (!JS::AddPromiseReactions(cx, closedPromise, nullptr, onRejected)) {
    return false;
  }

  // Step 19: Return « branch1, branch2 ».
  return true;
}

/*** 3.4. The interface between readable streams and controllers ************/

inline static MOZ_MUST_USE bool AppendToListAtSlot(
    JSContext* cx, HandleNativeObject unwrappedContainer, uint32_t slot,
    HandleObject obj);

/**
 * Streams spec, 3.4.1.
 *      ReadableStreamAddReadIntoRequest ( stream, forAuthorCode )
 * Streams spec, 3.4.2.
 *      ReadableStreamAddReadRequest ( stream, forAuthorCode )
 *
 * Our implementation does not pass around forAuthorCode parameters in the same
 * places as the standard, but the effect is the same. See the comment on
 * `ReadableStreamReader::forAuthorCode()`.
 */
static MOZ_MUST_USE JSObject* ReadableStreamAddReadOrReadIntoRequest(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream) {
  // Step 1: Assert: ! IsReadableStream{BYOB,Default}Reader(stream.[[reader]])
  //         is true.
  // (Only default readers exist so far.)
  Rooted<ReadableStreamReader*> unwrappedReader(
      cx, UnwrapReaderFromStream(cx, unwrappedStream));
  if (!unwrappedReader) {
    return nullptr;
  }
  MOZ_ASSERT(unwrappedReader->is<ReadableStreamDefaultReader>());

  // Step 2 of 3.4.1: Assert: stream.[[state]] is "readable" or "closed".
  // Step 2 of 3.4.2: Assert: stream.[[state]] is "readable".
  MOZ_ASSERT(unwrappedStream->readable() || unwrappedStream->closed());
  MOZ_ASSERT_IF(unwrappedReader->is<ReadableStreamDefaultReader>(),
                unwrappedStream->readable());

  // Step 3: Let promise be a new promise.
  RootedObject promise(cx, PromiseObject::createSkippingExecutor(cx));
  if (!promise) {
    return nullptr;
  }

  // Step 4: Let read{Into}Request be
  //         Record {[[promise]]: promise, [[forAuthorCode]]: forAuthorCode}.
  // Step 5: Append read{Into}Request as the last element of
  //         stream.[[reader]].[[read{Into}Requests]].
  // Since we don't need the [[forAuthorCode]] field (see the comment on
  // `ReadableStreamReader::forAuthorCode()`), we elide the Record and store
  // only the promise.
  if (!AppendToListAtSlot(cx, unwrappedReader,
                          ReadableStreamReader::Slot_Requests, promise)) {
    return nullptr;
  }

  // Step 6: Return promise.
  return promise;
}

static MOZ_MUST_USE JSObject* ReadableStreamControllerCancelSteps(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController,
    HandleValue reason);

/**
 * Used for transforming the result of promise fulfillment/rejection.
 */
static bool ReturnUndefined(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  args.rval().setUndefined();
  return true;
}

MOZ_MUST_USE bool ReadableStreamCloseInternal(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream);

/**
 * Streams spec, 3.4.3. ReadableStreamCancel ( stream, reason )
 */
static MOZ_MUST_USE JSObject* ReadableStreamCancel(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream,
    HandleValue reason) {
  AssertSameCompartment(cx, reason);

  // Step 1: Set stream.[[disturbed]] to true.
  unwrappedStream->setDisturbed();

  // Step 2: If stream.[[state]] is "closed", return a new promise resolved
  //         with undefined.
  if (unwrappedStream->closed()) {
    return PromiseObject::unforgeableResolve(cx, UndefinedHandleValue);
  }

  // Step 3: If stream.[[state]] is "errored", return a new promise rejected
  //         with stream.[[storedError]].
  if (unwrappedStream->errored()) {
    RootedValue storedError(cx, unwrappedStream->storedError());
    if (!cx->compartment()->wrap(cx, &storedError)) {
      return nullptr;
    }
    return PromiseObject::unforgeableReject(cx, storedError);
  }

  // Step 4: Perform ! ReadableStreamClose(stream).
  if (!ReadableStreamCloseInternal(cx, unwrappedStream)) {
    return nullptr;
  }

  // Step 5: Let sourceCancelPromise be
  //         ! stream.[[readableStreamController]].[[CancelSteps]](reason).
  Rooted<ReadableStreamController*> unwrappedController(
      cx, unwrappedStream->controller());
  RootedObject sourceCancelPromise(
      cx, ReadableStreamControllerCancelSteps(cx, unwrappedController, reason));
  if (!sourceCancelPromise) {
    return nullptr;
  }

  // Step 6: Return the result of transforming sourceCancelPromise with a
  //         fulfillment handler that returns undefined.
  HandlePropertyName funName = cx->names().empty;
  RootedFunction returnUndefined(
      cx, NewNativeFunction(cx, ReturnUndefined, 0, funName,
                            gc::AllocKind::FUNCTION, GenericObject));
  if (!returnUndefined) {
    return nullptr;
  }
  return JS::CallOriginalPromiseThen(cx, sourceCancelPromise, returnUndefined,
                                     nullptr);
}

static MOZ_MUST_USE JSObject* ReadableStreamCreateReadResult(
    JSContext* cx, HandleValue value, bool done,
    ForAuthorCodeBool forAuthorCode);

/**
 * Streams spec, 3.4.4. ReadableStreamClose ( stream )
 */
MOZ_MUST_USE bool ReadableStreamCloseInternal(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream) {
  // Step 1: Assert: stream.[[state]] is "readable".
  MOZ_ASSERT(unwrappedStream->readable());

  // Step 2: Set stream.[[state]] to "closed".
  unwrappedStream->setClosed();

  // Step 4: If reader is undefined, return (reordered).
  if (!unwrappedStream->hasReader()) {
    return true;
  }

  // Step 3: Let reader be stream.[[reader]].
  Rooted<ReadableStreamReader*> unwrappedReader(
      cx, UnwrapReaderFromStream(cx, unwrappedStream));
  if (!unwrappedReader) {
    return false;
  }

  // Step 5: If ! IsReadableStreamDefaultReader(reader) is true,
  if (unwrappedReader->is<ReadableStreamDefaultReader>()) {
    ForAuthorCodeBool forAuthorCode = unwrappedReader->forAuthorCode();

    // Step a: Repeat for each readRequest that is an element of
    //         reader.[[readRequests]],
    Rooted<ListObject*> unwrappedReadRequests(cx, unwrappedReader->requests());
    uint32_t len = unwrappedReadRequests->length();
    RootedObject readRequest(cx);
    RootedObject resultObj(cx);
    RootedValue resultVal(cx);
    for (uint32_t i = 0; i < len; i++) {
      // Step i: Resolve readRequest.[[promise]] with
      //         ! ReadableStreamCreateReadResult(undefined, true,
      //                                          readRequest.[[forAuthorCode]]).
      readRequest = &unwrappedReadRequests->getAs<JSObject>(i);
      if (!cx->compartment()->wrap(cx, &readRequest)) {
        return false;
      }

      resultObj = ReadableStreamCreateReadResult(cx, UndefinedHandleValue, true,
                                                 forAuthorCode);
      if (!resultObj) {
        return false;
      }
      resultVal = ObjectValue(*resultObj);
      if (!ResolvePromise(cx, readRequest, resultVal)) {
        return false;
      }
    }

    // Step b: Set reader.[[readRequests]] to an empty List.
    unwrappedReader->clearRequests();
  }

  // Step 6: Resolve reader.[[closedPromise]] with undefined.
  RootedObject closedPromise(cx, unwrappedReader->closedPromise());
  if (!cx->compartment()->wrap(cx, &closedPromise)) {
    return false;
  }
  if (!ResolvePromise(cx, closedPromise, UndefinedHandleValue)) {
    return false;
  }

  if (unwrappedStream->mode() == JS::ReadableStreamMode::ExternalSource) {
    // Make sure we're in the stream's compartment.
    AutoRealm ar(cx, unwrappedStream);
    JS::ReadableStreamUnderlyingSource* source =
        unwrappedStream->controller()->externalSource();
    source->onClosed(cx, unwrappedStream);
  }

  return true;
}

/**
 * Streams spec, 3.4.5. ReadableStreamCreateReadResult ( value, done,
 * forAuthorCode )
 */
static MOZ_MUST_USE JSObject* ReadableStreamCreateReadResult(
    JSContext* cx, HandleValue value, bool done,
    ForAuthorCodeBool forAuthorCode) {
  // Step 1: Let prototype be null.
  // Step 2: If forAuthorCode is true, set prototype to %ObjectPrototype%.
  RootedObject templateObject(
      cx,
      forAuthorCode == ForAuthorCodeBool::Yes
          ? cx->realm()->getOrCreateIterResultTemplateObject(cx)
          : cx->realm()->getOrCreateIterResultWithoutPrototypeTemplateObject(
                cx));
  if (!templateObject) {
    return nullptr;
  }

  // Step 3: Assert: Type(done) is Boolean (implicit).

  // Step 4: Let obj be ObjectCreate(prototype).
  NativeObject* obj;
  JS_TRY_VAR_OR_RETURN_NULL(
      cx, obj,
      NativeObject::createWithTemplate(cx, gc::DefaultHeap, templateObject));

  // Step 5: Perform CreateDataProperty(obj, "value", value).
  obj->setSlot(Realm::IterResultObjectValueSlot, value);

  // Step 6: Perform CreateDataProperty(obj, "done", done).
  obj->setSlot(Realm::IterResultObjectDoneSlot,
               done ? TrueHandleValue : FalseHandleValue);

  // Step 7: Return obj.
  return obj;
}

/**
 * Streams spec, 3.4.6. ReadableStreamError ( stream, e )
 */
MOZ_MUST_USE bool ReadableStreamErrorInternal(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream, HandleValue e) {
  // Step 1: Assert: ! IsReadableStream(stream) is true (implicit).

  // Step 2: Assert: stream.[[state]] is "readable".
  MOZ_ASSERT(unwrappedStream->readable());

  // Step 3: Set stream.[[state]] to "errored".
  unwrappedStream->setErrored();

  // Step 4: Set stream.[[storedError]] to e.
  {
    AutoRealm ar(cx, unwrappedStream);
    RootedValue wrappedError(cx, e);
    if (!cx->compartment()->wrap(cx, &wrappedError)) {
      return false;
    }
    unwrappedStream->setStoredError(wrappedError);
  }

  // Step 6: If reader is undefined, return (reordered).
  if (!unwrappedStream->hasReader()) {
    return true;
  }

  // Step 5: Let reader be stream.[[reader]].
  Rooted<ReadableStreamReader*> unwrappedReader(
      cx, UnwrapReaderFromStream(cx, unwrappedStream));
  if (!unwrappedReader) {
    return false;
  }

  // Steps 7-8: (Identical in our implementation.)
  // Step 7.a/8.b: Repeat for each read{Into}Request that is an element of
  //               reader.[[read{Into}Requests]],
  Rooted<ListObject*> unwrappedReadRequests(cx, unwrappedReader->requests());
  RootedObject readRequest(cx);
  RootedValue val(cx);
  uint32_t len = unwrappedReadRequests->length();
  for (uint32_t i = 0; i < len; i++) {
    // Step i: Reject read{Into}Request.[[promise]] with e.
    val = unwrappedReadRequests->get(i);
    readRequest = &val.toObject();

    // Responses have to be created in the compartment from which the
    // error was triggered, which might not be the same as the one the
    // request was created in, so we have to wrap requests here.
    if (!cx->compartment()->wrap(cx, &readRequest)) {
      return false;
    }

    if (!RejectPromise(cx, readRequest, e)) {
      return false;
    }
  }

  // Step 7.b/8.c: Set reader.[[read{Into}Requests]] to a new empty List.
  if (!SetNewList(cx, unwrappedReader, ReadableStreamReader::Slot_Requests)) {
    return false;
  }

  // Step 9: Reject reader.[[closedPromise]] with e.
  //
  // The closedPromise might have been created in another compartment.
  // RejectPromise can deal with wrapped Promise objects, but all its arguments
  // must be same-compartment with cx, so we do need to wrap the Promise.
  RootedObject closedPromise(cx, unwrappedReader->closedPromise());
  if (!cx->compartment()->wrap(cx, &closedPromise)) {
    return false;
  }
  if (!RejectPromise(cx, closedPromise, e)) {
    return false;
  }

  if (unwrappedStream->mode() == JS::ReadableStreamMode::ExternalSource) {
    // Make sure we're in the stream's compartment.
    AutoRealm ar(cx, unwrappedStream);
    JS::ReadableStreamUnderlyingSource* source =
        unwrappedStream->controller()->externalSource();

    // Ensure that the embedding doesn't have to deal with
    // mixed-compartment arguments to the callback.
    RootedValue error(cx, e);
    if (!cx->compartment()->wrap(cx, &error)) {
      return false;
    }
    source->onErrored(cx, unwrappedStream, error);
  }

  return true;
}

/**
 * Streams spec, 3.4.7.
 *      ReadableStreamFulfillReadIntoRequest( stream, chunk, done )
 * Streams spec, 3.4.8.
 *      ReadableStreamFulfillReadRequest ( stream, chunk, done )
 * These two spec functions are identical in our implementation.
 */
static MOZ_MUST_USE bool ReadableStreamFulfillReadOrReadIntoRequest(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream, HandleValue chunk,
    bool done) {
  cx->check(chunk);

  // Step 1: Let reader be stream.[[reader]].
  Rooted<ReadableStreamReader*> unwrappedReader(
      cx, UnwrapReaderFromStream(cx, unwrappedStream));
  if (!unwrappedReader) {
    return false;
  }

  // Step 2: Let read{Into}Request be the first element of
  //         reader.[[read{Into}Requests]].
  // Step 3: Remove read{Into}Request from reader.[[read{Into}Requests]],
  //         shifting all other elements downward (so that the second becomes
  //         the first, and so on).
  Rooted<ListObject*> unwrappedReadIntoRequests(cx,
                                                unwrappedReader->requests());
  RootedObject readIntoRequest(
      cx, &unwrappedReadIntoRequests->popFirstAs<JSObject>(cx));
  MOZ_ASSERT(readIntoRequest);
  if (!cx->compartment()->wrap(cx, &readIntoRequest)) {
    return false;
  }

  // Step 4: Resolve read{Into}Request.[[promise]] with
  //         ! ReadableStreamCreateReadResult(chunk, done,
  //         readIntoRequest.[[forAuthorCode]]).
  RootedObject iterResult(
      cx, ReadableStreamCreateReadResult(cx, chunk, done,
                                         unwrappedReader->forAuthorCode()));
  if (!iterResult) {
    return false;
  }
  RootedValue val(cx, ObjectValue(*iterResult));
  return ResolvePromise(cx, readIntoRequest, val);
}

/**
 * Streams spec, 3.4.9. ReadableStreamGetNumReadIntoRequests ( stream )
 * Streams spec, 3.4.10. ReadableStreamGetNumReadRequests ( stream )
 * (Identical implementation.)
 */
static uint32_t ReadableStreamGetNumReadRequests(ReadableStream* stream) {
  // Step 1: Return the number of elements in
  //         stream.[[reader]].[[read{Into}Requests]].
  if (!stream->hasReader()) {
    return 0;
  }

  JS::AutoSuppressGCAnalysis nogc;
  ReadableStreamReader* reader = UnwrapReaderFromStreamNoThrow(stream);

  // Reader is a dead wrapper, treat it as non-existent.
  if (!reader) {
    return 0;
  }

  return reader->requests()->length();
}

/**
 * Streams spec 3.4.12. ReadableStreamHasDefaultReader ( stream )
 */
static MOZ_MUST_USE bool ReadableStreamHasDefaultReader(
    JSContext* cx, Handle<ReadableStream*> unwrappedStream, bool* result) {
  // Step 1: Let reader be stream.[[reader]].
  // Step 2: If reader is undefined, return false.
  if (!unwrappedStream->hasReader()) {
    *result = false;
    return true;
  }
  Rooted<ReadableStreamReader*> unwrappedReader(
      cx, UnwrapReaderFromStream(cx, unwrappedStream));
  if (!unwrappedReader) {
    return false;
  }

  // Step 3: If ! ReadableStreamDefaultReader(reader) is false, return false.
  // Step 4: Return true.
  *result = unwrappedReader->is<ReadableStreamDefaultReader>();
  return true;
}

/*** 3.5. Class ReadableStreamDefaultReader *********************************/

static MOZ_MUST_USE bool ReadableStreamReaderGenericInitialize(
    JSContext* cx, Handle<ReadableStreamReader*> reader,
    Handle<ReadableStream*> unwrappedStream, ForAuthorCodeBool forAuthorCode);

/**
 * Stream spec, 3.5.3. new ReadableStreamDefaultReader ( stream )
 * Steps 2-4.
 */
static MOZ_MUST_USE ReadableStreamDefaultReader*
CreateReadableStreamDefaultReader(JSContext* cx,
                                  Handle<ReadableStream*> unwrappedStream,
                                  ForAuthorCodeBool forAuthorCode,
                                  HandleObject proto /* = nullptr */) {
  Rooted<ReadableStreamDefaultReader*> reader(
      cx, NewObjectWithClassProto<ReadableStreamDefaultReader>(cx, proto));
  if (!reader) {
    return nullptr;
  }

  // Step 2: If ! IsReadableStreamLocked(stream) is true, throw a TypeError
  //         exception.
  if (unwrappedStream->locked()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAM_LOCKED);
    return nullptr;
  }

  // Step 3: Perform ! ReadableStreamReaderGenericInitialize(this, stream).
  // Step 4: Set this.[[readRequests]] to a new empty List.
  if (!ReadableStreamReaderGenericInitialize(cx, reader, unwrappedStream,
                                             forAuthorCode)) {
    return nullptr;
  }

  return reader;
}

/**
 * Stream spec, 3.5.3. new ReadableStreamDefaultReader ( stream )
 */
bool ReadableStreamDefaultReader::constructor(JSContext* cx, unsigned argc,
                                              Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  if (!ThrowIfNotConstructing(cx, args, "ReadableStreamDefaultReader")) {
    return false;
  }

  // Implicit in the spec: Find the prototype object to use.
  RootedObject proto(cx);
  if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Null, &proto)) {
    return false;
  }

  // Step 1: If ! IsReadableStream(stream) is false, throw a TypeError
  //         exception.
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapAndTypeCheckArgument<ReadableStream>(
              cx, args, "ReadableStreamDefaultReader constructor", 0));
  if (!unwrappedStream) {
    return false;
  }

  RootedObject reader(
      cx, CreateReadableStreamDefaultReader(cx, unwrappedStream,
                                            ForAuthorCodeBool::Yes, proto));
  if (!reader) {
    return false;
  }

  args.rval().setObject(*reader);
  return true;
}

/**
 * Streams spec, 3.5.4.1 get closed
 */
static MOZ_MUST_USE bool ReadableStreamDefaultReader_closed(JSContext* cx,
                                                            unsigned argc,
                                                            Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1: If ! IsReadableStreamDefaultReader(this) is false, return a promise
  //         rejected with a TypeError exception.
  Rooted<ReadableStreamDefaultReader*> unwrappedReader(
      cx, UnwrapAndTypeCheckThis<ReadableStreamDefaultReader>(cx, args,
                                                              "get closed"));
  if (!unwrappedReader) {
    return ReturnPromiseRejectedWithPendingError(cx, args);
  }

  // Step 2: Return this.[[closedPromise]].
  RootedObject closedPromise(cx, unwrappedReader->closedPromise());
  if (!cx->compartment()->wrap(cx, &closedPromise)) {
    return false;
  }

  args.rval().setObject(*closedPromise);
  return true;
}

static MOZ_MUST_USE JSObject* ReadableStreamReaderGenericCancel(
    JSContext* cx, Handle<ReadableStreamReader*> unwrappedReader,
    HandleValue reason);

/**
 * Streams spec, 3.5.4.2. cancel ( reason )
 */
static MOZ_MUST_USE bool ReadableStreamDefaultReader_cancel(JSContext* cx,
                                                            unsigned argc,
                                                            Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1: If ! IsReadableStreamDefaultReader(this) is false, return a promise
  //         rejected with a TypeError exception.
  Rooted<ReadableStreamDefaultReader*> unwrappedReader(
      cx,
      UnwrapAndTypeCheckThis<ReadableStreamDefaultReader>(cx, args, "cancel"));
  if (!unwrappedReader) {
    return ReturnPromiseRejectedWithPendingError(cx, args);
  }

  // Step 2: If this.[[ownerReadableStream]] is undefined, return a promise
  //         rejected with a TypeError exception.
  if (!unwrappedReader->hasStream()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAMREADER_NOT_OWNED, "cancel");
    return ReturnPromiseRejectedWithPendingError(cx, args);
  }

  // Step 3: Return ! ReadableStreamReaderGenericCancel(this, reason).
  JSObject* cancelPromise =
      ReadableStreamReaderGenericCancel(cx, unwrappedReader, args.get(0));
  if (!cancelPromise) {
    return false;
  }
  args.rval().setObject(*cancelPromise);
  return true;
}

/**
 * Streams spec, 3.5.4.3 read ( )
 */
static MOZ_MUST_USE bool ReadableStreamDefaultReader_read(JSContext* cx,
                                                          unsigned argc,
                                                          Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1: If ! IsReadableStreamDefaultReader(this) is false, return a promise
  //         rejected with a TypeError exception.
  Rooted<ReadableStreamDefaultReader*> unwrappedReader(
      cx,
      UnwrapAndTypeCheckThis<ReadableStreamDefaultReader>(cx, args, "read"));
  if (!unwrappedReader) {
    return ReturnPromiseRejectedWithPendingError(cx, args);
  }

  // Step 2: If this.[[ownerReadableStream]] is undefined, return a promise
  //         rejected with a TypeError exception.
  if (!unwrappedReader->hasStream()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAMREADER_NOT_OWNED, "read");
    return ReturnPromiseRejectedWithPendingError(cx, args);
  }

  // Step 3: Return ! ReadableStreamDefaultReaderRead(this, true).
  JSObject* readPromise =
      ::ReadableStreamDefaultReaderRead(cx, unwrappedReader);
  if (!readPromise) {
    return false;
  }
  args.rval().setObject(*readPromise);
  return true;
}

static MOZ_MUST_USE bool ReadableStreamReaderGenericRelease(
    JSContext* cx, Handle<ReadableStreamReader*> reader);

/**
 * Streams spec, 3.5.4.4. releaseLock ( )
 */
static bool ReadableStreamDefaultReader_releaseLock(JSContext* cx,
                                                    unsigned argc, Value* vp) {
  // Step 1: If ! IsReadableStreamDefaultReader(this) is false,
  //         throw a TypeError exception.
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<ReadableStreamDefaultReader*> reader(
      cx, UnwrapAndTypeCheckThis<ReadableStreamDefaultReader>(cx, args,
                                                              "releaseLock"));
  if (!reader) {
    return false;
  }

  // Step 2: If this.[[ownerReadableStream]] is undefined, return.
  if (!reader->hasStream()) {
    args.rval().setUndefined();
    return true;
  }

  // Step 3: If this.[[readRequests]] is not empty, throw a TypeError exception.
  Value val = reader->getFixedSlot(ReadableStreamReader::Slot_Requests);
  if (!val.isUndefined()) {
    ListObject* readRequests = &val.toObject().as<ListObject>();
    if (readRequests->length() != 0) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_READABLESTREAMREADER_NOT_EMPTY,
                                "releaseLock");
      return false;
    }
  }

  // Step 4: Perform ! ReadableStreamReaderGenericRelease(this).
  if (!ReadableStreamReaderGenericRelease(cx, reader)) {
    return false;
  }

  args.rval().setUndefined();
  return true;
}

static const JSFunctionSpec ReadableStreamDefaultReader_methods[] = {
    JS_FN("cancel", ReadableStreamDefaultReader_cancel, 1, 0),
    JS_FN("read", ReadableStreamDefaultReader_read, 0, 0),
    JS_FN("releaseLock", ReadableStreamDefaultReader_releaseLock, 0, 0),
    JS_FS_END};

static const JSPropertySpec ReadableStreamDefaultReader_properties[] = {
    JS_PSG("closed", ReadableStreamDefaultReader_closed, 0), JS_PS_END};

const Class ReadableStreamReader::class_ = {"ReadableStreamReader"};

CLASS_SPEC(ReadableStreamDefaultReader, 1, SlotCount,
           ClassSpec::DontDefineConstructor, 0, JS_NULL_CLASS_OPS);

/*** 3.7. Readable stream reader abstract operations ************************/

// Streams spec, 3.7.1. IsReadableStreamDefaultReader ( x )
// Implemented via is<ReadableStreamDefaultReader>()

// Streams spec, 3.7.2. IsReadableStreamBYOBReader ( x )
// Implemented via is<ReadableStreamBYOBReader>()

/**
 * Streams spec, 3.7.3. ReadableStreamReaderGenericCancel ( reader, reason )
 */
static MOZ_MUST_USE JSObject* ReadableStreamReaderGenericCancel(
    JSContext* cx, Handle<ReadableStreamReader*> unwrappedReader,
    HandleValue reason) {
  // Step 1: Let stream be reader.[[ownerReadableStream]].
  // Step 2: Assert: stream is not undefined (implicit).
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapStreamFromReader(cx, unwrappedReader));
  if (!unwrappedStream) {
    return nullptr;
  }

  // Step 3: Return ! ReadableStreamCancel(stream, reason).
  return ::ReadableStreamCancel(cx, unwrappedStream, reason);
}

/**
 * Streams spec, 3.7.4.
 *      ReadableStreamReaderGenericInitialize ( reader, stream )
 */
static MOZ_MUST_USE bool ReadableStreamReaderGenericInitialize(
    JSContext* cx, Handle<ReadableStreamReader*> reader,
    Handle<ReadableStream*> unwrappedStream, ForAuthorCodeBool forAuthorCode) {
  cx->check(reader);

  // Step 1: Set reader.[[ownerReadableStream]] to stream.
  {
    RootedObject readerCompartmentStream(cx, unwrappedStream);
    if (!cx->compartment()->wrap(cx, &readerCompartmentStream)) {
      return false;
    }
    reader->setStream(readerCompartmentStream);
  }

  // Step 2 is moved to the end.

  // Step 3: If stream.[[state]] is "readable",
  RootedObject promise(cx);
  if (unwrappedStream->readable()) {
    // Step a: Set reader.[[closedPromise]] to a new promise.
    promise = PromiseObject::createSkippingExecutor(cx);
  } else if (unwrappedStream->closed()) {
    // Step 4: Otherwise, if stream.[[state]] is "closed",
    // Step a: Set reader.[[closedPromise]] to a new promise resolved with
    //         undefined.
    promise = PromiseObject::unforgeableResolve(cx, UndefinedHandleValue);
  } else {
    // Step 5: Otherwise,
    // Step a: Assert: stream.[[state]] is "errored".
    MOZ_ASSERT(unwrappedStream->errored());

    // Step b: Set reader.[[closedPromise]] to a promise rejected with
    //         stream.[[storedError]].
    RootedValue storedError(cx, unwrappedStream->storedError());
    if (!cx->compartment()->wrap(cx, &storedError)) {
      return false;
    }
    promise = PromiseObject::unforgeableReject(cx, storedError);
    if (!promise) {
      return false;
    }

    // Step c. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
    promise->as<PromiseObject>().setHandled();
    cx->runtime()->removeUnhandledRejectedPromise(cx, promise);
  }

  if (!promise) {
    return false;
  }

  reader->setClosedPromise(promise);

  // Extra step not in the standard. See the comment on
  // `ReadableStreamReader::forAuthorCode()`.
  reader->setForAuthorCode(forAuthorCode);

  // Step 4 of caller 3.5.3. new ReadableStreamDefaultReader(stream):
  // Step 5 of caller 3.6.3. new ReadableStreamBYOBReader(stream):
  //     Set this.[[read{Into}Requests]] to a new empty List.
  if (!SetNewList(cx, reader, ReadableStreamReader::Slot_Requests)) {
    return false;
  }

  // Step 2: Set stream.[[reader]] to reader.
  // Doing this last prevents a partially-initialized reader from being
  // attached to the stream (and possibly left there on OOM).
  {
    AutoRealm ar(cx, unwrappedStream);
    RootedObject streamCompartmentReader(cx, reader);
    if (!cx->compartment()->wrap(cx, &streamCompartmentReader)) {
      return false;
    }
    unwrappedStream->setReader(streamCompartmentReader);
  }

  return true;
}

/**
 * Streams spec, 3.7.5. ReadableStreamReaderGenericRelease ( reader )
 */
static MOZ_MUST_USE bool ReadableStreamReaderGenericRelease(
    JSContext* cx, Handle<ReadableStreamReader*> unwrappedReader) {
  // Step 1: Assert: reader.[[ownerReadableStream]] is not undefined.
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapStreamFromReader(cx, unwrappedReader));
  if (!unwrappedStream) {
    return false;
  }

  // Step 2: Assert: reader.[[ownerReadableStream]].[[reader]] is reader.
#ifdef DEBUG
  // The assertion is weakened a bit to allow for nuked wrappers.
  ReadableStreamReader* unwrappedReader2 =
      UnwrapReaderFromStreamNoThrow(unwrappedStream);
  MOZ_ASSERT_IF(unwrappedReader2, unwrappedReader2 == unwrappedReader);
#endif

  // Create an exception to reject promises with below. We don't have a
  // clean way to do this, unfortunately.
  JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                            JSMSG_READABLESTREAMREADER_RELEASED);
  RootedValue exn(cx);
  if (!cx->isExceptionPending() || !GetAndClearException(cx, &exn)) {
    // Uncatchable error. Die immediately without resolving
    // reader.[[closedPromise]].
    return false;
  }

  // Step 3: If reader.[[ownerReadableStream]].[[state]] is "readable", reject
  //         reader.[[closedPromise]] with a TypeError exception.
  Rooted<PromiseObject*> unwrappedClosedPromise(cx);
  if (unwrappedStream->readable()) {
    unwrappedClosedPromise = UnwrapInternalSlot<PromiseObject>(
        cx, unwrappedReader, ReadableStreamReader::Slot_ClosedPromise);
    if (!unwrappedClosedPromise) {
      return false;
    }

    AutoRealm ar(cx, unwrappedClosedPromise);
    if (!cx->compartment()->wrap(cx, &exn)) {
      return false;
    }
    if (!PromiseObject::reject(cx, unwrappedClosedPromise, exn)) {
      return false;
    }
  } else {
    // Step 4: Otherwise, set reader.[[closedPromise]] to a new promise
    //         rejected with a TypeError exception.
    RootedObject closedPromise(cx, PromiseObject::unforgeableReject(cx, exn));
    if (!closedPromise) {
      return false;
    }
    unwrappedClosedPromise = &closedPromise->as<PromiseObject>();

    AutoRealm ar(cx, unwrappedReader);
    if (!cx->compartment()->wrap(cx, &closedPromise)) {
      return false;
    }
    unwrappedReader->setClosedPromise(closedPromise);
  }

  // Step 5: Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  unwrappedClosedPromise->setHandled();
  cx->runtime()->removeUnhandledRejectedPromise(cx, unwrappedClosedPromise);

  // Step 6: Set reader.[[ownerReadableStream]].[[reader]] to undefined.
  unwrappedStream->clearReader();

  // Step 7: Set reader.[[ownerReadableStream]] to undefined.
  unwrappedReader->clearStream();

  return true;
}

static MOZ_MUST_USE JSObject* ReadableStreamControllerPullSteps(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController);

/**
 * Streams spec, 3.7.7.
 *      ReadableStreamDefaultReaderRead ( reader [, forAuthorCode ] )
 */
static MOZ_MUST_USE JSObject* ReadableStreamDefaultReaderRead(
    JSContext* cx, Handle<ReadableStreamDefaultReader*> unwrappedReader) {
  // Step 1: If forAuthorCode was not passed, set it to false (implicit).

  // Step 2: Let stream be reader.[[ownerReadableStream]].
  // Step 3: Assert: stream is not undefined.
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapStreamFromReader(cx, unwrappedReader));
  if (!unwrappedStream) {
    return nullptr;
  }

  // Step 4: Set stream.[[disturbed]] to true.
  unwrappedStream->setDisturbed();

  // Step 5: If stream.[[state]] is "closed", return a promise resolved with
  //         ! ReadableStreamCreateReadResult(undefined, true, forAuthorCode).
  if (unwrappedStream->closed()) {
    RootedObject iterResult(
        cx, ReadableStreamCreateReadResult(cx, UndefinedHandleValue, true,
                                           unwrappedReader->forAuthorCode()));
    if (!iterResult) {
      return nullptr;
    }
    RootedValue iterResultVal(cx, ObjectValue(*iterResult));
    return PromiseObject::unforgeableResolve(cx, iterResultVal);
  }

  // Step 6: If stream.[[state]] is "errored", return a promise rejected
  //         with stream.[[storedError]].
  if (unwrappedStream->errored()) {
    RootedValue storedError(cx, unwrappedStream->storedError());
    if (!cx->compartment()->wrap(cx, &storedError)) {
      return nullptr;
    }
    return PromiseObject::unforgeableReject(cx, storedError);
  }

  // Step 7: Assert: stream.[[state]] is "readable".
  MOZ_ASSERT(unwrappedStream->readable());

  // Step 8: Return ! stream.[[readableStreamController]].[[PullSteps]]().
  Rooted<ReadableStreamController*> unwrappedController(
      cx, unwrappedStream->controller());
  return ReadableStreamControllerPullSteps(cx, unwrappedController);
}

/*** 3.8. Class ReadableStreamDefaultController *****************************/

inline static MOZ_MUST_USE bool ReadableStreamControllerCallPullIfNeeded(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController);

/**
 * Streams spec, 3.9.11. SetUpReadableStreamDefaultController, step 11
 * and
 * Streams spec, 3.12.26. SetUpReadableByteStreamController, step 16:
 *      Upon fulfillment of startPromise, [...]
 */
static bool ControllerStartHandler(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<ReadableStreamController*> controller(
      cx, TargetFromHandler<ReadableStreamController>(args));

  // Step a: Set controller.[[started]] to true.
  controller->setStarted();

  // Step b: Assert: controller.[[pulling]] is false.
  MOZ_ASSERT(!controller->pulling());

  // Step c: Assert: controller.[[pullAgain]] is false.
  MOZ_ASSERT(!controller->pullAgain());

  // Step d: Perform
  //      ! ReadableStreamDefaultControllerCallPullIfNeeded(controller)
  //      (or ReadableByteStreamControllerCallPullIfNeeded(controller)).
  if (!ReadableStreamControllerCallPullIfNeeded(cx, controller)) {
    return false;
  }
  args.rval().setUndefined();
  return true;
}

/**
 * Streams spec, 3.9.11. SetUpReadableStreamDefaultController, step 12
 * and
 * Streams spec, 3.12.26. SetUpReadableByteStreamController, step 17:
 *      Upon rejection of startPromise with reason r, [...]
 */
static bool ControllerStartFailedHandler(JSContext* cx, unsigned argc,
                                         Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<ReadableStreamController*> controller(
      cx, TargetFromHandler<ReadableStreamController>(args));

  // Step a: Perform
  //      ! ReadableStreamDefaultControllerError(controller, r)
  //      (or ReadableByteStreamControllerError(controller, r)).
  if (!ReadableStreamControllerError(cx, controller, args.get(0))) {
    return false;
  }

  args.rval().setUndefined();
  return true;
}

/**
 * Streams spec, 3.8.3.
 * new ReadableStreamDefaultController( stream, underlyingSource, size,
 *                                      highWaterMark )
 */
bool ReadableStreamDefaultController::constructor(JSContext* cx, unsigned argc,
                                                  Value* vp) {
  // Step 1: Throw a TypeError.
  JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                            JSMSG_BOGUS_CONSTRUCTOR,
                            "ReadableStreamDefaultController");
  return false;
}

static MOZ_MUST_USE double ReadableStreamControllerGetDesiredSizeUnchecked(
    ReadableStreamController* controller);

/**
 * Streams spec, 3.8.4.1. get desiredSize
 */
static bool ReadableStreamDefaultController_desiredSize(JSContext* cx,
                                                        unsigned argc,
                                                        Value* vp) {
  // Step 1: If ! IsReadableStreamDefaultController(this) is false, throw a
  //         TypeError exception.
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<ReadableStreamController*> unwrappedController(
      cx, UnwrapAndTypeCheckThis<ReadableStreamDefaultController>(
              cx, args, "get desiredSize"));
  if (!unwrappedController) {
    return false;
  }

  // 3.9.8. ReadableStreamDefaultControllerGetDesiredSize, steps 1-4.
  // 3.9.8. Step 1: Let stream be controller.[[controlledReadableStream]].
  ReadableStream* unwrappedStream = unwrappedController->stream();

  // 3.9.8. Step 2: Let state be stream.[[state]].
  // 3.9.8. Step 3: If state is "errored", return null.
  if (unwrappedStream->errored()) {
    args.rval().setNull();
    return true;
  }

  // 3.9.8. Step 4: If state is "closed", return 0.
  if (unwrappedStream->closed()) {
    args.rval().setInt32(0);
    return true;
  }

  // Step 2: Return ! ReadableStreamDefaultControllerGetDesiredSize(this).
  args.rval().setNumber(
      ReadableStreamControllerGetDesiredSizeUnchecked(unwrappedController));
  return true;
}

static MOZ_MUST_USE bool ReadableStreamDefaultControllerClose(
    JSContext* cx,
    Handle<ReadableStreamDefaultController*> unwrappedController);

/**
 * Unified implementation of step 2 of 3.8.4.2 and 3.8.4.3,
 * and steps 2-3 of 3.10.4.3.
 */
static MOZ_MUST_USE bool CheckReadableStreamControllerCanCloseOrEnqueue(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController,
    const char* action) {
  // 3.8.4.2. close(), step 2, and
  // 3.8.4.3. enqueue(chunk), step 2:
  //      If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is false,
  //      throw a TypeError exception.
  // RSDCCanCloseOrEnqueue returns false in two cases: (1)
  // controller.[[closeRequested]] is true; (2) the stream is not readable,
  // i.e. already closed or errored. This amounts to exactly the same thing as
  // 3.10.4.3 steps 2-3 below, and we want different error messages for the two
  // cases anyway.

  // 3.10.4.3. Step 2: If this.[[closeRequested]] is true, throw a TypeError
  //                   exception.
  if (unwrappedController->closeRequested()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAMCONTROLLER_CLOSED, action);
    return false;
  }

  // 3.10.4.3. Step 3: If this.[[controlledReadableByteStream]].[[state]] is
  //                   not "readable", throw a TypeError exception.
  ReadableStream* unwrappedStream = unwrappedController->stream();
  if (!unwrappedStream->readable()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAMCONTROLLER_NOT_READABLE,
                              action);
    return false;
  }

  return true;
}

/**
 * Streams spec, 3.8.4.2 close()
 */
static bool ReadableStreamDefaultController_close(JSContext* cx, unsigned argc,
                                                  Value* vp) {
  // Step 1: If ! IsReadableStreamDefaultController(this) is false, throw a
  //         TypeError exception.
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<ReadableStreamDefaultController*> unwrappedController(
      cx, UnwrapAndTypeCheckThis<ReadableStreamDefaultController>(cx, args,
                                                                  "close"));
  if (!unwrappedController) {
    return false;
  }

  // Step 2: If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is
  //         false, throw a TypeError exception.
  if (!CheckReadableStreamControllerCanCloseOrEnqueue(cx, unwrappedController,
                                                      "close")) {
    return false;
  }

  // Step 3: Perform ! ReadableStreamDefaultControllerClose(this).
  if (!ReadableStreamDefaultControllerClose(cx, unwrappedController)) {
    return false;
  }

  args.rval().setUndefined();
  return true;
}

/**
 * Streams spec, 3.8.4.3. enqueue ( chunk )
 */
static bool ReadableStreamDefaultController_enqueue(JSContext* cx,
                                                    unsigned argc, Value* vp) {
  // Step 1: If ! IsReadableStreamDefaultController(this) is false, throw a
  //         TypeError exception.
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<ReadableStreamDefaultController*> unwrappedController(
      cx, UnwrapAndTypeCheckThis<ReadableStreamDefaultController>(cx, args,
                                                                  "enqueue"));
  if (!unwrappedController) {
    return false;
  }

  // Step 2: If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is
  //         false, throw a TypeError exception.
  if (!CheckReadableStreamControllerCanCloseOrEnqueue(cx, unwrappedController,
                                                      "enqueue")) {
    return false;
  }

  // Step 3: Return ! ReadableStreamDefaultControllerEnqueue(this, chunk).
  if (!ReadableStreamDefaultControllerEnqueue(cx, unwrappedController,
                                              args.get(0))) {
    return false;
  }
  args.rval().setUndefined();
  return true;
}

/**
 * Streams spec, 3.8.4.4. error ( e )
 */
static bool ReadableStreamDefaultController_error(JSContext* cx, unsigned argc,
                                                  Value* vp) {
  // Step 1: If ! IsReadableStreamDefaultController(this) is false, throw a
  //         TypeError exception.
  CallArgs args = CallArgsFromVp(argc, vp);
  Rooted<ReadableStreamDefaultController*> unwrappedController(
      cx, UnwrapAndTypeCheckThis<ReadableStreamDefaultController>(cx, args,
                                                                  "enqueue"));
  if (!unwrappedController) {
    return false;
  }

  // Step 2: Perform ! ReadableStreamDefaultControllerError(this, e).
  if (!ReadableStreamControllerError(cx, unwrappedController, args.get(0))) {
    return false;
  }

  args.rval().setUndefined();
  return true;
}

static const JSPropertySpec ReadableStreamDefaultController_properties[] = {
    JS_PSG("desiredSize", ReadableStreamDefaultController_desiredSize, 0),
    JS_PS_END};

static const JSFunctionSpec ReadableStreamDefaultController_methods[] = {
    JS_FN("close", ReadableStreamDefaultController_close, 0, 0),
    JS_FN("enqueue", ReadableStreamDefaultController_enqueue, 1, 0),
    JS_FN("error", ReadableStreamDefaultController_error, 1, 0), JS_FS_END};

CLASS_SPEC(ReadableStreamDefaultController, 0, SlotCount,
           ClassSpec::DontDefineConstructor, 0, JS_NULL_CLASS_OPS);

static MOZ_MUST_USE JSObject* PromiseCall(JSContext* cx, HandleValue F,
                                          HandleValue V, HandleValue arg);

static void ReadableStreamControllerClearAlgorithms(
    Handle<ReadableStreamController*> controller);

/**
 * Unified implementation of ReadableStream controllers' [[CancelSteps]]
 * internal methods.
 * Streams spec, 3.8.5.1. [[CancelSteps]] ( reason )
 * and
 * Streams spec, 3.10.5.1. [[CancelSteps]] ( reason )
 */
static MOZ_MUST_USE JSObject* ReadableStreamControllerCancelSteps(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController,
    HandleValue reason) {
  AssertSameCompartment(cx, reason);

  // Step 1 of 3.10.5.1: If this.[[pendingPullIntos]] is not empty,
  if (!unwrappedController->is<ReadableStreamDefaultController>()) {
    Rooted<ListObject*> unwrappedPendingPullIntos(
        cx, unwrappedController->as<ReadableByteStreamController>()
                .pendingPullIntos());

    if (unwrappedPendingPullIntos->length() != 0) {
      // Step a: Let firstDescriptor be the first element of
      //         this.[[pendingPullIntos]].
      PullIntoDescriptor* unwrappedDescriptor =
          UnwrapAndDowncastObject<PullIntoDescriptor>(
              cx, &unwrappedPendingPullIntos->get(0).toObject());
      if (!unwrappedDescriptor) {
        return nullptr;
      }

      // Step b: Set firstDescriptor.[[bytesFilled]] to 0.
      unwrappedDescriptor->setBytesFilled(0);
    }
  }

  RootedValue unwrappedUnderlyingSource(cx);
  unwrappedUnderlyingSource = unwrappedController->underlyingSource();

  // Step 1 of 3.8.5.1, step 2 of 3.10.5.1: Perform ! ResetQueue(this).
  if (!ResetQueue(cx, unwrappedController)) {
    return nullptr;
  }

  // Step 2 of 3.8.5.1, step 3 of 3.10.5.1: Let result be the result of
  //     performing this.[[cancelAlgorithm]], passing reason.
  //
  // Our representation of cancel algorithms is a bit awkward, for
  // performance, so we must figure out which algorithm is being invoked.
  RootedObject result(cx);
  if (IsMaybeWrapped<TeeState>(unwrappedUnderlyingSource)) {
    // The cancel algorithm given in ReadableStreamTee step 13 or 14.
    MOZ_ASSERT(unwrappedUnderlyingSource.toObject().is<TeeState>(),
               "tee streams and controllers are always same-compartment with "
               "the TeeState object");
    Rooted<TeeState*> unwrappedTeeState(
        cx, &unwrappedUnderlyingSource.toObject().as<TeeState>());
    Rooted<ReadableStreamDefaultController*> unwrappedDefaultController(
        cx, &unwrappedController->as<ReadableStreamDefaultController>());
    result = ReadableStreamTee_Cancel(cx, unwrappedTeeState,
                                      unwrappedDefaultController, reason);
  } else if (unwrappedController->hasExternalSource()) {
    // An embedding-provided cancel algorithm.
    RootedValue rval(cx);
    {
      AutoRealm ar(cx, unwrappedController);
      JS::ReadableStreamUnderlyingSource* source =
          unwrappedController->externalSource();
      Rooted<ReadableStream*> stream(cx, unwrappedController->stream());
      RootedValue wrappedReason(cx, reason);
      if (!cx->compartment()->wrap(cx, &wrappedReason)) {
        return nullptr;
      }

      cx->check(stream, wrappedReason);
      rval = source->cancel(cx, stream, wrappedReason);
    }

    // Make sure the ReadableStreamControllerClearAlgorithms call below is
    // reached, even on error.
    if (!cx->compartment()->wrap(cx, &rval)) {
      result = nullptr;
    } else {
      result = PromiseObject::unforgeableResolve(cx, rval);
    }
  } else {
    // The algorithm created in
    // SetUpReadableByteStreamControllerFromUnderlyingSource step 5.
    RootedValue unwrappedCancelMethod(cx, unwrappedController->cancelMethod());
    if (unwrappedCancelMethod.isUndefined()) {
      // CreateAlgorithmFromUnderlyingMethod step 7.
      result = PromiseObject::unforgeableResolve(cx, UndefinedHandleValue);
    } else {
      // CreateAlgorithmFromUnderlyingMethod steps 6.c.i-ii.
      {
        AutoRealm ar(cx, &unwrappedCancelMethod.toObject());
        RootedValue underlyingSource(cx, unwrappedUnderlyingSource);
        if (!cx->compartment()->wrap(cx, &underlyingSource)) {
          return nullptr;
        }
        RootedValue wrappedReason(cx, reason);
        if (!cx->compartment()->wrap(cx, &wrappedReason)) {
          return nullptr;
        }

        // If PromiseCall fails, don't bail out until after the
        // ReadableStreamControllerClearAlgorithms call below.
        result = PromiseCall(cx, unwrappedCancelMethod, underlyingSource,
                             wrappedReason);
      }
      if (!cx->compartment()->wrap(cx, &result)) {
        result = nullptr;
      }
    }
  }

  // Step 3 (or 4): Perform
  //      ! ReadableStreamDefaultControllerClearAlgorithms(this)
  //      (or ReadableByteStreamControllerClearAlgorithms(this)).
  ReadableStreamControllerClearAlgorithms(unwrappedController);

  // Step 4 (or 5): Return result.
  return result;
}

inline static MOZ_MUST_USE bool DequeueValue(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedContainer,
    MutableHandleValue chunk);

/**
 * Streams spec, 3.8.5.2.
 *     ReadableStreamDefaultController [[PullSteps]]( forAuthorCode )
 */
static JSObject* ReadableStreamDefaultControllerPullSteps(
    JSContext* cx,
    Handle<ReadableStreamDefaultController*> unwrappedController) {
  // Step 1: Let stream be this.[[controlledReadableStream]].
  Rooted<ReadableStream*> unwrappedStream(cx, unwrappedController->stream());

  // Step 2: If this.[[queue]] is not empty,
  Rooted<ListObject*> unwrappedQueue(cx);
  RootedValue val(
      cx, unwrappedController->getFixedSlot(StreamController::Slot_Queue));
  if (val.isObject()) {
    unwrappedQueue = &val.toObject().as<ListObject>();
  }

  if (unwrappedQueue && unwrappedQueue->length() != 0) {
    // Step a: Let chunk be ! DequeueValue(this).
    RootedValue chunk(cx);
    if (!DequeueValue(cx, unwrappedController, &chunk)) {
      return nullptr;
    }

    // Step b: If this.[[closeRequested]] is true and this.[[queue]] is empty,
    if (unwrappedController->closeRequested() &&
        unwrappedQueue->length() == 0) {
      // Step i: Perform ! ReadableStreamDefaultControllerClearAlgorithms(this).
      ReadableStreamControllerClearAlgorithms(unwrappedController);

      // Step ii: Perform ! ReadableStreamClose(stream).
      if (!ReadableStreamCloseInternal(cx, unwrappedStream)) {
        return nullptr;
      }
    }

    // Step c: Otherwise, perform
    //         ! ReadableStreamDefaultControllerCallPullIfNeeded(this).
    else {
      if (!ReadableStreamControllerCallPullIfNeeded(cx, unwrappedController)) {
        return nullptr;
      }
    }

    // Step d: Return a promise resolved with
    //         ! ReadableStreamCreateReadResult(chunk, false, forAuthorCode).
    cx->check(chunk);
    ReadableStreamReader* unwrappedReader =
        UnwrapReaderFromStream(cx, unwrappedStream);
    if (!unwrappedReader) {
      return nullptr;
    }
    RootedObject readResultObj(
        cx, ReadableStreamCreateReadResult(cx, chunk, false,
                                           unwrappedReader->forAuthorCode()));
    if (!readResultObj) {
      return nullptr;
    }
    RootedValue readResult(cx, ObjectValue(*readResultObj));
    return PromiseObject::unforgeableResolve(cx, readResult);
  }

  // Step 3: Let pendingPromise be
  //         ! ReadableStreamAddReadRequest(stream, forAuthorCode).
  RootedObject pendingPromise(
      cx, ReadableStreamAddReadOrReadIntoRequest(cx, unwrappedStream));
  if (!pendingPromise) {
    return nullptr;
  }

  // Step 4: Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(this).
  if (!ReadableStreamControllerCallPullIfNeeded(cx, unwrappedController)) {
    return nullptr;
  }

  // Step 5: Return pendingPromise.
  return pendingPromise;
}

/*** 3.9. Readable stream default controller abstract operations ************/

// Streams spec, 3.9.1. IsReadableStreamDefaultController ( x )
// Implemented via is<ReadableStreamDefaultController>()

/**
 * Streams spec, 3.9.2 and 3.12.3. step 7:
 *      Upon fulfillment of pullPromise, [...]
 */
static bool ControllerPullHandler(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  Rooted<ReadableStreamController*> unwrappedController(
      cx, UnwrapCalleeSlot<ReadableStreamController>(cx, args, 0));
  if (!unwrappedController) {
    return false;
  }

  bool pullAgain = unwrappedController->pullAgain();

  // Step a: Set controller.[[pulling]] to false.
  // Step b.i: Set controller.[[pullAgain]] to false.
  unwrappedController->clearPullFlags();

  // Step b: If controller.[[pullAgain]] is true,
  if (pullAgain) {
    // Step ii: Perform
    //          ! ReadableStreamDefaultControllerCallPullIfNeeded(controller)
    //          (or ReadableByteStreamControllerCallPullIfNeeded(controller)).
    if (!ReadableStreamControllerCallPullIfNeeded(cx, unwrappedController)) {
      return false;
    }
  }

  args.rval().setUndefined();
  return true;
}

/**
 * Streams spec, 3.9.2 and 3.12.3. step 8:
 * Upon rejection of pullPromise with reason e,
 */
static bool ControllerPullFailedHandler(JSContext* cx, unsigned argc,
                                        Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  HandleValue e = args.get(0);

  Rooted<ReadableStreamController*> controller(
      cx, UnwrapCalleeSlot<ReadableStreamController>(cx, args, 0));
  if (!controller) {
    return false;
  }

  // Step a: Perform ! ReadableStreamDefaultControllerError(controller, e).
  //         (ReadableByteStreamControllerError in 3.12.3.)
  if (!ReadableStreamControllerError(cx, controller, e)) {
    return false;
  }

  args.rval().setUndefined();
  return true;
}

static bool ReadableStreamControllerShouldCallPull(
    ReadableStreamController* unwrappedController);

static MOZ_MUST_USE double ReadableStreamControllerGetDesiredSizeUnchecked(
    ReadableStreamController* unwrappedController);

/**
 * Streams spec, 3.9.2
 *      ReadableStreamDefaultControllerCallPullIfNeeded ( controller )
 * Streams spec, 3.12.3.
 *      ReadableByteStreamControllerCallPullIfNeeded ( controller )
 */
inline static MOZ_MUST_USE bool ReadableStreamControllerCallPullIfNeeded(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController) {
  // Step 1: Let shouldPull be
  //         ! ReadableStreamDefaultControllerShouldCallPull(controller).
  // (ReadableByteStreamDefaultControllerShouldCallPull in 3.12.3.)
  bool shouldPull = ReadableStreamControllerShouldCallPull(unwrappedController);

  // Step 2: If shouldPull is false, return.
  if (!shouldPull) {
    return true;
  }

  // Step 3: If controller.[[pulling]] is true,
  if (unwrappedController->pulling()) {
    // Step a: Set controller.[[pullAgain]] to true.
    unwrappedController->setPullAgain();

    // Step b: Return.
    return true;
  }

  // Step 4: Assert: controller.[[pullAgain]] is false.
  MOZ_ASSERT(!unwrappedController->pullAgain());

  // Step 5: Set controller.[[pulling]] to true.
  unwrappedController->setPulling();

  // We use this variable in step 7. For ease of error-handling, we wrap it
  // early.
  RootedObject wrappedController(cx, unwrappedController);
  if (!cx->compartment()->wrap(cx, &wrappedController)) {
    return false;
  }

  // Step 6: Let pullPromise be the result of performing
  //         controller.[[pullAlgorithm]].
  // Our representation of pull algorithms is a bit awkward, for performance,
  // so we must figure out which algorithm is being invoked.
  RootedObject pullPromise(cx);
  RootedValue unwrappedUnderlyingSource(
      cx, unwrappedController->underlyingSource());

  if (IsMaybeWrapped<TeeState>(unwrappedUnderlyingSource)) {
    // The pull algorithm given in ReadableStreamTee step 12.
    MOZ_ASSERT(unwrappedUnderlyingSource.toObject().is<TeeState>(),
               "tee streams and controllers are always same-compartment with "
               "the TeeState object");
    Rooted<TeeState*> unwrappedTeeState(
        cx, &unwrappedUnderlyingSource.toObject().as<TeeState>());
    pullPromise = ReadableStreamTee_Pull(cx, unwrappedTeeState);
  } else if (unwrappedController->hasExternalSource()) {
    // An embedding-provided pull algorithm.
    {
      AutoRealm ar(cx, unwrappedController);
      JS::ReadableStreamUnderlyingSource* source =
          unwrappedController->externalSource();
      Rooted<ReadableStream*> stream(cx, unwrappedController->stream());
      double desiredSize =
          ReadableStreamControllerGetDesiredSizeUnchecked(unwrappedController);
      source->requestData(cx, stream, desiredSize);
    }
    pullPromise = PromiseObject::unforgeableResolve(cx, UndefinedHandleValue);
  } else {
    // The pull algorithm created in
    // SetUpReadableStreamDefaultControllerFromUnderlyingSource step 4.
    RootedValue unwrappedPullMethod(cx, unwrappedController->pullMethod());
    if (unwrappedPullMethod.isUndefined()) {
      // CreateAlgorithmFromUnderlyingMethod step 7.
      pullPromise = PromiseObject::unforgeableResolve(cx, UndefinedHandleValue);
    } else {
      // CreateAlgorithmFromUnderlyingMethod step 6.b.i.
      {
        AutoRealm ar(cx, &unwrappedPullMethod.toObject());
        RootedValue underlyingSource(cx, unwrappedUnderlyingSource);
        if (!cx->compartment()->wrap(cx, &underlyingSource)) {
          return false;
        }
        RootedValue controller(cx, ObjectValue(*unwrappedController));
        if (!cx->compartment()->wrap(cx, &controller)) {
          return false;
        }
        pullPromise =
            PromiseCall(cx, unwrappedPullMethod, underlyingSource, controller);
        if (!pullPromise) {
          return false;
        }
      }
      if (!cx->compartment()->wrap(cx, &pullPromise)) {
        return false;
      }
    }
  }
  if (!pullPromise) {
    return false;
  }

  // Step 7: Upon fulfillment of pullPromise, [...]
  // Step 8. Upon rejection of pullPromise with reason e, [...]
  RootedObject onPullFulfilled(
      cx, NewHandler(cx, ControllerPullHandler, wrappedController));
  if (!onPullFulfilled) {
    return false;
  }
  RootedObject onPullRejected(
      cx, NewHandler(cx, ControllerPullFailedHandler, wrappedController));
  if (!onPullRejected) {
    return false;
  }
  return JS::AddPromiseReactions(cx, pullPromise, onPullFulfilled,
                                 onPullRejected);
}

/**
 * Streams spec, 3.9.3.
 *      ReadableStreamDefaultControllerShouldCallPull ( controller )
 * Streams spec, 3.12.25.
 *      ReadableByteStreamControllerShouldCallPull ( controller )
 */
static bool ReadableStreamControllerShouldCallPull(
    ReadableStreamController* unwrappedController) {
  // Step 1: Let stream be controller.[[controlledReadableStream]]
  //         (or [[controlledReadableByteStream]]).
  ReadableStream* unwrappedStream = unwrappedController->stream();

  // 3.9.3. Step 2:
  //      If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)
  //      is false, return false.
  // This turns out to be the same as 3.12.25 steps 2-3.

  // 3.12.25 Step 2: If stream.[[state]] is not "readable", return false.
  if (!unwrappedStream->readable()) {
    return false;
  }

  // 3.12.25 Step 3: If controller.[[closeRequested]] is true, return false.
  if (unwrappedController->closeRequested()) {
    return false;
  }

  // Step 3 (or 4):
  //      If controller.[[started]] is false, return false.
  if (!unwrappedController->started()) {
    return false;
  }

  // 3.9.3.
  // Step 4: If ! IsReadableStreamLocked(stream) is true and
  //      ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  //
  // 3.12.25.
  // Step 5: If ! ReadableStreamHasDefaultReader(stream) is true and
  //         ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  // Step 6: If ! ReadableStreamHasBYOBReader(stream) is true and
  //         ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
  //
  // All of these amount to the same thing in this implementation:
  if (unwrappedStream->locked() &&
      ReadableStreamGetNumReadRequests(unwrappedStream) > 0) {
    return true;
  }

  // Step 5 (or 7):
  //      Let desiredSize be
  //      ! ReadableStreamDefaultControllerGetDesiredSize(controller).
  //      (ReadableByteStreamControllerGetDesiredSize in 3.12.25.)
  double desiredSize =
      ReadableStreamControllerGetDesiredSizeUnchecked(unwrappedController);

  // Step 6 (or 8): Assert: desiredSize is not null (implicit).
  // Step 7 (or 9): If desiredSize > 0, return true.
  // Step 8 (or 10): Return false.
  return desiredSize > 0;
}

/**
 * Streams spec, 3.9.4.
 *      ReadableStreamDefaultControllerClearAlgorithms ( controller )
 * and 3.12.4.
 *      ReadableByteStreamControllerClearAlgorithms ( controller )
 */
static void ReadableStreamControllerClearAlgorithms(
    Handle<ReadableStreamController*> controller) {
  // Step 1: Set controller.[[pullAlgorithm]] to undefined.
  // Step 2: Set controller.[[cancelAlgorithm]] to undefined.
  // (In this implementation, the UnderlyingSource slot is part of the
  // representation of these algorithms.)
  controller->setPullMethod(UndefinedHandleValue);
  controller->setCancelMethod(UndefinedHandleValue);
  ReadableStreamController::clearUnderlyingSource(controller);

  // Step 3 (of 3.9.4 only) : Set controller.[[strategySizeAlgorithm]] to
  // undefined.
  if (controller->is<ReadableStreamDefaultController>()) {
    controller->as<ReadableStreamDefaultController>().setStrategySize(
        UndefinedHandleValue);
  }
}

/**
 * Streams spec, 3.9.5. ReadableStreamDefaultControllerClose ( controller )
 */
static MOZ_MUST_USE bool ReadableStreamDefaultControllerClose(
    JSContext* cx,
    Handle<ReadableStreamDefaultController*> unwrappedController) {
  // Step 1: Let stream be controller.[[controlledReadableStream]].
  Rooted<ReadableStream*> unwrappedStream(cx, unwrappedController->stream());

  // Step 2: Assert:
  //         ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)
  //         is true.
  MOZ_ASSERT(!unwrappedController->closeRequested());
  MOZ_ASSERT(unwrappedStream->readable());

  // Step 3: Set controller.[[closeRequested]] to true.
  unwrappedController->setCloseRequested();

  // Step 4: If controller.[[queue]] is empty,
  Rooted<ListObject*> unwrappedQueue(cx, unwrappedController->queue());
  if (unwrappedQueue->length() == 0) {
    // Step a: Perform
    //         ! ReadableStreamDefaultControllerClearAlgorithms(controller).
    ReadableStreamControllerClearAlgorithms(unwrappedController);

    // Step b: Perform ! ReadableStreamClose(stream).
    return ReadableStreamCloseInternal(cx, unwrappedStream);
  }

  return true;
}

static MOZ_MUST_USE bool EnqueueValueWithSize(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedContainer,
    HandleValue value, HandleValue sizeVal);

/**
 * Streams spec, 3.9.6.
 *      ReadableStreamDefaultControllerEnqueue ( controller, chunk )
 */
static MOZ_MUST_USE bool ReadableStreamDefaultControllerEnqueue(
    JSContext* cx, Handle<ReadableStreamDefaultController*> unwrappedController,
    HandleValue chunk) {
  AssertSameCompartment(cx, chunk);

  // Step 1: Let stream be controller.[[controlledReadableStream]].
  Rooted<ReadableStream*> unwrappedStream(cx, unwrappedController->stream());

  // Step 2: Assert:
  //      ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is
  //      true.
  MOZ_ASSERT(!unwrappedController->closeRequested());
  MOZ_ASSERT(unwrappedStream->readable());

  // Step 3: If ! IsReadableStreamLocked(stream) is true and
  //         ! ReadableStreamGetNumReadRequests(stream) > 0, perform
  //         ! ReadableStreamFulfillReadRequest(stream, chunk, false).
  if (unwrappedStream->locked() &&
      ReadableStreamGetNumReadRequests(unwrappedStream) > 0) {
    if (!ReadableStreamFulfillReadOrReadIntoRequest(cx, unwrappedStream, chunk,
                                                    false)) {
      return false;
    }
  } else {
    // Step 4: Otherwise,
    // Step a: Let result be the result of performing
    //         controller.[[strategySizeAlgorithm]], passing in chunk, and
    //         interpreting the result as an ECMAScript completion value.
    // Step c: (on success) Let chunkSize be result.[[Value]].
    RootedValue chunkSize(cx, NumberValue(1));
    bool success = true;
    RootedValue strategySize(cx, unwrappedController->strategySize());
    if (!strategySize.isUndefined()) {
      if (!cx->compartment()->wrap(cx, &strategySize)) {
        return false;
      }
      success = Call(cx, strategySize, UndefinedHandleValue, chunk, &chunkSize);
    }

    // Step d: Let enqueueResult be
    //         EnqueueValueWithSize(controller, chunk, chunkSize).
    if (success) {
      success = EnqueueValueWithSize(cx, unwrappedController, chunk, chunkSize);
    }

    // Step b: If result is an abrupt completion,
    // and
    // Step e: If enqueueResult is an abrupt completion,
    if (!success) {
      RootedValue exn(cx);
      if (!cx->isExceptionPending() || !GetAndClearException(cx, &exn)) {
        // Uncatchable error. Die immediately without erroring the
        // stream.
        return false;
      }

      // Step b.i: Perform ! ReadableStreamDefaultControllerError(
      //           controller, result.[[Value]]).
      // Step e.i: Perform ! ReadableStreamDefaultControllerError(
      //           controller, enqueueResult.[[Value]]).
      if (!ReadableStreamControllerError(cx, unwrappedController, exn)) {
        return false;
      }

      // Step b.ii: Return result.
      // Step e.ii: Return enqueueResult.
      // (I.e., propagate the exception.)
      cx->setPendingException(exn);
      return false;
    }
  }

  // Step 5: Perform
  //         ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  return ReadableStreamControllerCallPullIfNeeded(cx, unwrappedController);
}

static MOZ_MUST_USE bool ReadableByteStreamControllerClearPendingPullIntos(
    JSContext* cx, Handle<ReadableByteStreamController*> unwrappedController);

/**
 * Streams spec, 3.9.7. ReadableStreamDefaultControllerError ( controller, e )
 * Streams spec, 3.12.11. ReadableByteStreamControllerError ( controller, e )
 */
static MOZ_MUST_USE bool ReadableStreamControllerError(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController,
    HandleValue e) {
  MOZ_ASSERT(!cx->isExceptionPending());
  AssertSameCompartment(cx, e);

  // Step 1: Let stream be controller.[[controlledReadableStream]]
  //         (or controller.[[controlledReadableByteStream]]).
  Rooted<ReadableStream*> unwrappedStream(cx, unwrappedController->stream());

  // Step 2: If stream.[[state]] is not "readable", return.
  if (!unwrappedStream->readable()) {
    return true;
  }

  // Step 3 of 3.12.10:
  // Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
  if (unwrappedController->is<ReadableByteStreamController>()) {
    Rooted<ReadableByteStreamController*> unwrappedByteStreamController(
        cx, &unwrappedController->as<ReadableByteStreamController>());
    if (!ReadableByteStreamControllerClearPendingPullIntos(
            cx, unwrappedByteStreamController)) {
      return false;
    }
  }

  // Step 3 (or 4): Perform ! ResetQueue(controller).
  if (!ResetQueue(cx, unwrappedController)) {
    return false;
  }

  // Step 4 (or 5):
  //      Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller)
  //      (or ReadableByteStreamControllerClearAlgorithms(controller)).
  ReadableStreamControllerClearAlgorithms(unwrappedController);

  // Step 5 (or 6): Perform ! ReadableStreamError(stream, e).
  return ReadableStreamErrorInternal(cx, unwrappedStream, e);
}

/**
 * Streams spec, 3.9.8.
 *      ReadableStreamDefaultControllerGetDesiredSize ( controller )
 * Streams spec 3.12.14.
 *      ReadableByteStreamControllerGetDesiredSize ( controller )
 */
static MOZ_MUST_USE double ReadableStreamControllerGetDesiredSizeUnchecked(
    ReadableStreamController* controller) {
  // Steps 1-4 done at callsites, so only assert that they have been done.
#if DEBUG
  ReadableStream* stream = controller->stream();
  MOZ_ASSERT(!(stream->errored() || stream->closed()));
#endif  // DEBUG

  // Step 5: Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  return controller->strategyHWM() - controller->queueTotalSize();
}

/**
 * Streams spec, 3.9.11.
 *      SetUpReadableStreamDefaultController(stream, controller,
 *          startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark,
 *          sizeAlgorithm )
 *
 * The standard algorithm takes a `controller` argument which must be a new,
 * blank object. This implementation creates a new controller instead.
 *
 * In the spec, three algorithms (startAlgorithm, pullAlgorithm,
 * cancelAlgorithm) are passed as arguments to this routine. This
 * implementation passes these "algorithms" as data, using four arguments:
 * sourceAlgorithms, underlyingSource, pullMethod, and cancelMethod. The
 * sourceAlgorithms argument tells how to interpret the other three:
 *
 * -   SourceAlgorithms::Script - We're creating a stream from a JS source.
 *     The caller is `new ReadableStream(underlyingSource)` or
 *     `JS::NewReadableDefaultStreamObject`. `underlyingSource` is the
 *     source; `pullMethod` and `cancelMethod` are its .pull and
 *     .cancel methods, which the caller has already extracted and
 *     type-checked: each one must be either a callable JS object or undefined.
 *
 *     Script streams use the start/pull/cancel algorithms defined in
 *     3.9.12. SetUpReadableStreamDefaultControllerFromUnderlyingSource, which
 *     call JS methods of the underlyingSource.
 *
 * -   SourceAlgorithms::Tee - We're creating a tee stream. `underlyingSource`
 *     is a TeeState object. `pullMethod` and `cancelMethod` are undefined.
 *
 *     Tee streams use the start/pull/cancel algorithms given in
 *     3.3.9. ReadableStreamTee.
 *
 * Note: All arguments must be same-compartment with cx. ReadableStream
 * controllers are always created in the same compartment as the stream.
 */
static MOZ_MUST_USE bool SetUpReadableStreamDefaultController(
    JSContext* cx, Handle<ReadableStream*> stream,
    SourceAlgorithms sourceAlgorithms, HandleValue underlyingSource,
    HandleValue pullMethod, HandleValue cancelMethod, double highWaterMark,
    HandleValue size) {
  cx->check(stream, underlyingSource, size);
  MOZ_ASSERT(pullMethod.isUndefined() || IsCallable(pullMethod));
  MOZ_ASSERT(cancelMethod.isUndefined() || IsCallable(cancelMethod));
  MOZ_ASSERT_IF(sourceAlgorithms != SourceAlgorithms::Script,
                pullMethod.isUndefined());
  MOZ_ASSERT_IF(sourceAlgorithms != SourceAlgorithms::Script,
                cancelMethod.isUndefined());
  MOZ_ASSERT(highWaterMark >= 0);
  MOZ_ASSERT(size.isUndefined() || IsCallable(size));

  // Done elsewhere in the standard: Create the new controller.
  Rooted<ReadableStreamDefaultController*> controller(
      cx, NewBuiltinClassInstance<ReadableStreamDefaultController>(cx));
  if (!controller) {
    return false;
  }

  // Step 1: Assert: stream.[[readableStreamController]] is undefined.
  MOZ_ASSERT(!stream->hasController());

  // Step 2: Set controller.[[controlledReadableStream]] to stream.
  controller->setStream(stream);

  // Step 3: Set controller.[[queue]] and controller.[[queueTotalSize]] to
  //         undefined (implicit), then perform ! ResetQueue(controller).
  if (!ResetQueue(cx, controller)) {
    return false;
  }

  // Step 4: Set controller.[[started]], controller.[[closeRequested]],
  //         controller.[[pullAgain]], and controller.[[pulling]] to false.
  controller->setFlags(0);

  // Step 5: Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm
  //         and controller.[[strategyHWM]] to highWaterMark.
  controller->setStrategySize(size);
  controller->setStrategyHWM(highWaterMark);

  // Step 6: Set controller.[[pullAlgorithm]] to pullAlgorithm.
  // (In this implementation, the pullAlgorithm is determined by the
  // underlyingSource in combination with the pullMethod field.)
  controller->setUnderlyingSource(underlyingSource);
  controller->setPullMethod(pullMethod);

  // Step 7: Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  controller->setCancelMethod(cancelMethod);

  // Step 8: Set stream.[[readableStreamController]] to controller.
  stream->setController(controller);

  // Step 9: Let startResult be the result of performing startAlgorithm.
  RootedValue startResult(cx);
  if (sourceAlgorithms == SourceAlgorithms::Script) {
    RootedValue controllerVal(cx, ObjectValue(*controller));
    if (!InvokeOrNoop(cx, underlyingSource, cx->names().start, controllerVal,
                      &startResult)) {
      return false;
    }
  }

  // Step 10: Let startPromise be a promise resolved with startResult.
  RootedObject startPromise(cx,
                            PromiseObject::unforgeableResolve(cx, startResult));
  if (!startPromise) {
    return false;
  }

  // Step 11: Upon fulfillment of startPromise, [...]
  // Step 12: Upon rejection of startPromise with reason r, [...]
  RootedObject onStartFulfilled(
      cx, NewHandler(cx, ControllerStartHandler, controller));
  if (!onStartFulfilled) {
    return false;
  }
  RootedObject onStartRejected(
      cx, NewHandler(cx, ControllerStartFailedHandler, controller));
  if (!onStartRejected) {
    return false;
  }
  if (!JS::AddPromiseReactions(cx, startPromise, onStartFulfilled,
                               onStartRejected)) {
    return false;
  }

  return true;
}

static MOZ_MUST_USE bool CreateAlgorithmFromUnderlyingMethod(
    JSContext* cx, HandleValue underlyingObject,
    const char* methodNameForErrorMessage, HandlePropertyName methodName,
    MutableHandleValue method);

/**
 * Streams spec, 3.9.12.
 *      SetUpReadableStreamDefaultControllerFromUnderlyingSource( stream,
 *          underlyingSource, highWaterMark, sizeAlgorithm )
 */
static MOZ_MUST_USE bool
SetUpReadableStreamDefaultControllerFromUnderlyingSource(
    JSContext* cx, Handle<ReadableStream*> stream, HandleValue underlyingSource,
    double highWaterMark, HandleValue sizeAlgorithm) {
  // Step 1: Assert: underlyingSource is not undefined.
  MOZ_ASSERT(!underlyingSource.isUndefined());

  // Step 2: Let controller be ObjectCreate(the original value of
  //         ReadableStreamDefaultController's prototype property).
  // (Deferred to SetUpReadableStreamDefaultController.)

  // Step 3: Let startAlgorithm be the following steps:
  //         a. Return ? InvokeOrNoop(underlyingSource, "start",
  //                                  « controller »).
  SourceAlgorithms sourceAlgorithms = SourceAlgorithms::Script;

  // Step 4: Let pullAlgorithm be
  //         ? CreateAlgorithmFromUnderlyingMethod(underlyingSource, "pull",
  //                                               0, « controller »).
  RootedValue pullMethod(cx);
  if (!CreateAlgorithmFromUnderlyingMethod(cx, underlyingSource,
                                           "ReadableStream source.pull method",
                                           cx->names().pull, &pullMethod)) {
    return false;
  }

  // Step 5. Let cancelAlgorithm be
  //         ? CreateAlgorithmFromUnderlyingMethod(underlyingSource,
  //                                               "cancel", 1, « »).
  RootedValue cancelMethod(cx);
  if (!CreateAlgorithmFromUnderlyingMethod(
          cx, underlyingSource, "ReadableStream source.cancel method",
          cx->names().cancel, &cancelMethod)) {
    return false;
  }

  // Step 6. Perform ? SetUpReadableStreamDefaultController(stream,
  //             controller, startAlgorithm, pullAlgorithm, cancelAlgorithm,
  //             highWaterMark, sizeAlgorithm).
  return SetUpReadableStreamDefaultController(
      cx, stream, sourceAlgorithms, underlyingSource, pullMethod, cancelMethod,
      highWaterMark, sizeAlgorithm);
}

/*** 3.10. Class ReadableByteStreamController *******************************/

#if 0  // disable user-defined byte streams

/**
 * Streams spec, 3.10.3
 *      new ReadableByteStreamController ( stream, underlyingSource,
 *                                         highWaterMark )
 * Steps 3 - 16.
 *
 * Note: All arguments must be same-compartment with cx. ReadableStream
 * controllers are always created in the same compartment as the stream.
 */
static MOZ_MUST_USE ReadableByteStreamController*
CreateReadableByteStreamController(JSContext* cx,
                                   Handle<ReadableStream*> stream,
                                   HandleValue underlyingByteSource,
                                   HandleValue highWaterMarkVal)
{
    cx->check(stream, underlyingByteSource, highWaterMarkVal);

    Rooted<ReadableByteStreamController*> controller(cx,
        NewBuiltinClassInstance<ReadableByteStreamController>(cx));
    if (!controller) {
        return nullptr;
    }

    // Step 3: Set this.[[controlledReadableStream]] to stream.
    controller->setStream(stream);

    // Step 4: Set this.[[underlyingByteSource]] to underlyingByteSource.
    controller->setUnderlyingSource(underlyingByteSource);

    // Step 5: Set this.[[pullAgain]], and this.[[pulling]] to false.
    controller->setFlags(0);

    // Step 6: Perform ! ReadableByteStreamControllerClearPendingPullIntos(this).
    if (!ReadableByteStreamControllerClearPendingPullIntos(cx, controller)) {
        return nullptr;
    }

    // Step 7: Perform ! ResetQueue(this).
    if (!ResetQueue(cx, controller)) {
        return nullptr;
    }

    // Step 8: Set this.[[started]] and this.[[closeRequested]] to false.
    // These should be false by default, unchanged since step 5.
    MOZ_ASSERT(controller->flags() == 0);

    // Step 9: Set this.[[strategyHWM]] to
    //         ? ValidateAndNormalizeHighWaterMark(highWaterMark).
    double highWaterMark;
    if (!ValidateAndNormalizeHighWaterMark(cx, highWaterMarkVal, &highWaterMark)) {
        return nullptr;
    }
    controller->setStrategyHWM(highWaterMark);

    // Step 10: Let autoAllocateChunkSize be
    //          ? GetV(underlyingByteSource, "autoAllocateChunkSize").
    RootedValue autoAllocateChunkSize(cx);
    if (!GetProperty(cx, underlyingByteSource, cx->names().autoAllocateChunkSize,
                     &autoAllocateChunkSize))
    {
        return nullptr;
    }

    // Step 11: If autoAllocateChunkSize is not undefined,
    if (!autoAllocateChunkSize.isUndefined()) {
        // Step a: If ! IsInteger(autoAllocateChunkSize) is false, or if
        //         autoAllocateChunkSize ≤ 0, throw a RangeError exception.
        if (!IsInteger(autoAllocateChunkSize) || autoAllocateChunkSize.toNumber() <= 0) {
            JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                      JSMSG_READABLEBYTESTREAMCONTROLLER_BAD_CHUNKSIZE);
            return nullptr;
        }
    }

    // Step 12: Set this.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
    controller->setAutoAllocateChunkSize(autoAllocateChunkSize);

    // Step 13: Set this.[[pendingPullIntos]] to a new empty List.
    if (!SetNewList(cx, controller, ReadableByteStreamController::Slot_PendingPullIntos)) {
        return nullptr;
    }

    // Step 14: Let controller be this (implicit).

    // Step 15: Let startResult be
    //          ? InvokeOrNoop(underlyingSource, "start", « this »).
    RootedValue startResult(cx);
    RootedValue controllerVal(cx, ObjectValue(*controller));
    if (!InvokeOrNoop(cx, underlyingByteSource, cx->names().start, controllerVal, &startResult)) {
        return nullptr;
    }

    // Step 16: Let startPromise be a promise resolved with startResult:
    RootedObject startPromise(cx, PromiseObject::unforgeableResolve(cx, startResult));
    if (!startPromise) {
        return nullptr;
    }

    RootedObject onStartFulfilled(cx, NewHandler(cx, ControllerStartHandler, controller));
    if (!onStartFulfilled) {
        return nullptr;
    }

    RootedObject onStartRejected(cx, NewHandler(cx, ControllerStartFailedHandler, controller));
    if (!onStartRejected) {
        return nullptr;
    }

    if (!JS::AddPromiseReactions(cx, startPromise, onStartFulfilled, onStartRejected)) {
        return nullptr;
    }

    return controller;
}

#endif  // user-defined byte streams

/**
 * Streams spec, 3.10.3.
 * new ReadableByteStreamController ( stream, underlyingByteSource,
 *                                    highWaterMark )
 */
bool ReadableByteStreamController::constructor(JSContext* cx, unsigned argc,
                                               Value* vp) {
  // Step 1: Throw a TypeError exception.
  JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                            JSMSG_BOGUS_CONSTRUCTOR,
                            "ReadableByteStreamController");
  return false;
}

/**
 * Version of SetUpReadableByteStreamController that's specialized for handling
 * external, embedding-provided, underlying sources.
 */
static MOZ_MUST_USE bool SetUpExternalReadableByteStreamController(
    JSContext* cx, Handle<ReadableStream*> stream,
    JS::ReadableStreamUnderlyingSource* source) {
  // Done elsewhere in the standard: Create the controller object.
  Rooted<ReadableByteStreamController*> controller(
      cx, NewBuiltinClassInstance<ReadableByteStreamController>(cx));
  if (!controller) {
    return false;
  }

  // Step 1: Assert: stream.[[readableStreamController]] is undefined.
  MOZ_ASSERT(!stream->hasController());

  // Step 2: If autoAllocateChunkSize is not undefined, [...]
  // (It's treated as undefined.)

  // Step 3: Set controller.[[controlledReadableByteStream]] to stream.
  controller->setStream(stream);

  // Step 4: Set controller.[[pullAgain]] and controller.[[pulling]] to false.
  controller->setFlags(0);
  MOZ_ASSERT(!controller->pullAgain());
  MOZ_ASSERT(!controller->pulling());

  // Step 5: Perform
  //         ! ReadableByteStreamControllerClearPendingPullIntos(controller).
  // Omitted. This step is apparently redundant; see
  // <https://github.com/whatwg/streams/issues/975>.

  // Step 6: Perform ! ResetQueue(this).
  controller->setQueueTotalSize(0);

  // Step 7: Set controller.[[closeRequested]] and controller.[[started]] to
  //         false (implicit).
  MOZ_ASSERT(!controller->closeRequested());
  MOZ_ASSERT(!controller->started());

  // Step 8: Set controller.[[strategyHWM]] to
  //         ? ValidateAndNormalizeHighWaterMark(highWaterMark).
  controller->setStrategyHWM(0);

  // Step 9: Set controller.[[pullAlgorithm]] to pullAlgorithm.
  // Step 10: Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  // (These algorithms are given by source's virtual methods.)
  controller->setExternalSource(source);

  // Step 11: Set controller.[[autoAllocateChunkSize]] to
  //          autoAllocateChunkSize (implicit).
  MOZ_ASSERT(controller->autoAllocateChunkSize().isUndefined());

  // Step 12: Set this.[[pendingPullIntos]] to a new empty List.
  if (!SetNewList(cx, controller,
                  ReadableByteStreamController::Slot_PendingPullIntos)) {
    return false;
  }

  // Step 13: Set stream.[[readableStreamController]] to controller.
  stream->setController(controller);

  // Step 14: Let startResult be the result of performing startAlgorithm.
  // (For external sources, this algorithm does nothing and returns undefined.)
  // Step 15: Let startPromise be a promise resolved with startResult.
  RootedObject startPromise(
      cx, PromiseObject::unforgeableResolve(cx, UndefinedHandleValue));
  if (!startPromise) {
    return false;
  }

  // Step 16: Upon fulfillment of startPromise, [...]
  // Step 17: Upon rejection of startPromise with reason r, [...]
  RootedObject onStartFulfilled(
      cx, NewHandler(cx, ControllerStartHandler, controller));
  if (!onStartFulfilled) {
    return false;
  }
  RootedObject onStartRejected(
      cx, NewHandler(cx, ControllerStartFailedHandler, controller));
  if (!onStartRejected) {
    return false;
  }
  if (!JS::AddPromiseReactions(cx, startPromise, onStartFulfilled,
                               onStartRejected)) {
    return false;
  }

  return true;
}

static const JSPropertySpec ReadableByteStreamController_properties[] = {
    JS_PS_END};

static const JSFunctionSpec ReadableByteStreamController_methods[] = {
    JS_FS_END};

static void ReadableByteStreamControllerFinalize(FreeOp* fop, JSObject* obj) {
  ReadableByteStreamController& controller =
      obj->as<ReadableByteStreamController>();

  if (controller.getFixedSlot(ReadableStreamController::Slot_Flags)
          .isUndefined()) {
    return;
  }

  if (!controller.hasExternalSource()) {
    return;
  }

  controller.externalSource()->finalize();
}

static const ClassOps ReadableByteStreamControllerClassOps = {
    nullptr, /* addProperty */
    nullptr, /* delProperty */
    nullptr, /* enumerate */
    nullptr, /* newEnumerate */
    nullptr, /* resolve */
    nullptr, /* mayResolve */
    ReadableByteStreamControllerFinalize,
    nullptr, /* call        */
    nullptr, /* hasInstance */
    nullptr, /* construct   */
    nullptr, /* trace   */
};

CLASS_SPEC(ReadableByteStreamController, 0, SlotCount,
           ClassSpec::DontDefineConstructor, JSCLASS_BACKGROUND_FINALIZE,
           &ReadableByteStreamControllerClassOps);

// Streams spec, 3.10.5.1. [[CancelSteps]] ()
// Unified with 3.8.5.1 above.

static MOZ_MUST_USE bool ReadableByteStreamControllerHandleQueueDrain(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController);

/**
 * Streams spec, 3.10.5.2. [[PullSteps]] ( forAuthorCode )
 */
static MOZ_MUST_USE JSObject* ReadableByteStreamControllerPullSteps(
    JSContext* cx, Handle<ReadableByteStreamController*> unwrappedController) {
  // Step 1: Let stream be this.[[controlledReadableByteStream]].
  Rooted<ReadableStream*> unwrappedStream(cx, unwrappedController->stream());

  // Step 2: Assert: ! ReadableStreamHasDefaultReader(stream) is true.
#ifdef DEBUG
  bool result;
  if (!ReadableStreamHasDefaultReader(cx, unwrappedStream, &result)) {
    return nullptr;
  }
  MOZ_ASSERT(result);
#endif

  RootedValue val(cx);
  // Step 3: If this.[[queueTotalSize]] > 0,
  double queueTotalSize = unwrappedController->queueTotalSize();
  if (queueTotalSize > 0) {
    // Step 3.a: Assert: ! ReadableStreamGetNumReadRequests(_stream_) is 0.
    MOZ_ASSERT(ReadableStreamGetNumReadRequests(unwrappedStream) == 0);

    RootedObject view(cx);

    MOZ_RELEASE_ASSERT(unwrappedStream->mode() ==
                       JS::ReadableStreamMode::ExternalSource);
#if 0   // disable user-defined byte streams
        if (unwrappedStream->mode() == JS::ReadableStreamMode::ExternalSource)
#endif  // user-defined byte streams
    {
      JS::ReadableStreamUnderlyingSource* source =
          unwrappedController->externalSource();

      view = JS_NewUint8Array(cx, queueTotalSize);
      if (!view) {
        return nullptr;
      }

      size_t bytesWritten;
      {
        AutoRealm ar(cx, unwrappedStream);
        JS::AutoSuppressGCAnalysis suppressGC(cx);
        JS::AutoCheckCannotGC noGC;
        bool dummy;
        void* buffer = JS_GetArrayBufferViewData(view, &dummy, noGC);

        source->writeIntoReadRequestBuffer(cx, unwrappedStream, buffer,
                                           queueTotalSize, &bytesWritten);
      }

      queueTotalSize = queueTotalSize - bytesWritten;
    }

#if 0   // disable user-defined byte streams
        else {
            // Step 3.b: Let entry be the first element of this.[[queue]].
            // Step 3.c: Remove entry from this.[[queue]], shifting all other
            //           elements downward (so that the second becomes the
            //           first, and so on).
            Rooted<ListObject*> unwrappedQueue(cx, unwrappedController->queue());
            Rooted<ByteStreamChunk*> unwrappedEntry(cx,
                UnwrapAndDowncastObject<ByteStreamChunk>(
                    cx, &unwrappedQueue->popFirstAs<JSObject>(cx)));
            if (!unwrappedEntry) {
                return nullptr;
            }

            queueTotalSize = queueTotalSize - unwrappedEntry->byteLength();

            // Step 3.f: Let view be ! Construct(%Uint8Array%,
            //                                   « entry.[[buffer]],
            //                                     entry.[[byteOffset]],
            //                                     entry.[[byteLength]] »).
            // (reordered)
            RootedObject buffer(cx, unwrappedEntry->buffer());
            if (!cx->compartment()->wrap(cx, &buffer)) {
                return nullptr;
            }

            uint32_t byteOffset = unwrappedEntry->byteOffset();
            view = JS_NewUint8ArrayWithBuffer(cx, buffer, byteOffset, unwrappedEntry->byteLength());
            if (!view) {
                return nullptr;
            }
        }
#endif  // user-defined byte streams

    // Step 3.d: Set this.[[queueTotalSize]] to
    //           this.[[queueTotalSize]] − entry.[[byteLength]].
    // (reordered)
    unwrappedController->setQueueTotalSize(queueTotalSize);

    // Step 3.e: Perform ! ReadableByteStreamControllerHandleQueueDrain(this).
    // (reordered)
    if (!ReadableByteStreamControllerHandleQueueDrain(cx,
                                                      unwrappedController)) {
      return nullptr;
    }

    // Step 3.g: Return a promise resolved with
    //           ! ReadableStreamCreateReadResult(view, false, forAuthorCode).
    val.setObject(*view);
    ReadableStreamReader* unwrappedReader =
        UnwrapReaderFromStream(cx, unwrappedStream);
    if (!unwrappedReader) {
      return nullptr;
    }
    RootedObject readResult(
        cx, ReadableStreamCreateReadResult(cx, val, false,
                                           unwrappedReader->forAuthorCode()));
    if (!readResult) {
      return nullptr;
    }
    val.setObject(*readResult);

    return PromiseObject::unforgeableResolve(cx, val);
  }

  // Step 4: Let autoAllocateChunkSize be this.[[autoAllocateChunkSize]].
  val = unwrappedController->autoAllocateChunkSize();

  // Step 5: If autoAllocateChunkSize is not undefined,
  if (!val.isUndefined()) {
    double autoAllocateChunkSize = val.toNumber();

    // Step 5.a: Let buffer be
    //           Construct(%ArrayBuffer%, « autoAllocateChunkSize »).
    JSObject* bufferObj = JS::NewArrayBuffer(cx, autoAllocateChunkSize);

    // Step 5.b: If buffer is an abrupt completion,
    //           return a promise rejected with buffer.[[Value]].
    if (!bufferObj) {
      return PromiseRejectedWithPendingError(cx);
    }

    RootedArrayBufferObject buffer(cx, &bufferObj->as<ArrayBufferObject>());

    // Step 5.c: Let pullIntoDescriptor be
    //           Record {[[buffer]]: buffer.[[Value]],
    //                   [[byteOffset]]: 0,
    //                   [[byteLength]]: autoAllocateChunkSize,
    //                   [[bytesFilled]]: 0,
    //                   [[elementSize]]: 1,
    //                   [[ctor]]: %Uint8Array%,
    //                   [[readerType]]: `"default"`}.
    RootedObject pullIntoDescriptor(
        cx, PullIntoDescriptor::create(cx, buffer, 0, autoAllocateChunkSize, 0,
                                       1, nullptr, ReaderType_Default));
    if (!pullIntoDescriptor) {
      return PromiseRejectedWithPendingError(cx);
    }

    // Step 5.d: Append pullIntoDescriptor as the last element of
    //           this.[[pendingPullIntos]].
    if (!AppendToListAtSlot(cx, unwrappedController,
                            ReadableByteStreamController::Slot_PendingPullIntos,
                            pullIntoDescriptor)) {
      return nullptr;
    }
  }

  // Step 6: Let promise be ! ReadableStreamAddReadRequest(stream,
  //                                                       forAuthorCode).
  RootedObject promise(
      cx, ReadableStreamAddReadOrReadIntoRequest(cx, unwrappedStream));
  if (!promise) {
    return nullptr;
  }

  // Step 7: Perform ! ReadableByteStreamControllerCallPullIfNeeded(this).
  if (!ReadableStreamControllerCallPullIfNeeded(cx, unwrappedController)) {
    return nullptr;
  }

  // Step 8: Return promise.
  return promise;
}

/**
 * Unified implementation of ReadableStream controllers' [[PullSteps]] internal
 * methods.
 * Streams spec, 3.8.5.2. [[PullSteps]] ( forAuthorCode )
 * and
 * Streams spec, 3.10.5.2. [[PullSteps]] ( forAuthorCode )
 */
static MOZ_MUST_USE JSObject* ReadableStreamControllerPullSteps(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController) {
  if (unwrappedController->is<ReadableStreamDefaultController>()) {
    Rooted<ReadableStreamDefaultController*> unwrappedDefaultController(
        cx, &unwrappedController->as<ReadableStreamDefaultController>());
    return ReadableStreamDefaultControllerPullSteps(cx,
                                                    unwrappedDefaultController);
  }

  Rooted<ReadableByteStreamController*> unwrappedByteController(
      cx, &unwrappedController->as<ReadableByteStreamController>());
  return ReadableByteStreamControllerPullSteps(cx, unwrappedByteController);
}

/*** 3.12. Readable stream BYOB controller abstract operations **************/

// Streams spec, 3.12.1. IsReadableStreamBYOBRequest ( x )
// Implemented via is<ReadableStreamBYOBRequest>()

// Streams spec, 3.12.2. IsReadableByteStreamController ( x )
// Implemented via is<ReadableByteStreamController>()

// Streams spec, 3.12.3.
//      ReadableByteStreamControllerCallPullIfNeeded ( controller )
// Unified with 3.9.2 above.

static MOZ_MUST_USE bool ReadableByteStreamControllerInvalidateBYOBRequest(
    JSContext* cx, Handle<ReadableByteStreamController*> unwrappedController);

/**
 * Streams spec, 3.12.5.
 *      ReadableByteStreamControllerClearPendingPullIntos ( controller )
 */
static MOZ_MUST_USE bool ReadableByteStreamControllerClearPendingPullIntos(
    JSContext* cx, Handle<ReadableByteStreamController*> unwrappedController) {
  // Step 1: Perform
  //         ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
  if (!ReadableByteStreamControllerInvalidateBYOBRequest(cx,
                                                         unwrappedController)) {
    return false;
  }

  // Step 2: Set controller.[[pendingPullIntos]] to a new empty List.
  return SetNewList(cx, unwrappedController,
                    ReadableByteStreamController::Slot_PendingPullIntos);
}

/**
 * Streams spec, 3.12.6. ReadableByteStreamControllerClose ( controller )
 */
static MOZ_MUST_USE bool ReadableByteStreamControllerClose(
    JSContext* cx, Handle<ReadableByteStreamController*> unwrappedController) {
  // Step 1: Let stream be controller.[[controlledReadableByteStream]].
  Rooted<ReadableStream*> unwrappedStream(cx, unwrappedController->stream());

  // Step 2: Assert: controller.[[closeRequested]] is false.
  MOZ_ASSERT(!unwrappedController->closeRequested());

  // Step 3: Assert: stream.[[state]] is "readable".
  MOZ_ASSERT(unwrappedStream->readable());

  // Step 4: If controller.[[queueTotalSize]] > 0,
  if (unwrappedController->queueTotalSize() > 0) {
    // Step a: Set controller.[[closeRequested]] to true.
    unwrappedController->setCloseRequested();

    // Step b: Return.
    return true;
  }

  // Step 5: If controller.[[pendingPullIntos]] is not empty,
  Rooted<ListObject*> unwrappedPendingPullIntos(
      cx, unwrappedController->pendingPullIntos());
  if (unwrappedPendingPullIntos->length() != 0) {
    // Step a: Let firstPendingPullInto be the first element of
    //         controller.[[pendingPullIntos]].
    Rooted<PullIntoDescriptor*> unwrappedFirstPendingPullInto(
        cx, UnwrapAndDowncastObject<PullIntoDescriptor>(
                cx, &unwrappedPendingPullIntos->get(0).toObject()));
    if (!unwrappedFirstPendingPullInto) {
      return false;
    }

    // Step b: If firstPendingPullInto.[[bytesFilled]] > 0,
    if (unwrappedFirstPendingPullInto->bytesFilled() > 0) {
      // Step i: Let e be a new TypeError exception.
      JS_ReportErrorNumberASCII(
          cx, GetErrorMessage, nullptr,
          JSMSG_READABLEBYTESTREAMCONTROLLER_CLOSE_PENDING_PULL);
      RootedValue e(cx);
      if (!cx->isExceptionPending() || !GetAndClearException(cx, &e)) {
        // Uncatchable error. Die immediately without erroring the
        // stream.
        return false;
      }

      // Step ii: Perform ! ReadableByteStreamControllerError(controller, e).
      if (!ReadableStreamControllerError(cx, unwrappedController, e)) {
        return false;
      }

      // Step iii: Throw e.
      cx->setPendingException(e);
      return false;
    }
  }

  // Step 6: Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
  ReadableStreamControllerClearAlgorithms(unwrappedController);

  // Step 7: Perform ! ReadableStreamClose(stream).
  return ReadableStreamCloseInternal(cx, unwrappedStream);
}

// Streams spec, 3.12.11. ReadableByteStreamControllerError ( controller, e )
// Unified with 3.9.7 above.

// Streams spec 3.12.14.
//      ReadableByteStreamControllerGetDesiredSize ( controller )
// Unified with 3.9.8 above.

/**
 * Streams spec, 3.12.15.
 *      ReadableByteStreamControllerHandleQueueDrain ( controller )
 */
static MOZ_MUST_USE bool ReadableByteStreamControllerHandleQueueDrain(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedController) {
  MOZ_ASSERT(unwrappedController->is<ReadableByteStreamController>());

  // Step 1: Assert: controller.[[controlledReadableStream]].[[state]]
  //                 is "readable".
  Rooted<ReadableStream*> unwrappedStream(cx, unwrappedController->stream());
  MOZ_ASSERT(unwrappedStream->readable());

  // Step 2: If controller.[[queueTotalSize]] is 0 and
  //         controller.[[closeRequested]] is true,
  if (unwrappedController->queueTotalSize() == 0 &&
      unwrappedController->closeRequested()) {
    // Step a: Perform
    //         ! ReadableByteStreamControllerClearAlgorithms(controller).
    ReadableStreamControllerClearAlgorithms(unwrappedController);

    // Step b: Perform
    //         ! ReadableStreamClose(controller.[[controlledReadableStream]]).
    return ReadableStreamCloseInternal(cx, unwrappedStream);
  }

  // Step 3: Otherwise,
  // Step a: Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
  return ReadableStreamControllerCallPullIfNeeded(cx, unwrappedController);
}

enum BYOBRequestSlots {
  BYOBRequestSlot_Controller,
  BYOBRequestSlot_View,
  BYOBRequestSlotCount
};

/**
 * Streams spec 3.12.16.
 *      ReadableByteStreamControllerInvalidateBYOBRequest ( controller )
 */
static MOZ_MUST_USE bool ReadableByteStreamControllerInvalidateBYOBRequest(
    JSContext* cx, Handle<ReadableByteStreamController*> unwrappedController) {
  // Step 1: If controller.[[byobRequest]] is undefined, return.
  RootedValue unwrappedBYOBRequestVal(cx, unwrappedController->byobRequest());
  if (unwrappedBYOBRequestVal.isUndefined()) {
    return true;
  }

  RootedNativeObject unwrappedBYOBRequest(
      cx, UnwrapAndDowncastValue<NativeObject>(cx, unwrappedBYOBRequestVal));
  if (!unwrappedBYOBRequest) {
    return false;
  }

  // Step 2: Set controller.[[byobRequest]]
  //                       .[[associatedReadableByteStreamController]]
  //         to undefined.
  unwrappedBYOBRequest->setFixedSlot(BYOBRequestSlot_Controller,
                                     UndefinedValue());

  // Step 3: Set controller.[[byobRequest]].[[view]] to undefined.
  unwrappedBYOBRequest->setFixedSlot(BYOBRequestSlot_View, UndefinedValue());

  // Step 4: Set controller.[[byobRequest]] to undefined.
  unwrappedController->clearBYOBRequest();

  return true;
}

// Streams spec, 3.12.25.
//      ReadableByteStreamControllerShouldCallPull ( controller )
// Unified with 3.9.3 above.

/*** 6.1. Queuing strategies ************************************************/

/**
 * ECMA-262 7.3.4 CreateDataProperty(O, P, V)
 */
static MOZ_MUST_USE bool CreateDataProperty(JSContext* cx, HandleObject obj,
                                            HandlePropertyName key,
                                            HandleValue value,
                                            ObjectOpResult& result) {
  RootedId id(cx, NameToId(key));
  Rooted<PropertyDescriptor> desc(cx);
  desc.setDataDescriptor(value, JSPROP_ENUMERATE);
  return DefineProperty(cx, obj, id, desc, result);
}

// Streams spec, 6.1.2.2. new ByteLengthQueuingStrategy({ highWaterMark })
bool js::ByteLengthQueuingStrategy::constructor(JSContext* cx, unsigned argc,
                                                Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  if (!ThrowIfNotConstructing(cx, args, "ByteLengthQueuingStrategy")) {
    return false;
  }

  // Implicit in the spec: Create the new strategy object.
  RootedObject proto(cx);
  if (!GetPrototypeFromBuiltinConstructor(
          cx, args, JSProto_ByteLengthQueuingStrategy, &proto)) {
    return false;
  }
  RootedObject strategy(
      cx, NewObjectWithClassProto<ByteLengthQueuingStrategy>(cx, proto));
  if (!strategy) {
    return false;
  }

  // Implicit in the spec: Argument destructuring.
  RootedObject argObj(cx, ToObject(cx, args.get(0)));
  if (!argObj) {
    return false;
  }
  RootedValue highWaterMark(cx);
  if (!GetProperty(cx, argObj, argObj, cx->names().highWaterMark,
                   &highWaterMark)) {
    return false;
  }

  // Step 1: Perform ! CreateDataProperty(this, "highWaterMark",
  //                                      highWaterMark).
  ObjectOpResult ignored;
  if (!CreateDataProperty(cx, strategy, cx->names().highWaterMark,
                          highWaterMark, ignored)) {
    return false;
  }

  args.rval().setObject(*strategy);
  return true;
}

// Streams spec 6.1.2.3.1. size ( chunk )
bool ByteLengthQueuingStrategy_size(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1: Return ? GetV(chunk, "byteLength").
  return GetProperty(cx, args.get(0), cx->names().byteLength, args.rval());
}

static const JSPropertySpec ByteLengthQueuingStrategy_properties[] = {
    JS_PS_END};

static const JSFunctionSpec ByteLengthQueuingStrategy_methods[] = {
    JS_FN("size", ByteLengthQueuingStrategy_size, 1, 0), JS_FS_END};

CLASS_SPEC(ByteLengthQueuingStrategy, 1, 0, 0, 0, JS_NULL_CLASS_OPS);

// Streams spec, 6.1.3.2. new CountQueuingStrategy({ highWaterMark })
bool js::CountQueuingStrategy::constructor(JSContext* cx, unsigned argc,
                                           Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  if (!ThrowIfNotConstructing(cx, args, "CountQueuingStrategy")) {
    return false;
  }

  // Implicit in the spec: Create the new strategy object.
  RootedObject proto(cx);
  if (!GetPrototypeFromBuiltinConstructor(
          cx, args, JSProto_CountQueuingStrategy, &proto)) {
    return false;
  }
  Rooted<CountQueuingStrategy*> strategy(
      cx, NewObjectWithClassProto<CountQueuingStrategy>(cx, proto));
  if (!strategy) {
    return false;
  }

  // Implicit in the spec: Argument destructuring.
  RootedObject argObj(cx, ToObject(cx, args.get(0)));
  if (!argObj) {
    return false;
  }
  RootedValue highWaterMark(cx);
  if (!GetProperty(cx, argObj, argObj, cx->names().highWaterMark,
                   &highWaterMark)) {
    return false;
  }

  // Step 1: Perform ! CreateDataProperty(this, "highWaterMark", highWaterMark).
  ObjectOpResult ignored;
  if (!CreateDataProperty(cx, strategy, cx->names().highWaterMark,
                          highWaterMark, ignored)) {
    return false;
  }

  args.rval().setObject(*strategy);
  return true;
}

// Streams spec 6.2.3.3.1. size ( chunk )
bool CountQueuingStrategy_size(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1: Return 1.
  args.rval().setInt32(1);
  return true;
}

static const JSPropertySpec CountQueuingStrategy_properties[] = {JS_PS_END};

static const JSFunctionSpec CountQueuingStrategy_methods[] = {
    JS_FN("size", CountQueuingStrategy_size, 0, 0), JS_FS_END};

CLASS_SPEC(CountQueuingStrategy, 1, 0, 0, 0, JS_NULL_CLASS_OPS);

#undef CLASS_SPEC

/*** 6.2. Queue-with-sizes operations ***************************************/

/**
 * Streams spec, 6.2.1. DequeueValue ( container ) nothrow
 */
inline static MOZ_MUST_USE bool DequeueValue(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedContainer,
    MutableHandleValue chunk) {
  // Step 1: Assert: container has [[queue]] and [[queueTotalSize]] internal
  //         slots (implicit).
  // Step 2: Assert: queue is not empty.
  Rooted<ListObject*> unwrappedQueue(cx, unwrappedContainer->queue());
  MOZ_ASSERT(unwrappedQueue->length() > 0);

  // Step 3. Let pair be the first element of queue.
  // Step 4. Remove pair from queue, shifting all other elements downward
  //         (so that the second becomes the first, and so on).
  Rooted<QueueEntry*> unwrappedPair(
      cx, &unwrappedQueue->popFirstAs<QueueEntry>(cx));
  MOZ_ASSERT(unwrappedPair);

  // Step 5: Set container.[[queueTotalSize]] to
  //         container.[[queueTotalSize]] − pair.[[size]].
  // Step 6: If container.[[queueTotalSize]] < 0, set
  //         container.[[queueTotalSize]] to 0.
  //         (This can occur due to rounding errors.)
  double totalSize = unwrappedContainer->queueTotalSize();
  totalSize -= unwrappedPair->size();
  if (totalSize < 0) {
    totalSize = 0;
  }
  unwrappedContainer->setQueueTotalSize(totalSize);

  // Step 7: Return pair.[[value]].
  RootedValue val(cx, unwrappedPair->value());
  if (!cx->compartment()->wrap(cx, &val)) {
    return false;
  }
  chunk.set(val);
  return true;
}

/**
 * Streams spec, 6.2.2. EnqueueValueWithSize ( container, value, size ) throws
 */
static MOZ_MUST_USE bool EnqueueValueWithSize(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedContainer,
    HandleValue value, HandleValue sizeVal) {
  cx->check(value, sizeVal);

  // Step 1: Assert: container has [[queue]] and [[queueTotalSize]] internal
  //         slots (implicit).
  // Step 2: Let size be ? ToNumber(size).
  double size;
  if (!ToNumber(cx, sizeVal, &size)) {
    return false;
  }

  // Step 3: If ! IsFiniteNonNegativeNumber(size) is false, throw a RangeError
  //         exception.
  if (size < 0 || mozilla::IsNaN(size) || mozilla::IsInfinite(size)) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_NUMBER_MUST_BE_FINITE_NON_NEGATIVE, "size");
    return false;
  }

  // Step 4: Append Record {[[value]]: value, [[size]]: size} as the last
  //         element of container.[[queue]].
  {
    AutoRealm ar(cx, unwrappedContainer);
    Rooted<ListObject*> queue(cx, unwrappedContainer->queue());
    RootedValue wrappedVal(cx, value);
    if (!cx->compartment()->wrap(cx, &wrappedVal)) {
      return false;
    }

    QueueEntry* entry = QueueEntry::create(cx, wrappedVal, size);
    if (!entry) {
      return false;
    }
    RootedValue val(cx, ObjectValue(*entry));
    if (!queue->append(cx, val)) {
      return false;
    }
  }

  // Step 5: Set container.[[queueTotalSize]] to
  //         container.[[queueTotalSize]] + size.
  unwrappedContainer->setQueueTotalSize(unwrappedContainer->queueTotalSize() +
                                        size);

  return true;
}

/**
 * Streams spec, 6.2.4. ResetQueue ( container ) nothrow
 */
inline static MOZ_MUST_USE bool ResetQueue(
    JSContext* cx, Handle<ReadableStreamController*> unwrappedContainer) {
  // Step 1: Assert: container has [[queue]] and [[queueTotalSize]] internal
  //         slots (implicit).
  // Step 2: Set container.[[queue]] to a new empty List.
  if (!SetNewList(cx, unwrappedContainer, StreamController::Slot_Queue)) {
    return false;
  }

  // Step 3: Set container.[[queueTotalSize]] to 0.
  unwrappedContainer->setQueueTotalSize(0);

  return true;
}

/*** 6.3. Miscellaneous operations ******************************************/

/**
 * Appends the given |obj| to the given list |container|'s list.
 */
inline static MOZ_MUST_USE bool AppendToListAtSlot(
    JSContext* cx, HandleNativeObject unwrappedContainer, uint32_t slot,
    HandleObject obj) {
  Rooted<ListObject*> list(
      cx, &unwrappedContainer->getFixedSlot(slot).toObject().as<ListObject>());

  AutoRealm ar(cx, list);
  RootedValue val(cx, ObjectValue(*obj));
  if (!cx->compartment()->wrap(cx, &val)) {
    return false;
  }
  return list->append(cx, val);
}

/**
 * Streams spec, 6.3.1.
 *      CreateAlgorithmFromUnderlyingMethod ( underlyingObject, methodName,
 *                                            algoArgCount, extraArgs )
 *
 * This function only partly implements the standard algorithm. We do not
 * actually create a new JSFunction completely encapsulating the new algorithm.
 * Instead, this just gets the specified method and checks for errors. It's the
 * caller's responsibility to make sure that later, when the algorithm is
 * "performed", the appropriate steps are carried out.
 */
static MOZ_MUST_USE bool CreateAlgorithmFromUnderlyingMethod(
    JSContext* cx, HandleValue underlyingObject,
    const char* methodNameForErrorMessage, HandlePropertyName methodName,
    MutableHandleValue method) {
  // Step 1: Assert: underlyingObject is not undefined.
  MOZ_ASSERT(!underlyingObject.isUndefined());

  // Step 2: Assert: ! IsPropertyKey(methodName) is true (implicit).
  // Step 3: Assert: algoArgCount is 0 or 1 (omitted).
  // Step 4: Assert: extraArgs is a List (omitted).

  // Step 5: Let method be ? GetV(underlyingObject, methodName).
  if (!GetProperty(cx, underlyingObject, methodName, method)) {
    return false;
  }

  // Step 6: If method is not undefined,
  if (!method.isUndefined()) {
    // Step a: If ! IsCallable(method) is false, throw a TypeError
    //         exception.
    if (!IsCallable(method)) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_NOT_FUNCTION, methodNameForErrorMessage);
      return false;
    }

    // Step b: If algoArgCount is 0, return an algorithm that performs the
    //         following steps:
    //     Step i: Return ! PromiseCall(method, underlyingObject,
    //             extraArgs).
    // Step c: Otherwise, return an algorithm that performs the following
    //         steps, taking an arg argument:
    //     Step i: Let fullArgs be a List consisting of arg followed by the
    //             elements of extraArgs in order.
    //     Step ii: Return ! PromiseCall(method, underlyingObject,
    //                                   fullArgs).
    // (These steps are deferred to the code that performs the algorithm.
    // See ReadableStreamControllerCancelSteps and
    // ReadableStreamControllerCallPullIfNeeded.)
    return true;
  }

  // Step 7: Return an algorithm which returns a promise resolved with
  //         undefined (implicit).
  return true;
}

/**
 * Streams spec, 6.3.2. InvokeOrNoop ( O, P, args )
 * As it happens, all callers pass exactly one argument.
 */
inline static MOZ_MUST_USE bool InvokeOrNoop(JSContext* cx, HandleValue O,
                                             HandlePropertyName P,
                                             HandleValue arg,
                                             MutableHandleValue rval) {
  cx->check(O, P, arg);

  // Step 1: Assert: O is not undefined.
  MOZ_ASSERT(!O.isUndefined());

  // Step 2: Assert: ! IsPropertyKey(P) is true (implicit).
  // Step 3: Assert: args is a List (implicit).
  // Step 4: Let method be ? GetV(O, P).
  RootedValue method(cx);
  if (!GetProperty(cx, O, P, &method)) {
    return false;
  }

  // Step 5: If method is undefined, return.
  if (method.isUndefined()) {
    return true;
  }

  // Step 6: Return ? Call(method, O, args).
  return Call(cx, method, O, arg, rval);
}

/**
 * Streams spec, 6.3.5. PromiseCall ( F, V, args )
 * As it happens, all callers pass exactly one argument.
 */
static MOZ_MUST_USE JSObject* PromiseCall(JSContext* cx, HandleValue F,
                                          HandleValue V, HandleValue arg) {
  cx->check(F, V, arg);

  // Step 1: Assert: ! IsCallable(F) is true.
  MOZ_ASSERT(IsCallable(F));

  // Step 2: Assert: V is not undefined.
  MOZ_ASSERT(!V.isUndefined());

  // Step 3: Assert: args is a List (implicit).
  // Step 4: Let returnValue be Call(F, V, args).
  RootedValue rval(cx);
  if (!Call(cx, F, V, arg, &rval)) {
    // Step 5: If returnValue is an abrupt completion, return a promise rejected
    // with returnValue.[[Value]].
    return PromiseRejectedWithPendingError(cx);
  }

  // Step 6: Otherwise, return a promise resolved with returnValue.[[Value]].
  return PromiseObject::unforgeableResolve(cx, rval);
}

/**
 * Streams spec, 6.3.7. ValidateAndNormalizeHighWaterMark ( highWaterMark )
 */
static MOZ_MUST_USE bool ValidateAndNormalizeHighWaterMark(
    JSContext* cx, HandleValue highWaterMarkVal, double* highWaterMark) {
  // Step 1: Set highWaterMark to ? ToNumber(highWaterMark).
  if (!ToNumber(cx, highWaterMarkVal, highWaterMark)) {
    return false;
  }

  // Step 2: If highWaterMark is NaN or highWaterMark < 0, throw a RangeError
  // exception.
  if (mozilla::IsNaN(*highWaterMark) || *highWaterMark < 0) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_STREAM_INVALID_HIGHWATERMARK);
    return false;
  }

  // Step 3: Return highWaterMark.
  return true;
}

/**
 * Streams spec, 6.3.8. MakeSizeAlgorithmFromSizeFunction ( size )
 *
 * The standard makes a big deal of turning JavaScript functions (grubby,
 * touched by users, covered with germs) into algorithms (pristine,
 * respectable, purposeful). We don't bother. Here we only check for errors and
 * leave `size` unchanged. Then, in ReadableStreamDefaultControllerEnqueue,
 * where this value is used, we have to check for undefined and behave as if we
 * had "made" an "algorithm" as described below.
 */
static MOZ_MUST_USE bool MakeSizeAlgorithmFromSizeFunction(JSContext* cx,
                                                           HandleValue size) {
  // Step 1: If size is undefined, return an algorithm that returns 1.
  if (size.isUndefined()) {
    // Deferred. Size algorithm users must check for undefined.
    return true;
  }

  // Step 2: If ! IsCallable(size) is false, throw a TypeError exception.
  if (!IsCallable(size)) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NOT_FUNCTION,
                              "ReadableStream argument options.size");
    return false;
  }

  // Step 3: Return an algorithm that performs the following steps, taking a
  //         chunk argument:
  //     a. Return ? Call(size, undefined, « chunk »).
  // Deferred. Size algorithm users must know how to call the size function.
  return true;
}

/*** API entry points *******************************************************/

JS_FRIEND_API JSObject* js::UnwrapReadableStream(JSObject* obj) {
  return obj->maybeUnwrapIf<ReadableStream>();
}

JS_PUBLIC_API JSObject* JS::NewReadableDefaultStreamObject(
    JSContext* cx, JS::HandleObject underlyingSource /* = nullptr */,
    JS::HandleFunction size /* = nullptr */, double highWaterMark /* = 1 */,
    JS::HandleObject proto /* = nullptr */) {
  MOZ_ASSERT(!cx->zone()->isAtomsZone());
  AssertHeapIsIdle();
  CHECK_THREAD(cx);
  cx->check(underlyingSource, size, proto);
  MOZ_ASSERT(highWaterMark >= 0);

  // A copy of ReadableStream::constructor, with most of the
  // argument-checking done implicitly by C++ type checking.
  Rooted<ReadableStream*> stream(cx, ReadableStream::create(cx));
  if (!stream) {
    return nullptr;
  }
  RootedValue sourceVal(cx);
  if (underlyingSource) {
    sourceVal.setObject(*underlyingSource);
  } else {
    JSObject* source = NewBuiltinClassInstance<PlainObject>(cx);
    if (!source) {
      return nullptr;
    }
    sourceVal.setObject(*source);
  }
  RootedValue sizeVal(cx, size ? ObjectValue(*size) : UndefinedValue());

  if (!SetUpReadableStreamDefaultControllerFromUnderlyingSource(
          cx, stream, sourceVal, highWaterMark, sizeVal)) {
    return nullptr;
  }

  return stream;
}

JS_PUBLIC_API JSObject* JS::NewReadableExternalSourceStreamObject(
    JSContext* cx, JS::ReadableStreamUnderlyingSource* underlyingSource,
    HandleObject proto /* = nullptr */) {
  MOZ_ASSERT(!cx->zone()->isAtomsZone());
  AssertHeapIsIdle();
  CHECK_THREAD(cx);
  MOZ_ASSERT(underlyingSource);
  MOZ_ASSERT((uintptr_t(underlyingSource) & 1) == 0,
             "external underlying source pointers must be aligned");
  cx->check(proto);

  return ReadableStream::createExternalSourceStream(cx, underlyingSource,
                                                    proto);
}

JS_PUBLIC_API bool JS::IsReadableStream(JSObject* obj) {
  return obj->canUnwrapAs<ReadableStream>();
}

JS_PUBLIC_API bool JS::IsReadableStreamReader(JSObject* obj) {
  return obj->canUnwrapAs<ReadableStreamDefaultReader>();
}

JS_PUBLIC_API bool JS::IsReadableStreamDefaultReader(JSObject* obj) {
  return obj->canUnwrapAs<ReadableStreamDefaultReader>();
}

template <class T>
static MOZ_MUST_USE T* APIUnwrapAndDowncast(JSContext* cx, JSObject* obj) {
  cx->check(obj);
  return UnwrapAndDowncastObject<T>(cx, obj);
}

JS_PUBLIC_API bool JS::ReadableStreamIsReadable(JSContext* cx,
                                                HandleObject streamObj,
                                                bool* result) {
  ReadableStream* unwrappedStream =
      APIUnwrapAndDowncast<ReadableStream>(cx, streamObj);
  if (!unwrappedStream) {
    return false;
  }

  *result = unwrappedStream->readable();
  return true;
}

JS_PUBLIC_API bool JS::ReadableStreamIsLocked(JSContext* cx,
                                              HandleObject streamObj,
                                              bool* result) {
  ReadableStream* unwrappedStream =
      APIUnwrapAndDowncast<ReadableStream>(cx, streamObj);
  if (!unwrappedStream) {
    return false;
  }

  *result = unwrappedStream->locked();
  return true;
}

JS_PUBLIC_API bool JS::ReadableStreamIsDisturbed(JSContext* cx,
                                                 HandleObject streamObj,
                                                 bool* result) {
  ReadableStream* unwrappedStream =
      APIUnwrapAndDowncast<ReadableStream>(cx, streamObj);
  if (!unwrappedStream) {
    return false;
  }

  *result = unwrappedStream->disturbed();
  return true;
}

JS_PUBLIC_API JSObject* JS::ReadableStreamCancel(JSContext* cx,
                                                 HandleObject streamObj,
                                                 HandleValue reason) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);
  cx->check(reason);

  Rooted<ReadableStream*> unwrappedStream(
      cx, APIUnwrapAndDowncast<ReadableStream>(cx, streamObj));
  if (!unwrappedStream) {
    return nullptr;
  }

  return ::ReadableStreamCancel(cx, unwrappedStream, reason);
}

JS_PUBLIC_API bool JS::ReadableStreamGetMode(JSContext* cx,
                                             HandleObject streamObj,
                                             JS::ReadableStreamMode* mode) {
  ReadableStream* unwrappedStream =
      APIUnwrapAndDowncast<ReadableStream>(cx, streamObj);
  if (!unwrappedStream) {
    return false;
  }

  *mode = unwrappedStream->mode();
  return true;
}

JS_PUBLIC_API JSObject* JS::ReadableStreamGetReader(
    JSContext* cx, HandleObject streamObj, ReadableStreamReaderMode mode) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);

  Rooted<ReadableStream*> unwrappedStream(
      cx, APIUnwrapAndDowncast<ReadableStream>(cx, streamObj));
  if (!unwrappedStream) {
    return nullptr;
  }

  JSObject* result = CreateReadableStreamDefaultReader(cx, unwrappedStream);
  MOZ_ASSERT_IF(result, IsObjectInContextCompartment(result, cx));
  return result;
}

JS_PUBLIC_API bool JS::ReadableStreamGetExternalUnderlyingSource(
    JSContext* cx, HandleObject streamObj,
    JS::ReadableStreamUnderlyingSource** source) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);

  Rooted<ReadableStream*> unwrappedStream(
      cx, APIUnwrapAndDowncast<ReadableStream>(cx, streamObj));
  if (!unwrappedStream) {
    return false;
  }

  MOZ_ASSERT(unwrappedStream->mode() == JS::ReadableStreamMode::ExternalSource);
  if (unwrappedStream->locked()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAM_LOCKED);
    return false;
  }
  if (!unwrappedStream->readable()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAMCONTROLLER_NOT_READABLE,
                              "ReadableStreamGetExternalUnderlyingSource");
    return false;
  }

  auto unwrappedController =
      &unwrappedStream->controller()->as<ReadableByteStreamController>();
  unwrappedController->setSourceLocked();
  *source = unwrappedController->externalSource();
  return true;
}

JS_PUBLIC_API bool JS::ReadableStreamReleaseExternalUnderlyingSource(
    JSContext* cx, HandleObject streamObj) {
  ReadableStream* unwrappedStream =
      APIUnwrapAndDowncast<ReadableStream>(cx, streamObj);
  if (!unwrappedStream) {
    return false;
  }

  MOZ_ASSERT(unwrappedStream->mode() == JS::ReadableStreamMode::ExternalSource);
  MOZ_ASSERT(unwrappedStream->locked());
  MOZ_ASSERT(unwrappedStream->controller()->sourceLocked());
  unwrappedStream->controller()->clearSourceLocked();
  return true;
}

JS_PUBLIC_API bool JS::ReadableStreamUpdateDataAvailableFromSource(
    JSContext* cx, JS::HandleObject streamObj, uint32_t availableData) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);

  Rooted<ReadableStream*> unwrappedStream(
      cx, APIUnwrapAndDowncast<ReadableStream>(cx, streamObj));
  if (!unwrappedStream) {
    return false;
  }

  // This is based on Streams spec 3.10.4.4. enqueue(chunk) steps 1-3 and
  // 3.12.9. ReadableByteStreamControllerEnqueue(controller, chunk) steps
  // 8-9.
  //
  // Adapted to handling updates signaled by the embedding for streams with
  // external underlying sources.
  //
  // The remaining steps of those two functions perform checks and asserts
  // that don't apply to streams with external underlying sources.

  Rooted<ReadableByteStreamController*> unwrappedController(
      cx, &unwrappedStream->controller()->as<ReadableByteStreamController>());

  // Step 2: If this.[[closeRequested]] is true, throw a TypeError exception.
  if (unwrappedController->closeRequested()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAMCONTROLLER_CLOSED, "enqueue");
    return false;
  }

  // Step 3: If this.[[controlledReadableStream]].[[state]] is not "readable",
  //         throw a TypeError exception.
  if (!unwrappedController->stream()->readable()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAMCONTROLLER_NOT_READABLE,
                              "enqueue");
    return false;
  }

  unwrappedController->clearPullFlags();

#if DEBUG
  uint32_t oldAvailableData =
      unwrappedController->getFixedSlot(StreamController::Slot_TotalSize)
          .toInt32();
#endif  // DEBUG
  unwrappedController->setQueueTotalSize(availableData);

  // 3.12.9. ReadableByteStreamControllerEnqueue
  // Step 8.a: If ! ReadableStreamGetNumReadRequests(stream) is 0,
  // Reordered because for externally-sourced streams it applies regardless
  // of reader type.
  if (ReadableStreamGetNumReadRequests(unwrappedStream) == 0) {
    return true;
  }

  // Step 8: If ! ReadableStreamHasDefaultReader(stream) is true
  bool hasDefaultReader;
  if (!ReadableStreamHasDefaultReader(cx, unwrappedStream, &hasDefaultReader)) {
    return false;
  }
  if (hasDefaultReader) {
    // Step b: Otherwise,
    // Step i: Assert: controller.[[queue]] is empty.
    MOZ_ASSERT(oldAvailableData == 0);

    // Step ii: Let transferredView be
    //          ! Construct(%Uint8Array%, transferredBuffer,
    //                      byteOffset, byteLength).
    JSObject* viewObj = JS_NewUint8Array(cx, availableData);
    if (!viewObj) {
      return false;
    }
    Rooted<ArrayBufferViewObject*> transferredView(
        cx, &viewObj->as<ArrayBufferViewObject>());
    if (!transferredView) {
      return false;
    }

    JS::ReadableStreamUnderlyingSource* source =
        unwrappedController->externalSource();

    size_t bytesWritten;
    {
      AutoRealm ar(cx, unwrappedStream);
      JS::AutoSuppressGCAnalysis suppressGC(cx);
      JS::AutoCheckCannotGC noGC;
      bool dummy;
      void* buffer = JS_GetArrayBufferViewData(transferredView, &dummy, noGC);
      source->writeIntoReadRequestBuffer(cx, unwrappedStream, buffer,
                                         availableData, &bytesWritten);
    }

    // Step iii: Perform ! ReadableStreamFulfillReadRequest(stream,
    //                                                      transferredView,
    //                                                      false).
    RootedValue chunk(cx, ObjectValue(*transferredView));
    if (!ReadableStreamFulfillReadOrReadIntoRequest(cx, unwrappedStream, chunk,
                                                    false)) {
      return false;
    }

    unwrappedController->setQueueTotalSize(availableData - bytesWritten);
  } else {
    // Step 9: Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,
    //         [...]
    // (Omitted. BYOB readers are not implemented.)

    // Step 10: Otherwise,
    // Step a: Assert: ! IsReadableStreamLocked(stream) is false.
    MOZ_ASSERT(!unwrappedStream->locked());

    // Step b: Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(
    //         controller, transferredBuffer, byteOffset, byteLength).
    // (Not needed for external underlying sources.)
  }

  return true;
}

JS_PUBLIC_API bool JS::ReadableStreamTee(JSContext* cx, HandleObject streamObj,
                                         MutableHandleObject branch1Obj,
                                         MutableHandleObject branch2Obj) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);

  Rooted<ReadableStream*> unwrappedStream(
      cx, APIUnwrapAndDowncast<ReadableStream>(cx, streamObj));
  if (!unwrappedStream) {
    return false;
  }

  Rooted<ReadableStream*> branch1Stream(cx);
  Rooted<ReadableStream*> branch2Stream(cx);
  if (!ReadableStreamTee(cx, unwrappedStream, false, &branch1Stream,
                         &branch2Stream)) {
    return false;
  }

  branch1Obj.set(branch1Stream);
  branch2Obj.set(branch2Stream);
  return true;
}

JS_PUBLIC_API bool JS::ReadableStreamGetDesiredSize(JSContext* cx,
                                                    JSObject* streamObj,
                                                    bool* hasValue,
                                                    double* value) {
  ReadableStream* unwrappedStream =
      APIUnwrapAndDowncast<ReadableStream>(cx, streamObj);
  if (!unwrappedStream) {
    return false;
  }

  if (unwrappedStream->errored()) {
    *hasValue = false;
    return true;
  }

  *hasValue = true;

  if (unwrappedStream->closed()) {
    *value = 0;
    return true;
  }

  *value = ReadableStreamControllerGetDesiredSizeUnchecked(
      unwrappedStream->controller());
  return true;
}

JS_PUBLIC_API bool JS::ReadableStreamClose(JSContext* cx,
                                           HandleObject streamObj) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);

  Rooted<ReadableStream*> unwrappedStream(
      cx, APIUnwrapAndDowncast<ReadableStream>(cx, streamObj));
  if (!unwrappedStream) {
    return false;
  }

  Rooted<ReadableStreamController*> unwrappedControllerObj(
      cx, unwrappedStream->controller());
  if (!CheckReadableStreamControllerCanCloseOrEnqueue(
          cx, unwrappedControllerObj, "close")) {
    return false;
  }

  if (unwrappedControllerObj->is<ReadableStreamDefaultController>()) {
    Rooted<ReadableStreamDefaultController*> unwrappedController(cx);
    unwrappedController =
        &unwrappedControllerObj->as<ReadableStreamDefaultController>();
    return ReadableStreamDefaultControllerClose(cx, unwrappedController);
  }

  Rooted<ReadableByteStreamController*> unwrappedController(cx);
  unwrappedController =
      &unwrappedControllerObj->as<ReadableByteStreamController>();
  return ReadableByteStreamControllerClose(cx, unwrappedController);
}

JS_PUBLIC_API bool JS::ReadableStreamEnqueue(JSContext* cx,
                                             HandleObject streamObj,
                                             HandleValue chunk) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);
  cx->check(chunk);

  Rooted<ReadableStream*> unwrappedStream(
      cx, APIUnwrapAndDowncast<ReadableStream>(cx, streamObj));
  if (!unwrappedStream) {
    return false;
  }

  if (unwrappedStream->mode() != JS::ReadableStreamMode::Default) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_READABLESTREAM_NOT_DEFAULT_CONTROLLER,
                              "JS::ReadableStreamEnqueue");
    return false;
  }

  Rooted<ReadableStreamDefaultController*> unwrappedController(cx);
  unwrappedController =
      &unwrappedStream->controller()->as<ReadableStreamDefaultController>();

  MOZ_ASSERT(!unwrappedController->closeRequested());
  MOZ_ASSERT(unwrappedStream->readable());

  return ReadableStreamDefaultControllerEnqueue(cx, unwrappedController, chunk);
}

JS_PUBLIC_API bool JS::ReadableStreamError(JSContext* cx,
                                           HandleObject streamObj,
                                           HandleValue error) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);
  cx->check(error);

  Rooted<ReadableStream*> unwrappedStream(
      cx, APIUnwrapAndDowncast<ReadableStream>(cx, streamObj));
  if (!unwrappedStream) {
    return false;
  }

  Rooted<ReadableStreamController*> unwrappedController(
      cx, unwrappedStream->controller());
  return ReadableStreamControllerError(cx, unwrappedController, error);
}

JS_PUBLIC_API bool JS::ReadableStreamReaderIsClosed(JSContext* cx,
                                                    HandleObject readerObj,
                                                    bool* result) {
  Rooted<ReadableStreamReader*> unwrappedReader(
      cx, APIUnwrapAndDowncast<ReadableStreamReader>(cx, readerObj));
  if (!unwrappedReader) {
    return false;
  }

  *result = unwrappedReader->isClosed();
  return true;
}

JS_PUBLIC_API bool JS::ReadableStreamReaderCancel(JSContext* cx,
                                                  HandleObject readerObj,
                                                  HandleValue reason) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);
  cx->check(reason);

  Rooted<ReadableStreamReader*> unwrappedReader(
      cx, APIUnwrapAndDowncast<ReadableStreamReader>(cx, readerObj));
  if (!unwrappedReader) {
    return false;
  }
  MOZ_ASSERT(unwrappedReader->forAuthorCode() == ForAuthorCodeBool::No,
             "C++ code should not touch readers created by scripts");

  return ReadableStreamReaderGenericCancel(cx, unwrappedReader, reason);
}

JS_PUBLIC_API bool JS::ReadableStreamReaderReleaseLock(JSContext* cx,
                                                       HandleObject readerObj) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);

  Rooted<ReadableStreamReader*> unwrappedReader(
      cx, APIUnwrapAndDowncast<ReadableStreamReader>(cx, readerObj));
  if (!unwrappedReader) {
    return false;
  }
  MOZ_ASSERT(unwrappedReader->forAuthorCode() == ForAuthorCodeBool::No,
             "C++ code should not touch readers created by scripts");

#ifdef DEBUG
  Rooted<ReadableStream*> unwrappedStream(
      cx, UnwrapStreamFromReader(cx, unwrappedReader));
  if (!unwrappedStream) {
    return false;
  }
  MOZ_ASSERT(ReadableStreamGetNumReadRequests(unwrappedStream) == 0);
#endif  // DEBUG

  return ReadableStreamReaderGenericRelease(cx, unwrappedReader);
}

JS_PUBLIC_API JSObject* JS::ReadableStreamDefaultReaderRead(
    JSContext* cx, HandleObject readerObj) {
  AssertHeapIsIdle();
  CHECK_THREAD(cx);

  Rooted<ReadableStreamDefaultReader*> unwrappedReader(
      cx, APIUnwrapAndDowncast<ReadableStreamDefaultReader>(cx, readerObj));
  if (!unwrappedReader) {
    return nullptr;
  }
  MOZ_ASSERT(unwrappedReader->forAuthorCode() == ForAuthorCodeBool::No,
             "C++ code should not touch readers created by scripts");

  return ::ReadableStreamDefaultReaderRead(cx, unwrappedReader);
}