@qzsy/vinext 0.1.7

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 (803) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +773 -0
  3. package/dist/build/assets-ignore.d.ts +32 -0
  4. package/dist/build/assets-ignore.js +48 -0
  5. package/dist/build/clean-output.d.ts +13 -0
  6. package/dist/build/clean-output.js +34 -0
  7. package/dist/build/client-build-config.d.ts +171 -0
  8. package/dist/build/client-build-config.js +270 -0
  9. package/dist/build/css-url-assets.d.ts +29 -0
  10. package/dist/build/css-url-assets.js +213 -0
  11. package/dist/build/google-fonts/build-url.d.ts +9 -0
  12. package/dist/build/google-fonts/build-url.js +28 -0
  13. package/dist/build/google-fonts/fallback-metrics-data.js +14029 -0
  14. package/dist/build/google-fonts/fallback-metrics.d.ts +12 -0
  15. package/dist/build/google-fonts/fallback-metrics.js +44 -0
  16. package/dist/build/google-fonts/find-font-files-in-css.d.ts +16 -0
  17. package/dist/build/google-fonts/find-font-files-in-css.js +28 -0
  18. package/dist/build/google-fonts/font-data.js +24983 -0
  19. package/dist/build/google-fonts/font-metadata.d.ts +16 -0
  20. package/dist/build/google-fonts/font-metadata.js +5 -0
  21. package/dist/build/google-fonts/get-axes.d.ts +6 -0
  22. package/dist/build/google-fonts/get-axes.js +37 -0
  23. package/dist/build/google-fonts/sort-variants.d.ts +4 -0
  24. package/dist/build/google-fonts/sort-variants.js +12 -0
  25. package/dist/build/google-fonts/validate.d.ts +27 -0
  26. package/dist/build/google-fonts/validate.js +54 -0
  27. package/dist/build/inline-css.d.ts +6 -0
  28. package/dist/build/inline-css.js +48 -0
  29. package/dist/build/layout-classification-types.d.ts +61 -0
  30. package/dist/build/layout-classification-types.js +1 -0
  31. package/dist/build/layout-classification.d.ts +59 -0
  32. package/dist/build/layout-classification.js +98 -0
  33. package/dist/build/next-client-runtime-manifests.d.ts +14 -0
  34. package/dist/build/next-client-runtime-manifests.js +39 -0
  35. package/dist/build/nitro-route-rules.d.ts +49 -0
  36. package/dist/build/nitro-route-rules.js +79 -0
  37. package/dist/build/precompress.d.ts +27 -0
  38. package/dist/build/precompress.js +110 -0
  39. package/dist/build/prerender.d.ts +209 -0
  40. package/dist/build/prerender.js +932 -0
  41. package/dist/build/report.d.ts +132 -0
  42. package/dist/build/report.js +504 -0
  43. package/dist/build/route-classification-injector.d.ts +34 -0
  44. package/dist/build/route-classification-injector.js +59 -0
  45. package/dist/build/route-classification-manifest.d.ts +52 -0
  46. package/dist/build/route-classification-manifest.js +143 -0
  47. package/dist/build/run-prerender.d.ts +61 -0
  48. package/dist/build/run-prerender.js +224 -0
  49. package/dist/build/server-manifest.d.ts +18 -0
  50. package/dist/build/server-manifest.js +22 -0
  51. package/dist/build/ssr-manifest.d.ts +18 -0
  52. package/dist/build/ssr-manifest.js +69 -0
  53. package/dist/build/standalone.d.ts +31 -0
  54. package/dist/build/standalone.js +203 -0
  55. package/dist/build/static-export.d.ts +55 -0
  56. package/dist/build/static-export.js +60 -0
  57. package/dist/cache/cache-adapters-virtual.d.ts +50 -0
  58. package/dist/cache/cache-adapters-virtual.js +45 -0
  59. package/dist/cache.d.ts +2 -0
  60. package/dist/cache.js +2 -0
  61. package/dist/check.d.ts +87 -0
  62. package/dist/check.js +1037 -0
  63. package/dist/cli-args.d.ts +33 -0
  64. package/dist/cli-args.js +124 -0
  65. package/dist/cli.d.ts +1 -0
  66. package/dist/cli.js +744 -0
  67. package/dist/client/app-nav-failure-handler.d.ts +8 -0
  68. package/dist/client/app-nav-failure-handler.js +44 -0
  69. package/dist/client/empty-module.d.ts +1 -0
  70. package/dist/client/empty-module.js +1 -0
  71. package/dist/client/instrumentation-client-inject.d.ts +33 -0
  72. package/dist/client/instrumentation-client-inject.js +55 -0
  73. package/dist/client/instrumentation-client-state.d.ts +9 -0
  74. package/dist/client/instrumentation-client-state.js +17 -0
  75. package/dist/client/instrumentation-client.d.ts +7 -0
  76. package/dist/client/instrumentation-client.js +6 -0
  77. package/dist/client/navigation-runtime.d.ts +70 -0
  78. package/dist/client/navigation-runtime.js +169 -0
  79. package/dist/client/pages-router-link-navigation.d.ts +61 -0
  80. package/dist/client/pages-router-link-navigation.js +42 -0
  81. package/dist/client/validate-module-path.d.ts +17 -0
  82. package/dist/client/validate-module-path.js +24 -0
  83. package/dist/client/vinext-next-data.d.ts +44 -0
  84. package/dist/client/vinext-next-data.js +50 -0
  85. package/dist/client/window-next.d.ts +168 -0
  86. package/dist/client/window-next.js +57 -0
  87. package/dist/cloudflare/index.d.ts +3 -0
  88. package/dist/cloudflare/index.js +3 -0
  89. package/dist/cloudflare/src/cache/cdn-adapter.runtime.js +102 -0
  90. package/dist/cloudflare/src/cache/kv-data-adapter.runtime.d.ts +126 -0
  91. package/dist/cloudflare/src/cache/kv-data-adapter.runtime.js +435 -0
  92. package/dist/cloudflare/src/utils/cache-control-metadata.js +20 -0
  93. package/dist/cloudflare/tpr.d.ts +82 -0
  94. package/dist/cloudflare/tpr.js +558 -0
  95. package/dist/config/config-matchers.d.ts +257 -0
  96. package/dist/config/config-matchers.js +1046 -0
  97. package/dist/config/dotenv.d.ts +56 -0
  98. package/dist/config/dotenv.js +88 -0
  99. package/dist/config/next-config.d.ts +540 -0
  100. package/dist/config/next-config.js +1050 -0
  101. package/dist/config/tsconfig-paths.d.ts +21 -0
  102. package/dist/config/tsconfig-paths.js +157 -0
  103. package/dist/deploy.d.ts +190 -0
  104. package/dist/deploy.js +1033 -0
  105. package/dist/entries/app-browser-entry.d.ts +29 -0
  106. package/dist/entries/app-browser-entry.js +83 -0
  107. package/dist/entries/app-rsc-entry.d.ts +81 -0
  108. package/dist/entries/app-rsc-entry.js +943 -0
  109. package/dist/entries/app-rsc-manifest.d.ts +53 -0
  110. package/dist/entries/app-rsc-manifest.js +294 -0
  111. package/dist/entries/app-ssr-entry.d.ts +15 -0
  112. package/dist/entries/app-ssr-entry.js +24 -0
  113. package/dist/entries/pages-client-entry.d.ts +11 -0
  114. package/dist/entries/pages-client-entry.js +204 -0
  115. package/dist/entries/pages-entry-helpers.d.ts +2 -0
  116. package/dist/entries/pages-entry-helpers.js +2 -0
  117. package/dist/entries/pages-server-entry.d.ts +11 -0
  118. package/dist/entries/pages-server-entry.js +398 -0
  119. package/dist/entries/runtime-entry-module.d.ts +25 -0
  120. package/dist/entries/runtime-entry-module.js +46 -0
  121. package/dist/index.d.ts +115 -0
  122. package/dist/index.js +2661 -0
  123. package/dist/init.d.ts +69 -0
  124. package/dist/init.js +253 -0
  125. package/dist/plugins/ast-utils.d.ts +20 -0
  126. package/dist/plugins/ast-utils.js +78 -0
  127. package/dist/plugins/async-hooks-stub.d.ts +18 -0
  128. package/dist/plugins/async-hooks-stub.js +40 -0
  129. package/dist/plugins/client-reference-dedup.d.ts +35 -0
  130. package/dist/plugins/client-reference-dedup.js +189 -0
  131. package/dist/plugins/css-data-url.d.ts +6 -0
  132. package/dist/plugins/css-data-url.js +83 -0
  133. package/dist/plugins/dynamic-preload-metadata.d.ts +13 -0
  134. package/dist/plugins/dynamic-preload-metadata.js +413 -0
  135. package/dist/plugins/extensionless-dynamic-import.d.ts +6 -0
  136. package/dist/plugins/extensionless-dynamic-import.js +155 -0
  137. package/dist/plugins/fonts.d.ts +95 -0
  138. package/dist/plugins/fonts.js +711 -0
  139. package/dist/plugins/import-meta-url.d.ts +16 -0
  140. package/dist/plugins/import-meta-url.js +353 -0
  141. package/dist/plugins/instrumentation-client.d.ts +6 -0
  142. package/dist/plugins/instrumentation-client.js +27 -0
  143. package/dist/plugins/middleware-export-validation.d.ts +5 -0
  144. package/dist/plugins/middleware-export-validation.js +36 -0
  145. package/dist/plugins/middleware-server-only.d.ts +53 -0
  146. package/dist/plugins/middleware-server-only.js +90 -0
  147. package/dist/plugins/og-asset-ownership.d.ts +27 -0
  148. package/dist/plugins/og-asset-ownership.js +285 -0
  149. package/dist/plugins/og-assets.d.ts +50 -0
  150. package/dist/plugins/og-assets.js +229 -0
  151. package/dist/plugins/optimize-imports.d.ts +42 -0
  152. package/dist/plugins/optimize-imports.js +587 -0
  153. package/dist/plugins/postcss.d.ts +26 -0
  154. package/dist/plugins/postcss.js +96 -0
  155. package/dist/plugins/remove-console.d.ts +21 -0
  156. package/dist/plugins/remove-console.js +177 -0
  157. package/dist/plugins/require-context.d.ts +6 -0
  158. package/dist/plugins/require-context.js +185 -0
  159. package/dist/plugins/rsc-client-reference-loaders.d.ts +6 -0
  160. package/dist/plugins/rsc-client-reference-loaders.js +46 -0
  161. package/dist/plugins/rsc-client-shim-excludes.d.ts +6 -0
  162. package/dist/plugins/rsc-client-shim-excludes.js +35 -0
  163. package/dist/plugins/sass.d.ts +62 -0
  164. package/dist/plugins/sass.js +268 -0
  165. package/dist/plugins/server-externals-manifest.d.ts +26 -0
  166. package/dist/plugins/server-externals-manifest.js +81 -0
  167. package/dist/plugins/strip-server-exports.d.ts +21 -0
  168. package/dist/plugins/strip-server-exports.js +519 -0
  169. package/dist/plugins/typeof-window.d.ts +14 -0
  170. package/dist/plugins/typeof-window.js +150 -0
  171. package/dist/plugins/wasm-module-import.d.ts +15 -0
  172. package/dist/plugins/wasm-module-import.js +50 -0
  173. package/dist/routing/app-route-graph.d.ts +336 -0
  174. package/dist/routing/app-route-graph.js +1518 -0
  175. package/dist/routing/app-router.d.ts +30 -0
  176. package/dist/routing/app-router.js +59 -0
  177. package/dist/routing/file-matcher.d.ts +60 -0
  178. package/dist/routing/file-matcher.js +147 -0
  179. package/dist/routing/pages-router.d.ts +48 -0
  180. package/dist/routing/pages-router.js +163 -0
  181. package/dist/routing/route-matching.d.ts +27 -0
  182. package/dist/routing/route-matching.js +42 -0
  183. package/dist/routing/route-pattern.d.ts +64 -0
  184. package/dist/routing/route-pattern.js +165 -0
  185. package/dist/routing/route-trie.d.ts +67 -0
  186. package/dist/routing/route-trie.js +143 -0
  187. package/dist/routing/route-validation.d.ts +10 -0
  188. package/dist/routing/route-validation.js +101 -0
  189. package/dist/routing/utils.d.ts +117 -0
  190. package/dist/routing/utils.js +242 -0
  191. package/dist/server/accept-encoding.d.ts +29 -0
  192. package/dist/server/accept-encoding.js +95 -0
  193. package/dist/server/api-handler.d.ts +17 -0
  194. package/dist/server/api-handler.js +276 -0
  195. package/dist/server/app-action-request.d.ts +4 -0
  196. package/dist/server/app-action-request.js +9 -0
  197. package/dist/server/app-bfcache-id.d.ts +5 -0
  198. package/dist/server/app-bfcache-id.js +5 -0
  199. package/dist/server/app-bfcache-identity.d.ts +36 -0
  200. package/dist/server/app-bfcache-identity.js +156 -0
  201. package/dist/server/app-browser-action-result.d.ts +64 -0
  202. package/dist/server/app-browser-action-result.js +111 -0
  203. package/dist/server/app-browser-client-reuse-manifest.d.ts +12 -0
  204. package/dist/server/app-browser-client-reuse-manifest.js +101 -0
  205. package/dist/server/app-browser-entry.d.ts +1 -0
  206. package/dist/server/app-browser-entry.js +1087 -0
  207. package/dist/server/app-browser-error.d.ts +13 -0
  208. package/dist/server/app-browser-error.js +52 -0
  209. package/dist/server/app-browser-history-controller.d.ts +104 -0
  210. package/dist/server/app-browser-history-controller.js +210 -0
  211. package/dist/server/app-browser-hydration.d.ts +32 -0
  212. package/dist/server/app-browser-hydration.js +29 -0
  213. package/dist/server/app-browser-interception-context.d.ts +24 -0
  214. package/dist/server/app-browser-interception-context.js +43 -0
  215. package/dist/server/app-browser-mpa-navigation.d.ts +16 -0
  216. package/dist/server/app-browser-mpa-navigation.js +42 -0
  217. package/dist/server/app-browser-navigation-controller.d.ts +109 -0
  218. package/dist/server/app-browser-navigation-controller.js +465 -0
  219. package/dist/server/app-browser-popstate.d.ts +26 -0
  220. package/dist/server/app-browser-popstate.js +44 -0
  221. package/dist/server/app-browser-rsc-redirect.d.ts +38 -0
  222. package/dist/server/app-browser-rsc-redirect.js +64 -0
  223. package/dist/server/app-browser-server-action-client.d.ts +32 -0
  224. package/dist/server/app-browser-server-action-client.js +128 -0
  225. package/dist/server/app-browser-server-action-navigation.d.ts +6 -0
  226. package/dist/server/app-browser-server-action-navigation.js +9 -0
  227. package/dist/server/app-browser-state.d.ts +140 -0
  228. package/dist/server/app-browser-state.js +315 -0
  229. package/dist/server/app-browser-stream.d.ts +28 -0
  230. package/dist/server/app-browser-stream.js +122 -0
  231. package/dist/server/app-browser-visible-commit.d.ts +78 -0
  232. package/dist/server/app-browser-visible-commit.js +241 -0
  233. package/dist/server/app-client-reference-preloader.d.ts +14 -0
  234. package/dist/server/app-client-reference-preloader.js +44 -0
  235. package/dist/server/app-elements-wire.d.ts +192 -0
  236. package/dist/server/app-elements-wire.js +443 -0
  237. package/dist/server/app-elements.d.ts +9 -0
  238. package/dist/server/app-elements.js +18 -0
  239. package/dist/server/app-fallback-renderer.d.ts +89 -0
  240. package/dist/server/app-fallback-renderer.js +136 -0
  241. package/dist/server/app-history-state.d.ts +85 -0
  242. package/dist/server/app-history-state.js +223 -0
  243. package/dist/server/app-hook-warning-suppression.d.ts +6 -0
  244. package/dist/server/app-hook-warning-suppression.js +10 -0
  245. package/dist/server/app-inline-css-client.d.ts +6 -0
  246. package/dist/server/app-inline-css-client.js +35 -0
  247. package/dist/server/app-interception-context-header.d.ts +32 -0
  248. package/dist/server/app-interception-context-header.js +42 -0
  249. package/dist/server/app-layout-param-observation.d.ts +43 -0
  250. package/dist/server/app-layout-param-observation.js +168 -0
  251. package/dist/server/app-middleware.d.ts +46 -0
  252. package/dist/server/app-middleware.js +168 -0
  253. package/dist/server/app-mounted-slots-header.d.ts +35 -0
  254. package/dist/server/app-mounted-slots-header.js +58 -0
  255. package/dist/server/app-optimistic-routing.d.ts +53 -0
  256. package/dist/server/app-optimistic-routing.js +227 -0
  257. package/dist/server/app-page-boundary-render.d.ts +85 -0
  258. package/dist/server/app-page-boundary-render.js +305 -0
  259. package/dist/server/app-page-boundary.d.ts +102 -0
  260. package/dist/server/app-page-boundary.js +120 -0
  261. package/dist/server/app-page-cache-finalizer.d.ts +62 -0
  262. package/dist/server/app-page-cache-finalizer.js +122 -0
  263. package/dist/server/app-page-cache-render.d.ts +53 -0
  264. package/dist/server/app-page-cache-render.js +91 -0
  265. package/dist/server/app-page-cache.d.ts +83 -0
  266. package/dist/server/app-page-cache.js +272 -0
  267. package/dist/server/app-page-dispatch.d.ts +223 -0
  268. package/dist/server/app-page-dispatch.js +610 -0
  269. package/dist/server/app-page-element-builder.d.ts +96 -0
  270. package/dist/server/app-page-element-builder.js +205 -0
  271. package/dist/server/app-page-execution.d.ts +138 -0
  272. package/dist/server/app-page-execution.js +328 -0
  273. package/dist/server/app-page-head.d.ts +65 -0
  274. package/dist/server/app-page-head.js +228 -0
  275. package/dist/server/app-page-method.d.ts +15 -0
  276. package/dist/server/app-page-method.js +25 -0
  277. package/dist/server/app-page-params.d.ts +8 -0
  278. package/dist/server/app-page-params.js +39 -0
  279. package/dist/server/app-page-ppr-runtime.d.ts +7 -0
  280. package/dist/server/app-page-ppr-runtime.js +70 -0
  281. package/dist/server/app-page-probe.d.ts +134 -0
  282. package/dist/server/app-page-probe.js +276 -0
  283. package/dist/server/app-page-render-identity.d.ts +21 -0
  284. package/dist/server/app-page-render-identity.js +40 -0
  285. package/dist/server/app-page-render-observation.d.ts +36 -0
  286. package/dist/server/app-page-render-observation.js +82 -0
  287. package/dist/server/app-page-render.d.ts +111 -0
  288. package/dist/server/app-page-render.js +602 -0
  289. package/dist/server/app-page-request.d.ts +137 -0
  290. package/dist/server/app-page-request.js +216 -0
  291. package/dist/server/app-page-response.d.ts +68 -0
  292. package/dist/server/app-page-response.js +120 -0
  293. package/dist/server/app-page-route-wiring.d.ts +151 -0
  294. package/dist/server/app-page-route-wiring.js +452 -0
  295. package/dist/server/app-page-search-params-observation.d.ts +10 -0
  296. package/dist/server/app-page-search-params-observation.js +20 -0
  297. package/dist/server/app-page-segment-state.d.ts +9 -0
  298. package/dist/server/app-page-segment-state.js +80 -0
  299. package/dist/server/app-page-stream.d.ts +151 -0
  300. package/dist/server/app-page-stream.js +143 -0
  301. package/dist/server/app-pages-bridge.d.ts +63 -0
  302. package/dist/server/app-pages-bridge.js +63 -0
  303. package/dist/server/app-post-middleware-context.d.ts +15 -0
  304. package/dist/server/app-post-middleware-context.js +26 -0
  305. package/dist/server/app-ppr-fallback-shell-render.d.ts +18 -0
  306. package/dist/server/app-ppr-fallback-shell-render.js +26 -0
  307. package/dist/server/app-ppr-fallback-shell.d.ts +33 -0
  308. package/dist/server/app-ppr-fallback-shell.js +89 -0
  309. package/dist/server/app-prerender-endpoints.d.ts +18 -0
  310. package/dist/server/app-prerender-endpoints.js +94 -0
  311. package/dist/server/app-prerender-static-params.d.ts +30 -0
  312. package/dist/server/app-prerender-static-params.js +81 -0
  313. package/dist/server/app-render-dependency.d.ts +14 -0
  314. package/dist/server/app-render-dependency.js +41 -0
  315. package/dist/server/app-request-context.d.ts +20 -0
  316. package/dist/server/app-request-context.js +29 -0
  317. package/dist/server/app-route-handler-cache.d.ts +46 -0
  318. package/dist/server/app-route-handler-cache.js +78 -0
  319. package/dist/server/app-route-handler-dispatch.d.ts +49 -0
  320. package/dist/server/app-route-handler-dispatch.js +163 -0
  321. package/dist/server/app-route-handler-execution.d.ts +86 -0
  322. package/dist/server/app-route-handler-execution.js +128 -0
  323. package/dist/server/app-route-handler-policy.d.ts +55 -0
  324. package/dist/server/app-route-handler-policy.js +58 -0
  325. package/dist/server/app-route-handler-response.d.ts +28 -0
  326. package/dist/server/app-route-handler-response.js +145 -0
  327. package/dist/server/app-route-handler-runtime.d.ts +39 -0
  328. package/dist/server/app-route-handler-runtime.js +250 -0
  329. package/dist/server/app-route-module-loader.d.ts +91 -0
  330. package/dist/server/app-route-module-loader.js +83 -0
  331. package/dist/server/app-router-entry.d.ts +13 -0
  332. package/dist/server/app-router-entry.js +49 -0
  333. package/dist/server/app-rsc-cache-busting.d.ts +64 -0
  334. package/dist/server/app-rsc-cache-busting.js +206 -0
  335. package/dist/server/app-rsc-embedded-chunks.d.ts +8 -0
  336. package/dist/server/app-rsc-embedded-chunks.js +32 -0
  337. package/dist/server/app-rsc-error-handler.d.ts +20 -0
  338. package/dist/server/app-rsc-error-handler.js +28 -0
  339. package/dist/server/app-rsc-errors.d.ts +40 -0
  340. package/dist/server/app-rsc-errors.js +60 -0
  341. package/dist/server/app-rsc-handler.d.ts +201 -0
  342. package/dist/server/app-rsc-handler.js +538 -0
  343. package/dist/server/app-rsc-render-mode.d.ts +11 -0
  344. package/dist/server/app-rsc-render-mode.js +25 -0
  345. package/dist/server/app-rsc-request-normalization.d.ts +48 -0
  346. package/dist/server/app-rsc-request-normalization.js +75 -0
  347. package/dist/server/app-rsc-response-finalizer.d.ts +37 -0
  348. package/dist/server/app-rsc-response-finalizer.js +54 -0
  349. package/dist/server/app-rsc-route-matching.d.ts +93 -0
  350. package/dist/server/app-rsc-route-matching.js +134 -0
  351. package/dist/server/app-segment-config.d.ts +46 -0
  352. package/dist/server/app-segment-config.js +113 -0
  353. package/dist/server/app-server-action-execution.d.ts +219 -0
  354. package/dist/server/app-server-action-execution.js +767 -0
  355. package/dist/server/app-ssr-entry.d.ts +52 -0
  356. package/dist/server/app-ssr-entry.js +295 -0
  357. package/dist/server/app-ssr-error-meta.d.ts +13 -0
  358. package/dist/server/app-ssr-error-meta.js +48 -0
  359. package/dist/server/app-ssr-router-instance.d.ts +6 -0
  360. package/dist/server/app-ssr-router-instance.js +24 -0
  361. package/dist/server/app-ssr-stream.d.ts +60 -0
  362. package/dist/server/app-ssr-stream.js +408 -0
  363. package/dist/server/app-static-generation.d.ts +15 -0
  364. package/dist/server/app-static-generation.js +19 -0
  365. package/dist/server/app-visited-response-cache.d.ts +23 -0
  366. package/dist/server/app-visited-response-cache.js +19 -0
  367. package/dist/server/artifact-compatibility.d.ts +54 -0
  368. package/dist/server/artifact-compatibility.js +91 -0
  369. package/dist/server/before-interactive-head.d.ts +17 -0
  370. package/dist/server/before-interactive-head.js +35 -0
  371. package/dist/server/cache-control.d.ts +37 -0
  372. package/dist/server/cache-control.js +56 -0
  373. package/dist/server/cache-headers.d.ts +6 -0
  374. package/dist/server/cache-headers.js +17 -0
  375. package/dist/server/cache-proof.d.ts +364 -0
  376. package/dist/server/cache-proof.js +794 -0
  377. package/dist/server/client-reuse-manifest.d.ts +104 -0
  378. package/dist/server/client-reuse-manifest.js +209 -0
  379. package/dist/server/client-trace-metadata.d.ts +30 -0
  380. package/dist/server/client-trace-metadata.js +81 -0
  381. package/dist/server/cookie-utils.d.ts +12 -0
  382. package/dist/server/cookie-utils.js +18 -0
  383. package/dist/server/csp.d.ts +10 -0
  384. package/dist/server/csp.js +41 -0
  385. package/dist/server/default-global-error-module.d.ts +19 -0
  386. package/dist/server/default-global-error-module.js +18 -0
  387. package/dist/server/default-not-found-module.d.ts +19 -0
  388. package/dist/server/default-not-found-module.js +18 -0
  389. package/dist/server/defer-until-stream-consumed.d.ts +7 -0
  390. package/dist/server/defer-until-stream-consumed.js +34 -0
  391. package/dist/server/dev-error-overlay-store.d.ts +39 -0
  392. package/dist/server/dev-error-overlay-store.js +86 -0
  393. package/dist/server/dev-error-overlay.d.ts +51 -0
  394. package/dist/server/dev-error-overlay.js +1341 -0
  395. package/dist/server/dev-initial-server-error.d.ts +9 -0
  396. package/dist/server/dev-initial-server-error.js +26 -0
  397. package/dist/server/dev-lockfile.d.ts +109 -0
  398. package/dist/server/dev-lockfile.js +179 -0
  399. package/dist/server/dev-module-runner.d.ts +30 -0
  400. package/dist/server/dev-module-runner.js +91 -0
  401. package/dist/server/dev-origin-check.d.ts +62 -0
  402. package/dist/server/dev-origin-check.js +156 -0
  403. package/dist/server/dev-route-files.d.ts +6 -0
  404. package/dist/server/dev-route-files.js +71 -0
  405. package/dist/server/dev-server.d.ts +58 -0
  406. package/dist/server/dev-server.js +1114 -0
  407. package/dist/server/dev-stack-sourcemap-endpoint.d.ts +4 -0
  408. package/dist/server/dev-stack-sourcemap-endpoint.js +4 -0
  409. package/dist/server/dev-stack-sourcemap.d.ts +43 -0
  410. package/dist/server/dev-stack-sourcemap.js +443 -0
  411. package/dist/server/document-initial-head.d.ts +6 -0
  412. package/dist/server/document-initial-head.js +33 -0
  413. package/dist/server/edge-api-runtime.d.ts +4 -0
  414. package/dist/server/edge-api-runtime.js +6 -0
  415. package/dist/server/file-based-metadata.d.ts +29 -0
  416. package/dist/server/file-based-metadata.js +401 -0
  417. package/dist/server/headers.d.ts +114 -0
  418. package/dist/server/headers.js +136 -0
  419. package/dist/server/html.d.ts +28 -0
  420. package/dist/server/html.js +41 -0
  421. package/dist/server/http-error-responses.d.ts +91 -0
  422. package/dist/server/http-error-responses.js +105 -0
  423. package/dist/server/hybrid-route-priority.d.ts +22 -0
  424. package/dist/server/hybrid-route-priority.js +33 -0
  425. package/dist/server/image-optimization.d.ts +130 -0
  426. package/dist/server/image-optimization.js +247 -0
  427. package/dist/server/implicit-tags.d.ts +6 -0
  428. package/dist/server/implicit-tags.js +44 -0
  429. package/dist/server/instrumentation-runtime.d.ts +49 -0
  430. package/dist/server/instrumentation-runtime.js +35 -0
  431. package/dist/server/instrumentation.d.ts +85 -0
  432. package/dist/server/instrumentation.js +130 -0
  433. package/dist/server/isr-cache.d.ts +127 -0
  434. package/dist/server/isr-cache.js +282 -0
  435. package/dist/server/isr-decision.d.ts +79 -0
  436. package/dist/server/isr-decision.js +70 -0
  437. package/dist/server/metadata-route-build-data.d.ts +24 -0
  438. package/dist/server/metadata-route-build-data.js +148 -0
  439. package/dist/server/metadata-route-response.d.ts +16 -0
  440. package/dist/server/metadata-route-response.js +205 -0
  441. package/dist/server/metadata-routes.d.ts +139 -0
  442. package/dist/server/metadata-routes.js +433 -0
  443. package/dist/server/middleware-matcher.d.ts +14 -0
  444. package/dist/server/middleware-matcher.js +111 -0
  445. package/dist/server/middleware-request-headers.d.ts +11 -0
  446. package/dist/server/middleware-request-headers.js +65 -0
  447. package/dist/server/middleware-response-headers.d.ts +12 -0
  448. package/dist/server/middleware-response-headers.js +42 -0
  449. package/dist/server/middleware-runtime.d.ts +67 -0
  450. package/dist/server/middleware-runtime.js +240 -0
  451. package/dist/server/middleware.d.ts +62 -0
  452. package/dist/server/middleware.js +114 -0
  453. package/dist/server/navigation-planner.d.ts +308 -0
  454. package/dist/server/navigation-planner.js +831 -0
  455. package/dist/server/navigation-trace.d.ts +68 -0
  456. package/dist/server/navigation-trace.js +71 -0
  457. package/dist/server/next-error-digest.d.ts +44 -0
  458. package/dist/server/next-error-digest.js +40 -0
  459. package/dist/server/normalize-path.d.ts +38 -0
  460. package/dist/server/normalize-path.js +70 -0
  461. package/dist/server/open-redirect.d.ts +12 -0
  462. package/dist/server/open-redirect.js +21 -0
  463. package/dist/server/operation-token.d.ts +40 -0
  464. package/dist/server/operation-token.js +85 -0
  465. package/dist/server/otel-tracer-extension.d.ts +45 -0
  466. package/dist/server/otel-tracer-extension.js +89 -0
  467. package/dist/server/pages-api-route.d.ts +83 -0
  468. package/dist/server/pages-api-route.js +75 -0
  469. package/dist/server/pages-asset-tags.d.ts +78 -0
  470. package/dist/server/pages-asset-tags.js +126 -0
  471. package/dist/server/pages-body-parser-config.d.ts +59 -0
  472. package/dist/server/pages-body-parser-config.js +77 -0
  473. package/dist/server/pages-data-route.d.ts +121 -0
  474. package/dist/server/pages-data-route.js +157 -0
  475. package/dist/server/pages-default-404.d.ts +30 -0
  476. package/dist/server/pages-default-404.js +38 -0
  477. package/dist/server/pages-dev-module-url.d.ts +4 -0
  478. package/dist/server/pages-dev-module-url.js +15 -0
  479. package/dist/server/pages-document-initial-props.d.ts +77 -0
  480. package/dist/server/pages-document-initial-props.js +109 -0
  481. package/dist/server/pages-get-initial-props.d.ts +67 -0
  482. package/dist/server/pages-get-initial-props.js +92 -0
  483. package/dist/server/pages-i18n.d.ts +106 -0
  484. package/dist/server/pages-i18n.js +183 -0
  485. package/dist/server/pages-media-type.d.ts +15 -0
  486. package/dist/server/pages-media-type.js +24 -0
  487. package/dist/server/pages-node-compat.d.ts +55 -0
  488. package/dist/server/pages-node-compat.js +235 -0
  489. package/dist/server/pages-page-data.d.ts +223 -0
  490. package/dist/server/pages-page-data.js +484 -0
  491. package/dist/server/pages-page-handler.d.ts +100 -0
  492. package/dist/server/pages-page-handler.js +403 -0
  493. package/dist/server/pages-page-method.d.ts +47 -0
  494. package/dist/server/pages-page-method.js +17 -0
  495. package/dist/server/pages-page-response.d.ts +138 -0
  496. package/dist/server/pages-page-response.js +285 -0
  497. package/dist/server/pages-readiness.d.ts +36 -0
  498. package/dist/server/pages-readiness.js +21 -0
  499. package/dist/server/pages-request-pipeline.d.ts +116 -0
  500. package/dist/server/pages-request-pipeline.js +311 -0
  501. package/dist/server/pages-revalidate.d.ts +15 -0
  502. package/dist/server/pages-revalidate.js +19 -0
  503. package/dist/server/pages-serializable-props.d.ts +24 -0
  504. package/dist/server/pages-serializable-props.js +67 -0
  505. package/dist/server/pregenerated-concrete-paths.d.ts +16 -0
  506. package/dist/server/pregenerated-concrete-paths.js +61 -0
  507. package/dist/server/prerender-manifest.d.ts +33 -0
  508. package/dist/server/prerender-manifest.js +54 -0
  509. package/dist/server/prerender-route-params.d.ts +23 -0
  510. package/dist/server/prerender-route-params.js +113 -0
  511. package/dist/server/prerender-work-unit-setup.d.ts +6 -0
  512. package/dist/server/prerender-work-unit-setup.js +28 -0
  513. package/dist/server/prod-server.d.ts +148 -0
  514. package/dist/server/prod-server.js +1136 -0
  515. package/dist/server/proxy-trust.d.ts +40 -0
  516. package/dist/server/proxy-trust.js +68 -0
  517. package/dist/server/request-log.d.ts +39 -0
  518. package/dist/server/request-log.js +56 -0
  519. package/dist/server/request-pipeline.d.ts +187 -0
  520. package/dist/server/request-pipeline.js +447 -0
  521. package/dist/server/rsc-stream-hints.d.ts +10 -0
  522. package/dist/server/rsc-stream-hints.js +41 -0
  523. package/dist/server/seed-cache.d.ts +29 -0
  524. package/dist/server/seed-cache.js +125 -0
  525. package/dist/server/server-action-not-found.d.ts +21 -0
  526. package/dist/server/server-action-not-found.js +62 -0
  527. package/dist/server/server-globals.d.ts +4 -0
  528. package/dist/server/server-globals.js +35 -0
  529. package/dist/server/skip-cache-proof.d.ts +61 -0
  530. package/dist/server/skip-cache-proof.js +168 -0
  531. package/dist/server/socket-error-backstop.d.ts +34 -0
  532. package/dist/server/socket-error-backstop.js +200 -0
  533. package/dist/server/static-file-cache.d.ts +56 -0
  534. package/dist/server/static-file-cache.js +231 -0
  535. package/dist/server/static-layout-client-reuse-proof.d.ts +15 -0
  536. package/dist/server/static-layout-client-reuse-proof.js +33 -0
  537. package/dist/server/streaming-metadata.d.ts +4 -0
  538. package/dist/server/streaming-metadata.js +8 -0
  539. package/dist/server/worker-utils.d.ts +7 -0
  540. package/dist/server/worker-utils.js +99 -0
  541. package/dist/shims/amp.d.ts +19 -0
  542. package/dist/shims/amp.js +23 -0
  543. package/dist/shims/app-router-scroll-state.d.ts +15 -0
  544. package/dist/shims/app-router-scroll-state.js +61 -0
  545. package/dist/shims/app-router-scroll.d.ts +29 -0
  546. package/dist/shims/app-router-scroll.js +141 -0
  547. package/dist/shims/app.d.ts +42 -0
  548. package/dist/shims/app.js +48 -0
  549. package/dist/shims/before-interactive-context.d.ts +40 -0
  550. package/dist/shims/before-interactive-context.js +8 -0
  551. package/dist/shims/cache-for-request.d.ts +57 -0
  552. package/dist/shims/cache-for-request.js +72 -0
  553. package/dist/shims/cache-handler.d.ts +106 -0
  554. package/dist/shims/cache-handler.js +176 -0
  555. package/dist/shims/cache-request-state.d.ts +47 -0
  556. package/dist/shims/cache-request-state.js +126 -0
  557. package/dist/shims/cache-runtime.d.ts +83 -0
  558. package/dist/shims/cache-runtime.js +452 -0
  559. package/dist/shims/cache.d.ts +145 -0
  560. package/dist/shims/cache.js +401 -0
  561. package/dist/shims/cdn-cache.d.ts +125 -0
  562. package/dist/shims/cdn-cache.js +100 -0
  563. package/dist/shims/client-hook-error.d.ts +13 -0
  564. package/dist/shims/client-hook-error.js +17 -0
  565. package/dist/shims/client-locale.d.ts +14 -0
  566. package/dist/shims/client-locale.js +11 -0
  567. package/dist/shims/client-only.d.ts +1 -0
  568. package/dist/shims/client-only.js +1 -0
  569. package/dist/shims/compat-router.d.ts +16 -0
  570. package/dist/shims/compat-router.js +25 -0
  571. package/dist/shims/config.d.ts +28 -0
  572. package/dist/shims/config.js +21 -0
  573. package/dist/shims/constants.d.ts +130 -0
  574. package/dist/shims/constants.js +167 -0
  575. package/dist/shims/default-global-error.d.ts +31 -0
  576. package/dist/shims/default-global-error.js +179 -0
  577. package/dist/shims/default-not-found.d.ts +11 -0
  578. package/dist/shims/default-not-found.js +59 -0
  579. package/dist/shims/document.d.ts +92 -0
  580. package/dist/shims/document.js +76 -0
  581. package/dist/shims/dynamic-preload-chunks.d.ts +8 -0
  582. package/dist/shims/dynamic-preload-chunks.js +79 -0
  583. package/dist/shims/dynamic.d.ts +35 -0
  584. package/dist/shims/dynamic.js +204 -0
  585. package/dist/shims/error-boundary-navigation.d.ts +7 -0
  586. package/dist/shims/error-boundary-navigation.js +44 -0
  587. package/dist/shims/error-boundary.d.ts +155 -0
  588. package/dist/shims/error-boundary.js +342 -0
  589. package/dist/shims/error.d.ts +31 -0
  590. package/dist/shims/error.js +123 -0
  591. package/dist/shims/error.react-server.d.ts +9 -0
  592. package/dist/shims/error.react-server.js +6 -0
  593. package/dist/shims/fetch-cache.d.ts +136 -0
  594. package/dist/shims/fetch-cache.js +766 -0
  595. package/dist/shims/font-google-base.d.ts +83 -0
  596. package/dist/shims/font-google-base.js +290 -0
  597. package/dist/shims/font-google.d.ts +2 -0
  598. package/dist/shims/font-google.js +2 -0
  599. package/dist/shims/font-local.d.ts +50 -0
  600. package/dist/shims/font-local.js +195 -0
  601. package/dist/shims/font-utils.d.ts +56 -0
  602. package/dist/shims/font-utils.js +107 -0
  603. package/dist/shims/form.d.ts +19 -0
  604. package/dist/shims/form.js +236 -0
  605. package/dist/shims/hash-scroll.d.ts +10 -0
  606. package/dist/shims/hash-scroll.js +47 -0
  607. package/dist/shims/head-state.d.ts +16 -0
  608. package/dist/shims/head-state.js +43 -0
  609. package/dist/shims/head.d.ts +73 -0
  610. package/dist/shims/head.js +340 -0
  611. package/dist/shims/headers.d.ts +253 -0
  612. package/dist/shims/headers.js +754 -0
  613. package/dist/shims/i18n-context.d.ts +22 -0
  614. package/dist/shims/i18n-context.js +42 -0
  615. package/dist/shims/i18n-state.d.ts +14 -0
  616. package/dist/shims/i18n-state.js +38 -0
  617. package/dist/shims/image-config.d.ts +45 -0
  618. package/dist/shims/image-config.js +85 -0
  619. package/dist/shims/image.d.ts +55 -0
  620. package/dist/shims/image.js +582 -0
  621. package/dist/shims/internal/als-registry.d.ts +14 -0
  622. package/dist/shims/internal/als-registry.js +80 -0
  623. package/dist/shims/internal/api-utils.d.ts +14 -0
  624. package/dist/shims/internal/api-utils.js +1 -0
  625. package/dist/shims/internal/app-page-props-cache-key.d.ts +5 -0
  626. package/dist/shims/internal/app-page-props-cache-key.js +16 -0
  627. package/dist/shims/internal/app-route-detection.d.ts +39 -0
  628. package/dist/shims/internal/app-route-detection.js +62 -0
  629. package/dist/shims/internal/app-router-context.d.ts +31 -0
  630. package/dist/shims/internal/app-router-context.js +28 -0
  631. package/dist/shims/internal/cookie-serialize.d.ts +45 -0
  632. package/dist/shims/internal/cookie-serialize.js +49 -0
  633. package/dist/shims/internal/cookies.d.ts +2 -0
  634. package/dist/shims/internal/cookies.js +2 -0
  635. package/dist/shims/internal/hybrid-client-route-owner.d.ts +31 -0
  636. package/dist/shims/internal/hybrid-client-route-owner.js +143 -0
  637. package/dist/shims/internal/interpolate-as.d.ts +25 -0
  638. package/dist/shims/internal/interpolate-as.js +196 -0
  639. package/dist/shims/internal/link-status-registry.d.ts +43 -0
  640. package/dist/shims/internal/link-status-registry.js +42 -0
  641. package/dist/shims/internal/make-hanging-promise.d.ts +15 -0
  642. package/dist/shims/internal/make-hanging-promise.js +44 -0
  643. package/dist/shims/internal/navigation-untracked.d.ts +35 -0
  644. package/dist/shims/internal/navigation-untracked.js +56 -0
  645. package/dist/shims/internal/pages-data-fetch-dedup.d.ts +54 -0
  646. package/dist/shims/internal/pages-data-fetch-dedup.js +121 -0
  647. package/dist/shims/internal/pages-data-target.d.ts +62 -0
  648. package/dist/shims/internal/pages-data-target.js +98 -0
  649. package/dist/shims/internal/pages-data-url.d.ts +41 -0
  650. package/dist/shims/internal/pages-data-url.js +71 -0
  651. package/dist/shims/internal/pages-router-accessor.d.ts +19 -0
  652. package/dist/shims/internal/pages-router-accessor.js +13 -0
  653. package/dist/shims/internal/route-pattern-for-warning.d.ts +27 -0
  654. package/dist/shims/internal/route-pattern-for-warning.js +40 -0
  655. package/dist/shims/internal/router-context.d.ts +7 -0
  656. package/dist/shims/internal/router-context.js +13 -0
  657. package/dist/shims/internal/utils.d.ts +52 -0
  658. package/dist/shims/internal/utils.js +27 -0
  659. package/dist/shims/internal/work-unit-async-storage.d.ts +30 -0
  660. package/dist/shims/internal/work-unit-async-storage.js +17 -0
  661. package/dist/shims/layout-segment-context.d.ts +24 -0
  662. package/dist/shims/layout-segment-context.js +39 -0
  663. package/dist/shims/legacy-image.d.ts +41 -0
  664. package/dist/shims/legacy-image.js +49 -0
  665. package/dist/shims/link-prefetch.d.ts +41 -0
  666. package/dist/shims/link-prefetch.js +43 -0
  667. package/dist/shims/link.d.ts +102 -0
  668. package/dist/shims/link.js +687 -0
  669. package/dist/shims/metadata.d.ts +285 -0
  670. package/dist/shims/metadata.js +820 -0
  671. package/dist/shims/navigation-context-state.d.ts +40 -0
  672. package/dist/shims/navigation-context-state.js +116 -0
  673. package/dist/shims/navigation-errors.d.ts +55 -0
  674. package/dist/shims/navigation-errors.js +110 -0
  675. package/dist/shims/navigation-server.d.ts +3 -0
  676. package/dist/shims/navigation-server.js +3 -0
  677. package/dist/shims/navigation-state.d.ts +25 -0
  678. package/dist/shims/navigation-state.js +66 -0
  679. package/dist/shims/navigation.d.ts +286 -0
  680. package/dist/shims/navigation.js +1206 -0
  681. package/dist/shims/navigation.react-server.d.ts +14 -0
  682. package/dist/shims/navigation.react-server.js +32 -0
  683. package/dist/shims/offline.d.ts +4 -0
  684. package/dist/shims/offline.js +15 -0
  685. package/dist/shims/og.d.ts +17 -0
  686. package/dist/shims/og.js +48 -0
  687. package/dist/shims/pages-router-runtime.d.ts +12 -0
  688. package/dist/shims/pages-router-runtime.js +24 -0
  689. package/dist/shims/ppr-fallback-shell.d.ts +33 -0
  690. package/dist/shims/ppr-fallback-shell.js +170 -0
  691. package/dist/shims/readonly-url-search-params.d.ts +13 -0
  692. package/dist/shims/readonly-url-search-params.js +26 -0
  693. package/dist/shims/request-context.d.ts +58 -0
  694. package/dist/shims/request-context.js +45 -0
  695. package/dist/shims/request-state-types.d.ts +12 -0
  696. package/dist/shims/request-state-types.js +1 -0
  697. package/dist/shims/root-params.d.ts +12 -0
  698. package/dist/shims/root-params.js +30 -0
  699. package/dist/shims/router-state.d.ts +32 -0
  700. package/dist/shims/router-state.js +39 -0
  701. package/dist/shims/router.d.ts +192 -0
  702. package/dist/shims/router.js +1786 -0
  703. package/dist/shims/script-nonce-context.d.ts +11 -0
  704. package/dist/shims/script-nonce-context.js +23 -0
  705. package/dist/shims/script.d.ts +43 -0
  706. package/dist/shims/script.js +370 -0
  707. package/dist/shims/server-only.d.ts +1 -0
  708. package/dist/shims/server-only.js +1 -0
  709. package/dist/shims/server.d.ts +323 -0
  710. package/dist/shims/server.js +729 -0
  711. package/dist/shims/slot.d.ts +45 -0
  712. package/dist/shims/slot.js +230 -0
  713. package/dist/shims/thenable-params.d.ts +11 -0
  714. package/dist/shims/thenable-params.js +176 -0
  715. package/dist/shims/unified-request-context.d.ts +68 -0
  716. package/dist/shims/unified-request-context.js +86 -0
  717. package/dist/shims/unrecognized-action-error.d.ts +34 -0
  718. package/dist/shims/unrecognized-action-error.js +39 -0
  719. package/dist/shims/url-safety.d.ts +34 -0
  720. package/dist/shims/url-safety.js +70 -0
  721. package/dist/shims/url-utils.d.ts +51 -0
  722. package/dist/shims/url-utils.js +156 -0
  723. package/dist/shims/use-merged-ref.d.ts +6 -0
  724. package/dist/shims/use-merged-ref.js +38 -0
  725. package/dist/shims/web-vitals.d.ts +8 -0
  726. package/dist/shims/web-vitals.js +22 -0
  727. package/dist/typegen.d.ts +9 -0
  728. package/dist/typegen.js +228 -0
  729. package/dist/utils/asset-prefix.d.ts +96 -0
  730. package/dist/utils/asset-prefix.js +122 -0
  731. package/dist/utils/base-path.d.ts +31 -0
  732. package/dist/utils/base-path.js +45 -0
  733. package/dist/utils/built-asset-url.d.ts +4 -0
  734. package/dist/utils/built-asset-url.js +11 -0
  735. package/dist/utils/cache-control-metadata.d.ts +4 -0
  736. package/dist/utils/cache-control-metadata.js +12 -0
  737. package/dist/utils/client-build-manifest.d.ts +21 -0
  738. package/dist/utils/client-build-manifest.js +87 -0
  739. package/dist/utils/client-entry-manifest.d.ts +11 -0
  740. package/dist/utils/client-entry-manifest.js +29 -0
  741. package/dist/utils/client-runtime-metadata.d.ts +45 -0
  742. package/dist/utils/client-runtime-metadata.js +63 -0
  743. package/dist/utils/commonjs-loader.d.ts +16 -0
  744. package/dist/utils/commonjs-loader.js +100 -0
  745. package/dist/utils/compare.d.ts +4 -0
  746. package/dist/utils/compare.js +8 -0
  747. package/dist/utils/deployment-id.d.ts +8 -0
  748. package/dist/utils/deployment-id.js +22 -0
  749. package/dist/utils/dev-error-recovery-event.d.ts +4 -0
  750. package/dist/utils/dev-error-recovery-event.js +4 -0
  751. package/dist/utils/domain-locale.d.ts +26 -0
  752. package/dist/utils/domain-locale.js +50 -0
  753. package/dist/utils/encode-cache-tag.d.ts +30 -0
  754. package/dist/utils/encode-cache-tag.js +36 -0
  755. package/dist/utils/error-cause.d.ts +4 -0
  756. package/dist/utils/error-cause.js +95 -0
  757. package/dist/utils/has-trailing-comma.d.ts +24 -0
  758. package/dist/utils/has-trailing-comma.js +62 -0
  759. package/dist/utils/hash.d.ts +24 -0
  760. package/dist/utils/hash.js +55 -0
  761. package/dist/utils/html-limited-bots.d.ts +21 -0
  762. package/dist/utils/html-limited-bots.js +35 -0
  763. package/dist/utils/lazy-chunks.d.ts +59 -0
  764. package/dist/utils/lazy-chunks.js +112 -0
  765. package/dist/utils/manifest-paths.d.ts +30 -0
  766. package/dist/utils/manifest-paths.js +66 -0
  767. package/dist/utils/mdx-scan.d.ts +9 -0
  768. package/dist/utils/mdx-scan.js +34 -0
  769. package/dist/utils/navigation-signal.d.ts +4 -0
  770. package/dist/utils/navigation-signal.js +12 -0
  771. package/dist/utils/number.d.ts +4 -0
  772. package/dist/utils/number.js +6 -0
  773. package/dist/utils/parse-cookie.d.ts +13 -0
  774. package/dist/utils/parse-cookie.js +52 -0
  775. package/dist/utils/path.d.ts +22 -0
  776. package/dist/utils/path.js +30 -0
  777. package/dist/utils/prerender-output-paths.d.ts +14 -0
  778. package/dist/utils/prerender-output-paths.js +22 -0
  779. package/dist/utils/project.d.ts +76 -0
  780. package/dist/utils/project.js +213 -0
  781. package/dist/utils/promise.d.ts +4 -0
  782. package/dist/utils/promise.js +6 -0
  783. package/dist/utils/public-routes.d.ts +4 -0
  784. package/dist/utils/public-routes.js +48 -0
  785. package/dist/utils/query.d.ts +49 -0
  786. package/dist/utils/query.js +122 -0
  787. package/dist/utils/record.d.ts +4 -0
  788. package/dist/utils/record.js +6 -0
  789. package/dist/utils/regex.d.ts +4 -0
  790. package/dist/utils/regex.js +6 -0
  791. package/dist/utils/safe-json-file.d.ts +17 -0
  792. package/dist/utils/safe-json-file.js +23 -0
  793. package/dist/utils/sorted-array.d.ts +8 -0
  794. package/dist/utils/sorted-array.js +20 -0
  795. package/dist/utils/text-stream.d.ts +28 -0
  796. package/dist/utils/text-stream.js +64 -0
  797. package/dist/utils/vinext-root.d.ts +23 -0
  798. package/dist/utils/vinext-root.js +29 -0
  799. package/dist/utils/virtual-module.d.ts +5 -0
  800. package/dist/utils/virtual-module.js +0 -0
  801. package/dist/utils/vite-version.d.ts +21 -0
  802. package/dist/utils/vite-version.js +42 -0
  803. package/package.json +145 -0
