vitest 5.1.0-beta.1 → 5.1.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.
Files changed (68) hide show
  1. package/dist/browser.d.ts +8 -6
  2. package/dist/browser.js +10 -10
  3. package/dist/chunks/{base.PJyN9N0u.js → base.C2su7_N0.js} +16 -21
  4. package/dist/chunks/{browser.d.D7a15z82.d.ts → browser.d.B-QwH_F6.d.ts} +3 -3
  5. package/dist/chunks/{cac.Ccf5Je_F.js → cac.BK306qhQ.js} +29 -22
  6. package/dist/chunks/{cli-api.DE22LIzq.js → cli-api.D6E8EtSi.js} +990 -166
  7. package/dist/chunks/{config.d.BgktgHfG.d.ts → config.d.BpJq6tRA.d.ts} +43 -2
  8. package/dist/chunks/{console.DrMPSuFo.js → console.VJUxd1rM.js} +3 -3
  9. package/dist/chunks/{coverage.-bm5IxnW.js → coverage.9iqXE2gN.js} +1 -1
  10. package/dist/chunks/{coverage.cTDc4uSS.js → coverage.jGCktcGP.js} +1 -1
  11. package/dist/chunks/{creator.BQ3onxbh.js → creator.CoOCr85O.js} +17 -15
  12. package/dist/chunks/{display.BlTmubjj.js → display.Cj2h2zsY.js} +1 -1
  13. package/dist/chunks/{doctor.CPlMs7-y.js → doctor.SRjZIZuA.js} +2 -2
  14. package/dist/chunks/{environment.d.CbTLsZSj.d.ts → environment.d.rlpAM-ON.d.ts} +1 -1
  15. package/dist/chunks/{globals.TipXUFcZ.js → globals.Mxora3_v.js} +11 -10
  16. package/dist/chunks/{index.BFXLpwll.js → index.C7Nn66Gy.js} +79 -41
  17. package/dist/chunks/{index.DmDMHCg8.js → index.CAmut2NG.js} +25 -1
  18. package/dist/chunks/{index.BXttT2gP.js → index.DNcttN5a.js} +288 -437
  19. package/dist/chunks/{index.B03wg4V0.js → index.Da_szXbS.js} +5 -5
  20. package/dist/chunks/{index.D14IAvnE.js → index.ER9afepi.js} +269 -141
  21. package/dist/chunks/{index.D0heQG4v.js → index.Or9psEGe.js} +1 -1
  22. package/dist/chunks/{init-forks.BL1E3__4.js → init-forks.q4IoGYZe.js} +7 -1
  23. package/dist/chunks/{init-threads.CYXAGzKQ.js → init-threads.Bf1Frg9S.js} +1 -1
  24. package/dist/chunks/{init.DVorxUyL.js → init.dGO4K2C0.js} +17 -9
  25. package/dist/chunks/{inspector.CvyFGlXm.js → inspector.D6o1NPo1.js} +12 -1
  26. package/dist/chunks/{module-dependencies.CwNPkcV4.js → module-dependencies._2Eei3FO.js} +1 -1
  27. package/dist/chunks/{modules.BJuCwlRJ.js → moduleSourceMap.Dp1WduWi.js} +31 -1
  28. package/dist/chunks/{native.cdzHIdmv.js → native.D5q1ylZC.js} +3 -2
  29. package/dist/chunks/{nativeModuleMocker.3uBcOd84.js → nativeModuleMocker.ihb3q7Cg.js} +6 -4
  30. package/dist/chunks/{nativeModuleRunner.xi64Afb2.js → nativeModuleRunner.9xPIMzi7.js} +1 -1
  31. package/dist/chunks/{node.uQulW0ei.js → node.B9mkVmLH.js} +1 -1
  32. package/dist/chunks/{pathe.M-eThtNZ.Ba-7h1rE.js → pathe.M-eThtNZ.zq3TM4NT.js} +1 -1
  33. package/dist/chunks/{plugin.d.olEn8IL9.d.ts → plugin.d.Du7hHZwb.d.ts} +115 -41
  34. package/dist/chunks/{plugins.DPQHVT0p.js → plugins.BPruPOR8.js} +1 -1
  35. package/dist/chunks/rawSnapshot.DvoRLRNr.js +356 -0
  36. package/dist/chunks/{resolver.CtCcxIy1.js → resolver.BzpmeQeT.js} +1 -1
  37. package/dist/chunks/{rpc.BV0XpJ5q.js → rpc.CNYWPa97.js} +3 -19
  38. package/dist/chunks/{rpc.d.DGFP7vWr.d.ts → rpc.d.DHfuwqP0.d.ts} +2 -2
  39. package/dist/chunks/{run.BfrMbGVD.js → run.zBhXlcZQ.js} +118 -51
  40. package/dist/chunks/{setup-common.llxJkJaD.js → setup-common.wwc_NYRJ.js} +3 -3
  41. package/dist/chunks/{source-map.BjWcsIL9.js → source-map.DPHGMWvM.js} +14 -14
  42. package/dist/chunks/{source-map.d.C5A_Tr6V.d.ts → source-map.d.xB6_75fl.d.ts} +2 -1
  43. package/dist/chunks/{spy.DDMXghXv.js → spy.BO0hTE3G.js} +76 -53
  44. package/dist/chunks/{task-utils.d.BUh7ylUT.d.ts → task-utils.d.DgSjIb7r.d.ts} +1 -1
  45. package/dist/chunks/{utils.DSfl_w8V.js → utils.sAsh2ClK.js} +7 -8
  46. package/dist/chunks/{vm.Cwj01UFE.js → vm.agn4qnmT.js} +15 -13
  47. package/dist/chunks/{worker.d.gsA26mmR.d.ts → worker.d.BigfbIsH.d.ts} +3 -3
  48. package/dist/cli.js +2 -2
  49. package/dist/config.d.ts +8 -8
  50. package/dist/index.d.ts +17 -12
  51. package/dist/index.js +11 -10
  52. package/dist/module-evaluator.d.ts +3 -3
  53. package/dist/module-evaluator.js +1 -1
  54. package/dist/node.d.ts +12 -11
  55. package/dist/node.js +23 -19
  56. package/dist/runtime.d.ts +5 -4
  57. package/dist/runtime.js +7 -5
  58. package/dist/spy.js +1 -1
  59. package/dist/task-utils.js +7 -3
  60. package/dist/worker.d.ts +4 -4
  61. package/dist/worker.js +23 -21
  62. package/dist/workers/forks.js +24 -22
  63. package/dist/workers/runVmTests.js +20 -17
  64. package/dist/workers/threads.js +24 -22
  65. package/dist/workers/vmForks.js +16 -15
  66. package/dist/workers/vmThreads.js +16 -15
  67. package/dist/workers/watchdog.js +20 -0
  68. package/package.json +21 -21
@@ -1,49 +1,79 @@
1
1
  import * as fs from 'node:fs';
2
2
  import fs__default, { promises, existsSync, writeFileSync, mkdirSync, readFileSync, statSync, readdirSync } from 'node:fs';
3
- import { r as resolveCoverageProviderModule, g as getCoverageFilesDirectory, C as CoverageProviderMap } from './coverage.cTDc4uSS.js';
4
- import { o as parse, s as stringify, k as isFileServingAllowed, q as getSpecificationDocblock, t as resolveStaticMocks, u as getStaticMocks, f as createDebugger, v as hash, w as resolveCoverageReporters, x as createIndexLocationsMap, y as getOutputFile, z as groupBy, A as generateCodeFrame, C as printStack, R as RangeLocationFilterProvidedError, I as IncludeTaskLocationDisabledError, D as LocationFilterFileNotFoundError, E as GitCommandError, G as GitNotFoundError, H as VitestResolver, M as ModuleTransformService, l as resolveConfig$1, J as createClusterServer, S as ServerModuleRunner, K as attachProjectsFromEntries, N as TestProject, O as resolveAndAttachProjects, Q as RandomSequencer, b as FilesNotFoundError, U as createPool, W as astCollectTests, X as createFailedFileTask, Y as matchesProjectFilter, Z as nanoid, L as Logger, V as VitestPackageInstaller, P as PluginHarness, _ as stdout, p as prompt } from './index.D14IAvnE.js';
5
- import { rm, readFile, writeFile, rename, stat, unlink, mkdir, readdir, copyFile } from 'node:fs/promises';
3
+ import { r as resolveCoverageProviderModule, g as getCoverageFilesDirectory, C as CoverageProviderMap } from './coverage.jGCktcGP.js';
4
+ import { o as parse, s as stringify, k as isFileServingAllowed, q as getSpecificationDocblock, t as resolveStaticMocks, u as getStaticMocks, f as createDebugger, v as resolveCoverageReporters, w as createIndexLocationsMap, x as getOutputFile, y as groupBy, z as generateCodeFrame, A as printStack, R as RangeLocationFilterProvidedError, I as IncludeTaskLocationDisabledError, C as LocationFilterFileNotFoundError, D as GitCommandError, G as GitNotFoundError, E as VitestResolver, M as ModuleTransformService, l as resolveConfig$1, H as createClusterServer, S as ServerModuleRunner, J as attachProjectsFromEntries, K as TestProject, N as resolveAndAttachProjects, O as RandomSequencer, b as FilesNotFoundError, Q as createPool, U as astCollectTests, W as createFailedFileTask, X as matchesProjectFilter, Y as nanoid, L as Logger, V as VitestPackageInstaller, P as PluginHarness, Z as stdout, p as prompt } from './index.ER9afepi.js';
5
+ import { readFile, writeFile, rename, stat, unlink, rm, mkdir, readdir, copyFile } from 'node:fs/promises';
6
6
  import os__default, { tmpdir, hostname } from 'node:os';
7
- import { j as join, b as basename, d as dirname, i as isAbsolute, r as resolve, D as noop, e as createDefer, c as cleanUrl, a as relative, s as slash, F as sanitizeFilePath, t as toArray, G as deepMerge, m as isPrimitive, f as extname, n as normalize, p as deepClone } from './pathe.M-eThtNZ.Ba-7h1rE.js';
8
- import { T as TraceMap, o as originalPositionFor, p as parseStacktrace, e as parseErrorStacktrace, b as serializeValue } from './source-map.BjWcsIL9.js';
9
- import { v as version } from './cac.Ccf5Je_F.js';
7
+ import { j as join, b as basename, d as dirname, i as isAbsolute, r as resolve, D as noop, e as createDefer, c as cleanUrl, a as relative, s as slash, F as sanitizeFilePath, t as toArray, x as ordinal, G as deepMerge, p as isPrimitive, k as extname, n as normalize$1, u as deepClone } from './pathe.M-eThtNZ.zq3TM4NT.js';
8
+ import { T as TraceMap, o as originalPositionFor, p as parseStacktrace, e as parseErrorStacktrace, b as serializeValue } from './source-map.DPHGMWvM.js';
9
+ import { v as version } from './cac.BK306qhQ.js';
10
10
  import { performance as performance$1 } from 'node:perf_hooks';
11
- import { c as createBirpc } from './index.DmDMHCg8.js';
12
- import require$$0$3 from 'events';
11
+ import { c as createBirpc } from './index.CAmut2NG.js';
12
+ import require$$0$4 from 'events';
13
13
  import require$$1$1 from 'https';
14
- import require$$2$1 from 'http';
14
+ import require$$0 from 'http';
15
15
  import require$$3 from 'net';
16
16
  import require$$4 from 'tls';
17
17
  import require$$1 from 'crypto';
18
- import require$$0$2 from 'stream';
18
+ import require$$0$3 from 'stream';
19
19
  import require$$7 from 'url';
20
- import require$$0 from 'zlib';
21
- import require$$0$1 from 'buffer';
20
+ import require$$0$1 from 'zlib';
21
+ import require$$0$2 from 'buffer';
22
22
  import require$$2 from 'util';
23
- import { g as getDefaultExportFromCjs } from './index.D0heQG4v.js';
23
+ import { g as getDefaultExportFromCjs } from './index.Or9psEGe.js';
24
24
  import { A as API_PATH, d as defaultBrowserPort } from './constants.DLYM6cZY.js';
25
- import { i as isBuiltin } from './modules.BJuCwlRJ.js';
26
- import crypto, { createHash } from 'node:crypto';
25
+ import { i as isBuiltin, s as splitSourceMap, b as appendSourceMap } from './moduleSourceMap.Dp1WduWi.js';
26
+ import crypto, { hash, createHash } from 'node:crypto';
27
27
  import { distDir } from '../path.js';
28
- import { z as limitConcurrency, A as createTagsFilter } from './run.BfrMbGVD.js';
29
- import { N as NativeModuleRunner } from './nativeModuleRunner.xi64Afb2.js';
28
+ import { B as limitConcurrency, C as createTagsFilter } from './run.zBhXlcZQ.js';
29
+ import { N as NativeModuleRunner } from './nativeModuleRunner.9xPIMzi7.js';
30
30
  import { getTestName, hasFailed, hasFailedSnapshot, getTests, getSuites, getTasks, getFullName, createFileTask, generateFileHash, interpretTaskModes, convertTasksToEvents } from '../task-utils.js';
31
31
  import { Traces } from '../traces.js';
32
32
  import { $ } from './tinyrainbow.Do8I1XRG.js';
33
33
  import { searchForWorkspaceRoot } from 'vite';
