vinext 1.0.0-beta.6 → 1.0.0-beta.8

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 (179) hide show
  1. package/README.md +47 -3
  2. package/dist/build/action-owner-manifest.d.ts +42 -0
  3. package/dist/build/action-owner-manifest.js +110 -0
  4. package/dist/build/clean-output.js +1 -4
  5. package/dist/build/client-build-config.js +10 -11
  6. package/dist/build/prerender.d.ts +1 -1
  7. package/dist/build/prerender.js +12 -6
  8. package/dist/build/report.d.ts +1 -1
  9. package/dist/build/route-classification-manifest.d.ts +1 -1
  10. package/dist/build/static-export.d.ts +1 -1
  11. package/dist/client/app-nav-failure-handler.js +1 -0
  12. package/dist/client/navigation-runtime.d.ts +5 -3
  13. package/dist/client/navigation-runtime.js +4 -8
  14. package/dist/entries/app-browser-entry.d.ts +1 -1
  15. package/dist/entries/app-rsc-entry.d.ts +2 -1
  16. package/dist/entries/app-rsc-entry.js +111 -8
  17. package/dist/entries/pages-client-entry.d.ts +1 -1
  18. package/dist/entries/pages-server-entry.d.ts +1 -1
  19. package/dist/index.d.ts +3 -0
  20. package/dist/index.js +119 -26
  21. package/dist/plugins/action-owner-manifest.d.ts +14 -0
  22. package/dist/plugins/action-owner-manifest.js +84 -0
  23. package/dist/plugins/ast-utils.d.ts +30 -1
  24. package/dist/plugins/ast-utils.js +76 -1
  25. package/dist/plugins/css-module-imports.d.ts +2 -2
  26. package/dist/plugins/css-module-imports.js +5 -13
  27. package/dist/plugins/dynamic-preload-metadata.js +13 -34
  28. package/dist/plugins/environment.d.ts +11 -0
  29. package/dist/plugins/environment.js +7 -0
  30. package/dist/plugins/extensionless-dynamic-import.js +11 -35
  31. package/dist/plugins/fonts.js +8 -12
  32. package/dist/plugins/ignore-dynamic-requests.d.ts +2 -4
  33. package/dist/plugins/ignore-dynamic-requests.js +29 -59
  34. package/dist/plugins/import-meta-url.d.ts +15 -9
  35. package/dist/plugins/import-meta-url.js +310 -85
  36. package/dist/plugins/instrumentation-client.js +4 -5
  37. package/dist/plugins/middleware-export-validation.js +5 -17
  38. package/dist/plugins/middleware-server-only.js +2 -2
  39. package/dist/plugins/og-asset-ownership.js +18 -26
  40. package/dist/plugins/og-assets.js +2 -4
  41. package/dist/plugins/optimize-imports.js +2 -4
  42. package/dist/plugins/pages-node-externals.js +13 -40
  43. package/dist/plugins/remove-console.js +2 -4
  44. package/dist/plugins/require-condition-resolution.d.ts +16 -0
  45. package/dist/plugins/require-condition-resolution.js +167 -0
  46. package/dist/plugins/require-context.js +11 -46
  47. package/dist/plugins/sass.js +1 -1
  48. package/dist/plugins/server-externals-manifest.js +1 -23
  49. package/dist/plugins/strip-server-exports.js +13 -19
  50. package/dist/plugins/styled-jsx.js +17 -19
  51. package/dist/plugins/transform-result.d.ts +10 -0
  52. package/dist/plugins/transform-result.js +10 -0
  53. package/dist/plugins/transitive-externals.js +7 -21
  54. package/dist/plugins/typeof-window.d.ts +3 -8
  55. package/dist/plugins/typeof-window.js +5 -15
  56. package/dist/plugins/use-cache-callable.js +12 -22
  57. package/dist/plugins/wasm-module-import.js +1 -1
  58. package/dist/plugins/worker-image-imports.d.ts +12 -0
  59. package/dist/plugins/worker-image-imports.js +136 -0
  60. package/dist/routing/app-route-graph.d.ts +3 -2
  61. package/dist/routing/app-route-graph.js +1 -1
  62. package/dist/routing/route-pattern.d.ts +8 -1
  63. package/dist/routing/route-pattern.js +28 -1
  64. package/dist/routing/route-validation.js +7 -1
  65. package/dist/server/accept-encoding.d.ts +1 -2
  66. package/dist/server/accept-encoding.js +1 -4
  67. package/dist/server/app-action-forwarding.d.ts +18 -0
  68. package/dist/server/app-action-forwarding.js +140 -0
  69. package/dist/server/app-browser-entry.js +231 -50
  70. package/dist/server/app-browser-error.d.ts +1 -2
  71. package/dist/server/app-browser-error.js +1 -5
  72. package/dist/server/app-browser-history-controller.d.ts +16 -1
  73. package/dist/server/app-browser-history-controller.js +135 -18
  74. package/dist/server/app-browser-navigation-abort.d.ts +16 -0
  75. package/dist/server/app-browser-navigation-abort.js +29 -0
  76. package/dist/server/app-browser-navigation-controller.d.ts +4 -0
  77. package/dist/server/app-browser-navigation-controller.js +22 -6
  78. package/dist/server/app-browser-navigation-response.d.ts +11 -0
  79. package/dist/server/app-browser-navigation-response.js +8 -0
  80. package/dist/server/app-browser-popstate.d.ts +6 -1
  81. package/dist/server/app-browser-popstate.js +6 -2
  82. package/dist/server/app-browser-server-action-client.js +1 -1
  83. package/dist/server/app-browser-state.d.ts +2 -2
  84. package/dist/server/app-browser-state.js +3 -3
  85. package/dist/server/app-browser-stream.d.ts +0 -2
  86. package/dist/server/app-browser-supplemental-refresh.d.ts +49 -0
  87. package/dist/server/app-browser-supplemental-refresh.js +190 -0
  88. package/dist/server/app-browser-visible-commit.js +23 -12
  89. package/dist/server/app-elements-wire.d.ts +2 -0
  90. package/dist/server/app-elements-wire.js +7 -0
  91. package/dist/server/app-history-state.d.ts +22 -1
  92. package/dist/server/app-history-state.js +93 -9
  93. package/dist/server/app-optimistic-routing.d.ts +22 -1
  94. package/dist/server/app-optimistic-routing.js +137 -12
  95. package/dist/server/app-page-cache-finalizer.d.ts +3 -1
  96. package/dist/server/app-page-cache-finalizer.js +6 -6
  97. package/dist/server/app-page-cache.d.ts +2 -1
  98. package/dist/server/app-page-cache.js +2 -2
  99. package/dist/server/app-page-dispatch.d.ts +4 -1
  100. package/dist/server/app-page-dispatch.js +10 -1
  101. package/dist/server/app-page-element-builder.d.ts +1 -0
  102. package/dist/server/app-page-element-builder.js +1 -0
  103. package/dist/server/app-page-ppr-runtime.js +3 -2
  104. package/dist/server/app-page-render.d.ts +2 -1
  105. package/dist/server/app-page-render.js +6 -3
  106. package/dist/server/app-page-request.d.ts +2 -33
  107. package/dist/server/app-page-request.js +1 -27
  108. package/dist/server/app-page-route-wiring.d.ts +1 -0
  109. package/dist/server/app-page-route-wiring.js +4 -0
  110. package/dist/server/app-page-segment-state.d.ts +2 -2
  111. package/dist/server/app-page-segment-state.js +14 -8
  112. package/dist/server/app-ppr-fallback-shell.d.ts +2 -2
  113. package/dist/server/app-ppr-fallback-shell.js +3 -6
  114. package/dist/server/app-route-handler-dispatch.js +4 -1
  115. package/dist/server/app-route-handler-execution.js +1 -1
  116. package/dist/server/app-rsc-cache-busting.d.ts +2 -1
  117. package/dist/server/app-rsc-cache-busting.js +34 -8
  118. package/dist/server/app-rsc-handler.d.ts +4 -2
  119. package/dist/server/app-rsc-handler.js +57 -9
  120. package/dist/server/app-rsc-request-normalization.d.ts +2 -0
  121. package/dist/server/app-rsc-request-normalization.js +5 -1
  122. package/dist/server/app-rsc-route-matching.d.ts +4 -3
  123. package/dist/server/app-rsc-route-matching.js +14 -42
  124. package/dist/server/app-server-action-execution.d.ts +3 -0
  125. package/dist/server/app-server-action-execution.js +77 -2
  126. package/dist/server/app-ssr-entry.js +6 -6
  127. package/dist/server/app-ssr-stream.d.ts +1 -1
  128. package/dist/server/app-ssr-stream.js +2 -2
  129. package/dist/server/app-visited-response-cache.d.ts +6 -1
  130. package/dist/server/app-visited-response-cache.js +18 -2
  131. package/dist/server/dev-route-files.js +2 -5
  132. package/dist/server/dev-server.d.ts +5 -13
  133. package/dist/server/dev-server.js +22 -22
  134. package/dist/server/dev-stack-sourcemap.d.ts +1 -2
  135. package/dist/server/dev-stack-sourcemap.js +1 -4
  136. package/dist/server/headers.d.ts +5 -1
  137. package/dist/server/headers.js +5 -1
  138. package/dist/server/isr-cache.d.ts +6 -14
  139. package/dist/server/isr-cache.js +6 -27
  140. package/dist/server/middleware.d.ts +3 -16
  141. package/dist/server/middleware.js +2 -19
  142. package/dist/server/navigation-planner.d.ts +1 -0
  143. package/dist/server/navigation-planner.js +57 -9
  144. package/dist/server/navigation-trace.d.ts +1 -0
  145. package/dist/server/navigation-trace.js +1 -0
  146. package/dist/server/pages-data-route.d.ts +1 -10
  147. package/dist/server/pages-data-route.js +1 -12
  148. package/dist/server/pages-node-compat.d.ts +1 -4
  149. package/dist/server/pages-node-compat.js +1 -7
  150. package/dist/server/pages-readiness.js +4 -4
  151. package/dist/server/prerender-route-params.d.ts +1 -2
  152. package/dist/server/prerender-route-params.js +1 -4
  153. package/dist/server/prod-server.js +3 -1
  154. package/dist/shims/cache-runtime.js +39 -22
  155. package/dist/shims/cache.d.ts +1 -1
  156. package/dist/shims/dynamic.d.ts +3 -3
  157. package/dist/shims/dynamic.js +4 -6
  158. package/dist/shims/error.js +1 -1
  159. package/dist/shims/fetch-cache.d.ts +3 -1
  160. package/dist/shims/fetch-cache.js +23 -4
  161. package/dist/shims/internal/app-route-prefetch-policy.d.ts +6 -7
  162. package/dist/shims/internal/app-route-prefetch-policy.js +5 -4
  163. package/dist/shims/link.js +1 -1
  164. package/dist/shims/navigation.d.ts +12 -3
  165. package/dist/shims/navigation.js +46 -11
  166. package/dist/shims/navigation.react-server.js +1 -1
  167. package/dist/shims/request-state-types.d.ts +1 -1
  168. package/dist/shims/router.js +75 -4
  169. package/dist/shims/unified-request-context.d.ts +1 -1
  170. package/dist/shims/unified-request-context.js +1 -0
  171. package/dist/utils/built-asset-url.d.ts +1 -1
  172. package/dist/utils/built-asset-url.js +4 -2
  173. package/dist/utils/package-name.d.ts +11 -0
  174. package/dist/utils/package-name.js +18 -0
  175. package/dist/utils/path.d.ts +8 -1
  176. package/dist/utils/path.js +21 -1
  177. package/dist/utils/react-compiler-support.d.ts +20 -0
  178. package/dist/utils/react-compiler-support.js +29 -0
  179. package/package.json +3 -2
