All files / lib/internal/http2 core.js

97.11% Statements 3296/3394
92.77% Branches 860/927
96.71% Functions 147/152
97.11% Lines 3296/3394

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 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 33953x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 232x 3x 3x 3x 3x 3x 119430x 119430x 119430x 119430x 3x 60744x 60744x 60744x 60744x 60744x 3x 31033x 31033x 31033x 31033x 3x 29685x 29685x 29685x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 24114x 24114x 24114x 3x 3x 3x 3x 3x 3x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 23443x 11744x               11744x 11744x 11744x 11736x 11736x 7x 7x 7x 7x 7x 11744x 8x 8x 8x 11744x 11744x 11744x 23443x 11699x 11699x 11699x 11682x 11682x 11682x 11682x 4x 11682x 11678x 11678x 11699x 7x 7x 17x 4x 8x 6x 6x 11699x 11699x 1x 1x 1x 11699x 11699x 11699x 23443x 10702x 10702x 23443x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 37x 37x 37x 37x 37x 33x 1x 1x 1x 37x 3x 3x 3x 119x 119x 118x 118x 119x 3x 3x 3x 2176x 2176x 2176x 2x 2x 2176x 1x 1x 2176x 12x 12x 2176x 342x 342x 2176x     2176x 2176x 3x 284x 284x 284x       284x       284x 1x 1x 1x 1x 284x     284x     284x 284x 3x 3x 3x 120235x 120235x 120235x 120221x 120235x 2x 2x 120235x 1x 1x 120235x 120235x 3x 2359x 2359x 2359x 2136x 2359x     2359x     2359x 2359x 3x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 23574x 23574x 23574x 23574x 23436x 23436x 23436x 23436x 23436x 23436x 23436x 23436x 23436x 23436x 23436x 23574x 12345x 12345x 12456x 11091x 11091x 11091x 11091x 11091x 11091x 11091x 11091x 11091x 11091x 11091x 11091x 11091x 10082x 10082x 11091x 23436x 23574x 3x 3x 3x 13x 13x 13x 13x 13x 13x 13x 13x 13x 3x 3x 3x 3x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 14x 14x 14x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 14x 14x 3x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 5x 4x 5x 3x 3x 3x 3x 3x 3x 3x 311x 311x 311x 311x 311x 311x 311x 311x 311x 311x 311x 311x 311x 298x 298x 298x 298x 310x 13x 13x 13x 13x 13x 13x 13x 311x 3x 3x 3x 3x 11785x 11785x 11785x 11785x 11785x 11785x 11785x 11783x 11783x 11783x 11784x 1x 1x 1x 1x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11784x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11782x 11784x 7x 7x 7x 2x 2x 2x 7x 1x 1x 1x 7x 4x 7x 7x 7x 11775x 11785x 3x 3x 3x 3x 3x 3x 3x 3x 3x 11851x 11836x 11851x 6x 6x 11845x 11851x 11834x 11848x 6x 6x 11839x 11851x 11831x 11851x 6x 6x 11833x 11851x 11827x 11827x 6x 6x 3x 3x 3x 3x 10x 10x 10x 10x 3x 542x 542x 542x 542x 540x 540x 540x 540x 540x 542x 2x 2x 2x 2x 542x 3x 3x 676x 676x 676x 676x 676x 676x 676x 676x 2x 2x 676x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 590x 590x 590x 587x 587x 587x 590x 3x 3x 3x 38x 38x 38x 38x 3x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 10x 38x 25x 25x 25x 24x 24x 25x 25x 38x 3x 3x 2x 2x 2x 1x 3x 3x 20x 20x 20x 20x 3x 3x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 10x 20x 7x 7x 7x 6x 6x 20x 20x 3x 3x 3x 3x 3x 3x 3x 3x 13x 13x 13x 10x 13x 3x 3x 13x 13x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 767x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 765x 767x 767x 20x 20x 20x 767x 767x 8x 8x 8x 3x 3x 3x 3x 988x 988x 988x 988x 988x 310x 3720x 11x 11x 3720x 310x 988x 988x 988x 329x 310x 310x 19x 988x 988x 12x 12x 12x 12x 12x 988x 988x 3x 3x 3x 3x 3x 671x 671x 671x 671x 671x 671x 5x 5x 5x 666x 666x 666x 666x 666x 666x 666x 666x 666x 666x 666x 666x 666x 671x 666x 666x 666x 671x 310x 310x 310x 310x 666x 666x 666x 671x 50x 50x 668x 616x 616x 616x 616x 616x 616x 666x 671x 4x 4x 4x 4x 666x 671x         666x 670x 671x 671x 671x 671x 671x 671x 1x 1x 666x 666x 671x 3x 3x 3x 655x 655x 655x 655x 655x 3x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 662x 3x 662x 662x 662x 662x 662x 662x 662x 613x 613x 606x 606x 606x 606x 606x 606x 606x 606x 606x 606x 606x 613x 649x 49x 49x 662x 3x 663x 663x 663x 663x 663x 663x 663x 663x 663x 663x 663x 663x 663x 33x 33x 33x 33x 663x 663x 663x 663x 663x 663x 663x 647x 647x 647x 662x 16x 16x 663x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 682x 682x 682x 20x 20x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 682x 326x 326x 326x 315x 315x 315x     326x 682x 356x 356x 682x 682x 326x 326x 326x 682x 682x 682x 682x 682x 3x 3x 3x 3x 21x 21x 3x 3x 3x 3x 3x 5x 5x 3x 3x 3x 3x 3x 3x 3x 11x 11x 9x 11x 3x 3x 3x 13699x 13699x 3x 3x 3x 60214x 60214x 3x 3x 3x 135667x 135667x 3x 3x 3x 82257x 82257x 82257x 82257x 3x 3x 3x 3x 3x 10x 10x 8x 8x 10x 10x 1x 10x 3x 3x 3x 3x 3x 11x 11x 9x 9x 9x 9x 9x     11x 3x 3x 3x 3x 3x 35x 35x 33x 33x 7x 7x 7x 35x 8x 8x 8x 8x 35x 4x 4x 21x 21x 21x 35x       13x 13x 35x 3x 3x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 3x 3x 3x 10x 10x 10x 2x 10x 3x 3x 3x     3x 3x 3x     3x 3x 3x     3x 3x 3x 5x 5x 3x 3x 3x 19x 19x 19x 3x 3x 3x 3x 549x 549x 549x 541x 549x 549x 536x 536x 549x 3x 3x 3x 44x 44x 8x 8x 8x 8x 8x 36x 44x 44x 29x 29x 29x 44x 3x 3x 3x 716x 716x 714x 714x 714x 716x 6x 6x 676x 676x 676x 676x 676x 676x 716x 1x 1x 1x 675x 716x 3x 3x 3x 3x 3x 3x 611x 611x 608x 611x 5x 5x 5x 5x 603x 603x 603x 603x 603x 603x 611x 6x 6x 6x 587x 611x 3x 3x 3x 3x 693x 693x 663x 663x 663x 674x 621x 621x 621x 621x 621x 693x 693x 663x 663x 693x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 618x 618x 589x 589x 589x 618x 589x 589x 618x 3x 3x 1x 1x 1x 1x 1x 1x   1x 1x 3x 3x 3x 3x 3x 24170x 24170x 24170x 24170x 24170x 24170x 23556x 23556x 24170x 614x 24170x 3x 3x 16x 16x 3x 3x 1x 1x 1x 1x 3x 3x 7x 6x 6x 7x 3x 3x 3x 3x 3x 3x 3x 341x 341x 341x 341x 341x 341x 341x 341x 341x 3x 3x     3x 3x 3x 3x 3x 3x 27x 27x 27x 27x 27x 27x 27x 3x 3x 3x 27x 8x 6x 6x 6x 2x 24x 8x 8x 8x 8x 8x 8x 8x 8x 8x 3x 3x 3x 8x 3x 3x 8x 14x 14x 14x 27x 6x 6x 27x 27x 5x 27x 27x 3x 3x 3x 14x 14x 14x 14x 14x 13x 13x 13x 13x 14x 17x 17x 9x 17x 6x 6x 16x 16x 17x 10x 10x 10x 10x 6x 6x 14x 5x 5x 14x 3x 3x 3x 3x 3x 3x 3x 3x 3x 341x 341x 341x 3x 3x 3x 3x 11851x 11851x 11851x 11851x 11849x 11849x 11851x 11849x 11849x 11849x 11851x 11622x 11622x 13106x 13106x 12024x 12097x 1082x 13106x 11621x 11848x 11848x 11848x 11848x 11848x 11848x 11848x 11848x 11848x 11848x 11848x 11848x 11851x 11812x 11812x 11812x 11812x 11687x 11812x 11812x 11851x 36x 36x 35x 36x 34x 36x 36x 11845x 11845x 11845x 11845x 11813x 11813x 11813x 11813x 11851x 6x 6x 11815x 11815x 11815x 11815x 11815x 11815x 11815x 11815x 11815x 11815x 11819x 11791x 11791x 11821x 11791x 11791x 11801x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 11791x 11791x 11791x 11791x 588x 375x 583x 213x 213x 207x 207x 213x 213x 11801x 11203x 11203x 11791x 11851x 3x 3x 3870x 3870x 3870x 3870x 3870x 3870x 3x 23499x 23499x 23499x 23499x 3x 143x 143x 143x 143x 3x 23464x 23464x 23464x 23464x 23244x 23464x 23464x 23464x 23464x 23464x 3x 24489x 24489x 24489x 24488x 24488x 1024x 1024x 1024x 23464x 23464x 23464x 23464x 23464x 23464x 23464x 23464x 23464x 24489x 3x 32x 32x 32x 32x 32x 32x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 32x 3x 3x 3x 3x 3x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 23539x 23539x 120x 120x 120x 120x 3x 3x 120x 23539x 3x 119x 119x 119x 119x 119x 119x 1x 1x 1x 1x 118x 119x 3x 3x 3x 3x 3x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 23544x 3x 3x 45663x 45663x 45663x 45663x 45663x 45663x 45663x 3x 3x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 23528x 3x 3x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 3x 3x 20x 20x 20x 20x 3x 3x 4x 4x 3x 3x 9x 9x 3x 3x 1x 1x 3x 3x 1x 1x 3x 3x 51414x 51414x 3x 3x 3x 3x 8x 8x 3x 3x 3x 18848x 18848x 3x 3x 9x 9x 3x 3x 3x 40909x 40909x 3x 3x 3x 92x 92x 3x 3x 3x 1914x 1914x 3x 3x 3x 23464x 23464x 3x 3x 3x 37x 37x 37x 11x 37x 3x 3x       3x 3x 3503x 3503x 3503x 3503x 3503x 3x 3x 3877x 3877x 3877x 3877x 3877x 22x 22x 22x 22x 22x 22x 22x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3877x 3855x 3855x 3855x 3877x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 7710x 3855x 3855x 3855x 3855x 7710x     3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 3855x 1367x 1367x 3855x 3855x 3855x 3875x 3780x 3780x 3855x 3855x 3877x 3x 3x 3780x 3780x 3x 3x 75x 75x 3x 3x 23768x 646x 646x 646x 23122x 23122x 23768x 3x 3x 23506x       23506x 10832x 10832x 10832x 23506x 23006x 23452x 500x 500x 23506x 3x 3x 7x 7x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 2x 7x 3x 3x 36x 36x 35x 36x 34x 36x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 36x 3x 3x 131061x 131061x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1132x 1132x 1132x 8x 8x 1121x 1121x 1128x 43x 43x 44x 43x 43x 1132x 3x 3x 3x 3x 3x 3x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23486x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23523x 23523x 23539x 16x 16x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 23539x 3x 3x 3x 47029x       47029x 47029x 36886x 12308x 12308x 12308x 24578x 24578x 24578x 24578x 24578x 36859x 36886x 36886x 36886x 36886x 36886x 1081x 1081x 1081x 1081x 1081x 36886x 47029x 3x 3x 25x 25x 25x 25x 25x 22x 22x 22x 22x 22x 25x 10x 10x 10x 10x 10x 10x 10x 10x 10x 12x 12x 25x 3x 1081x 1081x 1081x 3x 11731x 11731x 11731x 11731x 11731x 10459x 10459x 10748x 10748x 10748x 10748x 10459x 10459x 11731x 11731x 11731x 11731x 11731x 11731x 11729x 11729x 11728x 11728x 11729x 11731x 11731x 11731x 11731x 11731x 11731x 11731x 11731x 11731x 11728x 11728x 11731x 11731x 11728x 11728x 11731x 3x 3x 14x 14x 14x 14x 6x 8x 8x 14x 3x 3x 3x 13x 13x 13x 1x 1x 13x 3x 21x 21x 21x 21x 21x 21x 21x 21x 21x       21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 6x 6x 6x 15x 15x 15x 21x 3x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 3x 2x 2x       2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 3x 16x 16x 16x 16x               16x 16x 3x 3x 3x 3x 2x 2x 2x 2x 2x     2x 2x 1x 1x 1x 1x 14x 16x         14x 14x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 13x 13x 12x 12x 1x 12x 12x 12x 12x 13x 13x 13x 13x 13x 16x 3x 18x 18x 18x 18x 2x 2x 1x 1x 2x 2x 18x       16x 16x 16x 16x 16x 16x 18x 3x 3x 3x 11745x 11745x 11745x 11745x 11745x 11745x 3x 3x 3x 22x 22x 22x 22x 22x 22x 3x 3x 3x 3x 20x 20x 18x 18x 17x 17x 17x 17x 17x 17x 17x 17x 14x 14x 14x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 16x 17x 16x 17x 16x 17x 16x 16x 16x 18x 16x 16x 16x 16x 20x 20x 20x 20x 20x 6x 6x 1x 1x 6x 1x 1x 6x 4x 4x 6x 6x 6x 6x 9x 9x 9x 9x 9x 9x 10x 9x 9x 10x 9x 9x 20x 3x 3x 3x 11701x 11701x 11699x 11700x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11700x 11698x 11700x 163x 163x 163x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11698x 11701x 11701x 11701x 11701x 10137x 10137x 10137x 11691x 11691x 11691x 11700x 11701x 3x 3x 3x 3x 3x 3x 3x 3x 37x 37x 36x 37x 35x 35x 35x 35x 35x 35x 37x 37x 29x 37x 37x 23x 37x 37x 6x 6x 17x 17x 37x       17x 17x 37x 16x 16x 11x 11x 11x 11x 11x 11x 11x 11x 37x 37x 37x 37x 3x 3x 8x 8x 2x 2x 2x 2x 2x 2x 6x 6x 6x 6x 6x 37x 3x 3x 3x 3x 3x 3x 3x 3x 3x 42x 42x 41x 42x 40x 40x 40x 40x 42x 42x 34x 42x 42x 28x 42x 42x 6x 6x 22x 22x 42x       22x 22x 22x 22x 22x 22x 22x 22x 22x 42x 42x 42x 42x 4x 4x 18x 18x 18x 18x 42x 3x 3x 3x 3x 3x 3x 3x 3x 3x 17x 17x 15x 15x 14x 14x 14x 14x 14x 14x 15x 13x 13x 13x 13x 1x 1x 13x 12x 12x 12x 12x 12x 15x 1x 1x 11x 11x 11x 15x 17x 3x 3x 3x 3x 3x 3x 11799x 11799x 11799x 11799x 11799x 11799x 3x 3x 5x 5x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 50x 50x 50x 10x 10x 10x 10x 10x 10x 10x 50x 3x 3x 3x 11736x 11736x 11736x 11736x 3x 4x 4x 4x 4x 3x 20x 20x 20x 20x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 3x 346x 346x 346x 346x 346x 5x 5x 2x 2x 2x 2x 3x 3x 3x 4x 2x 2x 2x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 341x 341x 341x 341x 341x 341x 341x 341x 341x 341x 341x 344x 341x 341x 341x 341x 346x 3x 349x 349x 349x 349x 349x 349x 349x 349x 325x 325x 4x 4x 4x 4x 4x 321x 321x 321x 320x 320x 320x 321x 321x 321x 321x 349x 349x 349x 349x 349x 349x 349x 349x 349x 349x 3x 67x 67x 67x 67x 67x 67x 67x 53x 67x 3x         3x 3x 3x 43x 43x 43x 43x 43x 43x 43x 29x 43x 3x 3x 10x 10x 7x 7x 7x 4x 10x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 282x 282x 282x 282x 282x 282x 282x 282x 3x 3x 9x 9x 7x 7x 7x 3x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 3x       3x 3x 3x 583x 583x 82x 82x 82x 82x 82x 82x 82x 583x 3x 661x 661x 661x 42x 42x 42x 42x 42x 42x 42x 42x 661x 3x 342x 342x 46x 46x 46x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 342x 329x 329x 329x 329x 342x     342x 342x 342x 16x 342x 326x 326x 301x 301x 326x 24x 24x 326x 1x 326x 326x 341x 341x 341x 342x 342x 342x 342x 342x 341x 341x 341x 341x 341x 341x 341x 341x 2x 2x 2x 2x 2x 2x 341x 341x 341x 342x 3x 3x 3x 3x 1x 1x 1x 1x 3x 3x 43x 43x 43x 3x 282x 282x 43x 43x 43x 282x 282x 3x 3x 3x 3x 45x 45x 45x 45x 45x 45x 3x 15x 15x 7x 7x 7x 8x 15x 6x 6x 15x 26x 26x 26x 26x 26x 3x 3x 26x 5x 5x 26x 3x 3x 26x 3x 3x 26x 4x 4x 26x 3x 3x 26x 5x 26x 26x 26x 6x 15x 15x 5x 5x 15x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x  
'use strict';
 
