vitest 4.1.12 → 5.1.0

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 (121) hide show
  1. package/LICENSE.md +192 -10
  2. package/browser/context.d.ts +7 -1
  3. package/browser/context.js +5 -5
  4. package/config.d.ts +0 -2
  5. package/dist/browser.d.ts +52 -21
  6. package/dist/browser.js +12 -13
  7. package/dist/chunks/{acorn.B2iPLyUM.js → acorn.C1kjbUFw.js} +30 -30
  8. package/dist/chunks/{base.B6Opl8PE.js → base.Cof-UHJf.js} +81 -52
  9. package/dist/chunks/{browser.d.BcoexmFG.d.ts → browser.d.C7tWgUvw.d.ts} +17 -14
  10. package/dist/chunks/{cac.DzDtg8hz.js → cac.BYbt0aJp.js} +143 -87
  11. package/dist/chunks/{cli-api.B0Pz1_R7.js → cli-api.COfZo8lK.js} +7160 -7189
  12. package/dist/chunks/config.d.B3YV4t0O.d.ts +3873 -0
  13. package/dist/chunks/{console.3WNpx0tS.js → console.CQZ877Hi.js} +69 -63
  14. package/dist/chunks/{constants.CPYnjOGj.js → constants.DLYM6cZY.js} +2 -2
  15. package/dist/chunks/coverage.9iqXE2gN.js +26 -0
  16. package/dist/chunks/{coverage.CTzCuANN.js → coverage.jGCktcGP.js} +7 -2
  17. package/dist/chunks/{creator.DgVhQm5q.js → creator.DHWmytIK.js} +65 -28
  18. package/dist/chunks/{defaults.9aQKnqFk.js → defaults.B1FCaFfh.js} +16 -9
  19. package/dist/chunks/display.BlTmubjj.js +194 -0
  20. package/dist/chunks/doctor.B-oPbwps.js +465 -0
  21. package/dist/chunks/{env.D4Lgay0q.js → env.BKKtU2WC.js} +2 -1
  22. package/dist/chunks/{environment.d.CrsxCzP1.d.ts → environment.d.BFQtFKdZ.d.ts} +9 -1
  23. package/dist/chunks/globals.ZKtKSkEf.js +29 -0
  24. package/dist/chunks/index.Bi0NXYPf.js +1708 -0
  25. package/dist/chunks/{index.CMESou6r.js → index.BoyTG_B7.js} +82 -81
  26. package/dist/chunks/index.CZzC1gGg.js +8501 -0
  27. package/dist/chunks/index.D0heQG4v.js +1318 -0
  28. package/dist/chunks/index.Di8au7q4.js +15665 -0
  29. package/dist/chunks/{index.Chj8NDwU.js → index.DmDMHCg8.js} +6 -12
  30. package/dist/chunks/{index.DXx9Dtk7.js → index.w_oBZ9N8.js} +25 -12
  31. package/dist/chunks/{init-forks.H5ZuobOQ.js → init-forks.BaDXQSD8.js} +7 -10
  32. package/dist/chunks/{init-threads.6kl1khcL.js → init-threads.ZX_Vov0z.js} +1 -1
  33. package/dist/chunks/{init.k9zZ9sLh.js → init.CO4AB7HZ.js} +113 -38
  34. package/dist/chunks/module-dependencies._2Eei3FO.js +71 -0
  35. package/dist/chunks/{native.DPzPHdi5.js → native.upB-V0CK.js} +50 -37
  36. package/dist/chunks/{nativeModuleMocker.BkNfQMkH.js → nativeModuleMocker.Dh5azSB4.js} +48 -19
  37. package/dist/chunks/{index.BCY_7LL2.js → nativeModuleRunner.9xPIMzi7.js} +110 -42
  38. package/dist/chunks/node.B9mkVmLH.js +47 -0
  39. package/dist/chunks/offset.Dy-5Fdfn.js +24 -0
  40. package/dist/chunks/pathe.M-eThtNZ.zq3TM4NT.js +492 -0
  41. package/dist/chunks/{reporters.d.DtoKVV2s.d.ts → plugin.d.LRFSN46m.d.ts} +2573 -1453
  42. package/dist/chunks/plugins.DPQHVT0p.js +37 -0
  43. package/dist/chunks/rawSnapshot.DqSiqIEx.js +356 -0
  44. package/dist/chunks/resolver.BzpmeQeT.js +48 -0
  45. package/dist/chunks/rpc.Uhkwr2NM.js +93 -0
  46. package/dist/chunks/rpc.d.3FOhdFx8.d.ts +75 -0
  47. package/dist/chunks/run.CjdgFZiW.js +4231 -0
  48. package/dist/chunks/setup-common.CqAQCXzx.js +36 -0
  49. package/dist/chunks/source-map.DakdQc29.js +1788 -0
  50. package/dist/chunks/source-map.d.BkG8YK_3.d.ts +89 -0
  51. package/dist/chunks/spy.DDMXghXv.js +509 -0
  52. package/dist/chunks/task-utils.d.D-gFPNFi.d.ts +144 -0
  53. package/dist/chunks/tinyrainbow.Do8I1XRG.js +88 -0
  54. package/dist/chunks/{utils.BS4fH3nR.js → utils.BBk_icFG.js} +50 -52
  55. package/dist/chunks/{utils.BX5Fg8C4.js → utils.DYj33du9.js} +1 -17
  56. package/dist/chunks/vm.b4MbCAJQ.js +1329 -0
  57. package/dist/chunks/{worker.d.ZpHpO4yb.d.ts → worker.d.CyJRpyfZ.d.ts} +34 -19
  58. package/dist/cli.js +5 -6
  59. package/dist/config.cjs +9 -6
  60. package/dist/config.d.ts +27 -25
  61. package/dist/config.js +3 -3
  62. package/dist/index.d.ts +471 -38
  63. package/dist/index.js +18 -19
  64. package/dist/module-evaluator.d.ts +64 -5
  65. package/dist/module-evaluator.js +122 -62
  66. package/dist/node.d.ts +355 -87
  67. package/dist/node.js +49 -73
  68. package/dist/runtime.d.ts +43 -6
  69. package/dist/runtime.js +7 -9
  70. package/dist/spy.js +1 -1
  71. package/dist/task-utils.js +290 -0
  72. package/dist/{chunks/traces.DT5aQ62U.js → traces.js} +3 -2
  73. package/dist/worker.d.ts +8 -10
  74. package/dist/worker.js +33 -43
  75. package/dist/workers/forks.js +30 -40
  76. package/dist/workers/runVmTests.js +66 -43
  77. package/dist/workers/threads.js +30 -40
  78. package/dist/workers/vmForks.js +19 -20
  79. package/dist/workers/vmThreads.js +19 -20
  80. package/globals.d.ts +19 -19
  81. package/index.cjs +3 -3
  82. package/optional-runtime-types.d.ts +1 -1
  83. package/optional-types.d.ts +1 -1
  84. package/package.json +59 -74
  85. package/suppress-warnings.cjs +1 -1
  86. package/dist/chunks/_commonjsHelpers.D26ty3Ew.js +0 -6
  87. package/dist/chunks/benchmark.CX_oY03V.js +0 -40
  88. package/dist/chunks/benchmark.d.DAaHLpsq.d.ts +0 -24
  89. package/dist/chunks/config.d.A1h_Y6Jt.d.ts +0 -232
  90. package/dist/chunks/coverage.DM_a_rWm.js +0 -1087
  91. package/dist/chunks/coverage.d.BZtK59WP.d.ts +0 -37
  92. package/dist/chunks/evaluatedModules.Dg1zASAC.js +0 -17
  93. package/dist/chunks/global.d.DVsSRdQ5.d.ts +0 -100
  94. package/dist/chunks/globals.Dj1TGiMC.js +0 -31
  95. package/dist/chunks/index.DC7d2Pf8.js +0 -729
  96. package/dist/chunks/index.DdgEv5B1.js +0 -42
  97. package/dist/chunks/index.UpGiHP7g.js +0 -4255
  98. package/dist/chunks/index.og1WyBLx.js +0 -6358
  99. package/dist/chunks/nativeModuleRunner.BIakptoF.js +0 -36
  100. package/dist/chunks/node.COQbm6gK.js +0 -14
  101. package/dist/chunks/plugin.d.DwFIiJ7i.d.ts +0 -38
  102. package/dist/chunks/rpc.MzXet3jl.js +0 -144
  103. package/dist/chunks/rpc.d.B_8sPU0w.d.ts +0 -30
  104. package/dist/chunks/setup-common.DYx3LtFI.js +0 -60
  105. package/dist/chunks/startVitestModuleRunner.DB-7oCpn.js +0 -740
  106. package/dist/chunks/suite.d.udJtyAgw.d.ts +0 -10
  107. package/dist/chunks/test.DNmyFkvJ.js +0 -4430
  108. package/dist/chunks/traces.d.D2T_R8rx.d.ts +0 -60
  109. package/dist/chunks/vm.CXMd5FHa.js +0 -785
  110. package/dist/coverage.d.ts +0 -123
  111. package/dist/coverage.js +0 -27
  112. package/dist/environments.d.ts +0 -22
  113. package/dist/environments.js +0 -5
  114. package/dist/reporters.d.ts +0 -27
  115. package/dist/reporters.js +0 -26
  116. package/dist/runners.d.ts +0 -70
  117. package/dist/runners.js +0 -19
  118. package/dist/snapshot.d.ts +0 -9
  119. package/dist/snapshot.js +0 -6
  120. package/dist/suite.d.ts +0 -5
  121. package/dist/suite.js +0 -8
