vinext 0.0.54 → 0.1.0

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 (977) hide show
  1. package/README.md +52 -15
  2. package/dist/build/clean-output.d.ts +1 -2
  3. package/dist/build/clean-output.js +0 -2
  4. package/dist/build/client-build-config.d.ts +16 -3
  5. package/dist/build/client-build-config.js +29 -4
  6. package/dist/build/css-url-assets.d.ts +29 -0
  7. package/dist/build/css-url-assets.js +211 -0
  8. package/dist/build/google-fonts/build-url.d.ts +1 -2
  9. package/dist/build/google-fonts/build-url.js +0 -2
  10. package/dist/build/google-fonts/fallback-metrics-data.js +0 -2
  11. package/dist/build/google-fonts/fallback-metrics.d.ts +1 -2
  12. package/dist/build/google-fonts/fallback-metrics.js +0 -2
  13. package/dist/build/google-fonts/font-data.js +0 -2
  14. package/dist/build/google-fonts/font-metadata.d.ts +1 -2
  15. package/dist/build/google-fonts/font-metadata.js +0 -2
  16. package/dist/build/google-fonts/get-axes.d.ts +1 -2
  17. package/dist/build/google-fonts/get-axes.js +0 -2
  18. package/dist/build/google-fonts/sort-variants.d.ts +1 -2
  19. package/dist/build/google-fonts/sort-variants.js +0 -2
  20. package/dist/build/google-fonts/validate.d.ts +1 -2
  21. package/dist/build/google-fonts/validate.js +0 -2
  22. package/dist/build/inline-css.d.ts +1 -2
  23. package/dist/build/inline-css.js +0 -2
  24. package/dist/build/layout-classification-types.d.ts +1 -2
  25. package/dist/build/layout-classification.d.ts +2 -3
  26. package/dist/build/layout-classification.js +1 -3
  27. package/dist/build/next-client-runtime-manifests.d.ts +14 -0
  28. package/dist/build/next-client-runtime-manifests.js +39 -0
  29. package/dist/build/nitro-route-rules.d.ts +1 -2
  30. package/dist/build/nitro-route-rules.js +0 -2
  31. package/dist/build/precompress.d.ts +1 -2
  32. package/dist/build/precompress.js +0 -2
  33. package/dist/build/prerender.d.ts +2 -3
  34. package/dist/build/prerender.js +14 -2
  35. package/dist/build/report.d.ts +1 -2
  36. package/dist/build/report.js +0 -2
  37. package/dist/build/route-classification-injector.d.ts +1 -2
  38. package/dist/build/route-classification-injector.js +4 -6
  39. package/dist/build/route-classification-manifest.d.ts +5 -6
  40. package/dist/build/route-classification-manifest.js +5 -7
  41. package/dist/build/run-prerender.d.ts +1 -2
  42. package/dist/build/run-prerender.js +15 -7
  43. package/dist/build/server-manifest.d.ts +1 -2
  44. package/dist/build/server-manifest.js +0 -2
  45. package/dist/build/ssr-manifest.d.ts +1 -2
  46. package/dist/build/ssr-manifest.js +2 -4
  47. package/dist/build/standalone.d.ts +1 -2
  48. package/dist/build/standalone.js +0 -2
  49. package/dist/build/static-export.d.ts +2 -3
  50. package/dist/build/static-export.js +0 -2
  51. package/dist/cache/cache-adapters-virtual.d.ts +50 -0
  52. package/dist/cache/cache-adapters-virtual.js +45 -0
  53. package/dist/check.d.ts +33 -2
  54. package/dist/check.js +321 -27
  55. package/dist/cli-args.d.ts +1 -2
  56. package/dist/cli-args.js +0 -2
  57. package/dist/cli.js +7 -13
  58. package/dist/client/instrumentation-client-inject.d.ts +1 -2
  59. package/dist/client/instrumentation-client-inject.js +0 -2
  60. package/dist/client/instrumentation-client-state.d.ts +1 -2
  61. package/dist/client/instrumentation-client-state.js +0 -2
  62. package/dist/client/instrumentation-client.d.ts +1 -2
  63. package/dist/client/instrumentation-client.js +0 -2
  64. package/dist/client/navigation-runtime.d.ts +2 -2
  65. package/dist/client/navigation-runtime.js +1 -3
  66. package/dist/client/pages-router-link-navigation.d.ts +1 -2
  67. package/dist/client/pages-router-link-navigation.js +0 -2
  68. package/dist/client/validate-module-path.d.ts +1 -2
  69. package/dist/client/validate-module-path.js +0 -2
  70. package/dist/client/vinext-next-data.d.ts +1 -2
  71. package/dist/client/vinext-next-data.js +0 -2
  72. package/dist/client/window-next.d.ts +1 -2
  73. package/dist/client/window-next.js +0 -2
  74. package/dist/cloudflare/index.d.ts +1 -1
  75. package/dist/cloudflare/index.js +1 -1
  76. package/dist/cloudflare/src/cache/cdn-adapter.runtime.js +97 -0
  77. package/dist/cloudflare/{kv-cache-handler.d.ts → src/cache/kv-data-adapter.runtime.d.ts} +25 -6
  78. package/dist/cloudflare/{kv-cache-handler.js → src/cache/kv-data-adapter.runtime.js} +36 -28
  79. package/dist/cloudflare/src/utils/cache-control-metadata.js +20 -0
  80. package/dist/cloudflare/tpr.d.ts +2 -3
  81. package/dist/cloudflare/tpr.js +8 -8
  82. package/dist/config/config-matchers.d.ts +1 -2
  83. package/dist/config/config-matchers.js +0 -2
  84. package/dist/config/dotenv.d.ts +1 -2
  85. package/dist/config/dotenv.js +0 -2
  86. package/dist/config/next-config.d.ts +30 -3
  87. package/dist/config/next-config.js +47 -8
  88. package/dist/config/tsconfig-paths.d.ts +12 -4
  89. package/dist/config/tsconfig-paths.js +58 -31
  90. package/dist/deploy.d.ts +48 -3
  91. package/dist/deploy.js +141 -112
  92. package/dist/entries/app-browser-entry.d.ts +1 -2
  93. package/dist/entries/app-browser-entry.js +0 -2
  94. package/dist/entries/app-rsc-entry.d.ts +6 -5
  95. package/dist/entries/app-rsc-entry.js +62 -61
  96. package/dist/entries/app-rsc-manifest.d.ts +1 -2
  97. package/dist/entries/app-rsc-manifest.js +42 -12
  98. package/dist/entries/app-ssr-entry.d.ts +1 -2
  99. package/dist/entries/app-ssr-entry.js +0 -2
  100. package/dist/entries/pages-client-entry.d.ts +3 -3
  101. package/dist/entries/pages-client-entry.js +16 -5
  102. package/dist/entries/pages-entry-helpers.d.ts +2 -11
  103. package/dist/entries/pages-entry-helpers.js +1 -20
  104. package/dist/entries/pages-server-entry.d.ts +2 -3
  105. package/dist/entries/pages-server-entry.js +94 -670
  106. package/dist/entries/runtime-entry-module.d.ts +1 -2
  107. package/dist/entries/runtime-entry-module.js +0 -2
  108. package/dist/index.d.ts +22 -2
  109. package/dist/index.js +297 -140
  110. package/dist/init.d.ts +1 -2
  111. package/dist/init.js +1 -3
  112. package/dist/plugins/ast-utils.d.ts +20 -0
  113. package/dist/plugins/ast-utils.js +78 -0
  114. package/dist/plugins/async-hooks-stub.d.ts +1 -2
  115. package/dist/plugins/async-hooks-stub.js +0 -2
  116. package/dist/plugins/client-reference-dedup.d.ts +1 -2
  117. package/dist/plugins/client-reference-dedup.js +4 -8
  118. package/dist/plugins/css-data-url.d.ts +1 -2
  119. package/dist/plugins/css-data-url.js +0 -2
  120. package/dist/plugins/fonts.d.ts +13 -3
  121. package/dist/plugins/fonts.js +19 -13
  122. package/dist/plugins/import-meta-url.d.ts +16 -0
  123. package/dist/plugins/import-meta-url.js +347 -0
  124. package/dist/plugins/instrumentation-client.d.ts +1 -2
  125. package/dist/plugins/instrumentation-client.js +0 -2
  126. package/dist/plugins/middleware-server-only.d.ts +1 -2
  127. package/dist/plugins/middleware-server-only.js +0 -2
  128. package/dist/plugins/og-assets.d.ts +32 -8
  129. package/dist/plugins/og-assets.js +126 -34
  130. package/dist/plugins/optimize-imports.d.ts +1 -2
  131. package/dist/plugins/optimize-imports.js +9 -17
  132. package/dist/plugins/postcss.d.ts +1 -2
  133. package/dist/plugins/postcss.js +0 -2
  134. package/dist/plugins/remove-console.d.ts +1 -2
  135. package/dist/plugins/remove-console.js +0 -2
  136. package/dist/plugins/rsc-client-reference-loaders.d.ts +1 -2
  137. package/dist/plugins/rsc-client-reference-loaders.js +0 -2
  138. package/dist/plugins/rsc-client-shim-excludes.d.ts +1 -2
  139. package/dist/plugins/rsc-client-shim-excludes.js +0 -2
  140. package/dist/plugins/sass.d.ts +1 -2
  141. package/dist/plugins/sass.js +0 -2
  142. package/dist/plugins/server-externals-manifest.d.ts +1 -2
  143. package/dist/plugins/server-externals-manifest.js +0 -2
  144. package/dist/plugins/strip-server-exports.d.ts +1 -2
  145. package/dist/plugins/strip-server-exports.js +0 -2
  146. package/dist/routing/app-route-graph.d.ts +2 -9
  147. package/dist/routing/app-route-graph.js +9 -30
  148. package/dist/routing/app-router.d.ts +1 -2
  149. package/dist/routing/app-router.js +0 -2
  150. package/dist/routing/file-matcher.d.ts +6 -2
  151. package/dist/routing/file-matcher.js +15 -7
  152. package/dist/routing/pages-router.d.ts +1 -2
  153. package/dist/routing/pages-router.js +0 -2
  154. package/dist/routing/route-matching.d.ts +1 -2
  155. package/dist/routing/route-matching.js +0 -2
  156. package/dist/routing/route-pattern.d.ts +1 -2
  157. package/dist/routing/route-pattern.js +0 -2
  158. package/dist/routing/route-trie.d.ts +1 -2
  159. package/dist/routing/route-trie.js +0 -2
  160. package/dist/routing/route-validation.d.ts +1 -2
  161. package/dist/routing/route-validation.js +0 -2
  162. package/dist/routing/utils.d.ts +44 -2
  163. package/dist/routing/utils.js +62 -3
  164. package/dist/server/api-handler.d.ts +1 -2
  165. package/dist/server/api-handler.js +0 -2
  166. package/dist/server/app-bfcache-id.d.ts +5 -0
  167. package/dist/server/app-bfcache-id.js +5 -0
  168. package/dist/server/app-browser-action-result.d.ts +9 -17
  169. package/dist/server/app-browser-action-result.js +25 -16
  170. package/dist/server/app-browser-client-reuse-manifest.d.ts +12 -0
  171. package/dist/server/app-browser-client-reuse-manifest.js +101 -0
  172. package/dist/server/app-browser-entry.js +352 -115
  173. package/dist/server/app-browser-error.d.ts +1 -2
  174. package/dist/server/app-browser-error.js +0 -2
  175. package/dist/server/app-browser-hydration.d.ts +1 -2
  176. package/dist/server/app-browser-hydration.js +0 -2
  177. package/dist/server/app-browser-interception-context.d.ts +1 -2
  178. package/dist/server/app-browser-interception-context.js +0 -2
  179. package/dist/server/app-browser-mpa-navigation.d.ts +16 -0
  180. package/dist/server/app-browser-mpa-navigation.js +42 -0
  181. package/dist/server/app-browser-navigation-controller.d.ts +5 -4
  182. package/dist/server/app-browser-navigation-controller.js +3 -3
  183. package/dist/server/app-browser-popstate.d.ts +4 -3
  184. package/dist/server/app-browser-popstate.js +15 -3
  185. package/dist/server/app-browser-rsc-redirect.d.ts +1 -2
  186. package/dist/server/app-browser-rsc-redirect.js +0 -2
  187. package/dist/server/app-browser-state.d.ts +28 -4
  188. package/dist/server/app-browser-state.js +195 -11
  189. package/dist/server/app-browser-stream.d.ts +1 -2
  190. package/dist/server/app-browser-stream.js +0 -2
  191. package/dist/server/app-browser-visible-commit.d.ts +2 -3
  192. package/dist/server/app-browser-visible-commit.js +24 -17
  193. package/dist/server/app-client-reference-preloader.d.ts +1 -2
  194. package/dist/server/app-client-reference-preloader.js +0 -2
  195. package/dist/server/app-elements-wire.d.ts +14 -8
  196. package/dist/server/app-elements-wire.js +45 -24
  197. package/dist/server/app-elements.d.ts +2 -3
  198. package/dist/server/app-elements.js +2 -4
  199. package/dist/server/app-fallback-renderer.d.ts +5 -5
  200. package/dist/server/app-fallback-renderer.js +4 -3
  201. package/dist/server/app-history-state.d.ts +18 -2
  202. package/dist/server/app-history-state.js +68 -10
  203. package/dist/server/app-hook-warning-suppression.d.ts +1 -2
  204. package/dist/server/app-hook-warning-suppression.js +0 -2
  205. package/dist/server/app-inline-css-client.d.ts +1 -2
  206. package/dist/server/app-inline-css-client.js +0 -2
  207. package/dist/server/app-interception-context-header.d.ts +1 -2
  208. package/dist/server/app-interception-context-header.js +0 -2
  209. package/dist/server/app-layout-param-observation.d.ts +43 -0
  210. package/dist/server/app-layout-param-observation.js +168 -0
  211. package/dist/server/app-middleware.d.ts +1 -2
  212. package/dist/server/app-middleware.js +0 -2
  213. package/dist/server/app-mounted-slots-header.d.ts +1 -2
  214. package/dist/server/app-mounted-slots-header.js +0 -2
  215. package/dist/server/app-optimistic-routing.d.ts +1 -2
  216. package/dist/server/app-optimistic-routing.js +0 -2
  217. package/dist/server/app-page-boundary-render.d.ts +4 -3
  218. package/dist/server/app-page-boundary-render.js +20 -11
  219. package/dist/server/app-page-boundary.d.ts +11 -2
  220. package/dist/server/app-page-boundary.js +13 -4
  221. package/dist/server/app-page-cache.d.ts +3 -3
  222. package/dist/server/app-page-cache.js +36 -11
  223. package/dist/server/app-page-dispatch.d.ts +19 -5
  224. package/dist/server/app-page-dispatch.js +119 -24
  225. package/dist/server/app-page-element-builder.d.ts +3 -2
  226. package/dist/server/app-page-element-builder.js +9 -11
  227. package/dist/server/app-page-execution.d.ts +8 -3
  228. package/dist/server/app-page-execution.js +55 -24
  229. package/dist/server/app-page-head.d.ts +1 -2
  230. package/dist/server/app-page-head.js +6 -6
  231. package/dist/server/app-page-method.d.ts +1 -2
  232. package/dist/server/app-page-method.js +0 -2
  233. package/dist/server/app-page-params.d.ts +2 -2
  234. package/dist/server/app-page-params.js +14 -3
  235. package/dist/server/app-page-probe.d.ts +90 -2
  236. package/dist/server/app-page-probe.js +201 -6
  237. package/dist/server/app-page-render-identity.d.ts +1 -2
  238. package/dist/server/app-page-render-identity.js +0 -2
  239. package/dist/server/app-page-render-observation.d.ts +1 -2
  240. package/dist/server/app-page-render-observation.js +0 -2
  241. package/dist/server/app-page-render.d.ts +9 -3
  242. package/dist/server/app-page-render.js +167 -10
  243. package/dist/server/app-page-request.d.ts +4 -3
  244. package/dist/server/app-page-request.js +1 -3
  245. package/dist/server/app-page-response.d.ts +2 -2
  246. package/dist/server/app-page-response.js +5 -3
  247. package/dist/server/app-page-route-wiring.d.ts +14 -3
  248. package/dist/server/app-page-route-wiring.js +63 -11
  249. package/dist/server/app-page-search-params-observation.d.ts +10 -0
  250. package/dist/server/app-page-search-params-observation.js +20 -0
  251. package/dist/server/app-page-segment-state.d.ts +1 -2
  252. package/dist/server/app-page-segment-state.js +1 -8
  253. package/dist/server/app-page-stream.d.ts +19 -9
  254. package/dist/server/app-page-stream.js +28 -10
  255. package/dist/server/app-pages-bridge.d.ts +25 -0
  256. package/dist/server/app-pages-bridge.js +34 -0
  257. package/dist/server/app-post-middleware-context.d.ts +1 -2
  258. package/dist/server/app-post-middleware-context.js +0 -2
  259. package/dist/server/app-ppr-fallback-shell.d.ts +21 -0
  260. package/dist/server/app-ppr-fallback-shell.js +82 -0
  261. package/dist/server/app-prerender-endpoints.d.ts +1 -2
  262. package/dist/server/app-prerender-endpoints.js +0 -2
  263. package/dist/server/app-prerender-static-params.d.ts +15 -2
  264. package/dist/server/app-prerender-static-params.js +44 -13
  265. package/dist/server/app-render-dependency.d.ts +3 -2
  266. package/dist/server/app-render-dependency.js +9 -3
  267. package/dist/server/app-request-context.d.ts +1 -2
  268. package/dist/server/app-request-context.js +0 -2
  269. package/dist/server/app-route-handler-cache.d.ts +1 -2
  270. package/dist/server/app-route-handler-cache.js +0 -2
  271. package/dist/server/app-route-handler-dispatch.d.ts +1 -2
  272. package/dist/server/app-route-handler-dispatch.js +0 -2
  273. package/dist/server/app-route-handler-execution.d.ts +1 -2
  274. package/dist/server/app-route-handler-execution.js +2 -4
  275. package/dist/server/app-route-handler-policy.d.ts +1 -2
  276. package/dist/server/app-route-handler-policy.js +0 -2
  277. package/dist/server/app-route-handler-response.d.ts +2 -3
  278. package/dist/server/app-route-handler-response.js +8 -7
  279. package/dist/server/app-route-handler-runtime.d.ts +1 -2
  280. package/dist/server/app-route-handler-runtime.js +0 -2
  281. package/dist/server/app-route-module-loader.d.ts +43 -0
  282. package/dist/server/app-route-module-loader.js +32 -0
  283. package/dist/server/app-router-entry.d.ts +1 -2
  284. package/dist/server/app-router-entry.js +2 -2
  285. package/dist/server/app-rsc-cache-busting.d.ts +12 -3
  286. package/dist/server/app-rsc-cache-busting.js +21 -10
  287. package/dist/server/app-rsc-embedded-chunks.d.ts +1 -2
  288. package/dist/server/app-rsc-embedded-chunks.js +0 -2
  289. package/dist/server/app-rsc-error-handler.d.ts +1 -2
  290. package/dist/server/app-rsc-error-handler.js +0 -2
  291. package/dist/server/app-rsc-errors.d.ts +1 -2
  292. package/dist/server/app-rsc-errors.js +0 -2
  293. package/dist/server/app-rsc-handler.d.ts +16 -2
  294. package/dist/server/app-rsc-handler.js +32 -14
  295. package/dist/server/app-rsc-render-mode.d.ts +1 -2
  296. package/dist/server/app-rsc-render-mode.js +0 -2
  297. package/dist/server/app-rsc-request-normalization.d.ts +4 -5
  298. package/dist/server/app-rsc-request-normalization.js +2 -4
  299. package/dist/server/app-rsc-response-finalizer.d.ts +1 -2
  300. package/dist/server/app-rsc-response-finalizer.js +2 -2
  301. package/dist/server/app-rsc-route-matching.d.ts +1 -2
  302. package/dist/server/app-rsc-route-matching.js +0 -2
  303. package/dist/server/app-segment-config.d.ts +5 -3
  304. package/dist/server/app-segment-config.js +12 -3
  305. package/dist/server/app-server-action-execution.d.ts +12 -2
  306. package/dist/server/app-server-action-execution.js +200 -25
  307. package/dist/server/app-ssr-entry.d.ts +5 -4
  308. package/dist/server/app-ssr-entry.js +31 -15
  309. package/dist/server/app-ssr-error-meta.d.ts +1 -2
  310. package/dist/server/app-ssr-error-meta.js +0 -2
  311. package/dist/server/app-ssr-stream.d.ts +1 -2
  312. package/dist/server/app-ssr-stream.js +31 -3
  313. package/dist/server/app-static-generation.d.ts +1 -2
  314. package/dist/server/app-static-generation.js +0 -2
  315. package/dist/server/app-visited-response-cache.d.ts +23 -0
  316. package/dist/server/app-visited-response-cache.js +19 -0
  317. package/dist/server/artifact-compatibility.d.ts +2 -2
  318. package/dist/server/artifact-compatibility.js +12 -7
  319. package/dist/server/cache-control.d.ts +15 -2
  320. package/dist/server/cache-control.js +21 -3
  321. package/dist/server/cache-headers.d.ts +1 -2
  322. package/dist/server/cache-headers.js +0 -2
  323. package/dist/server/cache-proof.d.ts +1 -2
  324. package/dist/server/cache-proof.js +0 -2
  325. package/dist/server/client-reuse-manifest.d.ts +10 -5
  326. package/dist/server/client-reuse-manifest.js +7 -10
  327. package/dist/server/client-trace-metadata.d.ts +1 -2
  328. package/dist/server/client-trace-metadata.js +0 -2
  329. package/dist/server/cookie-utils.d.ts +1 -2
  330. package/dist/server/cookie-utils.js +0 -2
  331. package/dist/server/csp.d.ts +1 -2
  332. package/dist/server/csp.js +0 -2
  333. package/dist/server/default-global-error-module.d.ts +1 -2
  334. package/dist/server/default-global-error-module.js +0 -2
  335. package/dist/server/default-not-found-module.d.ts +1 -2
  336. package/dist/server/default-not-found-module.js +0 -2
  337. package/dist/server/dev-error-overlay-store.d.ts +20 -4
  338. package/dist/server/dev-error-overlay-store.js +23 -4
  339. package/dist/server/dev-error-overlay.d.ts +39 -3
  340. package/dist/server/dev-error-overlay.js +952 -164
  341. package/dist/server/dev-initial-server-error.d.ts +9 -0
  342. package/dist/server/dev-initial-server-error.js +26 -0
  343. package/dist/server/dev-lockfile.d.ts +1 -2
  344. package/dist/server/dev-lockfile.js +0 -2
  345. package/dist/server/dev-module-runner.d.ts +1 -2
  346. package/dist/server/dev-module-runner.js +0 -2
  347. package/dist/server/dev-origin-check.d.ts +1 -2
  348. package/dist/server/dev-origin-check.js +0 -2
  349. package/dist/server/dev-route-files.d.ts +1 -2
  350. package/dist/server/dev-route-files.js +0 -2
  351. package/dist/server/dev-server.d.ts +2 -3
  352. package/dist/server/dev-server.js +127 -28
  353. package/dist/server/dev-stack-sourcemap-endpoint.d.ts +4 -0
  354. package/dist/server/dev-stack-sourcemap-endpoint.js +4 -0
  355. package/dist/server/dev-stack-sourcemap.d.ts +43 -0
  356. package/dist/server/dev-stack-sourcemap.js +443 -0
  357. package/dist/server/document-initial-head.d.ts +6 -0
  358. package/dist/server/document-initial-head.js +33 -0
  359. package/dist/server/edge-api-runtime.d.ts +1 -2
  360. package/dist/server/edge-api-runtime.js +0 -2
  361. package/dist/server/file-based-metadata.d.ts +1 -2
  362. package/dist/server/file-based-metadata.js +0 -2
  363. package/dist/server/headers.d.ts +3 -2
  364. package/dist/server/headers.js +3 -3
  365. package/dist/server/html.d.ts +1 -2
  366. package/dist/server/html.js +0 -2
  367. package/dist/server/http-error-responses.d.ts +1 -2
  368. package/dist/server/http-error-responses.js +0 -2
  369. package/dist/server/image-optimization.d.ts +1 -2
  370. package/dist/server/image-optimization.js +0 -2
  371. package/dist/server/implicit-tags.d.ts +1 -2
  372. package/dist/server/implicit-tags.js +0 -2
  373. package/dist/server/instrumentation-runtime.d.ts +1 -2
  374. package/dist/server/instrumentation-runtime.js +0 -2
  375. package/dist/server/instrumentation.d.ts +1 -2
  376. package/dist/server/instrumentation.js +0 -2
  377. package/dist/server/isr-cache.d.ts +10 -3
  378. package/dist/server/isr-cache.js +13 -28
  379. package/dist/server/metadata-route-build-data.d.ts +1 -2
  380. package/dist/server/metadata-route-build-data.js +0 -2
  381. package/dist/server/metadata-route-response.d.ts +1 -2
  382. package/dist/server/metadata-route-response.js +0 -2
  383. package/dist/server/metadata-routes.d.ts +1 -2
  384. package/dist/server/metadata-routes.js +0 -2
  385. package/dist/server/middleware-matcher.d.ts +1 -2
  386. package/dist/server/middleware-matcher.js +0 -2
  387. package/dist/server/middleware-request-headers.d.ts +1 -2
  388. package/dist/server/middleware-request-headers.js +0 -2
  389. package/dist/server/middleware-response-headers.d.ts +1 -2
  390. package/dist/server/middleware-response-headers.js +0 -2
  391. package/dist/server/middleware-runtime.d.ts +1 -2
  392. package/dist/server/middleware-runtime.js +14 -5
  393. package/dist/server/middleware.d.ts +2 -3
  394. package/dist/server/middleware.js +0 -2
  395. package/dist/server/navigation-planner.d.ts +16 -2
  396. package/dist/server/navigation-planner.js +1 -3
  397. package/dist/server/navigation-trace.d.ts +1 -2
  398. package/dist/server/navigation-trace.js +0 -2
  399. package/dist/server/next-error-digest.d.ts +1 -2
  400. package/dist/server/next-error-digest.js +0 -2
  401. package/dist/server/normalize-path.d.ts +1 -2
  402. package/dist/server/normalize-path.js +0 -2
  403. package/dist/server/pages-api-route.d.ts +1 -2
  404. package/dist/server/pages-api-route.js +1 -3
  405. package/dist/server/pages-asset-tags.d.ts +66 -0
  406. package/dist/server/pages-asset-tags.js +116 -0
  407. package/dist/server/pages-body-parser-config.d.ts +1 -2
  408. package/dist/server/pages-body-parser-config.js +0 -2
  409. package/dist/server/pages-data-route.d.ts +39 -2
  410. package/dist/server/pages-data-route.js +46 -3
  411. package/dist/server/pages-default-404.d.ts +1 -2
  412. package/dist/server/pages-default-404.js +0 -2
  413. package/dist/server/pages-document-initial-props.d.ts +84 -3
  414. package/dist/server/pages-document-initial-props.js +127 -3
  415. package/dist/server/pages-get-initial-props.d.ts +17 -0
  416. package/dist/server/pages-get-initial-props.js +50 -0
  417. package/dist/server/pages-i18n.d.ts +1 -2
  418. package/dist/server/pages-i18n.js +0 -2
  419. package/dist/server/pages-media-type.d.ts +1 -2
  420. package/dist/server/pages-media-type.js +1 -2
  421. package/dist/server/pages-node-compat.d.ts +9 -2
  422. package/dist/server/pages-node-compat.js +35 -4
  423. package/dist/server/pages-page-data.d.ts +7 -3
  424. package/dist/server/pages-page-data.js +75 -33
  425. package/dist/server/pages-page-handler.d.ts +90 -0
  426. package/dist/server/pages-page-handler.js +335 -0
  427. package/dist/server/pages-page-method.d.ts +1 -2
  428. package/dist/server/pages-page-method.js +0 -2
  429. package/dist/server/pages-page-response.d.ts +15 -2
  430. package/dist/server/pages-page-response.js +39 -12
  431. package/dist/server/pages-serializable-props.d.ts +1 -2
  432. package/dist/server/pages-serializable-props.js +0 -2
  433. package/dist/server/pregenerated-concrete-paths.d.ts +32 -0
  434. package/dist/server/pregenerated-concrete-paths.js +78 -0
  435. package/dist/server/prerender-route-params.d.ts +13 -3
  436. package/dist/server/prerender-route-params.js +30 -11
  437. package/dist/server/prerender-work-unit-setup.d.ts +1 -2
  438. package/dist/server/prerender-work-unit-setup.js +0 -2
  439. package/dist/server/prod-server.d.ts +2 -4
  440. package/dist/server/prod-server.js +13 -8
  441. package/dist/server/proxy-trust.d.ts +1 -2
  442. package/dist/server/proxy-trust.js +0 -2
  443. package/dist/server/request-log.d.ts +1 -2
  444. package/dist/server/request-log.js +0 -2
  445. package/dist/server/request-pipeline.d.ts +14 -2
  446. package/dist/server/request-pipeline.js +42 -3
  447. package/dist/server/rsc-stream-hints.d.ts +1 -2
  448. package/dist/server/rsc-stream-hints.js +0 -2
  449. package/dist/server/seed-cache.d.ts +6 -2
  450. package/dist/server/seed-cache.js +10 -8
  451. package/dist/server/server-action-not-found.d.ts +1 -2
  452. package/dist/server/server-action-not-found.js +0 -2
  453. package/dist/server/server-globals.d.ts +1 -2
  454. package/dist/server/server-globals.js +0 -2
  455. package/dist/server/skip-cache-proof.d.ts +23 -3
  456. package/dist/server/skip-cache-proof.js +81 -14
  457. package/dist/server/socket-error-backstop.d.ts +1 -2
  458. package/dist/server/socket-error-backstop.js +0 -2
  459. package/dist/server/static-file-cache.d.ts +1 -2
  460. package/dist/server/static-file-cache.js +0 -2
  461. package/dist/server/static-layout-client-reuse-proof.d.ts +15 -0
  462. package/dist/server/static-layout-client-reuse-proof.js +33 -0
  463. package/dist/server/streaming-metadata.d.ts +1 -2
  464. package/dist/server/streaming-metadata.js +0 -2
  465. package/dist/server/worker-utils.d.ts +1 -2
  466. package/dist/server/worker-utils.js +3 -6
  467. package/dist/shims/amp.d.ts +1 -2
  468. package/dist/shims/amp.js +0 -2
  469. package/dist/shims/app-router-scroll-state.d.ts +1 -2
  470. package/dist/shims/app-router-scroll-state.js +0 -2
  471. package/dist/shims/app-router-scroll.d.ts +3 -5
  472. package/dist/shims/app-router-scroll.js +0 -2
  473. package/dist/shims/app.d.ts +1 -2
  474. package/dist/shims/app.js +0 -2
  475. package/dist/shims/before-interactive-context.d.ts +1 -2
  476. package/dist/shims/before-interactive-context.js +0 -2
  477. package/dist/shims/cache-for-request.d.ts +1 -2
  478. package/dist/shims/cache-for-request.js +0 -2
  479. package/dist/shims/cache-runtime.d.ts +20 -5
  480. package/dist/shims/cache-runtime.js +35 -30
  481. package/dist/shims/cache.d.ts +68 -7
  482. package/dist/shims/cache.js +179 -25
  483. package/dist/shims/cdn-cache.d.ts +125 -0
  484. package/dist/shims/cdn-cache.js +100 -0
  485. package/dist/shims/client-hook-error.d.ts +1 -2
  486. package/dist/shims/client-hook-error.js +0 -2
  487. package/dist/shims/client-locale.d.ts +1 -2
  488. package/dist/shims/client-locale.js +1 -3
  489. package/dist/shims/compat-router.d.ts +1 -2
  490. package/dist/shims/compat-router.js +0 -2
  491. package/dist/shims/config.d.ts +1 -2
  492. package/dist/shims/config.js +0 -2
  493. package/dist/shims/constants.d.ts +1 -2
  494. package/dist/shims/constants.js +0 -2
  495. package/dist/shims/default-global-error.d.ts +3 -4
  496. package/dist/shims/default-global-error.js +0 -2
  497. package/dist/shims/default-not-found.d.ts +1 -2
  498. package/dist/shims/default-not-found.js +0 -2
  499. package/dist/shims/document.d.ts +11 -7
  500. package/dist/shims/document.js +7 -10
  501. package/dist/shims/dynamic.d.ts +1 -2
  502. package/dist/shims/dynamic.js +0 -2
  503. package/dist/shims/error-boundary.d.ts +16 -12
  504. package/dist/shims/error-boundary.js +60 -28
  505. package/dist/shims/error.d.ts +1 -2
  506. package/dist/shims/error.js +0 -2
  507. package/dist/shims/fetch-cache.d.ts +3 -2
  508. package/dist/shims/fetch-cache.js +18 -9
  509. package/dist/shims/font-google-base.d.ts +1 -2
  510. package/dist/shims/font-google-base.js +1 -13
  511. package/dist/shims/font-local.d.ts +1 -2
  512. package/dist/shims/font-local.js +1 -15
  513. package/dist/shims/font-utils.d.ts +7 -2
  514. package/dist/shims/font-utils.js +13 -3
  515. package/dist/shims/form.d.ts +12 -5
  516. package/dist/shims/form.js +98 -21
  517. package/dist/shims/hash-scroll.d.ts +4 -2
  518. package/dist/shims/hash-scroll.js +13 -3
  519. package/dist/shims/head-state.d.ts +2 -2
  520. package/dist/shims/head-state.js +18 -5
  521. package/dist/shims/head.d.ts +35 -2
  522. package/dist/shims/head.js +113 -16
  523. package/dist/shims/headers.d.ts +9 -2
  524. package/dist/shims/headers.js +13 -3
  525. package/dist/shims/i18n-context.d.ts +1 -2
  526. package/dist/shims/i18n-context.js +0 -2
  527. package/dist/shims/i18n-state.d.ts +1 -2
  528. package/dist/shims/i18n-state.js +0 -2
  529. package/dist/shims/image-config.d.ts +1 -2
  530. package/dist/shims/image-config.js +0 -2
  531. package/dist/shims/image.d.ts +1 -2
  532. package/dist/shims/image.js +1 -3
  533. package/dist/shims/internal/als-registry.d.ts +1 -2
  534. package/dist/shims/internal/als-registry.js +0 -2
  535. package/dist/shims/internal/api-utils.d.ts +1 -2
  536. package/dist/shims/internal/app-route-detection.d.ts +1 -2
  537. package/dist/shims/internal/app-route-detection.js +0 -2
  538. package/dist/shims/internal/app-router-context.d.ts +1 -2
  539. package/dist/shims/internal/app-router-context.js +0 -2
  540. package/dist/shims/internal/cookie-serialize.d.ts +1 -2
  541. package/dist/shims/internal/cookie-serialize.js +0 -2
  542. package/dist/shims/internal/make-hanging-promise.d.ts +1 -2
  543. package/dist/shims/internal/make-hanging-promise.js +0 -2
  544. package/dist/shims/internal/pages-data-fetch-dedup.d.ts +55 -0
  545. package/dist/shims/internal/pages-data-fetch-dedup.js +68 -0
  546. package/dist/shims/internal/pages-data-target.d.ts +1 -2
  547. package/dist/shims/internal/pages-data-target.js +0 -2
  548. package/dist/shims/internal/pages-data-url.d.ts +1 -2
  549. package/dist/shims/internal/pages-data-url.js +0 -2
  550. package/dist/shims/internal/parse-cookie-header.d.ts +1 -2
  551. package/dist/shims/internal/parse-cookie-header.js +0 -2
  552. package/dist/shims/internal/router-context.d.ts +2 -4
  553. package/dist/shims/internal/router-context.js +0 -2
  554. package/dist/shims/internal/utils.d.ts +1 -2
  555. package/dist/shims/internal/utils.js +0 -2
  556. package/dist/shims/internal/work-unit-async-storage.d.ts +1 -2
  557. package/dist/shims/internal/work-unit-async-storage.js +0 -2
  558. package/dist/shims/layout-segment-context.d.ts +2 -4
  559. package/dist/shims/layout-segment-context.js +0 -2
  560. package/dist/shims/legacy-image.d.ts +1 -2
  561. package/dist/shims/legacy-image.js +0 -2
  562. package/dist/shims/link-prefetch.d.ts +1 -2
  563. package/dist/shims/link-prefetch.js +0 -2
  564. package/dist/shims/link.d.ts +2 -2
  565. package/dist/shims/link.js +47 -15
  566. package/dist/shims/metadata.d.ts +4 -5
  567. package/dist/shims/metadata.js +1 -3
  568. package/dist/shims/navigation-state.d.ts +1 -2
  569. package/dist/shims/navigation-state.js +0 -2
  570. package/dist/shims/navigation.d.ts +61 -7
  571. package/dist/shims/navigation.js +244 -47
  572. package/dist/shims/navigation.react-server.d.ts +1 -2
  573. package/dist/shims/navigation.react-server.js +0 -2
  574. package/dist/shims/offline.d.ts +1 -2
  575. package/dist/shims/offline.js +0 -2
  576. package/dist/shims/og.d.ts +1 -2
  577. package/dist/shims/og.js +2 -4
  578. package/dist/shims/pages-router-runtime.d.ts +7 -2
  579. package/dist/shims/pages-router-runtime.js +11 -3
  580. package/dist/shims/ppr-fallback-shell.d.ts +29 -0
  581. package/dist/shims/ppr-fallback-shell.js +149 -0
  582. package/dist/shims/readonly-url-search-params.d.ts +1 -2
  583. package/dist/shims/readonly-url-search-params.js +0 -2
  584. package/dist/shims/request-context.d.ts +9 -5
  585. package/dist/shims/request-context.js +0 -2
  586. package/dist/shims/request-state-types.d.ts +1 -1
  587. package/dist/shims/root-params.d.ts +1 -2
  588. package/dist/shims/root-params.js +0 -2
  589. package/dist/shims/router-state.d.ts +1 -2
  590. package/dist/shims/router-state.js +0 -2
  591. package/dist/shims/router.d.ts +1 -2
  592. package/dist/shims/router.js +172 -37
  593. package/dist/shims/script-nonce-context.d.ts +1 -2
  594. package/dist/shims/script-nonce-context.js +0 -2
  595. package/dist/shims/script.d.ts +1 -2
  596. package/dist/shims/script.js +0 -2
  597. package/dist/shims/server.d.ts +1 -2
  598. package/dist/shims/server.js +0 -2
  599. package/dist/shims/slot.d.ts +11 -4
  600. package/dist/shims/slot.js +121 -9
  601. package/dist/shims/thenable-params.d.ts +6 -3
  602. package/dist/shims/thenable-params.js +131 -12
  603. package/dist/shims/unified-request-context.d.ts +1 -2
  604. package/dist/shims/unified-request-context.js +3 -2
  605. package/dist/shims/unrecognized-action-error.d.ts +1 -2
  606. package/dist/shims/unrecognized-action-error.js +0 -2
  607. package/dist/shims/url-safety.d.ts +1 -2
  608. package/dist/shims/url-safety.js +0 -2
  609. package/dist/shims/url-utils.d.ts +1 -2
  610. package/dist/shims/url-utils.js +0 -2
  611. package/dist/shims/use-merged-ref.d.ts +1 -2
  612. package/dist/shims/use-merged-ref.js +0 -2
  613. package/dist/shims/web-vitals.d.ts +1 -2
  614. package/dist/shims/web-vitals.js +0 -2
  615. package/dist/typegen.d.ts +1 -2
  616. package/dist/typegen.js +2 -9
  617. package/dist/utils/asset-prefix.d.ts +1 -2
  618. package/dist/utils/asset-prefix.js +0 -2
  619. package/dist/utils/base-path.d.ts +1 -2
  620. package/dist/utils/base-path.js +0 -2
  621. package/dist/utils/cache-control-metadata.d.ts +1 -4
  622. package/dist/utils/cache-control-metadata.js +1 -3
  623. package/dist/utils/client-build-manifest.d.ts +14 -0
  624. package/dist/utils/client-build-manifest.js +52 -0
  625. package/dist/utils/compare.d.ts +4 -0
  626. package/dist/utils/compare.js +8 -0
  627. package/dist/utils/dev-error-recovery-event.d.ts +4 -0
  628. package/dist/utils/dev-error-recovery-event.js +4 -0
  629. package/dist/utils/domain-locale.d.ts +1 -2
  630. package/dist/utils/domain-locale.js +2 -4
  631. package/dist/utils/encode-cache-tag.d.ts +1 -2
  632. package/dist/utils/encode-cache-tag.js +0 -2
  633. package/dist/utils/error-cause.d.ts +1 -2
  634. package/dist/utils/error-cause.js +0 -2
  635. package/dist/utils/hash.d.ts +1 -2
  636. package/dist/utils/hash.js +1 -3
  637. package/dist/utils/html-limited-bots.d.ts +1 -2
  638. package/dist/utils/html-limited-bots.js +0 -2
  639. package/dist/utils/lazy-chunks.d.ts +1 -2
  640. package/dist/utils/lazy-chunks.js +0 -2
  641. package/dist/utils/manifest-paths.d.ts +8 -3
  642. package/dist/utils/manifest-paths.js +15 -3
  643. package/dist/utils/mdx-scan.d.ts +1 -2
  644. package/dist/utils/mdx-scan.js +0 -2
  645. package/dist/utils/navigation-signal.d.ts +1 -2
  646. package/dist/utils/navigation-signal.js +0 -2
  647. package/dist/utils/number.d.ts +4 -0
  648. package/dist/utils/number.js +6 -0
  649. package/dist/utils/path.d.ts +4 -2
  650. package/dist/utils/path.js +5 -3
  651. package/dist/utils/prerender-output-paths.d.ts +1 -2
  652. package/dist/utils/prerender-output-paths.js +0 -2
  653. package/dist/utils/project.d.ts +1 -2
  654. package/dist/utils/project.js +0 -2
  655. package/dist/utils/promise.d.ts +4 -0
  656. package/dist/utils/promise.js +6 -0
  657. package/dist/utils/public-routes.d.ts +1 -2
  658. package/dist/utils/public-routes.js +0 -2
  659. package/dist/utils/query.d.ts +1 -2
  660. package/dist/utils/query.js +0 -2
  661. package/dist/utils/record.d.ts +1 -2
  662. package/dist/utils/record.js +0 -2
  663. package/dist/utils/regex.d.ts +4 -0
  664. package/dist/utils/regex.js +6 -0
  665. package/dist/utils/safe-json-file.d.ts +1 -2
  666. package/dist/utils/safe-json-file.js +0 -2
  667. package/dist/utils/sorted-array.d.ts +1 -2
  668. package/dist/utils/sorted-array.js +0 -2
  669. package/dist/utils/text-stream.d.ts +1 -2
  670. package/dist/utils/text-stream.js +0 -2
  671. package/dist/utils/vinext-root.d.ts +1 -2
  672. package/dist/utils/vinext-root.js +0 -2
  673. package/dist/utils/vite-version.d.ts +10 -0
  674. package/dist/utils/vite-version.js +34 -0
  675. package/package.json +20 -7
  676. package/dist/build/clean-output.js.map +0 -1
  677. package/dist/build/client-build-config.js.map +0 -1
  678. package/dist/build/google-fonts/build-url.js.map +0 -1
  679. package/dist/build/google-fonts/fallback-metrics-data.js.map +0 -1
  680. package/dist/build/google-fonts/fallback-metrics.js.map +0 -1
  681. package/dist/build/google-fonts/font-data.js.map +0 -1
  682. package/dist/build/google-fonts/font-metadata.js.map +0 -1
  683. package/dist/build/google-fonts/get-axes.js.map +0 -1
  684. package/dist/build/google-fonts/sort-variants.js.map +0 -1
  685. package/dist/build/google-fonts/validate.js.map +0 -1
  686. package/dist/build/inline-css.js.map +0 -1
  687. package/dist/build/layout-classification.js.map +0 -1
  688. package/dist/build/nitro-route-rules.js.map +0 -1
  689. package/dist/build/precompress.js.map +0 -1
  690. package/dist/build/prerender.js.map +0 -1
  691. package/dist/build/report.js.map +0 -1
  692. package/dist/build/route-classification-injector.js.map +0 -1
  693. package/dist/build/route-classification-manifest.js.map +0 -1
  694. package/dist/build/run-prerender.js.map +0 -1
  695. package/dist/build/server-manifest.js.map +0 -1
  696. package/dist/build/ssr-manifest.js.map +0 -1
  697. package/dist/build/standalone.js.map +0 -1
  698. package/dist/build/static-export.js.map +0 -1
  699. package/dist/check.js.map +0 -1
  700. package/dist/cli-args.js.map +0 -1
  701. package/dist/cli.js.map +0 -1
  702. package/dist/client/instrumentation-client-inject.js.map +0 -1
  703. package/dist/client/instrumentation-client-state.js.map +0 -1
  704. package/dist/client/instrumentation-client.js.map +0 -1
  705. package/dist/client/navigation-runtime.js.map +0 -1
  706. package/dist/client/pages-router-link-navigation.js.map +0 -1
  707. package/dist/client/validate-module-path.js.map +0 -1
  708. package/dist/client/vinext-next-data.js.map +0 -1
  709. package/dist/client/window-next.js.map +0 -1
  710. package/dist/cloudflare/kv-cache-handler.js.map +0 -1
  711. package/dist/cloudflare/tpr.js.map +0 -1
  712. package/dist/config/config-matchers.js.map +0 -1
  713. package/dist/config/dotenv.js.map +0 -1
  714. package/dist/config/next-config.js.map +0 -1
  715. package/dist/config/tsconfig-paths.js.map +0 -1
  716. package/dist/deploy.js.map +0 -1
  717. package/dist/entries/app-browser-entry.js.map +0 -1
  718. package/dist/entries/app-rsc-entry.js.map +0 -1
  719. package/dist/entries/app-rsc-manifest.js.map +0 -1
  720. package/dist/entries/app-ssr-entry.js.map +0 -1
  721. package/dist/entries/pages-client-entry.js.map +0 -1
  722. package/dist/entries/pages-entry-helpers.js.map +0 -1
  723. package/dist/entries/pages-server-entry.js.map +0 -1
  724. package/dist/entries/runtime-entry-module.js.map +0 -1
  725. package/dist/index.js.map +0 -1
  726. package/dist/init.js.map +0 -1
  727. package/dist/plugins/async-hooks-stub.js.map +0 -1
  728. package/dist/plugins/client-reference-dedup.js.map +0 -1
  729. package/dist/plugins/css-data-url.js.map +0 -1
  730. package/dist/plugins/fonts.js.map +0 -1
  731. package/dist/plugins/instrumentation-client.js.map +0 -1
  732. package/dist/plugins/middleware-server-only.js.map +0 -1
  733. package/dist/plugins/og-assets.js.map +0 -1
  734. package/dist/plugins/optimize-imports.js.map +0 -1
  735. package/dist/plugins/postcss.js.map +0 -1
  736. package/dist/plugins/remove-console.js.map +0 -1
  737. package/dist/plugins/rsc-client-reference-loaders.js.map +0 -1
  738. package/dist/plugins/rsc-client-shim-excludes.js.map +0 -1
  739. package/dist/plugins/sass.js.map +0 -1
  740. package/dist/plugins/server-externals-manifest.js.map +0 -1
  741. package/dist/plugins/strip-server-exports.js.map +0 -1
  742. package/dist/routing/app-route-graph.js.map +0 -1
  743. package/dist/routing/app-router.js.map +0 -1
  744. package/dist/routing/file-matcher.js.map +0 -1
  745. package/dist/routing/pages-router.js.map +0 -1
  746. package/dist/routing/route-matching.js.map +0 -1
  747. package/dist/routing/route-pattern.js.map +0 -1
  748. package/dist/routing/route-trie.js.map +0 -1
  749. package/dist/routing/route-validation.js.map +0 -1
  750. package/dist/routing/utils.js.map +0 -1
  751. package/dist/server/api-handler.js.map +0 -1
  752. package/dist/server/app-browser-action-result.js.map +0 -1
  753. package/dist/server/app-browser-entry.js.map +0 -1
  754. package/dist/server/app-browser-error.js.map +0 -1
  755. package/dist/server/app-browser-hydration.js.map +0 -1
  756. package/dist/server/app-browser-interception-context.js.map +0 -1
  757. package/dist/server/app-browser-navigation-controller.js.map +0 -1
  758. package/dist/server/app-browser-popstate.js.map +0 -1
  759. package/dist/server/app-browser-rsc-redirect.js.map +0 -1
  760. package/dist/server/app-browser-state.js.map +0 -1
  761. package/dist/server/app-browser-stream.js.map +0 -1
  762. package/dist/server/app-browser-visible-commit.js.map +0 -1
  763. package/dist/server/app-client-reference-preloader.js.map +0 -1
  764. package/dist/server/app-elements-wire.js.map +0 -1
  765. package/dist/server/app-elements.js.map +0 -1
  766. package/dist/server/app-fallback-renderer.js.map +0 -1
  767. package/dist/server/app-history-state.js.map +0 -1
  768. package/dist/server/app-hook-warning-suppression.js.map +0 -1
  769. package/dist/server/app-inline-css-client.js.map +0 -1
  770. package/dist/server/app-interception-context-header.js.map +0 -1
  771. package/dist/server/app-middleware.js.map +0 -1
  772. package/dist/server/app-mounted-slots-header.js.map +0 -1
  773. package/dist/server/app-optimistic-routing.js.map +0 -1
  774. package/dist/server/app-page-boundary-render.js.map +0 -1
  775. package/dist/server/app-page-boundary.js.map +0 -1
  776. package/dist/server/app-page-cache.js.map +0 -1
  777. package/dist/server/app-page-dispatch.js.map +0 -1
  778. package/dist/server/app-page-element-builder.js.map +0 -1
  779. package/dist/server/app-page-execution.js.map +0 -1
  780. package/dist/server/app-page-head.js.map +0 -1
  781. package/dist/server/app-page-method.js.map +0 -1
  782. package/dist/server/app-page-params.js.map +0 -1
  783. package/dist/server/app-page-probe.js.map +0 -1
  784. package/dist/server/app-page-render-identity.js.map +0 -1
  785. package/dist/server/app-page-render-observation.js.map +0 -1
  786. package/dist/server/app-page-render.js.map +0 -1
  787. package/dist/server/app-page-request.js.map +0 -1
  788. package/dist/server/app-page-response.js.map +0 -1
  789. package/dist/server/app-page-route-wiring.js.map +0 -1
  790. package/dist/server/app-page-segment-state.js.map +0 -1
  791. package/dist/server/app-page-stream.js.map +0 -1
  792. package/dist/server/app-post-middleware-context.js.map +0 -1
  793. package/dist/server/app-prerender-endpoints.js.map +0 -1
  794. package/dist/server/app-prerender-static-params.js.map +0 -1
  795. package/dist/server/app-render-dependency.js.map +0 -1
  796. package/dist/server/app-request-context.js.map +0 -1
  797. package/dist/server/app-route-handler-cache.js.map +0 -1
  798. package/dist/server/app-route-handler-dispatch.js.map +0 -1
  799. package/dist/server/app-route-handler-execution.js.map +0 -1
  800. package/dist/server/app-route-handler-policy.js.map +0 -1
  801. package/dist/server/app-route-handler-response.js.map +0 -1
  802. package/dist/server/app-route-handler-runtime.js.map +0 -1
  803. package/dist/server/app-router-entry.js.map +0 -1
  804. package/dist/server/app-rsc-cache-busting.js.map +0 -1
  805. package/dist/server/app-rsc-embedded-chunks.js.map +0 -1
  806. package/dist/server/app-rsc-error-handler.js.map +0 -1
  807. package/dist/server/app-rsc-errors.js.map +0 -1
  808. package/dist/server/app-rsc-handler.js.map +0 -1
  809. package/dist/server/app-rsc-render-mode.js.map +0 -1
  810. package/dist/server/app-rsc-request-normalization.js.map +0 -1
  811. package/dist/server/app-rsc-response-finalizer.js.map +0 -1
  812. package/dist/server/app-rsc-route-matching.js.map +0 -1
  813. package/dist/server/app-segment-config.js.map +0 -1
  814. package/dist/server/app-server-action-execution.js.map +0 -1
  815. package/dist/server/app-ssr-entry.js.map +0 -1
  816. package/dist/server/app-ssr-error-meta.js.map +0 -1
  817. package/dist/server/app-ssr-stream.js.map +0 -1
  818. package/dist/server/app-static-generation.js.map +0 -1
  819. package/dist/server/artifact-compatibility.js.map +0 -1
  820. package/dist/server/cache-control.js.map +0 -1
  821. package/dist/server/cache-headers.js.map +0 -1
  822. package/dist/server/cache-proof.js.map +0 -1
  823. package/dist/server/client-reuse-manifest.js.map +0 -1
  824. package/dist/server/client-trace-metadata.js.map +0 -1
  825. package/dist/server/cookie-utils.js.map +0 -1
  826. package/dist/server/csp.js.map +0 -1
  827. package/dist/server/default-global-error-module.js.map +0 -1
  828. package/dist/server/default-not-found-module.js.map +0 -1
  829. package/dist/server/dev-error-overlay-store.js.map +0 -1
  830. package/dist/server/dev-error-overlay.js.map +0 -1
  831. package/dist/server/dev-lockfile.js.map +0 -1
  832. package/dist/server/dev-module-runner.js.map +0 -1
  833. package/dist/server/dev-origin-check.js.map +0 -1
  834. package/dist/server/dev-route-files.js.map +0 -1
  835. package/dist/server/dev-server.js.map +0 -1
  836. package/dist/server/edge-api-runtime.js.map +0 -1
  837. package/dist/server/file-based-metadata.js.map +0 -1
  838. package/dist/server/headers.js.map +0 -1
  839. package/dist/server/html.js.map +0 -1
  840. package/dist/server/http-error-responses.js.map +0 -1
  841. package/dist/server/image-optimization.js.map +0 -1
  842. package/dist/server/implicit-tags.js.map +0 -1
  843. package/dist/server/instrumentation-runtime.js.map +0 -1
  844. package/dist/server/instrumentation.js.map +0 -1
  845. package/dist/server/isr-cache.js.map +0 -1
  846. package/dist/server/metadata-route-build-data.js.map +0 -1
  847. package/dist/server/metadata-route-response.js.map +0 -1
  848. package/dist/server/metadata-routes.js.map +0 -1
  849. package/dist/server/middleware-matcher.js.map +0 -1
  850. package/dist/server/middleware-request-headers.js.map +0 -1
  851. package/dist/server/middleware-response-headers.js.map +0 -1
  852. package/dist/server/middleware-runtime.js.map +0 -1
  853. package/dist/server/middleware.js.map +0 -1
  854. package/dist/server/navigation-planner.js.map +0 -1
  855. package/dist/server/navigation-trace.js.map +0 -1
  856. package/dist/server/next-error-digest.js.map +0 -1
  857. package/dist/server/normalize-path.js.map +0 -1
  858. package/dist/server/pages-api-route.js.map +0 -1
  859. package/dist/server/pages-body-parser-config.js.map +0 -1
  860. package/dist/server/pages-data-route.js.map +0 -1
  861. package/dist/server/pages-default-404.js.map +0 -1
  862. package/dist/server/pages-document-initial-props.js.map +0 -1
  863. package/dist/server/pages-i18n.js.map +0 -1
  864. package/dist/server/pages-media-type.js.map +0 -1
  865. package/dist/server/pages-node-compat.js.map +0 -1
  866. package/dist/server/pages-page-data.js.map +0 -1
  867. package/dist/server/pages-page-method.js.map +0 -1
  868. package/dist/server/pages-page-response.js.map +0 -1
  869. package/dist/server/pages-serializable-props.js.map +0 -1
  870. package/dist/server/prerender-route-params.js.map +0 -1
  871. package/dist/server/prerender-work-unit-setup.js.map +0 -1
  872. package/dist/server/prod-server.js.map +0 -1
  873. package/dist/server/proxy-trust.js.map +0 -1
  874. package/dist/server/request-log.js.map +0 -1
  875. package/dist/server/request-pipeline.js.map +0 -1
  876. package/dist/server/rsc-stream-hints.js.map +0 -1
  877. package/dist/server/seed-cache.js.map +0 -1
  878. package/dist/server/server-action-not-found.js.map +0 -1
  879. package/dist/server/server-globals.js.map +0 -1
  880. package/dist/server/skip-cache-proof.js.map +0 -1
  881. package/dist/server/socket-error-backstop.js.map +0 -1
  882. package/dist/server/static-file-cache.js.map +0 -1
  883. package/dist/server/streaming-metadata.js.map +0 -1
  884. package/dist/server/worker-utils.js.map +0 -1
  885. package/dist/shims/amp.js.map +0 -1
  886. package/dist/shims/app-router-scroll-state.js.map +0 -1
  887. package/dist/shims/app-router-scroll.js.map +0 -1
  888. package/dist/shims/app.js.map +0 -1
  889. package/dist/shims/before-interactive-context.js.map +0 -1
  890. package/dist/shims/cache-for-request.js.map +0 -1
  891. package/dist/shims/cache-runtime.js.map +0 -1
  892. package/dist/shims/cache.js.map +0 -1
  893. package/dist/shims/client-hook-error.js.map +0 -1
  894. package/dist/shims/client-locale.js.map +0 -1
  895. package/dist/shims/compat-router.js.map +0 -1
  896. package/dist/shims/config.js.map +0 -1
  897. package/dist/shims/constants.js.map +0 -1
  898. package/dist/shims/default-global-error.js.map +0 -1
  899. package/dist/shims/default-not-found.js.map +0 -1
  900. package/dist/shims/document.js.map +0 -1
  901. package/dist/shims/dynamic.js.map +0 -1
  902. package/dist/shims/error-boundary.js.map +0 -1
  903. package/dist/shims/error.js.map +0 -1
  904. package/dist/shims/fetch-cache.js.map +0 -1
  905. package/dist/shims/font-google-base.js.map +0 -1
  906. package/dist/shims/font-local.js.map +0 -1
  907. package/dist/shims/font-utils.js.map +0 -1
  908. package/dist/shims/form.js.map +0 -1
  909. package/dist/shims/hash-scroll.js.map +0 -1
  910. package/dist/shims/head-state.js.map +0 -1
  911. package/dist/shims/head.js.map +0 -1
  912. package/dist/shims/headers.js.map +0 -1
  913. package/dist/shims/i18n-context.js.map +0 -1
  914. package/dist/shims/i18n-state.js.map +0 -1
  915. package/dist/shims/image-config.js.map +0 -1
  916. package/dist/shims/image.js.map +0 -1
  917. package/dist/shims/internal/als-registry.js.map +0 -1
  918. package/dist/shims/internal/app-route-detection.js.map +0 -1
  919. package/dist/shims/internal/app-router-context.js.map +0 -1
  920. package/dist/shims/internal/cookie-serialize.js.map +0 -1
  921. package/dist/shims/internal/make-hanging-promise.js.map +0 -1
  922. package/dist/shims/internal/pages-data-target.js.map +0 -1
  923. package/dist/shims/internal/pages-data-url.js.map +0 -1
  924. package/dist/shims/internal/parse-cookie-header.js.map +0 -1
  925. package/dist/shims/internal/router-context.js.map +0 -1
  926. package/dist/shims/internal/utils.js.map +0 -1
  927. package/dist/shims/internal/work-unit-async-storage.js.map +0 -1
  928. package/dist/shims/layout-segment-context.js.map +0 -1
  929. package/dist/shims/legacy-image.js.map +0 -1
  930. package/dist/shims/link-prefetch.js.map +0 -1
  931. package/dist/shims/link.js.map +0 -1
  932. package/dist/shims/metadata.js.map +0 -1
  933. package/dist/shims/navigation-state.js.map +0 -1
  934. package/dist/shims/navigation.js.map +0 -1
  935. package/dist/shims/navigation.react-server.js.map +0 -1
  936. package/dist/shims/offline.js.map +0 -1
  937. package/dist/shims/og.js.map +0 -1
  938. package/dist/shims/pages-router-runtime.js.map +0 -1
  939. package/dist/shims/readonly-url-search-params.js.map +0 -1
  940. package/dist/shims/request-context.js.map +0 -1
  941. package/dist/shims/root-params.js.map +0 -1
  942. package/dist/shims/router-state.js.map +0 -1
  943. package/dist/shims/router.js.map +0 -1
  944. package/dist/shims/script-nonce-context.js.map +0 -1
  945. package/dist/shims/script.js.map +0 -1
  946. package/dist/shims/server.js.map +0 -1
  947. package/dist/shims/slot.js.map +0 -1
  948. package/dist/shims/thenable-params.js.map +0 -1
  949. package/dist/shims/unified-request-context.js.map +0 -1
  950. package/dist/shims/unrecognized-action-error.js.map +0 -1
  951. package/dist/shims/url-safety.js.map +0 -1
  952. package/dist/shims/url-utils.js.map +0 -1
  953. package/dist/shims/use-merged-ref.js.map +0 -1
  954. package/dist/shims/web-vitals.js.map +0 -1
  955. package/dist/typegen.js.map +0 -1
  956. package/dist/utils/asset-prefix.js.map +0 -1
  957. package/dist/utils/base-path.js.map +0 -1
  958. package/dist/utils/cache-control-metadata.js.map +0 -1
  959. package/dist/utils/domain-locale.js.map +0 -1
  960. package/dist/utils/encode-cache-tag.js.map +0 -1
  961. package/dist/utils/error-cause.js.map +0 -1
  962. package/dist/utils/hash.js.map +0 -1
  963. package/dist/utils/html-limited-bots.js.map +0 -1
  964. package/dist/utils/lazy-chunks.js.map +0 -1
  965. package/dist/utils/manifest-paths.js.map +0 -1
  966. package/dist/utils/mdx-scan.js.map +0 -1
  967. package/dist/utils/navigation-signal.js.map +0 -1
  968. package/dist/utils/path.js.map +0 -1
  969. package/dist/utils/prerender-output-paths.js.map +0 -1
  970. package/dist/utils/project.js.map +0 -1
  971. package/dist/utils/public-routes.js.map +0 -1
  972. package/dist/utils/query.js.map +0 -1
  973. package/dist/utils/record.js.map +0 -1
  974. package/dist/utils/safe-json-file.js.map +0 -1
  975. package/dist/utils/sorted-array.js.map +0 -1
  976. package/dist/utils/text-stream.js.map +0 -1
  977. package/dist/utils/vinext-root.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"tpr.js","names":[],"sources":["../../src/cloudflare/tpr.ts"],"sourcesContent":["/**\n * TPR: Traffic-aware Pre-Rendering\n *\n * Uses Cloudflare zone analytics to determine which pages actually get\n * traffic, and pre-renders only those during deploy. The pre-rendered\n * HTML is uploaded to KV in the same format ISR uses at runtime — no\n * runtime changes needed.\n *\n * Flow:\n * 1. Parse wrangler config to find custom domain and KV namespace\n * 2. Resolve the Cloudflare zone for the custom domain\n * 3. Query zone analytics (GraphQL) for top pages by request count\n * 4. Walk ranked list until coverage threshold is met\n * 5. Start the built production server locally\n * 6. Fetch each hot route to produce HTML\n * 7. Upload pre-rendered HTML to KV (same KVCacheEntry format ISR reads)\n *\n * TPR is an experimental feature enabled via --experimental-tpr. It\n * gracefully skips when no custom domain, no API token, no traffic data,\n * or no KV namespace is configured.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { VINEXT_REVALIDATE_HEADER } from \"../server/headers.js\";\nimport { isrCacheKey } from \"../server/isr-cache.js\";\nimport { ENTRY_PREFIX } from \"./kv-cache-handler.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport type TPROptions = {\n /** Project root directory. */\n root: string;\n /** Traffic coverage percentage (0–100). Default: 90. */\n coverage: number;\n /** Hard cap on number of pages to pre-render. Default: 1000. */\n limit: number;\n /** Analytics lookback window in hours. Default: 24. */\n window: number;\n};\n\nexport type TPRResult = {\n /** Total unique page paths found in analytics. */\n totalPaths: number;\n /** Number of pages successfully pre-rendered and uploaded. */\n prerenderedCount: number;\n /** Actual traffic coverage achieved (percentage). */\n coverageAchieved: number;\n /** Wall-clock duration of the TPR step in milliseconds. */\n durationMs: number;\n /** If TPR was skipped, the reason. */\n skipped?: string;\n};\n\ntype TrafficEntry = {\n path: string;\n requests: number;\n};\n\ntype SelectedRoutes = {\n routes: TrafficEntry[];\n totalRequests: number;\n coveredRequests: number;\n coveragePercent: number;\n};\n\ntype PrerenderResult = {\n html: string;\n status: number;\n headers: Record<string, string>;\n};\n\ntype WranglerConfig = {\n accountId?: string;\n kvNamespaceId?: string;\n customDomain?: string;\n};\n\n// ─── Wrangler Config Parsing ─────────────────────────────────────────────────\n\n/**\n * Parse wrangler config (JSONC or TOML) to extract the fields TPR needs:\n * account_id, VINEXT_CACHE KV namespace ID, and custom domain.\n */\nexport function parseWranglerConfig(root: string): WranglerConfig | null {\n // Try JSONC / JSON first\n for (const filename of [\"wrangler.jsonc\", \"wrangler.json\"]) {\n const filepath = path.join(root, filename);\n if (fs.existsSync(filepath)) {\n const content = fs.readFileSync(filepath, \"utf-8\");\n try {\n const json = JSON.parse(stripJsonComments(content));\n return extractFromJSON(json);\n } catch {\n continue;\n }\n }\n }\n\n // Try TOML\n const tomlPath = path.join(root, \"wrangler.toml\");\n if (fs.existsSync(tomlPath)) {\n const content = fs.readFileSync(tomlPath, \"utf-8\");\n return extractFromTOML(content);\n }\n\n return null;\n}\n\n/**\n * Strip single-line (//) and multi-line comments from JSONC while\n * preserving strings that contain slashes.\n */\nfunction stripJsonComments(str: string): string {\n let result = \"\";\n let inString = false;\n let inSingleLine = false;\n let inMultiLine = false;\n let escapeNext = false;\n\n for (let i = 0; i < str.length; i++) {\n const ch = str[i];\n const next = str[i + 1];\n\n if (escapeNext) {\n if (!inSingleLine && !inMultiLine) result += ch;\n escapeNext = false;\n continue;\n }\n\n if (ch === \"\\\\\" && inString) {\n result += ch;\n escapeNext = true;\n continue;\n }\n\n if (inSingleLine) {\n if (ch === \"\\n\") {\n inSingleLine = false;\n result += ch;\n }\n continue;\n }\n\n if (inMultiLine) {\n if (ch === \"*\" && next === \"/\") {\n inMultiLine = false;\n i++;\n }\n continue;\n }\n\n if (ch === '\"' && !inString) {\n inString = true;\n result += ch;\n continue;\n }\n\n if (ch === '\"' && inString) {\n inString = false;\n result += ch;\n continue;\n }\n\n if (!inString && ch === \"/\" && next === \"/\") {\n inSingleLine = true;\n i++;\n continue;\n }\n\n if (!inString && ch === \"/\" && next === \"*\") {\n inMultiLine = true;\n i++;\n continue;\n }\n\n result += ch;\n }\n\n return result;\n}\n\nfunction extractFromJSON(config: Record<string, unknown>): WranglerConfig {\n const result: WranglerConfig = {};\n\n // account_id\n if (typeof config.account_id === \"string\") {\n result.accountId = config.account_id;\n }\n\n // KV namespace ID for VINEXT_CACHE\n if (Array.isArray(config.kv_namespaces)) {\n const vinextKV = config.kv_namespaces.find(\n (ns: Record<string, unknown>) =>\n ns && typeof ns === \"object\" && ns.binding === \"VINEXT_CACHE\",\n );\n if (vinextKV && typeof vinextKV.id === \"string\" && vinextKV.id !== \"<your-kv-namespace-id>\") {\n result.kvNamespaceId = vinextKV.id;\n }\n }\n\n // Custom domain — check routes[] and custom_domains[]\n const domain = extractDomainFromRoutes(config.routes) ?? extractDomainFromCustomDomains(config);\n if (domain) result.customDomain = domain;\n\n return result;\n}\n\nfunction extractDomainFromRoutes(routes: unknown): string | null {\n if (!Array.isArray(routes)) return null;\n\n for (const route of routes) {\n if (typeof route === \"string\") {\n const domain = cleanDomain(route);\n if (domain && !domain.includes(\"workers.dev\")) return domain;\n } else if (route && typeof route === \"object\") {\n const r = route as Record<string, unknown>;\n const pattern =\n typeof r.zone_name === \"string\"\n ? r.zone_name\n : typeof r.pattern === \"string\"\n ? r.pattern\n : null;\n if (pattern) {\n const domain = cleanDomain(pattern);\n if (domain && !domain.includes(\"workers.dev\")) return domain;\n }\n }\n }\n return null;\n}\n\nfunction extractDomainFromCustomDomains(config: Record<string, unknown>): string | null {\n // Workers Custom Domains: \"custom_domains\": [\"example.com\"]\n if (Array.isArray(config.custom_domains)) {\n for (const d of config.custom_domains) {\n if (typeof d === \"string\" && !d.includes(\"workers.dev\")) {\n return cleanDomain(d);\n }\n }\n }\n return null;\n}\n\n/** Strip protocol and trailing wildcards from a route pattern to get a bare domain. */\nfunction cleanDomain(raw: string): string | null {\n const cleaned = raw\n .replace(/^https?:\\/\\//, \"\")\n .replace(/\\/\\*$/, \"\")\n .replace(/\\/+$/, \"\")\n .split(\"/\")[0]; // Take only the host part\n return cleaned || null;\n}\n\n/**\n * Simple extraction of specific fields from wrangler.toml content.\n * Not a full TOML parser — just enough for the fields we need.\n */\nfunction extractFromTOML(content: string): WranglerConfig {\n const result: WranglerConfig = {};\n\n // account_id = \"...\"\n const accountMatch = content.match(/^account_id\\s*=\\s*\"([^\"]+)\"/m);\n if (accountMatch) result.accountId = accountMatch[1];\n\n // KV namespace with binding = \"VINEXT_CACHE\"\n // Look for [[kv_namespaces]] blocks\n const kvBlocks = content.split(/\\[\\[kv_namespaces\\]\\]/);\n for (let i = 1; i < kvBlocks.length; i++) {\n const block = kvBlocks[i].split(/\\[\\[/)[0]; // Take until next section\n const bindingMatch = block.match(/binding\\s*=\\s*\"([^\"]+)\"/);\n const idMatch = block.match(/\\bid\\s*=\\s*\"([^\"]+)\"/);\n if (\n bindingMatch?.[1] === \"VINEXT_CACHE\" &&\n idMatch?.[1] &&\n idMatch[1] !== \"<your-kv-namespace-id>\"\n ) {\n result.kvNamespaceId = idMatch[1];\n }\n }\n\n // routes — both string and table forms\n // route = \"example.com/*\"\n const routeMatch = content.match(/^route\\s*=\\s*\"([^\"]+)\"/m);\n if (routeMatch) {\n const domain = cleanDomain(routeMatch[1]);\n if (domain && !domain.includes(\"workers.dev\")) {\n result.customDomain = domain;\n }\n }\n\n // [[routes]] blocks\n if (!result.customDomain) {\n const routeBlocks = content.split(/\\[\\[routes\\]\\]/);\n for (let i = 1; i < routeBlocks.length; i++) {\n const block = routeBlocks[i].split(/\\[\\[/)[0];\n const patternMatch = block.match(/pattern\\s*=\\s*\"([^\"]+)\"/);\n if (patternMatch) {\n const domain = cleanDomain(patternMatch[1]);\n if (domain && !domain.includes(\"workers.dev\")) {\n result.customDomain = domain;\n break;\n }\n }\n }\n }\n\n return result;\n}\n\n// ─── Cloudflare API ──────────────────────────────────────────────────────────\n\n/**\n * Generate zone lookup candidates from shortest (2-part) to longest.\n * Tries the most common case first (e.g., \"example.com\") and progressively\n * adds labels for multi-part TLDs (e.g., \"co.uk\" → \"example.co.uk\").\n *\n * \"shop.example.com\" → [\"example.com\", \"shop.example.com\"]\n * \"shop.example.co.uk\" → [\"co.uk\", \"example.co.uk\", \"shop.example.co.uk\"]\n * \"example.com\" → [\"example.com\"]\n */\nexport function domainCandidates(domain: string): string[] {\n const parts = domain.split(\".\");\n const candidates: string[] = [];\n for (let i = parts.length - 2; i >= 0; i--) {\n candidates.push(parts.slice(i).join(\".\"));\n }\n return candidates;\n}\n\n/** Resolve zone ID from a domain name via the Cloudflare API. */\nasync function resolveZoneId(domain: string, apiToken: string): Promise<string | null> {\n // Try progressively longer domain candidates until one matches a zone.\n // This handles all public suffixes without a hardcoded TLD list —\n // for simple TLDs (.com, .io) the 2-part candidate hits on the first try;\n // for multi-part TLDs (.co.uk, .com.au) it takes one extra call.\n for (const candidate of domainCandidates(domain)) {\n const response = await fetch(\n `https://api.cloudflare.com/client/v4/zones?name=${encodeURIComponent(candidate)}`,\n {\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n },\n );\n\n if (!response.ok) continue;\n\n const data = (await response.json()) as {\n success: boolean;\n result?: Array<{ id: string }>;\n };\n if (data.success && data.result?.length) {\n return data.result[0].id;\n }\n }\n\n return null;\n}\n\n/** Resolve the account ID associated with the API token. */\nasync function resolveAccountId(apiToken: string): Promise<string | null> {\n const response = await fetch(\"https://api.cloudflare.com/client/v4/accounts?per_page=1\", {\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!response.ok) return null;\n\n const data = (await response.json()) as {\n success: boolean;\n result?: Array<{ id: string }>;\n };\n if (!data.success || !data.result?.length) return null;\n\n return data.result[0].id;\n}\n\n// ─── Traffic Querying ────────────────────────────────────────────────────────\n\n/**\n * Query Cloudflare zone analytics for top page paths by request count\n * over the given time window.\n */\nasync function queryTraffic(\n zoneTag: string,\n apiToken: string,\n windowHours: number,\n): Promise<TrafficEntry[]> {\n const now = new Date();\n const start = new Date(now.getTime() - windowHours * 60 * 60 * 1000);\n\n const query = `{\n viewer {\n zones(filter: { zoneTag: \"${zoneTag}\" }) {\n httpRequestsAdaptiveGroups(\n limit: 10000\n orderBy: [sum_requests_DESC]\n filter: {\n datetime_geq: \"${start.toISOString()}\"\n datetime_lt: \"${now.toISOString()}\"\n requestSource: \"eyeball\"\n }\n ) {\n sum { requests }\n dimensions { clientRequestPath }\n }\n }\n }\n }`;\n\n const response = await fetch(\"https://api.cloudflare.com/client/v4/graphql\", {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ query }),\n });\n\n if (!response.ok) {\n throw new Error(`Zone analytics query failed: ${response.status} ${response.statusText}`);\n }\n\n const data = (await response.json()) as {\n errors?: Array<{ message: string }>;\n data?: {\n viewer?: {\n zones?: Array<{\n httpRequestsAdaptiveGroups?: Array<{\n sum: { requests: number };\n dimensions: { clientRequestPath: string };\n }>;\n }>;\n };\n };\n };\n\n if (data.errors?.length) {\n throw new Error(`Zone analytics error: ${data.errors[0].message}`);\n }\n\n const groups = data.data?.viewer?.zones?.[0]?.httpRequestsAdaptiveGroups;\n if (!groups || groups.length === 0) return [];\n\n return filterTrafficPaths(\n groups.map((g) => ({\n path: g.dimensions.clientRequestPath,\n requests: g.sum.requests,\n })),\n );\n}\n\n/** Filter out non-page requests (static assets, API routes, internal routes). */\nfunction filterTrafficPaths(entries: TrafficEntry[]): TrafficEntry[] {\n return entries.filter((e) => {\n if (!e.path.startsWith(\"/\")) return false;\n // Static assets\n if (/\\.(js|css|png|jpg|jpeg|gif|svg|ico|woff2?|ttf|eot|map|webp|avif)$/i.test(e.path))\n return false;\n // API routes\n if (e.path.startsWith(\"/api/\")) return false;\n // Internal routes\n if (e.path.startsWith(\"/_next/\") || e.path.startsWith(\"/__vinext/\")) return false;\n // RSC requests\n if (e.path.endsWith(\".rsc\")) return false;\n return true;\n });\n}\n\n// ─── Route Selection ─────────────────────────────────────────────────────────\n\n/**\n * Walk the ranked traffic list, accumulating request counts until the\n * coverage target is met or the hard cap is reached.\n */\nfunction selectRoutes(\n traffic: TrafficEntry[],\n coverageTarget: number,\n limit: number,\n): SelectedRoutes {\n const totalRequests = traffic.reduce((sum, e) => sum + e.requests, 0);\n if (totalRequests === 0) {\n return { routes: [], totalRequests: 0, coveredRequests: 0, coveragePercent: 0 };\n }\n\n const target = totalRequests * (coverageTarget / 100);\n const selected: TrafficEntry[] = [];\n let accumulated = 0;\n\n // Traffic is already sorted DESC by requests from the GraphQL query\n for (const entry of traffic) {\n if (accumulated >= target || selected.length >= limit) break;\n selected.push(entry);\n accumulated += entry.requests;\n }\n\n return {\n routes: selected,\n totalRequests,\n coveredRequests: accumulated,\n coveragePercent: (accumulated / totalRequests) * 100,\n };\n}\n\n// ─── Pre-rendering ───────────────────────────────────────────────────────────\n\n/** Pre-render port — high number to avoid collisions with dev servers. */\nconst PRERENDER_PORT = 19384;\n\n/** Max time to wait for the local server to start (ms). */\nconst SERVER_STARTUP_TIMEOUT = 30_000;\n\n/** Max concurrent fetch requests during pre-rendering. */\nconst FETCH_CONCURRENCY = 10;\n\n/**\n * Start a local production server, fetch each route to produce HTML,\n * and return the results. Pages that fail to render are skipped.\n */\nasync function prerenderRoutes(\n routes: string[],\n root: string,\n hostDomain?: string,\n): Promise<Map<string, PrerenderResult>> {\n const results = new Map<string, PrerenderResult>();\n let failedCount = 0;\n const port = PRERENDER_PORT;\n\n // Verify dist/ exists\n const distDir = path.join(root, \"dist\");\n if (!fs.existsSync(distDir)) {\n console.log(\" TPR: Skipping pre-render — dist/ directory not found\");\n return results;\n }\n\n // Start the local production server as a subprocess\n const serverProcess = startLocalServer(root, port);\n\n try {\n await waitForServer(port, SERVER_STARTUP_TIMEOUT);\n\n // Fetch routes in batches to limit concurrency\n for (let i = 0; i < routes.length; i += FETCH_CONCURRENCY) {\n const batch = routes.slice(i, i + FETCH_CONCURRENCY);\n const promises = batch.map(async (routePath) => {\n try {\n const response = await fetch(`http://127.0.0.1:${port}${routePath}`, {\n headers: {\n \"User-Agent\": \"vinext-tpr/1.0\",\n ...(hostDomain ? { Host: hostDomain } : {}),\n },\n redirect: \"manual\", // Don't follow redirects — cache the redirect itself\n });\n\n // Only cache successful responses (2xx and 3xx)\n if (response.status < 400) {\n const html = await response.text();\n const headers: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n // Only keep relevant headers\n if (\n key === \"content-type\" ||\n key === \"cache-control\" ||\n key === VINEXT_REVALIDATE_HEADER ||\n key === \"location\"\n ) {\n headers[key] = value;\n }\n });\n results.set(routePath, {\n html,\n status: response.status,\n headers,\n });\n }\n } catch {\n // Skip pages that fail to render — they may depend on\n // request-specific data (cookies, headers, auth) that\n // isn't available during pre-rendering.\n failedCount++;\n }\n });\n\n await Promise.all(promises);\n }\n\n if (failedCount > 0) {\n console.log(` TPR: ${failedCount} page(s) failed to pre-render (skipped)`);\n }\n } finally {\n serverProcess.kill(\"SIGTERM\");\n // Give it a moment to clean up\n await new Promise<void>((resolve) => {\n serverProcess.on(\"exit\", resolve);\n setTimeout(resolve, 2000);\n });\n }\n\n return results;\n}\n\n/**\n * Spawn a subprocess running the vinext production server.\n * Uses the same Node.js binary and resolves prod-server.js relative\n * to the current module (works whether vinext is installed or linked).\n */\nfunction startLocalServer(root: string, port: number): ChildProcess {\n const prodServerPath = path.resolve(import.meta.dirname, \"..\", \"server\", \"prod-server.js\");\n const outDir = path.join(root, \"dist\");\n\n // Escape backslashes for Windows paths inside the JS string\n const escapedProdServer = prodServerPath.replace(/\\\\/g, \"\\\\\\\\\");\n const escapedOutDir = outDir.replace(/\\\\/g, \"\\\\\\\\\");\n\n const script = [\n `import(\"file://${escapedProdServer}\")`,\n `.then(m => m.startProdServer({ port: ${port}, host: \"127.0.0.1\", outDir: \"${escapedOutDir}\" }))`,\n `.catch(e => { console.error(\"[vinext-tpr] Server failed to start:\", e); process.exit(1); });`,\n ].join(\"\");\n\n const proc = spawn(process.execPath, [\"--input-type=module\", \"-e\", script], {\n cwd: root,\n stdio: \"pipe\",\n env: { ...process.env, NODE_ENV: \"production\" },\n });\n\n // Forward server errors to the parent's stderr for debugging\n proc.stderr?.on(\"data\", (chunk: Buffer) => {\n const msg = chunk.toString().trim();\n if (msg) console.error(` [tpr-server] ${msg}`);\n });\n\n return proc;\n}\n\n/** Poll the local server until it responds or the timeout is reached. */\nasync function waitForServer(port: number, timeoutMs: number): Promise<void> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 2000);\n const response = await fetch(`http://127.0.0.1:${port}/`, {\n redirect: \"manual\",\n signal: controller.signal,\n });\n clearTimeout(timer);\n // Any response means the server is up\n await response.text(); // consume body\n return;\n } catch {\n await new Promise<void>((r) => setTimeout(r, 300));\n }\n }\n throw new Error(`Local production server failed to start within ${timeoutMs / 1000}s`);\n}\n\n// ─── KV Upload ───────────────────────────────────────────────────────────────\n\n/** KV bulk API accepts up to 10,000 pairs per request */\nconst KV_BATCH_SIZE = 10_000;\n\n/** Maximum KV expiration TTL: 30 days */\nconst MAX_KV_TTL_SECONDS = 30 * 24 * 3600;\n\n/**\n * Build KV bulk API pairs from pre-rendered entries.\n *\n * Key format matches the runtime KVCacheHandler exactly:\n * ENTRY_PREFIX + isrCacheKey(\"app\", pathname, buildId) + \":html\"\n * → \"cache:app:<buildId>:<pathname>:html\"\n */\nexport function buildTprKVPairs(\n entries: Map<string, PrerenderResult>,\n buildId: string | undefined,\n defaultRevalidateSeconds: number,\n): Array<{ key: string; value: string; expiration_ttl: number }> {\n const now = Date.now();\n const pairs: Array<{ key: string; value: string; expiration_ttl: number }> = [];\n\n for (const [routePath, result] of entries) {\n const revalidateHeader = result.headers[VINEXT_REVALIDATE_HEADER];\n const revalidateSeconds =\n revalidateHeader && !isNaN(Number(revalidateHeader))\n ? Number(revalidateHeader)\n : defaultRevalidateSeconds;\n\n const revalidateAt = revalidateSeconds > 0 ? now + revalidateSeconds * 1000 : null;\n\n // For revalidating entries: 30-day TTL matches runtime KVCacheHandler.set().\n // For non-revalidating entries: runtime uses no TTL (entries persist indefinitely),\n // but TPR uses a 24h fallback so pre-warmed entries don't accumulate forever.\n const kvTtl = revalidateSeconds > 0 ? MAX_KV_TTL_SECONDS : 24 * 3600;\n\n const entry = {\n value: {\n kind: \"APP_PAGE\" as const,\n html: result.html,\n headers: result.headers,\n status: result.status,\n },\n tags: [] as string[],\n lastModified: now,\n revalidateAt,\n };\n\n const cacheKey = ENTRY_PREFIX + isrCacheKey(\"app\", routePath, buildId) + \":html\";\n\n pairs.push({\n key: cacheKey,\n value: JSON.stringify(entry),\n expiration_ttl: kvTtl,\n });\n }\n\n return pairs;\n}\n\n/**\n * Upload pre-rendered pages to KV using the Cloudflare REST API.\n * Writes in the same KVCacheEntry format that KVCacheHandler reads\n * at runtime, so ISR serves these entries without any code changes.\n */\nasync function uploadToKV(\n entries: Map<string, PrerenderResult>,\n namespaceId: string,\n accountId: string,\n apiToken: string,\n defaultRevalidateSeconds: number,\n buildId?: string,\n): Promise<void> {\n const pairs = buildTprKVPairs(entries, buildId, defaultRevalidateSeconds);\n for (let i = 0; i < pairs.length; i += KV_BATCH_SIZE) {\n const batch = pairs.slice(i, i + KV_BATCH_SIZE);\n const response = await fetch(\n `https://api.cloudflare.com/client/v4/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,\n {\n method: \"PUT\",\n headers: {\n Authorization: `Bearer ${apiToken}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(batch),\n },\n );\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(\n `KV bulk upload failed (batch ${Math.floor(i / KV_BATCH_SIZE) + 1}): ${response.status} — ${text}`,\n );\n }\n }\n}\n\n// ─── Main Entry ──────────────────────────────────────────────────────────────\n\n/** Default revalidation TTL for pre-rendered pages (1 hour). */\nconst DEFAULT_REVALIDATE_SECONDS = 3600;\n\n/**\n * Run the TPR pipeline: query traffic, select routes, pre-render, upload.\n *\n * Designed to be called between the build step and wrangler deploy in\n * the `vinext deploy` pipeline. Gracefully skips (never errors) when\n * the prerequisites aren't met.\n */\nexport async function runTPR(options: TPROptions): Promise<TPRResult> {\n const startTime = Date.now();\n const { root, coverage, limit, window: windowHours } = options;\n\n const skip = (reason: string): TPRResult => ({\n totalPaths: 0,\n prerenderedCount: 0,\n coverageAchieved: 0,\n durationMs: Date.now() - startTime,\n skipped: reason,\n });\n\n // ── 1. Check for API token ────────────────────────────────────\n const apiToken = process.env.CLOUDFLARE_API_TOKEN;\n if (!apiToken) {\n return skip(\"no CLOUDFLARE_API_TOKEN set\");\n }\n\n // ── 2. Parse wrangler config ──────────────────────────────────\n const wranglerConfig = parseWranglerConfig(root);\n if (!wranglerConfig) {\n return skip(\"could not parse wrangler config\");\n }\n\n // ── 3. Check for custom domain ────────────────────────────────\n if (!wranglerConfig.customDomain) {\n return skip(\"no custom domain — zone analytics unavailable\");\n }\n\n // ── 4. Check for KV namespace ─────────────────────────────────\n if (!wranglerConfig.kvNamespaceId) {\n return skip(\"no VINEXT_CACHE KV namespace configured\");\n }\n\n // ── 5. Resolve account ID ─────────────────────────────────────\n const accountId = wranglerConfig.accountId ?? (await resolveAccountId(apiToken));\n if (!accountId) {\n return skip(\"could not resolve Cloudflare account ID\");\n }\n\n // ── 6. Resolve zone ID ────────────────────────────────────────\n console.log(` TPR: Analyzing traffic for ${wranglerConfig.customDomain} (last ${windowHours}h)`);\n\n const zoneId = await resolveZoneId(wranglerConfig.customDomain, apiToken);\n if (!zoneId) {\n return skip(`could not resolve zone for ${wranglerConfig.customDomain}`);\n }\n\n // ── 7. Query traffic data ─────────────────────────────────────\n let traffic: TrafficEntry[];\n try {\n traffic = await queryTraffic(zoneId, apiToken, windowHours);\n } catch (err) {\n return skip(`analytics query failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n if (traffic.length === 0) {\n return skip(\"no traffic data available (first deploy?)\");\n }\n\n // ── 8. Select routes by coverage ──────────────────────────────\n const selection = selectRoutes(traffic, coverage, limit);\n\n console.log(\n ` TPR: ${traffic.length.toLocaleString()} unique paths — ` +\n `${selection.routes.length} pages cover ${Math.round(selection.coveragePercent)}% of traffic`,\n );\n\n if (selection.routes.length === 0) {\n return {\n totalPaths: traffic.length,\n prerenderedCount: 0,\n coverageAchieved: 0,\n durationMs: Date.now() - startTime,\n skipped: \"no pre-renderable routes after filtering\",\n };\n }\n\n // ── 9. Pre-render selected routes ─────────────────────────────\n console.log(` TPR: Pre-rendering ${selection.routes.length} pages...`);\n\n const routePaths = selection.routes.map((r) => r.path);\n let rendered: Map<string, PrerenderResult>;\n try {\n rendered = await prerenderRoutes(routePaths, root, wranglerConfig.customDomain);\n } catch (err) {\n return skip(`pre-rendering failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n if (rendered.size === 0) {\n return {\n totalPaths: traffic.length,\n prerenderedCount: 0,\n coverageAchieved: selection.coveragePercent,\n durationMs: Date.now() - startTime,\n skipped: \"all pages failed to pre-render (request-dependent?)\",\n };\n }\n\n // ── 10. Upload to KV ──────────────────────────────────────────\n // Read buildId from the BUILD_ID file written by vinext:build-id plugin.\n let buildId: string;\n try {\n buildId = fs.readFileSync(path.join(root, \"dist\", \"server\", \"BUILD_ID\"), \"utf-8\").trim();\n } catch {\n // BUILD_ID is written by vinext:build-id during every production build.\n // If missing, the build output is likely corrupted or incomplete.\n // Proceeding without buildId would write keys that never match runtime.\n console.warn(\n \" TPR: Could not read BUILD_ID from dist/server/ — KV keys will not match runtime. Skipping KV upload.\",\n );\n return skip(\"BUILD_ID not found in dist/server/ — build output may be incomplete\");\n }\n\n try {\n await uploadToKV(\n rendered,\n wranglerConfig.kvNamespaceId,\n accountId,\n apiToken,\n DEFAULT_REVALIDATE_SECONDS,\n buildId,\n );\n } catch (err) {\n return skip(`KV upload failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const durationMs = Date.now() - startTime;\n console.log(\n ` TPR: Pre-rendered ${rendered.size} pages in ${(durationMs / 1000).toFixed(1)}s → KV cache`,\n );\n\n return {\n totalPaths: traffic.length,\n prerenderedCount: rendered.size,\n coverageAchieved: selection.coveragePercent,\n durationMs,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAgB,oBAAoB,MAAqC;CAEvE,KAAK,MAAM,YAAY,CAAC,kBAAkB,gBAAgB,EAAE;EAC1D,MAAM,WAAW,KAAK,KAAK,MAAM,SAAS;EAC1C,IAAI,GAAG,WAAW,SAAS,EAAE;GAC3B,MAAM,UAAU,GAAG,aAAa,UAAU,QAAQ;GAClD,IAAI;IAEF,OAAO,gBADM,KAAK,MAAM,kBAAkB,QAAQ,CACvB,CAAC;WACtB;IACN;;;;CAMN,MAAM,WAAW,KAAK,KAAK,MAAM,gBAAgB;CACjD,IAAI,GAAG,WAAW,SAAS,EAEzB,OAAO,gBADS,GAAG,aAAa,UAAU,QACZ,CAAC;CAGjC,OAAO;;;;;;AAOT,SAAS,kBAAkB,KAAqB;CAC9C,IAAI,SAAS;CACb,IAAI,WAAW;CACf,IAAI,eAAe;CACnB,IAAI,cAAc;CAClB,IAAI,aAAa;CAEjB,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI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,QAAQ;EACpB,kBAAkB,SAAS;EAC3B,kBAAkB,UAAU;EAC5B;EACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"config-matchers.js","names":[],"sources":["../../src/config/config-matchers.ts"],"sourcesContent":["/**\n * Config pattern matching and rule application utilities.\n *\n * Shared between the dev server (index.ts) and the production server\n * (prod-server.ts) so both apply next.config.js rules identically.\n */\n\nimport type {\n NextI18nConfig,\n NextRedirect,\n NextRewrite,\n NextHeader,\n HasCondition,\n} from \"./next-config.js\";\nimport {\n MIDDLEWARE_HEADER_PREFIX,\n VINEXT_MW_CTX_HEADER,\n VINEXT_PRERENDER_ROUTE_PARAMS_HEADER,\n VINEXT_PRERENDER_SECRET_HEADER,\n} from \"../server/headers.js\";\nimport { buildRequestHeadersFromMiddlewareResponse } from \"../server/middleware-request-headers.js\";\n\n/**\n * Cache for compiled regex patterns in matchConfigPattern.\n *\n * Redirect/rewrite patterns are static — they come from next.config.js and\n * never change at runtime. Without caching, every request that hits the regex\n * branch re-runs the full tokeniser walk + isSafeRegex + new RegExp() for\n * every rule in the array. On apps with many locale-prefixed rules (which all\n * contain `(` and therefore enter the regex branch) this dominated profiling\n * at ~2.4 seconds of CPU self-time.\n *\n * Value is `null` when safeRegExp rejected the pattern (ReDoS risk), so we\n * skip it on subsequent requests too without re-running the scanner.\n */\nconst _compiledPatternCache = new Map<string, { re: RegExp; paramNames: string[] } | null>();\n\n/**\n * Cache for compiled header source regexes in matchHeaders.\n *\n * Each NextHeader rule has a `source` that is run through escapeHeaderSource()\n * then safeRegExp() to produce a RegExp. Both are pure functions of the source\n * string and the result never changes. Without caching, every request\n * re-runs the full escapeHeaderSource tokeniser + isSafeRegex scan + new RegExp()\n * for every header rule.\n *\n * Value is `null` when safeRegExp rejected the pattern (ReDoS risk).\n */\nconst _compiledHeaderSourceCache = new Map<string, RegExp | null>();\n\n/**\n * Cache for compiled has/missing condition value regexes in checkSingleCondition.\n *\n * Each has/missing condition may carry a `value` string that is passed directly\n * to safeRegExp() for matching against header/cookie/query/host values. The\n * condition objects are static (from next.config.js) so the compiled RegExp\n * never changes. Without caching, safeRegExp() is called on every request for\n * every condition on every rule.\n *\n * Value is `null` when safeRegExp rejected the pattern, or `false` when the\n * value string was undefined (no regex needed — use exact string comparison).\n */\nconst _compiledConditionCache = new Map<string, RegExp | null>();\n\n/**\n * Cache for destination substitution regexes in substituteDestinationParams.\n *\n * The regex depends only on the set of param keys captured from the matched\n * source pattern. Caching by sorted key list avoids recompiling a new RegExp\n * for repeated redirect/rewrite calls that use the same param shape.\n */\nconst _compiledDestinationParamCache = new Map<string, RegExp>();\n\n/**\n * Generic helper for the regex compilation caches above.\n *\n * Each cache stores the compiled artifact (or `null` when safeRegExp rejected\n * the pattern) the first time a key is seen, and reuses it forever. The\n * `undefined` sentinel distinguishes \"not yet seen\" from \"seen and rejected\"\n * so we never re-run isSafeRegex on the same input.\n *\n * Keep the security path intact: `compile()` is responsible for calling\n * safeRegExp(); this helper only handles caching.\n */\nfunction getCachedRegex<K, V>(cache: Map<K, V | null>, key: K, compile: () => V | null): V | null {\n let value = cache.get(key);\n if (value === undefined) {\n value = compile();\n cache.set(key, value);\n }\n return value;\n}\n\n/**\n * Redirect index for O(1) locale-static rule lookup.\n *\n * Many Next.js apps generate 50-100 redirect rules of the form:\n * /:locale(en|es|fr|...)?/some-static-path → /some-destination\n *\n * The compiled regex for each is like:\n * ^/(en|es|fr|...)?/some-static-path$\n *\n * When no redirect matches (the common case for ordinary page loads),\n * matchRedirect previously ran exec() on every one of those regexes —\n * ~2ms per call, ~2992ms total self-time in profiles.\n *\n * The index splits rules into two buckets:\n *\n * localeStatic — rules whose source is exactly /:paramName(alt1|alt2|...)?/suffix\n * where `suffix` is a static path with no further params or regex groups.\n * These are indexed in a Map<suffix, entry[]> for O(1) lookup after a\n * single fast strip of the optional locale prefix.\n *\n * linear — all other rules. Matched with the original O(n) loop.\n *\n * The index is stored in a WeakMap keyed by the redirects array so it is\n * computed once per config load and GC'd when the array is no longer live.\n *\n * ## Ordering invariant\n *\n * Redirect rules must be evaluated in their original order (first match wins).\n * Each locale-static entry stores its `originalIndex` so that, when a\n * locale-static fast-path match is found, any linear rules that appear earlier\n * in the array are still checked first.\n */\n\n/**\n * Matches `/:param(alternation)?/static/suffix` — the locale-static pattern.\n *\n * The `?` after the capture group is itself optional so that both forms are\n * detected:\n * - `/:locale(en|fr)?/foo` (locale segment optional — user-written rules)\n * - `/:nextInternalLocale(en|fr)/foo` (locale segment mandatory — emitted\n * by `applyLocaleToRoutes` for the locale-capture variant)\n * Both forms benefit from O(1) suffix lookup; the optionality is recorded\n * on the entry so we know whether to try the no-locale-prefix bucket.\n */\nconst _LOCALE_STATIC_RE = /^\\/:[\\w-]+\\(([^)]+)\\)(\\??)\\/([a-zA-Z0-9_~.%@!$&'*+,;=:/-]+)$/;\n\ntype LocaleStaticEntry = {\n /** The param name extracted from the source (e.g. \"locale\"). */\n paramName: string;\n /** The compiled regex matching just the alternation, used at match time. */\n altRe: RegExp;\n /** Whether the locale segment is optional (the source had `?` after the group). */\n optional: boolean;\n /** The original redirect rule. */\n redirect: NextRedirect;\n /** Position of this rule in the original redirects array. */\n originalIndex: number;\n};\n\ntype RedirectIndex = {\n /** Fast-path map: strippedPath (e.g. \"/security\") → matching entries. */\n localeStatic: Map<string, LocaleStaticEntry[]>;\n /**\n * Linear fallback for rules that couldn't be indexed.\n * Each entry is [originalIndex, redirect].\n */\n linear: Array<[number, NextRedirect]>;\n};\n\nconst _redirectIndexCache = new WeakMap<NextRedirect[], RedirectIndex>();\n\n/**\n * Build (or retrieve from cache) the redirect index for a given redirects array.\n *\n * Called once per config load from matchRedirect. The WeakMap ensures the index\n * is recomputed if the config is reloaded (new array reference) and GC'd when\n * the array is collected.\n */\nfunction _getRedirectIndex(redirects: NextRedirect[]): RedirectIndex {\n let index = _redirectIndexCache.get(redirects);\n if (index !== undefined) return index;\n\n const localeStatic = new Map<string, LocaleStaticEntry[]>();\n const linear: Array<[number, NextRedirect]> = [];\n\n for (let i = 0; i < redirects.length; i++) {\n const redirect = redirects[i];\n const m = _LOCALE_STATIC_RE.exec(redirect.source);\n if (m) {\n const paramName = redirect.source.slice(2, redirect.source.indexOf(\"(\"));\n const alternation = m[1];\n const optional = m[2] === \"?\";\n const suffix = \"/\" + m[3]; // e.g. \"/security\"\n // Build a small regex to validate the captured locale value against the\n // alternation. Using anchored match to avoid partial matches.\n // The alternation comes from user config; run it through safeRegExp to\n // guard against ReDoS in pathological configs.\n const altRe = safeRegExp(\"^(?:\" + alternation + \")$\");\n if (!altRe) {\n // Unsafe alternation — fall back to linear scan for this rule.\n linear.push([i, redirect]);\n continue;\n }\n const entry: LocaleStaticEntry = {\n paramName,\n altRe,\n optional,\n redirect,\n originalIndex: i,\n };\n const bucket = localeStatic.get(suffix);\n if (bucket) {\n bucket.push(entry);\n } else {\n localeStatic.set(suffix, [entry]);\n }\n } else {\n linear.push([i, redirect]);\n }\n }\n\n index = { localeStatic, linear };\n _redirectIndexCache.set(redirects, index);\n return index;\n}\n\n/** Hop-by-hop headers that should not be forwarded through a proxy. */\nconst HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/**\n * Request hop-by-hop headers to strip before proxying with fetch().\n * Intentionally narrower than HOP_BY_HOP_HEADERS: external rewrite proxying\n * still forwards proxy auth credentials, while response sanitization strips\n * them before returning data to the client.\n */\nconst REQUEST_HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\nfunction stripHopByHopRequestHeaders(headers: Headers): void {\n const connectionTokens = (headers.get(\"connection\") || \"\")\n .split(\",\")\n .map((value) => value.trim().toLowerCase())\n .filter(Boolean);\n\n for (const header of REQUEST_HOP_BY_HOP_HEADERS) {\n headers.delete(header);\n }\n\n for (const token of connectionTokens) {\n headers.delete(token);\n }\n}\n\n/**\n * Detect regex patterns vulnerable to catastrophic backtracking (ReDoS).\n *\n * Uses a lightweight heuristic: scans the pattern string for nested quantifiers\n * (a quantifier applied to a group that itself contains a quantifier). This\n * catches the most common pathological patterns like `(a+)+`, `(.*)*`,\n * `([^/]+)+`, `(a|a+)+` without needing a full regex parser.\n *\n * Returns true if the pattern appears safe, false if it's potentially dangerous.\n */\nexport function isSafeRegex(pattern: string): boolean {\n // Track parenthesis nesting depth and whether we've seen a quantifier\n // at each depth level.\n const quantifierAtDepth: boolean[] = [];\n let depth = 0;\n let i = 0;\n\n while (i < pattern.length) {\n const ch = pattern[i];\n\n // Skip escaped characters\n if (ch === \"\\\\\") {\n i += 2;\n continue;\n }\n\n // Skip character classes [...] — quantifiers inside them are literal\n if (ch === \"[\") {\n i++;\n while (i < pattern.length && pattern[i] !== \"]\") {\n if (pattern[i] === \"\\\\\") i++; // skip escaped char in class\n i++;\n }\n i++; // skip closing ]\n continue;\n }\n\n if (ch === \"(\") {\n depth++;\n // Initialize: no quantifier seen yet at this new depth\n if (quantifierAtDepth.length <= depth) {\n quantifierAtDepth.push(false);\n } else {\n quantifierAtDepth[depth] = false;\n }\n i++;\n continue;\n }\n\n if (ch === \")\") {\n const hadQuantifier = depth > 0 && quantifierAtDepth[depth];\n if (depth > 0) depth--;\n\n // Look ahead for a quantifier on this group: +, *, {n,m}\n // Note: '?' after ')' means \"zero or one\" which does NOT cause catastrophic\n // backtracking — it only allows 2 paths (match/skip), not exponential.\n // Only unbounded repetition (+, *, {n,}) on a group with inner quantifiers is dangerous.\n const next = pattern[i + 1];\n if (next === \"+\" || next === \"*\" || next === \"{\") {\n if (hadQuantifier) {\n // Nested quantifier detected: quantifier on a group that contains a quantifier\n return false;\n }\n // Mark the enclosing depth as having a quantifier\n if (depth >= 0 && depth < quantifierAtDepth.length) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n // Detect quantifiers: +, *, ?, {n,m}\n // '?' is a quantifier (optional) unless it follows another quantifier (+, *, ?, })\n // in which case it's a non-greedy modifier.\n if (ch === \"+\" || ch === \"*\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i++;\n continue;\n }\n\n if (ch === \"?\") {\n // '?' after +, *, ?, or } is a non-greedy modifier, not a quantifier\n const prev = i > 0 ? pattern[i - 1] : \"\";\n if (prev !== \"+\" && prev !== \"*\" && prev !== \"?\" && prev !== \"}\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n if (ch === \"{\") {\n // Check if this is a quantifier {n}, {n,}, {n,m}\n let j = i + 1;\n while (j < pattern.length && /[\\d,]/.test(pattern[j])) j++;\n if (j < pattern.length && pattern[j] === \"}\" && j > i + 1) {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i = j + 1;\n continue;\n }\n }\n\n i++;\n }\n\n return true;\n}\n\n/**\n * Compile a regex pattern safely. Returns the compiled RegExp or null if the\n * pattern is invalid or vulnerable to ReDoS.\n *\n * Logs a warning when a pattern is rejected so developers can fix their config.\n */\nexport function safeRegExp(pattern: string, flags?: string): RegExp | null {\n if (!isSafeRegex(pattern)) {\n console.warn(\n `[vinext] Ignoring potentially unsafe regex pattern (ReDoS risk): ${pattern}\\n` +\n ` Patterns with nested quantifiers (e.g. (a+)+) can cause catastrophic backtracking.\\n` +\n ` Simplify the pattern to avoid nested repetition.`,\n );\n return null;\n }\n try {\n return new RegExp(pattern, flags);\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a Next.js header/rewrite/redirect source pattern into a regex string.\n *\n * Regex groups in the source (e.g. `(\\d+)`) are extracted first, the remaining\n * text is escaped/converted in a **single pass** (avoiding chained `.replace()`\n * which CodeQL flags as incomplete sanitization), then groups are restored.\n */\nexport function escapeHeaderSource(source: string): string {\n // Sentinel character for group placeholders. Uses a Unicode private-use-area\n // codepoint that will never appear in real source patterns.\n const S = \"\\uE000\";\n\n // Step 1: extract regex groups and replace with numbered placeholders.\n const groups: string[] = [];\n const withPlaceholders = source.replace(/\\(([^)]+)\\)/g, (_m, inner) => {\n groups.push(inner);\n return `${S}G${groups.length - 1}${S}`;\n });\n\n // Step 2: single-pass conversion of the placeholder-bearing string.\n // Match named params (:[\\w-]+), sentinel group placeholders, metacharacters, and literal text.\n // The regex uses non-overlapping alternatives to avoid backtracking:\n // :[\\w-]+ — named parameter (constraint sentinel is checked procedurally;\n // param names may contain hyphens, e.g. :auth-method)\n // sentinel group — standalone regex group placeholder\n // [.+?*] — single metachar to escape/convert\n // [^.+?*:\\uE000]+ — literal text (excludes all chars that start other alternatives)\n let result = \"\";\n const re = new RegExp(\n `${S}G(\\\\d+)${S}|:[\\\\w-]+|[.+?*]|[^.+?*:\\\\uE000]+`, // lgtm[js/redos] — alternatives are non-overlapping\n \"g\",\n );\n let m: RegExpExecArray | null;\n while ((m = re.exec(withPlaceholders)) !== null) {\n if (m[1] !== undefined) {\n // Standalone regex group — restore as-is\n result += `(${groups[Number(m[1])]})`;\n } else if (m[0].startsWith(\":\")) {\n // Named parameter — check if followed by a constraint group placeholder\n const afterParam = withPlaceholders.slice(re.lastIndex);\n const constraintMatch = afterParam.match(new RegExp(`^${S}G(\\\\d+)${S}`));\n if (constraintMatch) {\n // :param(constraint) — use the constraint as the capture group\n re.lastIndex += constraintMatch[0].length;\n result += `(${groups[Number(constraintMatch[1])]})`;\n } else {\n // Plain named parameter → match one segment\n result += \"[^/]+\";\n }\n } else {\n switch (m[0]) {\n case \".\":\n result += \"\\\\.\";\n break;\n case \"+\":\n result += \"\\\\+\";\n break;\n case \"?\":\n result += \"\\\\?\";\n break;\n case \"*\":\n result += \".*\";\n break;\n default:\n result += m[0];\n break;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Request context needed for evaluating has/missing conditions.\n * Callers extract the relevant parts from the incoming Request.\n */\nexport type RequestContext = {\n headers: Headers;\n cookies: Record<string, string>;\n query: URLSearchParams;\n host: string;\n};\n\n/**\n * basePath gating state passed alongside the pathname to every matcher.\n *\n * Rewrites/redirects/headers run with default `basePath: true` semantics in\n * Next.js: the rule only matches when the inbound request was under the\n * configured `basePath`. Rules with `basePath: false` opt out and match\n * the original (un-stripped) pathname regardless of prefix.\n *\n * When `basePath` is empty (not configured) every rule is treated as\n * basePath-defaulted: every request matches.\n *\n * @see .nextjs-ref/packages/next/src/lib/load-custom-routes.ts:198-220\n */\nexport type BasePathMatchState = {\n /** Configured `basePath` (without trailing slash) or \"\" when unset. */\n basePath: string;\n /**\n * True when the inbound request was originally under `basePath` (i.e.\n * the prod-server/handler stripped the prefix before the matcher runs).\n * Ignored when `basePath` is empty.\n */\n hadBasePath: boolean;\n};\n\nconst _BASEPATH_DEFAULT: BasePathMatchState = { basePath: \"\", hadBasePath: true };\n\n/**\n * Decide whether a rule should be evaluated at all given the current\n * basePath-gating state.\n *\n * Encodes the Next.js rules:\n * - basePath: false rule → only when the request was NOT under basePath\n * (i.e. it's the explicit opt-out path). When `basePath` itself is\n * empty, basePath: false rules are still allowed to match — there's\n * just no basePath to gate them.\n * - default rule (basePath !== false) → only when the request WAS under\n * basePath (or no basePath is configured).\n */\nfunction shouldEvaluateRule(ruleBasePath: false | undefined, state: BasePathMatchState): boolean {\n if (!state.basePath) return true;\n return ruleBasePath === false ? !state.hadBasePath : state.hadBasePath;\n}\n\n/**\n * Parse a Cookie header string into a key-value record.\n */\nexport function parseCookies(cookieHeader: string | null): Record<string, string> {\n if (!cookieHeader) return {};\n const cookies: Record<string, string> = {};\n for (const part of cookieHeader.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim();\n if (key) cookies[key] = value;\n }\n return cookies;\n}\n\n/**\n * Build a RequestContext from a Web Request object.\n */\nexport function requestContextFromRequest(request: Request): RequestContext {\n const url = new URL(request.url);\n return {\n headers: request.headers,\n cookies: parseCookies(request.headers.get(\"cookie\")),\n query: url.searchParams,\n host: normalizeHost(request.headers.get(\"host\"), url.hostname),\n };\n}\n\nexport function normalizeHost(hostHeader: string | null, fallbackHostname: string): string {\n const host = hostHeader ?? fallbackHostname;\n return host.split(\":\", 1)[0].toLowerCase();\n}\n\n/**\n * Unpack `x-middleware-request-*` headers from the collected middleware\n * response headers into the actual request, and strip all `x-middleware-*`\n * internal signals so they never reach clients.\n *\n * `middlewareHeaders` is mutated in-place (matching keys are deleted).\n * Returns a (possibly cloned) `Request` with the unpacked headers applied,\n * and a fresh `RequestContext` built from it — ready for post-middleware\n * config rule matching (beforeFiles, afterFiles, fallback).\n *\n * Works for both Node.js requests (mutable headers) and Workers requests\n * (immutable — cloned only when there are headers to apply).\n *\n * `x-middleware-request-*` values are always plain strings (they carry\n * individual header values), so the wider `string | string[]` type of\n * `middlewareHeaders` is safe to cast here.\n */\nexport function applyMiddlewareRequestHeaders(\n middlewareHeaders: Record<string, string | string[]>,\n request: Request,\n options: { preserveCredentialHeaders?: boolean } = {},\n): { request: Request; postMwReqCtx: RequestContext } {\n const nextHeaders = buildRequestHeadersFromMiddlewareResponse(\n request.headers,\n middlewareHeaders,\n options,\n );\n\n for (const key of Object.keys(middlewareHeaders)) {\n if (key.startsWith(MIDDLEWARE_HEADER_PREFIX)) {\n delete middlewareHeaders[key];\n }\n }\n\n if (nextHeaders) {\n // Headers may be immutable (Workers), so always clone via new Headers().\n request = new Request(request.url, {\n method: request.method,\n headers: nextHeaders,\n body: request.body,\n // @ts-expect-error — duplex needed for streaming request bodies\n duplex: request.body ? \"half\" : undefined,\n });\n }\n\n return { request, postMwReqCtx: requestContextFromRequest(request) };\n}\n\nfunction _emptyParams(): Record<string, string> {\n return Object.create(null) as Record<string, string>;\n}\n\nfunction _matchConditionValue(\n actualValue: string,\n expectedValue: string | undefined,\n): Record<string, string> | null {\n if (expectedValue === undefined) return _emptyParams();\n\n const re = _cachedConditionRegex(expectedValue);\n if (re) {\n const match = re.exec(actualValue);\n if (!match) return null;\n\n const params = _emptyParams();\n if (match.groups) {\n for (const [key, value] of Object.entries(match.groups)) {\n if (value !== undefined) params[key] = value;\n }\n }\n return params;\n }\n\n return actualValue === expectedValue ? _emptyParams() : null;\n}\n\n/**\n * Check a single has/missing condition against request context.\n * Returns captured params when the condition is satisfied, or null otherwise.\n */\nfunction matchSingleCondition(\n condition: HasCondition,\n ctx: RequestContext,\n): Record<string, string> | null {\n switch (condition.type) {\n case \"header\": {\n const headerValue = ctx.headers.get(condition.key);\n if (headerValue === null) return null;\n return _matchConditionValue(headerValue, condition.value);\n }\n case \"cookie\": {\n const cookieValue = ctx.cookies[condition.key];\n if (cookieValue === undefined) return null;\n return _matchConditionValue(cookieValue, condition.value);\n }\n case \"query\": {\n const queryValue = ctx.query.get(condition.key);\n if (queryValue === null) return null;\n return _matchConditionValue(queryValue, condition.value);\n }\n case \"host\": {\n if (condition.value !== undefined) return _matchConditionValue(ctx.host, condition.value);\n return ctx.host === condition.key ? _emptyParams() : null;\n }\n default:\n return null;\n }\n}\n\n/**\n * Return a cached RegExp for a has/missing condition value string, compiling\n * on first use. Returns null if safeRegExp rejected the pattern or if the\n * value is not a valid regex (fall back to exact string comparison).\n */\nfunction _cachedConditionRegex(value: string): RegExp | null {\n return getCachedRegex(_compiledConditionCache, value, () =>\n // Anchor the regex to match the full value, not a substring.\n // Matches Next.js: new RegExp(`^${hasItem.value}$`)\n // Without anchoring, has:[cookie:role=admin] would match \"not-admin\".\n safeRegExp(`^${value}$`),\n );\n}\n\n/**\n * Check all has/missing conditions for a config rule.\n * Returns true if the rule should be applied (all has conditions pass, all missing conditions pass).\n *\n * - has: every condition must match (the request must have it)\n * - missing: every condition must NOT match (the request must not have it)\n */\nfunction collectConditionParams(\n has: HasCondition[] | undefined,\n missing: HasCondition[] | undefined,\n ctx: RequestContext,\n): Record<string, string> | null {\n const params = _emptyParams();\n\n if (has) {\n for (const condition of has) {\n const conditionParams = matchSingleCondition(condition, ctx);\n if (!conditionParams) return null;\n Object.assign(params, conditionParams);\n }\n }\n\n if (missing) {\n for (const condition of missing) {\n if (matchSingleCondition(condition, ctx)) return null;\n }\n }\n\n return params;\n}\n\nexport function checkHasConditions(\n has: HasCondition[] | undefined,\n missing: HasCondition[] | undefined,\n ctx: RequestContext,\n): boolean {\n return collectConditionParams(has, missing, ctx) !== null;\n}\n\n/**\n * If the current position in `str` starts with a parenthesized group, consume\n * it and advance `re.lastIndex` past the closing `)`. Returns the group\n * contents or null if no group is present.\n */\nfunction extractConstraint(str: string, re: RegExp): string | null {\n if (str[re.lastIndex] !== \"(\") return null;\n const start = re.lastIndex + 1;\n let depth = 1;\n let i = start;\n while (i < str.length && depth > 0) {\n if (str[i] === \"(\") depth++;\n else if (str[i] === \")\") depth--;\n i++;\n }\n if (depth !== 0) return null;\n re.lastIndex = i;\n return str.slice(start, i - 1);\n}\n\n/**\n * Match a Next.js config pattern (from redirects/rewrites sources) against a pathname.\n * Returns matched params or null.\n *\n * Supports:\n * :param - matches a single path segment\n * :param* - matches zero or more segments (catch-all)\n * :param+ - matches one or more segments\n * (regex) - inline regex patterns in the source\n * :param(constraint) - named param with inline regex constraint\n */\n/**\n * Strip a single trailing slash from a pathname for config-source matching.\n *\n * Next.js conditionally appends `(/)?` to rewrite/redirect/header source\n * regexes when `trailingSlash: true` (see Next.js\n * `resolve-rewrites.ts` and `server-utils.ts:checkRewrite`). Rather than\n * threading the trailingSlash flag through every matcher, we unconditionally\n * strip a trailing slash from the incoming pathname. When `trailingSlash: false`\n * the request pipeline emits a normalizing redirect (step 3) before config\n * rewrites/redirects (step 6) ever run, so the pathname is already slash-free;\n * the unconditional strip is defense-in-depth for that ordering. When\n * `trailingSlash: true` it bridges the gap between the canonicalized request\n * path (`/rewrite-1/`) and source patterns written without a trailing slash\n * (`/rewrite-1`).\n *\n * The root path `\"/\"` is preserved as-is.\n */\nfunction stripTrailingSlashForConfigMatch(pathname: string): string {\n return pathname.length > 1 && pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n}\n\nexport function matchConfigPattern(\n pathname: string,\n pattern: string,\n): Record<string, string> | null {\n // See `stripTrailingSlashForConfigMatch` — the source pattern itself is left\n // unchanged because catch-all patterns (`:param*` / `:param+`) and the root\n // `/` already consume any trailing slash; stripping the pattern would change\n // those semantics.\n pathname = stripTrailingSlashForConfigMatch(pathname);\n\n // If the pattern contains regex groups like (\\d+) or (.*), use regex matching.\n // Also enter this branch when a catch-all parameter (:param* or :param+) is\n // followed by a literal suffix (e.g. \"/:path*.md\"). Without this, the suffix\n // pattern falls through to the simple segment matcher which incorrectly treats\n // the whole segment (\":path*.md\") as a named parameter and matches everything.\n // The last condition catches simple params with literal suffixes (e.g. \"/:slug.md\")\n // where the param name is followed by a dot — the simple matcher would treat\n // \"slug.md\" as the param name and match any single segment regardless of suffix.\n // Enter the full regex branch when:\n // - the pattern uses explicit regex groups or escapes,\n // - a catch-all (`:foo*` / `:foo+`) is followed by a literal suffix that\n // the simple catch-all branch cannot express,\n // - a named param is followed by a dot (the simple branch would treat\n // \"slug.md\" as the whole param name),\n // - the pattern has multiple named params and any of them is a catch-all\n // (e.g. `/:locale/files/:path*`). The simple catch-all branch only\n // handles trailing-catch-all-with-static-prefix; mixed cases need regex.\n const catchAllAnchor = /:[\\w-]+[*+]/.test(pattern);\n const namedParamCount = (pattern.match(/:[\\w-]+/g) || []).length;\n if (\n pattern.includes(\"(\") ||\n pattern.includes(\"\\\\\") ||\n /:[\\w-]+[*+][^/]/.test(pattern) ||\n /:[\\w-]+\\./.test(pattern) ||\n (catchAllAnchor && namedParamCount > 1)\n ) {\n try {\n // Look up the compiled regex in the module-level cache. Patterns come\n // from next.config.js and are static, so we only need to compile each\n // one once across the lifetime of the worker/server process.\n // null is stored for rejected patterns so we don't re-run isSafeRegex.\n const compiled = getCachedRegex(_compiledPatternCache, pattern, () => {\n // Cache miss — compile the pattern now and store the result.\n // Param names may contain hyphens (e.g. :auth-method, :sign-in).\n const paramNames: string[] = [];\n // Single-pass conversion with procedural suffix handling. The tokenizer\n // matches only simple, non-overlapping tokens; quantifier/constraint\n // suffixes after :param are consumed procedurally to avoid polynomial\n // backtracking in the regex engine.\n let regexStr = \"\";\n const tokenRe = /:([\\w-]+)|[.]|[^:.]+/g; // lgtm[js/redos] — alternatives are non-overlapping (`:` and `.` excluded from `[^:.]+`)\n let tok: RegExpExecArray | null;\n while ((tok = tokenRe.exec(pattern)) !== null) {\n if (tok[1] !== undefined) {\n const name = tok[1];\n const rest = pattern.slice(tokenRe.lastIndex);\n // Check for quantifier (* or +) with optional constraint\n if (rest.startsWith(\"*\") || rest.startsWith(\"+\")) {\n const quantifier = rest[0];\n tokenRe.lastIndex += 1;\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n if (constraint !== null) {\n regexStr += `(${constraint})`;\n } else {\n regexStr += quantifier === \"*\" ? \"(.*)\" : \"(.+)\";\n }\n } else {\n // Check for inline constraint without quantifier\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n regexStr += constraint !== null ? `(${constraint})` : \"([^/]+)\";\n }\n } else if (tok[0] === \".\") {\n regexStr += \"\\\\.\";\n } else {\n regexStr += tok[0];\n }\n }\n const re = safeRegExp(\"^\" + regexStr + \"$\");\n return re ? { re, paramNames } : null;\n });\n if (!compiled) return null;\n const match = compiled.re.exec(pathname);\n if (!match) return null;\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < compiled.paramNames.length; i++) {\n params[compiled.paramNames[i]] = match[i + 1] ?? \"\";\n }\n return params;\n } catch {\n // Fall through to segment-based matching\n }\n }\n\n // Check for catch-all patterns (:param* or :param+) without regex groups\n // Param names may contain hyphens (e.g. :sign-in*, :sign-up+).\n const catchAllMatch = pattern.match(/:([\\w-]+)(\\*|\\+)$/);\n if (catchAllMatch) {\n const prefix = pattern.slice(0, pattern.lastIndexOf(\":\"));\n const paramName = catchAllMatch[1];\n const isPlus = catchAllMatch[2] === \"+\";\n\n const prefixNoSlash = prefix.replace(/\\/$/, \"\");\n if (!pathname.startsWith(prefixNoSlash)) return null;\n const charAfter = pathname[prefixNoSlash.length];\n if (charAfter !== undefined && charAfter !== \"/\") return null;\n\n const rest = pathname.slice(prefixNoSlash.length);\n if (isPlus && (!rest || rest === \"/\")) return null;\n let restValue = rest.startsWith(\"/\") ? rest.slice(1) : rest;\n // NOTE: Do NOT decodeURIComponent here. The pathname is already decoded at\n // the request entry point. Decoding again would produce incorrect param values.\n return { [paramName]: restValue };\n }\n\n // Simple segment-based matching for exact patterns and :param\n const parts = pattern.split(\"/\");\n const pathParts = pathname.split(\"/\");\n\n if (parts.length !== pathParts.length) return null;\n\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < parts.length; i++) {\n if (parts[i].startsWith(\":\")) {\n params[parts[i].slice(1)] = pathParts[i];\n } else if (parts[i] !== pathParts[i]) {\n return null;\n }\n }\n return params;\n}\n\n/**\n * Apply redirect rules from next.config.js.\n * Returns the redirect info if a redirect was matched, or null.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating redirects, so this parameter is required.\n *\n * ## Performance\n *\n * Rules with a locale-capture-group prefix (the dominant pattern in large\n * Next.js apps — e.g. `/:locale(en|es|fr|...)?/some-path`) are handled via\n * a pre-built index. Instead of running exec() on each locale regex\n * individually, we:\n *\n * 1. Strip the optional locale prefix from the pathname with one cheap\n * string-slice check (no regex exec on the hot path).\n * 2. Look up the stripped suffix in a Map<suffix, entry[]>.\n * 3. For each matching entry, validate the captured locale string against\n * a small, anchored alternation regex.\n *\n * This reduces the per-request cost from O(n × regex) to O(1) map lookup +\n * O(matches × tiny-regex), eliminating the ~2992ms self-time reported in\n * profiles for apps with 63+ locale-prefixed rules.\n *\n * Rules that don't fit the locale-static pattern fall back to the original\n * linear matchConfigPattern scan.\n *\n * ## Ordering invariant\n *\n * First match wins, preserving the original redirect array order. When a\n * locale-static fast-path match is found at position N, all linear rules with\n * an original index < N are checked via matchConfigPattern first — they are\n * few in practice (typically zero) so this is not a hot-path concern.\n */\nexport function matchRedirect(\n pathname: string,\n redirects: NextRedirect[],\n ctx: RequestContext,\n basePathState: BasePathMatchState = _BASEPATH_DEFAULT,\n): { destination: string; permanent: boolean } | null {\n if (redirects.length === 0) return null;\n\n // Strip trailing slash so the locale-static fast path (Map.get on the\n // pathname) matches keys derived from slash-free source patterns. The\n // linear fallback also passes through `matchConfigPattern` which strips\n // again, but normalizing once here keeps both paths consistent.\n pathname = stripTrailingSlashForConfigMatch(pathname);\n\n const index = _getRedirectIndex(redirects);\n\n // --- Locate the best locale-static candidate ---\n //\n // We look for the locale-static entry with the LOWEST originalIndex that\n // matches this pathname (and passes has/missing conditions).\n //\n // Strategy: try both the full pathname (locale omitted, e.g. \"/security\")\n // and the pathname with the first segment stripped (locale present, e.g.\n // \"/en/security\" → suffix \"/security\", locale \"en\").\n //\n // We do NOT use a regex here — just a single indexOf('/') to locate the\n // second slash, which is O(n) on the path length but far cheaper than\n // running 63 compiled regexes.\n\n let localeMatch: { destination: string; permanent: boolean } | null = null;\n let localeMatchIndex = Infinity;\n\n if (index.localeStatic.size > 0) {\n // Case 1: no locale prefix — pathname IS the suffix.\n // Only valid for entries whose source had `?` after the alternation\n // (the locale segment was optional). Mandatory-locale entries — emitted\n // by `applyLocaleToRoutes` as `/:nextInternalLocale(en|fr)/foo` — must\n // not match here because they require the locale segment to be present.\n const noLocaleBucket = index.localeStatic.get(pathname);\n if (noLocaleBucket) {\n for (const entry of noLocaleBucket) {\n if (!entry.optional) continue; // mandatory-locale rule — skip\n if (entry.originalIndex >= localeMatchIndex) continue; // already have a better match\n const redirect = entry.redirect;\n if (!shouldEvaluateRule(redirect.basePath, basePathState)) continue;\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n // Locale was omitted (the `?` made it optional) — param value is \"\".\n const dest = substituteAndSanitizeDestination(redirect.destination, {\n [entry.paramName]: \"\",\n ...conditionParams,\n });\n localeMatch = { destination: dest, permanent: redirect.permanent };\n localeMatchIndex = entry.originalIndex;\n break; // bucket entries are in insertion order = original order\n }\n }\n\n // Case 2: locale prefix present — first path segment is the locale.\n // Find the second slash: pathname = \"/locale/rest/of/path\"\n // ^--- slashTwo\n const slashTwo = pathname.indexOf(\"/\", 1);\n if (slashTwo !== -1) {\n const suffix = pathname.slice(slashTwo); // e.g. \"/security\"\n const localePart = pathname.slice(1, slashTwo); // e.g. \"en\"\n const localeBucket = index.localeStatic.get(suffix);\n if (localeBucket) {\n for (const entry of localeBucket) {\n if (entry.originalIndex >= localeMatchIndex) continue;\n // Validate that `localePart` is one of the allowed alternation values.\n if (!entry.altRe.test(localePart)) continue;\n const redirect = entry.redirect;\n if (!shouldEvaluateRule(redirect.basePath, basePathState)) continue;\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n const dest = substituteAndSanitizeDestination(redirect.destination, {\n [entry.paramName]: localePart,\n ...conditionParams,\n });\n localeMatch = { destination: dest, permanent: redirect.permanent };\n localeMatchIndex = entry.originalIndex;\n break; // bucket entries are in insertion order = original order\n }\n }\n }\n }\n\n // --- Linear fallback: all non-locale-static rules ---\n //\n // We only need to check linear rules whose originalIndex < localeMatchIndex.\n // If localeMatchIndex is Infinity (no locale match), we check all of them.\n for (const [origIdx, redirect] of index.linear) {\n if (origIdx >= localeMatchIndex) {\n // This linear rule comes after the best locale-static match —\n // the locale-static match wins. Stop scanning.\n break;\n }\n if (!shouldEvaluateRule(redirect.basePath, basePathState)) continue;\n const params = matchConfigPattern(pathname, redirect.source);\n if (params) {\n const conditionParams =\n redirect.has || redirect.missing\n ? collectConditionParams(redirect.has, redirect.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n const dest = substituteAndSanitizeDestination(redirect.destination, {\n ...params,\n ...conditionParams,\n });\n return { destination: dest, permanent: redirect.permanent };\n }\n }\n\n // Return the locale-static match if found (no earlier linear rule matched).\n return localeMatch;\n}\n\n/**\n * Apply rewrite rules from next.config.js.\n * Returns the rewritten URL or null if no rewrite matched.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating rewrites, so this parameter is required.\n */\nexport function matchRewrite(\n pathname: string,\n rewrites: NextRewrite[],\n ctx: RequestContext,\n basePathState: BasePathMatchState = _BASEPATH_DEFAULT,\n): string | null {\n for (const rewrite of rewrites) {\n if (!shouldEvaluateRule(rewrite.basePath, basePathState)) continue;\n const params = matchConfigPattern(pathname, rewrite.source);\n if (params) {\n const conditionParams =\n rewrite.has || rewrite.missing\n ? collectConditionParams(rewrite.has, rewrite.missing, ctx)\n : _emptyParams();\n if (!conditionParams) continue;\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n return substituteAndSanitizeDestination(rewrite.destination, {\n ...params,\n ...conditionParams,\n });\n }\n }\n return null;\n}\n\n/**\n * Substitute all matched route params into a redirect/rewrite destination.\n *\n * Handles repeated params (e.g. `/api/:id/:id`) and catch-all suffix forms\n * (`:path*`, `:path+`) in a single pass. Unknown params are left intact.\n */\nfunction substituteDestinationParams(destination: string, params: Record<string, string>): string {\n const keys = Object.keys(params);\n if (keys.length === 0) return destination;\n\n // Match only the concrete param keys captured from the source pattern.\n // Sorting longest-first ensures hyphenated names like `auth-method`\n // win over shorter prefixes like `auth`. The negative lookahead keeps\n // alphanumeric/underscore suffixes attached, while allowing `-` to act\n // as a literal delimiter in destinations like `:year-:month`.\n const sortedKeys = [...keys].sort((a, b) => b.length - a.length);\n const cacheKey = sortedKeys.join(\"\\0\");\n let paramRe = _compiledDestinationParamCache.get(cacheKey);\n if (!paramRe) {\n const paramAlternation = sortedKeys\n .map((key) => key.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n .join(\"|\");\n paramRe = new RegExp(`:(${paramAlternation})([+*])?(?![A-Za-z0-9_])`, \"g\");\n _compiledDestinationParamCache.set(cacheKey, paramRe);\n }\n\n return destination.replace(paramRe, (_token, key: string) => params[key]);\n}\n\n/**\n * Substitute params into a redirect/rewrite destination and sanitize the\n * result. Used by every redirect/rewrite branch — the substitution can\n * introduce protocol-relative URLs (e.g. `//evil.com` from a decoded `%2F`\n * in a catch-all param), which sanitizeDestination collapses.\n */\nfunction substituteAndSanitizeDestination(\n destination: string,\n params: Record<string, string>,\n): string {\n return sanitizeDestination(substituteDestinationParams(destination, params));\n}\n\n/**\n * Sanitize a redirect/rewrite destination to collapse protocol-relative URLs.\n *\n * After parameter substitution, a destination like `/:path*` can become\n * `//evil.com` if the catch-all captured a decoded `%2F` (`/evil.com`).\n * Browsers interpret `//evil.com` as a protocol-relative URL, redirecting\n * users off-site.\n *\n * This function collapses any leading double (or more) slashes to a single\n * slash for non-external (relative) destinations.\n */\nexport function sanitizeDestination(dest: string): string {\n // External URLs (http://, https://) are intentional — don't touch them\n if (dest.startsWith(\"http://\") || dest.startsWith(\"https://\")) {\n return dest;\n }\n // Normalize leading backslashes to forward slashes. Browsers interpret\n // backslash as forward slash in URL contexts, so \"\\/evil.com\" becomes\n // \"//evil.com\" (protocol-relative redirect). Replace any mix of leading\n // slashes and backslashes with a single forward slash.\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n return dest;\n}\n\n/**\n * Check if a URL is external (absolute URL or protocol-relative).\n * Detects any URL scheme (http:, https:, data:, javascript:, blob:, etc.)\n * per RFC 3986, plus protocol-relative URLs (//).\n */\nexport function isExternalUrl(url: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith(\"//\");\n}\n\n/**\n * Proxy an incoming request to an external URL and return the upstream response.\n *\n * Used for external rewrites (e.g. `/ph/:path*` → `https://us.i.posthog.com/:path*`).\n * Next.js handles these as server-side reverse proxies, forwarding the request\n * method, headers, and body to the external destination.\n *\n * Works in all runtimes (Node.js, Cloudflare Workers) via the standard fetch() API.\n */\nexport async function proxyExternalRequest(\n request: Request,\n externalUrl: string,\n): Promise<Response> {\n // Build the full external URL, preserving query parameters from the original request\n const originalUrl = new URL(request.url);\n const targetUrl = new URL(externalUrl);\n const destinationKeys = new Set(targetUrl.searchParams.keys());\n\n // If the rewrite destination already has query params, merge them.\n // Destination params take precedence — original request params are only added\n // when the destination doesn't already specify that key.\n for (const [key, value] of originalUrl.searchParams) {\n if (!destinationKeys.has(key)) {\n targetUrl.searchParams.append(key, value);\n }\n }\n\n // Forward the request with appropriate headers\n const headers = new Headers(request.headers);\n // Set Host to the external target (required for correct routing)\n headers.set(\"host\", targetUrl.host);\n // Remove headers that should not be forwarded to external services.\n // fetch() handles framing independently, so hop-by-hop transport headers\n // from the client must not be forwarded upstream. In particular,\n // transfer-encoding could cause request boundary disagreement between the\n // proxy and backend (defense-in-depth against request smuggling,\n // ref: CVE GHSA-ggv3-7p47-pfv8).\n stripHopByHopRequestHeaders(headers);\n const keysToDelete: string[] = [];\n for (const key of headers.keys()) {\n if (key.startsWith(MIDDLEWARE_HEADER_PREFIX)) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n headers.delete(key);\n }\n // Internal prerender authentication header must never be forwarded to\n // external rewrite destinations. It authorizes hidden production endpoints\n // used only by vinext's own prerender pipeline.\n headers.delete(VINEXT_PRERENDER_SECRET_HEADER);\n headers.delete(VINEXT_PRERENDER_ROUTE_PARAMS_HEADER);\n // Internal App Router dev middleware context must never leave the dev server.\n headers.delete(VINEXT_MW_CTX_HEADER);\n\n const method = request.method;\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n const init: RequestInit & { duplex?: string } = {\n method,\n headers,\n redirect: \"manual\", // Don't follow redirects — pass them through to the client\n };\n\n if (hasBody && request.body) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n\n // Enforce a timeout so slow/unresponsive upstreams don't hold connections\n // open indefinitely (DoS amplification risk on Node.js dev/prod servers).\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 30_000);\n let upstreamResponse: Response;\n try {\n upstreamResponse = await fetch(targetUrl.href, { ...init, signal: controller.signal });\n } catch (e) {\n if (e instanceof Error && e.name === \"AbortError\") {\n console.error(\"[vinext] External rewrite proxy timeout:\", targetUrl.href);\n return new Response(\"Gateway Timeout\", { status: 504 });\n }\n console.error(\"[vinext] External rewrite proxy error:\", e);\n return new Response(\"Bad Gateway\", { status: 502 });\n } finally {\n clearTimeout(timeout);\n }\n\n // Build the response to return to the client.\n // Copy all upstream headers except hop-by-hop headers.\n // Node.js fetch() auto-decompresses responses (gzip, br, etc.), so the body\n // we receive is already plain text. Forwarding the original content-encoding\n // and content-length headers causes the browser to attempt a second\n // decompression on the already-decoded body, resulting in\n // ERR_CONTENT_DECODING_FAILED. Strip both headers on Node.js only.\n // On Workers, fetch() preserves wire encoding, so the headers stay accurate.\n const isNodeRuntime = typeof process !== \"undefined\" && !!process.versions?.node;\n const responseHeaders = new Headers();\n upstreamResponse.headers.forEach((value, key) => {\n const lower = key.toLowerCase();\n if (HOP_BY_HOP_HEADERS.has(lower)) return;\n if (isNodeRuntime && (lower === \"content-encoding\" || lower === \"content-length\")) return;\n responseHeaders.append(key, value);\n });\n\n return new Response(upstreamResponse.body, {\n status: upstreamResponse.status,\n statusText: upstreamResponse.statusText,\n headers: responseHeaders,\n });\n}\n\n/**\n * Apply custom header rules from next.config.js.\n * Returns an array of { key, value } pairs to set on the response.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating headers, so this parameter is required.\n */\nexport function matchHeaders(\n pathname: string,\n headers: NextHeader[],\n ctx: RequestContext,\n basePathState: BasePathMatchState = _BASEPATH_DEFAULT,\n): Array<{ key: string; value: string }> {\n // Header source regexes are compiled without a trailing-slash tolerance,\n // so the incoming pathname must be normalized the same way config rewrites\n // and redirects are. See `stripTrailingSlashForConfigMatch`.\n pathname = stripTrailingSlashForConfigMatch(pathname);\n\n const result: Array<{ key: string; value: string }> = [];\n for (const rule of headers) {\n if (!shouldEvaluateRule(rule.basePath, basePathState)) continue;\n // Cache the compiled source regex — escapeHeaderSource() + safeRegExp() are\n // pure functions of rule.source and the result never changes between requests.\n const sourceRegex = getCachedRegex(_compiledHeaderSourceCache, rule.source, () =>\n safeRegExp(\"^\" + escapeHeaderSource(rule.source) + \"$\"),\n );\n if (sourceRegex && sourceRegex.test(pathname)) {\n if (rule.has || rule.missing) {\n if (!checkHasConditions(rule.has, rule.missing, ctx)) {\n continue;\n }\n }\n result.push(...rule.headers);\n }\n }\n return result;\n}\n\n/**\n * Escape a string for inclusion in a regex character class / alternation.\n * Mirrors `escape-string-regexp` semantics used by Next.js's processRoutes.\n */\nfunction _escapeRegexString(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\n/**\n * Apply Next.js i18n locale-prefix transformation to a set of redirect or\n * rewrite rules. Mirrors the relevant slice of Next.js's `processRoutes`\n * (load-custom-routes.ts) with one deliberate divergence noted below.\n *\n * For each rule:\n * - If `locale === false` or no i18n is configured, the rule is emitted\n * untouched. This is the core of issue #1336 item 1: with `locale: false`\n * the user-supplied source is matched against the raw locale-prefixed\n * URL so a `:locale` segment in the source captures the prefix itself.\n * - Otherwise an internal locale-capture variant is produced whose source\n * starts with `/:nextInternalLocale(en|sv|nl)` so that locale-prefixed\n * URLs match. For redirects only, a second variant prefixed with\n * `/${defaultLocale}` is also emitted, matching Next.js exactly.\n * - **Vinext divergence**: we ALSO retain the original (unprefixed) source\n * so that requests for the default locale that arrive without a prefix\n * still match. Next.js solves this upstream by path-normalising every\n * incoming default-locale request to include the prefix\n * (`resolve-routes.ts` lines ~251-263); vinext currently does that\n * normalisation only inside the pages-server-entry route matcher, so\n * the rewrite/redirect matcher would otherwise miss unprefixed paths.\n * Keeping the unprefixed variant gives functionally identical behaviour\n * without requiring a server-wide path normalisation pass. The original\n * source is appended LAST so the locale-aware variants win when both\n * forms could match.\n *\n * Destinations that are local (start with `/`) are similarly rewritten with\n * `/:nextInternalLocale` for the locale-capture variant so the locale\n * survives the rewrite/redirect target.\n *\n * Mirrors the Next.js reference in\n * packages/next/src/lib/load-custom-routes.ts — see `processRoutes`.\n */\nexport function applyLocaleToRoutes<T extends NextRedirect | NextRewrite>(\n routes: T[],\n i18n: NextI18nConfig | null | undefined,\n type: \"redirect\" | \"rewrite\",\n options: { trailingSlash?: boolean } = {},\n): T[] {\n if (!i18n || routes.length === 0) return routes;\n\n const trailingSlash = options.trailingSlash ?? false;\n const localesAlternation = i18n.locales.map(_escapeRegexString).join(\"|\");\n const internalLocale = `/:nextInternalLocale(${localesAlternation})`;\n\n // Mirrors Next.js: the root source `\"/\"` is collapsed to `\"\"` only when\n // `trailingSlash` is unset. With `trailingSlash: true` the source is\n // preserved so the emitted variant is `/:nextInternalLocale(en|fr)/`\n // rather than `/:nextInternalLocale(en|fr)`.\n const suffixFor = (source: string): string => (source === \"/\" && !trailingSlash ? \"\" : source);\n\n // For redirects, Next.js emits a per-default-locale literal variant\n // (so that `/${defaultLocale}/old` redirects to the unprefixed destination\n // and the default locale is implicitly stripped). For rewrites Next.js\n // emits only the `:nextInternalLocale` form. We mirror that distinction.\n //\n // The list is a single-element array today; domain-locale support (which\n // Next.js wires up alongside `i18n.domains`) will append each domain's\n // `defaultLocale` here once vinext mirrors that branch — tracked as part\n // of #1336's follow-ups.\n const defaultLocales: string[] = type === \"redirect\" ? [i18n.defaultLocale] : [];\n\n const out: T[] = [];\n for (const r of routes) {\n if (r.locale === false) {\n out.push(r);\n continue;\n }\n\n // Destinations may be absolute URLs (external) — Next.js skips the\n // locale-prefix injection on external destinations.\n const isExternal = !!r.destination && !r.destination.startsWith(\"/\");\n\n // For each default locale, emit a literal `/${locale}/...` variant\n // whose destination does NOT carry a locale prefix (Next.js parity).\n if (!isExternal) {\n for (const locale of defaultLocales) {\n const localizedSource = `/${locale}${suffixFor(r.source)}`;\n out.push({\n ...r,\n source: localizedSource,\n });\n }\n }\n\n // Emit the `:nextInternalLocale` variant that matches all locales.\n const internalSource = `${internalLocale}${suffixFor(r.source)}`;\n let internalDestination = r.destination;\n if (internalDestination && internalDestination.startsWith(\"/\") && !isExternal) {\n internalDestination = `/:nextInternalLocale${\n internalDestination === \"/\" && !trailingSlash ? \"\" : internalDestination\n }`;\n }\n out.push({\n ...r,\n source: internalSource,\n destination: internalDestination,\n });\n\n // Retain the original unprefixed source as a fallback so default-locale\n // requests that arrive without a prefix (e.g. `/old`) still match.\n // See the docblock above for why this differs from upstream Next.js.\n out.push(r);\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmCA,MAAM,wCAAwB,IAAI,KAA0D;;;;;;;;;;;;AAa5F,MAAM,6CAA6B,IAAI,KAA4B;;;;;;;;;;;;;AAcnE,MAAM,0CAA0B,IAAI,KAA4B;;;;;;;;AAShE,MAAM,iDAAiC,IAAI,KAAqB;;;;;;;;;;;;AAahE,SAAS,eAAqB,OAAyB,KAAQ,SAAmC;CAChG,IAAI,QAAQ,MAAM,IAAI,IAAI;CAC1B,IAAI,UAAU,KAAA,GAAW;EACvB,QAAQ,SAAS;EACjB,MAAM,IAAI,KAAK,MAAM;;CAEvB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CT,MAAM,oBAAoB;AAyB1B,MAAM,sCAAsB,IAAI,SAAwC;;;;;;;;AASxE,SAAS,kBAAkB,WAA0C;CACnE,IAAI,QAAQ,oBAAoB,IAAI,UAAU;CAC9C,IAAI,UAAU,KAAA,GAAW,OAAO;CAEhC,MAAM,+BAAe,IAAI,KAAkC;CAC3D,MAAM,SAAwC,EAAE;CAEhD,KAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;EACzC,MAAM,WAAW,UAAU;EAC3B,MAAM,IAAI,kBAAkB,KAAK,SAAS,OAAO;EACjD,IAAI,GAAG;GACL,MAAM,YAAY,SAAS,OAAO,MAAM,GAAG,SAAS,OAAO,QAAQ,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AKF,MAAM,aAAa,CAAC,CAAC,EAAE,eAAe,CAAC,EAAE,YAAY,WAAW,IAAI;EAIpE,IAAI,CAAC,YACH,KAAK,MAAM,UAAU,gBAAgB;GACnC,MAAM,kBAAkB,IAAI,SAAS,UAAU,EAAE,OAAO;GACxD,IAAI,KAAK;IACP,GAAG;IACH,QAAQ;IACT,CAAC;;EAKN,MAAM,iBAAiB,GAAG,iBAAiB,UAAU,EAAE,OAAO;EAC9D,IAAI,sBAAsB,EAAE;EAC5B,IAAI,uBAAuB,oBAAoB,WAAW,IAAI,IAAI,CAAC,YACjE,sBAAsB,uBACpB,wBAAwB,OAAO,CAAC,gBAAgB,KAAK;EAGzD,IAAI,KAAK;GACP,GAAG;GACH,QAAQ;GACR,aAAa;GACd,CAAC;EAKF,IAAI,KAAK,EAAE;;CAEb,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"dotenv.js","names":[],"sources":["../../src/config/dotenv.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { parseEnv } from \"node:util\";\n\ntype VinextEnvMode = \"development\" | \"production\" | \"test\";\n\n/**\n * Environment-variable bag accepted by {@link loadDotenv}.\n *\n * Intentionally a plain string→string|undefined dictionary rather than\n * `NodeJS.ProcessEnv`. `NodeJS.ProcessEnv` is augmented by `@types/node` (and\n * by Next.js, when it's anywhere in the workspace) to make `NODE_ENV` a\n * required, readonly property, which doesn't reflect Node's real runtime\n * behaviour and breaks tests that pass throwaway dictionaries here.\n */\ntype EnvBag = Record<string, string | undefined>;\n\ntype LoadDotenvOptions = {\n root: string;\n mode: VinextEnvMode;\n processEnv?: EnvBag;\n};\n\ntype LoadDotenvResult = {\n mode: VinextEnvMode;\n loadedFiles: string[];\n loadedEnv: Record<string, string>;\n};\n\n/**\n * Next.js-compatible dotenv lookup order (highest priority first).\n */\nexport function getDotenvFiles(mode: VinextEnvMode): string[] {\n return [`.env.${mode}.local`, ...(mode === \"test\" ? [] : [\".env.local\"]), `.env.${mode}`, \".env\"];\n}\n\n/**\n * Load .env files into processEnv with Next.js-like precedence:\n * process.env > .env.<mode>.local > .env.local > .env.<mode> > .env.\n *\n * This mutates processEnv (defaults to process.env).\n *\n * ## Interaction with Vite's own .env loading\n *\n * Vite also loads .env files internally during createServer()/build(). That's\n * fine — the two systems serve different purposes and don't conflict:\n *\n * - **vinext** populates `process.env` so that server-side code (SSR, API\n * routes, Server Components) can read env vars at runtime, and so the Vite\n * plugin's `config()` hook can scan `process.env` for `NEXT_PUBLIC_*` vars\n * to inline via `define`.\n *\n * - **Vite** loads .env files to populate `import.meta.env.VITE_*` for its\n * own client exposure mechanism (which Next.js apps don't use).\n *\n * Because we load first and neither system overwrites existing keys, Vite's\n * pass is effectively a no-op for overlapping keys. For `start` and `deploy`\n * commands (which don't go through Vite at all), this is the only loading.\n */\nexport function loadDotenv({\n root,\n mode,\n processEnv = process.env,\n}: LoadDotenvOptions): LoadDotenvResult {\n const loadedFiles: string[] = [];\n const loadedEnv: Record<string, string> = {};\n\n for (const relativeFile of getDotenvFiles(mode)) {\n const filePath = path.join(root, relativeFile);\n if (!fs.existsSync(filePath)) continue;\n\n const fileContent = fs.readFileSync(filePath, \"utf-8\");\n const parsed = parseEnv(fileContent) as Record<string, string>;\n const expanded = expandEnv(parsed, processEnv);\n\n for (const [key, value] of Object.entries(expanded)) {\n if (processEnv[key] !== undefined) continue;\n processEnv[key] = value;\n loadedEnv[key] = value;\n }\n\n loadedFiles.push(relativeFile);\n }\n\n return {\n mode,\n loadedFiles,\n loadedEnv,\n };\n}\n\nconst ENV_REF_RE = /(\\\\)?\\$(?:\\{([A-Za-z_][A-Za-z0-9_]*)\\}|([A-Za-z_][A-Za-z0-9_]*))/g;\n\nfunction expandEnv(parsed: Record<string, string>, processEnv: EnvBag): Record<string, string> {\n const expanded: Record<string, string> = {};\n const resolving = new Set<string>();\n const context: Record<string, string | undefined> = {\n ...parsed,\n ...processEnv,\n };\n\n function resolveValue(key: string): string {\n const cached = expanded[key];\n if (cached !== undefined) return cached;\n\n if (resolving.has(key)) {\n return context[key] ?? \"\";\n }\n\n const raw = context[key];\n if (raw === undefined) return \"\";\n\n resolving.add(key);\n let value = raw.replace(ENV_REF_RE, (match, escaped, braced, bare) => {\n if (escaped) return match.slice(1);\n\n const refKey = (braced || bare) as string;\n return resolveValue(refKey);\n });\n // Strip remaining \\$ escapes not caught by the regex (e.g. \\$100 where\n // what follows $ isn't a valid variable name).\n value = value.replace(/\\\\\\$/g, \"$\");\n resolving.delete(key);\n\n expanded[key] = value;\n context[key] = value;\n return value;\n }\n\n for (const key of Object.keys(parsed)) {\n resolveValue(key);\n }\n\n return expanded;\n}\n"],"mappings":";;;;;;;AAgCA,SAAgB,eAAe,MAA+B;CAC5D,OAAO;EAAC,QAAQ,KAAK;EAAS,GAAI,SAAS,SAAS,EAAE,GAAG,CAAC,aAAa;EAAG,QAAQ;EAAQ;EAAO;;;;;;;;;;;;;;;;;;;;;;;;;AA0BnG,SAAgB,WAAW,EACzB,MACA,MACA,aAAa,QAAQ,OACiB;CACtC,MAAM,cAAwB,EAAE;CAChC,MAAM,YAAoC,EAAE;CAE5C,KAAK,MAAM,gBAAgB,eAAe,KAAK,EAAE;EAC/C,MAAM,WAAW,KAAK,KAAK,MAAM,aAAa;EAC9C,IAAI,CAAC,GAAG,WAAW,SAAS,EAAE;EAI9B,MAAM,WAAW,UADF,SADK,GAAG,aAAa,UAAU,QACX,CACF,EAAE,WAAW;EAE9C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,EAAE;GACnD,IAAI,WAAW,SAAS,KAAA,GAAW;GACnC,WAAW,OAAO;GAClB,UAAU,OAAO;;EAGnB,YAAY,KAAK,aAAa;;CAGhC,OAAO;EACL;EACA;EACA;EACD;;AAGH,MAAM,aAAa;AAEnB,SAAS,UAAU,QAAgC,YAA4C;CAC7F,MAAM,WAAmC,EAAE;CAC3C,MAAM,4BAAY,IAAI,KAAa;CACnC,MAAM,UAA8C;EAClD,GAAG;EACH,GAAG;EACJ;CAED,SAAS,aAAa,KAAqB;EACzC,MAAM,SAAS,SAAS;EACxB,IAAI,WAAW,KAAA,GAAW,OAAO;EAEjC,IAAI,UAAU,IAAI,IAAI,EACpB,OAAO,QAAQ,QAAQ;EAGzB,MAAM,MAAM,QAAQ;EACpB,IAAI,QAAQ,KAAA,GAAW,OAAO;EAE9B,UAAU,IAAI,IAAI;EAClB,IAAI,QAAQ,IAAI,QAAQ,aAAa,OAAO,SAAS,QAAQ,SAAS;GACpE,IAAI,SAAS,OAAO,MAAM,MAAM,EAAE;GAGlC,OAAO,aADS,UAAU,KACC;IAC3B;EAGF,QAAQ,MAAM,QAAQ,SAAS,IAAI;EACnC,UAAU,OAAO,IAAI;EAErB,SAAS,OAAO;EAChB,QAAQ,OAAO;EACf,OAAO;;CAGT,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,EACnC,aAAa,IAAI;CAGnB,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"next-config.js","names":[],"sources":["../../src/config/next-config.ts"],"sourcesContent":["/**\n * next.config.js / next.config.mjs / next.config.ts parser\n *\n * Loads the Next.js config file (if present) and extracts supported options.\n * Unsupported options are logged as warnings.\n */\nimport path from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport fs from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { randomUUID } from \"node:crypto\";\nimport commonjs from \"vite-plugin-commonjs\";\nimport { PHASE_DEVELOPMENT_SERVER } from \"vinext/shims/constants\";\nimport { normalizePageExtensions } from \"../routing/file-matcher.js\";\nimport { getHtmlLimitedBotRegex } from \"../utils/html-limited-bots.js\";\nimport { isUnknownRecord } from \"../utils/record.js\";\nimport { applyLocaleToRoutes, isExternalUrl } from \"./config-matchers.js\";\nimport { loadTsconfigPathAliasesForRoot } from \"./tsconfig-paths.js\";\n\n/**\n * Parse a body size limit value (string or number) into bytes.\n * Accepts Next.js-style strings like \"1mb\", \"500kb\", \"10mb\", bare number strings like \"1048576\" (bytes),\n * and numeric values. Supports b, kb, mb, gb, tb, pb units.\n * Returns the default 1MB if the value is not provided or invalid.\n * Throws if the parsed value is less than 1.\n */\nexport function parseBodySizeLimit(value: string | number | undefined | null): number {\n if (value === undefined || value === null) return 1 * 1024 * 1024;\n if (typeof value === \"number\") {\n if (value < 1) throw new Error(`Body size limit must be a positive number, got ${value}`);\n return value;\n }\n const trimmed = value.trim();\n const match = trimmed.match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|tb|pb)?$/i);\n if (!match) {\n console.warn(\n `[vinext] Invalid bodySizeLimit value: \"${value}\". Expected a number or a string like \"1mb\", \"500kb\". Falling back to 1MB.`,\n );\n return 1 * 1024 * 1024;\n }\n const num = parseFloat(match[1]);\n const unit = (match[2] ?? \"b\").toLowerCase();\n let bytes: number;\n switch (unit) {\n case \"b\":\n bytes = Math.floor(num);\n break;\n case \"kb\":\n bytes = Math.floor(num * 1024);\n break;\n case \"mb\":\n bytes = Math.floor(num * 1024 * 1024);\n break;\n case \"gb\":\n bytes = Math.floor(num * 1024 * 1024 * 1024);\n break;\n case \"tb\":\n bytes = Math.floor(num * 1024 * 1024 * 1024 * 1024);\n break;\n case \"pb\":\n bytes = Math.floor(num * 1024 * 1024 * 1024 * 1024 * 1024);\n break;\n default:\n return 1 * 1024 * 1024;\n }\n if (bytes < 1) throw new Error(`Body size limit must be a positive number, got ${bytes}`);\n return bytes;\n}\n\nexport type HasCondition = {\n type: \"header\" | \"cookie\" | \"query\" | \"host\";\n key: string;\n value?: string;\n};\n\nexport type NextRedirect = {\n source: string;\n destination: string;\n permanent: boolean;\n has?: HasCondition[];\n missing?: HasCondition[];\n /**\n * When true (the default with i18n configured), Next.js prepends an internal\n * locale alternation to the source so the rule matches locale-prefixed paths.\n * When `false`, the source is left untouched and matches the raw path,\n * letting user-supplied `:locale` segments capture the prefix themselves.\n * See https://nextjs.org/docs/app/api-reference/config/next-config-js/redirects#locale\n */\n locale?: false;\n /**\n * When `false`, the rule is NOT prefixed with `basePath`. Source and\n * destination are matched/applied verbatim. Mirrors Next.js's\n * `Redirect.basePath: false` opt-out — see\n * `.nextjs-ref/packages/next/src/lib/load-custom-routes.ts:26`.\n */\n basePath?: false;\n};\n\nexport type NextRewrite = {\n source: string;\n destination: string;\n has?: HasCondition[];\n missing?: HasCondition[];\n /** See {@link NextRedirect.locale}. */\n locale?: false;\n /** See {@link NextRedirect.basePath}. */\n basePath?: false;\n};\n\nexport type NextHeader = {\n source: string;\n has?: HasCondition[];\n missing?: HasCondition[];\n headers: Array<{ key: string; value: string }>;\n /** See {@link NextRedirect.basePath}. */\n basePath?: false;\n};\n\nexport type NextI18nConfig = {\n /** List of supported locales */\n locales: string[];\n /** The default locale (used when no locale prefix is in the URL) */\n defaultLocale: string;\n /**\n * Whether to auto-detect locale from Accept-Language header.\n * Defaults to true in Next.js.\n */\n localeDetection?: boolean;\n /**\n * Domain-based routing. Each domain maps to a specific locale.\n */\n domains?: Array<{\n domain: string;\n defaultLocale: string;\n locales?: string[];\n http?: boolean;\n }>;\n};\n\n/**\n * MDX compilation options extracted from @next/mdx config.\n * These are passed through to @mdx-js/rollup so that custom\n * remark/rehype/recma plugins configured in next.config work with Vite.\n */\nexport type MdxOptions = {\n remarkPlugins?: unknown[];\n rehypePlugins?: unknown[];\n recmaPlugins?: unknown[];\n};\n\nexport type NextConfig = {\n /** Additional env variables */\n env?: Record<string, string>;\n /** Base URL path prefix */\n basePath?: string;\n /**\n * Prefix applied to every emitted JS/CSS/image/static asset URL.\n * Accepts a path prefix (e.g. `/custom-asset-prefix`) or an absolute\n * URL (e.g. `https://cdn.example.com`). Distinct from `basePath`:\n * `basePath` affects route URLs; `assetPrefix` only affects asset URLs.\n * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix\n */\n assetPrefix?: string;\n /** Whether to add trailing slashes */\n trailingSlash?: boolean;\n /** Internationalization routing config */\n i18n?: NextI18nConfig;\n /** URL redirect rules */\n redirects?: () => Promise<NextRedirect[]> | NextRedirect[];\n /** URL rewrite rules */\n rewrites?: () =>\n | Promise<\n | NextRewrite[]\n | {\n beforeFiles: NextRewrite[];\n afterFiles: NextRewrite[];\n fallback: NextRewrite[];\n }\n >\n | NextRewrite[]\n | {\n beforeFiles: NextRewrite[];\n afterFiles: NextRewrite[];\n fallback: NextRewrite[];\n };\n /** Custom response headers */\n headers?: () => Promise<NextHeader[]> | NextHeader[];\n /** Image optimization config */\n images?: {\n remotePatterns?: Array<{\n protocol?: string;\n hostname: string;\n port?: string;\n pathname?: string;\n search?: string;\n }>;\n domains?: string[];\n unoptimized?: boolean;\n /** Allowed device widths for image optimization. Defaults to Next.js defaults: [640, 750, 828, 1080, 1200, 1920, 2048, 3840] */\n deviceSizes?: number[];\n /** Allowed image sizes for fixed-width images. Defaults to Next.js defaults: [16, 32, 48, 64, 96, 128, 256, 384] */\n imageSizes?: number[];\n /** Allow SVG images through the image optimization endpoint. SVG can contain scripts, so only enable if you trust all image sources. */\n dangerouslyAllowSVG?: boolean;\n /** Allow image optimization for hostnames that resolve to private IP addresses. This is a security risk (SSRF) — only enable for private networks when you understand the risk. */\n dangerouslyAllowLocalIP?: boolean;\n /** Content-Disposition header for image responses. Defaults to \"inline\". */\n contentDispositionType?: \"inline\" | \"attachment\";\n /** Content-Security-Policy header for image responses. Defaults to \"script-src 'none'; frame-src 'none'; sandbox;\" */\n contentSecurityPolicy?: string;\n };\n /** Build output mode: 'export' for full static export, 'standalone' for single server */\n output?: \"export\" | \"standalone\";\n /** File extensions treated as routable pages/routes (Next.js pageExtensions) */\n pageExtensions?: string[];\n /**\n * Module specifiers that are required for side effects on the client before\n * hydration, in array order, ahead of the user's `instrumentation-client.{ts,js}`.\n * Each entry may be a bare npm package name or a path relative to the project root.\n */\n instrumentationClientInject?: string[];\n /** Extra origins allowed to access the dev server. */\n allowedDevOrigins?: string[];\n /** Maximum age in seconds for stale ISR entries before blocking regeneration. */\n expireTime?: number;\n /** User agents that require blocking metadata in the initial head. */\n htmlLimitedBots?: RegExp | string;\n /**\n * Enable Cache Components (Next.js 16).\n * When true, enables the \"use cache\" directive for pages, components, and functions.\n * Replaces the removed experimental.ppr and experimental.dynamicIO flags.\n */\n cacheComponents?: boolean;\n /**\n * Enables source maps while generating static pages.\n * Helps with errors during the prerender phase in `vinext build`.\n * Defaults to `true`. Set to `false` to disable.\n */\n enablePrerenderSourceMaps?: boolean;\n /** Transpile packages (Vite handles this natively) */\n transpilePackages?: string[];\n /**\n * Packages that should be treated as server-external (not bundled by Vite).\n * Corresponds to Next.js `serverExternalPackages` (or the legacy\n * `experimental.serverComponentsExternalPackages`).\n */\n serverExternalPackages?: string[];\n /** Webpack config (ignored — we use Vite) */\n webpack?: unknown;\n /**\n * Compiler options for build-time code transforms.\n * vinext supports the subset that maps to Vite-compatible transforms.\n */\n compiler?: {\n /** Remove `console.*` calls from the client bundle. */\n removeConsole?: boolean | { exclude?: string[] };\n /**\n * Inline compile-time constants in both client and server bundles.\n * Mirrors Next.js `compiler.define`.\n * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/compiler#define\n */\n define?: Record<string, string | number | boolean>;\n /**\n * Inline compile-time constants in server bundles only (not client).\n * Mirrors Next.js `compiler.defineServer`.\n */\n defineServer?: Record<string, string | number | boolean>;\n };\n /**\n * Path to a custom cache handler module (e.g., KV, Redis, DynamoDB).\n * Accepts relative paths, absolute paths, or file:// URLs from import.meta.resolve().\n * When \"type\": \"module\" is set in package.json, use import.meta.resolve() instead of\n * require.resolve() to get a valid path.\n */\n cacheHandler?: string;\n /**\n * Maximum memory size (bytes) for the default in-memory cache handler.\n * Set to 0 to disable in-memory caching entirely.\n */\n cacheMaxMemorySize?: number;\n /**\n * Custom build ID generator. If provided, called once at build/dev start.\n * Must return a non-empty string, or null to use the default random ID.\n */\n generateBuildId?: () => string | null | Promise<string | null>;\n /** Identifier for deployment-aware cache keys and version skew protection. */\n deploymentId?: string;\n /** Any other options */\n [key: string]: unknown;\n};\n\nexport type NextConfigFactory = (\n phase: string,\n opts: { defaultConfig: NextConfig },\n) => NextConfig | Promise<NextConfig>;\n\nexport type NextConfigInput = NextConfig | NextConfigFactory;\n\n/**\n * Resolved configuration with all async values awaited.\n */\nexport type ResolvedNextConfig = {\n env: Record<string, string>;\n basePath: string;\n /**\n * Resolved `assetPrefix` from next.config.\n *\n * Empty string when unset. Trailing slashes are trimmed. May be either:\n * - a path prefix beginning with `/` (e.g. `\"/custom-asset-prefix\"`), or\n * - an absolute URL with `http(s)://` origin (e.g. `\"https://cdn.example.com\"`\n * or `\"https://cdn.example.com/sub\"`).\n *\n * Mirrors Next.js semantics — `assetPrefix` controls emitted asset URLs\n * only; route URLs continue to live under `basePath`.\n *\n * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix\n */\n assetPrefix: string;\n trailingSlash: boolean;\n output: \"\" | \"export\" | \"standalone\";\n pageExtensions: string[];\n instrumentationClientInject: string[];\n cacheComponents: boolean;\n redirects: NextRedirect[];\n rewrites: {\n beforeFiles: NextRewrite[];\n afterFiles: NextRewrite[];\n fallback: NextRewrite[];\n };\n headers: NextHeader[];\n images: NextConfig[\"images\"];\n i18n: NextI18nConfig | null;\n /** MDX remark/rehype/recma plugins extracted from @next/mdx config */\n mdx: MdxOptions | null;\n /** Explicit module aliases preserved from wrapped next.config plugins. */\n aliases: Record<string, string>;\n /** Extra allowed origins for dev server access (from allowedDevOrigins). */\n allowedDevOrigins: string[];\n /** Extra allowed origins for server action CSRF validation (from experimental.serverActions.allowedOrigins). */\n serverActionsAllowedOrigins: string[];\n /** Packages whose barrel imports should be optimized (from experimental.optimizePackageImports). */\n optimizePackageImports: string[];\n /** Inline app CSS into production HTML (from experimental.inlineCss). */\n inlineCss: boolean;\n /** Parsed body size limit for server actions in bytes (from experimental.serverActions.bodySizeLimit). Defaults to 1MB. */\n serverActionsBodySizeLimit: number;\n /** Route-level expire fallback in seconds for ISR entries with numeric revalidate. */\n expireTime: number;\n /** Serialized htmlLimitedBots regexp source from next.config. */\n htmlLimitedBots: string | undefined;\n /**\n * Packages that should be treated as server-external (not bundled by Vite).\n * Sourced from `serverExternalPackages` or the legacy\n * `experimental.serverComponentsExternalPackages` in next.config.\n */\n serverExternalPackages: string[];\n /** Enable sourcemaps for prerender error stack traces. Defaults to true. */\n enablePrerenderSourceMaps: boolean;\n /** Resolved build ID (from generateBuildId, or a random UUID if not provided). */\n buildId: string;\n /** Resolved deployment ID from next.config.js or NEXT_DEPLOYMENT_ID. */\n deploymentId: string | undefined;\n /**\n * Path to a custom cache handler module. file:// URLs are resolved to\n * filesystem paths via fileURLToPath() during config resolution.\n */\n cacheHandler: string | undefined;\n /**\n * Maximum memory size (bytes) for the default in-memory cache handler.\n * Set to 0 to disable in-memory caching entirely.\n */\n cacheMaxMemorySize: number | undefined;\n /**\n * Concatenated hash salt from `experimental.outputHashSalt` config option\n * and `NEXT_HASH_SALT` environment variable. Empty string when neither is set.\n * When non-empty, mix into content-addressed output filenames so hash values\n * change without modifying source — useful for cache-busting after CDN poisoning.\n */\n hashSalt: string;\n /**\n * Raw `sassOptions` object from next.config (or `null` when unset). vinext\n * passes the relevant keys through to Vite's `css.preprocessorOptions.scss`\n * so SCSS variables defined via `additionalData` / `prependData`, partials\n * resolved via `includePaths` / `loadPaths`, and a custom `implementation`\n * all behave the same as in Next.js.\n *\n * Kept loose (`Record<string, unknown> | null`) to match Next.js's typing —\n * the object is forwarded to Sass and may contain any modern Sass option.\n */\n sassOptions: Record<string, unknown> | null;\n /**\n * When enabled, strip `console.*` calls from the client bundle.\n * Mirrors Next.js `compiler.removeConsole` option.\n * `true` strips all console calls; `{ exclude: [\"error\"] }` strips all\n * except the specified method names (case-insensitive).\n */\n removeConsole: boolean | { exclude: string[] };\n /**\n * Mirrors Next.js `experimental.disableOptimizedLoading`. When `false`\n * (the default), Pages Router page scripts are emitted with `defer` in\n * `<head>` so the browser can prefetch them in parallel with HTML parsing.\n * When `true`, scripts are emitted without `defer` (legacy behaviour).\n *\n * See `.nextjs-ref/packages/next/src/pages/_document.tsx` (`getScripts` →\n * `defer={!disableOptimizedLoading}`) and the upstream\n * `test/e2e/optimized-loading` test fixture.\n */\n disableOptimizedLoading: boolean;\n /**\n * Build-time constant replacement map applied to BOTH client and server\n * bundles. Sourced from `compiler.define` in next.config. Values are\n * pre-serialized via `JSON.stringify` so they can be fed straight into\n * Vite's `define` config (which expects strings of source code).\n *\n * Mirrors Next.js — strings, numbers, and booleans are accepted; other\n * value shapes are dropped.\n * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/compiler#define\n */\n compilerDefine: Record<string, string>;\n /**\n * Build-time constant replacement map applied to SERVER bundles only\n * (RSC + SSR + middleware). Sourced from `compiler.defineServer` in\n * next.config. Same serialization rules as `compilerDefine`. Client\n * bundles intentionally never see these substitutions, so referencing\n * a `defineServer` identifier from the browser stays as the raw\n * identifier (typically resolving to `undefined`).\n */\n compilerDefineServer: Record<string, string>;\n /**\n * Allow-list of keys, sourced from `experimental.clientTraceMetadata`,\n * to forward from the active OpenTelemetry context into the SSR HTML head\n * as `<meta>` tags. `undefined` (or empty) disables injection.\n *\n * Mirrors Next.js: packages/next/src/server/lib/trace/utils.ts (getTracedMetadata).\n */\n clientTraceMetadata: string[] | undefined;\n /**\n * App Router client cache freshness windows in seconds, sourced from\n * `experimental.staleTimes`. Controls how long prefetched route segments\n * are considered fresh in the client-side router cache.\n *\n * `dynamic` applies to partial/dynamic prefetches (default 0 — no reuse).\n * `static` applies to full-route prefetches (default 300 — 5 minutes).\n * Mirrors Next.js' `process.env.__NEXT_CLIENT_ROUTER_{DYNAMIC,STATIC}_STALETIME`.\n */\n staleTimes: { dynamic: number; static: number };\n};\n\n// Mirrors Next.js's accepted set in packages/next/src/shared/lib/constants.ts\n// (`.js`/`.mjs`/`.ts`/`.mts`) and adds `.cjs` for parity with vinext's own\n// loader, which has historically accepted CJS configs as well. The order is\n// significant: findNextConfigPath returns the first match, so prefer the more\n// modern flavours first.\nconst CONFIG_FILES = [\n \"next.config.ts\",\n \"next.config.mts\",\n \"next.config.mjs\",\n \"next.config.js\",\n \"next.config.cjs\",\n];\nconst DEFAULT_EXPIRE_TIME = 31_536_000;\n\n/**\n * Check whether an error indicates a CJS module was loaded in an ESM context\n * (i.e. the file uses `require()` which is not available in ESM).\n */\nfunction isCjsError(e: unknown): boolean {\n if (!(e instanceof Error)) return false;\n const msg = e.message;\n return (\n msg.includes(\"require is not a function\") ||\n msg.includes(\"require is not defined\") ||\n msg.includes(\"exports is not defined\") ||\n msg.includes(\"module is not defined\") ||\n msg.includes(\"__dirname is not defined\") ||\n msg.includes(\"__filename is not defined\")\n );\n}\n\n// Dev-server phase is the safe default for config loading: it enables all\n// optional config sections (headers, redirects, rewrites) without triggering\n// build-only behaviour. Used in two default parameter values below to avoid\n// repeating PHASE_DEVELOPMENT_SERVER inline.\nconst DEFAULT_PHASE = PHASE_DEVELOPMENT_SERVER;\n\n/**\n * Emit a warning when config loading fails, with a targeted hint for\n * known plugin wrappers that are unnecessary in vinext.\n */\nfunction warnConfigLoadFailure(filename: string, err: Error): void {\n const msg = err.message ?? \"\";\n const stack = err.stack ?? \"\";\n const isNextIntlPlugin =\n msg.includes(\"next-intl\") ||\n stack.includes(\"next-intl/plugin\") ||\n stack.includes(\"next-intl/dist\");\n\n console.log();\n console.error(`[vinext] Failed to load ${filename}: ${msg}`);\n console.log();\n if (isNextIntlPlugin) {\n console.warn(\n \"[vinext] Hint: createNextIntlPlugin() is not needed with vinext. \" +\n \"Remove the next-intl/plugin wrapper from your next.config — \" +\n \"vinext auto-detects next-intl and registers the i18n config alias automatically.\",\n );\n }\n}\n\n/**\n * Resolve a Next-style config value, calling it if it's a function-form config\n * (Next.js supports `module.exports = (phase, opts) => config`).\n */\nasync function resolveConfigValue(\n config: unknown,\n phase: string = DEFAULT_PHASE,\n): Promise<NextConfig> {\n if (typeof config === \"function\") {\n const result = await config(phase, {\n defaultConfig: {},\n });\n return result as NextConfig;\n }\n return config as NextConfig;\n}\n\n/**\n * Named export attached by `cjsGlobalsInjectorPlugin` when the source\n * statically looks like it assigns to `module.exports`. Holds the wrapper\n * `module` object so {@link unwrapConfig} can read back the user's CJS-style\n * export. Pure-ESM configs skip the wrapper entirely and rely on the ESM\n * `default` export instead.\n */\nconst VINEXT_CJS_EXPORTS_KEY = \"__vinext_cjs_exports\";\n\n/**\n * Companion named export pointing at the initial empty `{}` that the wrapper\n * is constructed with. Lets {@link unwrapConfig} distinguish \"user reassigned\n * or mutated module.exports\" from \"module.exports is still the untouched\n * empty wrapper\" — the latter happens when {@link reassignsModuleExports}\n * matches inside a string or comment (a harmless false positive that should\n * still fall through to the ESM `default` export).\n */\nconst VINEXT_CJS_INITIAL_KEY = \"__vinext_cjs_initial_exports\";\n\n/**\n * Unwrap the config value from a loaded module namespace.\n *\n * Prefers `module.exports` (CJS style) when the config file reassigned it,\n * otherwise falls back to `default`/the namespace itself. Mirrors Next.js's\n * behaviour, where the config is loaded through `Module._compile` and CJS\n * assignments override any ESM-style exports.\n *\n * The presence of the `__vinext_cjs_exports` named export is the static\n * signal (set by `cjsGlobalsInjectorPlugin` when `reassignsModuleExports`\n * matched) that this file might use CJS-style exports. We then disambiguate\n * \"user actually touched module.exports\" from \"static heuristic was a false\n * positive\" by comparing identity against the initial empty wrapper: if\n * `module.exports` is still the original `{}`, fall back to ESM `default`.\n */\nasync function unwrapConfig(\n // oxlint-disable-next-line typescript/no-explicit-any\n mod: any,\n phase: string = PHASE_DEVELOPMENT_SERVER,\n): Promise<NextConfig> {\n const cjsModule = mod?.[VINEXT_CJS_EXPORTS_KEY];\n const cjsExports = cjsModule?.exports;\n const cjsInitial = mod?.[VINEXT_CJS_INITIAL_KEY];\n const userTouchedExports =\n cjsExports !== undefined &&\n cjsExports !== null &&\n // Either reassigned outright, or mutated keys on the initial object.\n (cjsExports !== cjsInitial ||\n (typeof cjsExports === \"object\" && Object.keys(cjsExports).length > 0));\n if (userTouchedExports) {\n return await resolveConfigValue(cjsExports, phase);\n }\n return await resolveConfigValue(mod.default ?? mod, phase);\n}\n\n/**\n * Resolve a path through filesystem symlinks, falling back to the original\n * path when the file does not exist (e.g. virtual ids, query-suffixed ids).\n */\nfunction safeRealpath(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n/**\n * Whole-word substring check for any of the CJS-style globals that the\n * injector plugin would shim. Used to skip the transform entirely for the\n * common case where the config is pure ESM (no `__filename`, `__dirname`,\n * `require`, `module`, or `exports` references).\n *\n * False positives are harmless: a comment, string literal, or unrelated\n * identifier like `node:module` will trigger the transform unnecessarily,\n * but the resulting injection is idempotent and the loaded config is\n * unaffected. False negatives would be a correctness bug, so we err on the\n * side of matching too eagerly.\n *\n * Note: `\\bexports\\b` does not match `export default` (different word\n * boundaries), and `\\brequire\\b` does not match `requireSomething`.\n */\nexport function referencesCjsGlobals(source: string): boolean {\n return /\\b(?:__filename|__dirname|require|module|exports)\\b/.test(source);\n}\n\n/**\n * Static heuristic: returns true when the source appears to assign to\n * `module.exports` — either via `module.exports = …`, `module.exports.foo = …`,\n * or `module.exports[…] = …`. Used to decide whether the injector plugin\n * needs to wire up the wrapper `module` object so {@link unwrapConfig} can\n * read back the user's CJS-style export.\n *\n * Pure-ESM configs skip the wrapper entirely, which means a faster transform\n * (no extra `export const` line) and a simpler unwrap path (no need to\n * disambiguate \"initial empty object\" from \"user reassigned to {}\").\n *\n * Like {@link referencesCjsGlobals}, false positives are harmless: at worst\n * we emit an unused `__vinext_cjs_exports` named export, and `unwrapConfig`\n * still prefers it (it points at an empty object, which then gets treated\n * as the config — equivalent to today's sentinel logic for pure-ESM files\n * that happen to mention `module.exports` only in a string).\n */\nexport function reassignsModuleExports(source: string): boolean {\n // Match `module.exports` followed by `=` (not `==` / `===`), `.identifier =`,\n // or `[...] =`. Whitespace allowed around the dot.\n return /\\bmodule\\s*\\.\\s*exports\\b\\s*(?:=(?!=)|\\.\\s*[A-Za-z_$][\\w$]*\\s*=(?!=)|\\[)/.test(source);\n}\n\n/**\n * Vite plugin that prepends CJS-style globals (`__filename`, `__dirname`,\n * `module`, `exports`, `require`) to the next.config.* source before\n * Vite's module runner evaluates it.\n *\n * Next.js's `next.config.ts` loader (packages/next/src/build/next-config-ts/\n * transpile-config.ts → require-hook.ts) feeds the file through Node's\n * `Module._compile`, which provides these CJS globals even when the source\n * uses ESM syntax. Upstream test fixtures in `test/e2e/app-dir/next-config-ts*`\n * rely on that, e.g. `node-api-cjs/next.config.ts` reads\n * `fs.readFileSync(path.join(__dirname, 'foo.txt'), 'utf8')`. vinext loads\n * configs through Vite's ESM-only module runner, so we inject the same\n * globals as plain `const` declarations.\n *\n * For configs that don't reference any CJS global (the common case — every\n * upstream `next-config-ts` fixture except `node-api-cjs` is pure ESM) we\n * skip the transform entirely; see {@link referencesCjsGlobals}.\n *\n * `module.exports` reassignment is preserved by exposing the injected\n * `module` object as a named export (see {@link VINEXT_CJS_EXPORTS_KEY}) and\n * reading it back in {@link unwrapConfig}.\n */\nfunction cjsGlobalsInjectorPlugin(configPath: string): {\n name: string;\n enforce: \"pre\";\n // oxlint-disable-next-line typescript/no-explicit-any\n transform(this: unknown, code: string, id: string): any;\n} {\n // Resolve symlinks once so we can compare against the (possibly\n // symlink-resolved) id Vite passes to `transform`. On macOS, `/var/folders`\n // is a symlink to `/private/var/folders`, so the temp-dir path in tests\n // would otherwise mismatch.\n const normalizedTarget = safeRealpath(path.resolve(configPath));\n return {\n name: \"vinext:next-config-cjs-globals\",\n enforce: \"pre\",\n transform(code: string, id: string) {\n // Vite may pass an id with a query suffix (?v=...) or as a file URL.\n const idPath = id.startsWith(\"file://\") ? fileURLToPath(id) : id.split(\"?\")[0];\n const resolvedId = safeRealpath(path.resolve(idPath));\n if (resolvedId !== normalizedTarget) return null;\n\n // Fast path: skip the transform when the source contains no bareword\n // reference to any of the shimmed globals. The vast majority of\n // `next.config.ts` files are pure ESM (`export default { ... }`) and\n // pay no cost from this plugin.\n if (!referencesCjsGlobals(code)) return null;\n\n const dirname = path.dirname(normalizedTarget);\n // JSON.stringify produces safe JS string literals for paths.\n const filenameLiteral = JSON.stringify(normalizedTarget);\n const dirnameLiteral = JSON.stringify(dirname);\n const requireBaseLiteral = JSON.stringify(path.join(dirname, \"package.json\"));\n\n // Only wire up the wrapper `module` object — and the corresponding\n // named export read by unwrapConfig — when the source statically looks\n // like it assigns to module.exports. Pure-ESM configs avoid the extra\n // export and the unwrap-by-wrapper code path.\n const needsModuleWrapper = reassignsModuleExports(code);\n const moduleLines = needsModuleWrapper\n ? `const __vinextInitialExports = {};\\n` +\n `const module = { exports: __vinextInitialExports };\\n` +\n `const exports = module.exports;\\n` +\n `export const ${VINEXT_CJS_EXPORTS_KEY} = module;\\n` +\n `export const ${VINEXT_CJS_INITIAL_KEY} = __vinextInitialExports;\\n`\n : \"\";\n\n // Preamble runs after ESM imports are hoisted; the const bindings shadow\n // any global lookups the source would otherwise perform.\n const preamble =\n `import { createRequire as __vinextCreateRequire } from \"node:module\";\\n` +\n `const __filename = ${filenameLiteral};\\n` +\n `const __dirname = ${dirnameLiteral};\\n` +\n `const require = __vinextCreateRequire(${requireBaseLiteral});\\n` +\n moduleLines;\n\n return {\n code: preamble + code,\n map: null,\n };\n },\n };\n}\n\nexport function findNextConfigPath(root: string): string | null {\n for (const filename of CONFIG_FILES) {\n const configPath = path.join(root, filename);\n if (fs.existsSync(configPath)) return configPath;\n }\n return null;\n}\n\nexport async function resolveNextConfigInput(\n config: NextConfigInput,\n phase: string = PHASE_DEVELOPMENT_SERVER,\n): Promise<NextConfig> {\n // Inline vinext({ nextConfig }) already receives the config value itself,\n // not a module namespace object, so do not treat a \"default\" key specially.\n return await resolveConfigValue(config, phase);\n}\n\n/**\n * Load a CJS-flavoured next.config.{js,cjs} via createRequire.\n *\n * For `.cjs` (or `.js` in a non-type-module package) Node's loader picks the\n * right format automatically and `require()` just works. For `.js` in a\n * `\"type\": \"module\"` package, Node infers ESM from package.json and the file\n * fails with `require is not defined`. In that case we copy the source to a\n * sibling temp `.cjs` (where the explicit extension forces CJS regardless of\n * the parent type field) and require *that*. Relative imports inside the\n * config still resolve against the original directory.\n */\nasync function loadConfigViaRequire(\n configPath: string,\n root: string,\n phase: string,\n): Promise<NextConfig> {\n const require = createRequire(path.join(root, \"package.json\"));\n try {\n return await unwrapConfig(require(configPath), phase);\n } catch (e) {\n if (!isCjsError(e) || !configPath.endsWith(\".js\")) throw e;\n return await loadConfigViaCjsTempCopy(configPath, root, phase);\n }\n}\n\nasync function loadConfigViaCjsTempCopy(\n configPath: string,\n root: string,\n phase: string,\n): Promise<NextConfig> {\n const dir = path.dirname(configPath);\n // Hidden + uniquely-named to avoid clashing with user files or being picked\n // up by next.js's own config scanner if a concurrent next dev is running.\n const tmpPath = path.join(dir, `.vinext-next-config.${process.pid}.${Date.now()}.cjs`);\n fs.copyFileSync(configPath, tmpPath);\n try {\n const require = createRequire(path.join(root, \"package.json\"));\n return await unwrapConfig(require(tmpPath), phase);\n } finally {\n try {\n fs.unlinkSync(tmpPath);\n } catch {\n // Best-effort cleanup; a stray tmp file is harmless.\n }\n }\n}\n\n/**\n * Find and load the next.config file from the project root.\n * Returns null if no config file is found.\n *\n * Attempts Vite's module runner first so TS configs and extensionless local\n * imports (e.g. `import \"./env\"`) resolve consistently. If loading fails due\n * to CJS constructs (`require`, `module.exports`), falls back to `createRequire`\n * so common CJS plugin wrappers (nextra, @next/mdx, etc.) still work, including\n * `next.config.js` files written in CJS syntax inside a `\"type\": \"module\"`\n * package (the common shape after `vinext init`).\n */\nexport async function loadNextConfig(\n root: string,\n phase: string = DEFAULT_PHASE,\n): Promise<NextConfig | null> {\n const configPath = findNextConfigPath(root);\n if (!configPath) return null;\n\n const filename = path.basename(configPath);\n\n // Mirror Next.js: read `compilerOptions.paths` from the project's\n // tsconfig.json so aliased imports inside next.config.ts (e.g.\n // `import { foo } from '@/foo'`) resolve at config-load time. Next.js\n // passes these to SWC; we pass them to Vite's resolver as `resolve.alias`.\n // See packages/next/src/build/next-config-ts/transpile-config.ts.\n const tsconfigAliases = loadTsconfigPathAliasesForRoot(root);\n\n // Symlink-resolved config path, used by the `commonjs()` filter below to\n // exclude the config file itself. macOS uses /private/var symlinks, so\n // string-compare without realpath would falsely include the config.\n const normalizedConfigPath = safeRealpath(path.resolve(configPath));\n\n try {\n // Load config via Vite's module runner (TS + extensionless import support)\n const { runnerImport } = await import(\"vite\");\n const { module: mod } = await runnerImport(configPath, {\n root,\n logLevel: \"error\",\n clearScreen: false,\n resolve: {\n alias: tsconfigAliases,\n // Include `.cjs` and `.cts` so `vite-plugin-commonjs` recognises\n // those extensions (the plugin keys off `config.resolve.extensions`,\n // which on Vite defaults to `[.mjs, .js, .mts, .ts, .jsx, .tsx,\n // .json]` — no CJS extensions). This also lets the runner's resolver\n // find `./foo` style imports that resolve to a `.cjs`/`.cts` sibling.\n extensions: [\".mjs\", \".js\", \".cjs\", \".mts\", \".ts\", \".cts\", \".jsx\", \".tsx\", \".json\"],\n },\n // Only inject CJS globals for TypeScript config flavours. Next.js\n // applies its `Module._compile` / SWC pipeline (which exposes the\n // CJS globals) exclusively to `.ts`/`.mts`/`.cts`; legacy `.js`/`.cjs`\n // configs are loaded through Node and already have `require`/`module`,\n // and `.mjs` configs are explicitly ESM-only.\n //\n // Pair that with `vite-plugin-commonjs` (the same plugin used for\n // application code in index.ts) so sibling imports like `.cjs`/`.cts`,\n // or `.js`/`.ts` files that assign to `module.exports`, are converted\n // to ESM before Vite's runner evaluates them. The default `filter`\n // skips `node_modules`; we opt back in so bare-import packages\n // imported by next.config.* (e.g. CJS plugin wrappers) keep working —\n // this mirrors how Next.js's SWC pipeline handles those imports too.\n //\n // The config file itself is excluded from `commonjs()`: when it needs\n // CJS globals it goes through `cjsGlobalsInjectorPlugin`, which sets\n // up a specific `__vinext_cjs_exports` wiring that `unwrapConfig` reads\n // back. Letting both plugins inject `module = { exports: {} }` for the\n // same source produces an `Identifier 'module' has already been\n // declared` syntax error.\n plugins: [\n ...(/\\.[cm]?ts$/.test(configPath) ? [cjsGlobalsInjectorPlugin(configPath)] : []),\n commonjs({\n filter: (id: string) => {\n const idPath = id.startsWith(\"file://\") ? fileURLToPath(id) : id.split(\"?\")[0];\n const resolvedId = safeRealpath(path.resolve(idPath));\n if (resolvedId === normalizedConfigPath) return false;\n // Returning `true` forces the transform to run even for ids\n // inside `node_modules` (default behaviour skips them);\n // `undefined` falls through to the plugin's default for\n // user code.\n return id.includes(\"node_modules\") ? true : undefined;\n },\n }),\n ],\n });\n return await unwrapConfig(mod, phase);\n } catch (e) {\n // If the error indicates a CJS file loaded in ESM context, retry with\n // createRequire which provides a proper CommonJS environment.\n if (isCjsError(e) && (filename.endsWith(\".js\") || filename.endsWith(\".cjs\"))) {\n try {\n return await loadConfigViaRequire(configPath, root, phase);\n } catch (e2) {\n warnConfigLoadFailure(filename, e2 as Error);\n throw e2;\n }\n }\n\n warnConfigLoadFailure(filename, e as Error);\n throw e;\n }\n}\n\n/**\n * Generate a UUID that doesn't contain \"ad\" to avoid false-positive ad-blocker hits.\n * Mirrors Next.js's own nanoid retry loop.\n */\nfunction safeUUID(): string {\n let id = randomUUID();\n while (/ad/i.test(id)) id = randomUUID();\n return id;\n}\n\n/**\n * Call the user's generateBuildId function and validate its return value.\n * Follows Next.js semantics: null return falls back to a random UUID; any\n * other non-string throws. Leading/trailing whitespace is trimmed.\n *\n * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/generateBuildId\n */\nasync function resolveBuildId(\n generate: (() => string | null | Promise<string | null>) | undefined,\n): Promise<string> {\n if (!generate) return safeUUID();\n\n const result = await generate();\n\n if (result === null) return safeUUID();\n\n if (typeof result !== \"string\") {\n throw new Error(\n \"generateBuildId did not return a string. https://nextjs.org/docs/messages/generatebuildid-not-a-string\",\n );\n }\n\n const trimmed = result.trim();\n if (trimmed.length === 0) {\n throw new Error(\n \"generateBuildId returned an empty string. https://nextjs.org/docs/messages/generatebuildid-not-a-string\",\n );\n }\n\n return trimmed;\n}\n\n/**\n * Normalize the `assetPrefix` option from next.config.\n *\n * Accepts both absolute URLs (`https://cdn.example.com[/subpath]`) and\n * path prefixes (`/custom-asset-prefix`). Trailing slashes are trimmed.\n * Empty/whitespace-only strings are treated as unset and return `\"\"`.\n *\n * Path prefixes that omit the leading slash get one added so they always\n * begin with `/` — this matches how Next.js routes match against them.\n *\n * Non-string values are rejected to surface config mistakes early.\n *\n * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/assetPrefix\n */\nexport function normalizeAssetPrefix(value: unknown): string {\n if (value === undefined || value === null || value === \"\") return \"\";\n\n if (typeof value !== \"string\") {\n throw new Error(\n `Invalid \\`assetPrefix\\` configuration: must be a string, got ${typeof value}. ` +\n `Accepts a path prefix (\"/custom-asset-prefix\") or an absolute URL ` +\n `(\"https://cdn.example.com\").`,\n );\n }\n\n // Avoid `replace(/\\/+$/, \"\")` — CodeQL flags it as polynomial backtracking\n // on uncontrolled input. An explicit loop has the same effect with linear time.\n let trimmed = value.trim();\n while (trimmed.endsWith(\"/\")) trimmed = trimmed.slice(0, -1);\n if (trimmed === \"\") return \"\";\n\n // Absolute URL — keep origin verbatim, validate parseability so a typo\n // surfaces at config-load time instead of as a confusing build error.\n if (/^https?:\\/\\//i.test(trimmed)) {\n if (!URL.canParse(trimmed)) {\n throw new Error(`Invalid \\`assetPrefix\\` configuration: \"${value}\" is not a parseable URL.`);\n }\n return trimmed;\n }\n\n // Path prefix — always begin with \"/\", consistent with basePath.\n return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\nfunction resolveDeploymentId(configDeploymentId: unknown): string | undefined {\n const deploymentId =\n configDeploymentId !== undefined ? configDeploymentId : process.env.NEXT_DEPLOYMENT_ID;\n if (deploymentId === undefined || deploymentId === \"\") return undefined;\n\n if (typeof deploymentId !== \"string\") {\n throw new Error(\n \"Invalid `deploymentId` configuration: must be a string. https://nextjs.org/docs/messages/deploymentid-not-a-string\",\n );\n }\n\n if (!/^[a-zA-Z0-9_-]+$/.test(deploymentId)) {\n throw new Error(\n \"Invalid `deploymentId` configuration: contains invalid characters. Only alphanumeric characters, hyphens, and underscores are allowed. https://nextjs.org/docs/messages/deploymentid-invalid-characters\",\n );\n }\n\n return deploymentId;\n}\n\n/**\n * Converts a cache handler path to a filesystem path.\n * ESM's import.meta.resolve() returns file:// URLs which break when concatenated\n * with path operations like path.join or path.relative.\n * @param filePath - Absolute path, relative path, or file:// URL (e.g. from import.meta.resolve)\n * @returns A filesystem path suitable for path operations\n */\nfunction resolveCacheHandlerPathToFilesystem(filePath: string): string {\n if (filePath.startsWith(\"file://\")) {\n return fileURLToPath(filePath);\n }\n return filePath;\n}\n\nfunction resolveHtmlLimitedBots(value: NextConfig[\"htmlLimitedBots\"]): string | undefined {\n const source =\n value instanceof RegExp ? value.source : typeof value === \"string\" ? value : undefined;\n if (!source) return undefined;\n\n try {\n getHtmlLimitedBotRegex(source);\n } catch (error) {\n throw new Error(\n 'Invalid next.config option \"htmlLimitedBots\": expected a valid regular expression source',\n { cause: error },\n );\n }\n\n return source;\n}\n\nfunction readOptionalRecord(value: unknown): Record<string, unknown> | undefined {\n return isUnknownRecord(value) ? value : undefined;\n}\n\nfunction readOptionalString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction readOptionalBodySizeLimit(value: unknown): string | number | undefined {\n return typeof value === \"string\" || typeof value === \"number\" ? value : undefined;\n}\n\nfunction readStringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === \"string\")\n : [];\n}\n\n/**\n * Serialize a `compiler.define` / `compiler.defineServer` map into the\n * Vite-friendly `Record<string, string>` shape where each value is already\n * a JSON-encoded literal of source code. Entries whose values are not a\n * string/number/boolean are silently dropped, matching how Next.js types\n * the API (other shapes are not part of the contract).\n *\n * Mirrors Next.js: packages/next/src/build/define-env.ts (serializeDefineEnv).\n */\nfunction serializeCompilerDefine(value: unknown): Record<string, string> {\n if (!isUnknownRecord(value)) return {};\n const out: Record<string, string> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (typeof raw === \"string\" || typeof raw === \"number\" || typeof raw === \"boolean\") {\n out[key] = JSON.stringify(raw);\n }\n }\n return out;\n}\n\n/**\n * Defaults for `experimental.staleTimes` (in seconds), matching Next.js'\n * `config-shared.ts` defaults.\n */\nconst DEFAULT_STALE_TIMES = { dynamic: 0, static: 300 };\n\n/**\n * Parse `experimental.staleTimes` from a raw next.config object.\n *\n * Mirrors Next.js' `build/define-env.ts` parsing logic:\n * - missing / NaN / negative values fall back to the documented defaults\n * (`dynamic: 0`, `static: 300`) — matching Next.js parity and the\n * non-negative guard in `resolvePrefetchCacheTtl`\n * - all values are in seconds\n *\n * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/staleTimes\n */\nfunction resolveStaleTimes(experimental: Record<string, unknown> | undefined): {\n dynamic: number;\n static: number;\n} {\n const staleTimes = readOptionalRecord(experimental?.staleTimes);\n const dynamicRaw = Number(staleTimes?.dynamic);\n const staticRaw = Number(staleTimes?.static);\n\n return {\n dynamic:\n Number.isFinite(dynamicRaw) && dynamicRaw >= 0 ? dynamicRaw : DEFAULT_STALE_TIMES.dynamic,\n static: Number.isFinite(staticRaw) && staticRaw >= 0 ? staticRaw : DEFAULT_STALE_TIMES.static,\n };\n}\n\n/**\n * Resolve a NextConfig into a fully-resolved ResolvedNextConfig.\n * Awaits async functions for redirects/rewrites/headers.\n */\nexport async function resolveNextConfig(\n config: NextConfig | null,\n root: string = process.cwd(),\n): Promise<ResolvedNextConfig> {\n if (!config) {\n const buildId = await resolveBuildId(undefined);\n const deploymentId = resolveDeploymentId(undefined);\n const resolved: ResolvedNextConfig = {\n env: {},\n basePath: \"\",\n assetPrefix: \"\",\n trailingSlash: false,\n output: \"\",\n pageExtensions: normalizePageExtensions(),\n cacheComponents: false,\n redirects: [],\n rewrites: { beforeFiles: [], afterFiles: [], fallback: [] },\n headers: [],\n images: undefined,\n i18n: null,\n mdx: null,\n aliases: {},\n allowedDevOrigins: [],\n serverActionsAllowedOrigins: [],\n optimizePackageImports: [],\n inlineCss: false,\n serverActionsBodySizeLimit: 1 * 1024 * 1024,\n expireTime: DEFAULT_EXPIRE_TIME,\n htmlLimitedBots: undefined,\n serverExternalPackages: [],\n cacheHandler: undefined,\n cacheMaxMemorySize: undefined,\n enablePrerenderSourceMaps: true,\n hashSalt: process.env.NEXT_HASH_SALT ?? \"\",\n buildId,\n deploymentId,\n sassOptions: null,\n removeConsole: false,\n disableOptimizedLoading: false,\n compilerDefine: {},\n compilerDefineServer: {},\n instrumentationClientInject: [],\n clientTraceMetadata: undefined,\n staleTimes: { ...DEFAULT_STALE_TIMES },\n };\n detectNextIntlConfig(root, resolved);\n return resolved;\n }\n\n // Resolve redirects\n let redirects: NextRedirect[] = [];\n if (config.redirects) {\n const result = await config.redirects();\n redirects = Array.isArray(result) ? result : [];\n }\n\n // Resolve rewrites\n let rewrites: {\n beforeFiles: NextRewrite[];\n afterFiles: NextRewrite[];\n fallback: NextRewrite[];\n } = {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n };\n if (config.rewrites) {\n const result = await config.rewrites();\n if (Array.isArray(result)) {\n rewrites.afterFiles = result;\n } else {\n rewrites = {\n beforeFiles: result.beforeFiles ?? [],\n afterFiles: result.afterFiles ?? [],\n fallback: result.fallback ?? [],\n };\n }\n }\n\n {\n const allRewrites = [...rewrites.beforeFiles, ...rewrites.afterFiles, ...rewrites.fallback];\n const externalRewrites = allRewrites.filter((rewrite) => isExternalUrl(rewrite.destination));\n\n if (externalRewrites.length > 0) {\n const noun = externalRewrites.length === 1 ? \"external rewrite\" : \"external rewrites\";\n const listing = externalRewrites\n .map((rewrite) => ` ${rewrite.source} → ${rewrite.destination}`)\n .join(\"\\n\");\n\n console.warn(\n `[vinext] Found ${externalRewrites.length} ${noun} that proxy requests to external origins:\\n` +\n `${listing}\\n` +\n `Request headers, including credential headers (cookie, authorization, proxy-authorization, x-api-key), ` +\n `are forwarded to the external origin to match Next.js behavior. ` +\n `If you do not want to forward credentials, use an API route or route handler where you control exactly which headers are sent.`,\n );\n }\n }\n\n // Resolve headers\n let headers: NextHeader[] = [];\n if (config.headers) {\n headers = await config.headers();\n }\n\n // Probe wrapped webpack config once so alias extraction and MDX extraction\n // observe the same mock environment.\n const webpackProbe = await probeWebpackConfig(config, root);\n const mdx = webpackProbe.mdx;\n const aliases = {\n ...extractTurboAliases(config, root),\n ...webpackProbe.aliases,\n };\n\n const allowedDevOrigins = Array.isArray(config.allowedDevOrigins) ? config.allowedDevOrigins : [];\n\n // Resolve serverActions.allowedOrigins and bodySizeLimit from experimental config\n const experimental = readOptionalRecord(config.experimental);\n const serverActionsConfig = readOptionalRecord(experimental?.serverActions);\n const serverActionsAllowedOrigins = readStringArray(serverActionsConfig?.allowedOrigins);\n const serverActionsBodySizeLimit = parseBodySizeLimit(\n readOptionalBodySizeLimit(serverActionsConfig?.bodySizeLimit),\n );\n\n // Resolve hashSalt from experimental.outputHashSalt config + NEXT_HASH_SALT env var.\n // Next.js concatenates them: config value first, then env var.\n const configOutputHashSalt = readOptionalString(experimental?.outputHashSalt);\n const hashSalt = (configOutputHashSalt ?? \"\") + (process.env.NEXT_HASH_SALT ?? \"\");\n const htmlLimitedBots = resolveHtmlLimitedBots(config.htmlLimitedBots);\n\n // Resolve optimizePackageImports from experimental config\n const rawOptimize = experimental?.optimizePackageImports;\n const optimizePackageImports = Array.isArray(rawOptimize)\n ? rawOptimize.filter((x): x is string => typeof x === \"string\")\n : [];\n const inlineCss = experimental?.inlineCss === true;\n\n // Resolve serverExternalPackages — support the current top-level key and the\n // legacy experimental.serverComponentsExternalPackages name that Next.js still\n // accepts (it moved out of experimental in Next.js 14.2).\n const topLevelServerExternalPackages = Array.isArray(config.serverExternalPackages)\n ? readStringArray(config.serverExternalPackages)\n : undefined;\n const legacyServerComponentsExternal = readStringArray(\n experimental?.serverComponentsExternalPackages,\n );\n const serverExternalPackages = topLevelServerExternalPackages ?? legacyServerComponentsExternal;\n\n // Warn about unsupported experimental.swcEnvOptions. vinext uses Vite for\n // transforms, not SWC, so automatic polyfill injection is not applicable.\n if (experimental?.swcEnvOptions !== undefined) {\n console.warn(\n '[vinext] next.config option \"experimental.swcEnvOptions\" is not applicable and will be ignored (vinext uses Vite, not SWC). ' +\n \"A Vite-compatible polyfill solution may be explored in the future.\",\n );\n }\n\n // `next/root-params` is now stable — no longer requires an experimental flag.\n if (experimental?.rootParams !== undefined) {\n console.warn(\n \"[vinext] `experimental.rootParams` is no longer needed, because `next/root-params` is available by default. \" +\n \"You can remove it from next.config.(js|mjs|ts).\",\n );\n }\n\n // Warn about unsupported webpack usage. We preserve alias injection and\n // extract MDX settings, but all other webpack customization is still ignored.\n if (config.webpack !== undefined) {\n if (mdx || Object.keys(webpackProbe.aliases).length > 0) {\n console.warn(\n '[vinext] next.config option \"webpack\" is only partially supported. ' +\n \"vinext preserves resolve.alias entries and MDX loader settings, but other webpack customization is ignored\",\n );\n } else {\n console.warn(\n '[vinext] next.config option \"webpack\" is not yet supported and will be ignored',\n );\n }\n }\n\n const output = readOptionalString(config.output) ?? \"\";\n if (output && output !== \"export\" && output !== \"standalone\") {\n console.warn(`[vinext] Unknown output mode \"${output}\", ignoring`);\n }\n\n const pageExtensions = normalizePageExtensions(config.pageExtensions);\n\n // Parse i18n config\n let i18n: NextI18nConfig | null = null;\n if (config.i18n) {\n i18n = {\n locales: config.i18n.locales,\n defaultLocale: config.i18n.defaultLocale,\n localeDetection: config.i18n.localeDetection ?? true,\n domains: config.i18n.domains,\n };\n }\n\n const buildId = await resolveBuildId(config.generateBuildId);\n const deploymentId = resolveDeploymentId(config.deploymentId);\n\n // Resolve cacheHandler path — handle file:// URLs from import.meta.resolve()\n const cacheHandler: string | undefined =\n typeof config.cacheHandler === \"string\"\n ? resolveCacheHandlerPathToFilesystem(config.cacheHandler)\n : undefined;\n\n // Resolve cacheMaxMemorySize\n const cacheMaxMemorySize: number | undefined =\n typeof config.cacheMaxMemorySize === \"number\" ? config.cacheMaxMemorySize : undefined;\n\n // Apply Next.js i18n locale-prefix transformation to redirects/rewrites.\n // When i18n is configured and a rule does NOT carry `locale: false`, the\n // source is rewritten to match locale-prefixed URLs. Rules with\n // `locale: false` are left untouched so user-supplied `:locale` segments\n // can capture the prefix themselves. Mirrors processRoutes() in\n // packages/next/src/lib/load-custom-routes.ts.\n if (i18n) {\n const opts = { trailingSlash: config.trailingSlash ?? false };\n redirects = applyLocaleToRoutes(redirects, i18n, \"redirect\", opts);\n rewrites = {\n beforeFiles: applyLocaleToRoutes(rewrites.beforeFiles, i18n, \"rewrite\", opts),\n afterFiles: applyLocaleToRoutes(rewrites.afterFiles, i18n, \"rewrite\", opts),\n fallback: applyLocaleToRoutes(rewrites.fallback, i18n, \"rewrite\", opts),\n };\n }\n\n const resolved: ResolvedNextConfig = {\n env: config.env ?? {},\n basePath: config.basePath ?? \"\",\n assetPrefix: normalizeAssetPrefix(config.assetPrefix),\n trailingSlash: config.trailingSlash ?? false,\n output: output === \"export\" || output === \"standalone\" ? output : \"\",\n pageExtensions,\n instrumentationClientInject: Array.isArray(config.instrumentationClientInject)\n ? (config.instrumentationClientInject as unknown[]).filter(\n (x): x is string => typeof x === \"string\",\n )\n : [],\n cacheComponents: config.cacheComponents ?? false,\n redirects,\n rewrites,\n headers,\n images: config.images,\n i18n,\n mdx,\n aliases,\n allowedDevOrigins,\n serverActionsAllowedOrigins,\n optimizePackageImports,\n inlineCss,\n serverActionsBodySizeLimit,\n expireTime: typeof config.expireTime === \"number\" ? config.expireTime : DEFAULT_EXPIRE_TIME,\n htmlLimitedBots,\n serverExternalPackages,\n cacheHandler,\n cacheMaxMemorySize,\n enablePrerenderSourceMaps: config.enablePrerenderSourceMaps ?? true,\n hashSalt,\n buildId,\n deploymentId,\n sassOptions: readOptionalRecord(config.sassOptions) ?? null,\n removeConsole:\n config.compiler?.removeConsole === true\n ? true\n : isUnknownRecord(config.compiler?.removeConsole)\n ? { exclude: readStringArray(config.compiler!.removeConsole.exclude) }\n : false,\n // Next.js stores this under `experimental.disableOptimizedLoading`.\n // Default `false` matches Next.js: page scripts get `defer` in <head>.\n disableOptimizedLoading: experimental?.disableOptimizedLoading === true,\n compilerDefine: serializeCompilerDefine(config.compiler?.define),\n compilerDefineServer: serializeCompilerDefine(config.compiler?.defineServer),\n clientTraceMetadata: Array.isArray(experimental?.clientTraceMetadata)\n ? (experimental.clientTraceMetadata as unknown[]).filter(\n (value): value is string => typeof value === \"string\",\n )\n : undefined,\n staleTimes: resolveStaleTimes(experimental),\n };\n\n // Auto-detect next-intl (lowest priority — explicit aliases from\n // webpack/turbopack already in `aliases` take precedence)\n detectNextIntlConfig(root, resolved);\n\n // Parity with Next.js: when `basePath` is configured but `assetPrefix` is\n // not, fall back to using `basePath` as the asset prefix. This ensures the\n // on-disk layout under `dist/client` is rooted at `<basePath>/_next/static/`\n // (matching the URL Vite emits via `base + assetsDir`), so Cloudflare's\n // ASSETS binding and the prod-server static layer can serve requests\n // verbatim without any runtime path rewriting.\n //\n // Mirrors Next.js: packages/next/src/server/config.ts:509-532\n // https://github.com/vercel/next.js/blob/canary/packages/next/src/server/config.ts\n // Conditions copied verbatim:\n // - `basePath !== \"\"` (skips when basePath is unset)\n // - `basePath !== \"/\"` (Next.js rejects this earlier, but we mirror the\n // guard so we don't silently produce `assetPrefix === \"/\"`)\n // - `assetPrefix === \"\"` (user did not explicitly opt out by setting it)\n if (resolved.basePath !== \"\" && resolved.basePath !== \"/\" && resolved.assetPrefix === \"\") {\n resolved.assetPrefix = resolved.basePath;\n }\n\n return resolved;\n}\n\nfunction normalizeAliasEntries(\n aliases: Record<string, unknown> | undefined,\n root: string,\n): Record<string, string> {\n if (!aliases) return {};\n\n const normalized: Record<string, string> = {};\n for (const [key, value] of Object.entries(aliases)) {\n if (typeof value !== \"string\") continue;\n normalized[key] = path.isAbsolute(value) ? value : path.resolve(root, value);\n }\n return normalized;\n}\n\nfunction extractTurboAliases(config: NextConfig, root: string): Record<string, string> {\n const experimental = readOptionalRecord(config.experimental);\n const experimentalTurbo = readOptionalRecord(experimental?.turbo);\n const topLevelTurbopack = readOptionalRecord(config.turbopack);\n\n return {\n ...normalizeAliasEntries(readOptionalRecord(experimentalTurbo?.resolveAlias), root),\n ...normalizeAliasEntries(readOptionalRecord(topLevelTurbopack?.resolveAlias), root),\n };\n}\n\nasync function probeWebpackConfig(\n config: NextConfig,\n root: string,\n): Promise<{ aliases: Record<string, string>; mdx: MdxOptions | null }> {\n if (typeof config.webpack !== \"function\") {\n return { aliases: {}, mdx: null };\n }\n\n // oxlint-disable-next-line typescript/no-explicit-any\n const mockModuleRules: any[] = [];\n const mockResolve: { alias: Record<string, unknown> } = { alias: {} };\n const mockConfig = {\n context: root,\n resolve: mockResolve,\n module: { rules: mockModuleRules },\n // oxlint-disable-next-line typescript/no-explicit-any\n plugins: [] as any[],\n };\n const mockOptions = {\n defaultLoaders: { babel: { loader: \"next-babel-loader\" } },\n isServer: false,\n dev: false,\n dir: root,\n };\n\n try {\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n const result = await (config.webpack as Function)(mockConfig, mockOptions);\n const finalConfig = result ?? mockConfig;\n // oxlint-disable-next-line typescript/no-explicit-any\n const rules: any[] = finalConfig.module?.rules ?? mockModuleRules;\n // Invoke loader callbacks for any side effects on `process.env`.\n // Next.js webpack loaders sometimes mutate `process.env.X = ...` at\n // compile time (see issue #1500), and vinext otherwise never sees the\n // value because we don't run the webpack loader pipeline. Calling each\n // loader once with a dummy source lets build-time env mutations land in\n // the shared Node process so they become visible to defines and\n // server-side code during the same build.\n invokeLoaderSideEffects(rules, root);\n return {\n aliases: normalizeAliasEntries(finalConfig.resolve?.alias, root),\n mdx: extractMdxOptionsFromRules(rules),\n };\n } catch {\n return { aliases: {}, mdx: null };\n }\n}\n\n/**\n * Walk webpack module rules and invoke each referenced loader once with a\n * dummy source string. Loaders that mutate `process.env` at compile time (a\n * pattern supported by Next.js' webpack pipeline — see issue #1500) get a\n * chance to land their mutations before vinext computes its defines.\n * Failures are swallowed: a loader throwing on dummy input must not break\n * the build, since vinext doesn't actually use the loader's transform output.\n */\n// oxlint-disable-next-line typescript/no-explicit-any\nfunction invokeLoaderSideEffects(rules: any[], root: string): void {\n const require = createRequire(path.join(root, \"package.json\"));\n const seen = new Set<unknown>();\n\n // oxlint-disable-next-line typescript/no-explicit-any\n const invokeLoaderEntry = (entry: any, ruleOptions?: unknown): void => {\n if (!entry) return;\n let loaderPath: string | undefined;\n let loaderFn: unknown;\n let options: unknown = ruleOptions;\n if (typeof entry === \"string\") {\n loaderPath = entry;\n } else if (typeof entry === \"function\") {\n loaderFn = entry;\n } else if (typeof entry === \"object\") {\n // oxlint-disable-next-line typescript/no-explicit-any\n const e = entry as any;\n if (typeof e.loader === \"string\") loaderPath = e.loader;\n else if (typeof e.loader === \"function\") loaderFn = e.loader;\n if (e.options !== undefined) options = e.options;\n }\n if (loaderPath !== undefined) {\n if (seen.has(loaderPath)) return;\n seen.add(loaderPath);\n // Skip well-known framework loaders. These don't typically mutate\n // process.env and may pull in heavy dependencies or fail to resolve\n // outside webpack's loader runtime.\n if (\n loaderPath.includes(\"next-babel-loader\") ||\n loaderPath.includes(\"mdx\") ||\n loaderPath.startsWith(\"next/dist/build/webpack\")\n ) {\n return;\n }\n try {\n loaderFn = require(loaderPath);\n if (\n loaderFn &&\n typeof loaderFn === \"object\" &&\n // oxlint-disable-next-line typescript/no-explicit-any\n typeof (loaderFn as any).default === \"function\"\n ) {\n // oxlint-disable-next-line typescript/no-explicit-any\n loaderFn = (loaderFn as any).default;\n }\n } catch {\n return;\n }\n }\n if (typeof loaderFn !== \"function\") return;\n if (seen.has(loaderFn)) return;\n seen.add(loaderFn);\n try {\n // Mimic the webpack loader runtime: `this` carries getOptions(),\n // query, callback(), async(), etc. We stub the minimum a typical\n // loader might touch. We don't care about the return value — only\n // side effects on process.env.\n const loaderThis = {\n async: () => () => {},\n callback: () => {},\n emitError: () => {},\n emitWarning: () => {},\n cacheable: () => {},\n getOptions: () => options ?? {},\n query: options ?? {},\n resourcePath: \"\",\n resource: \"\",\n rootContext: root,\n context: root,\n mode: \"production\",\n };\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n (loaderFn as Function).call(loaderThis, \"\");\n } catch {\n // Ignore — the loader may have thrown on the dummy source.\n // process.env mutations made before the throw still apply.\n }\n };\n\n // oxlint-disable-next-line typescript/no-explicit-any\n const visit = (rule: any): void => {\n if (!rule || typeof rule !== \"object\") return;\n if (Array.isArray(rule)) {\n for (const child of rule) visit(child);\n return;\n }\n if (Array.isArray(rule.oneOf)) for (const child of rule.oneOf) visit(child);\n if (Array.isArray(rule.rules)) for (const child of rule.rules) visit(child);\n const uses = Array.isArray(rule.use) ? rule.use : rule.use ? [rule.use] : [];\n for (const use of uses) invokeLoaderEntry(use);\n if (rule.loader !== undefined) invokeLoaderEntry(rule.loader, rule.options);\n };\n\n for (const rule of rules) visit(rule);\n}\n\n/**\n * Extract MDX compilation options (remark/rehype/recma plugins) from\n * a Next.js config that uses @next/mdx.\n *\n * @next/mdx wraps the config with a webpack function that injects an MDX\n * loader rule. The remark/rehype plugins are captured in that closure.\n * We probe the webpack function with a mock config to extract them.\n */\nexport async function extractMdxOptions(\n config: NextConfig,\n root: string = process.cwd(),\n): Promise<MdxOptions | null> {\n return (await probeWebpackConfig(config, root)).mdx;\n}\n\n/**\n * Probe file candidates relative to root. Returns the first one that exists,\n * or null if none match.\n */\nfunction probeFiles(root: string, candidates: string[]): string | null {\n for (const candidate of candidates) {\n const abs = path.resolve(root, candidate);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\nconst I18N_REQUEST_CANDIDATES = [\n \"i18n/request.ts\",\n \"i18n/request.tsx\",\n \"i18n/request.js\",\n \"i18n/request.jsx\",\n \"src/i18n/request.ts\",\n \"src/i18n/request.tsx\",\n \"src/i18n/request.js\",\n \"src/i18n/request.jsx\",\n];\n\n/**\n * Detect next-intl in the project and auto-register the `next-intl/config`\n * alias if needed.\n *\n * next-intl's `createNextIntlPlugin()` crashes in vinext because it calls\n * `require('next/package.json')` to check the Next.js version. Instead,\n * vinext detects next-intl and registers the alias automatically.\n *\n * Note: `require.resolve('next-intl')` walks up to parent `node_modules`\n * directories via standard Node module resolution. In a monorepo, next-intl\n * installed at the workspace root will trigger detection even if not listed\n * in the project's own package.json. This is acceptable since a workspace-root\n * install implies the user wants it available.\n *\n * Mutates `resolved.aliases` and `resolved.env` in place.\n */\nexport function detectNextIntlConfig(root: string, resolved: ResolvedNextConfig): void {\n // Explicit alias wins — user or plugin already set it\n if (resolved.aliases[\"next-intl/config\"]) return;\n\n // Check if next-intl is installed (use main entry — some packages\n // don't expose ./package.json in their exports map)\n const require = createRequire(path.join(root, \"package.json\"));\n try {\n require.resolve(\"next-intl\");\n } catch {\n return; // next-intl not installed\n }\n\n // Probe for the i18n request config file\n const configPath = probeFiles(root, I18N_REQUEST_CANDIDATES);\n if (!configPath) return;\n\n resolved.aliases[\"next-intl/config\"] = configPath;\n\n if (resolved.trailingSlash) {\n resolved.env._next_intl_trailing_slash = \"true\";\n }\n}\n\n// oxlint-disable-next-line typescript/no-explicit-any\nfunction extractMdxOptionsFromRules(rules: any[]): MdxOptions | null {\n // Search through webpack rules for the MDX loader injected by @next/mdx\n for (const rule of rules) {\n const loaders = extractMdxLoaders(rule);\n if (loaders) return loaders;\n }\n return null;\n}\n\n/**\n * Recursively search a webpack rule (which may have nested `oneOf` arrays)\n * for an MDX loader and extract its remark/rehype/recma plugin options.\n */\n// oxlint-disable-next-line typescript/no-explicit-any\nfunction extractMdxLoaders(rule: any): MdxOptions | null {\n if (!rule) return null;\n\n // Check `oneOf` arrays (Next.js uses these extensively)\n if (Array.isArray(rule.oneOf)) {\n for (const child of rule.oneOf) {\n const result = extractMdxLoaders(child);\n if (result) return result;\n }\n }\n\n // Check `use` array (loader chain)\n const use = Array.isArray(rule.use) ? rule.use : rule.use ? [rule.use] : [];\n for (const loader of use) {\n const loaderPath = typeof loader === \"string\" ? loader : loader?.loader;\n if (typeof loaderPath === \"string\" && isMdxLoader(loaderPath)) {\n const opts = typeof loader === \"object\" ? loader.options : {};\n return extractPluginsFromOptions(opts);\n }\n }\n\n // Check direct `loader` field\n if (typeof rule.loader === \"string\" && isMdxLoader(rule.loader)) {\n return extractPluginsFromOptions(rule.options);\n }\n\n return null;\n}\n\nfunction isMdxLoader(loaderPath: string): boolean {\n return (\n loaderPath.includes(\"mdx\") &&\n (loaderPath.includes(\"@next\") ||\n loaderPath.includes(\"@mdx-js\") ||\n loaderPath.includes(\"mdx-js-loader\") ||\n loaderPath.includes(\"next-mdx\"))\n );\n}\n\n// oxlint-disable-next-line typescript/no-explicit-any\nfunction extractPluginsFromOptions(opts: any): MdxOptions | null {\n if (!opts || typeof opts !== \"object\") return null;\n\n const remarkPlugins = Array.isArray(opts.remarkPlugins) ? opts.remarkPlugins : undefined;\n const rehypePlugins = Array.isArray(opts.rehypePlugins) ? opts.rehypePlugins : undefined;\n const recmaPlugins = Array.isArray(opts.recmaPlugins) ? opts.recmaPlugins : undefined;\n\n // Only return if at least one plugin array is non-empty\n if (\n (remarkPlugins && remarkPlugins.length > 0) ||\n (rehypePlugins && rehypePlugins.length > 0) ||\n (recmaPlugins && recmaPlugins.length > 0)\n ) {\n return {\n ...(remarkPlugins && remarkPlugins.length > 0 ? { remarkPlugins } : {}),\n ...(rehypePlugins && rehypePlugins.length > 0 ? { rehypePlugins } : {}),\n ...(recmaPlugins && recmaPlugins.length > 0 ? { recmaPlugins } : {}),\n };\n }\n\n return null;\n}\n\nexport { PHASE_PRODUCTION_BUILD } from \"vinext/shims/constants\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,mBAAmB,OAAmD;CACpF,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,IAAI,OAAO;CAC7D,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,QAAQ,GAAG,MAAM,IAAI,MAAM,kDAAkD,QAAQ;EACzF,OAAO;;CAGT,MAAM,QADU,MAAM,MACD,CAAC,MAAM,2CAA2C;CACvE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-paths.js","names":[],"sources":["../../src/config/tsconfig-paths.ts"],"sourcesContent":["/**\n * tsconfig.json `compilerOptions.paths` loader.\n *\n * Used to make tsconfig path aliases (e.g. `@/foo` mapping to `./src/foo`)\n * available when vinext loads `next.config.ts` through Vite's `runnerImport`.\n *\n * Next.js's own `next.config.ts` loader (packages/next/src/build/next-config-ts/\n * transpile-config.ts) reads `compilerOptions.paths` from the project's\n * `tsconfig.json` and passes them to SWC so that imports like\n * `import { foo } from '@/foo'` resolve at config load time. We do the same\n * here, but as Vite `resolve.alias` entries.\n *\n * The implementation is intentionally minimal:\n * - Static JSON-style parse of tsconfig.json (handles trailing commas /\n * comments via the shared `parseStaticObjectLiteral` helper)\n * - `extends` is followed up to a small recursion depth, with cycle\n * detection — matches the subset Next.js supports\n * - Only the common `\"@/*\": [\"./src/*\"]` / `\"@/*\": [\"src/*\"]` pattern is\n * supported; non-wildcard paths and exact aliases also work\n * - Returned alias values are always absolute paths so they work with\n * `runnerImport`'s inline environment (which has its own root).\n */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport { parseStaticObjectLiteral } from \"../plugins/fonts.js\";\n\nconst TSCONFIG_FILES = [\"tsconfig.json\", \"jsconfig.json\"];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction resolveTsconfigPathCandidate(candidate: string): string | null {\n const candidates = candidate.endsWith(\".json\")\n ? [candidate]\n : [candidate, `${candidate}.json`, path.join(candidate, \"tsconfig.json\")];\n\n for (const item of candidates) {\n if (fs.existsSync(item) && fs.statSync(item).isFile()) {\n return item;\n }\n }\n\n return null;\n}\n\nfunction resolveTsconfigExtends(configPath: string, specifier: string): string | null {\n const fromDir = path.dirname(configPath);\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\") || specifier.startsWith(\"\\\\\")) {\n return resolveTsconfigPathCandidate(path.resolve(fromDir, specifier));\n }\n\n const requireFromConfig = createRequire(configPath);\n const candidates = [specifier, `${specifier}.json`, path.join(specifier, \"tsconfig.json\")];\n\n for (const item of candidates) {\n try {\n return requireFromConfig.resolve(item);\n } catch {}\n }\n\n return null;\n}\n\nfunction materializeAliases(\n pathsConfig: Record<string, unknown>,\n baseUrl: string,\n): Record<string, string> {\n const aliases: Record<string, string> = {};\n\n for (const [find, rawTargets] of Object.entries(pathsConfig)) {\n const target = Array.isArray(rawTargets)\n ? rawTargets.find((value): value is string => typeof value === \"string\")\n : typeof rawTargets === \"string\"\n ? rawTargets\n : null;\n if (!target) continue;\n\n if (find.includes(\"*\") || target.includes(\"*\")) {\n // Only support trailing wildcard (the common `\"@/*\": [\"./src/*\"]` form).\n if (!find.endsWith(\"/*\") || !target.endsWith(\"/*\")) continue;\n if (find.indexOf(\"*\") !== find.length - 1 || target.indexOf(\"*\") !== target.length - 1) {\n continue;\n }\n\n const aliasKey = find.slice(0, -2);\n const targetDir = target.slice(0, -2);\n if (!aliasKey || !targetDir) continue;\n\n aliases[aliasKey] = path.resolve(baseUrl, targetDir);\n continue;\n }\n\n aliases[find] = path.resolve(baseUrl, target);\n }\n\n return aliases;\n}\n\nfunction loadAliasesFromTsconfigFile(\n configPath: string,\n seen: Set<string>,\n): Record<string, string> {\n if (seen.has(configPath)) return {};\n seen.add(configPath);\n\n let parsed: Record<string, unknown> | null = null;\n try {\n parsed = parseStaticObjectLiteral(fs.readFileSync(configPath, \"utf-8\"));\n } catch {\n return {};\n }\n if (!parsed) return {};\n\n let aliases: Record<string, string> = {};\n if (typeof parsed.extends === \"string\") {\n const extendedPath = resolveTsconfigExtends(configPath, parsed.extends);\n if (extendedPath) {\n aliases = loadAliasesFromTsconfigFile(extendedPath, seen);\n }\n }\n\n const compilerOptions = isRecord(parsed.compilerOptions) ? parsed.compilerOptions : null;\n const pathsConfig =\n compilerOptions && isRecord(compilerOptions.paths) ? compilerOptions.paths : null;\n if (!pathsConfig) return aliases;\n\n const baseUrl =\n compilerOptions && typeof compilerOptions.baseUrl === \"string\" ? compilerOptions.baseUrl : \".\";\n const resolvedBaseUrl = path.resolve(path.dirname(configPath), baseUrl);\n\n return {\n ...aliases,\n ...materializeAliases(pathsConfig, resolvedBaseUrl),\n };\n}\n\n/**\n * Read the project's tsconfig.json (or jsconfig.json) and return its\n * `compilerOptions.paths` as absolute-path Vite `resolve.alias` entries.\n *\n * Returns an empty object if no config is found or no paths are configured.\n * Errors during parsing are swallowed — this is a best-effort helper that\n * must not break config loading.\n */\nexport function loadTsconfigPathAliasesForRoot(projectRoot: string): Record<string, string> {\n for (const name of TSCONFIG_FILES) {\n const candidate = path.join(projectRoot, name);\n if (!fs.existsSync(candidate)) continue;\n return loadAliasesFromTsconfigFile(candidate, new Set());\n }\n return {};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,iBAAiB,CAAC,iBAAiB,gBAAgB;AAEzD,SAAS,SAAS,OAAkD;CAClE,OAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM;;AAGtE,SAAS,6BAA6B,WAAkC;CACtE,MAAM,aAAa,UAAU,SAAS,QAAQ,GAC1C,CAAC,UAAU,GACX;EAAC;EAAW,GAAG,UAAU;EAAQ,KAAK,KAAK,WAAW,gBAAgB;EAAC;CAE3E,KAAK,MAAM,QAAQ,YACjB,IAAI,GAAG,WAAW,KAAK,IAAI,GAAG,SAAS,KAAK,CAAC,QAAQ,EACnD,OAAO;CAIX,OAAO;;AAGT,SAAS,uBAAuB,YAAoB,WAAkC;CACpF,MAAM,UAAU,KAAK,QAAQ,WAAW;CACxC,IAAI,UAAU,WAAW,IAAI,IAAI,UAAU,WAAW,IAAI,IAAI,UAAU,WAAW,KAAK,EACtF,OAAO,6BAA6B,KAAK,QAAQ,SAAS,UAAU,CAAC;CAGvE,MAAM,oBAAoB,cAAc,WAAW;CACnD,MAAM,aAAa;EAAC;EAAW,GAAG,UAAU;EAAQ,KAAK,KAAK,WAAW,gBA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