vinext 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/dist/build/static-export.d.ts +78 -0
  4. package/dist/build/static-export.d.ts.map +1 -0
  5. package/dist/build/static-export.js +553 -0
  6. package/dist/build/static-export.js.map +1 -0
  7. package/dist/check.d.ts +52 -0
  8. package/dist/check.d.ts.map +1 -0
  9. package/dist/check.js +483 -0
  10. package/dist/check.js.map +1 -0
  11. package/dist/cli.d.ts +15 -0
  12. package/dist/cli.d.ts.map +1 -0
  13. package/dist/cli.js +565 -0
  14. package/dist/cli.js.map +1 -0
  15. package/dist/client/entry.d.ts +2 -0
  16. package/dist/client/entry.d.ts.map +1 -0
  17. package/dist/client/entry.js +85 -0
  18. package/dist/client/entry.js.map +1 -0
  19. package/dist/cloudflare/index.d.ts +8 -0
  20. package/dist/cloudflare/index.d.ts.map +1 -0
  21. package/dist/cloudflare/index.js +8 -0
  22. package/dist/cloudflare/index.js.map +1 -0
  23. package/dist/cloudflare/kv-cache-handler.d.ts +68 -0
  24. package/dist/cloudflare/kv-cache-handler.d.ts.map +1 -0
  25. package/dist/cloudflare/kv-cache-handler.js +304 -0
  26. package/dist/cloudflare/kv-cache-handler.js.map +1 -0
  27. package/dist/cloudflare/tpr.d.ts +78 -0
  28. package/dist/cloudflare/tpr.d.ts.map +1 -0
  29. package/dist/cloudflare/tpr.js +672 -0
  30. package/dist/cloudflare/tpr.js.map +1 -0
  31. package/dist/config/config-matchers.d.ts +106 -0
  32. package/dist/config/config-matchers.d.ts.map +1 -0
  33. package/dist/config/config-matchers.js +499 -0
  34. package/dist/config/config-matchers.js.map +1 -0
  35. package/dist/config/next-config.d.ts +153 -0
  36. package/dist/config/next-config.d.ts.map +1 -0
  37. package/dist/config/next-config.js +274 -0
  38. package/dist/config/next-config.js.map +1 -0
  39. package/dist/deploy.d.ts +87 -0
  40. package/dist/deploy.d.ts.map +1 -0
  41. package/dist/deploy.js +644 -0
  42. package/dist/deploy.js.map +1 -0
  43. package/dist/index.d.ts +156 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +3287 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/init.d.ts +55 -0
  48. package/dist/init.d.ts.map +1 -0
  49. package/dist/init.js +201 -0
  50. package/dist/init.js.map +1 -0
  51. package/dist/routing/app-router.d.ts +96 -0
  52. package/dist/routing/app-router.d.ts.map +1 -0
  53. package/dist/routing/app-router.js +815 -0
  54. package/dist/routing/app-router.js.map +1 -0
  55. package/dist/routing/pages-router.d.ts +52 -0
  56. package/dist/routing/pages-router.d.ts.map +1 -0
  57. package/dist/routing/pages-router.js +239 -0
  58. package/dist/routing/pages-router.js.map +1 -0
  59. package/dist/server/api-handler.d.ts +18 -0
  60. package/dist/server/api-handler.d.ts.map +1 -0
  61. package/dist/server/api-handler.js +169 -0
  62. package/dist/server/api-handler.js.map +1 -0
  63. package/dist/server/app-dev-server.d.ts +42 -0
  64. package/dist/server/app-dev-server.d.ts.map +1 -0
  65. package/dist/server/app-dev-server.js +2718 -0
  66. package/dist/server/app-dev-server.js.map +1 -0
  67. package/dist/server/app-router-entry.d.ts +18 -0
  68. package/dist/server/app-router-entry.d.ts.map +1 -0
  69. package/dist/server/app-router-entry.js +34 -0
  70. package/dist/server/app-router-entry.js.map +1 -0
  71. package/dist/server/dev-server.d.ts +40 -0
  72. package/dist/server/dev-server.d.ts.map +1 -0
  73. package/dist/server/dev-server.js +758 -0
  74. package/dist/server/dev-server.js.map +1 -0
  75. package/dist/server/html.d.ts +22 -0
  76. package/dist/server/html.d.ts.map +1 -0
  77. package/dist/server/html.js +29 -0
  78. package/dist/server/html.js.map +1 -0
  79. package/dist/server/image-optimization.d.ts +56 -0
  80. package/dist/server/image-optimization.d.ts.map +1 -0
  81. package/dist/server/image-optimization.js +103 -0
  82. package/dist/server/image-optimization.js.map +1 -0
  83. package/dist/server/instrumentation.d.ts +68 -0
  84. package/dist/server/instrumentation.d.ts.map +1 -0
  85. package/dist/server/instrumentation.js +90 -0
  86. package/dist/server/instrumentation.js.map +1 -0
  87. package/dist/server/isr-cache.d.ts +61 -0
  88. package/dist/server/isr-cache.d.ts.map +1 -0
  89. package/dist/server/isr-cache.js +134 -0
  90. package/dist/server/isr-cache.js.map +1 -0
  91. package/dist/server/metadata-routes.d.ts +103 -0
  92. package/dist/server/metadata-routes.d.ts.map +1 -0
  93. package/dist/server/metadata-routes.js +270 -0
  94. package/dist/server/metadata-routes.js.map +1 -0
  95. package/dist/server/middleware.d.ts +77 -0
  96. package/dist/server/middleware.d.ts.map +1 -0
  97. package/dist/server/middleware.js +228 -0
  98. package/dist/server/middleware.js.map +1 -0
  99. package/dist/server/prod-server.d.ts +78 -0
  100. package/dist/server/prod-server.d.ts.map +1 -0
  101. package/dist/server/prod-server.js +712 -0
  102. package/dist/server/prod-server.js.map +1 -0
  103. package/dist/shims/amp.d.ts +17 -0
  104. package/dist/shims/amp.d.ts.map +1 -0
  105. package/dist/shims/amp.js +21 -0
  106. package/dist/shims/amp.js.map +1 -0
  107. package/dist/shims/app.d.ts +12 -0
  108. package/dist/shims/app.d.ts.map +1 -0
  109. package/dist/shims/app.js +2 -0
  110. package/dist/shims/app.js.map +1 -0
  111. package/dist/shims/cache-runtime.d.ts +68 -0
  112. package/dist/shims/cache-runtime.d.ts.map +1 -0
  113. package/dist/shims/cache-runtime.js +437 -0
  114. package/dist/shims/cache-runtime.js.map +1 -0
  115. package/dist/shims/cache.d.ts +243 -0
  116. package/dist/shims/cache.d.ts.map +1 -0
  117. package/dist/shims/cache.js +415 -0
  118. package/dist/shims/cache.js.map +1 -0
  119. package/dist/shims/client-only.d.ts +18 -0
  120. package/dist/shims/client-only.d.ts.map +1 -0
  121. package/dist/shims/client-only.js +18 -0
  122. package/dist/shims/client-only.js.map +1 -0
  123. package/dist/shims/config.d.ts +27 -0
  124. package/dist/shims/config.d.ts.map +1 -0
  125. package/dist/shims/config.js +30 -0
  126. package/dist/shims/config.js.map +1 -0
  127. package/dist/shims/constants.d.ts +13 -0
  128. package/dist/shims/constants.d.ts.map +1 -0
  129. package/dist/shims/constants.js +13 -0
  130. package/dist/shims/constants.js.map +1 -0
  131. package/dist/shims/document.d.ts +33 -0
  132. package/dist/shims/document.d.ts.map +1 -0
  133. package/dist/shims/document.js +32 -0
  134. package/dist/shims/document.js.map +1 -0
  135. package/dist/shims/dynamic.d.ts +33 -0
  136. package/dist/shims/dynamic.d.ts.map +1 -0
  137. package/dist/shims/dynamic.js +148 -0
  138. package/dist/shims/dynamic.js.map +1 -0
  139. package/dist/shims/error-boundary.d.ts +33 -0
  140. package/dist/shims/error-boundary.d.ts.map +1 -0
  141. package/dist/shims/error-boundary.js +88 -0
  142. package/dist/shims/error-boundary.js.map +1 -0
  143. package/dist/shims/error.d.ts +16 -0
  144. package/dist/shims/error.d.ts.map +1 -0
  145. package/dist/shims/error.js +45 -0
  146. package/dist/shims/error.js.map +1 -0
  147. package/dist/shims/fetch-cache.d.ts +61 -0
  148. package/dist/shims/fetch-cache.d.ts.map +1 -0
  149. package/dist/shims/fetch-cache.js +307 -0
  150. package/dist/shims/fetch-cache.js.map +1 -0
  151. package/dist/shims/font-google.d.ts +122 -0
  152. package/dist/shims/font-google.d.ts.map +1 -0
  153. package/dist/shims/font-google.js +387 -0
  154. package/dist/shims/font-google.js.map +1 -0
  155. package/dist/shims/font-local.d.ts +61 -0
  156. package/dist/shims/font-local.d.ts.map +1 -0
  157. package/dist/shims/font-local.js +303 -0
  158. package/dist/shims/font-local.js.map +1 -0
  159. package/dist/shims/form.d.ts +30 -0
  160. package/dist/shims/form.d.ts.map +1 -0
  161. package/dist/shims/form.js +78 -0
  162. package/dist/shims/form.js.map +1 -0
  163. package/dist/shims/head-state.d.ts +11 -0
  164. package/dist/shims/head-state.d.ts.map +1 -0
  165. package/dist/shims/head-state.js +47 -0
  166. package/dist/shims/head-state.js.map +1 -0
  167. package/dist/shims/head.d.ts +28 -0
  168. package/dist/shims/head.d.ts.map +1 -0
  169. package/dist/shims/head.js +148 -0
  170. package/dist/shims/head.js.map +1 -0
  171. package/dist/shims/headers.d.ts +150 -0
  172. package/dist/shims/headers.d.ts.map +1 -0
  173. package/dist/shims/headers.js +412 -0
  174. package/dist/shims/headers.js.map +1 -0
  175. package/dist/shims/image-config.d.ts +30 -0
  176. package/dist/shims/image-config.d.ts.map +1 -0
  177. package/dist/shims/image-config.js +91 -0
  178. package/dist/shims/image-config.js.map +1 -0
  179. package/dist/shims/image.d.ts +63 -0
  180. package/dist/shims/image.d.ts.map +1 -0
  181. package/dist/shims/image.js +284 -0
  182. package/dist/shims/image.js.map +1 -0
  183. package/dist/shims/internal/api-utils.d.ts +12 -0
  184. package/dist/shims/internal/api-utils.d.ts.map +1 -0
  185. package/dist/shims/internal/api-utils.js +7 -0
  186. package/dist/shims/internal/api-utils.js.map +1 -0
  187. package/dist/shims/internal/app-router-context.d.ts +21 -0
  188. package/dist/shims/internal/app-router-context.d.ts.map +1 -0
  189. package/dist/shims/internal/app-router-context.js +15 -0
  190. package/dist/shims/internal/app-router-context.js.map +1 -0
  191. package/dist/shims/internal/cookies.d.ts +9 -0
  192. package/dist/shims/internal/cookies.d.ts.map +1 -0
  193. package/dist/shims/internal/cookies.js +9 -0
  194. package/dist/shims/internal/cookies.js.map +1 -0
  195. package/dist/shims/internal/router-context.d.ts +2 -0
  196. package/dist/shims/internal/router-context.d.ts.map +1 -0
  197. package/dist/shims/internal/router-context.js +9 -0
  198. package/dist/shims/internal/router-context.js.map +1 -0
  199. package/dist/shims/internal/utils.d.ts +48 -0
  200. package/dist/shims/internal/utils.d.ts.map +1 -0
  201. package/dist/shims/internal/utils.js +35 -0
  202. package/dist/shims/internal/utils.js.map +1 -0
  203. package/dist/shims/internal/work-unit-async-storage.d.ts +12 -0
  204. package/dist/shims/internal/work-unit-async-storage.d.ts.map +1 -0
  205. package/dist/shims/internal/work-unit-async-storage.js +13 -0
  206. package/dist/shims/internal/work-unit-async-storage.js.map +1 -0
  207. package/dist/shims/layout-segment-context.d.ts +21 -0
  208. package/dist/shims/layout-segment-context.d.ts.map +1 -0
  209. package/dist/shims/layout-segment-context.js +27 -0
  210. package/dist/shims/layout-segment-context.js.map +1 -0
  211. package/dist/shims/legacy-image.d.ts +52 -0
  212. package/dist/shims/legacy-image.d.ts.map +1 -0
  213. package/dist/shims/legacy-image.js +46 -0
  214. package/dist/shims/legacy-image.js.map +1 -0
  215. package/dist/shims/link.d.ts +48 -0
  216. package/dist/shims/link.d.ts.map +1 -0
  217. package/dist/shims/link.js +395 -0
  218. package/dist/shims/link.js.map +1 -0
  219. package/dist/shims/metadata.d.ts +184 -0
  220. package/dist/shims/metadata.d.ts.map +1 -0
  221. package/dist/shims/metadata.js +472 -0
  222. package/dist/shims/metadata.js.map +1 -0
  223. package/dist/shims/navigation-state.d.ts +14 -0
  224. package/dist/shims/navigation-state.d.ts.map +1 -0
  225. package/dist/shims/navigation-state.js +77 -0
  226. package/dist/shims/navigation-state.js.map +1 -0
  227. package/dist/shims/navigation.d.ts +201 -0
  228. package/dist/shims/navigation.d.ts.map +1 -0
  229. package/dist/shims/navigation.js +672 -0
  230. package/dist/shims/navigation.js.map +1 -0
  231. package/dist/shims/og.d.ts +20 -0
  232. package/dist/shims/og.d.ts.map +1 -0
  233. package/dist/shims/og.js +19 -0
  234. package/dist/shims/og.js.map +1 -0
  235. package/dist/shims/router-state.d.ts +11 -0
  236. package/dist/shims/router-state.d.ts.map +1 -0
  237. package/dist/shims/router-state.js +56 -0
  238. package/dist/shims/router-state.js.map +1 -0
  239. package/dist/shims/router.d.ts +103 -0
  240. package/dist/shims/router.d.ts.map +1 -0
  241. package/dist/shims/router.js +536 -0
  242. package/dist/shims/router.js.map +1 -0
  243. package/dist/shims/script.d.ts +58 -0
  244. package/dist/shims/script.d.ts.map +1 -0
  245. package/dist/shims/script.js +163 -0
  246. package/dist/shims/script.js.map +1 -0
  247. package/dist/shims/server-only.d.ts +19 -0
  248. package/dist/shims/server-only.d.ts.map +1 -0
  249. package/dist/shims/server-only.js +19 -0
  250. package/dist/shims/server-only.js.map +1 -0
  251. package/dist/shims/server.d.ts +178 -0
  252. package/dist/shims/server.d.ts.map +1 -0
  253. package/dist/shims/server.js +377 -0
  254. package/dist/shims/server.js.map +1 -0
  255. package/dist/shims/web-vitals.d.ts +24 -0
  256. package/dist/shims/web-vitals.d.ts.map +1 -0
  257. package/dist/shims/web-vitals.js +17 -0
  258. package/dist/shims/web-vitals.js.map +1 -0
  259. package/dist/utils/hash.d.ts +6 -0
  260. package/dist/utils/hash.d.ts.map +1 -0
  261. package/dist/utils/hash.js +20 -0
  262. package/dist/utils/hash.js.map +1 -0
  263. package/dist/utils/project.d.ts +36 -0
  264. package/dist/utils/project.d.ts.map +1 -0
  265. package/dist/utils/project.js +112 -0
  266. package/dist/utils/project.js.map +1 -0
  267. package/dist/utils/query.d.ts +10 -0
  268. package/dist/utils/query.d.ts.map +1 -0
  269. package/dist/utils/query.js +27 -0
  270. package/dist/utils/query.js.map +1 -0
  271. package/package.json +65 -7
  272. package/index.js +0 -1