@@ -1,25 +1,49 @@
1
1
  import path, { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { canonicalizeFilePath, isPathInsideOrEqual, stripViteModuleQuery } from "../utils/path.js";
3
+ import { magicStringTransformResult } from "./transform-result.js";
2
4
  import { VIRTUAL_MODULE_ID_RE } from "../utils/virtual-module.js";
3
- import { collectBindingNames, forEachAstChild, hasRange, isAstRecord, isIdentifierNamed, nodeArray } from "./ast-utils.js";
4
- import { tryRealpathSync } from "../build/ssr-manifest.js";
5
+ import { SCRIPT_MODULE_ID_RE, collectBindingNames, forEachAstChild, hasRange, isAstRecord, isIdentifierNamed, nodeArray, scriptParserLanguage } from "./ast-utils.js";
6
+ import fs from "node:fs";
5
7
  import { parseAst } from "vite";
6
- import { pathToFileURL } from "node:url";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { randomUUID } from "node:crypto";
7
10
  import MagicString from "magic-string";
8
11
  //#region src/plugins/import-meta-url.ts
9
- const TRANSFORMABLE_SCRIPT_EXTENSIONS = /* @__PURE__ */ new Set([
10
- ".cjs",
11
- ".cts",
12
- ".js",
13
- ".jsx",
14
- ".mjs",
15
- ".mts",
16
- ".ts",
17
- ".tsx"
18
- ]);
12
+ const MAX_DEPENDENCY_FORMAT_CACHE_ENTRIES = 512;
13
+ const MAX_TRANSFORM_CACHE_ENTRIES = 2048;
14
+ const BLOCK_COMMENT_PATTERN = String.raw`\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/`;
15
+ const JAVASCRIPT_TRIVIA_PATTERN = String.raw`(?:\s|${BLOCK_COMMENT_PATTERN}|\/\/[^\r\n\u2028\u2029]*)*`;
16
+ const UNICODE_IDENTIFIER_ESCAPE_PATTERN = String.raw`\\u(?:[\dA-Fa-f]{4}|\{[\dA-Fa-f]+\})`;
17
+ const IMPORT_META_URL_CANDIDATE_PATTERN = String.raw`\bimport${JAVASCRIPT_TRIVIA_PATTERN}\.${JAVASCRIPT_TRIVIA_PATTERN}meta${JAVASCRIPT_TRIVIA_PATTERN}\??\.${JAVASCRIPT_TRIVIA_PATTERN}(?:u|${UNICODE_IDENTIFIER_ESCAPE_PATTERN})(?:r|${UNICODE_IDENTIFIER_ESCAPE_PATTERN})(?:l|${UNICODE_IDENTIFIER_ESCAPE_PATTERN})`;
18
+ const IMPORT_META_URL_CANDIDATE_RE = new RegExp(IMPORT_META_URL_CANDIDATE_PATTERN, "u");
19
+ const SOURCE_IDENTITY_FILTER_RE = new RegExp(`${IMPORT_META_URL_CANDIDATE_PATTERN}|__filename|__dirname`, "u");
19
20
  function createImportMetaUrlPlugin(options) {
20
21
  let rootPaths;
21
22
  let outputDirs = [];
23
+ let resolveEmittedModuleFileName = (_, fileName) => fileName;
22
24
  const transformCache = /* @__PURE__ */ new Map();
25
+ const dependencyModuleCache = /* @__PURE__ */ new Map();
26
+ const emittedModuleIdentity = createEmittedModuleIdentity();
27
+ function dependencyModule(id) {
28
+ const cleanId = stripViteModuleQuery(id);
29
+ const paths = getRootPaths();
30
+ const cached = dependencyModuleCache.get(cleanId);
31
+ if (cached && cached.canonicalRoot === paths?.canonicalRoot) return cached.value;
32
+ const dependency = canonicalDependencyModuleId(cleanId, paths);
33
+ const result = dependency === null ? null : {
34
+ canonicalId: dependency.canonicalId,
35
+ isCommonJs: isCommonJsDependency(dependency.canonicalId, dependency.allowUnpackaged)
36
+ };
37
+ setBoundedCacheEntry(dependencyModuleCache, cleanId, {
38
+ canonicalRoot: paths?.canonicalRoot,
39
+ value: result
40
+ }, MAX_DEPENDENCY_FORMAT_CACHE_ENTRIES);
41
+ return result;
42
+ }
43
+ function commonJsDependencyCanonicalId(id) {
44
+ const dependency = dependencyModule(id);
45
+ return dependency?.isCommonJs ? dependency.canonicalId : null;
46
+ }
23
47
  function getRootPaths() {
24
48
  const root = options.getRoot();
25
49
  if (!root) return rootPaths;
@@ -27,49 +51,108 @@ function createImportMetaUrlPlugin(options) {
27
51
  return rootPaths;
28
52
  }
29
53
  return {
30
- name: "vinext:import-meta-url",
31
- enforce: "post",
32
- configResolved(config) {
33
- const root = options.getRoot() ?? config.root;
34
- outputDirs = [config.build.outDir];
35
- rootPaths = createRootPaths(root, { outputDirs });
54
+ vitePlugin: {
55
+ name: "vinext:import-meta-url",
56
+ enforce: "post",
57
+ configResolved(config) {
58
+ const root = options.getRoot() ?? config.root;
59
+ const environments = Object.entries(config.environments ?? {});
60
+ outputDirs = [config.build.outDir, ...environments.map(([, environment]) => environment.build.outDir)];
61
+ resolveEmittedModuleFileName = options.createEmittedModuleFileNameResolver?.(config) ?? ((_, fileName) => fileName);
62
+ rootPaths = createRootPaths(root, { outputDirs });
63
+ },
64
+ watchChange() {
65
+ dependencyModuleCache.clear();
66
+ },
67
+ transform: {
68
+ filter: {
69
+ id: {
70
+ include: SCRIPT_MODULE_ID_RE,
71
+ exclude: VIRTUAL_MODULE_ID_RE
72
+ },
73
+ code: SOURCE_IDENTITY_FILTER_RE
74
+ },
75
+ handler(code, id) {
76
+ if (!mayContainSourceIdentityToken(code)) return null;
77
+ const cleanId = stripViteModuleQuery(id);
78
+ if (this.environment?.config?.consumer !== "client") {
79
+ const dependency = dependencyModule(cleanId);
80
+ if (dependency) {
81
+ const importMetaUrlReplacement = mayContainImportMetaUrl(code) ? this.environment.mode === "dev" ? JSON.stringify(pathToFileURL(dependency.canonicalId).href) : emittedModuleIdentity.importMetaUrlInitializer : void 0;
82
+ const cjsGlobalInitializers = dependency.isCommonJs && mayContainServerCjsGlobal(code) ? this.environment.mode === "dev" ? sourcePathCjsGlobalInitializers(dependency.canonicalId) : emittedModuleIdentity.cjsGlobalInitializers : void 0;
83
+ if (importMetaUrlReplacement !== void 0 || cjsGlobalInitializers) return rewriteModuleIdentity(code, {
84
+ id: dependency.canonicalId,
85
+ importMetaUrlReplacement,
86
+ cjsGlobalInitializers
87
+ });
88
+ }
89
+ }
90
+ if (isNodeModulesId(cleanId)) return null;
91
+ const paths = getRootPaths();
92
+ if (!paths) return null;
93
+ const canonicalId = transformableModuleCanonicalId(cleanId, paths);
94
+ if (!canonicalId) return null;
95
+ const environment = this.environment?.name === "client" ? "client" : "server";
96
+ const explicitCommonJs = [".cjs", ".cts"].includes(path.extname(canonicalId));
97
+ const transformKind = environment === "client" ? "client" : explicitCommonJs ? this.environment.mode === "dev" ? "server-cjs-dev" : "server-cjs-build" : this.environment.mode === "dev" ? "server-dev" : "server-build";
98
+ let entry = transformCache.get(id);
99
+ if (!entry || entry.source !== code || entry.canonicalRoot !== paths.canonicalRoot || entry.canonicalId !== canonicalId) {
100
+ entry = {
101
+ source: code,
102
+ canonicalRoot: paths.canonicalRoot,
103
+ canonicalId,
104
+ results: /* @__PURE__ */ new Map()
105
+ };
106
+ setBoundedCacheEntry(transformCache, id, entry, MAX_TRANSFORM_CACHE_ENTRIES);
107
+ }
108
+ const cached = entry.results.get(transformKind);
109
+ if (cached) return cached.value;
110
+ const value = rewriteCanonicalSourceIdentity(code, canonicalId, paths, environment, this.environment.mode === "build" && mayContainServerCjsGlobal(code) ? emittedModuleIdentity.cjsGlobalInitializers : sourcePathCjsGlobalInitializers(canonicalId));
111
+ entry.results.set(transformKind, { value });
112
+ return value;
113
+ }
114
+ },
115
+ renderChunk: {
116
+ order: "post",
117
+ handler(code, chunk, outputOptions) {
118
+ if (this.environment?.config.consumer !== "server" || outputOptions.format !== "es") return null;
119
+ const emittedFileName = resolveEmittedModuleFileName(this.environment?.name, chunk.fileName);
120
+ return finalizeEmittedModuleIdentity(code, emittedModuleIdentity.replacements, emittedFileName);
121
+ }
122
+ }
36
123
  },
37
- transform: {
38
- filter: {
39
- id: {
40
- include: /\.(?:[cm]?[jt]s|[jt]sx)(?:\?.*)?$/,
41
- exclude: [/[\\/]node_modules[\\/]/, VIRTUAL_MODULE_ID_RE]
124
+ optimizeDepsPlugin: {
125
+ name: "vinext:import-meta-url:optimize-deps",
126
+ transform: {
127
+ filter: {
128
+ id: /\.(?:[cm]?[jt]s|[jt]sx)(?:\?.*)?$/,
129
+ code: SOURCE_IDENTITY_FILTER_RE
42
130
  },
43
- code: /import\.meta(?:\.|\?\.)url|__filename|__dirname/
131
+ handler(code, id) {
132
+ if (!mayContainSourceIdentityToken(code)) return null;
133
+ const dependency = dependencyModule(id);
134
+ if (!dependency) return null;
135
+ return rewriteModuleIdentity(code, {
136
+ id: dependency.canonicalId,
137
+ importMetaUrlReplacement: mayContainImportMetaUrl(code) ? emittedModuleIdentity.importMetaUrlInitializer : void 0,
138
+ cjsGlobalInitializers: dependency.isCommonJs && mayContainServerCjsGlobal(code) ? emittedModuleIdentity.cjsGlobalInitializers : void 0
139
+ });
140
+ }
44
141
  },
45
- handler(code, id) {
46
- const paths = getRootPaths();
47
- if (!paths) return null;
48
- const canonicalId = transformableModuleCanonicalId(cleanModuleId(id), paths);
49
- if (!canonicalId) return null;
50
- const environment = this.environment?.name === "client" ? "client" : "server";
51
- let entry = transformCache.get(id);
52
- if (!entry || entry.source !== code || entry.canonicalRoot !== paths.canonicalRoot || entry.canonicalId !== canonicalId) {
53
- entry = {
54
- source: code,
55
- canonicalRoot: paths.canonicalRoot,
56
- canonicalId,
57
- results: /* @__PURE__ */ new Map()
58
- };
59
- transformCache.set(id, entry);
142
+ renderChunk: {
143
+ order: "post",
144
+ handler(code, chunk, outputOptions) {
145
+ if (outputOptions.format !== "es") return null;
146
+ return finalizeEmittedModuleIdentity(code, emittedModuleIdentity.replacements, chunk.fileName);
60
147
  }
61
- const cached = entry.results.get(environment);
62
- if (cached) return cached.value;
63
- const value = rewriteCanonicalSourceIdentity(code, canonicalId, paths, environment);
64
- entry.results.set(environment, { value });
65
- return value;
66
148
  }
67
- }
149
+ },
150
+ isBundledCommonJsDependencyId: (id) => commonJsDependencyCanonicalId(id) !== null
68
151
  };
69
152
  }
70
153
  function rewriteImportMetaUrl(code, id, root, environment) {
71
154
  if (!mayContainImportMetaUrl(code)) return null;
72
- return rewriteCanonicalSourceIdentity(code, canonicalizePath(id), createRootPaths(root), environment);
155
+ return rewriteCanonicalSourceIdentity(code, canonicalizeFilePath(id), createRootPaths(root), environment);
73
156
  }
74
157
  function rewriteServerCjsGlobals(code, id, root) {
75
158
  if (!mayContainServerCjsGlobal(code)) return null;
@@ -78,43 +161,182 @@ function rewriteServerCjsGlobals(code, id, root) {
78
161
  if (!canonicalId) return null;
79
162
  return rewriteCanonicalSourceIdentity(code, canonicalId, rootPaths, "server");
80
163
  }
81
- function rewriteCanonicalSourceIdentity(code, canonicalId, rootPaths, environment) {
164
+ function rewriteCanonicalSourceIdentity(code, canonicalId, rootPaths, environment, cjsGlobalInitializers) {
165
+ return rewriteModuleIdentity(code, {
166
+ id: canonicalId,
167
+ importMetaUrlReplacement: mayContainImportMetaUrl(code) ? JSON.stringify(importMetaUrlValue(canonicalId, rootPaths, environment)) : void 0,
168
+ cjsGlobalInitializers: environment === "server" && mayContainServerCjsGlobal(code) ? cjsGlobalInitializers ?? sourcePathCjsGlobalInitializers(canonicalId) : void 0
169
+ });
170
+ }
171
+ function createEmittedModuleIdentity() {
172
+ const nonce = randomUUID().replaceAll("-", "");
173
+ const filenameMarker = `__VINEXT_EMITTED_MODULE_FILENAME_${nonce}__`;
174
+ const dirnameMarker = `__VINEXT_EMITTED_MODULE_DIRNAME_${nonce}__`;
175
+ const urlMarker = `__VINEXT_EMITTED_MODULE_URL_${nonce}__`;
176
+ const filenameSentinel = JSON.stringify(filenameMarker);
177
+ const dirnameSentinel = JSON.stringify(dirnameMarker);
178
+ const urlSentinel = JSON.stringify(urlMarker);
179
+ return {
180
+ cjsGlobalInitializers: {
181
+ __filename: emittedModuleIdentityInitializer(filenameSentinel),
182
+ __dirname: emittedModuleIdentityInitializer(dirnameSentinel)
183
+ },
184
+ importMetaUrlInitializer: emittedModuleIdentityInitializer(urlSentinel),
185
+ replacements: /* @__PURE__ */ new Map([
186
+ [filenameSentinel, "__filename"],
187
+ [dirnameSentinel, "__dirname"],
188
+ [urlSentinel, "url"]
189
+ ])
190
+ };
191
+ }
192
+ function emittedModuleIdentityInitializer(sentinel) {
193
+ return `({ get value() { return ${sentinel}; } }).value`;
194
+ }
195
+ function finalizeEmittedModuleIdentity(code, emittedIdentitySentinels, fileName) {
196
+ if (!code.includes("__VINEXT_EMITTED_MODULE_")) return null;
197
+ const runtimeBindings = new Set(code.match(/\b__vinext_module_(?:process|fs|url|identity)_*\b/g) ?? []);
198
+ function selectRuntimeBinding(base) {
199
+ let binding = base;
200
+ while (runtimeBindings.has(binding)) binding += "_";
201
+ return binding;
202
+ }
203
+ const processNamespaceBinding = selectRuntimeBinding("__vinext_module_process");
204
+ const fsNamespaceBinding = selectRuntimeBinding("__vinext_module_fs");
205
+ const urlNamespaceBinding = selectRuntimeBinding("__vinext_module_url");
206
+ const identityBinding = selectRuntimeBinding("__vinext_module_identity");
207
+ const emittedFileName = toSlash(fileName).replace(/^\.\//, "").replace(/^\/+/, "");
208
+ const processCwd = `(typeof ${processNamespaceBinding}.cwd === "function" ? ${processNamespaceBinding}.cwd() : "")`;
209
+ const emittedPathFallback = emittedFileName ? `(${processCwd}.replace(/[\\\\/]$/, "") + ${JSON.stringify(`/${emittedFileName}`)})` : `(${processCwd} || "/")`;
210
+ const emittedDirName = path.dirname(emittedFileName);
211
+ const emittedDirFallback = emittedDirName === "." ? `(${processCwd} || "/")` : `(${processCwd}.replace(/[\\\\/]$/, "") + ${JSON.stringify(`/${emittedDirName}`)})`;
212
+ const absoluteEmittedPath = JSON.stringify(`/${emittedFileName}`.replace(/\/$/, "") || "/");
213
+ const replacements = {
214
+ __filename: `${identityBinding}.filename`,
215
+ __dirname: `${identityBinding}.dirname`,
216
+ url: `${identityBinding}.url`
217
+ };
218
+ const output = new MagicString(code);
219
+ let changed = false;
220
+ const usedFields = /* @__PURE__ */ new Set();
221
+ for (const [sentinel, field] of emittedIdentitySentinels) {
222
+ let start = code.indexOf(sentinel);
223
+ while (start !== -1) {
224
+ output.overwrite(start, start + sentinel.length, replacements[field]);
225
+ changed = true;
226
+ usedFields.add(field);
227
+ start = code.indexOf(sentinel, start + sentinel.length);
228
+ }
229
+ }
230
+ if (!changed) return null;
231
+ const needsUrl = usedFields.has("url");
232
+ const needsPath = usedFields.has("__filename") || usedFields.has("__dirname");
233
+ const runtimePreamble = [
234
+ ...needsPath ? [`import * as ${processNamespaceBinding} from "node:process";`] : [],
235
+ ...needsPath ? [`import * as ${fsNamespaceBinding} from "node:fs";`] : [],
236
+ ...needsUrl ? [`import * as ${urlNamespaceBinding} from "node:url";`] : [],
237
+ `const ${identityBinding} = (() => {`,
238
+ ...needsPath ? [
239
+ ` const filename = import.meta.filename;`,
240
+ ` const native = typeof filename === "string" && ${fsNamespaceBinding}.existsSync(filename);`,
241
+ ` const resolvedFilename = native ? filename : ${emittedPathFallback};`
242
+ ] : [` const runtimeUrl = import.meta.url;`, ` const runtimeFilename = import.meta.filename;`],
243
+ ` return {`,
244
+ ...needsPath ? [` filename: resolvedFilename,`, ` dirname: native ? import.meta.dirname : ${emittedDirFallback},`] : [],
245
+ ...needsUrl ? [needsPath ? ` url: ${urlNamespaceBinding}.pathToFileURL(resolvedFilename).href,` : ` url: typeof runtimeUrl === "string" && runtimeUrl.startsWith("file:") ? runtimeUrl : ${urlNamespaceBinding}.pathToFileURL(typeof runtimeFilename === "string" ? runtimeFilename : ${absoluteEmittedPath}).href,`] : [],
246
+ ` };`,
247
+ `})();`,
248
+ ""
249
+ ].join("\n");
250
+ if (code.startsWith("#!")) output.appendLeft(code.indexOf("\n") + 1, runtimePreamble);
251
+ else output.prepend(runtimePreamble);
252
+ return magicStringTransformResult(output);
253
+ }
254
+ function rewriteModuleIdentity(code, options) {
82
255
  let ast;
83
256
  try {
84
- ast = parseAst(code);
257
+ ast = parseAst(code, {
258
+ lang: scriptParserLanguage(options.id) ?? "jsx",
259
+ sourceType: options.cjsGlobalInitializers ? "commonjs" : void 0
260
+ });
85
261
  } catch {
86
- return null;
262
+ if (!options.cjsGlobalInitializers) return null;
263
+ try {
264
+ ast = parseAst(code, { lang: scriptParserLanguage(options.id) ?? "jsx" });
265
+ } catch {
266
+ return null;
267
+ }
87
268
  }
88
269
  const output = new MagicString(code);
89
270
  let changed = false;
90
- if (mayContainImportMetaUrl(code)) {
271
+ if (options.importMetaUrlReplacement !== void 0) {
91
272
  const importMetaRanges = collectImportMetaUrlRanges(ast);
92
- if (importMetaRanges.length > 0) {
93
- const replacement = JSON.stringify(importMetaUrlValue(canonicalId, rootPaths, environment));
94
- for (const range of importMetaRanges) {
95
- output.overwrite(range.start, range.end, replacement);
96
- changed = true;
97
- }
273
+ if (importMetaRanges.length > 0) for (const range of importMetaRanges) {
274
+ output.overwrite(range.start, range.end, options.importMetaUrlReplacement);
275
+ changed = true;
98
276
  }
99
277
  }
100
- if (environment === "server" && mayContainServerCjsGlobal(code)) {
101
- const injected = injectServerCjsGlobals(ast, canonicalId);
278
+ if (options.cjsGlobalInitializers) {
279
+ const injected = injectServerCjsGlobals(ast, options.cjsGlobalInitializers);
102
280
  if (injected) {
103
281
  output.appendLeft(findDirectivePrologueEnd(ast), `\n${injected}`);
104
282
  changed = true;
105
283
  }
106
284
  }
107
285
  if (!changed) return null;
286
+ return magicStringTransformResult(output);
287
+ }
288
+ function isNodeModulesId(id) {
289
+ return id.includes("/node_modules/") || id.includes("\\node_modules\\");
290
+ }
291
+ function setBoundedCacheEntry(cache, key, value, limit) {
292
+ if (!cache.has(key) && cache.size >= limit) {
293
+ const oldestKey = cache.keys().next().value;
294
+ if (oldestKey !== void 0) cache.delete(oldestKey);
295
+ }
296
+ cache.set(key, value);
297
+ }
298
+ function canonicalDependencyModuleId(id, rootPaths) {
299
+ const cleanId = stripViteModuleQuery(id);
300
+ if (!cleanId || cleanId.startsWith("\0")) return null;
301
+ let filePath;
302
+ try {
303
+ filePath = cleanId.startsWith("file:") ? toSlash(fileURLToPath(cleanId)) : toSlash(cleanId);
304
+ } catch {
305
+ return null;
306
+ }
307
+ if (!path.isAbsolute(filePath)) return null;
308
+ if (scriptParserLanguage(filePath) === null) return null;
309
+ const canonicalId = canonicalizeFilePath(filePath);
310
+ if (isNodeModulesId(filePath)) return {
311
+ canonicalId,
312
+ allowUnpackaged: true
313
+ };
314
+ if (!rootPaths || isPathInsideOrEqual(rootPaths.canonicalRoot, canonicalId)) return null;
108
315
  return {
109
- code: output.toString(),
110
- map: output.generateMap({ hires: "boundary" })
316
+ canonicalId,
317
+ allowUnpackaged: false
111
318
  };
112
319
  }
113
- function cleanModuleId(id) {
114
- return id.split("?", 1)[0];
320
+ function isCommonJsDependency(canonicalId, allowUnpackaged) {
321
+ const extension = path.extname(canonicalId);
322
+ if (extension === ".cjs" || extension === ".cts") return true;
323
+ if (extension === ".mjs" || extension === ".mts") return false;
324
+ let directory = path.dirname(canonicalId);
325
+ for (;;) {
326
+ const packageJsonPath = path.join(directory, "package.json");
327
+ if (fs.existsSync(packageJsonPath)) try {
328
+ return JSON.parse(fs.readFileSync(packageJsonPath, "utf8")).type !== "module";
329
+ } catch {
330
+ return true;
331
+ }
332
+ if (path.basename(directory) === "node_modules") return allowUnpackaged;
333
+ const parent = path.dirname(directory);
334
+ if (parent === directory) return allowUnpackaged;
335
+ directory = parent;
336
+ }
115
337
  }
116
338
  function createRootPaths(root, options = {}) {
117
- const canonicalRoot = canonicalizePath(root);
339
+ const canonicalRoot = canonicalizeFilePath(root);
118
340
  return {
119
341
  root,
120
342
  canonicalRoot,
@@ -126,14 +348,17 @@ function transformableModuleCanonicalId(id, rootPaths) {
126
348
  if (!path.isAbsolute(id)) return null;
127
349
  const slashedInputId = toSlash(id);
128
350
  if (slashedInputId.includes("/node_modules/")) return null;
129
- if (!TRANSFORMABLE_SCRIPT_EXTENSIONS.has(path.extname(slashedInputId))) return null;
130
- const canonicalId = canonicalizePath(id);
131
- if (!isPathWithin(canonicalId, rootPaths.canonicalRoot)) return null;
351
+ if (scriptParserLanguage(slashedInputId) === null) return null;
352
+ const canonicalId = canonicalizeFilePath(id);
353
+ if (!isPathInsideOrEqual(rootPaths.canonicalRoot, canonicalId)) return null;
132
354
  if (isExcludedRelativePath(path.relative(rootPaths.canonicalRoot, canonicalId), rootPaths.excludedRelativePrefixes)) return null;
133
355
  return canonicalId;
134
356
  }
135
357
  function mayContainImportMetaUrl(code) {
136
- return code.includes("import.meta.url") || code.includes("import.meta?.url");
358
+ return IMPORT_META_URL_CANDIDATE_RE.test(code);
359
+ }
360
+ function mayContainSourceIdentityToken(code) {
361
+ return mayContainImportMetaUrl(code) || mayContainServerCjsGlobal(code);
137
362
  }
138
363
  function mayContainServerCjsGlobal(code) {
139
364
  return code.includes("__filename") || code.includes("__dirname");
@@ -147,8 +372,8 @@ function excludedRelativePrefixes(canonicalRoot, options) {
147
372
  "out"
148
373
  ]);
149
374
  for (const outputDir of options.outputDirs ?? []) {
150
- const canonicalOutputDir = canonicalizePath(path.isAbsolute(outputDir) ? outputDir : path.resolve(canonicalRoot, outputDir));
151
- if (!isPathWithin(canonicalOutputDir, canonicalRoot)) continue;
375
+ const canonicalOutputDir = canonicalizeFilePath(path.isAbsolute(outputDir) ? outputDir : path.resolve(canonicalRoot, outputDir));
376
+ if (!isPathInsideOrEqual(canonicalRoot, canonicalOutputDir)) continue;
152
377
  const relativePath = path.relative(canonicalRoot, canonicalOutputDir);
153
378
  if (relativePath && relativePath !== ".") prefixes.add(relativePath);
154
379
  }
@@ -157,17 +382,10 @@ function excludedRelativePrefixes(canonicalRoot, options) {
157
382
  function isExcludedRelativePath(relativePath, prefixes) {
158
383
  return prefixes.some((prefix) => relativePath === prefix || relativePath.startsWith(`${prefix}/`));
159
384
  }
160
- function isPathWithin(candidate, root) {
161
- return candidate === root || candidate.startsWith(root.endsWith("/") ? root : `${root}/`);
162
- }
163
385
  function importMetaUrlValue(canonicalId, rootPaths, environment) {
164
386
  if (environment === "client") return `file:///ROOT/${path.relative(rootPaths.canonicalRoot, canonicalId)}`;
165
387
  return pathToFileURL(canonicalId).href;
166
388
  }
167
- function canonicalizePath(value) {
168
- const real = tryRealpathSync(value);
169
- return real === null ? path.resolve(value) : toSlash(real);
170
- }
171
389
  function collectImportMetaUrlRanges(ast) {
172
390
  const ranges = [];
173
391
  function visit(value) {
@@ -189,7 +407,7 @@ function collectImportMetaUrlRanges(ast) {
189
407
  if (isNewUrlExpression(value)) {
190
408
  const args = nodeArray(value.arguments);
191
409
  for (let index = 0; index < args.length; index += 1) {
192
- if (index === 1 && isImportMetaUrlOrChainedNode(args[index])) continue;
410
+ if (index === 1 && isImportMetaUrlBaseNode(args[index])) continue;
193
411
  visit(args[index]);
194
412
  }
195
413
  return;
@@ -203,13 +421,15 @@ const CJS_GLOBALS = ["__filename", "__dirname"];
203
421
  function isCjsGlobalName(name) {
204
422
  return name === "__filename" || name === "__dirname";
205
423
  }
206
- function injectServerCjsGlobals(ast, canonicalId) {
207
- const analysis = analyzeServerCjsGlobals(ast);
208
- const values = {
209
- __filename: canonicalId,
210
- __dirname: path.dirname(canonicalId)
424
+ function sourcePathCjsGlobalInitializers(canonicalId) {
425
+ return {
426
+ __filename: JSON.stringify(canonicalId),
427
+ __dirname: JSON.stringify(path.dirname(canonicalId))
211
428
  };
212
- const parts = CJS_GLOBALS.filter((name) => analysis.reads.has(name) && !analysis.moduleBindings.has(name)).map((name) => `var ${name} = ${JSON.stringify(values[name])};`);
429
+ }
430
+ function injectServerCjsGlobals(ast, initializers) {
431
+ const analysis = analyzeServerCjsGlobals(ast);
432
+ const parts = CJS_GLOBALS.filter((name) => analysis.reads.has(name) && !analysis.moduleBindings.has(name)).map((name) => `var ${name} = ${initializers[name]};`);
213
433
  return parts.length ? parts.join("") : null;
214
434
  }
215
435
  function analyzeServerCjsGlobals(ast) {
@@ -221,6 +441,7 @@ function analyzeServerCjsGlobals(ast) {
221
441
  for (const name of names) if (isCjsGlobalName(name)) moduleBindings.add(name);
222
442
  }
223
443
  function recordDirectTopLevelBindings(statement) {
444
+ if (statement.declare === true) return;
224
445
  switch (statement.type) {
225
446
  case "ImportDeclaration":
226
447
  for (const specifier of nodeArray(statement.specifiers)) {
@@ -256,7 +477,7 @@ function analyzeServerCjsGlobals(ast) {
256
477
  }
257
478
  return;
258
479
  case "VariableDeclaration":
259
- if (node.kind !== "var") return;
480
+ if (node.kind !== "var" || node.declare === true) return;
260
481
  for (const declarator of nodeArray(node.declarations)) {
261
482
  if (!isAstRecord(declarator) || declarator.type !== "VariableDeclarator") continue;
262
483
  recordBinding(declarator.id);
@@ -341,6 +562,10 @@ function isImportMetaUrlOrChainedNode(value) {
341
562
  if (isImportMetaUrlNode(value)) return true;
342
563
  return isAstRecord(value) && value.type === "ChainExpression" && isImportMetaUrlNode(value.expression);
343
564
  }
565
+ function isImportMetaUrlBaseNode(value) {
566
+ if (isImportMetaUrlOrChainedNode(value)) return true;
567
+ return isAstRecord(value) && value.type === "BinaryExpression" && value.operator === "+" && isAstRecord(value.left) && value.left.type === "Literal" && value.left.value === "" && isImportMetaUrlOrChainedNode(value.right);
568
+ }
344
569
  function isChainExpressionWrappingImportMetaUrl(value) {
345
570
  return isAstRecord(value) && value.type === "ChainExpression" && hasRange(value) && isImportMetaUrlNode(value.expression);
346
571
  }
@@ -1,3 +1,5 @@
1
+ import { stripViteModuleQuery } from "../utils/path.js";
2
+ import { magicStringTransformResult } from "./transform-result.js";
1
3
  import { normalizePath, parseAst } from "vite";
2
4
  import MagicString from "magic-string";
3
5
  //#region src/plugins/instrumentation-client.ts
@@ -8,7 +10,7 @@ function createInstrumentationClientTransformPlugin(getInstrumentationClientPath
8
10
  transform(code, id) {
9
11
  const instrumentationClientPath = getInstrumentationClientPath();
10
12
  if (!instrumentationClientPath) return null;
11
- if (normalizePath(id.split("?", 1)[0]) !== instrumentationClientPath) return null;
13
+ if (normalizePath(stripViteModuleQuery(id)) !== instrumentationClientPath) return null;
12
14
  if (code.includes("__vinextInstrumentationClientStart")) return null;
13
15
  const ast = parseAst(code);
14
16
  let insertPos = 0;
@@ -16,10 +18,7 @@ function createInstrumentationClientTransformPlugin(getInstrumentationClientPath
16
18
  const s = new MagicString(code);
17
19
  s.appendLeft(insertPos, "\nconst __vinextInstrumentationClientStart = performance.now();\n");
18
20
  s.append("\nconst __vinextInstrumentationClientEnd = performance.now();\nconst __vinextInstrumentationClientDuration = __vinextInstrumentationClientEnd - __vinextInstrumentationClientStart;\n// Match Next.js: only report slow client instrumentation during dev.\n// Production should execute the hook without additional timing overhead.\nif (__vinextInstrumentationClientDuration > 16) {\n console.log(`[Client Instrumentation Hook] Slow execution detected: ${__vinextInstrumentationClientDuration.toFixed(0)}ms (Note: Code download overhead is not included in this measurement)`);\n}\n");
19
- return {
20
- code: s.toString(),
21
- map: s.generateMap({ hires: true })
22
- };
21
+ return magicStringTransformResult(s, { hires: true });
23
22
  }
24
23
  };
25
24
  }
@@ -1,31 +1,19 @@
1
1
  import { createMiddlewareMissingExportError } from "../server/middleware-runtime.js";
2
- import { stripViteModuleQuery } from "../utils/path.js";
2
+ import { getAstName, scriptParserLanguage } from "./ast-utils.js";
3
3
  import { parseAst } from "vite";
4
4
  //#region src/plugins/middleware-export-validation.ts
5
- function parserLanguage(id) {
6
- const cleanId = stripViteModuleQuery(id).toLowerCase();
7
- if (cleanId.endsWith(".tsx")) return "tsx";
8
- if (cleanId.endsWith(".ts") || cleanId.endsWith(".mts") || cleanId.endsWith(".cts")) return "ts";
9
- return "jsx";
10
- }
11
- function astName(value) {
12
- if (!value) return null;
13
- if (typeof value.name === "string") return value.name;
14
- if (typeof value.value === "string") return value.value;
15
- return null;
16
- }
17
5
  function hasValidMiddlewareModuleExport(source, id, isProxy) {
18
- const ast = parseAst(source, { lang: parserLanguage(id) });
6
+ const ast = parseAst(source, { lang: scriptParserLanguage(id) ?? "jsx" });
19
7
  const expectedExport = isProxy ? "proxy" : "middleware";
20
8
  for (const statement of ast.body) {
21
9
  if (statement.type === "ExportDefaultDeclaration") return true;
22
10
  if (statement.type !== "ExportNamedDeclaration") continue;
23
11
  const declaration = statement.declaration;
24
- if (declaration?.type === "FunctionDeclaration" && astName(declaration.id) === expectedExport) return true;
12
+ if (declaration?.type === "FunctionDeclaration" && getAstName(declaration.id) === expectedExport) return true;
25
13
  if (declaration?.type === "VariableDeclaration") {
26
- for (const declarator of declaration.declarations ?? []) if (astName(declarator.id) === expectedExport) return true;
14
+ for (const declarator of declaration.declarations ?? []) if (getAstName(declarator.id) === expectedExport) return true;
27
15
  }
28
- for (const specifier of statement.specifiers ?? []) if (astName(specifier.exported ?? specifier.local) === expectedExport) return true;
16
+ for (const specifier of statement.specifiers ?? []) if (getAstName(specifier.exported ?? specifier.local) === expectedExport) return true;
29
17
  }
30
18
  return false;
31
19
  }
@@ -1,4 +1,5 @@
1
1
  import { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index.js";
2
+ import { stripViteModuleQuery } from "../utils/path.js";
2
3
  //#region src/plugins/middleware-server-only.ts
3
4
  /**
4
5
  * Allow `import 'server-only'` from neutral server targets (and any module
@@ -47,8 +48,7 @@ import { toSlash } from "../deps/.pnpm/pathslash@0.1.0/deps/pathslash/dist/index
47
48
  function createMiddlewareServerOnlyPlugin(options) {
48
49
  const tainted = /* @__PURE__ */ new Set();
49
50
  function canonicalizeId(id) {
50
- const queryIndex = id.indexOf("?");
51
- return toSlash(queryIndex === -1 ? id : id.slice(0, queryIndex));
51
+ return toSlash(stripViteModuleQuery(id));
52
52
  }
53
53
  function isTainted(id) {
54
54
  if (!id) return false;