vinext 0.0.52 → 0.0.54

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 (330) hide show
  1. package/README.md +1 -1
  2. package/dist/build/clean-output.d.ts +14 -0
  3. package/dist/build/clean-output.js +36 -0
  4. package/dist/build/clean-output.js.map +1 -0
  5. package/dist/build/inline-css.d.ts +7 -0
  6. package/dist/build/inline-css.js +50 -0
  7. package/dist/build/inline-css.js.map +1 -0
  8. package/dist/build/prerender.d.ts +6 -2
  9. package/dist/build/prerender.js +51 -12
  10. package/dist/build/prerender.js.map +1 -1
  11. package/dist/build/run-prerender.js +10 -1
  12. package/dist/build/run-prerender.js.map +1 -1
  13. package/dist/build/static-export.d.ts +5 -0
  14. package/dist/build/static-export.js +8 -3
  15. package/dist/build/static-export.js.map +1 -1
  16. package/dist/check.js +4 -0
  17. package/dist/check.js.map +1 -1
  18. package/dist/cli.js +19 -4
  19. package/dist/cli.js.map +1 -1
  20. package/dist/client/instrumentation-client-inject.d.ts +34 -0
  21. package/dist/client/instrumentation-client-inject.js +57 -0
  22. package/dist/client/instrumentation-client-inject.js.map +1 -0
  23. package/dist/client/navigation-runtime.d.ts +16 -2
  24. package/dist/client/navigation-runtime.js +16 -1
  25. package/dist/client/navigation-runtime.js.map +1 -1
  26. package/dist/client/vinext-next-data.d.ts +2 -1
  27. package/dist/client/vinext-next-data.js.map +1 -1
  28. package/dist/client/window-next.d.ts +17 -2
  29. package/dist/client/window-next.js.map +1 -1
  30. package/dist/cloudflare/tpr.js +1 -1
  31. package/dist/cloudflare/tpr.js.map +1 -1
  32. package/dist/config/config-matchers.js +2 -1
  33. package/dist/config/config-matchers.js.map +1 -1
  34. package/dist/config/next-config.d.ts +95 -4
  35. package/dist/config/next-config.js +173 -14
  36. package/dist/config/next-config.js.map +1 -1
  37. package/dist/deploy.js +42 -7
  38. package/dist/deploy.js.map +1 -1
  39. package/dist/entries/app-browser-entry.d.ts +11 -1
  40. package/dist/entries/app-browser-entry.js +16 -6
  41. package/dist/entries/app-browser-entry.js.map +1 -1
  42. package/dist/entries/app-rsc-entry.d.ts +12 -3
  43. package/dist/entries/app-rsc-entry.js +41 -8
  44. package/dist/entries/app-rsc-entry.js.map +1 -1
  45. package/dist/entries/app-rsc-manifest.d.ts +21 -1
  46. package/dist/entries/app-rsc-manifest.js +6 -4
  47. package/dist/entries/app-rsc-manifest.js.map +1 -1
  48. package/dist/entries/pages-client-entry.d.ts +4 -1
  49. package/dist/entries/pages-client-entry.js +40 -3
  50. package/dist/entries/pages-client-entry.js.map +1 -1
  51. package/dist/entries/pages-server-entry.js +292 -34
  52. package/dist/entries/pages-server-entry.js.map +1 -1
  53. package/dist/entries/runtime-entry-module.d.ts +1 -10
  54. package/dist/entries/runtime-entry-module.js +2 -12
  55. package/dist/entries/runtime-entry-module.js.map +1 -1
  56. package/dist/index.js +91 -10
  57. package/dist/index.js.map +1 -1
  58. package/dist/plugins/fonts.js +25 -2
  59. package/dist/plugins/fonts.js.map +1 -1
  60. package/dist/plugins/remove-console.d.ts +16 -0
  61. package/dist/plugins/remove-console.js +176 -0
  62. package/dist/plugins/remove-console.js.map +1 -0
  63. package/dist/routing/app-route-graph.d.ts +24 -1
  64. package/dist/routing/app-route-graph.js +52 -4
  65. package/dist/routing/app-route-graph.js.map +1 -1
  66. package/dist/routing/app-router.d.ts +2 -2
  67. package/dist/routing/app-router.js +2 -2
  68. package/dist/routing/app-router.js.map +1 -1
  69. package/dist/routing/file-matcher.d.ts +21 -1
  70. package/dist/routing/file-matcher.js +39 -1
  71. package/dist/routing/file-matcher.js.map +1 -1
  72. package/dist/routing/pages-router.d.ts +1 -1
  73. package/dist/routing/pages-router.js +10 -3
  74. package/dist/routing/pages-router.js.map +1 -1
  75. package/dist/routing/route-trie.js +13 -18
  76. package/dist/routing/route-trie.js.map +1 -1
  77. package/dist/routing/utils.d.ts +11 -1
  78. package/dist/routing/utils.js +15 -1
  79. package/dist/routing/utils.js.map +1 -1
  80. package/dist/server/api-handler.js +19 -10
  81. package/dist/server/api-handler.js.map +1 -1
  82. package/dist/server/app-browser-action-result.d.ts +16 -1
  83. package/dist/server/app-browser-action-result.js +15 -1
  84. package/dist/server/app-browser-action-result.js.map +1 -1
  85. package/dist/server/app-browser-entry.js +47 -28
  86. package/dist/server/app-browser-entry.js.map +1 -1
  87. package/dist/server/app-browser-navigation-controller.d.ts +2 -0
  88. package/dist/server/app-browser-navigation-controller.js +4 -0
  89. package/dist/server/app-browser-navigation-controller.js.map +1 -1
  90. package/dist/server/app-elements-wire.d.ts +13 -4
  91. package/dist/server/app-elements-wire.js +10 -1
  92. package/dist/server/app-elements-wire.js.map +1 -1
  93. package/dist/server/app-elements.d.ts +2 -2
  94. package/dist/server/app-elements.js +2 -2
  95. package/dist/server/app-elements.js.map +1 -1
  96. package/dist/server/app-fallback-renderer.d.ts +27 -8
  97. package/dist/server/app-fallback-renderer.js +19 -8
  98. package/dist/server/app-fallback-renderer.js.map +1 -1
  99. package/dist/server/app-history-state.js +6 -2
  100. package/dist/server/app-history-state.js.map +1 -1
  101. package/dist/server/app-inline-css-client.d.ts +7 -0
  102. package/dist/server/app-inline-css-client.js +37 -0
  103. package/dist/server/app-inline-css-client.js.map +1 -0
  104. package/dist/server/app-interception-context-header.d.ts +33 -0
  105. package/dist/server/app-interception-context-header.js +44 -0
  106. package/dist/server/app-interception-context-header.js.map +1 -0
  107. package/dist/server/app-mounted-slots-header.d.ts +19 -0
  108. package/dist/server/app-mounted-slots-header.js +40 -1
  109. package/dist/server/app-mounted-slots-header.js.map +1 -1
  110. package/dist/server/app-optimistic-routing.js +26 -18
  111. package/dist/server/app-optimistic-routing.js.map +1 -1
  112. package/dist/server/app-page-boundary-render.d.ts +1 -0
  113. package/dist/server/app-page-boundary-render.js +2 -0
  114. package/dist/server/app-page-boundary-render.js.map +1 -1
  115. package/dist/server/app-page-boundary.d.ts +22 -1
  116. package/dist/server/app-page-boundary.js +30 -3
  117. package/dist/server/app-page-boundary.js.map +1 -1
  118. package/dist/server/app-page-cache.d.ts +9 -3
  119. package/dist/server/app-page-cache.js +14 -8
  120. package/dist/server/app-page-cache.js.map +1 -1
  121. package/dist/server/app-page-dispatch.d.ts +13 -1
  122. package/dist/server/app-page-dispatch.js +136 -82
  123. package/dist/server/app-page-dispatch.js.map +1 -1
  124. package/dist/server/app-page-element-builder.d.ts +2 -1
  125. package/dist/server/app-page-element-builder.js +17 -30
  126. package/dist/server/app-page-element-builder.js.map +1 -1
  127. package/dist/server/app-page-execution.d.ts +1 -0
  128. package/dist/server/app-page-execution.js +2 -0
  129. package/dist/server/app-page-execution.js.map +1 -1
  130. package/dist/server/app-page-head.d.ts +1 -0
  131. package/dist/server/app-page-head.js +8 -0
  132. package/dist/server/app-page-head.js.map +1 -1
  133. package/dist/server/app-page-render-identity.d.ts +22 -0
  134. package/dist/server/app-page-render-identity.js +42 -0
  135. package/dist/server/app-page-render-identity.js.map +1 -0
  136. package/dist/server/app-page-render-observation.js +1 -1
  137. package/dist/server/app-page-render.d.ts +9 -1
  138. package/dist/server/app-page-render.js +8 -2
  139. package/dist/server/app-page-render.js.map +1 -1
  140. package/dist/server/app-page-request.d.ts +6 -3
  141. package/dist/server/app-page-request.js +5 -2
  142. package/dist/server/app-page-request.js.map +1 -1
  143. package/dist/server/app-page-response.d.ts +11 -1
  144. package/dist/server/app-page-response.js +16 -4
  145. package/dist/server/app-page-response.js.map +1 -1
  146. package/dist/server/app-page-route-wiring.d.ts +16 -0
  147. package/dist/server/app-page-route-wiring.js +25 -10
  148. package/dist/server/app-page-route-wiring.js.map +1 -1
  149. package/dist/server/app-page-stream.d.ts +12 -0
  150. package/dist/server/app-page-stream.js +3 -0
  151. package/dist/server/app-page-stream.js.map +1 -1
  152. package/dist/server/app-route-handler-dispatch.d.ts +1 -0
  153. package/dist/server/app-route-handler-dispatch.js +3 -0
  154. package/dist/server/app-route-handler-dispatch.js.map +1 -1
  155. package/dist/server/app-route-handler-execution.d.ts +1 -0
  156. package/dist/server/app-route-handler-execution.js +1 -0
  157. package/dist/server/app-route-handler-execution.js.map +1 -1
  158. package/dist/server/app-route-handler-response.js +38 -6
  159. package/dist/server/app-route-handler-response.js.map +1 -1
  160. package/dist/server/app-rsc-handler.d.ts +16 -3
  161. package/dist/server/app-rsc-handler.js +60 -11
  162. package/dist/server/app-rsc-handler.js.map +1 -1
  163. package/dist/server/app-rsc-request-normalization.d.ts +2 -1
  164. package/dist/server/app-rsc-request-normalization.js +6 -4
  165. package/dist/server/app-rsc-request-normalization.js.map +1 -1
  166. package/dist/server/app-segment-config.d.ts +4 -1
  167. package/dist/server/app-segment-config.js +6 -1
  168. package/dist/server/app-segment-config.js.map +1 -1
  169. package/dist/server/app-server-action-execution.d.ts +22 -3
  170. package/dist/server/app-server-action-execution.js +46 -7
  171. package/dist/server/app-server-action-execution.js.map +1 -1
  172. package/dist/server/app-ssr-entry.d.ts +6 -0
  173. package/dist/server/app-ssr-entry.js +57 -6
  174. package/dist/server/app-ssr-entry.js.map +1 -1
  175. package/dist/server/app-ssr-error-meta.js +3 -3
  176. package/dist/server/app-ssr-error-meta.js.map +1 -1
  177. package/dist/server/app-ssr-stream.d.ts +25 -1
  178. package/dist/server/app-ssr-stream.js +237 -19
  179. package/dist/server/app-ssr-stream.js.map +1 -1
  180. package/dist/server/app-static-generation.d.ts +1 -0
  181. package/dist/server/app-static-generation.js +2 -1
  182. package/dist/server/app-static-generation.js.map +1 -1
  183. package/dist/server/client-trace-metadata.d.ts +31 -0
  184. package/dist/server/client-trace-metadata.js +83 -0
  185. package/dist/server/client-trace-metadata.js.map +1 -0
  186. package/dist/server/cookie-utils.d.ts +13 -0
  187. package/dist/server/cookie-utils.js +20 -0
  188. package/dist/server/cookie-utils.js.map +1 -0
  189. package/dist/server/default-not-found-module.d.ts +20 -0
  190. package/dist/server/default-not-found-module.js +20 -0
  191. package/dist/server/default-not-found-module.js.map +1 -0
  192. package/dist/server/dev-server.d.ts +8 -1
  193. package/dist/server/dev-server.js +56 -11
  194. package/dist/server/dev-server.js.map +1 -1
  195. package/dist/server/headers.d.ts +5 -1
  196. package/dist/server/headers.js +5 -1
  197. package/dist/server/headers.js.map +1 -1
  198. package/dist/server/html.d.ts +2 -1
  199. package/dist/server/html.js +6 -1
  200. package/dist/server/html.js.map +1 -1
  201. package/dist/server/image-optimization.d.ts +13 -4
  202. package/dist/server/image-optimization.js +15 -4
  203. package/dist/server/image-optimization.js.map +1 -1
  204. package/dist/server/isr-cache.d.ts +7 -5
  205. package/dist/server/isr-cache.js +17 -6
  206. package/dist/server/isr-cache.js.map +1 -1
  207. package/dist/server/middleware-runtime.js +1 -2
  208. package/dist/server/middleware-runtime.js.map +1 -1
  209. package/dist/server/middleware.js +1 -1
  210. package/dist/server/middleware.js.map +1 -1
  211. package/dist/server/pages-api-route.d.ts +18 -0
  212. package/dist/server/pages-api-route.js +3 -1
  213. package/dist/server/pages-api-route.js.map +1 -1
  214. package/dist/server/pages-body-parser-config.d.ts +60 -0
  215. package/dist/server/pages-body-parser-config.js +79 -0
  216. package/dist/server/pages-body-parser-config.js.map +1 -0
  217. package/dist/server/pages-data-route.js +1 -0
  218. package/dist/server/pages-data-route.js.map +1 -1
  219. package/dist/server/pages-default-404.d.ts +31 -0
  220. package/dist/server/pages-default-404.js +40 -0
  221. package/dist/server/pages-default-404.js.map +1 -0
  222. package/dist/server/pages-document-initial-props.d.ts +7 -0
  223. package/dist/server/pages-document-initial-props.js +14 -0
  224. package/dist/server/pages-document-initial-props.js.map +1 -0
  225. package/dist/server/pages-node-compat.d.ts +10 -0
  226. package/dist/server/pages-node-compat.js +12 -1
  227. package/dist/server/pages-node-compat.js.map +1 -1
  228. package/dist/server/pages-page-data.d.ts +40 -0
  229. package/dist/server/pages-page-data.js +19 -14
  230. package/dist/server/pages-page-data.js.map +1 -1
  231. package/dist/server/pages-page-method.d.ts +48 -0
  232. package/dist/server/pages-page-method.js +19 -0
  233. package/dist/server/pages-page-method.js.map +1 -0
  234. package/dist/server/pages-page-response.d.ts +8 -0
  235. package/dist/server/pages-page-response.js +21 -11
  236. package/dist/server/pages-page-response.js.map +1 -1
  237. package/dist/server/pages-serializable-props.d.ts +25 -0
  238. package/dist/server/pages-serializable-props.js +69 -0
  239. package/dist/server/pages-serializable-props.js.map +1 -0
  240. package/dist/server/prerender-route-params.d.ts +14 -0
  241. package/dist/server/prerender-route-params.js +94 -0
  242. package/dist/server/prerender-route-params.js.map +1 -0
  243. package/dist/server/prod-server.d.ts +3 -23
  244. package/dist/server/prod-server.js +43 -57
  245. package/dist/server/prod-server.js.map +1 -1
  246. package/dist/server/proxy-trust.d.ts +41 -0
  247. package/dist/server/proxy-trust.js +70 -0
  248. package/dist/server/proxy-trust.js.map +1 -0
  249. package/dist/server/request-pipeline.d.ts +3 -3
  250. package/dist/server/request-pipeline.js +5 -4
  251. package/dist/server/request-pipeline.js.map +1 -1
  252. package/dist/server/seed-cache.js +12 -6
  253. package/dist/server/seed-cache.js.map +1 -1
  254. package/dist/server/server-action-not-found.js +3 -2
  255. package/dist/server/server-action-not-found.js.map +1 -1
  256. package/dist/server/static-file-cache.js +2 -1
  257. package/dist/server/static-file-cache.js.map +1 -1
  258. package/dist/server/streaming-metadata.d.ts +5 -0
  259. package/dist/server/streaming-metadata.js +10 -0
  260. package/dist/server/streaming-metadata.js.map +1 -0
  261. package/dist/shims/app-router-scroll-state.d.ts +14 -0
  262. package/dist/shims/app-router-scroll-state.js +51 -0
  263. package/dist/shims/app-router-scroll-state.js.map +1 -0
  264. package/dist/shims/app-router-scroll.d.ts +28 -0
  265. package/dist/shims/app-router-scroll.js +115 -0
  266. package/dist/shims/app-router-scroll.js.map +1 -0
  267. package/dist/shims/before-interactive-context.d.ts +30 -0
  268. package/dist/shims/before-interactive-context.js +10 -0
  269. package/dist/shims/before-interactive-context.js.map +1 -0
  270. package/dist/shims/cache-runtime.d.ts +1 -1
  271. package/dist/shims/cache-runtime.js +14 -1
  272. package/dist/shims/cache-runtime.js.map +1 -1
  273. package/dist/shims/cache.d.ts +6 -0
  274. package/dist/shims/cache.js +7 -0
  275. package/dist/shims/cache.js.map +1 -1
  276. package/dist/shims/default-not-found.d.ts +12 -0
  277. package/dist/shims/default-not-found.js +61 -0
  278. package/dist/shims/default-not-found.js.map +1 -0
  279. package/dist/shims/error.js +3 -0
  280. package/dist/shims/error.js.map +1 -1
  281. package/dist/shims/font-local.d.ts +5 -0
  282. package/dist/shims/font-local.js +6 -2
  283. package/dist/shims/font-local.js.map +1 -1
  284. package/dist/shims/head.js +4 -4
  285. package/dist/shims/head.js.map +1 -1
  286. package/dist/shims/headers.d.ts +13 -2
  287. package/dist/shims/headers.js +73 -22
  288. package/dist/shims/headers.js.map +1 -1
  289. package/dist/shims/image.d.ts +1 -1
  290. package/dist/shims/image.js +4 -4
  291. package/dist/shims/image.js.map +1 -1
  292. package/dist/shims/internal/app-route-detection.d.ts +37 -0
  293. package/dist/shims/internal/app-route-detection.js +69 -0
  294. package/dist/shims/internal/app-route-detection.js.map +1 -0
  295. package/dist/shims/internal/pages-data-target.d.ts +58 -0
  296. package/dist/shims/internal/pages-data-target.js +91 -0
  297. package/dist/shims/internal/pages-data-target.js.map +1 -0
  298. package/dist/shims/internal/pages-data-url.d.ts +42 -0
  299. package/dist/shims/internal/pages-data-url.js +73 -0
  300. package/dist/shims/internal/pages-data-url.js.map +1 -0
  301. package/dist/shims/link.d.ts +18 -2
  302. package/dist/shims/link.js +129 -15
  303. package/dist/shims/link.js.map +1 -1
  304. package/dist/shims/metadata.d.ts +9 -7
  305. package/dist/shims/metadata.js +70 -7
  306. package/dist/shims/metadata.js.map +1 -1
  307. package/dist/shims/navigation.d.ts +1 -2
  308. package/dist/shims/navigation.js +94 -20
  309. package/dist/shims/navigation.js.map +1 -1
  310. package/dist/shims/router.d.ts +5 -0
  311. package/dist/shims/router.js +389 -80
  312. package/dist/shims/router.js.map +1 -1
  313. package/dist/shims/script.d.ts +11 -1
  314. package/dist/shims/script.js +158 -15
  315. package/dist/shims/script.js.map +1 -1
  316. package/dist/shims/server.js +1 -0
  317. package/dist/shims/server.js.map +1 -1
  318. package/dist/shims/url-utils.d.ts +2 -1
  319. package/dist/shims/url-utils.js +15 -4
  320. package/dist/shims/url-utils.js.map +1 -1
  321. package/dist/utils/html-limited-bots.d.ts +5 -0
  322. package/dist/utils/html-limited-bots.js +15 -0
  323. package/dist/utils/html-limited-bots.js.map +1 -0
  324. package/dist/utils/path.d.ts +13 -0
  325. package/dist/utils/path.js +16 -0
  326. package/dist/utils/path.js.map +1 -0
  327. package/dist/utils/query.d.ts +6 -0
  328. package/dist/utils/query.js +10 -1
  329. package/dist/utils/query.js.map +1 -1
  330. package/package.json +1 -1
