vitest 0.24.4 → 0.25.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 (49) hide show
  1. package/LICENSE.md +286 -57
  2. package/dist/browser.d.ts +3 -3
  3. package/dist/browser.js +17 -9
  4. package/dist/{chunk-api-setup.5a197c69.js → chunk-api-setup.a13c5f9d.js} +38 -19
  5. package/dist/{chunk-install-pkg.22707ee4.js → chunk-install-pkg.55bfe508.js} +4 -5
  6. package/dist/{chunk-integrations-coverage.cca09977.js → chunk-integrations-coverage.befed097.js} +57 -1
  7. package/dist/chunk-integrations-globals.391b3839.js +25 -0
  8. package/dist/{chunk-node-git.82174cfe.js → chunk-node-git.af5c9d73.js} +5 -6
  9. package/dist/{chunk-runtime-chain.a5cd236b.js → chunk-runtime-chain.3b531731.js} +27 -23
  10. package/dist/chunk-runtime-error.3cc15c6f.js +142 -0
  11. package/dist/{chunk-runtime-mocker.f994e23a.js → chunk-runtime-mocker.a5d87666.js} +4 -4
  12. package/dist/chunk-runtime-rpc.4a2d45ab.js +30 -0
  13. package/dist/chunk-runtime-setup.f644ac4c.js +1350 -0
  14. package/dist/{chunk-runtime-hooks.66004497.js → chunk-runtime-test-state.31ce8643.js} +106 -6
  15. package/dist/{chunk-mock-date.9fe2b438.js → chunk-typecheck-constants.410fa7b2.js} +23 -4
  16. package/dist/{chunk-utils-env.b1281522.js → chunk-utils-env.7fe285cc.js} +2 -0
  17. package/dist/chunk-utils-source-map.1a66263d.js +90 -0
  18. package/dist/{chunk-utils-source-map.d9d36eb0.js → chunk-utils-timers.d1fcc6bb.js} +309 -3722
  19. package/dist/{chunk-vite-node-client.9fbd5d5b.js → chunk-vite-node-client.13ea0a59.js} +25 -5
  20. package/dist/{chunk-vite-node-externalize.e66d46f6.js → chunk-vite-node-externalize.01d0d22c.js} +824 -97
  21. package/dist/chunk-vite-node-utils.b89230f3.js +1400 -0
  22. package/dist/cli-wrapper.js +5 -6
  23. package/dist/cli.js +27 -13
  24. package/dist/config.cjs +6 -1
  25. package/dist/config.d.ts +6 -1
  26. package/dist/config.js +6 -1
  27. package/dist/entry.js +11 -9
  28. package/dist/environments.d.ts +1 -1
  29. package/dist/index-b68b3c09.d.ts +256 -0
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +13 -7
  32. package/dist/loader.js +4 -3
  33. package/dist/node.d.ts +2 -2
  34. package/dist/node.js +18 -11
  35. package/dist/suite.js +6 -6
  36. package/dist/{global-58e8e951.d.ts → types-b3ff5eea.d.ts} +215 -18
  37. package/dist/{vendor-index.cc8d244b.js → vendor-index.16d769d7.js} +1 -2
  38. package/dist/{vendor-index.12d51d29.js → vendor-index.22806ffb.js} +279 -7
  39. package/dist/{vendor-index.9c919048.js → vendor-index.808a85a6.js} +0 -0
  40. package/dist/worker.js +11 -8
  41. package/globals.d.ts +2 -0
  42. package/package.json +13 -9
  43. package/dist/chunk-integrations-globals.88fd2e64.js +0 -25
  44. package/dist/chunk-runtime-error.9c28c08f.js +0 -807
  45. package/dist/chunk-runtime-rpc.e583f5e7.js +0 -16
  46. package/dist/chunk-utils-timers.ab764c0c.js +0 -27
  47. package/dist/chunk-vite-node-utils.5096a80d.js +0 -6952
  48. package/dist/index-220c1d70.d.ts +0 -117
  49. package/dist/vendor-index.1a291e86.js +0 -275
