All files / lib/internal/webstreams readablestream.js

99.53% Statements 2737/2750
98.53% Branches 668/678
96.32% Functions 131/136
99.53% Lines 2737/2750

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2751182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 956x 956x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 955x 956x 956x 956x 956x 956x 137x 137x 133x 133x 133x 133x 133x 133x 812x 812x 922x 809x 809x 809x 809x 809x 809x 809x 809x 956x 182x 182x 6x 6x 182x 182x 182x 182x 182x 182x 79x 79x 76x 79x 182x 182x 182x 182x 182x 182x 87x 87x 85x 4x 4x 4x 80x 87x 182x 182x 182x 182x 182x 182x 182x 182x 576x 576x 573x 576x 576x 576x 576x 97x 97x 131x 86x 576x 182x 182x 182x 182x 182x 182x 182x 51x 51x 51x 51x 8x 8x 8x 8x 8x 51x 51x 7x 7x 7x 7x 7x 25x 25x 25x 51x 51x 51x 51x 51x 51x 51x 15x 15x 44x 13x 43x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 51x 182x 182x 182x 182x 182x 182x 182x 185x 185x 185x 183x 2x 2x 2x 2x 2x 180x 185x 185x 185x 185x 185x 185x 185x 171x 171x 178x 169x 177x 167x 167x 167x 167x 167x 167x 167x 167x 185x 18x 18x 185x 182x 182x 182x 182x 182x 41x 41x 38x 41x 182x 182x 182x 182x 182x 182x 182x 182x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 97x 97x 93x 97x         93x 93x 93x 93x 67x 67x 93x 93x 18x 18x 18x 18x 93x 93x 7x 7x 7x 7x 7x 93x 93x 97x 63x 63x 32x 32x 27x 27x 32x       27x 32x 19x 19x 19x 18x 18x 8x 8x 8x 32x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 63x 97x 97x 97x 97x 97x 97x 97x 45x 45x 45x 97x 97x 97x 97x 63x 63x 63x 32x 6x 6x 6x 32x 32x 63x 63x 63x 63x 63x 182x 182x 9x 9x 9x 9x 9x 182x 182x 10x 10x 9x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 10x 182x 182x 8x 8x 8x 8x 8x 182x 182x 8x 8x 8x 8x 8x 8x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 182x 182x 182x 182x 182x 182x 182x 182x 18x 18x 182x 182x 182x 182x 182x 182x 171x 171x 168x 171x 182x 182x 182x 182x 182x 161x 161x 158x 158x 158x 158x 161x 68x 68x 68x 90x 90x 90x 90x 90x 161x 2x 2x 2x 88x 88x 161x 182x 182x 182x 182x 182x 151x 151x 148x 148x 148x 148x 151x 66x 66x 66x 82x 82x 151x 182x 182x 65x 65x 65x 65x 65x 182x 182x 182x 182x 182x 182x 182x 182x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 182x 182x 182x 450x 450x 182x 182x 291x 291x 182x 182x 106x 106x 182x 182x 40x 40x 182x 182x 182x 182x 182x 182x 274x 274x 182x 182x 232x 232x 182x 182x 12x 12x 182x 182x 8x 8x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 777x 777x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x 777x 182x 182x 182x 182x 182x 182x 182x 182x 460x 460x 458x 7x 7x 7x 7x 450x 450x 450x 460x 182x 182x 49x 49x 46x 47x 47x 3x 3x 3x 41x 49x 182x 182x 182x 182x 182x 182x 236x 236x 233x 236x 182x 182x 182x 182x 182x 182x 41x 41x 38x 2x 2x 2x 36x 41x 182x 182x 3x 3x 3x 3x 3x 3x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 90x 90x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 90x 182x 182x 182x 182x 182x 182x 182x 182x 182x 285x 285x 285x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 278x 278x 278x 278x 285x 3x 3x 3x 3x 275x 275x 284x 1x 1x 1x 1x 274x 274x 274x 285x 182x 182x 10x 10x 7x 7x 7x 1x 1x 1x 5x 10x 182x 182x 182x 182x 182x 182x 11x 11x 8x 11x 182x 182x 182x 182x 182x 182x 8x 8x 5x 1x 1x 1x 4x 8x 182x 182x 2x 2x 2x 2x 2x 2x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 2x 2x 182x 182x 182x 182x 182x 182x 110x 110x 182x 182x 196x 196x 188x 196x 182x 182x 182x 182x 182x 408x 408x 397x 408x 182x 182x 182x 182x 182x 98x 98x 182x 182x 166x 166x 182x 182x 591x 591x 182x 182x 3x 3x 182x 182x 182x 182x 182x 182x 182x 182x 182x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 182x 182x 182x 182x 182x 182x 182x 2x 2x 182x 182x 182x 182x 182x 182x 166x 166x 163x 166x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 163x 166x 182x 182x 182x 182x 182x 182x 19x 19x 16x 19x 182x 182x 35x 35x 32x 32x 31x 32x 30x 35x 182x 182x 182x 182x 182x 56x 56x 53x 2x 2x 2x 2x 2x 2x 2x 2x 2x 51x 51x 51x 51x 56x 4x 4x 4x 47x 52x 47x 51x 45x 45x 45x 45x 45x 56x 182x 182x 182x 182x 182x 13x 13x 10x 13x 182x 182x 7x 7x 182x 182x 34x 34x 182x 182x 65x 65x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 182x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 2x 2x 195x 195x 195x 195x 195x 197x 1x 1x 1x 1x 1x 1x 194x 194x 194x 194x 194x 194x 194x 194x 194x 190x 190x 190x 190x 190x 190x 57x 57x 190x 194x 194x 117x 117x 114x 115x 117x 194x 194x 270x 134x 270x 270x 85x 85x 85x 85x 85x 85x 49x 49x 49x 131x 131x 131x 131x 131x 270x 194x 194x 71x 56x 59x 71x 31x 31x 31x 31x 31x 31x 25x 71x 194x 194x 17x 17x 17x 17x 13x 13x 13x 12x 12x 2x 13x 13x 17x 15x 15x 15x 12x 12x 3x 15x 15x 17x 17x 17x 17x 17x 17x 194x 194x 364x 364x 338x 338x 364x 194x 194x 182x 182x 150x 150x 182x 194x 194x 280x 280x 253x 208x 208x 208x 208x 208x 98x 98x 98x 208x 208x 208x 208x 208x 280x 194x 194x 182x 182x 182x 194x 194x 19x 12x 12x 12x 7x 7x 182x 182x 182x 182x 70x 47x 47x 47x 47x 47x 23x 182x 182x 182x 126x 99x 99x 99x 99x 99x 27x 182x 182x 182x 108x 94x 94x 94x 14x 182x 182x 182x 197x 20x 20x 20x 13x 13x 20x 7x 7x 20x 182x 182x 197x 182x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 83x 53x 53x 53x 24x 24x 24x 24x 24x 1x 1x 1x 24x 22x 22x 22x 22x 24x 19x 19x 19x 19x 24x 53x 53x 11x 11x 11x 11x 11x 11x 11x 53x 53x 10x 53x 53x 53x 83x 39x 39x 11x 11x 11x 2x 2x 2x 11x 11x 39x 39x 15x 15x 15x 8x 8x 8x 15x 15x 39x 39x 39x 39x 39x 39x 39x 39x 39x 11x 11x 11x 11x 39x 39x 39x 39x 182x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 249x 249x 249x 250x 182x 3275x 3275x 3275x 182x 203x 203x 203x 203x 20x 203x 10x 203x 173x 173x 173x 173x 203x 4x 4x 4x 4x 173x 173x 173x 173x 173x 173x 173x 203x 182x 462x 462x 462x 462x 462x 462x 462x 462x 462x 462x 312x 312x 312x 317x 292x 292x 292x 292x 462x 182x 183x 183x 183x 183x 183x 183x 183x 183x 183x 183x 183x 125x 125x 125x 125x 130x 119x 119x 119x 183x 6x 6x 6x 6x 6x 183x 182x 3069x 3069x 3069x 3069x 3069x 3069x 3069x 3028x 3028x 3069x 3069x 182x 1619x 1619x 1619x 1619x 182x 917x 917x 917x 917x 917x 917x 917x 875x 875x 917x 917x 182x 275x 275x 275x 275x 182x 228x 228x 228x 228x 228x 228x 228x 228x 228x 228x 228x 228x 228x 228x 228x 228x 228x 182x 81x 81x 81x 81x 81x 81x 81x 81x 81x 75x 75x 81x 182x 373x 373x 373x 373x 373x 182x 111x 111x 111x 111x 111x 111x 111x 182x 59x 59x 59x 59x 59x 59x 59x 182x 832x 832x 832x 832x 832x 656x 656x 832x 123x 123x 123x 123x 123x 123x 832x 53x 53x 53x 53x 53x 53x 53x 832x 832x 182x 288x 288x 288x 288x 288x 288x 288x 288x 56x 56x 288x 232x 232x 232x 232x 232x 232x 232x 288x 288x 288x 288x 182x 274x 274x 274x 274x 274x 274x 274x 1x 1x 1x 273x 273x 273x 273x 274x 182x 804x 804x 804x 804x 804x 804x 804x 804x 121x 121x 804x 51x 51x 804x 625x 804x 804x 182x 89x 89x 89x 86x 86x 86x 86x 89x 84x 84x 89x 182x 773x 773x 773x 748x 748x 773x 182x 281x 281x 281x 276x 277x 211x 211x 211x 281x 182x 568x 568x 568x 567x 567x 567x 567x 567x 568x 568x 207x 563x 360x 360x 360x 360x 360x 360x 360x 360x 11x 11x 11x 360x 556x 568x 182x 116x 116x 116x 182x 3806x 3806x 3806x 3806x 3806x 3806x 3806x 182x 1162x 1162x 1162x 1162x 1162x 1162x 1162x 1162x 1162x 1162x 1156x 1162x 1162x 182x 2228x 2228x 2228x 2228x 2228x 2228x 2228x 1477x 2045x 2228x 431x 431x 1046x 1046x 1046x 1046x 1046x 2228x 182x 2112x 2112x 2112x 2112x 220x 220x 220x 800x 800x 800x 800x 800x 730x 730x 176x 176x 176x 800x 800x 2112x 182x 586x 586x 586x 586x 586x 182x 202x 202x 202x 202x 202x 169x 169x 169x 169x 202x 182x 166x 166x 166x 166x 166x 166x 182x 591x 591x 591x 591x 591x 591x 247x 247x 52x 52x 246x 195x 195x 247x 247x 247x 344x 344x 591x 182x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 841x 841x 841x 841x 875x 875x 875x 182x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 881x 182x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 30x 30x 6x 6x 6x 24x 30x 14x 14x 1x 1x 1x 1x 14x 23x 23x 23x 31x 182x 92x 92x 92x 92x 6x 6x 6x 92x 92x 92x 92x 92x 11x 92x 81x 81x 81x 92x 182x 158x 158x 158x 105x 105x 105x 158x 182x 47x 47x 47x 47x 182x 21x 21x 21x 21x 182x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 182x 620x 620x 620x 620x 620x 620x 620x 284x 284x 620x 620x 32x 32x 304x 619x 620x 160x 160x 144x 144x 144x 144x 144x 620x 182x 162x 162x 162x 162x 162x 162x 162x 162x 3x 3x 3x 3x 159x 162x 182x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 273x 1x 1x 1x 272x 272x 272x 272x 272x 272x 272x 272x 272x 272x 273x 8x 8x 8x 8x 273x 3x 3x 3x 3x 273x 161x 161x 161x 157x 157x 157x 157x 157x 157x 159x 1x 1x 1x 1x 1x 161x 103x 103x 103x 273x 182x 95x 95x 95x 95x 95x 95x 95x 95x 8x 8x 1x 7x 95x 87x 87x 87x 86x 86x 86x 86x 86x 92x 95x 182x 90x 90x 90x 90x 90x 90x 90x 90x 90x 6x 6x 89x 84x 84x 84x 84x 82x 82x 82x 84x 86x 86x 86x 86x 90x 182x 7x 7x 7x 7x 7x 7x 5x 6x 6x 6x 6x 5x 7x 182x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 182x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 45x 45x 45x 45x 9x 9x 9x 9x 9x 2x 2x 2x 7x 7x 7x 7x 42x 42x 42x 43x 11x 1x 1x 1x 1x 1x 11x 10x 10x 10x 10x 10x 43x 8x 8x 8x 8x 8x 8x 8x 31x 23x 23x 23x 23x 23x 23x 23x 42x 46x 182x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 182x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 169x 161x 161x 161x 169x 169x 169x 169x 169x 171x 171x 171x 171x 171x 171x 171x       171x 171x 171x 171x 171x 171x 171x 171x 21x 171x 150x 150x 150x 171x 171x 171x 171x 171x 171x 171x 169x 169x 8x 8x 8x 8x 169x 169x 182x 90x 90x 90x 90x 90x 90x 90x 90x 90x 13x 13x 8x 8x 8x 13x 4x 4x 4x 13x 90x 182x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 86x 85x 85x 85x 85x 85x 85x 85x 85x 82x 82x 82x 82x 82x 85x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 82x 82x 82x 82x 82x 86x 182x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 66x 66x 66x 66x 66x 66x 66x 66x 66x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 10x 10x 10x 10x 82x 182x 92x 92x 92x 92x 182x 620x 620x 620x 619x 73x 73x 73x 126x 126x 126x 126x 126x 122x 122x 69x 69x 69x 126x 126x 620x 182x 16x 16x 16x 16x 16x 16x 14x 14x 14x 14x 16x 182x 7x 7x 7x 7x 7x 7x 7x 182x 34x 34x 34x 34x 34x 34x 34x 34x 34x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 29x 29x 29x 34x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x       13x 29x 29x 29x 34x 182x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 7x 7x 7x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 126x 126x 126x 126x 127x 127x 127x 182x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 1x 1x 1x 1x 127x 127x 127x 127x 127x 127x 127x 127x 129x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x 182x  
'use strict';
 