/* eslint-disable no-use-before-define */
 
const {
  ArrayFrom,
  ArrayIsArray,
  ArrayPrototypeForEach,
  ArrayPrototypePush,
  ArrayPrototypeUnshift,
  FunctionPrototypeBind,
  FunctionPrototypeCall,
  MathMin,
  ObjectAssign,
  ObjectCreate,
  ObjectKeys,
  ObjectDefineProperty,
  ObjectPrototypeHasOwnProperty,
  Promise,
  PromisePrototypeCatch,
  Proxy,
  ReflectApply,
  ReflectGet,
  ReflectGetPrototypeOf,
  ReflectSet,
  RegExpPrototypeTest,
  SafeArrayIterator,
  SafeMap,
  SafeSet,
  StringPrototypeSlice,
  Symbol,
  TypedArrayPrototypeGetLength,
  Uint32Array,
  Uint8Array,
} = primordials;
 
const {
  assertCrypto,
  customInspectSymbol: kInspect,
  promisify
} = require('internal/util');
 
assertCrypto();
 
const assert = require('assert');
const EventEmitter = require('events');
const fs = require('fs');
const http = require('http');
const { readUInt16BE, readUInt32BE } = require('internal/buffer');
const { URL } = require('internal/url');
const net = require('net');
const { Duplex } = require('stream');
const tls = require('tls');
const { setImmediate, setTimeout, clearTimeout } = require('timers');
 
const {
  kIncomingMessage,
  _checkIsHttpToken: checkIsHttpToken
} = require('_http_common');
const { kServerResponse } = require('_http_server');
const JSStreamSocket = require('internal/js_stream_socket');
 
const {
  defaultTriggerAsyncIdScope,
  symbols: {
    async_id_symbol,
    owner_symbol,
  },
} = require('internal/async_hooks');
const {
  aggregateTwoErrors,
  codes: {
    ERR_HTTP2_ALTSVC_INVALID_ORIGIN,
    ERR_HTTP2_ALTSVC_LENGTH,
    ERR_HTTP2_CONNECT_AUTHORITY,
    ERR_HTTP2_CONNECT_PATH,
    ERR_HTTP2_CONNECT_SCHEME,
    ERR_HTTP2_GOAWAY_SESSION,
    ERR_HTTP2_HEADERS_AFTER_RESPOND,
    ERR_HTTP2_HEADERS_SENT,
    ERR_HTTP2_INVALID_INFO_STATUS,
    ERR_HTTP2_INVALID_ORIGIN,
    ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH,
    ERR_HTTP2_INVALID_SESSION,
    ERR_HTTP2_INVALID_SETTING_VALUE,
    ERR_HTTP2_INVALID_STREAM,
    ERR_HTTP2_MAX_PENDING_SETTINGS_ACK,
    ERR_HTTP2_NESTED_PUSH,
    ERR_HTTP2_NO_MEM,
    ERR_HTTP2_NO_SOCKET_MANIPULATION,
    ERR_HTTP2_ORIGIN_LENGTH,
    ERR_HTTP2_OUT_OF_STREAMS,
    ERR_HTTP2_PAYLOAD_FORBIDDEN,
    ERR_HTTP2_PING_CANCEL,
    ERR_HTTP2_PING_LENGTH,
    ERR_HTTP2_PUSH_DISABLED,
    ERR_HTTP2_SEND_FILE,
    ERR_HTTP2_SEND_FILE_NOSEEK,
    ERR_HTTP2_SESSION_ERROR,
    ERR_HTTP2_SETTINGS_CANCEL,
    ERR_HTTP2_SOCKET_BOUND,
    ERR_HTTP2_SOCKET_UNBOUND,
    ERR_HTTP2_STATUS_101,
    ERR_HTTP2_STATUS_INVALID,
    ERR_HTTP2_STREAM_CANCEL,
    ERR_HTTP2_STREAM_ERROR,
    ERR_HTTP2_STREAM_SELF_DEPENDENCY,
    ERR_HTTP2_TRAILERS_ALREADY_SENT,
    ERR_HTTP2_TRAILERS_NOT_READY,
    ERR_HTTP2_UNSUPPORTED_PROTOCOL,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
    ERR_INVALID_CHAR,
    ERR_INVALID_HTTP_TOKEN,
    ERR_OUT_OF_RANGE,
    ERR_SOCKET_CLOSED
  },
  hideStackFrames,
  AbortError
} = require('internal/errors');
const {
  isUint32,
  validateCallback,
  validateInt32,
  validateInteger,
  validateNumber,
  validateString,
  validateUint32,
  validateAbortSignal
} = require('internal/validators');
const fsPromisesInternal = require('internal/fs/promises');
const { utcDate } = require('internal/http');
const {
  Http2ServerRequest,
  Http2ServerResponse,
  onServerStream,
} = require('internal/http2/compat');
 
const {
  assertIsObject,
  assertValidPseudoHeader,
  assertValidPseudoHeaderResponse,
  assertValidPseudoHeaderTrailer,
  assertWithinRange,
  getAuthority,
  getDefaultSettings,
  getSessionState,
  getSettings,
  getStreamState,
  isPayloadMeaningless,
  kSensitiveHeaders,
  kSocket,
  kRequest,
  kProxySocket,
  mapToHeaders,
  NghttpError,
  sessionName,
  toHeaderObject,
  updateOptionsBuffer,
  updateSettingsBuffer
} = require('internal/http2/util');
const {
  writeGeneric,
  writevGeneric,
  onStreamRead,
  kAfterAsyncWrite,
  kMaybeDestroy,
  kUpdateTimer,
  kHandle,
  kSession,
  setStreamTimeout
} = require('internal/stream_base_commons');
const { kTimeout } = require('internal/timers');
const { isArrayBufferView } = require('internal/util/types');
const { format } = require('internal/util/inspect');
 
const { FileHandle } = internalBinding('fs');
const binding = internalBinding('http2');
const {
  ShutdownWrap,
  kReadBytesOrError,
  streamBaseState
} = internalBinding('stream_wrap');
const { UV_EOF } = internalBinding('uv');
 
const { StreamPipe } = internalBinding('stream_pipe');
const { _connectionListener: httpConnectionListener } = http;
let debug = require('internal/util/debuglog').debuglog('http2', (fn) => {
  debug = fn;
});
 
// TODO(addaleax): See if this can be made more efficient by figuring out
// whether debugging is enabled before we perform any further steps. Currently,
// this seems pretty fast, though.
function debugStream(id, sessionType, message, ...args) {
  debug('Http2Stream %s [Http2Session %s]: ' + message,
        id, sessionName(sessionType), ...new SafeArrayIterator(args));
}
 
function debugStreamObj(stream, message, ...args) {
  const session = stream[kSession];
  const type = session ? session[kType] : undefined;
  debugStream(stream[kID], type, message, ...new SafeArrayIterator(args));
}
 
function debugSession(sessionType, message, ...args) {
  debug('Http2Session %s: ' + message, sessionName(sessionType),
        ...new SafeArrayIterator(args));
}
 
function debugSessionObj(session, message, ...args) {
  debugSession(session[kType], message, ...new SafeArrayIterator(args));
}
 
const kMaxFrameSize = (2 ** 24) - 1;
const kMaxInt = (2 ** 32) - 1;
const kMaxStreams = (2 ** 32) - 1;
const kMaxALTSVC = (2 ** 14) - 2;
 
// eslint-disable-next-line no-control-regex
const kQuotedString = /^[\x09\x20-\x5b\x5d-\x7e\x80-\xff]*$/;
 
const { constants, nameForErrorCode } = binding;
 
const NETServer = net.Server;
const TLSServer = tls.Server;
 
const kAlpnProtocol = Symbol('alpnProtocol');
const kAuthority = Symbol('authority');
const kEncrypted = Symbol('encrypted');
const kID = Symbol('id');
const kInit = Symbol('init');
const kInfoHeaders = Symbol('sent-info-headers');
const kLocalSettings = Symbol('local-settings');
const kNativeFields = Symbol('kNativeFields');
const kOptions = Symbol('options');
const kOwner = owner_symbol;
const kOrigin = Symbol('origin');
const kPendingRequestCalls = Symbol('kPendingRequestCalls');
const kProceed = Symbol('proceed');
const kProtocol = Symbol('protocol');
const kRemoteSettings = Symbol('remote-settings');
const kSelectPadding = Symbol('select-padding');
const kSentHeaders = Symbol('sent-headers');
const kSentTrailers = Symbol('sent-trailers');
const kServer = Symbol('server');
const kState = Symbol('state');
const kType = Symbol('type');
const kWriteGeneric = Symbol('write-generic');
 
const {
  kBitfield,
  kSessionPriorityListenerCount,
  kSessionFrameErrorListenerCount,
  kSessionMaxInvalidFrames,
  kSessionMaxRejectedStreams,
  kSessionUint8FieldCount,
  kSessionHasRemoteSettingsListeners,
  kSessionRemoteSettingsIsUpToDate,
  kSessionHasPingListeners,
  kSessionHasAltsvcListeners,
} = binding;
 
const {
  NGHTTP2_CANCEL,
  NGHTTP2_REFUSED_STREAM,
  NGHTTP2_DEFAULT_WEIGHT,
  NGHTTP2_FLAG_END_STREAM,
  NGHTTP2_HCAT_PUSH_RESPONSE,
  NGHTTP2_HCAT_RESPONSE,
  NGHTTP2_INTERNAL_ERROR,
  NGHTTP2_NO_ERROR,
  NGHTTP2_SESSION_CLIENT,
  NGHTTP2_SESSION_SERVER,
  NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE,
  NGHTTP2_ERR_INVALID_ARGUMENT,
  NGHTTP2_ERR_STREAM_CLOSED,
  NGHTTP2_ERR_NOMEM,
 
  HTTP2_HEADER_AUTHORITY,
  HTTP2_HEADER_DATE,
  HTTP2_HEADER_METHOD,
  HTTP2_HEADER_PATH,
  HTTP2_HEADER_PROTOCOL,
  HTTP2_HEADER_SCHEME,
  HTTP2_HEADER_STATUS,
  HTTP2_HEADER_CONTENT_LENGTH,
 
  NGHTTP2_SETTINGS_HEADER_TABLE_SIZE,
  NGHTTP2_SETTINGS_ENABLE_PUSH,
  NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS,
  NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE,
  NGHTTP2_SETTINGS_MAX_FRAME_SIZE,
  NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE,
  NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL,
 
  HTTP2_METHOD_GET,
  HTTP2_METHOD_HEAD,
  HTTP2_METHOD_CONNECT,
 
  HTTP_STATUS_CONTINUE,
  HTTP_STATUS_RESET_CONTENT,
  HTTP_STATUS_OK,
  HTTP_STATUS_NO_CONTENT,
  HTTP_STATUS_NOT_MODIFIED,
  HTTP_STATUS_SWITCHING_PROTOCOLS,
  HTTP_STATUS_MISDIRECTED_REQUEST,
 
  STREAM_OPTION_EMPTY_PAYLOAD,
  STREAM_OPTION_GET_TRAILERS
} = constants;
 
const STREAM_FLAGS_PENDING = 0x0;
const STREAM_FLAGS_READY = 0x1;
const STREAM_FLAGS_CLOSED = 0x2;
const STREAM_FLAGS_HEADERS_SENT = 0x4;
const STREAM_FLAGS_HEAD_REQUEST = 0x8;
const STREAM_FLAGS_ABORTED = 0x10;
const STREAM_FLAGS_HAS_TRAILERS = 0x20;
 
const SESSION_FLAGS_PENDING = 0x0;
const SESSION_FLAGS_READY = 0x1;
const SESSION_FLAGS_CLOSED = 0x2;
const SESSION_FLAGS_DESTROYED = 0x4;
 
// Top level to avoid creating a closure
function emit(self, ...args) {
  ReflectApply(self.emit, self, args);
}
 
// Called when a new block of headers has been received for a given
// stream. The stream may or may not be new. If the stream is new,
// create the associated Http2Stream instance and emit the 'stream'
// event. If the stream is not new, emit the 'headers' event to pass
// the block of headers on.
function onSessionHeaders(handle, id, cat, flags, headers, sensitiveHeaders) {
  const session = this[kOwner];
  if (session.destroyed)
    return;
 
  const type = session[kType];
  session[kUpdateTimer]();
  debugStream(id, type, 'headers received');
  const streams = session[kState].streams;
 
  const endOfStream = !!(flags & NGHTTP2_FLAG_END_STREAM);
  let stream = streams.get(id);
 
  // Convert the array of header name value pairs into an object
  const obj = toHeaderObject(headers, sensitiveHeaders);
 
  if (stream === undefined) {
    if (session.closed) {
      // We are not accepting any new streams at this point. This callback
      // should not be invoked at this point in time, but just in case it is,
      // refuse the stream using an RST_STREAM and destroy the handle.
      handle.rstStream(NGHTTP2_REFUSED_STREAM);
      handle.destroy();
      return;
    }
    const opts = { readable: !endOfStream };
    // session[kType] can be only one of two possible values
    if (type === NGHTTP2_SESSION_SERVER) {
      stream = new ServerHttp2Stream(session, handle, id, opts, obj);
      if (obj[HTTP2_HEADER_METHOD] === HTTP2_METHOD_HEAD) {
        // For head requests, there must not be a body...
        // end the writable side immediately.
        stream.end();
        stream[kState].flags |= STREAM_FLAGS_HEAD_REQUEST;
      }
    } else {
      stream = new ClientHttp2Stream(session, handle, id, opts);
      stream.end();
    }
    if (endOfStream)
      stream[kState].endAfterHeaders = true;
    process.nextTick(emit, session, 'stream', stream, obj, flags, headers);
  } else {
    let event;
    const status = obj[HTTP2_HEADER_STATUS];
    if (cat === NGHTTP2_HCAT_RESPONSE) {
      if (!endOfStream &&
          status !== undefined &&
          status >= 100 &&
          status < 200) {
        event = 'headers';
      } else {
        event = 'response';
      }
    } else if (cat === NGHTTP2_HCAT_PUSH_RESPONSE) {
      event = 'push';
      // cat === NGHTTP2_HCAT_HEADERS:
    } else if (!endOfStream && status !== undefined && status >= 200) {
      event = 'response';
    } else {
      event = endOfStream ? 'trailers' : 'headers';
    }
    const session = stream.session;
    if (status === HTTP_STATUS_MISDIRECTED_REQUEST) {
      const originSet = session[kState].originSet = initOriginSet(session);
      originSet.delete(stream[kOrigin]);
    }
    debugStream(id, type, "emitting stream '%s' event", event);
    process.nextTick(emit, stream, event, obj, flags, headers);
  }
  if (endOfStream) {
    stream.push(null);
  }
}
 
