vinext 1.2.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 (110) hide show
  1. package/README.md +1 -1
  2. package/dist/build/output-root-externals.d.ts +21 -0
  3. package/dist/build/output-root-externals.js +40 -0
  4. package/dist/build/prerender-paths.js +1 -1
  5. package/dist/build/prerender.js +1 -1
  6. package/dist/check.js +5 -6
  7. package/dist/cli-dev-config.js +3 -3
  8. package/dist/cli.js +1 -1
  9. package/dist/config/config-matchers.js +12 -7
  10. package/dist/index.js +113 -94
  11. package/dist/init.d.ts +1 -1
  12. package/dist/init.js +86 -6
  13. package/dist/plugins/ast-utils.d.ts +53 -2
  14. package/dist/plugins/ast-utils.js +90 -2
  15. package/dist/plugins/cloudflare-dev-module-urls.d.ts +41 -0
  16. package/dist/plugins/cloudflare-dev-module-urls.js +271 -0
  17. package/dist/plugins/commonjs-esm-facade.js +2 -2
  18. package/dist/plugins/css-module-imports.js +13 -20
  19. package/dist/plugins/dynamic-preload-metadata.js +2 -3
  20. package/dist/plugins/extensionless-dynamic-import.js +2 -3
  21. package/dist/plugins/fonts.d.ts +1 -1
  22. package/dist/plugins/fonts.js +3 -3
  23. package/dist/plugins/ignore-dynamic-requests.js +2 -3
  24. package/dist/plugins/import-meta-url.js +3 -4
  25. package/dist/plugins/instrumentation-client.js +3 -2
  26. package/dist/plugins/middleware-export-validation.js +2 -3
  27. package/dist/plugins/og-harfbuzz.js +2 -3
  28. package/dist/plugins/optimize-imports.js +3 -4
  29. package/dist/plugins/pages-node-externals.js +2 -3
  30. package/dist/plugins/remove-console.js +2 -18
  31. package/dist/plugins/require-condition-resolution.js +3 -3
  32. package/dist/plugins/require-context.js +2 -3
  33. package/dist/plugins/strip-server-exports.js +3 -4
  34. package/dist/plugins/styled-jsx.js +2 -3
  35. package/dist/plugins/use-cache-callable.d.ts +21 -2
  36. package/dist/plugins/use-cache-callable.js +76 -33
  37. package/dist/plugins/worker-image-imports.js +30 -33
  38. package/dist/plugins/worker-use-server.js +38 -14
  39. package/dist/server/api-handler.js +1 -1
  40. package/dist/server/app-action-forwarding.js +2 -2
  41. package/dist/server/app-browser-entry.js +3 -3
  42. package/dist/server/app-browser-interception-context.js +1 -1
  43. package/dist/server/app-browser-prefetch-response.js +2 -2
  44. package/dist/server/app-browser-state.js +1 -1
  45. package/dist/server/app-browser-supplemental-refresh.js +1 -1
  46. package/dist/server/app-optimistic-routing.js +1 -1
  47. package/dist/server/app-page-dispatch.js +1 -1
  48. package/dist/server/app-page-render.js +1 -1
  49. package/dist/server/app-pages-bridge.js +1 -1
  50. package/dist/server/app-prerender-endpoints.js +1 -1
  51. package/dist/server/app-render-abort-error.d.ts +19 -0
  52. package/dist/server/app-render-abort-error.js +31 -1
  53. package/dist/server/app-request-stage-independent-entry.js +5 -5
  54. package/dist/server/app-response-stage-entry.js +2 -2
  55. package/dist/server/app-route-handler-runtime.js +1 -1
  56. package/dist/server/app-router-entry.js +5 -5
  57. package/dist/server/app-rsc-cache-busting.d.ts +16 -0
  58. package/dist/server/app-rsc-cache-busting.js +29 -12
  59. package/dist/server/app-rsc-handler.js +5 -5
  60. package/dist/server/app-rsc-request-normalization.js +3 -3
  61. package/dist/server/app-rsc-response-stage.js +2 -2
  62. package/dist/server/app-server-action-execution.js +1 -1
  63. package/dist/server/app-ssr-entry.js +5 -4
  64. package/dist/server/app-visited-response-cache.js +2 -2
  65. package/dist/server/config-headers.js +1 -1
  66. package/dist/server/defer-until-stream-consumed.d.ts +2 -1
  67. package/dist/server/defer-until-stream-consumed.js +3 -1
  68. package/dist/server/dev-server.js +1 -1
  69. package/dist/server/image-optimization.js +1 -0
  70. package/dist/server/metadata-route-response.js +2 -2
  71. package/dist/server/middleware-path-to-regexp.js +1 -1
  72. package/dist/server/middleware-runtime.js +5 -5
  73. package/dist/server/navigation-planner.js +1 -1
  74. package/dist/server/open-redirect.d.ts +11 -4
  75. package/dist/server/open-redirect.js +11 -4
  76. package/dist/server/pages-api-route.js +2 -2
  77. package/dist/server/pages-data-route.js +2 -1
  78. package/dist/server/pages-page-data.js +1 -1
  79. package/dist/server/pages-page-handler.js +1 -1
  80. package/dist/server/pages-page-response.js +1 -1
  81. package/dist/server/pages-request-pipeline.js +5 -5
  82. package/dist/server/pages-request-stage-entry.js +4 -4
  83. package/dist/server/pages-revalidate.js +2 -2
  84. package/dist/server/pages-router-entry.js +1 -1
  85. package/dist/server/prod-server.js +5 -5
  86. package/dist/server/rsc-stream-hints.d.ts +1 -1
  87. package/dist/server/rsc-stream-hints.js +21 -3
  88. package/dist/server/worker-image-optimization.js +19 -6
  89. package/dist/shims/head.js +1 -1
  90. package/dist/shims/headers.js +2 -2
  91. package/dist/shims/internal/hybrid-client-route-owner-direct.js +1 -1
  92. package/dist/shims/internal/hybrid-client-route-owner.js +1 -0
  93. package/dist/shims/link-prefetch.js +5 -4
  94. package/dist/shims/link.js +2 -2
  95. package/dist/shims/navigation.js +4 -5
  96. package/dist/shims/router.js +9 -12
  97. package/dist/shims/server.d.ts +11 -4
  98. package/dist/shims/server.js +41 -5
  99. package/dist/shims/url-utils.d.ts +7 -0
  100. package/dist/shims/url-utils.js +12 -3
  101. package/dist/utils/domain-locale.js +1 -1
  102. package/dist/utils/plugin-rsc-version.d.ts +2 -0
  103. package/dist/utils/plugin-rsc-version.js +28 -2
  104. package/dist/utils/react-version.d.ts +7 -0
  105. package/dist/utils/react-version.js +39 -16
  106. package/package.json +6 -6
  107. package/dist/build/nitro-route-rules.d.ts +0 -47
  108. package/dist/build/nitro-route-rules.js +0 -79
  109. package/dist/plugins/cache-flight-codec.d.ts +0 -19
  110. package/dist/plugins/cache-flight-codec.js +0 -68