@@ -1 +1 @@
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_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 // 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":";;;;;;;;;;;;;;;;AAkCA,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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C;CAMlE,MAAM,aAAa,WAA4B,WAAW,OAAO,CAAC,gBAAgB,KAAK;CAWvF,MAAM,iBAA2B,SAAS,aAAa,CAAC,KAAK,cAAc,GAAG,EAAE;CAEhF,MAAM,MAAW,EAAE;CACnB,KAAK,MAAM,KAAK,QAAQ;EACtB,IAAI,EAAE,WAAW,OAAO;GACtB,IAAI,KAAK,EAAE;GACX;;EAKF,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
+ {"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,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124
124
  contentSecurityPolicy?: string;
125
125
  }; /** Build output mode: 'export' for full static export, 'standalone' for single server */
126
126
  output?: "export" | "standalone"; /** File extensions treated as routable pages/routes (Next.js pageExtensions) */
127
- pageExtensions?: string[]; /** Extra origins allowed to access the dev server. */
127
+ pageExtensions?: string[];
128
+ /**
129
+ * Module specifiers that are required for side effects on the client before
130
+ * hydration, in array order, ahead of the user's `instrumentation-client.{ts,js}`.
131
+ * Each entry may be a bare npm package name or a path relative to the project root.
132
+ */
133
+ instrumentationClientInject?: string[]; /** Extra origins allowed to access the dev server. */
128
134
  allowedDevOrigins?: string[]; /** Maximum age in seconds for stale ISR entries before blocking regeneration. */
