File size: 194,431 Bytes
b91e262 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 | import type { ComponentType, ErrorInfo, JSX, ReactNode } from 'react'
import type { RenderOpts, PreloadCallbacks } from './types'
import type {
ActionResult,
DynamicParamTypesShort,
FlightRouterState,
Segment,
CacheNodeSeedData,
RSCPayload,
FlightData,
InitialRSCPayload,
FlightDataPath,
} from '../../shared/lib/app-router-types'
import type { Readable } from 'node:stream'
import {
workAsyncStorage,
type WorkStore,
} from '../app-render/work-async-storage.external'
import type {
PrerenderStoreModernRuntime,
RequestStore,
} from '../app-render/work-unit-async-storage.external'
import type { NextParsedUrlQuery } from '../request-meta'
import type { LoaderTree } from '../lib/app-dir-module'
import type { AppPageModule } from '../route-modules/app-page/module'
import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { IncomingHttpHeaders } from 'http'
import * as ReactClient from 'react'
import RenderResult, {
type AppPageRenderResultMetadata,
type RenderResultOptions,
} from '../render-result'
import {
chainStreams,
renderToInitialFizzStream,
createDocumentClosingStream,
continueFizzStream,
continueDynamicPrerender,
continueStaticPrerender,
continueDynamicHTMLResume,
streamToBuffer,
streamToString,
continueStaticFallbackPrerender,
} from '../stream-utils/node-web-streams-helper'
import { stripInternalQueries } from '../internal-utils'
import {
NEXT_HMR_REFRESH_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_ROUTER_STALE_TIME_HEADER,
NEXT_URL,
RSC_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_REQUEST_ID_HEADER,
NEXT_HTML_REQUEST_ID_HEADER,
} from '../../client/components/app-router-headers'
import { createMetadataContext } from '../../lib/metadata/metadata-context'
import { createRequestStoreForRender } from '../async-storage/request-store'
import { createWorkStore } from '../async-storage/work-store'
import {
getAccessFallbackErrorTypeByStatus,
getAccessFallbackHTTPStatus,
isHTTPAccessFallbackError,
} from '../../client/components/http-access-fallback/http-access-fallback'
import {
getURLFromRedirectError,
getRedirectStatusCodeFromError,
} from '../../client/components/redirect'
import { isRedirectError } from '../../client/components/redirect-error'
import { getImplicitTags, type ImplicitTags } from '../lib/implicit-tags'
import { AppRenderSpan, NextNodeServerSpan } from '../lib/trace/constants'
import { getTracer, SpanStatusCode } from '../lib/trace/tracer'
import { FlightRenderResult } from './flight-render-result'
import {
createReactServerErrorHandler,
createHTMLErrorHandler,
type DigestedError,
isUserLandError,
getDigestForWellKnownError,
} from './create-error-handler'
import { dynamicParamTypes } from './get-short-dynamic-param-type'
import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param'
import { getScriptNonceFromHeader } from './get-script-nonce-from-header'
import { parseAndValidateFlightRouterState } from './parse-and-validate-flight-router-state'
import { createFlightRouterStateFromLoaderTree } from './create-flight-router-state-from-loader-tree'
import { handleAction } from './action-handler'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { warn, error } from '../../build/output/log'
import { appendMutableCookies } from '../web/spec-extension/adapters/request-cookies'
import { createServerInsertedHTML } from './server-inserted-html'
import { getRequiredScripts } from './required-scripts'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
import { makeGetServerInsertedHTML } from './make-get-server-inserted-html'
import { walkTreeWithFlightRouterState } from './walk-tree-with-flight-router-state'
import { createComponentTree, getRootParams } from './create-component-tree'
import { getAssetQueryString } from './get-asset-query-string'
import {
getClientReferenceManifest,
getServerModuleMap,
} from './manifests-singleton'
import {
DynamicState,
type PostponedState,
DynamicHTMLPreludeState,
parsePostponedState,
} from './postponed-state'
import {
getDynamicDataPostponedState,
getDynamicHTMLPostponedState,
getPostponedFromState,
} from './postponed-state'
import { isDynamicServerError } from '../../client/components/hooks-server-context'
import {
getFlightStream,
createInlinedDataReadableStream,
} from './use-flight-response'
import {
StaticGenBailoutError,
isStaticGenBailoutError,
} from '../../client/components/static-generation-bailout'
import { getStackWithoutErrorMessage } from '../../lib/format-server-error'
import {
accessedDynamicData,
createRenderInBrowserAbortSignal,
formatDynamicAPIAccesses,
isPrerenderInterruptedError,
createDynamicTrackingState,
createDynamicValidationState,
trackAllowedDynamicAccess,
throwIfDisallowedDynamic,
PreludeState,
consumeDynamicAccess,
type DynamicAccess,
logDisallowedDynamicError,
trackDynamicHoleInRuntimeShell,
trackDynamicHoleInStaticShell,
getStaticShellDisallowedDynamicReasons,
} from './dynamic-rendering'
import {
getClientComponentLoaderMetrics,
wrapClientComponentLoader,
} from '../client-component-renderer-logger'
import { isNodeNextRequest } from '../base-http/helpers'
import { parseRelativeUrl } from '../../shared/lib/router/utils/parse-relative-url'
import AppRouter from '../../client/components/app-router'
import type { ServerComponentsHmrCache } from '../response-cache'
import type { RequestErrorContext } from '../instrumentation/types'
import { getIsPossibleServerAction } from '../lib/server-action-request-meta'
import { createInitialRouterState } from '../../client/components/router-reducer/create-initial-router-state'
import { createMutableActionQueue } from '../../client/components/app-router-instance'
import { getRevalidateReason } from '../instrumentation/utils'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import {
prerenderAndAbortInSequentialTasksWithStages,
processPrelude,
} from './app-render-prerender-utils'
import {
type ReactServerPrerenderResult,
ReactServerResult,
createReactServerPrerenderResult,
createReactServerPrerenderResultFromRender,
prerenderAndAbortInSequentialTasks,
} from './app-render-prerender-utils'
import {
Phase,
printDebugThrownValueForProspectiveRender,
} from './prospective-render-utils'
import {
pipelineInSequentialTasks,
scheduleInSequentialTasks,
} from './app-render-render-utils'
import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler'
import {
getHmrRefreshHash,
workUnitAsyncStorage,
type PrerenderStore,
} from './work-unit-async-storage.external'
import { consoleAsyncStorage } from './console-async-storage.external'
import { CacheSignal } from './cache-signal'
import { getTracedMetadata } from '../lib/trace/utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { HTML_CONTENT_TYPE_HEADER, INFINITE_CACHE } from '../../lib/constants'
import { createComponentStylesAndScripts } from './create-component-styles-and-scripts'
import { parseLoaderTree } from '../../shared/lib/router/utils/parse-loader-tree'
import {
createPrerenderResumeDataCache,
createRenderResumeDataCache,
type PrerenderResumeDataCache,
type RenderResumeDataCache,
} from '../resume-data-cache/resume-data-cache'
import type { MetadataErrorType } from '../../lib/metadata/resolve-metadata'
import isError from '../../lib/is-error'
import { createServerInsertedMetadata } from './metadata-insertion/create-server-inserted-metadata'
import { getPreviouslyRevalidatedTags } from '../server-utils'
import { executeRevalidates } from '../revalidation-utils'
import {
trackPendingChunkLoad,
trackPendingImport,
trackPendingModules,
} from './module-loading/track-module-loading.external'
import { isReactLargeShellError } from './react-large-shell-error'
import type { GlobalErrorComponent } from '../../client/components/builtin/global-error'
import { normalizeConventionFilePath } from './segment-explorer-path'
import { getRequestMeta } from '../request-meta'
import {
getDynamicParam,
interpolateParallelRouteParams,
} from '../../shared/lib/router/utils/get-dynamic-param'
import type { ExperimentalConfig } from '../config-shared'
import type { Params } from '../request/params'
import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'
import { ImageConfigContext } from '../../shared/lib/image-config-context.shared-runtime'
import { imageConfigDefault } from '../../shared/lib/image-config'
import { RenderStage, StagedRenderingController } from './staged-rendering'
import { anySegmentHasRuntimePrefetchEnabled } from './staged-validation'
import { warnOnce } from '../../shared/lib/utils/warn-once'
export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug]
segment: string
) => DynamicParam | null
export type DynamicParam = {
param: string
value: string | string[] | null
treeSegment: Segment
type: DynamicParamTypesShort
}
export type GenerateFlight = typeof generateDynamicFlightRenderResult
export type AppSharedContext = {
buildId: string
}
export type AppRenderContext = {
sharedContext: AppSharedContext
workStore: WorkStore
url: ReturnType<typeof parseRelativeUrl>
componentMod: AppPageModule
renderOpts: RenderOpts
parsedRequestHeaders: ParsedRequestHeaders
getDynamicParamFromSegment: GetDynamicParamFromSegment
query: NextParsedUrlQuery
isPrefetch: boolean
isPossibleServerAction: boolean
requestTimestamp: number
appUsingSizeAdjustment: boolean
flightRouterState?: FlightRouterState
requestId: string
htmlRequestId: string
pagePath: string
assetPrefix: string
isNotFoundPath: boolean
nonce: string | undefined
res: BaseNextResponse
/**
* For now, the implicit tags are common for the whole route. If we ever start
* rendering/revalidating segments independently, they need to move to the
* work unit store.
*/
implicitTags: ImplicitTags
}
interface ParseRequestHeadersOptions {
readonly isRoutePPREnabled: boolean
readonly previewModeId: string | undefined
}
const flightDataPathHeadKey = 'h'
const getFlightViewportKey = (requestId: string) => requestId + 'v'
const getFlightMetadataKey = (requestId: string) => requestId + 'm'
const filterStackFrame =
process.env.NODE_ENV !== 'production'
? (require('../lib/source-maps') as typeof import('../lib/source-maps'))
.filterStackFrameDEV
: undefined
interface ParsedRequestHeaders {
/**
* Router state provided from the client-side router. Used to handle rendering
* from the common layout down. This value will be undefined if the request is
* not a client-side navigation request, or if the request is a prefetch
* request.
*/
readonly flightRouterState: FlightRouterState | undefined
readonly isPrefetchRequest: boolean
readonly isRuntimePrefetchRequest: boolean
readonly isRouteTreePrefetchRequest: boolean
readonly isHmrRefresh: boolean
readonly isRSCRequest: boolean
readonly nonce: string | undefined
readonly previouslyRevalidatedTags: string[]
readonly requestId: string | undefined
readonly htmlRequestId: string | undefined
}
function parseRequestHeaders(
headers: IncomingHttpHeaders,
options: ParseRequestHeadersOptions
): ParsedRequestHeaders {
// runtime prefetch requests are *not* treated as prefetch requests
// (TODO: this is confusing, we should refactor this to express this better)
const isPrefetchRequest = headers[NEXT_ROUTER_PREFETCH_HEADER] === '1'
const isRuntimePrefetchRequest = headers[NEXT_ROUTER_PREFETCH_HEADER] === '2'
const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined
const isRSCRequest = headers[RSC_HEADER] !== undefined
const shouldProvideFlightRouterState =
isRSCRequest && (!isPrefetchRequest || !options.isRoutePPREnabled)
const flightRouterState = shouldProvideFlightRouterState
? parseAndValidateFlightRouterState(headers[NEXT_ROUTER_STATE_TREE_HEADER])
: undefined
// Checks if this is a prefetch of the Route Tree by the Segment Cache
const isRouteTreePrefetchRequest =
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] === '/_tree'
const csp =
headers['content-security-policy'] ||
headers['content-security-policy-report-only']
const nonce =
typeof csp === 'string' ? getScriptNonceFromHeader(csp) : undefined
const previouslyRevalidatedTags = getPreviouslyRevalidatedTags(
headers,
options.previewModeId
)
let requestId: string | undefined
let htmlRequestId: string | undefined
if (process.env.NODE_ENV !== 'production') {
// The request IDs are only used in development mode to send debug
// information to the matching client (identified by the HTML request ID
// that was sent to the client with the HTML document) for the current
// request (identified by the request ID, as defined by the client).
requestId =
typeof headers[NEXT_REQUEST_ID_HEADER] === 'string'
? headers[NEXT_REQUEST_ID_HEADER]
: undefined
htmlRequestId =
typeof headers[NEXT_HTML_REQUEST_ID_HEADER] === 'string'
? headers[NEXT_HTML_REQUEST_ID_HEADER]
: undefined
}
return {
flightRouterState,
isPrefetchRequest,
isRuntimePrefetchRequest,
isRouteTreePrefetchRequest,
isHmrRefresh,
isRSCRequest,
nonce,
previouslyRevalidatedTags,
requestId,
htmlRequestId,
}
}
function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
const components = loaderTree[2]
const hasGlobalNotFound = !!components['global-not-found']
const notFoundTreeComponents: LoaderTree[2] = hasGlobalNotFound
? {
layout: components['global-not-found']!,
page: [() => null, 'next/dist/client/components/builtin/empty-stub'],
}
: {
page: components['not-found'],
}
return [
'',
{
children: [PAGE_SEGMENT_KEY, {}, notFoundTreeComponents],
},
// When global-not-found is present, skip layout from components
hasGlobalNotFound ? components : {},
]
}
/**
* Returns a function that parses the dynamic segment and return the associated value.
*/
function makeGetDynamicParamFromSegment(
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null
): GetDynamicParamFromSegment {
return function getDynamicParamFromSegment(
// [slug] / [[slug]] / [...slug]
segment: string
) {
const segmentParam = getSegmentParam(segment)
if (!segmentParam) {
return null
}
const segmentKey = segmentParam.paramName
const dynamicParamType = dynamicParamTypes[segmentParam.paramType]
return getDynamicParam(
interpolatedParams,
segmentKey,
dynamicParamType,
fallbackRouteParams
)
}
}
function NonIndex({
createElement,
pagePath,
statusCode,
isPossibleServerAction,
}: {
createElement: typeof ReactClient.createElement
pagePath: string
statusCode: number | undefined
isPossibleServerAction: boolean
}) {
const is404Page = pagePath === '/404'
const isInvalidStatusCode = typeof statusCode === 'number' && statusCode > 400
// Only render noindex for page request, skip for server actions
// TODO: is this correct if `isPossibleServerAction` is a false positive?
if (!isPossibleServerAction && (is404Page || isInvalidStatusCode)) {
return createElement('meta', {
name: 'robots',
content: 'noindex',
})
}
return null
}
/**
* This is used by server actions & client-side navigations to generate RSC data from a client-side request.
* This function is only called on "dynamic" requests (ie, there wasn't already a static response).
* It uses request headers (namely `next-router-state-tree`) to determine where to start rendering.
*/
async function generateDynamicRSCPayload(
ctx: AppRenderContext,
options?: {
actionResult?: ActionResult
skipPageRendering?: boolean
runtimePrefetchSentinel?: number
}
): Promise<RSCPayload> {
// Flight data that is going to be passed to the browser.
// Currently a single item array but in the future multiple patches might be combined in a single request.
// We initialize `flightData` to an empty string because the client router knows how to tolerate
// it (treating it as an MPA navigation). The only time this function wouldn't generate flight data
// is for server actions, if the server action handler instructs this function to skip it. When the server
// action reducer sees a falsy value, it'll simply resolve the action with no data.
let flightData: FlightData = ''
const {
componentMod: {
routeModule: {
userland: { loaderTree },
},
createElement,
createMetadataComponents,
Fragment,
},
getDynamicParamFromSegment,
query,
requestId,
flightRouterState,
workStore,
url,
} = ctx
const serveStreamingMetadata = !!ctx.renderOpts.serveStreamingMetadata
if (!options?.skipPageRendering) {
const preloadCallbacks: PreloadCallbacks = []
const { Viewport, Metadata, MetadataOutlet } = createMetadataComponents({
tree: loaderTree,
parsedQuery: query,
pathname: url.pathname,
metadataContext: createMetadataContext(ctx.renderOpts),
getDynamicParamFromSegment,
workStore,
serveStreamingMetadata,
})
flightData = (
await walkTreeWithFlightRouterState({
ctx,
loaderTreeToFilter: loaderTree,
parentParams: {},
flightRouterState,
// For flight, render metadata inside leaf page
rscHead: createElement(
Fragment,
{
key: flightDataPathHeadKey,
},
createElement(NonIndex, {
createElement,
pagePath: ctx.pagePath,
statusCode: ctx.res.statusCode,
isPossibleServerAction: ctx.isPossibleServerAction,
}),
createElement(Viewport, {
key: getFlightViewportKey(requestId),
}),
createElement(Metadata, {
key: getFlightMetadataKey(requestId),
})
),
injectedCSS: new Set(),
injectedJS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
preloadCallbacks,
MetadataOutlet,
})
).map((path) => path.slice(1)) // remove the '' (root) segment
}
const varyHeader = ctx.res.getHeader('vary')
const couldBeIntercepted =
typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL)
// If we have an action result, then this is a server action response.
// We can rely on this because `ActionResult` will always be a promise, even if
// the result is falsey.
if (options?.actionResult) {
return {
a: options.actionResult,
f: flightData,
b: ctx.sharedContext.buildId,
q: getRenderedSearch(query),
i: !!couldBeIntercepted,
}
}
// Otherwise, it's a regular RSC response.
const baseResponse = {
b: ctx.sharedContext.buildId,
f: flightData,
q: getRenderedSearch(query),
i: !!couldBeIntercepted,
S: workStore.isStaticGeneration,
}
// For runtime prefetches, we encode the stale time and isPartial flag in the response body
// rather than relying on response headers. Both of these values will be transformed
// by a transform stream before being sent to the client.
if (options?.runtimePrefetchSentinel !== undefined) {
return {
...baseResponse,
rp: [options.runtimePrefetchSentinel] as any,
}
}
return baseResponse
}
function createErrorContext(
ctx: AppRenderContext,
renderSource: RequestErrorContext['renderSource']
): RequestErrorContext {
return {
routerKind: 'App Router',
routePath: ctx.pagePath,
// TODO: is this correct if `isPossibleServerAction` is a false positive?
routeType: ctx.isPossibleServerAction ? 'action' : 'render',
renderSource,
revalidateReason: getRevalidateReason(ctx.workStore),
}
}
/**
* Produces a RenderResult containing the Flight data for the given request. See
* `generateDynamicRSCPayload` for information on the contents of the render result.
*/
async function generateDynamicFlightRenderResult(
req: BaseNextRequest,
ctx: AppRenderContext,
requestStore: RequestStore,
options?: {
actionResult: ActionResult
skipPageRendering: boolean
componentTree?: CacheNodeSeedData
preloadCallbacks?: PreloadCallbacks
temporaryReferences?: WeakMap<any, string>
waitUntil?: Promise<unknown>
}
): Promise<RenderResult> {
const {
componentMod: { renderToReadableStream },
htmlRequestId,
renderOpts,
requestId,
workStore,
} = ctx
const {
dev = false,
onInstrumentationRequestError,
setReactDebugChannel,
nextExport = false,
} = renderOpts
function onFlightDataRenderError(err: DigestedError, silenceLog: boolean) {
return onInstrumentationRequestError?.(
err,
req,
createErrorContext(ctx, 'react-server-components-payload'),
silenceLog
)
}
const onError = createReactServerErrorHandler(
dev,
nextExport,
workStore.reactServerErrorsByDigest,
onFlightDataRenderError
)
const debugChannel = setReactDebugChannel && createDebugChannel()
if (debugChannel) {
setReactDebugChannel(debugChannel.clientSide, htmlRequestId, requestId)
}
const { clientModules } = getClientReferenceManifest()
// For app dir, use the bundled version of Flight server renderer (renderToReadableStream)
// which contains the subset React.
const rscPayload = await workUnitAsyncStorage.run(
requestStore,
generateDynamicRSCPayload,
ctx,
options
)
const flightReadableStream = workUnitAsyncStorage.run(
requestStore,
renderToReadableStream,
rscPayload,
clientModules,
{
onError,
temporaryReferences: options?.temporaryReferences,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
return new FlightRenderResult(
flightReadableStream,
{ fetchMetrics: workStore.fetchMetrics },
options?.waitUntil
)
}
type RenderToReadableStreamServerOptions = NonNullable<
Parameters<
(typeof import('react-server-dom-webpack/server.node'))['renderToReadableStream']
>[2]
>
async function stagedRenderToReadableStreamWithoutCachesInDev(
ctx: AppRenderContext,
requestStore: RequestStore,
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
options: Omit<RenderToReadableStreamServerOptions, 'environmentName'>
) {
const {
componentMod: { renderToReadableStream },
} = ctx
// We're rendering while bypassing caches,
// so we have no hope of showing a useful runtime stage.
// But we still want things like `params` to show up in devtools correctly,
// which relies on mechanisms we've set up for staged rendering,
// so we do a 2-task version (Static -> Dynamic) instead.
// We aren't doing any validation in this kind of render so we say there
// is not runtime prefetch regardless of whether there is or not
const hasRuntimePrefetch = false
// We aren't filling caches so we don't need to abort this render, it'll
// stream in a single pass
const abortSignal = null
const stageController = new StagedRenderingController(
abortSignal,
hasRuntimePrefetch
)
const environmentName = () => {
const currentStage = stageController.currentStage
switch (currentStage) {
case RenderStage.Before:
case RenderStage.Static:
return 'Prerender'
case RenderStage.Runtime:
case RenderStage.Dynamic:
case RenderStage.Abandoned:
return 'Server'
default:
currentStage satisfies never
throw new InvariantError(`Invalid render stage: ${currentStage}`)
}
}
requestStore.stagedRendering = stageController
requestStore.asyncApiPromises = createAsyncApiPromisesInDev(
stageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
const { clientModules } = getClientReferenceManifest()
const rscPayload = await getPayload(requestStore)
return await workUnitAsyncStorage.run(
requestStore,
scheduleInSequentialTasks,
() => {
stageController.advanceStage(RenderStage.Static)
return renderToReadableStream(rscPayload, clientModules, {
...options,
environmentName,
})
},
() => {
stageController.advanceStage(RenderStage.Dynamic)
}
)
}
/**
* Fork of `generateDynamicFlightRenderResult` that renders using `renderWithRestartOnCacheMissInDev`
* to ensure correct separation of environments Prerender/Server (for use in Cache Components)
*/
async function generateDynamicFlightRenderResultWithStagesInDev(
req: BaseNextRequest,
ctx: AppRenderContext,
initialRequestStore: RequestStore,
createRequestStore: (() => RequestStore) | undefined,
devFallbackParams: OpaqueFallbackRouteParams | null
): Promise<RenderResult> {
const {
htmlRequestId,
renderOpts,
requestId,
workStore,
componentMod: { createElement },
url,
} = ctx
const {
dev = false,
onInstrumentationRequestError,
setReactDebugChannel,
setCacheStatus,
nextExport = false,
} = renderOpts
function onFlightDataRenderError(err: DigestedError, silenceLog: boolean) {
return onInstrumentationRequestError?.(
err,
req,
createErrorContext(ctx, 'react-server-components-payload'),
silenceLog
)
}
const onError = createReactServerErrorHandler(
dev,
nextExport,
workStore.reactServerErrorsByDigest,
onFlightDataRenderError
)
// We only validate RSC requests if it is for HMR refreshes since we know we
// will render all the layouts necessary to perform the validation.
const shouldValidate =
!isBypassingCachesInDev(renderOpts, initialRequestStore) &&
initialRequestStore.isHmrRefresh === true
const getPayload = async (requestStore: RequestStore) => {
const payload: RSCPayload &
RSCPayloadDevProperties &
RSCInitialPayloadPartialDev = await workUnitAsyncStorage.run(
requestStore,
generateDynamicRSCPayload,
ctx,
undefined
)
if (isBypassingCachesInDev(renderOpts, requestStore)) {
// Mark the RSC payload to indicate that caches were bypassed in dev.
// This lets the client know not to cache anything based on this render.
payload._bypassCachesInDev = createElement(WarnForBypassCachesInDev, {
route: workStore.route,
})
} else if (shouldValidate) {
// If this payload will be used for validation, it needs to contain the
// canonical URL. Without it we'd get an error.
payload.c = prepareInitialCanonicalUrl(url)
}
return payload
}
let debugChannel: DebugChannelPair | undefined
let stream: ReadableStream<Uint8Array>
if (
// We only do this flow if we can safely recreate the store from scratch
// (which is not the case for renders after an action)
createRequestStore &&
// We only do this flow if we're not bypassing caches in dev using
// "disable cache" in devtools or a hard refresh (cache-control: "no-store")
!isBypassingCachesInDev(renderOpts, initialRequestStore)
) {
// Before we kick off the render, we set the cache status back to it's initial state
// in case a previous render bypassed the cache.
if (setCacheStatus) {
setCacheStatus('ready', htmlRequestId)
}
const {
stream: serverStream,
accumulatedChunksPromise,
staticInterruptReason,
runtimeInterruptReason,
staticStageEndTime,
runtimeStageEndTime,
debugChannel: returnedDebugChannel,
requestStore: finalRequestStore,
} = await renderWithRestartOnCacheMissInDev(
ctx,
initialRequestStore,
createRequestStore,
getPayload,
onError
)
if (shouldValidate) {
let validationDebugChannelClient: Readable | undefined = undefined
if (returnedDebugChannel) {
const [t1, t2] = returnedDebugChannel.clientSide.readable.tee()
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = nodeStreamFromReadableStream(t2)
}
consoleAsyncStorage.run(
{ dim: true },
spawnStaticShellValidationInDev,
accumulatedChunksPromise,
staticInterruptReason,
runtimeInterruptReason,
staticStageEndTime,
runtimeStageEndTime,
ctx,
finalRequestStore,
devFallbackParams,
validationDebugChannelClient
)
}
debugChannel = returnedDebugChannel
stream = serverStream
} else {
// We're either bypassing caches or we can't restart the render.
// Do a dynamic render, but with (basic) environment labels.
// Set cache status to bypass when specifically bypassing caches in dev
if (setCacheStatus) {
setCacheStatus('bypass', htmlRequestId)
}
debugChannel = setReactDebugChannel && createDebugChannel()
stream = await stagedRenderToReadableStreamWithoutCachesInDev(
ctx,
initialRequestStore,
getPayload,
{
onError: onError,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
}
if (debugChannel && setReactDebugChannel) {
setReactDebugChannel(debugChannel.clientSide, htmlRequestId, requestId)
}
return new FlightRenderResult(stream, {
fetchMetrics: workStore.fetchMetrics,
})
}
async function generateRuntimePrefetchResult(
req: BaseNextRequest,
ctx: AppRenderContext,
requestStore: RequestStore
): Promise<RenderResult> {
const { workStore, renderOpts } = ctx
const { nextExport = false, onInstrumentationRequestError } = renderOpts
function onFlightDataRenderError(err: DigestedError, silenceLog: boolean) {
return onInstrumentationRequestError?.(
err,
req,
// TODO(runtime-ppr): should we use a different value?
createErrorContext(ctx, 'react-server-components-payload'),
silenceLog
)
}
const onError = createReactServerErrorHandler(
false,
nextExport,
workStore.reactServerErrorsByDigest,
onFlightDataRenderError
)
const metadata: AppPageRenderResultMetadata = {}
// Generate a random sentinel that will be used as a placeholder in the payload
// and later replaced by the transform stream
const runtimePrefetchSentinel = Math.floor(
Math.random() * Number.MAX_SAFE_INTEGER
)
const generatePayload = () =>
generateDynamicRSCPayload(ctx, { runtimePrefetchSentinel })
const {
componentMod: {
routeModule: {
userland: { loaderTree },
},
},
getDynamicParamFromSegment,
} = ctx
const rootParams = getRootParams(loaderTree, getDynamicParamFromSegment)
// We need to share caches between the prospective prerender and the final prerender,
// but we're not going to persist this anywhere.
const prerenderResumeDataCache = createPrerenderResumeDataCache()
// We're not resuming an existing render.
const renderResumeDataCache = null
await prospectiveRuntimeServerPrerender(
ctx,
generatePayload,
prerenderResumeDataCache,
renderResumeDataCache,
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode
)
const response = await finalRuntimeServerPrerender(
ctx,
generatePayload,
prerenderResumeDataCache,
renderResumeDataCache,
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode,
onError,
runtimePrefetchSentinel
)
applyMetadataFromPrerenderResult(response, metadata, workStore)
metadata.fetchMetrics = ctx.workStore.fetchMetrics
return new FlightRenderResult(response.result.prelude, metadata)
}
async function prospectiveRuntimeServerPrerender(
ctx: AppRenderContext,
getPayload: () => any,
prerenderResumeDataCache: PrerenderResumeDataCache | null,
renderResumeDataCache: RenderResumeDataCache | null,
rootParams: Params,
headers: PrerenderStoreModernRuntime['headers'],
cookies: PrerenderStoreModernRuntime['cookies'],
draftMode: PrerenderStoreModernRuntime['draftMode']
) {
const { implicitTags, renderOpts, workStore } = ctx
const { ComponentMod } = renderOpts
// Prerender controller represents the lifetime of the prerender.
// It will be aborted when a Task is complete or a synchronously aborting
// API is called. Notably during cache-filling renders this does not actually
// terminate the render itself which will continue until all caches are filled
const initialServerPrerenderController = new AbortController()
// This controller represents the lifetime of the React render call. Notably
// during the cache-filling render it is different from the prerender controller
// because we don't want to end the react render until all caches are filled.
const initialServerRenderController = new AbortController()
// The cacheSignal helps us track whether caches are still filling or we are ready
// to cut the render off.
const cacheSignal = new CacheSignal()
const initialServerPrerenderStore: PrerenderStoreModernRuntime = {
type: 'prerender-runtime',
phase: 'render',
rootParams,
implicitTags,
renderSignal: initialServerRenderController.signal,
controller: initialServerPrerenderController,
// During the initial prerender we need to track all cache reads to ensure
// we render long enough to fill every cache it is possible to visit during
// the final prerender.
cacheSignal,
// We only need to track dynamic accesses during the final prerender.
dynamicTracking: null,
// Runtime prefetches are never cached server-side, only client-side,
// so we set `expire` and `revalidate` to their minimum values just in case.
revalidate: 1,
expire: 0,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
renderResumeDataCache,
prerenderResumeDataCache,
hmrRefreshHash: undefined,
// We only need task sequencing in the final prerender.
runtimeStagePromise: null,
// These are not present in regular prerenders, but allowed in a runtime prerender.
headers,
cookies,
draftMode,
}
const { clientModules } = getClientReferenceManifest()
// We're not going to use the result of this render because the only time it could be used
// is if it completes in a microtask and that's likely very rare for any non-trivial app
const initialServerPayload = await workUnitAsyncStorage.run(
initialServerPrerenderStore,
getPayload
)
const pendingInitialServerResult = workUnitAsyncStorage.run(
initialServerPrerenderStore,
ComponentMod.prerender,
initialServerPayload,
clientModules,
{
filterStackFrame,
onError: (err) => {
const digest = getDigestForWellKnownError(err)
if (digest) {
return digest
}
if (initialServerPrerenderController.signal.aborted) {
// The render aborted before this error was handled which indicates
// the error is caused by unfinished components within the render
return
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
printDebugThrownValueForProspectiveRender(
err,
workStore.route,
Phase.ProspectiveRender
)
}
},
// We don't want to stop rendering until the cacheSignal is complete so we pass
// a different signal to this render call than is used by dynamic APIs to signify
// transitioning out of the prerender environment
signal: initialServerRenderController.signal,
}
)
// Wait for all caches to be finished filling and for async imports to resolve
trackPendingModules(cacheSignal)
await cacheSignal.cacheReady()
initialServerRenderController.abort()
initialServerPrerenderController.abort()
// We don't need to continue the prerender process if we already
// detected invalid dynamic usage in the initial prerender phase.
if (workStore.invalidDynamicUsageError) {
throw workStore.invalidDynamicUsageError
}
try {
return await createReactServerPrerenderResult(pendingInitialServerResult)
} catch (err) {
if (
initialServerRenderController.signal.aborted ||
initialServerPrerenderController.signal.aborted
) {
// These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(
err,
workStore.route,
Phase.ProspectiveRender
)
}
return null
}
}
/**
* Updates the runtime prefetch metadata in the RSC payload as it streams:
* "rp":[<sentinel>] -> "rp":[<isPartial>,<staleTime>]
*
* We use a transform stream to do this to avoid needing to trigger an additional render.
* A random sentinel number guarantees no collision with user data.
*/
function createRuntimePrefetchTransformStream(
sentinel: number,
isPartial: boolean,
staleTime: number
): TransformStream<Uint8Array, Uint8Array> {
const encoder = new TextEncoder()
// Search for: [<sentinel>]
// Replace with: [<isPartial>,<staleTime>]
const search = encoder.encode(`[${sentinel}]`)
const first = search[0]
const replace = encoder.encode(`[${isPartial},${staleTime}]`)
const searchLen = search.length
let currentChunk: Uint8Array | null = null
let found = false
function processChunk(
controller: TransformStreamDefaultController<Uint8Array>,
nextChunk: null | Uint8Array
) {
if (found) {
if (nextChunk) {
controller.enqueue(nextChunk)
}
return
}
if (currentChunk) {
// We can't search past the index that can contain a full match
let exclusiveUpperBound = currentChunk.length - (searchLen - 1)
if (nextChunk) {
// If we have any overflow bytes we can search up to the chunk's final byte
exclusiveUpperBound += Math.min(nextChunk.length, searchLen - 1)
}
if (exclusiveUpperBound < 1) {
// we can't match the current chunk.
controller.enqueue(currentChunk)
currentChunk = nextChunk // advance so we don't process this chunk again
return
}
let currentIndex = currentChunk.indexOf(first)
// check the current candidate match if it is within the bounds of our search space for the currentChunk
candidateLoop: while (
-1 < currentIndex &&
currentIndex < exclusiveUpperBound
) {
// We already know index 0 matches because we used indexOf to find the candidateIndex so we start at index 1
let matchIndex = 1
while (matchIndex < searchLen) {
const candidateIndex = currentIndex + matchIndex
const candidateValue =
candidateIndex < currentChunk.length
? currentChunk[candidateIndex]
: // if we ever hit this condition it is because there is a nextChunk we can read from
nextChunk![candidateIndex - currentChunk.length]
if (candidateValue !== search[matchIndex]) {
// No match, reset and continue the search from the next position
currentIndex = currentChunk.indexOf(first, currentIndex + 1)
continue candidateLoop
}
matchIndex++
}
// We found a complete match. currentIndex is our starting point to replace the value.
found = true
// enqueue everything up to the match
controller.enqueue(currentChunk.subarray(0, currentIndex))
// enqueue the replacement value
controller.enqueue(replace)
// If there are bytes in the currentChunk after the match enqueue them
if (currentIndex + searchLen < currentChunk.length) {
controller.enqueue(currentChunk.slice(currentIndex + searchLen))
}
// If we have a next chunk we enqueue it now
if (nextChunk) {
// if replacement spills over to the next chunk we first exclude the replaced bytes
const overflowBytes = currentIndex + searchLen - currentChunk.length
const truncatedChunk =
overflowBytes > 0 ? nextChunk!.subarray(overflowBytes) : nextChunk
controller.enqueue(truncatedChunk)
}
// We are now in found mode and don't need to track currentChunk anymore
currentChunk = null
return
}
// No match found in this chunk, emit it and wait for the next one
controller.enqueue(currentChunk)
}
// Advance to the next chunk
currentChunk = nextChunk
}
return new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
processChunk(controller, chunk)
},
flush(controller) {
processChunk(controller, null)
},
})
}
async function finalRuntimeServerPrerender(
ctx: AppRenderContext,
getPayload: () => any,
prerenderResumeDataCache: PrerenderResumeDataCache | null,
renderResumeDataCache: RenderResumeDataCache | null,
rootParams: Params,
headers: PrerenderStoreModernRuntime['headers'],
cookies: PrerenderStoreModernRuntime['cookies'],
draftMode: PrerenderStoreModernRuntime['draftMode'],
onError: (err: unknown) => string | undefined,
runtimePrefetchSentinel: number
) {
const { implicitTags, renderOpts } = ctx
const { ComponentMod, experimental, isDebugDynamicAccesses } = renderOpts
const selectStaleTime = createSelectStaleTime(experimental)
let serverIsDynamic = false
const finalServerController = new AbortController()
const serverDynamicTracking = createDynamicTrackingState(
isDebugDynamicAccesses
)
const { promise: runtimeStagePromise, resolve: resolveBlockedRuntimeAPIs } =
createPromiseWithResolvers<void>()
const finalServerPrerenderStore: PrerenderStoreModernRuntime = {
type: 'prerender-runtime',
phase: 'render',
rootParams,
implicitTags,
renderSignal: finalServerController.signal,
controller: finalServerController,
// All caches we could read must already be filled so no tracking is necessary
cacheSignal: null,
dynamicTracking: serverDynamicTracking,
// Runtime prefetches are never cached server-side, only client-side,
// so we set `expire` and `revalidate` to their minimum values just in case.
revalidate: 1,
expire: 0,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
// Used to separate the "Static" stage from the "Runtime" stage.
runtimeStagePromise,
// These are not present in regular prerenders, but allowed in a runtime prerender.
headers,
cookies,
draftMode,
}
const { clientModules } = getClientReferenceManifest()
const finalRSCPayload = await workUnitAsyncStorage.run(
finalServerPrerenderStore,
getPayload
)
let prerenderIsPending = true
const result = await prerenderAndAbortInSequentialTasksWithStages(
async () => {
// Static stage
const prerenderResult = await workUnitAsyncStorage.run(
finalServerPrerenderStore,
ComponentMod.prerender,
finalRSCPayload,
clientModules,
{
filterStackFrame,
onError,
signal: finalServerController.signal,
}
)
prerenderIsPending = false
return prerenderResult
},
() => {
// Advance to the runtime stage.
//
// We make runtime APIs hang during the first task (above), and unblock them in the following task (here).
// This makes sure that, at this point, we'll have finished all the static parts (what we'd prerender statically).
// We know that they don't contain any incorrect sync IO, because that'd have caused a build error.
// After we unblock Runtime APIs, if we encounter sync IO (e.g. `await cookies(); Date.now()`),
// we'll abort, but we'll produce at least as much output as a static prerender would.
resolveBlockedRuntimeAPIs()
},
() => {
// Abort.
if (finalServerController.signal.aborted) {
// If the server controller is already aborted we must have called something
// that required aborting the prerender synchronously such as with new Date()
serverIsDynamic = true
return
}
if (prerenderIsPending) {
// If prerenderIsPending then we have blocked for longer than a Task and we assume
// there is something unfinished.
serverIsDynamic = true
}
finalServerController.abort()
}
)
// Update the RSC payload stream to replace the sentinel with actual values.
// React has already serialized the payload with the sentinel, so we need to transform the stream.
const collectedStale = selectStaleTime(finalServerPrerenderStore.stale)
result.prelude = result.prelude.pipeThrough(
createRuntimePrefetchTransformStream(
runtimePrefetchSentinel,
serverIsDynamic,
collectedStale
)
)
return {
result,
// TODO(runtime-ppr): do we need to produce a digest map here?
// digestErrorsMap: ...,
dynamicAccess: serverDynamicTracking,
isPartial: serverIsDynamic,
collectedRevalidate: finalServerPrerenderStore.revalidate,
collectedExpire: finalServerPrerenderStore.expire,
collectedStale,
collectedTags: finalServerPrerenderStore.tags,
}
}
/**
* Crawlers will inadvertently think the canonicalUrl in the RSC payload should be crawled
* when our intention is to just seed the router state with the current URL.
* This function splits up the pathname so that we can later join it on
* when we're ready to consume the path.
*/
function prepareInitialCanonicalUrl(url: RequestStore['url']) {
return (url.pathname + url.search).split('/')
}
function getRenderedSearch(query: NextParsedUrlQuery): string {
// Inlined implementation of querystring.encode, which is not available in
// the Edge runtime.
const pairs = []
for (const key in query) {
const value = query[key]
if (value == null) continue
if (Array.isArray(value)) {
for (const v of value) {
pairs.push(
`${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`
)
}
} else {
pairs.push(
`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
)
}
}
// The result should match the format of a web URL's `search` property, since
// this is the format that's stored in the App Router state.
// TODO: We're a bit inconsistent about this. The x-nextjs-rewritten-query
// header omits the leading question mark. Should refactor to always do
// that instead.
if (pairs.length === 0) {
// If the search string is empty, return an empty string.
return ''
}
// Prepend '?' to the search params string.
return '?' + pairs.join('&')
}
// This is the data necessary to render <AppRouter /> when no SSR errors are encountered
async function getRSCPayload(
tree: LoaderTree,
ctx: AppRenderContext,
is404: boolean
): Promise<InitialRSCPayload & { P: ReactNode }> {
const injectedCSS = new Set<string>()
const injectedJS = new Set<string>()
const injectedFontPreloadTags = new Set<string>()
let missingSlots: Set<string> | undefined
// We only track missing parallel slots in development
if (process.env.NODE_ENV === 'development') {
missingSlots = new Set<string>()
}
const {
getDynamicParamFromSegment,
query,
appUsingSizeAdjustment,
componentMod: { createMetadataComponents, createElement, Fragment },
url,
workStore,
} = ctx
const initialTree = createFlightRouterStateFromLoaderTree(
tree,
getDynamicParamFromSegment,
query
)
const serveStreamingMetadata = !!ctx.renderOpts.serveStreamingMetadata
const hasGlobalNotFound = !!tree[2]['global-not-found']
const { Viewport, Metadata, MetadataOutlet } = createMetadataComponents({
tree,
// When it's using global-not-found, metadata errorType is undefined, which will retrieve the
// metadata from the page.
// When it's using not-found, metadata errorType is 'not-found', which will retrieve the
// metadata from the not-found.js boundary.
// TODO: remove this condition and keep it undefined when global-not-found is stabilized.
errorType: is404 && !hasGlobalNotFound ? 'not-found' : undefined,
parsedQuery: query,
pathname: url.pathname,
metadataContext: createMetadataContext(ctx.renderOpts),
getDynamicParamFromSegment,
workStore,
serveStreamingMetadata,
})
const preloadCallbacks: PreloadCallbacks = []
const seedData = await createComponentTree({
ctx,
loaderTree: tree,
parentParams: {},
injectedCSS,
injectedJS,
injectedFontPreloadTags,
rootLayoutIncluded: false,
missingSlots,
preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts,
MetadataOutlet,
})
// When the `vary` response header is present with `Next-URL`, that means there's a chance
// it could respond differently if there's an interception route. We provide this information
// to `AppRouter` so that it can properly seed the prefetch cache with a prefix, if needed.
const varyHeader = ctx.res.getHeader('vary')
const couldBeIntercepted =
typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL)
const initialHead = createElement(
Fragment,
{
key: flightDataPathHeadKey,
},
createElement(NonIndex, {
createElement,
pagePath: ctx.pagePath,
statusCode: ctx.res.statusCode,
isPossibleServerAction: ctx.isPossibleServerAction,
}),
createElement(Viewport, null),
createElement(Metadata, null),
appUsingSizeAdjustment
? createElement('meta', {
name: 'next-size-adjust',
content: '',
})
: null
)
const { GlobalError, styles: globalErrorStyles } = await getGlobalErrorStyles(
tree,
ctx
)
// Assume the head we're rendering contains only partial data if PPR is
// enabled and this is a statically generated response. This is used by the
// client Segment Cache after a prefetch to determine if it can skip the
// second request to fill in the dynamic data.
//
// See similar comment in create-component-tree.tsx for more context.
const isPossiblyPartialHead =
workStore.isStaticGeneration &&
ctx.renderOpts.experimental.isRoutePPREnabled === true
return {
// See the comment above the `Preloads` component (below) for why this is part of the payload
P: createElement(Preloads, {
preloadCallbacks: preloadCallbacks,
}),
b: ctx.sharedContext.buildId,
c: prepareInitialCanonicalUrl(url),
q: getRenderedSearch(query),
i: !!couldBeIntercepted,
f: [
[
initialTree,
seedData,
initialHead,
isPossiblyPartialHead,
] as FlightDataPath,
],
m: missingSlots,
G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration,
}
}
/**
* Preload calls (such as `ReactDOM.preloadStyle` and `ReactDOM.preloadFont`) need to be called during rendering
* in order to create the appropriate preload tags in the DOM, otherwise they're a no-op. Since we invoke
* renderToReadableStream with a function that returns component props rather than a component itself, we use
* this component to "render " the preload calls.
*/
function Preloads({ preloadCallbacks }: { preloadCallbacks: Function[] }) {
preloadCallbacks.forEach((preloadFn) => preloadFn())
return null
}
// This is the data necessary to render <AppRouter /> when an error state is triggered
async function getErrorRSCPayload(
tree: LoaderTree,
ctx: AppRenderContext,
ssrError: unknown,
errorType: MetadataErrorType | 'redirect' | undefined
) {
const {
getDynamicParamFromSegment,
query,
componentMod: { createMetadataComponents, createElement, Fragment },
url,
workStore,
} = ctx
const serveStreamingMetadata = !!ctx.renderOpts.serveStreamingMetadata
const { Viewport, Metadata } = createMetadataComponents({
tree,
parsedQuery: query,
pathname: url.pathname,
metadataContext: createMetadataContext(ctx.renderOpts),
errorType,
getDynamicParamFromSegment,
workStore,
serveStreamingMetadata: serveStreamingMetadata,
})
const initialHead = createElement(
Fragment,
{
key: flightDataPathHeadKey,
},
createElement(NonIndex, {
createElement,
pagePath: ctx.pagePath,
statusCode: ctx.res.statusCode,
isPossibleServerAction: ctx.isPossibleServerAction,
}),
createElement(Viewport, null),
process.env.NODE_ENV === 'development' &&
createElement('meta', {
name: 'next-error',
content: 'not-found',
}),
createElement(Metadata, null)
)
const initialTree = createFlightRouterStateFromLoaderTree(
tree,
getDynamicParamFromSegment,
query
)
let err: Error | undefined = undefined
if (ssrError) {
err = isError(ssrError) ? ssrError : new Error(ssrError + '')
}
// For metadata notFound error there's no global not found boundary on top
// so we create a not found page with AppRouter
const seedData: CacheNodeSeedData = [
createElement(
'html',
{
id: '__next_error__',
},
createElement('head', null),
createElement(
'body',
null,
process.env.NODE_ENV !== 'production' && err
? createElement('template', {
'data-next-error-message': err.message,
'data-next-error-digest': 'digest' in err ? err.digest : '',
'data-next-error-stack': err.stack,
})
: null
)
),
{},
null,
false,
false, // We don't currently support runtime prefetching for error pages.
]
const { GlobalError, styles: globalErrorStyles } = await getGlobalErrorStyles(
tree,
ctx
)
const isPossiblyPartialHead =
workStore.isStaticGeneration &&
ctx.renderOpts.experimental.isRoutePPREnabled === true
return {
b: ctx.sharedContext.buildId,
c: prepareInitialCanonicalUrl(url),
q: getRenderedSearch(query),
m: undefined,
i: false,
f: [
[
initialTree,
seedData,
initialHead,
isPossiblyPartialHead,
] as FlightDataPath,
],
G: [GlobalError, globalErrorStyles],
S: workStore.isStaticGeneration,
} satisfies InitialRSCPayload
}
// This component must run in an SSR context. It will render the RSC root component
function App<T>({
reactServerStream,
reactDebugStream,
debugEndTime,
preinitScripts,
ServerInsertedHTMLProvider,
nonce,
images,
}: {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
reactServerStream: Readable | BinaryStreamOf<T>
reactDebugStream: Readable | ReadableStream<Uint8Array> | undefined
debugEndTime: number | undefined
preinitScripts: () => void
ServerInsertedHTMLProvider: ComponentType<{
children: JSX.Element
}>
images: RenderOpts['images']
nonce?: string
}): JSX.Element {
preinitScripts()
const response = ReactClient.use(
getFlightStream<InitialRSCPayload>(
reactServerStream,
reactDebugStream,
debugEndTime,
nonce
)
)
const initialState = createInitialRouterState({
// This is not used during hydration, so we don't have to pass a
// real timestamp.
navigatedAt: -1,
initialFlightData: response.f,
initialCanonicalUrlParts: response.c,
initialRenderedSearch: response.q,
// location is not initialized in the SSR render
// it's set to window.location during hydration
location: null,
})
const actionQueue = createMutableActionQueue(initialState, null)
const { HeadManagerContext } =
require('../../shared/lib/head-manager-context.shared-runtime') as typeof import('../../shared/lib/head-manager-context.shared-runtime')
return (
<HeadManagerContext.Provider
value={{
appDir: true,
nonce,
}}
>
<ImageConfigContext.Provider value={images ?? imageConfigDefault}>
<ServerInsertedHTMLProvider>
<AppRouter actionQueue={actionQueue} globalErrorState={response.G} />
</ServerInsertedHTMLProvider>
</ImageConfigContext.Provider>
</HeadManagerContext.Provider>
)
/* eslint-enable @next/internal/no-ambiguous-jsx -- React Client */
}
// @TODO our error stream should be probably just use the same root component. But it was previously
// different I don't want to figure out if that is meaningful at this time so just keeping the behavior
// consistent for now.
function ErrorApp<T>({
reactServerStream,
preinitScripts,
ServerInsertedHTMLProvider,
nonce,
images,
}: {
reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void
ServerInsertedHTMLProvider: ComponentType<{
children: JSX.Element
}>
nonce?: string
images: RenderOpts['images']
}): JSX.Element {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
preinitScripts()
const response = ReactClient.use(
getFlightStream<InitialRSCPayload>(
reactServerStream,
undefined,
undefined,
nonce
)
)
const initialState = createInitialRouterState({
// This is not used during hydration, so we don't have to pass a
// real timestamp.
navigatedAt: -1,
initialFlightData: response.f,
initialCanonicalUrlParts: response.c,
initialRenderedSearch: response.q,
// location is not initialized in the SSR render
// it's set to window.location during hydration
location: null,
})
const actionQueue = createMutableActionQueue(initialState, null)
return (
<ImageConfigContext.Provider value={images ?? imageConfigDefault}>
<ServerInsertedHTMLProvider>
<AppRouter actionQueue={actionQueue} globalErrorState={response.G} />
</ServerInsertedHTMLProvider>
</ImageConfigContext.Provider>
)
/* eslint-enable @next/internal/no-ambiguous-jsx -- React Client */
}
// We use a trick with TS Generics to branch streams with a type so we can
// consume the parsed value of a Readable Stream if it was constructed with a
// certain object shape. The generic type is not used directly in the type so it
// requires a disabling of the eslint rule disallowing unused vars
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type BinaryStreamOf<T> = ReadableStream<Uint8Array>
async function renderToHTMLOrFlightImpl(
req: BaseNextRequest,
res: BaseNextResponse,
url: ReturnType<typeof parseRelativeUrl>,
pagePath: string,
query: NextParsedUrlQuery,
renderOpts: RenderOpts,
workStore: WorkStore,
parsedRequestHeaders: ParsedRequestHeaders,
postponedState: PostponedState | null,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
sharedContext: AppSharedContext,
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null
) {
const isNotFoundPath = pagePath === '/404'
if (isNotFoundPath) {
res.statusCode = 404
}
// A unique request timestamp used by development to ensure that it's
// consistent and won't change during this request. This is important to
// avoid that resources can be deduped by React Float if the same resource is
// rendered or preloaded multiple times: `<link href="a.css?v={Date.now()}"/>`.
const requestTimestamp = Date.now()
const {
ComponentMod,
nextFontManifest,
serverActions,
assetPrefix = '',
enableTainting,
cacheComponents,
} = renderOpts
// We need to expose the bundled `require` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
if (ComponentMod.__next_app__) {
const instrumented = wrapClientComponentLoader(ComponentMod)
// When we are prerendering if there is a cacheSignal for tracking
// cache reads we track calls to `loadChunk` and `require`. This allows us
// to treat chunk/module loading with similar semantics as cache reads to avoid
// module loading from causing a prerender to abort too early.
const shouldTrackModuleLoading = () => {
if (!cacheComponents) {
return false
}
if (renderOpts.dev) {
return true
}
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore) {
return false
}
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'cache':
case 'private-cache':
return true
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
return false
default:
workUnitStore satisfies never
}
}
const __next_require__: typeof instrumented.require = (...args) => {
const exportsOrPromise = instrumented.require(...args)
if (shouldTrackModuleLoading()) {
// requiring an async module returns a promise.
trackPendingImport(exportsOrPromise)
}
return exportsOrPromise
}
// @ts-expect-error
globalThis.__next_require__ = __next_require__
const __next_chunk_load__: typeof instrumented.loadChunk = (...args) => {
const loadingChunk = instrumented.loadChunk(...args)
if (shouldTrackModuleLoading()) {
trackPendingChunkLoad(loadingChunk)
}
return loadingChunk
}
// @ts-expect-error
globalThis.__next_chunk_load__ = __next_chunk_load__
}
if (
process.env.NODE_ENV === 'development' &&
renderOpts.setIsrStatus &&
!cacheComponents
) {
// Reset the ISR status at start of request.
const { pathname } = new URL(req.url || '/', 'http://n')
renderOpts.setIsrStatus(
pathname,
// Only pages using the Node runtime can use ISR, Edge is always dynamic.
process.env.NEXT_RUNTIME === 'edge' ? false : undefined
)
}
if (
// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextRequest(req)
) {
res.onClose(() => {
// We stop tracking fetch metrics when the response closes, since we
// report them at that time.
workStore.shouldTrackFetchMetrics = false
})
req.originalRequest.on('end', () => {
if ('performance' in globalThis) {
const metrics = getClientComponentLoaderMetrics({ reset: true })
if (metrics) {
getTracer()
.startSpan(NextNodeServerSpan.clientComponentLoading, {
startTime: metrics.clientComponentLoadStart,
attributes: {
'next.clientComponentLoadCount':
metrics.clientComponentLoadCount,
'next.span_type': NextNodeServerSpan.clientComponentLoading,
},
})
.end(
metrics.clientComponentLoadStart +
metrics.clientComponentLoadTimes
)
}
}
})
}
const metadata: AppPageRenderResultMetadata = {
statusCode: isNotFoundPath ? 404 : undefined,
}
const appUsingSizeAdjustment = !!nextFontManifest?.appUsingSizeAdjust
ComponentMod.patchFetch()
// Pull out the hooks/references from the component.
const {
routeModule: {
userland: { loaderTree },
},
taintObjectReference,
} = ComponentMod
if (enableTainting) {
taintObjectReference(
'Do not pass process.env to Client Components since it will leak sensitive data',
process.env
)
}
workStore.fetchMetrics = []
metadata.fetchMetrics = workStore.fetchMetrics
// don't modify original query object
query = { ...query }
stripInternalQueries(query)
const { isStaticGeneration } = workStore
let requestId: string
let htmlRequestId: string
const {
flightRouterState,
isPrefetchRequest,
isRuntimePrefetchRequest,
isRSCRequest,
isHmrRefresh,
nonce,
} = parsedRequestHeaders
if (parsedRequestHeaders.requestId) {
// If the client has provided a request ID (in development mode), we use it.
requestId = parsedRequestHeaders.requestId
} else {
// Otherwise we generate a new request ID.
if (isStaticGeneration) {
requestId = Buffer.from(
await crypto.subtle.digest('SHA-1', Buffer.from(req.url))
).toString('hex')
} else if (process.env.NEXT_RUNTIME === 'edge') {
requestId = crypto.randomUUID()
} else {
requestId = (
require('next/dist/compiled/nanoid') as typeof import('next/dist/compiled/nanoid')
).nanoid()
}
}
// If the client has provided an HTML request ID, we use it to associate the
// request with the HTML document from which it originated, which is used to
// send debug information to the associated WebSocket client. Otherwise, this
// is the request for the HTML document, so we use the request ID also as the
// HTML request ID.
htmlRequestId = parsedRequestHeaders.htmlRequestId || requestId
const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(
interpolatedParams,
fallbackRouteParams
)
const isPossibleActionRequest = getIsPossibleServerAction(req)
const implicitTags = await getImplicitTags(
workStore.page,
url,
fallbackRouteParams
)
const ctx: AppRenderContext = {
componentMod: ComponentMod,
url,
renderOpts,
workStore,
parsedRequestHeaders,
getDynamicParamFromSegment,
query,
isPrefetch: isPrefetchRequest,
isPossibleServerAction: isPossibleActionRequest,
requestTimestamp,
appUsingSizeAdjustment,
flightRouterState,
requestId,
htmlRequestId,
pagePath,
assetPrefix,
isNotFoundPath,
nonce,
res,
sharedContext,
implicitTags,
}
getTracer().setRootSpanAttribute('next.route', pagePath)
if (isStaticGeneration) {
// We're either building or revalidating. In either case we need to
// prerender our page rather than render it.
const prerenderToStreamWithTracing = getTracer().wrap(
AppRenderSpan.getBodyResult,
{
spanName: `prerender route (app) ${pagePath}`,
attributes: {
'next.route': pagePath,
},
},
prerenderToStream
)
const response = await prerenderToStreamWithTracing(
req,
res,
ctx,
metadata,
loaderTree,
fallbackRouteParams
)
// If we're debugging partial prerendering, print all the dynamic API accesses
// that occurred during the render.
// @TODO move into renderToStream function
if (
response.dynamicAccess &&
accessedDynamicData(response.dynamicAccess) &&
renderOpts.isDebugDynamicAccesses
) {
warn('The following dynamic usage was detected:')
for (const access of formatDynamicAPIAccesses(response.dynamicAccess)) {
warn(access)
}
}
// If we encountered any unexpected errors during build we fail the
// prerendering phase and the build.
if (workStore.invalidDynamicUsageError) {
logDisallowedDynamicError(workStore, workStore.invalidDynamicUsageError)
throw new StaticGenBailoutError()
}
if (response.digestErrorsMap.size) {
const buildFailingError = response.digestErrorsMap.values().next().value
if (buildFailingError) throw buildFailingError
}
// Pick first userland SSR error, which is also not a RSC error.
if (response.ssrErrors.length) {
const buildFailingError = response.ssrErrors.find((err) =>
isUserLandError(err)
)
if (buildFailingError) throw buildFailingError
}
const options: RenderResultOptions = {
metadata,
contentType: HTML_CONTENT_TYPE_HEADER,
}
// If we have pending revalidates, wait until they are all resolved.
const maybeRevalidatesPromise = executeRevalidates(workStore)
if (maybeRevalidatesPromise !== false) {
const revalidatesPromise = maybeRevalidatesPromise.finally(() => {
if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {
console.log('pending revalidates promise finished for:', url.href)
}
})
if (renderOpts.waitUntil) {
renderOpts.waitUntil(revalidatesPromise)
} else {
options.waitUntil = revalidatesPromise
}
}
applyMetadataFromPrerenderResult(response, metadata, workStore)
if (response.renderResumeDataCache) {
metadata.renderResumeDataCache = response.renderResumeDataCache
}
return new RenderResult(await streamToString(response.stream), options)
} else {
// We're rendering dynamically
const renderResumeDataCache =
renderOpts.renderResumeDataCache ??
postponedState?.renderResumeDataCache ??
null
const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment)
const devFallbackParams = getRequestMeta(req, 'devFallbackParams') || null
const createRequestStore = createRequestStoreForRender.bind(
null,
req,
res,
url,
rootParams,
implicitTags,
renderOpts.onUpdateCookies,
renderOpts.previewProps,
isHmrRefresh,
serverComponentsHmrCache,
renderResumeDataCache,
devFallbackParams
)
const requestStore = createRequestStore()
if (
process.env.NODE_ENV === 'development' &&
renderOpts.setIsrStatus &&
!cacheComponents &&
// Only pages using the Node runtime can use ISR, so we only need to
// update the status for those.
// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextRequest(req)
) {
const setIsrStatus = renderOpts.setIsrStatus
req.originalRequest.on('end', () => {
const { pathname } = new URL(req.url || '/', 'http://n')
const isStatic = !requestStore.usedDynamic && !workStore.forceDynamic
setIsrStatus(pathname, isStatic)
})
}
if (isRSCRequest) {
if (isRuntimePrefetchRequest) {
return generateRuntimePrefetchResult(req, ctx, requestStore)
} else {
if (
process.env.NODE_ENV === 'development' &&
process.env.NEXT_RUNTIME !== 'edge' &&
cacheComponents
) {
return generateDynamicFlightRenderResultWithStagesInDev(
req,
ctx,
requestStore,
createRequestStore,
devFallbackParams
)
} else {
return generateDynamicFlightRenderResult(req, ctx, requestStore)
}
}
}
let didExecuteServerAction = false
let formState: null | any = null
if (isPossibleActionRequest) {
// For action requests, we don't want to use the resume data cache.
requestStore.renderResumeDataCache = null
// For action requests, we handle them differently with a special render result.
const actionRequestResult = await handleAction({
req,
res,
ComponentMod,
generateFlight: generateDynamicFlightRenderResult,
workStore,
requestStore,
serverActions,
ctx,
metadata,
})
if (actionRequestResult) {
if (actionRequestResult.type === 'not-found') {
const notFoundLoaderTree = createNotFoundLoaderTree(loaderTree)
res.statusCode = 404
metadata.statusCode = 404
const stream = await renderToStream(
requestStore,
req,
res,
ctx,
notFoundLoaderTree,
formState,
postponedState,
metadata,
undefined, // Prevent restartable-render behavior in dev + Cache Components mode
devFallbackParams
)
return new RenderResult(stream, {
metadata,
contentType: HTML_CONTENT_TYPE_HEADER,
})
} else if (actionRequestResult.type === 'done') {
if (actionRequestResult.result) {
actionRequestResult.result.assignMetadata(metadata)
return actionRequestResult.result
} else if (actionRequestResult.formState) {
formState = actionRequestResult.formState
}
}
}
didExecuteServerAction = true
// Restore the resume data cache
requestStore.renderResumeDataCache = renderResumeDataCache
}
const options: RenderResultOptions = {
metadata,
contentType: HTML_CONTENT_TYPE_HEADER,
}
const stream = await renderToStream(
// NOTE: in Cache Components (dev), if the render is restarted, it will use a different requestStore
// than the one that we're passing in here.
requestStore,
req,
res,
ctx,
loaderTree,
formState,
postponedState,
metadata,
// If we're rendering HTML after an action, we don't want restartable-render behavior
// because the result should be dynamic, like it is in prod.
// Also, the request store might have been mutated by the action (e.g. enabling draftMode)
// and we currently we don't copy changes over when creating a new store,
// so the restarted render wouldn't be correct.
didExecuteServerAction ? undefined : createRequestStore,
devFallbackParams
)
// Invalid dynamic usages should only error the request in development.
// In production, it's better to produce a result.
// (the dynamic error will still be thrown inside the component tree, but it's catchable by error boundaries)
if (workStore.invalidDynamicUsageError && workStore.dev) {
throw workStore.invalidDynamicUsageError
}
// If we have pending revalidates, wait until they are all resolved.
const maybeRevalidatesPromise = executeRevalidates(workStore)
if (maybeRevalidatesPromise !== false) {
const revalidatesPromise = maybeRevalidatesPromise.finally(() => {
if (process.env.NEXT_PRIVATE_DEBUG_CACHE) {
console.log('pending revalidates promise finished for:', url.href)
}
})
if (renderOpts.waitUntil) {
renderOpts.waitUntil(revalidatesPromise)
} else {
options.waitUntil = revalidatesPromise
}
}
// Create the new render result for the response.
return new RenderResult(stream, options)
}
}
export type AppPageRender = (
req: BaseNextRequest,
res: BaseNextResponse,
pagePath: string,
query: NextParsedUrlQuery,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
renderOpts: RenderOpts,
serverComponentsHmrCache: ServerComponentsHmrCache | undefined,
sharedContext: AppSharedContext
) => Promise<RenderResult<AppPageRenderResultMetadata>>
export const renderToHTMLOrFlight: AppPageRender = (
req,
res,
pagePath,
query,
fallbackRouteParams,
renderOpts,
serverComponentsHmrCache,
sharedContext
) => {
if (!req.url) {
throw new Error('Invalid URL')
}
const url = parseRelativeUrl(req.url, undefined, false)
// We read these values from the request object as, in certain cases,
// base-server will strip them to opt into different rendering behavior.
const parsedRequestHeaders = parseRequestHeaders(req.headers, {
isRoutePPREnabled: renderOpts.experimental.isRoutePPREnabled === true,
previewModeId: renderOpts.previewProps?.previewModeId,
})
const { isPrefetchRequest, previouslyRevalidatedTags, nonce } =
parsedRequestHeaders
let interpolatedParams: Params
let postponedState: PostponedState | null = null
// If provided, the postpone state should be parsed so it can be provided to
// React.
if (typeof renderOpts.postponed === 'string') {
if (fallbackRouteParams) {
throw new InvariantError(
'postponed state should not be provided when fallback params are provided'
)
}
interpolatedParams = interpolateParallelRouteParams(
renderOpts.ComponentMod.routeModule.userland.loaderTree,
renderOpts.params ?? {},
pagePath,
fallbackRouteParams
)
postponedState = parsePostponedState(
renderOpts.postponed,
interpolatedParams,
renderOpts.experimental.maxPostponedStateSizeBytes
)
} else {
interpolatedParams = interpolateParallelRouteParams(
renderOpts.ComponentMod.routeModule.userland.loaderTree,
renderOpts.params ?? {},
pagePath,
fallbackRouteParams
)
}
if (
postponedState?.renderResumeDataCache &&
renderOpts.renderResumeDataCache
) {
throw new InvariantError(
'postponed state and dev warmup immutable resume data cache should not be provided together'
)
}
const workStore = createWorkStore({
page: renderOpts.routeModule.definition.page,
renderOpts,
// @TODO move to workUnitStore of type Request
isPrefetchRequest,
buildId: sharedContext.buildId,
previouslyRevalidatedTags,
nonce,
})
return workAsyncStorage.run(
workStore,
// The function to run
renderToHTMLOrFlightImpl,
// all of it's args
req,
res,
url,
pagePath,
query,
renderOpts,
workStore,
parsedRequestHeaders,
postponedState,
serverComponentsHmrCache,
sharedContext,
interpolatedParams,
fallbackRouteParams
)
}
function applyMetadataFromPrerenderResult(
response: Pick<
PrerenderToStreamResult,
| 'collectedExpire'
| 'collectedRevalidate'
| 'collectedStale'
| 'collectedTags'
>,
metadata: AppPageRenderResultMetadata,
workStore: WorkStore
) {
if (response.collectedTags) {
metadata.fetchTags = response.collectedTags.join(',')
}
// Let the client router know how long to keep the cached entry around.
const staleHeader = String(response.collectedStale)
metadata.headers ??= {}
metadata.headers[NEXT_ROUTER_STALE_TIME_HEADER] = staleHeader
// If force static is specifically set to false, we should not revalidate
// the page.
if (workStore.forceStatic === false || response.collectedRevalidate === 0) {
metadata.cacheControl = { revalidate: 0, expire: undefined }
} else {
// Copy the cache control value onto the render result metadata.
metadata.cacheControl = {
revalidate:
response.collectedRevalidate >= INFINITE_CACHE
? false
: response.collectedRevalidate,
expire:
response.collectedExpire >= INFINITE_CACHE
? undefined
: response.collectedExpire,
}
}
// provide bailout info for debugging
if (metadata.cacheControl.revalidate === 0) {
metadata.staticBailoutInfo = {
description: workStore.dynamicUsageDescription,
stack: workStore.dynamicUsageStack,
}
}
}
type RSCPayloadDevProperties = {
/** Only available during cacheComponents development builds. Used for logging errors. */
_validation?: Promise<ReactNode>
_bypassCachesInDev?: ReactNode
}
type RSCInitialPayloadPartialDev = {
c?: InitialRSCPayload['c']
}
async function renderToStream(
requestStore: RequestStore,
req: BaseNextRequest,
res: BaseNextResponse,
ctx: AppRenderContext,
tree: LoaderTree,
formState: any,
postponedState: PostponedState | null,
metadata: AppPageRenderResultMetadata,
createRequestStore: (() => RequestStore) | undefined,
devFallbackParams: OpaqueFallbackRouteParams | null
): Promise<ReadableStream<Uint8Array>> {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
const {
assetPrefix,
htmlRequestId,
nonce,
pagePath,
renderOpts,
requestId,
workStore,
} = ctx
const {
basePath,
buildManifest,
ComponentMod: {
createElement,
renderToReadableStream: serverRenderToReadableStream,
},
crossOrigin,
dev = false,
experimental,
nextExport = false,
onInstrumentationRequestError,
page,
reactMaxHeadersLength,
setReactDebugChannel,
shouldWaitOnAllReady,
subresourceIntegrityManifest,
supportsDynamicResponse,
cacheComponents,
} = renderOpts
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML()
const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
experimental.clientTraceMetadata
)
const polyfills: JSX.IntrinsicElements['script'][] =
buildManifest.polyfillFiles
.filter(
(polyfill) =>
polyfill.endsWith('.js') && !polyfill.endsWith('.module.js')
)
.map((polyfill) => ({
src: `${assetPrefix}/_next/${polyfill}${getAssetQueryString(
ctx,
false
)}`,
integrity: subresourceIntegrityManifest?.[polyfill],
crossOrigin,
noModule: true,
nonce,
}))
const [preinitScripts, bootstrapScript] = getRequiredScripts(
buildManifest,
// Why is assetPrefix optional on renderOpts?
// @TODO make it default empty string on renderOpts and get rid of it from ctx
assetPrefix,
crossOrigin,
subresourceIntegrityManifest,
getAssetQueryString(ctx, true),
nonce,
page
)
// In development mode, set the request ID as a global variable, before the
// bootstrap script is executed, which depends on it during hydration.
const bootstrapScriptContent =
process.env.NODE_ENV !== 'production'
? `self.__next_r=${JSON.stringify(requestId)}`
: undefined
// Create the "render route (app)" span manually so we can keep it open during streaming.
// This is necessary because errors inside Suspense boundaries are reported asynchronously
// during stream consumption, after a typical wrapped function would have ended the span.
// Note: We pass the full span name as the first argument since startSpan uses it directly.
const renderSpan = getTracer().startSpan(
`render route (app) ${pagePath}` as any,
{
attributes: {
'next.span_name': `render route (app) ${pagePath}`,
'next.span_type': AppRenderSpan.getBodyResult,
'next.route': pagePath,
},
}
)
// Helper to end the span with error status (used when throwing from catch blocks)
const endSpanWithError = (err: unknown) => {
if (!renderSpan.isRecording()) return
if (err instanceof Error) {
renderSpan.recordException(err)
renderSpan.setAttribute('error.type', err.name)
}
renderSpan.setStatus({
code: SpanStatusCode.ERROR,
message: err instanceof Error ? err.message : undefined,
})
renderSpan.end()
}
// Run the rest of the function within the span's context so child spans
// (like "build component tree", "generateMetadata") are properly parented.
return getTracer().withSpan(renderSpan, async () => {
const { reactServerErrorsByDigest } = workStore
function onHTMLRenderRSCError(err: DigestedError, silenceLog: boolean) {
return onInstrumentationRequestError?.(
err,
req,
createErrorContext(ctx, 'react-server-components'),
silenceLog
)
}
const serverComponentsErrorHandler = createReactServerErrorHandler(
dev,
nextExport,
reactServerErrorsByDigest,
onHTMLRenderRSCError,
renderSpan
)
function onHTMLRenderSSRError(err: DigestedError) {
// We don't need to silence logs here. onHTMLRenderSSRError won't be called
// at all if the error was logged before in the RSC error handler.
const silenceLog = false
return onInstrumentationRequestError?.(
err,
req,
createErrorContext(ctx, 'server-rendering'),
silenceLog
)
}
const allCapturedErrors: Array<unknown> = []
const htmlRendererErrorHandler = createHTMLErrorHandler(
dev,
nextExport,
reactServerErrorsByDigest,
allCapturedErrors,
onHTMLRenderSSRError,
renderSpan
)
let reactServerResult: null | ReactServerResult = null
let reactDebugStream: ReadableStream<Uint8Array> | undefined
const setHeader = res.setHeader.bind(res)
const appendHeader = res.appendHeader.bind(res)
const { clientModules } = getClientReferenceManifest()
try {
if (
// We only want this behavior when we have React's dev builds available
process.env.NODE_ENV === 'development' &&
// We only want this behavior when running `next dev`
dev &&
// Edge routes never prerender so we don't have a Prerender environment for anything in edge runtime
process.env.NEXT_RUNTIME !== 'edge' &&
// We only have a Prerender environment for projects opted into cacheComponents
cacheComponents
) {
let debugChannel: DebugChannelPair | undefined
const getPayload = async (
// eslint-disable-next-line @typescript-eslint/no-shadow
requestStore: RequestStore
) => {
const payload: InitialRSCPayload & RSCPayloadDevProperties =
await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
)
if (isBypassingCachesInDev(renderOpts, requestStore)) {
// Mark the RSC payload to indicate that caches were bypassed in dev.
// This lets the client know not to cache anything based on this render.
if (renderOpts.setCacheStatus) {
// we know this is available when cacheComponents is enabled, but typeguard to be safe
renderOpts.setCacheStatus('bypass', htmlRequestId)
}
payload._bypassCachesInDev = createElement(
WarnForBypassCachesInDev,
{
route: workStore.route,
}
)
}
return payload
}
if (
// We only do this flow if we can safely recreate the store from scratch
// (which is not the case for renders after an action)
createRequestStore &&
// We only do this flow if we're not bypassing caches in dev using
// "disable cache" in devtools or a hard refresh (cache-control: "no-store")
!isBypassingCachesInDev(renderOpts, requestStore)
) {
const {
stream: serverStream,
accumulatedChunksPromise,
staticInterruptReason,
runtimeInterruptReason,
staticStageEndTime,
runtimeStageEndTime,
debugChannel: returnedDebugChannel,
requestStore: finalRequestStore,
} = await renderWithRestartOnCacheMissInDev(
ctx,
requestStore,
createRequestStore,
getPayload,
serverComponentsErrorHandler
)
let validationDebugChannelClient: Readable | undefined = undefined
if (returnedDebugChannel) {
const [t1, t2] = returnedDebugChannel.clientSide.readable.tee()
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = nodeStreamFromReadableStream(t2)
}
consoleAsyncStorage.run(
{ dim: true },
spawnStaticShellValidationInDev,
accumulatedChunksPromise,
staticInterruptReason,
runtimeInterruptReason,
staticStageEndTime,
runtimeStageEndTime,
ctx,
finalRequestStore,
devFallbackParams,
validationDebugChannelClient
)
reactServerResult = new ReactServerResult(serverStream)
requestStore = finalRequestStore
debugChannel = returnedDebugChannel
} else {
// We're either bypassing caches or we can't restart the render.
// Do a dynamic render, but with (basic) environment labels.
debugChannel = setReactDebugChannel && createDebugChannel()
const serverStream =
await stagedRenderToReadableStreamWithoutCachesInDev(
ctx,
requestStore,
getPayload,
{
onError: serverComponentsErrorHandler,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
reactServerResult = new ReactServerResult(serverStream)
}
if (debugChannel && setReactDebugChannel) {
const [readableSsr, readableBrowser] =
debugChannel.clientSide.readable.tee()
reactDebugStream = readableSsr
setReactDebugChannel(
{ readable: readableBrowser },
htmlRequestId,
requestId
)
}
} else {
// This is a dynamic render. We don't do dynamic tracking because we're not prerendering
const RSCPayload: RSCPayload & RSCPayloadDevProperties =
await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
)
const debugChannel = setReactDebugChannel && createDebugChannel()
if (debugChannel) {
const [readableSsr, readableBrowser] =
debugChannel.clientSide.readable.tee()
reactDebugStream = readableSsr
setReactDebugChannel(
{ readable: readableBrowser },
htmlRequestId,
requestId
)
}
reactServerResult = new ReactServerResult(
workUnitAsyncStorage.run(
requestStore,
serverRenderToReadableStream,
RSCPayload,
clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
debugChannel: debugChannel?.serverSide,
}
)
)
}
// React doesn't start rendering synchronously but we want the RSC render to have a chance to start
// before we begin SSR rendering because we want to capture any available preload headers so we tick
// one task before continuing
await waitAtLeastOneReactRenderTask()
// If provided, the postpone state should be parsed as JSON so it can be
// provided to React.
if (typeof renderOpts.postponed === 'string') {
if (postponedState?.type === DynamicState.DATA) {
// We have a complete HTML Document in the prerender but we need to
// still include the new server component render because it was not included
// in the static prelude.
const inlinedReactServerDataStream = createInlinedDataReadableStream(
reactServerResult.tee(),
nonce,
formState
)
// End the span since there's no async rendering in this path
if (renderSpan.isRecording()) renderSpan.end()
return chainStreams(
inlinedReactServerDataStream,
createDocumentClosingStream()
)
} else if (postponedState) {
// We assume we have dynamic HTML requiring a resume render to complete
const { postponed, preludeState } =
getPostponedFromState(postponedState)
const resume = (
require('react-dom/server') as typeof import('react-dom/server')
).resume
const htmlStream = await workUnitAsyncStorage.run(
requestStore,
resume,
<App
reactServerStream={reactServerResult.tee()}
reactDebugStream={reactDebugStream}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
postponed,
{ onError: htmlRendererErrorHandler, nonce }
)
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
htmlStream.allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
return await continueDynamicHTMLResume(htmlStream, {
// If the prelude is empty (i.e. is no static shell), we should wait for initial HTML to be rendered
// to avoid injecting RSC data too early.
// If we have a non-empty-prelude (i.e. a static HTML shell), then it's already been sent separately,
// so we shouldn't wait for any HTML to be emitted from the resume before sending RSC data.
delayDataUntilFirstHtmlChunk:
preludeState === DynamicHTMLPreludeState.Empty,
inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consume(),
nonce,
formState
),
getServerInsertedHTML,
getServerInsertedMetadata,
})
}
}
// This is a regular dynamic render
const renderToReadableStream = (
require('react-dom/server') as typeof import('react-dom/server')
).renderToReadableStream
const htmlStream = await workUnitAsyncStorage.run(
requestStore,
renderToReadableStream,
<App
reactServerStream={reactServerResult.tee()}
reactDebugStream={reactDebugStream}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
onError: htmlRendererErrorHandler,
nonce,
onHeaders: (headers: Headers) => {
headers.forEach((value, key) => {
appendHeader(key, value)
})
},
maxHeadersLength: reactMaxHeadersLength,
bootstrapScriptContent,
bootstrapScripts: [bootstrapScript],
formState,
}
)
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
htmlStream.allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
/**
* Rules of Static & Dynamic HTML:
*
* 1.) We must generate static HTML unless the caller explicitly opts
* in to dynamic HTML support.
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for a static page.
*
* 3.) If `shouldWaitOnAllReady` is true, which indicates we need to
* resolve all suspenses and generate a full HTML. e.g. when it's a
* html limited bot requests, we produce the full HTML content.
*
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/
const generateStaticHTML =
supportsDynamicResponse !== true || !!shouldWaitOnAllReady
return await continueFizzStream(htmlStream, {
inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consume(),
nonce,
formState
),
isStaticGeneration: generateStaticHTML,
isBuildTimePrerendering: ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
getServerInsertedHTML,
getServerInsertedMetadata,
validateRootLayout: dev,
})
} catch (err) {
if (
isStaticGenBailoutError(err) ||
(typeof err === 'object' &&
err !== null &&
'message' in err &&
typeof err.message === 'string' &&
err.message.includes(
'https://nextjs.org/docs/advanced-features/static-html-export'
))
) {
// Ensure that "next dev" prints the red error overlay
endSpanWithError(err)
throw err
}
// If a bailout made it to this point, it means it wasn't wrapped inside
// a suspense boundary.
const shouldBailoutToCSR = isBailoutToCSRError(err)
if (shouldBailoutToCSR) {
const stack = getStackWithoutErrorMessage(err)
error(
`${err.reason} should be wrapped in a suspense boundary at page "${pagePath}". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n${stack}`
)
endSpanWithError(err)
throw err
}
let errorType: MetadataErrorType | 'redirect' | undefined
if (isHTTPAccessFallbackError(err)) {
res.statusCode = getAccessFallbackHTTPStatus(err)
metadata.statusCode = res.statusCode
errorType = getAccessFallbackErrorTypeByStatus(res.statusCode)
} else if (isRedirectError(err)) {
errorType = 'redirect'
res.statusCode = getRedirectStatusCodeFromError(err)
metadata.statusCode = res.statusCode
const redirectUrl = addPathPrefix(
getURLFromRedirectError(err),
basePath
)
// If there were mutable cookies set, we need to set them on the
// response.
const headers = new Headers()
if (appendMutableCookies(headers, requestStore.mutableCookies)) {
setHeader('set-cookie', Array.from(headers.values()))
}
setHeader('location', redirectUrl)
} else if (!shouldBailoutToCSR) {
res.statusCode = 500
metadata.statusCode = res.statusCode
}
const [errorPreinitScripts, errorBootstrapScript] = getRequiredScripts(
buildManifest,
assetPrefix,
crossOrigin,
subresourceIntegrityManifest,
getAssetQueryString(ctx, false),
nonce,
'/_not-found/page'
)
let errorRSCPayload: InitialRSCPayload
let errorServerStream: ReturnType<typeof serverRenderToReadableStream>
try {
errorRSCPayload = await workUnitAsyncStorage.run(
requestStore,
getErrorRSCPayload,
tree,
ctx,
reactServerErrorsByDigest.has((err as any).digest) ? null : err,
errorType
)
errorServerStream = workUnitAsyncStorage.run(
requestStore,
serverRenderToReadableStream,
errorRSCPayload,
clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
}
)
if (reactServerResult === null) {
// We errored when we did not have an RSC stream to read from. This is not just a render
// error, we need to throw early
endSpanWithError(err)
throw err
}
} catch (setupErr) {
endSpanWithError(setupErr)
throw setupErr
}
try {
const fizzStream = await workUnitAsyncStorage.run(
requestStore,
renderToInitialFizzStream,
{
ReactDOMServer:
require('react-dom/server') as typeof import('react-dom/server'),
element: (
<ErrorApp
reactServerStream={errorServerStream}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts}
nonce={nonce}
images={ctx.renderOpts.images}
/>
),
streamOptions: {
nonce,
bootstrapScriptContent,
// Include hydration scripts in the HTML
bootstrapScripts: [errorBootstrapScript],
formState,
},
}
)
// End the render span only after React completed rendering (including anything inside Suspense boundaries)
fizzStream.allReady.finally(() => {
if (renderSpan.isRecording()) renderSpan.end()
})
/**
* Rules of Static & Dynamic HTML:
*
* 1.) We must generate static HTML unless the caller explicitly opts
* in to dynamic HTML support.
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for a static page.
* 3.) If `shouldWaitOnAllReady` is true, which indicates we need to
* resolve all suspenses and generate a full HTML. e.g. when it's a
* html limited bot requests, we produce the full HTML content.
*
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/
const generateStaticHTML =
supportsDynamicResponse !== true || !!shouldWaitOnAllReady
return await continueFizzStream(fizzStream, {
inlinedDataStream: createInlinedDataReadableStream(
// This is intentionally using the readable datastream from the
// main render rather than the flight data from the error page
// render
reactServerResult.consume(),
nonce,
formState
),
isStaticGeneration: generateStaticHTML,
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
getServerInsertedHTML: makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: [],
basePath,
tracingMetadata: tracingMetadata,
}),
getServerInsertedMetadata,
validateRootLayout: dev,
})
} catch (finalErr: any) {
if (
process.env.NODE_ENV === 'development' &&
isHTTPAccessFallbackError(finalErr)
) {
const { bailOnRootNotFound } =
require('../../client/components/dev-root-http-access-fallback-boundary') as typeof import('../../client/components/dev-root-http-access-fallback-boundary')
bailOnRootNotFound()
}
endSpanWithError(finalErr)
throw finalErr
}
}
})
/* eslint-enable @next/internal/no-ambiguous-jsx */
}
async function renderWithRestartOnCacheMissInDev(
ctx: AppRenderContext,
initialRequestStore: RequestStore,
createRequestStore: () => RequestStore,
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
onError: (error: unknown) => void
) {
const {
htmlRequestId,
renderOpts,
componentMod: {
routeModule: {
userland: { loaderTree },
},
},
} = ctx
const { ComponentMod, setCacheStatus, setReactDebugChannel } = renderOpts
const hasRuntimePrefetch =
await anySegmentHasRuntimePrefetchEnabled(loaderTree)
// If the render is restarted, we'll recreate a fresh request store
let requestStore: RequestStore = initialRequestStore
const environmentName = () => {
const currentStage = requestStore.stagedRendering!.currentStage
switch (currentStage) {
case RenderStage.Before:
case RenderStage.Static:
return 'Prerender'
case RenderStage.Runtime:
return hasRuntimePrefetch ? 'Prefetch' : 'Prefetchable'
case RenderStage.Dynamic:
case RenderStage.Abandoned:
return 'Server'
default:
currentStage satisfies never
throw new InvariantError(`Invalid render stage: ${currentStage}`)
}
}
//===============================================
// Initial render
//===============================================
// Try to render the page and see if there's any cache misses.
// If there are, wait for caches to finish and restart the render.
// This render might end up being used as a prospective render (if there's cache misses),
// so we need to set it up for filling caches.
const cacheSignal = new CacheSignal()
// If we encounter async modules that delay rendering, we'll also need to restart.
// TODO(restart-on-cache-miss): technically, we only need to wait for pending *server* modules here,
// but `trackPendingModules` doesn't distinguish between client and server.
trackPendingModules(cacheSignal)
const prerenderResumeDataCache = createPrerenderResumeDataCache()
const initialReactController = new AbortController()
const initialDataController = new AbortController() // Controls hanging promises we create
const initialStageController = new StagedRenderingController(
initialDataController.signal,
hasRuntimePrefetch
)
requestStore.prerenderResumeDataCache = prerenderResumeDataCache
// `getRenderResumeDataCache` will fall back to using `prerenderResumeDataCache` as `renderResumeDataCache`,
// so not having a resume data cache won't break any expectations in case we don't need to restart.
requestStore.renderResumeDataCache = null
requestStore.stagedRendering = initialStageController
requestStore.asyncApiPromises = createAsyncApiPromisesInDev(
initialStageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
requestStore.cacheSignal = cacheSignal
let debugChannel = setReactDebugChannel && createDebugChannel()
const { clientModules } = getClientReferenceManifest()
// Note: The stage controller starts out in the `Before` stage,
// where sync IO does not cause aborts, so it's okay if it happens before render.
const initialRscPayload = await getPayload(requestStore)
const maybeInitialStreamResult = await workUnitAsyncStorage.run(
requestStore,
() =>
pipelineInSequentialTasks(
() => {
// Static stage
initialStageController.advanceStage(RenderStage.Static)
const stream = ComponentMod.renderToReadableStream(
initialRscPayload,
clientModules,
{
onError,
environmentName,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
signal: initialReactController.signal,
}
)
// If we abort the render, we want to reject the stage-dependent promises as well.
// Note that we want to install this listener after the render is started
// so that it runs after react is finished running its abort code.
initialReactController.signal.addEventListener('abort', () => {
initialDataController.abort(initialReactController.signal.reason)
})
const [continuationStream, accumulatingStream] = stream.tee()
const accumulatedChunksPromise = accumulateStreamChunks(
accumulatingStream,
initialStageController,
initialDataController.signal
)
return { stream: continuationStream, accumulatedChunksPromise }
},
({ stream, accumulatedChunksPromise }) => {
// Runtime stage
if (initialStageController.currentStage === RenderStage.Abandoned) {
// If we abandoned the render in the static stage, we won't proceed further.
return null
}
// If we had a cache miss in the static stage, we'll have to discard this stream
// and render again once the caches are warm.
// If we already advanced stages we similarly had sync IO that might be from module loading
// and need to render again once the caches are warm.
if (cacheSignal.hasPendingReads()) {
// Regardless of whether we are going to abandon this
// render we need the unblock runtime b/c it's essential
// filling caches.
initialStageController.abandonRender()
return null
}
initialStageController.advanceStage(RenderStage.Runtime)
return { stream, accumulatedChunksPromise }
},
(result) => {
// Dynamic stage
if (
result === null ||
initialStageController.currentStage === RenderStage.Abandoned
) {
// If we abandoned the render in the static or runtime stage, we won't proceed further.
return null
}
// If we had cache misses in either of the previous stages,
// then we'll only use this render for filling caches.
// We won't advance the stage, and thus leave dynamic APIs hanging,
// because they won't be cached anyway, so it'd be wasted work.
if (cacheSignal.hasPendingReads()) {
initialStageController.abandonRender()
return null
}
// Regardless of whether we are going to abandon this
// render we need the unblock runtime b/c it's essential
// filling caches.
initialStageController.advanceStage(RenderStage.Dynamic)
return result
}
)
)
if (maybeInitialStreamResult !== null) {
// No cache misses. We can use the result as-is.
return {
stream: maybeInitialStreamResult.stream,
accumulatedChunksPromise:
maybeInitialStreamResult.accumulatedChunksPromise,
staticInterruptReason: initialStageController.getStaticInterruptReason(),
runtimeInterruptReason:
initialStageController.getRuntimeInterruptReason(),
staticStageEndTime: initialStageController.getStaticStageEndTime(),
runtimeStageEndTime: initialStageController.getRuntimeStageEndTime(),
debugChannel,
requestStore,
}
}
if (process.env.NODE_ENV === 'development' && setCacheStatus) {
setCacheStatus('filling', htmlRequestId)
}
// Cache miss. We will use the initial render to fill caches, and discard its result.
// Then, we can render again with warm caches.
// TODO(restart-on-cache-miss):
// This might end up waiting for more caches than strictly necessary,
// because we can't abort the render yet, and we'll let runtime/dynamic APIs resolve.
// Ideally we'd only wait for caches that are needed in the static stage.
// This will be optimized in the future by not allowing runtime/dynamic APIs to resolve.
await cacheSignal.cacheReady()
initialReactController.abort()
//===============================================
// Final render (restarted)
//===============================================
// The initial render acted as a prospective render to warm the caches.
requestStore = createRequestStore()
// We are going to render this pass all the way through because we've already
// filled any caches so we won't be aborting this time.
const abortSignal = null
const finalStageController = new StagedRenderingController(
abortSignal,
hasRuntimePrefetch
)
// We've filled the caches, so now we can render as usual,
// without any cache-filling mechanics.
requestStore.prerenderResumeDataCache = null
requestStore.renderResumeDataCache = createRenderResumeDataCache(
prerenderResumeDataCache
)
requestStore.stagedRendering = finalStageController
requestStore.cacheSignal = null
requestStore.asyncApiPromises = createAsyncApiPromisesInDev(
finalStageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
// The initial render already wrote to its debug channel.
// We're not using it, so we need to create a new one.
debugChannel = setReactDebugChannel && createDebugChannel()
// Note: The stage controller starts out in the `Before` stage,
// where sync IO does not cause aborts, so it's okay if it happens before render.
const finalRscPayload = await getPayload(requestStore)
const finalStreamResult = await workUnitAsyncStorage.run(requestStore, () =>
pipelineInSequentialTasks(
() => {
// Static stage
finalStageController.advanceStage(RenderStage.Static)
const stream = ComponentMod.renderToReadableStream(
finalRscPayload,
clientModules,
{
onError,
environmentName,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
const [continuationStream, accumulatingStream] = stream.tee()
const accumulatedChunksPromise = accumulateStreamChunks(
accumulatingStream,
finalStageController,
null
)
return { stream: continuationStream, accumulatedChunksPromise }
},
(result) => {
// Runtime stage
finalStageController.advanceStage(RenderStage.Runtime)
return result
},
(result) => {
// Dynamic stage
finalStageController.advanceStage(RenderStage.Dynamic)
return result
}
)
)
if (process.env.NODE_ENV === 'development' && setCacheStatus) {
setCacheStatus('filled', htmlRequestId)
}
return {
stream: finalStreamResult.stream,
accumulatedChunksPromise: finalStreamResult.accumulatedChunksPromise,
staticInterruptReason: finalStageController.getStaticInterruptReason(),
runtimeInterruptReason: finalStageController.getRuntimeInterruptReason(),
staticStageEndTime: finalStageController.getStaticStageEndTime(),
runtimeStageEndTime: finalStageController.getRuntimeStageEndTime(),
debugChannel,
requestStore,
}
}
interface AccumulatedStreamChunks {
readonly staticChunks: Array<Uint8Array>
readonly runtimeChunks: Array<Uint8Array>
readonly dynamicChunks: Array<Uint8Array>
}
async function accumulateStreamChunks(
stream: ReadableStream<Uint8Array>,
stageController: StagedRenderingController,
signal: AbortSignal | null
): Promise<AccumulatedStreamChunks> {
const staticChunks: Array<Uint8Array> = []
const runtimeChunks: Array<Uint8Array> = []
const dynamicChunks: Array<Uint8Array> = []
const reader = stream.getReader()
let cancelled = false
function cancel() {
if (!cancelled) {
cancelled = true
reader.cancel()
}
}
if (signal) {
signal.addEventListener('abort', cancel, { once: true })
}
try {
while (!cancelled) {
const { done, value } = await reader.read()
if (done) {
cancel()
break
}
switch (stageController.currentStage) {
case RenderStage.Before:
throw new InvariantError(
'Unexpected stream chunk while in Before stage'
)
case RenderStage.Static:
staticChunks.push(value)
// fall through
case RenderStage.Runtime:
runtimeChunks.push(value)
// fall through
case RenderStage.Dynamic:
dynamicChunks.push(value)
break
case RenderStage.Abandoned:
// If the render was abandoned, we won't use the chunks,
// so there's no need to accumulate them
break
default:
stageController.currentStage satisfies never
break
}
}
} catch {
// When we release the lock we may reject the read
}
return { staticChunks, runtimeChunks, dynamicChunks }
}
function createAsyncApiPromisesInDev(
stagedRendering: StagedRenderingController,
cookies: RequestStore['cookies'],
mutableCookies: RequestStore['mutableCookies'],
headers: RequestStore['headers']
): NonNullable<RequestStore['asyncApiPromises']> {
return {
// Runtime APIs
cookies: stagedRendering.delayUntilStage(
RenderStage.Runtime,
'cookies',
cookies
),
mutableCookies: stagedRendering.delayUntilStage(
RenderStage.Runtime,
'cookies',
mutableCookies as RequestStore['cookies']
),
headers: stagedRendering.delayUntilStage(
RenderStage.Runtime,
'headers',
headers
),
// These are not used directly, but we chain other `params`/`searchParams` promises off of them.
sharedParamsParent: stagedRendering.delayUntilStage(
RenderStage.Runtime,
undefined,
'<internal params>'
),
sharedSearchParamsParent: stagedRendering.delayUntilStage(
RenderStage.Runtime,
undefined,
'<internal searchParams>'
),
connection: stagedRendering.delayUntilStage(
RenderStage.Dynamic,
'connection',
undefined
),
}
}
type DebugChannelPair = {
serverSide: DebugChannelServer
clientSide: DebugChannelClient
}
type DebugChannelServer = {
readable?: ReadableStream<Uint8Array>
writable: WritableStream<Uint8Array>
}
type DebugChannelClient = {
readable: ReadableStream<Uint8Array>
writable?: WritableStream<Uint8Array>
}
function createDebugChannel(): DebugChannelPair | undefined {
if (process.env.NODE_ENV === 'production') {
return undefined
}
let readableController: ReadableStreamDefaultController | undefined
let clientSideReadable = new ReadableStream<Uint8Array>({
start(controller) {
readableController = controller
},
})
return {
serverSide: {
writable: new WritableStream<Uint8Array>({
write(chunk) {
readableController?.enqueue(chunk)
},
close() {
readableController?.close()
},
abort(err) {
readableController?.error(err)
},
}),
},
clientSide: { readable: clientSideReadable },
}
}
/**
* Logs the given messages, and sends the error instances to the browser as an
* RSC stream, where they can be deserialized and logged (or otherwise presented
* in the devtools), while leveraging React's capabilities to not only
* source-map the stack frames (via findSourceMapURL), but also create virtual
* server modules that allow users to inspect the server source code in the
* browser.
*/
async function logMessagesAndSendErrorsToBrowser(
messages: unknown[],
ctx: AppRenderContext
): Promise<void> {
const { componentMod: ComponentMod, htmlRequestId, renderOpts } = ctx
const { sendErrorsToBrowser } = renderOpts
const errors: Error[] = []
for (const message of messages) {
// Log the error to the CLI. Prevent the logs from being dimmed, which we
// apply for other logs during the spawned validation.
consoleAsyncStorage.exit(() => {
console.error(message)
})
// Error instances are also sent to the browser. We're currently using a
// non-Error message only in debug build mode as a message that is only
// meant for the CLI. FIXME: This is a bit spooky action at a distance. We
// should maybe have a more explicit way of determining which messages
// should be sent to the browser. Regardless, only real errors with a proper
// stack make sense to be "replayed" in the browser.
if (message instanceof Error) {
errors.push(message)
}
}
if (errors.length > 0) {
if (!sendErrorsToBrowser) {
throw new InvariantError(
'Expected `sendErrorsToBrowser` to be defined in renderOpts.'
)
}
const { clientModules } = getClientReferenceManifest()
const errorsRscStream = ComponentMod.renderToReadableStream(
errors,
clientModules,
{ filterStackFrame }
)
sendErrorsToBrowser(errorsRscStream, htmlRequestId)
}
}
/**
* This function is a fork of prerenderToStream cacheComponents branch.
* While it doesn't return a stream we want it to have identical
* prerender semantics to prerenderToStream and should update it
* in conjunction with any changes to that function.
*/
async function spawnStaticShellValidationInDev(
accumulatedChunksPromise: Promise<AccumulatedStreamChunks>,
staticInterruptReason: Error | null,
runtimeInterruptReason: Error | null,
staticStageEndTime: number,
runtimeStageEndTime: number,
ctx: AppRenderContext,
requestStore: RequestStore,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
debugChannelClient: Readable | undefined
): Promise<void> {
const {
componentMod: ComponentMod,
getDynamicParamFromSegment,
renderOpts,
workStore,
} = ctx
const { allowEmptyStaticShell = false } = renderOpts
const rootParams = getRootParams(
ComponentMod.routeModule.userland.loaderTree,
getDynamicParamFromSegment
)
const hmrRefreshHash = getHmrRefreshHash(workStore, requestStore)
// We don't need to continue the prerender process if we already
// detected invalid dynamic usage in the initial prerender phase.
const { invalidDynamicUsageError } = workStore
if (invalidDynamicUsageError) {
return logMessagesAndSendErrorsToBrowser([invalidDynamicUsageError], ctx)
}
if (staticInterruptReason) {
return logMessagesAndSendErrorsToBrowser([staticInterruptReason], ctx)
}
if (runtimeInterruptReason) {
return logMessagesAndSendErrorsToBrowser([runtimeInterruptReason], ctx)
}
const { staticChunks, runtimeChunks, dynamicChunks } =
await accumulatedChunksPromise
// First we warmup SSR with the runtime chunks. This ensures that when we do
// the full prerender pass with dynamic tracking module loading won't
// interrupt the prerender and can properly observe the entire content
await warmupModuleCacheForRuntimeValidationInDev(
runtimeChunks,
dynamicChunks,
rootParams,
fallbackRouteParams,
allowEmptyStaticShell,
ctx
)
let debugChunks: Uint8Array[] | null = null
if (debugChannelClient) {
debugChunks = []
debugChannelClient.on('data', (c) => debugChunks!.push(c))
}
const runtimeResult = await validateStagedShell(
runtimeChunks,
dynamicChunks,
debugChunks,
runtimeStageEndTime,
rootParams,
fallbackRouteParams,
allowEmptyStaticShell,
ctx,
hmrRefreshHash,
trackDynamicHoleInRuntimeShell
)
if (runtimeResult.length > 0) {
// We have something to report from the runtime validation
// We can skip the static validation
return logMessagesAndSendErrorsToBrowser(runtimeResult, ctx)
}
const staticResult = await validateStagedShell(
staticChunks,
dynamicChunks,
debugChunks,
staticStageEndTime,
rootParams,
fallbackRouteParams,
allowEmptyStaticShell,
ctx,
hmrRefreshHash,
trackDynamicHoleInStaticShell
)
return logMessagesAndSendErrorsToBrowser(staticResult, ctx)
}
async function warmupModuleCacheForRuntimeValidationInDev(
runtimeServerChunks: Array<Uint8Array>,
allServerChunks: Array<Uint8Array>,
rootParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
allowEmptyStaticShell: boolean,
ctx: AppRenderContext
) {
const { implicitTags, nonce, workStore } = ctx
// Warmup SSR
const initialClientPrerenderController = new AbortController()
const initialClientReactController = new AbortController()
const initialClientRenderController = new AbortController()
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const initialClientPrerenderStore: PrerenderStore = {
type: 'prerender-client',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: initialClientRenderController.signal,
controller: initialClientPrerenderController,
// For HTML Generation the only cache tracked activity
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
// TODO should this be removed from client stores?
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash: undefined,
}
const runtimeServerStream = createNodeStreamFromChunks(
runtimeServerChunks,
allServerChunks,
initialClientReactController.signal
)
const prerender = (
require('react-dom/static') as typeof import('react-dom/static')
).prerender
const pendingInitialClientResult = workUnitAsyncStorage.run(
initialClientPrerenderStore,
prerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- React Client
<App
reactServerStream={runtimeServerStream}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
signal: initialClientReactController.signal,
onError: (err) => {
const digest = getDigestForWellKnownError(err)
if (digest) {
return digest
}
if (isReactLargeShellError(err)) {
// TODO: Aggregate
console.error(err)
return undefined
}
if (initialClientReactController.signal.aborted) {
// These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(
err,
workStore.route,
Phase.ProspectiveRender
)
}
},
// We don't need bootstrap scripts in this prerender
// bootstrapScripts: [bootstrapScript],
}
)
// The listener to abort our own render controller must be added after React
// has added its listener, to ensure that pending I/O is not
// aborted/rejected too early.
initialClientReactController.signal.addEventListener(
'abort',
() => {
initialClientRenderController.abort()
},
{ once: true }
)
pendingInitialClientResult.catch((err) => {
if (
initialClientReactController.signal.aborted ||
isPrerenderInterruptedError(err)
) {
// These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(
err,
workStore.route,
Phase.ProspectiveRender
)
}
})
// This is mostly needed for dynamic `import()`s in client components.
// Promises passed to client were already awaited above (assuming that they came from cached functions)
const cacheSignal = new CacheSignal()
trackPendingModules(cacheSignal)
await cacheSignal.cacheReady()
initialClientReactController.abort()
}
async function validateStagedShell(
stageChunks: Array<Uint8Array>,
allServerChunks: Array<Uint8Array>,
debugChunks: null | Array<Uint8Array>,
debugEndTime: number | undefined,
rootParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
allowEmptyStaticShell: boolean,
ctx: AppRenderContext,
hmrRefreshHash: string | undefined,
trackDynamicHole:
| typeof trackDynamicHoleInStaticShell
| typeof trackDynamicHoleInRuntimeShell
): Promise<Array<unknown>> {
const { implicitTags, nonce, workStore } = ctx
const clientDynamicTracking = createDynamicTrackingState(
false //isDebugDynamicAccesses
)
const clientReactController = new AbortController()
const clientRenderController = new AbortController()
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const finalClientPrerenderStore: PrerenderStore = {
type: 'prerender-client',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: clientRenderController.signal,
controller: clientReactController,
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null,
dynamicTracking: clientDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
// TODO should this be removed from client stores?
prerenderResumeDataCache: null,
renderResumeDataCache: null,
hmrRefreshHash,
}
let runtimeDynamicValidation = createDynamicValidationState()
const serverStream = createNodeStreamFromChunks(
stageChunks,
allServerChunks,
clientReactController.signal
)
const debugChannelClient = debugChunks
? createNodeStreamFromChunks(
debugChunks,
debugChunks,
clientReactController.signal
)
: undefined
const prerender = (
require('react-dom/static') as typeof import('react-dom/static')
).prerender
try {
let { prelude: unprocessedPrelude } =
await prerenderAndAbortInSequentialTasks(
() => {
const pendingFinalClientResult = workUnitAsyncStorage.run(
finalClientPrerenderStore,
prerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx -- React Client
<App
reactServerStream={serverStream}
reactDebugStream={debugChannelClient}
debugEndTime={debugEndTime}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
signal: clientReactController.signal,
onError: (err: unknown, errorInfo: ErrorInfo) => {
if (
isPrerenderInterruptedError(err) ||
clientReactController.signal.aborted
) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
trackDynamicHole(
workStore,
componentStack,
runtimeDynamicValidation,
clientDynamicTracking
)
}
return
}
if (isReactLargeShellError(err)) {
// TODO: Aggregate
console.error(err)
return undefined
}
return getDigestForWellKnownError(err)
},
// We don't need bootstrap scripts in this prerender
// bootstrapScripts: [bootstrapScript],
}
)
// The listener to abort our own render controller must be added after
// React has added its listener, to ensure that pending I/O is not
// aborted/rejected too early.
clientReactController.signal.addEventListener(
'abort',
() => {
clientRenderController.abort()
},
{ once: true }
)
return pendingFinalClientResult
},
() => {
clientReactController.abort()
}
)
const { preludeIsEmpty } = await processPrelude(unprocessedPrelude)
return getStaticShellDisallowedDynamicReasons(
workStore,
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
runtimeDynamicValidation
)
} catch (thrownValue) {
// Even if the root errors we still want to report any cache components errors
// that were discovered before the root errored.
let errors: Array<unknown> = getStaticShellDisallowedDynamicReasons(
workStore,
PreludeState.Errored,
runtimeDynamicValidation
)
if (process.env.NEXT_DEBUG_BUILD || process.env.__NEXT_VERBOSE_LOGGING) {
errors.unshift(
'During dynamic validation the root of the page errored. The next logged error is the thrown value. It may be a duplicate of errors reported during the normal development mode render.',
thrownValue
)
}
return errors
}
}
type PrerenderToStreamResult = {
stream: ReadableStream<Uint8Array>
digestErrorsMap: Map<string, DigestedError>
ssrErrors: Array<unknown>
dynamicAccess?: null | Array<DynamicAccess>
collectedRevalidate: number
collectedExpire: number
collectedStale: number
collectedTags: null | string[]
renderResumeDataCache?: RenderResumeDataCache
}
/**
* Determines whether we should generate static flight data.
*/
function shouldGenerateStaticFlightData(workStore: WorkStore): boolean {
const { isStaticGeneration } = workStore
if (!isStaticGeneration) return false
return true
}
async function prerenderToStream(
req: BaseNextRequest,
res: BaseNextResponse,
ctx: AppRenderContext,
metadata: AppPageRenderResultMetadata,
tree: LoaderTree,
fallbackRouteParams: OpaqueFallbackRouteParams | null
): Promise<PrerenderToStreamResult> {
// When prerendering formState is always null. We still include it
// because some shared APIs expect a formState value and this is slightly
// more explicit than making it an optional function argument
const formState = null
const {
assetPrefix,
getDynamicParamFromSegment,
implicitTags,
nonce,
pagePath,
renderOpts,
workStore,
} = ctx
const {
allowEmptyStaticShell = false,
basePath,
buildManifest,
ComponentMod,
crossOrigin,
dev = false,
experimental,
isDebugDynamicAccesses,
nextExport = false,
onInstrumentationRequestError,
page,
reactMaxHeadersLength,
subresourceIntegrityManifest,
cacheComponents,
} = renderOpts
const rootParams = getRootParams(tree, getDynamicParamFromSegment)
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML()
const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
experimental.clientTraceMetadata
)
const polyfills: JSX.IntrinsicElements['script'][] =
buildManifest.polyfillFiles
.filter(
(polyfill) =>
polyfill.endsWith('.js') && !polyfill.endsWith('.module.js')
)
.map((polyfill) => ({
src: `${assetPrefix}/_next/${polyfill}${getAssetQueryString(
ctx,
false
)}`,
integrity: subresourceIntegrityManifest?.[polyfill],
crossOrigin,
noModule: true,
nonce,
}))
const [preinitScripts, bootstrapScript] = getRequiredScripts(
buildManifest,
// Why is assetPrefix optional on renderOpts?
// @TODO make it default empty string on renderOpts and get rid of it from ctx
assetPrefix,
crossOrigin,
subresourceIntegrityManifest,
getAssetQueryString(ctx, true),
nonce,
page
)
const { reactServerErrorsByDigest } = workStore
// We don't report errors during prerendering through our instrumentation hooks
const reportErrors = !experimental.isRoutePPREnabled
function onHTMLRenderRSCError(err: DigestedError, silenceLog: boolean) {
if (reportErrors) {
return onInstrumentationRequestError?.(
err,
req,
createErrorContext(ctx, 'react-server-components'),
silenceLog
)
}
}
const serverComponentsErrorHandler = createReactServerErrorHandler(
dev,
nextExport,
reactServerErrorsByDigest,
onHTMLRenderRSCError
)
function onHTMLRenderSSRError(err: DigestedError) {
if (reportErrors) {
// We don't need to silence logs here. onHTMLRenderSSRError won't be
// called at all if the error was logged before in the RSC error handler.
const silenceLog = false
return onInstrumentationRequestError?.(
err,
req,
createErrorContext(ctx, 'server-rendering'),
silenceLog
)
}
}
const allCapturedErrors: Array<unknown> = []
const htmlRendererErrorHandler = createHTMLErrorHandler(
dev,
nextExport,
reactServerErrorsByDigest,
allCapturedErrors,
onHTMLRenderSSRError
)
let reactServerPrerenderResult: null | ReactServerPrerenderResult = null
const setMetadataHeader = (name: string) => {
metadata.headers ??= {}
metadata.headers[name] = res.getHeader(name)
}
const setHeader = (name: string, value: string | string[]) => {
res.setHeader(name, value)
setMetadataHeader(name)
return res
}
const appendHeader = (name: string, value: string | string[]) => {
if (Array.isArray(value)) {
value.forEach((item) => {
res.appendHeader(name, item)
})
} else {
res.appendHeader(name, value)
}
setMetadataHeader(name)
}
const selectStaleTime = createSelectStaleTime(experimental)
const { clientModules } = getClientReferenceManifest()
let prerenderStore: PrerenderStore | null = null
try {
if (cacheComponents) {
/**
* cacheComponents with PPR
*
* The general approach is to render the RSC stream first allowing any cache reads to resolve.
* Once we have settled all cache reads we restart the render and abort after a single Task.
*
* Unlike with the non PPR case we can't synchronously abort the render when a dynamic API is used
* during the initial render because we need to ensure all caches can be filled as part of the initial Task
* and a synchronous abort might prevent us from filling all caches.
*
* Once the render is complete we allow the SSR render to finish and use a combination of the postponed state
* and the reactServerIsDynamic value to determine how to treat the resulting render
*/
// The prerender controller represents the lifetime of the prerender. It
// will be aborted when a task is complete or a synchronously aborting API
// is called. Notably, during prospective prerenders, this does not
// actually terminate the prerender itself, which will continue until all
// caches are filled.
const initialServerPrerenderController = new AbortController()
// This controller is used to abort the React prerender.
const initialServerReactController = new AbortController()
// This controller represents the lifetime of the React prerender. Its
// signal can be used for any I/O operation to abort the I/O and/or to
// reject, when prerendering aborts. This includes our own hanging
// promises for accessing request data, and for fetch calls. It might be
// replaced in the future by React.cacheSignal(). It's aborted after the
// React controller, so that no pending I/O can register abort listeners
// that are called before React's abort listener is called. This ensures
// that pending I/O is not rejected too early when aborting the prerender.
// Notably, during the prospective prerender, it is different from the
// prerender controller because we don't want to end the React prerender
// until all caches are filled.
const initialServerRenderController = new AbortController()
// The cacheSignal helps us track whether caches are still filling or we are ready
// to cut the render off.
const cacheSignal = new CacheSignal()
let resumeDataCache: RenderResumeDataCache | PrerenderResumeDataCache
let renderResumeDataCache: RenderResumeDataCache | null = null
let prerenderResumeDataCache: PrerenderResumeDataCache | null = null
if (renderOpts.renderResumeDataCache) {
// If a prefilled immutable render resume data cache is provided, e.g.
// when prerendering an optional fallback shell after having prerendered
// pages with defined params, we use this instead of a prerender resume
// data cache.
resumeDataCache = renderResumeDataCache =
renderOpts.renderResumeDataCache
} else {
// Otherwise we create a new mutable prerender resume data cache.
resumeDataCache = prerenderResumeDataCache =
createPrerenderResumeDataCache()
}
const initialServerPayloadPrerenderStore: PrerenderStore = {
type: 'prerender',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
// While this render signal isn't going to be used to abort a React render while getting the RSC payload
// various request data APIs bind to this controller to reject after completion.
renderSignal: initialServerRenderController.signal,
// When we generate the RSC payload we might abort this controller due to sync IO
// but we don't actually care about sync IO in this phase so we use a throw away controller
// that isn't connected to anything
controller: new AbortController(),
// During the initial prerender we need to track all cache reads to ensure
// we render long enough to fill every cache it is possible to visit during
// the final prerender.
cacheSignal,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
}
// We're not going to use the result of this render because the only time it could be used
// is if it completes in a microtask and that's likely very rare for any non-trivial app
const initialServerPayload = await workUnitAsyncStorage.run(
initialServerPayloadPrerenderStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
)
const initialServerPrerenderStore: PrerenderStore = (prerenderStore = {
type: 'prerender',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: initialServerRenderController.signal,
controller: initialServerPrerenderController,
// During the initial prerender we need to track all cache reads to ensure
// we render long enough to fill every cache it is possible to visit during
// the final prerender.
cacheSignal,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
})
const pendingInitialServerResult = workUnitAsyncStorage.run(
initialServerPrerenderStore,
ComponentMod.prerender,
initialServerPayload,
clientModules,
{
filterStackFrame,
onError: (err) => {
const digest = getDigestForWellKnownError(err)
if (digest) {
return digest
}
if (isReactLargeShellError(err)) {
// TODO: Aggregate
console.error(err)
return undefined
}
if (initialServerPrerenderController.signal.aborted) {
// The render aborted before this error was handled which indicates
// the error is caused by unfinished components within the render
return
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
printDebugThrownValueForProspectiveRender(
err,
workStore.route,
Phase.ProspectiveRender
)
}
},
// We don't want to stop rendering until the cacheSignal is complete so we pass
// a different signal to this render call than is used by dynamic APIs to signify
// transitioning out of the prerender environment
signal: initialServerReactController.signal,
}
)
// The listener to abort our own render controller must be added after
// React has added its listener, to ensure that pending I/O is not
// aborted/rejected too early.
initialServerReactController.signal.addEventListener(
'abort',
() => {
initialServerRenderController.abort()
initialServerPrerenderController.abort()
},
{ once: true }
)
// Wait for all caches to be finished filling and for async imports to resolve
trackPendingModules(cacheSignal)
await cacheSignal.cacheReady()
initialServerReactController.abort()
// We don't need to continue the prerender process if we already
// detected invalid dynamic usage in the initial prerender phase.
if (workStore.invalidDynamicUsageError) {
logDisallowedDynamicError(workStore, workStore.invalidDynamicUsageError)
throw new StaticGenBailoutError()
}
let initialServerResult
try {
initialServerResult = await createReactServerPrerenderResult(
pendingInitialServerResult
)
} catch (err) {
if (
initialServerReactController.signal.aborted ||
initialServerPrerenderController.signal.aborted
) {
// These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(
err,
workStore.route,
Phase.ProspectiveRender
)
}
}
if (initialServerResult) {
const initialClientPrerenderController = new AbortController()
const initialClientReactController = new AbortController()
const initialClientRenderController = new AbortController()
const initialClientPrerenderStore: PrerenderStore = {
type: 'prerender-client',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: initialClientRenderController.signal,
controller: initialClientPrerenderController,
// For HTML Generation the only cache tracked activity
// is module loading, which has it's own cache signal
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
}
const prerender = (
require('react-dom/static') as typeof import('react-dom/static')
).prerender
const pendingInitialClientResult = workUnitAsyncStorage.run(
initialClientPrerenderStore,
prerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={initialServerResult.asUnclosingStream()}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
signal: initialClientReactController.signal,
onError: (err) => {
const digest = getDigestForWellKnownError(err)
if (digest) {
return digest
}
if (isReactLargeShellError(err)) {
// TODO: Aggregate
console.error(err)
return undefined
}
if (initialClientReactController.signal.aborted) {
// These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(
err,
workStore.route,
Phase.ProspectiveRender
)
}
},
bootstrapScripts: [bootstrapScript],
}
)
// The listener to abort our own render controller must be added after
// React has added its listener, to ensure that pending I/O is not
// aborted/rejected too early.
initialClientReactController.signal.addEventListener(
'abort',
() => {
initialClientRenderController.abort()
},
{ once: true }
)
pendingInitialClientResult.catch((err) => {
if (
initialClientReactController.signal.aborted ||
isPrerenderInterruptedError(err)
) {
// These are expected errors that might error the prerender. we ignore them.
} else if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
// We don't normally log these errors because we are going to retry anyway but
// it can be useful for debugging Next.js itself to get visibility here when needed
printDebugThrownValueForProspectiveRender(
err,
workStore.route,
Phase.ProspectiveRender
)
}
})
// This is mostly needed for dynamic `import()`s in client components.
// Promises passed to client were already awaited above (assuming that they came from cached functions)
trackPendingModules(cacheSignal)
await cacheSignal.cacheReady()
initialClientReactController.abort()
}
const finalServerReactController = new AbortController()
const finalServerRenderController = new AbortController()
const finalServerPayloadPrerenderStore: PrerenderStore = {
type: 'prerender',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
// While this render signal isn't going to be used to abort a React render while getting the RSC payload
// various request data APIs bind to this controller to reject after completion.
renderSignal: finalServerRenderController.signal,
// When we generate the RSC payload we might abort this controller due to sync IO
// but we don't actually care about sync IO in this phase so we use a throw away controller
// that isn't connected to anything
controller: new AbortController(),
// All caches we could read must already be filled so no tracking is necessary
cacheSignal: null,
dynamicTracking: null,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
}
const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
finalServerPayloadPrerenderStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
)
const serverDynamicTracking = createDynamicTrackingState(
isDebugDynamicAccesses
)
let serverIsDynamic = false
const finalServerPrerenderStore: PrerenderStore = (prerenderStore = {
type: 'prerender',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: finalServerRenderController.signal,
controller: finalServerReactController,
// All caches we could read must already be filled so no tracking is necessary
cacheSignal: null,
dynamicTracking: serverDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
})
let prerenderIsPending = true
const reactServerResult = (reactServerPrerenderResult =
await createReactServerPrerenderResult(
prerenderAndAbortInSequentialTasks(
async () => {
const pendingPrerenderResult = workUnitAsyncStorage.run(
// The store to scope
finalServerPrerenderStore,
// The function to run
ComponentMod.prerender,
// ... the arguments for the function to run
finalAttemptRSCPayload,
clientModules,
{
filterStackFrame,
onError: (err: unknown) => {
return serverComponentsErrorHandler(err)
},
signal: finalServerReactController.signal,
}
)
// The listener to abort our own render controller must be added
// after React has added its listener, to ensure that pending I/O
// is not aborted/rejected too early.
finalServerReactController.signal.addEventListener(
'abort',
() => {
finalServerRenderController.abort()
},
{ once: true }
)
const prerenderResult = await pendingPrerenderResult
prerenderIsPending = false
return prerenderResult
},
() => {
if (finalServerReactController.signal.aborted) {
// If the server controller is already aborted we must have called something
// that required aborting the prerender synchronously such as with new Date()
serverIsDynamic = true
return
}
if (prerenderIsPending) {
// If prerenderIsPending then we have blocked for longer than a Task and we assume
// there is something unfinished.
serverIsDynamic = true
}
finalServerReactController.abort()
}
)
))
const clientDynamicTracking = createDynamicTrackingState(
isDebugDynamicAccesses
)
const finalClientReactController = new AbortController()
const finalClientRenderController = new AbortController()
const finalClientPrerenderStore: PrerenderStore = {
type: 'prerender-client',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
renderSignal: finalClientRenderController.signal,
controller: finalClientReactController,
// No APIs require a cacheSignal through the workUnitStore during the HTML prerender
cacheSignal: null,
dynamicTracking: clientDynamicTracking,
allowEmptyStaticShell,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
renderResumeDataCache,
hmrRefreshHash: undefined,
}
let dynamicValidation = createDynamicValidationState()
const prerender = (
require('react-dom/static') as typeof import('react-dom/static')
).prerender
let { prelude: unprocessedPrelude, postponed } =
await prerenderAndAbortInSequentialTasks(
() => {
const pendingFinalClientResult = workUnitAsyncStorage.run(
finalClientPrerenderStore,
prerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={reactServerResult.asUnclosingStream()}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
signal: finalClientReactController.signal,
onError: (err: unknown, errorInfo: ErrorInfo) => {
if (
isPrerenderInterruptedError(err) ||
finalClientReactController.signal.aborted
) {
const componentStack: string | undefined = (
errorInfo as any
).componentStack
if (typeof componentStack === 'string') {
trackAllowedDynamicAccess(
workStore,
componentStack,
dynamicValidation,
clientDynamicTracking
)
}
return
}
return htmlRendererErrorHandler(err, errorInfo)
},
onHeaders: (headers: Headers) => {
headers.forEach((value, key) => {
appendHeader(key, value)
})
},
maxHeadersLength: reactMaxHeadersLength,
bootstrapScripts: [bootstrapScript],
}
)
// The listener to abort our own render controller must be added
// after React has added its listener, to ensure that pending I/O is
// not aborted/rejected too early.
finalClientReactController.signal.addEventListener(
'abort',
() => {
finalClientRenderController.abort()
},
{ once: true }
)
return pendingFinalClientResult
},
() => {
finalClientReactController.abort()
}
)
const { prelude, preludeIsEmpty } =
await processPrelude(unprocessedPrelude)
// If we've disabled throwing on empty static shell, then we don't need to
// track any dynamic access that occurs above the suspense boundary because
// we'll do so in the route shell.
if (!allowEmptyStaticShell) {
throwIfDisallowedDynamic(
workStore,
preludeIsEmpty ? PreludeState.Empty : PreludeState.Full,
dynamicValidation,
serverDynamicTracking
)
}
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
const flightData = await streamToBuffer(reactServerResult.asStream())
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
flightData,
finalServerPrerenderStore,
ComponentMod,
renderOpts
)
if (serverIsDynamic) {
// Dynamic case
// We will always need to perform a "resume" render of some kind when this route is accessed
// because the RSC data itself is dynamic. We determine if there are any HTML holes or not
// but generally this is a "partial" prerender in that there will be a per-request compute
// concatenated to the static shell.
if (postponed != null) {
// Dynamic HTML case
metadata.postponed = await getDynamicHTMLPostponedState(
postponed,
preludeIsEmpty
? DynamicHTMLPreludeState.Empty
: DynamicHTMLPreludeState.Full,
fallbackRouteParams,
resumeDataCache,
cacheComponents
)
} else {
// Dynamic Data case
metadata.postponed = await getDynamicDataPostponedState(
resumeDataCache,
cacheComponents
)
}
reactServerResult.consume()
return {
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML,
getServerInsertedMetadata,
}),
dynamicAccess: consumeDynamicAccess(
serverDynamicTracking,
clientDynamicTracking
),
// TODO: Should this include the SSR pass?
collectedRevalidate: finalServerPrerenderStore.revalidate,
collectedExpire: finalServerPrerenderStore.expire,
collectedStale: selectStaleTime(finalServerPrerenderStore.stale),
collectedTags: finalServerPrerenderStore.tags,
renderResumeDataCache: createRenderResumeDataCache(resumeDataCache),
}
} else {
// Static case
// We will not perform resumption per request. The result can be served statically to the requestor
// and if there was anything dynamic it will only be rendered in the browser.
if (workStore.forceDynamic) {
throw new StaticGenBailoutError(
'Invariant: a Page with `dynamic = "force-dynamic"` did not trigger the dynamic pathway. This is a bug in Next.js'
)
}
let htmlStream = prelude
if (postponed != null) {
// We postponed but nothing dynamic was used. We resume the render now and immediately abort it
// so we can set all the postponed boundaries to client render mode before we store the HTML response
const resume = (
require('react-dom/server') as typeof import('react-dom/server')
).resume
// We don't actually want to render anything so we just pass a stream
// that never resolves. The resume call is going to abort immediately anyway
const foreverStream = new ReadableStream<Uint8Array>()
const resumeStream = await resume(
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={foreverStream}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={() => {}}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
JSON.parse(JSON.stringify(postponed)),
{
signal: createRenderInBrowserAbortSignal(),
onError: htmlRendererErrorHandler,
nonce,
}
)
// First we write everything from the prerender, then we write everything from the aborted resume render
htmlStream = chainStreams(prelude, resumeStream)
}
let finalStream
const hasFallbackRouteParams =
fallbackRouteParams && fallbackRouteParams.size > 0
if (hasFallbackRouteParams) {
// This is a "static fallback" prerender: although the page didn't
// access any runtime params in a Server Component, it may have
// accessed a runtime param in a client segment.
//
// TODO: If there were no client segments, we can use the fully static
// path instead.
//
// Rather than use a dynamic server resume to fill in the params,
// we can rely on the client to parse the params from the URL and use
// that to hydrate the page.
//
// Send an empty InitialRSCPayload to the server component renderer
// The data will be fetched by the client instead.
// TODO: In the future, rather than defer the entire hydration payload
// to be fetched by the client, we should only defer the client
// segments, since those are the only ones whose data is not complete.
const emptyReactServerResult =
await createReactServerPrerenderResultFromRender(
ComponentMod.renderToReadableStream([], clientModules, {
filterStackFrame,
onError: serverComponentsErrorHandler,
})
)
finalStream = await continueStaticFallbackPrerender(htmlStream, {
inlinedDataStream: createInlinedDataReadableStream(
emptyReactServerResult.consumeAsStream(),
nonce,
formState
),
getServerInsertedHTML,
getServerInsertedMetadata,
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
})
} else {
// Normal static prerender case, no fallback param handling needed
finalStream = await continueStaticPrerender(htmlStream, {
inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consumeAsStream(),
nonce,
formState
),
getServerInsertedHTML,
getServerInsertedMetadata,
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
})
}
return {
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: finalStream,
dynamicAccess: consumeDynamicAccess(
serverDynamicTracking,
clientDynamicTracking
),
// TODO: Should this include the SSR pass?
collectedRevalidate: finalServerPrerenderStore.revalidate,
collectedExpire: finalServerPrerenderStore.expire,
collectedStale: selectStaleTime(finalServerPrerenderStore.stale),
collectedTags: finalServerPrerenderStore.tags,
renderResumeDataCache: createRenderResumeDataCache(resumeDataCache),
}
}
} else if (experimental.isRoutePPREnabled) {
// We're statically generating with PPR and need to do dynamic tracking
let dynamicTracking = createDynamicTrackingState(isDebugDynamicAccesses)
const prerenderResumeDataCache = createPrerenderResumeDataCache()
const reactServerPrerenderStore: PrerenderStore = (prerenderStore = {
type: 'prerender-ppr',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
dynamicTracking,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
})
const RSCPayload = await workUnitAsyncStorage.run(
reactServerPrerenderStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
)
const reactServerResult = (reactServerPrerenderResult =
await createReactServerPrerenderResultFromRender(
workUnitAsyncStorage.run(
reactServerPrerenderStore,
ComponentMod.renderToReadableStream,
// ... the arguments for the function to run
RSCPayload,
clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
}
)
))
const ssrPrerenderStore: PrerenderStore = {
type: 'prerender-ppr',
phase: 'render',
rootParams,
fallbackRouteParams,
implicitTags,
dynamicTracking,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
prerenderResumeDataCache,
}
const prerender = (
require('react-dom/static') as typeof import('react-dom/static')
).prerender
const { prelude: unprocessedPrelude, postponed } =
await workUnitAsyncStorage.run(
ssrPrerenderStore,
prerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={reactServerResult.asUnclosingStream()}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
onError: htmlRendererErrorHandler,
onHeaders: (headers: Headers) => {
headers.forEach((value, key) => {
appendHeader(key, value)
})
},
maxHeadersLength: reactMaxHeadersLength,
bootstrapScripts: [bootstrapScript],
}
)
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
// After awaiting here we've waited for the entire RSC render to complete. Crucially this means
// that when we detect whether we've used dynamic APIs below we know we'll have picked up even
// parts of the React Server render that might not be used in the SSR render.
const flightData = await streamToBuffer(reactServerResult.asStream())
if (shouldGenerateStaticFlightData(workStore)) {
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
flightData,
ssrPrerenderStore,
ComponentMod,
renderOpts
)
}
const { prelude, preludeIsEmpty } =
await processPrelude(unprocessedPrelude)
/**
* When prerendering there are three outcomes to consider
*
* Dynamic HTML: The prerender has dynamic holes (caused by using Next.js Dynamic Rendering APIs)
* We will need to resume this result when requests are handled and we don't include
* any server inserted HTML or inlined flight data in the static HTML
*
* Dynamic Data: The prerender has no dynamic holes but dynamic APIs were used. We will not
* resume this render when requests are handled but we will generate new inlined
* flight data since it is dynamic and differences may end up reconciling on the client
*
* Static: The prerender has no dynamic holes and no dynamic APIs were used. We statically encode
* all server inserted HTML and flight data
*/
// First we check if we have any dynamic holes in our HTML prerender
if (accessedDynamicData(dynamicTracking.dynamicAccesses)) {
if (postponed != null) {
// Dynamic HTML case.
metadata.postponed = await getDynamicHTMLPostponedState(
postponed,
preludeIsEmpty
? DynamicHTMLPreludeState.Empty
: DynamicHTMLPreludeState.Full,
fallbackRouteParams,
prerenderResumeDataCache,
cacheComponents
)
} else {
// Dynamic Data case.
metadata.postponed = await getDynamicDataPostponedState(
prerenderResumeDataCache,
cacheComponents
)
}
// Regardless of whether this is the Dynamic HTML or Dynamic Data case we need to ensure we include
// server inserted html in the static response because the html that is part of the prerender may depend on it
// It is possible in the set of stream transforms for Dynamic HTML vs Dynamic Data may differ but currently both states
// require the same set so we unify the code path here
reactServerResult.consume()
return {
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML,
getServerInsertedMetadata,
}),
dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass?
collectedRevalidate: reactServerPrerenderStore.revalidate,
collectedExpire: reactServerPrerenderStore.expire,
collectedStale: selectStaleTime(reactServerPrerenderStore.stale),
collectedTags: reactServerPrerenderStore.tags,
}
} else if (fallbackRouteParams && fallbackRouteParams.size > 0) {
// Rendering the fallback case.
metadata.postponed = await getDynamicDataPostponedState(
prerenderResumeDataCache,
cacheComponents
)
return {
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueDynamicPrerender(prelude, {
getServerInsertedHTML,
getServerInsertedMetadata,
}),
dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass?
collectedRevalidate: reactServerPrerenderStore.revalidate,
collectedExpire: reactServerPrerenderStore.expire,
collectedStale: selectStaleTime(reactServerPrerenderStore.stale),
collectedTags: reactServerPrerenderStore.tags,
}
} else {
// Static case
// We still have not used any dynamic APIs. At this point we can produce an entirely static prerender response
if (workStore.forceDynamic) {
throw new StaticGenBailoutError(
'Invariant: a Page with `dynamic = "force-dynamic"` did not trigger the dynamic pathway. This is a bug in Next.js'
)
}
let htmlStream = prelude
if (postponed != null) {
// We postponed but nothing dynamic was used. We resume the render now and immediately abort it
// so we can set all the postponed boundaries to client render mode before we store the HTML response
const resume = (
require('react-dom/server') as typeof import('react-dom/server')
).resume
// We don't actually want to render anything so we just pass a stream
// that never resolves. The resume call is going to abort immediately anyway
const foreverStream = new ReadableStream<Uint8Array>()
const resumeStream = await resume(
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={foreverStream}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={() => {}}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
JSON.parse(JSON.stringify(postponed)),
{
signal: createRenderInBrowserAbortSignal(),
onError: htmlRendererErrorHandler,
nonce,
}
)
// First we write everything from the prerender, then we write everything from the aborted resume render
htmlStream = chainStreams(prelude, resumeStream)
}
return {
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueStaticPrerender(htmlStream, {
inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consumeAsStream(),
nonce,
formState
),
getServerInsertedHTML,
getServerInsertedMetadata,
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
}),
dynamicAccess: dynamicTracking.dynamicAccesses,
// TODO: Should this include the SSR pass?
collectedRevalidate: reactServerPrerenderStore.revalidate,
collectedExpire: reactServerPrerenderStore.expire,
collectedStale: selectStaleTime(reactServerPrerenderStore.stale),
collectedTags: reactServerPrerenderStore.tags,
}
}
} else {
const prerenderLegacyStore: PrerenderStore = (prerenderStore = {
type: 'prerender-legacy',
phase: 'render',
rootParams,
implicitTags,
revalidate: INFINITE_CACHE,
expire: INFINITE_CACHE,
stale: INFINITE_CACHE,
tags: [...implicitTags.tags],
})
// This is a regular static generation. We don't do dynamic tracking because we rely on
// the old-school dynamic error handling to bail out of static generation
const RSCPayload = await workUnitAsyncStorage.run(
prerenderLegacyStore,
getRSCPayload,
tree,
ctx,
res.statusCode === 404
)
const reactServerResult = (reactServerPrerenderResult =
await createReactServerPrerenderResultFromRender(
workUnitAsyncStorage.run(
prerenderLegacyStore,
ComponentMod.renderToReadableStream,
RSCPayload,
clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
}
)
))
const renderToReadableStream = (
require('react-dom/server') as typeof import('react-dom/server')
).renderToReadableStream
const htmlStream = await workUnitAsyncStorage.run(
prerenderLegacyStore,
renderToReadableStream,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={reactServerResult.asUnclosingStream()}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
nonce={nonce}
images={ctx.renderOpts.images}
/>,
{
onError: htmlRendererErrorHandler,
nonce,
bootstrapScripts: [bootstrapScript],
}
)
if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer(reactServerResult.asStream())
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
flightData,
prerenderLegacyStore,
ComponentMod,
renderOpts
)
}
const getServerInsertedHTML = makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: allCapturedErrors,
basePath,
tracingMetadata: tracingMetadata,
})
return {
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueFizzStream(htmlStream, {
inlinedDataStream: createInlinedDataReadableStream(
reactServerResult.consumeAsStream(),
nonce,
formState
),
isStaticGeneration: true,
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
getServerInsertedHTML,
getServerInsertedMetadata,
}),
// TODO: Should this include the SSR pass?
collectedRevalidate: prerenderLegacyStore.revalidate,
collectedExpire: prerenderLegacyStore.expire,
collectedStale: selectStaleTime(prerenderLegacyStore.stale),
collectedTags: prerenderLegacyStore.tags,
}
}
} catch (err) {
if (
isStaticGenBailoutError(err) ||
(typeof err === 'object' &&
err !== null &&
'message' in err &&
typeof err.message === 'string' &&
err.message.includes(
'https://nextjs.org/docs/advanced-features/static-html-export'
))
) {
// Ensure that "next dev" prints the red error overlay
throw err
}
// If this is a static generation error, we need to throw it so that it
// can be handled by the caller if we're in static generation mode.
if (isDynamicServerError(err)) {
throw err
}
// If a bailout made it to this point, it means it wasn't wrapped inside
// a suspense boundary.
const shouldBailoutToCSR = isBailoutToCSRError(err)
if (shouldBailoutToCSR) {
const stack = getStackWithoutErrorMessage(err)
error(
`${err.reason} should be wrapped in a suspense boundary at page "${pagePath}". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n${stack}`
)
throw err
}
// If we errored when we did not have an RSC stream to read from. This is
// not just a render error, we need to throw early.
if (reactServerPrerenderResult === null) {
throw err
}
let errorType: MetadataErrorType | 'redirect' | undefined
if (isHTTPAccessFallbackError(err)) {
res.statusCode = getAccessFallbackHTTPStatus(err)
metadata.statusCode = res.statusCode
errorType = getAccessFallbackErrorTypeByStatus(res.statusCode)
} else if (isRedirectError(err)) {
errorType = 'redirect'
res.statusCode = getRedirectStatusCodeFromError(err)
metadata.statusCode = res.statusCode
const redirectUrl = addPathPrefix(getURLFromRedirectError(err), basePath)
setHeader('location', redirectUrl)
} else if (!shouldBailoutToCSR) {
res.statusCode = 500
metadata.statusCode = res.statusCode
}
const [errorPreinitScripts, errorBootstrapScript] = getRequiredScripts(
buildManifest,
assetPrefix,
crossOrigin,
subresourceIntegrityManifest,
getAssetQueryString(ctx, false),
nonce,
'/_not-found/page'
)
const prerenderLegacyStore: PrerenderStore = (prerenderStore = {
type: 'prerender-legacy',
phase: 'render',
rootParams,
implicitTags: implicitTags,
revalidate:
typeof prerenderStore?.revalidate !== 'undefined'
? prerenderStore.revalidate
: INFINITE_CACHE,
expire:
typeof prerenderStore?.expire !== 'undefined'
? prerenderStore.expire
: INFINITE_CACHE,
stale:
typeof prerenderStore?.stale !== 'undefined'
? prerenderStore.stale
: INFINITE_CACHE,
tags: [...(prerenderStore?.tags || implicitTags.tags)],
})
const errorRSCPayload = await workUnitAsyncStorage.run(
prerenderLegacyStore,
getErrorRSCPayload,
tree,
ctx,
reactServerErrorsByDigest.has((err as any).digest) ? undefined : err,
errorType
)
const errorServerStream = workUnitAsyncStorage.run(
prerenderLegacyStore,
ComponentMod.renderToReadableStream,
errorRSCPayload,
clientModules,
{
filterStackFrame,
onError: serverComponentsErrorHandler,
}
)
try {
// TODO we should use the same prerender semantics that we initially rendered
// with in this case too. The only reason why this is ok atm is because it's essentially
// an empty page and no user code runs.
const fizzStream = await workUnitAsyncStorage.run(
prerenderLegacyStore,
renderToInitialFizzStream,
{
ReactDOMServer:
require('react-dom/server') as typeof import('react-dom/server'),
element: (
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<ErrorApp
reactServerStream={errorServerStream}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts}
nonce={nonce}
images={ctx.renderOpts.images}
/>
),
streamOptions: {
nonce,
// Include hydration scripts in the HTML
bootstrapScripts: [errorBootstrapScript],
formState,
},
}
)
if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer(
reactServerPrerenderResult.asStream()
)
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
flightData,
prerenderLegacyStore,
ComponentMod,
renderOpts
)
}
// This is intentionally using the readable datastream from the main
// render rather than the flight data from the error page render
const flightStream = reactServerPrerenderResult.consumeAsStream()
return {
// Returning the error that was thrown so it can be used to handle
// the response in the caller.
digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors,
stream: await continueFizzStream(fizzStream, {
inlinedDataStream: createInlinedDataReadableStream(
flightStream,
nonce,
formState
),
isStaticGeneration: true,
isBuildTimePrerendering:
ctx.workStore.isBuildTimePrerendering === true,
buildId: ctx.workStore.buildId,
getServerInsertedHTML: makeGetServerInsertedHTML({
polyfills,
renderServerInsertedHTML,
serverCapturedErrors: [],
basePath,
tracingMetadata: tracingMetadata,
}),
getServerInsertedMetadata,
validateRootLayout: dev,
}),
dynamicAccess: null,
collectedRevalidate:
prerenderStore !== null ? prerenderStore.revalidate : INFINITE_CACHE,
collectedExpire:
prerenderStore !== null ? prerenderStore.expire : INFINITE_CACHE,
collectedStale: selectStaleTime(
prerenderStore !== null ? prerenderStore.stale : INFINITE_CACHE
),
collectedTags: prerenderStore !== null ? prerenderStore.tags : null,
}
} catch (finalErr: any) {
if (
process.env.NODE_ENV === 'development' &&
isHTTPAccessFallbackError(finalErr)
) {
const { bailOnRootNotFound } =
require('../../client/components/dev-root-http-access-fallback-boundary') as typeof import('../../client/components/dev-root-http-access-fallback-boundary')
bailOnRootNotFound()
}
throw finalErr
}
}
}
const getGlobalErrorStyles = async (
tree: LoaderTree,
ctx: AppRenderContext
): Promise<{
GlobalError: GlobalErrorComponent
styles: ReactNode | undefined
}> => {
const {
modules: { 'global-error': globalErrorModule },
} = parseLoaderTree(tree)
const {
componentMod: { createElement },
} = ctx
const GlobalErrorComponent: GlobalErrorComponent =
ctx.componentMod.GlobalError
let globalErrorStyles
if (globalErrorModule) {
const [, styles] = await createComponentStylesAndScripts({
ctx,
filePath: globalErrorModule[1],
getComponent: globalErrorModule[0],
injectedCSS: new Set(),
injectedJS: new Set(),
})
globalErrorStyles = styles
}
if (ctx.renderOpts.dev) {
const dir =
(process.env.NEXT_RUNTIME === 'edge'
? process.env.__NEXT_EDGE_PROJECT_DIR
: ctx.renderOpts.dir) || ''
const globalErrorModulePath = normalizeConventionFilePath(
dir,
globalErrorModule?.[1]
)
if (globalErrorModulePath) {
const SegmentViewNode = ctx.componentMod.SegmentViewNode
globalErrorStyles =
// This will be rendered next to GlobalError component under ErrorBoundary,
// it requires a key to avoid React warning about duplicate keys.
createElement(
SegmentViewNode,
{
key: 'ge-svn',
type: 'global-error',
pagePath: globalErrorModulePath,
},
globalErrorStyles
)
}
}
return {
GlobalError: GlobalErrorComponent,
styles: globalErrorStyles,
}
}
function createSelectStaleTime(experimental: ExperimentalConfig) {
return (stale: number) =>
stale === INFINITE_CACHE &&
typeof experimental.staleTimes?.static === 'number'
? experimental.staleTimes.static
: stale
}
async function collectSegmentData(
fullPageDataBuffer: Buffer,
prerenderStore: PrerenderStore,
ComponentMod: AppPageModule,
renderOpts: RenderOpts
): Promise<Map<string, Buffer> | undefined> {
// Per-segment prefetch data
//
// All of the segments for a page are generated simultaneously, including
// during revalidations. This is to ensure consistency, because it's
// possible for a mismatch between a layout and page segment can cause the
// client to error during rendering. We want to preserve the ability of the
// client to recover from such a mismatch by re-requesting all the segments
// to get a consistent view of the page.
//
// For performance, we reuse the Flight output that was created when
// generating the initial page HTML. The Flight stream for the whole page is
// decomposed into a separate stream per segment.
const { clientModules, edgeRscModuleMapping, rscModuleMapping } =
getClientReferenceManifest()
// Manifest passed to the Flight client for reading the full-page Flight
// stream. Based off similar code in use-cache-wrapper.ts.
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
const serverConsumerManifest = {
// moduleLoading must be null because we don't want to trigger preloads of ClientReferences
// to be added to the consumer. Instead, we'll wait for any ClientReference to be emitted
// which themselves will handle the preloading.
moduleLoading: null,
moduleMap: isEdgeRuntime ? edgeRscModuleMapping : rscModuleMapping,
serverModuleMap: getServerModuleMap(),
}
const selectStaleTime = createSelectStaleTime(renderOpts.experimental)
const staleTime = selectStaleTime(prerenderStore.stale)
return await ComponentMod.collectSegmentData(
renderOpts.cacheComponents,
fullPageDataBuffer,
staleTime,
clientModules,
serverConsumerManifest
)
}
function isBypassingCachesInDev(
renderOpts: RenderOpts,
requestStore: RequestStore
): boolean {
return (
process.env.NODE_ENV === 'development' &&
!!renderOpts.dev &&
requestStore.headers.get('cache-control') === 'no-cache'
)
}
function WarnForBypassCachesInDev({ route }: { route: string }) {
warnOnce(
`Route ${route} is rendering with server caches disabled. For this navigation, Component Metadata in React DevTools will not accurately reflect what is statically prerenderable and runtime prefetchable. See more info here: https://nextjs.org/docs/messages/cache-bypass-in-dev`
)
return null
}
function nodeStreamFromReadableStream<T>(stream: ReadableStream<T>) {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'nodeStreamFromReadableStream cannot be used in the edge runtime'
)
} else {
const reader = stream.getReader()
const { Readable } = require('node:stream') as typeof import('node:stream')
return new Readable({
read() {
reader
.read()
.then(({ done, value }) => {
if (done) {
this.push(null)
} else {
this.push(value)
}
})
.catch((err) => this.destroy(err))
},
})
}
}
function createNodeStreamFromChunks(
partialChunks: Array<Uint8Array>,
allChunks: Array<Uint8Array>,
signal: AbortSignal
): Readable {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'createNodeStreamFromChunks cannot be used in the edge runtime'
)
} else {
const { Readable } = require('node:stream') as typeof import('node:stream')
let nextIndex = 0
const readable = new Readable({
read() {
while (nextIndex < partialChunks.length) {
this.push(partialChunks[nextIndex])
nextIndex++
}
},
})
signal.addEventListener(
'abort',
() => {
// Flush any remaining chunks from the original set
while (nextIndex < partialChunks.length) {
readable.push(partialChunks[nextIndex])
nextIndex++
}
// Flush all chunks since we're now aborted and can't schedule
// any new work but these chunks might unblock debugInfo
while (nextIndex < allChunks.length) {
readable.push(allChunks[nextIndex])
nextIndex++
}
setImmediate(() => {
readable.push(null)
})
},
{ once: true }
)
return readable
}
}
|