/* eslint-disable no-use-before-define */
 
const {
  ArrayBuffer,
  ArrayBufferPrototypeSlice,
  ArrayPrototypePush,
  ArrayPrototypeShift,
  DataViewCtor,
  FunctionPrototypeBind,
  FunctionPrototypeCall,
  MathMin,
  NumberIsInteger,
  ObjectCreate,
  ObjectDefineProperties,
  ObjectSetPrototypeOf,
  Promise,
  PromisePrototypeCatch,
  PromisePrototypeThen,
  PromiseResolve,
  PromiseReject,
  PromiseAll,
  ReflectConstruct,
  Symbol,
  SymbolAsyncIterator,
  SymbolToStringTag,
  Uint8Array,
} = primordials;
 
const {
  codes: {
    ERR_ILLEGAL_CONSTRUCTOR,
    ERR_INVALID_ARG_VALUE,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_STATE,
    ERR_INVALID_THIS,
  },
} = require('internal/errors');
 
const {
  DOMException,
} = internalBinding('messaging');
 
const {
  isArrayBufferView,
  isDataView,
} = require('internal/util/types');
 
const {
  createDeferredPromise,
  customInspectSymbol: kInspect,
} = require('internal/util');
 
const {
  serialize,
  deserialize,
} = require('v8');
 
const {
  validateObject,
} = require('internal/validators');
 
const {
  kAborted,
} = require('internal/abort_controller');
 
const {
  MessageChannel,
} = require('internal/worker/io');
 
const {
  kDeserialize,
  kTransfer,
  kTransferList,
  makeTransferable,
} = require('internal/worker/js_transferable');
 
const {
  queueMicrotask,
} = require('internal/process/task_queues');
 
const {
  kIsDisturbed,
} = require('internal/streams/utils');
 
const {
  ArrayBufferViewGetBuffer,
  ArrayBufferViewGetByteLength,
  ArrayBufferViewGetByteOffset,
  ArrayBufferGetByteLength,
  AsyncIterator,
  copyArrayBuffer,
  customInspect,
  dequeueValue,
  ensureIsPromise,
  enqueueValueWithSize,
  extractHighWaterMark,
  extractSizeAlgorithm,
  lazyTransfer,
  isBrandCheck,
  resetQueue,
  setPromiseHandled,
  transferArrayBuffer,
  nonOpCancel,
  nonOpPull,
  nonOpStart,
  kType,
  kState,
  kEnumerableProperty,
} = require('internal/webstreams/util');
 
const {
  WritableStreamDefaultWriter,
 
  isWritableStream,
  isWritableStreamLocked,
  isWritableStreamDefaultController,
  isWritableStreamDefaultWriter,
 
  writableStreamAbort,
  writableStreamCloseQueuedOrInFlight,
  writableStreamDefaultWriterCloseWithErrorPropagation,
  writableStreamDefaultWriterRelease,
  writableStreamDefaultWriterWrite,
} = require('internal/webstreams/writablestream');
 
const assert = require('internal/assert');
 
const kCancel = Symbol('kCancel');
const kClose = Symbol('kClose');
const kChunk = Symbol('kChunk');
const kError = Symbol('kError');
const kPull = Symbol('kPull');
 
/**
 * @typedef {import('../abort_controller').AbortSignal} AbortSignal
 * @typedef {import('./queuingstrategies').QueuingStrategy} QueuingStrategy
 * @typedef {import('./queuingstrategies').QueuingStrategySize
 * } QueuingStrategySize
 * @typedef {import('./writablestream').WritableStream} WritableStream
 *
 * @typedef {ReadableStreamDefaultController | ReadableByteStreamController
 * } ReadableStreamController
 *
 * @typedef {ReadableStreamDefaultReader | ReadableStreamBYOBReader
 * } ReadableStreamReader
 *
 * @callback UnderlyingSourceStartCallback
 * @param {ReadableStreamController} controller
 * @returns { any | Promise<void> }
 *
 * @callback UnderlyingSourcePullCallback
 * @param {ReadableStreamController} controller
 * @returns { Promise<void> }
 *
 * @callback UnderlyingSourceCancelCallback
 * @param {any} reason
 * @returns { Promise<void> }
 *
 * @typedef {{
 *   readable: ReadableStream,
 *   writable: WritableStream,
 * }} ReadableWritablePair
 *
 * @typedef {{
 *   preventClose? : boolean,
 *   preventAbort? : boolean,
 *   preventCancel? : boolean,
 *   signal? : AbortSignal,
 * }} StreamPipeOptions
 *
 * @typedef {{
 *   start? : UnderlyingSourceStartCallback,
 *   pull? : UnderlyingSourcePullCallback,
 *   cancel? : UnderlyingSourceCancelCallback,
 *   type? : "bytes",
 *   autoAllocateChunkSize? : number
 * }} UnderlyingSource
 *
 */
 
class ReadableStream {
  [kType] = 'ReadableStream';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  /**
   * @param {UnderlyingSource} [source]
   * @param {QueuingStrategy} [strategy]
   */
  constructor(source = {}, strategy = {}) {
    if (source === null)
      throw new ERR_INVALID_ARG_VALUE('source', 'Object', source);
    this[kState] = {
      disturbed: false,
      state: 'readable',
      storedError: undefined,
      stream: undefined,
      transfer: {
        writable: undefined,
        port1: undefined,
        port2: undefined,
        promise: undefined,
      }
    };
 
    // The spec requires handling of the strategy first
    // here. Specifically, if getting the size and
    // highWaterMark from the strategy fail, that has
    // to trigger a throw before getting the details
    // from the source. So be sure to keep these in
    // this order.
    const size = strategy?.size;
    const highWaterMark = strategy?.highWaterMark;
    const type = source.type;
 
    if (`${type}` === 'bytes') {
      if (size !== undefined)
        throw new ERR_INVALID_ARG_VALUE.RangeError('strategy.size', size);
      setupReadableByteStreamControllerFromSource(
        this,
        source,
        extractHighWaterMark(highWaterMark, 0));
      return;
    }
 
    if (type !== undefined)
      throw new ERR_INVALID_ARG_VALUE('source.type', type);
    setupReadableStreamDefaultControllerFromSource(
      this,
      source,
      extractHighWaterMark(highWaterMark, 1),
      extractSizeAlgorithm(size));
 
    // eslint-disable-next-line no-constructor-return
    return makeTransferable(this);
  }
 
  get [kIsDisturbed]() {
    return this[kState].disturbed;
  }
 
  /**
   * @readonly
   * @type {boolean}
   */
  get locked() {
    if (!isReadableStream(this))
      throw new ERR_INVALID_THIS('ReadableStream');
    return isReadableStreamLocked(this);
  }
 