function tryClose(fd) {
  // Try to close the file descriptor. If closing fails, assert because
  // an error really should not happen at this point.
  fs.close(fd, assert.ifError);
}
 
// Called when the Http2Stream has finished sending data and is ready for
// trailers to be sent. This will only be called if the { hasOptions: true }
// option is set.
function onStreamTrailers() {
  const stream = this[kOwner];
  stream[kState].trailersReady = true;
  if (stream.destroyed || stream.closed)
    return;
  if (!stream.emit('wantTrailers')) {
    // There are no listeners, send empty trailing HEADERS frame and close.
    stream.sendTrailers({});
  }
}
 
// Submit an RST-STREAM frame to be sent to the remote peer.
// This will cause the Http2Stream to be closed.
function submitRstStream(code) {
  if (this[kHandle] !== undefined) {
    this[kHandle].rstStream(code);
  }
}
 
// Keep track of the number/presence of JS event listeners. Knowing that there
// are no listeners allows the C++ code to skip calling into JS for an event.
function sessionListenerAdded(name) {
  switch (name) {
    case 'ping':
      this[kNativeFields][kBitfield] |= 1 << kSessionHasPingListeners;
      break;
    case 'altsvc':
      this[kNativeFields][kBitfield] |= 1 << kSessionHasAltsvcListeners;
      break;
    case 'remoteSettings':
      this[kNativeFields][kBitfield] |= 1 << kSessionHasRemoteSettingsListeners;
      break;
    case 'priority':
      this[kNativeFields][kSessionPriorityListenerCount]++;
      break;
    case 'frameError':
      this[kNativeFields][kSessionFrameErrorListenerCount]++;
      break;
  }
}
 
function sessionListenerRemoved(name) {
  switch (name) {
    case 'ping':
      if (this.listenerCount(name) > 0) return;
      this[kNativeFields][kBitfield] &= ~(1 << kSessionHasPingListeners);
      break;
    case 'altsvc':
      if (this.listenerCount(name) > 0) return;
      this[kNativeFields][kBitfield] &= ~(1 << kSessionHasAltsvcListeners);
      break;
    case 'remoteSettings':
      if (this.listenerCount(name) > 0) return;
      this[kNativeFields][kBitfield] &=
          ~(1 << kSessionHasRemoteSettingsListeners);
      break;
    case 'priority':
      this[kNativeFields][kSessionPriorityListenerCount]--;
      break;
    case 'frameError':
      this[kNativeFields][kSessionFrameErrorListenerCount]--;
      break;
  }
}
 
// Also keep track of listeners for the Http2Stream instances, as some events
// are emitted on those objects.
function streamListenerAdded(name) {
  const session = this[kSession];
  if (!session) return;
  switch (name) {
    case 'priority':
      session[kNativeFields][kSessionPriorityListenerCount]++;
      break;
    case 'frameError':
      session[kNativeFields][kSessionFrameErrorListenerCount]++;
      break;
  }
}
 
function streamListenerRemoved(name) {
  const session = this[kSession];
  if (!session) return;
  switch (name) {
    case 'priority':
      session[kNativeFields][kSessionPriorityListenerCount]--;
      break;
    case 'frameError':
      session[kNativeFields][kSessionFrameErrorListenerCount]--;
      break;
  }
}
 
function onPing(payload) {
  const session = this[kOwner];
  if (session.destroyed)
    return;
  session[kUpdateTimer]();
  debugSessionObj(session, 'new ping received');
  session.emit('ping', payload);
}
 
// Called when the stream is closed either by sending or receiving an
// RST_STREAM frame, or through a natural end-of-stream.
// If the writable and readable sides of the stream are still open at this
// point, close them. If there is an open fd for file send, close that also.
// At this point the underlying node::http2:Http2Stream handle is no
// longer usable so destroy it also.
function onStreamClose(code) {
  const stream = this[kOwner];
  if (!stream || stream.destroyed)
    return false;
 
  debugStreamObj(
    stream, 'closed with code %d, closed %s, readable %s',
    code, stream.closed, stream.readable
  );
 
  if (!stream.closed)
    closeStream(stream, code, kNoRstStream);
 
  stream[kState].fd = -1;
  // Defer destroy we actually emit end.
  if (!stream.readable || code !== NGHTTP2_NO_ERROR) {
    // If errored or ended, we can destroy immediately.
    stream.destroy();
  } else {
    // Wait for end to destroy.
    stream.on('end', stream[kMaybeDestroy]);
    // Push a null so the stream can end whenever the client consumes
    // it completely.
    stream.push(null);
 
    // If the user hasn't tried to consume the stream (and this is a server
    // session) then just dump the incoming data so that the stream can
    // be destroyed.
    if (stream[kSession][kType] === NGHTTP2_SESSION_SERVER &&
        !stream[kState].didRead &&
        stream.readableFlowing === null)
      stream.resume();
    else
      stream.read(0);
  }
  return true;
}
 
// Called when the remote peer settings have been updated.
// Resets the cached settings.
function onSettings() {
  const session = this[kOwner];
  if (session.destroyed)
    return;
  session[kUpdateTimer]();
  debugSessionObj(session, 'new settings received');
  session[kRemoteSettings] = undefined;
  session.emit('remoteSettings', session.remoteSettings);
}
 
// If the stream exists, an attempt will be made to emit an event
// on the stream object itself. Otherwise, forward it on to the
// session (which may, in turn, forward it on to the server)
function onPriority(id, parent, weight, exclusive) {
  const session = this[kOwner];
  if (session.destroyed)
    return;
  debugStream(id, session[kType],
              'priority [parent: %d, weight: %d, exclusive: %s]',
              parent, weight, exclusive);
  const emitter = session[kState].streams.get(id) || session;
  if (!emitter.destroyed) {
    emitter[kUpdateTimer]();
    emitter.emit('priority', id, parent, weight, exclusive);
  }
}
 
// Called by the native layer when an error has occurred sending a
// frame. This should be exceedingly rare.
function onFrameError(id, type, code) {
  const session = this[kOwner];
  if (session.destroyed)
    return;
  debugSessionObj(session, 'error sending frame type %d on stream %d, code: %d',
                  type, id, code);
  const emitter = session[kState].streams.get(id) || session;
  emitter[kUpdateTimer]();
  emitter.emit('frameError', type, code, id);
}
 
function onAltSvc(stream, origin, alt) {
  const session = this[kOwner];
  if (session.destroyed)
    return;
  debugSessionObj(session, 'altsvc received: stream: %d, origin: %s, alt: %s',
                  stream, origin, alt);
  session[kUpdateTimer]();
  session.emit('altsvc', alt, origin, stream);
}
 
function initOriginSet(session) {
  let originSet = session[kState].originSet;
  if (originSet === undefined) {
    const socket = session[kSocket];
    session[kState].originSet = originSet = new SafeSet();
    if (socket.servername != null) {
      let originString = `https://${socket.servername}`;
      if (socket.remotePort != null)
        originString += `:${socket.remotePort}`;
      // We have to ensure that it is a properly serialized
      // ASCII origin string. The socket.servername might not
      // be properly ASCII encoded.
      originSet.add((new URL(originString)).origin);
    }
  }
  return originSet;
}
 
function onOrigin(origins) {
  const session = this[kOwner];
  if (session.destroyed)
    return;
  debugSessionObj(session, 'origin received: %j', origins);
  session[kUpdateTimer]();
  if (!session.encrypted || session.destroyed)
    return undefined;
  const originSet = initOriginSet(session);
  for (let n = 0; n < origins.length; n++)
    originSet.add(origins[n]);
  session.emit('origin', origins);
}
 
// Receiving a GOAWAY frame from the connected peer is a signal that no
// new streams should be created. If the code === NGHTTP2_NO_ERROR, we
// are going to send our close, but allow existing frames to close
// normally. If code !== NGHTTP2_NO_ERROR, we are going to send our own
// close using the same code then destroy the session with an error.
// The goaway event will be emitted on next tick.
function onGoawayData(code, lastStreamID, buf) {
  const session = this[kOwner];
  if (session.destroyed)
    return;
  debugSessionObj(session, 'goaway %d received [last stream id: %d]',
                  code, lastStreamID);
 
  const state = session[kState];
  state.goawayCode = code;
  state.goawayLastStreamID = lastStreamID;
 
  session.emit('goaway', code, lastStreamID, buf);
  if (code === NGHTTP2_NO_ERROR) {
    // If this is a no error goaway, begin shutting down.
    // No new streams permitted, but existing streams may
    // close naturally on their own.
    session.close();
  } else {
    // However, if the code is not NGHTTP_NO_ERROR, destroy the
    // session immediately. We destroy with an error but send a
    // goaway using NGHTTP2_NO_ERROR because there was no error
    // condition on this side of the session that caused the
    // shutdown.
    session.destroy(new ERR_HTTP2_SESSION_ERROR(code), NGHTTP2_NO_ERROR);
  }
}
 
// When a ClientHttp2Session is first created, the socket may not yet be
// connected. If request() is called during this time, the actual request
// will be deferred until the socket is ready to go.
function requestOnConnect(headers, options) {
  const session = this[kSession];
 
  // At this point, the stream should have already been destroyed during
  // the session.destroy() method. Do nothing else.
  if (session === undefined || session.destroyed)
    return;
 
  // If the session was closed while waiting for the connect, destroy
  // the stream and do not continue with the request.
  if (session.closed) {
    const err = new ERR_HTTP2_GOAWAY_SESSION();
    this.destroy(err);
    return;
  }
 
  debugSessionObj(session, 'connected, initializing request');
 
  let streamOptions = 0;
  if (options.endStream)
    streamOptions |= STREAM_OPTION_EMPTY_PAYLOAD;
 
  if (options.waitForTrailers)
    streamOptions |= STREAM_OPTION_GET_TRAILERS;
 
  // `ret` will be either the reserved stream ID (if positive)
  // or an error code (if negative)
  const ret = session[kHandle].request(headers,
                                       streamOptions,
                                       options.parent | 0,
                                       options.weight | 0,
                                       !!options.exclusive);
 
  // In an error condition, one of three possible response codes will be
  // possible:
  // * NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE - Maximum stream ID is reached, this
  //   is fatal for the session
  // * NGHTTP2_ERR_INVALID_ARGUMENT - Stream was made dependent on itself, this
  //   impacts on this stream.
  // For the first two, emit the error on the session,
  // For the third, emit the error on the stream, it will bubble up to the
  // session if not handled.
  if (typeof ret === 'number') {
    let err;
    switch (ret) {
      case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE:
        err = new ERR_HTTP2_OUT_OF_STREAMS();
        this.destroy(err);
        break;
      case NGHTTP2_ERR_INVALID_ARGUMENT:
        err = new ERR_HTTP2_STREAM_SELF_DEPENDENCY();
        this.destroy(err);
        break;
      default:
        session.destroy(new NghttpError(ret));
    }
    return;
  }
  this[kInit](ret.id(), ret);
}
 
// Validates that priority options are correct, specifically:
// 1. options.weight must be a number
// 2. options.parent must be a positive number
// 3. options.exclusive must be a boolean
// 4. if specified, options.silent must be a boolean
//
// Also sets the default priority options if they are not set.
const setAndValidatePriorityOptions = hideStackFrames((options) => {
  if (options.weight === undefined) {
    options.weight = NGHTTP2_DEFAULT_WEIGHT;
  } else if (typeof options.weight !== 'number') {
    throw new ERR_INVALID_ARG_VALUE('options.weight', options.weight);
  }
 
  if (options.parent === undefined) {
    options.parent = 0;
  } else if (typeof options.parent !== 'number' || options.parent < 0) {
    throw new ERR_INVALID_ARG_VALUE('options.parent', options.parent);
  }
 
  if (options.exclusive === undefined) {
    options.exclusive = false;
  } else if (typeof options.exclusive !== 'boolean') {
    throw new ERR_INVALID_ARG_VALUE('options.exclusive', options.exclusive);
  }
 
  if (options.silent === undefined) {
    options.silent = false;
  } else if (typeof options.silent !== 'boolean') {
    throw new ERR_INVALID_ARG_VALUE('options.silent', options.silent);
  }
});
 
// When an error occurs internally at the binding level, immediately
// destroy the session.
function onSessionInternalError(integerCode, customErrorCode) {
  if (this[kOwner] !== undefined)
    this[kOwner].destroy(new NghttpError(integerCode, customErrorCode));
}
 
function settingsCallback(cb, ack, duration) {
  this[kState].pendingAck--;
  this[kLocalSettings] = undefined;
  if (ack) {
    debugSessionObj(this, 'settings received');
    const settings = this.localSettings;
    if (typeof cb === 'function')
      cb(null, settings, duration);
    this.emit('localSettings', settings);
  } else {
    debugSessionObj(this, 'settings canceled');
    if (typeof cb === 'function')
      cb(new ERR_HTTP2_SETTINGS_CANCEL());
  }
}
 
// Submits a SETTINGS frame to be sent to the remote peer.
function submitSettings(settings, callback) {
  if (this.destroyed)
    return;
  debugSessionObj(this, 'submitting settings');
  this[kUpdateTimer]();
  updateSettingsBuffer(settings);
  if (!this[kHandle].settings(FunctionPrototypeBind(settingsCallback,
                                                    this, callback))) {
    this.destroy(new ERR_HTTP2_MAX_PENDING_SETTINGS_ACK());
  }
}
 
// Submits a PRIORITY frame to be sent to the remote peer
// Note: If the silent option is true, the change will be made
// locally with no PRIORITY frame sent.
function submitPriority(options) {
  if (this.destroyed)
    return;
  this[kUpdateTimer]();
 
  // If the parent is the id, do nothing because a
  // stream cannot be made to depend on itself.
  if (options.parent === this[kID])
    return;
 
  this[kHandle].priority(options.parent | 0,
                         options.weight | 0,
                         !!options.exclusive,
                         !!options.silent);
}
 
// Submit a GOAWAY frame to be sent to the remote peer.
// If the lastStreamID is set to <= 0, then the lastProcStreamID will
// be used. The opaqueData must either be a typed array or undefined
// (which will be checked elsewhere).
function submitGoaway(code, lastStreamID, opaqueData) {
  if (this.destroyed)
    return;
  debugSessionObj(this, 'submitting goaway');
  this[kUpdateTimer]();
  this[kHandle].goaway(code, lastStreamID, opaqueData);
}
 
const proxySocketHandler = {
  get(session, prop) {
    switch (prop) {
      case 'setTimeout':
      case 'ref':
      case 'unref':
        return FunctionPrototypeBind(session[prop], session);
      case 'destroy':
      case 'emit':
      case 'end':
      case 'pause':
      case 'read':
      case 'resume':
      case 'write':
      case 'setEncoding':
      case 'setKeepAlive':
      case 'setNoDelay':
        throw new ERR_HTTP2_NO_SOCKET_MANIPULATION();
      default:
        const socket = session[kSocket];
        if (socket === undefined)
          throw new ERR_HTTP2_SOCKET_UNBOUND();
        const value = socket[prop];
        return typeof value === 'function' ?
          FunctionPrototypeBind(value, socket) :
          value;
    }
  },
  getPrototypeOf(session) {
    const socket = session[kSocket];
    if (socket === undefined)
      throw new ERR_HTTP2_SOCKET_UNBOUND();
    return ReflectGetPrototypeOf(socket);
  },
  set(session, prop, value) {
    switch (prop) {
      case 'setTimeout':
      case 'ref':
      case 'unref':
        session[prop] = value;
        return true;
      case 'destroy':
      case 'emit':
      case 'end':
      case 'pause':
      case 'read':
      case 'resume':
      case 'write':
      case 'setEncoding':
      case 'setKeepAlive':
      case 'setNoDelay':
        throw new ERR_HTTP2_NO_SOCKET_MANIPULATION();
      default:
        const socket = session[kSocket];
        if (socket === undefined)
          throw new ERR_HTTP2_SOCKET_UNBOUND();
        socket[prop] = value;
        return true;
    }
  }
};
 
