vitest 4.0.0-beta.8 → 4.0.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 (85) hide show
  1. package/LICENSE.md +86 -102
  2. package/browser/context.d.ts +7 -0
  3. package/browser/context.js +20 -0
  4. package/dist/browser.d.ts +26 -9
  5. package/dist/browser.js +17 -7
  6. package/dist/chunks/base.CtHM3ryk.js +128 -0
  7. package/dist/chunks/{benchmark.UW6Ezvxy.js → benchmark.DHKMYAts.js} +2 -2
  8. package/dist/chunks/{browser.d.DOMmqJQx.d.ts → browser.d.B9iJzZyn.d.ts} +3 -3
  9. package/dist/chunks/{cac.By1HvRIk.js → cac.B99MQg-w.js} +47 -91
  10. package/dist/chunks/{cli-api.C-JHgQgp.js → cli-api.PwHwIMss.js} +1544 -310
  11. package/dist/chunks/{config.d._GBBbReY.d.ts → config.d.u2CUDWwS.d.ts} +6 -19
  12. package/dist/chunks/{console.B0quX7yH.js → console.CTJL2nuH.js} +4 -6
  13. package/dist/chunks/{coverage.DarITf6U.js → coverage.FU3w4IrQ.js} +128 -1142
  14. package/dist/chunks/{creator.KEg6n5IC.js → creator.DucAaYBz.js} +10 -37
  15. package/dist/chunks/{defaults.CXFFjsi8.js → defaults.BOqNVLsY.js} +0 -1
  16. package/dist/chunks/environment.d.CrsxCzP1.d.ts +29 -0
  17. package/dist/chunks/evaluatedModules.Dg1zASAC.js +17 -0
  18. package/dist/chunks/{global.d.K6uBQHzY.d.ts → global.d.BgJSTpgQ.d.ts} +2 -17
  19. package/dist/chunks/{globals.lgsmH00r.js → globals.BGT_RUsD.js} +12 -9
  20. package/dist/chunks/{index.BuwjkI-q.js → index.BdSLhLDZ.js} +3 -3
  21. package/dist/chunks/{index.DfviD7lX.js → index.CbWINfS7.js} +49 -21
  22. package/dist/chunks/{index.AzwzFtyi.js → index.CcRZ6fUh.js} +1493 -114
  23. package/dist/chunks/{index.X0nbfr6-.js → index.Dc3xnDvT.js} +48 -289
  24. package/dist/chunks/{index.AR8aAkCC.js → index.RwjEGCQ0.js} +7 -8
  25. package/dist/chunks/init-forks.DSafeltJ.js +54 -0
  26. package/dist/chunks/init-threads.SUtZ-067.js +17 -0
  27. package/dist/chunks/init.B2EESLQM.js +213 -0
  28. package/dist/chunks/{inspector.CvQD-Nie.js → inspector.DLZxSeU3.js} +2 -6
  29. package/dist/chunks/{moduleRunner.d.CX4DuqOx.d.ts → moduleRunner.d.YtNsMIoJ.d.ts} +12 -14
  30. package/dist/chunks/{node.BOqcT2jW.js → node.BwAWWjHZ.js} +3 -4
  31. package/dist/chunks/{plugin.d.CHe6slQs.d.ts → plugin.d.DQU1R5px.d.ts} +1 -1
  32. package/dist/chunks/{reporters.d.37tJQ2uV.d.ts → reporters.d.BMKt7f6I.d.ts} +1066 -1030
  33. package/dist/chunks/{index.CsFXYRkW.js → resolveSnapshotEnvironment.DJJKMKxb.js} +18 -24
  34. package/dist/chunks/{rpc.RpPylpp0.js → rpc.cD77ENhU.js} +13 -14
  35. package/dist/chunks/{setup-common.hLGRxhC8.js → setup-common.DR1sucx6.js} +8 -8
  36. package/dist/chunks/{startModuleRunner.C8TW8zTN.js → startModuleRunner.C2tTvmF9.js} +131 -110
  37. package/dist/chunks/test.C3RPt8JR.js +214 -0
  38. package/dist/chunks/{utils.C7__0Iv5.js → utils.CG9h5ccR.js} +3 -15
  39. package/dist/chunks/{vi.BfdOiD4j.js → vi.BZvkKVkM.js} +73 -176
  40. package/dist/chunks/{vm.BHBje7cC.js → vm.DBeOXrP9.js} +29 -33
  41. package/dist/chunks/{worker.d.DYlqbejz.d.ts → worker.d.BFk-vvBU.d.ts} +42 -6
  42. package/dist/cli.js +12 -11
  43. package/dist/config.cjs +0 -1
  44. package/dist/config.d.ts +12 -14
  45. package/dist/config.js +1 -1
  46. package/dist/coverage.d.ts +8 -7
  47. package/dist/coverage.js +3 -14
  48. package/dist/environments.d.ts +3 -6
  49. package/dist/environments.js +1 -1
  50. package/dist/index.d.ts +24 -30
  51. package/dist/index.js +12 -11
  52. package/dist/module-evaluator.d.ts +6 -4
  53. package/dist/module-evaluator.js +14 -16
  54. package/dist/module-runner.js +5 -5
  55. package/dist/node.d.ts +83 -27
  56. package/dist/node.js +23 -20
  57. package/dist/reporters.d.ts +11 -10
  58. package/dist/reporters.js +12 -11
  59. package/dist/runners.d.ts +1 -1
  60. package/dist/runners.js +14 -216
  61. package/dist/snapshot.js +3 -3
  62. package/dist/suite.js +4 -3
  63. package/dist/worker.d.ts +26 -0
  64. package/dist/worker.js +45 -166
  65. package/dist/workers/forks.js +41 -35
  66. package/dist/workers/runVmTests.js +25 -22
  67. package/dist/workers/threads.js +41 -23
  68. package/dist/workers/vmForks.js +26 -39
  69. package/dist/workers/vmThreads.js +26 -29
  70. package/package.json +48 -35
  71. package/worker.d.ts +1 -0
  72. package/browser.d.ts +0 -1
  73. package/dist/chunks/base.BXI97p6t.js +0 -39
  74. package/dist/chunks/environment.d.2fYMoz3o.d.ts +0 -66
  75. package/dist/chunks/moduleTransport.I-bgQy0S.js +0 -19
  76. package/dist/chunks/resolver.Bx6lE0iq.js +0 -119
  77. package/dist/chunks/runBaseTests.D6sfuWBM.js +0 -99
  78. package/dist/chunks/typechecker.DSo_maXz.js +0 -762
  79. package/dist/chunks/utils.C2YI6McM.js +0 -52
  80. package/dist/chunks/worker.d.BKu8cnnX.d.ts +0 -8
  81. package/dist/workers.d.ts +0 -38
  82. package/dist/workers.js +0 -31
  83. package/execute.d.ts +0 -1
  84. package/utils.d.ts +0 -1
  85. package/workers.d.ts +0 -1
