vinext 1.1.0 → 1.2.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 (288) hide show
  1. package/README.md +22 -10
  2. package/dist/build/client-build-config.d.ts +10 -0
  3. package/dist/build/client-build-config.js +18 -2
  4. package/dist/build/output-root-externals.d.ts +21 -0
  5. package/dist/build/output-root-externals.js +40 -0
  6. package/dist/build/pages-client-assets-module.d.ts +8 -0
  7. package/dist/build/pages-client-assets-module.js +21 -1
  8. package/dist/build/prerender-paths.js +6 -4
  9. package/dist/build/prerender.js +1 -1
  10. package/dist/build/run-prerender.js +1 -1
  11. package/dist/build/ssr-manifest.d.ts +2 -0
  12. package/dist/build/ssr-manifest.js +6 -2
  13. package/dist/check.js +12 -12
  14. package/dist/cli-dev-config.js +3 -3
  15. package/dist/cli.js +3 -2
  16. package/dist/client/client-redirect-matcher.d.ts +14 -0
  17. package/dist/client/client-redirect-matcher.js +37 -0
  18. package/dist/client/client-redirects.d.ts +27 -0
  19. package/dist/client/client-redirects.js +28 -0
  20. package/dist/client/client-rewrites.d.ts +2 -1
  21. package/dist/client/client-rewrites.js +1 -1
  22. package/dist/config/config-matchers.d.ts +26 -11
  23. package/dist/config/config-matchers.js +90 -88
  24. package/dist/config/destination-params.d.ts +47 -0
  25. package/dist/config/destination-params.js +116 -0
  26. package/dist/config/next-config.d.ts +7 -0
  27. package/dist/config/next-config.js +3 -0
  28. package/dist/entries/app-rsc-entry.d.ts +4 -0
  29. package/dist/entries/app-rsc-entry.js +20 -6
  30. package/dist/entries/pages-client-entry.js +3 -1
  31. package/dist/entries/pages-server-entry.js +13 -37
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +246 -136
  34. package/dist/init-cloudflare.d.ts +9 -0
  35. package/dist/init-cloudflare.js +107 -31
  36. package/dist/init-platform.d.ts +4 -0
  37. package/dist/init-platform.js +27 -2
  38. package/dist/init.d.ts +2 -1
  39. package/dist/init.js +153 -9
  40. package/dist/plugins/ast-scope.d.ts +7 -0
  41. package/dist/plugins/ast-scope.js +59 -3
  42. package/dist/plugins/ast-utils.d.ts +53 -2
  43. package/dist/plugins/ast-utils.js +90 -2
  44. package/dist/plugins/cloudflare-dev-module-urls.d.ts +41 -0
  45. package/dist/plugins/cloudflare-dev-module-urls.js +271 -0
  46. package/dist/plugins/commonjs-esm-facade.js +2 -2
  47. package/dist/plugins/css-module-imports.js +13 -20
  48. package/dist/plugins/dynamic-preload-metadata.d.ts +1 -1
  49. package/dist/plugins/dynamic-preload-metadata.js +11 -11
  50. package/dist/plugins/extensionless-dynamic-import.js +2 -3
  51. package/dist/plugins/fonts.d.ts +1 -1
  52. package/dist/plugins/fonts.js +3 -3
  53. package/dist/plugins/ignore-dynamic-requests.d.ts +1 -1
  54. package/dist/plugins/ignore-dynamic-requests.js +5 -7
  55. package/dist/plugins/import-meta-url.js +3 -4
  56. package/dist/plugins/instrumentation-client.js +3 -2
  57. package/dist/plugins/middleware-export-validation.js +2 -3
  58. package/dist/plugins/middleware-server-only.d.ts +5 -4
  59. package/dist/plugins/middleware-server-only.js +8 -5
  60. package/dist/plugins/og-harfbuzz.js +2 -3
  61. package/dist/plugins/optimize-imports.js +3 -4
  62. package/dist/plugins/pages-node-externals.js +3 -4
  63. package/dist/plugins/remove-console.js +2 -18
  64. package/dist/plugins/require-condition-resolution.js +3 -3
  65. package/dist/plugins/require-context.js +2 -3
  66. package/dist/plugins/rsc-scan-glob-imports.d.ts +19 -0
  67. package/dist/plugins/rsc-scan-glob-imports.js +50 -0
  68. package/dist/plugins/strip-server-exports.js +265 -102
  69. package/dist/plugins/styled-jsx.js +2 -3
  70. package/dist/plugins/transform-result.d.ts +9 -5
  71. package/dist/plugins/transitive-externals.js +1 -1
  72. package/dist/plugins/typeof-window.d.ts +2 -2
  73. package/dist/plugins/use-cache-callable.d.ts +21 -2
  74. package/dist/plugins/use-cache-callable.js +84 -35
  75. package/dist/plugins/worker-image-imports.js +30 -33
  76. package/dist/plugins/worker-server-only-imports.d.ts +20 -0
  77. package/dist/plugins/worker-server-only-imports.js +31 -0
  78. package/dist/plugins/worker-use-server.d.ts +25 -0
  79. package/dist/plugins/worker-use-server.js +153 -0
  80. package/dist/server/api-handler.d.ts +1 -0
  81. package/dist/server/api-handler.js +3 -2
  82. package/dist/server/app-action-forwarding.js +2 -2
  83. package/dist/server/app-browser-action-result.d.ts +1 -1
  84. package/dist/server/app-browser-action-result.js +9 -2
  85. package/dist/server/app-browser-entry.js +3 -3
  86. package/dist/server/app-browser-interception-context.js +1 -1
  87. package/dist/server/app-browser-navigation-controller.js +1 -1
  88. package/dist/server/app-browser-prefetch-response.js +2 -2
  89. package/dist/server/app-browser-server-action-client.js +1 -1
  90. package/dist/server/app-browser-state.js +1 -1
  91. package/dist/server/app-browser-supplemental-refresh.js +1 -1
  92. package/dist/server/app-middleware.d.ts +11 -0
  93. package/dist/server/app-middleware.js +17 -2
  94. package/dist/server/app-optimistic-routing.js +1 -1
  95. package/dist/server/app-page-cache.d.ts +1 -1
  96. package/dist/server/app-page-cache.js +1 -1
  97. package/dist/server/app-page-dispatch.d.ts +3 -1
  98. package/dist/server/app-page-dispatch.js +5 -4
  99. package/dist/server/app-page-ppr-runtime.js +1 -1
  100. package/dist/server/app-page-render-observation.js +1 -1
  101. package/dist/server/app-page-render.js +1 -1
  102. package/dist/server/app-page-request.js +53 -15
  103. package/dist/server/app-page-route-wiring.js +2 -2
  104. package/dist/server/app-pages-bridge.d.ts +1 -1
  105. package/dist/server/app-pages-bridge.js +3 -4
  106. package/dist/server/app-prerender-endpoints.js +9 -6
  107. package/dist/server/app-render-abort-error.d.ts +19 -0
  108. package/dist/server/app-render-abort-error.js +31 -1
  109. package/dist/server/app-request-stage-dispatch.js +6 -2
  110. package/dist/server/app-request-stage-independent-entry.js +29 -9
  111. package/dist/server/app-response-stage-entry.js +11 -3
  112. package/dist/server/app-route-handler-cache.d.ts +1 -0
  113. package/dist/server/app-route-handler-cache.js +1 -0
  114. package/dist/server/app-route-handler-dispatch.d.ts +1 -0
  115. package/dist/server/app-route-handler-dispatch.js +5 -2
  116. package/dist/server/app-route-handler-execution.d.ts +1 -0
  117. package/dist/server/app-route-handler-execution.js +1 -0
  118. package/dist/server/app-route-handler-runtime.d.ts +4 -1
  119. package/dist/server/app-route-handler-runtime.js +46 -25
  120. package/dist/server/app-router-entry.js +29 -10
  121. package/dist/server/app-rsc-cache-busting.d.ts +16 -0
  122. package/dist/server/app-rsc-cache-busting.js +30 -13
  123. package/dist/server/app-rsc-errors.js +20 -16
  124. package/dist/server/app-rsc-handler.d.ts +7 -0
  125. package/dist/server/app-rsc-handler.js +89 -39
  126. package/dist/server/app-rsc-request-normalization.js +3 -3
  127. package/dist/server/app-rsc-response-stage.js +5 -3
  128. package/dist/server/app-segment-config.d.ts +2 -1
  129. package/dist/server/app-server-action-execution.d.ts +2 -1
  130. package/dist/server/app-server-action-execution.js +62 -23
  131. package/dist/server/app-ssr-entry.js +7 -5
  132. package/dist/server/app-visited-response-cache.js +2 -2
  133. package/dist/server/app-worker-stages.d.ts +5 -0
  134. package/dist/server/app-worker-stages.js +1 -1
  135. package/dist/server/cacheability-request.js +2 -2
  136. package/dist/server/client-build-files.d.ts +16 -0
  137. package/dist/server/client-build-files.js +36 -0
  138. package/dist/server/client-reuse-manifest.js +1 -1
  139. package/dist/server/config-headers.js +1 -1
  140. package/dist/server/defer-until-stream-consumed.d.ts +2 -1
  141. package/dist/server/defer-until-stream-consumed.js +3 -1
  142. package/dist/server/dev-server.js +39 -28
  143. package/dist/server/dev-stack-sourcemap.js +18 -23
  144. package/dist/server/document-initial-head.d.ts +0 -11
  145. package/dist/server/document-initial-head.js +1 -1
  146. package/dist/server/forwarded-middleware-context.d.ts +5 -0
  147. package/dist/server/forwarded-middleware-context.js +22 -0
  148. package/dist/server/headers.d.ts +4 -1
  149. package/dist/server/headers.js +4 -1
  150. package/dist/server/http-conditional.d.ts +11 -0
  151. package/dist/server/http-conditional.js +10 -1
  152. package/dist/server/http-error-responses.d.ts +1 -1
  153. package/dist/server/image-optimization.d.ts +38 -0
  154. package/dist/server/image-optimization.js +94 -4
  155. package/dist/server/isr-cache.d.ts +10 -0
  156. package/dist/server/isr-cache.js +41 -6
  157. package/dist/server/metadata-route-response.js +11 -10
  158. package/dist/server/middleware-matcher.d.ts +2 -0
  159. package/dist/server/middleware-matcher.js +23 -2
  160. package/dist/server/middleware-path-to-regexp.js +1 -1
  161. package/dist/server/middleware-runtime.d.ts +13 -0
  162. package/dist/server/middleware-runtime.js +38 -25
  163. package/dist/server/middleware.d.ts +1 -1
  164. package/dist/server/middleware.js +3 -1
  165. package/dist/server/multi-stage.d.ts +11 -0
  166. package/dist/server/navigation-planner.js +1 -1
  167. package/dist/server/normalize-path.d.ts +0 -13
  168. package/dist/server/normalize-path.js +1 -34
  169. package/dist/server/open-redirect.d.ts +11 -4
  170. package/dist/server/open-redirect.js +11 -4
  171. package/dist/server/pages-api-route.d.ts +3 -2
  172. package/dist/server/pages-api-route.js +6 -5
  173. package/dist/server/pages-cache-tag.d.ts +12 -0
  174. package/dist/server/pages-cache-tag.js +19 -0
  175. package/dist/server/pages-client-assets.d.ts +2 -0
  176. package/dist/server/pages-data-route.d.ts +10 -0
  177. package/dist/server/pages-data-route.js +21 -3
  178. package/dist/server/pages-document-asset-props.d.ts +5 -1
  179. package/dist/server/pages-document-asset-props.js +13 -5
  180. package/dist/server/pages-document-splice.d.ts +19 -0
  181. package/dist/server/pages-document-splice.js +55 -0
  182. package/dist/server/pages-i18n.d.ts +12 -1
  183. package/dist/server/pages-i18n.js +18 -4
  184. package/dist/server/pages-node-compat.d.ts +16 -5
  185. package/dist/server/pages-node-compat.js +20 -12
  186. package/dist/server/pages-page-data.d.ts +32 -24
  187. package/dist/server/pages-page-data.js +51 -121
  188. package/dist/server/pages-page-handler.d.ts +0 -6
  189. package/dist/server/pages-page-handler.js +189 -127
  190. package/dist/server/pages-page-response.d.ts +12 -6
  191. package/dist/server/pages-page-response.js +42 -35
  192. package/dist/server/pages-request-pipeline.d.ts +10 -2
  193. package/dist/server/pages-request-pipeline.js +41 -22
  194. package/dist/server/pages-request-stage-entry.d.ts +6 -0
  195. package/dist/server/pages-request-stage-entry.js +75 -16
  196. package/dist/server/pages-response-stage-entry.js +4 -0
  197. package/dist/server/pages-revalidate.js +3 -3
  198. package/dist/server/pages-router-entry.js +5 -4
  199. package/dist/server/prerender-manifest.d.ts +3 -3
  200. package/dist/server/prerender-manifest.js +4 -3
  201. package/dist/server/prerender-work-unit-setup.js +4 -0
  202. package/dist/server/prod-server.d.ts +12 -0
  203. package/dist/server/prod-server.js +204 -74
  204. package/dist/server/proper-error.d.ts +4 -0
  205. package/dist/server/proper-error.js +31 -0
  206. package/dist/server/request-pipeline.d.ts +4 -1
  207. package/dist/server/request-pipeline.js +3 -2
  208. package/dist/server/revalidation-request.d.ts +1 -0
  209. package/dist/server/revalidation-request.js +1 -1
  210. package/dist/server/rsc-stream-hints.d.ts +1 -1
  211. package/dist/server/rsc-stream-hints.js +52 -5
  212. package/dist/server/seed-cache.d.ts +1 -0
  213. package/dist/server/seed-cache.js +5 -4
  214. package/dist/server/server-reference-loader.d.ts +4 -0
  215. package/dist/server/server-reference-loader.js +29 -0
  216. package/dist/server/socket-error-backstop.d.ts +9 -1
  217. package/dist/server/socket-error-backstop.js +46 -17
  218. package/dist/server/static-file-signal.d.ts +15 -4
  219. package/dist/server/static-file-signal.js +46 -12
  220. package/dist/server/worker-image-optimization.d.ts +34 -0
  221. package/dist/server/worker-image-optimization.js +99 -0
  222. package/dist/server/worker-stages.d.ts +1 -1
  223. package/dist/server/worker-stages.js +2 -2
  224. package/dist/server/worker-utils.d.ts +8 -3
  225. package/dist/server/worker-utils.js +12 -7
  226. package/dist/shims/app-router-scroll.js +4 -1
  227. package/dist/shims/app-router-tree-context.d.ts +5 -0
  228. package/dist/shims/app-router-tree-context.js +27 -0
  229. package/dist/shims/cache-callable-runtime.d.ts +4 -2
  230. package/dist/shims/cache-callable-runtime.js +21 -12
  231. package/dist/shims/cache-handler.js +1 -9
  232. package/dist/shims/cache-runtime.d.ts +6 -1
  233. package/dist/shims/cache-runtime.js +2 -1
  234. package/dist/shims/cache.d.ts +2 -2
  235. package/dist/shims/cache.js +40 -13
  236. package/dist/shims/cdn-cache.d.ts +8 -0
  237. package/dist/shims/cdn-cache.js +17 -1
  238. package/dist/shims/disable-smooth-scroll.d.ts +3 -0
  239. package/dist/shims/disable-smooth-scroll.js +36 -0
  240. package/dist/shims/document-placeholders.d.ts +19 -0
  241. package/dist/shims/document-placeholders.js +45 -0
  242. package/dist/shims/document.js +21 -5
  243. package/dist/shims/dynamic-preload-chunks.d.ts +1 -0
  244. package/dist/shims/dynamic-preload-chunks.js +13 -9
  245. package/dist/shims/dynamic.d.ts +1 -1
  246. package/dist/shims/dynamic.js +60 -8
  247. package/dist/shims/fetch-cache-state.d.ts +66 -0
  248. package/dist/shims/fetch-cache-state.js +92 -0
  249. package/dist/shims/fetch-cache.d.ts +3 -67
  250. package/dist/shims/fetch-cache.js +160 -125
  251. package/dist/shims/head.d.ts +10 -6
  252. package/dist/shims/head.js +16 -14
  253. package/dist/shims/headers.js +2 -2
  254. package/dist/shims/image.js +2 -1
  255. package/dist/shims/internal/hybrid-client-route-owner-direct.js +1 -1
  256. package/dist/shims/internal/hybrid-client-route-owner.js +1 -0
  257. package/dist/shims/internal/work-store-scope.d.ts +5 -0
  258. package/dist/shims/internal/work-store-scope.js +24 -0
  259. package/dist/shims/link-prefetch.js +5 -4
  260. package/dist/shims/link.js +2 -2
  261. package/dist/shims/navigation.js +34 -9
  262. package/dist/shims/request-context.d.ts +2 -0
  263. package/dist/shims/request-state-types.d.ts +2 -1
  264. package/dist/shims/router.js +21 -32
  265. package/dist/shims/server.d.ts +27 -4
  266. package/dist/shims/server.js +65 -9
  267. package/dist/shims/unified-request-context.d.ts +1 -1
  268. package/dist/shims/url-utils.d.ts +9 -0
  269. package/dist/shims/url-utils.js +15 -4
  270. package/dist/utils/client-runtime-metadata.js +1 -1
  271. package/dist/utils/domain-locale.js +1 -1
  272. package/dist/utils/hash.d.ts +7 -0
  273. package/dist/utils/hash.js +11 -1
  274. package/dist/utils/package-name.d.ts +6 -0
  275. package/dist/utils/package-name.js +12 -1
  276. package/dist/utils/plugin-rsc-version.d.ts +6 -0
  277. package/dist/utils/plugin-rsc-version.js +41 -0
  278. package/dist/utils/prerender-output-paths.js +15 -4
  279. package/dist/utils/public-file-path.d.ts +10 -2
  280. package/dist/utils/public-file-path.js +13 -9
  281. package/dist/utils/public-routes.js +2 -2
  282. package/dist/utils/react-version.d.ts +10 -0
  283. package/dist/utils/react-version.js +39 -16
  284. package/package.json +11 -7
  285. package/dist/build/nitro-route-rules.d.ts +0 -47
  286. package/dist/build/nitro-route-rules.js +0 -79
  287. package/dist/plugins/cache-flight-codec.d.ts +0 -19
  288. package/dist/plugins/cache-flight-codec.js +0 -68