// pingCallback() returns a function that is invoked when an HTTP2 PING
// frame acknowledgement is received. The ack is either true or false to
// indicate if the ping was successful or not. The duration indicates the
// number of milliseconds elapsed since the ping was sent and the ack
// received. The payload is a Buffer containing the 8 bytes of payload
// data received on the PING acknowledgement.
function pingCallback(cb) {
  return function pingCallback(ack, duration, payload) {
    if (ack) {
      cb(null, duration, payload);
    } else {
      cb(new ERR_HTTP2_PING_CANCEL());
    }
  };
}
 
// Validates the values in a settings object. Specifically:
// 1. headerTableSize must be a number in the range 0 <= n <= kMaxInt
// 2. initialWindowSize must be a number in the range 0 <= n <= kMaxInt
// 3. maxFrameSize must be a number in the range 16384 <= n <= kMaxFrameSize
// 4. maxConcurrentStreams must be a number in the range 0 <= n <= kMaxStreams
// 5. maxHeaderListSize must be a number in the range 0 <= n <= kMaxInt
// 6. enablePush must be a boolean
// 7. enableConnectProtocol must be a boolean
// All settings are optional and may be left undefined
const validateSettings = hideStackFrames((settings) => {
  if (settings === undefined) return;
  assertWithinRange('headerTableSize',
                    settings.headerTableSize,
                    0, kMaxInt);
  assertWithinRange('initialWindowSize',
                    settings.initialWindowSize,
                    0, kMaxInt);
  assertWithinRange('maxFrameSize',
                    settings.maxFrameSize,
                    16384, kMaxFrameSize);
  assertWithinRange('maxConcurrentStreams',
                    settings.maxConcurrentStreams,
                    0, kMaxStreams);
  assertWithinRange('maxHeaderListSize',
                    settings.maxHeaderListSize,
                    0, kMaxInt);
  assertWithinRange('maxHeaderSize',
                    settings.maxHeaderSize,
                    0, kMaxInt);
  if (settings.enablePush !== undefined &&
      typeof settings.enablePush !== 'boolean') {
    throw new ERR_HTTP2_INVALID_SETTING_VALUE('enablePush',
                                              settings.enablePush);
  }
  if (settings.enableConnectProtocol !== undefined &&
      typeof settings.enableConnectProtocol !== 'boolean') {
    throw new ERR_HTTP2_INVALID_SETTING_VALUE('enableConnectProtocol',
                                              settings.enableConnectProtocol);
  }
});
 
// Wrap a typed array in a proxy, and allow selectively copying the entries
// that have explicitly been set to another typed array.
function trackAssignmentsTypedArray(typedArray) {
  const typedArrayLength = TypedArrayPrototypeGetLength(typedArray);
  const modifiedEntries = new Uint8Array(typedArrayLength);
 
  function copyAssigned(target) {
    for (let i = 0; i < typedArrayLength; i++) {
      if (modifiedEntries[i]) {
        target[i] = typedArray[i];
      }
    }
  }
 
  return new Proxy(typedArray, {
    get(obj, prop, receiver) {
      if (prop === 'copyAssigned') {
        return copyAssigned;
      }
      return ReflectGet(obj, prop, receiver);
    },
    set(obj, prop, value) {
      if (`${+prop}` === prop) {
        modifiedEntries[prop] = 1;
      }
      return ReflectSet(obj, prop, value);
    }
  });
}
 
// Creates the internal binding.Http2Session handle for an Http2Session
// instance. This occurs only after the socket connection has been
// established. Note: the binding.Http2Session will take over ownership
// of the socket. No other code should read from or write to the socket.
function setupHandle(socket, type, options) {
  // If the session has been destroyed, go ahead and emit 'connect',
  // but do nothing else. The various on('connect') handlers set by
  // core will check for session.destroyed before progressing, this
  // ensures that those at l`east get cleared out.
  if (this.destroyed) {
    process.nextTick(emit, this, 'connect', this, socket);
    return;
  }
 
  assert(socket._handle !== undefined,
         'Internal HTTP/2 Failure. The socket is not connected. Please ' +
         'report this as a bug in Node.js');
 
  debugSession(type, 'setting up session handle');
  this[kState].flags |= SESSION_FLAGS_READY;
 
  updateOptionsBuffer(options);
  const handle = new binding.Http2Session(type);
  handle[kOwner] = this;
 
  if (typeof options.selectPadding === 'function')
    this[kSelectPadding] = options.selectPadding;
  handle.consume(socket._handle);
 
  this[kHandle] = handle;
  if (this[kNativeFields]) {
    // If some options have already been set before the handle existed, copy
    // those (and only those) that have manually been set over.
    this[kNativeFields].copyAssigned(handle.fields);
  }
 
  this[kNativeFields] = handle.fields;
 
  if (socket.encrypted) {
    this[kAlpnProtocol] = socket.alpnProtocol;
    this[kEncrypted] = true;
  } else {
    // 'h2c' is the protocol identifier for HTTP/2 over plain-text. We use
    // it here to identify any session that is not explicitly using an
    // encrypted socket.
    this[kAlpnProtocol] = 'h2c';
    this[kEncrypted] = false;
  }
 
  if (isUint32(options.maxSessionInvalidFrames)) {
    const uint32 = new Uint32Array(
      this[kNativeFields].buffer, kSessionMaxInvalidFrames, 1);
    uint32[0] = options.maxSessionInvalidFrames;
  }
 
  if (isUint32(options.maxSessionRejectedStreams)) {
    const uint32 = new Uint32Array(
      this[kNativeFields].buffer, kSessionMaxRejectedStreams, 1);
    uint32[0] = options.maxSessionRejectedStreams;
  }
 
  const settings = typeof options.settings === 'object' ?
    options.settings : {};
 
  this.settings(settings);
 
  if (type === NGHTTP2_SESSION_SERVER &&
      ArrayIsArray(options.origins)) {
    ReflectApply(this.origin, this, options.origins);
  }
 
  process.nextTick(emit, this, 'connect', this, socket);
}
 
// Emits a close event followed by an error event if err is truthy. Used
// by Http2Session.prototype.destroy()
function emitClose(self, error) {
  if (error)
    self.emit('error', error);
  self.emit('close');
}
 
function cleanupSession(session) {
  const socket = session[kSocket];
  const handle = session[kHandle];
  session[kProxySocket] = undefined;
  session[kSocket] = undefined;
  session[kHandle] = undefined;
  session[kNativeFields] = trackAssignmentsTypedArray(
    new Uint8Array(kSessionUint8FieldCount));
  if (handle)
    handle.ondone = null;
  if (socket) {
    socket[kSession] = undefined;
    socket[kServer] = undefined;
  }
}
 
function finishSessionClose(session, error) {
  debugSessionObj(session, 'finishSessionClose');
 
  const socket = session[kSocket];
  cleanupSession(session);
 
  if (socket && !socket.destroyed) {
    // Always wait for writable side to finish.
    socket.end((err) => {
      debugSessionObj(session, 'finishSessionClose socket end', err, error);
      // Due to the way the underlying stream is handled in Http2Session we
      // won't get graceful Readable end from the other side even if it was sent
      // as the stream is already considered closed and will neither be read
      // from nor keep the event loop alive.
      // Therefore destroy the socket immediately.
      // Fixing this would require some heavy juggling of ReadStart/ReadStop
      // mostly on Windows as on Unix it will be fine with just ReadStart
      // after this 'ondone' callback.
      socket.destroy(error);
      emitClose(session, error);
    });
  } else {
    process.nextTick(emitClose, session, error);
  }
}
 
function closeSession(session, code, error) {
  debugSessionObj(session, 'start closing/destroying', error);
 
  const state = session[kState];
  state.flags |= SESSION_FLAGS_DESTROYED;
  state.destroyCode = code;
 
  // Clear timeout and remove timeout listeners.
  session.setTimeout(0);
  session.removeAllListeners('timeout');
 
  // Destroy any pending and open streams
  if (state.pendingStreams.size > 0 || state.streams.size > 0) {
    const cancel = new ERR_HTTP2_STREAM_CANCEL(error);
    state.pendingStreams.forEach((stream) => stream.destroy(cancel));
    state.streams.forEach((stream) => stream.destroy(error));
  }
 
  // Disassociate from the socket and server.
  const socket = session[kSocket];
  const handle = session[kHandle];
 
  // Destroy the handle if it exists at this point.
  if (handle !== undefined) {
    handle.ondone = FunctionPrototypeBind(finishSessionClose,
                                          null, session, error);
    handle.destroy(code, socket.destroyed);
  } else {
    finishSessionClose(session, error);
  }
}
 
// Upon creation, the Http2Session takes ownership of the socket. The session
// may not be ready to use immediately if the socket is not yet fully connected.
// In that case, the Http2Session will wait for the socket to connect. Once
// the Http2Session is ready, it will emit its own 'connect' event.
//
// The Http2Session.goaway() method will send a GOAWAY frame, signalling
// to the connected peer that a shutdown is in progress. Sending a goaway
// frame has no other effect, however.
//
// Receiving a GOAWAY frame will cause the Http2Session to first emit a 'goaway'
// event notifying the user that a shutdown is in progress. If the goaway
// error code equals 0 (NGHTTP2_NO_ERROR), session.close() will be called,
// causing the Http2Session to send its own GOAWAY frame and switch itself
// into a graceful closing state. In this state, new inbound or outbound
// Http2Streams will be rejected. Existing *pending* streams (those created
// but without an assigned stream ID or handle) will be destroyed with a
// cancel error. Existing open streams will be permitted to complete on their
// own. Once all existing streams close, session.destroy() will be called
// automatically.
//
// Calling session.destroy() will tear down the Http2Session immediately,
// making it no longer usable. Pending and existing streams will be destroyed.
// The bound socket will be destroyed. Once all resources have been freed up,
// the 'close' event will be emitted. Note that pending streams will be
// destroyed using a specific "ERR_HTTP2_STREAM_CANCEL" error. Existing open
// streams will be destroyed using the same error passed to session.destroy()
//
// If destroy is called with an error, an 'error' event will be emitted
// immediately following the 'close' event.
//
// The socket and Http2Session lifecycles are tightly bound. Once one is
// destroyed, the other should also be destroyed. When the socket is destroyed
// with an error, session.destroy() will be called with that same error.
// Likewise, when session.destroy() is called with an error, the same error
// will be sent to the socket.
class Http2Session extends EventEmitter {
  constructor(type, options, socket) {
    super();
 
    if (!socket._handle || !socket._handle.isStreamBase) {
      socket = new JSStreamSocket(socket);
    }
    socket.on('error', socketOnError);
    socket.on('close', socketOnClose);
 
    // No validation is performed on the input parameters because this
    // constructor is not exported directly for users.
 
    // If the session property already exists on the socket,
    // then it has already been bound to an Http2Session instance
    // and cannot be attached again.
    if (socket[kSession] !== undefined)
      throw new ERR_HTTP2_SOCKET_BOUND();
 
    socket[kSession] = this;
 
    this[kState] = {
      destroyCode: NGHTTP2_NO_ERROR,
      flags: SESSION_FLAGS_PENDING,
      goawayCode: null,
      goawayLastStreamID: null,
      streams: new SafeMap(),
      pendingStreams: new SafeSet(),
      pendingAck: 0,
      shutdownWritableCalled: false,
      writeQueueSize: 0,
      originSet: undefined
    };
 
    this[kEncrypted] = undefined;
    this[kAlpnProtocol] = undefined;
    this[kType] = type;
    this[kProxySocket] = null;
    this[kSocket] = socket;
    this[kTimeout] = null;
    this[kHandle] = undefined;
 
    // Do not use nagle's algorithm
    if (typeof socket.setNoDelay === 'function')
      socket.setNoDelay();
 
    // Disable TLS renegotiation on the socket
    if (typeof socket.disableRenegotiation === 'function')
      socket.disableRenegotiation();
 
    const setupFn = FunctionPrototypeBind(setupHandle, this,
                                          socket, type, options);
    if (socket.connecting || socket.secureConnecting) {
      const connectEvent =
        socket instanceof tls.TLSSocket ? 'secureConnect' : 'connect';
      socket.once(connectEvent, () => {
        try {
          setupFn();
        } catch (error) {
          socket.destroy(error);
        }
      });
    } else {
      setupFn();
    }
 
    if (!this[kNativeFields]) {
      this[kNativeFields] = trackAssignmentsTypedArray(
        new Uint8Array(kSessionUint8FieldCount));
    }
    this.on('newListener', sessionListenerAdded);
    this.on('removeListener', sessionListenerRemoved);
 
    debugSession(type, 'created');
  }
 
  // Returns undefined if the socket is not yet connected, true if the
  // socket is a TLSSocket, and false if it is not.
  get encrypted() {
    return this[kEncrypted];
  }
 
  // Returns undefined if the socket is not yet connected, `h2` if the
  // socket is a TLSSocket and the alpnProtocol is `h2`, or `h2c` if the
  // socket is not a TLSSocket.
  get alpnProtocol() {
    return this[kAlpnProtocol];
  }
 
  // TODO(jasnell): originSet is being added in preparation for ORIGIN frame
  // support. At the current time, the ORIGIN frame specification is awaiting
  // publication as an RFC and is awaiting implementation in nghttp2. Once
  // added, an ORIGIN frame will add to the origins included in the origin
  // set. 421 responses will remove origins from the set.
  get originSet() {
    if (!this.encrypted || this.destroyed)
      return undefined;
    return ArrayFrom(initOriginSet(this));
  }
 
  // True if the Http2Session is still waiting for the socket to connect
  get connecting() {
    return (this[kState].flags & SESSION_FLAGS_READY) === 0;
  }
 
  // True if Http2Session.prototype.close() has been called
  get closed() {
    return !!(this[kState].flags & SESSION_FLAGS_CLOSED);
  }
 
  // True if Http2Session.prototype.destroy() has been called
  get destroyed() {
    return !!(this[kState].flags & SESSION_FLAGS_DESTROYED);
  }
 
  // Resets the timeout counter
  [kUpdateTimer]() {
    if (this.destroyed)
      return;
    if (this[kTimeout]) this[kTimeout].refresh();
  }
 
  // Sets the id of the next stream to be created by this Http2Session.
  // The value must be a number in the range 0 <= n <= kMaxStreams. The
  // value also needs to be larger than the current next stream ID.
  setNextStreamID(id) {
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_SESSION();
 
    validateNumber(id, 'id');
    if (id <= 0 || id > kMaxStreams)
      throw new ERR_OUT_OF_RANGE('id', `> 0 and <= ${kMaxStreams}`, id);
    this[kHandle].setNextStreamID(id);
  }
 
  // Sets the local window size (local endpoints's window size)
  // Returns 0 if success or throw an exception if NGHTTP2_ERR_NOMEM
  // if the window allocation fails
  setLocalWindowSize(windowSize) {
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_SESSION();
 
    validateInt32(windowSize, 'windowSize', 0);
    const ret = this[kHandle].setLocalWindowSize(windowSize);
 
    if (ret === NGHTTP2_ERR_NOMEM) {
      this.destroy(new ERR_HTTP2_NO_MEM());
    }
  }
 
  // If ping is called while we are still connecting, or after close() has
  // been called, the ping callback will be invoked immediately with a ping
  // cancelled error and a duration of 0.0.
  ping(payload, callback) {
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_SESSION();
 
    if (typeof payload === 'function') {
      callback = payload;
      payload = undefined;
    }
    if (payload && !isArrayBufferView(payload)) {
      throw new ERR_INVALID_ARG_TYPE('payload',
                                     ['Buffer', 'TypedArray', 'DataView'],
                                     payload);
    }
    if (payload && payload.length !== 8) {
      throw new ERR_HTTP2_PING_LENGTH();
    }
    validateCallback(callback);
 
    const cb = pingCallback(callback);
    if (this.connecting || this.closed) {
      process.nextTick(cb, false, 0.0, payload);
      return;
    }
 
    return this[kHandle].ping(payload, cb);
  }
 