@@ -1,14 +1,15 @@
1
- import { equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT, ASYMMETRIC_MATCHERS_OBJECT, getState, setState, addCustomEqualityTesters, customMatchers } from '@vitest/expect';
1
+ import { chai, equals, iterableEquality, subsetEquality, JestExtend, JestChaiExpect, JestAsymmetricMatchers, GLOBAL_EXPECT, ASYMMETRIC_MATCHERS_OBJECT, getState, setState, addCustomEqualityTesters, customMatchers } from '@vitest/expect';
2
2
  import { getCurrentTest } from '@vitest/runner';
3
3
  import { getNames, getTestName } from '@vitest/runner/utils';
4
- import * as chai$1 from 'chai';
5
- import { g as getWorkerState, a as getCurrentEnvironment, i as isChildProcess, w as waitForImportsToResolve, r as resetModules } from './utils.C7__0Iv5.js';
6
- import { getSafeTimers, assertTypes, createSimpleStackTrace } from '@vitest/utils';
7
- import { g as getDefaultExportFromCjs, c as commonjsGlobal } from './_commonjsHelpers.BFTU3MAI.js';
4
+ import { g as getWorkerState, i as isChildProcess, w as waitForImportsToResolve, r as resetModules } from './utils.CG9h5ccR.js';
5
+ import { getSafeTimers } from '@vitest/utils/timers';
8
6
  import { stripSnapshotIndentation, addSerializer, SnapshotClient } from '@vitest/snapshot';
9
7
  import '@vitest/utils/error';
8
+ import { assertTypes, createSimpleStackTrace } from '@vitest/utils/helpers';
10
9
  import { fn, spyOn, restoreAllMocks, resetAllMocks, clearAllMocks, isMockFunction } from '@vitest/spy';
10
+ import '@vitest/utils/offset';
11
11
  import { parseSingleStack } from '@vitest/utils/source-map';
12
+ import { c as commonjsGlobal } from './_commonjsHelpers.BFTU3MAI.js';
12
13
  import { R as RealDate, r as resetDate, m as mockDate } from './date.-jtEtIeV.js';
13
14
 
14
15
  // these matchers are not supported because they don't make sense with poll
@@ -26,13 +27,13 @@ const unsupported = [
26
27
  ];
