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
@@ -1,740 +0,0 @@
1
- import fs from 'node:fs';
2
- import { splitFileAndPostfix as splitFileAndPostfix$1, isBareImport } from '@vitest/utils/helpers';
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.BX5Fg8C4.js';
5
- import { pathToFileURL } from 'node:url';
6
- import { normalize, join } from 'pathe';
7
- import { distDir } from '../path.js';
8
- import { VitestModuleEvaluator, unwrapId } from '../module-evaluator.js';
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 { T as Traces } from './traces.DT5aQ62U.js';
15
-
16
- class BareModuleMocker {
17
- static pendingIds = [];
18
- spyModule;
19
- primitives;
20
- registries = /* @__PURE__ */ new Map();
21
- mockContext = { callstack: null };
22
- _otel;
23
- constructor(options) {
24
- this.options = options;
25
- this._otel = options.traces;
26
- this.primitives = {
27
- Object,
28
- Error,
29
- Function,
30
- RegExp,
31
- Symbol: globalThis.Symbol,
32
- Array,
33
- Map
34
- };
35
- if (options.spyModule) this.spyModule = options.spyModule;
36
- }
37
- get root() {
38
- return this.options.root;
39
- }
40
- get moduleDirectories() {
41
- return this.options.moduleDirectories || [];
42
- }
43
- getMockerRegistry() {
44
- const suite = this.getSuiteFilepath();
45
- if (!this.registries.has(suite)) this.registries.set(suite, new MockerRegistry());
46
- return this.registries.get(suite);
47
- }
48
- reset() {
49
- this.registries.clear();
50
- }
51
- invalidateModuleById(_id) {
52
- // implemented by mockers that control the module runner
53
- }
54
- isModuleDirectory(path) {
55
- return this.moduleDirectories.some((dir) => path.includes(dir));
56
- }
57
- getSuiteFilepath() {
58
- return this.options.getCurrentTestFilepath() || "global";
59
- }
60
- createError(message, codeFrame) {
61
- const Error = this.primitives.Error;
62
- const error = new Error(message);
63
- Object.assign(error, { codeFrame });
64
- return error;
65
- }
66
- async resolveId(rawId, importer) {
67
- return this._otel.$("vitest.mocker.resolve_id", { attributes: {
68
- "vitest.module.raw_id": rawId,
69
- "vitest.module.importer": rawId
70
- } }, async (span) => {
71
- const result = await this.options.resolveId(rawId, importer);
72
- if (!result) {
73
- span.addEvent("could not resolve id, fallback to unresolved values");
74
- const id = normalizeModuleId(rawId);
75
- span.setAttributes({
76
- "vitest.module.id": id,
77
- "vitest.module.url": rawId,
78
- "vitest.module.external": id,
79
- "vitest.module.fallback": true
80
- });
81
- return {
82
- id,
83
- url: rawId,
84
- external: id
85
- };
86
- }
87
- // external is node_module or unresolved module
88
- // for example, some people mock "vscode" and don't have it installed
89
- const external = !isAbsolute(result.file) || this.isModuleDirectory(result.file) ? normalizeModuleId(rawId) : null;
90
- const id = normalizeModuleId(result.id);
91
- span.setAttributes({
92
- "vitest.module.id": id,
93
- "vitest.module.url": result.url,
94
- "vitest.module.external": external ?? false
95
- });
96
- return {
97
- ...result,
98
- id,
99
- external
100
- };
101
- });
102
- }
103
- async resolveMocks() {
104
- if (!BareModuleMocker.pendingIds.length) return;
105
- const resolveMock = async (mock) => {
106
- const { id, url, external } = await this.resolveId(mock.id, mock.importer);
107
- if (mock.action === "unmock") this.unmockPath(id);
108
- if (mock.action === "mock") this.mockPath(mock.id, id, url, external, mock.type, mock.factory);
109
- };
110
- // group consecutive mocks of the same action type together,
111
- // resolve in parallel inside each group, but run groups sequentially
112
- // to preserve mock/unmock ordering
113
- const groups = groupByConsecutiveAction(BareModuleMocker.pendingIds);
114
- for (const group of groups) await Promise.all(group.map(resolveMock));
115
- BareModuleMocker.pendingIds = [];
116
- }
117
- // public method to avoid circular dependency
118
- getMockContext() {
119
- return this.mockContext;
120
- }
121
- // path used to store mocked dependencies
122
- getMockPath(dep) {
123
- return `mock:${dep}`;
124
- }
125
- getDependencyMock(id) {
126
- return this.getMockerRegistry().getById(fixLeadingSlashes(id));
127
- }
128
- getDependencyMockByUrl(url) {
129
- return this.getMockerRegistry().get(url);
130
- }
131
- findMockRedirect(mockPath, external) {
132
- return findMockRedirect(this.root, mockPath, external);
133
- }
134
- mockObject(object, mockExportsOrModuleType, moduleType) {
135
- let mockExports;
136
- if (mockExportsOrModuleType === "automock" || mockExportsOrModuleType === "autospy") {
137
- moduleType = mockExportsOrModuleType;
138
- mockExports = void 0;
139
- } else mockExports = mockExportsOrModuleType;
140
- moduleType ??= "automock";
141
- const createMockInstance = this.spyModule?.createMockInstance;
142
- if (!createMockInstance) throw this.createError("[vitest] `spyModule` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
143
- return mockObject({
144
- globalConstructors: this.primitives,
145
- createMockInstance,
146
- type: moduleType
147
- }, object, mockExports);
148
- }
149
- unmockPath(id) {
150
- this.getMockerRegistry().deleteById(id);
151
- this.invalidateModuleById(id);
152
- }
153
- mockPath(originalId, id, url, external, mockType, factory) {
154
- const registry = this.getMockerRegistry();
155
- if (mockType === "manual") registry.register("manual", originalId, id, url, factory);
156
- else if (mockType === "autospy") registry.register("autospy", originalId, id, url);
157
- else {
158
- const redirect = this.findMockRedirect(id, external);
159
- if (redirect) registry.register("redirect", originalId, id, url, redirect);
160
- else registry.register("automock", originalId, id, url);
161
- }
162
- // every time the mock is registered, we remove the previous one from the cache
163
- this.invalidateModuleById(id);
164
- }
165
- async importActual(_rawId, _importer, _callstack) {
166
- throw new Error(`importActual is not implemented`);
167
- }
168
- async importMock(_rawId, _importer, _callstack) {
169
- throw new Error(`importMock is not implemented`);
170
- }
171
- queueMock(id, importer, factoryOrOptions) {
172
- const mockType = getMockType(factoryOrOptions);
173
- BareModuleMocker.pendingIds.push({
174
- action: "mock",
175
- id,
176
- importer,
177
- factory: typeof factoryOrOptions === "function" ? factoryOrOptions : void 0,
178
- type: mockType
179
- });
180
- }
181
- queueUnmock(id, importer) {
182
- BareModuleMocker.pendingIds.push({
183
- action: "unmock",
184
- id,
185
- importer
186
- });
187
- }
188
- }
189
- function getMockType(factoryOrOptions) {
190
- if (!factoryOrOptions) return "automock";
191
- if (typeof factoryOrOptions === "function") return "manual";
192
- return factoryOrOptions.spy ? "autospy" : "automock";
193
- }
194
- // unique id that is not available as "$bare_import" like "test"
195
- // https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
196
- const prefixedBuiltins = new Set([
197
- "node:sea",
198
- "node:sqlite",
199
- "node:test",
200
- "node:test/reporters"
201
- ]);
202
- const isWindows$1 = process.platform === "win32";
203
- // transform file url to id
204
- // virtual:custom -> virtual:custom
205
- // \0custom -> \0custom
206
- // /root/id -> /id
207
- // /root/id.js -> /id.js
208
- // C:/root/id.js -> /id.js
209
- // C:\root\id.js -> /id.js
210
- // TODO: expose this in vite/module-runner
211
- function normalizeModuleId(file) {
212
- if (prefixedBuiltins.has(file)) return file;
213
- // if it's not in the root, keep it as a path, not a URL
214
- return slash(file).replace(/^\/@fs\//, isWindows$1 ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\//, "/");
215
- }
216
- const windowsSlashRE = /\\/g;
217
- function slash(p) {
218
- return p.replace(windowsSlashRE, "/");
219
- }
220
- function groupByConsecutiveAction(mocks) {
221
- const groups = [];
222
- for (const mock of mocks) {
223
- const last = groups.at(-1);
224
- if (last?.[0].action === mock.action) last.push(mock);
225
- else groups.push([mock]);
226
- }
227
- return groups;
228
- }
229
- const multipleSlashRe = /^\/+/;
230
- // module-runner incorrectly replaces file:///path with `///path`
231
- function fixLeadingSlashes(id) {
232
- if (id.startsWith("//")) return id.replace(multipleSlashRe, "/");
233
- return id;
234
- }
235
-
236
- // copied from vite
237
- // https://github.com/vitejs/vite/blob/4417b4f305623b2850bd6ae6553834c017694672/packages/vite/src/shared/utils.ts
238
- // https://github.com/vitejs/vite/blob/4417b4f305623b2850bd6ae6553834c017694672/packages/vite/src/node/utils.ts
239
- const postfixRE = /[?#].*$/;
240
- const trailingSeparatorRE = /[?&]$/;
241
- function cleanUrl(url) {
242
- return url.replace(postfixRE, "");
243
- }
244
- function splitFileAndPostfix(path) {
245
- const file = cleanUrl(path);
246
- return {
247
- file,
248
- postfix: path.slice(file.length)
249
- };
250
- }
251
- function injectQuery(url, queryToInject) {
252
- const { file, postfix } = splitFileAndPostfix(url);
253
- return `${file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`;
254
- }
255
- function removeQuery(url, queryToRemove) {
256
- return url.replace(new RegExp(`([?&])${queryToRemove}(?:&|$)`), "$1").replace(trailingSeparatorRE, "");
257
- }
258
-
259
- const spyModulePath = resolve(distDir, "spy.js");
260
- class VitestMocker extends BareModuleMocker {
261
- filterPublicKeys;
262
- constructor(moduleRunner, options) {
263
- super(options);
264
- this.moduleRunner = moduleRunner;
265
- this.options = options;
266
- const context = this.options.context;
267
- if (context) this.primitives = vm.runInContext("({ Object, Error, Function, RegExp, Symbol, Array, Map })", context);
268
- const Symbol = this.primitives.Symbol;
269
- this.filterPublicKeys = [
270
- "__esModule",
271
- Symbol.asyncIterator,
272
- Symbol.hasInstance,
273
- Symbol.isConcatSpreadable,
274
- Symbol.iterator,
275
- Symbol.match,
276
- Symbol.matchAll,
277
- Symbol.replace,
278
- Symbol.search,
279
- Symbol.split,
280
- Symbol.species,
281
- Symbol.toPrimitive,
282
- Symbol.toStringTag,
283
- Symbol.unscopables
284
- ];
285
- }
286
- get evaluatedModules() {
287
- return this.moduleRunner.evaluatedModules;
288
- }
289
- async initializeSpyModule() {
290
- if (this.spyModule) return;
291
- this.spyModule = await this.moduleRunner.import(spyModulePath);
292
- }
293
- reset() {
294
- this.registries.clear();
295
- }
296
- invalidateModuleById(id) {
297
- const mockId = this.getMockPath(id);
298
- const node = this.evaluatedModules.getModuleById(mockId);
299
- if (node) {
300
- this.evaluatedModules.invalidateModule(node);
301
- node.mockedExports = void 0;
302
- }
303
- }
304
- ensureModule(id, url) {
305
- const node = this.evaluatedModules.ensureModule(id, url);
306
- // TODO
307
- node.meta = {
308
- id,
309
- url,
310
- code: "",
311
- file: null,
312
- invalidate: false
313
- };
314
- return node;
315
- }
316
- async callFunctionMock(id, url, mock) {
317
- const node = this.ensureModule(id, url);
318
- if (node.exports) return node.exports;
319
- const exports$1 = await mock.resolve();
320
- const moduleExports = new Proxy(exports$1, { get: (target, prop) => {
321
- const val = target[prop];
322
- // 'then' can exist on non-Promise objects, need nested instanceof check for logic to work
323
- if (prop === "then") {
324
- if (target instanceof Promise) return target.then.bind(target);
325
- } else if (!(prop in target)) {
326
- if (this.filterPublicKeys.includes(prop)) return;
327
- throw this.createError(`[vitest] No "${String(prop)}" export is defined on the "${mock.raw}" mock. Did you forget to return it from "vi.mock"?
328
- If you need to partially mock a module, you can use "importOriginal" helper inside:
329
- `, `vi.mock(import("${mock.raw}"), async (importOriginal) => {
330
- const actual = await importOriginal()
331
- return {
332
- ...actual,
333
- // your mocked methods
334
- }
335
- })`);
336
- }
337
- return val;
338
- } });
339
- node.exports = moduleExports;
340
- return moduleExports;
341
- }
342
- async importActual(rawId, importer, callstack) {
343
- const { url } = await this.resolveId(rawId, importer);
344
- const actualUrl = injectQuery(url, "_vitest_original");
345
- const node = await this.moduleRunner.fetchModule(actualUrl, importer);
346
- return await this.moduleRunner.cachedRequest(node.url, node, callstack || [importer], void 0, true);
347
- }
348
- async importMock(rawId, importer) {
349
- const { id, url, external } = await this.resolveId(rawId, importer);
350
- let mock = this.getDependencyMock(id);
351
- if (!mock) {
352
- const redirect = this.findMockRedirect(id, external);
353
- if (redirect) mock = new RedirectedModule(rawId, id, rawId, redirect);
354
- else mock = new AutomockedModule(rawId, id, rawId);
355
- }
356
- if (mock.type === "automock" || mock.type === "autospy") {
357
- const node = await this.moduleRunner.fetchModule(url, importer);
358
- const mod = await this.moduleRunner.cachedRequest(url, node, [importer], void 0, true);
359
- const Object = this.primitives.Object;
360
- return this.mockObject(mod, Object.create(Object.prototype), mock.type);
361
- }
362
- if (mock.type === "manual") return this.callFunctionMock(id, url, mock);
363
- const node = await this.moduleRunner.fetchModule(mock.redirect);
364
- return this.moduleRunner.cachedRequest(mock.redirect, node, [importer], void 0, true);
365
- }
366
- async requestWithMockedModule(url, evaluatedNode, callstack, mock) {
367
- return this._otel.$("vitest.mocker.evaluate", async (span) => {
368
- const mockId = this.getMockPath(evaluatedNode.id);
369
- span.setAttributes({
370
- "vitest.module.id": mockId,
371
- "vitest.mock.type": mock.type,
372
- "vitest.mock.id": mock.id,
373
- "vitest.mock.url": mock.url,
374
- "vitest.mock.raw": mock.raw
375
- });
376
- if (mock.type === "automock" || mock.type === "autospy") {
377
- const cache = this.evaluatedModules.getModuleById(mockId);
378
- if (cache && cache.mockedExports) return cache.mockedExports;
379
- const Object = this.primitives.Object;
380
- // we have to define a separate object that will copy all properties into itself
381
- // and can't just use the same `exports` define automatically by Vite before the evaluator
382
- const exports$1 = Object.create(null);
383
- Object.defineProperty(exports$1, Symbol.toStringTag, {
384
- value: "Module",
385
- configurable: true,
386
- writable: true
387
- });
388
- const node = this.ensureModule(mockId, this.getMockPath(evaluatedNode.url));
389
- node.meta = evaluatedNode.meta;
390
- node.file = evaluatedNode.file;
391
- node.mockedExports = exports$1;
392
- const mod = await this.moduleRunner.cachedRequest(url, node, callstack, void 0, true);
393
- this.mockObject(mod, exports$1, mock.type);
394
- return exports$1;
395
- }
396
- if (mock.type === "manual" && !callstack.includes(mockId) && !callstack.includes(url)) try {
397
- callstack.push(mockId);
398
- // this will not work if user does Promise.all(import(), import())
399
- // we can also use AsyncLocalStorage to store callstack, but this won't work in the browser
400
- // maybe we should improve mock API in the future?
401
- this.mockContext.callstack = callstack;
402
- return await this.callFunctionMock(mockId, this.getMockPath(url), mock);
403
- } finally {
404
- this.mockContext.callstack = null;
405
- const indexMock = callstack.indexOf(mockId);
406
- callstack.splice(indexMock, 1);
407
- }
408
- else if (mock.type === "redirect" && !callstack.includes(mock.redirect)) {
409
- span.setAttribute("vitest.mock.redirect", mock.redirect);
410
- return mock.redirect;
411
- }
412
- });
413
- }
414
- async mockedRequest(url, evaluatedNode, callstack) {
415
- const mock = this.getDependencyMock(evaluatedNode.id);
416
- if (!mock) return;
417
- return this.requestWithMockedModule(url, evaluatedNode, callstack, mock);
418
- }
419
- }
420
-
421
- class VitestTransport {
422
- constructor(options, evaluatedModules, callstacks) {
423
- this.options = options;
424
- this.evaluatedModules = evaluatedModules;
425
- this.callstacks = callstacks;
426
- }
427
- async invoke(event) {
428
- if (event.type !== "custom") return { error: /* @__PURE__ */ new Error(`Vitest Module Runner doesn't support Vite HMR events.`) };
429
- if (event.event !== "vite:invoke") return { error: /* @__PURE__ */ new Error(`Vitest Module Runner doesn't support ${event.event} event.`) };
430
- const { name, data } = event.data;
431
- if (name === "getBuiltins")
432
- // we return an empty array here to avoid client-side builtin check,
433
- // as we need builtins to go through `fetchModule`
434
- return { result: [] };
435
- if (name !== "fetchModule") return { error: /* @__PURE__ */ new Error(`Unknown method: ${name}. Expected "fetchModule".`) };
436
- try {
437
- return { result: await this.options.fetchModule(...data) };
438
- } catch (cause) {
439
- if (cause instanceof EnvironmentTeardownError) {
440
- const [id, importer] = data;
441
- let message = `Cannot load '${id}'${importer ? ` imported from ${importer}` : ""} after the environment was torn down. This is not a bug in Vitest.`;
442
- const moduleNode = importer ? this.evaluatedModules.getModuleById(importer) : void 0;
443
- const callstack = moduleNode ? this.callstacks.get(moduleNode) : void 0;
444
- if (callstack) message += ` The last recorded callstack:\n- ${[
445
- ...callstack,
446
- importer,
447
- id
448
- ].reverse().join("\n- ")}`;
449
- const error = new EnvironmentTeardownError(message);
450
- if (cause.stack) error.stack = cause.stack.replace(cause.message, error.message);
451
- return { error };
452
- }
453
- return { error: cause };
454
- }
455
- }
456
- }
457
-
458
- const createNodeImportMeta = (modulePath) => {
459
- if (!viteModuleRunner.createDefaultImportMeta) throw new Error(`createNodeImportMeta is not supported in this version of Vite.`);
460
- const defaultMeta = viteModuleRunner.createDefaultImportMeta(modulePath);
461
- const href = defaultMeta.url;
462
- const importMetaResolver = createImportMetaResolver();
463
- return {
464
- ...defaultMeta,
465
- main: false,
466
- resolve(id, parent) {
467
- return (importMetaResolver ?? defaultMeta.resolve)(id, parent ?? href);
468
- }
469
- };
470
- };
471
- function createImportMetaResolver() {
472
- if (!import.meta.resolve) return;
473
- return (specifier, importer) => import.meta.resolve(specifier, importer);
474
- }
475
- // @ts-expect-error overriding private method
476
- class VitestModuleRunner extends viteModuleRunner.ModuleRunner {
477
- mocker;
478
- moduleExecutionInfo;
479
- _otel;
480
- _callstacks;
481
- constructor(vitestOptions) {
482
- const options = vitestOptions;
483
- const evaluatedModules = options.evaluatedModules;
484
- const callstacks = /* @__PURE__ */ new WeakMap();
485
- const transport = new VitestTransport(options.transport, evaluatedModules, callstacks);
486
- super({
487
- transport,
488
- hmr: false,
489
- evaluatedModules,
490
- sourcemapInterceptor: "prepareStackTrace",
491
- createImportMeta: vitestOptions.createImportMeta
492
- }, options.evaluator);
493
- this.vitestOptions = vitestOptions;
494
- this._callstacks = callstacks;
495
- this._otel = vitestOptions.traces || new Traces({ enabled: false });
496
- this.moduleExecutionInfo = options.getWorkerState().moduleExecutionInfo;
497
- this.mocker = options.mocker || new VitestMocker(this, {
498
- spyModule: options.spyModule,
499
- context: options.vm?.context,
500
- traces: this._otel,
501
- resolveId: options.transport.resolveId,
502
- get root() {
503
- return options.getWorkerState().config.root;
504
- },
505
- get moduleDirectories() {
506
- return options.getWorkerState().config.deps.moduleDirectories || [];
507
- },
508
- getCurrentTestFilepath() {
509
- return options.getWorkerState().filepath;
510
- }
511
- });
512
- if (options.vm) options.vm.context.__vitest_mocker__ = this.mocker;
513
- else Object.defineProperty(globalThis, "__vitest_mocker__", {
514
- configurable: true,
515
- writable: true,
516
- value: this.mocker
517
- });
518
- }
519
- /**
520
- * Vite checks that the module has exports emulating the Node.js behaviour,
521
- * but Vitest is more relaxed.
522
- *
523
- * We should keep the Vite behavior when there is a `strict` flag.
524
- * @internal
525
- */
526
- processImport(exports$1) {
527
- return exports$1;
528
- }
529
- async import(rawId) {
530
- const resolved = await this._otel.$("vitest.module.resolve_id", { attributes: { "vitest.module.raw_id": rawId } }, async (span) => {
531
- const result = await this.vitestOptions.transport.resolveId(rawId);
532
- if (result) span.setAttributes({
533
- "vitest.module.url": result.url,
534
- "vitest.module.file": result.file,
535
- "vitest.module.id": result.id
536
- });
537
- return result;
538
- });
539
- return super.import(resolved ? resolved.url : rawId);
540
- }
541
- async fetchModule(url, importer) {
542
- return await this.cachedModule(url, importer);
543
- }
544
- _cachedRequest(url, module, callstack = [], metadata) {
545
- // @ts-expect-error "cachedRequest" is private
546
- return super.cachedRequest(url, module, callstack, metadata);
547
- }
548
- /**
549
- * @internal
550
- */
551
- async cachedRequest(url, mod, callstack = [], metadata, ignoreMock = false) {
552
- // Track for a better error message if dynamic import is not resolved properly
553
- this._callstacks.set(mod, callstack);
554
- if (ignoreMock) return this._cachedRequest(url, mod, callstack, metadata);
555
- let mocked;
556
- if (mod.meta && "mockedModule" in mod.meta) {
557
- const mockedModule = mod.meta.mockedModule;
558
- const mockId = this.mocker.getMockPath(mod.id);
559
- // bypass mock and force "importActual" behavior when:
560
- // - mock was removed by doUnmock (stale mockedModule in meta)
561
- // - self-import: mock factory/file is importing the module it's mocking
562
- const isStale = !this.mocker.getDependencyMock(mod.id);
563
- const isSelfImport = callstack.includes(mockId) || callstack.includes(url) || "redirect" in mockedModule && callstack.includes(mockedModule.redirect);
564
- if (isStale || isSelfImport) {
565
- const node = await this.fetchModule(injectQuery(url, "_vitest_original"));
566
- return this._cachedRequest(node.url, node, callstack, metadata);
567
- }
568
- mocked = await this.mocker.requestWithMockedModule(url, mod, callstack, mockedModule);
569
- } else mocked = await this.mocker.mockedRequest(url, mod, callstack);
570
- if (typeof mocked === "string") {
571
- const node = await this.fetchModule(mocked);
572
- return this._cachedRequest(mocked, node, callstack, metadata);
573
- }
574
- if (mocked != null && typeof mocked === "object") return mocked;
575
- return this._cachedRequest(url, mod, callstack, metadata);
576
- }
577
- /** @internal */
578
- _invalidateSubTreeById(ids, invalidated = /* @__PURE__ */ new Set()) {
579
- for (const id of ids) {
580
- if (invalidated.has(id)) continue;
581
- const node = this.evaluatedModules.getModuleById(id);
582
- if (!node) continue;
583
- invalidated.add(id);
584
- const subIds = Array.from(this.evaluatedModules.idToModuleMap).filter(([, mod]) => mod.importers.has(id)).map(([key]) => key);
585
- if (subIds.length) this._invalidateSubTreeById(subIds, invalidated);
586
- this.evaluatedModules.invalidateModule(node);
587
- }
588
- }
589
- }
590
-
591
- const bareVitestRegexp = /^@?vitest(?:\/|$)/;
592
- const normalizedDistDir = normalize(distDir);
593
- const relativeIds = {};
594
- const externalizeMap = /* @__PURE__ */ new Map();
595
- // all Vitest imports always need to be externalized
596
- function getCachedVitestImport(id, state) {
597
- if (id.startsWith("/@fs/") || id.startsWith("\\@fs\\")) id = id.slice(process.platform === "win32" ? 5 : 4);
598
- if (externalizeMap.has(id)) return {
599
- externalize: externalizeMap.get(id),
600
- type: "module"
601
- };
602
- // always externalize Vitest because we import from there before running tests
603
- // so we already have it cached by Node.js
604
- const root = state().config.root;
605
- const relativeRoot = relativeIds[root] ?? (relativeIds[root] = normalizedDistDir.slice(root.length));
606
- if (id.includes(distDir) || id.includes(normalizedDistDir)) {
607
- const { file, postfix } = splitFileAndPostfix$1(id);
608
- const externalize = id.startsWith("file://") ? id : `${pathToFileURL(file)}${postfix}`;
609
- externalizeMap.set(id, externalize);
610
- return {
611
- externalize,
612
- type: "module"
613
- };
614
- }
615
- if (relativeRoot && relativeRoot !== "/" && id.startsWith(relativeRoot)) {
616
- const { file, postfix } = splitFileAndPostfix$1(id);
617
- const externalize = `${pathToFileURL(join(root, file))}${postfix}`;
618
- externalizeMap.set(id, externalize);
619
- return {
620
- externalize,
621
- type: "module"
622
- };
623
- }
624
- if (bareVitestRegexp.test(id)) {
625
- externalizeMap.set(id, id);
626
- return {
627
- externalize: id,
628
- type: "module"
629
- };
630
- }
631
- return null;
632
- }
633
-
634
- const { readFileSync } = fs;
635
- const VITEST_VM_CONTEXT_SYMBOL = "__vitest_vm_context__";
636
- const cwd = process.cwd();
637
- const isWindows = process.platform === "win32";
638
- function startVitestModuleRunner(options) {
639
- const traces = options.traces;
640
- const state = () => getSafeWorkerState() || options.state;
641
- const rpc = () => state().rpc;
642
- const environment = () => {
643
- const environment = state().environment;
644
- return environment.viteEnvironment || environment.name;
645
- };
646
- const vm = options.context && options.externalModulesExecutor ? {
647
- context: options.context,
648
- externalModulesExecutor: options.externalModulesExecutor
649
- } : void 0;
650
- const evaluator = options.evaluator || new VitestModuleEvaluator(vm, {
651
- traces,
652
- evaluatedModules: options.evaluatedModules,
653
- get moduleExecutionInfo() {
654
- return state().moduleExecutionInfo;
655
- },
656
- get interopDefault() {
657
- return state().config.deps.interopDefault;
658
- },
659
- getCurrentTestFilepath: () => state().filepath
660
- });
661
- const moduleRunner = new VitestModuleRunner({
662
- spyModule: options.spyModule,
663
- evaluatedModules: options.evaluatedModules,
664
- evaluator,
665
- traces,
666
- mocker: options.mocker,
667
- transport: {
668
- async fetchModule(id, importer, options) {
669
- const resolvingModules = state().resolvingModules;
670
- if (isWindows) {
671
- if (id[1] === ":") {
672
- // The drive letter is different for whatever reason, we need to normalize it to CWD
673
- 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);
674
- // always mark absolute windows paths, otherwise Vite will externalize it
675
- id = `/@id/${id}`;
676
- }
677
- }
678
- const vitest = getCachedVitestImport(id, state);
679
- if (vitest) return vitest;
680
- // strip _vitest_original query added by importActual so that
681
- // the plugin pipeline sees the original import id (e.g. virtual modules's load hook)
682
- const isImportActual = id.includes("_vitest_original");
683
- if (isImportActual) id = removeQuery(id, "_vitest_original");
684
- const rawId = unwrapId(id);
685
- resolvingModules.add(rawId);
686
- try {
687
- if (VitestMocker.pendingIds.length) await moduleRunner.mocker.resolveMocks();
688
- if (!isImportActual) {
689
- const resolvedMock = moduleRunner.mocker.getDependencyMockByUrl(id);
690
- if (resolvedMock?.type === "manual" || resolvedMock?.type === "redirect") return {
691
- code: "",
692
- file: null,
693
- id: resolvedMock.id,
694
- url: resolvedMock.url,
695
- invalidate: false,
696
- mockedModule: resolvedMock
697
- };
698
- }
699
- if (isBuiltin(rawId)) return {
700
- externalize: rawId,
701
- type: "builtin"
702
- };
703
- if (isBrowserExternal(rawId)) return {
704
- externalize: toBuiltin(rawId),
705
- type: "builtin"
706
- };
707
- // if module is invalidated, the worker will be recreated,
708
- // so cached is always true in a single worker
709
- if (!isImportActual && options?.cached) return { cache: true };
710
- const otelCarrier = traces?.getContextCarrier();
711
- const result = await rpc().fetch(id, importer, environment(), options, otelCarrier);
712
- if ("cached" in result) return {
713
- code: readFileSync(result.tmp, "utf-8"),
714
- ...result
715
- };
716
- return result;
717
- } catch (cause) {
718
- // rethrow vite error if it cannot load the module because it's not resolved
719
- 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 '")) {
720
- const error = new Error(`Cannot find ${isBareImport(id) ? "package" : "module"} '${id}'${importer ? ` imported from ${importer}` : ""}`, { cause });
721
- error.code = "ERR_MODULE_NOT_FOUND";
722
- throw error;
723
- }
724
- throw cause;
725
- } finally {
726
- resolvingModules.delete(rawId);
727
- }
728
- },
729
- resolveId(id, importer) {
730
- return rpc().resolve(id, importer, environment());
731
- }
732
- },
733
- getWorkerState: state,
734
- vm,
735
- createImportMeta: options.createImportMeta
736
- });
737
- return moduleRunner;
738
- }
739
-
740
- export { BareModuleMocker as B, VITEST_VM_CONTEXT_SYMBOL as V, VitestModuleRunner as a, VitestTransport as b, createNodeImportMeta as c, normalizeModuleId as n, startVitestModuleRunner as s };