129
- expireTime?: number;
135
+ expireTime?: number; /** User agents that require blocking metadata in the initial head. */
136
+ htmlLimitedBots?: RegExp | string;
130
137
  /**
131
138
  * Enable Cache Components (Next.js 16).
132
139
  * When true, enables the "use cache" directive for pages, components, and functions.
@@ -147,6 +154,26 @@ type NextConfig = {
147
154
  */
148
155
  serverExternalPackages?: string[]; /** Webpack config (ignored — we use Vite) */
149
156
  webpack?: unknown;
157
+ /**
158
+ * Compiler options for build-time code transforms.
159
+ * vinext supports the subset that maps to Vite-compatible transforms.
160
+ */
161
+ compiler?: {
162
+ /** Remove `console.*` calls from the client bundle. */removeConsole?: boolean | {
163
+ exclude?: string[];
164
+ };
165
+ /**
166
+ * Inline compile-time constants in both client and server bundles.
167
+ * Mirrors Next.js `compiler.define`.
168
+ * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/compiler#define
169
+ */
170
+ define?: Record<string, string | number | boolean>;
171
+ /**
172
+ * Inline compile-time constants in server bundles only (not client).
173
+ * Mirrors Next.js `compiler.defineServer`.
174
+ */
175
+ defineServer?: Record<string, string | number | boolean>;
176
+ };
150
177
  /**
151
178
  * Path to a custom cache handler module (e.g., KV, Redis, DynamoDB).
152
179
  * Accepts relative paths, absolute paths, or file:// URLs from import.meta.resolve().
@@ -194,6 +221,7 @@ type ResolvedNextConfig = {
194
221
  trailingSlash: boolean;
195
222
  output: "" | "export" | "standalone";
196
223
  pageExtensions: string[];
224
+ instrumentationClientInject: string[];
197
225
  cacheComponents: boolean;
198
226
  redirects: NextRedirect[];
199
227
  rewrites: {
@@ -208,9 +236,11 @@ type ResolvedNextConfig = {
208
236
  aliases: Record<string, string>; /** Extra allowed origins for dev server access (from allowedDevOrigins). */
