vinext 0.2.1 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +67 -30
  2. package/dist/build/assets-ignore.js +1 -1
  3. package/dist/build/clean-output.js +1 -1
  4. package/dist/build/client-build-config.d.ts +13 -92
  5. package/dist/build/client-build-config.js +23 -99
  6. package/dist/build/css-url-assets.js +3 -3
  7. package/dist/build/google-fonts/fallback-metrics.js +1 -1
  8. package/dist/build/google-fonts/font-metadata.js +1 -1
  9. package/dist/build/inject-pregenerated-paths.js +1 -1
  10. package/dist/build/inline-css.js +2 -5
  11. package/dist/build/module-dependency-cache.d.ts +4 -0
  12. package/dist/build/module-dependency-cache.js +13 -0
  13. package/dist/build/next-client-runtime-manifests.js +1 -1
  14. package/dist/build/pages-client-assets-module.js +1 -1
  15. package/dist/build/precompress.js +7 -7
  16. package/dist/build/prerender-paths.d.ts +23 -0
  17. package/dist/build/prerender-paths.js +291 -0
  18. package/dist/build/prerender-server-pool.js +2 -2
  19. package/dist/build/prerender.d.ts +12 -1
  20. package/dist/build/prerender.js +2 -2
  21. package/dist/build/preview-credentials.d.ts +11 -0
  22. package/dist/build/preview-credentials.js +19 -0
  23. package/dist/build/report.d.ts +0 -3
  24. package/dist/build/report.js +2 -4
  25. package/dist/build/run-prerender.d.ts +2 -11
  26. package/dist/build/run-prerender.js +2 -10
  27. package/dist/build/server-manifest.js +1 -1
  28. package/dist/build/ssr-manifest.d.ts +4 -0
  29. package/dist/build/ssr-manifest.js +10 -6
  30. package/dist/build/standalone.js +37 -37
  31. package/dist/cache/cache-adapters-virtual.d.ts +7 -17
  32. package/dist/cache/cache-adapters-virtual.js +35 -2
  33. package/dist/check.d.ts +0 -16
  34. package/dist/check.js +17 -34
  35. package/dist/cli.js +86 -101
  36. package/dist/client/instrumentation-client-inject.js +1 -1
  37. package/dist/client/pages-router-link-navigation.js +1 -1
  38. package/dist/config/config-matchers.js +2 -2
  39. package/dist/config/dotenv.js +1 -1
  40. package/dist/config/next-config.d.ts +4 -1
  41. package/dist/config/next-config.js +82 -16
  42. package/dist/config/prerender.d.ts +12 -2
  43. package/dist/config/prerender.js +22 -12
  44. package/dist/config/server-external-packages.js +1 -1
  45. package/dist/config/tsconfig-paths.js +7 -3
  46. package/dist/{node_modules/.pnpm/am-i-vibing@0.5.0/node_modules → deps/.pnpm/am-i-vibing@0.5.0/deps}/am-i-vibing/dist/detector-1yx2Hoe0.js +2 -2
  47. package/dist/deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js +50 -0
  48. package/dist/entries/app-rsc-entry.js +12 -5
  49. package/dist/entries/app-rsc-manifest.js +4 -4
  50. package/dist/entries/pages-client-entry.js +6 -5
  51. package/dist/entries/pages-server-entry.js +15 -26
  52. package/dist/entries/runtime-entry-module.js +2 -2
  53. package/dist/image/image-adapters-virtual.js +1 -0
  54. package/dist/index.d.ts +1 -1
  55. package/dist/index.js +500 -338
  56. package/dist/init-cloudflare.js +13 -4
  57. package/dist/init-platform.d.ts +10 -1
  58. package/dist/init-platform.js +79 -13
  59. package/dist/init.d.ts +11 -3
  60. package/dist/init.js +133 -35
  61. package/dist/plugins/ast-utils.js +1 -1
  62. package/dist/plugins/dynamic-preload-metadata.js +7 -7
  63. package/dist/plugins/extensionless-dynamic-import.js +1 -1
  64. package/dist/plugins/fonts.js +3 -3
  65. package/dist/plugins/ignore-dynamic-requests.js +13 -8
  66. package/dist/plugins/import-meta-url.js +16 -17
  67. package/dist/plugins/middleware-export-validation.js +1 -1
  68. package/dist/plugins/middleware-server-only.js +2 -2
  69. package/dist/plugins/og-asset-ownership.js +7 -6
  70. package/dist/plugins/og-assets.js +4 -5
  71. package/dist/plugins/optimize-imports.js +12 -13
  72. package/dist/plugins/postcss.js +1 -1
  73. package/dist/plugins/remove-console.js +1 -1
  74. package/dist/plugins/require-context.js +1 -1
  75. package/dist/plugins/sass.js +2 -2
  76. package/dist/plugins/server-externals-manifest.js +1 -1
  77. package/dist/plugins/strip-server-exports.js +1 -1
  78. package/dist/plugins/styled-jsx.js +3 -2
  79. package/dist/plugins/typeof-window.js +1 -1
  80. package/dist/routing/app-route-graph.d.ts +3 -10
  81. package/dist/routing/app-route-graph.js +28 -76
  82. package/dist/routing/app-router.d.ts +0 -5
  83. package/dist/routing/app-router.js +0 -5
  84. package/dist/routing/file-matcher.d.ts +2 -6
  85. package/dist/routing/file-matcher.js +10 -11
  86. package/dist/routing/pages-router.js +3 -3
  87. package/dist/server/api-handler.js +41 -33
  88. package/dist/server/app-browser-entry.js +15 -11
  89. package/dist/server/app-browser-navigation-controller.js +9 -4
  90. package/dist/server/app-browser-server-action-client.js +1 -1
  91. package/dist/server/app-elements-wire.d.ts +2 -1
  92. package/dist/server/app-fallback-renderer.d.ts +8 -0
  93. package/dist/server/app-fallback-renderer.js +13 -1
  94. package/dist/server/app-layout-param-observation.d.ts +1 -1
  95. package/dist/server/app-page-boundary-render.d.ts +14 -1
  96. package/dist/server/app-page-boundary-render.js +107 -54
  97. package/dist/server/app-page-cache-render.d.ts +1 -1
  98. package/dist/server/app-page-dispatch.d.ts +2 -1
  99. package/dist/server/app-page-dispatch.js +29 -40
  100. package/dist/server/app-page-element-builder.d.ts +2 -1
  101. package/dist/server/app-page-element-builder.js +3 -3
  102. package/dist/server/app-page-execution.d.ts +3 -1
  103. package/dist/server/app-page-execution.js +31 -39
  104. package/dist/server/app-page-render.d.ts +1 -1
  105. package/dist/server/app-page-request.js +1 -1
  106. package/dist/server/app-page-route-wiring.js +4 -4
  107. package/dist/server/app-route-handler-execution.d.ts +1 -1
  108. package/dist/server/app-route-tree-prefetch.js +1 -1
  109. package/dist/server/app-rsc-cache-busting.js +1 -2
  110. package/dist/server/app-rsc-handler.js +2 -2
  111. package/dist/server/app-rsc-redirect-flight.d.ts +66 -0
  112. package/dist/server/app-rsc-redirect-flight.js +71 -0
  113. package/dist/server/app-rsc-render-mode.d.ts +2 -5
  114. package/dist/server/app-rsc-render-mode.js +2 -12
  115. package/dist/server/app-segment-config.js +2 -2
  116. package/dist/server/app-server-action-execution.js +3 -3
  117. package/dist/server/app-ssr-entry.js +4 -1
  118. package/dist/server/app-ssr-stream.d.ts +2 -1
  119. package/dist/server/app-ssr-stream.js +4 -1
  120. package/dist/server/cache-proof.js +1 -1
  121. package/dist/server/default-global-error-module.d.ts +3 -1
  122. package/dist/server/default-not-found-module.d.ts +3 -1
  123. package/dist/server/dev-lockfile.js +2 -3
  124. package/dist/server/dev-module-runner.js +1 -1
  125. package/dist/server/dev-origin-check.d.ts +2 -2
  126. package/dist/server/dev-origin-check.js +2 -2
  127. package/dist/server/dev-route-files.js +1 -1
  128. package/dist/server/dev-server.js +256 -164
  129. package/dist/server/dev-stack-sourcemap.js +4 -3
  130. package/dist/server/headers.d.ts +3 -1
  131. package/dist/server/headers.js +3 -1
  132. package/dist/server/image-optimization.d.ts +12 -1
  133. package/dist/server/image-optimization.js +15 -3
  134. package/dist/server/implicit-tags.js +2 -1
  135. package/dist/server/instrumentation.js +2 -2
  136. package/dist/server/isr-cache.d.ts +12 -4
  137. package/dist/server/isr-cache.js +3 -3
  138. package/dist/server/metadata-routes.js +4 -4
  139. package/dist/server/middleware-response-headers.js +1 -1
  140. package/dist/server/middleware-runtime.js +1 -1
  141. package/dist/server/middleware.d.ts +1 -0
  142. package/dist/server/middleware.js +1 -1
  143. package/dist/server/navigation-planner.d.ts +2 -0
  144. package/dist/server/navigation-planner.js +8 -2
  145. package/dist/server/next-error-digest.d.ts +9 -24
  146. package/dist/server/next-error-digest.js +23 -15
  147. package/dist/server/operation-token.js +1 -1
  148. package/dist/server/pages-body-parser-config.js +2 -1
  149. package/dist/server/pages-dev-hydration.d.ts +14 -0
  150. package/dist/server/pages-dev-hydration.js +83 -0
  151. package/dist/server/pages-dev-module-url.js +2 -2
  152. package/dist/server/pages-node-compat.d.ts +13 -6
  153. package/dist/server/pages-node-compat.js +44 -45
  154. package/dist/server/pages-page-data.d.ts +1 -1
  155. package/dist/server/pages-page-data.js +5 -4
  156. package/dist/server/pages-page-handler.js +61 -29
  157. package/dist/server/pages-page-response.d.ts +2 -2
  158. package/dist/server/pages-page-response.js +2 -2
  159. package/dist/server/pages-preview.d.ts +26 -0
  160. package/dist/server/pages-preview.js +165 -0
  161. package/dist/server/pages-readiness.d.ts +2 -1
  162. package/dist/server/pages-readiness.js +4 -2
  163. package/dist/server/pages-request-pipeline.js +1 -1
  164. package/dist/server/prerender-manifest.d.ts +15 -1
  165. package/dist/server/prerender-manifest.js +29 -1
  166. package/dist/server/prod-server.d.ts +6 -5
  167. package/dist/server/prod-server.js +15 -15
  168. package/dist/server/request-pipeline.js +1 -1
  169. package/dist/server/seed-cache.js +1 -1
  170. package/dist/server/socket-error-backstop.js +1 -1
  171. package/dist/server/static-file-cache.js +8 -9
  172. package/dist/server/worker-utils.js +1 -1
  173. package/dist/shims/cache.d.ts +1 -1
  174. package/dist/shims/cache.js +2 -1
  175. package/dist/shims/cdn-cache.d.ts +2 -7
  176. package/dist/shims/cdn-cache.js +2 -14
  177. package/dist/shims/constants.js +1 -1
  178. package/dist/shims/error-boundary.d.ts +4 -4
  179. package/dist/shims/error.d.ts +21 -5
  180. package/dist/shims/error.js +52 -14
  181. package/dist/shims/fetch-cache.js +1 -1
  182. package/dist/shims/font-utils.js +1 -1
  183. package/dist/shims/form.d.ts +1 -1
  184. package/dist/shims/head.js +3 -3
  185. package/dist/shims/headers.js +6 -4
  186. package/dist/shims/internal/pages-data-fetch-dedup.js +5 -3
  187. package/dist/shims/layout-segment-context.d.ts +1 -1
  188. package/dist/shims/link.d.ts +3 -1
  189. package/dist/shims/link.js +6 -3
  190. package/dist/shims/navigation-errors.d.ts +2 -1
  191. package/dist/shims/navigation-errors.js +9 -13
  192. package/dist/shims/navigation.d.ts +1 -1
  193. package/dist/shims/navigation.js +5 -5
  194. package/dist/shims/request-state-types.d.ts +2 -2
  195. package/dist/shims/router-state.d.ts +1 -0
  196. package/dist/shims/router.d.ts +2 -1
  197. package/dist/shims/router.js +18 -11
  198. package/dist/shims/script.js +1 -1
  199. package/dist/shims/server.js +2 -2
  200. package/dist/shims/slot.d.ts +1 -1
  201. package/dist/shims/thenable-params.js +1 -1
  202. package/dist/shims/unified-request-context.d.ts +1 -1
  203. package/dist/typegen.js +9 -11
  204. package/dist/utils/client-build-manifest.js +2 -2
  205. package/dist/utils/client-entry-manifest.js +1 -1
  206. package/dist/utils/client-runtime-metadata.js +1 -1
  207. package/dist/utils/commonjs-loader.js +3 -3
  208. package/dist/utils/mdx-scan.js +1 -1
  209. package/dist/utils/path.d.ts +1 -13
  210. package/dist/utils/path.js +1 -15
  211. package/dist/utils/plugin-options.d.ts +4 -0
  212. package/dist/utils/plugin-options.js +8 -0
  213. package/dist/utils/project.d.ts +1 -7
  214. package/dist/utils/project.js +2 -8
  215. package/dist/utils/public-routes.js +2 -2
  216. package/dist/utils/react-version.js +1 -1
  217. package/dist/utils/redirect-digest.d.ts +9 -0
  218. package/dist/utils/redirect-digest.js +25 -0
  219. package/dist/utils/vinext-root.js +1 -1
  220. package/dist/utils/vite-version.d.ts +6 -13
  221. package/dist/utils/vite-version.js +68 -34
  222. package/package.json +33 -14
  223. package/dist/cloudflare/index.d.ts +0 -3
  224. package/dist/cloudflare/index.js +0 -3
  225. package/dist/packages/cloudflare/src/cache/cdn-adapter.runtime.js +0 -102
  226. package/dist/packages/cloudflare/src/cache/kv-data-adapter.runtime.d.ts +0 -126
  227. package/dist/packages/cloudflare/src/cache/kv-data-adapter.runtime.js +0 -442
  228. package/dist/packages/cloudflare/src/deploy-config.js +0 -150
  229. package/dist/packages/cloudflare/src/deploy-help.js +0 -55
  230. package/dist/packages/cloudflare/src/deploy.js +0 -272
  231. package/dist/packages/cloudflare/src/tpr.d.ts +0 -45
  232. package/dist/packages/cloudflare/src/tpr.js +0 -582
  233. package/dist/packages/cloudflare/src/utils/cache-control-metadata.js +0 -20
  234. /package/dist/build/google-fonts/{fallback-metrics-data.js → fallback-metrics-data.json.js} +0 -0
  235. /package/dist/build/google-fonts/{font-data.js → font-data.json.js} +0 -0
  236. /package/dist/{node_modules/.pnpm/process-ancestry@0.1.0/node_modules → deps/.pnpm/process-ancestry@0.1.0/deps}/process-ancestry/dist/index.js +0 -0
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
+ import path, { toSlash } from "./deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
1
2
  import { detectPackageManager, formatMissingCloudflarePluginError, hasWranglerConfig } from "./utils/project.js";