  /**
   * @param {any} [reason]
   * @returns { Promise<void> }
   */
  cancel(reason = undefined) {
    if (!isReadableStream(this))
      return PromiseReject(new ERR_INVALID_THIS('ReadableStream'));
    if (isReadableStreamLocked(this)) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError('ReadableStream is locked'));
    }
    return readableStreamCancel(this, reason);
  }
 
  /**
   * @param {{
   *   mode? : "byob"
   * }} [options]
   * @returns {ReadableStreamReader}
   */
  getReader(options = {}) {
    if (!isReadableStream(this))
      throw new ERR_INVALID_THIS('ReadableStream');
    validateObject(options, 'options', { nullable: true, allowFunction: true });
    const mode = options?.mode;
 
    if (mode === undefined)
      return new ReadableStreamDefaultReader(this);
 
    if (`${mode}` !== 'byob')
      throw new ERR_INVALID_ARG_VALUE('options.mode', mode);
    return new ReadableStreamBYOBReader(this);
  }
 
  /**
   * @param {ReadableWritablePair} transform
   * @param {StreamPipeOptions} [options]
   * @returns {ReadableStream}
   */
  pipeThrough(transform, options = {}) {
    if (!isReadableStream(this))
      throw new ERR_INVALID_THIS('ReadableStream');
    const readable = transform?.readable;
    if (!isReadableStream(readable)) {
      throw new ERR_INVALID_ARG_TYPE(
        'transform.readable',
        'ReadableStream',
        readable);
    }
    const writable = transform?.writable;
    if (!isWritableStream(writable)) {
      throw new ERR_INVALID_ARG_TYPE(
        'transform.writable',
        'WritableStream',
        writable);
    }
 
    // The web platform tests require that these be handled one at a
    // time and in a specific order. options can be null or undefined.
    const preventAbort = options?.preventAbort;
    const preventCancel = options?.preventCancel;
    const preventClose = options?.preventClose;
    const signal = options?.signal;
 
    if (signal !== undefined && signal?.[kAborted] === undefined)
      throw new ERR_INVALID_ARG_TYPE('options.signal', 'AbortSignal', signal);
 
    if (isReadableStreamLocked(this))
      throw new ERR_INVALID_STATE.TypeError('The ReadableStream is locked');
    if (isWritableStreamLocked(writable))
      throw new ERR_INVALID_STATE.TypeError('The WritableStream is locked');
 
    const promise = readableStreamPipeTo(
      this,
      writable,
      !!preventClose,
      !!preventAbort,
      !!preventCancel,
      signal);
    setPromiseHandled(promise);
 
    return readable;
  }
 
  /**
   * @param {WritableStream} destination
   * @param {StreamPipeOptions} [options]
   * @returns {Promise<void>}
   */
  pipeTo(destination, options = {}) {
    try {
      if (!isReadableStream(this))
        throw new ERR_INVALID_THIS('ReadableStream');
      if (!isWritableStream(destination)) {
        throw new ERR_INVALID_ARG_TYPE(
          'transform.writable',
          'WritableStream',
          destination);
      }
 
      const preventAbort = options?.preventAbort;
      const preventCancel = options?.preventCancel;
      const preventClose = options?.preventClose;
      const signal = options?.signal;
 
      if (signal !== undefined && signal?.[kAborted] === undefined)
        throw new ERR_INVALID_ARG_TYPE('options.signal', 'AbortSignal', signal);
 
      if (isReadableStreamLocked(this))
        throw new ERR_INVALID_STATE.TypeError('The ReadableStream is locked');
      if (isWritableStreamLocked(destination))
        throw new ERR_INVALID_STATE.TypeError('The WritableStream is locked');
 
      return readableStreamPipeTo(
        this,
        destination,
        !!preventClose,
        !!preventAbort,
        !!preventCancel,
        signal);
    } catch (error) {
      return PromiseReject(error);
    }
  }
 
  /**
   * @returns {ReadableStream[]}
   */
  tee() {
    if (!isReadableStream(this))
      throw new ERR_INVALID_THIS('ReadableStream');
    return readableStreamTee(this, false);
  }
 
  /**
   * @param {{
   *   preventCancel? : boolean,
   * }} [options]
   * @returns {AsyncIterable}
   */
  values(options = {}) {
    if (!isReadableStream(this))
      throw new ERR_INVALID_THIS('ReadableStream');
    validateObject(options, 'options');
    const {
      preventCancel = false,
    } = options;
 
    const reader = new ReadableStreamDefaultReader(this);
    let done = false;
    let started = false;
    let current;
 
    // The nextSteps function is not an async function in order
    // to make it more efficient. Because nextSteps explicitly
    // creates a Promise and returns it in the common case,
    // making it an async function just causes two additional
    // unnecessary Promise allocations to occur, which just add
    // cost.
    function nextSteps() {
      if (done)
        return PromiseResolve({ done: true, value: undefined });
 
      if (reader[kState].stream === undefined) {
        return PromiseReject(
          new ERR_INVALID_STATE.TypeError(
            'The reader is not bound to a ReadableStream'));
      }
      const promise = createDeferredPromise();
 
      readableStreamDefaultReaderRead(reader, {
        [kChunk](chunk) {
          current = undefined;
          promise.resolve({ value: chunk, done: false });
        },
        [kClose]() {
          current = undefined;
          done = true;
          readableStreamReaderGenericRelease(reader);
          promise.resolve({ done: true, value: undefined });
        },
        [kError](error) {
          current = undefined;
          done = true;
          readableStreamReaderGenericRelease(reader);
          promise.reject(error);
        }
      });
      return promise.promise;
    }
 
    async function returnSteps(value) {
      if (done)
        return { done: true, value };
      done = true;
 
      if (reader[kState].stream === undefined) {
        throw new ERR_INVALID_STATE.TypeError(
          'The reader is not bound to a ReadableStream');
      }
      assert(!reader[kState].readRequests.length);
      if (!preventCancel) {
        const result = readableStreamReaderGenericCancel(reader, value);
        readableStreamReaderGenericRelease(reader);
        await result;
        return { done: true, value };
      }
 
      readableStreamReaderGenericRelease(reader);
      return { done: true, value };
    }
 
    // TODO(@jasnell): Explore whether an async generator
    // can be used here instead of a custom iterator object.
    return ObjectSetPrototypeOf({
      // Changing either of these functions (next or return)
      // to async functions causes a failure in the streams
      // Web Platform Tests that check for use of a modified
      // Promise.prototype.then. Since the await keyword
      // uses Promise.prototype.then, it is open to prototype
      // pollution, which causes the test to fail. The other
      // await uses here do not trigger that failure because
      // the test that fails does not trigger those code paths.
      next() {
        // If this is the first read, delay by one microtask
        // to ensure that the controller has had an opportunity
        // to properly start and perform the initial pull.
        // TODO(@jasnell): The spec doesn't call this out so
        // need to investigate if it's a bug in our impl or
        // the spec.
        if (!started) {
          current = PromiseResolve();
          started = true;
        }
        current = current !== undefined ?
          PromisePrototypeThen(current, nextSteps, nextSteps) :
          nextSteps();
        return current;
      },
 
      return(error) {
        return current ?
          PromisePrototypeThen(
            current,
            () => returnSteps(error),
            () => returnSteps(error)) :
          returnSteps(error);
      },
 
      [SymbolAsyncIterator]() { return this; }
    }, AsyncIterator);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], {
      locked: this.locked,
      state: this[kState].state,
    });
  }
 
  [kTransfer]() {
    if (!isReadableStream(this))
      throw new ERR_INVALID_THIS('ReadableStream');
    if (this.locked) {
      this[kState].transfer.port1?.close();
      this[kState].transfer.port1 = undefined;
      this[kState].transfer.port2 = undefined;
      throw new DOMException(
        'Cannot transfer a locked ReadableStream',
        'DataCloneError');
    }
 
    const {
      writable,
      promise,
    } = lazyTransfer().newCrossRealmWritableSink(
      this,
      this[kState].transfer.port1);
 
    this[kState].transfer.writable = writable;
    this[kState].transfer.promise = promise;
 
    return {
      data: { port: this[kState].transfer.port2 },
      deserializeInfo:
        'internal/webstreams/readablestream:TransferredReadableStream'
    };
  }
 
  [kTransferList]() {
    const { port1, port2 } = new MessageChannel();
    this[kState].transfer.port1 = port1;
    this[kState].transfer.port2 = port2;
    return [ port2 ];
  }
 
  [kDeserialize]({ port }) {
    const transfer = lazyTransfer();
    setupReadableStreamDefaultControllerFromSource(
      this,
      new transfer.CrossRealmTransformReadableSource(port),
      0, () => 1);
  }
}
 
ObjectDefineProperties(ReadableStream.prototype, {
  [SymbolAsyncIterator]: {
    configurable: true,
    enumerable: false,
    writable: true,
    value: ReadableStream.prototype.values,
  },
  locked: kEnumerableProperty,
  cancel: kEnumerableProperty,
  getReader: kEnumerableProperty,
  pipeThrough: kEnumerableProperty,
  pipeTo: kEnumerableProperty,
  tee: kEnumerableProperty,
});
 
function TransferredReadableStream() {
  return makeTransferable(ReflectConstruct(
    function() {
      this[kType] = 'ReadableStream';
      this[kState] = {
        disturbed: false,
        state: 'readable',
        storedError: undefined,
        stream: undefined,
        transfer: {
          writable: undefined,
          port: undefined,
          promise: undefined,
        }
      };
    },
    [], ReadableStream));
}
TransferredReadableStream.prototype[kDeserialize] = () => {};
 
class ReadableStreamBYOBRequest {
  [kType] = 'ReadableStreamBYOBRequest';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  constructor() {
    throw new ERR_ILLEGAL_CONSTRUCTOR();
  }
 
  /**
   * @readonly
   * @type {ArrayBufferView}
   */
  get view() {
    if (!isReadableStreamBYOBRequest(this))
      throw new ERR_INVALID_THIS('ReadableStreamBYOBRequest');
    return this[kState].view;
  }
 
  /**
   * @param {number} bytesWritten
   */
  respond(bytesWritten) {
    if (!isReadableStreamBYOBRequest(this))
      throw new ERR_INVALID_THIS('ReadableStreamBYOBRequest');
    const {
      view,
      controller,
    } = this[kState];
    if (controller === undefined) {
      throw new ERR_INVALID_STATE.TypeError(
        'This BYOB request has been invalidated');
    }
 
    const viewByteLength = ArrayBufferViewGetByteLength(view);
    const viewBuffer = ArrayBufferViewGetBuffer(view);
    const viewBufferByteLength = ArrayBufferGetByteLength(viewBuffer);
 
    if (viewByteLength === 0 || viewBufferByteLength === 0) {
      throw new ERR_INVALID_STATE.TypeError(
        'View ArrayBuffer is zero-length or detached');
    }
 
    readableByteStreamControllerRespond(controller, bytesWritten);
  }
 
  /**
   * @param {ArrayBufferView} view
   */
  respondWithNewView(view) {
    if (!isReadableStreamBYOBRequest(this))
      throw new ERR_INVALID_THIS('ReadableStreamBYOBRequest');
    const {
      controller,
    } = this[kState];
 
    if (controller === undefined) {
      throw new ERR_INVALID_STATE.TypeError(
        'This BYOB request has been invalidated');
    }
 
    readableByteStreamControllerRespondWithNewView(controller, view);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], {
      view: this.view,
      controller: this[kState].controller,
    });
  }
}
 
ObjectDefineProperties(ReadableStreamBYOBRequest.prototype, {
  view: kEnumerableProperty,
  respond: kEnumerableProperty,
  respondWithNewView: kEnumerableProperty,
});
 
function createReadableStreamBYOBRequest(controller, view) {
  return ReflectConstruct(
    function() {
      this[kType] = 'ReadableStreamBYOBRequest';
      this[kState] = {
        controller,
        view,
      };
    },
    [],
    ReadableStreamBYOBRequest
  );
}
 
class DefaultReadRequest {
  constructor() {
    this[kState] = createDeferredPromise();
  }
 
  [kChunk](value) {
    this[kState].resolve?.({ value, done: false });
  }
 
  [kClose]() {
    this[kState].resolve?.({ value: undefined, done: true });
  }
 
  [kError](error) {
    this[kState].reject?.(error);
  }
 
  get promise() { return this[kState].promise; }
}
 
class ReadIntoRequest {
  constructor() {
    this[kState] = createDeferredPromise();
  }
 
  [kChunk](value) {
    this[kState].resolve?.({ value, done: false });
  }
 
  [kClose](value) {
    this[kState].resolve?.({ value, done: true });
  }
 
  [kError](error) {
    this[kState].reject?.(error);
  }
 
  get promise() { return this[kState].promise; }
}
 
class ReadableStreamDefaultReader {
  [kType] = 'ReadableStreamDefaultReader';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  /**
   * @param {ReadableStream} stream
   */
  constructor(stream) {
    if (!isReadableStream(stream))
      throw new ERR_INVALID_ARG_TYPE('stream', 'ReadableStream', stream);
    this[kState] = {
      readRequests: [],
      stream: undefined,
      close: {
        promise: undefined,
        resolve: undefined,
        reject: undefined,
      },
    };
    setupReadableStreamDefaultReader(this, stream);
  }
 