  [kInspect](depth, opts) {
    if (typeof depth === 'number' && depth < 0)
      return this;
 
    const obj = {
      type: this[kType],
      closed: this.closed,
      destroyed: this.destroyed,
      state: this.state,
      localSettings: this.localSettings,
      remoteSettings: this.remoteSettings
    };
    return `Http2Session ${format(obj)}`;
  }
 
  // The socket owned by this session
  get socket() {
    const proxySocket = this[kProxySocket];
    if (proxySocket === null)
      return this[kProxySocket] = new Proxy(this, proxySocketHandler);
    return proxySocket;
  }
 
  // The session type
  get type() {
    return this[kType];
  }
 
  // If a GOAWAY frame has been received, gives the error code specified
  get goawayCode() {
    return this[kState].goawayCode || NGHTTP2_NO_ERROR;
  }
 
  // If a GOAWAY frame has been received, gives the last stream ID reported
  get goawayLastStreamID() {
    return this[kState].goawayLastStreamID || 0;
  }
 
  // True if the Http2Session is waiting for a settings acknowledgement
  get pendingSettingsAck() {
    return this[kState].pendingAck > 0;
  }
 
  // Retrieves state information for the Http2Session
  get state() {
    return this.connecting || this.destroyed ?
      {} : getSessionState(this[kHandle]);
  }
 
  // The settings currently in effect for the local peer. These will
  // be updated only when a settings acknowledgement has been received.
  get localSettings() {
    const settings = this[kLocalSettings];
    if (settings !== undefined)
      return settings;
 
    if (this.destroyed || this.connecting)
      return {};
 
    return this[kLocalSettings] = getSettings(this[kHandle], false); // Local
  }
 
  // The settings currently in effect for the remote peer.
  get remoteSettings() {
    if (this[kNativeFields][kBitfield] &
        (1 << kSessionRemoteSettingsIsUpToDate)) {
      const settings = this[kRemoteSettings];
      if (settings !== undefined) {
        return settings;
      }
    }
 
    if (this.destroyed || this.connecting)
      return {};
 
    this[kNativeFields][kBitfield] |= (1 << kSessionRemoteSettingsIsUpToDate);
    return this[kRemoteSettings] = getSettings(this[kHandle], true); // Remote
  }
 
  // Submits a SETTINGS frame to be sent to the remote peer.
  settings(settings, callback) {
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_SESSION();
    assertIsObject(settings, 'settings');
    validateSettings(settings);
 
    if (callback) {
      validateCallback(callback);
    }
    debugSessionObj(this, 'sending settings');
 
    this[kState].pendingAck++;
 
    const settingsFn = FunctionPrototypeBind(submitSettings, this,
                                             { ...settings }, callback);
    if (this.connecting) {
      this.once('connect', settingsFn);
      return;
    }
    settingsFn();
  }
 
  // Submits a GOAWAY frame to be sent to the remote peer. Note that this
  // is only a notification, and does not affect the usable state of the
  // session with the notable exception that new incoming streams will
  // be rejected automatically.
  goaway(code = NGHTTP2_NO_ERROR, lastStreamID = 0, opaqueData) {
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_SESSION();
 
    if (opaqueData !== undefined && !isArrayBufferView(opaqueData)) {
      throw new ERR_INVALID_ARG_TYPE('opaqueData',
                                     ['Buffer', 'TypedArray', 'DataView'],
                                     opaqueData);
    }
    validateNumber(code, 'code');
    validateNumber(lastStreamID, 'lastStreamID');
 
    const goawayFn = FunctionPrototypeBind(submitGoaway,
                                           this,
                                           code, lastStreamID, opaqueData);
    if (this.connecting) {
      this.once('connect', goawayFn);
      return;
    }
    goawayFn();
  }
 
  // Destroy the Http2Session, making it no longer usable and cancelling
  // any pending activity.
  destroy(error = NGHTTP2_NO_ERROR, code) {
    if (this.destroyed)
      return;
 
    debugSessionObj(this, 'destroying');
 
    if (typeof error === 'number') {
      code = error;
      error =
        code !== NGHTTP2_NO_ERROR ?
          new ERR_HTTP2_SESSION_ERROR(code) : undefined;
    }
    if (code === undefined && error != null)
      code = NGHTTP2_INTERNAL_ERROR;
 
    closeSession(this, code, error);
  }
 
  // Closing the session will:
  // 1. Send a goaway frame
  // 2. Mark the session as closed
  // 3. Prevent new inbound or outbound streams from being opened
  // 4. Optionally register a 'close' event handler
  // 5. Will cause the session to automatically destroy after the
  //    last currently open Http2Stream closes.
  //
  // Close always assumes a good, non-error shutdown (NGHTTP_NO_ERROR)
  //
  // If the session has not connected yet, the closed flag will still be
  // set but the goaway will not be sent until after the connect event
  // is emitted.
  close(callback) {
    if (this.closed || this.destroyed)
      return;
    debugSessionObj(this, 'marking session closed');
    this[kState].flags |= SESSION_FLAGS_CLOSED;
    if (typeof callback === 'function')
      this.once('close', callback);
    this.goaway();
    this[kMaybeDestroy]();
  }
 
  [EventEmitter.captureRejectionSymbol](err, event, ...args) {
    switch (event) {
      case 'stream':
        const stream = args[0];
        stream.destroy(err);
        break;
      default:
        this.destroy(err);
    }
  }
 
  // Destroy the session if:
  // * error is not undefined/null
  // * session is closed and there are no more pending or open streams
  [kMaybeDestroy](error) {
    if (error == null) {
      const state = this[kState];
      // Do not destroy if we're not closed and there are pending/open streams
      if (!this.closed ||
          state.streams.size > 0 ||
          state.pendingStreams.size > 0) {
        return;
      }
    }
    this.destroy(error);
  }
 
  _onTimeout() {
    callTimeout(this);
  }
 
  ref() {
    if (this[kSocket]) {
      this[kSocket].ref();
    }
  }
 
  unref() {
    if (this[kSocket]) {
      this[kSocket].unref();
    }
  }
}
 
// ServerHttp2Session instances should never have to wait for the socket
// to connect as they are always created after the socket has already been
// established.
class ServerHttp2Session extends Http2Session {
  constructor(options, socket, server) {
    super(NGHTTP2_SESSION_SERVER, options, socket);
    this[kServer] = server;
    // This is a bit inaccurate because it does not reflect changes to
    // number of listeners made after the session was created. This should
    // not be an issue in practice. Additionally, the 'priority' event on
    // server instances (or any other object) is fully undocumented.
    this[kNativeFields][kSessionPriorityListenerCount] =
      server.listenerCount('priority');
  }
 
  get server() {
    return this[kServer];
  }
 
  // Submits an altsvc frame to be sent to the client. `stream` is a
  // numeric Stream ID. origin is a URL string that will be used to get
  // the origin. alt is a string containing the altsvc details. No fancy
  // API is provided for that.
  altsvc(alt, originOrStream) {
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_SESSION();
 
    let stream = 0;
    let origin;
 
    if (typeof originOrStream === 'string') {
      origin = (new URL(originOrStream)).origin;
      if (origin === 'null')
        throw new ERR_HTTP2_ALTSVC_INVALID_ORIGIN();
    } else if (typeof originOrStream === 'number') {
      if (originOrStream >>> 0 !== originOrStream || originOrStream === 0) {
        throw new ERR_OUT_OF_RANGE('originOrStream',
                                   `> 0 && < ${2 ** 32}`, originOrStream);
      }
      stream = originOrStream;
    } else if (originOrStream !== undefined) {
      // Allow origin to be passed a URL or object with origin property
      if (originOrStream !== null && typeof originOrStream === 'object')
        origin = originOrStream.origin;
      // Note: if originOrStream is an object with an origin property other
      // than a URL, then it is possible that origin will be malformed.
      // We do not verify that here. Users who go that route need to
      // ensure they are doing the right thing or the payload data will
      // be invalid.
      if (typeof origin !== 'string') {
        throw new ERR_INVALID_ARG_TYPE('originOrStream',
                                       ['string', 'number', 'URL', 'object'],
                                       originOrStream);
      } else if (origin === 'null' || origin.length === 0) {
        throw new ERR_HTTP2_ALTSVC_INVALID_ORIGIN();
      }
    }
 
    validateString(alt, 'alt');
    if (!RegExpPrototypeTest(kQuotedString, alt))
      throw new ERR_INVALID_CHAR('alt');
 
    // Max length permitted for ALTSVC
    if ((alt.length + (origin !== undefined ? origin.length : 0)) > kMaxALTSVC)
      throw new ERR_HTTP2_ALTSVC_LENGTH();
 
    this[kHandle].altsvc(stream, origin || '', alt);
  }
 
  // Submits an origin frame to be sent.
  origin(...origins) {
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_SESSION();
 
    if (origins.length === 0)
      return;
 
    let arr = '';
    let len = 0;
    const count = origins.length;
    for (let i = 0; i < count; i++) {
      let origin = origins[i];
      if (typeof origin === 'string') {
        origin = (new URL(origin)).origin;
      } else if (origin != null && typeof origin === 'object') {
        origin = origin.origin;
      }
      validateString(origin, 'origin');
      if (origin === 'null')
        throw new ERR_HTTP2_INVALID_ORIGIN();
 
      arr += `${origin}\0`;
      len += origin.length;
    }
 
    if (len > kMaxALTSVC)
      throw new ERR_HTTP2_ORIGIN_LENGTH();
 
    this[kHandle].origin(arr, count);
  }
 
}
 
// ClientHttp2Session instances have to wait for the socket to connect after
// they have been created. Various operations such as request() may be used,
// but the actual protocol communication will only occur after the socket
// has been connected.
class ClientHttp2Session extends Http2Session {
  constructor(options, socket) {
    super(NGHTTP2_SESSION_CLIENT, options, socket);
    this[kPendingRequestCalls] = null;
  }
 
  // Submits a new HTTP2 request to the connected peer. Returns the
  // associated Http2Stream instance.
  request(headers, options) {
    debugSessionObj(this, 'initiating request');
 
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_SESSION();
 
    if (this.closed)
      throw new ERR_HTTP2_GOAWAY_SESSION();
 
    this[kUpdateTimer]();
 
    if (headers !== null && headers !== undefined) {
      const keys = ObjectKeys(headers);
      for (let i = 0; i < keys.length; i++) {
        const header = keys[i];
        if (header[0] === ':') {
          assertValidPseudoHeader(header);
        } else if (header && !checkIsHttpToken(header))
          this.destroy(new ERR_INVALID_HTTP_TOKEN('Header name', header));
      }
    }
 
    assertIsObject(headers, 'headers');
    assertIsObject(options, 'options');
 
    headers = ObjectAssign(ObjectCreate(null), headers);
    options = { ...options };
 
    if (headers[HTTP2_HEADER_METHOD] === undefined)
      headers[HTTP2_HEADER_METHOD] = HTTP2_METHOD_GET;
 
    const connect = headers[HTTP2_HEADER_METHOD] === HTTP2_METHOD_CONNECT;
 
    if (!connect || headers[HTTP2_HEADER_PROTOCOL] !== undefined) {
      if (getAuthority(headers) === undefined)
        headers[HTTP2_HEADER_AUTHORITY] = this[kAuthority];
      if (headers[HTTP2_HEADER_SCHEME] === undefined)
        headers[HTTP2_HEADER_SCHEME] = StringPrototypeSlice(this[kProtocol],
                                                            0, -1);
      if (headers[HTTP2_HEADER_PATH] === undefined)
        headers[HTTP2_HEADER_PATH] = '/';
    } else {
      if (headers[HTTP2_HEADER_AUTHORITY] === undefined)
        throw new ERR_HTTP2_CONNECT_AUTHORITY();
      if (headers[HTTP2_HEADER_SCHEME] !== undefined)
        throw new ERR_HTTP2_CONNECT_SCHEME();
      if (headers[HTTP2_HEADER_PATH] !== undefined)
        throw new ERR_HTTP2_CONNECT_PATH();
    }
 
    setAndValidatePriorityOptions(options);
 
    if (options.endStream === undefined) {
      // For some methods, we know that a payload is meaningless, so end the
      // stream by default if the user has not specifically indicated a
      // preference.
      options.endStream = isPayloadMeaningless(headers[HTTP2_HEADER_METHOD]);
    } else if (typeof options.endStream !== 'boolean') {
      throw new ERR_INVALID_ARG_VALUE('options.endStream', options.endStream);
    }
 
    const headersList = mapToHeaders(headers);
 
    const stream = new ClientHttp2Stream(this, undefined, undefined, {});
    stream[kSentHeaders] = headers;
    stream[kOrigin] = `${headers[HTTP2_HEADER_SCHEME]}://` +
                      `${getAuthority(headers)}`;
 
    // Close the writable side of the stream if options.endStream is set.
    if (options.endStream)
      stream.end();
 
    if (options.waitForTrailers)
      stream[kState].flags |= STREAM_FLAGS_HAS_TRAILERS;
 
    const { signal } = options;
    if (signal) {
      validateAbortSignal(signal, 'options.signal');
      const aborter = () => stream.destroy(new AbortError());
      if (signal.aborted) {
        aborter();
      } else {
        signal.addEventListener('abort', aborter);
        stream.once('close', () => {
          signal.removeEventListener('abort', aborter);
        });
      }
    }
 
    const onConnect = FunctionPrototypeBind(requestOnConnect,
                                            stream, headersList, options);
    if (this.connecting) {
      if (this[kPendingRequestCalls] !== null) {
        ArrayPrototypePush(this[kPendingRequestCalls], onConnect);
      } else {
        this[kPendingRequestCalls] = [onConnect];
        this.once('connect', () => {
          ArrayPrototypeForEach(this[kPendingRequestCalls], (f) => f());
          this[kPendingRequestCalls] = null;
        });
      }
    } else {
      onConnect();
    }
    return stream;
  }
}
 
function trackWriteState(stream, bytes) {
  const session = stream[kSession];
  stream[kState].writeQueueSize += bytes;
  session[kState].writeQueueSize += bytes;
  session[kHandle].chunksSentSinceLastWrite = 0;
}
 
function streamOnResume() {
  if (!this.destroyed)
    this[kHandle].readStart();
}
 
function streamOnPause() {
  if (!this.destroyed && !this.pending)
    this[kHandle].readStop();
}
 
function afterShutdown(status) {
  const stream = this.handle[kOwner];
  if (stream) {
    stream.on('finish', () => {
      stream[kMaybeDestroy]();
    });
  }
  // Currently this status value is unused
  this.callback();
}
 
function shutdownWritable(callback) {
  const handle = this[kHandle];
  if (!handle) return callback();
  const state = this[kState];
  if (state.shutdownWritableCalled) {
    debugStreamObj(this, 'shutdownWritable() already called');
    return callback();
  }
  state.shutdownWritableCalled = true;
 
  const req = new ShutdownWrap();
  req.oncomplete = afterShutdown;
  req.callback = callback;
  req.handle = handle;
  const err = handle.shutdown(req);
  if (err === 1)  // synchronous finish
    return ReflectApply(afterShutdown, req, [0]);
}
 
function finishSendTrailers(stream, headersList) {
  // The stream might be destroyed and in that case
  // there is nothing to do.
  // This can happen because finishSendTrailers is
  // scheduled via setImmediate.
  if (stream.destroyed) {
    return;
  }
 
  stream[kState].flags &= ~STREAM_FLAGS_HAS_TRAILERS;
 
  const ret = stream[kHandle].trailers(headersList);
  if (ret < 0)
    stream.destroy(new NghttpError(ret));
  else
    stream[kMaybeDestroy]();
}
 
const kNoRstStream = 0;
const kSubmitRstStream = 1;
const kForceRstStream = 2;
 