2
- import { normalizePathSeparators, stripJsExtension, stripViteModuleQuery } from "./utils/path.js";
3
3
  import { normalizePathnameForRouteMatchStrict } from "./routing/utils.js";
4
- import { escapeRegExp } from "./utils/regex.js";
5
4
  import { buildViteResolveExtensions, createValidFileMatcher, findFileWithExts, normalizeViteResolveExtensions } from "./routing/file-matcher.js";
6
5
  import { apiRouter, invalidateRouteCache, matchRoute, pagesRouter } from "./routing/pages-router.js";
7
6
  import { VINEXT_MW_CTX_HEADER } from "./utils/protocol-headers.js";
@@ -21,6 +20,7 @@ import { logRequest, now } from "./server/request-log.js";
21
20
  import { resolvePagesI18nRequest, stripI18nLocaleForApiRoute } from "./server/pages-i18n.js";
22
21
  import { isNextDataPathname, normalizeNextDataPagePathname, parseNextDataPathname } from "./server/pages-data-route.js";
23
22
  import { resolveAssetsDir } from "./utils/asset-prefix.js";
23
+ import { getPagesPreviewModeId } from "./server/pages-preview.js";
24
24
  import { createSSRHandler } from "./server/dev-server.js";
25
25
  import { handleApiRoute } from "./server/api-handler.js";
26
26
  import { DEFAULT_DEVICE_SIZES, DEFAULT_IMAGE_SIZES, isImageOptimizationPath, resolveDevImageRedirect } from "./server/image-optimization.js";
@@ -31,15 +31,14 @@ import { createDirectRunner } from "./server/dev-module-runner.js";
31
31
  import { validateDevRequest } from "./server/dev-origin-check.js";
32
32
  import { generateRscEntry } from "./entries/app-rsc-entry.js";
33
33
  import { generateSsrEntry } from "./entries/app-ssr-entry.js";
34
- import { VIRTUAL_CACHE_ADAPTERS, generateCacheAdaptersModule } from "./cache/cache-adapters-virtual.js";
34
+ import { VINEXT_CACHE_CONFIG_PLUGIN_PROPERTY, VIRTUAL_CACHE_ADAPTERS, generateCacheAdaptersModule } from "./cache/cache-adapters-virtual.js";
35
35
  import { VIRTUAL_IMAGE_ADAPTERS, generateImageAdaptersModule } from "./image/image-adapters-virtual.js";
36
36
  import { generateBrowserEntry, isLinkPrefetchRoute, toDocumentOnlyAppRoute, toLinkPrefetchRoute } from "./entries/app-browser-entry.js";
37
37
  import { collectRouteClassificationManifest } from "./build/route-classification-manifest.js";
38
38
  import { planRouteClassificationInjection } from "./build/route-classification-injector.js";
39
39
  import { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } from "./shims/constants.js";
40
40
  import { RESOLVED_VIRTUAL_GOOGLE_FONTS, VIRTUAL_GOOGLE_FONTS, createGoogleFontsPlugin, createLocalFontsPlugin, generateGoogleFontsVirtualModule, parseStaticObjectLiteral } from "./plugins/fonts.js";
41
- import { getDepOptimizeNodeEnvOptions, getViteMajorVersion, serializeViteDefine } from "./utils/vite-version.js";
42
- import { createRscCompatibilityId, findNextConfigPath, loadNextConfig, resolveNextConfig, resolveNextConfigInput } from "./config/next-config.js";
41
+ import { VINEXT_NEXT_CONFIG_PLUGIN_PROPERTY, createRscCompatibilityId, findNextConfigPath, loadNextConfig, resolveNextConfig, resolveNextConfigInput } from "./config/next-config.js";
43
42
  import { mergeServerExternalPackages } from "./config/server-external-packages.js";
44
43
  import { precompressAssets } from "./build/precompress.js";
45
44
  import { ensureAssetsIgnore } from "./build/assets-ignore.js";
@@ -60,6 +59,7 @@ import { createInstrumentationClientTransformPlugin } from "./plugins/instrument
60
59
  import { createStyledJsxPlugin } from "./plugins/styled-jsx.js";
61
60
  import { INSTRUMENTATION_CLIENT_EMPTY_MODULE, generateInstrumentationClientInjectModule } from "./client/instrumentation-client-inject.js";
62
61
  import { createMiddlewareServerOnlyPlugin } from "./plugins/middleware-server-only.js";
62
+ import { stripJsExtension, stripViteModuleQuery } from "./utils/path.js";
63
63
  import { validateMiddlewareModuleExports } from "./plugins/middleware-export-validation.js";
64
64
  import { createOptimizeImportsPlugin } from "./plugins/optimize-imports.js";
65
65
  import { augmentSsrManifestFromBundle, relativeWithinRoot, tryRealpathSync } from "./build/ssr-manifest.js";
@@ -71,10 +71,12 @@ import { createServerExternalsManifestPlugin } from "./plugins/server-externals-
71
71
  import { VINEXT_CLIENT_ENTRY_MANIFEST } from "./utils/client-entry-manifest.js";
72
72
  import { computeClientRuntimeMetadata } from "./utils/client-runtime-metadata.js";
73
73
  import { PAGES_CLIENT_ASSETS_MODULE, buildPagesClientAssetsModule, setPagesClientAssetsBuildMetadata, takePagesClientAssetsBuildMetadata, writePagesClientAssetsModuleIfMissing } from "./build/pages-client-assets-module.js";
74
+ import { createPreviewBuildCredentials, getPreviewBuildCredentials } from "./build/preview-credentials.js";
75
+ import { createModuleDependencyCache } from "./build/module-dependency-cache.js";
74
76
  import { resolvePostcssStringPlugins } from "./plugins/postcss.js";
75
77
  import { markCssUrlAssetReferences, restoreDedupedCssAssetReferences } from "./build/css-url-assets.js";
76
78
  import { buildSassPreprocessorOptions, createSassAwareFileSystemLoader, createSassCssUrlAssetImporter, createSassTildeImporter } from "./plugins/sass.js";
77
- import { createClientAssetFileNames, createClientCodeSplittingConfig, createClientFileNameConfig, createClientManualChunks, createClientOutputConfig, createRscFrameworkChunkOutputConfig, getBuildBundlerOptions, getClientTreeshakeConfigForVite, withBuildBundlerOptions } from "./build/client-build-config.js";
79
+ import { createClientAssetFileNames, createClientCodeSplittingConfig, createClientFileNameConfig, createClientManualChunks, createRscFrameworkChunkOutputConfig, getBuildBundlerOptions, getClientTreeshakeConfig, withBuildBundlerOptions } from "./build/client-build-config.js";
78
80
  import { hasExportAllCandidate, stripServerExports, validatePageExports } from "./plugins/strip-server-exports.js";
79
81
  import { removeConsoleCalls } from "./plugins/remove-console.js";
80
82
  import { createImportMetaUrlPlugin } from "./plugins/import-meta-url.js";
@@ -85,14 +87,14 @@ import { getTypeofWindowReplacement, replaceTypeofWindow } from "./plugins/typeo
85
87
  import { hasMdxFiles } from "./utils/mdx-scan.js";
86
88
  import { scanPublicFileRoutes } from "./utils/public-routes.js";
87
89
  import { createIgnoreDynamicRequestsPlugin } from "./plugins/ignore-dynamic-requests.js";
88
- import { VINEXT_PRERENDER_CONFIG_PLUGIN_PROPERTY, normalizeVinextPrerenderConfig } from "./config/prerender.js";
90
+ import { assertSupportedViteVersion, getDepOptimizeNodeEnvOptions, serializeViteDefine } from "./utils/vite-version.js";
91
+ import { VINEXT_PRERENDER_CONFIG_PLUGIN_PROPERTY, VINEXT_ROUTE_ROOT_CONFIG_PLUGIN_PROPERTY, normalizeVinextPrerenderConfig } from "./config/prerender.js";
89
92
  import { staticExportApp, staticExportPages } from "./build/static-export.js";
90
93
  import { createRequire } from "node:module";
91
94
  import fs from "node:fs";
92
- import path from "node:path";
93
- import { loadEnv, parseAst, transformWithOxc } from "vite";
95
+ import { createLogger, loadEnv, parseAst, transformWithOxc } from "vite";
94
96
  import { pathToFileURL } from "node:url";
95
- import { createHash, randomBytes, randomUUID } from "node:crypto";
97
+ import { createHash, randomBytes } from "node:crypto";
96
98
  import commonjs from "vite-plugin-commonjs";
97
99
  import MagicString from "magic-string";
98
100
  //#region src/index.ts
@@ -109,10 +111,6 @@ const OPTIONAL_OPTIMIZE_DEPS_WARNING_RE = /Failed to resolve dependency: .*use-s
109
111
  const VINEXT_FILTERED_OPTIMIZE_DEPS_WARN = Symbol.for("vinext.filteredOptimizeDepsWarn");
110
112
  const ANSI_ESCAPE_RE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
111
113
  installSocketErrorBackstop();
112
- function getCacheDirPrefix(cacheDir) {
113
- const normalizedCacheDir = normalizePathSeparators(cacheDir);
114
- return normalizedCacheDir.endsWith("/") ? normalizedCacheDir : `${normalizedCacheDir}/`;
115
- }
116
114
  function isInsideDirectory(dir, filePath) {
117
115
  const relativePath = path.relative(dir, filePath);
118
116
  return relativePath !== "" && !relativePath.startsWith("..") && !path.isAbsolute(relativePath);
@@ -159,32 +157,28 @@ function resolveOptionalDependency(projectRoot, specifier) {
159
157
  } catch {}
160
158
  return null;
161
159
  }
162
- async function loadVite7TsconfigPathsPlugin(projectRoot) {
163
- const resolvedPath = resolveOptionalDependency(projectRoot, "vite-tsconfig-paths");
164
- 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.");
165
- return (await import(pathToFileURL(resolvedPath).href)).default();
166
- }
167
160
  function resolveShimModulePath(shimsDir, moduleName) {
168
161
  for (const ext of [
169
162
  ".ts",
170
163
  ".tsx",
171
164
  ".js"
172
165
  ]) {
173
- const candidate = path.posix.join(shimsDir, `${moduleName}${ext}`);
166
+ const candidate = path.join(shimsDir, `${moduleName}${ext}`);
174
167
  if (fs.existsSync(candidate)) return candidate;
175
168
  }
176
- return path.posix.join(shimsDir, `${moduleName}.js`);
169
+ return path.join(shimsDir, `${moduleName}.js`);
177
170
  }
178
171
  function isVercelOgImport(id) {
179
172
  return id === "@vercel/og" || id === "@vercel/og.js";
180
173
  }
181
174
  function isVinextOgShimImporter(importer) {
182
175
  if (!importer) return false;
183
- const normalizedImporter = (importer.startsWith("\0") ? importer.slice(1) : importer).split("?")[0].replace(/\\/g, "/");
176
+ const cleanImporter = (importer.startsWith("\0") ? importer.slice(1) : importer).split("?")[0];
177
+ const normalizedImporter = toSlash(cleanImporter);
184
178
  return normalizedImporter.endsWith("/shims/og.tsx") || normalizedImporter.endsWith("/shims/og.js") || normalizedImporter.endsWith("/dist/shims/og.js");
185
179
  }
186
180
  function toRelativeFileEntry(root, absPath) {
187
- return path.relative(root, absPath).split(path.sep).join("/");
181
+ return path.relative(root, absPath);
188
182
  }
189
183
  const DEV_PAGES_CLIENT_ENTRY = "/@id/__x00__virtual:vinext-client-entry";
190
184
  const STYLESHEET_IMPORT_RE = /\.(?:css|scss|sass)$/i;
@@ -248,7 +242,7 @@ function isScriptModuleId(id) {
248
242
  return SCRIPT_IMPORT_RE.test(stripViteModuleQuery(id).toLowerCase());
249
243
  }
250
244
  function skipCommonjsForLocalCjs(id) {
251
- const cleanId = normalizePathSeparators(stripViteModuleQuery(id));
245
+ const cleanId = toSlash(stripViteModuleQuery(id));
252
246
  return /\.c[jt]s$/i.test(cleanId) && !cleanId.includes("node_modules") ? false : void 0;
253
247
  }