209
237
  allowedDevOrigins: string[]; /** Extra allowed origins for server action CSRF validation (from experimental.serverActions.allowedOrigins). */
210
238
  serverActionsAllowedOrigins: string[]; /** Packages whose barrel imports should be optimized (from experimental.optimizePackageImports). */
211
- optimizePackageImports: string[]; /** Parsed body size limit for server actions in bytes (from experimental.serverActions.bodySizeLimit). Defaults to 1MB. */
239
+ optimizePackageImports: string[]; /** Inline app CSS into production HTML (from experimental.inlineCss). */
240
+ inlineCss: boolean; /** Parsed body size limit for server actions in bytes (from experimental.serverActions.bodySizeLimit). Defaults to 1MB. */
212
241
  serverActionsBodySizeLimit: number; /** Route-level expire fallback in seconds for ISR entries with numeric revalidate. */
213
- expireTime: number;
242
+ expireTime: number; /** Serialized htmlLimitedBots regexp source from next.config. */
243
+ htmlLimitedBots: string | undefined;
214
244
  /**
215
245
  * Packages that should be treated as server-external (not bundled by Vite).
216
246
  * Sourced from `serverExternalPackages` or the legacy
@@ -248,6 +278,67 @@ type ResolvedNextConfig = {
248
278
  * the object is forwarded to Sass and may contain any modern Sass option.
249
279
  */