@@ -1,4 +1,4 @@
1
- import { ESTree } from "vite";
1
+ import { ESTree, ParseResult, ParserOptions } from "vite";
2
2
  //#region src/plugins/ast-utils.d.ts
3
3
  export type ScriptParserLanguage = "js" | "jsx" | "ts" | "tsx";
4
4
  export declare const SCRIPT_MODULE_ID_RE: RegExp;
@@ -8,7 +8,7 @@ export declare const SCRIPT_MODULE_ID_RE: RegExp;
8
8
  * Static imports — `import x from "..."`, `import { ... } from "..."`,
9
9
  * `import "..."` — never place a `(` (nor a comment leading to one) immediately
10
10
  * after the `import` keyword. Plugins that act only on dynamic `import(...)` use
11
- * this to skip `parseAst` for the overwhelming majority of modules in a large
11
+ * this to skip parsing for the overwhelming majority of modules in a large
12
12
  * app: at ~5k routes, where almost every module is a static-import-only page,
13
13
  * it removes most of the build's AST-parse/GC cost. This is a deliberate,
14
14
  * measured performance filter — keep it a regex, never a parse.
@@ -36,6 +36,57 @@ export declare function mayContainDynamicImport(code: string): boolean;
36
36
  * necessarily been lowered.
37
37
  */
38
38
  export declare function scriptParserLanguage(id: string): ScriptParserLanguage | null;