  /**
   * @returns {Promise<{
   *   value : any,
   *   done : boolean
   * }>}
   */
  read() {
    if (!isReadableStreamDefaultReader(this))
      return PromiseReject(new ERR_INVALID_THIS('ReadableStreamDefaultReader'));
    if (this[kState].stream === undefined) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError(
          'The reader is not attached to a stream'));
    }
    const readRequest = new DefaultReadRequest();
    readableStreamDefaultReaderRead(this, readRequest);
    return readRequest.promise;
  }
 
  releaseLock() {
    if (!isReadableStreamDefaultReader(this))
      throw new ERR_INVALID_THIS('ReadableStreamDefaultReader');
    if (this[kState].stream === undefined)
      return;
    if (this[kState].readRequests.length) {
      throw new ERR_INVALID_STATE.TypeError(
        'Cannot release with pending read requests');
    }
    readableStreamReaderGenericRelease(this);
  }
 
  /**
   * @readonly
   * @type {Promise<void>}
   */
  get closed() {
    if (!isReadableStreamDefaultReader(this))
      return PromiseReject(new ERR_INVALID_THIS('ReadableStreamDefaultReader'));
    return this[kState].close.promise;
  }
 
  /**
   * @param {any} reason
   * @returns {Promise<void>}
   */
  cancel(reason = undefined) {
    if (!isReadableStreamDefaultReader(this))
      return PromiseReject(new ERR_INVALID_THIS('ReadableStreamDefaultReader'));
    if (this[kState].stream === undefined) {
      return PromiseReject(new ERR_INVALID_STATE.TypeError(
        'The reader is not attached to a stream'));
    }
    return readableStreamReaderGenericCancel(this, reason);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], {
      stream: this[kState].stream,
      readRequests: this[kState].readRequests.length,
      close: this[kState].close.promise,
    });
  }
}
 
ObjectDefineProperties(ReadableStreamDefaultReader.prototype, {
  closed: kEnumerableProperty,
  read: kEnumerableProperty,
  releaseLock: kEnumerableProperty,
  cancel: kEnumerableProperty,
});
 
class ReadableStreamBYOBReader {
  [kType] = 'ReadableStreamBYOBReader';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  /**
   * @param {ReadableStream} stream
   */
  constructor(stream) {
    if (!isReadableStream(stream))
      throw new ERR_INVALID_ARG_TYPE('stream', 'ReadableStream', stream);
    this[kState] = {
      stream: undefined,
      requestIntoRequests: [],
      close: {
        promise: undefined,
        resolve: undefined,
        reject: undefined,
      },
    };
    setupReadableStreamBYOBReader(this, stream);
  }
 
  /**
   * @param {ArrayBufferView} view
   * @returns {Promise<{
   *   view : ArrayBufferView,
   *   done : boolean,
   * }>}
   */
  read(view) {
    if (!isReadableStreamBYOBReader(this))
      return PromiseReject(new ERR_INVALID_THIS('ReadableStreamBYOBReader'));
    if (!isArrayBufferView(view)) {
      return PromiseReject(
        new ERR_INVALID_ARG_TYPE(
          'view',
          [
            'Buffer',
            'TypedArray',
            'DataView',
          ],
          view));
    }
    const viewByteLength = ArrayBufferViewGetByteLength(view);
    const viewBuffer = ArrayBufferViewGetBuffer(view);
    const viewBufferByteLength = ArrayBufferGetByteLength(viewBuffer);
 
    if (viewByteLength === 0 || viewBufferByteLength === 0) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError(
          'View ArrayBuffer is zero-length or detached'));
    }
    // Supposed to assert here that the view's buffer is not
    // detached, but there's no API available to use to check that.
    if (this[kState].stream === undefined) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError(
          'The reader is not attached to a stream'));
    }
    const readIntoRequest = new ReadIntoRequest();
    readableStreamBYOBReaderRead(this, view, readIntoRequest);
    return readIntoRequest.promise;
  }
 
  releaseLock() {
    if (!isReadableStreamBYOBReader(this))
      throw new ERR_INVALID_THIS('ReadableStreamBYOBReader');
    if (this[kState].stream === undefined)
      return;
    if (this[kState].readIntoRequests.length) {
      throw new ERR_INVALID_STATE.TypeError(
        'Cannot release with pending read requests');
    }
    readableStreamReaderGenericRelease(this);
  }
 
  /**
   * @readonly
   * @type {Promise<void>}
   */
  get closed() {
    if (!isReadableStreamBYOBReader(this))
      return PromiseReject(new ERR_INVALID_THIS('ReadableStreamBYOBReader'));
    return this[kState].close.promise;
  }
 
  /**
   * @param {any} reason
   * @returns {Promise<void>}
   */
  cancel(reason = undefined) {
    if (!isReadableStreamBYOBReader(this))
      return PromiseReject(new ERR_INVALID_THIS('ReadableStreamBYOBReader'));
    if (this[kState].stream === undefined) {
      return PromiseReject(new ERR_INVALID_STATE.TypeError(
        'The reader is not attached to a stream'));
    }
    return readableStreamReaderGenericCancel(this, reason);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], {
      stream: this[kState].stream,
      requestIntoRequests: this[kState].requestIntoRequests.length,
      close: this[kState].close.promise,
    });
  }
}
 
ObjectDefineProperties(ReadableStreamBYOBReader.prototype, {
  closed: kEnumerableProperty,
  read: kEnumerableProperty,
  releaseLock: kEnumerableProperty,
  cancel: kEnumerableProperty,
});
 
class ReadableStreamDefaultController {
  [kType] = 'ReadableStreamDefaultController';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  constructor() {
    throw new ERR_ILLEGAL_CONSTRUCTOR();
  }
 
  /**
   * @readonly
   * @type {number}
   */
  get desiredSize() {
    return readableStreamDefaultControllerGetDesiredSize(this);
  }
 
  close() {
    if (!readableStreamDefaultControllerCanCloseOrEnqueue(this))
      throw new ERR_INVALID_STATE.TypeError('Controller is already closed');
    readableStreamDefaultControllerClose(this);
  }
 
  /**
   * @param {any} chunk
   */
  enqueue(chunk = undefined) {
    if (!readableStreamDefaultControllerCanCloseOrEnqueue(this))
      throw new ERR_INVALID_STATE.TypeError('Controller is already closed');
    readableStreamDefaultControllerEnqueue(this, chunk);
  }
 
  /**
   * @param {any} error
   */
  error(error = undefined) {
    readableStreamDefaultControllerError(this, error);
  }
 
  [kCancel](reason) {
    return readableStreamDefaultControllerCancelSteps(this, reason);
  }
 
  [kPull](readRequest) {
    readableStreamDefaultControllerPullSteps(this, readRequest);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], { });
  }
}
 
ObjectDefineProperties(ReadableStreamDefaultController.prototype, {
  desiredSize: kEnumerableProperty,
  close: kEnumerableProperty,
  enqueue: kEnumerableProperty,
  error: kEnumerableProperty,
});
 
function createReadableStreamDefaultController() {
  return ReflectConstruct(
    function() {
      this[kType] = 'ReadableStreamDefaultController';
      this[kState] = {};
    },
    [],
    ReadableStreamDefaultController,
  );
}
 
class ReadableByteStreamController {
  [kType] = 'ReadableByteStreamController';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  constructor() {
    throw new ERR_ILLEGAL_CONSTRUCTOR();
  }
 
  /**
   * @readonly
   * @type {ReadableStreamBYOBRequest}
   */
  get byobRequest() {
    if (!isReadableByteStreamController(this))
      throw new ERR_INVALID_THIS('ReadableByteStreamController');
    if (this[kState].byobRequest === null &&
        this[kState].pendingPullIntos.length) {
      const {
        buffer,
        byteOffset,
        bytesFilled,
        byteLength,
      } = this[kState].pendingPullIntos[0];
      const view =
        new Uint8Array(
          buffer,
          byteOffset + bytesFilled,
          byteLength - bytesFilled);
      this[kState].byobRequest = createReadableStreamBYOBRequest(this, view);
    }
    return this[kState].byobRequest;
  }
 
  /**
   * @readonly
   * @type {number}
   */
  get desiredSize() {
    if (!isReadableByteStreamController(this))
      throw new ERR_INVALID_THIS('ReadableByteStreamController');
    return readableByteStreamControllerGetDesiredSize(this);
  }
 
  close() {
    if (!isReadableByteStreamController(this))
      throw new ERR_INVALID_THIS('ReadableByteStreamController');
    if (this[kState].closeRequested)
      throw new ERR_INVALID_STATE.TypeError('Controller is already closed');
    if (this[kState].stream[kState].state !== 'readable')
      throw new ERR_INVALID_STATE.TypeError('ReadableStream is already closed');
    readableByteStreamControllerClose(this);
  }
 
  /**
   * @param {ArrayBufferView} chunk
   */
  enqueue(chunk) {
    if (!isReadableByteStreamController(this))
      throw new ERR_INVALID_THIS('ReadableByteStreamController');
    if (!isArrayBufferView(chunk)) {
      throw new ERR_INVALID_ARG_TYPE(
        'chunk',
        [
          'Buffer',
          'TypedArray',
          'DataView',
        ],
        chunk);
    }
    const chunkByteLength = ArrayBufferViewGetByteLength(chunk);
    const chunkByteOffset = ArrayBufferViewGetByteOffset(chunk);
    const chunkBuffer = ArrayBufferViewGetBuffer(chunk);
    const chunkBufferByteLength = ArrayBufferGetByteLength(chunkBuffer);
    if (chunkByteLength === 0 || chunkBufferByteLength === 0) {
      throw new ERR_INVALID_STATE.TypeError(
        'chunk ArrayBuffer is zero-length or detached');
    }
    if (this[kState].closeRequested)
      throw new ERR_INVALID_STATE.TypeError('Controller is already closed');
    if (this[kState].stream[kState].state !== 'readable')
      throw new ERR_INVALID_STATE.TypeError('ReadableStream is already closed');
    readableByteStreamControllerEnqueue(
      this,
      chunkBuffer,
      chunkByteLength,
      chunkByteOffset);
  }
 
  /**
   * @param {any} error
   */
  error(error = undefined) {
    if (!isReadableByteStreamController(this))
      throw new ERR_INVALID_THIS('ReadableByteStreamController');
    readableByteStreamControllerError(this, error);
  }
 
  [kCancel](reason) {
    return readableByteStreamControllerCancelSteps(this, reason);
  }
 
  [kPull](readRequest) {
    readableByteStreamControllerPullSteps(this, readRequest);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], { });
  }
}
 
ObjectDefineProperties(ReadableByteStreamController.prototype, {
  byobRequest: kEnumerableProperty,
  desiredSize: kEnumerableProperty,
  close: kEnumerableProperty,
  enqueue: kEnumerableProperty,
  error: kEnumerableProperty,
});
 
function createReadableByteStreamController() {
  return ReflectConstruct(
    function() {
      this[kType] = 'ReadableByteStreamController';
      this[kState] = {};
    },
    [],
    ReadableByteStreamController,
  );
}
 
function createTeeReadableStream(start, pull, cancel) {
  return ReflectConstruct(
    function() {
      this[kType] = 'ReadableStream';
      this[kState] = {
        disturbed: false,
        state: 'readable',
        storedError: undefined,
        stream: undefined,
        transfer: {
          writable: undefined,
          port: undefined,
          promise: undefined,
        }
      };
      setupReadableStreamDefaultControllerFromSource(
        this,
        ObjectCreate(null, {
          start: { value: start },
          pull: { value: pull },
          cancel: { value: cancel }
        }),
        1,
        () => 1);
      return makeTransferable(this);
    }, [], ReadableStream,
  );
}
 
const isReadableStream =
  isBrandCheck('ReadableStream');
const isReadableByteStreamController =
  isBrandCheck('ReadableByteStreamController');
const isReadableStreamBYOBRequest =
  isBrandCheck('ReadableStreamBYOBRequest');
const isReadableStreamDefaultReader =
  isBrandCheck('ReadableStreamDefaultReader');
const isReadableStreamBYOBReader =
  isBrandCheck('ReadableStreamBYOBReader');
 
// ---- ReadableStream Implementation
 