250
280
  sassOptions: Record<string, unknown> | null;
281
+ /**
282
+ * When enabled, strip `console.*` calls from the client bundle.
283
+ * Mirrors Next.js `compiler.removeConsole` option.
284
+ * `true` strips all console calls; `{ exclude: ["error"] }` strips all
285
+ * except the specified method names (case-insensitive).
286
+ */
287
+ removeConsole: boolean | {
288
+ exclude: string[];
289
+ };
290
+ /**
291
+ * Mirrors Next.js `experimental.disableOptimizedLoading`. When `false`
292
+ * (the default), Pages Router page scripts are emitted with `defer` in
293
+ * `<head>` so the browser can prefetch them in parallel with HTML parsing.
294
+ * When `true`, scripts are emitted without `defer` (legacy behaviour).
295
+ *
296
+ * See `.nextjs-ref/packages/next/src/pages/_document.tsx` (`getScripts` →
297
+ * `defer={!disableOptimizedLoading}`) and the upstream
298
+ * `test/e2e/optimized-loading` test fixture.
299
+ */
300
+ disableOptimizedLoading: boolean;
301
+ /**
302
+ * Build-time constant replacement map applied to BOTH client and server
303
+ * bundles. Sourced from `compiler.define` in next.config. Values are
304
+ * pre-serialized via `JSON.stringify` so they can be fed straight into
305
+ * Vite's `define` config (which expects strings of source code).
306
+ *
307
+ * Mirrors Next.js — strings, numbers, and booleans are accepted; other
308
+ * value shapes are dropped.
309
+ * @see https://nextjs.org/docs/app/api-reference/config/next-config-js/compiler#define
310
+ */
311
+ compilerDefine: Record<string, string>;
312
+ /**
313
+ * Build-time constant replacement map applied to SERVER bundles only
314
+ * (RSC + SSR + middleware). Sourced from `compiler.defineServer` in
315
+ * next.config. Same serialization rules as `compilerDefine`. Client
316
+ * bundles intentionally never see these substitutions, so referencing
317
+ * a `defineServer` identifier from the browser stays as the raw
318
+ * identifier (typically resolving to `undefined`).
319
+ */
320
+ compilerDefineServer: Record<string, string>;
321
+ /**
322
+ * Allow-list of keys, sourced from `experimental.clientTraceMetadata`,
323
+ * to forward from the active OpenTelemetry context into the SSR HTML head
324
+ * as `<meta>` tags. `undefined` (or empty) disables injection.
325
+ *
326
+ * Mirrors Next.js: packages/next/src/server/lib/trace/utils.ts (getTracedMetadata).
327
+ */
328
+ clientTraceMetadata: string[] | undefined;
329
+ /**
330
+ * App Router client cache freshness windows in seconds, sourced from
331
+ * `experimental.staleTimes`. Controls how long prefetched route segments
332
+ * are considered fresh in the client-side router cache.
333
+ *
334
+ * `dynamic` applies to partial/dynamic prefetches (default 0 — no reuse).
335
+ * `static` applies to full-route prefetches (default 300 — 5 minutes).
336
+ * Mirrors Next.js' `process.env.__NEXT_CLIENT_ROUTER_{DYNAMIC,STATIC}_STALETIME`.
337
+ */
338
+ staleTimes: {
339
+ dynamic: number;
340
+ static: number;
341
+ };
251
342
  };
252
343
  /**
253
344
  * Whole-word substring check for any of the CJS-style globals that the