34
+ import { w as withLabel, F as F_TREE_NODE_MIDDLE, a as F_TREE_NODE_END, f as formatTimeString, t as taskFail, s as separator, b as F_CHECK, c as F_POINTER, d as F_DOWN_RIGHT, e as formatProjectName, g as getStateSymbol, n as noun, p as padSummaryTitle, r as renderSnapshotSummary, h as getStateString$1, i as formatTime, j as errorBanner, k as divider, l as F_RIGHT, m as getCols } from './utils.sAsh2ClK.js';
34
35
  import module$1 from 'node:module';
35
- import path, { resolve as resolve$1 } from 'node:path';
36
+ import path, { resolve as resolve$1, normalize } from 'node:path';
36
37
  import { fileURLToPath } from 'node:url';
37
38
  import pm from 'picomatch';
38
39
  import { glob } from 'tinyglobby';
39
40
  import { a as coverageConfigDefaults } from './defaults.B1FCaFfh.js';
40
41
  import { a as isTTY, b as isWindows } from './env.BKKtU2WC.js';
41
42
  import { stripVTControlCharacters } from 'node:util';
42
- import { f as formatTimeString, t as taskFail, s as separator, F as F_CHECK, a as F_POINTER, b as F_DOWN_RIGHT, c as formatProjectName, g as getStateSymbol, w as withLabel, n as noun, p as padSummaryTitle, r as renderSnapshotSummary, d as getStateString$1, e as formatTime, h as countTestErrors, i as errorBanner, j as divider, k as F_TREE_NODE_END, l as F_TREE_NODE_MIDDLE, m as F_RIGHT } from './utils.DSfl_w8V.js';
43
43
  import { isCI } from 'std-env';
44
44
  import assert from 'node:assert';
45
45
  import { x, NonZeroExitError } from 'tinyexec';
46
46
  import readline from 'node:readline';
47
+ import { a as saveInlineSnapshots, e as evaluateSnapshotFile, s as saveSnapshotFile, b as saveRawSnapshots } from './rawSnapshot.DvoRLRNr.js';
48
+
49
+ async function saveSnapshotUpdates(snapshots) {
50
+ const updatesByFile = /* @__PURE__ */ new Map();
51
+ const saves = [];
52
+ for (const [environment, updates] of snapshots) {
53
+ for (const update of updates) {
54
+ const fileUpdates = updatesByFile.get(update.file) ?? [];
55
+ if (fileUpdates.length === 0) updatesByFile.set(update.file, fileUpdates);
56
+ fileUpdates.push(update);
57
+ }
58
+ for (const [file, fileUpdates] of updatesByFile) {
59
+ const updates = Object.groupBy(fileUpdates.values(), (snapshot) => snapshot.type);
60
+ if (updates.inline) saves.push(saveInlineSnapshots(environment, updates.inline));
61
+ if (updates.file) {
62
+ let data;
63
+ if (environment.readSnapshotFileData) data = await environment.readSnapshotFileData(file);
64
+ else {
65
+ const content = await environment.readSnapshotFile(file);
66
+ data = content == null ? null : evaluateSnapshotFile(file, content);
67
+ }
68
+ const snapshotData = Object.assign(Object.create(null), data);
69
+ for (const snapshot of updates.file) snapshotData[snapshot.key] = snapshot.snapshot;
70
+ saves.push(saveSnapshotFile(environment, snapshotData, file));
71
+ }
72
+ if (updates.raw) saves.push(saveRawSnapshots(environment, updates.raw));
73
+ }
74
+ }
75
+ await Promise.all(saves);
76
+ }
47
77
 