function readableStreamPipeTo(
  source,
  dest,
  preventClose,
  preventAbort,
  preventCancel,
  signal) {
 
  let reader;
  let writer;
  // Both of these can throw synchronously. We want to capture
  // the error and return a rejected promise instead.
  try {
    reader = new ReadableStreamDefaultReader(source);
    writer = new WritableStreamDefaultWriter(dest);
  } catch (error) {
    return PromiseReject(error);
  }
 
  source[kState].disturbed = true;
 
  let shuttingDown = false;
 
  if (signal !== undefined && signal?.[kAborted] === undefined) {
    return PromiseReject(
      new ERR_INVALID_ARG_TYPE(
        'options.signal',
        'AbortSignal',
        signal));
  }
 
  const promise = createDeferredPromise();
 
  let currentWrite = PromiseResolve();
 
  // The error here can be undefined. The rejected arg
  // tells us that the promise must be rejected even
  // when error is undefine.
  function finalize(rejected, error) {
    writableStreamDefaultWriterRelease(writer);
    readableStreamReaderGenericRelease(reader);
    if (signal !== undefined)
      signal.removeEventListener('abort', abortAlgorithm);
    if (rejected)
      promise.reject(error);
    else
      promise.resolve();
  }
 
  async function waitForCurrentWrite() {
    const write = currentWrite;
    await write;
    if (write !== currentWrite)
      await waitForCurrentWrite();
  }
 
  function shutdownWithAnAction(action, rejected, originalError) {
    if (shuttingDown) return;
    shuttingDown = true;
    if (dest[kState].state === 'writable' &&
        !writableStreamCloseQueuedOrInFlight(dest)) {
      PromisePrototypeThen(
        waitForCurrentWrite(),
        complete,
        (error) => finalize(true, error));
      return;
    }
    complete();
 
    function complete() {
      PromisePrototypeThen(
        action(),
        () => finalize(rejected, originalError),
        (error) => finalize(true, error));
    }
  }
 
  function shutdown(rejected, error) {
    if (shuttingDown) return;
    shuttingDown = true;
    if (dest[kState].state === 'writable' &&
        !writableStreamCloseQueuedOrInFlight(dest)) {
      PromisePrototypeThen(
        waitForCurrentWrite(),
        () => finalize(rejected, error),
        (error) => finalize(true, error));
      return;
    }
    finalize(rejected, error);
  }
 
  function abortAlgorithm() {
    // Cannot use the AbortError class here. It must be a DOMException
    const error = new DOMException('The operation was aborted', 'AbortError');
    const actions = [];
    if (!preventAbort) {
      ArrayPrototypePush(
        actions,
        () => {
          if (dest[kState].state === 'writable')
            return writableStreamAbort(dest, error);
          return PromiseResolve();
        });
    }
    if (!preventCancel) {
      ArrayPrototypePush(
        actions,
        () => {
          if (source[kState].state === 'readable')
            return readableStreamCancel(source, error);
          return PromiseResolve();
        });
    }
 
    shutdownWithAnAction(
      async () => PromiseAll(actions.map((action) => action())),
      true,
      error);
  }
 
  function watchErrored(stream, promise, action) {
    if (stream[kState].state === 'errored')
      action(stream[kState].storedError);
    else
      PromisePrototypeCatch(promise, action);
  }
 
  function watchClosed(stream, promise, action) {
    if (stream[kState].state === 'closed')
      action(stream[kState].storedError);
    else
      PromisePrototypeThen(promise, action, () => {});
  }
 
  async function step() {
    if (shuttingDown)
      return true;
    await writer[kState].ready.promise;
    return new Promise((resolve, reject) => {
      readableStreamDefaultReaderRead(
        reader,
        {
          [kChunk](chunk) {
            currentWrite = writableStreamDefaultWriterWrite(writer, chunk);
            setPromiseHandled(currentWrite);
            resolve(false);
          },
          [kClose]: () => resolve(true),
          [kError]: reject,
        });
    });
  }
 
  async function run() {
    // Run until step resolves as true
    while (!await step()) {}
  }
 
  if (signal !== undefined) {
    if (signal.aborted) {
      abortAlgorithm();
      return promise.promise;
    }
    signal.addEventListener('abort', abortAlgorithm, { once: true });
  }
 
  setPromiseHandled(run());
 
  watchErrored(source, reader[kState].close.promise, (error) => {
    if (!preventAbort) {
      return shutdownWithAnAction(
        () => writableStreamAbort(dest, error),
        true,
        error);
    }
    shutdown(true, error);
  });
 
  watchErrored(dest, writer[kState].close.promise, (error) => {
    if (!preventCancel) {
      return shutdownWithAnAction(
        () => readableStreamCancel(source, error),
        true,
        error);
    }
    shutdown(true, error);
  });
 
  watchClosed(source, reader[kState].close.promise, () => {
    if (!preventClose) {
      return shutdownWithAnAction(
        () => writableStreamDefaultWriterCloseWithErrorPropagation(writer));
    }
    shutdown();
  });
 
  if (writableStreamCloseQueuedOrInFlight(dest) ||
      dest[kState].state === 'closed') {
    const error = new ERR_INVALID_STATE.TypeError(
      'Destination WritableStream is closed');
    if (!preventCancel) {
      shutdownWithAnAction(
        () => readableStreamCancel(source, error), true, error);
    } else {
      shutdown(true, error);
    }
  }
 
  return promise.promise;
}
 
function readableStreamTee(stream, cloneForBranch2) {
  const reader = new ReadableStreamDefaultReader(stream);
  let reading = false;
  let canceled1 = false;
  let canceled2 = false;
  let reason1;
  let reason2;
  let branch1;
  let branch2;
  const cancelPromise = createDeferredPromise();
 
  async function pullAlgorithm() {
    if (reading) return;
    reading = true;
    const readRequest = {
      [kChunk](value) {
        queueMicrotask(() => {
          reading = false;
          const value1 = value;
          let value2 = value;
          if (!canceled2 && cloneForBranch2) {
            // Structured Clone
            value2 = deserialize(serialize(value2));
          }
          if (!canceled1) {
            readableStreamDefaultControllerEnqueue(
              branch1[kState].controller,
              value1);
          }
          if (!canceled2) {
            readableStreamDefaultControllerEnqueue(
              branch2[kState].controller,
              value2);
          }
        });
      },
      [kClose]() {
        reading = false;
        if (!canceled1)
          readableStreamDefaultControllerClose(branch1[kState].controller);
        if (!canceled2)
          readableStreamDefaultControllerClose(branch2[kState].controller);
        if (!canceled1 || !canceled2)
          cancelPromise.resolve();
      },
      [kError]() {
        reading = false;
      },
    };
    readableStreamDefaultReaderRead(reader, readRequest);
  }
 
  function cancel1Algorithm(reason) {
    canceled1 = true;
    reason1 = reason;
    if (canceled2) {
      const compositeReason = [reason1, reason2];
      cancelPromise.resolve(readableStreamCancel(stream, compositeReason));
    }
    return cancelPromise.promise;
  }
 
  function cancel2Algorithm(reason) {
    canceled2 = true;
    reason2 = reason;
    if (canceled1) {
      const compositeReason = [reason1, reason2];
      cancelPromise.resolve(readableStreamCancel(stream, compositeReason));
    }
    return cancelPromise.promise;
  }
 
  branch1 =
    createTeeReadableStream(nonOpStart, pullAlgorithm, cancel1Algorithm);
  branch2 =
    createTeeReadableStream(nonOpStart, pullAlgorithm, cancel2Algorithm);
 
  PromisePrototypeCatch(
    reader[kState].close.promise,
    (error) => {
      readableStreamDefaultControllerError(branch1[kState].controller, error);
      readableStreamDefaultControllerError(branch2[kState].controller, error);
      if (!canceled1 || !canceled2)
        cancelPromise.resolve();
    });
 
  return [branch1, branch2];
}
 
function readableByteStreamControllerConvertPullIntoDescriptor(desc) {
  const {
    buffer,
    bytesFilled,
    byteLength,
    byteOffset,
    ctor,
    elementSize,
  } = desc;
  if (bytesFilled > byteLength)
    throw new ERR_INVALID_STATE.RangeError('The buffer size is invalid');
  assert(!(bytesFilled % elementSize));
  const transferredBuffer = transferArrayBuffer(buffer);
  return new ctor(transferredBuffer, byteOffset, bytesFilled / elementSize);
}
 
function isReadableStreamLocked(stream) {
  return stream[kState].reader !== undefined;
}
 
function readableStreamCancel(stream, reason) {
  stream[kState].disturbed = true;
  switch (stream[kState].state) {
    case 'closed':
      return PromiseResolve();
    case 'errored':
      return PromiseReject(stream[kState].storedError);
  }
  readableStreamClose(stream);
  const {
    reader,
  } = stream[kState];
  if (reader !== undefined && readableStreamHasBYOBReader(stream)) {
    for (let n = 0; n < reader[kState].readIntoRequests.length; n++)
      reader[kState].readIntoRequests[n][kClose]();
    reader[kState].readIntoRequests = [];
  }
 
  return PromisePrototypeThen(
    ensureIsPromise(
      stream[kState].controller[kCancel],
      stream[kState].controller,
      reason),
    () => {});
}
 
function readableStreamClose(stream) {
  assert(stream[kState].state === 'readable');
  stream[kState].state = 'closed';
 
  const {
    reader,
  } = stream[kState];
 
  if (reader === undefined)
    return;
 
  reader[kState].close.resolve();
 
  if (readableStreamHasDefaultReader(stream)) {
    for (let n = 0; n < reader[kState].readRequests.length; n++)
      reader[kState].readRequests[n][kClose]();
    reader[kState].readRequests = [];
  }
}
 
function readableStreamError(stream, error) {
  assert(stream[kState].state === 'readable');
  stream[kState].state = 'errored';
  stream[kState].storedError = error;
 
  const {
    reader
  } = stream[kState];
 
  if (reader === undefined)
    return;
 
  reader[kState].close.reject(error);
  setPromiseHandled(reader[kState].close.promise);
 
  if (readableStreamHasDefaultReader(stream)) {
    for (let n = 0; n < reader[kState].readRequests.length; n++)
      reader[kState].readRequests[n][kError](error);
    reader[kState].readRequests = [];
  } else {
    assert(readableStreamHasBYOBReader(stream));
    for (let n = 0; n < reader[kState].readIntoRequests.length; n++)
      reader[kState].readIntoRequests[n][kError](error);
    reader[kState].readIntoRequests = [];
  }
}
 
function readableStreamHasDefaultReader(stream) {
  const {
    reader,
  } = stream[kState];
 
  if (reader === undefined)
    return false;
 
  return reader[kState] !== undefined &&
         reader[kType] === 'ReadableStreamDefaultReader';
}
 
function readableStreamGetNumReadRequests(stream) {
  assert(readableStreamHasDefaultReader(stream));
  return stream[kState].reader[kState].readRequests.length;
}
 
function readableStreamHasBYOBReader(stream) {
  const {
    reader,
  } = stream[kState];
 
  if (reader === undefined)
    return false;
 
  return reader[kState] !== undefined &&
         reader[kType] === 'ReadableStreamBYOBReader';
}
 
function readableStreamGetNumReadIntoRequests(stream) {
  assert(readableStreamHasBYOBReader(stream));
  return stream[kState].reader[kState].readIntoRequests.length;
}
 
function readableStreamFulfillReadRequest(stream, chunk, done) {
  assert(readableStreamHasDefaultReader(stream));
  const {
    reader,
  } = stream[kState];
  assert(reader[kState].readRequests.length);
  const readRequest = ArrayPrototypeShift(reader[kState].readRequests);
 
  // TODO(@jasnell): It's not clear under what exact conditions done
  // will be true here. The spec requires this check but none of the
  // WPT's or other tests trigger it. Will need to investigate how to
  // get coverage for this.
  if (done)
    readRequest[kClose]();
  else
    readRequest[kChunk](chunk);
}
 