function closeStream(stream, code, rstStreamStatus = kSubmitRstStream) {
  const state = stream[kState];
  state.flags |= STREAM_FLAGS_CLOSED;
  state.rstCode = code;
 
  // Clear timeout and remove timeout listeners
  stream.setTimeout(0);
  stream.removeAllListeners('timeout');
 
  const { ending } = stream._writableState;
 
  if (!ending) {
    // If the writable side of the Http2Stream is still open, emit the
    // 'aborted' event and set the aborted flag.
    if (!stream.aborted) {
      state.flags |= STREAM_FLAGS_ABORTED;
      stream.emit('aborted');
    }
 
    // Close the writable side.
    stream.end();
  }
 
  if (rstStreamStatus !== kNoRstStream) {
    const finishFn = FunctionPrototypeBind(finishCloseStream, stream, code);
    if (!ending || stream.writableFinished || code !== NGHTTP2_NO_ERROR ||
        rstStreamStatus === kForceRstStream)
      finishFn();
    else
      stream.once('finish', finishFn);
  }
}
 
function finishCloseStream(code) {
  const rstStreamFn = FunctionPrototypeBind(submitRstStream, this, code);
  // If the handle has not yet been assigned, queue up the request to
  // ensure that the RST_STREAM frame is sent after the stream ID has
  // been determined.
  if (this.pending) {
    this.push(null);
    this.once('ready', rstStreamFn);
    return;
  }
  rstStreamFn();
}
 
// An Http2Stream is a Duplex stream that is backed by a
// node::http2::Http2Stream handle implementing StreamBase.
class Http2Stream extends Duplex {
  constructor(session, options) {
    options.allowHalfOpen = true;
    options.decodeStrings = false;
    options.autoDestroy = false;
    super(options);
    this[async_id_symbol] = -1;
 
    // Corking the stream automatically allows writes to happen
    // but ensures that those are buffered until the handle has
    // been assigned.
    this.cork();
    this[kSession] = session;
    session[kState].pendingStreams.add(this);
 
    // Allow our logic for determining whether any reads have happened to
    // work in all situations. This is similar to what we do in _http_incoming.
    this._readableState.readingMore = true;
 
    this[kTimeout] = null;
 
    this[kState] = {
      didRead: false,
      flags: STREAM_FLAGS_PENDING,
      rstCode: NGHTTP2_NO_ERROR,
      writeQueueSize: 0,
      trailersReady: false,
      endAfterHeaders: false
    };
 
    // Fields used by the compat API to avoid megamorphisms.
    this[kRequest] = null;
    this[kProxySocket] = null;
 
    this.on('pause', streamOnPause);
 
    this.on('newListener', streamListenerAdded);
    this.on('removeListener', streamListenerRemoved);
  }
 
  [kUpdateTimer]() {
    if (this.destroyed)
      return;
    if (this[kTimeout])
      this[kTimeout].refresh();
    if (this[kSession])
      this[kSession][kUpdateTimer]();
  }
 
  [kInit](id, handle) {
    const state = this[kState];
    state.flags |= STREAM_FLAGS_READY;
 
    const session = this[kSession];
    session[kState].pendingStreams.delete(this);
    session[kState].streams.set(id, this);
 
    this[kID] = id;
    this[async_id_symbol] = handle.getAsyncId();
    handle[kOwner] = this;
    this[kHandle] = handle;
    handle.onread = onStreamRead;
    this.uncork();
    this.emit('ready');
  }
 
  [kInspect](depth, opts) {
    if (typeof depth === 'number' && depth < 0)
      return this;
 
    const obj = {
      id: this[kID] || '<pending>',
      closed: this.closed,
      destroyed: this.destroyed,
      state: this.state,
      readableState: this._readableState,
      writableState: this._writableState
    };
    return `Http2Stream ${format(obj)}`;
  }
 
  get bufferSize() {
    // `bufferSize` properties of `net.Socket` are `undefined` when
    // their `_handle` are falsy. Here we avoid the behavior.
    return this[kState].writeQueueSize + this.writableLength;
  }
 
  get endAfterHeaders() {
    return this[kState].endAfterHeaders;
  }
 
  get sentHeaders() {
    return this[kSentHeaders];
  }
 
  get sentTrailers() {
    return this[kSentTrailers];
  }
 
  get sentInfoHeaders() {
    return this[kInfoHeaders];
  }
 
  get pending() {
    return this[kID] === undefined;
  }
 
  // The id of the Http2Stream, will be undefined if the socket is not
  // yet connected.
  get id() {
    return this[kID];
  }
 
  // The Http2Session that owns this Http2Stream.
  get session() {
    return this[kSession];
  }
 
  _onTimeout() {
    callTimeout(this, kSession);
  }
 
  // True if the HEADERS frame has been sent
  get headersSent() {
    return !!(this[kState].flags & STREAM_FLAGS_HEADERS_SENT);
  }
 
  // True if the Http2Stream was aborted abnormally.
  get aborted() {
    return !!(this[kState].flags & STREAM_FLAGS_ABORTED);
  }
 
  // True if dealing with a HEAD request
  get headRequest() {
    return !!(this[kState].flags & STREAM_FLAGS_HEAD_REQUEST);
  }
 
  // The error code reported when this Http2Stream was closed.
  get rstCode() {
    return this[kState].rstCode;
  }
 
  // State information for the Http2Stream
  get state() {
    const id = this[kID];
    if (this.destroyed || id === undefined)
      return {};
    return getStreamState(this[kHandle], id);
  }
 
  [kProceed]() {
    assert.fail('Implementors MUST implement this. Please report this as a ' +
                'bug in Node.js');
  }
 
  [kAfterAsyncWrite]({ bytes }) {
    this[kState].writeQueueSize -= bytes;
 
    if (this.session !== undefined)
      this.session[kState].writeQueueSize -= bytes;
  }
 
  [kWriteGeneric](writev, data, encoding, cb) {
    // When the Http2Stream is first created, it is corked until the
    // handle and the stream ID is assigned. However, if the user calls
    // uncork() before that happens, the Duplex will attempt to pass
    // writes through. Those need to be queued up here.
    if (this.pending) {
      this.once(
        'ready',
        FunctionPrototypeBind(this[kWriteGeneric],
                              this, writev, data, encoding, cb)
      );
      return;
    }
 
    // If the stream has been destroyed, there's nothing else we can do
    // because the handle has been destroyed. This should only be an
    // issue if a write occurs before the 'ready' event in the case where
    // the duplex is uncorked before the stream is ready to go. In that
    // case, drop the data on the floor. An error should have already been
    // emitted.
    if (this.destroyed)
      return;
 
    this[kUpdateTimer]();
    if (!this.headersSent)
      this[kProceed]();
 
    let req;
 
    let waitingForWriteCallback = true;
    let waitingForEndCheck = true;
    let writeCallbackErr;
    let endCheckCallbackErr;
    const done = () => {
      if (waitingForEndCheck || waitingForWriteCallback) return;
      const err = aggregateTwoErrors(endCheckCallbackErr, writeCallbackErr);
      // writeGeneric does not destroy on error and
      // we cannot enable autoDestroy,
      // so make sure to destroy on error.
      if (err) {
        this.destroy(err);
      }
      cb(err);
    };
    const writeCallback = (err) => {
      waitingForWriteCallback = false;
      writeCallbackErr = err;
      done();
    };
    const endCheckCallback = (err) => {
      waitingForEndCheck = false;
      endCheckCallbackErr = err;
      done();
    };
    // Shutdown write stream right after last chunk is sent
    // so final DATA frame can include END_STREAM flag
    process.nextTick(() => {
      if (writeCallbackErr ||
        !this._writableState.ending ||
        this._writableState.buffered.length ||
        (this[kState].flags & STREAM_FLAGS_HAS_TRAILERS))
        return endCheckCallback();
      debugStreamObj(this, 'shutting down writable on last write');
      shutdownWritable.call(this, endCheckCallback);
    });
 
    if (writev)
      req = writevGeneric(this, data, writeCallback);
    else
      req = writeGeneric(this, data, encoding, writeCallback);
 
    trackWriteState(this, req.bytes);
  }
 
  _write(data, encoding, cb) {
    this[kWriteGeneric](false, data, encoding, cb);
  }
 
  _writev(data, cb) {
    this[kWriteGeneric](true, data, '', cb);
  }
 
  _final(cb) {
    if (this.pending) {
      this.once('ready', () => this._final(cb));
      return;
    }
    debugStreamObj(this, 'shutting down writable on _final');
    ReflectApply(shutdownWritable, this, [cb]);
  }
 
  _read(nread) {
    if (this.destroyed) {
      this.push(null);
      return;
    }
    if (!this[kState].didRead) {
      this._readableState.readingMore = false;
      this[kState].didRead = true;
    }
    if (!this.pending) {
      FunctionPrototypeCall(streamOnResume, this);
    } else {
      this.once('ready', streamOnResume);
    }
  }
 
  priority(options) {
    if (this.destroyed)
      throw new ERR_HTTP2_INVALID_STREAM();
 
    assertIsObject(options, 'options');
    options = { ...options };
    setAndValidatePriorityOptions(options);
 
    const priorityFn = FunctionPrototypeBind(submitPriority, this, options);
 
    // If the handle has not yet been assigned, queue up the priority
    // frame to be sent as soon as the ready event is emitted.
    if (this.pending) {
      this.once('ready', priorityFn);
      return;
    }
    priorityFn();
  }
 
  sendTrailers(headers) {
    if (this.destroyed || this.closed)
      throw new ERR_HTTP2_INVALID_STREAM();
    if (this[kSentTrailers])
      throw new ERR_HTTP2_TRAILERS_ALREADY_SENT();
    if (!this[kState].trailersReady)
      throw new ERR_HTTP2_TRAILERS_NOT_READY();
 
    assertIsObject(headers, 'headers');
    headers = ObjectAssign(ObjectCreate(null), headers);
 
    debugStreamObj(this, 'sending trailers');
 
    this[kUpdateTimer]();
 
    const headersList = mapToHeaders(headers, assertValidPseudoHeaderTrailer);
    this[kSentTrailers] = headers;
 
    // Send the trailers in setImmediate so we don't do it on nghttp2 stack.
    setImmediate(finishSendTrailers, this, headersList);
  }
 
  get closed() {
    return !!(this[kState].flags & STREAM_FLAGS_CLOSED);
  }
 
  // Close initiates closing the Http2Stream instance by sending an RST_STREAM
  // frame to the connected peer. The readable and writable sides of the
  // Http2Stream duplex are closed and the timeout timer is cleared. If
  // a callback is passed, it is registered to listen for the 'close' event.
  //
  // If the handle and stream ID have not been assigned yet, the close
  // will be queued up to wait for the ready event. As soon as the stream ID
  // is determined, the close will proceed.
  //
  // Submitting the RST_STREAM frame to the underlying handle will cause
  // the Http2Stream to be closed and ultimately destroyed. After calling
  // close, it is still possible to queue up PRIORITY and RST_STREAM frames,
  // but no DATA and HEADERS frames may be sent.
  close(code = NGHTTP2_NO_ERROR, callback) {
    validateInteger(code, 'code', 0, kMaxInt);
 
    if (callback !== undefined) {
      validateCallback(callback);
    }
 
    if (this.closed)
      return;
 
    if (callback !== undefined)
      this.once('close', callback);
 
    closeStream(this, code);
  }
 
  // Called by this.destroy().
  // * Will submit an RST stream to shutdown the stream if necessary.
  //   This will cause the internal resources to be released.
  // * Then cleans up the resources on the js side
  _destroy(err, callback) {
    const session = this[kSession];
    const handle = this[kHandle];
    const id = this[kID];
 
    debugStream(this[kID] || 'pending', session[kType], 'destroying stream');
 
    const state = this[kState];
    const sessionState = session[kState];
    const sessionCode = sessionState.goawayCode || sessionState.destroyCode;
 
    // If a stream has already closed successfully, there is no error
    // to report from this stream, even if the session has errored.
    // This can happen if the stream was already in process of destroying
    // after a successful close, but the session had a error between
    // this stream's close and destroy operations.
    // Previously, this always overrode a successful close operation code
    // NGHTTP2_NO_ERROR (0) with sessionCode because the use of the || operator.
    const code = (err != null ?
      (sessionCode || NGHTTP2_INTERNAL_ERROR) :
      (this.closed ? this.rstCode : sessionCode)
    );
    const hasHandle = handle !== undefined;
 
    if (!this.closed)
      closeStream(this, code, hasHandle ? kForceRstStream : kNoRstStream);
    this.push(null);
 
    if (hasHandle) {
      handle.destroy();
      sessionState.streams.delete(id);
    } else {
      sessionState.pendingStreams.delete(this);
    }
 
    // Adjust the write queue size for accounting
    sessionState.writeQueueSize -= state.writeQueueSize;
    state.writeQueueSize = 0;
 
    // RST code 8 not emitted as an error as its used by clients to signify
    // abort and is already covered by aborted event, also allows more
    // seamless compatibility with http1
    if (err == null && code !== NGHTTP2_NO_ERROR && code !== NGHTTP2_CANCEL)
      err = new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code);
 
    this[kSession] = undefined;
    this[kHandle] = undefined;
 
    // This notifies the session that this stream has been destroyed and
    // gives the session the opportunity to clean itself up. The session
    // will destroy if it has been closed and there are no other open or
    // pending streams.
    session[kMaybeDestroy]();
    callback(err);
  }
  // The Http2Stream can be destroyed if it has closed and if the readable
  // side has received the final chunk.
  [kMaybeDestroy](code = NGHTTP2_NO_ERROR) {
    if (code !== NGHTTP2_NO_ERROR) {
      this.destroy();
      return;
    }
 
    if (this.writableFinished) {
      if (!this.readable && this.closed) {
        this.destroy();
        return;
      }
 
      // We've submitted a response from our server session, have not attempted
      // to process any incoming data, and have no trailers. This means we can
      // attempt to gracefully close the session.
      const state = this[kState];
      if (this.headersSent &&
          this[kSession] &&
          this[kSession][kType] === NGHTTP2_SESSION_SERVER &&
          !(state.flags & STREAM_FLAGS_HAS_TRAILERS) &&
          !state.didRead &&
          this.readableFlowing === null) {
        // By using setImmediate we allow pushStreams to make it through
        // before the stream is officially closed. This prevents a bug
        // in most browsers where those pushStreams would be rejected.
        setImmediate(callStreamClose, this);
      }
    }
  }
}
 
function callTimeout(self, kSession) {
  // If the session is destroyed, this should never actually be invoked,
  // but just in case...
  if (self.destroyed)
    return;
  // This checks whether a write is currently in progress and also whether
  // that write is actually sending data across the write. The kHandle
  // stored `chunksSentSinceLastWrite` is only updated when a timeout event
  // happens, meaning that if a write is ongoing it should never equal the
  // newly fetched, updated value.
  if (self[kState].writeQueueSize > 0) {
    const handle = kSession ? self[kSession][kHandle] : self[kHandle];
    const chunksSentSinceLastWrite = handle !== undefined ?
      handle.chunksSentSinceLastWrite : null;
    if (chunksSentSinceLastWrite !== null &&
      chunksSentSinceLastWrite !== handle.updateChunksSent()) {
      self[kUpdateTimer]();
      return;
    }
  }
 
  self.emit('timeout');
}
 
function callStreamClose(stream) {
  stream.close();
}
 