27
28
  function createExpectPoll(expect) {
28
29
  return function poll(fn, options = {}) {
29
- const state = getWorkerState(), defaults = state.config.expect?.poll ?? {}, { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options, assertion = expect(null, message).withContext({ poll: true });
30
+ const defaults = getWorkerState().config.expect?.poll ?? {}, { interval = defaults.interval ?? 50, timeout = defaults.timeout ?? 1e3, message } = options, assertion = expect(null, message).withContext({ poll: true });
30
31
  fn = fn.bind(assertion);
31
- const test = chai$1.util.flag(assertion, "vitest-test");
32
+ const test = chai.util.flag(assertion, "vitest-test");
32
33
  if (!test) throw new Error("expect.poll() must be called inside a test");
33
34
  const proxy = new Proxy(assertion, { get(target, key, receiver) {
34
35
  const assertionFunction = Reflect.get(target, key, receiver);
35
- if (typeof assertionFunction !== "function") return assertionFunction instanceof chai$1.Assertion ? proxy : assertionFunction;
36
+ if (typeof assertionFunction !== "function") return assertionFunction instanceof chai.Assertion ? proxy : assertionFunction;
36
37
  if (key === "assert") return assertionFunction;
37
38
  if (typeof key === "string" && unsupported.includes(key)) throw new SyntaxError(`expect.poll() is not supported in combination with .${key}(). Use vi.waitFor() if your assertion condition is unstable.`);
38
39
  return function(...args) {
@@ -40,17 +41,18 @@ function createExpectPoll(expect) {
40
41
  let intervalId, timeoutId, lastError;
41
42
  const { setTimeout, clearTimeout } = getSafeTimers(), check = async () => {
42
43
  try {
43
- chai$1.util.flag(assertion, "_name", key);
44
+ chai.util.flag(assertion, "_name", key);
44
45
  const obj = await fn();
45
- chai$1.util.flag(assertion, "object", obj), resolve(await assertionFunction.call(assertion, ...args)), clearTimeout(intervalId), clearTimeout(timeoutId);
46
+ chai.util.flag(assertion, "object", obj), resolve(await assertionFunction.call(assertion, ...args)), clearTimeout(intervalId), clearTimeout(timeoutId);
46
47
  } catch (err) {
47
- if (lastError = err, !chai$1.util.flag(assertion, "_isLastPollAttempt")) intervalId = setTimeout(check, interval);
48
+ if (lastError = err, !chai.util.flag(assertion, "_isLastPollAttempt")) intervalId = setTimeout(check, interval);
48
49
  }
49
50
  };
50
51
  timeoutId = setTimeout(() => {
51
- clearTimeout(intervalId), chai$1.util.flag(assertion, "_isLastPollAttempt", true);
52
- const rejectWithCause = (cause) => {
53
- reject(copyStackTrace$1(new Error("Matcher did not succeed in time.", { cause }), STACK_TRACE_ERROR));
52
+ clearTimeout(intervalId), chai.util.flag(assertion, "_isLastPollAttempt", true);
53
+ const rejectWithCause = (error) => {
54
+ if (error.cause == null) error.cause = /* @__PURE__ */ new Error("Matcher did not succeed in time.");
55
+ reject(copyStackTrace$1(error, STACK_TRACE_ERROR));
54
56
  };
55
57
  check().then(() => rejectWithCause(lastError)).catch((e) => rejectWithCause(e));
56
58
  }, timeout), check();
@@ -58,7 +60,7 @@ function createExpectPoll(expect) {
58
60
  let awaited = false;
59
61
  test.onFinished ??= [], test.onFinished.push(() => {
60
62
  if (!awaited) {
61
- const negated = chai$1.util.flag(assertion, "negate") ? "not." : "", name = chai$1.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)", assertionString = `expect.${name}.${negated}${String(key)}()`, error = /* @__PURE__ */ new Error(`${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:\n\nawait ${assertionString}\n`);
63
+ const negated = chai.util.flag(assertion, "negate") ? "not." : "", assertionString = `expect.${chai.util.flag(assertion, "_poll.element") ? "element(locator)" : "poll(assertion)"}.${negated}${String(key)}()`, error = /* @__PURE__ */ new Error(`${assertionString} was not awaited. This assertion is asynchronous and must be awaited; otherwise, it is not executed to avoid unhandled rejections:\n\nawait ${assertionString}\n`);
62
64
  throw copyStackTrace$1(error, STACK_TRACE_ERROR);
63
65
  }
64
66
  });
@@ -87,108 +89,9 @@ function copyStackTrace$1(target, source) {
87
89
  return target;
88
90
  }
89
91
 
90
- function commonjsRequire(path) {
91
- throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
92
- }
93
-
94
- var chaiSubset$1 = {exports: {}};
95
-
96
- var chaiSubset = chaiSubset$1.exports;
97
-
98
- var hasRequiredChaiSubset;
99
-
100
- function requireChaiSubset () {
101
- if (hasRequiredChaiSubset) return chaiSubset$1.exports;
102
- hasRequiredChaiSubset = 1;
103
- (function (module, exports) {
104
- (function() {
105
- (function(chaiSubset) {
106
- if (typeof commonjsRequire === 'function' && 'object' === 'object' && 'object' === 'object') {
107
- return module.exports = chaiSubset;
108
- } else {
109
- return chai.use(chaiSubset);
110
- }
111
- })(function(chai, utils) {
112
- var Assertion = chai.Assertion;
113
- var assertionPrototype = Assertion.prototype;
114
-
115
- Assertion.addMethod('containSubset', function (expected) {
116
- var actual = utils.flag(this, 'object');
117
- var showDiff = chai.config.showDiff;
118
-
119
- assertionPrototype.assert.call(this,
120
- compare(expected, actual),
121
- 'expected #{act} to contain subset #{exp}',
122
- 'expected #{act} to not contain subset #{exp}',
123
- expected,
124
- actual,
125
- showDiff
126
- );
127
- });
128
-
129
- chai.assert.containSubset = function(val, exp, msg) {
130
- new chai.Assertion(val, msg).to.be.containSubset(exp);
131
- };
132
-
133
- function compare(expected, actual) {
134
- if (expected === actual) {
135
- return true;
136
- }
137
- if (typeof(actual) !== typeof(expected)) {
138
- return false;
139
- }
140
- if (typeof(expected) !== 'object' || expected === null) {
141
- return expected === actual;
142
- }
143
- if (!!expected && !actual) {
144
- return false;
145
- }
146
-
147
- if (Array.isArray(expected)) {
148
- if (typeof(actual.length) !== 'number') {
149
- return false;
150
- }
151
- var aa = Array.prototype.slice.call(actual);
152
- return expected.every(function (exp) {
153
- return aa.some(function (act) {
154
- return compare(exp, act);
155
- });
156
- });
157
- }
158
-
159
- if (expected instanceof Date) {
160
- if (actual instanceof Date) {
161
- return expected.getTime() === actual.getTime();
162
- } else {
163
- return false;
164
- }
165
- }
166
-
167
- return Object.keys(expected).every(function (key) {
168
- var eo = expected[key];
169
- var ao = actual[key];
170
- if (typeof(eo) === 'object' && eo !== null && ao !== null) {
171
- return compare(eo, ao);
172
- }
173
- if (typeof(eo) === 'function') {
174
- return eo(ao);
175
- }
176
- return ao === eo;
177
- });
178
- }
179
- });
180
-
181
- }).call(chaiSubset);
182
- } (chaiSubset$1));
183
- return chaiSubset$1.exports;
184
- }
185
-
186
- var chaiSubsetExports = requireChaiSubset();
187
- var Subset = /*@__PURE__*/getDefaultExportFromCjs(chaiSubsetExports);
188
-
189
92
  function createAssertionMessage(util, assertion, hasArgs) {
190
- const not = util.flag(assertion, "negate") ? "not." : "", name = `${util.flag(assertion, "_name")}(${"expected" })`, promiseName = util.flag(assertion, "promise"), promise = promiseName ? `.${promiseName}` : "";
191
- return `expect(actual)${promise}.${not}${name}`;
93
+ const not = util.flag(assertion, "negate") ? "not." : "", name = `${util.flag(assertion, "_name")}(${"expected" })`, promiseName = util.flag(assertion, "promise");
94
+ return `expect(actual)${promiseName ? `.${promiseName}` : ""}.${not}${name}`;
192
95
  }
193
96
  function recordAsyncExpect(_test, promise, assertion, error) {
194
97
  const test = _test;
@@ -204,7 +107,7 @@ function recordAsyncExpect(_test, promise, assertion, error) {
204
107
  let resolved = false;
205
108
  return test.onFinished ??= [], test.onFinished.push(() => {
206
109
  if (!resolved) {
207
- const processor = globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""), stack = processor(error.stack);
110
+ const stack = (globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || ""))(error.stack);
208
111
  console.warn([
209
112
  `Promise returned by \`${assertion}\` was not awaited. `,
210
113
  "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
@@ -262,9 +165,7 @@ const SnapshotPlugin = (chai, utils) => {
262
165
  return test;
263
166
  }
264
167
  for (const key of ["matchSnapshot", "toMatchSnapshot"]) utils.addMethod(chai.Assertion.prototype, key, function(properties, message) {
265
- utils.flag(this, "_name", key);
266
- const isNot = utils.flag(this, "negate");
267
- if (isNot) throw new Error(`${key} cannot be used with "not"`);
168
+ if (utils.flag(this, "_name", key), utils.flag(this, "negate")) throw new Error(`${key} cannot be used with "not"`);
268
169
  const expected = utils.flag(this, "object"), test = getTest(key, this);
269
170
  if (typeof properties === "string" && typeof message === "undefined") message = properties, properties = void 0;
270
171
  const errorMessage = utils.flag(this, "message");
@@ -278,9 +179,7 @@ const SnapshotPlugin = (chai, utils) => {
278
179
  });
279
180
  });
280
181
  utils.addMethod(chai.Assertion.prototype, "toMatchFileSnapshot", function(file, message) {
281
- utils.flag(this, "_name", "toMatchFileSnapshot");
282
- const isNot = utils.flag(this, "negate");
283
- if (isNot) throw new Error("toMatchFileSnapshot cannot be used with \"not\"");
182
+ if (utils.flag(this, "_name", "toMatchFileSnapshot"), utils.flag(this, "negate")) throw new Error("toMatchFileSnapshot cannot be used with \"not\"");
284
183
  const error = /* @__PURE__ */ new Error("resolves"), expected = utils.flag(this, "object"), test = getTest("toMatchFileSnapshot", this), errorMessage = utils.flag(this, "message"), promise = getSnapshotClient().assertRaw({
285
184
  received: expected,
286
185
  message,
@@ -291,11 +190,9 @@ const SnapshotPlugin = (chai, utils) => {
291
190
  });
292
191
  return recordAsyncExpect(test, promise, createAssertionMessage(utils, this), error);
293
192
  }), utils.addMethod(chai.Assertion.prototype, "toMatchInlineSnapshot", function __INLINE_SNAPSHOT__(properties, inlineSnapshot, message) {
294
- utils.flag(this, "_name", "toMatchInlineSnapshot");
295
- const isNot = utils.flag(this, "negate");
296
- if (isNot) throw new Error("toMatchInlineSnapshot cannot be used with \"not\"");
297
- const test = getTest("toMatchInlineSnapshot", this), isInsideEach = test.each || test.suite?.each;
298
- if (isInsideEach) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
193
+ if (utils.flag(this, "_name", "toMatchInlineSnapshot"), utils.flag(this, "negate")) throw new Error("toMatchInlineSnapshot cannot be used with \"not\"");
194
+ const test = getTest("toMatchInlineSnapshot", this);
195
+ if (test.each || test.suite?.each) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
299
196
  const expected = utils.flag(this, "object"), error = utils.flag(this, "error");
300
197
  if (typeof properties === "string") message = inlineSnapshot, inlineSnapshot = properties, properties = void 0;
301
198
  if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
@@ -311,9 +208,7 @@ const SnapshotPlugin = (chai, utils) => {
311
208
  ...getTestNames(test)
312
209
  });
313
210
  }), utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingSnapshot", function(message) {
314
- utils.flag(this, "_name", "toThrowErrorMatchingSnapshot");
315
- const isNot = utils.flag(this, "negate");
316
- if (isNot) throw new Error("toThrowErrorMatchingSnapshot cannot be used with \"not\"");
211
+ if (utils.flag(this, "_name", "toThrowErrorMatchingSnapshot"), utils.flag(this, "negate")) throw new Error("toThrowErrorMatchingSnapshot cannot be used with \"not\"");
317
212
  const expected = utils.flag(this, "object"), test = getTest("toThrowErrorMatchingSnapshot", this), promise = utils.flag(this, "promise"), errorMessage = utils.flag(this, "message");
318
213
  getSnapshotClient().assert({
319
214
  received: getError(expected, promise),
@@ -322,10 +217,9 @@ const SnapshotPlugin = (chai, utils) => {
322
217
  ...getTestNames(test)
323
218
  });
324
219
  }), utils.addMethod(chai.Assertion.prototype, "toThrowErrorMatchingInlineSnapshot", function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
325
- const isNot = utils.flag(this, "negate");
326
- if (isNot) throw new Error("toThrowErrorMatchingInlineSnapshot cannot be used with \"not\"");
327
- const test = getTest("toThrowErrorMatchingInlineSnapshot", this), isInsideEach = test.each || test.suite?.each;
328
- if (isInsideEach) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
220
+ if (utils.flag(this, "negate")) throw new Error("toThrowErrorMatchingInlineSnapshot cannot be used with \"not\"");
221
+ const test = getTest("toThrowErrorMatchingInlineSnapshot", this);
222
+ if (test.each || test.suite?.each) throw new Error("InlineSnapshot cannot be used inside of test.each or describe.each");
329
223
  const expected = utils.flag(this, "object"), error = utils.flag(this, "error"), promise = utils.flag(this, "promise"), errorMessage = utils.flag(this, "message");
330
224
  if (inlineSnapshot) inlineSnapshot = stripSnapshotIndentation(inlineSnapshot);
331
225
  getSnapshotClient().assert({
@@ -340,16 +234,16 @@ const SnapshotPlugin = (chai, utils) => {
340
234
  }), utils.addMethod(chai.expect, "addSnapshotSerializer", addSerializer);
341
235
  };
342
236
 
343
- chai$1.use(JestExtend), chai$1.use(JestChaiExpect), chai$1.use(Subset), chai$1.use(SnapshotPlugin), chai$1.use(JestAsymmetricMatchers);
237
+ chai.use(JestExtend), chai.use(JestChaiExpect), chai.use(SnapshotPlugin), chai.use(JestAsymmetricMatchers);
344
238
 
345
239
  function createExpect(test) {
346
240
  const expect = ((value, message) => {
347
241
  const { assertionCalls } = getState(expect);
348
242
  setState({ assertionCalls: assertionCalls + 1 }, expect);
349
- const assert = chai$1.expect(value, message), _test = test || getCurrentTest();
243
+ const assert = chai.expect(value, message), _test = test || getCurrentTest();
350
244
  return _test ? assert.withTest(_test) : assert;
351
245
  });
352
- Object.assign(expect, chai$1.expect), Object.assign(expect, globalThis[ASYMMETRIC_MATCHERS_OBJECT]), expect.getState = () => getState(expect), expect.setState = (state) => setState(state, expect);
246
+ Object.assign(expect, chai.expect), Object.assign(expect, globalThis[ASYMMETRIC_MATCHERS_OBJECT]), expect.getState = () => getState(expect), expect.setState = (state) => setState(state, expect);
353
247
  // @ts-expect-error global is not typed
354
248
  const globalState = getState(globalThis[GLOBAL_EXPECT]) || {};
355
249
  setState({
@@ -359,16 +253,15 @@ function createExpect(test) {
359
253
  isExpectingAssertionsError: null,
360
254
  expectedAssertionsNumber: null,
361
255
  expectedAssertionsNumberErrorGen: null,
362
- environment: getCurrentEnvironment(),
363
256
  get testPath() {
364
257
  return getWorkerState().filepath;
365
258
  },
366
259
  currentTestName: test ? getTestName(test) : globalState.currentTestName
367
- }, expect), expect.extend = (matchers) => chai$1.expect.extend(expect, matchers), expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters), expect.soft = (...args) => {
260
+ }, expect), expect.assert = chai.assert, expect.extend = (matchers) => chai.expect.extend(expect, matchers), expect.addEqualityTesters = (customTesters) => addCustomEqualityTesters(customTesters), expect.soft = (...args) => {
368
261
  // @ts-expect-error private soft access
369
262
  return expect(...args).withContext({ soft: true });
370
263
  }, expect.poll = createExpectPoll(expect), expect.unreachable = (message) => {
371
- chai$1.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
264
+ chai.assert.fail(`expected${message ? ` "${message}" ` : " "}not to be reached`);
372
265
  };
373
266
  function assertions(expected) {
374
267
  const errorGen = () => /* @__PURE__ */ new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`);
@@ -386,7 +279,7 @@ function createExpect(test) {
386
279
  isExpectingAssertionsError: error
387
280
  });
388
281
  }
389
- return chai$1.util.addMethod(expect, "assertions", assertions), chai$1.util.addMethod(expect, "hasAssertions", hasAssertions), expect.extend(customMatchers), expect;
282
+ return chai.util.addMethod(expect, "assertions", assertions), chai.util.addMethod(expect, "hasAssertions", hasAssertions), expect.extend(customMatchers), expect;
390
283
  }
391
284
  const globalExpect = createExpect();
392
285
  Object.defineProperty(globalThis, GLOBAL_EXPECT, {
@@ -394,14 +287,15 @@ Object.defineProperty(globalThis, GLOBAL_EXPECT, {
394
287
  writable: true,
395
288
  configurable: true
396
289
  });
290
+ const assert = chai.assert;
291
+ const should = chai.should;
397
292
 
398
293
  /**
399
294
  * Gives access to injected context provided from the main thread.
400
295
  * This usually returns a value provided by `globalSetup` or an external library.
401
296
  */
402
297
  function inject(key) {
403
- const workerState = getWorkerState();
404
- return workerState.providedContext[key];
298
+ return getWorkerState().providedContext[key];
405
299
  }
406
300
 
407
301
  var fakeTimersSrc = {};
@@ -3503,9 +3397,9 @@ class FakeTimers {
3503
3397
  // | _fakingTime | _fakingDate |
3504
3398
  // +-------------+-------------+
3505
3399
  // | false | falsy | initial
3506
- // | false | truthy | vi.setSystemTime called first (for mocking only Date without fake timers)
3400
+ // | false | truthy | vi.setSystemTime called first (for mocking only Date without fake timers)
3507
3401
  // | true | falsy | vi.useFakeTimers called first
3508
- // | true | truthy | unreachable
3402
+ // | true | truthy | unreachable
3509
3403
  _fakingTime;
3510
3404
  _fakingDate;
3511
3405
  _fakeTimers;
@@ -3561,17 +3455,17 @@ class FakeTimers {
3561
3455
  if (this._fakingTime) this._clock.uninstall(), this._fakingTime = false;
3562
3456
  }
3563
3457
  useFakeTimers() {
3564
- if (this._fakingDate) throw new Error("\"setSystemTime\" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.");
3565
- if (!this._fakingTime) {
3566
- const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
3567
- if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) throw new Error("process.nextTick cannot be mocked inside child_process");
3568
- this._clock = this._fakeTimers.install({
3569
- now: Date.now(),
3570
- ...this._userConfig,
3571
- toFake: this._userConfig?.toFake || toFake,
3572
- ignoreMissingTimers: true
3573
- }), this._fakingTime = true;
3574
- }
3458
+ const fakeDate = this._fakingDate || Date.now();
3459
+ if (this._fakingDate) resetDate(), this._fakingDate = null;
3460
+ if (this._fakingTime) this._clock.uninstall();
3461
+ const toFake = Object.keys(this._fakeTimers.timers).filter((timer) => timer !== "nextTick" && timer !== "queueMicrotask");
3462
+ if (this._userConfig?.toFake?.includes("nextTick") && isChildProcess()) throw new Error("process.nextTick cannot be mocked inside child_process");
3463
+ this._clock = this._fakeTimers.install({
3464
+ now: fakeDate,
3465
+ ...this._userConfig,
3466
+ toFake: this._userConfig?.toFake || toFake,
3467
+ ignoreMissingTimers: true
3468
+ }), this._fakingTime = true;
3575
3469
  }
3576
3470
  reset() {
3577
3471
  if (this._checkFakeTimers()) {
@@ -3600,7 +3494,7 @@ class FakeTimers {
3600
3494
  return this._fakingTime;
3601
3495
  }
3602
3496
  _checkFakeTimers() {
3603
- if (!this._fakingTime) throw new Error("Timers are not mocked. Try calling \"vi.useFakeTimers()\" first.");
3497
+ if (!this._fakingTime) throw new Error("A function to advance timers was called but the timers APIs are not mocked. Call `vi.useFakeTimers()` in the test file first.");
3604
3498
  return this._fakingTime;
3605
3499
  }
3606
3500
  }
@@ -3677,11 +3571,11 @@ function waitUntil(callback, options = {}) {
3677
3571
 
3678
3572
  function createVitest() {
3679
3573
  let _config = null;
3680
- const workerState = getWorkerState();
3574
+ const state = () => getWorkerState();
3681
3575
  let _timers;
3682
3576
  const timers = () => _timers ||= new FakeTimers({
3683
3577
  global: globalThis,
3684
- config: workerState.config.fakeTimers
3578
+ config: state().config.fakeTimers
3685
3579
  }), _stubsGlobal = /* @__PURE__ */ new Map(), _stubsEnv = /* @__PURE__ */ new Map(), _envBooleans = [
3686
3580
  "PROD",
3687
3581
  "DEV",
@@ -3689,13 +3583,13 @@ function createVitest() {
3689
3583
  ], utils = {
3690
3584
  useFakeTimers(config) {
3691
3585
  if (isChildProcess()) {
3692
- if (config?.toFake?.includes("nextTick") || workerState.config?.fakeTimers?.toFake?.includes("nextTick")) throw new Error("vi.useFakeTimers({ toFake: [\"nextTick\"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.");
3586
+ if (config?.toFake?.includes("nextTick") || state().config?.fakeTimers?.toFake?.includes("nextTick")) throw new Error("vi.useFakeTimers({ toFake: [\"nextTick\"] }) is not supported in node:child_process. Use --pool=threads if mocking nextTick is required.");
3693
3587
  }
3694
3588
  if (config) timers().configure({
3695
- ...workerState.config.fakeTimers,
3589
+ ...state().config.fakeTimers,
3696
3590
  ...config
3697
3591
  });
3698
- else timers().configure(workerState.config.fakeTimers);
3592
+ else timers().configure(state().config.fakeTimers);
3699
3593
  return timers().useFakeTimers(), utils;
3700
3594
  },
3701
3595
  isFakeTimers() {
@@ -3772,13 +3666,16 @@ function createVitest() {
3772
3666
  },
3773
3667
  doUnmock(path) {
3774
3668
  if (typeof path !== "string") throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`);
3775
- _mocker().queueUnmock(path, getImporter("doUnmock"));
3669
+ const importer = getImporter("doUnmock");
3670
+ _mocker().queueUnmock(path, importer);
3776
3671
  },
3777
3672
  async importActual(path) {
3778
- return _mocker().importActual(path, getImporter("importActual"), _mocker().getMockContext().callstack);
3673
+ const importer = getImporter("importActual");
3674
+ return _mocker().importActual(path, importer, _mocker().getMockContext().callstack);
3779
3675
  },
3780
3676
  async importMock(path) {
3781
- return _mocker().importMock(path, getImporter("importMock"));
3677
+ const importer = getImporter("importMock");
3678
+ return _mocker().importMock(path, importer);
3782
3679
  },
3783
3680
  mockObject(value, options) {
3784
3681
  return _mocker().mockObject({ value }, void 0, options?.spy ? "autospy" : "automock").value;
@@ -3808,7 +3705,7 @@ function createVitest() {
3808
3705
  }), utils;
3809
3706
  },
3810
3707
  stubEnv(name, value) {
3811
- const state = getWorkerState(), env = state.metaEnv;
3708
+ const env = state().metaEnv;
3812
3709
  if (!_stubsEnv.has(name)) _stubsEnv.set(name, env[name]);
3813
3710
  if (_envBooleans.includes(name)) env[name] = value ? "1" : "";
3814
3711
  else if (value === void 0) delete env[name];
@@ -3822,24 +3719,24 @@ function createVitest() {
3822
3719
  }), _stubsGlobal.clear(), utils;
3823
3720
  },
3824
3721
  unstubAllEnvs() {
3825
- const state = getWorkerState(), env = state.metaEnv;
3722
+ const env = state().metaEnv;
3826
3723
  return _stubsEnv.forEach((original, name) => {
3827
3724
  if (original === void 0) delete env[name];
3828
3725
  else env[name] = original;
3829
3726
  }), _stubsEnv.clear(), utils;
3830
3727
  },
3831
3728
  resetModules() {
3832
- return resetModules(workerState.evaluatedModules), utils;
3729
+ return resetModules(state().evaluatedModules), utils;
3833
3730
  },
3834
3731
  async dynamicImportSettled() {
3835
3732
  return waitForImportsToResolve();
3836
3733
  },
3837
3734
  setConfig(config) {
3838
- if (!_config) _config = { ...workerState.config };
3839
- Object.assign(workerState.config, config);
3735
+ if (!_config) _config = { ...state().config };
3736
+ Object.assign(state().config, config);
3840
3737
  },
3841
3738
  resetConfig() {
3842
- if (_config) Object.assign(workerState.config, _config);
3739
+ if (_config) Object.assign(state().config, _config);
3843
3740
  }
3844
3741
  };
3845
3742
  return utils;
@@ -3853,10 +3750,10 @@ function _mocker() {
3853
3750
  } });
3854
3751
  }
3855
3752
  function getImporter(name) {
3856
- const stackTrace = createSimpleStackTrace({ stackTraceLimit: 5 }), stackArray = stackTrace.split("\n"), importerStackIndex = stackArray.findIndex((stack) => {
3753
+ const stackArray = createSimpleStackTrace({ stackTraceLimit: 5 }).split("\n"), importerStackIndex = stackArray.findLastIndex((stack) => {
3857
3754
  return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`);
3858
- }), stack = parseSingleStack(stackArray[importerStackIndex + 1]);
3859
- return stack?.file || "";
3755
+ });
3756
+ return parseSingleStack(stackArray[importerStackIndex + 1])?.file || "";
3860
3757
  }
3861
3758
 
3862
- export { globalExpect as a, vitest as b, createExpect as c, getSnapshotClient as g, inject as i, vi as v };
3759
+ export { getSnapshotClient as a, assert as b, createExpect as c, vitest as d, globalExpect as g, inject as i, should as s, vi as v };
@@ -1,16 +1,17 @@
1
1
  import { fileURLToPath, pathToFileURL } from 'node:url';
2
- import vm, { isContext } from 'node:vm';
2
+ import vm, { isContext, runInContext } from 'node:vm';
3
3
  import { dirname, basename, extname, normalize, resolve } from 'pathe';
4
4
  import { distDir } from '../path.js';
5
- import { createCustomConsole } from './console.B0quX7yH.js';
5
+ import { createCustomConsole } from './console.CTJL2nuH.js';
6
6
  import fs from 'node:fs';
7
7
  import { createRequire, Module, isBuiltin } from 'node:module';
8
- import { CSS_LANGS_RE, KNOWN_ASSET_RE, toArray, isBareImport } from '@vitest/utils';
9
- import { f as findNearestPackageData } from './resolver.Bx6lE0iq.js';
8
+ import { toArray, isBareImport } from '@vitest/utils/helpers';
9
+ import { findNearestPackageData } from '@vitest/utils/resolver';
10
10
  import { dirname as dirname$1 } from 'node:path';
11
+ import { CSS_LANGS_RE, KNOWN_ASSET_RE } from '@vitest/utils/constants';
11
12
  import { getDefaultRequestStubs } from '../module-evaluator.js';
12
- import { s as startVitestModuleRunner, a as VITEST_VM_CONTEXT_SYMBOL } from './startModuleRunner.C8TW8zTN.js';
13
- import { p as provideWorkerState } from './utils.C7__0Iv5.js';
13
+ import { s as startVitestModuleRunner, c as createNodeImportMeta, a as VITEST_VM_CONTEXT_SYMBOL } from './startModuleRunner.C2tTvmF9.js';
14
+ import { p as provideWorkerState } from './utils.CG9h5ccR.js';
14
15
 
15
16
  function interopCommonJsModule(interopDefault, mod) {
16
17
  if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) return {
@@ -35,8 +36,7 @@ function interopCommonJsModule(interopDefault, mod) {
35
36
  };
36
37
  }
37
38
  function isPrimitive(obj) {
38
- const isObject = obj != null && (typeof obj === "object" || typeof obj === "function");
39
- return !isObject;
39
+ return !(obj != null && (typeof obj === "object" || typeof obj === "function"));
40
40
  }
41
41
  const SyntheticModule = vm.SyntheticModule;
42
42
  const SourceTextModule = vm.SourceTextModule;
@@ -105,8 +105,7 @@ class CommonjsExecutor {
105
105
  }
106
106
  // exposed for external use, Node.js does the opposite
107
107
  static _load = (request, parent, _isMain) => {
108
- const require = Module$1.createRequire(parent?.filename ?? request);
109
- return require(request);
108
+ return Module$1.createRequire(parent?.filename ?? request)(request);
110
109
  };
111
110
  static wrap = (script) => {
112
111
  return Module$1.wrapper[0] + script + Module$1.wrapper[1];
@@ -156,8 +155,8 @@ class CommonjsExecutor {
156
155
  };
157
156
  createRequire = (filename) => {
158
157
  const _require = createRequire(filename), require = ((id) => {
159
- const resolved = _require.resolve(id), ext = extname(resolved);
160
- if (ext === ".node" || isBuiltin(resolved)) return this.requireCoreModule(resolved);
158
+ const resolved = _require.resolve(id);
159
+ if (extname(resolved) === ".node" || isBuiltin(resolved)) return this.requireCoreModule(resolved);
161
160
  const module = new this.Module(resolved);
162
161
  return this.loadCommonJSModule(module, resolved);
163
162
  });
@@ -187,8 +186,8 @@ class CommonjsExecutor {
187
186
  loadCommonJSModule(module, filename) {
188
187
  const cached = this.requireCache.get(filename);
189
188
  if (cached) return cached.exports;
190
- const extension = this.findLongestRegisteredExtension(filename), loader = this.extensions[extension] || this.extensions[".js"];
191
- return loader(module, filename), module.exports;
189
+ const extension = this.findLongestRegisteredExtension(filename);
190
+ return (this.extensions[extension] || this.extensions[".js"])(module, filename), module.exports;
192
191
  }
193
192
  findLongestRegisteredExtension(filename) {
194
193
  const name = basename(filename);
@@ -259,8 +258,7 @@ class CommonjsExecutor {
259
258
  // return namedExports
260
259
  // }
261
260
  require(identifier) {
262
- const ext = extname(identifier);
263
- if (ext === ".node" || isBuiltin(identifier)) return this.requireCoreModule(identifier);
261
+ if (extname(identifier) === ".node" || isBuiltin(identifier)) return this.requireCoreModule(identifier);
264
262
  const module = new this.Module(identifier);
265
263
  return this.loadCommonJSModule(module, identifier);
266
264
  }
@@ -345,7 +343,8 @@ class EsmExecutor {
345
343
  if (cached) return cached;
346
344
  const wasmModule = await WebAssembly.compile(source), exports = WebAssembly.Module.exports(wasmModule), imports = WebAssembly.Module.imports(wasmModule), moduleLookup = {};
347
345
  for (const { module } of imports) if (moduleLookup[module] === void 0) moduleLookup[module] = await this.executor.resolveModule(module, identifier);
348
- const evaluateModule = (module) => this.evaluateModule(module), syntheticModule = new SyntheticModule(exports.map(({ name }) => name), async function() {
346
+ const evaluateModule = (module) => this.evaluateModule(module);
347
+ return new SyntheticModule(exports.map(({ name }) => name), async function() {
349
348
  const importsObject = {};
350
349
  for (const { module, name } of imports) {
351
350
  if (!importsObject[module]) importsObject[module] = {};
@@ -357,7 +356,6 @@ class EsmExecutor {
357
356
  context: this.context,
358
357
  identifier
359
358
  });
360
- return syntheticModule;
361
359
  }
362
360
  cacheModule(identifier, module) {
363
361
  this.moduleCache.set(identifier, module);
@@ -416,9 +414,7 @@ class ViteExecutor {
416
414
  return this.options.context.__vitest_worker__;
417
415
  }
418
416
  async createViteModule(fileUrl) {
419
- if (fileUrl === CLIENT_FILE || fileUrl === CLIENT_ID) return this.createViteClientModule();
420
- const cached = this.esm.resolveCachedModule(fileUrl);
421
- return cached || this.esm.createEsModule(fileUrl, async () => {
417
+ return fileUrl === CLIENT_FILE || fileUrl === CLIENT_ID ? this.createViteClientModule() : this.esm.resolveCachedModule(fileUrl) || this.esm.createEsModule(fileUrl, async () => {
422
418
  try {
423
419
  const result = await this.options.transform(fileUrl);
424
420
  if (result.code) return result.code;
@@ -529,10 +525,7 @@ class ExternalModulesExecutor {
529
525
  // still experimental on NodeJS --experimental-wasm-modules
530
526
  // cf. ESM_FILE_FORMAT(url) in https://nodejs.org/docs/latest-v20.x/api/esm.html#resolution-algorithm
531
527
  type = "wasm";
532
- else {
533
- const pkgData = findNearestPackageData(normalize(pathUrl));
534
- type = pkgData.type === "module" ? "module" : "commonjs";
535
- }
528
+ else type = findNearestPackageData(normalize(pathUrl)).type === "module" ? "module" : "commonjs";
536
529
  return {
537
530
  type,
538
531
  path: pathUrl,
@@ -555,10 +548,7 @@ class ExternalModulesExecutor {
555
548
  case "module": return this.esm.createEsModule(url, () => this.fs.readFileAsync(path));
556
549
  case "commonjs": return this.cjs.getCjsSyntheticModule(path, identifier);
557
550
  case "network": return this.esm.createNetworkModule(url);
558
- default: {
559
- const _deadend = type;
560
- return _deadend;
561
- }
551
+ default: return type;
562
552
  }
563
553
  }
564
554
  get isNetworkSupported() {
@@ -611,13 +601,14 @@ async function runVmTests(method, state) {
611
601
  packageCache,
612
602
  transform: rpc.transform,
613
603
  viteClientModule: stubs["/@vite/client"]
614
- }), moduleRunner = await startVitestModuleRunner({
604
+ }), moduleRunner = startVitestModuleRunner({
615
605
  context,
616
606
  evaluatedModules: state.evaluatedModules,
617
607
  state,
618
- externalModulesExecutor
608
+ externalModulesExecutor,
609
+ createImportMeta: createNodeImportMeta
619
610
  });
620
- Object.defineProperty(context, VITEST_VM_CONTEXT_SYMBOL, {
611
+ if (Object.defineProperty(context, VITEST_VM_CONTEXT_SYMBOL, {
621
612
  value: {
622
613
  context,
623
614
  externalModulesExecutor
@@ -625,7 +616,12 @@ async function runVmTests(method, state) {
625
616
  configurable: true,
626
617
  enumerable: false,
627
618
  writable: false
628
- }), context.__vitest_mocker__ = moduleRunner.mocker;
619
+ }), context.__vitest_mocker__ = moduleRunner.mocker, ctx.config.serializedDefines) try {
620
+ runInContext(ctx.config.serializedDefines, context, { filename: "virtual:load-defines.js" });
621
+ } catch (error) {
622
+ throw new Error(`Failed to load custom "defines": ${error.message}`);
623
+ }
624
+ await moduleRunner.mocker.initializeSpyModule();
629
625
  const { run } = await moduleRunner.import(entryFile), fileSpecs = ctx.files.map((f) => typeof f === "string" ? {
630
626
  filepath: f,
631
627
  testLocations: void 0