39
+ /** The import/export record oxc builds alongside the AST. */
40
+ export type ModuleRecord = ParseResult["module"];
41
+ /**
42
+ * Parse `code` into an ESTree program, throwing on syntax errors.
43
+ *
44
+ * Replaces Vite's deprecated `parseAst` with the same defaults and contract.
45
+ * Callers that only need import/export declarations should use
46
+ * {@link parseModuleRecord}, which skips building the JS AST.
47
+ */
48
+ export declare function parseProgram(code: string, options?: ParserOptions): ESTree.Program;
49
+ /** Async {@link parseProgram}; replaces Vite's deprecated `parseAstAsync`. */
50
+ export declare function parseProgramAsync(code: string, options?: ParserOptions): Promise<ESTree.Program>;
51
+ /**
52
+ * Parse `code` and return only its static import/export and dynamic import
53
+ * record, or `null` when it has syntax errors.
54
+ *
55
+ * Reading the record never deserializes the JS AST, which is most of the cost
56
+ * of a parse (about 4x cheaper than {@link parseProgram} on large modules).
57
+ * The record omits import attributes; see {@link hasImportAttributes}.
58
+ */
59
+ export declare function parseModuleRecord(code: string, lang: ParserOptions["lang"]): ModuleRecord | null;
60
+ /**
61
+ * One whitespace character or comment. Each alternative can only match one
62
+ * way (a block comment stops at the first `*\/`, a line comment runs to the
63
+ * line end), so repeating it cannot backtrack exponentially.
64
+ */
65
+ export declare const TRIVIA_PATTERN: string;
66
+ /** Leading whitespace and comments. */
67
+ export declare const LEADING_TRIVIA_RE: RegExp;
68
+ /**
69
+ * Whether the static import/export statement ending at `statementEnd` has
70
+ * `with { ... }` (or legacy `assert { ... }`) attributes after its source
71
+ * string, which ends at `sourceEnd`. The module record does not report
72
+ * attributes.
73
+ */
74
+ export declare function hasImportAttributes(code: string, sourceEnd: number, statementEnd: number): boolean;
75
+ /**
76
+ * Whether a static import is erased by TypeScript: every binding is
77
+ * type-only, or it is `import type {} from "x"`, which the module record
78
+ * reports with no entries (like a runtime `import {} from "x"`).
79
+ */
80
+ export declare function isTypeOnlyImport(code: string, statement: ModuleRecord["staticImports"][number]): boolean;
81
+ /**
82
+ * The value of the string literal or expression-free template literal spanning
83
+ * `span`, or `null` for any other expression. The module record gives only the
84
+ * span of a dynamic import's source.
85
+ */
86
+ export declare function quotedStringAt(code: string, span: {
87
+ start: number;
88
+ end: number;
89
+ }): string | null;
39
90
  export declare function isIdentifierNamed(value: ESTree.Node | null | undefined, name: string): boolean;
40
91
  export declare function getAstName(node: ESTree.Node | null | undefined): string | null;
41
92
  /** Remove syntax-only wrappers while preserving the underlying expression. */
@@ -1,3 +1,4 @@
1
+ import { parse, parseSync } from "vite";
1
2
  //#region src/plugins/ast-utils.ts
2
3
  const SCRIPT_MODULE_EXTENSION_RE = /^\.(?:[cm]?[jt]s|[jt]sx)$/i;
