@vitest/runner 4.0.0-beta.9 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,1990 @@
1
- export { a as afterAll, b as afterEach, c as beforeAll, d as beforeEach, p as collectTests, j as createTaskCollector, k as describe, l as getCurrentSuite, q as getCurrentTest, g as getFn, f as getHooks, m as it, o as onTestFailed, e as onTestFinished, s as setFn, h as setHooks, i as startTests, n as suite, t as test, u as updateTask } from './chunk-hooks.js';
2
- export { processError } from '@vitest/utils/error';
3
- import '@vitest/utils';
4
- import 'strip-literal';
1
+ import { isObject, createDefer, toArray, isNegativeNaN, objectAttr, shuffle, assertTypes } from '@vitest/utils/helpers';
2
+ import { getSafeTimers } from '@vitest/utils/timers';
3
+ import { processError } from '@vitest/utils/error';
4
+ import { format, formatRegExp, objDisplay } from '@vitest/utils/display';
5
+ import { c as createChainable, f as findTestFileStackTrace, b as createFileTask, a as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, l as limitConcurrency, p as partitionSuiteChildren, q as hasTests, o as hasFailed } from './chunk-tasks.js';
5
6
  import '@vitest/utils/source-map';
6
7
  import 'pathe';
8
+
9
+ class PendingError extends Error {
10
+ code = "VITEST_PENDING";
11
+ taskId;
12
+ constructor(message, task, note) {
13
+ super(message);
14
+ this.message = message;
15
+ this.note = note;
16
+ this.taskId = task.id;
17
+ }
18
+ }
19
+ class TestRunAbortError extends Error {
20
+ name = "TestRunAbortError";
21
+ reason;
22
+ constructor(message, reason) {
23
+ super(message);
24
+ this.reason = reason;
25
+ }
26
+ }
27
+
28
+ // use WeakMap here to make the Test and Suite object serializable
29
+ const fnMap = new WeakMap();
30
+ const testFixtureMap = new WeakMap();
31
+ const hooksMap = new WeakMap();
32
+ function setFn(key, fn) {
33
+ fnMap.set(key, fn);
34
+ }
35
+ function getFn(key) {
36
+ return fnMap.get(key);
37
+ }
38
+ function setTestFixture(key, fixture) {
39
+ testFixtureMap.set(key, fixture);
40
+ }
41
+ function getTestFixture(key) {
42
+ return testFixtureMap.get(key);
43
+ }
44
+ function setHooks(key, hooks) {
45
+ hooksMap.set(key, hooks);
46
+ }
47
+ function getHooks(key) {
48
+ return hooksMap.get(key);
49
+ }
50
+
51
+ async function runSetupFiles(config, files, runner) {
52
+ if (config.sequence.setupFiles === "parallel") {
53
+ await Promise.all(files.map(async (fsPath) => {
54
+ await runner.importFile(fsPath, "setup");
55
+ }));
56
+ } else {
57
+ for (const fsPath of files) {
58
+ await runner.importFile(fsPath, "setup");
59
+ }
60
+ }
61
+ }
62
+
63
+ function mergeScopedFixtures(testFixtures, scopedFixtures) {
64
+ const scopedFixturesMap = scopedFixtures.reduce((map, fixture) => {
65
+ map[fixture.prop] = fixture;
66
+ return map;
67
+ }, {});
68
+ const newFixtures = {};
69
+ testFixtures.forEach((fixture) => {
70
+ const useFixture = scopedFixturesMap[fixture.prop] || { ...fixture };
71
+ newFixtures[useFixture.prop] = useFixture;
72
+ });
73
+ for (const fixtureKep in newFixtures) {
74
+ var _fixture$deps;
75
+ const fixture = newFixtures[fixtureKep];
76
+ // if the fixture was define before the scope, then its dep
77
+ // will reference the original fixture instead of the scope
78
+ fixture.deps = (_fixture$deps = fixture.deps) === null || _fixture$deps === void 0 ? void 0 : _fixture$deps.map((dep) => newFixtures[dep.prop]);
79
+ }
80
+ return Object.values(newFixtures);
81
+ }
82
+ function mergeContextFixtures(fixtures, context, runner) {
83
+ const fixtureOptionKeys = [
84
+ "auto",
85
+ "injected",
86
+ "scope"
87
+ ];
88
+ const fixtureArray = Object.entries(fixtures).map(([prop, value]) => {
89
+ const fixtureItem = { value };
90
+ if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) {
91
+ var _runner$injectValue;
92
+ // fixture with options
93
+ Object.assign(fixtureItem, value[1]);
94
+ const userValue = value[0];
95
+ fixtureItem.value = fixtureItem.injected ? ((_runner$injectValue = runner.injectValue) === null || _runner$injectValue === void 0 ? void 0 : _runner$injectValue.call(runner, prop)) ?? userValue : userValue;
96
+ }
97
+ fixtureItem.scope = fixtureItem.scope || "test";
98
+ if (fixtureItem.scope === "worker" && !runner.getWorkerContext) {
99
+ fixtureItem.scope = "file";
100
+ }
101
+ fixtureItem.prop = prop;
102
+ fixtureItem.isFn = typeof fixtureItem.value === "function";
103
+ return fixtureItem;
104
+ });
105
+ if (Array.isArray(context.fixtures)) {
106
+ context.fixtures = context.fixtures.concat(fixtureArray);
107
+ } else {
108
+ context.fixtures = fixtureArray;
109
+ }
110
+ // Update dependencies of fixture functions
111
+ fixtureArray.forEach((fixture) => {
112
+ if (fixture.isFn) {
113
+ const usedProps = getUsedProps(fixture.value);
114
+ if (usedProps.length) {
115
+ fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop));
116
+ }
117
+ // test can access anything, so we ignore it
118
+ if (fixture.scope !== "test") {
119
+ var _fixture$deps2;
120
+ (_fixture$deps2 = fixture.deps) === null || _fixture$deps2 === void 0 ? void 0 : _fixture$deps2.forEach((dep) => {
121
+ if (!dep.isFn) {
122
+ // non fn fixtures are always resolved and available to anyone
123
+ return;
124
+ }
125
+ // worker scope can only import from worker scope
126
+ if (fixture.scope === "worker" && dep.scope === "worker") {
127
+ return;
128
+ }
129
+ // file scope an import from file and worker scopes
130
+ if (fixture.scope === "file" && dep.scope !== "test") {
131
+ return;
132
+ }
133
+ throw new SyntaxError(`cannot use the ${dep.scope} fixture "${dep.prop}" inside the ${fixture.scope} fixture "${fixture.prop}"`);
134
+ });
135
+ }
136
+ }
137
+ });
138
+ return context;
139
+ }
140
+ const fixtureValueMaps = new Map();
141
+ const cleanupFnArrayMap = new Map();
142
+ async function callFixtureCleanup(context) {
143
+ const cleanupFnArray = cleanupFnArrayMap.get(context) ?? [];
144
+ for (const cleanup of cleanupFnArray.reverse()) {
145
+ await cleanup();
146
+ }
147
+ cleanupFnArrayMap.delete(context);
148
+ }
149
+ function withFixtures(runner, fn, testContext) {
150
+ return (hookContext) => {
151
+ const context = hookContext || testContext;
152
+ if (!context) {
153
+ return fn({});
154
+ }
155
+ const fixtures = getTestFixture(context);
156
+ if (!(fixtures === null || fixtures === void 0 ? void 0 : fixtures.length)) {
157
+ return fn(context);
158
+ }
159
+ const usedProps = getUsedProps(fn);
160
+ const hasAutoFixture = fixtures.some(({ auto }) => auto);
161
+ if (!usedProps.length && !hasAutoFixture) {
162
+ return fn(context);
163
+ }
164
+ if (!fixtureValueMaps.get(context)) {
165
+ fixtureValueMaps.set(context, new Map());
166
+ }
167
+ const fixtureValueMap = fixtureValueMaps.get(context);
168
+ if (!cleanupFnArrayMap.has(context)) {
169
+ cleanupFnArrayMap.set(context, []);
170
+ }
171
+ const cleanupFnArray = cleanupFnArrayMap.get(context);
172
+ const usedFixtures = fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop));
173
+ const pendingFixtures = resolveDeps(usedFixtures);
174
+ if (!pendingFixtures.length) {
175
+ return fn(context);
176
+ }
177
+ async function resolveFixtures() {
178
+ for (const fixture of pendingFixtures) {
179
+ // fixture could be already initialized during "before" hook
180
+ if (fixtureValueMap.has(fixture)) {
181
+ continue;
182
+ }
183
+ const resolvedValue = await resolveFixtureValue(runner, fixture, context, cleanupFnArray);
184
+ context[fixture.prop] = resolvedValue;
185
+ fixtureValueMap.set(fixture, resolvedValue);
186
+ if (fixture.scope === "test") {
187
+ cleanupFnArray.unshift(() => {
188
+ fixtureValueMap.delete(fixture);
189
+ });
190
+ }
191
+ }
192
+ }
193
+ return resolveFixtures().then(() => fn(context));
194
+ };
195
+ }
196
+ const globalFixturePromise = new WeakMap();
197
+ function resolveFixtureValue(runner, fixture, context, cleanupFnArray) {
198
+ var _runner$getWorkerCont;
199
+ const fileContext = getFileContext(context.task.file);
200
+ const workerContext = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner);
201
+ if (!fixture.isFn) {
202
+ var _fixture$prop;
203
+ fileContext[_fixture$prop = fixture.prop] ?? (fileContext[_fixture$prop] = fixture.value);
204
+ if (workerContext) {
205
+ var _fixture$prop2;
206
+ workerContext[_fixture$prop2 = fixture.prop] ?? (workerContext[_fixture$prop2] = fixture.value);
207
+ }
208
+ return fixture.value;
209
+ }
210
+ if (fixture.scope === "test") {
211
+ return resolveFixtureFunction(fixture.value, context, cleanupFnArray);
212
+ }
213
+ // in case the test runs in parallel
214
+ if (globalFixturePromise.has(fixture)) {
215
+ return globalFixturePromise.get(fixture);
216
+ }
217
+ let fixtureContext;
218
+ if (fixture.scope === "worker") {
219
+ if (!workerContext) {
220
+ throw new TypeError("[@vitest/runner] The worker context is not available in the current test runner. Please, provide the `getWorkerContext` method when initiating the runner.");
221
+ }
222
+ fixtureContext = workerContext;
223
+ } else {
224
+ fixtureContext = fileContext;
225
+ }
226
+ if (fixture.prop in fixtureContext) {
227
+ return fixtureContext[fixture.prop];
228
+ }
229
+ if (!cleanupFnArrayMap.has(fixtureContext)) {
230
+ cleanupFnArrayMap.set(fixtureContext, []);
231
+ }
232
+ const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext);
233
+ const promise = resolveFixtureFunction(fixture.value, fixtureContext, cleanupFnFileArray).then((value) => {
234
+ fixtureContext[fixture.prop] = value;
235
+ globalFixturePromise.delete(fixture);
236
+ return value;
237
+ });
238
+ globalFixturePromise.set(fixture, promise);
239
+ return promise;
240
+ }
241
+ async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) {
242
+ // wait for `use` call to extract fixture value
243
+ const useFnArgPromise = createDefer();
244
+ let isUseFnArgResolved = false;
245
+ const fixtureReturn = fixtureFn(context, async (useFnArg) => {
246
+ // extract `use` argument
247
+ isUseFnArgResolved = true;
248
+ useFnArgPromise.resolve(useFnArg);
249
+ // suspend fixture teardown by holding off `useReturnPromise` resolution until cleanup
250
+ const useReturnPromise = createDefer();
251
+ cleanupFnArray.push(async () => {
252
+ // start teardown by resolving `use` Promise
253
+ useReturnPromise.resolve();
254
+ // wait for finishing teardown
255
+ await fixtureReturn;
256
+ });
257
+ await useReturnPromise;
258
+ }).catch((e) => {
259
+ // treat fixture setup error as test failure
260
+ if (!isUseFnArgResolved) {
261
+ useFnArgPromise.reject(e);
262
+ return;
263
+ }
264
+ // otherwise re-throw to avoid silencing error during cleanup
265
+ throw e;
266
+ });
267
+ return useFnArgPromise;
268
+ }
269
+ function resolveDeps(fixtures, depSet = new Set(), pendingFixtures = []) {
270
+ fixtures.forEach((fixture) => {
271
+ if (pendingFixtures.includes(fixture)) {
272
+ return;
273
+ }
274
+ if (!fixture.isFn || !fixture.deps) {
275
+ pendingFixtures.push(fixture);
276
+ return;
277
+ }
278
+ if (depSet.has(fixture)) {
279
+ throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`);
280
+ }
281
+ depSet.add(fixture);
282
+ resolveDeps(fixture.deps, depSet, pendingFixtures);
283
+ pendingFixtures.push(fixture);
284
+ depSet.clear();
285
+ });
286
+ return pendingFixtures;
287
+ }
288
+ function getUsedProps(fn) {
289
+ let fnString = filterOutComments(fn.toString());
290
+ // match lowered async function and strip it off
291
+ // example code on esbuild-try https://esbuild.github.io/try/#YgAwLjI0LjAALS1zdXBwb3J0ZWQ6YXN5bmMtYXdhaXQ9ZmFsc2UAZQBlbnRyeS50cwBjb25zdCBvID0gewogIGYxOiBhc3luYyAoKSA9PiB7fSwKICBmMjogYXN5bmMgKGEpID0+IHt9LAogIGYzOiBhc3luYyAoYSwgYikgPT4ge30sCiAgZjQ6IGFzeW5jIGZ1bmN0aW9uKGEpIHt9LAogIGY1OiBhc3luYyBmdW5jdGlvbiBmZihhKSB7fSwKICBhc3luYyBmNihhKSB7fSwKCiAgZzE6IGFzeW5jICgpID0+IHt9LAogIGcyOiBhc3luYyAoeyBhIH0pID0+IHt9LAogIGczOiBhc3luYyAoeyBhIH0sIGIpID0+IHt9LAogIGc0OiBhc3luYyBmdW5jdGlvbiAoeyBhIH0pIHt9LAogIGc1OiBhc3luYyBmdW5jdGlvbiBnZyh7IGEgfSkge30sCiAgYXN5bmMgZzYoeyBhIH0pIHt9LAoKICBoMTogYXN5bmMgKCkgPT4ge30sCiAgLy8gY29tbWVudCBiZXR3ZWVuCiAgaDI6IGFzeW5jIChhKSA9PiB7fSwKfQ
292
+ // __async(this, null, function*
293
+ // __async(this, arguments, function*
294
+ // __async(this, [_0, _1], function*
295
+ if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) {
296
+ fnString = fnString.split(/__async\((?:this|null),/)[1];
297
+ }
298
+ const match = fnString.match(/[^(]*\(([^)]*)/);
299
+ if (!match) {
300
+ return [];
301
+ }
302
+ const args = splitByComma(match[1]);
303
+ if (!args.length) {
304
+ return [];
305
+ }
306
+ let first = args[0];
307
+ if ("__VITEST_FIXTURE_INDEX__" in fn) {
308
+ first = args[fn.__VITEST_FIXTURE_INDEX__];
309
+ if (!first) {
310
+ return [];
311
+ }
312
+ }
313
+ if (!(first[0] === "{" && first.endsWith("}"))) {
314
+ throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`);
315
+ }
316
+ const _first = first.slice(1, -1).replace(/\s/g, "");
317
+ const props = splitByComma(_first).map((prop) => {
318
+ return prop.replace(/:.*|=.*/g, "");
319
+ });
320
+ const last = props.at(-1);
321
+ if (last && last.startsWith("...")) {
322
+ throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`);
323
+ }
324
+ return props;
325
+ }
326
+ function filterOutComments(s) {
327
+ const result = [];
328
+ let commentState = "none";
329
+ for (let i = 0; i < s.length; ++i) {
330
+ if (commentState === "singleline") {
331
+ if (s[i] === "\n") {
332
+ commentState = "none";
333
+ }
334
+ } else if (commentState === "multiline") {
335
+ if (s[i - 1] === "*" && s[i] === "/") {
336
+ commentState = "none";
337
+ }
338
+ } else if (commentState === "none") {
339
+ if (s[i] === "/" && s[i + 1] === "/") {
340
+ commentState = "singleline";
341
+ } else if (s[i] === "/" && s[i + 1] === "*") {
342
+ commentState = "multiline";
343
+ i += 2;
344
+ } else {
345
+ result.push(s[i]);
346
+ }
347
+ }
348
+ }
349
+ return result.join("");
350
+ }
351
+ function splitByComma(s) {
352
+ const result = [];
353
+ const stack = [];
354
+ let start = 0;
355
+ for (let i = 0; i < s.length; i++) {
356
+ if (s[i] === "{" || s[i] === "[") {
357
+ stack.push(s[i] === "{" ? "}" : "]");
358
+ } else if (s[i] === stack.at(-1)) {
359
+ stack.pop();
360
+ } else if (!stack.length && s[i] === ",") {
361
+ const token = s.substring(start, i).trim();
362
+ if (token) {
363
+ result.push(token);
364
+ }
365
+ start = i + 1;
366
+ }
367
+ }
368
+ const lastToken = s.substring(start).trim();
369
+ if (lastToken) {
370
+ result.push(lastToken);
371
+ }
372
+ return result;
373
+ }
374
+
375
+ let _test;
376
+ function setCurrentTest(test) {
377
+ _test = test;
378
+ }
379
+ function getCurrentTest() {
380
+ return _test;
381
+ }
382
+ const tests = [];
383
+ function addRunningTest(test) {
384
+ tests.push(test);
385
+ return () => {
386
+ tests.splice(tests.indexOf(test));
387
+ };
388
+ }
389
+ function getRunningTests() {
390
+ return tests;
391
+ }
392
+
393
+ /**
394
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
395
+ * Suites can contain both tests and other suites, enabling complex test structures.
396
+ *
397
+ * @param {string} name - The name of the suite, used for identification and reporting.
398
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
399
+ * @example
400
+ * ```ts
401
+ * // Define a suite with two tests
402
+ * suite('Math operations', () => {
403
+ * test('should add two numbers', () => {
404
+ * expect(add(1, 2)).toBe(3);
405
+ * });
406
+ *
407
+ * test('should subtract two numbers', () => {
408
+ * expect(subtract(5, 2)).toBe(3);
409
+ * });
410
+ * });
411
+ * ```
412
+ * @example
413
+ * ```ts
414
+ * // Define nested suites
415
+ * suite('String operations', () => {
416
+ * suite('Trimming', () => {
417
+ * test('should trim whitespace from start and end', () => {
418
+ * expect(' hello '.trim()).toBe('hello');
419
+ * });
420
+ * });
421
+ *
422
+ * suite('Concatenation', () => {
423
+ * test('should concatenate two strings', () => {
424
+ * expect('hello' + ' ' + 'world').toBe('hello world');
425
+ * });
426
+ * });
427
+ * });
428
+ * ```
429
+ */
430
+ const suite = createSuite();
431
+ /**
432
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
433
+ *
434
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
435
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
436
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
437
+ * @throws {Error} If called inside another test function.
438
+ * @example
439
+ * ```ts
440
+ * // Define a simple test
441
+ * test('should add two numbers', () => {
442
+ * expect(add(1, 2)).toBe(3);
443
+ * });
444
+ * ```
445
+ * @example
446
+ * ```ts
447
+ * // Define a test with options
448
+ * test('should subtract two numbers', { retry: 3 }, () => {
449
+ * expect(subtract(5, 2)).toBe(3);
450
+ * });
451
+ * ```
452
+ */
453
+ const test = createTest(function(name, optionsOrFn, optionsOrTest) {
454
+ if (getCurrentTest()) {
455
+ throw new Error("Calling the test function inside another test function is not allowed. Please put it inside \"describe\" or \"suite\" so it can be properly collected.");
456
+ }
457
+ getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
458
+ });
459
+ /**
460
+ * Creates a suite of tests, allowing for grouping and hierarchical organization of tests.
461
+ * Suites can contain both tests and other suites, enabling complex test structures.
462
+ *
463
+ * @param {string} name - The name of the suite, used for identification and reporting.
464
+ * @param {Function} fn - A function that defines the tests and suites within this suite.
465
+ * @example
466
+ * ```ts
467
+ * // Define a suite with two tests
468
+ * describe('Math operations', () => {
469
+ * test('should add two numbers', () => {
470
+ * expect(add(1, 2)).toBe(3);
471
+ * });
472
+ *
473
+ * test('should subtract two numbers', () => {
474
+ * expect(subtract(5, 2)).toBe(3);
475
+ * });
476
+ * });
477
+ * ```
478
+ * @example
479
+ * ```ts
480
+ * // Define nested suites
481
+ * describe('String operations', () => {
482
+ * describe('Trimming', () => {
483
+ * test('should trim whitespace from start and end', () => {
484
+ * expect(' hello '.trim()).toBe('hello');
485
+ * });
486
+ * });
487
+ *
488
+ * describe('Concatenation', () => {
489
+ * test('should concatenate two strings', () => {
490
+ * expect('hello' + ' ' + 'world').toBe('hello world');
491
+ * });
492
+ * });
493
+ * });
494
+ * ```
495
+ */
496
+ const describe = suite;
497
+ /**
498
+ * Defines a test case with a given name and test function. The test function can optionally be configured with test options.
499
+ *
500
+ * @param {string | Function} name - The name of the test or a function that will be used as a test name.
501
+ * @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided.
502
+ * @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters.
503
+ * @throws {Error} If called inside another test function.
504
+ * @example
505
+ * ```ts
506
+ * // Define a simple test
507
+ * it('adds two numbers', () => {
508
+ * expect(add(1, 2)).toBe(3);
509
+ * });
510
+ * ```
511
+ * @example
512
+ * ```ts
513
+ * // Define a test with options
514
+ * it('subtracts two numbers', { retry: 3 }, () => {
515
+ * expect(subtract(5, 2)).toBe(3);
516
+ * });
517
+ * ```
518
+ */
519
+ const it = test;
520
+ let runner;
521
+ let defaultSuite;
522
+ let currentTestFilepath;
523
+ function assert(condition, message) {
524
+ if (!condition) {
525
+ throw new Error(`Vitest failed to find ${message}. This is a bug in Vitest. Please, open an issue with reproduction.`);
526
+ }
527
+ }
528
+ function getDefaultSuite() {
529
+ assert(defaultSuite, "the default suite");
530
+ return defaultSuite;
531
+ }
532
+ function getRunner() {
533
+ assert(runner, "the runner");
534
+ return runner;
535
+ }
536
+ function createDefaultSuite(runner) {
537
+ const config = runner.config.sequence;
538
+ const collector = suite("", { concurrent: config.concurrent }, () => {});
539
+ // no parent suite for top-level tests
540
+ delete collector.suite;
541
+ return collector;
542
+ }
543
+ function clearCollectorContext(filepath, currentRunner) {
544
+ if (!defaultSuite) {
545
+ defaultSuite = createDefaultSuite(currentRunner);
546
+ }
547
+ runner = currentRunner;
548
+ currentTestFilepath = filepath;
549
+ collectorContext.tasks.length = 0;
550
+ defaultSuite.clear();
551
+ collectorContext.currentSuite = defaultSuite;
552
+ }
553
+ function getCurrentSuite() {
554
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
555
+ assert(currentSuite, "the current suite");
556
+ return currentSuite;
557
+ }
558
+ function createSuiteHooks() {
559
+ return {
560
+ beforeAll: [],
561
+ afterAll: [],
562
+ beforeEach: [],
563
+ afterEach: []
564
+ };
565
+ }
566
+ function parseArguments(optionsOrFn, timeoutOrTest) {
567
+ if (timeoutOrTest != null && typeof timeoutOrTest === "object") {
568
+ throw new TypeError(`Siganture "test(name, fn, { ... })" was deprecated in Vitest 3 and removed in Vitest 4. Please, provide options as a second argument instead.`);
569
+ }
570
+ let options = {};
571
+ let fn;
572
+ // it('', () => {}, 1000)
573
+ if (typeof timeoutOrTest === "number") {
574
+ options = { timeout: timeoutOrTest };
575
+ } else if (typeof optionsOrFn === "object") {
576
+ options = optionsOrFn;
577
+ }
578
+ if (typeof optionsOrFn === "function") {
579
+ if (typeof timeoutOrTest === "function") {
580
+ throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
581
+ }
582
+ fn = optionsOrFn;
583
+ } else if (typeof timeoutOrTest === "function") {
584
+ fn = timeoutOrTest;
585
+ }
586
+ return {
587
+ options,
588
+ handler: fn
589
+ };
590
+ }
591
+ // implementations
592
+ function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions, parentCollectorFixtures) {
593
+ const tasks = [];
594
+ let suite;
595
+ initSuite(true);
596
+ const task = function(name = "", options = {}) {
597
+ var _collectorContext$cur;
598
+ const timeout = (options === null || options === void 0 ? void 0 : options.timeout) ?? runner.config.testTimeout;
599
+ const task = {
600
+ id: "",
601
+ name,
602
+ suite: (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.suite,
603
+ each: options.each,
604
+ fails: options.fails,
605
+ context: undefined,
606
+ type: "test",
607
+ file: undefined,
608
+ timeout,
609
+ retry: options.retry ?? runner.config.retry,
610
+ repeats: options.repeats,
611
+ mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
612
+ meta: options.meta ?? Object.create(null),
613
+ annotations: []
614
+ };
615
+ const handler = options.handler;
616
+ if (task.mode === "run" && !handler) {
617
+ task.mode = "todo";
618
+ }
619
+ if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) {
620
+ task.concurrent = true;
621
+ }
622
+ task.shuffle = suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle;
623
+ const context = createTestContext(task, runner);
624
+ // create test context
625
+ Object.defineProperty(task, "context", {
626
+ value: context,
627
+ enumerable: false
628
+ });
629
+ setTestFixture(context, options.fixtures);
630
+ // custom can be called from any place, let's assume the limit is 15 stacks
631
+ const limit = Error.stackTraceLimit;
632
+ Error.stackTraceLimit = 15;
633
+ const stackTraceError = new Error("STACK_TRACE_ERROR");
634
+ Error.stackTraceLimit = limit;
635
+ if (handler) {
636
+ setFn(task, withTimeout(withAwaitAsyncAssertions(withFixtures(runner, handler, context), task), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error)));
637
+ }
638
+ if (runner.config.includeTaskLocation) {
639
+ const error = stackTraceError.stack;
640
+ const stack = findTestFileStackTrace(currentTestFilepath, error);
641
+ if (stack) {
642
+ task.location = {
643
+ line: stack.line,
644
+ column: stack.column
645
+ };
646
+ }
647
+ }
648
+ tasks.push(task);
649
+ return task;
650
+ };
651
+ const test = createTest(function(name, optionsOrFn, timeoutOrTest) {
652
+ let { options, handler } = parseArguments(optionsOrFn, timeoutOrTest);
653
+ // inherit repeats, retry, timeout from suite
654
+ if (typeof suiteOptions === "object") {
655
+ options = Object.assign({}, suiteOptions, options);
656
+ }
657
+ // inherit concurrent / sequential from suite
658
+ options.concurrent = this.concurrent || !this.sequential && (options === null || options === void 0 ? void 0 : options.concurrent);
659
+ options.sequential = this.sequential || !this.concurrent && (options === null || options === void 0 ? void 0 : options.sequential);
660
+ const test = task(formatName(name), {
661
+ ...this,
662
+ ...options,
663
+ handler
664
+ });
665
+ test.type = "test";
666
+ });
667
+ let collectorFixtures = parentCollectorFixtures;
668
+ const collector = {
669
+ type: "collector",
670
+ name,
671
+ mode,
672
+ suite,
673
+ options: suiteOptions,
674
+ test,
675
+ tasks,
676
+ collect,
677
+ task,
678
+ clear,
679
+ on: addHook,
680
+ fixtures() {
681
+ return collectorFixtures;
682
+ },
683
+ scoped(fixtures) {
684
+ const parsed = mergeContextFixtures(fixtures, { fixtures: collectorFixtures }, runner);
685
+ if (parsed.fixtures) {
686
+ collectorFixtures = parsed.fixtures;
687
+ }
688
+ }
689
+ };
690
+ function addHook(name, ...fn) {
691
+ getHooks(suite)[name].push(...fn);
692
+ }
693
+ function initSuite(includeLocation) {
694
+ var _collectorContext$cur2;
695
+ if (typeof suiteOptions === "number") {
696
+ suiteOptions = { timeout: suiteOptions };
697
+ }
698
+ suite = {
699
+ id: "",
700
+ type: "suite",
701
+ name,
702
+ suite: (_collectorContext$cur2 = collectorContext.currentSuite) === null || _collectorContext$cur2 === void 0 ? void 0 : _collectorContext$cur2.suite,
703
+ mode,
704
+ each,
705
+ file: undefined,
706
+ shuffle: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle,
707
+ tasks: [],
708
+ meta: Object.create(null),
709
+ concurrent: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.concurrent
710
+ };
711
+ if (runner && includeLocation && runner.config.includeTaskLocation) {
712
+ const limit = Error.stackTraceLimit;
713
+ Error.stackTraceLimit = 15;
714
+ const error = new Error("stacktrace").stack;
715
+ Error.stackTraceLimit = limit;
716
+ const stack = findTestFileStackTrace(currentTestFilepath, error);
717
+ if (stack) {
718
+ suite.location = {
719
+ line: stack.line,
720
+ column: stack.column
721
+ };
722
+ }
723
+ }
724
+ setHooks(suite, createSuiteHooks());
725
+ }
726
+ function clear() {
727
+ tasks.length = 0;
728
+ initSuite(false);
729
+ }
730
+ async function collect(file) {
731
+ if (!file) {
732
+ throw new TypeError("File is required to collect tasks.");
733
+ }
734
+ if (factory) {
735
+ await runWithSuite(collector, () => factory(test));
736
+ }
737
+ const allChildren = [];
738
+ for (const i of tasks) {
739
+ allChildren.push(i.type === "collector" ? await i.collect(file) : i);
740
+ }
741
+ suite.file = file;
742
+ suite.tasks = allChildren;
743
+ allChildren.forEach((task) => {
744
+ task.file = file;
745
+ });
746
+ return suite;
747
+ }
748
+ collectTask(collector);
749
+ return collector;
750
+ }
751
+ function withAwaitAsyncAssertions(fn, task) {
752
+ return (async (...args) => {
753
+ const fnResult = await fn(...args);
754
+ // some async expect will be added to this array, in case user forget to await them
755
+ if (task.promises) {
756
+ const result = await Promise.allSettled(task.promises);
757
+ const errors = result.map((r) => r.status === "rejected" ? r.reason : undefined).filter(Boolean);
758
+ if (errors.length) {
759
+ throw errors;
760
+ }
761
+ }
762
+ return fnResult;
763
+ });
764
+ }
765
+ function createSuite() {
766
+ function suiteFn(name, factoryOrOptions, optionsOrFactory) {
767
+ var _currentSuite$options;
768
+ let mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
769
+ const currentSuite = collectorContext.currentSuite || defaultSuite;
770
+ let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory);
771
+ if (mode === "run" && !factory) {
772
+ mode = "todo";
773
+ }
774
+ const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false;
775
+ const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false;
776
+ // inherit options from current suite
777
+ options = {
778
+ ...currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.options,
779
+ ...options,
780
+ shuffle: this.shuffle ?? options.shuffle ?? (currentSuite === null || currentSuite === void 0 || (_currentSuite$options = currentSuite.options) === null || _currentSuite$options === void 0 ? void 0 : _currentSuite$options.shuffle) ?? (runner === null || runner === void 0 ? void 0 : runner.config.sequence.shuffle)
781
+ };
782
+ // inherit concurrent / sequential from suite
783
+ const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified;
784
+ const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
785
+ options.concurrent = isConcurrent && !isSequential;
786
+ options.sequential = isSequential && !isConcurrent;
787
+ return createSuiteCollector(formatName(name), factory, mode, this.each, options, currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fixtures());
788
+ }
789
+ suiteFn.each = function(cases, ...args) {
790
+ const suite = this.withContext();
791
+ this.setContext("each", true);
792
+ if (Array.isArray(cases) && args.length) {
793
+ cases = formatTemplateString(cases, args);
794
+ }
795
+ return (name, optionsOrFn, fnOrOptions) => {
796
+ const _name = formatName(name);
797
+ const arrayOnlyCases = cases.every(Array.isArray);
798
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
799
+ const fnFirst = typeof optionsOrFn === "function";
800
+ cases.forEach((i, idx) => {
801
+ const items = Array.isArray(i) ? i : [i];
802
+ if (fnFirst) {
803
+ if (arrayOnlyCases) {
804
+ suite(formatTitle(_name, items, idx), handler ? () => handler(...items) : undefined, options.timeout);
805
+ } else {
806
+ suite(formatTitle(_name, items, idx), handler ? () => handler(i) : undefined, options.timeout);
807
+ }
808
+ } else {
809
+ if (arrayOnlyCases) {
810
+ suite(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : undefined);
811
+ } else {
812
+ suite(formatTitle(_name, items, idx), options, handler ? () => handler(i) : undefined);
813
+ }
814
+ }
815
+ });
816
+ this.setContext("each", undefined);
817
+ };
818
+ };
819
+ suiteFn.for = function(cases, ...args) {
820
+ if (Array.isArray(cases) && args.length) {
821
+ cases = formatTemplateString(cases, args);
822
+ }
823
+ return (name, optionsOrFn, fnOrOptions) => {
824
+ const name_ = formatName(name);
825
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
826
+ cases.forEach((item, idx) => {
827
+ suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : undefined);
828
+ });
829
+ };
830
+ };
831
+ suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
832
+ suiteFn.runIf = (condition) => condition ? suite : suite.skip;
833
+ return createChainable([
834
+ "concurrent",
835
+ "sequential",
836
+ "shuffle",
837
+ "skip",
838
+ "only",
839
+ "todo"
840
+ ], suiteFn);
841
+ }
842
+ function createTaskCollector(fn, context) {
843
+ const taskFn = fn;
844
+ taskFn.each = function(cases, ...args) {
845
+ const test = this.withContext();
846
+ this.setContext("each", true);
847
+ if (Array.isArray(cases) && args.length) {
848
+ cases = formatTemplateString(cases, args);
849
+ }
850
+ return (name, optionsOrFn, fnOrOptions) => {
851
+ const _name = formatName(name);
852
+ const arrayOnlyCases = cases.every(Array.isArray);
853
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
854
+ const fnFirst = typeof optionsOrFn === "function";
855
+ cases.forEach((i, idx) => {
856
+ const items = Array.isArray(i) ? i : [i];
857
+ if (fnFirst) {
858
+ if (arrayOnlyCases) {
859
+ test(formatTitle(_name, items, idx), handler ? () => handler(...items) : undefined, options.timeout);
860
+ } else {
861
+ test(formatTitle(_name, items, idx), handler ? () => handler(i) : undefined, options.timeout);
862
+ }
863
+ } else {
864
+ if (arrayOnlyCases) {
865
+ test(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : undefined);
866
+ } else {
867
+ test(formatTitle(_name, items, idx), options, handler ? () => handler(i) : undefined);
868
+ }
869
+ }
870
+ });
871
+ this.setContext("each", undefined);
872
+ };
873
+ };
874
+ taskFn.for = function(cases, ...args) {
875
+ const test = this.withContext();
876
+ if (Array.isArray(cases) && args.length) {
877
+ cases = formatTemplateString(cases, args);
878
+ }
879
+ return (name, optionsOrFn, fnOrOptions) => {
880
+ const _name = formatName(name);
881
+ const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
882
+ cases.forEach((item, idx) => {
883
+ // monkey-patch handler to allow parsing fixture
884
+ const handlerWrapper = handler ? (ctx) => handler(item, ctx) : undefined;
885
+ if (handlerWrapper) {
886
+ handlerWrapper.__VITEST_FIXTURE_INDEX__ = 1;
887
+ handlerWrapper.toString = () => handler.toString();
888
+ }
889
+ test(formatTitle(_name, toArray(item), idx), options, handlerWrapper);
890
+ });
891
+ };
892
+ };
893
+ taskFn.skipIf = function(condition) {
894
+ return condition ? this.skip : this;
895
+ };
896
+ taskFn.runIf = function(condition) {
897
+ return condition ? this : this.skip;
898
+ };
899
+ taskFn.scoped = function(fixtures) {
900
+ const collector = getCurrentSuite();
901
+ collector.scoped(fixtures);
902
+ };
903
+ taskFn.extend = function(fixtures) {
904
+ const _context = mergeContextFixtures(fixtures, context || {}, runner);
905
+ const originalWrapper = fn;
906
+ return createTest(function(name, optionsOrFn, optionsOrTest) {
907
+ const collector = getCurrentSuite();
908
+ const scopedFixtures = collector.fixtures();
909
+ const context = { ...this };
910
+ if (scopedFixtures) {
911
+ context.fixtures = mergeScopedFixtures(context.fixtures || [], scopedFixtures);
912
+ }
913
+ originalWrapper.call(context, formatName(name), optionsOrFn, optionsOrTest);
914
+ }, _context);
915
+ };
916
+ taskFn.beforeEach = beforeEach;
917
+ taskFn.afterEach = afterEach;
918
+ taskFn.beforeAll = beforeAll;
919
+ taskFn.afterAll = afterAll;
920
+ const _test = createChainable([
921
+ "concurrent",
922
+ "sequential",
923
+ "skip",
924
+ "only",
925
+ "todo",
926
+ "fails"
927
+ ], taskFn);
928
+ if (context) {
929
+ _test.mergeContext(context);
930
+ }
931
+ return _test;
932
+ }
933
+ function createTest(fn, context) {
934
+ return createTaskCollector(fn, context);
935
+ }
936
+ function formatName(name) {
937
+ return typeof name === "string" ? name : typeof name === "function" ? name.name || "<anonymous>" : String(name);
938
+ }
939
+ function formatTitle(template, items, idx) {
940
+ if (template.includes("%#") || template.includes("%$")) {
941
+ // '%#' match index of the test case
942
+ template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%");
943
+ }
944
+ const count = template.split("%").length - 1;
945
+ if (template.includes("%f")) {
946
+ const placeholders = template.match(/%f/g) || [];
947
+ placeholders.forEach((_, i) => {
948
+ if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) {
949
+ // Replace the i-th occurrence of '%f' with '-%f'
950
+ let occurrence = 0;
951
+ template = template.replace(/%f/g, (match) => {
952
+ occurrence++;
953
+ return occurrence === i + 1 ? "-%f" : match;
954
+ });
955
+ }
956
+ });
957
+ }
958
+ const isObjectItem = isObject(items[0]);
959
+ function formatAttribute(s) {
960
+ return s.replace(/\$([$\w.]+)/g, (_, key) => {
961
+ var _runner$config;
962
+ const isArrayKey = /^\d+$/.test(key);
963
+ if (!isObjectItem && !isArrayKey) {
964
+ return `$${key}`;
965
+ }
966
+ const arrayElement = isArrayKey ? objectAttr(items, key) : undefined;
967
+ const value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement;
968
+ return objDisplay(value, { truncate: runner === null || runner === void 0 || (_runner$config = runner.config) === null || _runner$config === void 0 || (_runner$config = _runner$config.chaiConfig) === null || _runner$config === void 0 ? void 0 : _runner$config.truncateThreshold });
969
+ });
970
+ }
971
+ let output = "";
972
+ let i = 0;
973
+ handleRegexMatch(
974
+ template,
975
+ formatRegExp,
976
+ // format "%"
977
+ (match) => {
978
+ if (i < count) {
979
+ output += format(match[0], items[i++]);
980
+ } else {
981
+ output += match[0];
982
+ }
983
+ },
984
+ // format "$"
985
+ (nonMatch) => {
986
+ output += formatAttribute(nonMatch);
987
+ }
988
+ );
989
+ return output;
990
+ }
991
+ // based on https://github.com/unocss/unocss/blob/2e74b31625bbe3b9c8351570749aa2d3f799d919/packages/autocomplete/src/parse.ts#L11
992
+ function handleRegexMatch(input, regex, onMatch, onNonMatch) {
993
+ let lastIndex = 0;
994
+ for (const m of input.matchAll(regex)) {
995
+ if (lastIndex < m.index) {
996
+ onNonMatch(input.slice(lastIndex, m.index));
997
+ }
998
+ onMatch(m);
999
+ lastIndex = m.index + m[0].length;
1000
+ }
1001
+ if (lastIndex < input.length) {
1002
+ onNonMatch(input.slice(lastIndex));
1003
+ }
1004
+ }
1005
+ function formatTemplateString(cases, args) {
1006
+ const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
1007
+ const res = [];
1008
+ for (let i = 0; i < Math.floor(args.length / header.length); i++) {
1009
+ const oneCase = {};
1010
+ for (let j = 0; j < header.length; j++) {
1011
+ oneCase[header[j]] = args[i * header.length + j];
1012
+ }
1013
+ res.push(oneCase);
1014
+ }
1015
+ return res;
1016
+ }
1017
+
1018
+ const now$2 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1019
+ async function collectTests(specs, runner) {
1020
+ const files = [];
1021
+ const config = runner.config;
1022
+ for (const spec of specs) {
1023
+ var _runner$onCollectStar;
1024
+ const filepath = typeof spec === "string" ? spec : spec.filepath;
1025
+ const testLocations = typeof spec === "string" ? undefined : spec.testLocations;
1026
+ const file = createFileTask(filepath, config.root, config.name, runner.pool);
1027
+ setFileContext(file, Object.create(null));
1028
+ file.shuffle = config.sequence.shuffle;
1029
+ (_runner$onCollectStar = runner.onCollectStart) === null || _runner$onCollectStar === void 0 ? void 0 : _runner$onCollectStar.call(runner, file);
1030
+ clearCollectorContext(filepath, runner);
1031
+ try {
1032
+ var _runner$getImportDura;
1033
+ const setupFiles = toArray(config.setupFiles);
1034
+ if (setupFiles.length) {
1035
+ const setupStart = now$2();
1036
+ await runSetupFiles(config, setupFiles, runner);
1037
+ const setupEnd = now$2();
1038
+ file.setupDuration = setupEnd - setupStart;
1039
+ } else {
1040
+ file.setupDuration = 0;
1041
+ }
1042
+ const collectStart = now$2();
1043
+ await runner.importFile(filepath, "collect");
1044
+ const durations = (_runner$getImportDura = runner.getImportDurations) === null || _runner$getImportDura === void 0 ? void 0 : _runner$getImportDura.call(runner);
1045
+ if (durations) {
1046
+ file.importDurations = durations;
1047
+ }
1048
+ const defaultTasks = await getDefaultSuite().collect(file);
1049
+ const fileHooks = createSuiteHooks();
1050
+ mergeHooks(fileHooks, getHooks(defaultTasks));
1051
+ for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) {
1052
+ if (c.type === "test" || c.type === "suite") {
1053
+ file.tasks.push(c);
1054
+ } else if (c.type === "collector") {
1055
+ const suite = await c.collect(file);
1056
+ if (suite.name || suite.tasks.length) {
1057
+ mergeHooks(fileHooks, getHooks(suite));
1058
+ file.tasks.push(suite);
1059
+ }
1060
+ } else {
1061
+ // check that types are exhausted
1062
+ c;
1063
+ }
1064
+ }
1065
+ setHooks(file, fileHooks);
1066
+ file.collectDuration = now$2() - collectStart;
1067
+ } catch (e) {
1068
+ var _runner$getImportDura2;
1069
+ const error = processError(e);
1070
+ file.result = {
1071
+ state: "fail",
1072
+ errors: [error]
1073
+ };
1074
+ const durations = (_runner$getImportDura2 = runner.getImportDurations) === null || _runner$getImportDura2 === void 0 ? void 0 : _runner$getImportDura2.call(runner);
1075
+ if (durations) {
1076
+ file.importDurations = durations;
1077
+ }
1078
+ }
1079
+ calculateSuiteHash(file);
1080
+ const hasOnlyTasks = someTasksAreOnly(file);
1081
+ interpretTaskModes(file, config.testNamePattern, testLocations, hasOnlyTasks, false, config.allowOnly);
1082
+ if (file.mode === "queued") {
1083
+ file.mode = "run";
1084
+ }
1085
+ files.push(file);
1086
+ }
1087
+ return files;
1088
+ }
1089
+ function mergeHooks(baseHooks, hooks) {
1090
+ for (const _key in hooks) {
1091
+ const key = _key;
1092
+ baseHooks[key].push(...hooks[key]);
1093
+ }
1094
+ return baseHooks;
1095
+ }
1096
+
1097
+ const now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
1098
+ const unixNow = Date.now;
1099
+ const { clearTimeout, setTimeout } = getSafeTimers();
1100
+ function updateSuiteHookState(task, name, state, runner) {
1101
+ if (!task.result) {
1102
+ task.result = { state: "run" };
1103
+ }
1104
+ if (!task.result.hooks) {
1105
+ task.result.hooks = {};
1106
+ }
1107
+ const suiteHooks = task.result.hooks;
1108
+ if (suiteHooks) {
1109
+ suiteHooks[name] = state;
1110
+ let event = state === "run" ? "before-hook-start" : "before-hook-end";
1111
+ if (name === "afterAll" || name === "afterEach") {
1112
+ event = state === "run" ? "after-hook-start" : "after-hook-end";
1113
+ }
1114
+ updateTask(event, task, runner);
1115
+ }
1116
+ }
1117
+ function getSuiteHooks(suite, name, sequence) {
1118
+ const hooks = getHooks(suite)[name];
1119
+ if (sequence === "stack" && (name === "afterAll" || name === "afterEach")) {
1120
+ return hooks.slice().reverse();
1121
+ }
1122
+ return hooks;
1123
+ }
1124
+ async function callTestHooks(runner, test, hooks, sequence) {
1125
+ if (sequence === "stack") {
1126
+ hooks = hooks.slice().reverse();
1127
+ }
1128
+ if (!hooks.length) {
1129
+ return;
1130
+ }
1131
+ const context = test.context;
1132
+ const onTestFailed = test.context.onTestFailed;
1133
+ const onTestFinished = test.context.onTestFinished;
1134
+ context.onTestFailed = () => {
1135
+ throw new Error(`Cannot call "onTestFailed" inside a test hook.`);
1136
+ };
1137
+ context.onTestFinished = () => {
1138
+ throw new Error(`Cannot call "onTestFinished" inside a test hook.`);
1139
+ };
1140
+ if (sequence === "parallel") {
1141
+ try {
1142
+ await Promise.all(hooks.map((fn) => fn(test.context)));
1143
+ } catch (e) {
1144
+ failTask(test.result, e, runner.config.diffOptions);
1145
+ }
1146
+ } else {
1147
+ for (const fn of hooks) {
1148
+ try {
1149
+ await fn(test.context);
1150
+ } catch (e) {
1151
+ failTask(test.result, e, runner.config.diffOptions);
1152
+ }
1153
+ }
1154
+ }
1155
+ context.onTestFailed = onTestFailed;
1156
+ context.onTestFinished = onTestFinished;
1157
+ }
1158
+ async function callSuiteHook(suite, currentTask, name, runner, args) {
1159
+ const sequence = runner.config.sequence.hooks;
1160
+ const callbacks = [];
1161
+ // stop at file level
1162
+ const parentSuite = "filepath" in suite ? null : suite.suite || suite.file;
1163
+ if (name === "beforeEach" && parentSuite) {
1164
+ callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args));
1165
+ }
1166
+ const hooks = getSuiteHooks(suite, name, sequence);
1167
+ if (hooks.length > 0) {
1168
+ updateSuiteHookState(currentTask, name, "run", runner);
1169
+ }
1170
+ async function runHook(hook) {
1171
+ return getBeforeHookCleanupCallback(hook, await hook(...args), name === "beforeEach" ? args[0] : undefined);
1172
+ }
1173
+ if (sequence === "parallel") {
1174
+ callbacks.push(...await Promise.all(hooks.map((hook) => runHook(hook))));
1175
+ } else {
1176
+ for (const hook of hooks) {
1177
+ callbacks.push(await runHook(hook));
1178
+ }
1179
+ }
1180
+ if (hooks.length > 0) {
1181
+ updateSuiteHookState(currentTask, name, "pass", runner);
1182
+ }
1183
+ if (name === "afterEach" && parentSuite) {
1184
+ callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args));
1185
+ }
1186
+ return callbacks;
1187
+ }
1188
+ const packs = new Map();
1189
+ const eventsPacks = [];
1190
+ const pendingTasksUpdates = [];
1191
+ function sendTasksUpdate(runner) {
1192
+ if (packs.size) {
1193
+ var _runner$onTaskUpdate;
1194
+ const taskPacks = Array.from(packs).map(([id, task]) => {
1195
+ return [
1196
+ id,
1197
+ task[0],
1198
+ task[1]
1199
+ ];
1200
+ });
1201
+ const p = (_runner$onTaskUpdate = runner.onTaskUpdate) === null || _runner$onTaskUpdate === void 0 ? void 0 : _runner$onTaskUpdate.call(runner, taskPacks, eventsPacks);
1202
+ if (p) {
1203
+ pendingTasksUpdates.push(p);
1204
+ // remove successful promise to not grow array indefnitely,
1205
+ // but keep rejections so finishSendTasksUpdate can handle them
1206
+ p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {});
1207
+ }
1208
+ eventsPacks.length = 0;
1209
+ packs.clear();
1210
+ }
1211
+ }
1212
+ async function finishSendTasksUpdate(runner) {
1213
+ sendTasksUpdate(runner);
1214
+ await Promise.all(pendingTasksUpdates);
1215
+ }
1216
+ function throttle(fn, ms) {
1217
+ let last = 0;
1218
+ let pendingCall;
1219
+ return function call(...args) {
1220
+ const now = unixNow();
1221
+ if (now - last > ms) {
1222
+ last = now;
1223
+ clearTimeout(pendingCall);
1224
+ pendingCall = undefined;
1225
+ return fn.apply(this, args);
1226
+ }
1227
+ // Make sure fn is still called even if there are no further calls
1228
+ pendingCall ?? (pendingCall = setTimeout(() => call.bind(this)(...args), ms));
1229
+ };
1230
+ }
1231
+ // throttle based on summary reporter's DURATION_UPDATE_INTERVAL_MS
1232
+ const sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100);
1233
+ function updateTask(event, task, runner) {
1234
+ eventsPacks.push([
1235
+ task.id,
1236
+ event,
1237
+ undefined
1238
+ ]);
1239
+ packs.set(task.id, [task.result, task.meta]);
1240
+ sendTasksUpdateThrottled(runner);
1241
+ }
1242
+ async function callCleanupHooks(runner, cleanups) {
1243
+ const sequence = runner.config.sequence.hooks;
1244
+ if (sequence === "stack") {
1245
+ cleanups = cleanups.slice().reverse();
1246
+ }
1247
+ if (sequence === "parallel") {
1248
+ await Promise.all(cleanups.map(async (fn) => {
1249
+ if (typeof fn !== "function") {
1250
+ return;
1251
+ }
1252
+ await fn();
1253
+ }));
1254
+ } else {
1255
+ for (const fn of cleanups) {
1256
+ if (typeof fn !== "function") {
1257
+ continue;
1258
+ }
1259
+ await fn();
1260
+ }
1261
+ }
1262
+ }
1263
+ async function runTest(test, runner) {
1264
+ var _runner$onBeforeRunTa, _test$result, _runner$onAfterRunTas;
1265
+ await ((_runner$onBeforeRunTa = runner.onBeforeRunTask) === null || _runner$onBeforeRunTa === void 0 ? void 0 : _runner$onBeforeRunTa.call(runner, test));
1266
+ if (test.mode !== "run" && test.mode !== "queued") {
1267
+ updateTask("test-prepare", test, runner);
1268
+ updateTask("test-finished", test, runner);
1269
+ return;
1270
+ }
1271
+ if (((_test$result = test.result) === null || _test$result === void 0 ? void 0 : _test$result.state) === "fail") {
1272
+ // should not be possible to get here, I think this is just copy pasted from suite
1273
+ // TODO: maybe someone fails tests in `beforeAll` hooks?
1274
+ // https://github.com/vitest-dev/vitest/pull/7069
1275
+ updateTask("test-failed-early", test, runner);
1276
+ return;
1277
+ }
1278
+ const start = now$1();
1279
+ test.result = {
1280
+ state: "run",
1281
+ startTime: unixNow(),
1282
+ retryCount: 0
1283
+ };
1284
+ updateTask("test-prepare", test, runner);
1285
+ const cleanupRunningTest = addRunningTest(test);
1286
+ setCurrentTest(test);
1287
+ const suite = test.suite || test.file;
1288
+ const repeats = test.repeats ?? 0;
1289
+ for (let repeatCount = 0; repeatCount <= repeats; repeatCount++) {
1290
+ const retry = test.retry ?? 0;
1291
+ for (let retryCount = 0; retryCount <= retry; retryCount++) {
1292
+ var _runner$onAfterRetryT, _test$result2, _test$result3;
1293
+ let beforeEachCleanups = [];
1294
+ try {
1295
+ var _runner$onBeforeTryTa, _runner$onAfterTryTas;
1296
+ await ((_runner$onBeforeTryTa = runner.onBeforeTryTask) === null || _runner$onBeforeTryTa === void 0 ? void 0 : _runner$onBeforeTryTa.call(runner, test, {
1297
+ retry: retryCount,
1298
+ repeats: repeatCount
1299
+ }));
1300
+ test.result.repeatCount = repeatCount;
1301
+ beforeEachCleanups = await callSuiteHook(suite, test, "beforeEach", runner, [test.context, suite]);
1302
+ if (runner.runTask) {
1303
+ await runner.runTask(test);
1304
+ } else {
1305
+ const fn = getFn(test);
1306
+ if (!fn) {
1307
+ throw new Error("Test function is not found. Did you add it using `setFn`?");
1308
+ }
1309
+ await fn();
1310
+ }
1311
+ await ((_runner$onAfterTryTas = runner.onAfterTryTask) === null || _runner$onAfterTryTas === void 0 ? void 0 : _runner$onAfterTryTas.call(runner, test, {
1312
+ retry: retryCount,
1313
+ repeats: repeatCount
1314
+ }));
1315
+ if (test.result.state !== "fail") {
1316
+ if (!test.repeats) {
1317
+ test.result.state = "pass";
1318
+ } else if (test.repeats && retry === retryCount) {
1319
+ test.result.state = "pass";
1320
+ }
1321
+ }
1322
+ } catch (e) {
1323
+ failTask(test.result, e, runner.config.diffOptions);
1324
+ }
1325
+ try {
1326
+ var _runner$onTaskFinishe;
1327
+ await ((_runner$onTaskFinishe = runner.onTaskFinished) === null || _runner$onTaskFinishe === void 0 ? void 0 : _runner$onTaskFinishe.call(runner, test));
1328
+ } catch (e) {
1329
+ failTask(test.result, e, runner.config.diffOptions);
1330
+ }
1331
+ try {
1332
+ await callSuiteHook(suite, test, "afterEach", runner, [test.context, suite]);
1333
+ await callCleanupHooks(runner, beforeEachCleanups);
1334
+ await callFixtureCleanup(test.context);
1335
+ } catch (e) {
1336
+ failTask(test.result, e, runner.config.diffOptions);
1337
+ }
1338
+ await callTestHooks(runner, test, test.onFinished || [], "stack");
1339
+ if (test.result.state === "fail") {
1340
+ await callTestHooks(runner, test, test.onFailed || [], runner.config.sequence.hooks);
1341
+ }
1342
+ test.onFailed = undefined;
1343
+ test.onFinished = undefined;
1344
+ await ((_runner$onAfterRetryT = runner.onAfterRetryTask) === null || _runner$onAfterRetryT === void 0 ? void 0 : _runner$onAfterRetryT.call(runner, test, {
1345
+ retry: retryCount,
1346
+ repeats: repeatCount
1347
+ }));
1348
+ // skipped with new PendingError
1349
+ if (((_test$result2 = test.result) === null || _test$result2 === void 0 ? void 0 : _test$result2.pending) || ((_test$result3 = test.result) === null || _test$result3 === void 0 ? void 0 : _test$result3.state) === "skip") {
1350
+ var _test$result4;
1351
+ test.mode = "skip";
1352
+ test.result = {
1353
+ state: "skip",
1354
+ note: (_test$result4 = test.result) === null || _test$result4 === void 0 ? void 0 : _test$result4.note,
1355
+ pending: true,
1356
+ duration: now$1() - start
1357
+ };
1358
+ updateTask("test-finished", test, runner);
1359
+ setCurrentTest(undefined);
1360
+ cleanupRunningTest();
1361
+ return;
1362
+ }
1363
+ if (test.result.state === "pass") {
1364
+ break;
1365
+ }
1366
+ if (retryCount < retry) {
1367
+ // reset state when retry test
1368
+ test.result.state = "run";
1369
+ test.result.retryCount = (test.result.retryCount ?? 0) + 1;
1370
+ }
1371
+ // update retry info
1372
+ updateTask("test-retried", test, runner);
1373
+ }
1374
+ }
1375
+ // if test is marked to be failed, flip the result
1376
+ if (test.fails) {
1377
+ if (test.result.state === "pass") {
1378
+ const error = processError(new Error("Expect test to fail"));
1379
+ test.result.state = "fail";
1380
+ test.result.errors = [error];
1381
+ } else {
1382
+ test.result.state = "pass";
1383
+ test.result.errors = undefined;
1384
+ }
1385
+ }
1386
+ cleanupRunningTest();
1387
+ setCurrentTest(undefined);
1388
+ test.result.duration = now$1() - start;
1389
+ await ((_runner$onAfterRunTas = runner.onAfterRunTask) === null || _runner$onAfterRunTas === void 0 ? void 0 : _runner$onAfterRunTas.call(runner, test));
1390
+ updateTask("test-finished", test, runner);
1391
+ }
1392
+ function failTask(result, err, diffOptions) {
1393
+ if (err instanceof PendingError) {
1394
+ result.state = "skip";
1395
+ result.note = err.note;
1396
+ result.pending = true;
1397
+ return;
1398
+ }
1399
+ result.state = "fail";
1400
+ const errors = Array.isArray(err) ? err : [err];
1401
+ for (const e of errors) {
1402
+ const error = processError(e, diffOptions);
1403
+ result.errors ?? (result.errors = []);
1404
+ result.errors.push(error);
1405
+ }
1406
+ }
1407
+ function markTasksAsSkipped(suite, runner) {
1408
+ suite.tasks.forEach((t) => {
1409
+ t.mode = "skip";
1410
+ t.result = {
1411
+ ...t.result,
1412
+ state: "skip"
1413
+ };
1414
+ updateTask("test-finished", t, runner);
1415
+ if (t.type === "suite") {
1416
+ markTasksAsSkipped(t, runner);
1417
+ }
1418
+ });
1419
+ }
1420
+ async function runSuite(suite, runner) {
1421
+ var _runner$onBeforeRunSu, _suite$result;
1422
+ await ((_runner$onBeforeRunSu = runner.onBeforeRunSuite) === null || _runner$onBeforeRunSu === void 0 ? void 0 : _runner$onBeforeRunSu.call(runner, suite));
1423
+ if (((_suite$result = suite.result) === null || _suite$result === void 0 ? void 0 : _suite$result.state) === "fail") {
1424
+ markTasksAsSkipped(suite, runner);
1425
+ // failed during collection
1426
+ updateTask("suite-failed-early", suite, runner);
1427
+ return;
1428
+ }
1429
+ const start = now$1();
1430
+ const mode = suite.mode;
1431
+ suite.result = {
1432
+ state: mode === "skip" || mode === "todo" ? mode : "run",
1433
+ startTime: unixNow()
1434
+ };
1435
+ updateTask("suite-prepare", suite, runner);
1436
+ let beforeAllCleanups = [];
1437
+ if (suite.mode === "skip") {
1438
+ suite.result.state = "skip";
1439
+ updateTask("suite-finished", suite, runner);
1440
+ } else if (suite.mode === "todo") {
1441
+ suite.result.state = "todo";
1442
+ updateTask("suite-finished", suite, runner);
1443
+ } else {
1444
+ var _runner$onAfterRunSui;
1445
+ try {
1446
+ try {
1447
+ beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", runner, [suite]);
1448
+ } catch (e) {
1449
+ markTasksAsSkipped(suite, runner);
1450
+ throw e;
1451
+ }
1452
+ if (runner.runSuite) {
1453
+ await runner.runSuite(suite);
1454
+ } else {
1455
+ for (let tasksGroup of partitionSuiteChildren(suite)) {
1456
+ if (tasksGroup[0].concurrent === true) {
1457
+ await Promise.all(tasksGroup.map((c) => runSuiteChild(c, runner)));
1458
+ } else {
1459
+ const { sequence } = runner.config;
1460
+ if (suite.shuffle) {
1461
+ // run describe block independently from tests
1462
+ const suites = tasksGroup.filter((group) => group.type === "suite");
1463
+ const tests = tasksGroup.filter((group) => group.type === "test");
1464
+ const groups = shuffle([suites, tests], sequence.seed);
1465
+ tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed));
1466
+ }
1467
+ for (const c of tasksGroup) {
1468
+ await runSuiteChild(c, runner);
1469
+ }
1470
+ }
1471
+ }
1472
+ }
1473
+ } catch (e) {
1474
+ failTask(suite.result, e, runner.config.diffOptions);
1475
+ }
1476
+ try {
1477
+ await callSuiteHook(suite, suite, "afterAll", runner, [suite]);
1478
+ await callCleanupHooks(runner, beforeAllCleanups);
1479
+ if (suite.file === suite) {
1480
+ const context = getFileContext(suite);
1481
+ await callFixtureCleanup(context);
1482
+ }
1483
+ } catch (e) {
1484
+ failTask(suite.result, e, runner.config.diffOptions);
1485
+ }
1486
+ if (suite.mode === "run" || suite.mode === "queued") {
1487
+ if (!runner.config.passWithNoTests && !hasTests(suite)) {
1488
+ var _suite$result$errors;
1489
+ suite.result.state = "fail";
1490
+ if (!((_suite$result$errors = suite.result.errors) === null || _suite$result$errors === void 0 ? void 0 : _suite$result$errors.length)) {
1491
+ const error = processError(new Error(`No test found in suite ${suite.name}`));
1492
+ suite.result.errors = [error];
1493
+ }
1494
+ } else if (hasFailed(suite)) {
1495
+ suite.result.state = "fail";
1496
+ } else {
1497
+ suite.result.state = "pass";
1498
+ }
1499
+ }
1500
+ suite.result.duration = now$1() - start;
1501
+ await ((_runner$onAfterRunSui = runner.onAfterRunSuite) === null || _runner$onAfterRunSui === void 0 ? void 0 : _runner$onAfterRunSui.call(runner, suite));
1502
+ updateTask("suite-finished", suite, runner);
1503
+ }
1504
+ }
1505
+ let limitMaxConcurrency;
1506
+ async function runSuiteChild(c, runner) {
1507
+ if (c.type === "test") {
1508
+ return limitMaxConcurrency(() => runTest(c, runner));
1509
+ } else if (c.type === "suite") {
1510
+ return runSuite(c, runner);
1511
+ }
1512
+ }
1513
+ async function runFiles(files, runner) {
1514
+ limitMaxConcurrency ?? (limitMaxConcurrency = limitConcurrency(runner.config.maxConcurrency));
1515
+ for (const file of files) {
1516
+ if (!file.tasks.length && !runner.config.passWithNoTests) {
1517
+ var _file$result;
1518
+ if (!((_file$result = file.result) === null || _file$result === void 0 || (_file$result = _file$result.errors) === null || _file$result === void 0 ? void 0 : _file$result.length)) {
1519
+ const error = processError(new Error(`No test suite found in file ${file.filepath}`));
1520
+ file.result = {
1521
+ state: "fail",
1522
+ errors: [error]
1523
+ };
1524
+ }
1525
+ }
1526
+ await runSuite(file, runner);
1527
+ }
1528
+ }
1529
+ const workerRunners = new WeakSet();
1530
+ async function startTests(specs, runner) {
1531
+ var _runner$cancel;
1532
+ const cancel = (_runner$cancel = runner.cancel) === null || _runner$cancel === void 0 ? void 0 : _runner$cancel.bind(runner);
1533
+ // Ideally, we need to have an event listener for this, but only have a runner here.
1534
+ // Adding another onCancel felt wrong (maybe it needs to be refactored)
1535
+ runner.cancel = (reason) => {
1536
+ // We intentionally create only one error since there is only one test run that can be cancelled
1537
+ const error = new TestRunAbortError("The test run was aborted by the user.", reason);
1538
+ getRunningTests().forEach((test) => abortContextSignal(test.context, error));
1539
+ return cancel === null || cancel === void 0 ? void 0 : cancel(reason);
1540
+ };
1541
+ if (!workerRunners.has(runner)) {
1542
+ var _runner$onCleanupWork;
1543
+ (_runner$onCleanupWork = runner.onCleanupWorkerContext) === null || _runner$onCleanupWork === void 0 ? void 0 : _runner$onCleanupWork.call(runner, async () => {
1544
+ var _runner$getWorkerCont;
1545
+ const context = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner);
1546
+ if (context) {
1547
+ await callFixtureCleanup(context);
1548
+ }
1549
+ });
1550
+ workerRunners.add(runner);
1551
+ }
1552
+ try {
1553
+ var _runner$onBeforeColle, _runner$onCollected, _runner$onBeforeRunFi, _runner$onAfterRunFil;
1554
+ const paths = specs.map((f) => typeof f === "string" ? f : f.filepath);
1555
+ await ((_runner$onBeforeColle = runner.onBeforeCollect) === null || _runner$onBeforeColle === void 0 ? void 0 : _runner$onBeforeColle.call(runner, paths));
1556
+ const files = await collectTests(specs, runner);
1557
+ await ((_runner$onCollected = runner.onCollected) === null || _runner$onCollected === void 0 ? void 0 : _runner$onCollected.call(runner, files));
1558
+ await ((_runner$onBeforeRunFi = runner.onBeforeRunFiles) === null || _runner$onBeforeRunFi === void 0 ? void 0 : _runner$onBeforeRunFi.call(runner, files));
1559
+ await runFiles(files, runner);
1560
+ await ((_runner$onAfterRunFil = runner.onAfterRunFiles) === null || _runner$onAfterRunFil === void 0 ? void 0 : _runner$onAfterRunFil.call(runner, files));
1561
+ await finishSendTasksUpdate(runner);
1562
+ return files;
1563
+ } finally {
1564
+ runner.cancel = cancel;
1565
+ }
1566
+ }
1567
+ async function publicCollect(specs, runner) {
1568
+ var _runner$onBeforeColle2, _runner$onCollected2;
1569
+ const paths = specs.map((f) => typeof f === "string" ? f : f.filepath);
1570
+ await ((_runner$onBeforeColle2 = runner.onBeforeCollect) === null || _runner$onBeforeColle2 === void 0 ? void 0 : _runner$onBeforeColle2.call(runner, paths));
1571
+ const files = await collectTests(specs, runner);
1572
+ await ((_runner$onCollected2 = runner.onCollected) === null || _runner$onCollected2 === void 0 ? void 0 : _runner$onCollected2.call(runner, files));
1573
+ return files;
1574
+ }
1575
+
1576
+ const now = Date.now;
1577
+ const collectorContext = {
1578
+ tasks: [],
1579
+ currentSuite: null
1580
+ };
1581
+ function collectTask(task) {
1582
+ var _collectorContext$cur;
1583
+ (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.tasks.push(task);
1584
+ }
1585
+ async function runWithSuite(suite, fn) {
1586
+ const prev = collectorContext.currentSuite;
1587
+ collectorContext.currentSuite = suite;
1588
+ await fn();
1589
+ collectorContext.currentSuite = prev;
1590
+ }
1591
+ function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) {
1592
+ if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) {
1593
+ return fn;
1594
+ }
1595
+ const { setTimeout, clearTimeout } = getSafeTimers();
1596
+ // this function name is used to filter error in test/cli/test/fails.test.ts
1597
+ return (function runWithTimeout(...args) {
1598
+ const startTime = now();
1599
+ const runner = getRunner();
1600
+ runner._currentTaskStartTime = startTime;
1601
+ runner._currentTaskTimeout = timeout;
1602
+ return new Promise((resolve_, reject_) => {
1603
+ var _timer$unref;
1604
+ const timer = setTimeout(() => {
1605
+ clearTimeout(timer);
1606
+ rejectTimeoutError();
1607
+ }, timeout);
1608
+ // `unref` might not exist in browser
1609
+ (_timer$unref = timer.unref) === null || _timer$unref === void 0 ? void 0 : _timer$unref.call(timer);
1610
+ function rejectTimeoutError() {
1611
+ const error = makeTimeoutError(isHook, timeout, stackTraceError);
1612
+ onTimeout === null || onTimeout === void 0 ? void 0 : onTimeout(args, error);
1613
+ reject_(error);
1614
+ }
1615
+ function resolve(result) {
1616
+ runner._currentTaskStartTime = undefined;
1617
+ runner._currentTaskTimeout = undefined;
1618
+ clearTimeout(timer);
1619
+ // if test/hook took too long in microtask, setTimeout won't be triggered,
1620
+ // but we still need to fail the test, see
1621
+ // https://github.com/vitest-dev/vitest/issues/2920
1622
+ if (now() - startTime >= timeout) {
1623
+ rejectTimeoutError();
1624
+ return;
1625
+ }
1626
+ resolve_(result);
1627
+ }
1628
+ function reject(error) {
1629
+ runner._currentTaskStartTime = undefined;
1630
+ runner._currentTaskTimeout = undefined;
1631
+ clearTimeout(timer);
1632
+ reject_(error);
1633
+ }
1634
+ // sync test/hook will be caught by try/catch
1635
+ try {
1636
+ const result = fn(...args);
1637
+ // the result is a thenable, we don't wrap this in Promise.resolve
1638
+ // to avoid creating new promises
1639
+ if (typeof result === "object" && result != null && typeof result.then === "function") {
1640
+ result.then(resolve, reject);
1641
+ } else {
1642
+ resolve(result);
1643
+ }
1644
+ }
1645
+ // user sync test/hook throws an error
1646
+ catch (error) {
1647
+ reject(error);
1648
+ }
1649
+ });
1650
+ });
1651
+ }
1652
+ const abortControllers = new WeakMap();
1653
+ function abortIfTimeout([context], error) {
1654
+ if (context) {
1655
+ abortContextSignal(context, error);
1656
+ }
1657
+ }
1658
+ function abortContextSignal(context, error) {
1659
+ const abortController = abortControllers.get(context);
1660
+ abortController === null || abortController === void 0 ? void 0 : abortController.abort(error);
1661
+ }
1662
+ function createTestContext(test, runner) {
1663
+ var _runner$extendTaskCon;
1664
+ const context = function() {
1665
+ throw new Error("done() callback is deprecated, use promise instead");
1666
+ };
1667
+ let abortController = abortControllers.get(context);
1668
+ if (!abortController) {
1669
+ abortController = new AbortController();
1670
+ abortControllers.set(context, abortController);
1671
+ }
1672
+ context.signal = abortController.signal;
1673
+ context.task = test;
1674
+ context.skip = (condition, note) => {
1675
+ if (condition === false) {
1676
+ // do nothing
1677
+ return undefined;
1678
+ }
1679
+ test.result ?? (test.result = { state: "skip" });
1680
+ test.result.pending = true;
1681
+ throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note);
1682
+ };
1683
+ async function annotate(message, location, type, attachment) {
1684
+ const annotation = {
1685
+ message,
1686
+ type: type || "notice"
1687
+ };
1688
+ if (attachment) {
1689
+ if (attachment.body == null && !attachment.path) {
1690
+ throw new TypeError(`Test attachment requires "body" or "path" to be set. Both are missing.`);
1691
+ }
1692
+ if (attachment.body && attachment.path) {
1693
+ throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`);
1694
+ }
1695
+ annotation.attachment = attachment;
1696
+ // convert to a string so it's easier to serialise
1697
+ if (attachment.body instanceof Uint8Array) {
1698
+ attachment.body = encodeUint8Array(attachment.body);
1699
+ }
1700
+ }
1701
+ if (location) {
1702
+ annotation.location = location;
1703
+ }
1704
+ if (!runner.onTestAnnotate) {
1705
+ throw new Error(`Test runner doesn't support test annotations.`);
1706
+ }
1707
+ await finishSendTasksUpdate(runner);
1708
+ const resolvedAnnotation = await runner.onTestAnnotate(test, annotation);
1709
+ test.annotations.push(resolvedAnnotation);
1710
+ return resolvedAnnotation;
1711
+ }
1712
+ context.annotate = ((message, type, attachment) => {
1713
+ if (test.result && test.result.state !== "run") {
1714
+ throw new Error(`Cannot annotate tests outside of the test run. The test "${test.name}" finished running with the "${test.result.state}" state already.`);
1715
+ }
1716
+ const stack = findTestFileStackTrace(test.file.filepath, new Error("STACK_TRACE").stack);
1717
+ let location;
1718
+ if (stack) {
1719
+ location = {
1720
+ file: stack.file,
1721
+ line: stack.line,
1722
+ column: stack.column
1723
+ };
1724
+ }
1725
+ if (typeof type === "object") {
1726
+ return recordAsyncAnnotation(test, annotate(message, location, undefined, type));
1727
+ } else {
1728
+ return recordAsyncAnnotation(test, annotate(message, location, type, attachment));
1729
+ }
1730
+ });
1731
+ context.onTestFailed = (handler, timeout) => {
1732
+ test.onFailed || (test.onFailed = []);
1733
+ test.onFailed.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
1734
+ };
1735
+ context.onTestFinished = (handler, timeout) => {
1736
+ test.onFinished || (test.onFinished = []);
1737
+ test.onFinished.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
1738
+ };
1739
+ return ((_runner$extendTaskCon = runner.extendTaskContext) === null || _runner$extendTaskCon === void 0 ? void 0 : _runner$extendTaskCon.call(runner, context)) || context;
1740
+ }
1741
+ function makeTimeoutError(isHook, timeout, stackTraceError) {
1742
+ const message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.\nIf this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
1743
+ const error = new Error(message);
1744
+ if (stackTraceError === null || stackTraceError === void 0 ? void 0 : stackTraceError.stack) {
1745
+ error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message);
1746
+ }
1747
+ return error;
1748
+ }
1749
+ const fileContexts = new WeakMap();
1750
+ function getFileContext(file) {
1751
+ const context = fileContexts.get(file);
1752
+ if (!context) {
1753
+ throw new Error(`Cannot find file context for ${file.name}`);
1754
+ }
1755
+ return context;
1756
+ }
1757
+ function setFileContext(file, context) {
1758
+ fileContexts.set(file, context);
1759
+ }
1760
+ const table = [];
1761
+ for (let i = 65; i < 91; i++) {
1762
+ table.push(String.fromCharCode(i));
1763
+ }
1764
+ for (let i = 97; i < 123; i++) {
1765
+ table.push(String.fromCharCode(i));
1766
+ }
1767
+ for (let i = 0; i < 10; i++) {
1768
+ table.push(i.toString(10));
1769
+ }
1770
+ function encodeUint8Array(bytes) {
1771
+ let base64 = "";
1772
+ const len = bytes.byteLength;
1773
+ for (let i = 0; i < len; i += 3) {
1774
+ if (len === i + 1) {
1775
+ const a = (bytes[i] & 252) >> 2;
1776
+ const b = (bytes[i] & 3) << 4;
1777
+ base64 += table[a];
1778
+ base64 += table[b];
1779
+ base64 += "==";
1780
+ } else if (len === i + 2) {
1781
+ const a = (bytes[i] & 252) >> 2;
1782
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
1783
+ const c = (bytes[i + 1] & 15) << 2;
1784
+ base64 += table[a];
1785
+ base64 += table[b];
1786
+ base64 += table[c];
1787
+ base64 += "=";
1788
+ } else {
1789
+ const a = (bytes[i] & 252) >> 2;
1790
+ const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
1791
+ const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6;
1792
+ const d = bytes[i + 2] & 63;
1793
+ base64 += table[a];
1794
+ base64 += table[b];
1795
+ base64 += table[c];
1796
+ base64 += table[d];
1797
+ }
1798
+ }
1799
+ return base64;
1800
+ }
1801
+ function recordAsyncAnnotation(test, promise) {
1802
+ // if promise is explicitly awaited, remove it from the list
1803
+ promise = promise.finally(() => {
1804
+ if (!test.promises) {
1805
+ return;
1806
+ }
1807
+ const index = test.promises.indexOf(promise);
1808
+ if (index !== -1) {
1809
+ test.promises.splice(index, 1);
1810
+ }
1811
+ });
1812
+ // record promise
1813
+ if (!test.promises) {
1814
+ test.promises = [];
1815
+ }
1816
+ test.promises.push(promise);
1817
+ return promise;
1818
+ }
1819
+
1820
+ function getDefaultHookTimeout() {
1821
+ return getRunner().config.hookTimeout;
1822
+ }
1823
+ const CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT");
1824
+ const CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE");
1825
+ function getBeforeHookCleanupCallback(hook, result, context) {
1826
+ if (typeof result === "function") {
1827
+ const timeout = CLEANUP_TIMEOUT_KEY in hook && typeof hook[CLEANUP_TIMEOUT_KEY] === "number" ? hook[CLEANUP_TIMEOUT_KEY] : getDefaultHookTimeout();
1828
+ const stackTraceError = CLEANUP_STACK_TRACE_KEY in hook && hook[CLEANUP_STACK_TRACE_KEY] instanceof Error ? hook[CLEANUP_STACK_TRACE_KEY] : undefined;
1829
+ return withTimeout(result, timeout, true, stackTraceError, (_, error) => {
1830
+ if (context) {
1831
+ abortContextSignal(context, error);
1832
+ }
1833
+ });
1834
+ }
1835
+ }
1836
+ /**
1837
+ * Registers a callback function to be executed once before all tests within the current suite.
1838
+ * This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment.
1839
+ *
1840
+ * **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
1841
+ *
1842
+ * @param {Function} fn - The callback function to be executed before all tests.
1843
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1844
+ * @returns {void}
1845
+ * @example
1846
+ * ```ts
1847
+ * // Example of using beforeAll to set up a database connection
1848
+ * beforeAll(async () => {
1849
+ * await database.connect();
1850
+ * });
1851
+ * ```
1852
+ */
1853
+ function beforeAll(fn, timeout = getDefaultHookTimeout()) {
1854
+ assertTypes(fn, "\"beforeAll\" callback", ["function"]);
1855
+ const stackTraceError = new Error("STACK_TRACE_ERROR");
1856
+ return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(fn, timeout, true, stackTraceError), {
1857
+ [CLEANUP_TIMEOUT_KEY]: timeout,
1858
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
1859
+ }));
1860
+ }
1861
+ /**
1862
+ * Registers a callback function to be executed once after all tests within the current suite have completed.
1863
+ * This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files.
1864
+ *
1865
+ * **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1866
+ *
1867
+ * @param {Function} fn - The callback function to be executed after all tests.
1868
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1869
+ * @returns {void}
1870
+ * @example
1871
+ * ```ts
1872
+ * // Example of using afterAll to close a database connection
1873
+ * afterAll(async () => {
1874
+ * await database.disconnect();
1875
+ * });
1876
+ * ```
1877
+ */
1878
+ function afterAll(fn, timeout) {
1879
+ assertTypes(fn, "\"afterAll\" callback", ["function"]);
1880
+ return getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR")));
1881
+ }
1882
+ /**
1883
+ * Registers a callback function to be executed before each test within the current suite.
1884
+ * This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables.
1885
+ *
1886
+ * **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
1887
+ *
1888
+ * @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.
1889
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1890
+ * @returns {void}
1891
+ * @example
1892
+ * ```ts
1893
+ * // Example of using beforeEach to reset a database state
1894
+ * beforeEach(async () => {
1895
+ * await database.reset();
1896
+ * });
1897
+ * ```
1898
+ */
1899
+ function beforeEach(fn, timeout = getDefaultHookTimeout()) {
1900
+ assertTypes(fn, "\"beforeEach\" callback", ["function"]);
1901
+ const stackTraceError = new Error("STACK_TRACE_ERROR");
1902
+ const runner = getRunner();
1903
+ return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), {
1904
+ [CLEANUP_TIMEOUT_KEY]: timeout,
1905
+ [CLEANUP_STACK_TRACE_KEY]: stackTraceError
1906
+ }));
1907
+ }
1908
+ /**
1909
+ * Registers a callback function to be executed after each test within the current suite has completed.
1910
+ * This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions.
1911
+ *
1912
+ * **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1913
+ *
1914
+ * @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.
1915
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1916
+ * @returns {void}
1917
+ * @example
1918
+ * ```ts
1919
+ * // Example of using afterEach to delete temporary files created during a test
1920
+ * afterEach(async () => {
1921
+ * await fileSystem.deleteTempFiles();
1922
+ * });
1923
+ * ```
1924
+ */
1925
+ function afterEach(fn, timeout) {
1926
+ assertTypes(fn, "\"afterEach\" callback", ["function"]);
1927
+ const runner = getRunner();
1928
+ return getCurrentSuite().on("afterEach", withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1929
+ }
1930
+ /**
1931
+ * Registers a callback function to be executed when a test fails within the current suite.
1932
+ * This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics.
1933
+ *
1934
+ * **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1935
+ *
1936
+ * @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors).
1937
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1938
+ * @throws {Error} Throws an error if the function is not called within a test.
1939
+ * @returns {void}
1940
+ * @example
1941
+ * ```ts
1942
+ * // Example of using onTestFailed to log failure details
1943
+ * onTestFailed(({ errors }) => {
1944
+ * console.log(`Test failed: ${test.name}`, errors);
1945
+ * });
1946
+ * ```
1947
+ */
1948
+ const onTestFailed = createTestHook("onTestFailed", (test, handler, timeout) => {
1949
+ test.onFailed || (test.onFailed = []);
1950
+ test.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1951
+ });
1952
+ /**
1953
+ * Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail).
1954
+ * This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources.
1955
+ *
1956
+ * This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`.
1957
+ *
1958
+ * **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
1959
+ *
1960
+ * **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call.
1961
+ *
1962
+ * @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status.
1963
+ * @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.
1964
+ * @throws {Error} Throws an error if the function is not called within a test.
1965
+ * @returns {void}
1966
+ * @example
1967
+ * ```ts
1968
+ * // Example of using onTestFinished for cleanup
1969
+ * const db = await connectToDatabase();
1970
+ * onTestFinished(async () => {
1971
+ * await db.disconnect();
1972
+ * });
1973
+ * ```
1974
+ */
1975
+ const onTestFinished = createTestHook("onTestFinished", (test, handler, timeout) => {
1976
+ test.onFinished || (test.onFinished = []);
1977
+ test.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout));
1978
+ });
1979
+ function createTestHook(name, handler) {
1980
+ return (fn, timeout) => {
1981
+ assertTypes(fn, `"${name}" callback`, ["function"]);
1982
+ const current = getCurrentTest();
1983
+ if (!current) {
1984
+ throw new Error(`Hook ${name}() can only be called inside a test`);
1985
+ }
1986
+ return handler(current, fn, timeout);
1987
+ };
1988
+ }
1989
+
1990
+ export { afterAll, afterEach, beforeAll, beforeEach, publicCollect as collectTests, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, onTestFinished, setFn, setHooks, startTests, suite, test, updateTask };