@@ -0,0 +1,1708 @@
1
+ import fs__default from 'node:fs';
2
+ import { n as normalize, m as splitFileAndPostfix$1, j as join, o as isBareImport } from './pathe.M-eThtNZ.zq3TM4NT.js';
3
+ import { i as isBuiltin, a as isBrowserExternal, t as toBuiltin } from './modules.BJuCwlRJ.js';
4
+ import { E as EnvironmentTeardownError, a as getSafeWorkerState } from './utils.DYj33du9.js';
5
+ import { pathToFileURL, URL as URL$1 } from 'node:url';
6
+ import { distDir } from '../path.js';
7
+ import { VitestModuleEvaluator, unwrapId } from '../module-evaluator.js';
8
+ import { AsyncLocalStorage } from 'node:async_hooks';
9
+ import { isAbsolute, resolve } from 'node:path';
10
+ import vm from 'node:vm';
11
+ import { MockerRegistry, mockObject, RedirectedModule, AutomockedModule } from '@vitest/mocker';
12
+ import { findMockRedirect } from '@vitest/mocker/redirect';
13
+ import * as viteModuleRunner from 'vite/module-runner';
14
+ import { Traces } from '../traces.js';
15
+ import { createRequire } from 'node:module';
16
+ import { Console } from 'node:console';
17
+
18
+ class BareModuleMocker {
19
+ options;
20
+ static pendingIds = [];
21
+ spyModule;
22
+ primitives;
23
+ registries = /* @__PURE__ */ new Map();
24
+ mockContext = { callstack: null };
25
+ _otel;
26
+ constructor(options) {
27
+ this.options = options;
28
+ this._otel = options.traces;
29
+ this.primitives = {
30
+ Object,
31
+ Error,
32
+ Function,
33
+ RegExp,
34
+ Symbol: globalThis.Symbol,
35
+ Array,
36
+ Map
37
+ };
38
+ if (options.spyModule) this.spyModule = options.spyModule;
39
+ }
40
+ get root() {
41
+ return this.options.root;
42
+ }
43
+ get moduleDirectories() {
44
+ return this.options.moduleDirectories || [];
45
+ }
46
+ getMockerRegistry() {
47
+ const suite = this.getSuiteFilepath();
48
+ if (!this.registries.has(suite)) this.registries.set(suite, new MockerRegistry());
49
+ return this.registries.get(suite);
50
+ }
51
+ reset() {
52
+ for (const registry of this.registries.values()) for (const url of registry.keys()) this.invalidateModuleById(registry.get(url).id);
53
+ this.registries.clear();
54
+ BareModuleMocker.pendingIds = [];
55
+ }
56
+ invalidateModuleById(_id) {
57
+ // implemented by mockers that control the module runner
58
+ }
59
+ isModuleDirectory(path) {
60
+ return this.moduleDirectories.some((dir) => path.includes(dir));
61
+ }
62
+ getSuiteFilepath() {
63
+ return this.options.getCurrentTestFilepath() || "global";
64
+ }
65
+ createError(message, codeFrame) {
66
+ const Error = this.primitives.Error;
67
+ const error = new Error(message);
68
+ Object.assign(error, { codeFrame });
69
+ return error;
70
+ }
71
+ async resolveId(rawId, importer) {
72
+ return this._otel.$("vitest.mocker.resolve_id", { attributes: {
73
+ "vitest.module.raw_id": rawId,
74
+ "vitest.module.importer": rawId
75
+ } }, async (span) => {
76
+ const result = await this.options.resolveId(rawId, importer);
77
+ if (!result) {
78
+ span.addEvent("could not resolve id, fallback to unresolved values");
79
+ const id = normalizeModuleId(rawId);
80
+ span.setAttributes({
81
+ "vitest.module.id": id,
82
+ "vitest.module.url": rawId,
83
+ "vitest.module.external": id,
84
+ "vitest.module.fallback": true
85
+ });
86
+ return {
87
+ id,
88
+ url: rawId,
89
+ external: id
90
+ };
91
+ }
92
+ // external is node_module or unresolved module
93
+ // for example, some people mock "vscode" and don't have it installed
94
+ const external = !isAbsolute(result.file) || this.isModuleDirectory(result.file) ? normalizeModuleId(rawId) : null;
95
+ const id = normalizeModuleId(result.id);
96
+ span.setAttributes({
97
+ "vitest.module.id": id,
98
+ "vitest.module.url": result.url,
99
+ "vitest.module.external": external ?? false
100
+ });
101
+ return {
102
+ ...result,
103
+ id,
104
+ external
105
+ };
106
+ });
107
+ }
108
+ registeringMocks;
109
+ async resolveMocks() {
110
+ if (BareModuleMocker.pendingIds.length) {
111
+ const pendingIds = BareModuleMocker.pendingIds;
112
+ BareModuleMocker.pendingIds = [];
113
+ const registration = this.registerMocks(pendingIds, this.registeringMocks).finally(() => {
114
+ if (this.registeringMocks === registration) this.registeringMocks = void 0;
115
+ });
116
+ this.registeringMocks = registration;
117
+ }
118
+ await this.registeringMocks;
119
+ }
120
+ async registerMocks(pendingIds, previous) {
121
+ await previous?.catch(() => {});
122
+ const resolveMock = async (mock) => {
123
+ return {
124
+ mock,
125
+ ...await this.resolveId(mock.id, mock.importer)
126
+ };
127
+ };
128
+ // group consecutive mocks of the same action type together,
129
+ // resolve in parallel inside each group, but run groups sequentially
130
+ // to preserve mock/unmock ordering
131
+ const groups = groupByConsecutiveAction(pendingIds);
132
+ for (const group of groups) {
133
+ // apply in queue order: two mocks of the same path can resolve out of
134
+ // order, and the last queued one must win
135
+ const resolvedGroup = await Promise.all(group.map(resolveMock));
136
+ for (const { mock, id, url, external } of resolvedGroup) {
137
+ if (mock.action === "unmock") this.unmockPath(id);
138
+ if (mock.action === "mock") this.mockPath(mock.id, id, url, external, mock.type, mock.factory);
139
+ }
140
+ }
141
+ }
142
+ // public method to avoid circular dependency
143
+ getMockContext() {
144
+ return this.mockContext;
145
+ }
146
+ // path used to store mocked dependencies
147
+ getMockPath(dep) {
148
+ return `mock:${dep}`;
149
+ }
150
+ getDependencyMock(id) {
151
+ return this.getMockerRegistry().getById(fixLeadingSlashes(id));
152
+ }
153
+ getDependencyMockByUrl(url) {
154
+ return this.getMockerRegistry().get(url);
155
+ }
156
+ findMockRedirect(mockPath, external, rawId) {
157
+ return findMockRedirect(this.root, mockPath, external, rawId);
158
+ }
159
+ mockObject(object, mockExportsOrModuleType, moduleType) {
160
+ let mockExports;
161
+ if (mockExportsOrModuleType === "automock" || mockExportsOrModuleType === "autospy") {
162
+ moduleType = mockExportsOrModuleType;
163
+ mockExports = void 0;
164
+ } else mockExports = mockExportsOrModuleType;
165
+ moduleType ??= "automock";
166
+ const createMockInstance = this.spyModule?.createMockInstance;
167
+ if (!createMockInstance) throw this.createError("[vitest] `spyModule` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
168
+ return mockObject({
169
+ globalConstructors: this.primitives,
170
+ createMockInstance,
171
+ type: moduleType
172
+ }, object, mockExports);
173
+ }
174
+ unmockPath(id) {
175
+ this.getMockerRegistry().deleteById(id);
176
+ this.invalidateModuleById(id);
177
+ }
178
+ mockPath(originalId, id, url, external, mockType, factory) {
179
+ const registry = this.getMockerRegistry();
180
+ if (mockType === "manual") registry.register("manual", originalId, id, url, factory);
181
+ else if (mockType === "autospy") registry.register("autospy", originalId, id, url);
182
+ else {
183
+ const redirect = this.findMockRedirect(id, external, originalId);
184
+ if (redirect) registry.register("redirect", originalId, id, url, redirect);
185
+ else registry.register("automock", originalId, id, url);
186
+ }
187
+ // every time the mock is registered, we remove the previous one from the cache
188
+ this.invalidateModuleById(id);
189
+ }
190
+ async importActual(_rawId, _importer, _callstack) {
191
+ throw new Error(`importActual is not implemented`);
192
+ }
193
+ async importMock(_rawId, _importer, _callstack) {
194
+ throw new Error(`importMock is not implemented`);
195
+ }
196
+ queueMock(id, importer, factoryOrOptions) {
197
+ const mockType = getMockType(factoryOrOptions);
198
+ BareModuleMocker.pendingIds.push({
199
+ action: "mock",
200
+ id,
201
+ importer,
202
+ factory: typeof factoryOrOptions === "function" ? factoryOrOptions : void 0,
203
+ type: mockType
204
+ });
205
+ }
206
+ queueUnmock(id, importer) {
207
+ BareModuleMocker.pendingIds.push({
208
+ action: "unmock",
209
+ id,
210
+ importer
211
+ });
212
+ }
213
+ }
214
+ function getMockType(factoryOrOptions) {
215
+ if (!factoryOrOptions) return "automock";
216
+ if (typeof factoryOrOptions === "function") return "manual";
217
+ return factoryOrOptions.spy ? "autospy" : "automock";
218
+ }
219
+ // unique id that is not available as "$bare_import" like "test"
220
+ // https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
221
+ const prefixedBuiltins = /* @__PURE__ */ new Set([
222
+ "node:sea",
223
+ "node:sqlite",
224
+ "node:test",
225
+ "node:test/reporters"
226
+ ]);
227
+ const isWindows$1 = process.platform === "win32";
228
+ // transform file url to id
229
+ // virtual:custom -> virtual:custom
230
+ // \0custom -> \0custom
231
+ // /root/id -> /id
232
+ // /root/id.js -> /id.js
233
+ // C:/root/id.js -> /id.js
234
+ // C:\root\id.js -> /id.js
235
+ // TODO: expose this in vite/module-runner
236
+ function normalizeModuleId(file) {
237
+ if (prefixedBuiltins.has(file)) return file;
238
+ // if it's not in the root, keep it as a path, not a URL
239
+ return slash(file).replace(/^\/@fs\//, isWindows$1 ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\//, "/");
240
+ }
241
+ const windowsSlashRE = /\\/g;
242
+ function slash(p) {
243
+ return p.replace(windowsSlashRE, "/");
244
+ }
245
+ function groupByConsecutiveAction(mocks) {
246
+ const groups = [];
247
+ for (const mock of mocks) {
248
+ const last = groups.at(-1);
249
+ if (last?.[0].action === mock.action) last.push(mock);
250
+ else groups.push([mock]);
251
+ }
252
+ return groups;
253
+ }
254
+ const multipleSlashRe = /^\/+/;
255
+ // module-runner incorrectly replaces file:///path with `///path`
256
+ function fixLeadingSlashes(id) {
257
+ if (id.startsWith("//")) return id.replace(multipleSlashRe, "/");
258
+ return id;
259
+ }
260
+
261
+ // copied from vite
262
+ // https://github.com/vitejs/vite/blob/4417b4f305623b2850bd6ae6553834c017694672/packages/vite/src/shared/utils.ts
263
+ // https://github.com/vitejs/vite/blob/4417b4f305623b2850bd6ae6553834c017694672/packages/vite/src/node/utils.ts
264
+ const postfixRE = /[?#].*$/;
265
+ const trailingSeparatorRE = /[?&]$/;
266
+ function cleanUrl(url) {
267
+ return url.replace(postfixRE, "");
268
+ }
269
+ function splitFileAndPostfix(path) {
270
+ const file = cleanUrl(path);
271
+ return {
272
+ file,
273
+ postfix: path.slice(file.length)
274
+ };
275
+ }
276
+ function injectQuery(url, queryToInject) {
277
+ const { file, postfix } = splitFileAndPostfix(url);
278
+ return `${file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : /* hash only */ postfix}`;
279
+ }
280
+ function removeQuery(url, queryToRemove) {
281
+ return url.replace(new RegExp(`([?&])${queryToRemove}(?:&|$)`), "$1").replace(trailingSeparatorRE, "");
282
+ }
283
+
284
+ const spyModulePath = resolve(distDir, "spy.js");
285
+ class VitestMocker extends BareModuleMocker {
286
+ moduleRunner;
287
+ options;
288
+ filterPublicKeys;
289
+ // factories that run in the current async context, the innermost is last
290
+ factoryContexts = new AsyncLocalStorage();
291
+ pendingFactories = /* @__PURE__ */ new Map();
292
+ waitListeners = /* @__PURE__ */ new Set();
293
+ constructor(moduleRunner, options) {
294
+ super(options);
295
+ this.moduleRunner = moduleRunner;
296
+ this.options = options;
297
+ const context = this.options.context;
298
+ if (context) this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
299
+ const Symbol = this.primitives.Symbol;
300
+ this.filterPublicKeys = [
301
+ "__esModule",
302
+ Symbol.asyncIterator,
303
+ Symbol.hasInstance,
304
+ Symbol.isConcatSpreadable,
305
+ Symbol.iterator,
306
+ Symbol.match,
307
+ Symbol.matchAll,
308
+ Symbol.replace,
309
+ Symbol.search,
310
+ Symbol.split,
311
+ Symbol.species,
312
+ Symbol.toPrimitive,
313
+ Symbol.toStringTag,
314
+ Symbol.unscopables
315
+ ];
316
+ }
317
+ get evaluatedModules() {
318
+ return this.moduleRunner.evaluatedModules;
319
+ }
320
+ async initializeSpyModule() {
321
+ if (this.spyModule) return;
322
+ this.spyModule = await this.moduleRunner.import(spyModulePath);
323
+ }
324
+ invalidateModuleById(id) {
325
+ const mockId = this.getMockPath(id);
326
+ this.pendingFactories.delete(mockId);
327
+ const node = this.evaluatedModules.getModuleById(mockId);
328
+ if (node) {
329
+ this.evaluatedModules.invalidateModule(node);
330
+ node.mockedExports = void 0;
331
+ }
332
+ }
333
+ getMockContext() {
334
+ return { callstack: (this.factoryContexts.getStore()?.findLast((context) => this.pendingFactories.has(context.mockId)))?.callstack ?? null };
335
+ }
336
+ /**
337
+ * Whether the factory of this mock runs in the current async context,
338
+ * or waits for a factory that runs in it. Such imports get the original module.
339
+ * The callstack cannot tell it: all imports from one module share the same array.
340
+ */
341
+ isResolvingMock(mockId) {
342
+ if (!this.pendingFactories.has(mockId)) return false;
343
+ const factories = this.currentFactories();
344
+ return factories.includes(mockId) || this.waitsForFactories(mockId, factories);
345
+ }
346
+ /**
347
+ * Whether the module is still evaluating and waits for a factory
348
+ * that runs in the current async context.
349
+ */
350
+ isWaitingForFactory(mod) {
351
+ return !!mod.promise && !mod.evaluated && this.waitsForFactories(mod.id);
352
+ }
353
+ /**
354
+ * Waits for the module evaluation. If the module starts to wait
355
+ * for a factory that waits for it, the factory gets the partial exports.
356
+ */
357
+ awaitEvaluation(mod, request) {
358
+ if (!mod.promise || mod.evaluated) return request();
359
+ const factories = this.currentFactories();
360
+ if (!factories.length) return request();
361
+ let onWait;
362
+ const cycle = new Promise((resolve) => {
363
+ onWait = () => {
364
+ if (this.waitsForFactories(mod.id, factories)) resolve(mod.exports);
365
+ };
366
+ });
367
+ this.waitListeners.add(onWait);
368
+ return Promise.race([request(), cycle]).finally(() => this.waitListeners.delete(onWait));
369
+ }
370
+ currentFactories() {
371
+ return (this.factoryContexts.getStore() ?? []).map((context) => context.mockId);
372
+ }
373
+ waitsForFactories(id, factories = this.currentFactories()) {
374
+ const queue = [...factories];
375
+ const visited = new Set(factories);
376
+ // a factory that waits for the current one makes everything that waits for it wait too
377
+ while (queue.length) {
378
+ const waiting = this.pendingFactories.get(queue.pop())?.waiting;
379
+ if (waiting?.has(id)) return true;
380
+ waiting?.forEach((waiter) => {
381
+ if (this.pendingFactories.has(waiter) && !visited.has(waiter)) {
382
+ visited.add(waiter);
383
+ queue.push(waiter);
384
+ }
385
+ });
386
+ }
387
+ return false;
388
+ }
389
+ ensureModule(id, url) {
390
+ const node = this.evaluatedModules.ensureModule(id, url);
391
+ // TODO
392
+ node.meta = {
393
+ id,
394
+ url,
395
+ code: "",
396
+ file: null,
397
+ invalidate: false
398
+ };
399
+ return node;
400
+ }
401
+ callFunctionMock(id, url, mock, callstack) {
402
+ const node = this.ensureModule(id, url);
403
+ if (node.exports) return Promise.resolve(node.exports);
404
+ return this.resolveMockOnce(id, callstack, () => this.resolveFunctionMock(node, mock));
405
+ }
406
+ resolveMockOnce(id, callstack, resolve) {
407
+ const contexts = this.factoryContexts.getStore() ?? [];
408
+ const waiting = [...callstack, ...contexts.map((context) => context.mockId)];
409
+ const pending = this.pendingFactories.get(id);
410
+ if (pending) {
411
+ waiting.forEach((waiter) => pending.waiting.add(waiter));
412
+ this.waitListeners.forEach((onWait) => onWait());
413
+ return pending.promise;
414
+ }
415
+ const factory = {
416
+ promise: this.factoryContexts.run([...contexts, {
417
+ mockId: id,
418
+ callstack
419
+ }], resolve).finally(() => {
420
+ if (this.pendingFactories.get(id) === factory) this.pendingFactories.delete(id);
421
+ if (!this.pendingFactories.size)
422
+ // an enabled storage slows down every promise on Node 22
423
+ this.factoryContexts.disable();
424
+ }),
425
+ waiting: new Set(waiting)
426
+ };
427
+ this.pendingFactories.set(id, factory);
428
+ return factory.promise;
429
+ }
430
+ async resolveAutomock(url, mockId, evaluatedNode, callstack, type) {
431
+ const Object = this.primitives.Object;
432
+ // we have to define a separate object that will copy all properties into itself
433
+ // and can't just use the same `exports` define automatically by Vite before the evaluator
434
+ const exports = Object.create(null);
435
+ Object.defineProperty(exports, Symbol.toStringTag, {
436
+ value: "Module",
437
+ configurable: true,
438
+ writable: true
439
+ });
440
+ const node = this.ensureModule(mockId, this.getMockPath(evaluatedNode.url));
441
+ node.meta = evaluatedNode.meta;
442
+ node.file = evaluatedNode.file;
443
+ node.mockedExports = exports;
444
+ const mod = await this.moduleRunner.cachedRequest(url, node, callstack, void 0, true);
445
+ this.mockObject(mod, exports, type);
446
+ return exports;
447
+ }
448
+ async resolveFunctionMock(node, mock) {
449
+ const exports = await mock.resolve();
450
+ const moduleExports = new Proxy(exports, { get: (target, prop) => {
451
+ const val = target[prop];
452
+ // 'then' can exist on non-Promise objects, need nested instanceof check for logic to work
453
+ if (prop === "then") {
454
+ if (target instanceof Promise) return target.then.bind(target);
455
+ } else if (!(prop in target)) {
456
+ if (this.filterPublicKeys.includes(prop)) return;
457
+ throw this.createError(`[vitest] No "${String(prop)}" export is defined on the "${mock.raw}" mock. Did you forget to return it from "vi.mock"?
458
+ If you need to partially mock a module, you can use "importOriginal" helper inside:
459
+ `, `vi.mock(import("${mock.raw}"), async (importOriginal) => {
460
+ const actual = await importOriginal()
461
+ return {
462
+ ...actual,
463
+ // your mocked methods
464
+ }
465
+ })`);
466
+ }
467
+ return val;
468
+ } });
469
+ node.exports = moduleExports;
470
+ return moduleExports;
471
+ }
472
+ async importActual(rawId, importer, callstack) {
473
+ const { url } = await this.resolveId(rawId, importer);
474
+ const actualUrl = injectQuery(url, "_vitest_original");
475
+ const node = await this.moduleRunner.fetchModule(actualUrl, importer);
476
+ return await this.moduleRunner.cachedRequest(node.url, node, callstack || [importer], void 0, true);
477
+ }
478
+ async importMock(rawId, importer) {
479
+ const { id, url, external } = await this.resolveId(rawId, importer);
480
+ let mock = this.getDependencyMock(id);
481
+ if (!mock) {
482
+ const redirect = this.findMockRedirect(id, external, rawId);
483
+ if (redirect) mock = new RedirectedModule(rawId, id, rawId, redirect);
484
+ else mock = new AutomockedModule(rawId, id, rawId);
485
+ }
486
+ if (mock.type === "automock" || mock.type === "autospy") {
487
+ const node = await this.moduleRunner.fetchModule(url, importer);
488
+ const mod = await this.moduleRunner.cachedRequest(url, node, [importer], void 0, true);
489
+ const Object = this.primitives.Object;
490
+ return this.mockObject(mod, Object.create(Object.prototype), mock.type);
491
+ }
492
+ if (mock.type === "manual") {
493
+ const mockId = this.getMockPath(id);
494
+ return this.callFunctionMock(mockId, this.getMockPath(url), mock, [importer, mockId]);
495
+ }
496
+ const node = await this.moduleRunner.fetchModule(mock.redirect);
497
+ return this.moduleRunner.cachedRequest(mock.redirect, node, [importer], void 0, true);
498
+ }
499
+ async requestWithMockedModule(url, evaluatedNode, callstack, mock) {
500
+ return this._otel.$("vitest.mocker.evaluate", async (span) => {
501
+ const mockId = this.getMockPath(evaluatedNode.id);
502
+ span.setAttributes({
503
+ "vitest.module.id": mockId,
504
+ "vitest.mock.type": mock.type,
505
+ "vitest.mock.id": mock.id,
506
+ "vitest.mock.url": mock.url,
507
+ "vitest.mock.raw": mock.raw
508
+ });
509
+ if (mock.type === "automock" || mock.type === "autospy") {
510
+ const cache = this.evaluatedModules.getModuleById(mockId);
511
+ if (cache?.mockedExports) {
512
+ // while the original module evaluates, only its own imports get the partial object, like in a cycle
513
+ const isSelfImport = callstack.includes(evaluatedNode.id) || this.isResolvingMock(mockId);
514
+ if (!this.pendingFactories.has(mockId) || isSelfImport) return cache.mockedExports;
515
+ }
516
+ return this.resolveMockOnce(mockId, [...callstack, mockId], () => this.resolveAutomock(url, mockId, evaluatedNode, callstack, mock.type));
517
+ }
518
+ if (mock.type === "manual" && !callstack.includes(mockId) && !callstack.includes(url) && !this.isResolvingMock(mockId)) return this.callFunctionMock(mockId, this.getMockPath(url), mock, [...callstack, mockId]);
519
+ else if (mock.type === "redirect" && !callstack.includes(mock.redirect)) {
520
+ span.setAttribute("vitest.mock.redirect", mock.redirect);
521
+ return mock.redirect;
522
+ }
523
+ });
524
+ }
525
+ async mockedRequest(url, evaluatedNode, callstack) {
526
+ const mock = this.getDependencyMock(evaluatedNode.id);
527
+ if (!mock) return;
528
+ return this.requestWithMockedModule(url, evaluatedNode, callstack, mock);
529
+ }
530
+ }
531
+
532
+ class VitestTransport {
533
+ options;
534
+ evaluatedModules;
535
+ callstacks;
536
+ constructor(options, evaluatedModules, callstacks) {
537
+ this.options = options;
538
+ this.evaluatedModules = evaluatedModules;
539
+ this.callstacks = callstacks;
540
+ }
541
+ async invoke(event) {
542
+ if (event.type !== "custom") return { error: /* @__PURE__ */ new Error(`Vitest Module Runner doesn't support Vite HMR events.`) };
543
+ if (event.event !== "vite:invoke") return { error: /* @__PURE__ */ new Error(`Vitest Module Runner doesn't support ${event.event} event.`) };
544
+ const { name, data } = event.data;
545
+ if (name === "getBuiltins")
546
+ // we return an empty array here to avoid client-side builtin check,
547
+ // as we need builtins to go through `fetchModule`
548
+ return { result: [] };
549
+ if (name !== "fetchModule") return { error: /* @__PURE__ */ new Error(`Unknown method: ${name}. Expected "fetchModule".`) };
550
+ try {
551
+ return { result: await this.options.fetchModule(...data) };
552
+ } catch (cause) {
553
+ if (cause instanceof EnvironmentTeardownError) {
554
+ const [id, importer] = data;
555
+ let message = `Cannot load '${id}'${importer ? ` imported from ${importer}` : ""} after the environment was torn down. This is not a bug in Vitest.`;
556
+ const moduleNode = importer ? this.evaluatedModules.getModuleById(importer) : void 0;
557
+ const callstack = moduleNode ? this.callstacks.get(moduleNode) : void 0;
558
+ if (callstack) message += ` The last recorded callstack:\n- ${[
559
+ ...callstack,
560
+ importer,
561
+ id
562
+ ].reverse().join("\n- ")}`;
563
+ const error = new EnvironmentTeardownError(message);
564
+ if (cause.stack) error.stack = cause.stack.replace(cause.message, error.message);
565
+ return { error };
566
+ }
567
+ return { error: cause };
568
+ }
569
+ }
570
+ }
571
+
572
+ const createNodeImportMeta = (modulePath) => {
573
+ if (!viteModuleRunner.createDefaultImportMeta) throw new Error(`createNodeImportMeta is not supported in this version of Vite.`);
574
+ const defaultMeta = viteModuleRunner.createDefaultImportMeta(modulePath);
575
+ const href = defaultMeta.url;
576
+ const importMetaResolver = createImportMetaResolver() ?? defaultMeta.resolve;
577
+ return {
578
+ ...defaultMeta,
579
+ main: false,
580
+ resolve(id, parent) {
581
+ return importMetaResolver(id, parent ?? href);
582
+ }
583
+ };
584
+ };
585
+ function createImportMetaResolver() {
586
+ if (!import.meta.resolve) return;
587
+ return (specifier, importer) => import.meta.resolve(specifier, importer);
588
+ }
589
+ // @ts-expect-error overriding private method
590
+ class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
591
+ vitestOptions;
592
+ mocker;
593
+ moduleExecutionInfo;
594
+ _otel;
595
+ _callstacks;
596
+ constructor(vitestOptions) {
597
+ const options = vitestOptions;
598
+ const evaluatedModules = options.evaluatedModules;
599
+ const callstacks = /* @__PURE__ */ new WeakMap();
600
+ const transport = new VitestTransport(options.transport, evaluatedModules, callstacks);
601
+ super({
602
+ transport,
603
+ hmr: false,
604
+ evaluatedModules,
605
+ sourcemapInterceptor: "prepareStackTrace",
606
+ createImportMeta: vitestOptions.createImportMeta
607
+ }, options.evaluator);
608
+ this.vitestOptions = vitestOptions;
609
+ this._callstacks = callstacks;
610
+ this._otel = vitestOptions.traces || new Traces({ enabled: false });
611
+ this.moduleExecutionInfo = options.getWorkerState().moduleExecutionInfo;
612
+ this.mocker = options.mocker || new VitestMocker(this, {
613
+ spyModule: options.spyModule,
614
+ context: options.vm?.context,
615
+ traces: this._otel,
616
+ resolveId: options.transport.resolveId,
617
+ get root() {
618
+ return options.getWorkerState().config.root;
619
+ },
620
+ get moduleDirectories() {
621
+ return options.getWorkerState().config.deps.moduleDirectories || [];
622
+ },
623
+ getCurrentTestFilepath() {
624
+ return options.getWorkerState().filepath;
625
+ }
626
+ });
627
+ if (options.vm) options.vm.context.__vitest_mocker__ = this.mocker;
628
+ else Object.defineProperty(globalThis, "__vitest_mocker__", {
629
+ configurable: true,
630
+ writable: true,
631
+ value: this.mocker
632
+ });
633
+ }
634
+ /**
635
+ * Vite checks that the module has exports emulating the Node.js behaviour,
636
+ * but Vitest is more relaxed.
637
+ *
638
+ * We should keep the Vite behavior when there is a `strict` flag.
639
+ * @internal
640
+ */
641
+ processImport(exports) {
642
+ return exports;
643
+ }
644
+ async import(rawId, options) {
645
+ const resolved = await this._otel.$("vitest.module.resolve_id", { attributes: { "vitest.module.raw_id": rawId } }, async (span) => {
646
+ const result = await this.vitestOptions.transport.resolveId(rawId);
647
+ if (result) span.setAttributes({
648
+ "vitest.module.url": result.url,
649
+ "vitest.module.file": result.file,
650
+ "vitest.module.id": result.id
651
+ });
652
+ return result;
653
+ });
654
+ const url = resolved ? resolved.url : rawId;
655
+ if (options?.invalidate) {
656
+ const module = this.evaluatedModules.getModuleByUrl(url);
657
+ if (module?.evaluated) this.evaluatedModules.invalidateModule(module);
658
+ }
659
+ return super.import(url);
660
+ }
661
+ async fetchModule(url, importer) {
662
+ return await this.cachedModule(url, importer);
663
+ }
664
+ _cachedRequest(url, module, callstack = [], metadata) {
665
+ this.vitestOptions.getWorkerState().dependencies?.add(module.id);
666
+ return this.mocker.awaitEvaluation(module, () => super.cachedRequest(url, module, callstack, metadata));
667
+ }
668
+ /**
669
+ * @internal
670
+ */
671
+ async cachedRequest(url, mod, callstack = [], metadata, ignoreMock = false) {
672
+ // Track for a better error message if dynamic import is not resolved properly
673
+ this._callstacks.set(mod, callstack);
674
+ // the factory imports a module that waits for this factory, treat it as a cycle
675
+ if (mod.exports && this.mocker.isWaitingForFactory(mod)) return mod.exports;
676
+ if (ignoreMock) return this._cachedRequest(url, mod, callstack, metadata);
677
+ let mocked;
678
+ if (mod.meta && "mockedModule" in mod.meta) {
679
+ const mockId = this.mocker.getMockPath(mod.id);
680
+ const currentMock = this.mocker.getDependencyMock(mod.id);
681
+ // bypass mock and force "importActual" behavior when:
682
+ // - mock was removed by doUnmock (stale mockedModule in meta)
683
+ if (!currentMock) {
684
+ const node = await this.fetchModule(injectQuery(url, "_vitest_original"));
685
+ return this._cachedRequest(node.url, node, callstack, metadata);
686
+ }
687
+ if (callstack.includes(mockId) || this.mocker.isResolvingMock(mockId) || callstack.includes(url) || "redirect" in currentMock && callstack.includes(currentMock.redirect)) {
688
+ const node = await this.fetchModule(injectQuery(url, "_vitest_original"));
689
+ return this._cachedRequest(node.url, node, callstack, metadata);
690
+ }
691
+ if (currentMock.type === "automock" || currentMock.type === "autospy") {
692
+ const freshNode = await this.fetchModule(injectQuery(url, "_vitest_original"));
693
+ mocked = await this.mocker.requestWithMockedModule(url, freshNode, callstack, currentMock);
694
+ } else mocked = await this.mocker.requestWithMockedModule(url, mod, callstack, currentMock);
695
+ } else mocked = await this.mocker.mockedRequest(url, mod, callstack);
696
+ if (typeof mocked === "string") {
697
+ const node = await this.fetchModule(mocked);
698
+ return this._cachedRequest(mocked, node, callstack, metadata);
699
+ }
700
+ if (mocked != null && typeof mocked === "object") return mocked;
701
+ return this._cachedRequest(url, mod, callstack, metadata);
702
+ }
703
+ /** @internal */
704
+ _invalidateSubTreeById(ids, invalidated = /* @__PURE__ */ new Set()) {
705
+ for (const id of ids) {
706
+ if (invalidated.has(id)) continue;
707
+ const node = this.evaluatedModules.getModuleById(id);
708
+ if (!node) continue;
709
+ invalidated.add(id);
710
+ const subIds = Array.from(this.evaluatedModules.idToModuleMap).filter(([, mod]) => mod.importers.has(id)).map(([key]) => key);
711
+ if (subIds.length) this._invalidateSubTreeById(subIds, invalidated);
712
+ this.evaluatedModules.invalidateModule(node);
713
+ }
714
+ }
715
+ }
716
+
717
+ const platform = process.platform;
718
+ const bareVitestRegexp = /^@?vitest(?:\/|$)/;
719
+ const normalizedDistDir = normalize(distDir);
720
+ const relativeIds = {};
721
+ const externalizeMap = /* @__PURE__ */ new Map();
722
+ function getRelativeDistDir(root) {
723
+ const normalizedRoot = normalize(root).replace(/\/+$/, "") || "/";
724
+ const rootPrefix = normalizedRoot === "/" ? normalizedRoot : `${normalizedRoot}/`;
725
+ return normalizedDistDir.startsWith(rootPrefix) ? normalizedDistDir.slice(normalizedRoot.length) : "";
726
+ }
727
+ // all Vitest imports always need to be externalized
728
+ function getCachedVitestImport(id, state) {
729
+ if (id.startsWith("/@fs/") || id.startsWith("\\@fs\\")) id = id.slice(platform === "win32" ? 5 : 4);
730
+ if (externalizeMap.has(id)) return {
731
+ externalize: externalizeMap.get(id),
732
+ type: "module"
733
+ };
734
+ // always externalize Vitest because we import from there before running tests
735
+ // so we already have it cached by Node.js
736
+ const root = state().config.root;
737
+ const relativeRoot = relativeIds[root] ?? (relativeIds[root] = getRelativeDistDir(root));
738
+ if (id.includes(distDir) || id.includes(normalizedDistDir)) {
739
+ const { file, postfix } = splitFileAndPostfix$1(id);
740
+ // Vite resolves the Windows drive letter in upper case, but Node.js caches
741
+ // modules by URL, so keep the drive letter Vitest itself was loaded with
742
+ const path = file.startsWith(normalizedDistDir) ? distDir + file.slice(normalizedDistDir.length) : file;
743
+ const externalize = id.startsWith("file://") ? id : `${pathToFileURL(path)}${postfix}`;
744
+ externalizeMap.set(id, externalize);
745
+ return {
746
+ externalize,
747
+ type: "module"
748
+ };
749
+ }
750
+ if (relativeRoot && relativeRoot !== "/" && id.startsWith(relativeRoot)) {
751
+ const { file, postfix } = splitFileAndPostfix$1(id);
752
+ const path = join(root, file);
753
+ const externalize = `${pathToFileURL(path)}${postfix}`;
754
+ externalizeMap.set(id, externalize);
755
+ return {
756
+ externalize,
757
+ type: "module"
758
+ };
759
+ }
760
+ if (bareVitestRegexp.test(id)) {
761
+ externalizeMap.set(id, id);
762
+ return {
763
+ externalize: id,
764
+ type: "module"
765
+ };
766
+ }
767
+ return null;
768
+ }
769
+
770
+ const { readFileSync } = fs__default;
771
+ const VITEST_VM_CONTEXT_SYMBOL = "__vitest_vm_context__";
772
+ const cwd = process.cwd();
773
+ const isWindows = process.platform === "win32";
774
+ function startVitestModuleRunner(options) {
775
+ const traces = options.traces;
776
+ const state = () => getSafeWorkerState() || options.state;
777
+ const rpc = () => state().rpc;
778
+ // Wall time the worker spends blocked on server round-trips, measured as the
779
+ // union of in-flight intervals: sibling imports await fetches concurrently,
780
+ // so summing individual call durations would overcount the blocked time.
781
+ let fetchesInflight = 0;
782
+ let fetchesBusyStart = 0;
783
+ async function trackFetchTime(fetchPromise) {
784
+ if (fetchesInflight++ === 0) fetchesBusyStart = performance.now();
785
+ try {
786
+ return await fetchPromise;
787
+ } finally {
788
+ if (--fetchesInflight === 0) state().durations.fetch += performance.now() - fetchesBusyStart;
789
+ }
790
+ }
791
+ const environment = () => {
792
+ const environment = state().environment;
793
+ return environment.viteEnvironment || environment.name;
794
+ };
795
+ const vm = options.context && options.externalModulesExecutor ? {
796
+ context: options.context,
797
+ externalModulesExecutor: options.externalModulesExecutor
798
+ } : void 0;
799
+ // A fresh worker pays one sequential `fetch` round-trip per module in its
800
+ // test files' import graphs, even when the server has already processed
801
+ // them. So the module runner asks the server once for everything it has on
802
+ // disk for its first run request, and answers those fetches locally. Modules
803
+ // that only later files import are fetched one by one. Keeping the snapshot
804
+ // for the runner's lifetime is safe because a worker doesn't outlive a run,
805
+ // and the scheduled rerun picks up a file edited during a run.
806
+ let warmModules;
807
+ function fetchWarmModules() {
808
+ warmModules ??= rpc().fetchWarmModules(environment(), state().ctx.files.map((file) => file.filepath)).catch(() => null);
809
+ return warmModules;
810
+ }
811
+ // setup files are re-evaluated before every test file, so a reused worker
812
+ // resolves them and their `vi.mock` paths again each time
813
+ const resolvedIds = /* @__PURE__ */ new Map();
814
+ async function resolveId(id, importer) {
815
+ const key = `${environment()}\0${importer ?? ""}\0${id}`;
816
+ if (resolvedIds.has(key)) return resolvedIds.get(key);
817
+ const resolved = rpc().resolve(id, importer, environment());
818
+ resolvedIds.set(key, resolved);
819
+ resolved.then((value) => resolvedIds.set(key, value), () => resolvedIds.delete(key));
820
+ return resolved;
821
+ }
822
+ const evaluator = options.evaluator || new VitestModuleEvaluator(vm, {
823
+ traces,
824
+ metaEnv: state().metaEnv,
825
+ evaluatedModules: options.evaluatedModules,
826
+ get moduleExecutionInfo() {
827
+ return state().moduleExecutionInfo;
828
+ },
829
+ get interopDefault() {
830
+ return state().config.deps.interopDefault;
831
+ },
832
+ get injectCjsGlobals() {
833
+ return state().config.injectCjsGlobals;
834
+ },
835
+ getCurrentTestFilepath: () => state().filepath,
836
+ getEnvironmentName: environment,
837
+ getterTracker: state().getterTracker
838
+ });
839
+ const moduleRunner = new VitestModuleRunner({
840
+ spyModule: options.spyModule,
841
+ evaluatedModules: options.evaluatedModules,
842
+ evaluator,
843
+ traces,
844
+ mocker: options.mocker,
845
+ transport: {
846
+ async fetchModule(id, importer, options) {
847
+ const resolvingModules = state().resolvingModules;
848
+ if (isWindows) {
849
+ if (id[1] === ":") {
850
+ // The drive letter is different for whatever reason, we need to normalize it to CWD
851
+ if (id[0] !== cwd[0] && id[0].toUpperCase() === cwd[0].toUpperCase()) id = (cwd[0].toUpperCase() === cwd[0] ? id[0].toUpperCase() : id[0].toLowerCase()) + id.slice(1);
852
+ // always mark absolute windows paths, otherwise Vite will externalize it
853
+ id = `/@id/${id}`;
854
+ }
855
+ }
856
+ const vitest = getCachedVitestImport(id, state);
857
+ if (vitest) return vitest;
858
+ // strip _vitest_original query added by importActual so that
859
+ // the plugin pipeline sees the original import id (e.g. virtual modules' load hook)
860
+ const isImportActual = id.includes("_vitest_original");
861
+ if (isImportActual) id = removeQuery(id, "_vitest_original");
862
+ const rawId = unwrapId(id);
863
+ resolvingModules.add(rawId);
864
+ try {
865
+ if (VitestMocker.pendingIds.length || moduleRunner.mocker.registeringMocks) await moduleRunner.mocker.resolveMocks();
866
+ if (!isImportActual) {
867
+ const resolvedMock = moduleRunner.mocker.getDependencyMockByUrl(id);
868
+ if (resolvedMock?.type === "manual" || resolvedMock?.type === "redirect") return {
869
+ code: "",
870
+ file: null,
871
+ id: resolvedMock.id,
872
+ url: resolvedMock.url,
873
+ invalidate: false,
874
+ // the module node outlives the test file, so it must not keep the mock factory alive
875
+ mockedModule: true
876
+ };
877
+ }
878
+ if (isBuiltin(rawId)) return {
879
+ externalize: rawId,
880
+ type: "builtin"
881
+ };
882
+ if (isBrowserExternal(rawId)) return {
883
+ externalize: toBuiltin(rawId),
884
+ type: "builtin"
885
+ };
886
+ // if module is invalidated, the worker will be recreated,
887
+ // so cached is always true in a single worker
888
+ if (!isImportActual && options?.cached) return { cache: true };
889
+ // only dependency fetches consult the snapshot: by the time the
890
+ // first dependency is requested, the entry file is transformed and
891
+ // its import graph is connected on the server, so the snapshot
892
+ // actually covers the file's transitive dependencies
893
+ if (importer != null) {
894
+ const warm = await trackFetchTime(fetchWarmModules());
895
+ // the null prototype is not preserved by the IPC serialization, so
896
+ // ids like "constructor" must not fall through to Object.prototype
897
+ const warmResult = warm && (Object.hasOwn(warm, id) ? warm[id] : Object.hasOwn(warm, rawId) ? warm[rawId] : void 0);
898
+ if (warmResult) {
899
+ if ("tmp" in warmResult) try {
900
+ return {
901
+ code: readFileSync(warmResult.tmp, "utf-8"),
902
+ ...warmResult
903
+ };
904
+ } catch {}
905
+ else return warmResult;
906
+ }
907
+ }
908
+ const otelCarrier = traces?.getContextCarrier();
909
+ const result = await trackFetchTime(rpc().fetch(id, importer, environment(), options, otelCarrier));
910
+ if ("cached" in result) return {
911
+ code: readFileSync(result.tmp, "utf-8"),
912
+ ...result
913
+ };
914
+ return result;
915
+ } catch (cause) {
916
+ // rethrow vite error if it cannot load the module because it's not resolved
917
+ if (typeof cause === "object" && cause != null && cause.code === "ERR_LOAD_URL" || typeof cause?.message === "string" && cause.message.includes("Failed to load url") || typeof cause?.message === "string" && cause.message.startsWith("Cannot find module '")) {
918
+ const error = new Error(`Cannot find ${isBareImport(id) ? "package" : "module"} '${id}'${importer ? ` imported from ${importer}` : ""}`, { cause });
919
+ error.code = "ERR_MODULE_NOT_FOUND";
920
+ throw error;
921
+ }
922
+ throw cause;
923
+ } finally {
924
+ resolvingModules.delete(rawId);
925
+ }
926
+ },
927
+ resolveId
928
+ },
929
+ getWorkerState: state,
930
+ vm,
931
+ createImportMeta: options.createImportMeta
932
+ });
933
+ return moduleRunner;
934
+ }
935
+
936
+ // SEE https://github.com/jsdom/jsdom/blob/master/lib/jsdom/living/interfaces.js
937
+ const LIVING_KEYS = [
938
+ "DOMException",
939
+ "EventTarget",
940
+ "NamedNodeMap",
941
+ "Node",
942
+ "Attr",
943
+ "Element",
944
+ "DocumentFragment",
945
+ "DOMImplementation",
946
+ "Document",
947
+ "XMLDocument",
948
+ "CharacterData",
949
+ "Text",
950
+ "CDATASection",
951
+ "ProcessingInstruction",
952
+ "Comment",
953
+ "DocumentType",
954
+ "NodeList",
955
+ "RadioNodeList",
956
+ "HTMLCollection",
957
+ "HTMLOptionsCollection",
958
+ "DOMStringMap",
959
+ "DOMTokenList",
960
+ "StyleSheetList",
961
+ "HTMLElement",
962
+ "HTMLHeadElement",
963
+ "HTMLTitleElement",
964
+ "HTMLBaseElement",
965
+ "HTMLLinkElement",
966
+ "HTMLMetaElement",
967
+ "HTMLStyleElement",
968
+ "HTMLBodyElement",
969
+ "HTMLHeadingElement",
970
+ "HTMLParagraphElement",
971
+ "HTMLHRElement",
972
+ "HTMLPreElement",
973
+ "HTMLUListElement",
974
+ "HTMLOListElement",
975
+ "HTMLLIElement",
976
+ "HTMLMenuElement",
977
+ "HTMLDListElement",
978
+ "HTMLDivElement",
979
+ "HTMLAnchorElement",
980
+ "HTMLAreaElement",
981
+ "HTMLBRElement",
982
+ "HTMLButtonElement",
983
+ "HTMLCanvasElement",
984
+ "HTMLDataElement",
985
+ "HTMLDataListElement",
986
+ "HTMLDetailsElement",
987
+ "HTMLDialogElement",
988
+ "HTMLDirectoryElement",
989
+ "HTMLFieldSetElement",
990
+ "HTMLFontElement",
991
+ "HTMLFormElement",
992
+ "HTMLHtmlElement",
993
+ "HTMLImageElement",
994
+ "HTMLInputElement",
995
+ "HTMLLabelElement",
996
+ "HTMLLegendElement",
997
+ "HTMLMapElement",
998
+ "HTMLMarqueeElement",
999
+ "HTMLMediaElement",
1000
+ "HTMLMeterElement",
1001
+ "HTMLModElement",
1002
+ "HTMLOptGroupElement",
1003
+ "HTMLOptionElement",
1004
+ "HTMLOutputElement",
1005
+ "HTMLPictureElement",
1006
+ "HTMLProgressElement",
1007
+ "HTMLQuoteElement",
1008
+ "HTMLScriptElement",
1009
+ "HTMLSelectElement",
1010
+ "HTMLSlotElement",
1011
+ "HTMLSourceElement",
1012
+ "HTMLSpanElement",
1013
+ "HTMLTableCaptionElement",
1014
+ "HTMLTableCellElement",
1015
+ "HTMLTableColElement",
1016
+ "HTMLTableElement",
1017
+ "HTMLTimeElement",
1018
+ "HTMLTableRowElement",
1019
+ "HTMLTableSectionElement",
1020
+ "HTMLTemplateElement",
1021
+ "HTMLTextAreaElement",
1022
+ "HTMLUnknownElement",
1023
+ "HTMLFrameElement",
1024
+ "HTMLFrameSetElement",
1025
+ "HTMLIFrameElement",
1026
+ "HTMLEmbedElement",
1027
+ "HTMLObjectElement",
1028
+ "HTMLParamElement",
1029
+ "HTMLVideoElement",
1030
+ "HTMLAudioElement",
1031
+ "HTMLTrackElement",
1032
+ "HTMLFormControlsCollection",
1033
+ "SVGElement",
1034
+ "SVGGraphicsElement",
1035
+ "SVGSVGElement",
1036
+ "SVGTitleElement",
1037
+ "SVGAnimatedString",
1038
+ "SVGNumber",
1039
+ "SVGStringList",
1040
+ "Event",
1041
+ "CloseEvent",
1042
+ "CustomEvent",
1043
+ "MessageEvent",
1044
+ "ErrorEvent",
1045
+ "HashChangeEvent",
1046
+ "PopStateEvent",
1047
+ "StorageEvent",
1048
+ "ProgressEvent",
1049
+ "PageTransitionEvent",
1050
+ "SubmitEvent",
1051
+ "UIEvent",
1052
+ "FocusEvent",
1053
+ "InputEvent",
1054
+ "MouseEvent",
1055
+ "KeyboardEvent",
1056
+ "TouchEvent",
1057
+ "CompositionEvent",
1058
+ "WheelEvent",
1059
+ "BarProp",
1060
+ "External",
1061
+ "Location",
1062
+ "History",
1063
+ "Screen",
1064
+ "Crypto",
1065
+ "Performance",
1066
+ "Navigator",
1067
+ "PluginArray",
1068
+ "MimeTypeArray",
1069
+ "Plugin",
1070
+ "MimeType",
1071
+ "FileReader",
1072
+ "FormData",
1073
+ "Blob",
1074
+ "File",
1075
+ "FileList",
1076
+ "ValidityState",
1077
+ "DOMParser",
1078
+ "XMLSerializer",
1079
+ "XMLHttpRequestEventTarget",
1080
+ "XMLHttpRequestUpload",
1081
+ "XMLHttpRequest",
1082
+ "WebSocket",
1083
+ "NodeFilter",
1084
+ "NodeIterator",
1085
+ "TreeWalker",
1086
+ "AbstractRange",
1087
+ "Range",
1088
+ "StaticRange",
1089
+ "Selection",
1090
+ "Storage",
1091
+ "CustomElementRegistry",
1092
+ "ShadowRoot",
1093
+ "MutationObserver",
1094
+ "MutationRecord",
1095
+ "Uint8Array",
1096
+ "Uint16Array",
1097
+ "Uint32Array",
1098
+ "Uint8ClampedArray",
1099
+ "Int8Array",
1100
+ "Int16Array",
1101
+ "Int32Array",
1102
+ "Float32Array",
1103
+ "Float64Array",
1104
+ "ArrayBuffer",
1105
+ "DOMRectReadOnly",
1106
+ "DOMRect",
1107
+ "Image",
1108
+ "Audio",
1109
+ "Option",
1110
+ "CSS"
1111
+ ];
1112
+ const OTHER_KEYS = [
1113
+ "addEventListener",
1114
+ "alert",
1115
+ "blur",
1116
+ "cancelAnimationFrame",
1117
+ "close",
1118
+ "confirm",
1119
+ "createPopup",
1120
+ "dispatchEvent",
1121
+ "document",
1122
+ "focus",
1123
+ "frames",
1124
+ "getComputedStyle",
1125
+ "history",
1126
+ "innerHeight",
1127
+ "innerWidth",
1128
+ "length",
1129
+ "localStorage",
1130
+ "location",
1131
+ "matchMedia",
1132
+ "moveBy",
1133
+ "moveTo",
1134
+ "name",
1135
+ "navigator",
1136
+ "open",
1137
+ "outerHeight",
1138
+ "outerWidth",
1139
+ "pageXOffset",
1140
+ "pageYOffset",
1141
+ "parent",
1142
+ "postMessage",
1143
+ "print",
1144
+ "prompt",
1145
+ "removeEventListener",
1146
+ "requestAnimationFrame",
1147
+ "resizeBy",
1148
+ "resizeTo",
1149
+ "screen",
1150
+ "screenLeft",
1151
+ "screenTop",
1152
+ "screenX",
1153
+ "screenY",
1154
+ "scroll",
1155
+ "scrollBy",
1156
+ "scrollLeft",
1157
+ "scrollTo",
1158
+ "scrollTop",
1159
+ "scrollX",
1160
+ "scrollY",
1161
+ "self",
1162
+ "sessionStorage",
1163
+ "stop",
1164
+ "top",
1165
+ "Window",
1166
+ "window"
1167
+ ];
1168
+ const KEYS = LIVING_KEYS.concat(OTHER_KEYS);
1169
+
1170
+ const skipKeys = [
1171
+ "window",
1172
+ "self",
1173
+ "top",
1174
+ "parent"
1175
+ ];
1176
+ function getWindowKeys(global, win, additionalKeys = []) {
1177
+ const keysArray = [...additionalKeys, ...KEYS];
1178
+ return new Set(keysArray.concat(Object.getOwnPropertyNames(win)).filter((k) => {
1179
+ if (skipKeys.includes(k)) return false;
1180
+ if (k in global) return keysArray.includes(k);
1181
+ return true;
1182
+ }));
1183
+ }
1184
+ function isClassLikeName(name) {
1185
+ return name[0] === name[0].toUpperCase();
1186
+ }
1187
+ function populateGlobal(global, win, options = {}) {
1188
+ const { bindFunctions = false } = options;
1189
+ const keys = getWindowKeys(global, win, options.additionalKeys);
1190
+ const originals = /* @__PURE__ */ new Map();
1191
+ const overriddenKeys = /* @__PURE__ */ new Set([...KEYS, ...options.additionalKeys || []]);
1192
+ const overrideObject = /* @__PURE__ */ new Map();
1193
+ for (const key of keys) {
1194
+ const boundFunction = bindFunctions && typeof win[key] === "function" && !isClassLikeName(key) && win[key].bind(win);
1195
+ if (overriddenKeys.has(key) && key in global) {
1196
+ // capture the descriptor instead of the value to avoid invoking native
1197
+ // lazy getters such as Node's `localStorage`, which warns when accessed
1198
+ // without `--localstorage-file`
1199
+ const descriptor = Object.getOwnPropertyDescriptor(global, key) ?? {
1200
+ value: global[key],
1201
+ configurable: true,
1202
+ writable: true,
1203
+ enumerable: true
1204
+ };
1205
+ originals.set(key, descriptor);
1206
+ }
1207
+ Object.defineProperty(global, key, {
1208
+ get() {
1209
+ if (overrideObject.has(key)) return overrideObject.get(key);
1210
+ if (boundFunction) return boundFunction;
1211
+ return win[key];
1212
+ },
1213
+ set(v) {
1214
+ overrideObject.set(key, v);
1215
+ // propagate changes to underlying window implementation,
1216
+ // which can affect other window API behavior internally, e.g.
1217
+ // updating `innerWidth` affects `matchMedia("(max-width: *)")` on happy-dom.
1218
+ win[key] = v;
1219
+ },
1220
+ configurable: true
1221
+ });
1222
+ }
1223
+ global.window = global;
1224
+ global.self = global;
1225
+ global.top = global;
1226
+ global.parent = global;
1227
+ if (global.global) global.global = global;
1228
+ // rewrite defaultView to reference the same global context
1229
+ if (global.document && global.document.defaultView) Object.defineProperty(global.document, "defaultView", {
1230
+ get: () => global,
1231
+ enumerable: true,
1232
+ configurable: true
1233
+ });
1234
+ skipKeys.forEach((k) => keys.add(k));
1235
+ return {
1236
+ keys,
1237
+ skipKeys,
1238
+ originals
1239
+ };
1240
+ }
1241
+
1242
+ var edge = {
1243
+ name: "edge-runtime",
1244
+ viteEnvironment: "ssr",
1245
+ async setupVM() {
1246
+ const { EdgeVM } = await import('@edge-runtime/vm');
1247
+ const vm = new EdgeVM({ extend: (context) => {
1248
+ context.global = context;
1249
+ context.Buffer = Buffer;
1250
+ return context;
1251
+ } });
1252
+ return {
1253
+ getVmContext() {
1254
+ return vm.context;
1255
+ },
1256
+ teardown() {
1257
+ // nothing to teardown
1258
+ }
1259
+ };
1260
+ },
1261
+ async setup(global) {
1262
+ const { EdgeVM } = await import('@edge-runtime/vm');
1263
+ const vm = new EdgeVM({ extend: (context) => {
1264
+ context.global = context;
1265
+ context.Buffer = Buffer;
1266
+ KEYS.forEach((key) => {
1267
+ if (key in global) context[key] = global[key];
1268
+ });
1269
+ return context;
1270
+ } });
1271
+ const { keys, originals } = populateGlobal(global, vm.context, { bindFunctions: true });
1272
+ return { teardown(global) {
1273
+ keys.forEach((key) => delete global[key]);
1274
+ originals.forEach((d, k) => Object.defineProperty(global, k, d));
1275
+ } };
1276
+ }
1277
+ };
1278
+
1279
+ async function teardownWindow(win) {
1280
+ if (win.close && win.happyDOM.abort) {
1281
+ await win.happyDOM.abort();
1282
+ win.close();
1283
+ } else win.happyDOM.cancelAsync();
1284
+ }
1285
+ var happy = {
1286
+ name: "happy-dom",
1287
+ viteEnvironment: "client",
1288
+ async setupVM({ happyDOM = {} }) {
1289
+ const { Window } = await import('happy-dom');
1290
+ let win = new Window({
1291
+ ...happyDOM,
1292
+ console: console && globalThis.console ? globalThis.console : void 0,
1293
+ url: happyDOM.url || "http://localhost:3000",
1294
+ settings: {
1295
+ ...happyDOM.settings,
1296
+ disableErrorCapturing: true
1297
+ }
1298
+ });
1299
+ // TODO: browser doesn't expose Buffer, but a lot of dependencies use it
1300
+ win.Buffer = Buffer;
1301
+ // inject structuredClone if it exists
1302
+ if (typeof structuredClone !== "undefined" && !win.structuredClone) win.structuredClone = structuredClone;
1303
+ return {
1304
+ getVmContext() {
1305
+ return win;
1306
+ },
1307
+ async teardown() {
1308
+ await teardownWindow(win);
1309
+ win = void 0;
1310
+ }
1311
+ };
1312
+ },
1313
+ async setup(global, { happyDOM = {} }) {
1314
+ // happy-dom v3 introduced a breaking change to Window, but
1315
+ // provides GlobalWindow as a way to use previous behaviour
1316
+ const { Window, GlobalWindow } = await import('happy-dom');
1317
+ const win = new (GlobalWindow || Window)({
1318
+ ...happyDOM,
1319
+ console: console && global.console ? global.console : void 0,
1320
+ url: happyDOM.url || "http://localhost:3000",
1321
+ settings: {
1322
+ ...happyDOM.settings,
1323
+ disableErrorCapturing: true
1324
+ }
1325
+ });
1326
+ const { keys, originals } = populateGlobal(global, win, {
1327
+ bindFunctions: true,
1328
+ // jsdom doesn't support fetch API, but happy-dom does
1329
+ additionalKeys: [
1330
+ "Request",
1331
+ "Response",
1332
+ "MessagePort",
1333
+ "fetch",
1334
+ "Headers",
1335
+ "AbortController",
1336
+ "AbortSignal",
1337
+ "URL",
1338
+ "URLSearchParams",
1339
+ "FormData"
1340
+ ]
1341
+ });
1342
+ return { async teardown(global) {
1343
+ await teardownWindow(win);
1344
+ keys.forEach((key) => delete global[key]);
1345
+ originals.forEach((d, k) => Object.defineProperty(global, k, d));
1346
+ } };
1347
+ }
1348
+ };
1349
+
1350
+ function catchWindowErrors(window) {
1351
+ let userErrorListenerCount = 0;
1352
+ function throwUnhandlerError(e) {
1353
+ if (userErrorListenerCount === 0 && e.error != null) {
1354
+ e.preventDefault();
1355
+ process.emit("uncaughtException", e.error);
1356
+ }
1357
+ }
1358
+ const addEventListener = window.addEventListener.bind(window);
1359
+ const removeEventListener = window.removeEventListener.bind(window);
1360
+ window.addEventListener("error", throwUnhandlerError);
1361
+ window.addEventListener = function(...args) {
1362
+ if (args[0] === "error") userErrorListenerCount++;
1363
+ return addEventListener.apply(this, args);
1364
+ };
1365
+ window.removeEventListener = function(...args) {
1366
+ if (args[0] === "error" && userErrorListenerCount) userErrorListenerCount--;
1367
+ return removeEventListener.apply(this, args);
1368
+ };
1369
+ return function clearErrorHandlers() {
1370
+ window.removeEventListener("error", throwUnhandlerError);
1371
+ };
1372
+ }
1373
+ let NodeFormData_;
1374
+ let NodeBlob_;
1375
+ let NodeRequest_;
1376
+ function getResourceOptions(jsdom, resources, userAgent) {
1377
+ const ResourceLoader = jsdom.ResourceLoader;
1378
+ // jsdom 28 replaced ResourceLoader with a resources options object.
1379
+ if (!ResourceLoader) return { resources: userAgent ? { userAgent } : resources };
1380
+ return {
1381
+ resources: resources ?? (userAgent ? new ResourceLoader({ userAgent }) : void 0),
1382
+ userAgent
1383
+ };
1384
+ }
1385
+ var jsdom = {
1386
+ name: "jsdom",
1387
+ viteEnvironment: "client",
1388
+ async setupVM({ jsdom = {} }) {
1389
+ // delay initialization because it takes ~1s
1390
+ NodeFormData_ = globalThis.FormData;
1391
+ NodeBlob_ = globalThis.Blob;
1392
+ NodeRequest_ = globalThis.Request;
1393
+ const jsdomModule = await import('jsdom');
1394
+ const { CookieJar, JSDOM, VirtualConsole } = jsdomModule;
1395
+ const { html = "<!DOCTYPE html>", userAgent, url = "http://localhost:3000", contentType = "text/html", pretendToBeVisual = true, includeNodeLocations = false, runScripts = "dangerously", resources, console = false, cookieJar = false, ...restOptions } = jsdom;
1396
+ let virtualConsole;
1397
+ if (console && globalThis.console) {
1398
+ virtualConsole = new VirtualConsole();
1399
+ // jsdom <27
1400
+ if ("sendTo" in virtualConsole) virtualConsole.sendTo(globalThis.console);
1401
+ else virtualConsole.forwardTo(globalThis.console);
1402
+ }
1403
+ let dom = new JSDOM(html, {
1404
+ pretendToBeVisual,
1405
+ runScripts,
1406
+ url,
1407
+ virtualConsole,
1408
+ cookieJar: cookieJar ? new CookieJar() : void 0,
1409
+ includeNodeLocations,
1410
+ contentType,
1411
+ ...getResourceOptions(jsdomModule, resources, userAgent),
1412
+ ...restOptions
1413
+ });
1414
+ const clearAddEventListenerPatch = patchAddEventListener(dom.window);
1415
+ const clearWindowErrors = catchWindowErrors(dom.window);
1416
+ const utils = createCompatUtils(dom.window);
1417
+ // TODO: browser doesn't expose Buffer, but a lot of dependencies use it
1418
+ dom.window.Buffer = Buffer;
1419
+ dom.window.jsdom = dom;
1420
+ dom.window.Request = createCompatRequest(utils);
1421
+ dom.window.URL = createJSDOMCompatURL(utils);
1422
+ for (const name of [
1423
+ "structuredClone",
1424
+ "BroadcastChannel",
1425
+ "MessageChannel",
1426
+ "MessagePort",
1427
+ "TextEncoder",
1428
+ "TextDecoder"
1429
+ ]) {
1430
+ const value = globalThis[name];
1431
+ if (typeof value !== "undefined" && typeof dom.window[name] === "undefined") dom.window[name] = value;
1432
+ }
1433
+ for (const name of [
1434
+ "fetch",
1435
+ "Response",
1436
+ "Headers",
1437
+ "AbortController",
1438
+ "AbortSignal",
1439
+ "URLSearchParams"
1440
+ ]) {
1441
+ const value = globalThis[name];
1442
+ if (typeof value !== "undefined") dom.window[name] = value;
1443
+ }
1444
+ return {
1445
+ getVmContext() {
1446
+ return dom.getInternalVMContext();
1447
+ },
1448
+ teardown() {
1449
+ clearAddEventListenerPatch();
1450
+ clearWindowErrors();
1451
+ dom.window.close();
1452
+ dom = void 0;
1453
+ }
1454
+ };
1455
+ },
1456
+ async setup(global, { jsdom = {} }) {
1457
+ // delay initialization because it takes ~1s
1458
+ NodeFormData_ = globalThis.FormData;
1459
+ NodeBlob_ = globalThis.Blob;
1460
+ NodeRequest_ = globalThis.Request;
1461
+ const jsdomModule = await import('jsdom');
1462
+ const { CookieJar, JSDOM, VirtualConsole } = jsdomModule;
1463
+ const { html = "<!DOCTYPE html>", userAgent, url = "http://localhost:3000", contentType = "text/html", pretendToBeVisual = true, includeNodeLocations = false, runScripts = "dangerously", resources, console = false, cookieJar = false, ...restOptions } = jsdom;
1464
+ let virtualConsole;
1465
+ if (console && globalThis.console) {
1466
+ virtualConsole = new VirtualConsole();
1467
+ // jsdom <27
1468
+ if ("sendTo" in virtualConsole) virtualConsole.sendTo(globalThis.console);
1469
+ else virtualConsole.forwardTo(globalThis.console);
1470
+ }
1471
+ const dom = new JSDOM(html, {
1472
+ pretendToBeVisual,
1473
+ runScripts,
1474
+ url,
1475
+ virtualConsole,
1476
+ cookieJar: cookieJar ? new CookieJar() : void 0,
1477
+ includeNodeLocations,
1478
+ contentType,
1479
+ ...getResourceOptions(jsdomModule, resources, userAgent),
1480
+ ...restOptions
1481
+ });
1482
+ const clearAddEventListenerPatch = patchAddEventListener(dom.window);
1483
+ const { keys, originals } = populateGlobal(global, dom.window, { bindFunctions: true });
1484
+ const clearWindowErrors = catchWindowErrors(global);
1485
+ const utils = createCompatUtils(dom.window);
1486
+ global.jsdom = dom;
1487
+ global.Request = createCompatRequest(utils);
1488
+ global.URL = createJSDOMCompatURL(utils);
1489
+ return { teardown(global) {
1490
+ clearAddEventListenerPatch();
1491
+ clearWindowErrors();
1492
+ dom.window.close();
1493
+ delete global.jsdom;
1494
+ keys.forEach((key) => delete global[key]);
1495
+ originals.forEach((d, k) => Object.defineProperty(global, k, d));
1496
+ } };
1497
+ }
1498
+ };
1499
+ function createCompatRequest(utils) {
1500
+ class Request extends NodeRequest_ {
1501
+ constructor(...args) {
1502
+ const [input, init] = args;
1503
+ if (init?.body != null) {
1504
+ const compatInit = { ...init };
1505
+ if (init.body instanceof utils.window.Blob) compatInit.body = utils.makeCompatBlob(init.body);
1506
+ if (init.body instanceof utils.window.FormData) compatInit.body = utils.makeCompatFormData(init.body);
1507
+ super(input, compatInit);
1508
+ } else super(...args);
1509
+ }
1510
+ static [Symbol.hasInstance](instance) {
1511
+ return instance instanceof NodeRequest_;
1512
+ }
1513
+ }
1514
+ return Request;
1515
+ }
1516
+ function createJSDOMCompatURL(utils) {
1517
+ class URL extends URL$1 {
1518
+ static createObjectURL(blob) {
1519
+ if (blob instanceof utils.window.Blob) {
1520
+ const compatBlob = utils.makeCompatBlob(blob);
1521
+ return URL$1.createObjectURL(compatBlob);
1522
+ }
1523
+ return URL$1.createObjectURL(blob);
1524
+ }
1525
+ static [Symbol.hasInstance](instance) {
1526
+ return instance instanceof URL$1;
1527
+ }
1528
+ }
1529
+ return URL;
1530
+ }
1531
+ // jsdom keeps Blob bytes on an internal "impl" object and exposes no synchronous
1532
+ // public way to read them, so this reaches into its generated bindings
1533
+ function createBlobImplGetter(window) {
1534
+ const _require = createRequire(import.meta.url);
1535
+ // jsdom 28.1 moved the generated bindings; jsdom has no "exports" map, so both subpaths resolve
1536
+ for (const id of ["jsdom/lib/generated/idl/utils.js", "jsdom/lib/jsdom/living/generated/utils.js"]) try {
1537
+ const { implForWrapper } = _require(id);
1538
+ if (typeof implForWrapper === "function") return implForWrapper;
1539
+ } catch {}
1540
+ // jsdom < 30.1 also stores the impl under an own Symbol("impl")
1541
+ const implSymbol = Object.getOwnPropertySymbols(new window.Blob())[0];
1542
+ return (blob) => blob[implSymbol];
1543
+ }
1544
+ let getBlobImpl;
1545
+ function createCompatUtils(window) {
1546
+ getBlobImpl ??= createBlobImplGetter(window);
1547
+ const utils = {
1548
+ window,
1549
+ makeCompatFormData(formData) {
1550
+ const nodeFormData = new NodeFormData_();
1551
+ formData.forEach((value, key) => {
1552
+ if (value instanceof window.Blob) nodeFormData.append(key, utils.makeCompatBlob(value));
1553
+ else nodeFormData.append(key, value);
1554
+ });
1555
+ return nodeFormData;
1556
+ },
1557
+ makeCompatBlob(blob) {
1558
+ const impl = getBlobImpl(blob);
1559
+ if (!impl) throw new TypeError("Vitest cannot read the bytes of a jsdom Blob. This is a Vitest bug, please report it with your jsdom version.");
1560
+ // jsdom 28 renamed `_buffer` to `_bytes`
1561
+ return new NodeBlob_([impl._bytes ?? impl._buffer], { type: blob.type });
1562
+ }
1563
+ };
1564
+ return utils;
1565
+ }
1566
+ function patchAddEventListener(window) {
1567
+ const abortControllers = /* @__PURE__ */ new WeakMap();
1568
+ const JSDOMAbortSignal = window.AbortSignal;
1569
+ const JSDOMAbortController = window.AbortController;
1570
+ const originalAddEventListener = window.EventTarget.prototype.addEventListener;
1571
+ function getJsdomAbortController(signal) {
1572
+ if (!abortControllers.has(signal)) {
1573
+ const jsdomAbortController = new JSDOMAbortController();
1574
+ signal.addEventListener("abort", () => {
1575
+ jsdomAbortController.abort(signal.reason);
1576
+ });
1577
+ abortControllers.set(signal, jsdomAbortController);
1578
+ }
1579
+ return abortControllers.get(signal);
1580
+ }
1581
+ window.EventTarget.prototype.addEventListener = function addEventListener(type, callback, options) {
1582
+ if (typeof options === "object" && options?.signal != null) {
1583
+ const { signal, ...otherOptions } = options;
1584
+ // - this happens because AbortSignal is provided by Node.js,
1585
+ // but jsdom APIs require jsdom's AbortSignal, while Node APIs
1586
+ // (like fetch and Request) require a Node.js AbortSignal
1587
+ // - disable narrow typing with "as any" because we need it later
1588
+ if (!(signal instanceof JSDOMAbortSignal)) {
1589
+ const jsdomCompatOptions = Object.create(null);
1590
+ Object.assign(jsdomCompatOptions, otherOptions);
1591
+ jsdomCompatOptions.signal = getJsdomAbortController(signal).signal;
1592
+ return originalAddEventListener.call(this, type, callback, jsdomCompatOptions);
1593
+ }
1594
+ }
1595
+ return originalAddEventListener.call(this, type, callback, options);
1596
+ };
1597
+ return () => {
1598
+ window.EventTarget.prototype.addEventListener = originalAddEventListener;
1599
+ };
1600
+ }
1601
+
1602
+ // some globals we do not want, either because deprecated or we set it ourselves
1603
+ const denyList = /* @__PURE__ */ new Set([
1604
+ "GLOBAL",
1605
+ "root",
1606
+ "global",
1607
+ "Buffer",
1608
+ "ArrayBuffer",
1609
+ "Uint8Array"
1610
+ ]);
1611
+ const nodeGlobals = /* @__PURE__ */ new Map();
1612
+ function populateNodeGlobals() {
1613
+ if (nodeGlobals.size !== 0) return;
1614
+ const names = Object.getOwnPropertyNames(globalThis);
1615
+ const length = names.length;
1616
+ for (let i = 0; i < length; i++) {
1617
+ const globalName = names[i];
1618
+ if (!denyList.has(globalName)) {
1619
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, globalName);
1620
+ if (!descriptor) throw new Error(`No property descriptor for ${globalName}, this is a bug in Vitest.`);
1621
+ nodeGlobals.set(globalName, descriptor);
1622
+ }
1623
+ }
1624
+ }
1625
+ var node = {
1626
+ name: "node",
1627
+ viteEnvironment: "ssr",
1628
+ prewarmModules: false,
1629
+ // this is largely copied from jest's node environment
1630
+ async setupVM() {
1631
+ populateNodeGlobals();
1632
+ const vm = await import('node:vm');
1633
+ let context = vm.createContext();
1634
+ let global = vm.runInContext("this", context);
1635
+ const contextGlobals = new Set(Object.getOwnPropertyNames(global));
1636
+ for (const [nodeGlobalsKey, descriptor] of nodeGlobals) if (!contextGlobals.has(nodeGlobalsKey)) {
1637
+ if (descriptor.configurable) Object.defineProperty(global, nodeGlobalsKey, {
1638
+ configurable: true,
1639
+ enumerable: descriptor.enumerable,
1640
+ get() {
1641
+ // @ts-expect-error: no index signature
1642
+ const val = globalThis[nodeGlobalsKey];
1643
+ // override lazy getter
1644
+ Object.defineProperty(global, nodeGlobalsKey, {
1645
+ configurable: true,
1646
+ enumerable: descriptor.enumerable,
1647
+ value: val,
1648
+ // accessor globals like `performance` and `localStorage` (Node 25+) are assignable when they have a setter
1649
+ writable: descriptor.writable === true || typeof descriptor.set === "function"
1650
+ });
1651
+ return val;
1652
+ },
1653
+ set(val) {
1654
+ // override lazy getter
1655
+ Object.defineProperty(global, nodeGlobalsKey, {
1656
+ configurable: true,
1657
+ enumerable: descriptor.enumerable,
1658
+ value: val,
1659
+ writable: true
1660
+ });
1661
+ }
1662
+ });
1663
+ else if ("value" in descriptor) Object.defineProperty(global, nodeGlobalsKey, {
1664
+ configurable: false,
1665
+ enumerable: descriptor.enumerable,
1666
+ value: descriptor.value,
1667
+ writable: descriptor.writable
1668
+ });
1669
+ else Object.defineProperty(global, nodeGlobalsKey, {
1670
+ configurable: false,
1671
+ enumerable: descriptor.enumerable,
1672
+ get: descriptor.get,
1673
+ set: descriptor.set
1674
+ });
1675
+ }
1676
+ global.global = global;
1677
+ global.Buffer = Buffer;
1678
+ global.ArrayBuffer = ArrayBuffer;
1679
+ // TextEncoder (global or via 'util') references a Uint8Array constructor
1680
+ // different than the global one used by users in tests. This makes sure the
1681
+ // same constructor is referenced by both.
1682
+ global.Uint8Array = Uint8Array;
1683
+ return {
1684
+ getVmContext() {
1685
+ return context;
1686
+ },
1687
+ teardown() {
1688
+ context = void 0;
1689
+ global = void 0;
1690
+ }
1691
+ };
1692
+ },
1693
+ async setup(global) {
1694
+ global.console.Console = Console;
1695
+ return { teardown(global) {
1696
+ delete global.console.Console;
1697
+ } };
1698
+ }
1699
+ };
1700
+
1701
+ const environments = {
1702
+ node,
1703
+ jsdom,
1704
+ "happy-dom": happy,
1705
+ "edge-runtime": edge
1706
+ };
1707
+
1708
+ export { BareModuleMocker as B, VITEST_VM_CONTEXT_SYMBOL as V, VitestModuleRunner as a, VitestTransport as b, createNodeImportMeta as c, environments as e, normalizeModuleId as n, populateGlobal as p, startVitestModuleRunner as s };