@@ -0,0 +1,271 @@
1
+ import path from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { isCSSRequest } from "vite";
3
+ //#region src/plugins/cloudflare-dev-module-urls.ts
4
+ /**
5
+ * Serve Vite's module URLs before the Cloudflare plugin applies
6
+ * `assets.runWorkerFirst` during development.
7
+ *
8
+ * `vinext init` generates `runWorkerFirst: ["/*", "!/_next/static/*", ...]` so
9
+ * middleware runs for `public/` files. In dev, the Cloudflare plugin sends every
10
+ * request matching those patterns to the Worker before Vite's own middlewares
11
+ * run. That includes Vite's module URLs (`/@vite/client`, `/@id/*`, `/@fs/*`,
12
+ * source files such as `/app/globals.css`), which have no production
13
+ * equivalent, so the Worker answers them with the app's 404 page and nothing
14
+ * hydrates.
15
+ *
16
+ * This plugin registers a pre-middleware ahead of the Cloudflare plugin's and
17
+ * gives Vite's module-serving middlewares the first chance to handle each
18
+ * request. Vite decides what it serves: page navigations, non-GET requests, and
19
+ * unknown paths fall through to the Cloudflare plugin unchanged.
20
+ *
21
+ * The same change was made in the Cloudflare plugin itself in
22
+ * https://github.com/cloudflare/workers-sdk/pull/16281.
23
+ *
24
+ * See https://github.com/cloudflare/vinext/issues/4005.
25
+ */
26
+ /**
27
+ * Vite's internal middlewares that serve module requests (`/@vite/client`,
28
+ * `/@id/*`, JS and CSS source files) and `/@fs/*` paths, preceded by the one
29
+ * that strips a non-root `base` from the URL and the one that answers the HMR
30
+ * client's reconnect ping (`Accept: text/x-vite-ping`) with a 204 instead of
31
+ * the Worker rendering a page for it. If Vite renames them, none are found and
32
+ * every request falls through, which is the behavior without this plugin.
33
+ *
34
+ * `viteServePublicMiddleware` is deliberately excluded so that `public/` files
35
+ * reach the Worker and middleware, as they do in production. Without it, the
36
+ * transform middleware reports a public `.js` or `.css` file as an
37
+ * `ERR_LOAD_PUBLIC_URL` error, which is treated as a fall-through.
38
+ */
39
+ const VITE_MODULE_MIDDLEWARE_NAMES = /* @__PURE__ */ new Set([
40
+ "viteBaseMiddleware",
41
+ "viteHMRPingMiddleware",
42
+ "viteTransformMiddleware",
43
+ "viteServeRawFsMiddleware"
44
+ ]);
45
+ /**
46
+ * Vite's internal middleware that serves files under the project root. Vite
47
+ * gives imported assets root-relative URLs (`import logo from "./logo.svg"`
48
+ * and CSS `url(./bg.png)` both resolve to paths like `/app/logo.svg`), and only
49
+ * this middleware serves them. It also serves every other project file, and a
50
+ * Worker route can share its path with one (e.g. an `api/` directory and an
51
+ * `/api/*` route handler), so it only runs for referenced assets. See
52
+ * `isReferencedAsset`. Navigations to a referenced asset
53
+ * are served too: in production its URL is under `/_next/static/`, which never
54
+ * reaches the Worker.
55
+ */
56
+ const VITE_STATIC_MIDDLEWARE_NAME = "viteServeStaticMiddleware";
57
+ /**
58
+ * The Cloudflare plugin's middleware that sends requests matching
59
+ * `runWorkerFirst` to the Worker. It's only registered when `runWorkerFirst` is
60
+ * set, and without it Vite's middlewares already run in their usual order.
61
+ */
62
+ const CLOUDFLARE_PRE_MIDDLEWARE_NAME = "cloudflarePreMiddleware";
63
+ /**
64
+ * Creates the plugin that lets Vite serve its module URLs before the Cloudflare
65
+ * plugin's `runWorkerFirst` routing in dev.
66
+ *
67
+ * @param options - Plugin options
68
+ * @returns The Vite plugin
69
+ */
70
+ function createCloudflareDevModuleUrlsPlugin(options) {
71
+ return {
72
+ name: "vinext:cloudflare-dev-module-urls",
73
+ apply: "serve",
74
+ enforce: "pre",
75
+ configureServer(server) {
76
+ if (!options.isEnabled()) return;
77
+ server.middlewares.use(function vinextCloudflareDevModuleUrls(req, res, next) {
78
+ runViteModuleMiddlewares(server, req, res, next);
79
+ });
80
+ }
81
+ };
82
+ }
83
+ /**
84
+ * Runs Vite's module-serving middlewares in order, calling `next` once none of
85
+ * them handle the request.
86
+ *
87
+ * @param server - The Vite dev server whose middleware stack is searched
88
+ * @param req - The incoming request
89
+ * @param res - The outgoing response
90
+ * @param next - Called when no middleware handles the request, or with an error
91
+ */
92
+ function runViteModuleMiddlewares(server, req, res, next) {
93
+ const url = req.url;
94
+ if (req.method !== "GET" && req.method !== "HEAD" || !url?.startsWith(server.config.base)) {
95
+ next();
96
+ return;
97
+ }
98
+ const stack = server.middlewares.stack;
99
+ if (!stack.some((layer) => getHandleName(layer.handle) === CLOUDFLARE_PRE_MIDDLEWARE_NAME)) {
100
+ next();
101
+ return;
102
+ }
103
+ const handles = stack.flatMap((layer) => {
104
+ const handle = layer.handle;
105
+ if (typeof handle !== "function") return [];
106
+ if (VITE_MODULE_MIDDLEWARE_NAMES.has(handle.name)) return [handle];
107
+ if (handle.name === "viteServeStaticMiddleware") {
108
+ const serveStatic = handle;
109
+ return [(req, res, next) => isReferencedAsset(server, req.url) ? serveStatic(req, res, next) : next()];
110
+ }
111
+ return [];
112
+ });
113
+ let index = 0;
114
+ const tryNext = (error) => {
115
+ if (isPublicFileLoadError(error)) {
116
+ req.url = url;
117
+ next();
118
+ return;
119
+ }
120
+ if (error) {
121
+ next(error);
122
+ return;
123
+ }
124
+ const handle = handles[index++];
125
+ if (!handle) {
126
+ req.url = url;
127
+ next();
128
+ return;
129
+ }
130
+ try {
131
+ const result = handle(req, res, tryNext);
132
+ if (result instanceof Promise) result.catch(next);
133
+ } catch (e) {
134
+ next(e);
135
+ }
136
+ };
137
+ tryNext();
138
+ }
139
+ function getHandleName(handle) {
140
+ return typeof handle === "function" ? handle.name : void 0;
141
+ }
142
+ /**
143
+ * Whether the transform middleware rejected a request because it is for a
144
+ * `public/` file, which `viteServePublicMiddleware` would normally serve.
145
+ */
146
+ function isPublicFileLoadError(error) {
147
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ERR_LOAD_PUBLIC_URL";
148
+ }
149
+ /**
150
+ * Whether a request URL, with any `base` already stripped, is the URL of an
151
+ * asset that Vite gave to a module.
152
+ *
153
+ * The browser only learns an asset URL from a module Vite has transformed:
154
+ * - The asset's own JS module (`import logo from "./logo.svg"` or `?url`),
155
+ * whose code is `export default "<url>"`, possibly followed by a query or
156
+ * fragment (`?t=` after HMR). Only files Vite treats as assets and `?url`
157
+ * imports count: other modules, such as JSON or `?raw` and `?inline`
158
+ * imports, export the file's contents, which could look like a URL.
159
+ * - A JS module that uses `new URL("./logo.svg", import.meta.url)`, which Vite
160
+ * rewrites to `new URL("<url>", '' + import.meta.url)`.
161
+ * - A stylesheet whose `url()` or `image-set()` Vite resolved.
162
+ *
163
+ * The importers of the asset's file in the module graph cover the last two.
164
+ * Other project files can also be in the graph (Tailwind reports every file it
165
+ * scans as a dependency of the stylesheet), and other imports name the file
166
+ * with a query (`?raw` inlines its contents), but no module's code contains
167
+ * their bare URL in one of these forms, so they keep reaching the Worker.
168
+ *
169
+ * @param server - The Vite dev server whose module graphs are searched
170
+ * @param url - The request URL, with any `base` stripped
171
+ * @returns `true` if a module emitted the URL for the file
172
+ */
173
+ function isReferencedAsset(server, url) {
174
+ if (!url) return false;
175
+ const { pathname } = new URL(url, "http://localhost");
176
+ let decodedPathname;
177
+ try {
178
+ decodedPathname = decodeURI(pathname);
179
+ } catch {
180
+ return false;
181
+ }
182
+ const base = server.config.base;
183
+ let decodedBase = base;
184
+ try {
185
+ decodedBase = decodeURI(base);
186
+ } catch {}
187
+ const origin = server.config.server.origin?.replace(/\/+$/, "");
188
+ const urls = [...new Set([pathname, decodedPathname].flatMap((p) => {
189
+ const underBase = [base, decodedBase].map((b) => b + p.slice(1));
190
+ return [
191
+ p,
192
+ ...underBase,
193
+ ...origin ? underBase.map((u) => origin + u) : []
194
+ ];
195
+ }))];
196
+ const file = resolveStaticFile(server, decodedPathname);
197
+ const isAsset = server.config.assetsInclude(file);
198
+ for (const environment of Object.values(server.environments)) for (const module of environment.moduleGraph.getModulesByFile(file) ?? []) {
199
+ const code = module.transformResult?.code;
200
+ if (code && isAssetUrlModule(module.url, isAsset) && urls.some((u) => containsAssetUrl(code, u))) return true;
201
+ for (const importer of module.importers) {
202
+ const code = importer.transformResult?.code;
203
+ if (!code) continue;
204
+ const css = isCSSRequest(importer.url);
205
+ if (urls.some((u) => css ? containsCssUrl(code, u) : code.includes(`new URL("${u}", '' + import.meta.url)`))) return true;
206
+ }
207
+ }
208
+ return false;
209
+ }
210
+ /**
211
+ * Whether a module for the file exports the file's URL: a `?url` import, or an
212
+ * import of an asset without Vite's `raw` or `inline` queries, which export its
213
+ * contents.
214
+ */
215
+ function isAssetUrlModule(moduleUrl, isAsset) {
216
+ if (/[?&]url(?:&|$)/.test(moduleUrl)) return true;
217
+ return isAsset && !/[?&](?:raw|inline)(?:&|$)/.test(moduleUrl);
218
+ }
219
+ /**
220
+ * Whether an asset module's code exports `url` as a JS string, possibly with a
221
+ * query or fragment, as Vite's asset plugin emits it.
222
+ */
223
+ function containsAssetUrl(code, url) {
224
+ return [
225
+ `"${url}"`,
226
+ `"${url}?`,
227
+ `"${url}#`
228
+ ].some((literal) => code.includes(literal));
229
+ }
230
+ /**
231
+ * The file `viteServeStaticMiddleware` serves for a decoded pathname, applying
232
+ * `resolve.alias` the same way it does, so the file checked is the file served.
233
+ *
234
+ * @param server - The Vite dev server
235
+ * @param pathname - The decoded request pathname, with any `base` stripped
236
+ * @returns The absolute file path
237
+ */
238
+ function resolveStaticFile(server, pathname) {
239
+ const root = server.config.root;
240
+ for (const { find, replacement } of server.config.resolve.alias) if (typeof find === "string" ? pathname.startsWith(find) : find.test(pathname)) {
241
+ const redirected = pathname.replace(find, replacement);
242
+ return path.join(root, redirected.startsWith(root + "/") ? redirected.slice(root.length) : redirected);
243
+ }
244
+ return path.join(root, pathname);
245
+ }
246
+ /**
247
+ * Whether stylesheet code contains `url` as a resolved `url()` or `image-set()`
248
+ * reference, the only places Vite rewrites asset URLs in CSS. The code may be
249
+ * the CSS itself or a JS string of it, and the URL may be quoted and may keep a
250
+ * query or fragment from the source.
251
+ *
252
+ * @param code - Transformed stylesheet code
253
+ * @param url - The URL path to look for
254
+ * @returns `true` if the URL appears as a CSS URL
255
+ */
256
+ function containsCssUrl(code, url) {
257
+ for (let index = code.indexOf(url); index !== -1; index = code.indexOf(url, index + 1)) {
258
+ const after = code[index + url.length];
259
+ if (after === void 0 || !/[)"',?#\\\s]/.test(after)) continue;
260
+ const start = Math.max(0, index - 32);
261
+ const before = code.slice(start, index);
262
+ const urlFunction = /(^|[^\w\-\u0080-\uffff])url\(\s*\\?["']?$/.exec(before);
263
+ if (urlFunction && (urlFunction[1] !== "" || start === 0)) return true;
264
+ if (!/["']$/.test(before)) continue;
265
+ const imageSet = code.lastIndexOf("image-set(", index);
266
+ if (imageSet !== -1 && !/[;{}]/.test(code.slice(imageSet, index))) return true;
267
+ }
268
+ return false;
269
+ }
270
+ //#endregion
271
+ export { VITE_MODULE_MIDDLEWARE_NAMES, VITE_STATIC_MIDDLEWARE_NAME, createCloudflareDevModuleUrlsPlugin };
@@ -1,4 +1,4 @@
1
- import { parseAst } from "vite";
1
+ import { parseProgram } from "./ast-utils.js";
2
2
  import MagicString from "magic-string";
3
3
  //#region src/plugins/commonjs-esm-facade.ts
4
4
  const EXPORT_FACADE_START = "/* [vite-plugin-commonjs] export-statement-S */";
@@ -9,7 +9,7 @@ function hasEsmExports(code) {
9
9
  if (!EXPORT_KEYWORD_RE.test(code)) return false;
10
10
  let ast;
11
11
  try {
12
- ast = parseAst(code);
12
+ ast = parseProgram(code);
13
13
  } catch {
14
14
  return false;
15
15
  }
@@ -1,32 +1,25 @@
1
- import { SCRIPT_MODULE_ID_RE, scriptParserLanguage } from "./ast-utils.js";
1
+ import { LEADING_TRIVIA_RE, SCRIPT_MODULE_ID_RE, hasImportAttributes, parseModuleRecord, scriptParserLanguage } from "./ast-utils.js";
2
2
  import { magicStringTransformResult } from "./transform-result.js";
3
- import { parseAst } from "vite";
4
3
  import MagicString from "magic-string";
5
4
  //#region src/plugins/css-module-imports.ts
6
5
  const CSS_MODULE_RE = /\.module\.(?:css|scss|sass)$/i;
7
6
  const CSS_MODULE_HINT_RE = /\.module\.(?:css|scss|sass)/i;
8
7
  const MDX_RE = /\.mdx$/i;
9
8
  function rewriteCssModuleNamespaceImports(code, lang = "js") {
10
- let ast;
11
- try {
12
- ast = parseAst(code, { lang });
13
- } catch {
14
- return null;
15
- }
9
+ const record = parseModuleRecord(code, lang);
10
+ if (!record) return null;
16
11
  let output = null;
17
- for (const statement of ast.body) {
18
- if (statement.type !== "ImportDeclaration") continue;
19
- if (statement.importKind === "type") continue;
20
- if (typeof statement.source?.value !== "string") continue;
21
- if (!CSS_MODULE_RE.test(statement.source.value)) continue;
22
- if (statement.attributes && statement.attributes.length > 0) continue;
23
- if (statement.specifiers?.length !== 1) continue;
24
- const specifier = statement.specifiers[0];
25
- if (specifier.type !== "ImportNamespaceSpecifier") continue;
26
- if (typeof specifier.start !== "number" || typeof specifier.end !== "number") continue;
27
- if (typeof specifier.local?.name !== "string") continue;
12
+ for (const statement of record.staticImports) {
13
+ if (!CSS_MODULE_RE.test(statement.moduleRequest.value)) continue;
14
+ if (hasImportAttributes(code, statement.moduleRequest.end, statement.end)) continue;
15
+ if (statement.entries.length !== 1) continue;
16
+ const [entry] = statement.entries;
17
+ if (entry.isType || entry.importName.kind !== "NamespaceObject") continue;
18
+ const afterImport = statement.start + 6;
19
+ const starIndex = afterImport + (LEADING_TRIVIA_RE.exec(code.slice(afterImport, entry.localName.start))?.[0].length ?? 0);
20
+ if (code[starIndex] !== "*") continue;
28
21
  output ??= new MagicString(code);
29
- output.overwrite(specifier.start, specifier.end, specifier.local.name);
22
+ output.overwrite(starIndex, entry.localName.end, entry.localName.value);
30
23
  }
31
24
  if (!output) return null;
32
25
  return magicStringTransformResult(output, { hires: true });
@@ -7,5 +7,5 @@ type TransformResult = {
7
7
  };
8
8
  type ResolveDynamicImport = (specifier: string, importer: string) => Promise<string | null>;
9
9
  export declare function transformNextDynamicPreloadMetadata(code: string, id: string, root: string, resolveDynamicImport: ResolveDynamicImport): Promise<TransformResult | null>;
10
- export declare function createDynamicPreloadMetadataPlugin(): Plugin;
10
+ export declare function createDynamicPreloadMetadataPlugin(getTranspiledPackages: () => readonly string[]): Plugin;
11
11
  //#endregion
@@ -1,10 +1,10 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
- import { collectBindingNames, forEachAstChild, stringLiteralValue, walkAst } from "./ast-utils.js";
2
+ import { collectBindingNames, forEachAstChild, parseProgram, stringLiteralValue, walkAst } from "./ast-utils.js";
3
3
  import { hasTrailingComma } from "../utils/has-trailing-comma.js";
4
4
  import { magicStringTransformResult } from "./transform-result.js";
5
5
  import { stripViteModuleQuery } from "../utils/path.js";
6
- import { relativeWithinRoot, tryRealpathSync } from "../build/ssr-manifest.js";
7
- import { parseAst } from "vite";
6
+ import { isForeignNodeModule } from "../utils/package-name.js";
7
+ import { relativeToRoot, relativeWithinRoot, tryRealpathSync } from "../build/ssr-manifest.js";
8
8
  import MagicString from "magic-string";
9
9
  //#region src/plugins/dynamic-preload-metadata.ts
10
10
  function isNextDynamicSource(source) {
@@ -204,7 +204,7 @@ function toManifestModuleId(root, resolvedId) {
204
204
  const relative = relativeWithinRoot(rootCandidate, moduleCandidate);
205
205
  if (relative) return relative;
206
206
  }
207
- return null;
207
+ return relativeToRoot(root, cleaned) || null;
208
208
  }
209
209
  async function resolveManifestModuleIds(specifiers, importer, root, resolveDynamicImport) {
210
210
  const resolvedIds = [];
@@ -238,7 +238,7 @@ async function transformNextDynamicPreloadMetadata(code, id, root, resolveDynami
238
238
  if (!code.includes("next/dynamic")) return null;
239
239
  let ast;
240
240
  try {
241
- ast = parseAst(code);
241
+ ast = parseProgram(code);
242
242
  } catch (error) {
243
243
  if (typeof process !== "undefined" && process.env?.DEBUG?.includes("vinext")) console.debug(`[vinext] dynamic-preload-metadata: failed to parse ${id}:`, error);
244
244
  return null;
@@ -262,24 +262,24 @@ async function transformNextDynamicPreloadMetadata(code, id, root, resolveDynami
262
262
  if (!changed) return null;
263
263
  return magicStringTransformResult(output);
264
264
  }
265
- function createDynamicPreloadMetadataPlugin() {
265
+ function createDynamicPreloadMetadataPlugin(getTranspiledPackages) {
266
266
  let root = toSlash(process.cwd());
267
+ let isBuild = false;
267
268
  return {
268
269
  name: "vinext:dynamic-preload-metadata",
269
270
  configResolved(config) {
270
271
  root = config.root;
272
+ isBuild = config.command === "build";
271
273
  },
272
274
  transform: {
273
275
  filter: {
274
- id: {
275
- include: /\.(tsx?|jsx?|mjs)$/,
276
- exclude: /node_modules/
277
- },
276
+ id: /\.(tsx?|jsx?|mjs)$/,
278
277
  code: "next/dynamic"
279
278
  },
280
279
  async handler(code, id) {
281
- if (id.includes("node_modules") || id.startsWith("\0")) return null;
280
+ if (id.startsWith("\0")) return null;
282
281
  if (!/\.(tsx?|jsx?|mjs)$/.test(id)) return null;
282
+ if (id.includes("node_modules") && (!isBuild || isForeignNodeModule(id, getTranspiledPackages()))) return null;
283
283
  const result = await transformNextDynamicPreloadMetadata(code, id, root, async (specifier, importer) => {
284
284
  return (await this.resolve(specifier, importer, { skipSelf: true }))?.id ?? null;
285
285
  });
@@ -1,13 +1,12 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
2
  import { escapeRegExp } from "../utils/regex.js";
3
- import { DYNAMIC_IMPORT_PRESCAN, SCRIPT_MODULE_ID_RE, scriptParserLanguage, walkAst } from "./ast-utils.js";
3
+ import { DYNAMIC_IMPORT_PRESCAN, SCRIPT_MODULE_ID_RE, parseProgram, scriptParserLanguage, walkAst } from "./ast-utils.js";
4
4
  import { isUnknownRecord } from "../utils/record.js";
5
5
  import { magicStringTransformResult } from "./transform-result.js";
6
6
  import { NODE_MODULES_PATH_RE } from "../utils/path.js";
7
7
  import { createTransformCache } from "./transform-cache.js";
8
8
  import { createRequire } from "node:module";
9
9
  import fs from "node:fs";
10
- import { parseAst } from "vite";
11
10
  import MagicString from "magic-string";
12
11
  //#region src/plugins/extensionless-dynamic-import.ts
13
12
  const MODULE_EXTENSIONS = [
@@ -63,7 +62,7 @@ function transformExtensionlessImports(code, id, config) {
63
62
  const lang = scriptParserLanguage(id);
64
63
  let ast;
65
64
  try {
66
- ast = parseAst(code, { lang });
65
+ ast = parseProgram(code, { lang });
67
66
  } catch {
68
67
  return null;
69
68
  }
@@ -31,7 +31,7 @@ export declare const RESOLVED_VIRTUAL_GOOGLE_FONTS: string;
31
31
  export declare function _rewriteCachedFontCssToServedUrls(css: string, assetsDir?: string): string;
32
32
  /**
33
33
  * Safely parse a static JS object literal string into a plain object.
34
- * Uses Vite's parseAst (Rollup/acorn) so no code is ever evaluated.
34
+ * Uses Vite's bundled oxc parser so no code is ever evaluated.
35
35
  * Returns null if the expression contains anything dynamic (function calls,
36
36
  * template literals, identifiers, computed properties, etc.).
37
37
  *
@@ -1,5 +1,6 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
2
  import { escapeRegExp } from "../utils/regex.js";
3
+ import { parseProgram } from "./ast-utils.js";
3
4
  import { lastSignificantChar } from "../utils/has-trailing-comma.js";
4
5
  import { magicStringTransformResult } from "./transform-result.js";
5
6
  import { buildFallbackFontFace, getFallbackFontOverrideMetrics } from "../build/google-fonts/fallback-metrics.js";
@@ -10,7 +11,6 @@ import { findFontFilesInCss } from "../build/google-fonts/find-font-files-in-css
10
11
  import { ASSET_PREFIX_URL_DIR } from "../utils/asset-prefix.js";
11
12
  import { CONTENT_TYPES } from "../server/static-file-cache.js";
12
13
  import fs from "node:fs";
13
- import { parseAst } from "vite";
14
14
  import MagicString from "magic-string";
15
15
  //#region src/plugins/fonts.ts
16
16
  /**
@@ -127,7 +127,7 @@ function _rewriteCachedFontCssToServedUrls(css, assetsDir = DEFAULT_ASSETS_DIR)
127
127
  const DEFAULT_ASSETS_DIR = ASSET_PREFIX_URL_DIR;
128
128
  /**
129
129
  * Safely parse a static JS object literal string into a plain object.
130
- * Uses Vite's parseAst (Rollup/acorn) so no code is ever evaluated.
130
+ * Uses Vite's bundled oxc parser so no code is ever evaluated.
131
131
  * Returns null if the expression contains anything dynamic (function calls,
132
132
  * template literals, identifiers, computed properties, etc.).
133
133
  *
@@ -137,7 +137,7 @@ const DEFAULT_ASSETS_DIR = ASSET_PREFIX_URL_DIR;
137
137
  function parseStaticObjectLiteral(objectStr) {
138
138
  let ast;
139
139
  try {
140
- ast = parseAst(`(${objectStr})`);
140
+ ast = parseProgram(`(${objectStr})`);
141
141
  } catch {
142
142
  return null;
143
143
  }
@@ -11,7 +11,7 @@ import { Plugin } from "vite";
11
11
  * identifiers, falls through to the AST pass.
12
12
  */
13
13
  declare function mayContainVeryDynamicRequest(code: string): boolean;
14
- declare function transformVeryDynamicRequests(code: string, id: string): MagicStringTransformResult | null;
14
+ declare function transformVeryDynamicRequests(code: string, id: string): MagicStringTransformResult<import("magic-string").SourceMap> | null;
15
15
  export declare function createIgnoreDynamicRequestsPlugin(getTranspiledPackages?: () => readonly string[]): Plugin;
16
16
  export declare const _transformVeryDynamicRequests: typeof transformVeryDynamicRequests;
17
17
  export declare const _mayContainVeryDynamicRequest: typeof mayContainVeryDynamicRequest;
@@ -1,11 +1,11 @@
1
- import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
- import { DYNAMIC_IMPORT_PRESCAN, SCRIPT_MODULE_ID_RE, collectBindingNames, forEachAstChild, isIdentifierNamed, mayContainDynamicImport, scriptParserLanguage, stringLiteralValue, unwrapExpression } from "./ast-utils.js";
1
+ import path from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { DYNAMIC_IMPORT_PRESCAN, SCRIPT_MODULE_ID_RE, collectBindingNames, forEachAstChild, isIdentifierNamed, mayContainDynamicImport, parseProgram, scriptParserLanguage, stringLiteralValue, unwrapExpression } from "./ast-utils.js";
3
3
  import { magicStringTransformResult, omitUnusedBuildSourcemap } from "./transform-result.js";
4
4
  import { stripViteModuleQuery } from "../utils/path.js";
5
+ import { isForeignNodeModule } from "../utils/package-name.js";
5
6
  import { collectDirectScopeBindings, collectLoopScopeBindings, collectSwitchScopeBindings, collectVarScopeBindings, hasAstBinding, isFunctionNode } from "./ast-scope.js";
6
7
  import { createTransformCache } from "./transform-cache.js";
7
8
  import { fileURLToPath } from "node:url";
8
- import { parseAst } from "vite";
9
9
  import MagicString from "magic-string";
10
10
  //#region src/plugins/ignore-dynamic-requests.ts
11
11
  const DYNAMIC_REQUEST_ERROR = "Cannot find module as expression is too dynamic";
@@ -410,7 +410,7 @@ function transformVeryDynamicRequests(code, id) {
410
410
  const lang = scriptParserLanguage(id) ?? "js";
411
411
  let ast;
412
412
  try {
413
- ast = parseAst(code, { lang });
413
+ ast = parseProgram(code, { lang });
414
414
  } catch {
415
415
  return null;
416
416
  }
@@ -543,9 +543,7 @@ function createIgnoreDynamicRequestsPlugin(getTranspiledPackages = () => []) {
543
543
  }
544
544
  function shouldTransformVeryDynamicRequests(environment, id, transpiledPackages) {
545
545
  if (environment.config.consumer === "server") return true;
546
- const normalizedId = toSlash(id);
547
- if (!normalizedId.includes("/node_modules/")) return false;
548
- return !transpiledPackages.some((packageName) => normalizedId.includes(`/node_modules/${packageName}/`));
546
+ return isForeignNodeModule(id, transpiledPackages);
549
547
  }
550
548
  const _transformVeryDynamicRequests = transformVeryDynamicRequests;
551
549
  const _mayContainVeryDynamicRequest = mayContainVeryDynamicRequest;
@@ -1,11 +1,10 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
- import { SCRIPT_MODULE_ID_RE, collectBindingNames, forEachAstChild, isIdentifierNamed, scriptParserLanguage } from "./ast-utils.js";
2
+ import { SCRIPT_MODULE_ID_RE, collectBindingNames, forEachAstChild, isIdentifierNamed, parseProgram, scriptParserLanguage } from "./ast-utils.js";
3
3
  import { magicStringTransformResult, omitUnusedBuildSourcemap } from "./transform-result.js";
4
4
  import { canonicalizeFilePath, isPathInsideOrEqual, stripViteModuleQuery } from "../utils/path.js";
5
5
  import { VIRTUAL_MODULE_ID_RE } from "../utils/virtual-module.js";
6
6
  import fs from "node:fs";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
- import { parseAst } from "vite";
9
8
  import { randomUUID } from "node:crypto";
10
9
  import MagicString from "magic-string";
11
10
  //#region src/plugins/import-meta-url.ts
@@ -254,14 +253,14 @@ function finalizeEmittedModuleIdentity(code, emittedIdentitySentinels, fileName)
254
253
  function rewriteModuleIdentity(code, options) {
255
254
  let ast;
256
255
  try {
257
- ast = parseAst(code, {
256
+ ast = parseProgram(code, {
258
257
  lang: scriptParserLanguage(options.id) ?? "jsx",
259
258
  sourceType: options.cjsGlobalInitializers ? "commonjs" : void 0
260
259
  });
261
260
  } catch {
262
261
  if (!options.cjsGlobalInitializers) return null;
263
262
  try {
264
- ast = parseAst(code, { lang: scriptParserLanguage(options.id) ?? "jsx" });
263
+ ast = parseProgram(code, { lang: scriptParserLanguage(options.id) ?? "jsx" });
265
264
  } catch {
266
265
  return null;
267
266
  }
@@ -1,10 +1,11 @@
1
+ import { parseProgram } from "./ast-utils.js";
1
2
  import { magicStringTransformResult } from "./transform-result.js";
2
3
  import { stripViteModuleQuery } from "../utils/path.js";
3
- import { normalizePath, parseAst } from "vite";
4
+ import { normalizePath } from "vite";
4
5
  import MagicString from "magic-string";
5
6
  //#region src/plugins/instrumentation-client.ts
6
7
  function insertionPositionAfterDirectives(code) {
7
- const ast = parseAst(code);
8
+ const ast = parseProgram(code);
8
9
  let insertPos = 0;
9
10
  for (const node of ast.body) {
10
11
  if (node.type !== "ExpressionStatement" || node.directive === void 0) break;
@@ -1,9 +1,8 @@
1
- import { getAstName, scriptParserLanguage } from "./ast-utils.js";
1
+ import { getAstName, parseProgram, scriptParserLanguage } from "./ast-utils.js";
2
2
  import { createMiddlewareMissingExportError } from "../server/middleware-runtime.js";
3
- import { parseAst } from "vite";
4
3
  //#region src/plugins/middleware-export-validation.ts
5
4
  function hasValidMiddlewareModuleExport(source, id, isProxy) {
6
- const ast = parseAst(source, { lang: scriptParserLanguage(id) ?? "jsx" });
5
+ const ast = parseProgram(source, { lang: scriptParserLanguage(id) ?? "jsx" });
7
6
  const expectedExport = isProxy ? "proxy" : "middleware";
8
7
  for (const statement of ast.body) {
9
8
  if (statement.type === "ExportDefaultDeclaration") return true;
@@ -29,10 +29,11 @@ import { Plugin } from "vite";
29
29
  * to the tainted set. This propagates the taint along the import graph
30
30
  * synchronously, before plugin-rsc's `order: "pre"` validate-imports
31
31
  * handler sees the next `server-only` request.
32
- * 3. When a tainted module imports `server-only` in a non-RSC environment,
33
- * short-circuit to the no-op shim path so plugin-rsc's filter (which
34
- * matches the bare `^server-only$` specifier) never fires for that
35
- * import.
32
+ * 3. When a tainted module imports `server-only` in a non-RSC server
33
+ * environment, short-circuit to the no-op shim path so plugin-rsc's
34
+ * filter (which matches the bare `^server-only$` specifier) never fires
35
+ * for that import. Browser environments are skipped entirely, so the
36
+ * client `server-only` validators still see every import there.
36
37
  *
37
38
  * The taint set is scoped to the middleware chain only — `server-only`
38
39
  * imports from anywhere else (including client component code traversing
@@ -1,5 +1,6 @@
1
1
  import { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
2
  import { stripViteModuleQuery } from "../utils/path.js";
3
+ import { isServerEnvironment } from "./environment.js";
3
4
  //#region src/plugins/middleware-server-only.ts
4
5
  /**
5
6
  * Allow `import 'server-only'` from neutral server targets (and any module
@@ -30,10 +31,11 @@ import { stripViteModuleQuery } from "../utils/path.js";
30
31
  * to the tainted set. This propagates the taint along the import graph
31
32
  * synchronously, before plugin-rsc's `order: "pre"` validate-imports
32
33
  * handler sees the next `server-only` request.
33
- * 3. When a tainted module imports `server-only` in a non-RSC environment,
34
- * short-circuit to the no-op shim path so plugin-rsc's filter (which
35
- * matches the bare `^server-only$` specifier) never fires for that
36
- * import.
34
+ * 3. When a tainted module imports `server-only` in a non-RSC server
35
+ * environment, short-circuit to the no-op shim path so plugin-rsc's
36
+ * filter (which matches the bare `^server-only$` specifier) never fires
37
+ * for that import. Browser environments are skipped entirely, so the
38
+ * client `server-only` validators still see every import there.
37
39
  *
38
40
  * The taint set is scoped to the middleware chain only — `server-only`
39
41
  * imports from anywhere else (including client component code traversing
@@ -71,7 +73,8 @@ function createMiddlewareServerOnlyPlugin(options) {
71
73
  resolveId: {
72
74
  order: "pre",
73
75
  async handler(id, importer, opts) {
74
- if (this.environment?.name === "rsc") return;
76
+ const environment = this.environment;
77
+ if (!environment || !isServerEnvironment(environment) || environment.name === "rsc") return;
75
78
  if (!importer) return;
76
79
  if (!isTainted(importer) && !options.isNeutralServerModule?.(canonicalizeId(importer))) return;
77
80
  if (id === "server-only") return {
@@ -1,11 +1,10 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
- import { forEachAstChild, getAstName, staticStringValue } from "./ast-utils.js";
2
+ import { forEachAstChild, getAstName, parseProgram, staticStringValue } from "./ast-utils.js";
3
3
  import { magicStringTransformResult, omitUnusedBuildSourcemap } from "./transform-result.js";
4
4
  import { isFunctionNode } from "./ast-scope.js";
5
5
  import { createTransformCache } from "./transform-cache.js";
6
6
  import { createRequire } from "node:module";
7
7
  import fs from "node:fs";
8
- import { parseAst } from "vite";
9
8
  import MagicString from "magic-string";
10
9
  //#region src/plugins/og-harfbuzz.ts
11
10
  /**
@@ -220,7 +219,7 @@ function patchHarfbuzzBundle(code, id, isBuild, callbackModuleDir, error) {
220
219
  const ogEntry = toSlash(id.split("?", 1)[0]);
221
220
  const isWorkerd = ogEntry.endsWith("/index.edge.js");
222
221
  const fail = (reason) => error(`[vinext] Unsupported @vercel/og HarfBuzz bundle in ${ogEntry}: ${reason}. vinext must be updated to support this @vercel/og version.`);
223
- const sites = findHarfbuzzPatchSites(parseAst(code, { lang: "js" }));
222
+ const sites = findHarfbuzzPatchSites(parseProgram(code, { lang: "js" }));
224
223
  if (typeof sites === "string") return fail(sites);
225
224
  const output = new MagicString(code);
226
225
  for (const flag of sites.environmentFlags) output.overwrite(flag.start, flag.end, "false");