function processHeaders(oldHeaders, options) {
  assertIsObject(oldHeaders, 'headers');
  const headers = ObjectCreate(null);
 
  if (oldHeaders !== null && oldHeaders !== undefined) {
    // This loop is here for performance reason. Do not change.
    for (const key in oldHeaders) {
      if (ObjectPrototypeHasOwnProperty(oldHeaders, key)) {
        headers[key] = oldHeaders[key];
      }
    }
    headers[kSensitiveHeaders] = oldHeaders[kSensitiveHeaders];
  }
 
  const statusCode =
    headers[HTTP2_HEADER_STATUS] =
      headers[HTTP2_HEADER_STATUS] | 0 || HTTP_STATUS_OK;
 
  if (options.sendDate == null || options.sendDate) {
    if (headers[HTTP2_HEADER_DATE] === null ||
        headers[HTTP2_HEADER_DATE] === undefined) {
      headers[HTTP2_HEADER_DATE] = utcDate();
    }
  }
 
  // This is intentionally stricter than the HTTP/1 implementation, which
  // allows values between 100 and 999 (inclusive) in order to allow for
  // backwards compatibility with non-spec compliant code. With HTTP/2,
  // we have the opportunity to start fresh with stricter spec compliance.
  // This will have an impact on the compatibility layer for anyone using
  // non-standard, non-compliant status codes.
  if (statusCode < 200 || statusCode > 599)
    throw new ERR_HTTP2_STATUS_INVALID(headers[HTTP2_HEADER_STATUS]);
 
  const neverIndex = headers[kSensitiveHeaders];
  if (neverIndex !== undefined && !ArrayIsArray(neverIndex))
    throw new ERR_INVALID_ARG_VALUE('headers[http2.neverIndex]', neverIndex);
 
  return headers;
}
 
 
function onFileUnpipe() {
  const stream = this.sink[kOwner];
  if (stream.ownsFd)
    PromisePrototypeCatch(this.source.close(),
                          FunctionPrototypeBind(stream.destroy, stream));
  else
    this.source.releaseFD();
}
 
// This is only called once the pipe has returned back control, so
// it only has to handle errors and End-of-File.
function onPipedFileHandleRead() {
  const err = streamBaseState[kReadBytesOrError];
  if (err < 0 && err !== UV_EOF) {
    this.stream.close(NGHTTP2_INTERNAL_ERROR);
  }
}
 
function processRespondWithFD(self, fd, headers, offset = 0, length = -1,
                              streamOptions = 0) {
  const state = self[kState];
  state.flags |= STREAM_FLAGS_HEADERS_SENT;
 
  let headersList;
  try {
    headersList = mapToHeaders(headers, assertValidPseudoHeaderResponse);
  } catch (err) {
    self.destroy(err);
    return;
  }
  self[kSentHeaders] = headers;
 
  // Close the writable side of the stream, but only as far as the writable
  // stream implementation is concerned.
  self._final = null;
  self.end();
 
  const ret = self[kHandle].respond(headersList, streamOptions);
 
  if (ret < 0) {
    self.destroy(new NghttpError(ret));
    return;
  }
 
  defaultTriggerAsyncIdScope(self[async_id_symbol], startFilePipe,
                             self, fd, offset, length);
}
 
function startFilePipe(self, fd, offset, length) {
  const handle = new FileHandle(fd, offset, length);
  handle.onread = onPipedFileHandleRead;
  handle.stream = self;
 
  const pipe = new StreamPipe(handle, self[kHandle]);
  pipe.onunpipe = onFileUnpipe;
  pipe.start();
 
  // Exact length of the file doesn't matter here, since the
  // stream is closing anyway - just use 1 to signify that
  // a write does exist
  trackWriteState(self, 1);
}
 
function doSendFD(session, options, fd, headers, streamOptions, err, stat) {
  if (err) {
    this.destroy(err);
    return;
  }
 
  // This can happen if the stream is destroyed or closed while we are waiting
  // for the file descriptor to be opened or the stat call to be completed.
  // In either case, we do not want to continue because the we are shutting
  // down and should not attempt to send any data.
  if (this.destroyed || this.closed) {
    this.destroy(new ERR_HTTP2_INVALID_STREAM());
    return;
  }
 
  const statOptions = {
    offset: options.offset !== undefined ? options.offset : 0,
    length: options.length !== undefined ? options.length : -1
  };
 
  // options.statCheck is a user-provided function that can be used to
  // verify stat values, override or set headers, or even cancel the
  // response operation. If statCheck explicitly returns false, the
  // response is canceled. The user code may also send a separate type
  // of response so check again for the HEADERS_SENT flag
  if ((typeof options.statCheck === 'function' &&
       ReflectApply(options.statCheck, this,
                    [stat, headers, statOptions]) === false) ||
       (this[kState].flags & STREAM_FLAGS_HEADERS_SENT)) {
    return;
  }
 
  processRespondWithFD(this, fd, headers,
                       statOptions.offset | 0,
                       statOptions.length | 0,
                       streamOptions);
}
 
function doSendFileFD(session, options, fd, headers, streamOptions, err, stat) {
  const onError = options.onError;
 
  if (err) {
    tryClose(fd);
    if (onError)
      onError(err);
    else
      this.destroy(err);
    return;
  }
 
  if (!stat.isFile()) {
    const isDirectory = stat.isDirectory();
    if (options.offset !== undefined || options.offset > 0 ||
        options.length !== undefined || options.length >= 0 ||
        isDirectory) {
      const err = isDirectory ?
        new ERR_HTTP2_SEND_FILE() : new ERR_HTTP2_SEND_FILE_NOSEEK();
      tryClose(fd);
      if (onError)
        onError(err);
      else
        this.destroy(err);
      return;
    }
 
    options.offset = -1;
    options.length = -1;
  }
 
  if (this.destroyed || this.closed) {
    tryClose(fd);
    this.destroy(new ERR_HTTP2_INVALID_STREAM());
    return;
  }
 
  const statOptions = {
    offset: options.offset !== undefined ? options.offset : 0,
    length: options.length !== undefined ? options.length : -1
  };
 
  // options.statCheck is a user-provided function that can be used to
  // verify stat values, override or set headers, or even cancel the
  // response operation. If statCheck explicitly returns false, the
  // response is canceled. The user code may also send a separate type
  // of response so check again for the HEADERS_SENT flag
  if ((typeof options.statCheck === 'function' &&
       ReflectApply(options.statCheck, this, [stat, headers]) === false) ||
       (this[kState].flags & STREAM_FLAGS_HEADERS_SENT)) {
    tryClose(fd);
    return;
  }
 
  if (stat.isFile()) {
    statOptions.length =
      statOptions.length < 0 ? stat.size - (+statOptions.offset) :
        MathMin(stat.size - (+statOptions.offset),
                statOptions.length);
 
    headers[HTTP2_HEADER_CONTENT_LENGTH] = statOptions.length;
  }
 
  processRespondWithFD(this, fd, headers,
                       options.offset | 0,
                       statOptions.length | 0,
                       streamOptions);
}
 
function afterOpen(session, options, headers, streamOptions, err, fd) {
  const state = this[kState];
  const onError = options.onError;
  if (err) {
    if (onError)
      onError(err);
    else
      this.destroy(err);
    return;
  }
  if (this.destroyed || this.closed) {
    tryClose(fd);
    return;
  }
  state.fd = fd;
 
  fs.fstat(fd,
           FunctionPrototypeBind(doSendFileFD, this,
                                 session, options, fd,
                                 headers, streamOptions));
}
 
class ServerHttp2Stream extends Http2Stream {
  constructor(session, handle, id, options, headers) {
    super(session, options);
    handle.owner = this;
    this[kInit](id, handle);
    this[kProtocol] = headers[HTTP2_HEADER_SCHEME];
    this[kAuthority] = getAuthority(headers);
  }
 
  // True if the remote peer accepts push streams
  get pushAllowed() {
    return !this.destroyed &&
           !this.closed &&
           !this.session.closed &&
           !this.session.destroyed &&
           this[kSession].remoteSettings.enablePush;
  }
 
  // Create a push stream, call the given callback with the created
  // Http2Stream for the push stream.
  pushStream(headers, options, callback) {
    if (!this.pushAllowed)
      throw new ERR_HTTP2_PUSH_DISABLED();
    if (this[kID] % 2 === 0)
      throw new ERR_HTTP2_NESTED_PUSH();
 
    const session = this[kSession];
 
    debugStreamObj(this, 'initiating push stream');
 
    this[kUpdateTimer]();
 
    if (typeof options === 'function') {
      callback = options;
      options = undefined;
    }
 
    validateCallback(callback);
 
    assertIsObject(options, 'options');
    options = { ...options };
    options.endStream = !!options.endStream;
 
    assertIsObject(headers, 'headers');
    headers = ObjectAssign(ObjectCreate(null), headers);
 
    if (headers[HTTP2_HEADER_METHOD] === undefined)
      headers[HTTP2_HEADER_METHOD] = HTTP2_METHOD_GET;
    if (getAuthority(headers) === undefined)
      headers[HTTP2_HEADER_AUTHORITY] = this[kAuthority];
    if (headers[HTTP2_HEADER_SCHEME] === undefined)
      headers[HTTP2_HEADER_SCHEME] = this[kProtocol];
    if (headers[HTTP2_HEADER_PATH] === undefined)
      headers[HTTP2_HEADER_PATH] = '/';
 
    let headRequest = false;
    if (headers[HTTP2_HEADER_METHOD] === HTTP2_METHOD_HEAD)
      headRequest = options.endStream = true;
    options.readable = false;
 
    const headersList = mapToHeaders(headers);
 
    const streamOptions = options.endStream ? STREAM_OPTION_EMPTY_PAYLOAD : 0;
 
    const ret = this[kHandle].pushPromise(headersList, streamOptions);
    let err;
    if (typeof ret === 'number') {
      switch (ret) {
        case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE:
          err = new ERR_HTTP2_OUT_OF_STREAMS();
          break;
        case NGHTTP2_ERR_STREAM_CLOSED:
          err = new ERR_HTTP2_INVALID_STREAM();
          break;
        default:
          err = new NghttpError(ret);
          break;
      }
      process.nextTick(callback, err);
      return;
    }
 
    const id = ret.id();
    const stream = new ServerHttp2Stream(session, ret, id, options, headers);
    stream[kSentHeaders] = headers;
 
    if (options.endStream)
      stream.end();
 
    if (headRequest)
      stream[kState].flags |= STREAM_FLAGS_HEAD_REQUEST;
 
    process.nextTick(callback, null, stream, headers, 0);
  }
 
  // Initiate a response on this Http2Stream
  respond(headers, options) {
    if (this.destroyed || this.closed)
      throw new ERR_HTTP2_INVALID_STREAM();
    if (this.headersSent)
      throw new ERR_HTTP2_HEADERS_SENT();
 
    const state = this[kState];
 
    assertIsObject(options, 'options');
    options = { ...options };
 
    debugStreamObj(this, 'initiating response');
    this[kUpdateTimer]();
 
    options.endStream = !!options.endStream;
 
    let streamOptions = 0;
    if (options.endStream)
      streamOptions |= STREAM_OPTION_EMPTY_PAYLOAD;
 
    if (options.waitForTrailers) {
      streamOptions |= STREAM_OPTION_GET_TRAILERS;
      state.flags |= STREAM_FLAGS_HAS_TRAILERS;
    }
 
    headers = processHeaders(headers, options);
    const headersList = mapToHeaders(headers, assertValidPseudoHeaderResponse);
    this[kSentHeaders] = headers;
 
    state.flags |= STREAM_FLAGS_HEADERS_SENT;
 
    // Close the writable side if the endStream option is set or status
    // is one of known codes with no payload, or it's a head request
    const statusCode = headers[HTTP2_HEADER_STATUS] | 0;
    if (!!options.endStream ||
        statusCode === HTTP_STATUS_NO_CONTENT ||
        statusCode === HTTP_STATUS_RESET_CONTENT ||
        statusCode === HTTP_STATUS_NOT_MODIFIED ||
        this.headRequest === true) {
      options.endStream = true;
      this.end();
    }
 
    const ret = this[kHandle].respond(headersList, streamOptions);
    if (ret < 0)
      this.destroy(new NghttpError(ret));
  }
 
  // Initiate a response using an open FD. Note that there are fewer
  // protections with this approach. For one, the fd is not validated by
  // default. In respondWithFile, the file is checked to make sure it is a
  // regular file, here the fd is passed directly. If the underlying
  // mechanism is not able to read from the fd, then the stream will be
  // reset with an error code.
  respondWithFD(fd, headers, options) {
    if (this.destroyed || this.closed)
      throw new ERR_HTTP2_INVALID_STREAM();
    if (this.headersSent)
      throw new ERR_HTTP2_HEADERS_SENT();
 
    const session = this[kSession];
 
    assertIsObject(options, 'options');
    options = { ...options };
 
    if (options.offset !== undefined && typeof options.offset !== 'number')
      throw new ERR_INVALID_ARG_VALUE('options.offset', options.offset);
 
    if (options.length !== undefined && typeof options.length !== 'number')
      throw new ERR_INVALID_ARG_VALUE('options.length', options.length);
 
    if (options.statCheck !== undefined &&
        typeof options.statCheck !== 'function') {
      throw new ERR_INVALID_ARG_VALUE('options.statCheck', options.statCheck);
    }
 
    let streamOptions = 0;
    if (options.waitForTrailers) {
      streamOptions |= STREAM_OPTION_GET_TRAILERS;
      this[kState].flags |= STREAM_FLAGS_HAS_TRAILERS;
    }
 
    if (fd instanceof fsPromisesInternal.FileHandle)
      fd = fd.fd;
    else if (typeof fd !== 'number')
      throw new ERR_INVALID_ARG_TYPE('fd', ['number', 'FileHandle'], fd);
 
    debugStreamObj(this, 'initiating response from fd');
    this[kUpdateTimer]();
    this.ownsFd = false;
 
    headers = processHeaders(headers, options);
    const statusCode = headers[HTTP2_HEADER_STATUS] |= 0;
    // Payload/DATA frames are not permitted in these cases
    if (statusCode === HTTP_STATUS_NO_CONTENT ||
        statusCode === HTTP_STATUS_RESET_CONTENT ||
        statusCode === HTTP_STATUS_NOT_MODIFIED ||
        this.headRequest) {
      throw new ERR_HTTP2_PAYLOAD_FORBIDDEN(statusCode);
    }
 
    if (options.statCheck !== undefined) {
      fs.fstat(fd,
               FunctionPrototypeBind(doSendFD, this,
                                     session, options, fd,
                                     headers, streamOptions));
      return;
    }
 
    processRespondWithFD(this, fd, headers,
                         options.offset,
                         options.length,
                         streamOptions);
  }
 
  // Initiate a file response on this Http2Stream. The path is passed to
  // fs.open() to acquire the fd with mode 'r', then the fd is passed to
  // fs.fstat(). Assuming fstat is successful, a check is made to ensure
  // that the file is a regular file, then options.statCheck is called,
  // giving the user an opportunity to verify the details and set additional
  // headers. If statCheck returns false, the operation is aborted and no
  // file details are sent.
  respondWithFile(path, headers, options) {
    if (this.destroyed || this.closed)
      throw new ERR_HTTP2_INVALID_STREAM();
    if (this.headersSent)
      throw new ERR_HTTP2_HEADERS_SENT();
 
    assertIsObject(options, 'options');
    options = { ...options };
 
    if (options.offset !== undefined && typeof options.offset !== 'number')
      throw new ERR_INVALID_ARG_VALUE('options.offset', options.offset);
 
    if (options.length !== undefined && typeof options.length !== 'number')
      throw new ERR_INVALID_ARG_VALUE('options.length', options.length);
 
    if (options.statCheck !== undefined &&
        typeof options.statCheck !== 'function') {
      throw new ERR_INVALID_ARG_VALUE('options.statCheck', options.statCheck);
    }
 
    let streamOptions = 0;
    if (options.waitForTrailers) {
      streamOptions |= STREAM_OPTION_GET_TRAILERS;
      this[kState].flags |= STREAM_FLAGS_HAS_TRAILERS;
    }
 
    const session = this[kSession];
    debugStreamObj(this, 'initiating response from file');
    this[kUpdateTimer]();
    this.ownsFd = true;
 
    headers = processHeaders(headers, options);
    const statusCode = headers[HTTP2_HEADER_STATUS] |= 0;
    // Payload/DATA frames are not permitted in these cases
    if (statusCode === HTTP_STATUS_NO_CONTENT ||
        statusCode === HTTP_STATUS_RESET_CONTENT ||
        statusCode === HTTP_STATUS_NOT_MODIFIED ||
        this.headRequest) {
      throw new ERR_HTTP2_PAYLOAD_FORBIDDEN(statusCode);
    }
 
    fs.open(path, 'r',
            FunctionPrototypeBind(afterOpen, this,
                                  session, options, headers, streamOptions));
  }
 