function readableStreamFulfillReadIntoRequest(stream, chunk, done) {
  assert(readableStreamHasBYOBReader(stream));
  const {
    reader,
  } = stream[kState];
  assert(reader[kState].readIntoRequests.length);
  const readIntoRequest = ArrayPrototypeShift(reader[kState].readIntoRequests);
  if (done)
    readIntoRequest[kClose](chunk);
  else
    readIntoRequest[kChunk](chunk);
}
 
function readableStreamAddReadRequest(stream, readRequest) {
  assert(readableStreamHasDefaultReader(stream));
  assert(stream[kState].state === 'readable');
  ArrayPrototypePush(stream[kState].reader[kState].readRequests, readRequest);
}
 
function readableStreamAddReadIntoRequest(stream, readIntoRequest) {
  assert(readableStreamHasBYOBReader(stream));
  assert(stream[kState].state !== 'errored');
  ArrayPrototypePush(
    stream[kState].reader[kState].readIntoRequests,
    readIntoRequest);
}
 
function readableStreamReaderGenericCancel(reader, reason) {
  const {
    stream,
  } = reader[kState];
  assert(stream !== undefined);
  return readableStreamCancel(stream, reason);
}
 
function readableStreamReaderGenericInitialize(reader, stream) {
  reader[kState].stream = stream;
  stream[kState].reader = reader;
  switch (stream[kState].state) {
    case 'readable':
      reader[kState].close = createDeferredPromise();
      break;
    case 'closed':
      reader[kState].close = {
        promise: PromiseResolve(),
        resolve: undefined,
        reject: undefined,
      };
      break;
    case 'errored':
      reader[kState].close = {
        promise: PromiseReject(stream[kState].storedError),
        resolve: undefined,
        reject: undefined,
      };
      setPromiseHandled(reader[kState].close.promise);
      break;
  }
}
 
function readableStreamReaderGenericRelease(reader) {
  const {
    stream,
  } = reader[kState];
  assert(stream !== undefined);
  assert(stream[kState].reader === reader);
 
  if (stream[kState].state === 'readable') {
    reader[kState].close.reject?.(
      new ERR_INVALID_STATE.TypeError('Reader released'));
  } else {
    reader[kState].close = {
      promise: PromiseReject(
        new ERR_INVALID_STATE.TypeError('Reader released')),
      resolve: undefined,
      reject: undefined,
    };
  }
  setPromiseHandled(reader[kState].close.promise);
  stream[kState].reader = undefined;
  reader[kState].stream = undefined;
}
 
function readableStreamBYOBReaderRead(reader, view, readIntoRequest) {
  const {
    stream,
  } = reader[kState];
  assert(stream !== undefined);
  stream[kState].disturbed = true;
  if (stream[kState].state === 'errored') {
    readIntoRequest[kError](stream[kState].storedError);
    return;
  }
  readableByteStreamControllerPullInto(
    stream[kState].controller,
    view,
    readIntoRequest);
}
 
function readableStreamDefaultReaderRead(reader, readRequest) {
  const {
    stream,
  } = reader[kState];
  assert(stream !== undefined);
  stream[kState].disturbed = true;
  switch (stream[kState].state) {
    case 'closed':
      readRequest[kClose]();
      break;
    case 'errored':
      readRequest[kError](stream[kState].storedError);
      break;
    case 'readable':
      stream[kState].controller[kPull](readRequest);
  }
}
 
function setupReadableStreamBYOBReader(reader, stream) {
  if (isReadableStreamLocked(stream))
    throw new ERR_INVALID_STATE.TypeError('ReadableStream is locked');
  const {
    controller,
  } = stream[kState];
  if (!isReadableByteStreamController(controller))
    throw new ERR_INVALID_ARG_VALUE('reader', reader, 'must be a byte stream');
  readableStreamReaderGenericInitialize(reader, stream);
  reader[kState].readIntoRequests = [];
}
 
function setupReadableStreamDefaultReader(reader, stream) {
  if (isReadableStreamLocked(stream))
    throw new ERR_INVALID_STATE.TypeError('ReadableStream is locked');
  readableStreamReaderGenericInitialize(reader, stream);
  reader[kState].readRequests = [];
}
 
function readableStreamDefaultControllerClose(controller) {
  if (!readableStreamDefaultControllerCanCloseOrEnqueue(controller))
    return;
  controller[kState].closeRequested = true;
  if (!controller[kState].queue.length) {
    readableStreamDefaultControllerClearAlgorithms(controller);
    readableStreamClose(controller[kState].stream);
  }
}
 
function readableStreamDefaultControllerEnqueue(controller, chunk) {
  if (!readableStreamDefaultControllerCanCloseOrEnqueue(controller))
    return;
 
  const {
    stream,
  } = controller[kState];
 
  if (isReadableStreamLocked(stream) &&
      readableStreamGetNumReadRequests(stream)) {
    readableStreamFulfillReadRequest(stream, chunk, false);
  } else {
    try {
      const chunkSize =
        FunctionPrototypeCall(
          controller[kState].sizeAlgorithm,
          undefined,
          chunk);
      enqueueValueWithSize(controller, chunk, chunkSize);
    } catch (error) {
      readableStreamDefaultControllerError(controller, error);
      throw error;
    }
  }
  readableStreamDefaultControllerCallPullIfNeeded(controller);
}
 
function readableStreamDefaultControllerHasBackpressure(controller) {
  return !readableStreamDefaultControllerShouldCallPull(controller);
}
 
function readableStreamDefaultControllerCanCloseOrEnqueue(controller) {
  const {
    stream,
  } = controller[kState];
  return !controller[kState].closeRequested &&
         stream[kState].state === 'readable';
}
 
function readableStreamDefaultControllerGetDesiredSize(controller) {
  const {
    stream,
    highWaterMark,
    queueTotalSize,
  } = controller[kState];
  switch (stream[kState].state) {
    case 'errored': return null;
    case 'closed': return 0;
    default:
      return highWaterMark - queueTotalSize;
  }
}
 
function readableStreamDefaultControllerShouldCallPull(controller) {
  const {
    stream,
  } = controller[kState];
  if (!readableStreamDefaultControllerCanCloseOrEnqueue(controller) ||
      !controller[kState].started)
    return false;
 
  if (isReadableStreamLocked(stream) &&
      readableStreamGetNumReadRequests(stream)) {
    return true;
  }
 
  const desiredSize = readableStreamDefaultControllerGetDesiredSize(controller);
  assert(desiredSize !== null);
 
  return desiredSize > 0;
}
 
function readableStreamDefaultControllerCallPullIfNeeded(controller) {
  if (!readableStreamDefaultControllerShouldCallPull(controller))
    return;
  if (controller[kState].pulling) {
    controller[kState].pullAgain = true;
    return;
  }
  assert(!controller[kState].pullAgain);
  controller[kState].pulling = true;
  PromisePrototypeThen(
    ensureIsPromise(controller[kState].pullAlgorithm, controller),
    () => {
      controller[kState].pulling = false;
      if (controller[kState].pullAgain) {
        controller[kState].pullAgain = false;
        readableStreamDefaultControllerCallPullIfNeeded(controller);
      }
    },
    (error) => readableStreamDefaultControllerError(controller, error));
}
 
function readableStreamDefaultControllerClearAlgorithms(controller) {
  controller[kState].pullAlgorithm = undefined;
  controller[kState].cancelAlgorithm = undefined;
  controller[kState].sizeAlgorithm = undefined;
}
 
function readableStreamDefaultControllerError(controller, error) {
  const {
    stream,
  } = controller[kState];
  if (stream[kState].state === 'readable') {
    resetQueue(controller);
    readableStreamDefaultControllerClearAlgorithms(controller);
    readableStreamError(stream, error);
  }
}
 
function readableStreamDefaultControllerCancelSteps(controller, reason) {
  resetQueue(controller);
  const result = controller[kState].cancelAlgorithm(reason);
  readableStreamDefaultControllerClearAlgorithms(controller);
  return result;
}
 
function readableStreamDefaultControllerPullSteps(controller, readRequest) {
  const {
    stream,
    queue,
  } = controller[kState];
  if (queue.length) {
    const chunk = dequeueValue(controller);
    if (controller[kState].closeRequested && !queue.length) {
      readableStreamDefaultControllerClearAlgorithms(controller);
      readableStreamClose(stream);
    } else {
      readableStreamDefaultControllerCallPullIfNeeded(controller);
    }
    readRequest[kChunk](chunk);
    return;
  }
  readableStreamAddReadRequest(stream, readRequest);
  readableStreamDefaultControllerCallPullIfNeeded(controller);
}
 
function setupReadableStreamDefaultController(
  stream,
  controller,
  startAlgorithm,
  pullAlgorithm,
  cancelAlgorithm,
  highWaterMark,
  sizeAlgorithm) {
  assert(stream[kState].controller === undefined);
  controller[kState] = {
    cancelAlgorithm,
    closeRequested: false,
    highWaterMark,
    pullAgain: false,
    pullAlgorithm,
    pulling: false,
    queue: [],
    queueTotalSize: 0,
    started: false,
    sizeAlgorithm,
    stream,
  };
  stream[kState].controller = controller;
 
  const startResult = startAlgorithm();
 
  PromisePrototypeThen(
    PromiseResolve(startResult),
    () => {
      controller[kState].started = true;
      assert(!controller[kState].pulling);
      assert(!controller[kState].pullAgain);
      readableStreamDefaultControllerCallPullIfNeeded(controller);
    },
    (error) => readableStreamDefaultControllerError(controller, error));
}
 
function setupReadableStreamDefaultControllerFromSource(
  stream,
  source,
  highWaterMark,
  sizeAlgorithm) {
  const controller = createReadableStreamDefaultController();
  const start = source?.start;
  const pull = source?.pull;
  const cancel = source?.cancel;
  const startAlgorithm = start ?
    FunctionPrototypeBind(start, source, controller) :
    nonOpStart;
  const pullAlgorithm = pull ?
    FunctionPrototypeBind(pull, source, controller) :
    nonOpPull;
 
  const cancelAlgorithm = cancel ?
    FunctionPrototypeBind(cancel, source) :
    nonOpCancel;
 
  setupReadableStreamDefaultController(
    stream,
    controller,
    startAlgorithm,
    pullAlgorithm,
    cancelAlgorithm,
    highWaterMark,
    sizeAlgorithm);
}
 
function readableByteStreamControllerClose(controller) {
  const {
    closeRequested,
    pendingPullIntos,
    queueTotalSize,
    stream,
  } = controller[kState];
 
  if (closeRequested || stream[kState].state !== 'readable')
    return;
 
  if (queueTotalSize) {
    controller[kState].closeRequested = true;
    return;
  }
 
  if (pendingPullIntos.length) {
    const firstPendingPullInto = pendingPullIntos[0];
    if (firstPendingPullInto.bytesFilled > 0) {
      const error = new ERR_INVALID_STATE.TypeError('Partial read');
      readableByteStreamControllerError(controller, error);
      throw error;
    }
  }
 
  readableByteStreamControllerClearAlgorithms(controller);
  readableStreamClose(stream);
}
 
function readableByteStreamControllerCommitPullIntoDescriptor(stream, desc) {
  assert(stream[kState].state !== 'errored');
  let done = false;
  if (stream[kState].state === 'closed') {
    desc.bytesFilled = 0;
    done = true;
  }
 
  const filledView =
    readableByteStreamControllerConvertPullIntoDescriptor(desc);
 
  if (desc.type === 'default') {
    readableStreamFulfillReadRequest(stream, filledView, done);
  } else {
    assert(desc.type === 'byob');
    readableStreamFulfillReadIntoRequest(stream, filledView, done);
  }
}
 