package/dist/index.js ADDED
@@ -0,0 +1,2661 @@
1
+ import { detectPackageManager } from "./utils/project.js";
2
+ import { normalizePathSeparators, stripJsExtension, stripViteModuleQuery } from "./utils/path.js";
3
+ import { normalizePathnameForRouteMatchStrict } from "./routing/utils.js";
4
+ import { escapeRegExp } from "./utils/regex.js";
5
+ import { buildViteResolveExtensions, createValidFileMatcher, findFileWithExts, normalizeViteResolveExtensions } from "./routing/file-matcher.js";
6
+ import { apiRouter, invalidateRouteCache, matchRoute, pagesRouter } from "./routing/pages-router.js";
7
+ import { INTERNAL_HEADERS, NEXTJS_DEPLOYMENT_ID_HEADER, VINEXT_INTERNAL_HEADERS, VINEXT_MW_CTX_HEADER, VINEXT_TIMING_HEADER } from "./server/headers.js";
8
+ import { normalizePath as normalizePath$1 } from "./server/normalize-path.js";
9
+ import { matchesRewriteSource, proxyExternalRequest } from "./config/config-matchers.js";
10
+ import { isOpenRedirectShaped } from "./server/open-redirect.js";
11
+ import { filterInternalHeaders, normalizeTrailingSlash } from "./server/request-pipeline.js";
12
+ import { findMiddlewareFile, isProxyFile, runMiddleware } from "./server/middleware.js";
13
+ import { generateServerEntry } from "./entries/pages-server-entry.js";
14
+ import { generateClientEntry } from "./entries/pages-client-entry.js";
15
+ import { appRouteGraph, appRouter, invalidateAppRouteCache, matchAppRoute } from "./routing/app-router.js";
16
+ import { findInstrumentationClientFile, findInstrumentationFile, runInstrumentation } from "./server/instrumentation.js";
17
+ import { isUnknownRecord } from "./utils/record.js";
18
+ import { logRequest, now } from "./server/request-log.js";
19
+ import { createSSRHandler } from "./server/dev-server.js";
20
+ import { handleApiRoute } from "./server/api-handler.js";
21
+ import { DEFAULT_DEVICE_SIZES, DEFAULT_IMAGE_SIZES, isImageOptimizationPath, resolveDevImageRedirect } from "./server/image-optimization.js";
22
+ import { installSocketErrorBackstop } from "./server/socket-error-backstop.js";
23
+ import { scanMetadataFiles } from "./server/metadata-routes.js";
24
+ import { shouldInvalidateAppRouteFile } from "./server/dev-route-files.js";
25
+ import { createDirectRunner } from "./server/dev-module-runner.js";
26
+ import { validateDevRequest } from "./server/dev-origin-check.js";
27
+ import { generateRscEntry } from "./entries/app-rsc-entry.js";
28
+ import { generateSsrEntry } from "./entries/app-ssr-entry.js";
29
+ import { VIRTUAL_CACHE_ADAPTERS, generateCacheAdaptersModule } from "./cache/cache-adapters-virtual.js";
30
+ import { generateBrowserEntry, isLinkPrefetchRoute, toDocumentOnlyAppRoute, toLinkPrefetchRoute } from "./entries/app-browser-entry.js";
31
+ import { collectRouteClassificationManifest } from "./build/route-classification-manifest.js";
32
+ import { planRouteClassificationInjection } from "./build/route-classification-injector.js";
33
+ import { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } from "./shims/constants.js";
34
+ import { resolveAssetsDir } from "./utils/asset-prefix.js";
35
+ import { RESOLVED_VIRTUAL_GOOGLE_FONTS, VIRTUAL_GOOGLE_FONTS, createGoogleFontsPlugin, createLocalFontsPlugin, generateGoogleFontsVirtualModule, parseStaticObjectLiteral } from "./plugins/fonts.js";
36
+ import { getDepOptimizeNodeEnvOptions, getViteMajorVersion, serializeViteDefine } from "./utils/vite-version.js";
37
+ import { createRscCompatibilityId, findNextConfigPath, loadNextConfig, resolveNextConfig, resolveNextConfigInput } from "./config/next-config.js";
38
+ import { isNextDataPathname, parseNextDataPathname } from "./server/pages-data-route.js";
39
+ import { precompressAssets } from "./build/precompress.js";
40
+ import { ensureAssetsIgnore } from "./build/assets-ignore.js";
41
+ import { emitNextClientRuntimeManifests } from "./build/next-client-runtime-manifests.js";
42
+ import { collectInlineCssManifest, injectInlineCssManifestGlobal } from "./build/inline-css.js";
43
+ import { installDevStackSourcemapMiddleware } from "./server/dev-stack-sourcemap.js";
44
+ import { runPagesRequest } from "./server/pages-request-pipeline.js";
45
+ import { pagesRouteHasPriorityOverAppRoute, validateHybridRouteConflicts } from "./server/hybrid-route-priority.js";
46
+ import { VIRTUAL_MODULE_ID_RE } from "./utils/virtual-module.js";
47
+ import { renderVinextBuiltUrl } from "./utils/built-asset-url.js";
48
+ import { asyncHooksStubPlugin } from "./plugins/async-hooks-stub.js";
49
+ import { clientReferenceDedupPlugin } from "./plugins/client-reference-dedup.js";
50
+ import { dataUrlCssPlugin } from "./plugins/css-data-url.js";
51
+ import { createRscClientReferenceLoadersPlugin } from "./plugins/rsc-client-reference-loaders.js";
52
+ import { createInstrumentationClientTransformPlugin } from "./plugins/instrumentation-client.js";
53
+ import { INSTRUMENTATION_CLIENT_EMPTY_MODULE, generateInstrumentationClientInjectModule } from "./client/instrumentation-client-inject.js";
54
+ import { createMiddlewareServerOnlyPlugin } from "./plugins/middleware-server-only.js";
55
+ import { validateMiddlewareModuleExports } from "./plugins/middleware-export-validation.js";
56
+ import { createOptimizeImportsPlugin } from "./plugins/optimize-imports.js";
57
+ import { augmentSsrManifestFromBundle, relativeWithinRoot, tryRealpathSync } from "./build/ssr-manifest.js";
58
+ import { createDynamicPreloadMetadataPlugin } from "./plugins/dynamic-preload-metadata.js";
59
+ import { createOgAssetsPlugin, createOgInlineFetchAssetsPlugin } from "./plugins/og-assets.js";
60
+ import { generateRouteTypes } from "./typegen.js";
61
+ import { SSR_EXTERNAL_REACT_ENTRIES, VINEXT_OPTIMIZE_DEPS_EXCLUDE, mergeOptimizeDepsExclude } from "./plugins/rsc-client-shim-excludes.js";
62
+ import { createServerExternalsManifestPlugin } from "./plugins/server-externals-manifest.js";
63
+ import { VINEXT_CLIENT_ENTRY_MANIFEST } from "./utils/client-entry-manifest.js";
64
+ import { buildRuntimeGlobalsScript, computeClientRuntimeMetadata } from "./utils/client-runtime-metadata.js";
65
+ import { formatMissingCloudflarePluginError, hasWranglerConfig } from "./deploy.js";
66
+ import { resolvePostcssStringPlugins } from "./plugins/postcss.js";
67
+ import { buildSassPreprocessorOptions, createSassAwareFileSystemLoader, createSassTildeImporter } from "./plugins/sass.js";
68
+ import { createClientAssetFileNames, createClientCodeSplittingConfig, createClientFileNameConfig, createClientManualChunks, createClientOutputConfig, createRscFrameworkChunkOutputConfig, getBuildBundlerOptions, getClientTreeshakeConfigForVite, withBuildBundlerOptions } from "./build/client-build-config.js";
69
+ import { markCssUrlAssetReferences, restoreDedupedCssAssetReferences } from "./build/css-url-assets.js";
70
+ import { hasExportAllCandidate, stripServerExports, validatePageExports } from "./plugins/strip-server-exports.js";
71
+ import { removeConsoleCalls } from "./plugins/remove-console.js";
72
+ import { createImportMetaUrlPlugin } from "./plugins/import-meta-url.js";
73
+ import { createRequireContextPlugin } from "./plugins/require-context.js";
74
+ import { createExtensionlessDynamicImportPlugin } from "./plugins/extensionless-dynamic-import.js";
75
+ import { createWasmModuleImportPlugin } from "./plugins/wasm-module-import.js";
76
+ import { getTypeofWindowReplacement, replaceTypeofWindow } from "./plugins/typeof-window.js";
77
+ import { hasMdxFiles } from "./utils/mdx-scan.js";
78
+ import { scanPublicFileRoutes } from "./utils/public-routes.js";
79
+ import { staticExportApp, staticExportPages } from "./build/static-export.js";
80
+ import { createRequire } from "node:module";
81
+ import fs from "node:fs";
82
+ import path from "node:path";
83
+ import { loadEnv, parseAst, transformWithOxc } from "vite";
84
+ import { pathToFileURL } from "node:url";
85
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
86
+ import commonjs from "vite-plugin-commonjs";
87
+ import MagicString from "magic-string";
88
+ //#region src/index.ts
89
+ installSocketErrorBackstop();
90
+ function getCacheDirPrefix(cacheDir) {
91
+ const normalizedCacheDir = normalizePathSeparators(cacheDir);
92
+ return normalizedCacheDir.endsWith("/") ? normalizedCacheDir : `${normalizedCacheDir}/`;
93
+ }
94
+ function isInsideDirectory(dir, filePath) {
95
+ const relativePath = path.relative(dir, filePath);
96
+ return relativePath !== "" && !relativePath.startsWith("..") && !path.isAbsolute(relativePath);
97
+ }
98
+ function hasServerOnlyMarkerImport(code) {
99
+ if (!code.includes("server-only")) return false;
100
+ let ast;
101
+ try {
102
+ ast = parseAst(code);
103
+ } catch {
104
+ return false;
105
+ }
106
+ function walk(node) {
107
+ if (!node) return false;
108
+ if (Array.isArray(node)) return node.some((child) => walk(child));
109
+ if (typeof node !== "object") return false;
110
+ if (node.type === "ImportDeclaration") {
111
+ if (node.source?.value === "server-only") return true;
112
+ }
113
+ if (node.type === "CallExpression") {
114
+ const call = node;
115
+ if (call.callee?.type === "Identifier" && call.callee.name === "require" && call.arguments?.[0]?.type === "Literal" && call.arguments[0].value === "server-only") return true;
116
+ }
117
+ for (const key of Object.keys(node)) {
118
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "parent") continue;
119
+ const value = node[key];
120
+ if (Array.isArray(value)) {
121
+ if (value.some((child) => child && typeof child === "object" && walk(child))) return true;
122
+ } else if (value && typeof value === "object" && "type" in value) {
123
+ if (walk(value)) return true;
124
+ }
125
+ }
126
+ return false;
127
+ }
128
+ return walk(ast.body);
129
+ }
130
+ const __dirname = import.meta.dirname;
131
+ function resolveOptionalDependency(projectRoot, specifier) {
132
+ try {
133
+ return createRequire(path.join(projectRoot, "package.json")).resolve(specifier);
134
+ } catch {}
135
+ try {
136
+ return createRequire(import.meta.url).resolve(specifier);
137
+ } catch {}
138
+ return null;
139
+ }
140
+ async function loadVite7TsconfigPathsPlugin(projectRoot) {
141
+ const resolvedPath = resolveOptionalDependency(projectRoot, "vite-tsconfig-paths");
142
+ if (!resolvedPath) throw new Error("[vinext] Vite 7 requires the optional peer dependency vite-tsconfig-paths for tsconfig path alias support. Install vite-tsconfig-paths or upgrade to Vite 8.");
143
+ return (await import(pathToFileURL(resolvedPath).href)).default();
144
+ }
145
+ function resolveShimModulePath(shimsDir, moduleName) {
146
+ for (const ext of [
147
+ ".ts",
148
+ ".tsx",
149
+ ".js"
150
+ ]) {
151
+ const candidate = path.posix.join(shimsDir, `${moduleName}${ext}`);
152
+ if (fs.existsSync(candidate)) return candidate;
153
+ }
154
+ return path.posix.join(shimsDir, `${moduleName}.js`);
155
+ }
156
+ function isVercelOgImport(id) {
157
+ return id === "@vercel/og" || id === "@vercel/og.js";
158
+ }
159
+ function isVinextOgShimImporter(importer) {
160
+ if (!importer) return false;
161
+ const normalizedImporter = (importer.startsWith("\0") ? importer.slice(1) : importer).split("?")[0].replace(/\\/g, "/");
162
+ return normalizedImporter.endsWith("/shims/og.tsx") || normalizedImporter.endsWith("/shims/og.js") || normalizedImporter.endsWith("/dist/shims/og.js");
163
+ }
164
+ function toRelativeFileEntry(root, absPath) {
165
+ return path.relative(root, absPath).split(path.sep).join("/");
166
+ }
167
+ const TSCONFIG_FILES = ["tsconfig.json", "jsconfig.json"];
168
+ function resolveTsconfigPathCandidate(candidate) {
169
+ const candidates = candidate.endsWith(".json") ? [candidate] : [
170
+ candidate,
171
+ `${candidate}.json`,
172
+ path.join(candidate, "tsconfig.json")
173
+ ];
174
+ for (const item of candidates) if (fs.existsSync(item) && fs.statSync(item).isFile()) return item;
175
+ return null;
176
+ }
177
+ /**
178
+ * Normalize a tsconfig `extends` field into a list of specifier strings.
179
+ *
180
+ * TypeScript 5.0+ allows `extends` to be either a string or an array of
181
+ * strings. Matches Next.js's handling in
182
+ * packages/next/src/build/next-config-ts/transpile-config.ts, where parents
183
+ * are iterated in order and later entries override earlier ones.
184
+ */
185
+ function normalizeTsconfigExtends(extendsField) {
186
+ if (typeof extendsField === "string") return [extendsField];
187
+ if (Array.isArray(extendsField)) return extendsField.filter((value) => typeof value === "string");
188
+ return [];
189
+ }
190
+ function resolveTsconfigExtends(configPath, specifier) {
191
+ const fromDir = path.dirname(configPath);
192
+ if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("\\")) return resolveTsconfigPathCandidate(path.resolve(fromDir, specifier));
193
+ const requireFromConfig = createRequire(configPath);
194
+ const candidates = [
195
+ specifier,
196
+ `${specifier}.json`,
197
+ path.join(specifier, "tsconfig.json")
198
+ ];
199
+ for (const item of candidates) try {
200
+ return requireFromConfig.resolve(item);
201
+ } catch {}
202
+ return null;
203
+ }
204
+ function materializeTsconfigPathAliases(pathsConfig, baseUrl, projectRoot) {
205
+ const aliases = {};
206
+ for (const [find, rawTargets] of Object.entries(pathsConfig)) {
207
+ const target = Array.isArray(rawTargets) ? rawTargets.find((value) => typeof value === "string") : typeof rawTargets === "string" ? rawTargets : null;
208
+ if (!target) continue;
209
+ if (find.includes("*") || target.includes("*")) {
210
+ if (!find.endsWith("/*") || !target.endsWith("/*")) continue;
211
+ if (find.indexOf("*") !== find.length - 1 || target.indexOf("*") !== target.length - 1) continue;
212
+ const aliasKey = find.slice(0, -2);
213
+ const targetDir = target.slice(0, -2);
214
+ if (!aliasKey || !targetDir) continue;
215
+ aliases[aliasKey] = toViteAliasReplacement(path.resolve(baseUrl, targetDir), projectRoot);
216
+ continue;
217
+ }
218
+ aliases[find] = toViteAliasReplacement(path.resolve(baseUrl, target), projectRoot);
219
+ }
220
+ return aliases;
221
+ }
222
+ function toViteAliasReplacement(absolutePath, projectRoot) {
223
+ const normalizedPath = absolutePath.replace(/\\/g, "/");
224
+ const rootCandidates = new Set([projectRoot]);
225
+ const realRoot = tryRealpathSync(projectRoot);
226
+ if (realRoot) rootCandidates.add(realRoot);
227
+ const pathCandidates = new Set([absolutePath]);
228
+ const realPath = tryRealpathSync(absolutePath);
229
+ if (realPath) pathCandidates.add(realPath);
230
+ for (const rootCandidate of rootCandidates) for (const pathCandidate of pathCandidates) {
231
+ if (pathCandidate === rootCandidate) return normalizedPath;
232
+ const relativeId = relativeWithinRoot(rootCandidate, pathCandidate);
233
+ if (relativeId) return "/" + relativeId;
234
+ }
235
+ return normalizedPath;
236
+ }
237
+ function loadTsconfigPathAliases(configPath, projectRoot, seen = /* @__PURE__ */ new Set()) {
238
+ const normalizedPath = tryRealpathSync(configPath) ?? configPath;
239
+ if (seen.has(normalizedPath)) return {};
240
+ seen.add(normalizedPath);
241
+ let parsed = null;
242
+ try {
243
+ parsed = parseStaticObjectLiteral(fs.readFileSync(normalizedPath, "utf-8"));
244
+ } catch {
245
+ return {};
246
+ }
247
+ if (!parsed) return {};
248
+ let aliases = {};
249
+ for (const extendsSpecifier of normalizeTsconfigExtends(parsed.extends)) {
250
+ const extendedPath = resolveTsconfigExtends(normalizedPath, extendsSpecifier);
251
+ if (extendedPath) aliases = {
252
+ ...aliases,
253
+ ...loadTsconfigPathAliases(extendedPath, projectRoot, seen)
254
+ };
255
+ }
256
+ const compilerOptions = isUnknownRecord(parsed.compilerOptions) ? parsed.compilerOptions : null;
257
+ const pathsConfig = compilerOptions && isUnknownRecord(compilerOptions.paths) ? compilerOptions.paths : null;
258
+ if (!pathsConfig) return aliases;
259
+ const baseUrl = compilerOptions && typeof compilerOptions.baseUrl === "string" ? compilerOptions.baseUrl : ".";
260
+ const resolvedBaseUrl = path.resolve(path.dirname(normalizedPath), baseUrl);
261
+ return {
262
+ ...aliases,
263
+ ...materializeTsconfigPathAliases(pathsConfig, resolvedBaseUrl, projectRoot)
264
+ };
265
+ }
266
+ /**
267
+ * Read the vinext package version once at plugin load. Surfaced via
268
+ * `process.env.__NEXT_VERSION` define so `window.next.version` lands a
269
+ * real string instead of the `"vinext"` fallback. Resolved relative to
270
+ * this module's own `package.json`, not the project root.
271
+ *
272
+ * Defaults to `"vinext"` on read failure so a malformed install never
273
+ * breaks the build — only the diagnostic global loses fidelity.
274
+ */
275
+ let _vinextVersionCache = null;
276
+ function getVinextVersion() {
277
+ if (_vinextVersionCache !== null) return _vinextVersionCache;
278
+ try {
279
+ const pkgUrl = new URL("../package.json", import.meta.url);
280
+ const pkg = JSON.parse(fs.readFileSync(pkgUrl, "utf-8"));
281
+ _vinextVersionCache = typeof pkg.version === "string" ? pkg.version : "vinext";
282
+ } catch {
283
+ _vinextVersionCache = "vinext";
284
+ }
285
+ return _vinextVersionCache;
286
+ }
287
+ const _tsconfigAliasCache = /* @__PURE__ */ new Map();
288
+ function resolveTsconfigAliases(projectRoot) {
289
+ if (_tsconfigAliasCache.has(projectRoot)) return _tsconfigAliasCache.get(projectRoot);
290
+ let aliases = {};
291
+ for (const name of TSCONFIG_FILES) {
292
+ const candidate = path.join(projectRoot, name);
293
+ if (!fs.existsSync(candidate)) continue;
294
+ aliases = loadTsconfigPathAliases(candidate, projectRoot);
295
+ break;
296
+ }
297
+ _tsconfigAliasCache.set(projectRoot, aliases);
298
+ return aliases;
299
+ }
300
+ const VIRTUAL_SERVER_ENTRY = "virtual:vinext-server-entry";
301
+ const RESOLVED_SERVER_ENTRY = "\0virtual:vinext-server-entry";
302
+ const VIRTUAL_CLIENT_ENTRY = "virtual:vinext-client-entry";
303
+ const RESOLVED_CLIENT_ENTRY = "\0virtual:vinext-client-entry";
304
+ const VIRTUAL_RSC_ENTRY = "virtual:vinext-rsc-entry";
305
+ const RESOLVED_RSC_ENTRY = "\0virtual:vinext-rsc-entry";
306
+ const VIRTUAL_APP_SSR_ENTRY = "virtual:vinext-app-ssr-entry";
307
+ const RESOLVED_APP_SSR_ENTRY = "\0virtual:vinext-app-ssr-entry";
308
+ const VIRTUAL_APP_BROWSER_ENTRY = "virtual:vinext-app-browser-entry";
309
+ const RESOLVED_APP_BROWSER_ENTRY = "\0virtual:vinext-app-browser-entry";
310
+ const VIRTUAL_APP_CAPABILITIES = "virtual:vinext-app-capabilities";
311
+ const RESOLVED_APP_CAPABILITIES = "\0virtual:vinext-app-capabilities";
312
+ const RESOLVED_ROOT_PARAMS = "\0virtual:vinext-root-params";
313
+ /** Virtual module that registers config-driven cache adapters (see VinextOptions.cache). */
314
+ const RESOLVED_CACHE_ADAPTERS = "\0" + VIRTUAL_CACHE_ADAPTERS;
315
+ /** Virtual module for composed instrumentation-client bootstrap. */
316
+ const VIRTUAL_INSTRUMENTATION_CLIENT = "private-next-instrumentation-client";
317
+ const RESOLVED_INSTRUMENTATION_CLIENT = `${VIRTUAL_INSTRUMENTATION_CLIENT}.mjs`;
318
+ /** Image file extensions handled by the vinext:image-imports plugin.
319
+ * Shared between the Rolldown hook filter and the transform handler regex. */
320
+ const IMAGE_EXTS = "png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?";
321
+ /** Matches a trailing image extension on an import path. Built once: `IMAGE_EXTS`
322
+ * is constant, so there is no need to recompile this per transform invocation. */
323
+ const IMAGE_EXT_RE = new RegExp(`\\.(${IMAGE_EXTS})$`);
324
+ function createStaticImageAsset(imagePath) {
325
+ const source = fs.readFileSync(imagePath);
326
+ const extension = path.extname(imagePath);
327
+ return {
328
+ fileName: `media/${path.basename(imagePath, extension)}.${createHash("sha256").update(source).digest("hex").slice(0, 8)}${extension}`,
329
+ source
330
+ };
331
+ }
332
+ /**
333
+ * Absolute path to vinext's shims directory, with a trailing slash. Normalized
334
+ * to forward slashes because it is prefix-matched against Vite module ids (which
335
+ * Vite always normalizes to forward slashes) in the font plugins and
336
+ * clientManualChunks — a raw path.resolve value has backslashes on Windows and
337
+ * the `id.startsWith(_shimsDir)` checks would never match.
338
+ */
339
+ const _shimsDir = normalizePathSeparators(path.resolve(__dirname, "shims")) + "/";
340
+ const _fontGoogleShimPath = resolveShimModulePath(_shimsDir, "font-google");
341
+ const _appBrowserServerActionClientPath = resolveShimModulePath(normalizePathSeparators(path.resolve(__dirname, "server")), "app-browser-server-action-client");
342
+ const _appRscHandlerPath = resolveShimModulePath(normalizePathSeparators(path.resolve(__dirname, "server")), "app-rsc-handler");
343
+ const _canExternalizeAppRscHandler = _appRscHandlerPath.endsWith(".js");
344
+ function isValidExportIdentifier(name) {
345
+ return /^[$A-Z_a-z][$\w]*$/.test(name);
346
+ }
347
+ function isVirtualEntryFacade(id, virtualId) {
348
+ if (!id) return false;
349
+ const cleanId = id.startsWith("\0") ? id.slice(1) : id;
350
+ return cleanId === virtualId || cleanId.endsWith("/" + virtualId) || cleanId.endsWith("\\" + virtualId);
351
+ }
352
+ /**
353
+ * Returns the leading React `"use client"` or `"use server"` directive after
354
+ * stripping leading comments, hashbang, and whitespace.
355
+ *
356
+ * Used by `vinext:jsx-in-js` to opt `.js` files inside `node_modules` into the
357
+ * JSX transform. We mirror `@vitejs/plugin-rsc`'s detection by looking at the
358
+ * directive prologue rather than scanning the whole file — `code.includes`
359
+ * alone would match incidental occurrences in template literals or comments.
360
+ */
361
+ function getLeadingReactDirective(code) {
362
+ let i = 0;
363
+ const len = code.length;
364
+ if (code.charCodeAt(0) === 65279) i = 1;
365
+ if (code[i] === "#" && code[i + 1] === "!") {
366
+ const nl = code.indexOf("\n", i);
367
+ if (nl === -1) return null;
368
+ i = nl + 1;
369
+ }
370
+ while (i < len) {
371
+ while (i < len && /\s/.test(code[i] ?? "")) i++;
372
+ if (i >= len) return null;
373
+ if (code[i] === "/" && code[i + 1] === "/") {
374
+ const nl = code.indexOf("\n", i + 2);
375
+ if (nl === -1) return null;
376
+ i = nl + 1;
377
+ continue;
378
+ }
379
+ if (code[i] === "/" && code[i + 1] === "*") {
380
+ const end = code.indexOf("*/", i + 2);
381
+ if (end === -1) return null;
382
+ i = end + 2;
383
+ continue;
384
+ }
385
+ const quote = code[i];
386
+ if (quote !== "\"" && quote !== "'") return null;
387
+ const closing = code.indexOf(quote, i + 1);
388
+ if (closing === -1) return null;
389
+ const directive = code.slice(i + 1, closing);
390
+ if (directive === "use client" || directive === "use server") return directive;
391
+ i = closing + 1;
392
+ while (i < len && (code[i] === ";" || code[i] === " " || code[i] === " ")) i++;
393
+ if (code[i] === "\n") i++;
394
+ }
395
+ return null;
396
+ }
397
+ function hasReactDirective(code) {
398
+ return getLeadingReactDirective(code) !== null;
399
+ }
400
+ function generateRootParamsModule(rootParamNames) {
401
+ const names = Array.from(new Set(rootParamNames)).filter(isValidExportIdentifier).sort();
402
+ if (names.length === 0) return "export {};\n";
403
+ const rootParamsShimPath = resolveShimModulePath(_shimsDir, "root-params");
404
+ const exports = names.map((name) => `export function ${name}() { return getRootParam(${JSON.stringify(name)}); }`).join("\n");
405
+ return `import { getRootParam } from ${JSON.stringify(rootParamsShimPath)};\n${exports}\n`;
406
+ }
407
+ /**
408
+ * Shims with a `.react-server.ts` variant for the RSC environment.
409
+ * Maps import specifier → base shim name. In the RSC env, resolveId
410
+ * appends `.react-server`; in other envs it resolves to the base.
411
+ *
412
+ * These MUST NOT appear in `nextShimMap` (resolve.alias) because Vite's
413
+ * alias plugin runs before user `enforce:"pre"` plugins — aliases are
414
+ * unoverridable. Keeping them out of the alias lets the resolveId hook
415
+ * control resolution per-environment.
416
+ *
417
+ * To add a new react-server shim:
418
+ * 1. Create `<name>.react-server.ts` in src/shims/
419
+ * 2. Add entries here for each import specifier.
420
+ */
421
+ const _reactServerShims = new Map([
422
+ ["next/navigation", "navigation"],
423
+ ["next/navigation.js", "navigation"],
424
+ ["next/dist/client/components/navigation", "navigation"],
425
+ ["next/error", "error"],
426
+ ["next/error.js", "error"]
427
+ ]);
428
+ const clientManualChunks = createClientManualChunks(_shimsDir);
429
+ const clientCodeSplittingConfig = createClientCodeSplittingConfig(clientManualChunks);
430
+ const appClientManualChunks = createClientManualChunks(_shimsDir, true);
431
+ const appClientCodeSplittingConfig = createClientCodeSplittingConfig(appClientManualChunks);
432
+ function getClientOutputConfigForVite(viteMajorVersion, assetsDir, preserveAppRouteBoundaries = false) {
433
+ const manualChunks = preserveAppRouteBoundaries ? appClientManualChunks : clientManualChunks;
434
+ const codeSplitting = preserveAppRouteBoundaries ? appClientCodeSplittingConfig : clientCodeSplittingConfig;
435
+ return viteMajorVersion >= 8 ? {
436
+ ...createClientFileNameConfig(assetsDir),
437
+ assetFileNames: createClientAssetFileNames(assetsDir),
438
+ codeSplitting
439
+ } : createClientOutputConfig(manualChunks, assetsDir);
440
+ }
441
+ function vinext(options = {}) {
442
+ const viteMajorVersion = getViteMajorVersion();
443
+ let root;
444
+ let pagesDir;
445
+ let canonicalPagesDir;
446
+ let appDir;
447
+ let hasAppDir = false;
448
+ let hasPagesDir = false;
449
+ let nextConfig;
450
+ let fileMatcher;
451
+ let middlewarePath = null;
452
+ let instrumentationPath = null;
453
+ let instrumentationClientPath = null;
454
+ let clientInjectModule = null;
455
+ let clientAssetsInlineLimit = 0;
456
+ let hasCloudflarePlugin = false;
457
+ let warnedInlineNextConfigOverride = false;
458
+ let hasNitroPlugin = false;
459
+ let rscCompatibilityId;
460
+ const draftModeSecret = randomUUID();
461
+ const sassComposesLoader = createSassAwareFileSystemLoader();
462
+ const typeofWindowIdFilter = { exclude: /(?!)/ };
463
+ let rscClassificationManifest = null;
464
+ const shimsDir = normalizePathSeparators(path.resolve(__dirname, "shims"));
465
+ const canonicalize = (p) => normalizePathSeparators(tryRealpathSync(p) ?? p);
466
+ const pageTransformCanonicalPaths = /* @__PURE__ */ new Map();
467
+ const canonicalizePageTransformPath = (modulePath) => {
468
+ const cached = pageTransformCanonicalPaths.get(modulePath);
469
+ if (cached) return cached;
470
+ const canonicalPath = canonicalize(modulePath);
471
+ pageTransformCanonicalPaths.set(modulePath, canonicalPath);
472
+ return canonicalPath;
473
+ };
474
+ const isWithinPagesDirectory = (modulePath) => modulePath === pagesDir || modulePath.startsWith(`${pagesDir}/`) || modulePath === canonicalPagesDir || modulePath.startsWith(`${canonicalPagesDir}/`);
475
+ const isApiPage = (canonicalId) => {
476
+ const relativePath = fileMatcher.stripExtension(canonicalId.slice(canonicalPagesDir.length));
477
+ return relativePath === "/api" || relativePath.startsWith("/api/");
478
+ };
479
+ const dynamicShimPaths = new Set([
480
+ resolveShimModulePath(shimsDir, "headers"),
481
+ resolveShimModulePath(shimsDir, "server"),
482
+ resolveShimModulePath(shimsDir, "cache")
483
+ ].map(canonicalize));
484
+ let nextShimMap = {};
485
+ /**
486
+ * Generate the virtual SSR server entry module.
487
+ * This is the entry point for `vite build --ssr`.
488
+ */
489
+ async function generateServerEntry$1() {
490
+ return generateServerEntry(pagesDir, nextConfig, fileMatcher, middlewarePath, instrumentationPath);
491
+ }
492
+ /**
493
+ * Generate the virtual client hydration entry module.
494
+ * This is the entry point for `vite build` (client bundle).
495
+ *
496
+ * It maps route patterns to dynamic imports of page modules so Vite
497
+ * code-splits each page into its own chunk. At runtime it reads
498
+ * __NEXT_DATA__ to determine which page to hydrate.
499
+ */
500
+ async function generateClientEntry$1() {
501
+ const appPrefetchRoutes = hasAppDir ? (await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher)).map((route) => isLinkPrefetchRoute(route) ? toLinkPrefetchRoute(route) : toDocumentOnlyAppRoute(route)) : [];
502
+ return generateClientEntry(pagesDir, nextConfig, fileMatcher, {
503
+ appPrefetchRoutes,
504
+ instrumentationClientPath
505
+ });
506
+ }
507
+ async function writeRouteTypes() {
508
+ if (!hasAppDir) return;
509
+ await generateRouteTypes({
510
+ root,
511
+ appDir,
512
+ pageExtensions: nextConfig.pageExtensions
513
+ });
514
+ }
515
+ const autoRsc = options.rsc !== false;
516
+ const earlyBaseDir = options.appDir ?? process.cwd();
517
+ const earlyAppDirExists = !options.disableAppRouter && (fs.existsSync(path.join(earlyBaseDir, "app")) || fs.existsSync(path.join(earlyBaseDir, "src", "app")));
518
+ let resolvedReactPath = null;
519
+ let resolvedRscPath = null;
520
+ let resolvedRscTransformsPath = null;
521
+ let rscPluginModulePromise = null;
522
+ resolvedReactPath = resolveOptionalDependency(earlyBaseDir, "@vitejs/plugin-react");
523
+ resolvedRscPath = resolveOptionalDependency(earlyBaseDir, "@vitejs/plugin-rsc");
524
+ resolvedRscTransformsPath = resolveOptionalDependency(earlyBaseDir, "@vitejs/plugin-rsc/transforms");
525
+ let rscPluginPromise = null;
526
+ if (earlyAppDirExists && autoRsc) {
527
+ if (!resolvedRscPath) throw new Error("vinext: App Router detected but @vitejs/plugin-rsc is not installed.\nRun: " + detectPackageManager(process.cwd()) + " @vitejs/plugin-rsc");
528
+ const rscImport = import(pathToFileURL(resolvedRscPath).href);
529
+ rscPluginModulePromise = rscImport;
530
+ rscPluginPromise = rscImport.then((mod) => {
531
+ const rsc = mod.default;
532
+ return rsc({ entries: {
533
+ rsc: VIRTUAL_RSC_ENTRY,
534
+ ssr: VIRTUAL_APP_SSR_ENTRY,
535
+ client: VIRTUAL_APP_BROWSER_ENTRY
536
+ } });
537
+ }).catch((cause) => {
538
+ throw new Error("vinext: Failed to load @vitejs/plugin-rsc.", { cause });
539
+ });
540
+ }
541
+ async function resolveHasServerActions(config) {
542
+ if (config.command !== "build" || !rscPluginModulePromise) return true;
543
+ const { getPluginApi } = await rscPluginModulePromise;
544
+ const pluginApi = getPluginApi(config);
545
+ if (!pluginApi || pluginApi.manager.isScanBuild) return true;
546
+ return Object.keys(pluginApi.manager.serverReferenceMetaMap).length > 0;
547
+ }
548
+ const reactOptions = options.react && options.react !== true ? options.react : void 0;
549
+ let reactPluginPromise = null;
550
+ if (options.react !== false) {
551
+ if (!resolvedReactPath) throw new Error("vinext: @vitejs/plugin-react is not installed.\nRun: " + detectPackageManager(process.cwd()) + " @vitejs/plugin-react");
552
+ reactPluginPromise = import(pathToFileURL(resolvedReactPath).href).then((mod) => mod.default(reactOptions)).catch((cause) => {
553
+ throw new Error("vinext: Failed to load @vitejs/plugin-react.", { cause });
554
+ });
555
+ }
556
+ const imageImportDimCache = /* @__PURE__ */ new Map();
557
+ const staticImageAssets = /* @__PURE__ */ new Map();
558
+ const staticImageImportsByModule = /* @__PURE__ */ new Map();
559
+ const writtenStaticImageFiles = /* @__PURE__ */ new Set();
560
+ let mdxDelegate = null;
561
+ let mdxDelegatePromise = null;
562
+ let hasUserMdxPlugin = false;
563
+ let warnedMissingMdxPlugin = false;
564
+ async function ensureMdxDelegate(reason) {
565
+ if (mdxDelegate || hasUserMdxPlugin) return mdxDelegate;
566
+ if (!mdxDelegatePromise) mdxDelegatePromise = (async () => {
567
+ try {
568
+ const mdxRollup = await import("@mdx-js/rollup");
569
+ const mdxFactory = mdxRollup.default ?? mdxRollup;
570
+ const mdxOpts = {};
571
+ if (nextConfig.mdx) {
572
+ if (nextConfig.mdx.remarkPlugins) mdxOpts.remarkPlugins = nextConfig.mdx.remarkPlugins;
573
+ if (nextConfig.mdx.rehypePlugins) mdxOpts.rehypePlugins = nextConfig.mdx.rehypePlugins;
574
+ if (nextConfig.mdx.recmaPlugins) mdxOpts.recmaPlugins = nextConfig.mdx.recmaPlugins;
575
+ }
576
+ const delegate = mdxFactory(mdxOpts);
577
+ mdxDelegate = delegate;
578
+ if (reason === "detected") if (nextConfig.mdx) console.log("[vinext] Auto-injected @mdx-js/rollup with remark/rehype plugins from next.config");
579
+ else console.log("[vinext] Auto-injected @mdx-js/rollup for MDX support");
580
+ else console.log("[vinext] Auto-injected @mdx-js/rollup for on-demand MDX support");
581
+ return delegate;
582
+ } catch {
583
+ if (reason === "detected" && !warnedMissingMdxPlugin) {
584
+ warnedMissingMdxPlugin = true;
585
+ console.warn("[vinext] MDX files detected but @mdx-js/rollup is not installed. Install it with: " + detectPackageManager(process.cwd()) + " @mdx-js/rollup");
586
+ }
587
+ return null;
588
+ }
589
+ })();
590
+ return mdxDelegatePromise;
591
+ }
592
+ const plugins = [
593
+ ...viteMajorVersion >= 8 ? [] : [loadVite7TsconfigPathsPlugin(earlyBaseDir)],
594
+ reactPluginPromise,
595
+ commonjs(),
596
+ ...viteMajorVersion >= 8 ? [{
597
+ name: "vinext:jsx-in-js",
598
+ enforce: "pre",
599
+ transform: {
600
+ filter: { id: /\.m?js(?:\?.*)?$/ },
601
+ async handler(code, id) {
602
+ const cleanId = id.split("?")[0];
603
+ if (isInsideDirectory(__dirname, cleanId)) return;
604
+ if (cleanId.includes("/node_modules/")) {
605
+ if (!code.includes("use client") && !code.includes("use server")) return;
606
+ if (!hasReactDirective(code)) return;
607
+ }
608
+ const result = await transformWithOxc(code, id, {
609
+ lang: "jsx",
610
+ jsx: { runtime: "automatic" },
611
+ sourcemap: true
612
+ });
613
+ return {
614
+ code: result.code,
615
+ map: result.map
616
+ };
617
+ }
618
+ }
619
+ }] : [],
620
+ createMiddlewareServerOnlyPlugin({
621
+ getMiddlewarePath: () => middlewarePath,
622
+ getCanonicalMiddlewarePath: () => middlewarePath ? tryRealpathSync(middlewarePath) ?? middlewarePath : null,
623
+ serverOnlyShimPath: resolveShimModulePath(shimsDir, "server-only")
624
+ }),
625
+ dataUrlCssPlugin(),
626
+ {
627
+ name: "vinext:config",
628
+ enforce: "pre",
629
+ async config(config, env) {
630
+ root = normalizePathSeparators(config.root ?? process.cwd());
631
+ const userResolve = config.resolve;
632
+ const shouldEnableNativeTsconfigPaths = viteMajorVersion >= 8 && userResolve?.tsconfigPaths === void 0;
633
+ const tsconfigPathAliases = resolveTsconfigAliases(root);
634
+ const mode = env?.mode ?? "development";
635
+ const dotenvVars = loadEnv(mode, config.envDir ?? root, "");
636
+ for (const [key, value] of Object.entries(dotenvVars)) if (process.env[key] === void 0) process.env[key] = value;
637
+ let resolvedNodeEnv;
638
+ if (mode === "test") resolvedNodeEnv = "test";
639
+ else if (env?.command === "build" || env?.isPreview === true) resolvedNodeEnv = "production";
640
+ else resolvedNodeEnv = "development";
641
+ if (process.env.NODE_ENV !== resolvedNodeEnv) process.env.NODE_ENV = resolvedNodeEnv;
642
+ let baseDir;
643
+ if (options.appDir) baseDir = normalizePathSeparators(path.isAbsolute(options.appDir) ? options.appDir : path.resolve(root, options.appDir));
644
+ else {
645
+ const hasRootApp = fs.existsSync(path.posix.join(root, "app"));
646
+ const hasRootPages = fs.existsSync(path.posix.join(root, "pages"));
647
+ const hasSrcApp = fs.existsSync(path.posix.join(root, "src", "app"));
648
+ const hasSrcPages = fs.existsSync(path.posix.join(root, "src", "pages"));
649
+ if (hasRootApp || hasRootPages) baseDir = root;
650
+ else if (hasSrcApp || hasSrcPages) baseDir = path.posix.join(root, "src");
651
+ else baseDir = root;
652
+ }
653
+ pagesDir = path.posix.join(baseDir, "pages");
654
+ canonicalPagesDir = canonicalize(pagesDir);
655
+ appDir = path.posix.join(baseDir, "app");
656
+ hasPagesDir = fs.existsSync(pagesDir);
657
+ hasAppDir = !options.disableAppRouter && fs.existsSync(appDir);
658
+ if (!nextConfig) {
659
+ const phase = env?.command === "build" ? PHASE_PRODUCTION_BUILD : PHASE_DEVELOPMENT_SERVER;
660
+ let rawConfig;
661
+ if (options.nextConfig) {
662
+ const diskConfigPath = findNextConfigPath(root);
663
+ if (diskConfigPath && !warnedInlineNextConfigOverride) {
664
+ warnedInlineNextConfigOverride = true;
665
+ console.warn(`[vinext] vinext({ nextConfig }) overrides ${path.basename(diskConfigPath)}. Remove one of the config sources to avoid drift.`);
666
+ }
667
+ rawConfig = await resolveNextConfigInput(options.nextConfig, phase);
668
+ } else rawConfig = await loadNextConfig(root, phase);
669
+ nextConfig = await resolveNextConfig(rawConfig, root, { dev: env?.command === "serve" && env?.isPreview !== true });
670
+ const sharedBuildId = process.env.__VINEXT_SHARED_BUILD_ID;
671
+ if (sharedBuildId && sharedBuildId.length > 0) nextConfig = {
672
+ ...nextConfig,
673
+ buildId: sharedBuildId
674
+ };
675
+ }
676
+ if (rscCompatibilityId === void 0) {
677
+ const sharedRscCompatibilityId = process.env.__VINEXT_SHARED_RSC_COMPATIBILITY_ID;
678
+ rscCompatibilityId = sharedRscCompatibilityId && sharedRscCompatibilityId.length > 0 ? sharedRscCompatibilityId : createRscCompatibilityId(nextConfig);
679
+ }
680
+ fileMatcher = createValidFileMatcher(nextConfig.pageExtensions);
681
+ instrumentationPath = findInstrumentationFile(root, fileMatcher);
682
+ instrumentationClientPath = findInstrumentationClientFile(root, fileMatcher);
683
+ const middlewareConventionDir = canonicalize(baseDir) === canonicalize(path.posix.join(root, "src")) ? path.posix.join(root, "src") : root;
684
+ middlewarePath = findMiddlewareFile(root, fileMatcher, middlewareConventionDir);
685
+ const instrumentationClientInjects = nextConfig.instrumentationClientInject.map((spec) => spec.startsWith("./") || spec.startsWith("../") ? path.resolve(root, spec) : spec);
686
+ clientInjectModule = instrumentationClientInjects.length ? generateInstrumentationClientInjectModule(instrumentationClientInjects, instrumentationClientPath, INSTRUMENTATION_CLIENT_EMPTY_MODULE) : null;
687
+ if (env?.command === "build") await writeRouteTypes();
688
+ const defines = getNextPublicEnvDefines();
689
+ const userNodeEnvDefine = config.define?.["process.env.NODE_ENV"];
690
+ const hasUserNodeEnvDefine = Object.hasOwn(config.define ?? {}, "process.env.NODE_ENV");
691
+ const nodeEnvDefine = hasUserNodeEnvDefine ? serializeViteDefine(userNodeEnvDefine) : JSON.stringify(resolvedNodeEnv);
692
+ if (!hasUserNodeEnvDefine) defines["process.env.NODE_ENV"] = nodeEnvDefine;
693
+ for (const [key, value] of Object.entries(nextConfig.env)) {
694
+ if (key === "NODE_ENV") continue;
695
+ defines[`process.env.${key}`] = JSON.stringify(value);
696
+ }
697
+ defines["process.env.__NEXT_ROUTER_BASEPATH"] = JSON.stringify(nextConfig.basePath);
698
+ defines["process.env.__VINEXT_HAS_PAGES_ROUTER"] = JSON.stringify(String(hasPagesDir));
699
+ defines["process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME"] = JSON.stringify(String(nextConfig.staleTimes.static));
700
+ defines["process.env.__VINEXT_PREFETCH_INLINING"] = JSON.stringify(nextConfig.prefetchInlining ? "true" : "false");
701
+ defines["process.env.__NEXT_GESTURE_TRANSITION"] = JSON.stringify(nextConfig.gestureTransition);
702
+ defines["process.env.__NEXT_APP_NAV_FAIL_HANDLING"] = JSON.stringify(nextConfig.appNavFailHandling);
703
+ defines["process.env.__NEXT_SCROLL_RESTORATION"] = JSON.stringify(nextConfig.scrollRestoration ? "true" : "false");
704
+ defines["process.env.__VINEXT_TRAILING_SLASH"] = JSON.stringify(nextConfig.trailingSlash ? "true" : "false");
705
+ defines["process.env.__VINEXT_IMAGE_REMOTE_PATTERNS"] = JSON.stringify(JSON.stringify(nextConfig.images?.remotePatterns ?? []));
706
+ defines["process.env.__VINEXT_IMAGE_DOMAINS"] = JSON.stringify(JSON.stringify(nextConfig.images?.domains ?? []));
707
+ {
708
+ const deviceSizes = nextConfig.images?.deviceSizes ?? [
709
+ 640,
710
+ 750,
711
+ 828,
712
+ 1080,
713
+ 1200,
714
+ 1920,
715
+ 2048,
716
+ 3840
717
+ ];
718
+ const imageSizes = nextConfig.images?.imageSizes ?? [
719
+ 16,
720
+ 32,
721
+ 48,
722
+ 64,
723
+ 96,
724
+ 128,
725
+ 256,
726
+ 384
727
+ ];
728
+ defines["process.env.__VINEXT_IMAGE_DEVICE_SIZES"] = JSON.stringify(JSON.stringify(deviceSizes));
729
+ defines["process.env.__VINEXT_IMAGE_SIZES"] = JSON.stringify(JSON.stringify(imageSizes));
730
+ defines["process.env.__VINEXT_IMAGE_QUALITIES"] = JSON.stringify(JSON.stringify(nextConfig.images?.qualities ?? null));
731
+ }
732
+ defines["process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_SVG"] = JSON.stringify(String(nextConfig.images?.dangerouslyAllowSVG ?? false));
733
+ defines["process.env.__VINEXT_IMAGE_DANGEROUSLY_ALLOW_LOCAL_IP"] = JSON.stringify(String(nextConfig.images?.dangerouslyAllowLocalIP ?? false));
734
+ defines["process.env.__VINEXT_BUILD_ID"] = JSON.stringify(nextConfig.buildId);
735
+ defines["process.env.__VINEXT_RSC_COMPATIBILITY_ID"] = JSON.stringify(rscCompatibilityId);
736
+ defines["process.env.__VINEXT_DEPLOYMENT_ID"] = JSON.stringify(nextConfig.deploymentId ?? "");
737
+ defines["process.env.NEXT_DEPLOYMENT_ID"] = nextConfig.deploymentId ? JSON.stringify(nextConfig.deploymentId) : "false";
738
+ defines["process.env.NEXT_RUNTIME"] = "\"\"";
739
+ defines["process.env.__NEXT_VERSION"] = JSON.stringify(getVinextVersion());
740
+ defines["process.env.__NEXT_APP_SHELLS"] = JSON.stringify(nextConfig.appShells);
741
+ defines["process.env.__NEXT_CACHE_COMPONENTS"] = JSON.stringify(nextConfig.cacheComponents ?? false);
742
+ for (const [key, value] of Object.entries(nextConfig.compilerDefine)) {
743
+ if (key in defines) throw new Error(`The \`compiler.define\` option is configured to replace the \`${key}\` variable. This variable is either part of a built-in or is already configured.`);
744
+ defines[key] = value;
745
+ }
746
+ for (const key of Object.keys(nextConfig.compilerDefineServer)) if (key in defines) throw new Error(`The \`compiler.defineServer\` option is configured to replace the \`${key}\` variable. This variable is either part of a built-in or is already configured.`);
747
+ nextShimMap = Object.fromEntries(Object.entries({
748
+ "next/link": path.posix.join(shimsDir, "link"),
749
+ "next/head": path.posix.join(shimsDir, "head"),
750
+ "next/router": path.posix.join(shimsDir, "router"),
751
+ "next/compat/router": path.posix.join(shimsDir, "compat-router"),
752
+ "next/image": path.posix.join(shimsDir, "image"),
753
+ "next/legacy/image": path.posix.join(shimsDir, "legacy-image"),
754
+ "next/dynamic": path.posix.join(shimsDir, "dynamic"),
755
+ "next/app": path.posix.join(shimsDir, "app"),
756
+ "next/document": path.posix.join(shimsDir, "document"),
757
+ "next/config": path.posix.join(shimsDir, "config"),
758
+ "next/script": path.posix.join(shimsDir, "script"),
759
+ "next/server": path.posix.join(shimsDir, "server"),
760
+ "next/headers": path.posix.join(shimsDir, "headers"),
761
+ "next/font/google": path.posix.join(shimsDir, "font-google"),
762
+ "next/font/local": path.posix.join(shimsDir, "font-local"),
763
+ "next/cache": path.posix.join(shimsDir, "cache"),
764
+ "next/form": path.posix.join(shimsDir, "form"),
765
+ "next/og": path.posix.join(shimsDir, "og"),
766
+ "next/web-vitals": path.posix.join(shimsDir, "web-vitals"),
767
+ "next/amp": path.posix.join(shimsDir, "amp"),
768
+ "next/offline": path.posix.join(shimsDir, "offline"),
769
+ "next/constants": path.posix.join(shimsDir, "constants"),
770
+ "next/dist/shared/lib/app-router-context.shared-runtime": path.posix.join(shimsDir, "internal", "app-router-context"),
771
+ "next/dist/shared/lib/app-router-context": path.posix.join(shimsDir, "internal", "app-router-context"),
772
+ "next/dist/shared/lib/router-context.shared-runtime": path.posix.join(shimsDir, "internal", "router-context"),
773
+ "next/dist/shared/lib/utils": path.posix.join(shimsDir, "internal", "utils"),
774
+ "next/dist/server/api-utils": path.posix.join(shimsDir, "internal", "api-utils"),
775
+ "next/dist/server/web/spec-extension/cookies": path.posix.join(shimsDir, "internal", "cookies"),
776
+ "next/dist/compiled/@edge-runtime/cookies": path.posix.join(shimsDir, "internal", "cookies"),
777
+ "next/dist/server/app-render/work-unit-async-storage.external": path.posix.join(shimsDir, "internal", "work-unit-async-storage"),
778
+ "next/dist/client/components/work-unit-async-storage.external": path.posix.join(shimsDir, "internal", "work-unit-async-storage"),
779
+ "next/dist/client/components/request-async-storage.external": path.posix.join(shimsDir, "internal", "work-unit-async-storage"),
780
+ "next/dist/client/components/request-async-storage": path.posix.join(shimsDir, "internal", "work-unit-async-storage"),
781
+ "next/dist/server/request/root-params": path.posix.join(shimsDir, "root-params"),
782
+ "next/dist/server/config-shared": path.posix.join(shimsDir, "internal", "utils"),
783
+ "server-only": path.posix.join(shimsDir, "server-only"),
784
+ "client-only": path.posix.join(shimsDir, "client-only"),
785
+ "vinext/error-boundary": path.posix.join(shimsDir, "error-boundary"),
786
+ "vinext/layout-segment-context": path.posix.join(shimsDir, "layout-segment-context"),
787
+ "vinext/metadata": path.posix.join(shimsDir, "metadata"),
788
+ "vinext/fetch-cache": path.posix.join(shimsDir, "fetch-cache"),
789
+ "vinext/cache-runtime": path.posix.join(shimsDir, "cache-runtime"),
790
+ "vinext/navigation-state": path.posix.join(shimsDir, "navigation-state"),
791
+ "vinext/unified-request-context": path.posix.join(shimsDir, "unified-request-context"),
792
+ "vinext/pages-router-runtime": path.posix.join(shimsDir, "pages-router-runtime"),
793
+ "vinext/router-state": path.posix.join(shimsDir, "router-state"),
794
+ "vinext/head-state": path.posix.join(shimsDir, "head-state"),
795
+ "vinext/i18n-state": path.posix.join(shimsDir, "i18n-state"),
796
+ "vinext/i18n-context": path.posix.join(shimsDir, "i18n-context"),
797
+ "vinext/cache": path.resolve(__dirname, "cache"),
798
+ "vinext/instrumentation": path.resolve(__dirname, "server", "instrumentation"),
799
+ "vinext/instrumentation-client": path.resolve(__dirname, "client", "instrumentation-client"),
800
+ "vinext/dev-error-overlay": path.resolve(__dirname, "server", "dev-error-overlay"),
801
+ "vinext/html": path.resolve(__dirname, "server", "html"),
802
+ ...clientInjectModule === null ? { "private-next-instrumentation-client": instrumentationClientPath ?? INSTRUMENTATION_CLIENT_EMPTY_MODULE } : {}
803
+ }).flatMap(([k, v]) => k.startsWith("next/") ? [[k, v], [`${k}.js`, v]] : [[k, v]]));
804
+ const pluginsFlat = [];
805
+ function flattenPlugins(arr) {
806
+ for (const p of arr) if (Array.isArray(p)) flattenPlugins(p);
807
+ else if (p) pluginsFlat.push(p);
808
+ }
809
+ flattenPlugins(config.plugins ?? []);
810
+ hasCloudflarePlugin = pluginsFlat.some((p) => p && typeof p === "object" && "name" in p && typeof p.name === "string" && (p.name === "vite-plugin-cloudflare" || p.name.startsWith("vite-plugin-cloudflare:")));
811
+ hasNitroPlugin = pluginsFlat.some((p) => p && typeof p === "object" && "name" in p && typeof p.name === "string" && (p.name === "nitro" || p.name.startsWith("nitro:")));
812
+ let postcssOverride;
813
+ if (!config.css?.postcss || typeof config.css.postcss === "string") postcssOverride = await resolvePostcssStringPlugins(root);
814
+ const sassPreprocessorOptions = buildSassPreprocessorOptions(nextConfig.sassOptions);
815
+ hasUserMdxPlugin = pluginsFlat.some((p) => p && typeof p === "object" && "name" in p && typeof p.name === "string" && (p.name === "@mdx-js/rollup" || p.name === "mdx"));
816
+ if (!hasUserMdxPlugin && hasMdxFiles(root, hasAppDir ? appDir : null, hasPagesDir ? pagesDir : null)) await ensureMdxDelegate("detected");
817
+ const isSSR = !!config.build?.ssr;
818
+ const isMultiEnv = hasAppDir || hasCloudflarePlugin || hasNitroPlugin;
819
+ const hasBuildInput = getBuildBundlerOptions(config.build)?.input !== void 0;
820
+ const shouldInjectPlainPagesEnvironments = !hasAppDir && !hasCloudflarePlugin && !isSSR && !hasBuildInput;
821
+ const hasClientBuildEnvironment = hasAppDir || hasCloudflarePlugin || hasNitroPlugin || shouldInjectPlainPagesEnvironments;
822
+ const clientAssetsDir = resolveAssetsDir(nextConfig.assetPrefix ?? "");
823
+ clientAssetsInlineLimit = config.build?.assetsInlineLimit ?? 0;
824
+ const devHmrConfig = config.server?.hmr === false ? false : {
825
+ ...typeof config.server?.hmr === "object" ? config.server.hmr : {},
826
+ overlay: false
827
+ };
828
+ const cssModulesOverride = config.css?.modules === false || typeof config.css?.modules === "object" && "Loader" in config.css.modules ? {} : { modules: { Loader: sassComposesLoader.Loader } };
829
+ const viteConfig = {
830
+ appType: "custom",
831
+ build: {
832
+ ssrEmitAssets: true,
833
+ cssTarget: [
834
+ "chrome111",
835
+ "edge111",
836
+ "firefox114",
837
+ "safari15"
838
+ ],
839
+ assetsDir: clientAssetsDir,
840
+ ...!isSSR && !hasClientBuildEnvironment ? { assetsInlineLimit: clientAssetsInlineLimit } : {},
841
+ ...withBuildBundlerOptions(viteMajorVersion, {
842
+ onwarn: (() => {
843
+ const userOnwarn = getBuildBundlerOptions(config.build)?.onwarn;
844
+ return (warning, defaultHandler) => {
845
+ if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message?.includes("\"use client\"") || warning.message?.includes("\"use server\""))) return;
846
+ if (warning.code === "IMPORT_IS_UNDEFINED" && warning.message?.includes("generateStaticParams")) return;
847
+ if (warning.code === "IMPORT_IS_UNDEFINED" && /Import `(?:default|proxy|middleware)` will always be undefined/.test(warning.message ?? "") && /\b(?:proxy|middleware)\.\w+\b/.test(warning.message ?? "") && (warning.message?.includes("virtual:vinext-rsc-entry") || warning.message?.includes("virtual:vinext-server-entry"))) return;
848
+ if (userOnwarn) userOnwarn(warning, defaultHandler);
849
+ else defaultHandler(warning);
850
+ };
851
+ })(),
852
+ ...!isSSR && !isMultiEnv ? { treeshake: getClientTreeshakeConfigForVite(viteMajorVersion) } : {},
853
+ ...!isSSR && !isMultiEnv ? { output: getClientOutputConfigForVite(viteMajorVersion, clientAssetsDir) } : {}
854
+ })
855
+ },
856
+ server: {
857
+ cors: {
858
+ preflightContinue: true,
859
+ origin: /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/
860
+ },
861
+ hmr: devHmrConfig
862
+ },
863
+ ...hasCloudflarePlugin || hasNitroPlugin ? {} : config.ssr?.external === true ? { ssr: { external: true } } : { ssr: {
864
+ external: [
865
+ "react",
866
+ "react-dom",
867
+ "react-dom/server",
868
+ "ipaddr.js"
869
+ ],
870
+ noExternal: true
871
+ } },
872
+ resolve: {
873
+ alias: {
874
+ ...tsconfigPathAliases,
875
+ ...nextConfig.aliases,
876
+ ...nextShimMap
877
+ },
878
+ dedupe: [
879
+ "react",
880
+ "react-dom",
881
+ "react/jsx-runtime",
882
+ "react/jsx-dev-runtime"
883
+ ],
884
+ ...shouldEnableNativeTsconfigPaths ? { tsconfigPaths: true } : {}
885
+ },
886
+ ...viteMajorVersion >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } },
887
+ define: defines,
888
+ ...nextConfig.basePath ? { base: nextConfig.basePath + "/" } : {},
889
+ ...nextConfig.assetPrefix || nextConfig.deploymentId ? { experimental: { renderBuiltUrl: (filename, context) => renderVinextBuiltUrl(filename, nextConfig.assetPrefix, nextConfig.deploymentId, context.hostType) } } : {},
890
+ css: {
891
+ ...nextConfig.useLightningcss ? {
892
+ transformer: "lightningcss",
893
+ lightningcss: {
894
+ ...nextConfig.lightningCssFeatures.include ? { include: nextConfig.lightningCssFeatures.include } : {},
895
+ ...nextConfig.lightningCssFeatures.exclude ? { exclude: nextConfig.lightningCssFeatures.exclude } : {}
896
+ }
897
+ } : {},
898
+ ...postcssOverride ? { postcss: postcssOverride } : {},
899
+ preprocessorOptions: (() => {
900
+ const tildeImporter = createSassTildeImporter(root);
901
+ const baseOpts = {
902
+ ...sassPreprocessorOptions,
903
+ importers: [tildeImporter, ...sassPreprocessorOptions?.importers ?? []]
904
+ };
905
+ return {
906
+ scss: baseOpts,
907
+ sass: baseOpts
908
+ };
909
+ })(),
910
+ ...cssModulesOverride
911
+ }
912
+ };
913
+ const nextServerExternal = nextConfig?.serverExternalPackages ?? [];
914
+ const userSsrExternal = Array.isArray(config.ssr?.external) ? [...config.ssr.external, ...nextServerExternal] : config.ssr?.external === true ? true : nextServerExternal;
915
+ const externalizeSsrReactInDev = env.command === "serve" && !hasCloudflarePlugin && !hasNitroPlugin;
916
+ const incomingExclude = config.optimizeDeps?.exclude ?? [];
917
+ const incomingInclude = config.optimizeDeps?.include ?? [];
918
+ const depOptimizeAliasPlugin = {
919
+ name: "vinext:dep-optimize-alias",
920
+ resolveId(id) {
921
+ const shimBase = _reactServerShims.get(id);
922
+ if (shimBase !== void 0) return resolveShimModulePath(shimsDir, shimBase);
923
+ }
924
+ };
925
+ const depOptimizeNodeEnvOptions = getDepOptimizeNodeEnvOptions(viteMajorVersion, nodeEnvDefine);
926
+ viteConfig.optimizeDeps = {
927
+ exclude: mergeOptimizeDepsExclude(incomingExclude, VINEXT_OPTIMIZE_DEPS_EXCLUDE, ["@tailwindcss/oxide"]),
928
+ ...incomingInclude.length > 0 ? { include: incomingInclude } : {},
929
+ ...depOptimizeNodeEnvOptions,
930
+ rolldownOptions: {
931
+ ...depOptimizeNodeEnvOptions.rolldownOptions,
932
+ plugins: [depOptimizeAliasPlugin]
933
+ }
934
+ };
935
+ const pagesOptimizeEntries = !hasAppDir ? [...hasPagesDir ? [toRelativeFileEntry(root, pagesDir) + "/**/*.{tsx,ts,jsx,js}"] : [], ...[instrumentationPath, instrumentationClientPath].flatMap((entry) => entry ? [toRelativeFileEntry(root, entry)] : [])] : [];
936
+ if (hasAppDir) {
937
+ const appEntries = [`${path.relative(root, appDir)}/**/*.{tsx,ts,jsx,js}`];
938
+ const explicitInstrumentationEntries = [instrumentationPath, instrumentationClientPath].flatMap((entry) => entry ? [toRelativeFileEntry(root, entry)] : []);
939
+ const optimizeEntries = [...new Set([...appEntries, ...explicitInstrumentationEntries])];
940
+ const appClientInput = { index: VIRTUAL_APP_BROWSER_ENTRY };
941
+ if (hasPagesDir) appClientInput["vinext-client-entry"] = VIRTUAL_CLIENT_ENTRY;
942
+ viteConfig.environments = {
943
+ rsc: {
944
+ ...hasCloudflarePlugin || hasNitroPlugin ? {} : { resolve: {
945
+ external: userSsrExternal === true ? true : [
946
+ "satori",
947
+ "@resvg/resvg-js",
948
+ "yoga-wasm-web",
949
+ ...env?.command === "serve" && _canExternalizeAppRscHandler ? ["vinext/server/app-rsc-handler"] : [],
950
+ ...userSsrExternal
951
+ ],
952
+ ...userSsrExternal === true ? {} : { noExternal: true }
953
+ } },
954
+ optimizeDeps: {
955
+ exclude: mergeOptimizeDepsExclude(incomingExclude, VINEXT_OPTIMIZE_DEPS_EXCLUDE),
956
+ entries: optimizeEntries,
957
+ include: [...new Set([...incomingInclude, "react-server-dom-webpack/static.edge"])],
958
+ ...depOptimizeNodeEnvOptions
959
+ },
960
+ build: {
961
+ outDir: options.rscOutDir ?? "dist/server",
962
+ ...withBuildBundlerOptions(viteMajorVersion, {
963
+ input: { index: VIRTUAL_RSC_ENTRY },
964
+ output: createRscFrameworkChunkOutputConfig(viteMajorVersion)
965
+ })
966
+ }
967
+ },
968
+ ssr: {
969
+ ...hasCloudflarePlugin || hasNitroPlugin ? {} : { resolve: {
970
+ external: userSsrExternal === true ? true : [
971
+ ...userSsrExternal,
972
+ "ipaddr.js",
973
+ ...externalizeSsrReactInDev ? SSR_EXTERNAL_REACT_ENTRIES : []
974
+ ],
975
+ ...userSsrExternal === true ? {} : { noExternal: true }
976
+ } },
977
+ optimizeDeps: {
978
+ exclude: mergeOptimizeDepsExclude(incomingExclude, VINEXT_OPTIMIZE_DEPS_EXCLUDE, ["ipaddr.js"], userSsrExternal === true || externalizeSsrReactInDev ? SSR_EXTERNAL_REACT_ENTRIES : []),
979
+ entries: optimizeEntries,
980
+ ...depOptimizeNodeEnvOptions
981
+ },
982
+ build: {
983
+ outDir: options.ssrOutDir ?? "dist/server/ssr",
984
+ ...withBuildBundlerOptions(viteMajorVersion, { input: { index: VIRTUAL_APP_SSR_ENTRY } })
985
+ }
986
+ },
987
+ client: {
988
+ consumer: "client",
989
+ optimizeDeps: {
990
+ exclude: mergeOptimizeDepsExclude(incomingExclude, VINEXT_OPTIMIZE_DEPS_EXCLUDE, nextServerExternal),
991
+ entries: optimizeEntries,
992
+ include: [...new Set([
993
+ ...incomingInclude,
994
+ "react",
995
+ "react-dom",
996
+ "react-dom/client",
997
+ "react/jsx-runtime",
998
+ "react/jsx-dev-runtime"
999
+ ])]
1000
+ },
1001
+ build: {
1002
+ manifest: true,
1003
+ ...hasPagesDir ? { ssrManifest: true } : {},
1004
+ assetsInlineLimit: clientAssetsInlineLimit,
1005
+ ...withBuildBundlerOptions(viteMajorVersion, {
1006
+ input: appClientInput,
1007
+ output: getClientOutputConfigForVite(viteMajorVersion, clientAssetsDir, true),
1008
+ treeshake: getClientTreeshakeConfigForVite(viteMajorVersion)
1009
+ })
1010
+ }
1011
+ }
1012
+ };
1013
+ } else if (hasCloudflarePlugin) viteConfig.environments = { client: {
1014
+ consumer: "client",
1015
+ optimizeDeps: pagesOptimizeEntries.length > 0 ? { entries: pagesOptimizeEntries } : void 0,
1016
+ build: {
1017
+ manifest: true,
1018
+ ssrManifest: true,
1019
+ assetsInlineLimit: clientAssetsInlineLimit,
1020
+ ...withBuildBundlerOptions(viteMajorVersion, {
1021
+ input: { index: VIRTUAL_CLIENT_ENTRY },
1022
+ output: getClientOutputConfigForVite(viteMajorVersion, clientAssetsDir),
1023
+ treeshake: getClientTreeshakeConfigForVite(viteMajorVersion)
1024
+ })
1025
+ }
1026
+ } };
1027
+ else if (shouldInjectPlainPagesEnvironments) viteConfig.environments = {
1028
+ client: {
1029
+ consumer: "client",
1030
+ optimizeDeps: pagesOptimizeEntries.length > 0 ? { entries: pagesOptimizeEntries } : void 0,
1031
+ build: {
1032
+ outDir: "dist/client",
1033
+ manifest: true,
1034
+ ssrManifest: true,
1035
+ assetsInlineLimit: clientAssetsInlineLimit,
1036
+ ...withBuildBundlerOptions(viteMajorVersion, {
1037
+ input: { index: VIRTUAL_CLIENT_ENTRY },
1038
+ output: getClientOutputConfigForVite(viteMajorVersion, clientAssetsDir),
1039
+ treeshake: getClientTreeshakeConfigForVite(viteMajorVersion)
1040
+ })
1041
+ }
1042
+ },
1043
+ ssr: {
1044
+ resolve: {
1045
+ external: [
1046
+ "react",
1047
+ "react-dom",
1048
+ "react-dom/server",
1049
+ "ipaddr.js"
1050
+ ],
1051
+ noExternal: true
1052
+ },
1053
+ optimizeDeps: {
1054
+ exclude: ["ipaddr.js"],
1055
+ ...depOptimizeNodeEnvOptions
1056
+ },
1057
+ build: {
1058
+ outDir: "dist/server",
1059
+ ...withBuildBundlerOptions(viteMajorVersion, {
1060
+ input: { index: VIRTUAL_SERVER_ENTRY },
1061
+ output: { entryFileNames: "entry.js" }
1062
+ })
1063
+ }
1064
+ }
1065
+ };
1066
+ if (pagesOptimizeEntries.length > 0 && !hasCloudflarePlugin) viteConfig.optimizeDeps = {
1067
+ ...viteConfig.optimizeDeps,
1068
+ entries: pagesOptimizeEntries
1069
+ };
1070
+ return viteConfig;
1071
+ },
1072
+ configEnvironment(name, config) {
1073
+ const configuredExtensions = name === "client" ? nextConfig.resolveExtensions : nextConfig.serverResolveExtensions;
1074
+ const extensions = configuredExtensions === null ? buildViteResolveExtensions(nextConfig.pageExtensions, config.resolve?.extensions) : normalizeViteResolveExtensions(configuredExtensions);
1075
+ config.resolve ??= {};
1076
+ config.resolve.extensions = extensions;
1077
+ return null;
1078
+ },
1079
+ async configResolved(config) {
1080
+ const cacheDirPrefix = getCacheDirPrefix(config.cacheDir);
1081
+ typeofWindowIdFilter.exclude = new RegExp(`^${escapeRegExp(cacheDirPrefix)}`);
1082
+ sassComposesLoader.setResolvedConfig(config);
1083
+ if (config.command === "build" && hasAppDir && hasPagesDir) {
1084
+ const [appRoutes, pageRoutes, apiRoutes] = await Promise.all([
1085
+ appRouter(appDir, nextConfig?.pageExtensions, fileMatcher),
1086
+ pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher),
1087
+ apiRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher)
1088
+ ]);
1089
+ validateHybridRouteConflicts([...pageRoutes, ...apiRoutes].map((route) => ({
1090
+ ...route,
1091
+ sourcePath: path.relative(root, route.filePath)
1092
+ })), appRoutes.filter((route) => route.pagePath !== null || route.routePath !== null).map((route) => ({
1093
+ ...route,
1094
+ sourcePath: path.relative(root, route.pagePath ?? route.routePath)
1095
+ })));
1096
+ }
1097
+ if (hasAppDir) {
1098
+ const ssrEnv = config.environments?.ssr;
1099
+ if (ssrEnv?.resolve?.external === true && Array.isArray(ssrEnv.resolve.noExternal)) ssrEnv.resolve.noExternal = ssrEnv.resolve.noExternal.filter((entry) => typeof entry !== "string" || !SSR_EXTERNAL_REACT_ENTRIES.includes(entry));
1100
+ }
1101
+ // @vitejs/plugin-react AND the user also registers it manually, the
1102
+ if (reactPluginPromise) {
1103
+ const reactRootPlugins = config.plugins.filter((p) => p && typeof p === "object" && "name" in p && typeof p.name === "string" && p.name.startsWith("vite:react"));
1104
+ const counts = /* @__PURE__ */ new Map();
1105
+ for (const plugin of reactRootPlugins) counts.set(plugin.name, (counts.get(plugin.name) ?? 0) + 1);
1106
+ if ([...counts.values()].some((count) => count > 1)) throw new Error("[vinext] Duplicate @vitejs/plugin-react detected.\n vinext auto-registers @vitejs/plugin-react by default.\n Your config also registers it manually, which duplicates React transforms.\n\n Fix: remove the explicit react() call from your plugins array.\n Or: pass react: false to vinext() if you want to configure react() yourself.");
1107
+ }
1108
+ // @vitejs/plugin-rsc AND the user also registers it manually, the
1109
+ if (rscPluginPromise) {
1110
+ if (config.plugins.filter((p) => p && typeof p === "object" && "name" in p && p.name === "rsc").length > 1) throw new Error("[vinext] Duplicate @vitejs/plugin-rsc detected.\n vinext auto-registers @vitejs/plugin-rsc when app/ is detected.\n Your config also registers it manually, which doubles build time.\n\n Fix: remove the explicit rsc() call from your plugins array.\n Or: pass rsc: false to vinext() if you want to configure rsc() yourself.");
1111
+ }
1112
+ if (config.command === "build" && !hasCloudflarePlugin && !hasNitroPlugin && hasWranglerConfig(root) && !options.disableAppRouter) throw new Error(formatMissingCloudflarePluginError({
1113
+ isAppRouter: hasAppDir,
1114
+ configFile: config.configFile
1115
+ }));
1116
+ },
1117
+ resolveId: {
1118
+ filter: { id: /(?:next\/|vinext\/(?:shims\/|server\/app-rsc-handler)|virtual:vinext-|@vercel\/og(?:\.js)?$)/ },
1119
+ handler(id, importer) {
1120
+ const cleanId = id.startsWith("\0") ? id.slice(1) : id;
1121
+ if (cleanId === "vinext/server/app-rsc-handler") {
1122
+ if (_canExternalizeAppRscHandler && this.environment?.name === "rsc" && this.environment.config?.command === "serve") return {
1123
+ id: _appRscHandlerPath,
1124
+ external: true
1125
+ };
1126
+ return _appRscHandlerPath;
1127
+ }
1128
+ if (isVercelOgImport(cleanId) && !isVinextOgShimImporter(importer)) return resolveShimModulePath(_shimsDir, "og");
1129
+ if (cleanId.startsWith("vinext/shims/")) return resolveShimModulePath(_shimsDir, stripJsExtension(stripViteModuleQuery(cleanId.slice(13))));
1130
+ if (cleanId === VIRTUAL_SERVER_ENTRY) return RESOLVED_SERVER_ENTRY;
1131
+ if (cleanId === VIRTUAL_CLIENT_ENTRY) return RESOLVED_CLIENT_ENTRY;
1132
+ if (cleanId.endsWith("/virtual:vinext-server-entry") || cleanId.endsWith("\\virtual:vinext-server-entry")) return RESOLVED_SERVER_ENTRY;
1133
+ if (cleanId.endsWith("/virtual:vinext-client-entry") || cleanId.endsWith("\\virtual:vinext-client-entry")) return RESOLVED_CLIENT_ENTRY;
1134
+ if (cleanId === VIRTUAL_RSC_ENTRY) return RESOLVED_RSC_ENTRY;
1135
+ if (cleanId === VIRTUAL_APP_SSR_ENTRY) return RESOLVED_APP_SSR_ENTRY;
1136
+ if (cleanId === VIRTUAL_APP_BROWSER_ENTRY) return RESOLVED_APP_BROWSER_ENTRY;
1137
+ if (cleanId === VIRTUAL_APP_CAPABILITIES) return RESOLVED_APP_CAPABILITIES;
1138
+ if (cleanId === "next/root-params" || cleanId === "next/root-params.js") return RESOLVED_ROOT_PARAMS;
1139
+ if (cleanId === "virtual:vinext-cache-adapters" || cleanId.endsWith("/virtual:vinext-cache-adapters") || cleanId.endsWith("\\virtual:vinext-cache-adapters")) return RESOLVED_CACHE_ADAPTERS;
1140
+ if (cleanId.startsWith("virtual:vinext-google-fonts?")) return RESOLVED_VIRTUAL_GOOGLE_FONTS + cleanId.slice(VIRTUAL_GOOGLE_FONTS.length);
1141
+ if (cleanId.endsWith("/virtual:vinext-rsc-entry") || cleanId.endsWith("\\virtual:vinext-rsc-entry")) return RESOLVED_RSC_ENTRY;
1142
+ if (cleanId.endsWith("/virtual:vinext-app-ssr-entry") || cleanId.endsWith("\\virtual:vinext-app-ssr-entry")) return RESOLVED_APP_SSR_ENTRY;
1143
+ if (cleanId.endsWith("/virtual:vinext-app-browser-entry") || cleanId.endsWith("\\virtual:vinext-app-browser-entry")) return RESOLVED_APP_BROWSER_ENTRY;
1144
+ if (cleanId.includes("/virtual:vinext-google-fonts?") || cleanId.includes("\\virtual:vinext-google-fonts?")) {
1145
+ const queryIndex = cleanId.indexOf(VIRTUAL_GOOGLE_FONTS + "?");
1146
+ return RESOLVED_VIRTUAL_GOOGLE_FONTS + cleanId.slice(queryIndex + VIRTUAL_GOOGLE_FONTS.length);
1147
+ }
1148
+ const reactServerShim = _reactServerShims.get(cleanId);
1149
+ if (reactServerShim !== void 0) return resolveShimModulePath(_shimsDir, this.environment?.name === "rsc" ? `${reactServerShim}.react-server` : reactServerShim);
1150
+ }
1151
+ },
1152
+ async load(id) {
1153
+ if (id === RESOLVED_SERVER_ENTRY) return await generateServerEntry$1();
1154
+ if (id === RESOLVED_CLIENT_ENTRY) return await generateClientEntry$1();
1155
+ if (id === RESOLVED_RSC_ENTRY && hasAppDir) {
1156
+ const routes = await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher);
1157
+ const metaRoutes = scanMetadataFiles(appDir);
1158
+ const hasServerActions = await resolveHasServerActions(this.environment.config);
1159
+ const globalErrorPath = findFileWithExts(appDir, "global-error", fileMatcher);
1160
+ const globalNotFoundPath = findFileWithExts(appDir, "global-not-found", fileMatcher);
1161
+ rscClassificationManifest = collectRouteClassificationManifest(routes);
1162
+ return generateRscEntry(appDir, routes, middlewarePath, metaRoutes, globalErrorPath, nextConfig?.basePath, nextConfig?.trailingSlash, {
1163
+ redirects: nextConfig?.redirects,
1164
+ rewrites: nextConfig?.rewrites,
1165
+ headers: nextConfig?.headers,
1166
+ allowedOrigins: nextConfig?.serverActionsAllowedOrigins,
1167
+ allowedDevOrigins: nextConfig?.allowedDevOrigins,
1168
+ bodySizeLimit: nextConfig?.serverActionsBodySizeLimit,
1169
+ bodySizeLimitLabel: nextConfig?.serverActionsBodySizeLimitLabel,
1170
+ htmlLimitedBots: nextConfig?.htmlLimitedBots,
1171
+ clientTraceMetadata: nextConfig?.clientTraceMetadata,
1172
+ assetPrefix: nextConfig?.assetPrefix,
1173
+ expireTime: nextConfig?.expireTime,
1174
+ reactMaxHeadersLength: nextConfig?.reactMaxHeadersLength,
1175
+ cacheMaxMemorySize: nextConfig?.cacheMaxMemorySize,
1176
+ inlineCss: nextConfig?.inlineCss,
1177
+ cacheComponents: nextConfig?.cacheComponents,
1178
+ hasServerActions,
1179
+ i18n: nextConfig?.i18n,
1180
+ imageConfig: {
1181
+ deviceSizes: nextConfig?.images?.deviceSizes,
1182
+ imageSizes: nextConfig?.images?.imageSizes,
1183
+ qualities: nextConfig?.images?.qualities
1184
+ },
1185
+ hasPagesDir,
1186
+ publicFiles: scanPublicFileRoutes(root),
1187
+ globalNotFoundPath,
1188
+ draftModeSecret
1189
+ }, instrumentationPath);
1190
+ }
1191
+ if (id === RESOLVED_ROOT_PARAMS) return generateRootParamsModule((hasAppDir ? await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher) : []).flatMap((route) => route.rootParamNames ?? []));
1192
+ if (id === RESOLVED_CACHE_ADAPTERS) return generateCacheAdaptersModule(options.cache);
1193
+ if (id === RESOLVED_APP_SSR_ENTRY && hasAppDir) return generateSsrEntry(hasPagesDir);
1194
+ if (id === RESOLVED_APP_BROWSER_ENTRY && hasAppDir) {
1195
+ const graph = await appRouteGraph(appDir, nextConfig?.pageExtensions, fileMatcher);
1196
+ const pagesPrefetchRoutes = hasPagesDir ? [...(await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher)).map((route) => ({
1197
+ canPrefetchLoadingShell: false,
1198
+ isDynamic: route.isDynamic,
1199
+ patternParts: [...route.patternParts]
1200
+ })), ...(await apiRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher)).map((route) => ({
1201
+ canPrefetchLoadingShell: false,
1202
+ documentOnly: true,
1203
+ isDynamic: route.isDynamic,
1204
+ patternParts: [...route.patternParts]
1205
+ }))] : [];
1206
+ return generateBrowserEntry(graph.routes, graph.routeManifest, pagesPrefetchRoutes, nextConfig.rewrites);
1207
+ }
1208
+ if (id === RESOLVED_APP_CAPABILITIES && hasAppDir) {
1209
+ const hasServerActions = await resolveHasServerActions(this.environment.config);
1210
+ return `
1211
+ export const hasServerActions = ${JSON.stringify(hasServerActions)};
1212
+ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.stringify(_appBrowserServerActionClientPath)})` : "null"};
1213
+ `;
1214
+ }
1215
+ if (id.startsWith("\0virtual:vinext-google-fonts?")) return generateGoogleFontsVirtualModule(id, _fontGoogleShimPath);
1216
+ },
1217
+ // @vitejs/plugin-rsc runs the RSC environment build in two phases:
1218
+ renderChunk: {
1219
+ order: "pre",
1220
+ handler(code, chunk) {
1221
+ if (this.environment?.name !== "rsc") return null;
1222
+ if (!rscClassificationManifest) return null;
1223
+ if (!code.includes("__VINEXT_CLASS")) return null;
1224
+ const enableClassificationDebug = Boolean(process.env.VINEXT_DEBUG_CLASSIFICATION);
1225
+ const patchPlan = planRouteClassificationInjection({
1226
+ canonicalizeLayoutPath: canonicalize,
1227
+ chunks: [{
1228
+ code,
1229
+ fileName: chunk.fileName
1230
+ }],
1231
+ dynamicShimPaths,
1232
+ enableDebugReasons: enableClassificationDebug,
1233
+ manifest: rscClassificationManifest,
1234
+ moduleInfo: { getModuleInfo: (moduleId) => {
1235
+ const info = this.getModuleInfo(moduleId);
1236
+ if (!info) return null;
1237
+ return {
1238
+ importedIds: info.importedIds ?? [],
1239
+ dynamicImportedIds: info.dynamicallyImportedIds ?? []
1240
+ };
1241
+ } }
1242
+ });
1243
+ if (patchPlan.kind === "skip") return null;
1244
+ rscClassificationManifest = null;
1245
+ return {
1246
+ code: patchPlan.code,
1247
+ map: patchPlan.map
1248
+ };
1249
+ }
1250
+ }
1251
+ },
1252
+ {
1253
+ name: "vinext:css-url-assets-mark",
1254
+ enforce: "pre",
1255
+ apply: "build",
1256
+ transform: {
1257
+ filter: {
1258
+ id: /\.(?:css|scss|sass|less|styl|stylus)(?:\?|$)/i,
1259
+ code: "url("
1260
+ },
1261
+ handler(code, id) {
1262
+ const marked = markCssUrlAssetReferences(code, id);
1263
+ if (marked === null) return null;
1264
+ return {
1265
+ code: marked,
1266
+ map: null
1267
+ };
1268
+ }
1269
+ }
1270
+ },
1271
+ {
1272
+ name: "vinext:client-css-url-assets-defaults",
1273
+ apply: "build",
1274
+ configEnvironment(name) {
1275
+ if (name !== "client") return null;
1276
+ return { build: { assetsInlineLimit: clientAssetsInlineLimit } };
1277
+ }
1278
+ },
1279
+ {
1280
+ name: "vinext:server-minify-defaults",
1281
+ apply: "build",
1282
+ configEnvironment(name, config) {
1283
+ if (name === "client") return null;
1284
+ if (config.build?.minify !== void 0) return null;
1285
+ return { build: { minify: true } };
1286
+ }
1287
+ },
1288
+ {
1289
+ name: "vinext:css-url-assets-restore",
1290
+ enforce: "post",
1291
+ apply: "build",
1292
+ generateBundle(_options, bundle) {
1293
+ restoreDedupedCssAssetReferences(bundle, (asset) => {
1294
+ this.emitFile({
1295
+ type: "asset",
1296
+ fileName: asset.fileName,
1297
+ source: asset.source
1298
+ });
1299
+ });
1300
+ }
1301
+ },
1302
+ {
1303
+ name: "vinext:client-entry-manifest",
1304
+ apply: "build",
1305
+ generateBundle(_options, bundle) {
1306
+ if (this.environment?.name !== "client") return;
1307
+ const manifest = {};
1308
+ for (const chunk of Object.values(bundle)) {
1309
+ if (chunk.type !== "chunk" || !chunk.isEntry) continue;
1310
+ if (isVirtualEntryFacade(chunk.facadeModuleId, VIRTUAL_CLIENT_ENTRY)) manifest.pagesClientEntry = chunk.fileName;
1311
+ else if (isVirtualEntryFacade(chunk.facadeModuleId, VIRTUAL_APP_BROWSER_ENTRY)) manifest.appBrowserEntry = chunk.fileName;
1312
+ }
1313
+ if (!manifest.pagesClientEntry && !manifest.appBrowserEntry) return;
1314
+ this.emitFile({
1315
+ type: "asset",
1316
+ fileName: VINEXT_CLIENT_ENTRY_MANIFEST,
1317
+ source: JSON.stringify(manifest, null, 2) + "\n"
1318
+ });
1319
+ }
1320
+ },
1321
+ asyncHooksStubPlugin,
1322
+ createInstrumentationClientTransformPlugin(() => instrumentationClientPath),
1323
+ {
1324
+ name: "vinext:instrumentation-client-inject",
1325
+ enforce: "pre",
1326
+ resolveId(id) {
1327
+ if (id !== VIRTUAL_INSTRUMENTATION_CLIENT) return null;
1328
+ return clientInjectModule !== null ? RESOLVED_INSTRUMENTATION_CLIENT : null;
1329
+ },
1330
+ load(id) {
1331
+ if (id !== RESOLVED_INSTRUMENTATION_CLIENT) return null;
1332
+ return clientInjectModule;
1333
+ }
1334
+ },
1335
+ ...options.experimental?.clientReferenceDedup ? [clientReferenceDedupPlugin()] : [],
1336
+ {
1337
+ name: "vinext:mdx",
1338
+ enforce: "pre",
1339
+ config(config, env) {
1340
+ if (!mdxDelegate?.config) return;
1341
+ const hook = mdxDelegate.config;
1342
+ return (typeof hook === "function" ? hook : hook.handler).call(this, config, env);
1343
+ },
1344
+ transform: {
1345
+ filter: { id: {
1346
+ include: /\.mdx$/i,
1347
+ exclude: /\?/
1348
+ } },
1349
+ async handler(code, id, options) {
1350
+ const delegate = mdxDelegate ?? await ensureMdxDelegate("on-demand");
1351
+ if (delegate?.transform) {
1352
+ const hook = delegate.transform;
1353
+ return (typeof hook === "function" ? hook : hook.handler).call(this, code, id, options);
1354
+ }
1355
+ if (!hasUserMdxPlugin) throw new Error(`[vinext] Encountered MDX module ${id} but no MDX plugin is configured. Install @mdx-js/rollup or register an MDX plugin manually.`);
1356
+ }
1357
+ }
1358
+ },
1359
+ {
1360
+ name: "vinext:react-canary",
1361
+ enforce: "pre",
1362
+ resolveId(id) {
1363
+ if (id === "virtual:vinext-react-canary") return "\0virtual:vinext-react-canary";
1364
+ },
1365
+ load(id) {
1366
+ if (id === "\0virtual:vinext-react-canary") return [
1367
+ `export * from "react";`,
1368
+ `export { default } from "react";`,
1369
+ `import * as _React from "react";`,
1370
+ `export const ViewTransition = _React.ViewTransition || function ViewTransition({ children }) { return children; };`,
1371
+ `export const addTransitionType = _React.addTransitionType || function addTransitionType() {};`
1372
+ ].join("\n");
1373
+ },
1374
+ transform: {
1375
+ filter: {
1376
+ id: {
1377
+ include: /\.(tsx?|jsx?|mjs)$/,
1378
+ exclude: [/node_modules/, VIRTUAL_MODULE_ID_RE]
1379
+ },
1380
+ code: /import\s*\{[^}]*(ViewTransition|addTransitionType)[^}]*\}\s*from\s*['"]react['"]/
1381
+ },
1382
+ handler(code) {
1383
+ return {
1384
+ code: code.replace(/from\s*['"]react['"]/g, "from \"virtual:vinext-react-canary\""),
1385
+ map: null
1386
+ };
1387
+ }
1388
+ }
1389
+ },
1390
+ {
1391
+ name: "vinext:pages-router",
1392
+ hotUpdate(options) {
1393
+ if (!hasPagesDir || hasAppDir) return;
1394
+ if (options.file.startsWith(pagesDir) && fileMatcher.extensionRegex.test(options.file)) {
1395
+ options.server.environments.client.hot.send({ type: "full-reload" });
1396
+ return [];
1397
+ }
1398
+ },
1399
+ configureServer(server) {
1400
+ const pageExtensions = fileMatcher.extensionRegex;
1401
+ let pagesRunner = null;
1402
+ let cachedSSRHandler = null;
1403
+ function getPagesRunner() {
1404
+ if (!pagesRunner) pagesRunner = createDirectRunner(server.environments["ssr"] ?? Object.values(server.environments).find((e) => e !== server.environments["rsc"]) ?? Object.values(server.environments)[0]);
1405
+ return pagesRunner;
1406
+ }
1407
+ /**
1408
+ * Invalidate the virtual RSC entry module in Vite's module graph.
1409
+ *
1410
+ * The App Router route table is baked into the virtual RSC entry
1411
+ * at generation time. When routes are added or removed, clearing
1412
+ * the route cache alone is not enough: the virtual module must
1413
+ * also be invalidated so Vite re-calls the load() hook to
1414
+ * regenerate the entry with the updated route table.
1415
+ */
1416
+ function invalidateRscEntryModule() {
1417
+ const rscEnv = server.environments["rsc"];
1418
+ if (!rscEnv) return;
1419
+ const mod = rscEnv.moduleGraph.getModuleById(RESOLVED_RSC_ENTRY);
1420
+ if (mod) {
1421
+ rscEnv.moduleGraph.invalidateModule(mod);
1422
+ rscEnv.hot.send({ type: "full-reload" });
1423
+ }
1424
+ }
1425
+ function invalidateRootParamsModule() {
1426
+ for (const env of Object.values(server.environments)) {
1427
+ const mod = env.moduleGraph.getModuleById(RESOLVED_ROOT_PARAMS);
1428
+ if (mod) env.moduleGraph.invalidateModule(mod);
1429
+ }
1430
+ }
1431
+ function invalidateHybridClientEntries() {
1432
+ if (!hasAppDir || !hasPagesDir) return;
1433
+ for (const env of Object.values(server.environments)) for (const id of [RESOLVED_CLIENT_ENTRY, RESOLVED_APP_BROWSER_ENTRY]) {
1434
+ const mod = env.moduleGraph.getModuleById(id);
1435
+ if (mod) env.moduleGraph.invalidateModule(mod);
1436
+ }
1437
+ server.ws.send({ type: "full-reload" });
1438
+ }
1439
+ function invalidatePagesServerEntry() {
1440
+ for (const env of Object.values(server.environments)) {
1441
+ const mod = env.moduleGraph.getModuleById(RESOLVED_SERVER_ENTRY);
1442
+ if (mod) env.moduleGraph.invalidateModule(mod);
1443
+ }
1444
+ pagesRunner?.clearCache();
1445
+ }
1446
+ function invalidateAppRoutingModules() {
1447
+ invalidateAppRouteCache();
1448
+ invalidateRscEntryModule();
1449
+ invalidateRootParamsModule();
1450
+ }
1451
+ let hybridRouteValidation = Promise.resolve();
1452
+ let hybridRouteValidationError = null;
1453
+ function sendHybridRouteValidationError(error) {
1454
+ server.ws.send({
1455
+ type: "error",
1456
+ err: {
1457
+ message: error.message,
1458
+ stack: error.stack ?? error.message
1459
+ }
1460
+ });
1461
+ }
1462
+ server.ws.on("connection", () => {
1463
+ if (hybridRouteValidationError) sendHybridRouteValidationError(hybridRouteValidationError);
1464
+ });
1465
+ function revalidateHybridRoutes() {
1466
+ if (!hasAppDir || !hasPagesDir) return;
1467
+ hybridRouteValidation = hybridRouteValidation.catch(() => {}).then(async () => {
1468
+ const [appRoutes, pageRoutes, apiRoutes] = await Promise.all([
1469
+ appRouter(appDir, nextConfig?.pageExtensions, fileMatcher),
1470
+ pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher),
1471
+ apiRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher)
1472
+ ]);
1473
+ validateHybridRouteConflicts([...pageRoutes, ...apiRoutes].map((route) => ({
1474
+ ...route,
1475
+ sourcePath: path.relative(root, route.filePath)
1476
+ })), appRoutes.filter((route) => route.pagePath !== null || route.routePath !== null).map((route) => ({
1477
+ ...route,
1478
+ sourcePath: path.relative(root, route.pagePath ?? route.routePath)
1479
+ })));
1480
+ if (hybridRouteValidationError) {
1481
+ hybridRouteValidationError = null;
1482
+ server.ws.send({ type: "full-reload" });
1483
+ }
1484
+ }).catch((error) => {
1485
+ const err = error instanceof Error ? error : new Error(String(error));
1486
+ hybridRouteValidationError = err;
1487
+ sendHybridRouteValidationError(err);
1488
+ });
1489
+ }
1490
+ let appRouteTypeGeneration = null;
1491
+ let appRouteTypeGenerationPending = false;
1492
+ function warnRouteTypeGenerationFailure(error) {
1493
+ server.config.logger.warn(`[vinext] Failed to regenerate route types: ${error instanceof Error ? error.message : String(error)}`);
1494
+ }
1495
+ async function drainAppRouteTypeGeneration() {
1496
+ while (appRouteTypeGenerationPending) {
1497
+ appRouteTypeGenerationPending = false;
1498
+ try {
1499
+ await writeRouteTypes();
1500
+ } catch (error) {
1501
+ warnRouteTypeGenerationFailure(error);
1502
+ }
1503
+ }
1504
+ }
1505
+ function regenerateAppRouteTypes() {
1506
+ appRouteTypeGenerationPending = true;
1507
+ if (appRouteTypeGeneration) return;
1508
+ appRouteTypeGeneration = drainAppRouteTypeGeneration().finally(() => {
1509
+ appRouteTypeGeneration = null;
1510
+ if (appRouteTypeGenerationPending) regenerateAppRouteTypes();
1511
+ });
1512
+ }
1513
+ regenerateAppRouteTypes();
1514
+ revalidateHybridRoutes();
1515
+ server.httpServer?.on("connection", (socket) => {
1516
+ socket.on("error", () => {});
1517
+ });
1518
+ server.watcher.on("add", (filePath) => {
1519
+ let routeChanged = false;
1520
+ if (hasPagesDir && filePath.startsWith(pagesDir) && pageExtensions.test(filePath)) {
1521
+ invalidateRouteCache(pagesDir);
1522
+ routeChanged = true;
1523
+ }
1524
+ if (hasAppDir && shouldInvalidateAppRouteFile(appDir, filePath, fileMatcher)) {
1525
+ invalidateAppRoutingModules();
1526
+ regenerateAppRouteTypes();
1527
+ routeChanged = true;
1528
+ }
1529
+ if (routeChanged) {
1530
+ invalidatePagesServerEntry();
1531
+ invalidateHybridClientEntries();
1532
+ revalidateHybridRoutes();
1533
+ }
1534
+ });
1535
+ server.watcher.on("unlink", (filePath) => {
1536
+ let routeChanged = false;
1537
+ if (hasPagesDir && filePath.startsWith(pagesDir) && pageExtensions.test(filePath)) {
1538
+ invalidateRouteCache(pagesDir);
1539
+ routeChanged = true;
1540
+ }
1541
+ if (hasAppDir && shouldInvalidateAppRouteFile(appDir, filePath, fileMatcher)) {
1542
+ invalidateAppRoutingModules();
1543
+ regenerateAppRouteTypes();
1544
+ routeChanged = true;
1545
+ }
1546
+ if (routeChanged) {
1547
+ invalidatePagesServerEntry();
1548
+ invalidateHybridClientEntries();
1549
+ revalidateHybridRoutes();
1550
+ }
1551
+ });
1552
+ server.middlewares.use((req, res, next) => {
1553
+ const blockReason = validateDevRequest({
1554
+ origin: req.headers.origin,
1555
+ host: req.headers.host,
1556
+ "x-forwarded-host": req.headers["x-forwarded-host"],
1557
+ "sec-fetch-site": req.headers["sec-fetch-site"],
1558
+ "sec-fetch-mode": req.headers["sec-fetch-mode"]
1559
+ }, nextConfig?.allowedDevOrigins);
1560
+ if (blockReason) {
1561
+ console.warn(`[vinext] Blocked dev request: ${blockReason} (${req.url})`);
1562
+ res.writeHead(403, { "Content-Type": "text/plain" });
1563
+ res.end("Forbidden");
1564
+ return;
1565
+ }
1566
+ next();
1567
+ });
1568
+ installDevStackSourcemapMiddleware(server);
1569
+ return () => {
1570
+ const viteFilesystemMiddlewares = server.middlewares.stack.filter(({ handle }) => {
1571
+ const name = typeof handle === "function" ? handle.name : "";
1572
+ return name === "viteServePublicMiddleware" || name === "viteServeStaticMiddleware";
1573
+ }).map(({ handle }) => handle).filter((handle) => typeof handle === "function");
1574
+ const serveRewrittenViteFilesystemRoute = async (req, res, requestPathname, stagedHeaders) => {
1575
+ const originalUrl = req.url;
1576
+ const originalStatusCode = res.statusCode;
1577
+ const originalStatusMessage = res.statusMessage;
1578
+ const originalHeaders = res.getHeaders();
1579
+ req.url = requestPathname;
1580
+ for (const [key, value] of Object.entries(stagedHeaders)) res.setHeader(key, value);
1581
+ const restore = () => {
1582
+ req.url = originalUrl;
1583
+ res.statusCode = originalStatusCode;
1584
+ res.statusMessage = originalStatusMessage;
1585
+ for (const key of Object.keys(res.getHeaders())) res.removeHeader(key);
1586
+ for (const [key, value] of Object.entries(originalHeaders)) if (value !== void 0) res.setHeader(key, value);
1587
+ };
1588
+ try {
1589
+ for (const middleware of viteFilesystemMiddlewares) if (await new Promise((resolve, reject) => {
1590
+ let settled = false;
1591
+ const settle = (value, error) => {
1592
+ if (settled) return;
1593
+ settled = true;
1594
+ res.off("finish", onServed);
1595
+ res.off("close", onServed);
1596
+ if (error) reject(error);
1597
+ else resolve(value);
1598
+ };
1599
+ const onServed = () => settle("served");
1600
+ res.once("finish", onServed);
1601
+ res.once("close", onServed);
1602
+ middleware(req, res, (error) => settle("next", error));
1603
+ if (res.writableEnded) settle("served");
1604
+ }) === "served") {
1605
+ req.url = originalUrl;
1606
+ return true;
1607
+ }
1608
+ } catch (error) {
1609
+ restore();
1610
+ throw error;
1611
+ }
1612
+ restore();
1613
+ return false;
1614
+ };
1615
+ if (instrumentationPath && !hasAppDir) runInstrumentation(getPagesRunner(), instrumentationPath).catch((err) => {
1616
+ console.error("[vinext] Instrumentation error:", err);
1617
+ });
1618
+ if (hasAppDir) server.middlewares.use((req, res, next) => {
1619
+ const url = req.url ?? "/";
1620
+ const [pathname] = url.split("?");
1621
+ if (url.startsWith("/@") || url.startsWith("/__vite") || url.startsWith("/node_modules") || url.includes(".") && !pathname.endsWith(".html") && !pathname.endsWith(".rsc")) return next();
1622
+ const _reqStart = now();
1623
+ let _compileMs;
1624
+ let _renderMs;
1625
+ function _parseTiming(raw) {
1626
+ const [handlerStart, inHandlerCompileMs, renderMs] = String(raw).split(",").map((v) => Number(v));
1627
+ if (!Number.isNaN(handlerStart) && !Number.isNaN(inHandlerCompileMs) && inHandlerCompileMs !== -1) _compileMs = Math.max(0, Math.round(handlerStart - _reqStart)) + inHandlerCompileMs;
1628
+ if (!Number.isNaN(renderMs) && renderMs !== -1) _renderMs = renderMs;
1629
+ }
1630
+ const _origSetHeader = res.setHeader.bind(res);
1631
+ res.setHeader = function(name, value) {
1632
+ if (name.toLowerCase() === "x-vinext-timing") {
1633
+ _parseTiming(value);
1634
+ return res;
1635
+ }
1636
+ return _origSetHeader(name, value);
1637
+ };
1638
+ const _origWriteHead = res.writeHead.bind(res);
1639
+ res.writeHead = function(statusCode, ...args) {
1640
+ let headers;
1641
+ const [reasonOrHeaders, maybeHeaders] = args;
1642
+ if (typeof reasonOrHeaders === "string") headers = maybeHeaders;
1643
+ else headers = reasonOrHeaders;
1644
+ if (headers && typeof headers === "object" && !Array.isArray(headers)) {
1645
+ const timingKey = Object.keys(headers).find((k) => k.toLowerCase() === VINEXT_TIMING_HEADER);
1646
+ if (timingKey) {
1647
+ _parseTiming(headers[timingKey]);
1648
+ delete headers[timingKey];
1649
+ }
1650
+ }
1651
+ return _origWriteHead(statusCode, ...args);
1652
+ };
1653
+ res.on("finish", () => {
1654
+ const logUrl = url.replace(/\.rsc(\?|$)/, "$1");
1655
+ const totalMs = now() - _reqStart;
1656
+ const resolvedRenderMs = _renderMs !== void 0 ? _renderMs : _compileMs !== void 0 ? Math.max(0, Math.round(totalMs - _compileMs)) : void 0;
1657
+ logRequest({
1658
+ method: req.method ?? "GET",
1659
+ url: logUrl,
1660
+ status: res.statusCode,
1661
+ totalMs,
1662
+ compileMs: _compileMs,
1663
+ renderMs: resolvedRenderMs
1664
+ });
1665
+ });
1666
+ next();
1667
+ });
1668
+ const handlePagesMiddleware = async (req, res, next) => {
1669
+ try {
1670
+ let url = req.url ?? "/";
1671
+ const originalRequestUrl = url;
1672
+ if (!hasPagesDir) return next();
1673
+ if (url.startsWith("/@") || url.startsWith("/__vite") || url.startsWith("/node_modules")) return next();
1674
+ if (url.split("?")[0].endsWith(".rsc")) return next();
1675
+ const blockReason = validateDevRequest({
1676
+ origin: req.headers.origin,
1677
+ host: req.headers.host,
1678
+ "x-forwarded-host": req.headers["x-forwarded-host"],
1679
+ "sec-fetch-site": req.headers["sec-fetch-site"],
1680
+ "sec-fetch-mode": req.headers["sec-fetch-mode"]
1681
+ }, nextConfig?.allowedDevOrigins);
1682
+ if (blockReason) {
1683
+ console.warn(`[vinext] Blocked dev request: ${blockReason} (${url})`);
1684
+ res.writeHead(403, { "Content-Type": "text/plain" });
1685
+ res.end("Forbidden");
1686
+ return;
1687
+ }
1688
+ if (isImageOptimizationPath(url.split("?")[0])) {
1689
+ const encodedLocation = resolveDevImageRedirect(new URL(url, `http://${req.headers.host || "localhost"}`), [...nextConfig.images?.deviceSizes ?? DEFAULT_DEVICE_SIZES, ...nextConfig.images?.imageSizes ?? DEFAULT_IMAGE_SIZES], nextConfig.images?.qualities);
1690
+ if (!encodedLocation) {
1691
+ res.writeHead(400);
1692
+ res.end("Invalid image optimization parameters");
1693
+ return;
1694
+ }
1695
+ res.writeHead(302, { Location: encodedLocation });
1696
+ res.end();
1697
+ return;
1698
+ }
1699
+ const rawPathname = url.split("?")[0];
1700
+ if (rawPathname.endsWith("/index.html")) url = url.replace("/index.html", "/");
1701
+ else if (rawPathname.endsWith(".html")) url = url.replace(/\.html(?=\?|$)/, "");
1702
+ let pathname = url.split("?")[0];
1703
+ if (isOpenRedirectShaped(pathname)) {
1704
+ res.writeHead(404);
1705
+ res.end("This page could not be found");
1706
+ return;
1707
+ }
1708
+ pathname = pathname.replaceAll("\\", "/");
1709
+ try {
1710
+ pathname = normalizePath$1(normalizePathnameForRouteMatchStrict(pathname));
1711
+ } catch {
1712
+ res.writeHead(400);
1713
+ res.end("Bad Request");
1714
+ return;
1715
+ }
1716
+ {
1717
+ const qs = url.includes("?") ? url.slice(url.indexOf("?")) : "";
1718
+ url = pathname + qs;
1719
+ }
1720
+ const bp = nextConfig?.basePath ?? "";
1721
+ if (bp && pathname.startsWith(bp)) {
1722
+ const stripped = pathname.slice(bp.length) || "/";
1723
+ url = stripped + (url.includes("?") ? url.slice(url.indexOf("?")) : "");
1724
+ pathname = stripped;
1725
+ }
1726
+ if (nextConfig) {
1727
+ const qs = url.includes("?") ? url.slice(url.indexOf("?")) : "";
1728
+ const trailingSlashRedirect = normalizeTrailingSlash(pathname, bp, nextConfig.trailingSlash, qs);
1729
+ if (trailingSlashRedirect) {
1730
+ const location = trailingSlashRedirect.headers.get("Location");
1731
+ res.writeHead(trailingSlashRedirect.status, location ? { Location: location } : void 0);
1732
+ res.end();
1733
+ return;
1734
+ }
1735
+ }
1736
+ if (hasCloudflarePlugin) return next();
1737
+ let isDataReq = false;
1738
+ if (isNextDataPathname(pathname)) {
1739
+ const devBuildId = nextConfig?.buildId ?? process.env.__VINEXT_BUILD_ID ?? "development";
1740
+ const dataMatch = parseNextDataPathname(pathname, devBuildId);
1741
+ if (dataMatch) {
1742
+ isDataReq = true;
1743
+ const qs = url.includes("?") ? url.slice(url.indexOf("?")) : "";
1744
+ url = dataMatch.pagePathname + qs;
1745
+ pathname = dataMatch.pagePathname;
1746
+ req.url = url;
1747
+ } else {
1748
+ const deploymentId = process.env.__VINEXT_DEPLOYMENT_ID || process.env.NEXT_DEPLOYMENT_ID;
1749
+ const notFoundHeaders = { "Content-Type": "application/json" };
1750
+ if (deploymentId) notFoundHeaders[NEXTJS_DEPLOYMENT_ID_HEADER] = deploymentId;
1751
+ res.writeHead(404, notFoundHeaders);
1752
+ res.end("{}");
1753
+ return;
1754
+ }
1755
+ }
1756
+ const filePathMatchesRewrite = [
1757
+ ...nextConfig?.rewrites.beforeFiles ?? [],
1758
+ ...nextConfig?.rewrites.afterFiles ?? [],
1759
+ ...nextConfig?.rewrites.fallback ?? []
1760
+ ].some((rewrite) => matchesRewriteSource(pathname, rewrite, {
1761
+ basePath: bp,
1762
+ hadBasePath: true
1763
+ }));
1764
+ if (pathname.includes(".") && !pathname.endsWith(".html") && !filePathMatchesRewrite) return next();
1765
+ const rawHeaders = new Headers(Object.fromEntries(Object.entries(req.headers).filter(([k, v]) => v !== void 0 && !k.startsWith(":")).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : String(v)])));
1766
+ const isDataRequest = isDataReq;
1767
+ const nodeRequestHeaders = filterInternalHeaders(rawHeaders);
1768
+ for (const header of INTERNAL_HEADERS) delete req.headers[header];
1769
+ for (const header of VINEXT_INTERNAL_HEADERS) delete req.headers[header];
1770
+ const requestOrigin = `http://${req.headers.host || "localhost"}`;
1771
+ const method = req.method ?? "GET";
1772
+ const webRequest = new Request(new URL(url, requestOrigin), {
1773
+ method,
1774
+ headers: nodeRequestHeaders
1775
+ });
1776
+ const applyRequestHeadersToNodeRequest = (nextRequestHeaders) => {
1777
+ for (const key of Object.keys(req.headers)) delete req.headers[key];
1778
+ for (const [key, value] of nextRequestHeaders) req.headers[key] = value;
1779
+ };
1780
+ const capturedMiddlewarePath = middlewarePath;
1781
+ const devRunMiddlewareAdapter = capturedMiddlewarePath ? async (_request, _ctx, opts) => {
1782
+ const rawProto = process.env.VINEXT_TRUST_PROXY === "1" || (process.env.VINEXT_TRUSTED_HOSTS ?? "").split(",").some((h) => h.trim()) ? String(req.headers["x-forwarded-proto"] || "").split(",")[0].trim() : "";
1783
+ const mwOrigin = `${rawProto === "https" || rawProto === "http" ? rawProto : "http"}://${req.headers.host || "localhost"}`;
1784
+ const middlewareRequest = new Request(new URL(url, mwOrigin), {
1785
+ method: req.method,
1786
+ headers: nodeRequestHeaders
1787
+ });
1788
+ const result = await runMiddleware(getPagesRunner(), capturedMiddlewarePath, middlewareRequest, nextConfig?.i18n, nextConfig?.basePath, nextConfig?.trailingSlash, opts.isDataRequest);
1789
+ if (hasAppDir && result.continue) {
1790
+ const mwCtxEntries = [];
1791
+ if (result.responseHeaders) {
1792
+ for (const [key, value] of result.responseHeaders) if (key !== "x-middleware-next" && key !== "x-middleware-rewrite") mwCtxEntries.push([key, value]);
1793
+ }
1794
+ const mwStatus = result.status ?? result.rewriteStatus;
1795
+ req.headers[VINEXT_MW_CTX_HEADER] = JSON.stringify({
1796
+ h: mwCtxEntries,
1797
+ s: mwStatus ?? null,
1798
+ r: result.rewriteUrl ?? null
1799
+ });
1800
+ }
1801
+ return result;
1802
+ } : null;
1803
+ const devPageRoutes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);
1804
+ const pipelineResult = await runPagesRequest(webRequest, {
1805
+ basePath: bp,
1806
+ trailingSlash: nextConfig?.trailingSlash ?? false,
1807
+ i18nConfig: nextConfig?.i18n ?? null,
1808
+ configRedirects: nextConfig?.redirects ?? [],
1809
+ configRewrites: nextConfig?.rewrites ?? {
1810
+ beforeFiles: [],
1811
+ afterFiles: [],
1812
+ fallback: []
1813
+ },
1814
+ configHeaders: nextConfig?.headers ?? [],
1815
+ hadBasePath: true,
1816
+ isDataReq,
1817
+ isDataRequest,
1818
+ rawSearch: url.includes("?") ? url.slice(url.indexOf("?")) : "",
1819
+ runMiddleware: devRunMiddlewareAdapter,
1820
+ matchPageRoute: (resolvedPathname) => {
1821
+ const m = matchRoute(resolvedPathname, devPageRoutes);
1822
+ return m ? { route: { isDynamic: m.route.isDynamic } } : null;
1823
+ },
1824
+ proxyExternal: async (currentRequest, externalUrl) => {
1825
+ const externalMethod = req.method ?? "GET";
1826
+ const hasBody = externalMethod !== "GET" && externalMethod !== "HEAD";
1827
+ const externalInit = {
1828
+ method: externalMethod,
1829
+ headers: currentRequest.headers
1830
+ };
1831
+ if (hasBody) {
1832
+ const { Readable } = await import("node:stream");
1833
+ externalInit.body = Readable.toWeb(req);
1834
+ externalInit.duplex = "half";
1835
+ }
1836
+ return proxyExternalRequest(new Request(new URL(url, requestOrigin), externalInit), externalUrl);
1837
+ },
1838
+ serveFilesystemRoute: async (requestPathname, stagedHeaders, phase) => {
1839
+ if (phase === "direct" || req.method !== "GET" && req.method !== "HEAD" || requestPathname === "/" || requestPathname === "/api" || requestPathname.startsWith("/api/")) return false;
1840
+ return serveRewrittenViteFilesystemRoute(req, res, requestPathname, stagedHeaders);
1841
+ }
1842
+ });
1843
+ if (pipelineResult.type === "response") {
1844
+ await writeWebResponseToNodeRes(res, pipelineResult.response);
1845
+ return;
1846
+ }
1847
+ if (pipelineResult.type === "next") return next();
1848
+ if (pipelineResult.type === "handled") return;
1849
+ const flushStagedHeaders = () => {
1850
+ for (const [key, value] of Object.entries(pipelineResult.stagedHeaders)) if (Array.isArray(value)) for (const v of value) res.appendHeader(key, v);
1851
+ else res.appendHeader(key, value);
1852
+ };
1853
+ const flushRequestHeaders = () => {
1854
+ applyRequestHeadersToNodeRequest(pipelineResult.requestHeaders);
1855
+ };
1856
+ if (pipelineResult.type === "api") {
1857
+ const apiRoutes = await apiRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);
1858
+ const apiMatch = matchRoute(pipelineResult.apiUrl, apiRoutes);
1859
+ if (apiMatch && hasAppDir && appDir) {
1860
+ const appRoutes = await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher);
1861
+ const appMatch = matchAppRoute(pipelineResult.apiUrl, appRoutes);
1862
+ if (appMatch && !pagesRouteHasPriorityOverAppRoute(apiMatch.route, appMatch.route)) return next();
1863
+ }
1864
+ if (apiMatch) {
1865
+ flushStagedHeaders();
1866
+ flushRequestHeaders();
1867
+ if (pipelineResult.middlewareStatus !== void 0) req.__vinextMiddlewareStatus = pipelineResult.middlewareStatus;
1868
+ }
1869
+ if (await handleApiRoute(getPagesRunner(), req, res, pipelineResult.apiUrl, apiRoutes, {
1870
+ basePath: nextConfig?.basePath,
1871
+ i18n: nextConfig?.i18n,
1872
+ trailingSlash: nextConfig?.trailingSlash
1873
+ })) return;
1874
+ if (hasAppDir) return next();
1875
+ res.statusCode = 404;
1876
+ res.end("404 - API route not found");
1877
+ return;
1878
+ }
1879
+ {
1880
+ const routes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);
1881
+ const resolvedPathname = pipelineResult.resolvedUrl.split("#", 1)[0].split("?", 1)[0];
1882
+ const renderMatch = matchRoute(resolvedPathname, routes);
1883
+ if (hasAppDir && appDir) {
1884
+ if (!renderMatch) return next();
1885
+ const appMatch = matchAppRoute(resolvedPathname, await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher));
1886
+ if (appMatch && !pagesRouteHasPriorityOverAppRoute(renderMatch.route, appMatch.route)) return next();
1887
+ }
1888
+ if (!cachedSSRHandler || cachedSSRHandler.routes !== routes) cachedSSRHandler = {
1889
+ routes,
1890
+ handler: createSSRHandler(server, getPagesRunner(), routes, pagesDir, nextConfig?.i18n, fileMatcher, nextConfig?.basePath ?? "", nextConfig?.trailingSlash ?? false, middlewarePath !== null, (nextConfig?.rewrites.beforeFiles.length ?? 0) > 0 || (nextConfig?.rewrites.afterFiles.length ?? 0) > 0 || (nextConfig?.rewrites.fallback.length ?? 0) > 0, nextConfig?.clientTraceMetadata, nextConfig?.htmlLimitedBots)
1891
+ };
1892
+ flushStagedHeaders();
1893
+ flushRequestHeaders();
1894
+ if (pipelineResult.middlewareStatus !== void 0) req.__vinextMiddlewareStatus = pipelineResult.middlewareStatus;
1895
+ req.url = pipelineResult.resolvedUrl;
1896
+ await cachedSSRHandler.handler(req, res, pipelineResult.resolvedUrl, req.__vinextMiddlewareStatus, pipelineResult.isDataReq, originalRequestUrl);
1897
+ }
1898
+ } catch (e) {
1899
+ next(e);
1900
+ }
1901
+ };
1902
+ server.middlewares.use((req, res, next) => {
1903
+ handlePagesMiddleware(req, res, next);
1904
+ });
1905
+ };
1906
+ }
1907
+ },
1908
+ {
1909
+ name: "vinext:validate-middleware-exports",
1910
+ enforce: "pre",
1911
+ transform(code, id) {
1912
+ if (!middlewarePath) return null;
1913
+ const modulePath = stripViteModuleQuery(id);
1914
+ if (canonicalize(modulePath) !== canonicalize(middlewarePath)) return null;
1915
+ validateMiddlewareModuleExports(code, modulePath, middlewarePath, isProxyFile(middlewarePath));
1916
+ return null;
1917
+ }
1918
+ },
1919
+ {
1920
+ name: "vinext:validate-page-exports",
1921
+ transform: {
1922
+ filter: {
1923
+ id: { exclude: VIRTUAL_MODULE_ID_RE },
1924
+ code: /\bexport\b[\s\S]*\*/
1925
+ },
1926
+ handler(code, id) {
1927
+ if (this.environment?.name !== "client") return null;
1928
+ if (!hasPagesDir || !hasExportAllCandidate(code)) return null;
1929
+ const modulePath = stripViteModuleQuery(id);
1930
+ if (!isWithinPagesDirectory(modulePath)) return null;
1931
+ const canonicalId = canonicalizePageTransformPath(modulePath);
1932
+ if (!isWithinPagesDirectory(canonicalId)) return null;
1933
+ if (!fileMatcher.isPageFile(canonicalId)) return null;
1934
+ if (isApiPage(canonicalId)) return null;
1935
+ validatePageExports(code);
1936
+ return null;
1937
+ }
1938
+ }
1939
+ },
1940
+ {
1941
+ name: "vinext:strip-server-exports",
1942
+ transform: {
1943
+ filter: {
1944
+ id: { exclude: VIRTUAL_MODULE_ID_RE },
1945
+ code: /getServerSideProps|getStaticProps|getStaticPaths|unstable_getServerProps|unstable_getServerSideProps|unstable_getStaticProps|unstable_getStaticPaths/
1946
+ },
1947
+ handler(code, id) {
1948
+ if (this.environment?.name !== "client") return null;
1949
+ if (!hasPagesDir) return null;
1950
+ const modulePath = stripViteModuleQuery(id);
1951
+ if (!isWithinPagesDirectory(modulePath)) return null;
1952
+ const canonicalId = canonicalizePageTransformPath(modulePath);
1953
+ if (!isWithinPagesDirectory(canonicalId)) return null;
1954
+ if (!fileMatcher.isPageFile(canonicalId)) return null;
1955
+ const relativePath = canonicalId.slice(canonicalPagesDir.length);
1956
+ if (isApiPage(canonicalId)) return null;
1957
+ if (/^\/(?:_app|_document|_error)(?:\.[^/]*)?$/.test(relativePath)) return null;
1958
+ return stripServerExports(code);
1959
+ }
1960
+ }
1961
+ },
1962
+ {
1963
+ name: "vinext:validate-server-only-client-imports",
1964
+ transform: {
1965
+ filter: {
1966
+ id: {
1967
+ include: /\.(tsx?|jsx?|mjs)$/,
1968
+ exclude: VIRTUAL_MODULE_ID_RE
1969
+ },
1970
+ code: "server-only"
1971
+ },
1972
+ handler(code) {
1973
+ if (this.environment?.name !== "client") return null;
1974
+ if (getLeadingReactDirective(code) === "use server") return null;
1975
+ if (!hasServerOnlyMarkerImport(code)) return null;
1976
+ throw new Error(`You're importing a module that depends on "server-only". This API is only available in Server Components in the App Router, but this module is reachable from a client bundle.`);
1977
+ }
1978
+ }
1979
+ },
1980
+ {
1981
+ name: "vinext:remove-console",
1982
+ apply: "build",
1983
+ transform: {
1984
+ filter: {
1985
+ id: {
1986
+ include: /\.(tsx?|jsx?|mjs)$/,
1987
+ exclude: /\/node_modules\//
1988
+ },
1989
+ code: /\bconsole\b/
1990
+ },
1991
+ handler(code) {
1992
+ if (this.environment?.name !== "client") return null;
1993
+ if (!nextConfig.removeConsole) return null;
1994
+ return removeConsoleCalls(code, nextConfig.removeConsole);
1995
+ }
1996
+ }
1997
+ },
1998
+ {
1999
+ name: "vinext:typeof-window",
2000
+ enforce: "post",
2001
+ transform: {
2002
+ filter: {
2003
+ id: typeofWindowIdFilter,
2004
+ code: /typeof\s+window/
2005
+ },
2006
+ handler(code, id) {
2007
+ const cacheDirPrefix = getCacheDirPrefix(this.environment.config.cacheDir);
2008
+ if (normalizePathSeparators(id).startsWith(cacheDirPrefix)) return null;
2009
+ return replaceTypeofWindow(code, getTypeofWindowReplacement(this.environment));
2010
+ }
2011
+ }
2012
+ },
2013
+ {
2014
+ name: "vinext:compiler-define-server",
2015
+ configEnvironment(name) {
2016
+ if (name === "client") return null;
2017
+ const serverDefines = { ...nextConfig.compilerDefineServer };
2018
+ serverDefines["process.env.NEXT_RUNTIME"] = JSON.stringify("nodejs");
2019
+ const sharedRevalidateSecret = process.env.__VINEXT_SHARED_REVALIDATE_SECRET;
2020
+ if (sharedRevalidateSecret) serverDefines["process.env.__VINEXT_REVALIDATE_SECRET"] = JSON.stringify(sharedRevalidateSecret);
2021
+ return { define: serverDefines };
2022
+ }
2023
+ },
2024
+ {
2025
+ name: "vinext:image-imports",
2026
+ enforce: "pre",
2027
+ _dimCache: imageImportDimCache,
2028
+ buildStart() {
2029
+ imageImportDimCache.clear();
2030
+ staticImageAssets.clear();
2031
+ },
2032
+ watchChange(id) {
2033
+ const key = normalizePathSeparators(id);
2034
+ imageImportDimCache.delete(key);
2035
+ staticImageAssets.delete(key);
2036
+ staticImageImportsByModule.delete(key);
2037
+ },
2038
+ resolveId: {
2039
+ filter: { id: /\?vinext-(?:image-url|meta)$/ },
2040
+ handler(source, _importer) {
2041
+ if (source.endsWith("?vinext-image-url")) return `\0vinext-image-url:${source.slice(0, -17)}`;
2042
+ if (source.endsWith("?vinext-meta")) return `\0vinext-image-meta:${source.slice(0, -12)}`;
2043
+ return null;
2044
+ }
2045
+ },
2046
+ async load(id) {
2047
+ if (id.startsWith("\0vinext-image-url:")) {
2048
+ const imagePath = id.replace("\0vinext-image-url:", "");
2049
+ this.addWatchFile(imagePath);
2050
+ if (this.environment.config.command === "serve") return `import url from ${JSON.stringify(imagePath + "?url")}; export default url;`;
2051
+ const asset = createStaticImageAsset(imagePath);
2052
+ staticImageAssets.set(imagePath, asset);
2053
+ const builtFileName = `${resolveAssetsDir(nextConfig.assetPrefix)}/${asset.fileName}`;
2054
+ return `export default ${JSON.stringify(renderVinextBuiltUrl(builtFileName, nextConfig.assetPrefix, nextConfig.deploymentId))};`;
2055
+ }
2056
+ if (!id.startsWith("\0vinext-image-meta:")) return null;
2057
+ const imagePath = id.replace("\0vinext-image-meta:", "");
2058
+ this.addWatchFile(imagePath);
2059
+ const cache = imageImportDimCache;
2060
+ let dims = cache.get(imagePath);
2061
+ if (!dims) try {
2062
+ const { imageSize } = await import("image-size");
2063
+ const result = imageSize(fs.readFileSync(imagePath));
2064
+ dims = {
2065
+ width: result.width ?? 0,
2066
+ height: result.height ?? 0
2067
+ };
2068
+ cache.set(imagePath, dims);
2069
+ } catch {
2070
+ dims = {
2071
+ width: 0,
2072
+ height: 0
2073
+ };
2074
+ }
2075
+ return `export default ${JSON.stringify(dims)};`;
2076
+ },
2077
+ transform: {
2078
+ filter: {
2079
+ id: {
2080
+ include: /\.(tsx?|jsx?|mjs)$/,
2081
+ exclude: [/node_modules/, VIRTUAL_MODULE_ID_RE]
2082
+ },
2083
+ code: new RegExp(`import\\s+\\w+\\s+from\\s+['"][^'"]+\\.(${IMAGE_EXTS})['"]`)
2084
+ },
2085
+ async handler(code, id) {
2086
+ const lang = id.endsWith(".ts") ? "ts" : "tsx";
2087
+ let ast;
2088
+ try {
2089
+ ast = parseAst(code, { lang });
2090
+ } catch {
2091
+ return null;
2092
+ }
2093
+ const s = new MagicString(code);
2094
+ let hasChanges = false;
2095
+ const imageImports = /* @__PURE__ */ new Set();
2096
+ for (const node of ast.body) {
2097
+ if (node.type !== "ImportDeclaration") continue;
2098
+ const importNode = node;
2099
+ const importPath = importNode.source?.value;
2100
+ if (typeof importPath !== "string") continue;
2101
+ if (!IMAGE_EXT_RE.test(importPath)) continue;
2102
+ const specifiers = importNode.specifiers ?? [];
2103
+ if (specifiers.length !== 1) continue;
2104
+ const specifier = specifiers[0];
2105
+ if (specifier.type !== "ImportDefaultSpecifier") continue;
2106
+ const varName = specifier.local?.name;
2107
+ if (!varName) continue;
2108
+ const dir = path.dirname(id);
2109
+ const resolvedImage = importPath.startsWith(".") ? path.resolve(dir, importPath) : (await this.resolve(importPath, id, { skipSelf: true }))?.id;
2110
+ if (!resolvedImage) continue;
2111
+ const absImagePath = normalizePathSeparators(resolvedImage.split("?", 1)[0]);
2112
+ if (!fs.existsSync(absImagePath)) continue;
2113
+ imageImports.add(absImagePath);
2114
+ const urlVar = `__vinext_img_url_${varName}`;
2115
+ const metaVar = `__vinext_img_meta_${varName}`;
2116
+ const replacement = `import ${urlVar} from ${JSON.stringify(absImagePath + "?vinext-image-url")};\nimport ${metaVar} from ${JSON.stringify(absImagePath + "?vinext-meta")};\nvar ${varName} = { src: ${urlVar}, width: ${metaVar}.width, height: ${metaVar}.height };`;
2117
+ s.overwrite(importNode.start, importNode.end, replacement);
2118
+ hasChanges = true;
2119
+ }
2120
+ if (!hasChanges) {
2121
+ staticImageImportsByModule.delete(id);
2122
+ return null;
2123
+ }
2124
+ staticImageImportsByModule.set(id, imageImports);
2125
+ return {
2126
+ code: s.toString(),
2127
+ map: s.generateMap({ hires: "boundary" })
2128
+ };
2129
+ }
2130
+ },
2131
+ writeBundle: {
2132
+ sequential: true,
2133
+ order: "post",
2134
+ handler(outputOptions) {
2135
+ if (this.environment?.name !== "client") return;
2136
+ const clientOutDir = outputOptions.dir ? path.resolve(root, outputOptions.dir) : path.resolve(root, options.clientOutDir ?? "dist/client");
2137
+ const assetsDir = resolveAssetsDir(nextConfig.assetPrefix);
2138
+ const activeImagePaths = new Set(Array.from(staticImageImportsByModule.values()).flatMap((imports) => [...imports]));
2139
+ const nextWrittenFiles = /* @__PURE__ */ new Set();
2140
+ for (const imagePath of activeImagePaths) {
2141
+ if (!fs.existsSync(imagePath)) continue;
2142
+ const asset = staticImageAssets.get(imagePath) ?? createStaticImageAsset(imagePath);
2143
+ const outputPath = path.join(clientOutDir, assetsDir, asset.fileName);
2144
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
2145
+ fs.writeFileSync(outputPath, asset.source);
2146
+ nextWrittenFiles.add(outputPath);
2147
+ }
2148
+ for (const outputPath of writtenStaticImageFiles) if (!nextWrittenFiles.has(outputPath)) fs.rmSync(outputPath, { force: true });
2149
+ writtenStaticImageFiles.clear();
2150
+ for (const outputPath of nextWrittenFiles) writtenStaticImageFiles.add(outputPath);
2151
+ }
2152
+ }
2153
+ },
2154
+ createGoogleFontsPlugin(_fontGoogleShimPath, _shimsDir),
2155
+ createLocalFontsPlugin(_shimsDir),
2156
+ createOptimizeImportsPlugin(() => nextConfig, () => root),
2157
+ createDynamicPreloadMetadataPlugin(),
2158
+ {
2159
+ name: "vinext:use-cache",
2160
+ transform: {
2161
+ filter: {
2162
+ id: {
2163
+ include: /\.(tsx?|jsx?|mjs)$/,
2164
+ exclude: [/node_modules/, VIRTUAL_MODULE_ID_RE]
2165
+ },
2166
+ code: "use cache"
2167
+ },
2168
+ async handler(code, id) {
2169
+ const ast = parseAst(code);
2170
+ const cacheDirective = ast.body.find((node) => node.type === "ExpressionStatement" && node.expression?.type === "Literal" && typeof node.expression.value === "string" && node.expression.value.startsWith("use cache"));
2171
+ function nodeHasInlineCacheDirective(node) {
2172
+ if (!node || typeof node !== "object") return false;
2173
+ const fn = node.type === "MethodDefinition" ? node.value : node;
2174
+ const stmts = fn?.body?.type === "BlockStatement" ? fn.body.body : null;
2175
+ if (Array.isArray(stmts)) {
2176
+ for (const stmt of stmts) if (stmt?.type === "ExpressionStatement" && stmt.expression?.type === "Literal" && typeof stmt.expression?.value === "string" && /^use cache(:\s*\w+)?$/.test(stmt.expression.value)) return true;
2177
+ }
2178
+ return false;
2179
+ }
2180
+ function astHasInlineCache(nodes) {
2181
+ for (const node of nodes) {
2182
+ if (!node || typeof node !== "object") continue;
2183
+ if ((node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "MethodDefinition") && nodeHasInlineCacheDirective(node)) return true;
2184
+ for (const key of Object.keys(node)) {
2185
+ if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
2186
+ const child = node[key];
2187
+ if (Array.isArray(child) && child.some((c) => c && typeof c === "object")) {
2188
+ if (astHasInlineCache(child)) return true;
2189
+ } else if (child && typeof child === "object" && child.type) {
2190
+ if (astHasInlineCache([child])) return true;
2191
+ }
2192
+ }
2193
+ }
2194
+ return false;
2195
+ }
2196
+ const hasInlineCache = !cacheDirective && astHasInlineCache(ast.body);
2197
+ if (!cacheDirective && !hasInlineCache) return null;
2198
+ if (!resolvedRscTransformsPath) throw new Error("vinext: 'use cache' requires @vitejs/plugin-rsc to be installed.\nRun: " + detectPackageManager(process.cwd()) + " @vitejs/plugin-rsc");
2199
+ const { transformWrapExport, transformHoistInlineDirective } = await import(pathToFileURL(resolvedRscTransformsPath).href);
2200
+ if (cacheDirective) {
2201
+ const directiveValue = cacheDirective.expression.value;
2202
+ const variant = directiveValue === "use cache" ? "" : directiveValue.replace("use cache:", "").trim();
2203
+ const isLayoutOrTemplate = /\/(layout|template)\.(tsx?|jsx?|mjs)$/.test(id);
2204
+ const modulePath = stripViteModuleQuery(id);
2205
+ const moduleFileName = path.basename(modulePath);
2206
+ const isAppPageModule = hasAppDir && isInsideDirectory(appDir, modulePath) && path.parse(moduleFileName).name === "page" && fileMatcher.extensionRegex.test(moduleFileName);
2207
+ const runtimeModuleUrl = pathToFileURL(resolveShimModulePath(shimsDir, "cache-runtime")).href;
2208
+ const result = transformWrapExport(code, ast, {
2209
+ runtime: (value, name) => {
2210
+ const pageOptions = name === "default" && isAppPageModule ? `, { appPageDefaultExport: true }` : "";
2211
+ return `(await import(${JSON.stringify(runtimeModuleUrl)})).registerCachedFunction(${value}, ${JSON.stringify(id + ":" + name)}, ${JSON.stringify(variant)}${pageOptions})`;
2212
+ },
2213
+ rejectNonAsyncFunction: false,
2214
+ filter: (name, meta) => {
2215
+ if (meta.isFunction === false) return false;
2216
+ if (isLayoutOrTemplate && name === "default") return false;
2217
+ return true;
2218
+ }
2219
+ });
2220
+ if (result.exportNames.length > 0) {
2221
+ const output = result.output;
2222
+ output.overwrite(cacheDirective.start, cacheDirective.end, `/* "use cache" — wrapped by vinext */`);
2223
+ return {
2224
+ code: output.toString(),
2225
+ map: output.generateMap({ hires: "boundary" })
2226
+ };
2227
+ }
2228
+ const output = new MagicString(code);
2229
+ output.overwrite(cacheDirective.start, cacheDirective.end, `/* "use cache" — handled by vinext */`);
2230
+ return {
2231
+ code: output.toString(),
2232
+ map: output.generateMap({ hires: "boundary" })
2233
+ };
2234
+ }
2235
+ if (hasInlineCache) {
2236
+ const runtimeModuleUrl2 = pathToFileURL(resolveShimModulePath(shimsDir, "cache-runtime")).href;
2237
+ try {
2238
+ const result = transformHoistInlineDirective(code, ast, {
2239
+ directive: /^use cache(:\s*\w+)?$/,
2240
+ runtime: (value, name, meta) => {
2241
+ const directiveMatch = meta.directiveMatch[0];
2242
+ const variant = directiveMatch === "use cache" ? "" : directiveMatch.replace("use cache:", "").trim();
2243
+ return `(await import(${JSON.stringify(runtimeModuleUrl2)})).registerCachedFunction(${value}, ${JSON.stringify(id + ":" + name)}, ${JSON.stringify(variant)})`;
2244
+ },
2245
+ rejectNonAsyncFunction: false
2246
+ });
2247
+ if (result.names.length > 0) return {
2248
+ code: result.output.toString(),
2249
+ map: result.output.generateMap({ hires: "boundary" })
2250
+ };
2251
+ } catch {}
2252
+ }
2253
+ return null;
2254
+ }
2255
+ }
2256
+ },
2257
+ createImportMetaUrlPlugin({ getRoot: () => root }),
2258
+ createExtensionlessDynamicImportPlugin(),
2259
+ createRequireContextPlugin(),
2260
+ createOgInlineFetchAssetsPlugin(),
2261
+ createOgAssetsPlugin(),
2262
+ createServerExternalsManifestPlugin(),
2263
+ {
2264
+ name: "vinext:image-config",
2265
+ apply: "build",
2266
+ enforce: "post",
2267
+ writeBundle: {
2268
+ sequential: true,
2269
+ order: "post",
2270
+ handler(options) {
2271
+ if (this.environment?.name !== "rsc") return;
2272
+ const outDir = options.dir;
2273
+ if (!outDir) return;
2274
+ const imageConfig = {
2275
+ deviceSizes: nextConfig?.images?.deviceSizes,
2276
+ imageSizes: nextConfig?.images?.imageSizes,
2277
+ qualities: nextConfig?.images?.qualities,
2278
+ dangerouslyAllowSVG: nextConfig?.images?.dangerouslyAllowSVG,
2279
+ contentDispositionType: nextConfig?.images?.contentDispositionType,
2280
+ contentSecurityPolicy: nextConfig?.images?.contentSecurityPolicy
2281
+ };
2282
+ fs.writeFileSync(path.join(outDir, "image-config.json"), JSON.stringify(imageConfig));
2283
+ }
2284
+ }
2285
+ },
2286
+ (() => {
2287
+ let buildIdWritten = false;
2288
+ return {
2289
+ name: "vinext:build-id",
2290
+ apply: "build",
2291
+ enforce: "post",
2292
+ writeBundle: {
2293
+ sequential: true,
2294
+ order: "post",
2295
+ handler() {
2296
+ if (buildIdWritten) return;
2297
+ buildIdWritten = true;
2298
+ const outDir = path.join(root, "dist", "server");
2299
+ fs.mkdirSync(outDir, { recursive: true });
2300
+ fs.writeFileSync(path.join(outDir, "BUILD_ID"), nextConfig.buildId);
2301
+ }
2302
+ }
2303
+ };
2304
+ })(),
2305
+ {
2306
+ name: "vinext:hash-salt",
2307
+ apply: "build",
2308
+ augmentChunkHash() {
2309
+ if (this.environment?.name !== "client") return;
2310
+ const salt = nextConfig?.hashSalt;
2311
+ if (salt) return salt;
2312
+ }
2313
+ },
2314
+ (() => {
2315
+ const prerenderSecret = randomBytes(32).toString("hex");
2316
+ return {
2317
+ name: "vinext:server-manifest",
2318
+ apply: "build",
2319
+ enforce: "post",
2320
+ writeBundle: {
2321
+ sequential: true,
2322
+ order: "post",
2323
+ handler(options) {
2324
+ const envName = this.environment?.name;
2325
+ if (envName !== "rsc" && envName !== "ssr") return;
2326
+ const outDir = options.dir;
2327
+ if (!outDir) return;
2328
+ const manifest = { prerenderSecret };
2329
+ fs.writeFileSync(path.join(outDir, "vinext-server.json"), JSON.stringify(manifest));
2330
+ }
2331
+ }
2332
+ };
2333
+ })(),
2334
+ {
2335
+ name: "vinext:nitro-route-rules",
2336
+ nitro: { setup: async (nitro) => {
2337
+ if (nitro.options.dev) return;
2338
+ if (!nextConfig) return;
2339
+ if (!hasAppDir && !hasPagesDir) return;
2340
+ const { collectNitroRouteRules, mergeNitroRouteRules } = await import("./build/nitro-route-rules.js");
2341
+ const generatedRouteRules = await collectNitroRouteRules({
2342
+ appDir: hasAppDir ? appDir : null,
2343
+ pagesDir: hasPagesDir ? pagesDir : null,
2344
+ pageExtensions: nextConfig.pageExtensions
2345
+ });
2346
+ if (Object.keys(generatedRouteRules).length === 0) return;
2347
+ const { routeRules, skippedRoutes } = mergeNitroRouteRules(nitro.options.routeRules, generatedRouteRules);
2348
+ nitro.options.routeRules = routeRules;
2349
+ if (skippedRoutes.length > 0) (nitro.logger?.warn ?? console.warn)(`[vinext] Skipping generated Nitro routeRules for routes with existing exact cache config: ${skippedRoutes.join(", ")}`);
2350
+ } }
2351
+ },
2352
+ {
2353
+ name: "vinext:ssr-manifest-backfill",
2354
+ apply: "build",
2355
+ enforce: "post",
2356
+ writeBundle: {
2357
+ sequential: true,
2358
+ order: "post",
2359
+ handler(options, bundle) {
2360
+ const outDir = options.dir;
2361
+ if (!outDir) return;
2362
+ const viteDir = path.join(outDir, ".vite");
2363
+ const ssrManifestPath = path.join(viteDir, "ssr-manifest.json");
2364
+ if (!fs.existsSync(ssrManifestPath)) return;
2365
+ try {
2366
+ const augmentedManifest = augmentSsrManifestFromBundle(JSON.parse(fs.readFileSync(ssrManifestPath, "utf-8")), bundle, this.environment?.config.root ?? process.cwd(), this.environment?.config.base ?? "/");
2367
+ fs.writeFileSync(ssrManifestPath, JSON.stringify(augmentedManifest, null, 2));
2368
+ } catch (err) {
2369
+ console.warn("[vinext] Failed to augment SSR manifest:", err);
2370
+ }
2371
+ }
2372
+ }
2373
+ },
2374
+ {
2375
+ name: "vinext:next-client-runtime-manifests",
2376
+ apply: "build",
2377
+ enforce: "post",
2378
+ writeBundle: {
2379
+ sequential: true,
2380
+ order: "post",
2381
+ handler(outputOptions) {
2382
+ const clientDir = outputOptions.dir;
2383
+ if (!clientDir) return;
2384
+ if (!(this.environment?.name === "client")) return;
2385
+ emitNextClientRuntimeManifests({
2386
+ clientDir,
2387
+ assetsSubdir: resolveAssetsDir(nextConfig.assetPrefix),
2388
+ buildId: nextConfig.buildId,
2389
+ rewrites: nextConfig.rewrites
2390
+ });
2391
+ }
2392
+ }
2393
+ },
2394
+ (() => {
2395
+ let pendingPrecompress = null;
2396
+ let pendingPrecompressError = null;
2397
+ return {
2398
+ name: "vinext:precompress",
2399
+ apply: "build",
2400
+ enforce: "post",
2401
+ writeBundle: {
2402
+ sequential: true,
2403
+ order: "post",
2404
+ handler(outputOptions) {
2405
+ if (this.environment?.name !== "client") return;
2406
+ if (!options.precompress && process.env.VINEXT_PRECOMPRESS !== "1") return;
2407
+ const outDir = outputOptions.dir;
2408
+ if (!outDir) return;
2409
+ const assetsSubdir = resolveAssetsDir(nextConfig.assetPrefix);
2410
+ const assetsDir = path.join(outDir, assetsSubdir);
2411
+ if (!fs.existsSync(assetsDir)) return;
2412
+ const isTTY = process.stderr.isTTY;
2413
+ let lastLineLen = 0;
2414
+ pendingPrecompressError = null;
2415
+ pendingPrecompress = (async () => {
2416
+ const result = await precompressAssets(outDir, {
2417
+ assetsDir: assetsSubdir,
2418
+ onProgress: (completed, total, file) => {
2419
+ if (!isTTY) return;
2420
+ const pct = total > 0 ? Math.floor(completed / total * 100) : 0;
2421
+ const bar = `[${"█".repeat(Math.floor(pct / 5))}${" ".repeat(20 - Math.floor(pct / 5))}]`;
2422
+ const fileLabel = file.length > 30 ? "…" + file.slice(-29) : file;
2423
+ const line = `Compressing assets... ${bar} ${String(completed).padStart(String(total).length)}/${total} ${fileLabel}`;
2424
+ const padded = line.padEnd(lastLineLen);
2425
+ lastLineLen = line.length;
2426
+ process.stderr.write(`\r${padded}`);
2427
+ }
2428
+ });
2429
+ if (isTTY) process.stderr.write(`\r${" ".repeat(lastLineLen)}\r`);
2430
+ if (result.filesCompressed > 0) {
2431
+ const ratio = ((1 - result.totalBrotliBytes / result.totalOriginalBytes) * 100).toFixed(1);
2432
+ console.log(` Precompressed ${result.filesCompressed} assets (${ratio}% smaller with brotli)`);
2433
+ }
2434
+ })().catch((error) => {
2435
+ pendingPrecompressError = error;
2436
+ console.error("[vinext] Precompression failed:", error);
2437
+ });
2438
+ }
2439
+ },
2440
+ closeBundle: {
2441
+ sequential: true,
2442
+ order: "post",
2443
+ async handler() {
2444
+ if (this.environment?.name !== "ssr") return;
2445
+ if (!pendingPrecompress) return;
2446
+ const task = pendingPrecompress;
2447
+ pendingPrecompress = null;
2448
+ await task;
2449
+ if (pendingPrecompressError) {
2450
+ const error = pendingPrecompressError;
2451
+ pendingPrecompressError = null;
2452
+ throw error;
2453
+ }
2454
+ }
2455
+ }
2456
+ };
2457
+ })(),
2458
+ {
2459
+ name: "vinext:inline-css-manifest",
2460
+ apply: "build",
2461
+ enforce: "post",
2462
+ closeBundle: {
2463
+ sequential: true,
2464
+ order: "post",
2465
+ handler() {
2466
+ if (this.environment?.name !== "client") return;
2467
+ if (!hasAppDir || nextConfig?.inlineCss !== true) return;
2468
+ const envConfig = this.environment?.config;
2469
+ if (!envConfig) return;
2470
+ const buildRoot = envConfig.root ?? process.cwd();
2471
+ const manifest = collectInlineCssManifest(path.resolve(buildRoot, "dist", "client"), nextConfig.assetPrefix);
2472
+ const rscOutDir = path.resolve(buildRoot, options.rscOutDir ?? path.join("dist", "server"));
2473
+ for (const entryFile of ["index.js", "index.mjs"]) if (injectInlineCssManifestGlobal(path.join(rscOutDir, entryFile), manifest)) break;
2474
+ }
2475
+ }
2476
+ },
2477
+ {
2478
+ name: "vinext:cloudflare-build",
2479
+ apply: "build",
2480
+ enforce: "post",
2481
+ closeBundle: {
2482
+ sequential: true,
2483
+ order: "post",
2484
+ async handler() {
2485
+ const envName = this.environment?.name;
2486
+ if (!envName || !hasCloudflarePlugin) return;
2487
+ if (envName !== "client") return;
2488
+ const envConfig = this.environment?.config;
2489
+ if (!envConfig) return;
2490
+ const buildRoot = envConfig.root ?? process.cwd();
2491
+ const distDir = path.resolve(buildRoot, "dist");
2492
+ if (!fs.existsSync(distDir)) return;
2493
+ const clientDir = path.resolve(buildRoot, "dist", "client");
2494
+ const runtimeMetadata = computeClientRuntimeMetadata({
2495
+ clientDir,
2496
+ assetBase: envConfig.base ?? "/",
2497
+ assetPrefix: nextConfig.assetPrefix,
2498
+ includeClientEntry: !hasAppDir ? true : hasPagesDir ? "pages-client-entry" : false
2499
+ });
2500
+ const lazyChunksData = runtimeMetadata.lazyChunks ?? null;
2501
+ const dynamicPreloadsData = runtimeMetadata.dynamicPreloads ?? null;
2502
+ let clientEntryFile = runtimeMetadata.clientEntryFile ?? null;
2503
+ let ssrManifestData = null;
2504
+ const ssrManifestPath = path.join(clientDir, ".vite", "ssr-manifest.json");
2505
+ if (fs.existsSync(ssrManifestPath)) try {
2506
+ ssrManifestData = JSON.parse(fs.readFileSync(ssrManifestPath, "utf-8"));
2507
+ } catch {}
2508
+ if (hasAppDir) {
2509
+ const workerEntry = path.resolve(distDir, "server", "index.js");
2510
+ if (fs.existsSync(workerEntry)) {
2511
+ const script = buildRuntimeGlobalsScript({
2512
+ clientEntryFile,
2513
+ ssrManifest: ssrManifestData,
2514
+ lazyChunks: lazyChunksData,
2515
+ dynamicPreloads: dynamicPreloadsData
2516
+ });
2517
+ if (script) {
2518
+ const code = fs.readFileSync(workerEntry, "utf-8");
2519
+ fs.writeFileSync(workerEntry, script + "\n" + code);
2520
+ }
2521
+ }
2522
+ } else {
2523
+ let workerOutDir = null;
2524
+ for (const entry of fs.readdirSync(distDir)) {
2525
+ const candidate = path.join(distDir, entry);
2526
+ if (entry === "client") continue;
2527
+ if (fs.statSync(candidate).isDirectory() && fs.existsSync(path.join(candidate, "wrangler.json"))) {
2528
+ workerOutDir = candidate;
2529
+ break;
2530
+ }
2531
+ }
2532
+ if (!workerOutDir) return;
2533
+ const workerEntry = path.join(workerOutDir, "index.js");
2534
+ if (!fs.existsSync(workerEntry)) return;
2535
+ const script = buildRuntimeGlobalsScript({
2536
+ clientEntryFile,
2537
+ ssrManifest: ssrManifestData,
2538
+ lazyChunks: lazyChunksData,
2539
+ dynamicPreloads: dynamicPreloadsData
2540
+ });
2541
+ if (script) {
2542
+ const code = fs.readFileSync(workerEntry, "utf-8");
2543
+ fs.writeFileSync(workerEntry, script + "\n" + code);
2544
+ }
2545
+ }
2546
+ const headersPath = path.join(clientDir, "_headers");
2547
+ if (!fs.existsSync(headersPath)) {
2548
+ const headersContent = [
2549
+ "# Cache content-hashed assets immutably (generated by vinext)",
2550
+ `/${envConfig.build?.assetsDir ?? "_next/static"}/*`,
2551
+ " Cache-Control: public, max-age=31536000, immutable",
2552
+ ""
2553
+ ].join("\n");
2554
+ fs.mkdirSync(clientDir, { recursive: true });
2555
+ fs.writeFileSync(headersPath, headersContent);
2556
+ }
2557
+ ensureAssetsIgnore(clientDir);
2558
+ }
2559
+ }
2560
+ },
2561
+ createWasmModuleImportPlugin(),
2562
+ {
2563
+ name: "vinext:og-font-patch",
2564
+ enforce: "pre",
2565
+ transform: {
2566
+ filter: { id: /@vercel\/og.*index\.edge\.js/ },
2567
+ handler(code, id) {
2568
+ let result = code;
2569
+ const yogaMatch = /H = "data:application\/octet-stream;base64,([A-Za-z0-9+/]+=*)";/.exec(result);
2570
+ if (yogaMatch) {
2571
+ const yogaBase64 = yogaMatch[1];
2572
+ const distDir = path.dirname(id);
2573
+ const yogaWasmPath = path.join(distDir, "yoga.wasm");
2574
+ if (!fs.existsSync(yogaWasmPath)) fs.writeFileSync(yogaWasmPath, Buffer.from(yogaBase64, "base64"));
2575
+ result = result.replace(yogaMatch[0], `H = "";`);
2576
+ const YOGA_CALL = `yoga_wasm_base64_esm_default()`;
2577
+ const YOGA_CALL_PATCHED = [
2578
+ `yoga_wasm_base64_esm_default({ instantiateWasm: function(imports, callback) {`,
2579
+ ` __vi_yoga_mod.then(function(mod) {`,
2580
+ ` if (mod) {`,
2581
+ ` WebAssembly.instantiate(mod, imports).then(function(inst) { callback(inst); });`,
2582
+ ` } else {`,
2583
+ ` Promise.all([import("node:fs"), import("node:url")]).then(function(mods) {`,
2584
+ ` var p = mods[1].fileURLToPath(new URL("./yoga.wasm", import.meta.url));`,
2585
+ ` return mods[0].promises.readFile(p).then(function(bytes) {`,
2586
+ ` return WebAssembly.instantiate(bytes, imports).then(function(r) { callback(r.instance); });`,
2587
+ ` });`,
2588
+ ` });`,
2589
+ ` }`,
2590
+ ` });`,
2591
+ ` return {};`,
2592
+ `} })`
2593
+ ].join("\n");
2594
+ result = result.replace(YOGA_CALL, YOGA_CALL_PATCHED);
2595
+ result = [`var __vi_yoga_mod = import("./yoga.wasm?module").then(function(m) { return m.default; }).catch(function() { return null; });`].join("\n") + "\n" + result;
2596
+ }
2597
+ const resvgMatch = /import\s+resvg_wasm\s+from\s+["']\.\/resvg\.wasm\?module["']\s*;?/.exec(result);
2598
+ if (resvgMatch) {
2599
+ const resvgLoader = [
2600
+ `var resvg_wasm = import("./resvg.wasm?module").then(function(m) { return m.default; }).catch(function() {`,
2601
+ ` return Promise.all([import("node:fs"), import("node:url")]).then(function(mods) {`,
2602
+ ` var p = mods[1].fileURLToPath(new URL("./resvg.wasm", import.meta.url));`,
2603
+ ` return mods[0].promises.readFile(p).then(function(buf) { return WebAssembly.compile(buf); });`,
2604
+ ` });`,
2605
+ `});`
2606
+ ].join("\n");
2607
+ result = result.replace(resvgMatch[0], resvgLoader);
2608
+ }
2609
+ if (result === code) return null;
2610
+ return {
2611
+ code: result,
2612
+ map: null
2613
+ };
2614
+ }
2615
+ }
2616
+ }
2617
+ ];
2618
+ if (rscPluginPromise) {
2619
+ plugins.push(rscPluginPromise);
2620
+ plugins.push(createRscClientReferenceLoadersPlugin());
2621
+ }
2622
+ return plugins;
2623
+ }
2624
+ /**
2625
+ * Collect all NEXT_PUBLIC_* env vars and create Vite define entries
2626
+ * so they get inlined into the client bundle.
2627
+ */
2628
+ function getNextPublicEnvDefines() {
2629
+ const defines = {};
2630
+ for (const [key, value] of Object.entries(process.env)) if (key.startsWith("NEXT_PUBLIC_") && value !== void 0) defines[`process.env.${key}`] = JSON.stringify(value);
2631
+ return defines;
2632
+ }
2633
+ /**
2634
+ * Write a Web API Response to a Node.js ServerResponse.
2635
+ * Handles multi-value headers (Set-Cookie) correctly.
2636
+ */
2637
+ async function writeWebResponseToNodeRes(res, response) {
2638
+ const nodeHeaders = {};
2639
+ response.headers.forEach((value, key) => {
2640
+ if (key === "set-cookie") return;
2641
+ const existing = nodeHeaders[key];
2642
+ if (existing !== void 0) nodeHeaders[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];
2643
+ else nodeHeaders[key] = value;
2644
+ });
2645
+ const cookies = response.headers.getSetCookie?.() ?? [];
2646
+ if (cookies.length > 0) nodeHeaders["set-cookie"] = cookies;
2647
+ if (response.statusText) res.writeHead(response.status, response.statusText, nodeHeaders);
2648
+ else res.writeHead(response.status, nodeHeaders);
2649
+ if (response.body) {
2650
+ const { Readable } = await import("node:stream");
2651
+ const nodeStream = Readable.fromWeb(response.body);
2652
+ await new Promise((resolve, reject) => {
2653
+ nodeStream.on("error", reject);
2654
+ res.on("error", reject);
2655
+ nodeStream.pipe(res);
2656
+ nodeStream.on("end", resolve);
2657
+ });
2658
+ } else res.end();
2659
+ }
2660
+ //#endregion
2661
+ export { vinext as default, staticExportApp, staticExportPages };