254
248
  function hasOnlyTypeSpecifiers(statement) {
@@ -260,24 +254,37 @@ function resolvedStylesheetToDevManifestAsset(root, resolvedId) {
260
254
  const rootForRelative = tryRealpathSync(root) ?? root;
261
255
  const fileForRelative = tryRealpathSync(cleanId) ?? cleanId;
262
256
  const relativePath = path.relative(rootForRelative, fileForRelative);
263
- if (relativePath !== "" && !relativePath.startsWith("..") && !path.isAbsolute(relativePath)) return normalizePathSeparators(relativePath);
264
- return `@fs/${normalizePathSeparators(cleanId).replace(/^\/+/, "")}`;
257
+ if (relativePath !== "" && !relativePath.startsWith("..") && !path.isAbsolute(relativePath)) return relativePath;
258
+ return `@fs/${toSlash(cleanId).replace(/^\/+/, "")}`;
265
259
  }
266
- async function collectDevPagesAppStylesheetAssets(root, appFilePath, resolve) {
260
+ async function collectDevPagesAppStylesheetAssets(appFilePath, getModuleDependencies) {
267
261
  const stylesheetAssets = [];
268
262
  const seenAssets = /* @__PURE__ */ new Set();
269
263
  const seenModules = /* @__PURE__ */ new Set();
270
264
  async function visitModule(modulePath) {
265
+ if (seenModules.has(modulePath)) return;
266
+ seenModules.add(modulePath);
267
+ for (const dependency of await getModuleDependencies(modulePath)) if (dependency.type === "stylesheet") {
268
+ if (seenAssets.has(dependency.asset)) continue;
269
+ seenAssets.add(dependency.asset);
270
+ stylesheetAssets.push(dependency.asset);
271
+ } else await visitModule(dependency.id);
272
+ }
273
+ await visitModule(appFilePath);
274
+ return stylesheetAssets;
275
+ }
276
+ function createDevPagesModuleDependencyReader(root, resolve) {
277
+ return createModuleDependencyCache(collectModuleDependencies);
278
+ async function collectModuleDependencies(modulePath) {
271
279
  const cleanModulePath = stripViteModuleQuery(modulePath);
272
- if (!path.isAbsolute(cleanModulePath) || !fs.existsSync(cleanModulePath)) return;
273
- if (seenModules.has(cleanModulePath)) return;
274
- seenModules.add(cleanModulePath);
280
+ if (!path.isAbsolute(cleanModulePath) || !fs.existsSync(cleanModulePath)) return [];
275
281
  let ast;
276
282
  try {
277
283
  ast = parseAst(fs.readFileSync(cleanModulePath, "utf-8"), { lang: parserLanguageForScript(cleanModulePath) });
278
284
  } catch {
279
- return;
285
+ return [];
280
286
  }
287
+ const dependencies = [];
281
288
  for (const statement of ast.body) {
282
289
  if (statement.type !== "ImportDeclaration" && statement.type !== "ExportNamedDeclaration" && statement.type !== "ExportAllDeclaration") continue;
283
290
  if (statement.importKind === "type") continue;
@@ -290,17 +297,17 @@ async function collectDevPagesAppStylesheetAssets(root, appFilePath, resolve) {
290
297
  if (!resolved?.id) continue;
291
298
  if (isStylesheetSpecifier(specifier)) {
292
299
  const asset = resolvedStylesheetToDevManifestAsset(root, resolved.id);
293
- if (!asset || seenAssets.has(asset)) continue;
294
- seenAssets.add(asset);
295
- stylesheetAssets.push(asset);
296
- continue;
297
- }
298
- if (specifier.includes("?") || specifier.includes("#")) continue;
299
- if (isScriptModuleId(resolved.id)) await visitModule(resolved.id);
300
+ if (asset) dependencies.push({
301
+ type: "stylesheet",
302
+ asset
303
+ });
304
+ } else if (!specifier.includes("?") && !specifier.includes("#") && isScriptModuleId(resolved.id)) dependencies.push({
305
+ type: "script",
306
+ id: resolved.id
307
+ });
300
308
  }
309
+ return dependencies;
301
310
  }
302
- await visitModule(appFilePath);
303
- return stylesheetAssets;
304
311
  }
305
312
  const TSCONFIG_FILES = ["tsconfig.json", "jsconfig.json"];
306
313
  function resolveTsconfigPathCandidate(candidate) {
@@ -358,11 +365,11 @@ function materializeTsconfigPathAliases(pathsConfig, baseUrl, projectRoot) {
358
365
  return aliases;
359
366
  }
360
367
  function toViteAliasReplacement(absolutePath, projectRoot) {
361
- const normalizedPath = absolutePath.replace(/\\/g, "/");
362
- const rootCandidates = new Set([projectRoot]);
368
+ const normalizedPath = toSlash(absolutePath);
369
+ const rootCandidates = /* @__PURE__ */ new Set([projectRoot]);
363
370
  const realRoot = tryRealpathSync(projectRoot);
364
371
  if (realRoot) rootCandidates.add(realRoot);
365
- const pathCandidates = new Set([absolutePath]);
372
+ const pathCandidates = /* @__PURE__ */ new Set([absolutePath]);
366
373
  const realPath = tryRealpathSync(absolutePath);
367
374
  if (realPath) pathCandidates.add(realPath);
368
375
  for (const rootCandidate of rootCandidates) for (const pathCandidate of pathCandidates) {
@@ -383,7 +390,7 @@ function resolveSwcHelpersAlias(root) {
383
390
  resolvers.push(rootRequire, createRequire(import.meta.url));
384
391
  for (const resolver of resolvers) try {
385
392
  const packageJsonPath = resolver.resolve("@swc/helpers/package.json");
386
- return normalizePathSeparators(path.join(path.dirname(packageJsonPath), "_"));
393
+ return path.join(path.dirname(packageJsonPath), "_");
387
394
  } catch {}
388
395
  }
389
396
  function loadTsconfigPathAliases(configPath, projectRoot, seen = /* @__PURE__ */ new Set()) {
@@ -437,7 +444,7 @@ function getVinextVersion() {
437
444
  return _vinextVersionCache;
438
445
  }
439
446
  function mergeStringArrayValues(value, additions) {
440
- return [...new Set([...value === void 0 ? [] : Array.isArray(value) ? value : [value], ...additions])];
447
+ return [.../* @__PURE__ */ new Set([...value === void 0 ? [] : Array.isArray(value) ? value : [value], ...additions])];
441
448
  }
442
449
  function stripAnsi(value) {
443
450
  return value.replace(ANSI_ESCAPE_RE, "");
@@ -453,18 +460,98 @@ function suppressOptionalOptimizeDepsWarnings(logger) {
453
460
  marker[VINEXT_FILTERED_OPTIMIZE_DEPS_WARN] = true;
454
461
  }
455
462
  const _tsconfigAliasCache = /* @__PURE__ */ new Map();
463
+ /**
464
+ * Order materialized tsconfig path aliases by descending prefix length.
465
+ *
466
+ * TypeScript (and Next.js) match `paths` patterns by longest matched prefix,
467
+ * regardless of declaration order, while Vite's alias plugin picks the first
468
+ * matching entry. Overlapping patterns like `@/*` + `@/public/*` must
469
+ * therefore be materialized longest-first or the general pattern shadows the
470
+ * specific one (`@/public/foo.svg` would resolve into `src/public/`).
471
+ */
472
+ function sortTsconfigAliasesBySpecificity(aliases) {
473
+ return Object.fromEntries(Object.entries(aliases).sort((a, b) => b[0].length - a[0].length));
474
+ }
456
475
  function resolveTsconfigAliases(projectRoot) {
457
476
  if (_tsconfigAliasCache.has(projectRoot)) return _tsconfigAliasCache.get(projectRoot);
458
477
  let aliases = {};
459
478
  for (const name of TSCONFIG_FILES) {
460
479
  const candidate = path.join(projectRoot, name);
461
480
  if (!fs.existsSync(candidate)) continue;
462
- aliases = loadTsconfigPathAliases(candidate, projectRoot);
481
+ aliases = sortTsconfigAliasesBySpecificity(loadTsconfigPathAliases(candidate, projectRoot));
463
482
  break;
464
483
  }
465
484
  _tsconfigAliasCache.set(projectRoot, aliases);
466
485
  return aliases;
467
486
  }
487
+ /**
488
+ * Stylesheet importer contexts as seen by Vite's internal CSS resolvers.
489
+ *
490
+ * Vite resolves CSS `@import`/`composes`/`url()` specifiers through a
491
+ * dedicated resolver container that only runs the alias plugin plus Vite's
492
+ * own resolver — user plugins never participate. The importer is either the
493
+ * stylesheet's own path (sass, CSS modules `composes`, url() rewriting) or a
494
+ * synthetic `<basedir>/*` (postcss-import, less).
495
+ */
496
+ const STYLESHEET_IMPORTER_RE = /\.(?:css|scss|sass|less|styl|stylus|pcss|sss)$/i;
497
+ function isStylesheetImporter(importer) {
498
+ if (!importer) return false;
499
+ if (importer.endsWith("/*") || importer.endsWith("\\*")) return true;
500
+ return STYLESHEET_IMPORTER_RE.test(stripViteModuleQuery(importer));
501
+ }
502
+ /**
503
+ * Alias resolver for tsconfig-derived path aliases that keeps them out of
504
+ * stylesheet resolution.
505
+ *
506
+ * TypeScript `paths` never apply to CSS in Next.js — `@import` specifiers in
507
+ * stylesheets use standard bundler resolution, including package.json
508
+ * `exports` maps. A blind prefix-replacement alias breaks that: with
509
+ * `"@scope/ui/*": ["../../packages/ui/src/*"]` in tsconfig, an
510
+ * `@import "@scope/ui/globals.css"` whose real target is `exports`-mapped
511
+ * gets rewritten to a nonexistent source path and fails with ENOENT.
512
+ *
513
+ * Returning `null` for stylesheet importers makes the alias plugin fall
514
+ * through, so Vite's own resolver handles the original specifier. JS/TS
515
+ * importers keep the default alias behavior (Next.js applies `paths` there,
516
+ * including for `import "@/styles/globals.css"` from a layout), and Vite's
517
+ * glob/dynamic-import transforms — which require blind prefix replacement
518
+ * because their patterns never exist on disk — keep working.
519
+ */
520
+ const tsconfigAliasCustomResolver = async function(updatedId, importer, options) {
521
+ if (isStylesheetImporter(importer)) return null;
522
+ return await this.resolve(updatedId, importer, {
523
+ ...options,
524
+ skipSelf: true
525
+ }) ?? { id: updatedId };
526
+ };
527
+ /**
528
+ * Convert the merged alias map into Vite alias entries, attaching the
529
+ * stylesheet-scoping resolver to entries that came from tsconfig `paths`.
530
+ * Array order preserves the map's first-match ordering.
531
+ */
532
+ function buildResolveAliasEntries(aliasMap, tsconfigPathAliases) {
533
+ return Object.entries(aliasMap).map(([find, replacement]) => tsconfigPathAliases[find] === replacement ? {
534
+ find,
535
+ replacement,
536
+ customResolver: tsconfigAliasCustomResolver
537
+ } : {
538
+ find,
539
+ replacement
540
+ });
541
+ }
542
+ const ALIAS_CUSTOM_RESOLVER_DEPRECATION_RE = /`resolve\.alias` contains an alias with `customResolver` option/;
543
+ const VINEXT_FILTERED_ALIAS_DEPRECATION_WARN = Symbol.for("vinext.filteredAliasDeprecationWarn");
544
+ function suppressAliasCustomResolverDeprecationWarning(logger) {
545
+ const marker = logger;
546
+ if (marker[VINEXT_FILTERED_ALIAS_DEPRECATION_WARN]) return logger;
547
+ const warn = logger.warn.bind(logger);
548
+ logger.warn = (msg, warnOptions) => {
549
+ if (ALIAS_CUSTOM_RESOLVER_DEPRECATION_RE.test(stripAnsi(msg))) return;
550
+ warn(msg, warnOptions);
551
+ };
552
+ marker[VINEXT_FILTERED_ALIAS_DEPRECATION_WARN] = true;
553
+ return logger;
554
+ }
468
555
  const VIRTUAL_WORKER_ENTRY = "virtual:vinext-worker-entry";
469
556
  const RESOLVED_WORKER_ENTRY = "\0virtual:vinext-worker-entry";
470
557
  const VIRTUAL_SERVER_ENTRY = "virtual:vinext-server-entry";
@@ -504,14 +591,14 @@ function createStaticImageAsset(imagePath) {
504
591
  };
505
592
  }
506
593
  /**
507
- * Absolute path to vinext's shims directory, with a trailing slash. Normalized
508
- * to forward slashes because it is prefix-matched against Vite module ids (which
509
- * Vite always normalizes to forward slashes) in the font plugins and
510
- * clientManualChunks a raw path.resolve value has backslashes on Windows and
511
- * the `id.startsWith(_shimsDir)` checks would never match.
594
+ * Absolute path to vinext's shims directory, with a trailing slash. Forward
595
+ * slashes are guaranteed by pathslash's `path.resolve`, matching the Vite
596
+ * module ids (always forward-slash) that the `id.startsWith(_shimsDir)`
597
+ * prefix checks in the font plugins and clientManualChunks compare against.
598
+ * The trailing "/" keeps those prefix checks directory-exact.
512
599
  */
513
- const _shimsDir = normalizePathSeparators(path.resolve(__dirname, "shims")) + "/";
514
- const _serverDir = normalizePathSeparators(path.resolve(__dirname, "server"));
600
+ const _shimsDir = path.resolve(__dirname, "shims") + "/";
601
+ const _serverDir = path.resolve(__dirname, "server");
515
602
  const _fontGoogleShimPath = resolveShimModulePath(_shimsDir, "font-google");
516
603
  const _appBrowserServerActionClientPath = resolveShimModulePath(_serverDir, "app-browser-server-action-client");
517
604
  const _appRscHandlerPath = resolveShimModulePath(_serverDir, "app-rsc-handler");
@@ -522,8 +609,8 @@ function isValidExportIdentifier(name) {
522
609
  }
523
610
  function isVirtualEntryFacade(id, virtualId) {
524
611
  if (!id) return false;
525
- const cleanId = id.startsWith("\0") ? id.slice(1) : id;
526
- return cleanId === virtualId || cleanId.endsWith("/" + virtualId) || cleanId.endsWith("\\" + virtualId);
612
+ const cleanId = toSlash(id.startsWith("\0") ? id.slice(1) : id);
613
+ return cleanId === virtualId || cleanId.endsWith("/" + virtualId);
527
614
  }
528
615
  /**
529
616
  * Returns the leading React `"use client"` or `"use server"` directive after
@@ -594,29 +681,26 @@ function generateRootParamsModule(rootParamNames) {
594
681
  * 1. Create `<name>.react-server.ts` in src/shims/
595
682
  * 2. Add entries here for each import specifier.
596
683
  */
597
- const _reactServerShims = new Map([
684
+ const _reactServerShims = /* @__PURE__ */ new Map([
598
685
  ["next/navigation", "navigation"],
599
686
  ["next/navigation.js", "navigation"],
600
687
  ["next/dist/client/components/navigation", "navigation"],
601
688
  ["next/error", "error"],
602
689
  ["next/error.js", "error"]
603
690
  ]);
604
- const clientManualChunks = createClientManualChunks(_shimsDir);
605
- const clientCodeSplittingConfig = createClientCodeSplittingConfig(clientManualChunks);
606
- const appClientManualChunks = createClientManualChunks(_shimsDir, true);
607
- const appClientCodeSplittingConfig = createClientCodeSplittingConfig(appClientManualChunks);
608
- function getClientOutputConfigForVite(viteMajorVersion, assetsDir, preserveAppRouteBoundaries = false) {
609
- const manualChunks = preserveAppRouteBoundaries ? appClientManualChunks : clientManualChunks;
691
+ const clientCodeSplittingConfig = createClientCodeSplittingConfig(createClientManualChunks(_shimsDir));
692
+ const appClientCodeSplittingConfig = createClientCodeSplittingConfig(createClientManualChunks(_shimsDir, true));
693
+ function getClientOutputConfig(assetsDir, preserveAppRouteBoundaries = false) {
610
694
  const codeSplitting = preserveAppRouteBoundaries ? appClientCodeSplittingConfig : clientCodeSplittingConfig;
611
- return viteMajorVersion >= 8 ? {
695
+ return {
612
696
  ...createClientFileNameConfig(assetsDir),
613
697
  assetFileNames: createClientAssetFileNames(assetsDir),
614
698
  codeSplitting
615
- } : createClientOutputConfig(manualChunks, assetsDir);
699
+ };
616
700
  }
617
701
  function vinext(options = {}) {
702
+ const { supportsNativeTypeofWindowFolding: useNativeTypeofWindowFolding } = assertSupportedViteVersion();
618
703
  const prerenderConfig = normalizeVinextPrerenderConfig(options.prerender);
619
- const viteMajorVersion = getViteMajorVersion();
620
704
  let root;
621
705
  let pagesDir;
622
706
  let canonicalPagesDir;
@@ -634,17 +718,18 @@ function vinext(options = {}) {
634
718
  let hasCloudflarePlugin = false;
635
719
  let warnedInlineNextConfigOverride = false;
636
720
  let hasNitroPlugin = false;
721
+ let nitroTraceDepsFromServerExternals = [];
637
722
  let isServeCommand = false;
638
723
  let pagesOptimizeEntries = [];
639
724
  const pagesClientAssetsOutputDirs = /* @__PURE__ */ new Set();
640
725
  let pagesClientAssetsModule = null;
641
726
  let rscCompatibilityId;
642
- const draftModeSecret = randomUUID();
727
+ let draftModeSecret = getPagesPreviewModeId();
728
+ let previewBuildCredentials;
643
729
  const sassComposesLoader = createSassAwareFileSystemLoader();
644
- const typeofWindowIdFilter = { exclude: /(?!)/ };
645
730
  let rscClassificationManifest = null;
646
- const shimsDir = normalizePathSeparators(path.resolve(__dirname, "shims"));
647
- const canonicalize = (p) => normalizePathSeparators(tryRealpathSync(p) ?? p);
731
+ const shimsDir = path.resolve(__dirname, "shims");
732
+ const canonicalize = (p) => toSlash(tryRealpathSync(p) ?? p);
648
733
  const pageTransformCanonicalPaths = /* @__PURE__ */ new Map();
649
734
  const canonicalizePageTransformPath = (modulePath) => {
650
735
  const cached = pageTransformCanonicalPaths.get(modulePath);
@@ -729,11 +814,32 @@ function vinext(options = {}) {
729
814
  if (!pluginApi || pluginApi.manager.isScanBuild) return true;
730
815
  return Object.keys(pluginApi.manager.serverReferenceMetaMap).length > 0;
731
816
  }
732
- const reactOptions = options.react && options.react !== true ? options.react : void 0;
817
+ const configuredReactOptions = options.react && options.react !== true ? options.react : void 0;
818
+ const reactOptions = configuredReactOptions;
733
819
  let reactPluginPromise = null;
734
820
  if (options.react !== false) {
735
821
  if (!resolvedReactPath) throw new Error("vinext: @vitejs/plugin-react is not installed.\nRun: " + detectPackageManager(process.cwd()) + " @vitejs/plugin-react");
736
- reactPluginPromise = import(pathToFileURL(resolvedReactPath).href).then((mod) => mod.default(reactOptions)).catch((cause) => {
822
+ reactPluginPromise = import(pathToFileURL(resolvedReactPath).href).then((mod) => {
823
+ const react = mod.default;
824
+ const limitToCommand = (plugin, command) => {
825
+ const originalApply = plugin.apply;
826
+ return {
827
+ ...plugin,
828
+ apply(config, env) {
829
+ if (env.command !== command) return false;
830
+ if (!originalApply) return true;
831
+ if (typeof originalApply === "function") return originalApply(config, env);
832
+ return originalApply === env.command;
833
+ }
834
+ };
835
+ };
836
+ const buildPlugins = react(reactOptions).map((plugin) => limitToCommand(plugin, "build"));
837
+ const servePlugins = react(configuredReactOptions !== void 0 && Object.prototype.hasOwnProperty.call(configuredReactOptions, "include") ? reactOptions : {
838
+ ...reactOptions,
839
+ include: /\.(?:[tj]sx?|mdx)$/i
840
+ }).map((plugin) => limitToCommand(plugin, "serve"));
841
+ return [...buildPlugins, ...servePlugins];
842
+ }).catch((cause) => {
737
843
  throw new Error("vinext: Failed to load @vitejs/plugin-react.", { cause });
738
844
  });
739
845
  }
@@ -773,9 +879,36 @@ function vinext(options = {}) {
773
879
  })();
774
880
  return mdxDelegatePromise;
775
881
  }
882
+ const mdxProxyPlugin = {
883
+ name: "vinext:mdx",
884
+ enforce: "pre",
885
+ transform: {
886
+ filter: { id: {
887
+ include: /\.mdx$/i,
888
+ exclude: /\?/
889
+ } },
890
+ async handler(code, id, options) {
891
+ const delegate = mdxDelegate ?? await ensureMdxDelegate("on-demand");
892
+ if (delegate?.transform) {
893
+ const hook = delegate.transform;
894
+ return (typeof hook === "function" ? hook : hook.handler).call(this, code, id, options);
895
+ }
896
+ 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.`);
897
+ }
898
+ }
899
+ };
900
+ const mdxConfigProxyPlugin = {
901
+ name: "vinext:mdx-config",
902
+ enforce: "pre",
903
+ config(config, env) {
904
+ if (!mdxDelegate?.config) return;
905
+ const hook = mdxDelegate.config;
906
+ return (typeof hook === "function" ? hook : hook.handler).call(this, config, env);
907
+ }
908
+ };
776
909
  const plugins = [
777
- ...viteMajorVersion >= 8 ? [] : [loadVite7TsconfigPathsPlugin(earlyBaseDir)],
778
910
  createStyledJsxPlugin(earlyBaseDir),
911
+ mdxProxyPlugin,
779
912
  reactPluginPromise,
780
913
  createIgnoreDynamicRequestsPlugin(() => nextConfig?.turbopackTranspilePackages ?? []),
781
914
  commonjs({ filter: skipCommonjsForLocalCjs }),
@@ -789,13 +922,13 @@ function vinext(options = {}) {
789
922
  code: /\.(?:css|scss|sass)['"]/
790
923
  },
791
924
  handler(code, id) {
792
- const cleanId = normalizePathSeparators(stripViteModuleQuery(id));
925
+ const cleanId = toSlash(stripViteModuleQuery(id));
793
926
  if (!globalNotFoundCssIsolationPath || canonicalize(cleanId) !== canonicalize(globalNotFoundCssIsolationPath)) return null;
794
927
  return isolateGlobalNotFoundStylesheetImports(code, cleanId);
795
928
  }
796
929
  }
797
930
  },
798
- ...viteMajorVersion >= 8 ? [{
931
+ {
799
932
  name: "vinext:jsx-in-js",
800
933
  enforce: "pre",
801
934
  transform: {
@@ -818,7 +951,7 @@ function vinext(options = {}) {
818
951
  };
819
952
  }
820
953
  }
821
- }] : [],
954
+ },
822
955
  createMiddlewareServerOnlyPlugin({
823
956
  getMiddlewarePath: () => middlewarePath,
824
957
  getCanonicalMiddlewarePath: () => middlewarePath ? tryRealpathSync(middlewarePath) ?? middlewarePath : null,
@@ -834,13 +967,21 @@ function vinext(options = {}) {
834
967
  name: "vinext:config",
835
968
  enforce: "pre",
836
969
  [VINEXT_PRERENDER_CONFIG_PLUGIN_PROPERTY]: prerenderConfig,
970
+ [VINEXT_NEXT_CONFIG_PLUGIN_PROPERTY]: options.nextConfig ?? null,
971
+ [VINEXT_ROUTE_ROOT_CONFIG_PLUGIN_PROPERTY]: {
972
+ appDir: options.appDir,
973
+ disableAppRouter: options.disableAppRouter,
974
+ rscOutDir: options.rscOutDir,
975
+ ssrOutDir: options.ssrOutDir
976
+ },
977
+ [VINEXT_CACHE_CONFIG_PLUGIN_PROPERTY]: options.cache ?? null,
837
978
  async config(config, env) {
838
979
  isServeCommand = env.command === "serve";
839
- root = normalizePathSeparators(config.root ?? process.cwd());
840
- const userResolve = config.resolve;
841
- const shouldEnableNativeTsconfigPaths = viteMajorVersion >= 8 && userResolve?.tsconfigPaths === void 0;
980
+ root = toSlash(config.root ?? process.cwd());
981
+ const shouldEnableNativeTsconfigPaths = config.resolve?.tsconfigPaths === void 0;
842
982
  const tsconfigPathAliases = resolveTsconfigAliases(root);
843
983
  const swcHelpersAlias = resolveSwcHelpersAlias(root);
984
+ if (Object.keys(tsconfigPathAliases).length > 0) config.customLogger = suppressAliasCustomResolverDeprecationWarning(config.customLogger ?? createLogger(config.logLevel, { allowClearScreen: config.clearScreen }));
844
985
  const mode = env?.mode ?? "development";
845
986
  const dotenvVars = loadEnv(mode, config.envDir ?? root, "");
846
987
  for (const [key, value] of Object.entries(dotenvVars)) if (process.env[key] === void 0) process.env[key] = value;
@@ -849,20 +990,22 @@ function vinext(options = {}) {
849
990
  else if (env?.command === "build" || env?.isPreview === true) resolvedNodeEnv = "production";
850
991
  else resolvedNodeEnv = "development";
851
992
  if (process.env.NODE_ENV !== resolvedNodeEnv) process.env.NODE_ENV = resolvedNodeEnv;
993
+ if (env?.command === "build") previewBuildCredentials = getPreviewBuildCredentials() ?? createPreviewBuildCredentials();
994
+ draftModeSecret = previewBuildCredentials?.id ?? getPagesPreviewModeId();
852
995
  let baseDir;
853
- if (options.appDir) baseDir = normalizePathSeparators(path.isAbsolute(options.appDir) ? options.appDir : path.resolve(root, options.appDir));
996
+ if (options.appDir) baseDir = toSlash(path.isAbsolute(options.appDir) ? options.appDir : path.resolve(root, options.appDir));
854
997
  else {
855
- const hasRootApp = fs.existsSync(path.posix.join(root, "app"));
856
- const hasRootPages = fs.existsSync(path.posix.join(root, "pages"));
857
- const hasSrcApp = fs.existsSync(path.posix.join(root, "src", "app"));
858
- const hasSrcPages = fs.existsSync(path.posix.join(root, "src", "pages"));
998
+ const hasRootApp = fs.existsSync(path.join(root, "app"));
999
+ const hasRootPages = fs.existsSync(path.join(root, "pages"));
1000
+ const hasSrcApp = fs.existsSync(path.join(root, "src", "app"));
1001
+ const hasSrcPages = fs.existsSync(path.join(root, "src", "pages"));
859
1002
  if (hasRootApp || hasRootPages) baseDir = root;
860
- else if (hasSrcApp || hasSrcPages) baseDir = path.posix.join(root, "src");
1003
+ else if (hasSrcApp || hasSrcPages) baseDir = path.join(root, "src");
861
1004
  else baseDir = root;
862
1005
  }
863
- pagesDir = path.posix.join(baseDir, "pages");
1006
+ pagesDir = path.join(baseDir, "pages");
864
1007
  canonicalPagesDir = canonicalize(pagesDir);
865
- appDir = path.posix.join(baseDir, "app");
1008
+ appDir = path.join(baseDir, "app");
866
1009
  hasPagesDir = fs.existsSync(pagesDir);
867
1010
  hasAppDir = !options.disableAppRouter && fs.existsSync(appDir);
868
1011
  if (!nextConfig) {
@@ -891,7 +1034,7 @@ function vinext(options = {}) {
891
1034
  globalNotFoundCssIsolationPath = env?.command === "build" && nextConfig.globalNotFound ? findFileWithExts(appDir, "global-not-found", fileMatcher) : null;
892
1035
  instrumentationPath = findInstrumentationFile(root, fileMatcher);
893
1036
  instrumentationClientPath = findInstrumentationClientFile(root, fileMatcher);
894
- const middlewareConventionDir = canonicalize(baseDir) === canonicalize(path.posix.join(root, "src")) ? path.posix.join(root, "src") : root;
1037
+ const middlewareConventionDir = canonicalize(baseDir) === canonicalize(path.join(root, "src")) ? path.join(root, "src") : root;
895
1038
  middlewarePath = findMiddlewareFile(root, fileMatcher, middlewareConventionDir);
896
1039
  const instrumentationClientInjects = nextConfig.instrumentationClientInject.map((spec) => spec.startsWith("./") || spec.startsWith("../") ? path.resolve(root, spec) : spec);
897
1040
  clientInjectModule = instrumentationClientInjects.length ? generateInstrumentationClientInjectModule(instrumentationClientInjects, instrumentationClientPath, INSTRUMENTATION_CLIENT_EMPTY_MODULE) : null;
@@ -958,55 +1101,55 @@ function vinext(options = {}) {
958
1101
  }
959
1102
  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.`);
960
1103
  nextShimMap = Object.fromEntries(Object.entries({
961
- "next/link": path.posix.join(shimsDir, "link"),
962
- "next/head": path.posix.join(shimsDir, "head"),
963
- "next/router": path.posix.join(shimsDir, "router"),
964
- "next/compat/router": path.posix.join(shimsDir, "compat-router"),
965
- "next/image": path.posix.join(shimsDir, "image"),
966
- "next/legacy/image": path.posix.join(shimsDir, "legacy-image"),
967
- "next/dynamic": path.posix.join(shimsDir, "dynamic"),
968
- "next/app": path.posix.join(shimsDir, "app"),
969
- "next/document": path.posix.join(shimsDir, "document"),
970
- "next/config": path.posix.join(shimsDir, "config"),
971
- "next/script": path.posix.join(shimsDir, "script"),
972
- "next/server": path.posix.join(shimsDir, "server"),
973
- "next/headers": path.posix.join(shimsDir, "headers"),
974
- "next/font/google": path.posix.join(shimsDir, "font-google"),
975
- "next/font/local": path.posix.join(shimsDir, "font-local"),
976
- "next/cache": path.posix.join(shimsDir, "cache"),
977
- "next/form": path.posix.join(shimsDir, "form"),
978
- "next/og": path.posix.join(shimsDir, "og"),
979
- "next/web-vitals": path.posix.join(shimsDir, "web-vitals"),
980
- "next/amp": path.posix.join(shimsDir, "amp"),
981
- "next/offline": path.posix.join(shimsDir, "offline"),
982
- "next/constants": path.posix.join(shimsDir, "constants"),
983
- "next/dist/shared/lib/app-router-context.shared-runtime": path.posix.join(shimsDir, "internal", "app-router-context"),
984
- "next/dist/shared/lib/app-router-context": path.posix.join(shimsDir, "internal", "app-router-context"),
985
- "next/dist/shared/lib/router-context.shared-runtime": path.posix.join(shimsDir, "internal", "router-context"),
986
- "next/dist/shared/lib/utils": path.posix.join(shimsDir, "internal", "utils"),
987
- "next/dist/server/api-utils": path.posix.join(shimsDir, "internal", "api-utils"),
988
- "next/dist/server/web/spec-extension/cookies": path.posix.join(shimsDir, "internal", "cookies"),
989
- "next/dist/compiled/@edge-runtime/cookies": path.posix.join(shimsDir, "internal", "cookies"),
990
- "next/dist/server/app-render/work-unit-async-storage.external": path.posix.join(shimsDir, "internal", "work-unit-async-storage"),
991
- "next/dist/client/components/work-unit-async-storage.external": path.posix.join(shimsDir, "internal", "work-unit-async-storage"),
992
- "next/dist/client/components/request-async-storage.external": path.posix.join(shimsDir, "internal", "work-unit-async-storage"),
993
- "next/dist/client/components/request-async-storage": path.posix.join(shimsDir, "internal", "work-unit-async-storage"),
994
- "next/dist/server/request/root-params": path.posix.join(shimsDir, "root-params"),
995
- "next/dist/server/config-shared": path.posix.join(shimsDir, "internal", "utils"),
996
- "server-only": path.posix.join(shimsDir, "server-only"),
997
- "client-only": path.posix.join(shimsDir, "client-only"),
998
- "vinext/error-boundary": path.posix.join(shimsDir, "error-boundary"),
999
- "vinext/layout-segment-context": path.posix.join(shimsDir, "layout-segment-context"),
1000
- "vinext/metadata": path.posix.join(shimsDir, "metadata"),
1001
- "vinext/fetch-cache": path.posix.join(shimsDir, "fetch-cache"),
1002
- "vinext/cache-runtime": path.posix.join(shimsDir, "cache-runtime"),
1003
- "vinext/navigation-state": path.posix.join(shimsDir, "navigation-state"),
1004
- "vinext/unified-request-context": path.posix.join(shimsDir, "unified-request-context"),
1005
- "vinext/pages-router-runtime": path.posix.join(shimsDir, "pages-router-runtime"),
1006
- "vinext/router-state": path.posix.join(shimsDir, "router-state"),
1007
- "vinext/head-state": path.posix.join(shimsDir, "head-state"),
1008
- "vinext/i18n-state": path.posix.join(shimsDir, "i18n-state"),
1009
- "vinext/i18n-context": path.posix.join(shimsDir, "i18n-context"),
1104
+ "next/link": path.join(shimsDir, "link"),
1105
+ "next/head": path.join(shimsDir, "head"),
1106
+ "next/router": path.join(shimsDir, "router"),
1107
+ "next/compat/router": path.join(shimsDir, "compat-router"),
1108
+ "next/image": path.join(shimsDir, "image"),
1109
+ "next/legacy/image": path.join(shimsDir, "legacy-image"),
1110
+ "next/dynamic": path.join(shimsDir, "dynamic"),
1111
+ "next/app": path.join(shimsDir, "app"),
1112
+ "next/document": path.join(shimsDir, "document"),
1113
+ "next/config": path.join(shimsDir, "config"),
1114
+ "next/script": path.join(shimsDir, "script"),
1115
+ "next/server": path.join(shimsDir, "server"),
1116
+ "next/headers": path.join(shimsDir, "headers"),
1117
+ "next/font/google": path.join(shimsDir, "font-google"),
1118
+ "next/font/local": path.join(shimsDir, "font-local"),
1119
+ "next/cache": path.join(shimsDir, "cache"),
1120
+ "next/form": path.join(shimsDir, "form"),
1121
+ "next/og": path.join(shimsDir, "og"),
1122
+ "next/web-vitals": path.join(shimsDir, "web-vitals"),
1123
+ "next/amp": path.join(shimsDir, "amp"),
1124
+ "next/offline": path.join(shimsDir, "offline"),
1125
+ "next/constants": path.join(shimsDir, "constants"),
1126
+ "next/dist/shared/lib/app-router-context.shared-runtime": path.join(shimsDir, "internal", "app-router-context"),
1127
+ "next/dist/shared/lib/app-router-context": path.join(shimsDir, "internal", "app-router-context"),
1128
+ "next/dist/shared/lib/router-context.shared-runtime": path.join(shimsDir, "internal", "router-context"),
1129
+ "next/dist/shared/lib/utils": path.join(shimsDir, "internal", "utils"),
1130
+ "next/dist/server/api-utils": path.join(shimsDir, "internal", "api-utils"),
1131
+ "next/dist/server/web/spec-extension/cookies": path.join(shimsDir, "internal", "cookies"),
1132
+ "next/dist/compiled/@edge-runtime/cookies": path.join(shimsDir, "internal", "cookies"),
1133
+ "next/dist/server/app-render/work-unit-async-storage.external": path.join(shimsDir, "internal", "work-unit-async-storage"),
1134
+ "next/dist/client/components/work-unit-async-storage.external": path.join(shimsDir, "internal", "work-unit-async-storage"),
1135
+ "next/dist/client/components/request-async-storage.external": path.join(shimsDir, "internal", "work-unit-async-storage"),
1136
+ "next/dist/client/components/request-async-storage": path.join(shimsDir, "internal", "work-unit-async-storage"),
1137
+ "next/dist/server/request/root-params": path.join(shimsDir, "root-params"),
1138
+ "next/dist/server/config-shared": path.join(shimsDir, "internal", "utils"),
1139
+ "server-only": path.join(shimsDir, "server-only"),
1140
+ "client-only": path.join(shimsDir, "client-only"),
1141
+ "vinext/error-boundary": path.join(shimsDir, "error-boundary"),
1142
+ "vinext/layout-segment-context": path.join(shimsDir, "layout-segment-context"),
1143
+ "vinext/metadata": path.join(shimsDir, "metadata"),
1144
+ "vinext/fetch-cache": path.join(shimsDir, "fetch-cache"),
1145
+ "vinext/cache-runtime": path.join(shimsDir, "cache-runtime"),
1146
+ "vinext/navigation-state": path.join(shimsDir, "navigation-state"),
1147
+ "vinext/unified-request-context": path.join(shimsDir, "unified-request-context"),
1148
+ "vinext/pages-router-runtime": path.join(shimsDir, "pages-router-runtime"),
1149
+ "vinext/router-state": path.join(shimsDir, "router-state"),
1150
+ "vinext/head-state": path.join(shimsDir, "head-state"),
1151
+ "vinext/i18n-state": path.join(shimsDir, "i18n-state"),
1152
+ "vinext/i18n-context": path.join(shimsDir, "i18n-context"),
1010
1153
  "vinext/cache": path.resolve(__dirname, "cache"),
1011
1154
  "vinext/instrumentation": path.resolve(__dirname, "server", "instrumentation"),
1012
1155
  "vinext/instrumentation-client": path.resolve(__dirname, "client", "instrumentation-client"),
@@ -1030,6 +1173,7 @@ function vinext(options = {}) {
1030
1173
  const isSSR = !!config.build?.ssr;
1031
1174
  const serverTranspilePackages = [...nextConfig?.turbopackTranspilePackages ?? [], ...nextConfig?.optimizePackageImports ?? []];
1032
1175
  const nextServerExternal = mergeServerExternalPackages(nextConfig?.serverExternalPackages, serverTranspilePackages);
1176
+ nitroTraceDepsFromServerExternals = nextServerExternal;
1033
1177
  const isMultiEnv = hasAppDir || hasCloudflarePlugin || hasNitroPlugin;
1034
1178
  const hasBuildInput = getBuildBundlerOptions(config.build)?.input !== void 0;
1035
1179
  const shouldInjectPlainPagesEnvironments = !hasAppDir && !hasCloudflarePlugin && !isSSR && !hasBuildInput;
@@ -1053,7 +1197,7 @@ function vinext(options = {}) {
1053
1197
  ],
1054
1198
  assetsDir: clientAssetsDir,
1055
1199
  ...!isSSR && !hasClientBuildEnvironment ? { assetsInlineLimit: clientAssetsInlineLimit } : {},
1056
- ...withBuildBundlerOptions(viteMajorVersion, {
1200
+ ...withBuildBundlerOptions({
1057
1201
  onwarn: (() => {
1058
1202
  const userOnwarn = getBuildBundlerOptions(config.build)?.onwarn;
1059
1203
  return (warning, defaultHandler) => {
@@ -1064,8 +1208,8 @@ function vinext(options = {}) {
1064
1208
  else defaultHandler(warning);
1065
1209
  };
1066
1210
  })(),
1067
- ...!isSSR && !isMultiEnv ? { treeshake: getClientTreeshakeConfigForVite(viteMajorVersion) } : {},
1068
- ...!isSSR && !isMultiEnv ? { output: getClientOutputConfigForVite(viteMajorVersion, clientAssetsDir) } : {}
1211
+ ...!isSSR && !isMultiEnv ? { treeshake: getClientTreeshakeConfig() } : {},
1212
+ ...!isSSR && !isMultiEnv ? { output: getClientOutputConfig(clientAssetsDir) } : {}
1069
1213
  })
1070
1214
  },
1071
1215
  server: {
@@ -1087,13 +1231,13 @@ function vinext(options = {}) {
1087
1231
  noExternal: true
1088
1232
  } },
1089
1233
  resolve: {
1090
- alias: {
1234
+ alias: buildResolveAliasEntries({
1091
1235
  ...swcHelpersAlias ? { "@swc/helpers/_": swcHelpersAlias } : {},
1092
1236
  ...tsconfigPathAliases,
1093
1237
  ...nextConfig.aliases,
1094
1238
  ...nextShimMap,
1095
1239
  "vinext/server/pages-client-assets": _pagesClientAssetsPath
1096
- },
1240
+ }, tsconfigPathAliases),
1097
1241
  dedupe: [
1098
1242
  "react",
1099
1243
  "react-dom",
@@ -1102,13 +1246,10 @@ function vinext(options = {}) {
1102
1246
  ],
1103
1247
  ...shouldEnableNativeTsconfigPaths ? { tsconfigPaths: true } : {}
1104
1248
  },
1105
- ...viteMajorVersion >= 8 ? { oxc: {
1249
+ oxc: {
1106
1250
  jsx: { runtime: "automatic" },
1107
1251
  typescript: { onlyRemoveTypeImports: false }
1108
- } } : { esbuild: {
1109
- jsx: "automatic",
1110
- tsconfigRaw: { compilerOptions: { verbatimModuleSyntax: false } }
1111
- } },
1252
+ },
1112
1253
  define: defines,
1113
1254
  ...nextConfig.basePath ? { base: nextConfig.basePath + "/" } : {},
1114
1255
  ...nextConfig.assetPrefix || nextConfig.deploymentId ? { experimental: { renderBuiltUrl: (filename, context) => renderVinextBuiltUrl(filename, nextConfig.assetPrefix, nextConfig.deploymentId, context.hostType) } } : {},
@@ -1156,7 +1297,7 @@ function vinext(options = {}) {
1156
1297
  if (shimBase !== void 0) return resolveShimModulePath(shimsDir, shimBase);
1157
1298
  }
1158
1299
  };
1159
- const depOptimizeNodeEnvOptions = getDepOptimizeNodeEnvOptions(viteMajorVersion, nodeEnvDefine);
1300
+ const depOptimizeNodeEnvOptions = getDepOptimizeNodeEnvOptions(nodeEnvDefine);
1160
1301
  viteConfig.optimizeDeps = {
1161
1302
  exclude: mergeOptimizeDepsExclude(incomingExclude, VINEXT_OPTIMIZE_DEPS_EXCLUDE, ["@tailwindcss/oxide"]),
1162
1303
  ...incomingInclude.length > 0 ? { include: incomingInclude } : {},
@@ -1170,7 +1311,7 @@ function vinext(options = {}) {
1170
1311
  if (hasAppDir) {
1171
1312
  const appEntries = [`${path.relative(root, appDir)}/**/*.{tsx,ts,jsx,js}`];
1172
1313
  const explicitInstrumentationEntries = [instrumentationPath, instrumentationClientPath].flatMap((entry) => entry ? [toRelativeFileEntry(root, entry)] : []);
1173
- const optimizeEntries = [...new Set([...appEntries, ...explicitInstrumentationEntries])];
1314
+ const optimizeEntries = [.../* @__PURE__ */ new Set([...appEntries, ...explicitInstrumentationEntries])];
1174
1315
  const appClientInput = { index: VIRTUAL_APP_BROWSER_ENTRY };
1175
1316
  if (hasPagesDir) appClientInput["vinext-client-entry"] = VIRTUAL_CLIENT_ENTRY;
1176
1317
  viteConfig.environments = {
@@ -1188,14 +1329,14 @@ function vinext(options = {}) {
1188
1329
  optimizeDeps: {
1189
1330
  exclude: mergeOptimizeDepsExclude(incomingExclude, VINEXT_OPTIMIZE_DEPS_EXCLUDE),
1190
1331
  entries: optimizeEntries,
1191
- include: [...new Set([...incomingInclude, "react-server-dom-webpack/static.edge"])],
1332
+ include: [.../* @__PURE__ */ new Set([...incomingInclude, "react-server-dom-webpack/static.edge"])],
1192
1333
  ...depOptimizeNodeEnvOptions
1193
1334
  },
1194
1335
  build: {
1195
1336
  outDir: options.rscOutDir ?? "dist/server",
1196
- ...withBuildBundlerOptions(viteMajorVersion, {
1337
+ ...withBuildBundlerOptions({
1197
1338
  input: { index: VIRTUAL_RSC_ENTRY },
1198
- output: createRscFrameworkChunkOutputConfig(viteMajorVersion)
1339
+ output: createRscFrameworkChunkOutputConfig()
1199
1340
  })
1200
1341
  }
1201
1342
  },
@@ -1215,7 +1356,7 @@ function vinext(options = {}) {
1215
1356
  },
1216
1357
  build: {
1217
1358
  outDir: options.ssrOutDir ?? "dist/server/ssr",
1218
- ...withBuildBundlerOptions(viteMajorVersion, { input: { index: VIRTUAL_APP_SSR_ENTRY } })
1359
+ ...withBuildBundlerOptions({ input: { index: VIRTUAL_APP_SSR_ENTRY } })
1219
1360
  }
1220
1361
  },
1221
1362
  client: {
@@ -1223,7 +1364,7 @@ function vinext(options = {}) {
1223
1364
  optimizeDeps: {
1224
1365
  exclude: mergeOptimizeDepsExclude(incomingExclude, VINEXT_OPTIMIZE_DEPS_EXCLUDE, nextServerExternal),
1225
1366
  entries: optimizeEntries,
1226
- include: [...new Set([
1367
+ include: [.../* @__PURE__ */ new Set([
1227
1368
  ...incomingInclude,
1228
1369
  "react",
1229
1370
  "react-dom",
@@ -1237,10 +1378,10 @@ function vinext(options = {}) {
1237
1378
  manifest: true,
1238
1379
  ...hasPagesDir ? { ssrManifest: true } : {},
1239
1380
  assetsInlineLimit: clientAssetsInlineLimit,
1240
- ...withBuildBundlerOptions(viteMajorVersion, {
1381
+ ...withBuildBundlerOptions({
1241
1382
  input: appClientInput,
1242
- output: getClientOutputConfigForVite(viteMajorVersion, clientAssetsDir, true),
1243
- treeshake: getClientTreeshakeConfigForVite(viteMajorVersion)
1383
+ output: getClientOutputConfig(clientAssetsDir, true),
1384
+ treeshake: getClientTreeshakeConfig()
1244
1385
  })
1245
1386
  }
1246
1387
  }
@@ -1255,10 +1396,10 @@ function vinext(options = {}) {
1255
1396
  manifest: true,
1256
1397
  ssrManifest: true,
1257
1398
  assetsInlineLimit: clientAssetsInlineLimit,
1258
- ...withBuildBundlerOptions(viteMajorVersion, {
1399
+ ...withBuildBundlerOptions({
1259
1400
  input: { index: VIRTUAL_CLIENT_ENTRY },
1260
- output: getClientOutputConfigForVite(viteMajorVersion, clientAssetsDir),
1261
- treeshake: getClientTreeshakeConfigForVite(viteMajorVersion)
1401
+ output: getClientOutputConfig(clientAssetsDir),
1402
+ treeshake: getClientTreeshakeConfig()
1262
1403
  })
1263
1404
  }
1264
1405
  } };
@@ -1274,10 +1415,10 @@ function vinext(options = {}) {
1274
1415
  manifest: true,
1275
1416
  ssrManifest: true,
1276
1417
  assetsInlineLimit: clientAssetsInlineLimit,
1277
- ...withBuildBundlerOptions(viteMajorVersion, {
1418
+ ...withBuildBundlerOptions({
1278
1419
  input: { index: VIRTUAL_CLIENT_ENTRY },
1279
- output: getClientOutputConfigForVite(viteMajorVersion, clientAssetsDir),
1280
- treeshake: getClientTreeshakeConfigForVite(viteMajorVersion)
1420
+ output: getClientOutputConfig(clientAssetsDir),
1421
+ treeshake: getClientTreeshakeConfig()
1281
1422
  })
1282
1423
  }
1283
1424
  },
@@ -1298,7 +1439,7 @@ function vinext(options = {}) {
1298
1439
  },
1299
1440
  build: {
1300
1441
  outDir: "dist/server",
1301
- ...withBuildBundlerOptions(viteMajorVersion, {
1442
+ ...withBuildBundlerOptions({
1302
1443
  input: { index: VIRTUAL_SERVER_ENTRY },
1303
1444
  output: { entryFileNames: "entry.js" }
1304
1445
  })
@@ -1325,8 +1466,6 @@ function vinext(options = {}) {
1325
1466
  return null;
1326
1467
  },
1327
1468
  async configResolved(config) {
1328
- const cacheDirPrefix = getCacheDirPrefix(config.cacheDir);
1329
- typeofWindowIdFilter.exclude = new RegExp(`^${escapeRegExp(cacheDirPrefix)}`);
1330
1469
  if (isServeCommand && hasCloudflarePlugin && hasPagesDir && !hasAppDir) suppressOptionalOptimizeDepsWarnings(config.logger);
1331
1470
  sassComposesLoader.setResolvedConfig(config);
1332
1471
  if (config.command === "build" && hasAppDir && hasPagesDir) {
@@ -1366,7 +1505,7 @@ function vinext(options = {}) {
1366
1505
  resolveId: {
1367
1506
  filter: { id: /(?:next\/|vinext\/(?:shims\/|server\/app-rsc-handler)|virtual:vinext-|@vercel\/og(?:\.js)?$)/ },
1368
1507
  handler(id, importer) {
1369
- const cleanId = normalizePathSeparators(id.startsWith("\0") ? id.slice(1) : id);
1508
+ const cleanId = toSlash(id.startsWith("\0") ? id.slice(1) : id);
1370
1509
  if (cleanId === "vinext/server/app-rsc-handler") {
1371
1510
  if (_canExternalizeAppRscHandler && this.environment?.name === "rsc" && this.environment.config?.command === "serve") return {
1372
1511
  id: _appRscHandlerPath,
@@ -1398,94 +1537,101 @@ function vinext(options = {}) {
1398
1537
  return RESOLVED_VIRTUAL_GOOGLE_FONTS + cleanId.slice(queryIndex + VIRTUAL_GOOGLE_FONTS.length);
1399
1538
  }
1400
1539
  const reactServerShim = _reactServerShims.get(cleanId);
1401
- if (reactServerShim !== void 0) return resolveShimModulePath(_shimsDir, this.environment?.name === "rsc" ? `${reactServerShim}.react-server` : reactServerShim);
1540
+ if (reactServerShim !== void 0) {
1541
+ const shimName = this.environment?.name === "rsc" ? `${reactServerShim}.react-server` : reactServerShim;
1542
+ return resolveShimModulePath(_shimsDir, shimName);
1543
+ }
1402
1544
  }
1403
1545
  },
1404
- async load(id) {
1405
- if (id === RESOLVED_WORKER_ENTRY) return `export { default } from ${JSON.stringify(hasAppDir ? "vinext/server/app-router-entry" : "vinext/server/pages-router-entry")};`;
1406
- if (id === RESOLVED_SERVER_ENTRY) return await generateServerEntry$1();
1407
- if (id === RESOLVED_CLIENT_ENTRY) return await generateClientEntry$1();
1408
- if (id === RESOLVED_PAGES_CLIENT_ASSETS) {
1409
- const metadata = { clientEntry: DEV_PAGES_CLIENT_ENTRY };
1410
- const ssrManifest = {};
1411
- const appFilePath = findFileWithExts(pagesDir, "_app", fileMatcher);
1412
- const pagesRoutes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);
1413
- const moduleFilePaths = [...appFilePath ? [appFilePath] : [], ...pagesRoutes.map((route) => route.filePath)];
1414
- for (const moduleFilePath of moduleFilePaths) {
1415
- const stylesheetAssets = await collectDevPagesAppStylesheetAssets(root, moduleFilePath, this.resolve.bind(this));
1416
- if (stylesheetAssets.length > 0) ssrManifest[normalizePathSeparators(moduleFilePath)] = stylesheetAssets;
1546
+ load: {
1547
+ filter: { id: /virtual:vinext-/ },
1548
+ async handler(id) {
1549
+ if (id === RESOLVED_WORKER_ENTRY) return `export { default } from ${JSON.stringify(hasAppDir ? "vinext/server/app-router-entry" : "vinext/server/pages-router-entry")};`;
1550
+ if (id === RESOLVED_SERVER_ENTRY) return await generateServerEntry$1();
1551
+ if (id === RESOLVED_CLIENT_ENTRY) return await generateClientEntry$1();
1552
+ if (id === RESOLVED_PAGES_CLIENT_ASSETS) {
1553
+ const metadata = { clientEntry: DEV_PAGES_CLIENT_ENTRY };
1554
+ const ssrManifest = {};
1555
+ const appFilePath = findFileWithExts(pagesDir, "_app", fileMatcher);
1556
+ const pagesRoutes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);
1557
+ const moduleFilePaths = [...appFilePath ? [appFilePath] : [], ...pagesRoutes.map((route) => route.filePath)];
1558
+ const getModuleDependencies = createDevPagesModuleDependencyReader(root, this.resolve.bind(this));
1559
+ for (const moduleFilePath of moduleFilePaths) {
1560
+ const stylesheetAssets = await collectDevPagesAppStylesheetAssets(moduleFilePath, getModuleDependencies);
1561
+ if (stylesheetAssets.length > 0) ssrManifest[toSlash(moduleFilePath)] = stylesheetAssets;
1562
+ }
1563
+ if (Object.keys(ssrManifest).length > 0) metadata.ssrManifest = ssrManifest;
1564
+ return `export default ${JSON.stringify(metadata)};`;
1417
1565
  }
1418
- if (Object.keys(ssrManifest).length > 0) metadata.ssrManifest = ssrManifest;
1419
- return `export default ${JSON.stringify(metadata)};`;
1420
- }
1421
- if (id === RESOLVED_RSC_ENTRY && hasAppDir) {
1422
- const routes = await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher);
1423
- const metaRoutes = scanMetadataFiles(appDir);
1424
- const hasServerActions = await resolveHasServerActions(this.environment.config);
1425
- const globalErrorPath = findFileWithExts(appDir, "global-error", fileMatcher);
1426
- const globalNotFoundPath = nextConfig?.globalNotFound ? findFileWithExts(appDir, "global-not-found", fileMatcher) : null;
1427
- rscClassificationManifest = collectRouteClassificationManifest(routes);
1428
- return generateRscEntry(appDir, routes, middlewarePath, metaRoutes, globalErrorPath, nextConfig?.basePath, nextConfig?.trailingSlash, {
1429
- redirects: nextConfig?.redirects,
1430
- rewrites: nextConfig?.rewrites,
1431
- headers: nextConfig?.headers,
1432
- allowedOrigins: nextConfig?.serverActionsAllowedOrigins,
1433
- allowedDevOrigins: nextConfig?.allowedDevOrigins,
1434
- bodySizeLimit: nextConfig?.serverActionsBodySizeLimit,
1435
- bodySizeLimitLabel: nextConfig?.serverActionsBodySizeLimitLabel,
1436
- htmlLimitedBots: nextConfig?.htmlLimitedBots,
1437
- clientTraceMetadata: nextConfig?.clientTraceMetadata,
1438
- assetPrefix: nextConfig?.assetPrefix,
1439
- expireTime: nextConfig?.expireTime,
1440
- reactMaxHeadersLength: nextConfig?.reactMaxHeadersLength,
1441
- cacheMaxMemorySize: nextConfig?.cacheMaxMemorySize,
1442
- inlineCss: nextConfig?.inlineCss,
1443
- globalNotFound: nextConfig?.globalNotFound,
1444
- cacheComponents: nextConfig?.cacheComponents,
1445
- prefetchInlining: nextConfig?.prefetchInlining,
1446
- hasServerActions,
1447
- i18n: nextConfig?.i18n,
1448
- imageConfig: {
1449
- deviceSizes: nextConfig?.images?.deviceSizes,
1450
- imageSizes: nextConfig?.images?.imageSizes,
1451
- qualities: nextConfig?.images?.qualities,
1452
- dangerouslyAllowSVG: nextConfig?.images?.dangerouslyAllowSVG,
1453
- dangerouslyAllowLocalIP: nextConfig?.images?.dangerouslyAllowLocalIP,
1454
- contentDispositionType: nextConfig?.images?.contentDispositionType,
1455
- contentSecurityPolicy: nextConfig?.images?.contentSecurityPolicy
1456
- },
1457
- hasPagesDir,
1458
- publicFiles: scanPublicFileRoutes(root),
1459
- globalNotFoundPath,
1460
- draftModeSecret
1461
- }, instrumentationPath);
1462
- }
1463
- if (id === RESOLVED_ROOT_PARAMS) return generateRootParamsModule((hasAppDir ? await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher) : []).flatMap((route) => route.rootParamNames ?? []));
1464
- if (id === RESOLVED_CACHE_ADAPTERS) return generateCacheAdaptersModule(options.cache);
1465
- if (id === RESOLVED_IMAGE_ADAPTERS) return generateImageAdaptersModule(options.images);
1466
- if (id === RESOLVED_APP_SSR_ENTRY && hasAppDir) return generateSsrEntry(hasPagesDir);
1467
- if (id === RESOLVED_APP_BROWSER_ENTRY && hasAppDir) {
1468
- const graph = await appRouteGraph(appDir, nextConfig?.pageExtensions, fileMatcher);
1469
- const pagesPrefetchRoutes = hasPagesDir ? [...(await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher)).map((route) => ({
1470
- canPrefetchLoadingShell: false,
1471
- isDynamic: route.isDynamic,
1472
- patternParts: [...route.patternParts]
1473
- })), ...(await apiRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher)).map((route) => ({
1474
- canPrefetchLoadingShell: false,
1475
- documentOnly: true,
1476
- isDynamic: route.isDynamic,
1477
- patternParts: [...route.patternParts]
1478
- }))] : [];
1479
- return generateBrowserEntry(graph.routes, graph.routeManifest, pagesPrefetchRoutes, nextConfig.rewrites);
1480
- }
1481
- if (id === RESOLVED_APP_CAPABILITIES && hasAppDir) {
1482
- const hasServerActions = await resolveHasServerActions(this.environment.config);
1483
- return `
1566
+ if (id === RESOLVED_RSC_ENTRY && hasAppDir) {
1567
+ const routes = await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher);
1568
+ const metaRoutes = scanMetadataFiles(appDir);
1569
+ const hasServerActions = await resolveHasServerActions(this.environment.config);
1570
+ const globalErrorPath = findFileWithExts(appDir, "global-error", fileMatcher);
1571
+ const globalNotFoundPath = nextConfig?.globalNotFound ? findFileWithExts(appDir, "global-not-found", fileMatcher) : null;
1572
+ rscClassificationManifest = collectRouteClassificationManifest(routes);
1573
+ return generateRscEntry(appDir, routes, middlewarePath, metaRoutes, globalErrorPath, nextConfig?.basePath, nextConfig?.trailingSlash, {
1574
+ redirects: nextConfig?.redirects,
1575
+ rewrites: nextConfig?.rewrites,
1576
+ headers: nextConfig?.headers,
1577
+ allowedOrigins: nextConfig?.serverActionsAllowedOrigins,
1578
+ allowedDevOrigins: nextConfig?.allowedDevOrigins,
1579
+ bodySizeLimit: nextConfig?.serverActionsBodySizeLimit,
1580
+ bodySizeLimitLabel: nextConfig?.serverActionsBodySizeLimitLabel,
1581
+ htmlLimitedBots: nextConfig?.htmlLimitedBots,
1582
+ clientTraceMetadata: nextConfig?.clientTraceMetadata,
1583
+ assetPrefix: nextConfig?.assetPrefix,
1584
+ expireTime: nextConfig?.expireTime,
1585
+ reactMaxHeadersLength: nextConfig?.reactMaxHeadersLength,
1586
+ cacheMaxMemorySize: nextConfig?.cacheMaxMemorySize,
1587
+ inlineCss: nextConfig?.inlineCss,
1588
+ globalNotFound: nextConfig?.globalNotFound,
1589
+ cacheComponents: nextConfig?.cacheComponents,
1590
+ prefetchInlining: nextConfig?.prefetchInlining,
1591
+ hasServerActions,
1592
+ i18n: nextConfig?.i18n,
1593
+ imageConfig: {
1594
+ deviceSizes: nextConfig?.images?.deviceSizes,
1595
+ imageSizes: nextConfig?.images?.imageSizes,
1596
+ qualities: nextConfig?.images?.qualities,
1597
+ dangerouslyAllowSVG: nextConfig?.images?.dangerouslyAllowSVG,
1598
+ dangerouslyAllowLocalIP: nextConfig?.images?.dangerouslyAllowLocalIP,
1599
+ contentDispositionType: nextConfig?.images?.contentDispositionType,
1600
+ contentSecurityPolicy: nextConfig?.images?.contentSecurityPolicy
1601
+ },
1602
+ hasPagesDir,
1603
+ publicFiles: scanPublicFileRoutes(root),
1604
+ globalNotFoundPath,
1605
+ draftModeSecret
1606
+ }, instrumentationPath);
1607
+ }
1608
+ if (id === RESOLVED_ROOT_PARAMS) return generateRootParamsModule((hasAppDir ? await appRouter(appDir, nextConfig?.pageExtensions, fileMatcher) : []).flatMap((route) => route.rootParamNames ?? []));
1609
+ if (id === RESOLVED_CACHE_ADAPTERS) return generateCacheAdaptersModule(options.cache);
1610
+ if (id === RESOLVED_IMAGE_ADAPTERS) return generateImageAdaptersModule(options.images);
1611
+ if (id === RESOLVED_APP_SSR_ENTRY && hasAppDir) return generateSsrEntry(hasPagesDir);
1612
+ if (id === RESOLVED_APP_BROWSER_ENTRY && hasAppDir) {
1613
+ const graph = await appRouteGraph(appDir, nextConfig?.pageExtensions, fileMatcher);
1614
+ const pagesPrefetchRoutes = hasPagesDir ? [...(await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher)).map((route) => ({
1615
+ canPrefetchLoadingShell: false,
1616
+ isDynamic: route.isDynamic,
1617
+ patternParts: [...route.patternParts]
1618
+ })), ...(await apiRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher)).map((route) => ({
1619
+ canPrefetchLoadingShell: false,
1620
+ documentOnly: true,
1621
+ isDynamic: route.isDynamic,
1622
+ patternParts: [...route.patternParts]
1623
+ }))] : [];
1624
+ return generateBrowserEntry(graph.routes, graph.routeManifest, pagesPrefetchRoutes, nextConfig.rewrites);
1625
+ }
1626
+ if (id === RESOLVED_APP_CAPABILITIES && hasAppDir) {
1627
+ const hasServerActions = await resolveHasServerActions(this.environment.config);
1628
+ return `
1484
1629
  export const hasServerActions = ${JSON.stringify(hasServerActions)};
1485
1630
  export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.stringify(_appBrowserServerActionClientPath)})` : "null"};
1486
1631
  `;
1632
+ }
1633
+ if (id.startsWith("\0virtual:vinext-google-fonts?")) return generateGoogleFontsVirtualModule(id, _fontGoogleShimPath);
1487
1634
  }
1488
- if (id.startsWith("\0virtual:vinext-google-fonts?")) return generateGoogleFontsVirtualModule(id, _fontGoogleShimPath);
1489
1635
  },
1490
1636
  // @vitejs/plugin-rsc runs the RSC environment build in two phases:
1491
1637
  renderChunk: {
@@ -1528,13 +1674,13 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1528
1674
  resolveId: {
1529
1675
  filter: { id: /virtual:vinext-pages-client-assets$/ },
1530
1676
  handler(id) {
1531
- const cleanId = normalizePathSeparators(id.startsWith("\0") ? id.slice(1) : id);
1677
+ const cleanId = toSlash(id.startsWith("\0") ? id.slice(1) : id);
1532
1678
  if (cleanId !== VIRTUAL_PAGES_CLIENT_ASSETS && !cleanId.endsWith("/virtual:vinext-pages-client-assets")) return;
1533
1679
  if (this.environment?.config.command !== "build") return RESOLVED_PAGES_CLIENT_ASSETS;
1534
1680
  const buildRoot = this.environment.config.root ?? process.cwd();
1535
1681
  const environmentOutDir = path.resolve(buildRoot, this.environment.config.build.outDir);
1536
1682
  const sidecarDir = !hasAppDir && this.environment.name === "ssr" ? path.dirname(environmentOutDir) : environmentOutDir;
1537
- let externalId = normalizePathSeparators(path.relative(environmentOutDir, path.join(sidecarDir, PAGES_CLIENT_ASSETS_MODULE)));
1683
+ let externalId = path.relative(environmentOutDir, path.join(sidecarDir, PAGES_CLIENT_ASSETS_MODULE));
1538
1684
  if (!externalId.startsWith(".")) externalId = `./${externalId}`;
1539
1685
  pagesClientAssetsOutputDirs.add(sidecarDir);
1540
1686
  return {
@@ -1571,7 +1717,7 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1571
1717
  if (!hasAppDir || name !== "rsc" && name !== "ssr") return null;
1572
1718
  const output = getBuildBundlerOptions(config.build)?.output;
1573
1719
  if (Array.isArray(output) || output?.assetFileNames !== void 0) return null;
1574
- return { build: { ...withBuildBundlerOptions(viteMajorVersion, { output: { assetFileNames: createClientAssetFileNames(resolveAssetsDir(nextConfig.assetPrefix ?? "")) } }) } };
1720
+ return { build: { ...withBuildBundlerOptions({ output: { assetFileNames: createClientAssetFileNames(resolveAssetsDir(nextConfig.assetPrefix ?? "")) } }) } };
1575
1721
  }
1576
1722
  },
1577
1723
  {
@@ -1621,54 +1767,44 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1621
1767
  {
1622
1768
  name: "vinext:instrumentation-client-inject",
1623
1769
  enforce: "pre",
1624
- resolveId(id) {
1625
- if (id !== VIRTUAL_INSTRUMENTATION_CLIENT) return null;
1626
- return clientInjectModule !== null ? RESOLVED_INSTRUMENTATION_CLIENT : null;
1627
- },
1628
- load(id) {
1629
- if (id !== RESOLVED_INSTRUMENTATION_CLIENT) return null;
1630
- return clientInjectModule;
1631
- }
1632
- },
1633
- ...options.experimental?.clientReferenceDedup ? [clientReferenceDedupPlugin()] : [],
1634
- {
1635
- name: "vinext:mdx",
1636
- enforce: "pre",
1637
- config(config, env) {
1638
- if (!mdxDelegate?.config) return;
1639
- const hook = mdxDelegate.config;
1640
- return (typeof hook === "function" ? hook : hook.handler).call(this, config, env);
1770
+ resolveId: {
1771
+ filter: { id: /^private-next-instrumentation-client$/ },
1772
+ handler(id) {
1773
+ if (id !== VIRTUAL_INSTRUMENTATION_CLIENT) return null;
1774
+ return clientInjectModule !== null ? RESOLVED_INSTRUMENTATION_CLIENT : null;
1775
+ }
1641
1776
  },
1642
- transform: {
1643
- filter: { id: {
1644
- include: /\.mdx$/i,
1645
- exclude: /\?/
1646
- } },
1647
- async handler(code, id, options) {
1648
- const delegate = mdxDelegate ?? await ensureMdxDelegate("on-demand");
1649
- if (delegate?.transform) {
1650
- const hook = delegate.transform;
1651
- return (typeof hook === "function" ? hook : hook.handler).call(this, code, id, options);
1652
- }
1653
- 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.`);
1777
+ load: {
1778
+ filter: { id: /private-next-instrumentation-client\.mjs$/ },
1779
+ handler(id) {
1780
+ if (id !== RESOLVED_INSTRUMENTATION_CLIENT) return null;
1781
+ return clientInjectModule;
1654
1782
  }
1655
1783
  }
1656
1784
  },
1785
+ ...options.experimental?.clientReferenceDedup ? [clientReferenceDedupPlugin()] : [],
1786
+ mdxConfigProxyPlugin,
1657
1787
  createCssModuleImportCompatibilityPlugin({ compiledMdx: true }),
1658
1788
  {
1659
1789
  name: "vinext:react-canary",
1660
1790
  enforce: "pre",
1661
- resolveId(id) {
1662
- if (id === "virtual:vinext-react-canary") return "\0virtual:vinext-react-canary";
1791
+ resolveId: {
1792
+ filter: { id: /^virtual:vinext-react-canary$/ },
1793
+ handler(id) {
1794
+ if (id === "virtual:vinext-react-canary") return "\0virtual:vinext-react-canary";
1795
+ }
1663
1796
  },
1664
- load(id) {
1665
- if (id === "\0virtual:vinext-react-canary") return [
1666
- `export * from "react";`,
1667
- `export { default } from "react";`,
1668
- `import * as _React from "react";`,
1669
- `export const ViewTransition = _React.ViewTransition || function ViewTransition({ children }) { return children; };`,
1670
- `export const addTransitionType = _React.addTransitionType || function addTransitionType() {};`
1671
- ].join("\n");
1797
+ load: {
1798
+ filter: { id: /^\u0000virtual:vinext-react-canary$/ },
1799
+ handler(id) {
1800
+ if (id === "\0virtual:vinext-react-canary") return [
1801
+ `export * from "react";`,
1802
+ `export { default } from "react";`,
1803
+ `import * as _React from "react";`,
1804
+ `export const ViewTransition = _React.ViewTransition || function ViewTransition({ children }) { return children; };`,
1805
+ `export const addTransitionType = _React.addTransitionType || function addTransitionType() {};`
1806
+ ].join("\n");
1807
+ }
1672
1808
  },
1673
1809
  transform: {
1674
1810
  filter: {
@@ -1688,36 +1824,35 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1688
1824
  },
1689
1825
  {
1690
1826
  name: "vinext:pages-router",
1691
- hotUpdate(options) {
1692
- if (!hasPagesDir) return;
1693
- const isPagesAppFile = (filePath) => {
1694
- const relativePath = normalizePathSeparators(path.relative(pagesDir, filePath));
1695
- return !relativePath.includes("/") && relativePath.startsWith("_app.") && fileMatcher.extensionRegex.test(filePath);
1696
- };
1697
- const isPotentialPagesAssetGraphScript = (filePath) => {
1698
- const cleanPath = stripViteModuleQuery(filePath);
1699
- if (!path.isAbsolute(cleanPath)) return false;
1700
- if (!isScriptModuleId(cleanPath) || cleanPath.endsWith(".d.ts")) return false;
1701
- const relativeRootPath = normalizePathSeparators(path.relative(root, cleanPath));
1702
- if (relativeRootPath.startsWith("..") || path.isAbsolute(relativeRootPath)) return false;
1703
- if (relativeRootPath.includes("/node_modules/") || relativeRootPath.startsWith("node_modules/")) return false;
1704
- const relativeAppPath = normalizePathSeparators(path.relative(appDir, cleanPath));
1705
- return relativeAppPath.startsWith("..") || path.isAbsolute(relativeAppPath);
1706
- };
1707
- const pagesAppChanged = isPagesAppFile(options.file);
1708
- const pagesAssetGraphScriptChanged = isPotentialPagesAssetGraphScript(options.file);
1709
- if (pagesAppChanged || STYLESHEET_FILE_RE.test(options.file) || pagesAssetGraphScriptChanged) for (const env of Object.values(options.server.environments)) {
1710
- const mod = env.moduleGraph.getModuleById(RESOLVED_PAGES_CLIENT_ASSETS);
1711
- if (mod) env.moduleGraph.invalidateModule(mod);
1712
- }
1713
- if (pagesAppChanged || !hasAppDir && pagesAssetGraphScriptChanged) {
1714
- options.server.ws.send({ type: "full-reload" });
1715
- return [];
1716
- }
1717
- if (hasAppDir) return;
1718
- if (options.file.startsWith(pagesDir) && fileMatcher.extensionRegex.test(options.file)) {
1719
- options.server.environments.client.hot.send({ type: "full-reload" });
1720
- return [];
1827
+ // @vitejs/plugin-react to handle normal module updates. Next.js preserves
1828
+ hotUpdate: {
1829
+ order: "post",
1830
+ handler(options) {
1831
+ if (!hasPagesDir) return;
1832
+ const isPagesAppFile = (filePath) => {
1833
+ const relativePath = path.relative(pagesDir, filePath);
1834
+ return !relativePath.includes("/") && relativePath.startsWith("_app.") && fileMatcher.extensionRegex.test(filePath);
1835
+ };
1836
+ const isPotentialPagesAssetGraphScript = (filePath) => {
1837
+ const cleanPath = stripViteModuleQuery(filePath);
1838
+ if (!path.isAbsolute(cleanPath)) return false;
1839
+ if (!isScriptModuleId(cleanPath) || cleanPath.endsWith(".d.ts")) return false;
1840
+ const relativeRootPath = path.relative(root, cleanPath);
1841
+ if (relativeRootPath.startsWith("..") || path.isAbsolute(relativeRootPath)) return false;
1842
+ if (relativeRootPath.includes("/node_modules/") || relativeRootPath.startsWith("node_modules/")) return false;
1843
+ const relativeAppPath = path.relative(appDir, cleanPath);
1844
+ return relativeAppPath.startsWith("..") || path.isAbsolute(relativeAppPath);
1845
+ };
1846
+ const pagesAppChanged = isPagesAppFile(options.file);
1847
+ const pagesAssetGraphScriptChanged = isPotentialPagesAssetGraphScript(options.file);
1848
+ if (pagesAppChanged || STYLESHEET_FILE_RE.test(options.file) || pagesAssetGraphScriptChanged) for (const env of Object.values(options.server.environments)) {
1849
+ const mod = env.moduleGraph.getModuleById(RESOLVED_PAGES_CLIENT_ASSETS);
1850
+ if (mod) env.moduleGraph.invalidateModule(mod);
1851
+ }
1852
+ if (this.environment?.name === "ssr" && pagesAssetGraphScriptChanged) {
1853
+ for (const mod of options.modules) this.environment.moduleGraph.invalidateModule(mod, /* @__PURE__ */ new Set(), options.timestamp, true);
1854
+ return [];
1855
+ }
1721
1856
  }
1722
1857
  },
1723
1858
  configureServer(server) {
@@ -1767,13 +1902,12 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1767
1902
  }
1768
1903
  pagesRunner?.clearCache();
1769
1904
  }
1770
- function invalidatePagesClientAssetsModule(reloadDocument = false) {
1905
+ function invalidatePagesClientAssetsModule() {
1771
1906
  for (const env of Object.values(server.environments)) {
1772
1907
  const mod = env.moduleGraph.getModuleById(RESOLVED_PAGES_CLIENT_ASSETS);
1773
1908
  if (mod) env.moduleGraph.invalidateModule(mod);
1774
1909
  }
1775
1910
  pagesRunner?.clearCache();
1776
- if (reloadDocument) server.ws.send({ type: "full-reload" });
1777
1911
  }
1778
1912
  function invalidateAppRoutingModules() {
1779
1913
  invalidateAppRouteCache();
@@ -1823,17 +1957,17 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1823
1957
  let appRouteTypeGeneration = null;
1824
1958
  let appRouteTypeGenerationPending = false;
1825
1959
  function isPagesAppFile(filePath) {
1826
- const relativePath = normalizePathSeparators(path.relative(pagesDir, filePath));
1960
+ const relativePath = path.relative(pagesDir, filePath);
1827
1961
  return !relativePath.includes("/") && relativePath.startsWith("_app.") && fileMatcher.extensionRegex.test(filePath);
1828
1962
  }
1829
1963
  function isPotentialPagesAssetGraphScript(filePath) {
1830
1964
  const cleanPath = stripViteModuleQuery(filePath);
1831
1965
  if (!path.isAbsolute(cleanPath)) return false;
1832
1966
  if (!isScriptModuleId(cleanPath) || cleanPath.endsWith(".d.ts")) return false;
1833
- const relativeRootPath = normalizePathSeparators(path.relative(root, cleanPath));
1967
+ const relativeRootPath = path.relative(root, cleanPath);
1834
1968
  if (relativeRootPath.startsWith("..") || path.isAbsolute(relativeRootPath)) return false;
1835
1969
  if (relativeRootPath.includes("/node_modules/") || relativeRootPath.startsWith("node_modules/")) return false;
1836
- const relativeAppPath = normalizePathSeparators(path.relative(appDir, cleanPath));
1970
+ const relativeAppPath = path.relative(appDir, cleanPath);
1837
1971
  return relativeAppPath.startsWith("..") || path.isAbsolute(relativeAppPath);
1838
1972
  }
1839
1973
  function warnRouteTypeGenerationFailure(error) {
@@ -1866,8 +2000,8 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1866
2000
  let routeChanged = false;
1867
2001
  const pagesAppChanged = isPagesAppFile(filePath);
1868
2002
  const pagesAssetGraphScriptChanged = isPotentialPagesAssetGraphScript(filePath);
1869
- if (hasPagesDir && (pagesAppChanged || STYLESHEET_FILE_RE.test(filePath) || pagesAssetGraphScriptChanged)) invalidatePagesClientAssetsModule(pagesAppChanged || !hasAppDir && pagesAssetGraphScriptChanged);
1870
- if (hasPagesDir && filePath.startsWith(pagesDir) && pageExtensions.test(filePath)) {
2003
+ if (hasPagesDir && (pagesAppChanged || STYLESHEET_FILE_RE.test(filePath) || pagesAssetGraphScriptChanged)) invalidatePagesClientAssetsModule();
2004
+ if (hasPagesDir && toSlash(filePath).startsWith(pagesDir) && pageExtensions.test(filePath)) {
1871
2005
  invalidateRouteCache(pagesDir);
1872
2006
  routeChanged = true;
1873
2007
  }
@@ -1878,6 +2012,7 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1878
2012
  }
1879
2013
  if (routeChanged) {
1880
2014
  invalidatePagesServerEntry();
2015
+ if (!hasAppDir) server.ws.send({ type: "full-reload" });
1881
2016
  invalidateHybridClientEntries();
1882
2017
  revalidateHybridRoutes();
1883
2018
  }
@@ -1885,14 +2020,14 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1885
2020
  server.watcher.on("change", (filePath) => {
1886
2021
  const pagesAppChanged = isPagesAppFile(filePath);
1887
2022
  const pagesAssetGraphScriptChanged = isPotentialPagesAssetGraphScript(filePath);
1888
- if (hasPagesDir && (pagesAppChanged || STYLESHEET_FILE_RE.test(filePath) || pagesAssetGraphScriptChanged)) invalidatePagesClientAssetsModule(pagesAppChanged || !hasAppDir && pagesAssetGraphScriptChanged);
2023
+ if (hasPagesDir && (pagesAppChanged || STYLESHEET_FILE_RE.test(filePath) || pagesAssetGraphScriptChanged)) invalidatePagesClientAssetsModule();
1889
2024
  });
1890
2025
  server.watcher.on("unlink", (filePath) => {
1891
2026
  let routeChanged = false;
1892
2027
  const pagesAppChanged = isPagesAppFile(filePath);
1893
2028
  const pagesAssetGraphScriptChanged = isPotentialPagesAssetGraphScript(filePath);
1894
- if (hasPagesDir && (pagesAppChanged || STYLESHEET_FILE_RE.test(filePath) || pagesAssetGraphScriptChanged)) invalidatePagesClientAssetsModule(pagesAppChanged || !hasAppDir && pagesAssetGraphScriptChanged);
1895
- if (hasPagesDir && filePath.startsWith(pagesDir) && pageExtensions.test(filePath)) {
2029
+ if (hasPagesDir && (pagesAppChanged || STYLESHEET_FILE_RE.test(filePath) || pagesAssetGraphScriptChanged)) invalidatePagesClientAssetsModule();
2030
+ if (hasPagesDir && toSlash(filePath).startsWith(pagesDir) && pageExtensions.test(filePath)) {
1896
2031
  invalidateRouteCache(pagesDir);
1897
2032
  routeChanged = true;
1898
2033
  }
@@ -1903,6 +2038,7 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
1903
2038
  }
1904
2039
  if (routeChanged) {
1905
2040
  invalidatePagesServerEntry();
2041
+ if (!hasAppDir) server.ws.send({ type: "full-reload" });
1906
2042
  invalidateHybridClientEntries();
1907
2043
  revalidateHybridRoutes();
1908
2044
  }
@@ -2384,15 +2520,23 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2384
2520
  },
2385
2521
  {
2386
2522
  name: "vinext:typeof-window",
2523
+ configEnvironment(_name, environment) {
2524
+ if (!useNativeTypeofWindowFolding) return null;
2525
+ return { define: { "typeof window": environment.consumer === "client" ? "\"object\"" : "\"undefined\"" } };
2526
+ }
2527
+ },
2528
+ {
2529
+ name: "vinext:typeof-window-scan",
2530
+ apply(_config, environment) {
2531
+ return !useNativeTypeofWindowFolding || environment.command === "build";
2532
+ },
2387
2533
  enforce: "post",
2388
2534
  transform: {
2389
- filter: {
2390
- id: typeofWindowIdFilter,
2391
- code: /typeof\s+window/
2392
- },
2535
+ filter: { code: /\btypeof\s+window\b/ },
2393
2536
  handler(code, id) {
2394
- const cacheDirPrefix = getCacheDirPrefix(this.environment.config.cacheDir);
2395
- if (normalizePathSeparators(id).startsWith(cacheDirPrefix)) return null;
2537
+ if (useNativeTypeofWindowFolding && this.environment.config.build.write !== false) return null;
2538
+ const cacheDir = `${toSlash(this.environment.config.cacheDir).replace(/\/$/, "")}/`;
2539
+ if (toSlash(id).startsWith(cacheDir)) return null;
2396
2540
  return replaceTypeofWindow(code, getTypeofWindowReplacement(this.environment), id);
2397
2541
  }
2398
2542
  }
@@ -2405,9 +2549,26 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2405
2549
  serverDefines["process.env.NEXT_RUNTIME"] = JSON.stringify("nodejs");
2406
2550
  const sharedRevalidateSecret = process.env.__VINEXT_SHARED_REVALIDATE_SECRET;
2407
2551
  if (sharedRevalidateSecret) serverDefines["process.env.__VINEXT_REVALIDATE_SECRET"] = JSON.stringify(sharedRevalidateSecret);
2552
+ if (previewBuildCredentials) {
2553
+ serverDefines["process.env.__VINEXT_PREVIEW_MODE_ID"] = JSON.stringify(previewBuildCredentials.id);
2554
+ serverDefines["process.env.__VINEXT_PREVIEW_MODE_SIGNING_KEY"] = JSON.stringify(previewBuildCredentials.signingKey);
2555
+ serverDefines["process.env.__VINEXT_PREVIEW_MODE_ENCRYPTION_KEY"] = JSON.stringify(previewBuildCredentials.encryptionKey);
2556
+ }
2408
2557
  return { define: serverDefines };
2409
2558
  }
2410
2559
  },
2560
+ {
2561
+ name: "vinext:client-global-define",
2562
+ configEnvironment(name) {
2563
+ if (name !== "client") return null;
2564
+ if (Object.hasOwn(nextConfig.compilerDefine, "global")) return null;
2565
+ const define = { global: "globalThis" };
2566
+ return {
2567
+ define,
2568
+ optimizeDeps: { rolldownOptions: { transform: { define } } }
2569
+ };
2570
+ }
2571
+ },
2411
2572
  {
2412
2573
  name: "vinext:image-imports",
2413
2574
  enforce: "pre",
@@ -2417,7 +2578,7 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2417
2578
  staticImageAssets.clear();
2418
2579
  },
2419
2580
  watchChange(id) {
2420
- const key = normalizePathSeparators(id);
2581
+ const key = toSlash(id);
2421
2582
  imageImportDimCache.delete(key);
2422
2583
  staticImageAssets.delete(key);
2423
2584
  staticImageImportsByModule.delete(key);
@@ -2495,7 +2656,7 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2495
2656
  const dir = path.dirname(id);
2496
2657
  const resolvedImage = importPath.startsWith(".") ? path.resolve(dir, importPath) : (await this.resolve(importPath, id, { skipSelf: true }))?.id;
2497
2658
  if (!resolvedImage) continue;
2498
- const absImagePath = normalizePathSeparators(resolvedImage.split("?", 1)[0]);
2659
+ const absImagePath = toSlash(resolvedImage.split("?", 1)[0]);
2499
2660
  if (!fs.existsSync(absImagePath)) continue;
2500
2661
  imageImports.add(absImagePath);
2501
2662
  const urlVar = `__vinext_img_url_${varName}`;
@@ -2698,9 +2859,10 @@ export const loadServerActionClient = ${hasServerActions ? `() => import(${JSON.
2698
2859
  {
2699
2860
  name: "vinext:nitro-route-rules",
2700
2861
  nitro: { setup: async (nitro) => {
2701
- if (nitro.options.dev) return;
2702
2862
  if (!nextConfig) return;
2703
2863
  if (!hasAppDir && !hasPagesDir) return;
2864
+ if (nitroTraceDepsFromServerExternals.length > 0) nitro.options.traceDeps = [.../* @__PURE__ */ new Set([...nitro.options.traceDeps ?? [], ...nitroTraceDepsFromServerExternals])];
2865
+ if (nitro.options.dev) return;
2704
2866
  const { collectNitroRouteRules, mergeNitroRouteRules } = await import("./build/nitro-route-rules.js");
2705
2867
  const generatedRouteRules = await collectNitroRouteRules({
2706
2868
  appDir: hasAppDir ? appDir : null,