@@ -0,0 +1,2718 @@
1
+ /**
2
+ * App Router dev server handler.
3
+ *
4
+ * This module generates virtual entry points for the RSC/SSR/browser
5
+ * environments that @vitejs/plugin-rsc manages. The RSC entry does
6
+ * route matching and renders the component tree, then delegates to
7
+ * the SSR entry for HTML generation.
8
+ */
9
+ import fs from "node:fs";
10
+ /**
11
+ * Generate the virtual RSC entry module.
12
+ *
13
+ * This runs in the `rsc` Vite environment (react-server condition).
14
+ * It matches the incoming request URL to an app route, builds the
15
+ * nested layout + page tree, and renders it to an RSC stream.
16
+ */
17
+ export function generateRscEntry(appDir, routes, middlewarePath, metadataRoutes, globalErrorPath, basePath, trailingSlash, config) {
18
+ const bp = basePath ?? "";
19
+ const ts = trailingSlash ?? false;
20
+ const redirects = config?.redirects ?? [];
21
+ const rewrites = config?.rewrites ?? { beforeFiles: [], afterFiles: [], fallback: [] };
22
+ const headers = config?.headers ?? [];
23
+ const allowedOrigins = config?.allowedOrigins ?? [];
24
+ // Build import map for all page and layout files
25
+ const imports = [];
26
+ const importMap = new Map();
27
+ let importIdx = 0;
28
+ function getImportVar(filePath) {
29
+ if (importMap.has(filePath))
30
+ return importMap.get(filePath);
31
+ const varName = `mod_${importIdx++}`;
32
+ const absPath = filePath.replace(/\\/g, "/");
33
+ imports.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
34
+ importMap.set(filePath, varName);
35
+ return varName;
36
+ }
37
+ // Pre-register all modules
38
+ for (const route of routes) {
39
+ if (route.pagePath)
40
+ getImportVar(route.pagePath);
41
+ if (route.routePath)
42
+ getImportVar(route.routePath);
43
+ for (const layout of route.layouts)
44
+ getImportVar(layout);
45
+ for (const tmpl of route.templates)
46
+ getImportVar(tmpl);
47
+ if (route.loadingPath)
48
+ getImportVar(route.loadingPath);
49
+ if (route.errorPath)
50
+ getImportVar(route.errorPath);
51
+ if (route.layoutErrorPaths)
52
+ for (const ep of route.layoutErrorPaths) {
53
+ if (ep)
54
+ getImportVar(ep);
55
+ }
56
+ if (route.notFoundPath)
57
+ getImportVar(route.notFoundPath);
58
+ for (const nfp of route.notFoundPaths || []) {
59
+ if (nfp)
60
+ getImportVar(nfp);
61
+ }
62
+ if (route.forbiddenPath)
63
+ getImportVar(route.forbiddenPath);
64
+ if (route.unauthorizedPath)
65
+ getImportVar(route.unauthorizedPath);
66
+ // Register parallel slot modules
67
+ for (const slot of route.parallelSlots) {
68
+ if (slot.pagePath)
69
+ getImportVar(slot.pagePath);
70
+ if (slot.defaultPath)
71
+ getImportVar(slot.defaultPath);
72
+ if (slot.layoutPath)
73
+ getImportVar(slot.layoutPath);
74
+ if (slot.loadingPath)
75
+ getImportVar(slot.loadingPath);
76
+ if (slot.errorPath)
77
+ getImportVar(slot.errorPath);
78
+ // Register intercepting route page modules
79
+ for (const ir of slot.interceptingRoutes) {
80
+ getImportVar(ir.pagePath);
81
+ }
82
+ }
83
+ }
84
+ // Build route table as serialized JS
85
+ const routeEntries = routes.map((route) => {
86
+ const layoutVars = route.layouts.map((l) => getImportVar(l));
87
+ const templateVars = route.templates.map((t) => getImportVar(t));
88
+ const notFoundVars = (route.notFoundPaths || []).map((nf) => nf ? getImportVar(nf) : "null");
89
+ const slotEntries = route.parallelSlots.map((slot) => {
90
+ const interceptEntries = slot.interceptingRoutes.map((ir) => {
91
+ return ` {
92
+ convention: ${JSON.stringify(ir.convention)},
93
+ targetPattern: ${JSON.stringify(ir.targetPattern)},
94
+ page: ${getImportVar(ir.pagePath)},
95
+ params: ${JSON.stringify(ir.params)},
96
+ }`;
97
+ });
98
+ return ` ${JSON.stringify(slot.name)}: {
99
+ page: ${slot.pagePath ? getImportVar(slot.pagePath) : "null"},
100
+ default: ${slot.defaultPath ? getImportVar(slot.defaultPath) : "null"},
101
+ layout: ${slot.layoutPath ? getImportVar(slot.layoutPath) : "null"},
102
+ loading: ${slot.loadingPath ? getImportVar(slot.loadingPath) : "null"},
103
+ error: ${slot.errorPath ? getImportVar(slot.errorPath) : "null"},
104
+ layoutIndex: ${slot.layoutIndex},
105
+ intercepts: [
106
+ ${interceptEntries.join(",\n")}
107
+ ],
108
+ }`;
109
+ });
110
+ const layoutErrorVars = (route.layoutErrorPaths || []).map((ep) => ep ? getImportVar(ep) : "null");
111
+ return ` {
112
+ pattern: ${JSON.stringify(route.pattern)},
113
+ isDynamic: ${route.isDynamic},
114
+ params: ${JSON.stringify(route.params)},
115
+ page: ${route.pagePath ? getImportVar(route.pagePath) : "null"},
116
+ routeHandler: ${route.routePath ? getImportVar(route.routePath) : "null"},
117
+ layouts: [${layoutVars.join(", ")}],
118
+ layoutSegmentDepths: ${JSON.stringify(route.layoutSegmentDepths)},
119
+ templates: [${templateVars.join(", ")}],
120
+ errors: [${layoutErrorVars.join(", ")}],
121
+ slots: {
122
+ ${slotEntries.join(",\n")}
123
+ },
124
+ loading: ${route.loadingPath ? getImportVar(route.loadingPath) : "null"},
125
+ error: ${route.errorPath ? getImportVar(route.errorPath) : "null"},
126
+ notFound: ${route.notFoundPath ? getImportVar(route.notFoundPath) : "null"},
127
+ notFounds: [${notFoundVars.join(", ")}],
128
+ forbidden: ${route.forbiddenPath ? getImportVar(route.forbiddenPath) : "null"},
129
+ unauthorized: ${route.unauthorizedPath ? getImportVar(route.unauthorizedPath) : "null"},
130
+ }`;
131
+ });
132
+ // Find root not-found/forbidden/unauthorized pages and root layouts for global error handling
133
+ const rootRoute = routes.find((r) => r.pattern === "/");
134
+ const rootNotFoundVar = rootRoute?.notFoundPath
135
+ ? getImportVar(rootRoute.notFoundPath)
136
+ : null;
137
+ const rootForbiddenVar = rootRoute?.forbiddenPath
138
+ ? getImportVar(rootRoute.forbiddenPath)
139
+ : null;
140
+ const rootUnauthorizedVar = rootRoute?.unauthorizedPath
141
+ ? getImportVar(rootRoute.unauthorizedPath)
142
+ : null;
143
+ const rootLayoutVars = rootRoute
144
+ ? rootRoute.layouts.map((l) => getImportVar(l))
145
+ : [];
146
+ // Global error boundary (app/global-error.tsx)
147
+ const globalErrorVar = globalErrorPath ? getImportVar(globalErrorPath) : null;
148
+ // Build metadata route handling
149
+ const effectiveMetaRoutes = metadataRoutes ?? [];
150
+ const dynamicMetaRoutes = effectiveMetaRoutes.filter((r) => r.isDynamic);
151
+ // Import dynamic metadata modules
152
+ for (const mr of dynamicMetaRoutes) {
153
+ getImportVar(mr.filePath);
154
+ }
155
+ // Build metadata route table
156
+ // For static metadata files, read the file content at code-generation time
157
+ // and embed it as base64. This ensures static metadata files work on runtimes
158
+ // without filesystem access (e.g., Cloudflare Workers).
159
+ const metaRouteEntries = effectiveMetaRoutes.map((mr) => {
160
+ if (mr.isDynamic) {
161
+ return ` {
162
+ type: ${JSON.stringify(mr.type)},
163
+ isDynamic: true,
164
+ servedUrl: ${JSON.stringify(mr.servedUrl)},
165
+ contentType: ${JSON.stringify(mr.contentType)},
166
+ module: ${getImportVar(mr.filePath)},
167
+ }`;
168
+ }
169
+ // Static: read file and embed as base64
170
+ let fileDataBase64 = "";
171
+ try {
172
+ const buf = fs.readFileSync(mr.filePath);
173
+ fileDataBase64 = buf.toString("base64");
174
+ }
175
+ catch {
176
+ // File unreadable — will serve empty response at runtime
177
+ }
178
+ return ` {
179
+ type: ${JSON.stringify(mr.type)},
180
+ isDynamic: false,
181
+ servedUrl: ${JSON.stringify(mr.servedUrl)},
182
+ contentType: ${JSON.stringify(mr.contentType)},
183
+ fileDataBase64: ${JSON.stringify(fileDataBase64)},
184
+ }`;
185
+ });
186
+ return `
187
+ import {
188
+ renderToReadableStream,
189
+ decodeReply,
190
+ loadServerAction,
191
+ createTemporaryReferenceSet,
192
+ } from "@vitejs/plugin-rsc/rsc";
193
+ import { createElement, Suspense, Fragment } from "react";
194
+ import { setNavigationContext as _setNavigationContextOrig, getNavigationContext as _getNavigationContext } from "next/navigation";
195
+ import { setHeadersContext, headersContextFromRequest, getDraftModeCookieHeader, getAndClearPendingCookies, consumeDynamicUsage, markDynamicUsage, runWithHeadersContext, applyMiddlewareRequestHeaders } from "next/headers";
196
+ import { NextRequest } from "next/server";
197
+ import { ErrorBoundary, NotFoundBoundary } from "vinext/error-boundary";
198
+ import { LayoutSegmentProvider } from "vinext/layout-segment-context";
199
+ import { MetadataHead, mergeMetadata, resolveModuleMetadata, ViewportHead, mergeViewport, resolveModuleViewport } from "vinext/metadata";
200
+ ${middlewarePath ? `import * as middlewareModule from ${JSON.stringify(middlewarePath.replace(/\\/g, "/"))};` : ""}
201
+ ${effectiveMetaRoutes.length > 0 ? `import { sitemapToXml, robotsToText, manifestToJson } from ${JSON.stringify(new URL("./metadata-routes.js", import.meta.url).pathname.replace(/\\/g, "/"))};` : ""}
202
+ import { _consumeRequestScopedCacheLife, _initRequestScopedCacheState } from "next/cache";
203
+ import { runWithFetchCache } from "vinext/fetch-cache";
204
+ import { clearPrivateCache as _clearPrivateCache } from "vinext/cache-runtime";
205
+ // Import server-only state module to register ALS-backed accessors.
206
+ import "vinext/navigation-state";
207
+ import { reportRequestError as _reportRequestError } from "vinext/instrumentation";
208
+ import { getSSRFontLinks as _getSSRFontLinks, getSSRFontStyles as _getSSRFontStylesGoogle, getSSRFontPreloads as _getSSRFontPreloadsGoogle } from "next/font/google";
209
+ import { getSSRFontStyles as _getSSRFontStylesLocal, getSSRFontPreloads as _getSSRFontPreloadsLocal } from "next/font/local";
210
+ function _getSSRFontStyles() { return [..._getSSRFontStylesGoogle(), ..._getSSRFontStylesLocal()]; }
211
+ function _getSSRFontPreloads() { return [..._getSSRFontPreloadsGoogle(), ..._getSSRFontPreloadsLocal()]; }
212
+
213
+ // Set navigation context in the ALS-backed store. "use client" components
214
+ // rendered during SSR need the pathname/searchParams/params but the SSR
215
+ // environment has a separate module instance of next/navigation.
216
+ // Use _getNavigationContext() to read the current context — never cache
217
+ // it in a module-level variable (that would leak between concurrent requests).
218
+ function setNavigationContext(ctx) {
219
+ _setNavigationContextOrig(ctx);
220
+ }
221
+
222
+ // ISR cache is disabled in dev mode — every request re-renders fresh,
223
+ // matching Next.js dev behavior. Cache-Control headers are still emitted
224
+ // based on export const revalidate for testing purposes.
225
+ // Production ISR is handled by prod-server.ts and the Cloudflare worker entry.
226
+
227
+ // onError callback for renderToReadableStream — preserves the digest for
228
+ // Next.js navigation errors (redirect, notFound, forbidden, unauthorized)
229
+ // thrown during RSC streaming (e.g. inside Suspense boundaries).
230
+ // Without this, React's default onError returns undefined, the digest is lost,
231
+ // and client-side error boundaries can't identify the error type.
232
+ function rscOnError(error) {
233
+ if (error && typeof error === "object" && "digest" in error) {
234
+ return String(error.digest);
235
+ }
236
+ return undefined;
237
+ }
238
+
239
+ ${imports.join("\n")}
240
+
241
+ const routes = [
242
+ ${routeEntries.join(",\n")}
243
+ ];
244
+
245
+ const metadataRoutes = [
246
+ ${metaRouteEntries.join(",\n")}
247
+ ];
248
+
249
+ const rootNotFoundModule = ${rootNotFoundVar ? rootNotFoundVar : "null"};
250
+ const rootForbiddenModule = ${rootForbiddenVar ? rootForbiddenVar : "null"};
251
+ const rootUnauthorizedModule = ${rootUnauthorizedVar ? rootUnauthorizedVar : "null"};
252
+ const rootLayouts = [${rootLayoutVars.join(", ")}];
253
+
254
+ /**
255
+ * Render an HTTP access fallback page (not-found/forbidden/unauthorized) with layouts and noindex meta.
256
+ * Returns null if no matching component is available.
257
+ *
258
+ * @param opts.boundaryComponent - Override the boundary component (for layout-level notFound)
259
+ * @param opts.layouts - Override the layouts to wrap with (for layout-level notFound, excludes the throwing layout)
260
+ */
261
+ async function renderHTTPAccessFallbackPage(route, statusCode, isRscRequest, request, opts) {
262
+ // Determine which boundary component to use based on status code
263
+ let BoundaryComponent = opts?.boundaryComponent ?? null;
264
+ if (!BoundaryComponent) {
265
+ let boundaryModule;
266
+ if (statusCode === 403) {
267
+ boundaryModule = route?.forbidden ?? rootForbiddenModule;
268
+ } else if (statusCode === 401) {
269
+ boundaryModule = route?.unauthorized ?? rootUnauthorizedModule;
270
+ } else {
271
+ boundaryModule = route?.notFound ?? rootNotFoundModule;
272
+ }
273
+ BoundaryComponent = boundaryModule?.default ?? null;
274
+ }
275
+ const layouts = opts?.layouts ?? route?.layouts ?? rootLayouts;
276
+ if (!BoundaryComponent) return null;
277
+
278
+ // Resolve metadata and viewport from parent layouts so that not-found/error
279
+ // pages inherit title, description, OG tags etc. — matching Next.js behavior.
280
+ const metadataList = [];
281
+ const viewportList = [];
282
+ for (const layoutMod of layouts) {
283
+ if (layoutMod) {
284
+ const meta = await resolveModuleMetadata(layoutMod);
285
+ if (meta) metadataList.push(meta);
286
+ const vp = await resolveModuleViewport(layoutMod);
287
+ if (vp) viewportList.push(vp);
288
+ }
289
+ }
290
+ const resolvedMetadata = metadataList.length > 0 ? mergeMetadata(metadataList) : null;
291
+ const resolvedViewport = viewportList.length > 0 ? mergeViewport(viewportList) : null;
292
+
293
+ // Build element: metadata head + noindex meta + boundary component wrapped in layouts
294
+ // Always include charset and default viewport for parity with Next.js.
295
+ const charsetMeta = createElement("meta", { charSet: "utf-8" });
296
+ const noindexMeta = createElement("meta", { name: "robots", content: "noindex" });
297
+ const headElements = [charsetMeta, noindexMeta];
298
+ if (resolvedMetadata) headElements.push(createElement(MetadataHead, { metadata: resolvedMetadata }));
299
+ const effectiveViewport = resolvedViewport ?? { width: "device-width", initialScale: 1 };
300
+ headElements.push(createElement(ViewportHead, { viewport: effectiveViewport }));
301
+ let element = createElement(Fragment, null, ...headElements, createElement(BoundaryComponent));
302
+ if (isRscRequest) {
303
+ // For RSC requests (client-side navigation), wrap the element with the same
304
+ // component wrappers that buildPageElement() uses. Without these wrappers,
305
+ // React's reconciliation would see a mismatched tree structure between the
306
+ // old fiber tree (ErrorBoundary > LayoutSegmentProvider > html > body > NotFoundBoundary > ...)
307
+ // and the new tree (html > body > ...), causing it to destroy and recreate
308
+ // the entire DOM tree, resulting in a blank white page.
309
+ //
310
+ // We wrap each layout with LayoutSegmentProvider and add GlobalErrorBoundary
311
+ // to match the wrapping order in buildPageElement(), ensuring smooth
312
+ // client-side tree reconciliation.
313
+ const layoutDepths = route?.layoutSegmentDepths;
314
+ for (let i = layouts.length - 1; i >= 0; i--) {
315
+ const LayoutComponent = layouts[i]?.default;
316
+ if (LayoutComponent) {
317
+ element = createElement(LayoutComponent, { children: element });
318
+ const layoutDepth = layoutDepths ? layoutDepths[i] : 0;
319
+ element = createElement(LayoutSegmentProvider, { depth: layoutDepth }, element);
320
+ }
321
+ }
322
+ ${globalErrorVar ? `
323
+ const _GlobalErrorComponent = ${globalErrorVar}.default;
324
+ if (_GlobalErrorComponent) {
325
+ element = createElement(ErrorBoundary, {
326
+ fallback: _GlobalErrorComponent,
327
+ children: element,
328
+ });
329
+ }
330
+ ` : ""}
331
+ const rscStream = renderToReadableStream(element, { onError: rscOnError });
332
+ setHeadersContext(null);
333
+ setNavigationContext(null);
334
+ return new Response(rscStream, {
335
+ status: statusCode,
336
+ headers: { "Content-Type": "text/x-component; charset=utf-8" },
337
+ });
338
+ }
339
+ // For HTML (full page load) responses, wrap with layouts only (no client-side
340
+ // wrappers needed since SSR generates the complete HTML document).
341
+ for (let i = layouts.length - 1; i >= 0; i--) {
342
+ const LayoutComponent = layouts[i]?.default;
343
+ if (LayoutComponent) {
344
+ element = createElement(LayoutComponent, { children: element });
345
+ }
346
+ }
347
+ const rscStream = renderToReadableStream(element, { onError: rscOnError });
348
+ // Collect font data from RSC environment
349
+ const fontData = {
350
+ links: _getSSRFontLinks(),
351
+ styles: _getSSRFontStyles(),
352
+ preloads: _getSSRFontPreloads(),
353
+ };
354
+ const ssrEntry = await import.meta.viteRsc.loadModule("ssr", "index");
355
+ const htmlStream = await ssrEntry.handleSsr(rscStream, _getNavigationContext(), fontData);
356
+ setHeadersContext(null);
357
+ setNavigationContext(null);
358
+ const _respHeaders = { "Content-Type": "text/html; charset=utf-8" };
359
+ const _linkParts = (fontData.preloads || []).map(function(p) { return "<" + p.href + ">; rel=preload; as=font; type=" + p.type + "; crossorigin"; });
360
+ if (_linkParts.length > 0) _respHeaders["Link"] = _linkParts.join(", ");
361
+ return new Response(htmlStream, {
362
+ status: statusCode,
363
+ headers: _respHeaders,
364
+ });
365
+ }
366
+
367
+ /** Convenience: render a not-found page (404) */
368
+ async function renderNotFoundPage(route, isRscRequest, request) {
369
+ return renderHTTPAccessFallbackPage(route, 404, isRscRequest, request);
370
+ }
371
+
372
+ /**
373
+ * Render an error.tsx boundary page when a server component or generateMetadata() throws.
374
+ * Returns null if no error boundary component is available for this route.
375
+ *
376
+ * Next.js returns HTTP 200 when error.tsx catches an error (the error is "handled"
377
+ * by the boundary). This matches that behavior intentionally.
378
+ */
379
+ async function renderErrorBoundaryPage(route, error, isRscRequest, request) {
380
+ // Resolve the error boundary component: leaf error.tsx first, then walk per-layout
381
+ // errors from innermost to outermost (matching ancestor inheritance), then global-error.tsx.
382
+ let ErrorComponent = route?.error?.default ?? null;
383
+ if (!ErrorComponent && route?.errors) {
384
+ for (let i = route.errors.length - 1; i >= 0; i--) {
385
+ if (route.errors[i]?.default) {
386
+ ErrorComponent = route.errors[i].default;
387
+ break;
388
+ }
389
+ }
390
+ }
391
+ ErrorComponent = ErrorComponent${globalErrorVar ? ` ?? ${globalErrorVar}?.default` : ""};
392
+ if (!ErrorComponent) return null;
393
+
394
+ const errorObj = error instanceof Error ? error : new Error(String(error));
395
+ // Only pass error — reset is a client-side concern (re-renders the segment) and
396
+ // can't be serialized through RSC. The error.tsx component will receive reset=undefined
397
+ // during SSR, which is fine — onClick={undefined} is harmless, and the real reset
398
+ // function is only meaningful after hydration.
399
+ let element = createElement(ErrorComponent, {
400
+ error: errorObj,
401
+ });
402
+ const layouts = route?.layouts ?? rootLayouts;
403
+ if (isRscRequest) {
404
+ // For RSC requests (client-side navigation), wrap with the same component
405
+ // wrappers that buildPageElement() uses (LayoutSegmentProvider, GlobalErrorBoundary).
406
+ // This ensures React can reconcile the tree without destroying the DOM.
407
+ // Same rationale as renderHTTPAccessFallbackPage — see comment there.
408
+ const layoutDepths = route?.layoutSegmentDepths;
409
+ for (let i = layouts.length - 1; i >= 0; i--) {
410
+ const LayoutComponent = layouts[i]?.default;
411
+ if (LayoutComponent) {
412
+ element = createElement(LayoutComponent, { children: element });
413
+ const layoutDepth = layoutDepths ? layoutDepths[i] : 0;
414
+ element = createElement(LayoutSegmentProvider, { depth: layoutDepth }, element);
415
+ }
416
+ }
417
+ ${globalErrorVar ? `
418
+ const _ErrGlobalComponent = ${globalErrorVar}.default;
419
+ if (_ErrGlobalComponent) {
420
+ element = createElement(ErrorBoundary, {
421
+ fallback: _ErrGlobalComponent,
422
+ children: element,
423
+ });
424
+ }
425
+ ` : ""}
426
+ const rscStream = renderToReadableStream(element, { onError: rscOnError });
427
+ setHeadersContext(null);
428
+ setNavigationContext(null);
429
+ return new Response(rscStream, {
430
+ status: 200,
431
+ headers: { "Content-Type": "text/x-component; charset=utf-8" },
432
+ });
433
+ }
434
+ // For HTML (full page load) responses, wrap with layouts only.
435
+ for (let i = layouts.length - 1; i >= 0; i--) {
436
+ const LayoutComponent = layouts[i]?.default;
437
+ if (LayoutComponent) {
438
+ element = createElement(LayoutComponent, { children: element });
439
+ }
440
+ }
441
+ const rscStream = renderToReadableStream(element, { onError: rscOnError });
442
+ // Collect font data from RSC environment so error pages include font styles
443
+ const fontData = {
444
+ links: _getSSRFontLinks(),
445
+ styles: _getSSRFontStyles(),
446
+ preloads: _getSSRFontPreloads(),
447
+ };
448
+ const ssrEntry = await import.meta.viteRsc.loadModule("ssr", "index");
449
+ const htmlStream = await ssrEntry.handleSsr(rscStream, _getNavigationContext(), fontData);
450
+ setHeadersContext(null);
451
+ setNavigationContext(null);
452
+ const _errHeaders = { "Content-Type": "text/html; charset=utf-8" };
453
+ const _errLinkParts = (fontData.preloads || []).map(function(p) { return "<" + p.href + ">; rel=preload; as=font; type=" + p.type + "; crossorigin"; });
454
+ if (_errLinkParts.length > 0) _errHeaders["Link"] = _errLinkParts.join(", ");
455
+ return new Response(htmlStream, {
456
+ status: 200,
457
+ headers: _errHeaders,
458
+ });
459
+ }
460
+
461
+ function matchRoute(url, routes) {
462
+ const pathname = url.split("?")[0];
463
+ let normalizedUrl = pathname === "/" ? "/" : pathname.replace(/\\/$/, "");
464
+ try { normalizedUrl = decodeURIComponent(normalizedUrl); } catch {}
465
+ for (const route of routes) {
466
+ const params = matchPattern(normalizedUrl, route.pattern);
467
+ if (params !== null) return { route, params };
468
+ }
469
+ return null;
470
+ }
471
+
472
+ function matchPattern(url, pattern) {
473
+ const urlParts = url.split("/").filter(Boolean);
474
+ const patternParts = pattern.split("/").filter(Boolean);
475
+ const params = Object.create(null);
476
+ for (let i = 0; i < patternParts.length; i++) {
477
+ const pp = patternParts[i];
478
+ if (pp.endsWith("+")) {
479
+ const paramName = pp.slice(1, -1);
480
+ const remaining = urlParts.slice(i);
481
+ if (remaining.length === 0) return null;
482
+ params[paramName] = remaining;
483
+ return params;
484
+ }
485
+ if (pp.endsWith("*")) {
486
+ const paramName = pp.slice(1, -1);
487
+ params[paramName] = urlParts.slice(i);
488
+ return params;
489
+ }
490
+ if (pp.startsWith(":")) {
491
+ if (i >= urlParts.length) return null;
492
+ params[pp.slice(1)] = urlParts[i];
493
+ continue;
494
+ }
495
+ if (i >= urlParts.length || urlParts[i] !== pp) return null;
496
+ }
497
+ if (urlParts.length !== patternParts.length) return null;
498
+ return params;
499
+ }
500
+
501
+ // Build a global intercepting route lookup for RSC navigation.
502
+ // Maps target URL patterns to { sourceRouteIndex, slotName, interceptPage, params }.
503
+ const interceptLookup = [];
504
+ for (let ri = 0; ri < routes.length; ri++) {
505
+ const r = routes[ri];
506
+ if (!r.slots) continue;
507
+ for (const [slotName, slotMod] of Object.entries(r.slots)) {
508
+ if (!slotMod.intercepts) continue;
509
+ for (const intercept of slotMod.intercepts) {
510
+ interceptLookup.push({
511
+ sourceRouteIndex: ri,
512
+ slotName,
513
+ targetPattern: intercept.targetPattern,
514
+ page: intercept.page,
515
+ params: intercept.params,
516
+ });
517
+ }
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Check if a pathname matches any intercepting route.
523
+ * Returns the match info or null.
524
+ */
525
+ function findIntercept(pathname) {
526
+ for (const entry of interceptLookup) {
527
+ const params = matchPattern(pathname, entry.targetPattern);
528
+ if (params !== null) {
529
+ return { ...entry, matchedParams: params };
530
+ }
531
+ }
532
+ return null;
533
+ }
534
+
535
+ async function buildPageElement(route, params, opts, searchParams) {
536
+ const PageComponent = route.page?.default;
537
+ if (!PageComponent) {
538
+ return createElement("div", null, "Page has no default export");
539
+ }
540
+
541
+ // Resolve metadata and viewport from layouts and page
542
+ const metadataList = [];
543
+ const viewportList = [];
544
+ for (const layoutMod of route.layouts) {
545
+ if (layoutMod) {
546
+ const meta = await resolveModuleMetadata(layoutMod, params);
547
+ if (meta) metadataList.push(meta);
548
+ const vp = await resolveModuleViewport(layoutMod, params);
549
+ if (vp) viewportList.push(vp);
550
+ }
551
+ }
552
+ if (route.page) {
553
+ const pageMeta = await resolveModuleMetadata(route.page, params);
554
+ if (pageMeta) metadataList.push(pageMeta);
555
+ const pageVp = await resolveModuleViewport(route.page, params);
556
+ if (pageVp) viewportList.push(pageVp);
557
+ }
558
+ const resolvedMetadata = metadataList.length > 0 ? mergeMetadata(metadataList) : null;
559
+ const resolvedViewport = viewportList.length > 0 ? mergeViewport(viewportList) : null;
560
+
561
+ // Build nested layout tree from outermost to innermost.
562
+ // Next.js 16 passes params/searchParams as Promises (async pattern)
563
+ // but pre-16 code accesses them as plain objects (params.id).
564
+ // We create a "thenable object" that works both ways.
565
+ const asyncParams = Object.assign(Promise.resolve(params), params);
566
+ const pageProps = { params: asyncParams };
567
+ if (searchParams) {
568
+ const spObj = {};
569
+ let hasSearchParams = false;
570
+ if (searchParams.forEach) searchParams.forEach(function(v, k) {
571
+ hasSearchParams = true;
572
+ if (k in spObj) {
573
+ // Multi-value: promote to array (Next.js returns string[] for duplicate keys)
574
+ spObj[k] = Array.isArray(spObj[k]) ? spObj[k].concat(v) : [spObj[k], v];
575
+ } else {
576
+ spObj[k] = v;
577
+ }
578
+ });
579
+ // If the URL has query parameters, mark the page as dynamic.
580
+ // In Next.js, only accessing the searchParams prop signals dynamic usage,
581
+ // but a Proxy-based approach doesn't work here because React's RSC debug
582
+ // serializer accesses properties on all props (e.g. $$typeof check in
583
+ // isClientReference), triggering the Proxy even when user code doesn't
584
+ // read searchParams. Checking for non-empty query params is a safe
585
+ // approximation: pages with query params in the URL are almost always
586
+ // dynamic, and this avoids false positives from React internals.
587
+ if (hasSearchParams) markDynamicUsage();
588
+ pageProps.searchParams = Object.assign(Promise.resolve(spObj), spObj);
589
+ }
590
+ let element = createElement(PageComponent, pageProps);
591
+
592
+ // Add metadata + viewport head tags (React 19 hoists title/meta/link to <head>)
593
+ // Next.js always injects charset and default viewport even when no metadata/viewport
594
+ // is exported. We replicate that by always emitting these essential head elements.
595
+ {
596
+ const headElements = [];
597
+ // Always emit <meta charset="utf-8"> — Next.js includes this on every page
598
+ headElements.push(createElement("meta", { charSet: "utf-8" }));
599
+ if (resolvedMetadata) headElements.push(createElement(MetadataHead, { metadata: resolvedMetadata }));
600
+ // Default viewport to standard responsive settings when none is exported
601
+ const effectiveViewport = resolvedViewport ?? { width: "device-width", initialScale: 1 };
602
+ headElements.push(createElement(ViewportHead, { viewport: effectiveViewport }));
603
+ element = createElement(Fragment, null, ...headElements, element);
604
+ }
605
+
606
+ // Wrap with loading.tsx Suspense if present
607
+ if (route.loading?.default) {
608
+ element = createElement(
609
+ Suspense,
610
+ { fallback: createElement(route.loading.default) },
611
+ element,
612
+ );
613
+ }
614
+
615
+ // Wrap with the leaf's error.tsx ErrorBoundary if it's not already covered
616
+ // by a per-layout error boundary (i.e., the leaf has error.tsx but no layout).
617
+ // Per-layout error boundaries are interleaved with layouts below.
618
+ {
619
+ const lastLayoutError = route.errors ? route.errors[route.errors.length - 1] : null;
620
+ if (route.error?.default && route.error !== lastLayoutError) {
621
+ element = createElement(ErrorBoundary, {
622
+ fallback: route.error.default,
623
+ children: element,
624
+ });
625
+ }
626
+ }
627
+
628
+ // Wrap with NotFoundBoundary so client-side notFound() renders not-found.tsx
629
+ // instead of crashing the React tree. Must be above ErrorBoundary since
630
+ // ErrorBoundary re-throws notFound errors.
631
+ // Pre-render the not-found component as a React element since it may be a
632
+ // server component (not a client reference) and can't be passed as a function prop.
633
+ {
634
+ const NotFoundComponent = route.notFound?.default ?? ${rootNotFoundVar ? `${rootNotFoundVar}?.default` : "null"};
635
+ if (NotFoundComponent) {
636
+ element = createElement(NotFoundBoundary, {
637
+ fallback: createElement(NotFoundComponent),
638
+ children: element,
639
+ });
640
+ }
641
+ }
642
+
643
+ // Wrap with templates (innermost first, then outer)
644
+ // Templates are like layouts but re-mount on navigation (client-side concern).
645
+ // On the server, they just wrap the content like layouts do.
646
+ if (route.templates) {
647
+ for (let i = route.templates.length - 1; i >= 0; i--) {
648
+ const TemplateComponent = route.templates[i]?.default;
649
+ if (TemplateComponent) {
650
+ element = createElement(TemplateComponent, { children: element, params });
651
+ }
652
+ }
653
+ }
654
+
655
+ // Wrap with layouts (innermost first, then outer).
656
+ // At each layout level, first wrap with that level's error boundary (if any)
657
+ // so the boundary is inside the layout and catches errors from children.
658
+ // This matches Next.js behavior: Layout > ErrorBoundary > children.
659
+ // Parallel slots are passed as named props to the innermost layout
660
+ // (the layout at the same directory level as the page/slots)
661
+ for (let i = route.layouts.length - 1; i >= 0; i--) {
662
+ // Wrap with per-layout error boundary before wrapping with layout.
663
+ // This places the ErrorBoundary inside the layout, catching errors
664
+ // from child segments (matching Next.js per-segment error handling).
665
+ if (route.errors && route.errors[i]?.default) {
666
+ element = createElement(ErrorBoundary, {
667
+ fallback: route.errors[i].default,
668
+ children: element,
669
+ });
670
+ }
671
+
672
+ const LayoutComponent = route.layouts[i]?.default;
673
+ if (LayoutComponent) {
674
+ // Per-layout NotFoundBoundary: wraps this layout's children so that
675
+ // notFound() thrown from a child layout is caught here.
676
+ // Matches Next.js behavior where each segment has its own boundary.
677
+ // The boundary at level N catches errors from Layout[N+1] and below,
678
+ // but NOT from Layout[N] itself (which propagates to level N-1).
679
+ {
680
+ const LayoutNotFound = route.notFounds?.[i]?.default;
681
+ if (LayoutNotFound) {
682
+ element = createElement(NotFoundBoundary, {
683
+ fallback: createElement(LayoutNotFound),
684
+ children: element,
685
+ });
686
+ }
687
+ }
688
+
689
+ const layoutProps = { children: element, params: Object.assign(Promise.resolve(params), params) };
690
+
691
+ // Add parallel slot elements to the layout that defines them.
692
+ // Each slot has a layoutIndex indicating which layout it belongs to.
693
+ if (route.slots) {
694
+ for (const [slotName, slotMod] of Object.entries(route.slots)) {
695
+ // Attach slot to the layout at its layoutIndex, or to the innermost layout if -1
696
+ const targetIdx = slotMod.layoutIndex >= 0 ? slotMod.layoutIndex : route.layouts.length - 1;
697
+ if (i !== targetIdx) continue;
698
+ // Check if this slot has an intercepting route that should activate
699
+ let SlotPage = null;
700
+ let slotParams = params;
701
+
702
+ if (opts && opts.interceptSlot === slotName && opts.interceptPage) {
703
+ // Use the intercepting route's page component
704
+ SlotPage = opts.interceptPage.default;
705
+ slotParams = opts.interceptParams || params;
706
+ } else {
707
+ SlotPage = slotMod.page?.default || slotMod.default?.default;
708
+ }
709
+
710
+ if (SlotPage) {
711
+ let slotElement = createElement(SlotPage, { params: Object.assign(Promise.resolve(slotParams), slotParams) });
712
+ // Wrap with slot-specific layout if present.
713
+ // In Next.js, @slot/layout.tsx wraps the slot's page content
714
+ // before it is passed as a prop to the parent layout.
715
+ const SlotLayout = slotMod.layout?.default;
716
+ if (SlotLayout) {
717
+ slotElement = createElement(SlotLayout, {
718
+ children: slotElement,
719
+ params: Object.assign(Promise.resolve(slotParams), slotParams),
720
+ });
721
+ }
722
+ // Wrap with slot-specific loading if present
723
+ if (slotMod.loading?.default) {
724
+ slotElement = createElement(Suspense,
725
+ { fallback: createElement(slotMod.loading.default) },
726
+ slotElement,
727
+ );
728
+ }
729
+ // Wrap with slot-specific error boundary if present
730
+ if (slotMod.error?.default) {
731
+ slotElement = createElement(ErrorBoundary, {
732
+ fallback: slotMod.error.default,
733
+ children: slotElement,
734
+ });
735
+ }
736
+ layoutProps[slotName] = slotElement;
737
+ }
738
+ }
739
+ }
740
+
741
+ element = createElement(LayoutComponent, layoutProps);
742
+
743
+ // Wrap the layout with LayoutSegmentProvider so useSelectedLayoutSegments()
744
+ // called INSIDE this layout knows its URL segment depth. The depth tells the
745
+ // hook how many URL segments are above this layout, so it returns only the
746
+ // segments below. We wrap the layout (not just children) because hooks are
747
+ // called from components rendered inside the layout's own JSX.
748
+ const layoutDepth = route.layoutSegmentDepths ? route.layoutSegmentDepths[i] : 0;
749
+ element = createElement(LayoutSegmentProvider, { depth: layoutDepth }, element);
750
+ }
751
+ }
752
+
753
+ // Wrap with global error boundary if app/global-error.tsx exists.
754
+ // This catches errors in the root layout itself.
755
+ ${globalErrorVar ? `
756
+ const GlobalErrorComponent = ${globalErrorVar}.default;
757
+ if (GlobalErrorComponent) {
758
+ element = createElement(ErrorBoundary, {
759
+ fallback: GlobalErrorComponent,
760
+ children: element,
761
+ });
762
+ }
763
+ ` : ""}
764
+
765
+ return element;
766
+ }
767
+
768
+ ${middlewarePath ? `
769
+ function matchMiddlewarePath(pathname, matcher) {
770
+ if (!matcher) return true;
771
+ const patterns = typeof matcher === "string" ? [matcher]
772
+ : Array.isArray(matcher) ? matcher.map(m => typeof m === "string" ? m : m.source)
773
+ : [];
774
+ return patterns.some(pattern => {
775
+ const reStr = "^" + pattern
776
+ .replace(/\\./g, "\\\\.")
777
+ .replace(/:(\\w+)\\*/g, "(?:.*)")
778
+ .replace(/:(\\w+)\\+/g, "(?:.+)")
779
+ .replace(/:(\\w+)/g, "([^/]+)") + "$";
780
+ const re = __safeRegExp(reStr);
781
+ return re ? re.test(pathname) : false;
782
+ });
783
+ }
784
+ ` : ""}
785
+
786
+ const __basePath = ${JSON.stringify(bp)};
787
+ const __trailingSlash = ${JSON.stringify(ts)};
788
+ const __configRedirects = ${JSON.stringify(redirects)};
789
+ const __configRewrites = ${JSON.stringify(rewrites)};
790
+ const __configHeaders = ${JSON.stringify(headers)};
791
+ const __allowedOrigins = ${JSON.stringify(allowedOrigins)};
792
+
793
+ // ── CSRF origin validation for server actions ───────────────────────────
794
+ // Matches Next.js behavior: compare the Origin header against the Host header.
795
+ // If they don't match, the request is rejected with 403 unless the origin is
796
+ // in the allowedOrigins list (from experimental.serverActions.allowedOrigins).
797
+ function __isOriginAllowed(origin, allowed) {
798
+ for (const pattern of allowed) {
799
+ if (pattern.startsWith("*.")) {
800
+ // Wildcard: *.example.com matches sub.example.com, a.b.example.com
801
+ const suffix = pattern.slice(1); // ".example.com"
802
+ if (origin === pattern.slice(2) || origin.endsWith(suffix)) return true;
803
+ } else if (origin === pattern) {
804
+ return true;
805
+ }
806
+ }
807
+ return false;
808
+ }
809
+
810
+ function __validateCsrfOrigin(request) {
811
+ const originHeader = request.headers.get("origin");
812
+ // If there's no Origin header, allow the request — same-origin requests
813
+ // from non-fetch navigations (e.g. SSR) may lack an Origin header.
814
+ // The x-rsc-action custom header already provides protection against simple
815
+ // form-based CSRF since custom headers can't be set by cross-origin forms.
816
+ if (!originHeader || originHeader === "null") return null;
817
+
818
+ let originHost;
819
+ try {
820
+ originHost = new URL(originHeader).host.toLowerCase();
821
+ } catch {
822
+ return new Response("Forbidden", { status: 403, headers: { "Content-Type": "text/plain" } });
823
+ }
824
+
825
+ const hostHeader = (
826
+ request.headers.get("x-forwarded-host") ||
827
+ request.headers.get("host") ||
828
+ ""
829
+ ).split(",")[0].trim().toLowerCase();
830
+
831
+ if (!hostHeader) return null;
832
+
833
+ // Same origin — allow
834
+ if (originHost === hostHeader) return null;
835
+
836
+ // Check allowedOrigins from next.config.js
837
+ if (__allowedOrigins.length > 0 && __isOriginAllowed(originHost, __allowedOrigins)) return null;
838
+
839
+ console.warn(
840
+ \`[vinext] CSRF origin mismatch: origin "\${originHost}" does not match host "\${hostHeader}". Blocking server action request.\`
841
+ );
842
+ return new Response("Forbidden", { status: 403, headers: { "Content-Type": "text/plain" } });
843
+ }
844
+
845
+ // ── ReDoS-safe regex compilation ────────────────────────────────────────
846
+ function __isSafeRegex(pattern) {
847
+ const quantifierAtDepth = [];
848
+ let depth = 0;
849
+ let i = 0;
850
+ while (i < pattern.length) {
851
+ const ch = pattern[i];
852
+ if (ch === "\\\\") { i += 2; continue; }
853
+ if (ch === "[") {
854
+ i++;
855
+ while (i < pattern.length && pattern[i] !== "]") {
856
+ if (pattern[i] === "\\\\") i++;
857
+ i++;
858
+ }
859
+ i++;
860
+ continue;
861
+ }
862
+ if (ch === "(") {
863
+ depth++;
864
+ if (quantifierAtDepth.length <= depth) quantifierAtDepth.push(false);
865
+ else quantifierAtDepth[depth] = false;
866
+ i++;
867
+ continue;
868
+ }
869
+ if (ch === ")") {
870
+ const hadQ = depth > 0 && quantifierAtDepth[depth];
871
+ if (depth > 0) depth--;
872
+ const next = pattern[i + 1];
873
+ if (next === "+" || next === "*" || next === "{") {
874
+ if (hadQ) return false;
875
+ if (depth >= 0 && depth < quantifierAtDepth.length) quantifierAtDepth[depth] = true;
876
+ }
877
+ i++;
878
+ continue;
879
+ }
880
+ if (ch === "+" || ch === "*") {
881
+ if (depth > 0) quantifierAtDepth[depth] = true;
882
+ i++;
883
+ continue;
884
+ }
885
+ if (ch === "?") {
886
+ const prev = i > 0 ? pattern[i - 1] : "";
887
+ if (prev !== "+" && prev !== "*" && prev !== "?" && prev !== "}") {
888
+ if (depth > 0) quantifierAtDepth[depth] = true;
889
+ }
890
+ i++;
891
+ continue;
892
+ }
893
+ if (ch === "{") {
894
+ let j = i + 1;
895
+ while (j < pattern.length && /[\\d,]/.test(pattern[j])) j++;
896
+ if (j < pattern.length && pattern[j] === "}" && j > i + 1) {
897
+ if (depth > 0) quantifierAtDepth[depth] = true;
898
+ i = j + 1;
899
+ continue;
900
+ }
901
+ }
902
+ i++;
903
+ }
904
+ return true;
905
+ }
906
+ function __safeRegExp(pattern, flags) {
907
+ if (!__isSafeRegex(pattern)) {
908
+ console.warn("[vinext] Ignoring potentially unsafe regex pattern (ReDoS risk): " + pattern);
909
+ return null;
910
+ }
911
+ try { return new RegExp(pattern, flags); } catch { return null; }
912
+ }
913
+
914
+ // ── Config pattern matching (redirects, rewrites, headers) ──────────────
915
+ function __matchConfigPattern(pathname, pattern) {
916
+ if (pattern.includes("(") || pattern.includes("\\\\") || /:\\w+[*+][^/]/.test(pattern)) {
917
+ try {
918
+ const paramNames = [];
919
+ const regexStr = pattern
920
+ .replace(/\\./g, "\\\\.")
921
+ .replace(/:([a-zA-Z_]\\w*)\\*(?:\\(([^)]+)\\))?/g, (_, name, c) => { paramNames.push(name); return c ? "(" + c + ")" : "(.*)"; })
922
+ .replace(/:([a-zA-Z_]\\w*)\\+(?:\\(([^)]+)\\))?/g, (_, name, c) => { paramNames.push(name); return c ? "(" + c + ")" : "(.+)"; })
923
+ .replace(/:([a-zA-Z_]\\w*)\\(([^)]+)\\)/g, (_, name, c) => { paramNames.push(name); return "(" + c + ")"; })
924
+ .replace(/:([a-zA-Z_]\\w*)/g, (_, name) => { paramNames.push(name); return "([^/]+)"; });
925
+ const re = __safeRegExp("^" + regexStr + "$");
926
+ if (!re) return null;
927
+ const match = re.exec(pathname);
928
+ if (!match) return null;
929
+ const params = Object.create(null);
930
+ for (let i = 0; i < paramNames.length; i++) params[paramNames[i]] = match[i + 1] || "";
931
+ return params;
932
+ } catch { /* fall through */ }
933
+ }
934
+ const catchAllMatch = pattern.match(/:([a-zA-Z_]\\w*)(\\*|\\+)$/);
935
+ if (catchAllMatch) {
936
+ const prefix = pattern.slice(0, pattern.lastIndexOf(":"));
937
+ const paramName = catchAllMatch[1];
938
+ const isPlus = catchAllMatch[2] === "+";
939
+ if (!pathname.startsWith(prefix.replace(/\\/$/, ""))) return null;
940
+ const rest = pathname.slice(prefix.replace(/\\/$/, "").length);
941
+ if (isPlus && (!rest || rest === "/")) return null;
942
+ let restValue = rest.startsWith("/") ? rest.slice(1) : rest;
943
+ try { restValue = decodeURIComponent(restValue); } catch {}
944
+ return { [paramName]: restValue };
945
+ }
946
+ const parts = pattern.split("/");
947
+ const pathParts = pathname.split("/");
948
+ if (parts.length !== pathParts.length) return null;
949
+ const params = Object.create(null);
950
+ for (let i = 0; i < parts.length; i++) {
951
+ if (parts[i].startsWith(":")) params[parts[i].slice(1)] = pathParts[i];
952
+ else if (parts[i] !== pathParts[i]) return null;
953
+ }
954
+ return params;
955
+ }
956
+
957
+ function __parseCookies(cookieHeader) {
958
+ if (!cookieHeader) return {};
959
+ const cookies = {};
960
+ for (const part of cookieHeader.split(";")) {
961
+ const eq = part.indexOf("=");
962
+ if (eq === -1) continue;
963
+ const key = part.slice(0, eq).trim();
964
+ const value = part.slice(eq + 1).trim();
965
+ if (key) cookies[key] = value;
966
+ }
967
+ return cookies;
968
+ }
969
+
970
+ function __checkSingleCondition(condition, ctx) {
971
+ switch (condition.type) {
972
+ case "header": {
973
+ const v = ctx.headers.get(condition.key);
974
+ if (v === null) return false;
975
+ if (condition.value !== undefined) { const re = __safeRegExp(condition.value); return re ? re.test(v) : v === condition.value; }
976
+ return true;
977
+ }
978
+ case "cookie": {
979
+ const v = ctx.cookies[condition.key];
980
+ if (v === undefined) return false;
981
+ if (condition.value !== undefined) { const re = __safeRegExp(condition.value); return re ? re.test(v) : v === condition.value; }
982
+ return true;
983
+ }
984
+ case "query": {
985
+ const v = ctx.query.get(condition.key);
986
+ if (v === null) return false;
987
+ if (condition.value !== undefined) { const re = __safeRegExp(condition.value); return re ? re.test(v) : v === condition.value; }
988
+ return true;
989
+ }
990
+ case "host": {
991
+ if (condition.value !== undefined) { const re = __safeRegExp(condition.value); return re ? re.test(ctx.host) : ctx.host === condition.value; }
992
+ return ctx.host === condition.key;
993
+ }
994
+ default: return false;
995
+ }
996
+ }
997
+
998
+ function __checkHasConditions(has, missing, ctx) {
999
+ if (has) { for (const c of has) { if (!__checkSingleCondition(c, ctx)) return false; } }
1000
+ if (missing) { for (const c of missing) { if (__checkSingleCondition(c, ctx)) return false; } }
1001
+ return true;
1002
+ }
1003
+
1004
+ function __buildRequestContext(request) {
1005
+ const url = new URL(request.url);
1006
+ return {
1007
+ headers: request.headers,
1008
+ cookies: __parseCookies(request.headers.get("cookie")),
1009
+ query: url.searchParams,
1010
+ host: request.headers.get("host") || url.host,
1011
+ };
1012
+ }
1013
+
1014
+ function __applyConfigRedirects(pathname, ctx) {
1015
+ for (const rule of __configRedirects) {
1016
+ const params = __matchConfigPattern(pathname, rule.source);
1017
+ if (params) {
1018
+ if (ctx && (rule.has || rule.missing)) { if (!__checkHasConditions(rule.has, rule.missing, ctx)) continue; }
1019
+ let dest = rule.destination;
1020
+ for (const [key, value] of Object.entries(params)) { dest = dest.replace(":" + key + "*", value); dest = dest.replace(":" + key + "+", value); dest = dest.replace(":" + key, value); }
1021
+ return { destination: dest, permanent: rule.permanent };
1022
+ }
1023
+ }
1024
+ return null;
1025
+ }
1026
+
1027
+ function __applyConfigRewrites(pathname, rules, ctx) {
1028
+ for (const rule of rules) {
1029
+ const params = __matchConfigPattern(pathname, rule.source);
1030
+ if (params) {
1031
+ if (ctx && (rule.has || rule.missing)) { if (!__checkHasConditions(rule.has, rule.missing, ctx)) continue; }
1032
+ let dest = rule.destination;
1033
+ for (const [key, value] of Object.entries(params)) { dest = dest.replace(":" + key + "*", value); dest = dest.replace(":" + key + "+", value); dest = dest.replace(":" + key, value); }
1034
+ return dest;
1035
+ }
1036
+ }
1037
+ return null;
1038
+ }
1039
+
1040
+ function __isExternalUrl(url) {
1041
+ return url.startsWith("http://") || url.startsWith("https://");
1042
+ }
1043
+
1044
+ const __hopByHopHeaders = new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade"]);
1045
+
1046
+ async function __proxyExternalRequest(request, externalUrl) {
1047
+ const originalUrl = new URL(request.url);
1048
+ const targetUrl = new URL(externalUrl);
1049
+ for (const [key, value] of originalUrl.searchParams) {
1050
+ if (!targetUrl.searchParams.has(key)) targetUrl.searchParams.set(key, value);
1051
+ }
1052
+ const headers = new Headers(request.headers);
1053
+ headers.set("host", targetUrl.host);
1054
+ headers.delete("connection");
1055
+ const method = request.method;
1056
+ const hasBody = method !== "GET" && method !== "HEAD";
1057
+ const init = { method, headers, redirect: "manual" };
1058
+ if (hasBody && request.body) { init.body = request.body; init.duplex = "half"; }
1059
+ let upstream;
1060
+ try { upstream = await fetch(targetUrl.href, init); }
1061
+ catch (e) { console.error("[vinext] External rewrite proxy error:", e); return new Response("Bad Gateway", { status: 502 }); }
1062
+ const respHeaders = new Headers();
1063
+ upstream.headers.forEach(function(value, key) { if (!__hopByHopHeaders.has(key.toLowerCase())) respHeaders.append(key, value); });
1064
+ return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers: respHeaders });
1065
+ }
1066
+
1067
+ function __applyConfigHeaders(pathname) {
1068
+ const result = [];
1069
+ for (const rule of __configHeaders) {
1070
+ const groups = [];
1071
+ const withPlaceholders = rule.source.replace(/\\(([^)]+)\\)/g, (_, inner) => {
1072
+ groups.push(inner);
1073
+ return "___GROUP_" + (groups.length - 1) + "___";
1074
+ });
1075
+ const escaped = withPlaceholders
1076
+ .replace(/\\./g, "\\\\.")
1077
+ .replace(/\\+/g, "\\\\+")
1078
+ .replace(/\\?/g, "\\\\?")
1079
+ .replace(/\\*/g, ".*")
1080
+ .replace(/:[a-zA-Z_]\\w*/g, "[^/]+")
1081
+ .replace(/___GROUP_(\\d+)___/g, (_, idx) => "(" + groups[Number(idx)] + ")");
1082
+ const sourceRegex = __safeRegExp("^" + escaped + "$");
1083
+ if (sourceRegex && sourceRegex.test(pathname)) result.push(...rule.headers);
1084
+ }
1085
+ return result;
1086
+ }
1087
+
1088
+ export default async function handler(request) {
1089
+ // Wrap the entire request handling in runWithHeadersContext to ensure
1090
+ // headers() and cookies() work throughout the async RSC rendering pipeline.
1091
+ // This uses AsyncLocalStorage.run() which properly propagates through awaits.
1092
+ const headersCtx = headersContextFromRequest(request);
1093
+ return runWithHeadersContext(headersCtx, async () => {
1094
+ // Initialize per-request state for cache and private cache isolation.
1095
+ _initRequestScopedCacheState();
1096
+ _clearPrivateCache();
1097
+ // Install patched fetch with Next.js caching semantics for this request.
1098
+ // runWithFetchCache uses AsyncLocalStorage.run() for proper per-request
1099
+ // isolation of collected fetch tags in concurrent environments.
1100
+ return runWithFetchCache(async () => {
1101
+ const response = await _handleRequest(request);
1102
+ // Apply custom headers from next.config.js to non-redirect responses.
1103
+ // Skip redirects (3xx) because Response.redirect() creates immutable headers,
1104
+ // and Next.js doesn't apply custom headers to redirects anyway.
1105
+ if (__configHeaders.length && response && response.headers && !(response.status >= 300 && response.status < 400)) {
1106
+ const url = new URL(request.url);
1107
+ let pathname = url.pathname;
1108
+ ${bp ? `if (pathname.startsWith(${JSON.stringify(bp)})) pathname = pathname.slice(${JSON.stringify(bp)}.length) || "/";` : ""}
1109
+ const extraHeaders = __applyConfigHeaders(pathname);
1110
+ for (const h of extraHeaders) {
1111
+ response.headers.set(h.key, h.value);
1112
+ }
1113
+ }
1114
+ return response;
1115
+ });
1116
+ });
1117
+ }
1118
+
1119
+ async function _handleRequest(request) {
1120
+ const url = new URL(request.url);
1121
+ let pathname = url.pathname;
1122
+
1123
+ // Guard against protocol-relative URL open redirect attacks.
1124
+ // Paths like //example.com/ would be redirected to //example.com by the
1125
+ // trailing-slash normalizer, which browsers interpret as http://example.com.
1126
+ // Next.js returns 404 for these paths. Check the raw pathname before any
1127
+ // basePath stripping so the guard cannot be bypassed with a basePath prefix.
1128
+ if (pathname.startsWith("//")) {
1129
+ return new Response("404 Not Found", { status: 404 });
1130
+ }
1131
+
1132
+ ${bp ? `
1133
+ // Strip basePath prefix
1134
+ if (__basePath && pathname.startsWith(__basePath)) {
1135
+ pathname = pathname.slice(__basePath.length) || "/";
1136
+ }
1137
+ ` : ""}
1138
+
1139
+ // Trailing slash normalization (redirect to canonical form)
1140
+ if (pathname !== "/" && !pathname.startsWith("/api")) {
1141
+ const hasTrailing = pathname.endsWith("/");
1142
+ if (__trailingSlash && !hasTrailing && !pathname.endsWith(".rsc")) {
1143
+ return Response.redirect(new URL(__basePath + pathname + "/" + url.search, request.url), 308);
1144
+ } else if (!__trailingSlash && hasTrailing) {
1145
+ return Response.redirect(new URL(__basePath + pathname.replace(/\\/+$/, "") + url.search, request.url), 308);
1146
+ }
1147
+ }
1148
+
1149
+ // ── Apply redirects from next.config.js ───────────────────────────────
1150
+ const __reqCtx = __buildRequestContext(request);
1151
+ if (__configRedirects.length) {
1152
+ const __redir = __applyConfigRedirects(pathname, __reqCtx);
1153
+ if (__redir) {
1154
+ const __redirDest = __basePath && !__redir.destination.startsWith(__basePath)
1155
+ ? __basePath + __redir.destination
1156
+ : __redir.destination;
1157
+ return new Response(null, {
1158
+ status: __redir.permanent ? 308 : 307,
1159
+ headers: { Location: __redirDest },
1160
+ });
1161
+ }
1162
+ }
1163
+
1164
+ // ── Apply beforeFiles rewrites from next.config.js ────────────────────
1165
+ if (__configRewrites.beforeFiles && __configRewrites.beforeFiles.length) {
1166
+ const __rewritten = __applyConfigRewrites(pathname, __configRewrites.beforeFiles, __reqCtx);
1167
+ if (__rewritten) {
1168
+ if (__isExternalUrl(__rewritten)) {
1169
+ setHeadersContext(null);
1170
+ setNavigationContext(null);
1171
+ return __proxyExternalRequest(request, __rewritten);
1172
+ }
1173
+ pathname = __rewritten;
1174
+ }
1175
+ }
1176
+
1177
+ const isRscRequest = pathname.endsWith(".rsc") || request.headers.get("accept")?.includes("text/x-component");
1178
+ let cleanPathname = pathname.replace(/\\.rsc$/, "");
1179
+
1180
+ // Middleware response headers to merge into the final response
1181
+ let _middlewareResponseHeaders = null;
1182
+ // Custom status code from middleware rewrite (e.g. NextResponse.rewrite(url, { status: 403 }))
1183
+ let _middlewareRewriteStatus = null;
1184
+
1185
+ ${middlewarePath ? `
1186
+ // Run proxy/middleware if present and path matches
1187
+ const middlewareFn = middlewareModule.default || middlewareModule.proxy || middlewareModule.middleware;
1188
+ const middlewareMatcher = middlewareModule.config?.matcher;
1189
+ if (typeof middlewareFn === "function" && matchMiddlewarePath(cleanPathname, middlewareMatcher)) {
1190
+ try {
1191
+ // Wrap in NextRequest so middleware gets .nextUrl, .cookies, .geo, .ip, etc.
1192
+ const nextRequest = request instanceof NextRequest ? request : new NextRequest(request);
1193
+ const mwResponse = await middlewareFn(nextRequest);
1194
+ if (mwResponse) {
1195
+ // Check for x-middleware-next (continue)
1196
+ if (mwResponse.headers.get("x-middleware-next") === "1") {
1197
+ // Middleware wants to continue - save headers to merge into final response
1198
+ _middlewareResponseHeaders = new Headers();
1199
+ for (const [key, value] of mwResponse.headers) {
1200
+ if (key !== "x-middleware-next" && key !== "x-middleware-rewrite") {
1201
+ _middlewareResponseHeaders.set(key, value);
1202
+ }
1203
+ }
1204
+ } else {
1205
+ // Check for redirect
1206
+ if (mwResponse.status >= 300 && mwResponse.status < 400) {
1207
+ return mwResponse;
1208
+ }
1209
+ // Check for rewrite
1210
+ const rewriteUrl = mwResponse.headers.get("x-middleware-rewrite");
1211
+ if (rewriteUrl) {
1212
+ const rewriteParsed = new URL(rewriteUrl, request.url);
1213
+ cleanPathname = rewriteParsed.pathname;
1214
+ // Capture custom status code from rewrite (e.g. NextResponse.rewrite(url, { status: 403 }))
1215
+ if (mwResponse.status !== 200) {
1216
+ _middlewareRewriteStatus = mwResponse.status;
1217
+ }
1218
+ // Also save any other headers from the rewrite response
1219
+ _middlewareResponseHeaders = new Headers();
1220
+ for (const [key, value] of mwResponse.headers) {
1221
+ if (key !== "x-middleware-next" && key !== "x-middleware-rewrite") {
1222
+ _middlewareResponseHeaders.set(key, value);
1223
+ }
1224
+ }
1225
+ } else {
1226
+ // Middleware returned a custom response
1227
+ return mwResponse;
1228
+ }
1229
+ }
1230
+ }
1231
+ } catch (err) {
1232
+ console.error("[vinext] Middleware error:", err);
1233
+ return new Response("Internal Server Error", { status: 500 });
1234
+ }
1235
+ }
1236
+
1237
+ // Unpack x-middleware-request-* headers into the request context so that
1238
+ // headers() returns the middleware-modified headers instead of the original
1239
+ // request headers. Also strip those internal headers from the set that will
1240
+ // be merged into the outgoing HTTP response.
1241
+ if (_middlewareResponseHeaders) {
1242
+ applyMiddlewareRequestHeaders(_middlewareResponseHeaders);
1243
+ for (const key of [..._middlewareResponseHeaders.keys()]) {
1244
+ if (key.startsWith("x-middleware-request-")) {
1245
+ _middlewareResponseHeaders.delete(key);
1246
+ }
1247
+ }
1248
+ }
1249
+ ` : ""}
1250
+
1251
+ // ── Image optimization passthrough (dev mode — no transformation) ───────
1252
+ if (cleanPathname === "/_vinext/image") {
1253
+ const __imgUrl = url.searchParams.get("url");
1254
+ // Allowlist: must start with "/" but not "//" — blocks absolute URLs,
1255
+ // protocol-relative, and exotic schemes (data:, javascript:, etc.).
1256
+ if (!__imgUrl || !__imgUrl.startsWith("/") || __imgUrl.startsWith("//")) {
1257
+ return new Response(!__imgUrl ? "Missing url parameter" : "Only relative URLs allowed", { status: 400 });
1258
+ }
1259
+ // In dev, redirect to the original asset URL so Vite's static serving handles it.
1260
+ return Response.redirect(new URL(__imgUrl, request.url).href, 302);
1261
+ }
1262
+
1263
+ // Handle metadata routes (sitemap.xml, robots.txt, manifest.webmanifest, etc.)
1264
+ for (const metaRoute of metadataRoutes) {
1265
+ if (cleanPathname === metaRoute.servedUrl) {
1266
+ if (metaRoute.isDynamic) {
1267
+ // Dynamic metadata route — call the default export and serialize
1268
+ const metaFn = metaRoute.module.default;
1269
+ if (typeof metaFn === "function") {
1270
+ const result = await metaFn();
1271
+ let body;
1272
+ // If it's already a Response (e.g., ImageResponse), return directly
1273
+ if (result instanceof Response) return result;
1274
+ // Serialize based on type
1275
+ if (metaRoute.type === "sitemap") body = sitemapToXml(result);
1276
+ else if (metaRoute.type === "robots") body = robotsToText(result);
1277
+ else if (metaRoute.type === "manifest") body = manifestToJson(result);
1278
+ else body = JSON.stringify(result);
1279
+ return new Response(body, {
1280
+ headers: { "Content-Type": metaRoute.contentType },
1281
+ });
1282
+ }
1283
+ } else {
1284
+ // Static metadata file — decode from embedded base64 data
1285
+ try {
1286
+ const binary = atob(metaRoute.fileDataBase64);
1287
+ const bytes = new Uint8Array(binary.length);
1288
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1289
+ return new Response(bytes, {
1290
+ headers: {
1291
+ "Content-Type": metaRoute.contentType,
1292
+ "Cache-Control": "public, max-age=0, must-revalidate",
1293
+ },
1294
+ });
1295
+ } catch {
1296
+ return new Response("Not Found", { status: 404 });
1297
+ }
1298
+ }
1299
+ }
1300
+ }
1301
+
1302
+ // Set navigation context for Server Components.
1303
+ // Note: Headers context is already set by runWithHeadersContext in the handler wrapper.
1304
+ setNavigationContext({
1305
+ pathname: cleanPathname,
1306
+ searchParams: url.searchParams,
1307
+ params: {},
1308
+ });
1309
+
1310
+ // Handle server action POST requests
1311
+ const actionId = request.headers.get("x-rsc-action");
1312
+ if (request.method === "POST" && actionId) {
1313
+ // ── CSRF protection ─────────────────────────────────────────────────
1314
+ // Verify that the Origin header matches the Host header to prevent
1315
+ // cross-site request forgery, matching Next.js server action behavior.
1316
+ const csrfResponse = __validateCsrfOrigin(request);
1317
+ if (csrfResponse) return csrfResponse;
1318
+ try {
1319
+ const contentType = request.headers.get("content-type") || "";
1320
+ const body = contentType.startsWith("multipart/form-data")
1321
+ ? await request.formData()
1322
+ : await request.text();
1323
+ const temporaryReferences = createTemporaryReferenceSet();
1324
+ const args = await decodeReply(body, { temporaryReferences });
1325
+ const action = await loadServerAction(actionId);
1326
+ let returnValue;
1327
+ let actionRedirect = null;
1328
+ try {
1329
+ const data = await action.apply(null, args);
1330
+ returnValue = { ok: true, data };
1331
+ } catch (e) {
1332
+ // Detect redirect() / permanentRedirect() called inside the action.
1333
+ // These throw errors with digest "NEXT_REDIRECT;replace;url[;status]".
1334
+ if (e && typeof e === "object" && "digest" in e) {
1335
+ const digest = String(e.digest);
1336
+ if (digest.startsWith("NEXT_REDIRECT;")) {
1337
+ const parts = digest.split(";");
1338
+ actionRedirect = {
1339
+ url: parts[2],
1340
+ type: parts[1] || "replace", // "push" or "replace"
1341
+ status: parts[3] ? parseInt(parts[3], 10) : 307,
1342
+ };
1343
+ returnValue = { ok: true, data: undefined };
1344
+ } else if (digest === "NEXT_NOT_FOUND" || digest.startsWith("NEXT_HTTP_ERROR_FALLBACK;")) {
1345
+ // notFound() / forbidden() / unauthorized() in action — package as error
1346
+ returnValue = { ok: false, data: e };
1347
+ } else {
1348
+ returnValue = { ok: false, data: e };
1349
+ }
1350
+ } else {
1351
+ returnValue = { ok: false, data: e };
1352
+ }
1353
+ }
1354
+
1355
+ // If the action called redirect(), signal the client to navigate.
1356
+ // We can't use a real HTTP redirect (the fetch would follow it automatically
1357
+ // and receive a page HTML instead of RSC stream). Instead, we return a 200
1358
+ // with x-action-redirect header that the client entry detects and handles.
1359
+ if (actionRedirect) {
1360
+ const actionPendingCookies = getAndClearPendingCookies();
1361
+ const actionDraftCookie = getDraftModeCookieHeader();
1362
+ setHeadersContext(null);
1363
+ setNavigationContext(null);
1364
+ const redirectHeaders = new Headers({
1365
+ "Content-Type": "text/x-component; charset=utf-8",
1366
+ "x-action-redirect": actionRedirect.url,
1367
+ "x-action-redirect-type": actionRedirect.type,
1368
+ "x-action-redirect-status": String(actionRedirect.status),
1369
+ });
1370
+ for (const cookie of actionPendingCookies) {
1371
+ redirectHeaders.append("Set-Cookie", cookie);
1372
+ }
1373
+ if (actionDraftCookie) redirectHeaders.append("Set-Cookie", actionDraftCookie);
1374
+ // Send an empty RSC-like body (client will navigate instead of parsing)
1375
+ return new Response("", { status: 200, headers: redirectHeaders });
1376
+ }
1377
+
1378
+ // After the action, re-render the current page so the client
1379
+ // gets an updated React tree reflecting any mutations.
1380
+ const match = matchRoute(cleanPathname, routes);
1381
+ let element;
1382
+ if (match) {
1383
+ const { route: actionRoute, params: actionParams } = match;
1384
+ setNavigationContext({
1385
+ pathname: cleanPathname,
1386
+ searchParams: url.searchParams,
1387
+ params: actionParams,
1388
+ });
1389
+ element = buildPageElement(actionRoute, actionParams, undefined, url.searchParams);
1390
+ } else {
1391
+ element = createElement("div", null, "Page not found");
1392
+ }
1393
+
1394
+ const rscStream = renderToReadableStream(
1395
+ { root: element, returnValue },
1396
+ { temporaryReferences, onError: rscOnError },
1397
+ );
1398
+
1399
+ // Collect cookies set during the action
1400
+ const actionPendingCookies = getAndClearPendingCookies();
1401
+ const actionDraftCookie = getDraftModeCookieHeader();
1402
+ setHeadersContext(null);
1403
+ setNavigationContext(null);
1404
+
1405
+ const actionHeaders = { "Content-Type": "text/x-component; charset=utf-8" };
1406
+ const actionResponse = new Response(rscStream, { headers: actionHeaders });
1407
+ if (actionPendingCookies.length > 0 || actionDraftCookie) {
1408
+ for (const cookie of actionPendingCookies) {
1409
+ actionResponse.headers.append("Set-Cookie", cookie);
1410
+ }
1411
+ if (actionDraftCookie) actionResponse.headers.append("Set-Cookie", actionDraftCookie);
1412
+ }
1413
+ return actionResponse;
1414
+ } catch (err) {
1415
+ getAndClearPendingCookies(); // Clear pending cookies on error
1416
+ console.error("[vinext] Server action error:", err);
1417
+ _reportRequestError(
1418
+ err instanceof Error ? err : new Error(String(err)),
1419
+ { path: cleanPathname, method: request.method, headers: Object.fromEntries(request.headers.entries()) },
1420
+ { routerKind: "App Router", routePath: cleanPathname, routeType: "action" },
1421
+ ).catch(() => {});
1422
+ setHeadersContext(null);
1423
+ setNavigationContext(null);
1424
+ return new Response(
1425
+ process.env.NODE_ENV === "production"
1426
+ ? "Internal Server Error"
1427
+ : "Server action failed: " + (err && err.message ? err.message : String(err)),
1428
+ { status: 500 },
1429
+ );
1430
+ }
1431
+ }
1432
+
1433
+ // ── Apply afterFiles rewrites from next.config.js ──────────────────────
1434
+ if (__configRewrites.afterFiles && __configRewrites.afterFiles.length) {
1435
+ const __afterRewritten = __applyConfigRewrites(cleanPathname, __configRewrites.afterFiles, __reqCtx);
1436
+ if (__afterRewritten) {
1437
+ if (__isExternalUrl(__afterRewritten)) {
1438
+ setHeadersContext(null);
1439
+ setNavigationContext(null);
1440
+ return __proxyExternalRequest(request, __afterRewritten);
1441
+ }
1442
+ cleanPathname = __afterRewritten;
1443
+ }
1444
+ }
1445
+
1446
+ let match = matchRoute(cleanPathname, routes);
1447
+
1448
+ // ── Fallback rewrites from next.config.js (if no route matched) ───────
1449
+ if (!match && __configRewrites.fallback && __configRewrites.fallback.length) {
1450
+ const __fallbackRewritten = __applyConfigRewrites(cleanPathname, __configRewrites.fallback, __reqCtx);
1451
+ if (__fallbackRewritten) {
1452
+ if (__isExternalUrl(__fallbackRewritten)) {
1453
+ setHeadersContext(null);
1454
+ setNavigationContext(null);
1455
+ return __proxyExternalRequest(request, __fallbackRewritten);
1456
+ }
1457
+ cleanPathname = __fallbackRewritten;
1458
+ match = matchRoute(cleanPathname, routes);
1459
+ }
1460
+ }
1461
+
1462
+ if (!match) {
1463
+ // Render custom not-found page if available, otherwise plain 404
1464
+ const notFoundResponse = await renderNotFoundPage(null, isRscRequest, request);
1465
+ if (notFoundResponse) return notFoundResponse;
1466
+ setHeadersContext(null);
1467
+ setNavigationContext(null);
1468
+ return new Response("Not Found", { status: 404 });
1469
+ }
1470
+
1471
+ const { route, params } = match;
1472
+
1473
+ // Update navigation context with matched params
1474
+ setNavigationContext({
1475
+ pathname: cleanPathname,
1476
+ searchParams: url.searchParams,
1477
+ params,
1478
+ });
1479
+
1480
+ // Handle route.ts API handlers
1481
+ if (route.routeHandler) {
1482
+ const handler = route.routeHandler;
1483
+ const method = request.method.toUpperCase();
1484
+
1485
+ // Collect exported HTTP methods for OPTIONS auto-response and Allow header
1486
+ const HTTP_METHODS = ["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"];
1487
+ const exportedMethods = HTTP_METHODS.filter((m) => typeof handler[m] === "function");
1488
+ // If GET is exported, HEAD is implicitly supported
1489
+ if (exportedMethods.includes("GET") && !exportedMethods.includes("HEAD")) {
1490
+ exportedMethods.push("HEAD");
1491
+ }
1492
+ const hasDefault = typeof handler["default"] === "function";
1493
+
1494
+ // OPTIONS auto-implementation: respond with Allow header and 204
1495
+ if (method === "OPTIONS" && typeof handler["OPTIONS"] !== "function") {
1496
+ const allowMethods = hasDefault ? HTTP_METHODS : exportedMethods;
1497
+ if (!allowMethods.includes("OPTIONS")) allowMethods.push("OPTIONS");
1498
+ setHeadersContext(null);
1499
+ setNavigationContext(null);
1500
+ return new Response(null, {
1501
+ status: 204,
1502
+ headers: { "Allow": allowMethods.join(", ") },
1503
+ });
1504
+ }
1505
+
1506
+ // HEAD auto-implementation: run GET handler and strip body
1507
+ let handlerFn = handler[method] || handler["default"];
1508
+ let isAutoHead = false;
1509
+ if (method === "HEAD" && typeof handler["HEAD"] !== "function" && typeof handler["GET"] === "function") {
1510
+ handlerFn = handler["GET"];
1511
+ isAutoHead = true;
1512
+ }
1513
+
1514
+ if (typeof handlerFn === "function") {
1515
+ try {
1516
+ const response = await handlerFn(request, { params });
1517
+
1518
+ // Collect any Set-Cookie headers from cookies().set()/delete() calls
1519
+ const pendingCookies = getAndClearPendingCookies();
1520
+ const draftCookie = getDraftModeCookieHeader();
1521
+ setHeadersContext(null);
1522
+ setNavigationContext(null);
1523
+
1524
+ // If we have pending cookies, create a new response with them attached
1525
+ if (pendingCookies.length > 0 || draftCookie) {
1526
+ const newHeaders = new Headers(response.headers);
1527
+ for (const cookie of pendingCookies) {
1528
+ newHeaders.append("Set-Cookie", cookie);
1529
+ }
1530
+ if (draftCookie) newHeaders.append("Set-Cookie", draftCookie);
1531
+
1532
+ if (isAutoHead) {
1533
+ return new Response(null, {
1534
+ status: response.status,
1535
+ statusText: response.statusText,
1536
+ headers: newHeaders,
1537
+ });
1538
+ }
1539
+ return new Response(response.body, {
1540
+ status: response.status,
1541
+ statusText: response.statusText,
1542
+ headers: newHeaders,
1543
+ });
1544
+ }
1545
+
1546
+ if (isAutoHead) {
1547
+ // Strip body for auto-HEAD, preserve headers and status
1548
+ return new Response(null, {
1549
+ status: response.status,
1550
+ statusText: response.statusText,
1551
+ headers: response.headers,
1552
+ });
1553
+ }
1554
+ return response;
1555
+ } catch (err) {
1556
+ getAndClearPendingCookies(); // Clear any pending cookies on error
1557
+ // Catch redirect() / notFound() thrown from route handlers
1558
+ if (err && typeof err === "object" && "digest" in err) {
1559
+ const digest = String(err.digest);
1560
+ if (digest.startsWith("NEXT_REDIRECT;")) {
1561
+ const parts = digest.split(";");
1562
+ const redirectUrl = parts[2];
1563
+ const statusCode = parts[3] ? parseInt(parts[3], 10) : 307;
1564
+ setHeadersContext(null);
1565
+ setNavigationContext(null);
1566
+ return new Response(null, {
1567
+ status: statusCode,
1568
+ headers: { Location: new URL(redirectUrl, request.url).toString() },
1569
+ });
1570
+ }
1571
+ if (digest === "NEXT_NOT_FOUND" || digest.startsWith("NEXT_HTTP_ERROR_FALLBACK;")) {
1572
+ const statusCode = digest === "NEXT_NOT_FOUND" ? 404 : parseInt(digest.split(";")[1], 10);
1573
+ setHeadersContext(null);
1574
+ setNavigationContext(null);
1575
+ return new Response(null, { status: statusCode });
1576
+ }
1577
+ }
1578
+ setHeadersContext(null);
1579
+ setNavigationContext(null);
1580
+ console.error("[vinext] Route handler error:", err);
1581
+ _reportRequestError(
1582
+ err instanceof Error ? err : new Error(String(err)),
1583
+ { path: cleanPathname, method: request.method, headers: Object.fromEntries(request.headers.entries()) },
1584
+ { routerKind: "App Router", routePath: route.pattern, routeType: "route" },
1585
+ ).catch(() => {});
1586
+ return new Response(null, { status: 500 });
1587
+ }
1588
+ }
1589
+ setHeadersContext(null);
1590
+ setNavigationContext(null);
1591
+ return new Response(null, {
1592
+ status: 405,
1593
+ headers: { Allow: exportedMethods.join(", ") },
1594
+ });
1595
+ }
1596
+
1597
+ // Build the component tree: layouts wrapping the page
1598
+ const PageComponent = route.page?.default;
1599
+ if (!PageComponent) {
1600
+ setHeadersContext(null);
1601
+ setNavigationContext(null);
1602
+ return new Response("Page has no default export", { status: 500 });
1603
+ }
1604
+
1605
+ // Read route segment config from page module exports
1606
+ let revalidateSeconds = typeof route.page?.revalidate === "number" ? route.page.revalidate : null;
1607
+ const dynamicConfig = route.page?.dynamic; // 'auto' | 'force-dynamic' | 'force-static' | 'error'
1608
+ const dynamicParamsConfig = route.page?.dynamicParams; // true (default) | false
1609
+ const isForceStatic = dynamicConfig === "force-static";
1610
+ const isDynamicError = dynamicConfig === "error";
1611
+
1612
+ // force-static: replace headers/cookies context with empty values and
1613
+ // clear searchParams so dynamic APIs return defaults instead of real data
1614
+ if (isForceStatic) {
1615
+ setHeadersContext({ headers: new Headers(), cookies: new Map() });
1616
+ setNavigationContext({
1617
+ pathname: cleanPathname,
1618
+ searchParams: new URLSearchParams(),
1619
+ params,
1620
+ });
1621
+ }
1622
+
1623
+ // dynamic = 'error': set a trap context that throws when headers/cookies are accessed
1624
+ if (isDynamicError) {
1625
+ const errorMsg = 'Page with \`dynamic = "error"\` used a dynamic API. ' +
1626
+ 'This page was expected to be fully static, but headers(), cookies(), ' +
1627
+ 'or searchParams was accessed. Remove the dynamic API usage or change ' +
1628
+ 'the dynamic config to "auto" or "force-dynamic".';
1629
+ const throwingHeaders = new Proxy(new Headers(), {
1630
+ get(target, prop) {
1631
+ if (typeof prop === "string" && prop !== "then") throw new Error(errorMsg);
1632
+ return Reflect.get(target, prop);
1633
+ },
1634
+ });
1635
+ const throwingCookies = new Proxy(new Map(), {
1636
+ get(target, prop) {
1637
+ if (typeof prop === "string" && prop !== "then") throw new Error(errorMsg);
1638
+ return Reflect.get(target, prop);
1639
+ },
1640
+ });
1641
+ setHeadersContext({ headers: throwingHeaders, cookies: throwingCookies });
1642
+ setNavigationContext({
1643
+ pathname: cleanPathname,
1644
+ searchParams: new URLSearchParams(),
1645
+ params,
1646
+ });
1647
+ }
1648
+
1649
+ // dynamicParams = false: only params from generateStaticParams are allowed
1650
+ if (dynamicParamsConfig === false && route.isDynamic && typeof route.page?.generateStaticParams === "function") {
1651
+ try {
1652
+ // Pass parent params to generateStaticParams (Next.js top-down params passing).
1653
+ // Parent params = all matched params that DON'T belong to the leaf page's own dynamic segments.
1654
+ // We pass the full matched params; the function uses only what it needs.
1655
+ const staticParams = await route.page.generateStaticParams({ params });
1656
+ if (Array.isArray(staticParams)) {
1657
+ const paramKeys = Object.keys(params);
1658
+ const isAllowed = staticParams.some(sp =>
1659
+ paramKeys.every(key => {
1660
+ const val = params[key];
1661
+ const staticVal = sp[key];
1662
+ // Allow parent params to not be in the returned set (they're inherited)
1663
+ if (staticVal === undefined) return true;
1664
+ if (Array.isArray(val)) return JSON.stringify(val) === JSON.stringify(staticVal);
1665
+ return String(val) === String(staticVal);
1666
+ })
1667
+ );
1668
+ if (!isAllowed) {
1669
+ setHeadersContext(null);
1670
+ setNavigationContext(null);
1671
+ return new Response("Not Found", { status: 404 });
1672
+ }
1673
+ }
1674
+ } catch (err) {
1675
+ console.error("[vinext] generateStaticParams error:", err);
1676
+ }
1677
+ }
1678
+
1679
+ // force-dynamic: set no-store Cache-Control
1680
+ const isForceDynamic = dynamicConfig === "force-dynamic";
1681
+
1682
+ // Check for intercepting routes on RSC requests (client-side navigation).
1683
+ // If the target URL matches an intercepting route in a parallel slot,
1684
+ // render the source route with the intercepting page in the slot.
1685
+ let interceptOpts = undefined;
1686
+ if (isRscRequest) {
1687
+ const intercept = findIntercept(cleanPathname);
1688
+ if (intercept) {
1689
+ const sourceRoute = routes[intercept.sourceRouteIndex];
1690
+ if (sourceRoute && sourceRoute !== route) {
1691
+ // Render the source route (e.g. /feed) with the intercepting page in the slot
1692
+ const sourceMatch = matchRoute(sourceRoute.pattern, routes);
1693
+ const sourceParams = sourceMatch ? sourceMatch.params : {};
1694
+ setNavigationContext({
1695
+ pathname: cleanPathname,
1696
+ searchParams: url.searchParams,
1697
+ params: intercept.matchedParams,
1698
+ });
1699
+ const interceptElement = await buildPageElement(sourceRoute, sourceParams, {
1700
+ interceptSlot: intercept.slotName,
1701
+ interceptPage: intercept.page,
1702
+ interceptParams: intercept.matchedParams,
1703
+ }, url.searchParams);
1704
+ const interceptStream = renderToReadableStream(interceptElement, { onError: rscOnError });
1705
+ setHeadersContext(null);
1706
+ setNavigationContext(null);
1707
+ return new Response(interceptStream, {
1708
+ headers: { "Content-Type": "text/x-component; charset=utf-8" },
1709
+ });
1710
+ }
1711
+ // If sourceRoute === route, apply intercept opts to the normal render
1712
+ interceptOpts = {
1713
+ interceptSlot: intercept.slotName,
1714
+ interceptPage: intercept.page,
1715
+ interceptParams: intercept.matchedParams,
1716
+ };
1717
+ }
1718
+ }
1719
+
1720
+ let element;
1721
+ try {
1722
+ element = await buildPageElement(route, params, interceptOpts, url.searchParams);
1723
+ } catch (buildErr) {
1724
+ // Check for redirect/notFound/forbidden/unauthorized thrown during metadata resolution or async components
1725
+ if (buildErr && typeof buildErr === "object" && "digest" in buildErr) {
1726
+ const digest = String(buildErr.digest);
1727
+ if (digest.startsWith("NEXT_REDIRECT;")) {
1728
+ const parts = digest.split(";");
1729
+ const redirectUrl = parts[2];
1730
+ const statusCode = parts[3] ? parseInt(parts[3], 10) : 307;
1731
+ setHeadersContext(null);
1732
+ setNavigationContext(null);
1733
+ return Response.redirect(new URL(redirectUrl, request.url), statusCode);
1734
+ }
1735
+ if (digest === "NEXT_NOT_FOUND" || digest.startsWith("NEXT_HTTP_ERROR_FALLBACK;")) {
1736
+ const statusCode = digest === "NEXT_NOT_FOUND" ? 404 : parseInt(digest.split(";")[1], 10);
1737
+ const fallbackResp = await renderHTTPAccessFallbackPage(route, statusCode, isRscRequest, request);
1738
+ if (fallbackResp) return fallbackResp;
1739
+ setHeadersContext(null);
1740
+ setNavigationContext(null);
1741
+ const statusText = statusCode === 403 ? "Forbidden" : statusCode === 401 ? "Unauthorized" : "Not Found";
1742
+ return new Response(statusText, { status: statusCode });
1743
+ }
1744
+ }
1745
+ // Non-special error (e.g. generateMetadata() threw) — render error.tsx if available
1746
+ const errorBoundaryResp = await renderErrorBoundaryPage(route, buildErr, isRscRequest, request);
1747
+ if (errorBoundaryResp) return errorBoundaryResp;
1748
+ throw buildErr;
1749
+ }
1750
+
1751
+ // Note: CSS is automatically injected by @vitejs/plugin-rsc's
1752
+ // rscCssTransform — no manual loadCss() call needed.
1753
+
1754
+ // Helper: check if an error is a redirect/notFound/forbidden/unauthorized thrown by the navigation shim
1755
+ async function handleRenderError(err) {
1756
+ if (err && typeof err === "object" && "digest" in err) {
1757
+ const digest = String(err.digest);
1758
+ if (digest.startsWith("NEXT_REDIRECT;")) {
1759
+ const parts = digest.split(";");
1760
+ const redirectUrl = parts[2];
1761
+ const statusCode = parts[3] ? parseInt(parts[3], 10) : 307;
1762
+ setHeadersContext(null);
1763
+ setNavigationContext(null);
1764
+ return Response.redirect(new URL(redirectUrl, request.url), statusCode);
1765
+ }
1766
+ if (digest === "NEXT_NOT_FOUND" || digest.startsWith("NEXT_HTTP_ERROR_FALLBACK;")) {
1767
+ const statusCode = digest === "NEXT_NOT_FOUND" ? 404 : parseInt(digest.split(";")[1], 10);
1768
+ const fallbackResp = await renderHTTPAccessFallbackPage(route, statusCode, isRscRequest, request);
1769
+ if (fallbackResp) return fallbackResp;
1770
+ setHeadersContext(null);
1771
+ setNavigationContext(null);
1772
+ const statusText = statusCode === 403 ? "Forbidden" : statusCode === 401 ? "Unauthorized" : "Not Found";
1773
+ return new Response(statusText, { status: statusCode });
1774
+ }
1775
+ }
1776
+ return null;
1777
+ }
1778
+
1779
+ // Pre-render layout components to catch notFound()/redirect() thrown from layouts.
1780
+ // In Next.js, each layout level has its own NotFoundBoundary. When a layout throws
1781
+ // notFound(), the parent layout's boundary catches it and renders the parent's
1782
+ // not-found.tsx. Since React Flight doesn't activate client error boundaries during
1783
+ // RSC rendering, we catch layout-level throws here and render the appropriate
1784
+ // fallback page with only the layouts above the throwing one.
1785
+ //
1786
+ // IMPORTANT: Layout pre-render runs BEFORE page pre-render. In Next.js, layouts
1787
+ // render before their children — if a layout throws notFound(), the page never
1788
+ // executes. By checking layouts first, we avoid a bug where the page's notFound()
1789
+ // triggers renderHTTPAccessFallbackPage with ALL route layouts, but one of those
1790
+ // layouts itself throws notFound() during the fallback rendering (causing a 500).
1791
+ if (route.layouts && route.layouts.length > 0) {
1792
+ const asyncParams = Object.assign(Promise.resolve(params), params);
1793
+ for (let li = route.layouts.length - 1; li >= 0; li--) {
1794
+ const LayoutComp = route.layouts[li]?.default;
1795
+ if (!LayoutComp) continue;
1796
+ try {
1797
+ const lr = LayoutComp({ params: asyncParams, children: null });
1798
+ if (lr && typeof lr === "object" && typeof lr.then === "function") await lr;
1799
+ } catch (layoutErr) {
1800
+ if (layoutErr && typeof layoutErr === "object" && "digest" in layoutErr) {
1801
+ const digest = String(layoutErr.digest);
1802
+ if (digest.startsWith("NEXT_REDIRECT;")) {
1803
+ const parts = digest.split(";");
1804
+ const redirectUrl = parts[2];
1805
+ const statusCode = parts[3] ? parseInt(parts[3], 10) : 307;
1806
+ setHeadersContext(null);
1807
+ setNavigationContext(null);
1808
+ return Response.redirect(new URL(redirectUrl, request.url), statusCode);
1809
+ }
1810
+ if (digest === "NEXT_NOT_FOUND" || digest.startsWith("NEXT_HTTP_ERROR_FALLBACK;")) {
1811
+ const statusCode = digest === "NEXT_NOT_FOUND" ? 404 : parseInt(digest.split(";")[1], 10);
1812
+ // Find the not-found component from the parent level (the boundary that
1813
+ // would catch this in Next.js). Walk up from the throwing layout to find
1814
+ // the nearest not-found at a parent layout's directory.
1815
+ let parentNotFound = null;
1816
+ if (route.notFounds) {
1817
+ for (let pi = li - 1; pi >= 0; pi--) {
1818
+ if (route.notFounds[pi]?.default) {
1819
+ parentNotFound = route.notFounds[pi].default;
1820
+ break;
1821
+ }
1822
+ }
1823
+ }
1824
+ if (!parentNotFound) parentNotFound = ${rootNotFoundVar ? `${rootNotFoundVar}?.default` : "null"};
1825
+ // Wrap in only the layouts above the throwing one
1826
+ const parentLayouts = route.layouts.slice(0, li);
1827
+ const fallbackResp = await renderHTTPAccessFallbackPage(
1828
+ route, statusCode, isRscRequest, request,
1829
+ { boundaryComponent: parentNotFound, layouts: parentLayouts }
1830
+ );
1831
+ if (fallbackResp) return fallbackResp;
1832
+ setHeadersContext(null);
1833
+ setNavigationContext(null);
1834
+ const statusText = statusCode === 403 ? "Forbidden" : statusCode === 401 ? "Unauthorized" : "Not Found";
1835
+ return new Response(statusText, { status: statusCode });
1836
+ }
1837
+ }
1838
+ // Not a special error — let it propagate through normal RSC rendering
1839
+ }
1840
+ }
1841
+ }
1842
+
1843
+ // Pre-render the page component to catch redirect()/notFound() thrown synchronously.
1844
+ // Server Components are just functions — we can call PageComponent directly to detect
1845
+ // these special throws before starting the RSC stream.
1846
+ //
1847
+ // For routes with a loading.tsx Suspense boundary, we skip awaiting async components.
1848
+ // The Suspense boundary + rscOnError will handle redirect/notFound thrown during
1849
+ // streaming, and blocking here would defeat streaming (the slow component's delay
1850
+ // would be hit before the RSC stream even starts).
1851
+ //
1852
+ // Because this calls the component outside React's render cycle, hooks like use()
1853
+ // trigger "Invalid hook call" console.error in dev. Suppress that expected warning.
1854
+ const _hasLoadingBoundary = !!(route.loading && route.loading.default);
1855
+ const _origConsoleError = console.error;
1856
+ console.error = (...args) => {
1857
+ if (typeof args[0] === "string" && args[0].includes("Invalid hook call")) return;
1858
+ _origConsoleError.apply(console, args);
1859
+ };
1860
+ try {
1861
+ const testResult = PageComponent({ params });
1862
+ // If it's a promise (async component), only await if there's no loading boundary.
1863
+ // With a loading boundary, the Suspense streaming pipeline handles async resolution
1864
+ // and any redirect/notFound errors via rscOnError.
1865
+ if (testResult && typeof testResult === "object" && typeof testResult.then === "function") {
1866
+ if (!_hasLoadingBoundary) {
1867
+ await testResult;
1868
+ } else {
1869
+ // Suppress unhandled promise rejection — with a loading boundary,
1870
+ // redirect/notFound errors are handled by rscOnError during streaming.
1871
+ testResult.catch(() => {});
1872
+ }
1873
+ }
1874
+ } catch (preRenderErr) {
1875
+ const specialResponse = await handleRenderError(preRenderErr);
1876
+ if (specialResponse) return specialResponse;
1877
+ // Non-special errors from the pre-render test are expected (e.g. use() hook
1878
+ // fails outside React's render cycle, client references can't execute on server).
1879
+ // Only redirect/notFound/forbidden/unauthorized are actionable here — other
1880
+ // errors will be properly caught during actual RSC/SSR rendering below.
1881
+ } finally {
1882
+ console.error = _origConsoleError;
1883
+ }
1884
+
1885
+ // Render to RSC stream
1886
+ const rscStream = renderToReadableStream(element, { onError: rscOnError });
1887
+
1888
+ if (isRscRequest) {
1889
+ // Direct RSC stream response (for client-side navigation)
1890
+ // NOTE: Do NOT clear headers/navigation context here!
1891
+ // The RSC stream is consumed lazily - components render when chunks are read.
1892
+ // If we clear context now, headers()/cookies() will fail during rendering.
1893
+ // Context will be cleared when the next request starts (via runWithHeadersContext).
1894
+ const responseHeaders = { "Content-Type": "text/x-component; charset=utf-8" };
1895
+ // Include matched route params so the client can hydrate useParams()
1896
+ if (params && Object.keys(params).length > 0) {
1897
+ responseHeaders["X-Vinext-Params"] = JSON.stringify(params);
1898
+ }
1899
+ if (isForceDynamic) {
1900
+ responseHeaders["Cache-Control"] = "no-store, must-revalidate";
1901
+ } else if ((isForceStatic || isDynamicError) && !revalidateSeconds) {
1902
+ responseHeaders["Cache-Control"] = "s-maxage=31536000, stale-while-revalidate";
1903
+ responseHeaders["X-Vinext-Cache"] = "STATIC";
1904
+ } else if (revalidateSeconds) {
1905
+ responseHeaders["Cache-Control"] = "s-maxage=" + revalidateSeconds + ", stale-while-revalidate";
1906
+ }
1907
+ // Merge middleware response headers into the RSC response
1908
+ if (_middlewareResponseHeaders) {
1909
+ for (const [key, value] of _middlewareResponseHeaders) {
1910
+ responseHeaders[key] = value;
1911
+ }
1912
+ }
1913
+ return new Response(rscStream, { status: _middlewareRewriteStatus || 200, headers: responseHeaders });
1914
+ }
1915
+
1916
+ // Collect font data from RSC environment before passing to SSR
1917
+ // (Fonts are loaded during RSC rendering when layout.tsx calls Geist() etc.)
1918
+ const fontData = {
1919
+ links: _getSSRFontLinks(),
1920
+ styles: _getSSRFontStyles(),
1921
+ preloads: _getSSRFontPreloads(),
1922
+ };
1923
+
1924
+ // Build HTTP Link header for font preloading.
1925
+ // This lets the browser (and CDN) start fetching font files before parsing HTML,
1926
+ // eliminating the CSS → woff2 download waterfall.
1927
+ const fontPreloads = fontData.preloads || [];
1928
+ const fontLinkHeaderParts = [];
1929
+ for (const preload of fontPreloads) {
1930
+ fontLinkHeaderParts.push("<" + preload.href + ">; rel=preload; as=font; type=" + preload.type + "; crossorigin");
1931
+ }
1932
+ const fontLinkHeader = fontLinkHeaderParts.length > 0 ? fontLinkHeaderParts.join(", ") : "";
1933
+
1934
+ // Delegate to SSR environment for HTML rendering
1935
+ let htmlStream;
1936
+ try {
1937
+ const ssrEntry = await import.meta.viteRsc.loadModule("ssr", "index");
1938
+ htmlStream = await ssrEntry.handleSsr(rscStream, _getNavigationContext(), fontData);
1939
+ } catch (ssrErr) {
1940
+ const specialResponse = await handleRenderError(ssrErr);
1941
+ if (specialResponse) return specialResponse;
1942
+ // Non-special error during SSR — render error.tsx if available
1943
+ const errorBoundaryResp = await renderErrorBoundaryPage(route, ssrErr, isRscRequest, request);
1944
+ if (errorBoundaryResp) return errorBoundaryResp;
1945
+ throw ssrErr;
1946
+ }
1947
+
1948
+ // Check for draftMode Set-Cookie header (from draftMode().enable()/disable())
1949
+ const draftCookie = getDraftModeCookieHeader();
1950
+
1951
+ setHeadersContext(null);
1952
+ setNavigationContext(null);
1953
+
1954
+ // Helper to attach draftMode cookie, middleware headers, font Link header, and rewrite status to a response
1955
+ function attachMiddlewareContext(response) {
1956
+ if (draftCookie) {
1957
+ response.headers.append("Set-Cookie", draftCookie);
1958
+ }
1959
+ // Set HTTP Link header for font preloading
1960
+ if (fontLinkHeader) {
1961
+ response.headers.set("Link", fontLinkHeader);
1962
+ }
1963
+ // Merge middleware response headers into the final response
1964
+ if (_middlewareResponseHeaders) {
1965
+ for (const [key, value] of _middlewareResponseHeaders) {
1966
+ response.headers.set(key, value);
1967
+ }
1968
+ }
1969
+ // Apply custom status code from middleware rewrite
1970
+ if (_middlewareRewriteStatus) {
1971
+ return new Response(response.body, {
1972
+ status: _middlewareRewriteStatus,
1973
+ headers: response.headers,
1974
+ });
1975
+ }
1976
+ return response;
1977
+ }
1978
+
1979
+ // Check if any component called connection(), cookies(), headers(), or noStore()
1980
+ // during rendering. If so, treat as dynamic (skip ISR, set no-store).
1981
+ const dynamicUsedDuringRender = consumeDynamicUsage();
1982
+
1983
+ // Check if cacheLife() was called during rendering (e.g., page with file-level "use cache").
1984
+ // If so, use its revalidation period for the Cache-Control header.
1985
+ const requestCacheLife = _consumeRequestScopedCacheLife();
1986
+ if (requestCacheLife && requestCacheLife.revalidate !== undefined && revalidateSeconds === null) {
1987
+ revalidateSeconds = requestCacheLife.revalidate;
1988
+ }
1989
+
1990
+ // force-dynamic: always return no-store (highest priority)
1991
+ if (isForceDynamic) {
1992
+ return attachMiddlewareContext(new Response(htmlStream, {
1993
+ headers: {
1994
+ "Content-Type": "text/html; charset=utf-8",
1995
+ "Cache-Control": "no-store, must-revalidate",
1996
+ },
1997
+ }));
1998
+ }
1999
+
2000
+ // force-static / error: treat as static regardless of dynamic usage.
2001
+ // force-static intentionally provides empty headers/cookies context so
2002
+ // dynamic APIs return safe defaults; we ignore the dynamic usage signal.
2003
+ // dynamic='error' should have already thrown (via throwing Proxy) if user
2004
+ // code accessed dynamic APIs, so reaching here means rendering succeeded.
2005
+ if ((isForceStatic || isDynamicError) && (revalidateSeconds === null || revalidateSeconds === 0)) {
2006
+ return attachMiddlewareContext(new Response(htmlStream, {
2007
+ headers: {
2008
+ "Content-Type": "text/html; charset=utf-8",
2009
+ "Cache-Control": "s-maxage=31536000, stale-while-revalidate",
2010
+ "X-Vinext-Cache": "STATIC",
2011
+ },
2012
+ }));
2013
+ }
2014
+
2015
+ // auto mode: dynamic API usage (headers(), cookies(), connection(), noStore(),
2016
+ // searchParams access) opts the page into dynamic rendering with no-store.
2017
+ if (dynamicUsedDuringRender) {
2018
+ return attachMiddlewareContext(new Response(htmlStream, {
2019
+ headers: {
2020
+ "Content-Type": "text/html; charset=utf-8",
2021
+ "Cache-Control": "no-store, must-revalidate",
2022
+ },
2023
+ }));
2024
+ }
2025
+
2026
+ // Emit Cache-Control for ISR pages so tests can verify revalidate values,
2027
+ // but skip actual caching in dev — every request renders fresh.
2028
+ if (revalidateSeconds !== null && revalidateSeconds > 0) {
2029
+ return attachMiddlewareContext(new Response(htmlStream, {
2030
+ headers: {
2031
+ "Content-Type": "text/html; charset=utf-8",
2032
+ "Cache-Control": "s-maxage=" + revalidateSeconds + ", stale-while-revalidate",
2033
+ },
2034
+ }));
2035
+ }
2036
+
2037
+ return attachMiddlewareContext(new Response(htmlStream, {
2038
+ headers: { "Content-Type": "text/html; charset=utf-8" },
2039
+ }));
2040
+ }
2041
+
2042
+ if (import.meta.hot) {
2043
+ import.meta.hot.accept();
2044
+ }
2045
+ `;
2046
+ }
2047
+ /**
2048
+ * Generate the virtual SSR entry module.
2049
+ *
2050
+ * This runs in the `ssr` Vite environment. It receives an RSC stream,
2051
+ * deserializes it to a React tree, and renders to HTML.
2052
+ */
2053
+ export function generateSsrEntry() {
2054
+ return `
2055
+ import { createFromReadableStream } from "@vitejs/plugin-rsc/ssr";
2056
+ import { renderToReadableStream } from "react-dom/server.edge";
2057
+ import { setNavigationContext } from "next/navigation";
2058
+ import { safeJsonStringify } from "vinext/html";
2059
+
2060
+ /**
2061
+ * Collect all chunks from a ReadableStream into an array of text strings.
2062
+ * Used to capture the RSC payload for embedding in HTML.
2063
+ * The RSC flight protocol is text-based (line-delimited key:value pairs),
2064
+ * so we decode to text strings instead of byte arrays — this is dramatically
2065
+ * more compact when JSON-serialized into inline <script> tags.
2066
+ */
2067
+ async function collectStreamChunks(stream) {
2068
+ const reader = stream.getReader();
2069
+ const decoder = new TextDecoder();
2070
+ const chunks = [];
2071
+ while (true) {
2072
+ const { done, value } = await reader.read();
2073
+ if (done) break;
2074
+ // Decode Uint8Array to text string for compact JSON serialization
2075
+ chunks.push(decoder.decode(value, { stream: true }));
2076
+ }
2077
+ return chunks;
2078
+ }
2079
+
2080
+ /**
2081
+ * Create a TransformStream that appends RSC chunks as inline <script> tags
2082
+ * to the HTML stream. This allows progressive hydration — the browser receives
2083
+ * RSC data incrementally as Suspense boundaries resolve, rather than waiting
2084
+ * for the entire RSC payload before hydration can begin.
2085
+ *
2086
+ * Each chunk is written as:
2087
+ * <script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push("...")</script>
2088
+ *
2089
+ * Chunks are embedded as text strings (not byte arrays) since the RSC flight
2090
+ * protocol is text-based. The browser entry encodes them back to Uint8Array.
2091
+ * This is ~3x more compact than the previous byte-array format.
2092
+ */
2093
+ function createRscEmbedTransform(embedStream) {
2094
+ const reader = embedStream.getReader();
2095
+ const _decoder = new TextDecoder();
2096
+ let done = false;
2097
+ let pendingChunks = [];
2098
+ let reading = false;
2099
+
2100
+ // Fix invalid preload "as" values in RSC Flight hint lines before
2101
+ // they reach the client. React Flight emits HL hints with
2102
+ // as="stylesheet" for CSS, but the HTML spec requires as="style"
2103
+ // for <link rel="preload">. The fixPreloadAs() below only fixes the
2104
+ // server-rendered HTML stream; this fixes the raw Flight data that
2105
+ // gets embedded as __VINEXT_RSC_CHUNKS__ and processed client-side.
2106
+ function fixFlightHints(text) {
2107
+ // Flight hint format: <id>:HL["url","stylesheet"] or with options
2108
+ return text.replace(/(\\d+:HL\\[.*?),"stylesheet"(\\]|,)/g, '$1,"style"$2');
2109
+ }
2110
+
2111
+ // Start reading RSC chunks in the background, accumulating them as text strings.
2112
+ // The RSC flight protocol is text-based, so decoding to strings and embedding
2113
+ // as JSON strings is ~3x more compact than the byte-array format.
2114
+ async function pumpReader() {
2115
+ if (reading) return;
2116
+ reading = true;
2117
+ try {
2118
+ while (true) {
2119
+ const result = await reader.read();
2120
+ if (result.done) {
2121
+ done = true;
2122
+ break;
2123
+ }
2124
+ const text = _decoder.decode(result.value, { stream: true });
2125
+ pendingChunks.push(fixFlightHints(text));
2126
+ }
2127
+ } catch (err) {
2128
+ if (process.env.NODE_ENV !== "production") {
2129
+ console.warn("[vinext] RSC embed stream read error:", err);
2130
+ }
2131
+ done = true;
2132
+ }
2133
+ reading = false;
2134
+ }
2135
+
2136
+ // Fire off the background reader immediately
2137
+ const pumpPromise = pumpReader();
2138
+
2139
+ return {
2140
+ /**
2141
+ * Flush any accumulated RSC chunks as <script> tags.
2142
+ * Called after each HTML chunk is enqueued.
2143
+ */
2144
+ flush() {
2145
+ if (pendingChunks.length === 0) return "";
2146
+ const chunks = pendingChunks;
2147
+ pendingChunks = [];
2148
+ let scripts = "";
2149
+ for (const chunk of chunks) {
2150
+ scripts += "<script>self.__VINEXT_RSC_CHUNKS__=self.__VINEXT_RSC_CHUNKS__||[];self.__VINEXT_RSC_CHUNKS__.push(" + safeJsonStringify(chunk) + ")</script>";
2151
+ }
2152
+ return scripts;
2153
+ },
2154
+
2155
+ /**
2156
+ * Wait for the RSC stream to fully complete and return any final
2157
+ * script tags plus the closing signal.
2158
+ */
2159
+ async finalize() {
2160
+ await pumpPromise;
2161
+ let scripts = this.flush();
2162
+ // Signal that all RSC chunks have been sent.
2163
+ // Params are already embedded in <head> — no need to include here.
2164
+ scripts += "<script>self.__VINEXT_RSC_DONE__=true</script>";
2165
+ return scripts;
2166
+ },
2167
+ };
2168
+ }
2169
+
2170
+ /**
2171
+ * Render the RSC stream to HTML.
2172
+ *
2173
+ * @param rscStream - The RSC payload stream from the RSC environment
2174
+ * @param navContext - Navigation context for client component SSR hooks.
2175
+ * "use client" components like those using usePathname() need the current
2176
+ * request URL during SSR, and they run in this SSR environment (separate
2177
+ * from the RSC environment where the context was originally set).
2178
+ * @param fontData - Font links and styles collected from the RSC environment.
2179
+ * Fonts are loaded during RSC rendering (when layout calls Geist() etc.),
2180
+ * and the data needs to be passed to SSR since they're separate module instances.
2181
+ */
2182
+ export async function handleSsr(rscStream, navContext, fontData) {
2183
+ // Set navigation context so hooks like usePathname() work during SSR
2184
+ // of "use client" components
2185
+ if (navContext) {
2186
+ setNavigationContext(navContext);
2187
+ }
2188
+
2189
+ // Clear any stale callbacks from previous requests
2190
+ const { clearServerInsertedHTML, flushServerInsertedHTML } = await import("next/navigation");
2191
+ clearServerInsertedHTML();
2192
+
2193
+ try {
2194
+ // Tee the RSC stream - one for SSR rendering, one for embedding in HTML.
2195
+ // This ensures the browser uses the SAME RSC payload for hydration that
2196
+ // was used to generate the HTML, avoiding hydration mismatches (React #418).
2197
+ const [ssrStream, embedStream] = rscStream.tee();
2198
+
2199
+ // Create the progressive RSC embed helper — it reads the embed stream
2200
+ // in the background and provides script tags to inject into the HTML stream.
2201
+ const rscEmbed = createRscEmbedTransform(embedStream);
2202
+
2203
+ // Deserialize RSC stream back to React VDOM.
2204
+ // IMPORTANT: Do NOT await this — createFromReadableStream returns a thenable
2205
+ // that React's renderToReadableStream can consume progressively. By passing
2206
+ // the unresolved thenable, React will render Suspense fallbacks (loading.tsx)
2207
+ // immediately in the HTML shell, then stream in resolved content as RSC
2208
+ // chunks arrive. Awaiting here would block until all async server components
2209
+ // complete, collapsing the streaming behavior.
2210
+ const root = createFromReadableStream(ssrStream);
2211
+
2212
+ // Get the bootstrap script content for the browser entry
2213
+ const bootstrapScriptContent =
2214
+ await import.meta.viteRsc.loadBootstrapScriptContent("index");
2215
+
2216
+ // Render HTML (streaming SSR)
2217
+ // useServerInsertedHTML callbacks are registered during this render.
2218
+ // The onError callback preserves the digest for Next.js navigation errors
2219
+ // (redirect, notFound, forbidden, unauthorized) thrown inside Suspense
2220
+ // boundaries during RSC streaming. Without this, React's default onError
2221
+ // returns undefined and the digest is lost in the $RX() call, preventing
2222
+ // client-side error boundaries from identifying the error type.
2223
+ const htmlStream = await renderToReadableStream(root, {
2224
+ bootstrapScriptContent,
2225
+ onError(error) {
2226
+ if (error && typeof error === "object" && "digest" in error) {
2227
+ return String(error.digest);
2228
+ }
2229
+ return undefined;
2230
+ },
2231
+ });
2232
+
2233
+
2234
+ // Flush useServerInsertedHTML callbacks (CSS-in-JS style injection)
2235
+ const insertedElements = flushServerInsertedHTML();
2236
+
2237
+ // Render the inserted elements to HTML strings
2238
+ const { renderToStaticMarkup } = await import("react-dom/server.edge");
2239
+ const { createElement, Fragment } = await import("react");
2240
+ let insertedHTML = "";
2241
+ for (const el of insertedElements) {
2242
+ try {
2243
+ insertedHTML += renderToStaticMarkup(createElement(Fragment, null, el));
2244
+ } catch {
2245
+ // Skip elements that can't be rendered
2246
+ }
2247
+ }
2248
+
2249
+ // Escape HTML attribute values (defense-in-depth for font URLs/types).
2250
+ function _escAttr(s) { return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;"); }
2251
+
2252
+ // Build font HTML from data passed from RSC environment
2253
+ // (Fonts are loaded during RSC rendering, and RSC/SSR are separate module instances)
2254
+ let fontHTML = "";
2255
+ if (fontData) {
2256
+ if (fontData.links && fontData.links.length > 0) {
2257
+ for (const url of fontData.links) {
2258
+ fontHTML += '<link rel="stylesheet" href="' + _escAttr(url) + '" />\\n';
2259
+ }
2260
+ }
2261
+ // Emit <link rel="preload"> for local font files
2262
+ if (fontData.preloads && fontData.preloads.length > 0) {
2263
+ for (const preload of fontData.preloads) {
2264
+ fontHTML += '<link rel="preload" href="' + _escAttr(preload.href) + '" as="font" type="' + _escAttr(preload.type) + '" crossorigin />\\n';
2265
+ }
2266
+ }
2267
+ if (fontData.styles && fontData.styles.length > 0) {
2268
+ fontHTML += '<style data-vinext-fonts>' + fontData.styles.join("\\n") + '</style>\\n';
2269
+ }
2270
+ }
2271
+
2272
+ // Extract client entry module URL from bootstrapScriptContent to emit
2273
+ // a <link rel="modulepreload"> hint. The RSC plugin formats bootstrap
2274
+ // content as: import("URL") — we extract the URL so the browser can
2275
+ // speculatively fetch and parse the JS module while still processing
2276
+ // the HTML body, instead of waiting until it reaches the inline script.
2277
+ let modulePreloadHTML = "";
2278
+ if (bootstrapScriptContent) {
2279
+ const m = bootstrapScriptContent.match(/import\\("([^"]+)"\\)/);
2280
+ if (m && m[1]) {
2281
+ modulePreloadHTML = '<link rel="modulepreload" href="' + _escAttr(m[1]) + '" />\\n';
2282
+ }
2283
+ }
2284
+
2285
+ // Head-injected HTML: server-inserted HTML, font HTML, route params,
2286
+ // and modulepreload hints.
2287
+ // RSC payload is now embedded progressively via script tags in the body stream.
2288
+ // Params are embedded eagerly in <head> so they're available before client
2289
+ // hydration starts, avoiding the need for polling on the client.
2290
+ const paramsScript = '<script>self.__VINEXT_RSC_PARAMS__=' + safeJsonStringify(navContext?.params || {}) + '</script>';
2291
+ const injectHTML = paramsScript + modulePreloadHTML + insertedHTML + fontHTML;
2292
+
2293
+ // Inject the collected HTML before </head> and progressively embed RSC
2294
+ // chunks as script tags throughout the HTML body stream.
2295
+ const decoder = new TextDecoder();
2296
+ const encoder = new TextEncoder();
2297
+ let injected = false;
2298
+
2299
+ // Fix invalid preload "as" values in server-rendered HTML.
2300
+ // React Fizz emits <link rel="preload" as="stylesheet"> for CSS,
2301
+ // but the HTML spec requires as="style" for <link rel="preload">.
2302
+ // Note: fixFlightHints() in createRscEmbedTransform handles the
2303
+ // complementary case — fixing the raw Flight stream data before
2304
+ // it's embedded as __VINEXT_RSC_CHUNKS__ for client-side processing.
2305
+ // See: https://html.spec.whatwg.org/multipage/links.html#link-type-preload
2306
+ function fixPreloadAs(html) {
2307
+ // Match <link ...rel="preload"... as="stylesheet"...> in any attribute order
2308
+ return html.replace(/<link(?=[^>]*\\srel="preload")[^>]*>/g, function(tag) {
2309
+ return tag.replace(' as="stylesheet"', ' as="style"');
2310
+ });
2311
+ }
2312
+
2313
+ // Tick-buffered RSC script injection.
2314
+ //
2315
+ // React's renderToReadableStream (Fizz) flushes chunks synchronously
2316
+ // within one microtask — all chunks from a single flushCompletedQueues
2317
+ // call arrive in the same macrotask. We buffer HTML chunks as they
2318
+ // arrive, then use setTimeout(0) to defer emitting them plus any
2319
+ // accumulated RSC scripts to the next macrotask. This guarantees we
2320
+ // never inject <script> tags between partial HTML chunks (which would
2321
+ // corrupt split elements like "<linearGradi" + "ent>"), while still
2322
+ // delivering RSC data progressively as Suspense boundaries resolve.
2323
+ //
2324
+ // Reference: rsc-html-stream by Devon Govett (credited by Next.js)
2325
+ // https://github.com/devongovett/rsc-html-stream
2326
+ let buffered = [];
2327
+ let timeoutId = null;
2328
+
2329
+ const transform = new TransformStream({
2330
+ transform(chunk, controller) {
2331
+ const text = decoder.decode(chunk, { stream: true });
2332
+ const fixed = fixPreloadAs(text);
2333
+ buffered.push(fixed);
2334
+
2335
+ if (timeoutId !== null) return;
2336
+
2337
+ timeoutId = setTimeout(() => {
2338
+ // Flush all buffered HTML chunks from this React flush cycle
2339
+ for (const buf of buffered) {
2340
+ if (!injected) {
2341
+ const headEnd = buf.indexOf("</head>");
2342
+ if (headEnd !== -1) {
2343
+ const before = buf.slice(0, headEnd);
2344
+ const after = buf.slice(headEnd);
2345
+ controller.enqueue(encoder.encode(before + injectHTML + after));
2346
+ injected = true;
2347
+ continue;
2348
+ }
2349
+ }
2350
+ controller.enqueue(encoder.encode(buf));
2351
+ }
2352
+ buffered = [];
2353
+
2354
+ // Now safe to inject any accumulated RSC scripts — we're between
2355
+ // React flush cycles, so no partial HTML chunks can follow until
2356
+ // the next macrotask.
2357
+ const rscScripts = rscEmbed.flush();
2358
+ if (rscScripts) {
2359
+ controller.enqueue(encoder.encode(rscScripts));
2360
+ }
2361
+
2362
+ timeoutId = null;
2363
+ }, 0);
2364
+ },
2365
+ async flush(controller) {
2366
+ // Cancel any pending setTimeout callback — flush() drains
2367
+ // everything itself, so the callback would be a no-op but
2368
+ // cancelling makes the code obviously correct.
2369
+ if (timeoutId !== null) {
2370
+ clearTimeout(timeoutId);
2371
+ timeoutId = null;
2372
+ }
2373
+
2374
+ // Flush any remaining buffered HTML chunks
2375
+ for (const buf of buffered) {
2376
+ if (!injected) {
2377
+ const headEnd = buf.indexOf("</head>");
2378
+ if (headEnd !== -1) {
2379
+ const before = buf.slice(0, headEnd);
2380
+ const after = buf.slice(headEnd);
2381
+ controller.enqueue(encoder.encode(before + injectHTML + after));
2382
+ injected = true;
2383
+ continue;
2384
+ }
2385
+ }
2386
+ controller.enqueue(encoder.encode(buf));
2387
+ }
2388
+ buffered = [];
2389
+
2390
+ if (!injected && injectHTML) {
2391
+ controller.enqueue(encoder.encode(injectHTML));
2392
+ }
2393
+ // Finalize: wait for the RSC stream to complete and emit remaining
2394
+ // chunks plus the __VINEXT_RSC_DONE__ signal.
2395
+ const finalScripts = await rscEmbed.finalize();
2396
+ if (finalScripts) {
2397
+ controller.enqueue(encoder.encode(finalScripts));
2398
+ }
2399
+ },
2400
+ });
2401
+
2402
+ return htmlStream.pipeThrough(transform);
2403
+ } finally {
2404
+ // Clean up so we don't leak context between requests
2405
+ setNavigationContext(null);
2406
+ clearServerInsertedHTML();
2407
+ }
2408
+ }
2409
+ `;
2410
+ }
2411
+ /**
2412
+ * Generate the virtual browser entry module.
2413
+ *
2414
+ * This runs in the client (browser). It hydrates the page from the
2415
+ * embedded RSC payload and handles client-side navigation by re-fetching
2416
+ * RSC streams.
2417
+ */
2418
+ export function generateBrowserEntry() {
2419
+ return `
2420
+ import {
2421
+ createFromReadableStream,
2422
+ createFromFetch,
2423
+ setServerCallback,
2424
+ encodeReply,
2425
+ createTemporaryReferenceSet,
2426
+ } from "@vitejs/plugin-rsc/browser";
2427
+ import { hydrateRoot } from "react-dom/client";
2428
+ import { flushSync } from "react-dom";
2429
+ import { setClientParams, toRscUrl, getPrefetchCache, getPrefetchedUrls, PREFETCH_CACHE_TTL } from "next/navigation";
2430
+
2431
+ let reactRoot;
2432
+
2433
+ /**
2434
+ * Convert the embedded RSC chunks back to a ReadableStream.
2435
+ * Each chunk is a text string that needs to be encoded back to Uint8Array.
2436
+ */
2437
+ function chunksToReadableStream(chunks) {
2438
+ const encoder = new TextEncoder();
2439
+ return new ReadableStream({
2440
+ start(controller) {
2441
+ for (const chunk of chunks) {
2442
+ controller.enqueue(encoder.encode(chunk));
2443
+ }
2444
+ controller.close();
2445
+ }
2446
+ });
2447
+ }
2448
+
2449
+ /**
2450
+ * Create a ReadableStream from progressively-embedded RSC chunks.
2451
+ * The server injects RSC data as <script> tags that push to
2452
+ * self.__VINEXT_RSC_CHUNKS__ throughout the HTML stream, and sets
2453
+ * self.__VINEXT_RSC_DONE__ = true when complete.
2454
+ *
2455
+ * Instead of polling with setTimeout, we monkey-patch the array's
2456
+ * push() method so new chunks are delivered immediately when the
2457
+ * server's <script> tags execute. This eliminates unnecessary
2458
+ * wakeups and reduces latency — same pattern Next.js uses with
2459
+ * __next_f. The stream closes on DOMContentLoaded (when all
2460
+ * server-injected scripts have executed) or when __VINEXT_RSC_DONE__
2461
+ * is set, whichever comes first.
2462
+ */
2463
+ function createProgressiveRscStream() {
2464
+ const encoder = new TextEncoder();
2465
+ return new ReadableStream({
2466
+ start(controller) {
2467
+ const chunks = self.__VINEXT_RSC_CHUNKS__ || [];
2468
+
2469
+ // Deliver any chunks that arrived before this code ran
2470
+ // (from <script> tags that executed before the browser entry loaded)
2471
+ for (const chunk of chunks) {
2472
+ controller.enqueue(encoder.encode(chunk));
2473
+ }
2474
+
2475
+ // If the stream is already complete, close immediately
2476
+ if (self.__VINEXT_RSC_DONE__) {
2477
+ controller.close();
2478
+ return;
2479
+ }
2480
+
2481
+ // Monkey-patch push() so future chunks stream in immediately
2482
+ // when the server's <script> tags execute
2483
+ let closed = false;
2484
+ function closeOnce() {
2485
+ if (!closed) {
2486
+ closed = true;
2487
+ controller.close();
2488
+ }
2489
+ }
2490
+
2491
+ const arr = self.__VINEXT_RSC_CHUNKS__ = self.__VINEXT_RSC_CHUNKS__ || [];
2492
+ arr.push = function(chunk) {
2493
+ Array.prototype.push.call(this, chunk);
2494
+ if (!closed) {
2495
+ controller.enqueue(encoder.encode(chunk));
2496
+ if (self.__VINEXT_RSC_DONE__) {
2497
+ closeOnce();
2498
+ }
2499
+ }
2500
+ return this.length;
2501
+ };
2502
+
2503
+ // Safety net: if the server crashes mid-stream and __VINEXT_RSC_DONE__
2504
+ // never arrives, close the stream when all server-injected scripts
2505
+ // have executed (DOMContentLoaded). Without this, a truncated response
2506
+ // leaves the ReadableStream open forever, hanging hydration.
2507
+ if (typeof document !== "undefined") {
2508
+ if (document.readyState === "loading") {
2509
+ document.addEventListener("DOMContentLoaded", closeOnce);
2510
+ } else {
2511
+ // Document already loaded — close immediately if not already done
2512
+ closeOnce();
2513
+ }
2514
+ }
2515
+ }
2516
+ });
2517
+ }
2518
+
2519
+ // Register the server action callback — React calls this internally
2520
+ // when a "use server" function is invoked from client code.
2521
+ setServerCallback(async (id, args) => {
2522
+ const temporaryReferences = createTemporaryReferenceSet();
2523
+ const body = await encodeReply(args, { temporaryReferences });
2524
+
2525
+ const fetchResponse = await fetch(toRscUrl(window.location.pathname + window.location.search), {
2526
+ method: "POST",
2527
+ headers: { "x-rsc-action": id },
2528
+ body,
2529
+ });
2530
+
2531
+ // Check for redirect signal from server action that called redirect()
2532
+ const actionRedirect = fetchResponse.headers.get("x-action-redirect");
2533
+ if (actionRedirect) {
2534
+ // External URLs (different origin) need a hard redirect — client-side
2535
+ // RSC navigation only works for same-origin paths.
2536
+ try {
2537
+ const redirectUrl = new URL(actionRedirect, window.location.origin);
2538
+ if (redirectUrl.origin !== window.location.origin) {
2539
+ window.location.href = actionRedirect;
2540
+ return undefined;
2541
+ }
2542
+ } catch {
2543
+ // If URL parsing fails, fall through to client-side navigation
2544
+ }
2545
+
2546
+ // Navigate to the redirect target using client-side navigation
2547
+ const redirectType = fetchResponse.headers.get("x-action-redirect-type") || "replace";
2548
+ if (redirectType === "push") {
2549
+ window.history.pushState(null, "", actionRedirect);
2550
+ } else {
2551
+ window.history.replaceState(null, "", actionRedirect);
2552
+ }
2553
+ // Trigger RSC navigation to the redirect target
2554
+ if (typeof window.__VINEXT_RSC_NAVIGATE__ === "function") {
2555
+ window.__VINEXT_RSC_NAVIGATE__(actionRedirect);
2556
+ }
2557
+ return undefined;
2558
+ }
2559
+
2560
+ const result = await createFromFetch(Promise.resolve(fetchResponse), { temporaryReferences });
2561
+
2562
+ // The RSC response for actions contains { root, returnValue }.
2563
+ // Re-render the page with the updated tree.
2564
+ if (result && typeof result === "object" && "root" in result) {
2565
+ reactRoot.render(result.root);
2566
+ // Return the action's return value to the caller
2567
+ if (result.returnValue) {
2568
+ if (!result.returnValue.ok) throw result.returnValue.data;
2569
+ return result.returnValue.data;
2570
+ }
2571
+ return undefined;
2572
+ }
2573
+
2574
+ // Fallback: render the entire result as the tree
2575
+ reactRoot.render(result);
2576
+ return result;
2577
+ });
2578
+
2579
+ async function main() {
2580
+ let rscStream;
2581
+
2582
+ // Use embedded RSC data for initial hydration if available.
2583
+ // This ensures we use the SAME RSC payload that generated the HTML,
2584
+ // avoiding hydration mismatches (React error #418).
2585
+ //
2586
+ // The server embeds RSC chunks progressively as <script> tags that push
2587
+ // to self.__VINEXT_RSC_CHUNKS__. When complete, self.__VINEXT_RSC_DONE__
2588
+ // is set and self.__VINEXT_RSC_PARAMS__ contains route params.
2589
+ // For backwards compat, also check the legacy self.__VINEXT_RSC__ format.
2590
+ if (self.__VINEXT_RSC_CHUNKS__ || self.__VINEXT_RSC_DONE__ || self.__VINEXT_RSC__) {
2591
+ if (self.__VINEXT_RSC__) {
2592
+ // Legacy format: single object with all chunks
2593
+ const embedData = self.__VINEXT_RSC__;
2594
+ delete self.__VINEXT_RSC__;
2595
+ if (embedData.params) {
2596
+ setClientParams(embedData.params);
2597
+ }
2598
+ rscStream = chunksToReadableStream(embedData.rsc);
2599
+ } else {
2600
+ // Progressive format: chunks arrive incrementally via script tags.
2601
+ // Params are embedded in <head> so they're always available by this point.
2602
+ if (self.__VINEXT_RSC_PARAMS__) {
2603
+ setClientParams(self.__VINEXT_RSC_PARAMS__);
2604
+ }
2605
+ rscStream = createProgressiveRscStream();
2606
+ }
2607
+ } else {
2608
+ // Fallback: fetch fresh RSC (shouldn't happen on initial page load)
2609
+ const rscResponse = await fetch(toRscUrl(window.location.pathname + window.location.search));
2610
+
2611
+ // Hydrate useParams() with route params from the server before React hydration
2612
+ const paramsHeader = rscResponse.headers.get("X-Vinext-Params");
2613
+ if (paramsHeader) {
2614
+ try { setClientParams(JSON.parse(paramsHeader)); } catch (_e) { /* ignore */ }
2615
+ }
2616
+
2617
+ rscStream = rscResponse.body;
2618
+ }
2619
+
2620
+ const root = await createFromReadableStream(rscStream);
2621
+
2622
+ // Hydrate the document
2623
+ // In development, suppress Vite's error overlay for errors caught by React error
2624
+ // boundaries. Without this, React re-throws caught errors to the global handler,
2625
+ // which triggers Vite's overlay even though the error was handled by an error.tsx.
2626
+ // In production, preserve React's default onCaughtError (console.error) so
2627
+ // boundary-caught errors remain visible to error monitoring.
2628
+ reactRoot = hydrateRoot(document, root, import.meta.env.DEV ? {
2629
+ onCaughtError: function() {},
2630
+ } : undefined);
2631
+
2632
+ // Store for client-side navigation
2633
+ window.__VINEXT_RSC_ROOT__ = reactRoot;
2634
+
2635
+ // Client-side navigation handler
2636
+ // Checks the prefetch cache (populated by <Link> IntersectionObserver and
2637
+ // router.prefetch()) before making a network request. This makes navigation
2638
+ // near-instant for prefetched routes.
2639
+ window.__VINEXT_RSC_NAVIGATE__ = async function navigateRsc(href) {
2640
+ try {
2641
+ const url = new URL(href, window.location.origin);
2642
+ const rscUrl = toRscUrl(url.pathname + url.search);
2643
+
2644
+ // Check the in-memory prefetch cache first
2645
+ let navResponse;
2646
+ const prefetchCache = getPrefetchCache();
2647
+ const cached = prefetchCache.get(rscUrl);
2648
+ if (cached && (Date.now() - cached.timestamp) < PREFETCH_CACHE_TTL) {
2649
+ navResponse = cached.response;
2650
+ prefetchCache.delete(rscUrl); // Consume the cached entry (one-time use)
2651
+ getPrefetchedUrls().delete(rscUrl); // Allow re-prefetch when link is visible again
2652
+ } else if (cached) {
2653
+ prefetchCache.delete(rscUrl); // Expired, clean up
2654
+ getPrefetchedUrls().delete(rscUrl);
2655
+ }
2656
+
2657
+ // Fallback to network fetch if not in cache
2658
+ if (!navResponse) {
2659
+ navResponse = await fetch(rscUrl, {
2660
+ headers: { Accept: "text/x-component" },
2661
+ });
2662
+ }
2663
+
2664
+ // Update useParams() with route params from the server before re-rendering
2665
+ const navParamsHeader = navResponse.headers.get("X-Vinext-Params");
2666
+ if (navParamsHeader) {
2667
+ try { setClientParams(JSON.parse(navParamsHeader)); } catch (_e) { /* ignore */ }
2668
+ } else {
2669
+ setClientParams({});
2670
+ }
2671
+
2672
+ const rscPayload = await createFromFetch(Promise.resolve(navResponse));
2673
+ // Use flushSync to guarantee React commits the new tree to the DOM
2674
+ // synchronously before this function returns. Callers scroll to top
2675
+ // after awaiting, so the new content must be painted first.
2676
+ flushSync(function () { reactRoot.render(rscPayload); });
2677
+ } catch (err) {
2678
+ console.error("[vinext] RSC navigation error:", err);
2679
+ // Fallback to full page load
2680
+ window.location.href = href;
2681
+ }
2682
+ };
2683
+
2684
+ // Handle popstate (browser back/forward)
2685
+ // Store the navigation promise on a well-known property so that
2686
+ // restoreScrollPosition (in navigation.ts) can await it before scrolling.
2687
+ // This prevents a flash where the old content is visible at the restored
2688
+ // scroll position before the new RSC payload has rendered.
2689
+ window.addEventListener("popstate", () => {
2690
+ const p = window.__VINEXT_RSC_NAVIGATE__(window.location.href);
2691
+ window.__VINEXT_RSC_PENDING__ = p;
2692
+ p.finally(() => {
2693
+ // Clear once settled so stale promises aren't awaited later
2694
+ if (window.__VINEXT_RSC_PENDING__ === p) {
2695
+ window.__VINEXT_RSC_PENDING__ = null;
2696
+ }
2697
+ });
2698
+ });
2699
+
2700
+ // HMR: re-render on server module updates
2701
+ if (import.meta.hot) {
2702
+ import.meta.hot.on("rsc:update", async () => {
2703
+ try {
2704
+ const rscPayload = await createFromFetch(
2705
+ fetch(toRscUrl(window.location.pathname + window.location.search))
2706
+ );
2707
+ reactRoot.render(rscPayload);
2708
+ } catch (err) {
2709
+ console.error("[vinext] RSC HMR error:", err);
2710
+ }
2711
+ });
2712
+ }
2713
+ }
2714
+
2715
+ main();
2716
+ `;
2717
+ }
2718
+ //# sourceMappingURL=app-dev-server.js.map