@@ -0,0 +1,1350 @@
1
+ import { performance } from 'perf_hooks';
2
+ import { s as someTasksAreOnly, i as interpretTaskModes, t as takeCoverageInsideWorker, p as pLimit } from './chunk-integrations-coverage.befed097.js';
3
+ import { r as resetRunOnceCounter, i as index, v as vi, s as setCurrentTest } from './chunk-runtime-test-state.31ce8643.js';
4
+ import { g as getWorkerState, R as RealDate, t as toArray, k as relativePath, h as isRunningInBenchmark, p as partitionSuiteChildren, l as shuffle, o as hasTests, q as hasFailed, u as createDefer, d as assertTypes, e as getFullName } from './chunk-typecheck-constants.410fa7b2.js';
5
+ import { f as clearCollectorContext, h as defaultSuite, j as setHooks, k as getHooks, l as collectorContext, m as getFn, n as setState, G as GLOBAL_EXPECT, o as getState } from './chunk-runtime-chain.3b531731.js';
6
+ import { r as rpc } from './chunk-runtime-rpc.4a2d45ab.js';
7
+ import { p as processError } from './chunk-runtime-error.3cc15c6f.js';
8
+ import require$$0 from 'source-map';
9
+ import path from 'path';
10
+ import { e as environments } from './chunk-env-node.700b7e95.js';
11
+ import { i as isNode, a as isBrowser } from './chunk-utils-env.7fe285cc.js';
12
+ import { b as safeClearTimeout, s as safeSetTimeout } from './chunk-utils-timers.d1fcc6bb.js';
13
+
14
+ var sourceMapSupport = {exports: {}};
15
+
16
+ /* eslint-disable node/no-deprecated-api */
17
+
18
+ var toString = Object.prototype.toString;
19
+
20
+ var isModern = (
21
+ typeof Buffer !== 'undefined' &&
22
+ typeof Buffer.alloc === 'function' &&
23
+ typeof Buffer.allocUnsafe === 'function' &&
24
+ typeof Buffer.from === 'function'
25
+ );
26
+
27
+ function isArrayBuffer (input) {
28
+ return toString.call(input).slice(8, -1) === 'ArrayBuffer'
29
+ }
30
+
31
+ function fromArrayBuffer (obj, byteOffset, length) {
32
+ byteOffset >>>= 0;
33
+
34
+ var maxLength = obj.byteLength - byteOffset;
35
+
36
+ if (maxLength < 0) {
37
+ throw new RangeError("'offset' is out of bounds")
38
+ }
39
+
40
+ if (length === undefined) {
41
+ length = maxLength;
42
+ } else {
43
+ length >>>= 0;
44
+
45
+ if (length > maxLength) {
46
+ throw new RangeError("'length' is out of bounds")
47
+ }
48
+ }
49
+
50
+ return isModern
51
+ ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
52
+ : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
53
+ }
54
+
55
+ function fromString (string, encoding) {
56
+ if (typeof encoding !== 'string' || encoding === '') {
57
+ encoding = 'utf8';
58
+ }
59
+
60
+ if (!Buffer.isEncoding(encoding)) {
61
+ throw new TypeError('"encoding" must be a valid string encoding')
62
+ }
63
+
64
+ return isModern
65
+ ? Buffer.from(string, encoding)
66
+ : new Buffer(string, encoding)
67
+ }
68
+
69
+ function bufferFrom (value, encodingOrOffset, length) {
70
+ if (typeof value === 'number') {
71
+ throw new TypeError('"value" argument must not be a number')
72
+ }
73
+
74
+ if (isArrayBuffer(value)) {
75
+ return fromArrayBuffer(value, encodingOrOffset, length)
76
+ }
77
+
78
+ if (typeof value === 'string') {
79
+ return fromString(value, encodingOrOffset)
80
+ }
81
+
82
+ return isModern
83
+ ? Buffer.from(value)
84
+ : new Buffer(value)
85
+ }
86
+
87
+ var bufferFrom_1 = bufferFrom;
88
+
89
+ (function (module, exports) {
90
+ var SourceMapConsumer = require$$0.SourceMapConsumer;
91
+ var path$1 = path;
92
+
93
+ var fs;
94
+ try {
95
+ fs = require('fs');
96
+ if (!fs.existsSync || !fs.readFileSync) {
97
+ // fs doesn't have all methods we need
98
+ fs = null;
99
+ }
100
+ } catch (err) {
101
+ /* nop */
102
+ }
103
+
104
+ var bufferFrom = bufferFrom_1;
105
+
106
+ /**
107
+ * Requires a module which is protected against bundler minification.
108
+ *
109
+ * @param {NodeModule} mod
110
+ * @param {string} request
111
+ */
112
+ function dynamicRequire(mod, request) {
113
+ return mod.require(request);
114
+ }
115
+
116
+ // Only install once if called multiple times
117
+ var errorFormatterInstalled = false;
118
+ var uncaughtShimInstalled = false;
119
+
120
+ // If true, the caches are reset before a stack trace formatting operation
121
+ var emptyCacheBetweenOperations = false;
122
+
123
+ // Supports {browser, node, auto}
124
+ var environment = "auto";
125
+
126
+ // Maps a file path to a string containing the file contents
127
+ var fileContentsCache = {};
128
+
129
+ // Maps a file path to a source map for that file
130
+ var sourceMapCache = {};
131
+
132
+ // Regex for detecting source maps
133
+ var reSourceMap = /^data:application\/json[^,]+base64,/;
134
+
135
+ // Priority list of retrieve handlers
136
+ var retrieveFileHandlers = [];
137
+ var retrieveMapHandlers = [];
138
+
139
+ function isInBrowser() {
140
+ if (environment === "browser")
141
+ return true;
142
+ if (environment === "node")
143
+ return false;
144
+ return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
145
+ }
146
+
147
+ function hasGlobalProcessEventEmitter() {
148
+ return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
149
+ }
150
+
151
+ function globalProcessVersion() {
152
+ if ((typeof process === 'object') && (process !== null)) {
153
+ return process.version;
154
+ } else {
155
+ return '';
156
+ }
157
+ }
158
+
159
+ function globalProcessStderr() {
160
+ if ((typeof process === 'object') && (process !== null)) {
161
+ return process.stderr;
162
+ }
163
+ }
164
+
165
+ function globalProcessExit(code) {
166
+ if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) {
167
+ return process.exit(code);
168
+ }
169
+ }
170
+
171
+ function handlerExec(list) {
172
+ return function(arg) {
173
+ for (var i = 0; i < list.length; i++) {
174
+ var ret = list[i](arg);
175
+ if (ret) {
176
+ return ret;
177
+ }
178
+ }
179
+ return null;
180
+ };
181
+ }
182
+
183
+ var retrieveFile = handlerExec(retrieveFileHandlers);
184
+
185
+ retrieveFileHandlers.push(function(path) {
186
+ // Trim the path to make sure there is no extra whitespace.
187
+ path = path.trim();
188
+ if (/^file:/.test(path)) {
189
+ // existsSync/readFileSync can't handle file protocol, but once stripped, it works
190
+ path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
191
+ return drive ?
192
+ '' : // file:///C:/dir/file -> C:/dir/file
193
+ '/'; // file:///root-dir/file -> /root-dir/file
194
+ });
195
+ }
196
+ if (path in fileContentsCache) {
197
+ return fileContentsCache[path];
198
+ }
199
+
200
+ var contents = '';
201
+ try {
202
+ if (!fs) {
203
+ // Use SJAX if we are in the browser
204
+ var xhr = new XMLHttpRequest();
205
+ xhr.open('GET', path, /** async */ false);
206
+ xhr.send(null);
207
+ if (xhr.readyState === 4 && xhr.status === 200) {
208
+ contents = xhr.responseText;
209
+ }
210
+ } else if (fs.existsSync(path)) {
211
+ // Otherwise, use the filesystem
212
+ contents = fs.readFileSync(path, 'utf8');
213
+ }
214
+ } catch (er) {
215
+ /* ignore any errors */
216
+ }
217
+
218
+ return fileContentsCache[path] = contents;
219
+ });
220
+
221
+ // Support URLs relative to a directory, but be careful about a protocol prefix
222
+ // in case we are in the browser (i.e. directories may start with "http://" or "file:///")
223
+ function supportRelativeURL(file, url) {
224
+ if (!file) return url;
225
+ var dir = path$1.dirname(file);
226
+ var match = /^\w+:\/\/[^\/]*/.exec(dir);
227
+ var protocol = match ? match[0] : '';
228
+ var startPath = dir.slice(protocol.length);
229
+ if (protocol && /^\/\w\:/.test(startPath)) {
230
+ // handle file:///C:/ paths
231
+ protocol += '/';
232
+ return protocol + path$1.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/');
233
+ }
234
+ return protocol + path$1.resolve(dir.slice(protocol.length), url);
235
+ }
236
+
237
+ function retrieveSourceMapURL(source) {
238
+ var fileData;
239
+
240
+ if (isInBrowser()) {
241
+ try {
242
+ var xhr = new XMLHttpRequest();
243
+ xhr.open('GET', source, false);
244
+ xhr.send(null);
245
+ fileData = xhr.readyState === 4 ? xhr.responseText : null;
246
+
247
+ // Support providing a sourceMappingURL via the SourceMap header
248
+ var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
249
+ xhr.getResponseHeader("X-SourceMap");
250
+ if (sourceMapHeader) {
251
+ return sourceMapHeader;
252
+ }
253
+ } catch (e) {
254
+ }
255
+ }
256
+
257
+ // Get the URL of the source map
258
+ fileData = retrieveFile(source);
259
+ var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
260
+ // Keep executing the search to find the *last* sourceMappingURL to avoid
261
+ // picking up sourceMappingURLs from comments, strings, etc.
262
+ var lastMatch, match;
263
+ while (match = re.exec(fileData)) lastMatch = match;
264
+ if (!lastMatch) return null;
265
+ return lastMatch[1];
266
+ }
267
+ // Can be overridden by the retrieveSourceMap option to install. Takes a
268
+ // generated source filename; returns a {map, optional url} object, or null if
269
+ // there is no source map. The map field may be either a string or the parsed
270
+ // JSON object (ie, it must be a valid argument to the SourceMapConsumer
271
+ // constructor).
272
+ var retrieveSourceMap = handlerExec(retrieveMapHandlers);
273
+ retrieveMapHandlers.push(function(source) {
274
+ var sourceMappingURL = retrieveSourceMapURL(source);
275
+ if (!sourceMappingURL) return null;
276
+
277
+ // Read the contents of the source map
278
+ var sourceMapData;
279
+ if (reSourceMap.test(sourceMappingURL)) {
280
+ // Support source map URL as a data url
281
+ var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
282
+ sourceMapData = bufferFrom(rawData, "base64").toString();
283
+ sourceMappingURL = source;
284
+ } else {
285
+ // Support source map URLs relative to the source URL
286
+ sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
287
+ sourceMapData = retrieveFile(sourceMappingURL);
288
+ }
289
+
290
+ if (!sourceMapData) {
291
+ return null;
292
+ }
293
+
294
+ return {
295
+ url: sourceMappingURL,
296
+ map: sourceMapData
297
+ };
298
+ });
299
+
300
+ function mapSourcePosition(position) {
301
+ var sourceMap = sourceMapCache[position.source];
302
+ if (!sourceMap) {
303
+ // Call the (overrideable) retrieveSourceMap function to get the source map.
304
+ var urlAndMap = retrieveSourceMap(position.source);
305
+ if (urlAndMap) {
306
+ sourceMap = sourceMapCache[position.source] = {
307
+ url: urlAndMap.url,
308
+ map: new SourceMapConsumer(urlAndMap.map)
309
+ };
310
+
311
+ // Load all sources stored inline with the source map into the file cache
312
+ // to pretend like they are already loaded. They may not exist on disk.
313
+ if (sourceMap.map.sourcesContent) {
314
+ sourceMap.map.sources.forEach(function(source, i) {
315
+ var contents = sourceMap.map.sourcesContent[i];
316
+ if (contents) {
317
+ var url = supportRelativeURL(sourceMap.url, source);
318
+ fileContentsCache[url] = contents;
319
+ }
320
+ });
321
+ }
322
+ } else {
323
+ sourceMap = sourceMapCache[position.source] = {
324
+ url: null,
325
+ map: null
326
+ };
327
+ }
328
+ }
329
+
330
+ // Resolve the source URL relative to the URL of the source map
331
+ if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') {
332
+ var originalPosition = sourceMap.map.originalPositionFor(position);
333
+
334
+ // Only return the original position if a matching line was found. If no
335
+ // matching line is found then we return position instead, which will cause
336
+ // the stack trace to print the path and line for the compiled file. It is
337
+ // better to give a precise location in the compiled file than a vague
338
+ // location in the original file.
339
+ if (originalPosition.source !== null) {
340
+ originalPosition.source = supportRelativeURL(
341
+ sourceMap.url, originalPosition.source);
342
+ return originalPosition;
343
+ }
344
+ }
345
+
346
+ return position;
347
+ }
348
+
349
+ // Parses code generated by FormatEvalOrigin(), a function inside V8:
350
+ // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
351
+ function mapEvalOrigin(origin) {
352
+ // Most eval() calls are in this format
353
+ var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
354
+ if (match) {
355
+ var position = mapSourcePosition({
356
+ source: match[2],
357
+ line: +match[3],
358
+ column: match[4] - 1
359
+ });
360
+ return 'eval at ' + match[1] + ' (' + position.source + ':' +
361
+ position.line + ':' + (position.column + 1) + ')';
362
+ }
363
+
364
+ // Parse nested eval() calls using recursion
365
+ match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
366
+ if (match) {
367
+ return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
368
+ }
369
+
370
+ // Make sure we still return useful information if we didn't find anything
371
+ return origin;
372
+ }
373
+
374
+ // This is copied almost verbatim from the V8 source code at
375
+ // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
376
+ // implementation of wrapCallSite() used to just forward to the actual source
377
+ // code of CallSite.prototype.toString but unfortunately a new release of V8
378
+ // did something to the prototype chain and broke the shim. The only fix I
379
+ // could find was copy/paste.
380
+ function CallSiteToString() {
381
+ var fileName;
382
+ var fileLocation = "";
383
+ if (this.isNative()) {
384
+ fileLocation = "native";
385
+ } else {
386
+ fileName = this.getScriptNameOrSourceURL();
387
+ if (!fileName && this.isEval()) {
388
+ fileLocation = this.getEvalOrigin();
389
+ fileLocation += ", "; // Expecting source position to follow.
390
+ }
391
+
392
+ if (fileName) {
393
+ fileLocation += fileName;
394
+ } else {
395
+ // Source code does not originate from a file and is not native, but we
396
+ // can still get the source position inside the source string, e.g. in
397
+ // an eval string.
398
+ fileLocation += "<anonymous>";
399
+ }
400
+ var lineNumber = this.getLineNumber();
401
+ if (lineNumber != null) {
402
+ fileLocation += ":" + lineNumber;
403
+ var columnNumber = this.getColumnNumber();
404
+ if (columnNumber) {
405
+ fileLocation += ":" + columnNumber;
406
+ }
407
+ }
408
+ }
409
+
410
+ var line = "";
411
+ var functionName = this.getFunctionName();
412
+ var addSuffix = true;
413
+ var isConstructor = this.isConstructor();
414
+ var isMethodCall = !(this.isToplevel() || isConstructor);
415
+ if (isMethodCall) {
416
+ var typeName = this.getTypeName();
417
+ // Fixes shim to be backward compatable with Node v0 to v4
418
+ if (typeName === "[object Object]") {
419
+ typeName = "null";
420
+ }
421
+ var methodName = this.getMethodName();
422
+ if (functionName) {
423
+ if (typeName && functionName.indexOf(typeName) != 0) {
424
+ line += typeName + ".";
425
+ }
426
+ line += functionName;
427
+ if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
428
+ line += " [as " + methodName + "]";
429
+ }
430
+ } else {
431
+ line += typeName + "." + (methodName || "<anonymous>");
432
+ }
433
+ } else if (isConstructor) {
434
+ line += "new " + (functionName || "<anonymous>");
435
+ } else if (functionName) {
436
+ line += functionName;
437
+ } else {
438
+ line += fileLocation;
439
+ addSuffix = false;
440
+ }
441
+ if (addSuffix) {
442
+ line += " (" + fileLocation + ")";
443
+ }
444
+ return line;
445
+ }
446
+
447
+ function cloneCallSite(frame) {
448
+ var object = {};
449
+ Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
450
+ object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
451
+ });
452
+ object.toString = CallSiteToString;
453
+ return object;
454
+ }
455
+
456
+ function wrapCallSite(frame, state) {
457
+ // provides interface backward compatibility
458
+ if (state === undefined) {
459
+ state = { nextPosition: null, curPosition: null };
460
+ }
461
+ if(frame.isNative()) {
462
+ state.curPosition = null;
463
+ return frame;
464
+ }
465
+
466
+ // Most call sites will return the source file from getFileName(), but code
467
+ // passed to eval() ending in "//# sourceURL=..." will return the source file
468
+ // from getScriptNameOrSourceURL() instead
469
+ var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
470
+ if (source) {
471
+ var line = frame.getLineNumber();
472
+ var column = frame.getColumnNumber() - 1;
473
+
474
+ // Fix position in Node where some (internal) code is prepended.
475
+ // See https://github.com/evanw/node-source-map-support/issues/36
476
+ // Header removed in node at ^10.16 || >=11.11.0
477
+ // v11 is not an LTS candidate, we can just test the one version with it.
478
+ // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
479
+ var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
480
+ var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62;
481
+ if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
482
+ column -= headerLength;
483
+ }
484
+
485
+ var position = mapSourcePosition({
486
+ source: source,
487
+ line: line,
488
+ column: column
489
+ });
490
+ state.curPosition = position;
491
+ frame = cloneCallSite(frame);
492
+ var originalFunctionName = frame.getFunctionName;
493
+ frame.getFunctionName = function() {
494
+ if (state.nextPosition == null) {
495
+ return originalFunctionName();
496
+ }
497
+ return state.nextPosition.name || originalFunctionName();
498
+ };
499
+ frame.getFileName = function() { return position.source; };
500
+ frame.getLineNumber = function() { return position.line; };
501
+ frame.getColumnNumber = function() { return position.column + 1; };
502
+ frame.getScriptNameOrSourceURL = function() { return position.source; };
503
+ return frame;
504
+ }
505
+
506
+ // Code called using eval() needs special handling
507
+ var origin = frame.isEval() && frame.getEvalOrigin();
508
+ if (origin) {
509
+ origin = mapEvalOrigin(origin);
510
+ frame = cloneCallSite(frame);
511
+ frame.getEvalOrigin = function() { return origin; };
512
+ return frame;
513
+ }
514
+
515
+ // If we get here then we were unable to change the source position
516
+ return frame;
517
+ }
518
+
519
+ // This function is part of the V8 stack trace API, for more info see:
520
+ // https://v8.dev/docs/stack-trace-api
521
+ function prepareStackTrace(error, stack) {
522
+ if (emptyCacheBetweenOperations) {
523
+ fileContentsCache = {};
524
+ sourceMapCache = {};
525
+ }
526
+
527
+ var name = error.name || 'Error';
528
+ var message = error.message || '';
529
+ var errorString = name + ": " + message;
530
+
531
+ var state = { nextPosition: null, curPosition: null };
532
+ var processedStack = [];
533
+ for (var i = stack.length - 1; i >= 0; i--) {
534
+ processedStack.push('\n at ' + wrapCallSite(stack[i], state));
535
+ state.nextPosition = state.curPosition;
536
+ }
537
+ state.curPosition = state.nextPosition = null;
538
+ return errorString + processedStack.reverse().join('');
539
+ }
540
+
541
+ // Generate position and snippet of original source with pointer
542
+ function getErrorSource(error) {
543
+ var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
544
+ if (match) {
545
+ var source = match[1];
546
+ var line = +match[2];
547
+ var column = +match[3];
548
+
549
+ // Support the inline sourceContents inside the source map
550
+ var contents = fileContentsCache[source];
551
+
552
+ // Support files on disk
553
+ if (!contents && fs && fs.existsSync(source)) {
554
+ try {
555
+ contents = fs.readFileSync(source, 'utf8');
556
+ } catch (er) {
557
+ contents = '';
558
+ }
559
+ }
560
+
561
+ // Format the line from the original source code like node does
562
+ if (contents) {
563
+ var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
564
+ if (code) {
565
+ return source + ':' + line + '\n' + code + '\n' +
566
+ new Array(column).join(' ') + '^';
567
+ }
568
+ }
569
+ }
570
+ return null;
571
+ }
572
+
573
+ function printErrorAndExit (error) {
574
+ var source = getErrorSource(error);
575
+
576
+ // Ensure error is printed synchronously and not truncated
577
+ var stderr = globalProcessStderr();
578
+ if (stderr && stderr._handle && stderr._handle.setBlocking) {
579
+ stderr._handle.setBlocking(true);
580
+ }
581
+
582
+ if (source) {
583
+ console.error();
584
+ console.error(source);
585
+ }
586
+
587
+ console.error(error.stack);
588
+ globalProcessExit(1);
589
+ }
590
+
591
+ function shimEmitUncaughtException () {
592
+ var origEmit = process.emit;
593
+
594
+ process.emit = function (type) {
595
+ if (type === 'uncaughtException') {
596
+ var hasStack = (arguments[1] && arguments[1].stack);
597
+ var hasListeners = (this.listeners(type).length > 0);
598
+
599
+ if (hasStack && !hasListeners) {
600
+ return printErrorAndExit(arguments[1]);
601
+ }
602
+ }
603
+
604
+ return origEmit.apply(this, arguments);
605
+ };
606
+ }
607
+
608
+ var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
609
+ var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
610
+
611
+ exports.wrapCallSite = wrapCallSite;
612
+ exports.getErrorSource = getErrorSource;
613
+ exports.mapSourcePosition = mapSourcePosition;
614
+ exports.retrieveSourceMap = retrieveSourceMap;
615
+
616
+ exports.install = function(options) {
617
+ options = options || {};
618
+
619
+ if (options.environment) {
620
+ environment = options.environment;
621
+ if (["node", "browser", "auto"].indexOf(environment) === -1) {
622
+ throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
623
+ }
624
+ }
625
+
626
+ // Allow sources to be found by methods other than reading the files
627
+ // directly from disk.
628
+ if (options.retrieveFile) {
629
+ if (options.overrideRetrieveFile) {
630
+ retrieveFileHandlers.length = 0;
631
+ }
632
+
633
+ retrieveFileHandlers.unshift(options.retrieveFile);
634
+ }
635
+
636
+ // Allow source maps to be found by methods other than reading the files
637
+ // directly from disk.
638
+ if (options.retrieveSourceMap) {
639
+ if (options.overrideRetrieveSourceMap) {
640
+ retrieveMapHandlers.length = 0;
641
+ }
642
+
643
+ retrieveMapHandlers.unshift(options.retrieveSourceMap);
644
+ }
645
+
646
+ // Support runtime transpilers that include inline source maps
647
+ if (options.hookRequire && !isInBrowser()) {
648
+ // Use dynamicRequire to avoid including in browser bundles
649
+ var Module = dynamicRequire(module, 'module');
650
+ var $compile = Module.prototype._compile;
651
+
652
+ if (!$compile.__sourceMapSupport) {
653
+ Module.prototype._compile = function(content, filename) {
654
+ fileContentsCache[filename] = content;
655
+ sourceMapCache[filename] = undefined;
656
+ return $compile.call(this, content, filename);
657
+ };
658
+
659
+ Module.prototype._compile.__sourceMapSupport = true;
660
+ }
661
+ }
662
+
663
+ // Configure options
664
+ if (!emptyCacheBetweenOperations) {
665
+ emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
666
+ options.emptyCacheBetweenOperations : false;
667
+ }
668
+
669
+ // Install the error reformatter
670
+ if (!errorFormatterInstalled) {
671
+ errorFormatterInstalled = true;
672
+ Error.prepareStackTrace = prepareStackTrace;
673
+ }
674
+
675
+ if (!uncaughtShimInstalled) {
676
+ var installHandler = 'handleUncaughtExceptions' in options ?
677
+ options.handleUncaughtExceptions : true;
678
+
679
+ // Do not override 'uncaughtException' with our own handler in Node.js
680
+ // Worker threads. Workers pass the error to the main thread as an event,
681
+ // rather than printing something to stderr and exiting.
682
+ try {
683
+ // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
684
+ var worker_threads = dynamicRequire(module, 'worker_threads');
685
+ if (worker_threads.isMainThread === false) {
686
+ installHandler = false;
687
+ }
688
+ } catch(e) {}
689
+
690
+ // Provide the option to not install the uncaught exception handler. This is
691
+ // to support other uncaught exception handlers (in test frameworks, for
692
+ // example). If this handler is not installed and there are no other uncaught
693
+ // exception handlers, uncaught exceptions will be caught by node's built-in
694
+ // exception handler and the process will still be terminated. However, the
695
+ // generated JavaScript code will be shown above the stack trace instead of
696
+ // the original source code.
697
+ if (installHandler && hasGlobalProcessEventEmitter()) {
698
+ uncaughtShimInstalled = true;
699
+ shimEmitUncaughtException();
700
+ }
701
+ }
702
+ };
703
+
704
+ exports.resetRetrieveHandlers = function() {
705
+ retrieveFileHandlers.length = 0;
706
+ retrieveMapHandlers.length = 0;
707
+
708
+ retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
709
+ retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
710
+
711
+ retrieveSourceMap = handlerExec(retrieveMapHandlers);
712
+ retrieveFile = handlerExec(retrieveFileHandlers);
713
+ };
714
+ } (sourceMapSupport, sourceMapSupport.exports));
715
+
716
+ function installSourcemapsSupport(options) {
717
+ sourceMapSupport.exports.install({
718
+ environment: "node",
719
+ handleUncaughtExceptions: false,
720
+ retrieveSourceMap(source) {
721
+ const map = options.getSourceMap(source);
722
+ if (map) {
723
+ return {
724
+ url: source,
725
+ map
726
+ };
727
+ }
728
+ return null;
729
+ }
730
+ });
731
+ }
732
+
733
+ let globalSetup = false;
734
+ async function setupGlobalEnv(config) {
735
+ resetRunOnceCounter();
736
+ Object.defineProperty(globalThis, "__vitest_index__", {
737
+ value: index,
738
+ enumerable: false
739
+ });
740
+ setupDefines(config.defines);
741
+ if (globalSetup)
742
+ return;
743
+ globalSetup = true;
744
+ if (isNode) {
745
+ const state = getWorkerState();
746
+ installSourcemapsSupport({
747
+ getSourceMap: (source) => state.moduleCache.getSourceMap(source)
748
+ });
749
+ await setupConsoleLogSpy();
750
+ }
751
+ if (config.globals)
752
+ (await import('./chunk-integrations-globals.391b3839.js')).registerApiGlobally();
753
+ }
754
+ function setupDefines(defines) {
755
+ for (const key in defines)
756
+ globalThis[key] = defines[key];
757
+ }
758
+ async function setupConsoleLogSpy() {
759
+ const stdoutBuffer = /* @__PURE__ */ new Map();
760
+ const stderrBuffer = /* @__PURE__ */ new Map();
761
+ const timers = /* @__PURE__ */ new Map();
762
+ const unknownTestId = "__vitest__unknown_test__";
763
+ const { Writable } = await import('stream');
764
+ const { Console } = await import('console');
765
+ function schedule(taskId) {
766
+ const timer = timers.get(taskId);
767
+ const { stdoutTime, stderrTime } = timer;
768
+ safeClearTimeout(timer.timer);
769
+ timer.timer = safeSetTimeout(() => {
770
+ if (stderrTime < stdoutTime) {
771
+ sendStderr(taskId);
772
+ sendStdout(taskId);
773
+ } else {
774
+ sendStdout(taskId);
775
+ sendStderr(taskId);
776
+ }
777
+ });
778
+ }
779
+ function sendStdout(taskId) {
780
+ const buffer = stdoutBuffer.get(taskId);
781
+ if (!buffer)
782
+ return;
783
+ const content = buffer.map((i) => String(i)).join("");
784
+ if (!content.trim())
785
+ return;
786
+ const timer = timers.get(taskId);
787
+ rpc().onUserConsoleLog({
788
+ type: "stdout",
789
+ content,
790
+ taskId,
791
+ time: timer.stdoutTime || RealDate.now(),
792
+ size: buffer.length
793
+ });
794
+ stdoutBuffer.set(taskId, []);
795
+ timer.stdoutTime = 0;
796
+ }
797
+ function sendStderr(taskId) {
798
+ const buffer = stderrBuffer.get(taskId);
799
+ if (!buffer)
800
+ return;
801
+ const content = buffer.map((i) => String(i)).join("");
802
+ if (!content.trim())
803
+ return;
804
+ const timer = timers.get(taskId);
805
+ rpc().onUserConsoleLog({
806
+ type: "stderr",
807
+ content,
808
+ taskId,
809
+ time: timer.stderrTime || RealDate.now(),
810
+ size: buffer.length
811
+ });
812
+ stderrBuffer.set(taskId, []);
813
+ timer.stderrTime = 0;
814
+ }
815
+ const stdout = new Writable({
816
+ write(data, encoding, callback) {
817
+ var _a, _b;
818
+ const id = ((_b = (_a = getWorkerState()) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
819
+ let timer = timers.get(id);
820
+ if (timer) {
821
+ timer.stdoutTime = timer.stdoutTime || RealDate.now();
822
+ } else {
823
+ timer = { stdoutTime: RealDate.now(), stderrTime: RealDate.now(), timer: 0 };
824
+ timers.set(id, timer);
825
+ }
826
+ let buffer = stdoutBuffer.get(id);
827
+ if (!buffer) {
828
+ buffer = [];
829
+ stdoutBuffer.set(id, buffer);
830
+ }
831
+ buffer.push(data);
832
+ schedule(id);
833
+ callback();
834
+ }
835
+ });
836
+ const stderr = new Writable({
837
+ write(data, encoding, callback) {
838
+ var _a, _b;
839
+ const id = ((_b = (_a = getWorkerState()) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
840
+ let timer = timers.get(id);
841
+ if (timer) {
842
+ timer.stderrTime = timer.stderrTime || RealDate.now();
843
+ } else {
844
+ timer = { stderrTime: RealDate.now(), stdoutTime: RealDate.now(), timer: 0 };
845
+ timers.set(id, timer);
846
+ }
847
+ let buffer = stderrBuffer.get(id);
848
+ if (!buffer) {
849
+ buffer = [];
850
+ stderrBuffer.set(id, buffer);
851
+ }
852
+ buffer.push(data);
853
+ schedule(id);
854
+ callback();
855
+ }
856
+ });
857
+ globalThis.console = new Console({
858
+ stdout,
859
+ stderr,
860
+ colorMode: true,
861
+ groupIndentation: 2
862
+ });
863
+ }
864
+ async function loadEnvironment(name) {
865
+ const pkg = await import(`vitest-environment-${name}`);
866
+ if (!pkg || !pkg.default || typeof pkg.default !== "object" || typeof pkg.default.setup !== "function") {
867
+ throw new Error(
868
+ `Environment "${name}" is not a valid environment. Package "vitest-environment-${name}" should have default export with "setup" method.`
869
+ );
870
+ }
871
+ return pkg.default;
872
+ }
873
+ async function withEnv(name, options, fn) {
874
+ const config = environments[name] || await loadEnvironment(name);
875
+ const env = await config.setup(globalThis, options);
876
+ try {
877
+ await fn();
878
+ } finally {
879
+ await env.teardown(globalThis);
880
+ }
881
+ }
882
+ async function runSetupFiles(config) {
883
+ const files = toArray(config.setupFiles);
884
+ await Promise.all(
885
+ files.map(async (fsPath) => {
886
+ getWorkerState().moduleCache.delete(fsPath);
887
+ await import(fsPath);
888
+ })
889
+ );
890
+ }
891
+
892
+ const now$1 = Date.now;
893
+ function hash(str) {
894
+ let hash2 = 0;
895
+ if (str.length === 0)
896
+ return `${hash2}`;
897
+ for (let i = 0; i < str.length; i++) {
898
+ const char = str.charCodeAt(i);
899
+ hash2 = (hash2 << 5) - hash2 + char;
900
+ hash2 = hash2 & hash2;
901
+ }
902
+ return `${hash2}`;
903
+ }
904
+ async function collectTests(paths, config) {
905
+ const files = [];
906
+ const browserHashMap = getWorkerState().browserHashMap;
907
+ async function importFromBrowser(filepath) {
908
+ const match = filepath.match(/^(\w:\/)/);
909
+ const hash2 = browserHashMap.get(filepath);
910
+ if (match)
911
+ return await import(`/@fs/${filepath.slice(match[1].length)}?v=${hash2}`);
912
+ else
913
+ return await import(`${filepath}?v=${hash2}`);
914
+ }
915
+ for (const filepath of paths) {
916
+ const path = relativePath(config.root, filepath);
917
+ const file = {
918
+ id: hash(path),
919
+ name: path,
920
+ type: "suite",
921
+ mode: "run",
922
+ filepath,
923
+ tasks: []
924
+ };
925
+ clearCollectorContext();
926
+ try {
927
+ const setupStart = now$1();
928
+ await runSetupFiles(config);
929
+ const collectStart = now$1();
930
+ file.setupDuration = collectStart - setupStart;
931
+ if (config.browser && isBrowser)
932
+ await importFromBrowser(filepath);
933
+ else
934
+ await import(filepath);
935
+ const defaultTasks = await defaultSuite.collect(file);
936
+ setHooks(file, getHooks(defaultTasks));
937
+ for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) {
938
+ if (c.type === "test") {
939
+ file.tasks.push(c);
940
+ } else if (c.type === "benchmark") {
941
+ file.tasks.push(c);
942
+ } else if (c.type === "suite") {
943
+ file.tasks.push(c);
944
+ } else if (c.type === "collector") {
945
+ const suite = await c.collect(file);
946
+ if (suite.name || suite.tasks.length)
947
+ file.tasks.push(suite);
948
+ }
949
+ }
950
+ file.collectDuration = now$1() - collectStart;
951
+ } catch (e) {
952
+ file.result = {
953
+ state: "fail",
954
+ error: processError(e)
955
+ };
956
+ if (config.browser)
957
+ console.error(e);
958
+ }
959
+ calculateHash(file);
960
+ const hasOnlyTasks = someTasksAreOnly(file);
961
+ interpretTaskModes(file, config.testNamePattern, hasOnlyTasks, false, config.allowOnly);
962
+ files.push(file);
963
+ }
964
+ return files;
965
+ }
966
+ function calculateHash(parent) {
967
+ parent.tasks.forEach((t, idx) => {
968
+ t.id = `${parent.id}_${idx}`;
969
+ if (t.type === "suite")
970
+ calculateHash(t);
971
+ });
972
+ }
973
+
974
+ async function importTinybench() {
975
+ if (!globalThis.EventTarget)
976
+ await import('./vendor-index.534e612c.js').then(function (n) { return n.i; });
977
+ return await import('tinybench');
978
+ }
979
+ const now = Date.now;
980
+ function updateSuiteHookState(suite, name, state) {
981
+ var _a;
982
+ if (!suite.result)
983
+ suite.result = { state: "run" };
984
+ if (!((_a = suite.result) == null ? void 0 : _a.hooks))
985
+ suite.result.hooks = {};
986
+ const suiteHooks = suite.result.hooks;
987
+ if (suiteHooks) {
988
+ suiteHooks[name] = state;
989
+ updateTask(suite);
990
+ }
991
+ }
992
+ async function callSuiteHook(suite, currentTask, name, args) {
993
+ const callbacks = [];
994
+ if (name === "beforeEach" && suite.suite) {
995
+ callbacks.push(
996
+ ...await callSuiteHook(suite.suite, currentTask, name, args)
997
+ );
998
+ }
999
+ updateSuiteHookState(currentTask, name, "run");
1000
+ callbacks.push(
1001
+ ...await Promise.all(getHooks(suite)[name].map((fn) => fn(...args)))
1002
+ );
1003
+ updateSuiteHookState(currentTask, name, "pass");
1004
+ if (name === "afterEach" && suite.suite) {
1005
+ callbacks.push(
1006
+ ...await callSuiteHook(suite.suite, currentTask, name, args)
1007
+ );
1008
+ }
1009
+ return callbacks;
1010
+ }
1011
+ const packs = /* @__PURE__ */ new Map();
1012
+ let updateTimer;
1013
+ let previousUpdate;
1014
+ function updateTask(task) {
1015
+ packs.set(task.id, task.result);
1016
+ safeClearTimeout(updateTimer);
1017
+ updateTimer = safeSetTimeout(() => {
1018
+ previousUpdate = sendTasksUpdate();
1019
+ }, 10);
1020
+ }
1021
+ async function sendTasksUpdate() {
1022
+ safeClearTimeout(updateTimer);
1023
+ await previousUpdate;
1024
+ if (packs.size) {
1025
+ const p = rpc().onTaskUpdate(Array.from(packs));
1026
+ packs.clear();
1027
+ return p;
1028
+ }
1029
+ }
1030
+ const callCleanupHooks = async (cleanups) => {
1031
+ await Promise.all(cleanups.map(async (fn) => {
1032
+ if (!fn)
1033
+ return;
1034
+ assertTypes(fn, "hook teardown", ["function"]);
1035
+ await fn();
1036
+ }));
1037
+ };
1038
+ async function runTest(test) {
1039
+ var _a, _b, _c;
1040
+ if (test.mode !== "run") {
1041
+ const { getSnapshotClient } = await import('./chunk-runtime-chain.3b531731.js').then(function (n) { return n.q; });
1042
+ getSnapshotClient().skipTestSnapshots(test);
1043
+ return;
1044
+ }
1045
+ if (((_a = test.result) == null ? void 0 : _a.state) === "fail") {
1046
+ updateTask(test);
1047
+ return;
1048
+ }
1049
+ const start = now();
1050
+ test.result = {
1051
+ state: "run",
1052
+ startTime: start
1053
+ };
1054
+ updateTask(test);
1055
+ clearModuleMocks();
1056
+ setCurrentTest(test);
1057
+ if (isNode) {
1058
+ const { getSnapshotClient } = await import('./chunk-runtime-chain.3b531731.js').then(function (n) { return n.q; });
1059
+ await getSnapshotClient().setTest(test);
1060
+ }
1061
+ const workerState = getWorkerState();
1062
+ workerState.current = test;
1063
+ const retry = test.retry || 1;
1064
+ for (let retryCount = 0; retryCount < retry; retryCount++) {
1065
+ let beforeEachCleanups = [];
1066
+ try {
1067
+ beforeEachCleanups = await callSuiteHook(test.suite, test, "beforeEach", [test.context, test.suite]);
1068
+ setState({
1069
+ assertionCalls: 0,
1070
+ isExpectingAssertions: false,
1071
+ isExpectingAssertionsError: null,
1072
+ expectedAssertionsNumber: null,
1073
+ expectedAssertionsNumberErrorGen: null,
1074
+ testPath: (_b = test.suite.file) == null ? void 0 : _b.filepath,
1075
+ currentTestName: getFullName(test)
1076
+ }, globalThis[GLOBAL_EXPECT]);
1077
+ test.result.retryCount = retryCount;
1078
+ await getFn(test)();
1079
+ const {
1080
+ assertionCalls,
1081
+ expectedAssertionsNumber,
1082
+ expectedAssertionsNumberErrorGen,
1083
+ isExpectingAssertions,
1084
+ isExpectingAssertionsError
1085
+ } = test.context._local ? test.context.expect.getState() : getState(globalThis[GLOBAL_EXPECT]);
1086
+ if (expectedAssertionsNumber !== null && assertionCalls !== expectedAssertionsNumber)
1087
+ throw expectedAssertionsNumberErrorGen();
1088
+ if (isExpectingAssertions === true && assertionCalls === 0)
1089
+ throw isExpectingAssertionsError;
1090
+ test.result.state = "pass";
1091
+ } catch (e) {
1092
+ test.result.state = "fail";
1093
+ test.result.error = processError(e);
1094
+ }
1095
+ try {
1096
+ await callSuiteHook(test.suite, test, "afterEach", [test.context, test.suite]);
1097
+ await callCleanupHooks(beforeEachCleanups);
1098
+ } catch (e) {
1099
+ test.result.state = "fail";
1100
+ test.result.error = processError(e);
1101
+ }
1102
+ if (test.result.state === "pass")
1103
+ break;
1104
+ updateTask(test);
1105
+ }
1106
+ if (test.result.state === "fail")
1107
+ await Promise.all(((_c = test.onFailed) == null ? void 0 : _c.map((fn) => fn(test.result))) || []);
1108
+ if (test.fails) {
1109
+ if (test.result.state === "pass") {
1110
+ test.result.state = "fail";
1111
+ test.result.error = processError(new Error("Expect test to fail"));
1112
+ } else {
1113
+ test.result.state = "pass";
1114
+ test.result.error = void 0;
1115
+ }
1116
+ }
1117
+ if (isBrowser && test.result.error)
1118
+ console.error(test.result.error.message, test.result.error.stackStr);
1119
+ setCurrentTest(void 0);
1120
+ if (isNode) {
1121
+ const { getSnapshotClient } = await import('./chunk-runtime-chain.3b531731.js').then(function (n) { return n.q; });
1122
+ getSnapshotClient().clearTest();
1123
+ }
1124
+ test.result.duration = now() - start;
1125
+ if (workerState.config.logHeapUsage && isNode)
1126
+ test.result.heap = process.memoryUsage().heapUsed;
1127
+ workerState.current = void 0;
1128
+ updateTask(test);
1129
+ }
1130
+ function markTasksAsSkipped(suite) {
1131
+ suite.tasks.forEach((t) => {
1132
+ t.mode = "skip";
1133
+ t.result = { ...t.result, state: "skip" };
1134
+ updateTask(t);
1135
+ if (t.type === "suite")
1136
+ markTasksAsSkipped(t);
1137
+ });
1138
+ }
1139
+ async function runSuite(suite) {
1140
+ var _a;
1141
+ if (((_a = suite.result) == null ? void 0 : _a.state) === "fail") {
1142
+ markTasksAsSkipped(suite);
1143
+ updateTask(suite);
1144
+ return;
1145
+ }
1146
+ const start = now();
1147
+ suite.result = {
1148
+ state: "run",
1149
+ startTime: start
1150
+ };
1151
+ updateTask(suite);
1152
+ const workerState = getWorkerState();
1153
+ if (suite.mode === "skip") {
1154
+ suite.result.state = "skip";
1155
+ } else if (suite.mode === "todo") {
1156
+ suite.result.state = "todo";
1157
+ } else {
1158
+ try {
1159
+ const beforeAllCleanups = await callSuiteHook(suite, suite, "beforeAll", [suite]);
1160
+ if (isRunningInBenchmark()) {
1161
+ await runBenchmarkSuite(suite);
1162
+ } else {
1163
+ for (let tasksGroup of partitionSuiteChildren(suite)) {
1164
+ if (tasksGroup[0].concurrent === true) {
1165
+ const mutex = pLimit(workerState.config.maxConcurrency);
1166
+ await Promise.all(tasksGroup.map((c) => mutex(() => runSuiteChild(c))));
1167
+ } else {
1168
+ const { sequence } = workerState.config;
1169
+ if (sequence.shuffle || suite.shuffle) {
1170
+ const suites = tasksGroup.filter((group) => group.type === "suite");
1171
+ const tests = tasksGroup.filter((group) => group.type === "test");
1172
+ const groups = shuffle([suites, tests], sequence.seed);
1173
+ tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed));
1174
+ }
1175
+ for (const c of tasksGroup)
1176
+ await runSuiteChild(c);
1177
+ }
1178
+ }
1179
+ }
1180
+ await callSuiteHook(suite, suite, "afterAll", [suite]);
1181
+ await callCleanupHooks(beforeAllCleanups);
1182
+ } catch (e) {
1183
+ suite.result.state = "fail";
1184
+ suite.result.error = processError(e);
1185
+ }
1186
+ }
1187
+ suite.result.duration = now() - start;
1188
+ if (workerState.config.logHeapUsage && isNode)
1189
+ suite.result.heap = process.memoryUsage().heapUsed;
1190
+ if (suite.mode === "run") {
1191
+ if (!hasTests(suite)) {
1192
+ suite.result.state = "fail";
1193
+ if (!suite.result.error)
1194
+ suite.result.error = new Error(`No test found in suite ${suite.name}`);
1195
+ } else if (hasFailed(suite)) {
1196
+ suite.result.state = "fail";
1197
+ } else {
1198
+ suite.result.state = "pass";
1199
+ }
1200
+ }
1201
+ updateTask(suite);
1202
+ }
1203
+ function createBenchmarkResult(name) {
1204
+ return {
1205
+ name,
1206
+ rank: 0,
1207
+ rme: 0,
1208
+ samples: []
1209
+ };
1210
+ }
1211
+ async function runBenchmarkSuite(suite) {
1212
+ const { Task, Bench } = await importTinybench();
1213
+ const start = performance.now();
1214
+ const benchmarkGroup = [];
1215
+ const benchmarkSuiteGroup = [];
1216
+ for (const task of suite.tasks) {
1217
+ if (task.mode !== "run")
1218
+ continue;
1219
+ if (task.type === "benchmark")
1220
+ benchmarkGroup.push(task);
1221
+ else if (task.type === "suite")
1222
+ benchmarkSuiteGroup.push(task);
1223
+ }
1224
+ if (benchmarkSuiteGroup.length)
1225
+ await Promise.all(benchmarkSuiteGroup.map((subSuite) => runBenchmarkSuite(subSuite)));
1226
+ if (benchmarkGroup.length) {
1227
+ const defer = createDefer();
1228
+ const benchmarkMap = {};
1229
+ suite.result = {
1230
+ state: "run",
1231
+ startTime: start,
1232
+ benchmark: createBenchmarkResult(suite.name)
1233
+ };
1234
+ updateTask(suite);
1235
+ benchmarkGroup.forEach((benchmark, idx) => {
1236
+ const benchmarkInstance = new Bench(benchmark.options);
1237
+ const benchmarkFn = getFn(benchmark);
1238
+ benchmark.result = {
1239
+ state: "run",
1240
+ startTime: start,
1241
+ benchmark: createBenchmarkResult(benchmark.name)
1242
+ };
1243
+ const id = idx.toString();
1244
+ benchmarkMap[id] = benchmark;
1245
+ const task = new Task(benchmarkInstance, id, benchmarkFn);
1246
+ benchmark.task = task;
1247
+ updateTask(benchmark);
1248
+ });
1249
+ benchmarkGroup.forEach((benchmark) => {
1250
+ benchmark.task.addEventListener("complete", (e) => {
1251
+ const task = e.task;
1252
+ const _benchmark = benchmarkMap[task.name || ""];
1253
+ if (_benchmark) {
1254
+ const taskRes = task.result;
1255
+ const result = _benchmark.result.benchmark;
1256
+ Object.assign(result, taskRes);
1257
+ updateTask(_benchmark);
1258
+ }
1259
+ });
1260
+ benchmark.task.addEventListener("error", (e) => {
1261
+ const task = e.task;
1262
+ const _benchmark = benchmarkMap[task.name || ""];
1263
+ defer.reject(_benchmark ? task.result.error : e);
1264
+ });
1265
+ });
1266
+ Promise.all(benchmarkGroup.map(async (benchmark) => {
1267
+ await benchmark.task.warmup();
1268
+ return await new Promise((resolve) => safeSetTimeout(async () => {
1269
+ resolve(await benchmark.task.run());
1270
+ }));
1271
+ })).then((tasks) => {
1272
+ suite.result.duration = performance.now() - start;
1273
+ suite.result.state = "pass";
1274
+ tasks.sort((a, b) => a.result.mean - b.result.mean).forEach((cycle, idx) => {
1275
+ const benchmark = benchmarkMap[cycle.name || ""];
1276
+ benchmark.result.state = "pass";
1277
+ if (benchmark) {
1278
+ const result = benchmark.result.benchmark;
1279
+ result.rank = Number(idx) + 1;
1280
+ updateTask(benchmark);
1281
+ }
1282
+ });
1283
+ updateTask(suite);
1284
+ defer.resolve(null);
1285
+ });
1286
+ await defer;
1287
+ }
1288
+ }
1289
+ async function runSuiteChild(c) {
1290
+ if (c.type === "test")
1291
+ return runTest(c);
1292
+ else if (c.type === "suite")
1293
+ return runSuite(c);
1294
+ }
1295
+ async function runSuites(suites) {
1296
+ for (const suite of suites)
1297
+ await runSuite(suite);
1298
+ }
1299
+ async function runFiles(files, config) {
1300
+ var _a;
1301
+ for (const file of files) {
1302
+ if (!file.tasks.length && !config.passWithNoTests) {
1303
+ if (!((_a = file.result) == null ? void 0 : _a.error)) {
1304
+ file.result = {
1305
+ state: "fail",
1306
+ error: new Error(`No test suite found in file ${file.filepath}`)
1307
+ };
1308
+ }
1309
+ }
1310
+ await runSuite(file);
1311
+ }
1312
+ }
1313
+ async function startTestsBrowser(paths, config) {
1314
+ if (isNode) {
1315
+ rpc().onPathsCollected(paths);
1316
+ } else {
1317
+ const files = await collectTests(paths, config);
1318
+ await rpc().onCollected(files);
1319
+ await runSuites(files);
1320
+ await sendTasksUpdate();
1321
+ }
1322
+ }
1323
+ async function startTestsNode(paths, config) {
1324
+ const files = await collectTests(paths, config);
1325
+ rpc().onCollected(files);
1326
+ const { getSnapshotClient } = await import('./chunk-runtime-chain.3b531731.js').then(function (n) { return n.q; });
1327
+ getSnapshotClient().clear();
1328
+ await runFiles(files, config);
1329
+ const coverage = await takeCoverageInsideWorker(config.coverage);
1330
+ rpc().onAfterSuiteRun({ coverage });
1331
+ await getSnapshotClient().saveCurrent();
1332
+ await sendTasksUpdate();
1333
+ }
1334
+ async function startTests(paths, config) {
1335
+ if (config.browser)
1336
+ return startTestsBrowser(paths, config);
1337
+ else
1338
+ return startTestsNode(paths, config);
1339
+ }
1340
+ function clearModuleMocks() {
1341
+ const { clearMocks, mockReset, restoreMocks } = getWorkerState().config;
1342
+ if (restoreMocks)
1343
+ vi.restoreAllMocks();
1344
+ else if (mockReset)
1345
+ vi.resetAllMocks();
1346
+ else if (clearMocks)
1347
+ vi.clearAllMocks();
1348
+ }
1349
+
1350
+ export { setupGlobalEnv as a, startTests as s, withEnv as w };