48
78
  class SnapshotManager {
49
79
  options;
@@ -138,6 +168,8 @@ function requireBufferUtil () {
138
168
  if (hasRequiredBufferUtil) return bufferUtil.exports;
139
169
  hasRequiredBufferUtil = 1;
140
170
 
171
+ const { websocketMask, websocketUnmask } = require$$0;
172
+
141
173
  const { EMPTY_BUFFER } = requireConstants();
142
174
 
143
175
  const FastBuffer = Buffer[Symbol.species];
@@ -249,8 +281,17 @@ function requireBufferUtil () {
249
281
  unmask: _unmask
250
282
  };
251
283
 
252
- /* istanbul ignore else */
253
- if (!process.env.WS_NO_BUFFER_UTIL) {
284
+ if (websocketMask) {
285
+ bufferUtil.exports.mask = function (source, mask, output, offset, length) {
286
+ if (length < 24) _mask(source, mask, output, offset, length);
287
+ else websocketMask(source, mask, output, offset, length);
288
+ };
289
+
290
+ bufferUtil.exports.unmask = function (buffer, mask) {
291
+ if (buffer.length < 24) _unmask(buffer, mask);
292
+ else websocketUnmask(buffer, mask);
293
+ };
294
+ } /* istanbul ignore else */ else if (!process.env.WS_NO_BUFFER_UTIL) {
254
295
  try {
255
296
  const bufferUtil$1 = require('bufferutil');
256
297
 
@@ -340,7 +381,7 @@ function requirePermessageDeflate () {
340
381
  if (hasRequiredPermessageDeflate) return permessageDeflate;
341
382
  hasRequiredPermessageDeflate = 1;
342
383
 
343
- const zlib = require$$0;
384
+ const zlib = require$$0$1;
344
385
 
345
386
  const bufferUtil = requireBufferUtil();
346
387
  const Limiter = requireLimiter();
@@ -879,7 +920,7 @@ function requireValidation () {
879
920
  if (hasRequiredValidation) return validation.exports;
880
921
  hasRequiredValidation = 1;
881
922
 
882
- const { isUtf8 } = require$$0$1;
923
+ const { isUtf8 } = require$$0$2;
883
924
 
884
925
  const { hasBlob } = requireConstants();
885
926
 
@@ -1039,7 +1080,7 @@ function requireReceiver () {
1039
1080
  if (hasRequiredReceiver) return receiver;
1040
1081
  hasRequiredReceiver = 1;
1041
1082
 
1042
- const { Writable } = require$$0$2;
1083
+ const { Writable } = require$$0$3;
1043
1084
 
1044
1085
  const PerMessageDeflate = requirePermessageDeflate();
1045
1086
  const {
@@ -1792,7 +1833,7 @@ function requireSender () {
1792
1833
  if (hasRequiredSender) return sender;
1793
1834
  hasRequiredSender = 1;
1794
1835
 
1795
- const { Duplex } = require$$0$2;
1836
+ const { Duplex } = require$$0$3;
1796
1837
  const { randomFillSync } = require$$1;
1797
1838
  const {
1798
1839
  types: { isUint8Array }
@@ -1943,7 +1984,9 @@ function requireSender () {
1943
1984
  target.writeUIntBE(dataLength, 4, 6);
1944
1985
  }
1945
1986
 
1946
- if (!options.mask) return [target, data];
1987
+ if (!options.mask) {
1988
+ return dataLength ? [target, data] : [target];
1989
+ }
1947
1990
 
1948
1991
  target[1] |= 0x80;
1949
1992
  target[offset - 4] = mask[0];
@@ -1951,6 +1994,7 @@ function requireSender () {
1951
1994
  target[offset - 2] = mask[2];
1952
1995
  target[offset - 1] = mask[3];
1953
1996
 
1997
+ if (!dataLength) return [target];
1954
1998
  if (skipMasking) return [target, data];
1955
1999
 
1956
2000
  if (merge) {
@@ -2918,13 +2962,13 @@ function requireWebsocket () {
2918
2962
  if (hasRequiredWebsocket) return websocket;
2919
2963
  hasRequiredWebsocket = 1;
2920
2964
 
2921
- const EventEmitter = require$$0$3;
2965
+ const EventEmitter = require$$0$4;
2922
2966
  const https = require$$1$1;
2923
- const http = require$$2$1;
2967
+ const http = require$$0;
2924
2968
  const net = require$$3;
2925
2969
  const tls = require$$4;
2926
2970
  const { randomBytes, createHash } = require$$1;
2927
- const { Duplex, Readable } = require$$0$2;
2971
+ const { Duplex, Readable } = require$$0$3;
2928
2972
  const { URL } = require$$7;
2929
2973
 
2930
2974
  const PerMessageDeflate = requirePermessageDeflate();
@@ -3735,10 +3779,15 @@ function requireWebsocket () {
3735
3779
  }
3736
3780
 
3737
3781
  if (isIpcUrl) {
3738
- const parts = opts.path.split(':');
3782
+ const i = opts.path.indexOf(':');
3739
3783
 
3740
- opts.socketPath = parts[0];
3741
- opts.path = parts[1];
3784
+ if (i === -1) {
3785
+ opts.socketPath = opts.path;
3786
+ opts.path = '';
3787
+ } else {
3788
+ opts.socketPath = opts.path.slice(0, i);
3789
+ opts.path = opts.path.slice(i + 1);
3790
+ }
3742
3791
  }
3743
3792
 
3744
3793
  let req;
@@ -4348,7 +4397,7 @@ function requireStream () {
4348
4397
  hasRequiredStream = 1;
4349
4398
 
4350
4399
  requireWebsocket();
4351
- const { Duplex } = require$$0$2;
4400
+ const { Duplex } = require$$0$3;
4352
4401
 
4353
4402
  /**
4354
4403
  * Emits the `'close'` event on a stream.
@@ -4601,9 +4650,9 @@ function requireWebsocketServer () {
4601
4650
  if (hasRequiredWebsocketServer) return websocketServer;
4602
4651
  hasRequiredWebsocketServer = 1;
4603
4652
 
4604
- const EventEmitter = require$$0$3;
4605
- const http = require$$2$1;
4606
- const { Duplex } = require$$0$2;
4653
+ const EventEmitter = require$$0$4;
4654
+ const http = require$$0;
4655
+ const { Duplex } = require$$0$3;
4607
4656
  const { createHash } = require$$1;
4608
4657
 
4609
4658
  const extension = requireExtension();
@@ -5175,19 +5224,18 @@ function getTestFileEnvironment(project, testFile, browser = false) {
5175
5224
 
5176
5225
  async function getModuleGraph(ctx, projectName, testFilePath, viteEnvironment) {
5177
5226
  const project = ctx.getProjectByName(projectName);
5178
- const collector = createModuleGraphCollector(project, getModuleGraphEnvironment(project, testFilePath, viteEnvironment));
5227
+ const environment = findModuleGraphEnvironment(project, testFilePath, viteEnvironment);
5228
+ if (!environment) throw new Error(`Cannot find environment for ${testFilePath}`);
5229
+ const collector = createModuleGraphCollector(project, environment);
5179
5230
  const roots = collector.add(testFilePath);
5180
5231
  return {
5181
5232
  modules: collector.data.modules,
5182
5233
  roots
5183
5234
  };
5184
5235
  }
5185
- function getModuleGraphEnvironment(project, testFilePath, viteEnvironment) {
5186
- let environment;
5187
- if (viteEnvironment) environment = project.vite.environments[viteEnvironment];
5188
- else environment = project.config.experimental.viteModuleRunner === false ? project.vite.environments.__vitest__ : getTestFileEnvironment(project, testFilePath, project.config.browser.enabled);
5189
- if (!environment) throw new Error(`Cannot find environment for ${testFilePath}`);
5190
- return environment;
5236
+ function findModuleGraphEnvironment(project, testFilePath, viteEnvironment) {
5237
+ if (viteEnvironment) return project.vite.environments[viteEnvironment];
5238
+ return project.config.experimental.viteModuleRunner === false ? project.vite.environments.__vitest__ : getTestFileEnvironment(project, testFilePath, project.config.browser.enabled);
5191
5239
  }
5192
5240
  function createModuleGraphCollector(project, environment) {
5193
5241
  const data = {
@@ -5274,7 +5322,14 @@ catch {}
5274
5322
  }
5275
5323
 
5276
5324
  function setup(ctx, _server) {
5277
- const wss = new WebSocketServer({ noServer: true });
5325
+ const wss = new WebSocketServer({
5326
+ noServer: true,
5327
+ // Emit one message per event loop, allowing the server to fairly distribute
5328
+ // received messages from clients in the main thread.
5329
+ // Otherwise, a client that floods its connection will saturate the main thread,
5330
+ // delaying message handling, leading to timeouts.
5331
+ allowSynchronousEvents: false
5332
+ });
5278
5333
  const clients = /* @__PURE__ */ new Map();
5279
5334
  (_server || ctx.vite).httpServer?.on("upgrade", (request, socket, head) => {
5280
5335
  if (!request.url) return;
@@ -5768,9 +5823,12 @@ class ProjectGraph {
5768
5823
  const imports = /* @__PURE__ */ new Set([...transformed.deps || [], ...transformed.dynamicDeps || []]);
5769
5824
  const dependencies = [];
5770
5825
  const watchedFiles = [];
5826
+ let failed = false;
5771
5827
  // ids keep the query, so `./file.txt?raw` is walked as its own module
5772
5828
  this.environment.moduleGraph.getModuleById(id)?.importedModules.forEach((imported) => {
5773
- if (imported.id && imported.file && this.resolver.isLocalSourceFile(imported.file)) (imports.has(imported.url) ? dependencies : watchedFiles).push(imported.id);
5829
+ // a dynamic import of a missing file can be caught, a static one always fails
5830
+ if (isMissingFile(imported) && transformed.deps?.includes(imported.url)) failed = true;
5831
+ else if (imported.id && imported.file && this.resolver.isLocalSourceFile(imported.file)) (imports.has(imported.url) ? dependencies : watchedFiles).push(imported.id);
5774
5832
  });
5775
5833
  [...redirects, ...restored].forEach((file) => {
5776
5834
  if (this.resolver.isLocalSourceFile(file) && !dependencies.includes(file)) dependencies.push(file);
@@ -5779,10 +5837,15 @@ class ProjectGraph {
5779
5837
  dependencies,
5780
5838
  watchedFiles,
5781
5839
  mocked: new Set(Array.from(replaced, (mockedId) => cleanUrl(mockedId))),
5782
- restored: new Set(Array.from(restored, (restoredId) => cleanUrl(restoredId)))
5840
+ restored: new Set(Array.from(restored, (restoredId) => cleanUrl(restoredId))),
5841
+ failed
5783
5842
  };
5784
5843
  }
5785
5844
  }
5845
+ // in SSR, Vite keeps an import it can't resolve as is, a bare one can still be loaded by Node
5846
+ function isMissingFile(mod) {
5847
+ return mod.id?.[0] === "." || mod.meta?.["vite:alias"]?.noResolved === true;
5848
+ }
5786
5849
  /**
5787
5850
  * Walks the module graph once for every root, skipping a module only when every walk that reaches it mocks it.
5788
5851
  */
@@ -5894,6 +5957,7 @@ const debugMemory = createDebugger("vitest:cache:memory");
5894
5957
  const cacheComment = "\n//# vitestCache=";
5895
5958
  const cacheCommentLength = 17;
5896
5959
  const METADATA_FILE = "_metadata.json";
5960
+ const MANIFEST_SECTIONS = ["modules", "externalized"];
5897
5961
  // Default location of the module cache. It lives inside `node_modules` at the
5898
5962
  // workspace root so it's shared by every project and is naturally invalidated
5899
5963
  // whenever dependencies are reinstalled.
@@ -5911,7 +5975,7 @@ class FileSystemModuleCache {
5911
5975
  */
5912
5976
  rootCache;
5913
5977
  metadataFilePath;
5914
- version = "1.0.0-beta.8";
5978
+ version = "1.0.0-beta.10";
5915
5979
  fsCacheRoots = /* @__PURE__ */ new WeakMap();
5916
5980
  fsEnvironmentHashMap = /* @__PURE__ */ new WeakMap();
5917
5981
  fsCacheKeyGenerators = /* @__PURE__ */ new WeakMap();
@@ -5919,6 +5983,8 @@ class FileSystemModuleCache {
5919
5983
  // this exists only to avoid the perf. cost of reading a file and generating a hash again
5920
5984
  // surprisingly, on some machines this has negligible effect
5921
5985
  fsCacheKeys = /* @__PURE__ */ new WeakMap();
5986
+ manifests = /* @__PURE__ */ new Map();
5987
+ manifestEntries = /* @__PURE__ */ new WeakMap();
5922
5988
  constructor(vitest) {
5923
5989
  this.vitest = vitest;
5924
5990
  this.rootCache = vitest.config.fsModuleCachePath || join(searchForWorkspaceRoot(vitest.viteConfig.root), "node_modules", DEFAULT_CACHE_DIRNAME);
@@ -5949,14 +6015,12 @@ class FileSystemModuleCache {
5949
6015
  const fsCachePaths = [this.rootCache, ...this.vitest.projects.map((r) => r.config.fsModuleCachePath || this.rootCache)];
5950
6016
  const uniquePaths = Array.from(new Set(fsCachePaths));
5951
6017
  uniquePaths.forEach(forgetCacheDirTag);
5952
- await Promise.all(uniquePaths.map((directory) => rm(directory, {
5953
- force: true,
5954
- recursive: true
5955
- })));
6018
+ await Promise.all(uniquePaths.map((directory) => removeDirectory(directory)));
5956
6019
  if (log) this.vitest.logger.log(`[cache] cleared fs module cache at ${uniquePaths.join(", ")}`);
5957
6020
  }
5958
6021
  readCachedFileConcurrently(cachedFilePath) {
5959
- if (!parallelFsCacheRead.has(cachedFilePath)) parallelFsCacheRead.set(cachedFilePath, readFile(cachedFilePath, "utf-8").then((code) => {
6022
+ if (!parallelFsCacheRead.has(cachedFilePath)) parallelFsCacheRead.set(cachedFilePath, readFile(cachedFilePath, "utf-8").then((content) => {
6023
+ const { code, sourceMap } = splitSourceMap(content);
5960
6024
  const matchIndex = code.lastIndexOf(cacheComment);
5961
6025
  if (matchIndex === -1) {
5962
6026
  debugFs?.(`${$.red("[empty]")} ${cachedFilePath} exists, but doesn't have a ${cacheComment} comment, transforming by vite instead`);
@@ -5964,38 +6028,42 @@ class FileSystemModuleCache {
5964
6028
  }
5965
6029
  return {
5966
6030
  code,
6031
+ sourceMap,
5967
6032
  meta: this.fromBase64(code.slice(matchIndex + cacheCommentLength))
5968
6033
  };
6034
+ }, (error) => {
6035
+ // another process can remove the cache at any time
6036
+ if (error?.code !== "ENOENT") throw error;
6037
+ debugFs?.(`${$.red("[empty]")} ${cachedFilePath} doesn't exist, transforming by vite first`);
5969
6038
  }).finally(() => {
5970
6039
  parallelFsCacheRead.delete(cachedFilePath);
5971
6040
  }));
5972
6041
  return parallelFsCacheRead.get(cachedFilePath);
5973
6042
  }
5974
6043
  async getCachedModule(cachedFilePath) {
5975
- if (!existsSync(cachedFilePath)) {
5976
- debugFs?.(`${$.red("[empty]")} ${cachedFilePath} doesn't exist, transforming by vite first`);
5977
- return;
5978
- }
5979
6044
  const fileResult = await this.readCachedFileConcurrently(cachedFilePath);
5980
6045
  if (!fileResult) return;
5981
- const { code, meta } = fileResult;
6046
+ const { code, sourceMap, meta } = fileResult;
5982
6047
  debugFs?.(`${$.green("[read]")} ${meta.id} is cached in ${cachedFilePath}`);
5983
6048
  return {
5984
6049
  id: meta.id,
5985
6050
  file: meta.file,
5986
6051
  code,
6052
+ sourceMap,
5987
6053
  imports: meta.imports,
5988
6054
  mappings: meta.mappings,
5989
6055
  moduleType: meta.moduleType,
5990
6056
  deps: meta.deps,
5991
6057
  dynamicDeps: meta.dynamicDeps,
5992
- staticMocks: meta.staticMocks
6058
+ staticMocks: meta.staticMocks,
6059
+ hasCoverageData: meta.hasCoverageData,
6060
+ coverageData: meta.hasCoverageData ? await readCoverageData(cachedFilePath) : void 0
5993
6061
  };
5994
6062
  }
5995
6063
  async saveCachedModule(cachedFilePath, fetchResult, transformResult, imports = {
5996
6064
  urls: [],
5997
6065
  ids: {}
5998
- }, mappings = false) {
6066
+ }, mappings = false, coverageData) {
5999
6067
  if ("code" in fetchResult) {
6000
6068
  const result = {
6001
6069
  file: fetchResult.file,
@@ -6005,12 +6073,31 @@ class FileSystemModuleCache {
6005
6073
  moduleType: fetchResult.moduleType,
6006
6074
  deps: transformResult?.deps,
6007
6075
  dynamicDeps: transformResult?.dynamicDeps,
6008
- staticMocks: transformResult?.__vitestStaticMocks
6076
+ staticMocks: transformResult?.__vitestStaticMocks,
6077
+ hasCoverageData: coverageData !== void 0
6009
6078
  };
6010
6079
  debugFs?.(`${$.yellow("[write]")} ${fetchResult.id} is cached in ${cachedFilePath}`);
6011
- await atomicWriteFile(cachedFilePath, `${fetchResult.code}${cacheComment}${this.toBase64(result)}`);
6080
+ await Promise.all([result.hasCoverageData && atomicWriteFile(getCoverageDataPath(cachedFilePath), JSON.stringify(coverageData)), atomicWriteFile(cachedFilePath, appendSourceMap(`${fetchResult.code}${cacheComment}${this.toBase64(result)}`, fetchResult.sourceMap))]);
6012
6081
  }
6013
6082
  }
6083
+ getCoverageData(environment, id) {
6084
+ const coverageProvider = this.vitest.coverageProvider;
6085
+ if (!this.vitest.config.coverage.enabled || !coverageProvider?.requiresTransform?.(id)) return;
6086
+ return coverageProvider.getModuleCacheData?.(environment, id);
6087
+ }
6088
+ /**
6089
+ * Passes the data of the coverage provider back to it when the cached module is used
6090
+ */
6091
+ restoreCoverageData(environment, id, data) {
6092
+ this.vitest.coverageProvider?.restoreModuleCacheData?.(environment, id, data);
6093
+ }
6094
+ // Vite watches the files outside of the root when it loads them, a cached module skips that
6095
+ watchFile(file) {
6096
+ const server = this.vitest.vite;
6097
+ // plugins can import modules in `configureServer` before the root server is attached
6098
+ if (!server) return;
6099
+ if (!file.startsWith(`${server.config.root}/`) && existsSync(file)) server.watcher.add(file);
6100
+ }
6014
6101
  toBase64(obj) {
6015
6102
  const json = stringify(obj);
6016
6103
  return Buffer.from(json).toString("base64");
@@ -6033,12 +6120,29 @@ class FileSystemModuleCache {
6033
6120
  else if (result === null) debugMemory?.(`${$.green("[read]")} ${id} was bailed out`);
6034
6121
  return result;
6035
6122
  }
6123
+ /** Returns null when the cache directory cannot be created. */
6124
+ getCacheRoot(vitestConfig) {
6125
+ if (this.fsCacheRoots.has(vitestConfig)) return this.fsCacheRoots.get(vitestConfig) ?? null;
6126
+ let cacheRoot = vitestConfig.fsModuleCachePath || this.rootCache;
6127
+ try {
6128
+ mkdirSync(cacheRoot, { recursive: true });
6129
+ tagCacheDir(cacheRoot);
6130
+ } catch (error) {
6131
+ const reason = error instanceof Error ? error.message : String(error);
6132
+ this.vitest.logger.warn(withLabel("yellow", "Vitest", `fsModuleCache is enabled, but its directory "${cacheRoot}" could not be created (${reason}). Continuing without caching modules on disk. Set \`fsModuleCache: false\` to disable the cache and this warning.`));
6133
+ cacheRoot = null;
6134
+ }
6135
+ this.fsCacheRoots.set(vitestConfig, cacheRoot);
6136
+ return cacheRoot;
6137
+ }
6036
6138
  generateCachePath(vitestConfig, environment, id, fileContent) {
6037
- // bail out if file has import.meta.glob because it depends on other files
6139
+ const cacheRoot = this.getCacheRoot(vitestConfig);
6140
+ if (cacheRoot == null) return null;
6141
+ // bail out if file has a glob import because it depends on other files
6038
6142
  // TODO: figure out a way to still support it
6039
- if (fileContent.includes("import.meta.glob(")) {
6143
+ if (hasGlobImport(fileContent, environment.config.consumer)) {
6040
6144
  this.saveMemoryCache(environment, id, null);
6041
- debugMemory?.(`${$.yellow("[write]")} ${id} was bailed out because it has "import.meta.glob"`);
6145
+ debugMemory?.(`${$.yellow("[write]")} ${id} was bailed out because it has a glob import`);
6042
6146
  return null;
6043
6147
  }
6044
6148
  let hashString = "";
@@ -6058,7 +6162,8 @@ class FileSystemModuleCache {
6058
6162
  const config = environment.config;
6059
6163
  // coverage provider is dynamic, so we also clear the whole cache if
6060
6164
  // vitest.enableCoverage/vitest.disableCoverage is called
6061
- const coverageAffectsCache = String(this.vitest.config.coverage.enabled && this.vitest.coverageProvider?.requiresTransform?.(id));
6165
+ const coverageProvider = this.vitest.coverageProvider;
6166
+ const coverageAffectsCache = this.vitest.config.coverage.enabled && coverageProvider?.requiresTransform?.(id) ? `${coverageProvider.name}@${coverageProvider.version}` : "false";
6062
6167
  let environmentHash = this.fsEnvironmentHashMap.get(environment);
6063
6168
  if (!environmentHash) {
6064
6169
  const cacheConfig = JSON.stringify({
@@ -6086,20 +6191,107 @@ class FileSystemModuleCache {
6086
6191
  environmentHash = hash("sha1", (process.env.NODE_ENV ?? "") + this.version + cacheConfig, "hex");
6087
6192
  this.fsEnvironmentHashMap.set(environment, environmentHash);
6088
6193
  }
6089
- hashString += id + fileContent + environmentHash + coverageAffectsCache;
6194
+ // cached code imports optimized deps from `cacheDir` with `?v=<browserHash>`;
6195
+ // read live because the optimizer can re-run after `environmentHash` is memoized
6196
+ const depsOptimizer = environment.depsOptimizer;
6197
+ const optimizerHash = depsOptimizer ? environment.config.cacheDir + depsOptimizer.metadata.browserHash : "";
6198
+ hashString += id + fileContent + environmentHash + coverageAffectsCache + optimizerHash;
6090
6199
  const cacheKey = hash("sha1", hashString, "hex");
6091
- let cacheRoot = this.fsCacheRoots.get(vitestConfig);
6092
- if (cacheRoot == null) {
6093
- cacheRoot = vitestConfig.fsModuleCachePath || this.rootCache;
6094
- this.fsCacheRoots.set(vitestConfig, cacheRoot);
6095
- if (!existsSync(cacheRoot)) mkdirSync(cacheRoot, { recursive: true });
6096
- tagCacheDir(cacheRoot);
6097
- }
6098
6200
  const fsResultPath = join(cacheRoot, cacheKey);
6099
6201
  debugMemory?.(`${$.yellow("[write]")} ${id} generated a cache in ${fsResultPath}`);
6100
6202
  this.saveMemoryCache(environment, id, fsResultPath);
6101
6203
  return fsResultPath;
6102
6204
  }
6205
+ recordManifestModule(vitestConfig, environment, url, cachePath) {
6206
+ this.getManifestEntries(vitestConfig, environment)?.modules.set(url, cachePath);
6207
+ }
6208
+ recordManifestExternal(vitestConfig, environment, url, externalized) {
6209
+ this.getManifestEntries(vitestConfig, environment)?.externalized.set(url, externalized);
6210
+ }
6211
+ getManifestEntries(vitestConfig, environment) {
6212
+ let entries = this.manifestEntries.get(environment);
6213
+ if (entries) return entries;
6214
+ const cacheRoot = this.getCacheRoot(vitestConfig);
6215
+ if (cacheRoot == null) return;
6216
+ const manifest = this.getManifest(vitestConfig, cacheRoot);
6217
+ entries = manifest.environments.get(environment.name);
6218
+ if (!entries) {
6219
+ entries = {
6220
+ modules: /* @__PURE__ */ new Map(),
6221
+ externalized: /* @__PURE__ */ new Map()
6222
+ };
6223
+ manifest.environments.set(environment.name, entries);
6224
+ }
6225
+ this.manifestEntries.set(environment, entries);
6226
+ return entries;
6227
+ }
6228
+ getManifest(vitestConfig, cacheRoot) {
6229
+ // several projects and Vitest processes can share the cache directory
6230
+ const label = (vitestConfig.name || basename(vitestConfig.root)).replace(/[^\w@-]+/g, "_").slice(0, 50);
6231
+ const key = hash("sha1", `${vitestConfig.root}\0${vitestConfig.name}`, "hex").slice(0, 8);
6232
+ const path = join(cacheRoot, `_manifest-${label}-${key}.json`);
6233
+ let manifest = this.manifests.get(path);
6234
+ if (!manifest) {
6235
+ manifest = {
6236
+ path,
6237
+ name: vitestConfig.name,
6238
+ root: vitestConfig.root,
6239
+ environments: /* @__PURE__ */ new Map()
6240
+ };
6241
+ this.manifests.set(path, manifest);
6242
+ }
6243
+ return manifest;
6244
+ }
6245
+ async writeManifests() {
6246
+ await Promise.all(Array.from(this.manifests.values(), (manifest) => this.writeManifest(manifest)));
6247
+ }
6248
+ async writeManifest(manifest) {
6249
+ if (Array.from(manifest.environments.values()).every((entries) => !entries.modules.size && !entries.externalized.size)) return;
6250
+ const loaded = manifest.content;
6251
+ const content = loaded ?? await readManifestContent(manifest.path);
6252
+ manifest.content = content;
6253
+ const changes = [];
6254
+ for (const [environment, entries] of manifest.environments) for (const section of MANIFEST_SECTIONS) {
6255
+ const values = content[section][environment];
6256
+ for (const [url, recordedValue] of entries[section]) {
6257
+ const value = section === "modules" ? recordedValue.slice(recordedValue.lastIndexOf("/") + 1) : recordedValue;
6258
+ if (values?.[url] !== value) changes.push([
6259
+ section,
6260
+ environment,
6261
+ url,
6262
+ value
6263
+ ]);
6264
+ }
6265
+ entries[section].clear();
6266
+ }
6267
+ if (!changes.length) return;
6268
+ let target = content;
6269
+ if (loaded) {
6270
+ // another process can update the manifest after this one loaded it
6271
+ target = await readManifestContent(manifest.path);
6272
+ for (const section of MANIFEST_SECTIONS) for (const environment in content[section]) target[section][environment] = {
6273
+ ...content[section][environment],
6274
+ ...target[section][environment]
6275
+ };
6276
+ }
6277
+ for (const [section, environment, url, value] of changes) {
6278
+ (target[section][environment] ??= {})[url] = value;
6279
+ // a module can switch between being inlined and externalized
6280
+ delete target[section === "modules" ? "externalized" : "modules"][environment]?.[url];
6281
+ }
6282
+ manifest.content = target;
6283
+ try {
6284
+ const data = {
6285
+ name: manifest.name,
6286
+ root: manifest.root,
6287
+ ...target
6288
+ };
6289
+ await atomicWriteFile(manifest.path, JSON.stringify(data, null, 2));
6290
+ } catch (error) {
6291
+ manifest.content = void 0;
6292
+ debugFs?.(`failed to write fs cache manifest ${manifest.path}: ${error}`);
6293
+ }
6294
+ }
6103
6295
  saveMemoryCache(environment, id, cache) {
6104
6296
  let environmentKeys = this.fsCacheKeys.get(environment);
6105
6297
  if (!environmentKeys) {
@@ -6153,6 +6345,20 @@ class FileSystemModuleCache {
6153
6345
  debugFs?.(`fs cache was cleared because lockfile has changed`);
6154
6346
  }
6155
6347
  }
6348
+ async function readManifestContent(path) {
6349
+ try {
6350
+ const manifest = JSON.parse(await readFile(path, "utf-8"));
6351
+ return {
6352
+ modules: manifest.modules ?? {},
6353
+ externalized: manifest.externalized ?? {}
6354
+ };
6355
+ } catch {
6356
+ return {
6357
+ modules: {},
6358
+ externalized: {}
6359
+ };
6360
+ }
6361
+ }
6156
6362
  /**
6157
6363
  * Performs an atomic write operation using the write-then-rename pattern.
6158
6364
  *
@@ -6179,6 +6385,26 @@ async function atomicWriteFile(realFilePath, data) {
6179
6385
  } catch {}
6180
6386
  }
6181
6387
  }
6388
+ async function removeDirectory(directory) {
6389
+ // parallel processes can clear the same cache at once; moving it away first
6390
+ // keeps their removal from racing with another process recreating it
6391
+ const detachedPath = `${directory}.tmp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6392
+ try {
6393
+ await rename(directory, detachedPath);
6394
+ } catch (error) {
6395
+ if (error?.code === "ENOENT") return;
6396
+ // Windows can refuse to rename a directory with open files
6397
+ await rm(directory, {
6398
+ force: true,
6399
+ recursive: true
6400
+ });
6401
+ return;
6402
+ }
6403
+ await rm(detachedPath, {
6404
+ force: true,
6405
+ recursive: true
6406
+ });
6407
+ }
6182
6408
  // lockfile hash resolution taken from vite
6183
6409
  // since this is experimental, we don't ask to expose it
6184
6410
  const lockfileFormats = [
@@ -6263,6 +6489,14 @@ function lookupFile(dir, fileNames) {
6263
6489
  dir = parentDir;
6264
6490
  }
6265
6491
  }
6492
+ // Vite expands these templates into `import.meta.glob` calls
6493
+ const dynamicImportTemplateRE = /\bimport\s*\(\s*`[^`]*\$\{/;
6494
+ const newUrlTemplateRE = /\bnew\s+URL\s*\(\s*`[^`]*\$\{[^`]*`\s*,\s*import\.meta\.url\b/;
6495
+ function hasGlobImport(code, consumer) {
6496
+ if (code.includes("import.meta.glob")) return true;
6497
+ if (!code.includes("${")) return false;
6498
+ return dynamicImportTemplateRE.test(code) || consumer === "client" && newUrlTemplateRE.test(code);
6499
+ }
6266
6500
  function tryReadFileSync(file) {
6267
6501
  try {
6268
6502
  return readFileSync(file, "utf-8");
@@ -6276,6 +6510,14 @@ function tryStatSync(file) {
6276
6510
  return fs__default.statSync(file, { throwIfNoEntry: false });
6277
6511
  } catch {}
6278
6512
  }
6513
+ async function readCoverageData(cachedFilePath) {
6514
+ try {
6515
+ return JSON.parse(await readFile(getCoverageDataPath(cachedFilePath), "utf-8"));
6516
+ } catch {}
6517
+ }
6518
+ function getCoverageDataPath(cachedFilePath) {
6519
+ return `${cachedFilePath}.coverage.json`;
6520
+ }
6279
6521
 
6280
6522
  const debug$1 = createDebugger("vitest:cache:results");
6281
6523
  const RESULTS_VERSION = 1;
@@ -6712,7 +6954,11 @@ class VitestCache {
6712
6954
  }
6713
6955
  /** @internal */
6714
6956
  async _update(specifications, startTime) {
6715
- await Promise.all([this._results.update(specifications, startTime), this._dependencies.update(specifications, startTime)]);
6957
+ await Promise.all([
6958
+ this._results.update(specifications, startTime),
6959
+ this._dependencies.update(specifications, startTime),
6960
+ this._modules.writeManifests()
6961
+ ]);
6716
6962
  }
6717
6963
  /** @internal */
6718
6964
  async _clear() {
@@ -7247,6 +7493,7 @@ Update your dependencies and make sure the versions match.`));
7247
7493
  const code = await promises.readFile(filename, "utf-8");
7248
7494
  return {
7249
7495
  // `transform` mode will inject source maps comment at the end
7496
+ // Node 26 removed the 'transform' mode, older versions still support it
7250
7497
  code: module$1.stripTypeScriptTypes(code, { mode: isTransform ? "transform" : "strip" }),
7251
7498
  map: null
7252
7499
  };
@@ -7259,7 +7506,7 @@ Update your dependencies and make sure the versions match.`));
7259
7506
  return async (filename) => {
7260
7507
  let lastError;
7261
7508
  for (const project of projects) {
7262
- const root = project.config.root;
7509
+ const root = project.config.root.endsWith("/") ? project.config.root : `${project.config.root}/`;
7263
7510
  if (!filename.startsWith(root) && !filename.startsWith(`/${root}`) && project !== rootProject) continue;
7264
7511
  try {
7265
7512
  const environment = project.config.environment;
@@ -8104,6 +8351,192 @@ function padBenchRow(row, widths) {
8104
8351
  return row.map((v, i) => i === 0 ? v.padEnd(widths[i]) : v.padStart(widths[i]));
8105
8352
  }
8106
8353
 
8354
+ function groupTaskErrors(tasks) {
8355
+ const groups = [];
8356
+ for (const task of tasks)
8357
+ // Merge identical errors
8358
+ for (const { error, attempt } of getErrorsWithAttempt(task)) {
8359
+ let previous;
8360
+ if (error.stack) previous = groups.find((item) => {
8361
+ if (item.error.stack !== error.stack || item.error.diff !== error.diff) return false;
8362
+ const itemTask = item.sources[0].task;
8363
+ const currentProjectName = task?.projectName || task.file?.projectName || "";
8364
+ const projectName = itemTask?.projectName || itemTask.file?.projectName || "";
8365
+ const currentAnnotations = task.type === "test" && task.annotations;
8366
+ const itemAnnotations = itemTask.type === "test" && itemTask.annotations;
8367
+ return projectName === currentProjectName && deepEqual(currentAnnotations, itemAnnotations);
8368
+ });
8369
+ if (previous) previous.sources.push({
8370
+ task,
8371
+ attempt
8372
+ });
8373
+ else groups.push({
8374
+ error,
8375
+ sources: [{
8376
+ task,
8377
+ attempt
8378
+ }]
8379
+ });
8380
+ }
8381
+ return groups;
8382
+ }
8383
+ function getErrorsWithAttempt(task) {
8384
+ const attempts = task.result?.attempts;
8385
+ if (!attempts?.length) return (task.result?.errors ?? []).map((error) => ({ error }));
8386
+ return attempts.flatMap((attempt) => (attempt.errors ?? []).map((error) => ({
8387
+ error,
8388
+ attempt
8389
+ })));
8390
+ }
8391
+ function deepEqual(a, b) {
8392
+ if (a === b) return true;
8393
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
8394
+ const keysA = Object.keys(a);
8395
+ const keysB = Object.keys(b);
8396
+ if (keysA.length !== keysB.length) return false;
8397
+ for (const key of keysA) if (!Object.hasOwn(b, key) || !deepEqual(a[key], b[key])) return false;
8398
+ return true;
8399
+ }
8400
+
8401
+ function getTraceAttemptKey(trace) {
8402
+ return `${trace.repeats}:${trace.retry}`;
8403
+ }
8404
+ function groupTraceAttempts(traces) {
8405
+ const grouped = /* @__PURE__ */ new Map();
8406
+ for (const trace of traces) {
8407
+ const key = getTraceAttemptKey(trace);
8408
+ const group = grouped.get(key);
8409
+ if (group) group.push(trace);
8410
+ else grouped.set(key, [trace]);
8411
+ }
8412
+ const merged = /* @__PURE__ */ new Map();
8413
+ for (const [key, traces] of grouped) merged.set(key, {
8414
+ ...traces[0],
8415
+ entries: normalizeTraceEntries(traces.flatMap((trace) => trace.entries))
8416
+ });
8417
+ return merged;
8418
+ }
8419
+ function normalizeTraceEntries(entries) {
8420
+ const merged = [];
8421
+ const startMap = /* @__PURE__ */ new Map();
8422
+ const parents = [];
8423
+ for (const entry of entries) {
8424
+ const range = entry.range;
8425
+ if (!range) {
8426
+ merged.push({
8427
+ ...entry,
8428
+ depth: parents.length
8429
+ });
8430
+ continue;
8431
+ }
8432
+ if (range.phase === "start") {
8433
+ startMap.set(range.id, merged.length);
8434
+ merged.push({
8435
+ ...entry,
8436
+ depth: parents.length
8437
+ });
8438
+ parents.push(range.id);
8439
+ continue;
8440
+ }
8441
+ // when range.phase === 'end'
8442
+ const index = startMap.get(range.id);
8443
+ if (index == null) {
8444
+ // unpaired range shouldn't happen but just leave it there
8445
+ merged.push({
8446
+ ...entry,
8447
+ depth: 0
8448
+ });
8449
+ continue;
8450
+ }
8451
+ // Keep the start timestamp for positioning, but derive display duration
8452
+ // from the end event timestamp.
8453
+ const start = merged[index];
8454
+ merged[index] = {
8455
+ ...start,
8456
+ ...entry,
8457
+ startTime: start.startTime,
8458
+ duration: entry.startTime - start.startTime
8459
+ };
8460
+ parents.pop();
8461
+ }
8462
+ return merged;
8463
+ }
8464
+
8465
+ function formatTraceTimeline(artifacts, { retryIndex, repeatIndex }, root) {
8466
+ const traces = artifacts.flatMap((artifact) => artifact.type === "internal:browserTrace" ? [artifact.data] : []);
8467
+ const attempt = groupTraceAttempts(traces).get(getTraceAttemptKey({
8468
+ retry: retryIndex,
8469
+ repeats: repeatIndex
8470
+ }));
8471
+ if (!attempt) return;
8472
+ // the test end is already shown by the error location
8473
+ const visible = attempt.entries.filter((step) => step.name !== "vitest:onAfterRetryTask");
8474
+ if (!visible.length) return;
8475
+ const shown = visible.slice(-10);
8476
+ const prefixes = getTreePrefixes(shown);
8477
+ const headerRow = { cells: [
8478
+ "step",
8479
+ "locator",
8480
+ "start",
8481
+ "duration",
8482
+ "location"
8483
+ ] };
8484
+ const rows = [headerRow, ...shown.map((step, i) => formatStep(step, prefixes[i], root))];
8485
+ const widths = headerRow.cells.map((_, i) => Math.max(...rows.map((row) => row.cells[i].length)));
8486
+ const hasLocator = shown.some((step) => step.element?.locator);
8487
+ const lines = rows.map((row) => {
8488
+ // the last column is left unpadded so rows have no trailing spaces inside its color codes
8489
+ const [name, locator, start, duration, location] = row.cells.map((cell, i) => i === 4 ? cell : i === 2 || i === 3 ? cell.padStart(widths[i]) : cell.padEnd(widths[i]));
8490
+ if (row === headerRow) {
8491
+ const locatorColumn = hasLocator ? `${locator} ` : "";
8492
+ return $.dim(` ${name} ${locatorColumn}${start} ${duration} ${location}`);
8493
+ }
8494
+ const text = ` ${name} ${hasLocator ? `${colorCell(locator, $.cyan)} ` : ""}${start} ${colorCell(duration)} ${colorCell(location, $.dim)}`;
8495
+ return row.status === "fail" ? $.red(text) : text;
8496
+ });
8497
+ const omitted = visible.length - shown.length;
8498
+ if (omitted) lines.splice(1, 0, $.dim(` ... ${omitted} earlier ${omitted === 1 ? "step" : "steps"}`));
8499
+ const header = [];
8500
+ if (attempt.retry) header.push(`retry ${attempt.retry}`);
8501
+ if (attempt.repeats) header.push(`repeat ${attempt.repeats}`);
8502
+ return [`\n${header.length ? `Trace (${header.join(", ")}):` : "Trace:"}`, ...lines].join("\n");
8503
+ }
8504
+ function getTreePrefixes(steps) {
8505
+ const hasNextSibling = steps.map((step, i) => {
8506
+ return steps.slice(i + 1).find((other) => other.depth <= step.depth)?.depth === step.depth;
8507
+ });
8508
+ const lastAtDepth = [];
8509
+ return steps.map((step, i) => {
8510
+ lastAtDepth[step.depth] = i;
8511
+ if (step.depth === 0) return "";
8512
+ let prefix = "";
8513
+ for (let level = 1; level < step.depth; level++) prefix += hasNextSibling[lastAtDepth[level]] ? "│ " : " ";
8514
+ return `${prefix}${hasNextSibling[i] ? F_TREE_NODE_MIDDLE : F_TREE_NODE_END} `;
8515
+ });
8516
+ }
8517
+ function formatStep(step, prefix, root) {
8518
+ const location = step.location && `${relative(root, step.location.file)}:${step.location.line}:${step.location.column}`;
8519
+ return {
8520
+ cells: [
8521
+ `${prefix}${formatStepName(step.name)}`,
8522
+ step.element?.locator || "-",
8523
+ `+${formatMs(step.startTime)}`,
8524
+ step.duration == null ? "-" : formatMs(step.duration),
8525
+ location || "-"
8526
+ ],
8527
+ status: step.status
8528
+ };
8529
+ }
8530
+ function colorCell(cell, format = (text) => text) {
8531
+ return cell.trim() === "-" ? $.dim(cell) : format(cell);
8532
+ }
8533
+ function formatMs(ms) {
8534
+ return `${Math.round(ms)}ms`;
8535
+ }
8536
+ function formatStepName(name) {
8537
+ return name.startsWith("vitest:") ? name.slice(7) : name;
8538
+ }
8539
+
8107
8540
  const BADGE_PADDING = " ";
8108
8541
  class BaseReporter {
8109
8542
  start = 0;
@@ -8347,8 +8780,10 @@ class BaseReporter {
8347
8780
  else if (this.ctx.isCancelling) this.log(withLabel("red", "CANCELLED", "Test run cancelled. Watching for file changes..."));
8348
8781
  else this.log(withLabel("green", "PASS", "Waiting for file changes..."));
8349
8782
  const hints = [$.dim("press ") + $.bold("h") + $.dim(" to show help")];
8350
- if (hasFailedSnapshot(files)) hints.unshift($.dim("press ") + $.bold($.yellow("u")) + $.dim(" to update snapshot"));
8351
- else hints.push($.dim("press ") + $.bold("q") + $.dim(" to quit"));
8783
+ if (hasFailedSnapshot(files)) {
8784
+ hints.unshift($.dim("press ") + $.bold($.yellow("u")) + $.dim(" to update snapshot"));
8785
+ hints.unshift($.dim("press ") + $.bold($.yellow("i")) + $.dim(" to review snapshot fails"));
8786
+ } else hints.push($.dim("press ") + $.bold("q") + $.dim(" to quit"));
8352
8787
  this.log(BADGE_PADDING + hints.join($.dim(", ")));
8353
8788
  }
8354
8789
  onWatcherRerun(files, trigger) {
@@ -8768,17 +9203,18 @@ class BaseReporter {
8768
9203
  const tests = getTests(files);
8769
9204
  const failedSuites = suites.filter((i) => i.result?.errors);
8770
9205
  const failedTests = tests.filter((i) => i.result?.state === "fail");
8771
- const failedTotal = countTestErrors(failedSuites) + countTestErrors(failedTests);
8772
- // TODO: error divider should take into account merged errors for counting
9206
+ const suiteErrors = groupTaskErrors(failedSuites);
9207
+ const testErrors = groupTaskErrors(failedTests);
9208
+ const failedTotal = suiteErrors.length + testErrors.length;
8773
9209
  let current = 1;
8774
9210
  const errorDivider = () => this.error(`${$.red($.dim(divider(`[${current++}/${failedTotal}]`, void 0, 1)))}\n`);
8775
9211
  if (failedSuites.length) {
8776
9212
  this.error(`\n${errorBanner(`Failed Suites ${failedSuites.length}`)}\n`);
8777
- this.printTaskErrors(failedSuites, errorDivider);
9213
+ this.printTaskErrors(suiteErrors, errorDivider);
8778
9214
  }
8779
9215
  if (failedTests.length) {
8780
9216
  this.error(`\n${errorBanner(`Failed Tests ${failedTests.length}`)}\n`);
8781
- this.printTaskErrors(failedTests, errorDivider);
9217
+ this.printTaskErrors(testErrors, errorDivider);
8782
9218
  }
8783
9219
  if (errors.length) {
8784
9220
  this.ctx.logger.printUnhandledErrors(errors);
@@ -8871,46 +9307,32 @@ class BaseReporter {
8871
9307
  }
8872
9308
  }
8873
9309
  }
8874
- printTaskErrors(tasks, errorDivider) {
8875
- const errorsQueue = [];
8876
- for (const task of tasks)
8877
- // Merge identical errors
8878
- task.result?.errors?.forEach((error) => {
8879
- let previous;
8880
- if (error?.stack) previous = errorsQueue.find((i) => {
8881
- if (i[0]?.stack !== error.stack || i[0]?.diff !== error.diff) return false;
8882
- const currentProjectName = task?.projectName || task.file?.projectName || "";
8883
- const projectName = i[1][0]?.projectName || i[1][0].file?.projectName || "";
8884
- const currentAnnotations = task.type === "test" && task.annotations;
8885
- const itemAnnotations = i[1][0].type === "test" && i[1][0].annotations;
8886
- return projectName === currentProjectName && deepEqual(currentAnnotations, itemAnnotations);
8887
- });
8888
- if (previous) previous[1].push(task);
8889
- else errorsQueue.push([error, [task]]);
8890
- });
8891
- for (const [error, tasks] of errorsQueue) {
8892
- for (const task of tasks) {
9310
+ printTaskErrors(groups, errorDivider) {
9311
+ for (const { error, sources } of groups) {
9312
+ const tasks = sources.map(({ task }) => task);
9313
+ const attemptsByTask = /* @__PURE__ */ new Map();
9314
+ for (const { task, attempt } of sources) attemptsByTask.set(task, [...attemptsByTask.get(task) ?? [], attempt]);
9315
+ const screenshotPaths = [...attemptsByTask].flatMap(([task, attempts]) => [...new Set(attempts)].flatMap((attempt) => attempt ? getFailureScreenshotPaths(task, attempt) : []));
9316
+ for (const [task, attempts] of attemptsByTask) {
8893
9317
  const filepath = task?.filepath || "";
8894
9318
  const projectName = task?.projectName || task.file?.projectName || "";
8895
9319
  const project = this.ctx.projects.find((p) => p.name === projectName);
8896
9320
  let name = this.getFullName(task, separator);
9321
+ const attemptLabel = formatErrorAttempts(task, attempts);
9322
+ if (attemptLabel) name += $.dim(` (${attemptLabel})`);
8897
9323
  if (filepath) name += $.dim(` [ ${this.relative(filepath)} ]`);
8898
9324
  const label = this.ctx.state.blobs && task.file?.meta?.__vitest_label__;
8899
9325
  this.ctx.logger.error(`${$.bgRed($.bold(" FAIL "))} ${formatProjectName(project)}${label ? `${$.bgCyan($.bold(` ${label} `))} ` : ""}${name}`);
8900
9326
  }
8901
- const screenshotPaths = tasks.reduce((paths, t) => {
8902
- if (t.type === "test") {
8903
- for (const artifact of t.artifacts) if (artifact.type === "internal:failureScreenshot") {
8904
- if (artifact.attachments.length) paths.push(artifact.attachments[0].originalPath);
8905
- }
8906
- }
8907
- return paths;
8908
- }, []);
8909
9327
  this.ctx.logger.printError(error, {
8910
9328
  project: this.ctx.getProjectByName(tasks[0].file.projectName || ""),
8911
9329
  verbose: this.verbose,
8912
9330
  screenshotPaths
8913
9331
  });
9332
+ for (const [task, attempts] of attemptsByTask) for (const attempt of attempts) {
9333
+ const timeline = task.type === "test" && attempt && formatTraceTimeline(task.artifacts, attempt, this.ctx.config.root);
9334
+ if (timeline) this.error(`${timeline}\n`);
9335
+ }
8914
9336
  if (tasks[0].type === "test" && tasks[0].annotations.length) {
8915
9337
  const test = this.ctx.state.getReportedEntity(tasks[0]);
8916
9338
  this.printAnnotations(test, "error", 1);
@@ -8920,14 +9342,25 @@ class BaseReporter {
8920
9342
  }
8921
9343
  }
8922
9344
  }
8923
- function deepEqual(a, b) {
8924
- if (a === b) return true;
8925
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
8926
- const keysA = Object.keys(a);
8927
- const keysB = Object.keys(b);
8928
- if (keysA.length !== keysB.length) return false;
8929
- for (const key of keysA) if (!Object.hasOwn(b, key) || !deepEqual(a[key], b[key])) return false;
8930
- return true;
9345
+ function formatErrorAttempts(task, attempts) {
9346
+ const showAttempt = (task.result?.attempts?.length ?? 0) > 1;
9347
+ return [...Map.groupBy(attempts, (attempt) => attempt)].map(([attempt, occurrences]) => {
9348
+ const label = showAttempt && attempt ? formatAttempt(attempt) : "";
9349
+ const count = occurrences.length > 1 ? `${occurrences.length} times` : "";
9350
+ return count && label ? `${count} in ${label}` : count || label;
9351
+ }).filter(Boolean).join(", ");
9352
+ }
9353
+ function formatAttempt({ repeatIndex, retryIndex }) {
9354
+ const repeat = repeatIndex ? `${ordinal(repeatIndex)} repeat` : "";
9355
+ const retry = retryIndex ? `${ordinal(retryIndex)} retry` : "";
9356
+ if (repeat && retry) return `${retry} of ${repeat}`;
9357
+ return repeat || retry || "initial run";
9358
+ }
9359
+ function getFailureScreenshotPaths(task, attempt) {
9360
+ if (task.type !== "test") return [];
9361
+ const paths = [];
9362
+ for (const artifact of task.artifacts) if (artifact.type === "internal:failureScreenshot" && artifact.attachments.length && artifact.retryIndex === attempt.retryIndex && artifact.repeatIndex === attempt.repeatIndex) paths.push(artifact.attachments[0].originalPath);
9363
+ return paths;
8931
9364
  }
8932
9365
  function sum(items, cb) {
8933
9366
  return items.reduce((total, next) => {
@@ -9795,8 +10228,9 @@ class JsonReporter {
9795
10228
  const numTotalTestSuites = suites.length;
9796
10229
  const tests = getTests(files);
9797
10230
  const numTotalTests = tests.length;
9798
- const numFailedTestSuites = suites.filter((s) => s.result?.state === "fail").length;
9799
- const numPendingTestSuites = suites.filter((s) => s.result?.state === "run" || s.result?.state === "queued" || s.mode === "todo").length;
10231
+ const unfinishedFiles = new Set(files.filter(isUnfinished));
10232
+ const numFailedTestSuites = suites.filter((s) => s.result?.state === "fail" || unfinishedFiles.has(s)).length;
10233
+ const numPendingTestSuites = suites.filter((s) => !unfinishedFiles.has(s) && (s.result?.state === "run" || s.result?.state === "queued" || s.mode === "todo")).length;
9800
10234
  const numPassedTestSuites = numTotalTestSuites - numFailedTestSuites - numPendingTestSuites;
9801
10235
  const numFailedTests = tests.filter((t) => t.result?.state === "fail").length;
9802
10236
  const numPassedTests = tests.filter((t) => t.result?.state === "pass").length;
@@ -9844,7 +10278,7 @@ class JsonReporter {
9844
10278
  assertionResults,
9845
10279
  startTime,
9846
10280
  endTime,
9847
- status: file.result?.state === "fail" || hasFailedTests ? "failed" : "passed",
10281
+ status: unfinishedFiles.has(file) || file.result?.state === "fail" || hasFailedTests ? "failed" : "passed",
9848
10282
  message: file.result?.errors?.[0]?.message ?? "",
9849
10283
  name: file.filepath
9850
10284
  });
@@ -9881,6 +10315,12 @@ class JsonReporter {
9881
10315
  }
9882
10316
  }
9883
10317
  }
10318
+ // the file did not finish, for example because its worker crashed
10319
+ // (same as `pending` or `queued` in `TestModule.state()`)
10320
+ function isUnfinished(file) {
10321
+ const state = file.result?.state;
10322
+ return file.mode !== "skip" && file.mode !== "todo" && (state == null || state === "run" || state === "only" || state === "queued");
10323
+ }
9884
10324
 
9885
10325
  class IndentedLogger {
9886
10326
  baseLog;
@@ -10952,7 +11392,7 @@ class TestModule extends SuiteImplementation {
10952
11392
  * Checks the running state of the test file.
10953
11393
  */
10954
11394
  state() {
10955
- if (this.task.result?.state === "queued") return "queued";
11395
+ if (this.task.mode === "queued" && !this.task.result) return "queued";
10956
11396
  return getSuiteState(this.task);
10957
11397
  }
10958
11398
  /**
@@ -11103,7 +11543,7 @@ class StateManager {
11103
11543
  collectFiles(project, files = []) {
11104
11544
  files.forEach((file) => {
11105
11545
  const existing = this.filesMap.get(file.filepath) || [];
11106
- const currentFile = existing.find((i) => i.projectName === file.projectName && i.meta.typecheck === file.meta.typecheck && i.meta.__vitest_label__ === file.meta.__vitest_label__);
11546
+ const currentFile = existing.find((i) => i.id === file.id);
11107
11547
  // keep logs for the previous file because it should always be initiated before the collections phase
11108
11548
  // which means that all logs are collected during the collection and not inside tests
11109
11549
  if (currentFile) file.logs = currentFile.logs;
@@ -11844,15 +12284,16 @@ class Mime {
11844
12284
  for (let [type, extensions] of Object.entries(typeMap)) {
11845
12285
  type = type.toLowerCase();
11846
12286
  extensions = extensions.map((ext) => ext.toLowerCase());
11847
- if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
11848
- __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, new Set());
12287
+ let allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
12288
+ if (!allExtensions) {
12289
+ allExtensions = new Set();
12290
+ __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, allExtensions);
11849
12291
  }
11850
- const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
11851
12292
  let first = true;
11852
12293
  for (let extension of extensions) {
11853
12294
  const starred = extension.startsWith('*');
11854
12295
  extension = starred ? extension.slice(1) : extension;
11855
- allExtensions?.add(extension);
12296
+ allExtensions.add(extension);
11856
12297
  if (first) {
11857
12298
  __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
11858
12299
  }
@@ -11889,16 +12330,14 @@ class Mime {
11889
12330
  if (typeof type !== 'string')
11890
12331
  return null;
11891
12332
  type = type.split(';')[0].trim().toLowerCase();
11892
- return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type) ?? null;
12333
+ const extensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
12334
+ return extensions ? new Set(extensions) : null;
11893
12335
  }
11894
12336
  _freeze() {
11895
12337
  this.define = () => {
11896
12338
  throw new Error('define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances');
11897
12339
  };
11898
12340
  Object.freeze(this);
11899
- for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
11900
- Object.freeze(extensions);
11901
- }
11902
12341
  return this;
11903
12342
  }
11904
12343
  _getTestState() {
@@ -11953,6 +12392,24 @@ class TestRun {
11953
12392
  return artifact;
11954
12393
  }
11955
12394
  if (Array.isArray(artifact.attachments)) await Promise.all(artifact.attachments.map((attachment) => this.resolveTestAttachment(testCase, attachment)));
12395
+ // trace locations of browser tests need the browser server's source maps here,
12396
+ // while node trace stacks are already mapped in the worker except for external modules
12397
+ if (artifact.type === "internal:browserTrace") {
12398
+ const { entries } = artifact.data;
12399
+ const project = testCase.project;
12400
+ const isBrowser = testCase.task.file.pool === "browser";
12401
+ for (const entry of entries) if (entry.stack && !entry.location) {
12402
+ const [stack] = isBrowser ? project.browser?.parseStacktrace(entry.stack, { firstOnly: true }) || [] : parseStacktrace(entry.stack, {
12403
+ firstOnly: true,
12404
+ getSourceMap: (file) => getExternalSourceMap(project, file)
12405
+ });
12406
+ if (stack) entry.location = {
12407
+ file: stack.file,
12408
+ line: stack.line,
12409
+ column: stack.column
12410
+ };
12411
+ }
12412
+ }
11956
12413
  testCase.task.artifacts.push(artifact);
11957
12414
  await this.vitest.report("onTestCaseArtifactRecord", testCase, artifact);
11958
12415
  return artifact;
@@ -11977,28 +12434,19 @@ class TestRun {
11977
12434
  }
11978
12435
  async end(specifications, errors, coverage) {
11979
12436
  if (coverage) await this.vitest.report("onCoverage", coverage);
11980
- // specification won't have the File task if they were filtered by the --shard command
11981
12437
  const modules = specifications.map((spec) => spec.testModule).filter((s) => s != null);
11982
12438
  const state = this.vitest.isCancelling ? "interrupted" : // by this point, the run will be marked as failed if there are any errors,
11983
12439
  // should it be done by testRun.end?
11984
12440
  this.hasFailed(modules) ? "failed" : "passed";
11985
12441
  if (state !== "passed") process.exitCode = 1;
11986
12442
  await this.vitest.report("onTestRunEnd", modules, [...errors], state);
11987
- for (const project in this.vitest.state.metadata) {
11988
- const meta = this.vitest.state.metadata[project];
11989
- if (!meta?.dumpDir) continue;
11990
- const path = resolve(meta.dumpDir, "vitest-metadata.json");
11991
- meta.outline = {
11992
- externalized: Object.keys(meta.externalized).length,
11993
- inlined: Object.keys(meta.tmps).length
11994
- };
11995
- await writeFile(path, JSON.stringify(meta, null, 2), "utf-8");
11996
- this.vitest.logger.log(`Metadata written to ${path}`);
11997
- }
11998
12443
  }
11999
12444
  hasFailed(modules) {
12000
12445
  if (!modules.length) return !this.vitest.config.passWithNoTests;
12001
- return modules.some((m) => !m.ok() || m.state() === "pending");
12446
+ return modules.some((m) => {
12447
+ const state = m.state();
12448
+ return !m.ok() || state === "pending" || state === "queued";
12449
+ });
12002
12450
  }
12003
12451
  // make sure the error always has a "stacks" property
12004
12452
  syncUpdateStacks(update) {
@@ -12011,12 +12459,7 @@ class TestRun {
12011
12459
  if (isBrowser) error.stacks = project.browser?.parseErrorStacktrace(error, { frameFilter: project.config.onStackTrace }) || [];
12012
12460
  else error.stacks = parseErrorStacktrace(error, {
12013
12461
  frameFilter: project.config.onStackTrace,
12014
- getSourceMap(file) {
12015
- if (!project.vite.moduleGraph.getModuleById(file)?.transformResult && existsSync(file)) {
12016
- const code = readFileSync(file, "utf-8");
12017
- return extractSourcemapFromFile(code, file)?.map;
12018
- }
12019
- }
12462
+ getSourceMap: (file) => getExternalSourceMap(project, file)
12020
12463
  });
12021
12464
  });
12022
12465
  });
@@ -12094,6 +12537,12 @@ class TestRun {
12094
12537
  }
12095
12538
  }
12096
12539
  }
12540
+ function getExternalSourceMap(project, file) {
12541
+ if (!project.vite.moduleGraph.getModuleById(file)?.transformResult && existsSync(file)) {
12542
+ const code = readFileSync(file, "utf-8");
12543
+ return extractSourcemapFromFile(code, file)?.map;
12544
+ }
12545
+ }
12097
12546
 
12098
12547
  class GitVCSProvider {
12099
12548
  root;
@@ -12194,6 +12643,7 @@ class VitestWatcher {
12194
12643
  */
12195
12644
  changedTests = /* @__PURE__ */ new Set();
12196
12645
  _onRerun = [];
12646
+ trackers = /* @__PURE__ */ new Map();
12197
12647
  constructor(vitest) {
12198
12648
  this.vitest = vitest;
12199
12649
  }
@@ -12342,6 +12792,47 @@ class VitestWatcher {
12342
12792
  }
12343
12793
  return !!files.length;
12344
12794
  }
12795
+ createTracker() {
12796
+ const watcher = this.vitest.vite.watcher;
12797
+ watcher.on("all", this.handleTrackEvent);
12798
+ const stop = () => {
12799
+ watcher.off("all", this.handleTrackEvent);
12800
+ this.trackers.clear();
12801
+ };
12802
+ return {
12803
+ track: this.track,
12804
+ // @todo: implement [Symbol.dispose] when dropping support for Node 22
12805
+ stop
12806
+ };
12807
+ }
12808
+ track = (filepath, { timeout, type = "any" } = {}) => {
12809
+ const eventTrackers = this.trackers.get(type) ?? /* @__PURE__ */ new Map();
12810
+ if (eventTrackers.size === 0) this.trackers.set(type, eventTrackers);
12811
+ const normalizedFilepath = normalize(filepath);
12812
+ const fileTrackers = eventTrackers.get(normalizedFilepath) ?? /* @__PURE__ */ new Set();
12813
+ if (fileTrackers.size === 0) eventTrackers.set(normalizedFilepath, fileTrackers);
12814
+ const resolvers = Promise.withResolvers();
12815
+ if (timeout) {
12816
+ const timeoutId = setTimeout(resolvers.reject, timeout);
12817
+ resolvers.promise = resolvers.promise.then(() => {
12818
+ clearTimeout(timeoutId);
12819
+ }).catch(() => {});
12820
+ }
12821
+ resolvers.promise = resolvers.promise.finally(() => {
12822
+ fileTrackers.delete(resolvers);
12823
+ });
12824
+ fileTrackers.add(resolvers);
12825
+ return resolvers.promise;
12826
+ };
12827
+ handleTrackEvent = (eventName, path) => {
12828
+ this.resolveTrackEvent("any", path);
12829
+ this.resolveTrackEvent(eventName, path);
12830
+ };
12831
+ resolveTrackEvent(eventName, path) {
12832
+ const fileTrackers = this.trackers.get(eventName)?.get(path);
12833
+ if (fileTrackers === void 0) return;
12834
+ for (const resolvers of fileTrackers) resolvers.resolve();
12835
+ }
12345
12836
  }
12346
12837
  // files loaded outside of the test module graph that affect every test in the project
12347
12838
  function getProjectWatchedFiles(project) {
@@ -12442,6 +12933,7 @@ class Vitest {
12442
12933
  */
12443
12934
  _rootBrowserParent;
12444
12935
  /** @internal */ _browserSessions = new BrowserSessions();
12936
+ /** @internal */ _browserCacheStale = false;
12445
12937
  /** @internal */ reporters = [];
12446
12938
  /** @internal */ runner;
12447
12939
  /** @internal */ _testRun;
@@ -12456,6 +12948,7 @@ class Vitest {
12456
12948
  restartsCount = 0;
12457
12949
  specifications;
12458
12950
  pool;
12951
+ sequencer;
12459
12952
  _coverageProvider;
12460
12953
  /**
12461
12954
  * @deprecated Do not rely on this property, it's always `test`. Scheduled to be removed in the next major.
@@ -12492,9 +12985,15 @@ class Vitest {
12492
12985
  _setRootConfig(config) {
12493
12986
  this.watcher.unregisterWatcher();
12494
12987
  clearTimeout(this._rerunTimer);
12988
+ // the rerun timer is the only place that clears these sets. If a restart
12989
+ // cancels the timer, `handleFileChanged` ignores every later change of the
12990
+ // files that are still in the sets.
12991
+ this.watcher.changedTests.clear();
12992
+ this.watcher.invalidates.clear();
12495
12993
  this.restartsCount += 1;
12496
12994
  this.pool?.close?.();
12497
12995
  this.pool = void 0;
12996
+ this.sequencer = void 0;
12498
12997
  this.closingPromise = void 0;
12499
12998
  this.projects = [];
12500
12999
  this.runningPromise = void 0;
@@ -12551,7 +13050,7 @@ class Vitest {
12551
13050
  this._harness._prewarmedBrowsers = 0;
12552
13051
  // harness mimics `vitest` access like in `node/create.ts`
12553
13052
  this._harness.setVitest(void 0);
12554
- const config = await resolveConfig$1(this.config.cliOptions, this.config.viteOverrides, this._harness);
13053
+ const config = await resolveConfig$1(this.config.cliOptions, this.config.viteOverrides, this._harness, this.config._cliFilters);
12555
13054
  this._harness.setVitest(this);
12556
13055
  await this._start(config);
12557
13056
  }
@@ -12582,7 +13081,7 @@ class Vitest {
12582
13081
  if (resolved._containerConfigFiles?.length) server.watcher.add(resolved._containerConfigFiles);
12583
13082
  // since we set `server.hmr: false`, Vite does not auto restart itself
12584
13083
  server.watcher.on("change", async (file) => {
12585
- file = normalize(file);
13084
+ file = normalize$1(file);
12586
13085
  if (file === server.config.configFile || this.projects.some((p) => p.vite.config.configFile === file) || this.config._containerConfigFiles?.includes(file))
12587
13086
  // a floating rejection in an event handler would crash the process
12588
13087
  await this._restart("config").catch((error) => {
@@ -12869,7 +13368,7 @@ class Vitest {
12869
13368
  return this._traces.$("vitest.collect", async (collectSpan) => {
12870
13369
  const filenamePattern = filters && filters?.length > 0 ? filters : [];
12871
13370
  collectSpan.setAttribute("vitest.collect.filters", filenamePattern);
12872
- const files = await this._traces.$("vitest.config.resolve_include_glob", async () => {
13371
+ let files = await this._traces.$("vitest.config.resolve_include_glob", async () => {
12873
13372
  const specifications = await this.specifications.getRelevantTestSpecifications(filters);
12874
13373
  collectSpan.setAttribute("vitest.collect.specifications", specifications.map((s) => {
12875
13374
  const relativeModuleId = relative(s.project.config.root, s.moduleId);
@@ -12878,6 +13377,7 @@ class Vitest {
12878
13377
  }));
12879
13378
  return specifications;
12880
13379
  });
13380
+ files = await this._shardSpecifications(files);
12881
13381
  // if run with --changed, don't exit if no tests are found
12882
13382
  if (!files.length) return {
12883
13383
  testModules: [],
@@ -12931,13 +13431,7 @@ class Vitest {
12931
13431
  }));
12932
13432
  return specifications;
12933
13433
  });
12934
- if (this.config.experimental.preParse) {
12935
- // This populates specification.testModule with parsed information
12936
- await this.parseSpecifications(specifications);
12937
- specifications = specifications.filter(({ testModule }) => {
12938
- return !testModule || testModule.task.mode !== "skip";
12939
- });
12940
- }
13434
+ specifications = this.config.experimental.preParse ? await this.preParseSpecifications(specifications) : await this._shardSpecifications(specifications);
12941
13435
  // if run with --changed or --last-failed, don't exit if no tests are found
12942
13436
  if (!specifications.length) {
12943
13437
  await this._traces.$("vitest.test_run", async () => {
@@ -13066,7 +13560,8 @@ class Vitest {
13066
13560
  if (!this.isFirstRun && this._coverageOptions.cleanOnRerun) await this.coverageProvider?.clean();
13067
13561
  await this.initializeGlobalSetup(specs);
13068
13562
  try {
13069
- await this.pool.runTests(specs, invalidates);
13563
+ const sorted = await this.getSequencer().sort(specs);
13564
+ await this.pool.runTests(sorted, invalidates);
13070
13565
  } catch (err) {
13071
13566
  this.state.catchError(err, "Unhandled Error");
13072
13567
  }
@@ -13135,6 +13630,23 @@ class Vitest {
13135
13630
  return this.parseSpecifications(specifications, options);
13136
13631
  }
13137
13632
  async parseSpecifications(specifications, options) {
13633
+ return (await this.parseFiles(specifications, options)).map((file, index) => {
13634
+ this.state.collectFiles(specifications[index].project, [file]);
13635
+ return this.state.getReportedEntity(file);
13636
+ });
13637
+ }
13638
+ async preParseSpecifications(specifications) {
13639
+ const files = await this.parseFiles(specifications);
13640
+ const runnable = specifications.filter((_, index) => files[index].mode !== "skip");
13641
+ const sharded = await this._shardSpecifications(runnable);
13642
+ const inShard = new Set(sharded);
13643
+ specifications.forEach((specification, index) => {
13644
+ // files of other shards are not part of this run
13645
+ if (files[index].mode === "skip" || inShard.has(specification)) this.state.collectFiles(specification.project, [files[index]]);
13646
+ });
13647
+ return sharded;
13648
+ }
13649
+ async parseFiles(specifications, options) {
13138
13650
  const concurrency = options?.concurrency ?? (typeof os__default.availableParallelism === "function" ? os__default.availableParallelism() : os__default.cpus().length);
13139
13651
  const limit = limitConcurrency(concurrency);
13140
13652
  // Phase 1: parse all files in parallel (without mode interpretation)
@@ -13152,9 +13664,8 @@ class Vitest {
13152
13664
  for (const { file, specification } of results) {
13153
13665
  const config = specification.project.config;
13154
13666
  interpretTaskModes(file, config.testNamePattern, specification.testLines, specification.testIds, specification.testNames, tagsFilter, globalHasOnly, false, config.allowOnly);
13155
- this.state.collectFiles(specification.project, [file]);
13156
13667
  }
13157
- return results.map(({ file }) => this.state.getReportedEntity(file));
13668
+ return results.map(({ file }) => file);
13158
13669
  }
13159
13670
  async experimental_parseSpecification(specification) {
13160
13671
  const file = await astCollectTests(specification.project, specification.moduleId).catch((error) => {
@@ -13189,7 +13700,8 @@ class Vitest {
13189
13700
  this.state.clearErrors();
13190
13701
  await this.initializeGlobalSetup(specifications);
13191
13702
  try {
13192
- await this.pool.collectTests(specifications, invalidates);
13703
+ const sorted = await this.getSequencer().sort(specifications);
13704
+ await this.pool.collectTests(sorted, invalidates);
13193
13705
  } catch (err) {
13194
13706
  this.state.catchError(err, "Unhandled Error");
13195
13707
  }
@@ -13220,6 +13732,20 @@ class Vitest {
13220
13732
  await this.cancelPromise.finally(() => this.cancelPromise = void 0);
13221
13733
  await this.runningPromise;
13222
13734
  }
13735
+ getSequencer() {
13736
+ if (!this.sequencer) {
13737
+ const Sequencer = this.config.sequence.sequencer;
13738
+ this.sequencer = new Sequencer(this);
13739
+ }
13740
+ return this.sequencer;
13741
+ }
13742
+ /** @internal */
13743
+ async _shardSpecifications(specifications) {
13744
+ const shard = this.config.shard;
13745
+ if (!shard) return specifications;
13746
+ if (!this.config.passWithNoTests && shard.count > specifications.length) throw new Error(`--shard <count> must be a smaller than count of test files. Resolved ${specifications.length} test files for --shard=${shard.index}/${shard.count}.`);
13747
+ return this.getSequencer().shard(Array.from(specifications));
13748
+ }
13223
13749
  async initializeGlobalSetup(paths) {
13224
13750
  const projects = new Set(paths.map((spec) => spec.project));
13225
13751
  const coreProject = this.getRootProject();
@@ -13382,6 +13908,9 @@ class Vitest {
13382
13908
  */
13383
13909
  invalidateFile(filepath) {
13384
13910
  this.specifications.invalidateDocblock(filepath);
13911
+ // during `vitest run` the browser takes modules from its HTTP cache without asking the
13912
+ // server, so the browser pool opens new contexts before the next run
13913
+ if (!this.config.watch) this._browserCacheStale = true;
13385
13914
  this.projects.forEach(({ vite }) => {
13386
13915
  Object.values(vite.environments).forEach((environment) => {
13387
13916
  const { moduleGraph } = environment;
@@ -13589,7 +14118,7 @@ async function createVitest(modeOrOptions, optionsOrViteOverrides = {}, viteOver
13589
14118
  const logger = new Logger(vitestOptions.stdout, vitestOptions.stderr);
13590
14119
  const packageInstaller = vitestOptions.packageInstaller ?? new VitestPackageInstaller();
13591
14120
  const pluginHarness = new PluginHarness(logger, packageInstaller);
13592
- const config = await resolveConfig$1(options, viteOverrides, pluginHarness);
14121
+ const config = await resolveConfig$1(options, viteOverrides, pluginHarness, vitestOptions.cliFilters);
13593
14122
  const vitest = new Vitest(pluginHarness, config);
13594
14123
  try {
13595
14124
  await vitest._start(config);
@@ -13603,6 +14132,288 @@ catch (error) {
13603
14132
  }
13604
14133
  }
13605
14134
 
14135
+ function isCancelAction(str, key) {
14136
+ return str === "" || str === "\x1B" || !!key && key.ctrl === true && key.name === "c";
14137
+ }
14138
+
14139
+ class SnapshotReviewer {
14140
+ ctx;
14141
+ snapshots;
14142
+ #updates = {
14143
+ approved: [],
14144
+ rejected: []
14145
+ };
14146
+ constructor(ctx) {
14147
+ this.ctx = ctx;
14148
+ this.snapshots = this.#collectSnapshots();
14149
+ }
14150
+ #collectSnapshots() {
14151
+ const failedSnapshots = [];
14152
+ for (const files of this.ctx.state.getFiles()) {
14153
+ const project = this.ctx.getProjectByName(files.projectName ?? "");
14154
+ if (project.config.snapshotEnvironment !== void 0) continue;
14155
+ for (const test of getTests(files)) {
14156
+ if (test.result?.errors === void 0) continue;
14157
+ for (const error of test.result.errors) {
14158
+ const reviewableSnapshot = getReviewableSnapshot(error);
14159
+ if (reviewableSnapshot === null) continue;
14160
+ failedSnapshots.push({
14161
+ ...reviewableSnapshot,
14162
+ test,
14163
+ project
14164
+ });
14165
+ }
14166
+ }
14167
+ }
14168
+ return failedSnapshots;
14169
+ }
14170
+ #approve = (snapshot) => {
14171
+ this.#updates.approved.push(snapshot);
14172
+ };
14173
+ #reject = (snapshot) => {
14174
+ this.#updates.rejected.push(snapshot);
14175
+ };
14176
+ #review = async (render) => {
14177
+ for (const [index, snapshot] of this.snapshots.entries()) {
14178
+ const update = {
14179
+ ...snapshot.errorMeta.update,
14180
+ meta: { test: snapshot.test }
14181
+ };
14182
+ await render({
14183
+ snapshot,
14184
+ stats: {
14185
+ index,
14186
+ length: this.snapshots.length
14187
+ }
14188
+ }, () => this.#approve(update), () => this.#reject(update));
14189
+ }
14190
+ };
14191
+ async #updateSnapshots() {
14192
+ const snapshotEnvironment = await this.getEnvironment();
14193
+ const snapshotUpdates = /* @__PURE__ */ new Map([[snapshotEnvironment, this.#updates.approved]]);
14194
+ return saveSnapshotUpdates(snapshotUpdates);
14195
+ }
14196
+ async startReview() {
14197
+ this.ctx.watcher.unregisterWatcher();
14198
+ const tracker = this.ctx.watcher.createTracker();
14199
+ try {
14200
+ await this.collectReviews(this.#review);
14201
+ const fileUpdates = new Set(this.#updates.approved.map(({ file }) => file));
14202
+ const fsEvents = Promise.all(Array.from(fileUpdates).map((file) => tracker.track(file, {
14203
+ type: "change",
14204
+ timeout: 500
14205
+ })));
14206
+ await this.#updateSnapshots();
14207
+ for (const file of fileUpdates) {
14208
+ this.ctx.logger.clearHighlightCache(file);
14209
+ this.ctx.invalidateFile(file);
14210
+ }
14211
+ // @todo what should happen when there's no approved updates?
14212
+ await this.ctx.rerunFiles(Array.from(new Set(this.#updates.approved.map(({ meta }) => meta.test.file.filepath))), "interactive review done");
14213
+ // wait for fs events before enabling the watcher to not cause another re-run
14214
+ // in case some have not been dispatched/consumed yet
14215
+ await fsEvents;
14216
+ } catch (error) {
14217
+ console.error(error);
14218
+ } finally {
14219
+ tracker.stop();
14220
+ this.ctx.watcher.registerWatcher();
14221
+ }
14222
+ }
14223
+ get hasReviewableSnapshots() {
14224
+ return this.snapshots.length > 0;
14225
+ }
14226
+ }
14227
+ function getReviewableSnapshot(error) {
14228
+ const errorMeta = error.__vitest_error_context__?.meta;
14229
+ if (typeof error.diff !== "string" || !isMatchMeta(errorMeta)) return null;
14230
+ return {
14231
+ error: { diff: error.diff },
14232
+ errorMeta,
14233
+ frame: error.stacks?.[0] ?? null
14234
+ };
14235
+ }
14236
+ function isMatchMeta(meta) {
14237
+ return meta !== void 0 && Reflect.get(meta, "type") === "snapshot" && "update" in meta;
14238
+ }
14239
+ const REVIEW_KEYS = [[
14240
+ "a",
14241
+ "green",
14242
+ "accept",
14243
+ "keep the new snapshot"
14244
+ ], [
14245
+ "r",
14246
+ "red",
14247
+ "reject",
14248
+ "retain the old snapshot"
14249
+ ]];
14250
+ const REVIEW_DESCRIPTION_PADDING = Math.max(...REVIEW_KEYS.map((k) => k[2].length)) + 2;
14251
+ const REVIEW_KEYS_HELP = `\n${REVIEW_KEYS.map(([key, color, meaning, description]) => ` ${$[color](key)} ${$.reset(meaning)}${" ".repeat(REVIEW_DESCRIPTION_PADDING - meaning.length)}${$.dim(description)}`).join("\n")}\n`;
14252
+ class NodeSnapshotReviewer extends SnapshotReviewer {
14253
+ #stdin;
14254
+ #stdout;
14255
+ #snapshotEnvironment = void 0;
14256
+ constructor(ctx, stdin, stdout) {
14257
+ super(ctx);
14258
+ this.#stdin = stdin;
14259
+ this.#stdout = stdout;
14260
+ }
14261
+ async getEnvironment() {
14262
+ if (this.#snapshotEnvironment === void 0) this.#snapshotEnvironment = new (await (import('./node.B9mkVmLH.js'))).VitestNodeSnapshotEnvironment();
14263
+ return this.#snapshotEnvironment;
14264
+ }
14265
+ async collectReviews(review) {
14266
+ const controls = this.#handleKeypress();
14267
+ try {
14268
+ await review(async ({ snapshot: { error, errorMeta, frame, project, test }, stats }, approve, reject) => {
14269
+ const { update } = errorMeta;
14270
+ // undo `column--` from `SnapshotState` to match the error's stack frame
14271
+ const source = update.type === "inline" ? {
14272
+ ...update,
14273
+ column: update.column + 1
14274
+ } : frame;
14275
+ this.ctx.logger.clearFullScreen();
14276
+ this.#stdout.write([
14277
+ $.bold(`Reviewing [${$.yellow(`${stats.index + 1}/${stats.length}`)}]`) + (project.name ? ` ${formatProjectName(project, ":")}` : ":"),
14278
+ source && `Source: ${$.cyan(`${relative(project.config.root, source.file)}${$.dim(`:${source.line}:${source.column}`)}`)} ${$.dim(`(${test.fullTestName})`)}`,
14279
+ `Snapshot: ${$.yellow(errorMeta.key)}`,
14280
+ update.type !== "inline" && `Snapshot file: ${$.cyan(relative(project.config.root, update.file))}`,
14281
+ formatDiff(error.diff),
14282
+ REVIEW_KEYS_HELP
14283
+ ].filter(Boolean).join("\n"));
14284
+ switch (await controls.waitForAction()) {
14285
+ case "approved":
14286
+ approve();
14287
+ break;
14288
+ case "rejected": reject();
14289
+ }
14290
+ });
14291
+ this.ctx.logger.clearFullScreen();
14292
+ } catch (error) {
14293
+ controls.cleanup();
14294
+ // `waitForAction` can reject when pressing cancel keys, no need to log that
14295
+ if (error) console.error(error);
14296
+ await this.ctx.exit(true);
14297
+ }
14298
+ controls.cleanup();
14299
+ }
14300
+ #handleKeypress() {
14301
+ let resolvers;
14302
+ const rl = readline.createInterface({
14303
+ input: this.#stdin,
14304
+ escapeCodeTimeout: 50
14305
+ });
14306
+ readline.emitKeypressEvents(this.#stdin, rl);
14307
+ if (this.#stdin.isTTY) this.#stdin.setRawMode(true);
14308
+ this.#stdin.on("keypress", handler);
14309
+ const cleanup = () => {
14310
+ rl.close();
14311
+ this.#stdin.removeListener("keypress", handler);
14312
+ if (this.#stdin.isTTY) this.#stdin.setRawMode(false);
14313
+ };
14314
+ function handler(str, key) {
14315
+ if (resolvers === void 0) return;
14316
+ const currentResolvers = resolvers;
14317
+ // reset the resolvers so a cancel key string won't change the exit code without rejecting
14318
+ resolvers = void 0;
14319
+ if (isCancelAction(str, key)) {
14320
+ process.exitCode = 130;
14321
+ cleanup();
14322
+ return currentResolvers.reject();
14323
+ }
14324
+ switch (key.name) {
14325
+ // accept
14326
+ case "a":
14327
+ currentResolvers.resolve("approved");
14328
+ break;
14329
+ // reject
14330
+ case "r":
14331
+ currentResolvers.resolve("rejected");
14332
+ break;
14333
+ // ignore other keys
14334
+ default:
14335
+ // restore resolvers as we didn't resolve the promise
14336
+ resolvers = currentResolvers;
14337
+ }
14338
+ }
14339
+ return {
14340
+ waitForAction() {
14341
+ resolvers = Promise.withResolvers();
14342
+ return resolvers.promise;
14343
+ },
14344
+ cleanup
14345
+ };
14346
+ }
14347
+ }
14348
+ const DIFF_HEADER = `${$.green("- Expected")}\n${$.red("+ Received")}`;
14349
+ const SEPARATOR_H = "─";
14350
+ const SEPARATOR_V = "│";
14351
+ const JUNCTION_T = "┬";
14352
+ const JUNCTION_M = "┼";
14353
+ const JUNCTION_B = "┴";
14354
+ const DIFF_COL_WIDTH = 5;
14355
+ const HUNK_RE = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
14356
+ function formatDiff(diff) {
14357
+ const width = getCols();
14358
+ let oldLine = 0;
14359
+ let newLine = 0;
14360
+ let inHunk = false;
14361
+ const separatorLeft = 12;
14362
+ const separatorRight = Math.max(0, width - separatorLeft - 1);
14363
+ const separator = `${SEPARATOR_H.repeat(separatorLeft)}${JUNCTION_M}${SEPARATOR_H.repeat(separatorRight)}`;
14364
+ const lines = normalizeDiff(diff);
14365
+ return [
14366
+ SEPARATOR_H.repeat(width),
14367
+ DIFF_HEADER,
14368
+ lines.map((line, index) => {
14369
+ const plain = stripVTControlCharacters(line);
14370
+ const hunk = HUNK_RE.exec(plain);
14371
+ if (hunk) {
14372
+ oldLine = Number(hunk[1]);
14373
+ newLine = Number(hunk[2]);
14374
+ inHunk = true;
14375
+ if (index === 0) return `${SEPARATOR_H.repeat(separatorLeft)}${JUNCTION_T}${SEPARATOR_H.repeat(separatorRight)}`;
14376
+ return separator;
14377
+ }
14378
+ if (!inHunk) return line;
14379
+ switch (plain[0]) {
14380
+ case "-": return `${padLineNumber(oldLine++, $.green)} ${padLineNumber()} ${SEPARATOR_V}${line}`;
14381
+ case "+": return `${padLineNumber()} ${padLineNumber(newLine++, $.red)} ${SEPARATOR_V}${line}`;
14382
+ default: return `${padLineNumber(oldLine++)} ${padLineNumber(newLine++)} ${SEPARATOR_V}${line}`;
14383
+ }
14384
+ }).join("\n"),
14385
+ `${SEPARATOR_H.repeat(separatorLeft)}${JUNCTION_B}${SEPARATOR_H.repeat(separatorRight)}`
14386
+ ].join("\n");
14387
+ }
14388
+ const INLINE_RE = /(Expected|Received):\s/;
14389
+ function inlineValue(raw) {
14390
+ return raw.replace(INLINE_RE, "");
14391
+ }
14392
+ const DIFF_START = 3;
14393
+ const EXPECTED_SYMBOL = $.green("-");
14394
+ const RECEIVED_SYMBOL = $.red("+");
14395
+ function normalizeDiff(input) {
14396
+ const lines = input.split(/\r?\n/);
14397
+ const plain = lines.slice(0, 2).map(stripVTControlCharacters);
14398
+ // Inline `Expected: "..." / Received: "..."`
14399
+ if (plain[0]?.startsWith("Expected:") && plain[1]?.startsWith("Received:")) return [
14400
+ "@@ -1 +1 @@",
14401
+ `${EXPECTED_SYMBOL} ${inlineValue(lines[0])}`,
14402
+ `${RECEIVED_SYMBOL} ${inlineValue(lines[1])}`
14403
+ ];
14404
+ // Diff without hunk headers
14405
+ if (!(typeof lines[DIFF_START] === "string" && HUNK_RE.test(stripVTControlCharacters(lines[DIFF_START]))) && plain[0] === "- Expected" && plain[1] === "+ Received") {
14406
+ lines.splice(0, DIFF_START, "@@ -1 +1 @@");
14407
+ return lines;
14408
+ }
14409
+ // Diff with hunk headers
14410
+ return lines.slice(DIFF_START);
14411
+ }
14412
+ function padLineNumber(line, color = $.white) {
14413
+ if (line === void 0) return " ".repeat(DIFF_COL_WIDTH);
14414
+ return $.dim(color(String(line).padStart(DIFF_COL_WIDTH)));
14415
+ }
14416
+
13606
14417
  const MAX_RESULT_COUNT = 10;
13607
14418
  const SELECTION_MAX_INDEX = 7;
13608
14419
  const ESC = "\x1B[";
@@ -13734,6 +14545,7 @@ const keys = [
13734
14545
  ["r", "rerun current pattern tests"],
13735
14546
  ["f", "rerun only failed tests"],
13736
14547
  ["u", "update snapshot"],
14548
+ ["i", "interactively review snapshot fails"],
13737
14549
  ["p", "filter by a filename"],
13738
14550
  ["t", "filter by a test name regex pattern"],
13739
14551
  ["w", "filter by a project name"],
@@ -13781,7 +14593,7 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout) {
13781
14593
  async function _keypressHandler(str, key) {
13782
14594
  // Cancel run and exit when ctrl-c or esc is pressed.
13783
14595
  // If cancelling takes long and key is pressed multiple times, exit forcefully.
13784
- if (str === "" || str === "\x1B" || key && key.ctrl && key.name === "c") {
14596
+ if (isCancelAction(str, key)) {
13785
14597
  if (!ctx.isCancelling) {
13786
14598
  ctx.logger.log($.red("Cancelling test run. Press CTRL+c again to exit forcefully.\n"));
13787
14599
  process.exitCode = 130;
@@ -13799,7 +14611,7 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout) {
13799
14611
  }
13800
14612
  const name = key?.name;
13801
14613
  if (ctx.runningPromise) {
13802
- if (cancelKeys.includes(name)) await ctx.cancelCurrentRun("keyboard-input");
14614
+ if (name && cancelKeys.includes(name)) await ctx.cancelCurrentRun("keyboard-input");
13803
14615
  return;
13804
14616
  }
13805
14617
  // quit
@@ -13808,6 +14620,8 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout) {
13808
14620
  if (name === "h") return printShortcutsHelp();
13809
14621
  // update snapshot
13810
14622
  if (name === "u") return ctx.updateSnapshot();
14623
+ // interactive review
14624
+ if (name === "i") return reviewSnapshots();
13811
14625
  // rerun all tests
13812
14626
  if (name === "a" || name === "return") {
13813
14627
  const files = await ctx._globTestFilepaths();
@@ -13827,6 +14641,13 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout) {
13827
14641
  async function keypressHandler(str, key) {
13828
14642
  await _keypressHandler(str, key);
13829
14643
  }
14644
+ async function reviewSnapshots() {
14645
+ off();
14646
+ const snapshotReviewer = new NodeSnapshotReviewer(ctx, stdin, stdout);
14647
+ if (snapshotReviewer.hasReviewableSnapshots) await snapshotReviewer.startReview();
14648
+ else ctx.logger.log($.yellow(`No snapshots to review. ${$.dim("Press ") + $.bold("r") + $.dim(" to run tests again.")}\n`));
14649
+ on();
14650
+ }
13830
14651
  async function inputNamePattern() {
13831
14652
  off();
13832
14653
  const filter = await new WatchFilter("Input test name pattern (RegExp)", stdin, stdout).filter((str) => {
@@ -13984,7 +14805,10 @@ async function prepareVitest(modeOrOptions, optionsOrViteOverrides, viteOverride
13984
14805
  if (options.standalone && (cliFilters?.length || 0) > 0) options.standalone = false;
13985
14806
  // this shouldn't affect _application root_ that can be changed inside config
13986
14807
  const root = resolve(options.root || process.cwd());
13987
- const ctx = await createVitest(options, viteOverrides, vitestOptions);
14808
+ const ctx = await createVitest(options, viteOverrides, {
14809
+ ...vitestOptions,
14810
+ cliFilters
14811
+ });
13988
14812
  const environmentPackage = getEnvPackageName(ctx.config.environment);
13989
14813
  if (environmentPackage && !await ctx.packageInstaller.ensureInstalled(environmentPackage, root)) {
13990
14814
  process.exitCode = 1;