  // Sends a block of informational headers. In theory, the HTTP/2 spec
  // allows sending a HEADER block at any time during a streams lifecycle,
  // but the HTTP request/response semantics defined in HTTP/2 places limits
  // such that HEADERS may only be sent *before* or *after* DATA frames.
  // If the block of headers being sent includes a status code, it MUST be
  // a 1xx informational code and it MUST be sent before the request/response
  // headers are sent, or an error will be thrown.
  additionalHeaders(headers) {
    if (this.destroyed || this.closed)
      throw new ERR_HTTP2_INVALID_STREAM();
    if (this.headersSent)
      throw new ERR_HTTP2_HEADERS_AFTER_RESPOND();
 
    assertIsObject(headers, 'headers');
    headers = ObjectAssign(ObjectCreate(null), headers);
 
    debugStreamObj(this, 'sending additional headers');
 
    if (headers[HTTP2_HEADER_STATUS] != null) {
      const statusCode = headers[HTTP2_HEADER_STATUS] |= 0;
      if (statusCode === HTTP_STATUS_SWITCHING_PROTOCOLS)
        throw new ERR_HTTP2_STATUS_101();
      if (statusCode < 100 || statusCode >= 200) {
        throw new ERR_HTTP2_INVALID_INFO_STATUS(headers[HTTP2_HEADER_STATUS]);
      }
    }
 
    this[kUpdateTimer]();
 
    const headersList = mapToHeaders(headers, assertValidPseudoHeaderResponse);
    if (!this[kInfoHeaders])
      this[kInfoHeaders] = [headers];
    else
      ArrayPrototypePush(this[kInfoHeaders], headers);
 
    const ret = this[kHandle].info(headersList);
    if (ret < 0)
      this.destroy(new NghttpError(ret));
  }
}
 
ServerHttp2Stream.prototype[kProceed] = ServerHttp2Stream.prototype.respond;
 
class ClientHttp2Stream extends Http2Stream {
  constructor(session, handle, id, options) {
    super(session, options);
    this[kState].flags |= STREAM_FLAGS_HEADERS_SENT;
    if (id !== undefined)
      this[kInit](id, handle);
    this.on('headers', handleHeaderContinue);
  }
}
 
function handleHeaderContinue(headers) {
  if (headers[HTTP2_HEADER_STATUS] === HTTP_STATUS_CONTINUE)
    this.emit('continue');
}
 
const setTimeoutValue = {
  configurable: true,
  enumerable: true,
  writable: true,
  value: setStreamTimeout
};
ObjectDefineProperty(Http2Stream.prototype, 'setTimeout', setTimeoutValue);
ObjectDefineProperty(Http2Session.prototype, 'setTimeout', setTimeoutValue);
 
 
// When the socket emits an error, destroy the associated Http2Session and
// forward it the same error.
function socketOnError(error) {
  const session = this[kSession];
  if (session !== undefined) {
    // We can ignore ECONNRESET after GOAWAY was received as there's nothing
    // we can do and the other side is fully within its rights to do so.
    if (error.code === 'ECONNRESET' && session[kState].goawayCode !== null)
      return session.destroy();
    debugSessionObj(this, 'socket error [%s]', error.message);
    session.destroy(error);
  }
}
 
// Handles the on('stream') event for a session and forwards
// it on to the server object.
function sessionOnStream(stream, headers, flags, rawHeaders) {
  if (this[kServer] !== undefined)
    this[kServer].emit('stream', stream, headers, flags, rawHeaders);
}
 
function sessionOnPriority(stream, parent, weight, exclusive) {
  if (this[kServer] !== undefined)
    this[kServer].emit('priority', stream, parent, weight, exclusive);
}
 
function sessionOnError(error) {
  if (this[kServer] !== undefined)
    this[kServer].emit('sessionError', error, this);
}
 
// When the session times out on the server, try emitting a timeout event.
// If no handler is registered, destroy the session.
function sessionOnTimeout() {
  // If destroyed or closed already, do nothing
  if (this.destroyed || this.closed)
    return;
  const server = this[kServer];
  if (!server.emit('timeout', this))
    this.destroy();  // No error code, just things down.
}
 
function connectionListener(socket) {
  debug('Http2Session server: received a connection');
  const options = this[kOptions] || {};
 
  if (socket.alpnProtocol === false || socket.alpnProtocol === 'http/1.1') {
    // Fallback to HTTP/1.1
    if (options.allowHTTP1 === true) {
      socket.server[kIncomingMessage] = options.Http1IncomingMessage;
      socket.server[kServerResponse] = options.Http1ServerResponse;
      return FunctionPrototypeCall(httpConnectionListener, this, socket);
    }
    // Let event handler deal with the socket
    debug('Unknown protocol from %s:%s',
          socket.remoteAddress, socket.remotePort);
    if (!this.emit('unknownProtocol', socket)) {
      debug('Unknown protocol timeout:  %s', options.unknownProtocolTimeout);
      // Install a timeout if the socket was not successfully closed, then
      // destroy the socket to ensure that the underlying resources are
      // released.
      const timer = setTimeout(() => {
        if (!socket.destroyed) {
          debug('UnknownProtocol socket timeout, destroy socket');
          socket.destroy();
        }
      }, options.unknownProtocolTimeout);
      // Un-reference the timer to avoid blocking of application shutdown and
      // clear the timeout if the socket was successfully closed.
      timer.unref();
 
      socket.once('close', () => clearTimeout(timer));
 
      // We don't know what to do, so let's just tell the other side what's
      // going on in a format that they *might* understand.
      socket.end('HTTP/1.0 403 Forbidden\r\n' +
                 'Content-Type: text/plain\r\n\r\n' +
                 'Unknown ALPN Protocol, expected `h2` to be available.\n' +
                 'If this is a HTTP request: The server was not ' +
                 'configured with the `allowHTTP1` option or a ' +
                 'listener for the `unknownProtocol` event.\n');
    }
    return;
  }
 
  // Set up the Session
  const session = new ServerHttp2Session(options, socket, this);
 
  session.on('stream', sessionOnStream);
  session.on('error', sessionOnError);
  // Don't count our own internal listener.
  session.on('priority', sessionOnPriority);
  session[kNativeFields][kSessionPriorityListenerCount]--;
 
  if (this.timeout)
    session.setTimeout(this.timeout, sessionOnTimeout);
 
  socket[kServer] = this;
 
  this.emit('session', session);
}
 
function initializeOptions(options) {
  assertIsObject(options, 'options');
  options = { ...options };
  assertIsObject(options.settings, 'options.settings');
  options.settings = { ...options.settings };
 
  if (options.maxSessionInvalidFrames !== undefined)
    validateUint32(options.maxSessionInvalidFrames, 'maxSessionInvalidFrames');
 
  if (options.maxSessionRejectedStreams !== undefined) {
    validateUint32(
      options.maxSessionRejectedStreams,
      'maxSessionRejectedStreams'
    );
  }
 
  if (options.unknownProtocolTimeout !== undefined)
    validateUint32(options.unknownProtocolTimeout, 'unknownProtocolTimeout');
  else
    // TODO(danbev): is this a good default value?
    options.unknownProtocolTimeout = 10000;
 
 
  // Used only with allowHTTP1
  options.Http1IncomingMessage = options.Http1IncomingMessage ||
    http.IncomingMessage;
  options.Http1ServerResponse = options.Http1ServerResponse ||
    http.ServerResponse;
 
  options.Http2ServerRequest = options.Http2ServerRequest ||
                                       Http2ServerRequest;
  options.Http2ServerResponse = options.Http2ServerResponse ||
                                        Http2ServerResponse;
  return options;
}
 
function initializeTLSOptions(options, servername) {
  options = initializeOptions(options);
  options.ALPNProtocols = ['h2'];
  if (options.allowHTTP1 === true)
    ArrayPrototypePush(options.ALPNProtocols, 'http/1.1');
  if (servername !== undefined && options.servername === undefined)
    options.servername = servername;
  return options;
}
 
function onErrorSecureServerSession(err, socket) {
  if (!this.emit('clientError', err, socket))
    socket.destroy(err);
}
 
class Http2SecureServer extends TLSServer {
  constructor(options, requestListener) {
    options = initializeTLSOptions(options);
    super(options, connectionListener);
    this[kOptions] = options;
    this.timeout = 0;
    this.on('newListener', setupCompat);
    if (typeof requestListener === 'function')
      this.on('request', requestListener);
    this.on('tlsClientError', onErrorSecureServerSession);
  }
 
  setTimeout(msecs, callback) {
    this.timeout = msecs;
    if (callback !== undefined) {
      validateCallback(callback);
      this.on('timeout', callback);
    }
    return this;
  }
 
  updateSettings(settings) {
    assertIsObject(settings, 'settings');
    validateSettings(settings);
    this[kOptions].settings = { ...this[kOptions].settings, ...settings };
  }
}
 
class Http2Server extends NETServer {
  constructor(options, requestListener) {
    options = initializeOptions(options);
    super(options, connectionListener);
    this[kOptions] = options;
    this.timeout = 0;
    this.on('newListener', setupCompat);
    if (typeof requestListener === 'function')
      this.on('request', requestListener);
  }
 
  setTimeout(msecs, callback) {
    this.timeout = msecs;
    if (callback !== undefined) {
      validateCallback(callback);
      this.on('timeout', callback);
    }
    return this;
  }
 
  updateSettings(settings) {
    assertIsObject(settings, 'settings');
    validateSettings(settings);
    this[kOptions].settings = { ...this[kOptions].settings, ...settings };
  }
}
 
Http2Server.prototype[EventEmitter.captureRejectionSymbol] = function(
  err, event, ...args) {
 
  switch (event) {
    case 'stream':
      // TODO(mcollina): we might want to match this with what we do on
      // the compat side.
      const { 0: stream } = args;
      if (stream.sentHeaders) {
        stream.destroy(err);
      } else {
        stream.respond({ [HTTP2_HEADER_STATUS]: 500 });
        stream.end();
      }
      break;
    case 'request':
      const { 1: res } = args;
      if (!res.headersSent && !res.finished) {
        // Don't leak headers.
        for (const name of res.getHeaderNames()) {
          res.removeHeader(name);
        }
        res.statusCode = 500;
        res.end(http.STATUS_CODES[500]);
      } else {
        res.destroy();
      }
      break;
    default:
      ArrayPrototypeUnshift(args, err, event);
      ReflectApply(net.Server.prototype[EventEmitter.captureRejectionSymbol],
                   this, args);
  }
};
 
function setupCompat(ev) {
  if (ev === 'request') {
    this.removeListener('newListener', setupCompat);
    this.on('stream', FunctionPrototypeBind(onServerStream,
                                            this,
                                            this[kOptions].Http2ServerRequest,
                                            this[kOptions].Http2ServerResponse)
    );
  }
}
 
function socketOnClose() {
  const session = this[kSession];
  if (session !== undefined) {
    debugSessionObj(session, 'socket closed');
    const err = session.connecting ? new ERR_SOCKET_CLOSED() : null;
    const state = session[kState];
    state.streams.forEach((stream) => stream.close(NGHTTP2_CANCEL));
    state.pendingStreams.forEach((stream) => stream.close(NGHTTP2_CANCEL));
    session.close();
    session[kMaybeDestroy](err);
  }
}
 
function connect(authority, options, listener) {
  if (typeof options === 'function') {
    listener = options;
    options = undefined;
  }
 
  assertIsObject(options, 'options');
  options = { ...options };
 
  if (typeof authority === 'string')
    authority = new URL(authority);
 
  assertIsObject(authority, 'authority', ['string', 'Object', 'URL']);
 
  const protocol = authority.protocol || options.protocol || 'https:';
  const port = '' + (authority.port !== '' ?
    authority.port : (authority.protocol === 'http:' ? 80 : 443));
  let host = 'localhost';
 
  if (authority.hostname) {
    host = authority.hostname;
 
    if (host[0] === '[')
      host = StringPrototypeSlice(host, 1, -1);
  } else if (authority.host) {
    host = authority.host;
  }
 
  let socket;
  if (typeof options.createConnection === 'function') {
    socket = options.createConnection(authority, options);
  } else {
    switch (protocol) {
      case 'http:':
        socket = net.connect({ port, host, ...options });
        break;
      case 'https:':
        socket = tls.connect(port, host, initializeTLSOptions(options, host));
        break;
      default:
        throw new ERR_HTTP2_UNSUPPORTED_PROTOCOL(protocol);
    }
  }
 
  const session = new ClientHttp2Session(options, socket);
 
  session[kAuthority] = `${options.servername || host}:${port}`;
  session[kProtocol] = protocol;
 
  if (typeof listener === 'function')
    session.once('connect', listener);
 
  // Process data on the next tick - a remoteSettings handler may be attached.
  // https://github.com/nodejs/node/issues/35981
  process.nextTick(() => {
    debug('Http2Session connect', options.createConnection);
    // Socket already has some buffered data - emulate receiving it
    // https://github.com/nodejs/node/issues/35475
    if (socket && socket.readableLength) {
      let buf;
      while ((buf = socket.read()) !== null) {
        debug(`Http2Session connect: ${buf.length} bytes already in buffer`);
        session[kHandle].receive(buf);
      }
    }
  });
 
  return session;
}
 
// Support util.promisify
ObjectDefineProperty(connect, promisify.custom, {
  value: (authority, options) => {
    return new Promise((resolve) => {
      const server = connect(authority, options, () => resolve(server));
    });
  }
});
 
function createSecureServer(options, handler) {
  return new Http2SecureServer(options, handler);
}
 
function createServer(options, handler) {
  if (typeof options === 'function') {
    handler = options;
    options = {};
  }
  return new Http2Server(options, handler);
}
 
// Returns a Base64 encoded settings frame payload from the given
// object. The value is suitable for passing as the value of the
// HTTP2-Settings header frame.
function getPackedSettings(settings) {
  assertIsObject(settings, 'settings');
  validateSettings(settings);
  updateSettingsBuffer({ ...settings });
  return binding.packSettings();
}
 
function getUnpackedSettings(buf, options = {}) {
  if (!isArrayBufferView(buf) || buf.length === undefined) {
    throw new ERR_INVALID_ARG_TYPE('buf',
                                   ['Buffer', 'TypedArray'], buf);
  }
  if (buf.length % 6 !== 0)
    throw new ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH();
  const settings = {};
  let offset = 0;
  while (offset < buf.length) {
    const id = ReflectApply(readUInt16BE, buf, [offset]);
    offset += 2;
    const value = ReflectApply(readUInt32BE, buf, [offset]);
    switch (id) {
      case NGHTTP2_SETTINGS_HEADER_TABLE_SIZE:
        settings.headerTableSize = value;
        break;
      case NGHTTP2_SETTINGS_ENABLE_PUSH:
        settings.enablePush = value !== 0;
        break;
      case NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS:
        settings.maxConcurrentStreams = value;
        break;
      case NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE:
        settings.initialWindowSize = value;
        break;
      case NGHTTP2_SETTINGS_MAX_FRAME_SIZE:
        settings.maxFrameSize = value;
        break;
      case NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE:
        settings.maxHeaderListSize = settings.maxHeaderSize = value;
        break;
      case NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL:
        settings.enableConnectProtocol = value !== 0;
    }
    offset += 4;
  }
 
  if (options != null && options.validate)
    validateSettings(settings);
 
  return settings;
}
 
binding.setCallbackFunctions(
  onSessionInternalError,
  onPriority,
  onSettings,
  onPing,
  onSessionHeaders,
  onFrameError,
  onGoawayData,
  onAltSvc,
  onOrigin,
  onStreamTrailers,
  onStreamClose
);
 
// Exports
module.exports = {
  connect,
  constants,
  createServer,
  createSecureServer,
  getDefaultSettings,
  getPackedSettings,
  getUnpackedSettings,
  sensitiveHeaders: kSensitiveHeaders,
  Http2Session,
  Http2Stream,
  Http2ServerRequest,
  Http2ServerResponse
};
 
/* eslint-enable no-use-before-define */