function readableByteStreamControllerInvalidateBYOBRequest(controller) {
  if (controller[kState].byobRequest === null)
    return;
  controller[kState].byobRequest[kState].controller = undefined;
  controller[kState].byobRequest[kState].view = null;
  controller[kState].byobRequest = null;
}
 
function readableByteStreamControllerClearAlgorithms(controller) {
  controller[kState].pullAlgorithm = undefined;
  controller[kState].cancelAlgorithm = undefined;
}
 
function readableByteStreamControllerClearPendingPullIntos(controller) {
  readableByteStreamControllerInvalidateBYOBRequest(controller);
  controller[kState].pendingPullIntos = [];
}
 
function readableByteStreamControllerGetDesiredSize(controller) {
  const {
    stream,
    highWaterMark,
    queueTotalSize,
  } = controller[kState];
  switch (stream[kState].state) {
    case 'errored': return null;
    case 'closed': return 0;
    default: return highWaterMark - queueTotalSize;
  }
}
 
function readableByteStreamControllerShouldCallPull(controller) {
  const {
    stream,
  } = controller[kState];
  if (stream[kState].state !== 'readable' ||
      controller[kState].closeRequested ||
      !controller[kState].started) {
    return false;
  }
  if (readableStreamHasDefaultReader(stream) &&
      readableStreamGetNumReadRequests(stream) > 0) {
    return true;
  }
 
  if (readableStreamHasBYOBReader(stream) &&
      readableStreamGetNumReadIntoRequests(stream) > 0) {
    return true;
  }
 
  const desiredSize = readableByteStreamControllerGetDesiredSize(controller);
  assert(desiredSize !== null);
 
  return desiredSize > 0;
}
 
function readableByteStreamControllerHandleQueueDrain(controller) {
  const {
    closeRequested,
    queueTotalSize,
    stream,
  } = controller[kState];
  assert(stream[kState].state === 'readable');
  if (!queueTotalSize && closeRequested) {
    readableByteStreamControllerClearAlgorithms(controller);
    readableStreamClose(stream);
    return;
  }
  readableByteStreamControllerCallPullIfNeeded(controller);
}
 
function readableByteStreamControllerPullInto(
  controller,
  view,
  readIntoRequest) {
  const {
    closeRequested,
    stream,
    pendingPullIntos,
  } = controller[kState];
  let elementSize = 1;
  let ctor = DataViewCtor;
  if (isArrayBufferView(view) && !isDataView(view)) {
    elementSize = view.constructor.BYTES_PER_ELEMENT;
    ctor = view.constructor;
  }
  const buffer = ArrayBufferViewGetBuffer(view);
  const byteOffset = ArrayBufferViewGetByteOffset(view);
  const byteLength = ArrayBufferViewGetByteLength(view);
  const bufferByteLength = ArrayBufferGetByteLength(buffer);
 
  let transferredBuffer;
  try {
    transferredBuffer = transferArrayBuffer(buffer);
  } catch (error) {
    readIntoRequest[kError](error);
    return;
  }
  const desc = {
    buffer: transferredBuffer,
    bufferByteLength,
    byteOffset,
    byteLength,
    bytesFilled: 0,
    elementSize,
    ctor,
    type: 'byob',
  };
  if (pendingPullIntos.length) {
    ArrayPrototypePush(pendingPullIntos, desc);
    readableStreamAddReadIntoRequest(stream, readIntoRequest);
    return;
  }
  if (stream[kState].state === 'closed') {
    const emptyView = new ctor(desc.buffer, byteOffset, 0);
    readIntoRequest[kClose](emptyView);
    return;
  }
  if (controller[kState].queueTotalSize) {
    if (readableByteStreamControllerFillPullIntoDescriptorFromQueue(
      controller,
      desc)) {
      const filledView =
        readableByteStreamControllerConvertPullIntoDescriptor(desc);
      readableByteStreamControllerHandleQueueDrain(controller);
      readIntoRequest[kChunk](filledView);
      return;
    }
    if (closeRequested) {
      const error = new ERR_INVALID_STATE.TypeError('ReadableStream closed');
      readableByteStreamControllerError(controller, error);
      readIntoRequest[kError](error);
      return;
    }
  }
  ArrayPrototypePush(pendingPullIntos, desc);
  readableStreamAddReadIntoRequest(stream, readIntoRequest);
  readableByteStreamControllerCallPullIfNeeded(controller);
}
 
function readableByteStreamControllerRespondInternal(controller, bytesWritten) {
  const {
    stream,
    pendingPullIntos,
  } = controller[kState];
  const desc = pendingPullIntos[0];
  readableByteStreamControllerInvalidateBYOBRequest(controller);
  if (stream[kState].state === 'closed') {
    if (bytesWritten)
      throw new ERR_INVALID_STATE.TypeError(
        'Controller is closed but view is not zero-length');
    readableByteStreamControllerRespondInClosedState(controller, desc);
  } else {
    assert(stream[kState].state === 'readable');
    if (!bytesWritten)
      throw new ERR_INVALID_STATE.TypeError('View cannot be zero-length');
    readableByteStreamControllerRespondInReadableState(
      controller,
      bytesWritten,
      desc);
  }
  readableByteStreamControllerCallPullIfNeeded(controller);
}
 
function readableByteStreamControllerRespond(controller, bytesWritten) {
  const {
    pendingPullIntos,
    stream,
  } = controller[kState];
  assert(pendingPullIntos.length);
  const desc = pendingPullIntos[0];
 
  if (stream[kState].state === 'closed') {
    if (bytesWritten !== 0)
      throw new ERR_INVALID_ARG_VALUE('bytesWritten', bytesWritten);
  } else {
    assert(stream[kState].state === 'readable');
 
    if (!bytesWritten)
      throw new ERR_INVALID_ARG_VALUE('bytesWritten', bytesWritten);
 
    if ((desc.bytesFilled + bytesWritten) > desc.byteLength)
      throw new ERR_INVALID_ARG_VALUE.RangeError('bytesWritten', bytesWritten);
  }
 
  desc.buffer = transferArrayBuffer(desc.buffer);
 
  readableByteStreamControllerRespondInternal(controller, bytesWritten);
}
 
function readableByteStreamControllerRespondInClosedState(controller, desc) {
  assert(!desc.bytesFilled);
  const {
    stream,
  } = controller[kState];
  if (readableStreamHasBYOBReader(stream)) {
    while (readableStreamGetNumReadIntoRequests(stream) > 0) {
      readableByteStreamControllerCommitPullIntoDescriptor(
        stream,
        readableByteStreamControllerShiftPendingPullInto(controller));
    }
  }
}
 
function readableByteStreamControllerFillHeadPullIntoDescriptor(
  controller,
  size,
  desc) {
  const {
    pendingPullIntos,
    byobRequest,
  } = controller[kState];
  assert(!pendingPullIntos.length || pendingPullIntos[0] === desc);
  assert(byobRequest === null);
  desc.bytesFilled += size;
}
 
function readableByteStreamControllerEnqueue(
  controller,
  buffer,
  byteLength,
  byteOffset) {
  const {
    closeRequested,
    pendingPullIntos,
    queue,
    stream,
  } = controller[kState];
 
  if (closeRequested || stream[kState].state !== 'readable')
    return;
 
  const transferredBuffer = transferArrayBuffer(buffer);
 
  if (pendingPullIntos.length) {
    const firstPendingPullInto = pendingPullIntos[0];
 
    const pendingBufferByteLength =
      ArrayBufferGetByteLength(firstPendingPullInto.buffer);
    if (pendingBufferByteLength === 0) {
      throw new ERR_INVALID_STATE.TypeError(
        'Destination ArrayBuffer is zero-length or detached');
    }
 
    firstPendingPullInto.buffer =
      transferArrayBuffer(firstPendingPullInto.buffer);
  }
 
  readableByteStreamControllerInvalidateBYOBRequest(controller);
 
  if (readableStreamHasDefaultReader(stream)) {
    if (!readableStreamGetNumReadRequests(stream)) {
      readableByteStreamControllerEnqueueChunkToQueue(
        controller,
        transferredBuffer,
        byteOffset,
        byteLength);
    } else {
      assert(!queue.length);
      const transferredView =
        new Uint8Array(transferredBuffer, byteOffset, byteLength);
      readableStreamFulfillReadRequest(stream, transferredView, false);
    }
  } else if (readableStreamHasBYOBReader(stream)) {
    readableByteStreamControllerEnqueueChunkToQueue(
      controller,
      transferredBuffer,
      byteOffset,
      byteLength);
    readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(
      controller);
  } else {
    assert(!isReadableStreamLocked(stream));
    readableByteStreamControllerEnqueueChunkToQueue(
      controller,
      transferredBuffer,
      byteOffset,
      byteLength);
  }
  readableByteStreamControllerCallPullIfNeeded(controller);
}
 
function readableByteStreamControllerEnqueueChunkToQueue(
  controller,
  buffer,
  byteOffset,
  byteLength) {
  ArrayPrototypePush(
    controller[kState].queue,
    {
      buffer,
      byteOffset,
      byteLength,
    });
  controller[kState].queueTotalSize += byteLength;
}
 
function readableByteStreamControllerFillPullIntoDescriptorFromQueue(
  controller,
  desc) {
  const {
    buffer,
    byteLength,
    byteOffset,
    bytesFilled,
    elementSize,
  } = desc;
  const currentAlignedBytes = bytesFilled - (bytesFilled % elementSize);
  const maxBytesToCopy = MathMin(
    controller[kState].queueTotalSize,
    byteLength - bytesFilled);
  const maxBytesFilled = bytesFilled + maxBytesToCopy;
  const maxAlignedBytes = maxBytesFilled - (maxBytesFilled % elementSize);
  let totalBytesToCopyRemaining = maxBytesToCopy;
  let ready = false;
  if (maxAlignedBytes > currentAlignedBytes) {
    totalBytesToCopyRemaining = maxAlignedBytes - bytesFilled;
    ready = true;
  }
  const {
    queue,
  } = controller[kState];
 
  while (totalBytesToCopyRemaining) {
    const headOfQueue = queue[0];
    const bytesToCopy = MathMin(
      totalBytesToCopyRemaining,
      headOfQueue.byteLength);
    const destStart = byteOffset + desc.bytesFilled;
    const arrayBufferByteLength = ArrayBufferGetByteLength(buffer);
    if (arrayBufferByteLength - destStart < bytesToCopy) {
      throw new ERR_INVALID_STATE.RangeError(
        'view ArrayBuffer size is invalid');
    }
    assert(arrayBufferByteLength - destStart >= bytesToCopy);
    copyArrayBuffer(
      buffer,
      destStart,
      headOfQueue.buffer,
      headOfQueue.byteOffset,
      bytesToCopy);
    if (headOfQueue.byteLength === bytesToCopy) {
      ArrayPrototypeShift(queue);
    } else {
      headOfQueue.byteOffset += bytesToCopy;
      headOfQueue.byteLength -= bytesToCopy;
    }
    controller[kState].queueTotalSize -= bytesToCopy;
    readableByteStreamControllerFillHeadPullIntoDescriptor(
      controller,
      bytesToCopy,
      desc);
    totalBytesToCopyRemaining -= bytesToCopy;
  }
 
  if (!ready) {
    assert(!controller[kState].queueTotalSize);
    assert(desc.bytesFilled > 0);
    assert(desc.bytesFilled < elementSize);
  }
  return ready;
}
 
function readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(
  controller) {
  const {
    closeRequested,
    pendingPullIntos,
    stream,
  } = controller[kState];
  assert(!closeRequested);
  while (pendingPullIntos.length) {
    if (!controller[kState].queueTotalSize)
      return;
    const desc = pendingPullIntos[0];
    if (readableByteStreamControllerFillPullIntoDescriptorFromQueue(
      controller,
      desc)) {
      readableByteStreamControllerShiftPendingPullInto(controller);
      readableByteStreamControllerCommitPullIntoDescriptor(stream, desc);
    }
  }
}
 
function readableByteStreamControllerRespondInReadableState(
  controller,
  bytesWritten,
  desc) {
  const {
    buffer,
    bytesFilled,
    byteLength,
  } = desc;
 
  if (bytesFilled + bytesWritten > byteLength)
    throw new ERR_INVALID_STATE.RangeError('The buffer size is invalid');
 
  readableByteStreamControllerFillHeadPullIntoDescriptor(
    controller,
    bytesWritten,
    desc);
 
  if (desc.bytesFilled < desc.elementSize)
    return;
 
  readableByteStreamControllerShiftPendingPullInto(controller);
 
  const remainderSize = desc.bytesFilled % desc.elementSize;
 
  if (remainderSize) {
    const end = desc.byteOffset + desc.bytesFilled;
    const start = end - remainderSize;
    const remainder =
      ArrayBufferPrototypeSlice(
        buffer,
        start,
        end);
    readableByteStreamControllerEnqueueChunkToQueue(
      controller,
      remainder,
      0,
      ArrayBufferGetByteLength(remainder));
  }
  desc.bytesFilled -= remainderSize;
  readableByteStreamControllerCommitPullIntoDescriptor(
    controller[kState].stream,
    desc);
  readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
}
 
function readableByteStreamControllerRespondWithNewView(controller, view) {
  const {
    stream,
    pendingPullIntos,
  } = controller[kState];
  assert(pendingPullIntos.length);
 
  const desc = pendingPullIntos[0];
  assert(stream[kState].state !== 'errored');
 
  if (!isArrayBufferView(view)) {
    throw new ERR_INVALID_ARG_TYPE(
      'view',
      [
        'Buffer',
        'TypedArray',
        'DataView',
      ],
      view);
  }
  const viewByteLength = ArrayBufferViewGetByteLength(view);
  const viewByteOffset = ArrayBufferViewGetByteOffset(view);
  const viewBuffer = ArrayBufferViewGetBuffer(view);
  const viewBufferByteLength = ArrayBufferGetByteLength(viewBuffer);
 
  const {
    byteOffset,
    byteLength,
    bytesFilled,
    bufferByteLength,
  } = desc;
 
  if (byteOffset + bytesFilled !== viewByteOffset)
    throw new ERR_INVALID_ARG_VALUE.RangeError('view', view);
 
  if (bytesFilled + viewByteOffset > byteLength)
    throw new ERR_INVALID_ARG_VALUE.RangeError('view', view);
 
  if (bufferByteLength !== viewBufferByteLength)
    throw new ERR_INVALID_ARG_VALUE.RangeError('view', view);
 
  desc.buffer = transferArrayBuffer(viewBuffer);
 
  readableByteStreamControllerRespondInternal(controller, viewByteLength);
}
 
function readableByteStreamControllerShiftPendingPullInto(controller) {
  assert(controller[kState].byobRequest === null);
  return ArrayPrototypeShift(controller[kState].pendingPullIntos);
}
 
function readableByteStreamControllerCallPullIfNeeded(controller) {
  if (!readableByteStreamControllerShouldCallPull(controller))
    return;
  if (controller[kState].pulling) {
    controller[kState].pullAgain = true;
    return;
  }
  assert(!controller[kState].pullAgain);
  controller[kState].pulling = true;
  PromisePrototypeThen(
    ensureIsPromise(controller[kState].pullAlgorithm, controller),
    () => {
      controller[kState].pulling = false;
      if (controller[kState].pullAgain) {
        controller[kState].pullAgain = false;
        readableByteStreamControllerCallPullIfNeeded(controller);
      }
    },
    (error) => readableByteStreamControllerError(controller, error));
}
 
function readableByteStreamControllerError(controller, error) {
  const {
    stream,
  } = controller[kState];
  if (stream[kState].state !== 'readable')
    return;
  readableByteStreamControllerClearPendingPullIntos(controller);
  resetQueue(controller);
  readableByteStreamControllerClearAlgorithms(controller);
  readableStreamError(stream, error);
}
 
function readableByteStreamControllerCancelSteps(controller, reason) {
  readableByteStreamControllerClearPendingPullIntos(controller);
  resetQueue(controller);
  const result = controller[kState].cancelAlgorithm(reason);
  readableByteStreamControllerClearAlgorithms(controller);
  return result;
}
 
function readableByteStreamControllerPullSteps(controller, readRequest) {
  const {
    pendingPullIntos,
    queue,
    queueTotalSize,
    stream,
  } = controller[kState];
  assert(readableStreamHasDefaultReader(stream));
  if (queueTotalSize) {
    assert(!readableStreamGetNumReadRequests(stream));
    const {
      buffer,
      byteOffset,
      byteLength,
    } = ArrayPrototypeShift(queue);
    controller[kState].queueTotalSize -= byteLength;
    readableByteStreamControllerHandleQueueDrain(controller);
    const view = new Uint8Array(buffer, byteOffset, byteLength);
    readRequest[kChunk](view);
    return;
  }
  const {
    autoAllocateChunkSize,
  } = controller[kState];
  if (autoAllocateChunkSize !== undefined) {
    try {
      const buffer = new ArrayBuffer(autoAllocateChunkSize);
      ArrayPrototypePush(
        pendingPullIntos,
        {
          buffer,
          byteOffset: 0,
          byteLength: autoAllocateChunkSize,
          bytesFilled: 0,
          elementSize: 1,
          ctor: Uint8Array,
          type: 'default',
        });
    } catch (error) {
      readRequest[kError](error);
      return;
    }
  }
 
  readableStreamAddReadRequest(stream, readRequest);
  readableByteStreamControllerCallPullIfNeeded(controller);
}
 
function setupReadableByteStreamController(
  stream,
  controller,
  startAlgorithm,
  pullAlgorithm,
  cancelAlgorithm,
  highWaterMark,
  autoAllocateChunkSize) {
  assert(stream[kState].controller === undefined);
  if (autoAllocateChunkSize !== undefined) {
    assert(NumberIsInteger(autoAllocateChunkSize));
    assert(autoAllocateChunkSize > 0);
  }
  controller[kState] = {
    byobRequest: null,
    closeRequested: false,
    pullAgain: false,
    pulling: false,
    started: false,
    stream,
    queue: [],
    queueTotalSize: 0,
    highWaterMark,
    pullAlgorithm,
    cancelAlgorithm,
    autoAllocateChunkSize,
    pendingPullIntos: [],
  };
  stream[kState].controller = controller;
 
  const startResult = startAlgorithm();
 
  PromisePrototypeThen(
    PromiseResolve(startResult),
    () => {
      controller[kState].started = true;
      assert(!controller[kState].pulling);
      assert(!controller[kState].pullAgain);
      readableByteStreamControllerCallPullIfNeeded(controller);
    },
    (error) => readableByteStreamControllerError(controller, error));
}
 
function setupReadableByteStreamControllerFromSource(
  stream,
  source,
  highWaterMark) {
  const controller = createReadableByteStreamController();
  const start = source?.start;
  const pull = source?.pull;
  const cancel = source?.cancel;
  const autoAllocateChunkSize = source?.autoAllocateChunkSize;
  const startAlgorithm = start ?
    FunctionPrototypeBind(start, source, controller) :
    nonOpStart;
  const pullAlgorithm = pull ?
    FunctionPrototypeBind(pull, source, controller) :
    nonOpPull;
  const cancelAlgorithm = cancel ?
    FunctionPrototypeBind(cancel, source) :
    nonOpCancel;
 
  if (autoAllocateChunkSize === 0) {
    throw new ERR_INVALID_ARG_VALUE(
      'source.autoAllocateChunkSize',
      autoAllocateChunkSize);
  }
  setupReadableByteStreamController(
    stream,
    controller,
    startAlgorithm,
    pullAlgorithm,
    cancelAlgorithm,
    highWaterMark,
    autoAllocateChunkSize);
}
 
module.exports = {
  ReadableStream,
  ReadableStreamDefaultReader,
  ReadableStreamBYOBReader,
  ReadableStreamBYOBRequest,
  ReadableByteStreamController,
  ReadableStreamDefaultController,
  TransferredReadableStream,
 
  // Exported Brand Checks
  isReadableStream,
  isReadableByteStreamController,
  isReadableStreamBYOBRequest,
  isReadableStreamDefaultReader,
  isReadableStreamBYOBReader,
  isWritableStreamDefaultWriter,
  isWritableStreamDefaultController,
 
  readableStreamPipeTo,
  readableStreamTee,
  readableByteStreamControllerConvertPullIntoDescriptor,
  isReadableStreamLocked,
  readableStreamCancel,
  readableStreamClose,
  readableStreamError,
  readableStreamHasDefaultReader,
  readableStreamGetNumReadRequests,
  readableStreamHasBYOBReader,
  readableStreamGetNumReadIntoRequests,
  readableStreamFulfillReadRequest,
  readableStreamFulfillReadIntoRequest,
  readableStreamAddReadRequest,
  readableStreamAddReadIntoRequest,
  readableStreamReaderGenericCancel,
  readableStreamReaderGenericInitialize,
  readableStreamReaderGenericRelease,
  readableStreamBYOBReaderRead,
  readableStreamDefaultReaderRead,
  setupReadableStreamBYOBReader,
  setupReadableStreamDefaultReader,
  readableStreamDefaultControllerClose,
  readableStreamDefaultControllerEnqueue,
  readableStreamDefaultControllerHasBackpressure,
  readableStreamDefaultControllerCanCloseOrEnqueue,
  readableStreamDefaultControllerGetDesiredSize,
  readableStreamDefaultControllerShouldCallPull,
  readableStreamDefaultControllerCallPullIfNeeded,
  readableStreamDefaultControllerClearAlgorithms,
  readableStreamDefaultControllerError,
  readableStreamDefaultControllerCancelSteps,
  readableStreamDefaultControllerPullSteps,
  setupReadableStreamDefaultController,
  setupReadableStreamDefaultControllerFromSource,
  readableByteStreamControllerClose,
  readableByteStreamControllerCommitPullIntoDescriptor,
  readableByteStreamControllerInvalidateBYOBRequest,
  readableByteStreamControllerClearAlgorithms,
  readableByteStreamControllerClearPendingPullIntos,
  readableByteStreamControllerGetDesiredSize,
  readableByteStreamControllerShouldCallPull,
  readableByteStreamControllerHandleQueueDrain,
  readableByteStreamControllerPullInto,
  readableByteStreamControllerRespondInternal,
  readableByteStreamControllerRespond,
  readableByteStreamControllerRespondInClosedState,
  readableByteStreamControllerFillHeadPullIntoDescriptor,
  readableByteStreamControllerEnqueue,
  readableByteStreamControllerEnqueueChunkToQueue,
  readableByteStreamControllerFillPullIntoDescriptorFromQueue,
  readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue,
  readableByteStreamControllerRespondInReadableState,
  readableByteStreamControllerRespondWithNewView,
  readableByteStreamControllerShiftPendingPullInto,
  readableByteStreamControllerCallPullIfNeeded,
  readableByteStreamControllerError,
  readableByteStreamControllerCancelSteps,
  readableByteStreamControllerPullSteps,
  setupReadableByteStreamController,
  setupReadableByteStreamControllerFromSource,
};
 
/* eslint-enable no-use-before-define */