3
4
  const SCRIPT_MODULE_ID_RE = /\.(?:[cm]?[jt]s|[jt]sx)(?:[?#].*)?$/i;
@@ -7,7 +8,7 @@ const SCRIPT_MODULE_ID_RE = /\.(?:[cm]?[jt]s|[jt]sx)(?:[?#].*)?$/i;
7
8
  * Static imports — `import x from "..."`, `import { ... } from "..."`,
8
9
  * `import "..."` — never place a `(` (nor a comment leading to one) immediately
9
10
  * after the `import` keyword. Plugins that act only on dynamic `import(...)` use
10
- * this to skip `parseAst` for the overwhelming majority of modules in a large
11
+ * this to skip parsing for the overwhelming majority of modules in a large
11
12
  * app: at ~5k routes, where almost every module is a static-import-only page,
12
13
  * it removes most of the build's AST-parse/GC cost. This is a deliberate,
13
14
  * measured performance filter — keep it a regex, never a parse.
@@ -46,6 +47,93 @@ function scriptParserLanguage(id) {
46
47
  if (extension === ".tsx") return "tsx";
47
48
  return "jsx";
48
49
  }
50
+ const PROGRAM_PARSER_DEFAULTS = {
51
+ lang: "js",
52
+ preserveParens: false
53
+ };
54
+ const PARSE_FILENAME = "file.js";
55
+ function programOrThrow(result) {
56
+ if (result.errors.length > 0) {
57
+ const frames = result.errors.slice(0, 5).map((error) => error.codeframe ?? error.message);
58
+ throw new SyntaxError(`Parse failed with ${result.errors.length} error${result.errors.length === 1 ? "" : "s"}:\n${frames.join("\n")}`);
59
+ }
60
+ return result.program;
61
+ }
62
+ /**
63
+ * Parse `code` into an ESTree program, throwing on syntax errors.
64
+ *
65
+ * Replaces Vite's deprecated `parseAst` with the same defaults and contract.
66
+ * Callers that only need import/export declarations should use
67
+ * {@link parseModuleRecord}, which skips building the JS AST.
68
+ */
69
+ function parseProgram(code, options) {
70
+ return programOrThrow(parseSync(PARSE_FILENAME, code, {
71
+ ...PROGRAM_PARSER_DEFAULTS,
72
+ ...options
73
+ }));
74
+ }
75
+ /** Async {@link parseProgram}; replaces Vite's deprecated `parseAstAsync`. */
76
+ async function parseProgramAsync(code, options) {
77
+ return programOrThrow(await parse(PARSE_FILENAME, code, {
78
+ ...PROGRAM_PARSER_DEFAULTS,
79
+ ...options
80
+ }));
81
+ }
82
+ /**
83
+ * Parse `code` and return only its static import/export and dynamic import
84
+ * record, or `null` when it has syntax errors.
85
+ *
86
+ * Reading the record never deserializes the JS AST, which is most of the cost
87
+ * of a parse (about 4x cheaper than {@link parseProgram} on large modules).
88
+ * The record omits import attributes; see {@link hasImportAttributes}.
89
+ */
90
+ function parseModuleRecord(code, lang) {
91
+ const result = parseSync(PARSE_FILENAME, code, { lang });
92
+ return result.errors.length > 0 ? null : result.module;
93
+ }
94
+ /**
95
+ * One whitespace character or comment. Each alternative can only match one
96
+ * way (a block comment stops at the first `*\/`, a line comment runs to the
97
+ * line end), so repeating it cannot backtrack exponentially.
98
+ */
99
+ const TRIVIA_PATTERN = String.raw`(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/|\/\/[^\n\r\u2028\u2029]*(?![^\n\r\u2028\u2029]))`;
100
+ /** Leading whitespace and comments. */
101
+ const LEADING_TRIVIA_RE = new RegExp(`^${TRIVIA_PATTERN}*`);
102
+ /**
103
+ * Whether the static import/export statement ending at `statementEnd` has
104
+ * `with { ... }` (or legacy `assert { ... }`) attributes after its source
105
+ * string, which ends at `sourceEnd`. The module record does not report
106
+ * attributes.
107
+ */
108
+ function hasImportAttributes(code, sourceEnd, statementEnd) {
109
+ const afterSource = code.slice(sourceEnd, statementEnd);
110
+ const triviaLength = LEADING_TRIVIA_RE.exec(afterSource)?.[0].length ?? 0;
111
+ return /^(?:with|assert)\b/.test(afterSource.slice(triviaLength));
112
+ }
113
+ const EMPTY_TYPE_IMPORT_RE = new RegExp(String.raw`^import${TRIVIA_PATTERN}*type${TRIVIA_PATTERN}*\{`);
114
+ /**
115
+ * Whether a static import is erased by TypeScript: every binding is
116
+ * type-only, or it is `import type {} from "x"`, which the module record
117
+ * reports with no entries (like a runtime `import {} from "x"`).
118
+ */
119
+ function isTypeOnlyImport(code, statement) {
120
+ if (statement.entries.length > 0) return statement.entries.every((entry) => entry.isType);
121
+ return EMPTY_TYPE_IMPORT_RE.test(code.slice(statement.start, statement.moduleRequest.start));
122
+ }
123
+ /**
124
+ * The value of the string literal or expression-free template literal spanning
125
+ * `span`, or `null` for any other expression. The module record gives only the
126
+ * span of a dynamic import's source.
127
+ */
128
+ function quotedStringAt(code, span) {
129
+ const text = code.slice(span.start, span.end);
130
+ const match = /^(?:"([^"\\\r\n]*)"|'([^'\\\r\n]*)'|`([^`\\$]*)`)$/.exec(text);
131
+ if (match) return match[1] ?? match[2] ?? match[3];
132
+ if (!/^["'`]/.test(text)) return null;
133
+ const result = parseSync(PARSE_FILENAME, `(${text})`, PROGRAM_PARSER_DEFAULTS);
134
+ const statement = result.errors.length > 0 ? void 0 : result.program.body[0];
135
+ return statement?.type === "ExpressionStatement" ? staticStringValue(statement.expression) : null;
136
+ }
49
137
  const SKIP_CHILD_KEYS = /* @__PURE__ */ new Set([
50
138
  "type",
51
139
  "parent",
@@ -137,4 +225,4 @@ function collectBindingNames(node, target) {
137
225
  }
138
226
  }
139
227
  //#endregion
140
- export { DYNAMIC_IMPORT_PRESCAN, SCRIPT_MODULE_ID_RE, booleanLiteralValue, collectBindingNames, forEachAstChild, getAstName, isIdentifierNamed, mayContainDynamicImport, scriptParserLanguage, staticStringValue, stringLiteralValue, unwrapExpression, walkAst };
228
+ export { DYNAMIC_IMPORT_PRESCAN, LEADING_TRIVIA_RE, SCRIPT_MODULE_ID_RE, TRIVIA_PATTERN, booleanLiteralValue, collectBindingNames, forEachAstChild, getAstName, hasImportAttributes, isIdentifierNamed, isTypeOnlyImport, mayContainDynamicImport, parseModuleRecord, parseProgram, parseProgramAsync, quotedStringAt, scriptParserLanguage, staticStringValue, stringLiteralValue, unwrapExpression, walkAst };
@@ -0,0 +1,41 @@
1
+ import { Plugin } from "vite";
2
+ //#region src/plugins/cloudflare-dev-module-urls.d.ts
3
+ /**
4
+ * Vite's internal middlewares that serve module requests (`/@vite/client`,
5
+ * `/@id/*`, JS and CSS source files) and `/@fs/*` paths, preceded by the one
6
+ * that strips a non-root `base` from the URL and the one that answers the HMR
7
+ * client's reconnect ping (`Accept: text/x-vite-ping`) with a 204 instead of
8
+ * the Worker rendering a page for it. If Vite renames them, none are found and
9
+ * every request falls through, which is the behavior without this plugin.
10
+ *
11
+ * `viteServePublicMiddleware` is deliberately excluded so that `public/` files
12
+ * reach the Worker and middleware, as they do in production. Without it, the
13
+ * transform middleware reports a public `.js` or `.css` file as an
14
+ * `ERR_LOAD_PUBLIC_URL` error, which is treated as a fall-through.
15
+ */
16
+ export declare const VITE_MODULE_MIDDLEWARE_NAMES: Set<string>;
17
+ /**
18
+ * Vite's internal middleware that serves files under the project root. Vite
19
+ * gives imported assets root-relative URLs (`import logo from "./logo.svg"`
20
+ * and CSS `url(./bg.png)` both resolve to paths like `/app/logo.svg`), and only
21
+ * this middleware serves them. It also serves every other project file, and a
22
+ * Worker route can share its path with one (e.g. an `api/` directory and an
23
+ * `/api/*` route handler), so it only runs for referenced assets. See
24
+ * `isReferencedAsset`. Navigations to a referenced asset
25
+ * are served too: in production its URL is under `/_next/static/`, which never
26
+ * reaches the Worker.
27
+ */
28
+ export declare const VITE_STATIC_MIDDLEWARE_NAME = "viteServeStaticMiddleware";
29
+ type CloudflareDevModuleUrlsOptions = {
30
+ /** Whether the Cloudflare Vite plugin is present. Read when the dev server starts. */
31
+ isEnabled: () => boolean;
32
+ };
33
+ /**
34
+ * Creates the plugin that lets Vite serve its module URLs before the Cloudflare
35
+ * plugin's `runWorkerFirst` routing in dev.
36
+ *
37
+ * @param options - Plugin options
38
+ * @returns The Vite plugin
39
+ */
40
+ export declare function createCloudflareDevModuleUrlsPlugin(options: CloudflareDevModuleUrlsOptions): Plugin;
41
+ //#endregion
@@ -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 });
@@ -1,11 +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
6
  import { isForeignNodeModule } from "../utils/package-name.js";
7
7
  import { relativeToRoot, relativeWithinRoot, tryRealpathSync } from "../build/ssr-manifest.js";
8
- import { parseAst } from "vite";
9
8
  import MagicString from "magic-string";
10
9
  //#region src/plugins/dynamic-preload-metadata.ts
11
10
  function isNextDynamicSource(source) {
@@ -239,7 +238,7 @@ async function transformNextDynamicPreloadMetadata(code, id, root, resolveDynami
239
238
  if (!code.includes("next/dynamic")) return null;
240
239
  let ast;
241
240
  try {
242
- ast = parseAst(code);
241
+ ast = parseProgram(code);
243
242
  } catch (error) {
244
243
  if (typeof process !== "undefined" && process.env?.DEBUG?.includes("vinext")) console.debug(`[vinext] dynamic-preload-metadata: failed to parse ${id}:`, error);
245
244
  return null;
@@ -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
  }