vitest 5.1.0-beta.1 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/browser.d.ts +6 -5
  2. package/dist/browser.js +6 -6
  3. package/dist/chunks/{base.PJyN9N0u.js → base.Cof-UHJf.js} +14 -19
  4. package/dist/chunks/{browser.d.D7a15z82.d.ts → browser.d.C7tWgUvw.d.ts} +3 -3
  5. package/dist/chunks/{cac.Ccf5Je_F.js → cac.BYbt0aJp.js} +22 -20
  6. package/dist/chunks/{cli-api.DE22LIzq.js → cli-api.COfZo8lK.js} +714 -73
  7. package/dist/chunks/{config.d.BgktgHfG.d.ts → config.d.B3YV4t0O.d.ts} +37 -2
  8. package/dist/chunks/{console.DrMPSuFo.js → console.CQZ877Hi.js} +2 -2
  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.DHWmytIK.js} +10 -10
  12. package/dist/chunks/{doctor.CPlMs7-y.js → doctor.B-oPbwps.js} +2 -2
  13. package/dist/chunks/{environment.d.CbTLsZSj.d.ts → environment.d.BFQtFKdZ.d.ts} +1 -1
  14. package/dist/chunks/{globals.TipXUFcZ.js → globals.ZKtKSkEf.js} +6 -5
  15. package/dist/chunks/{index.BFXLpwll.js → index.Bi0NXYPf.js} +58 -32
  16. package/dist/chunks/{index.BXttT2gP.js → index.CZzC1gGg.js} +265 -425
  17. package/dist/chunks/{index.D14IAvnE.js → index.Di8au7q4.js} +68 -62
  18. package/dist/chunks/{index.B03wg4V0.js → index.w_oBZ9N8.js} +5 -5
  19. package/dist/chunks/{init-forks.BL1E3__4.js → init-forks.BaDXQSD8.js} +1 -1
  20. package/dist/chunks/{init-threads.CYXAGzKQ.js → init-threads.ZX_Vov0z.js} +1 -1
  21. package/dist/chunks/{init.DVorxUyL.js → init.CO4AB7HZ.js} +4 -4
  22. package/dist/chunks/{module-dependencies.CwNPkcV4.js → module-dependencies._2Eei3FO.js} +1 -1
  23. package/dist/chunks/{native.cdzHIdmv.js → native.upB-V0CK.js} +1 -1
  24. package/dist/chunks/{nativeModuleMocker.3uBcOd84.js → nativeModuleMocker.Dh5azSB4.js} +3 -3
  25. package/dist/chunks/{nativeModuleRunner.xi64Afb2.js → nativeModuleRunner.9xPIMzi7.js} +1 -1
  26. package/dist/chunks/{node.uQulW0ei.js → node.B9mkVmLH.js} +1 -1
  27. package/dist/chunks/{pathe.M-eThtNZ.Ba-7h1rE.js → pathe.M-eThtNZ.zq3TM4NT.js} +1 -1
  28. package/dist/chunks/{plugin.d.olEn8IL9.d.ts → plugin.d.LRFSN46m.d.ts} +90 -19
  29. package/dist/chunks/rawSnapshot.DqSiqIEx.js +356 -0
  30. package/dist/chunks/{resolver.CtCcxIy1.js → resolver.BzpmeQeT.js} +1 -1
  31. package/dist/chunks/{rpc.BV0XpJ5q.js → rpc.Uhkwr2NM.js} +2 -2
  32. package/dist/chunks/{rpc.d.DGFP7vWr.d.ts → rpc.d.3FOhdFx8.d.ts} +1 -1
  33. package/dist/chunks/{run.BfrMbGVD.js → run.CjdgFZiW.js} +7 -4
  34. package/dist/chunks/{setup-common.llxJkJaD.js → setup-common.CqAQCXzx.js} +2 -2
  35. package/dist/chunks/{source-map.BjWcsIL9.js → source-map.DakdQc29.js} +11 -13
  36. package/dist/chunks/{source-map.d.C5A_Tr6V.d.ts → source-map.d.BkG8YK_3.d.ts} +1 -1
  37. package/dist/chunks/{task-utils.d.BUh7ylUT.d.ts → task-utils.d.D-gFPNFi.d.ts} +1 -1
  38. package/dist/chunks/{utils.DSfl_w8V.js → utils.BBk_icFG.js} +6 -3
  39. package/dist/chunks/{vm.Cwj01UFE.js → vm.b4MbCAJQ.js} +15 -13
  40. package/dist/chunks/{worker.d.gsA26mmR.d.ts → worker.d.CyJRpyfZ.d.ts} +3 -3
  41. package/dist/cli.js +2 -2
  42. package/dist/config.d.ts +8 -8
  43. package/dist/index.d.ts +17 -12
  44. package/dist/index.js +6 -5
  45. package/dist/module-evaluator.d.ts +2 -2
  46. package/dist/node.d.ts +10 -10
  47. package/dist/node.js +15 -13
  48. package/dist/runtime.d.ts +4 -4
  49. package/dist/runtime.js +4 -4
  50. package/dist/task-utils.js +7 -3
  51. package/dist/worker.d.ts +4 -4
  52. package/dist/worker.js +14 -13
  53. package/dist/workers/forks.js +15 -14
  54. package/dist/workers/runVmTests.js +13 -10
  55. package/dist/workers/threads.js +15 -14
  56. package/dist/workers/vmForks.js +10 -10
  57. package/dist/workers/vmThreads.js +10 -10
  58. package/package.json +15 -15
@@ -1,12 +1,12 @@
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 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.Di8au7q4.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.DakdQc29.js';
9
+ import { v as version } from './cac.BYbt0aJp.js';
10
10
  import { performance as performance$1 } from 'node:perf_hooks';
11
11
  import { c as createBirpc } from './index.DmDMHCg8.js';
12
12
  import require$$0$3 from 'events';
@@ -25,25 +25,55 @@ import { A as API_PATH, d as defaultBrowserPort } from './constants.DLYM6cZY.js'
25
25
  import { i as isBuiltin } from './modules.BJuCwlRJ.js';
26
26
  import crypto, { 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 { A as limitConcurrency, B as createTagsFilter } from './run.CjdgFZiW.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 countTestErrors, k as errorBanner, l as divider, m as F_RIGHT, o as getCols } from './utils.BBk_icFG.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.DqSiqIEx.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;
@@ -5175,19 +5205,18 @@ function getTestFileEnvironment(project, testFile, browser = false) {
5175
5205
 
5176
5206
  async function getModuleGraph(ctx, projectName, testFilePath, viteEnvironment) {
5177
5207
  const project = ctx.getProjectByName(projectName);
5178
- const collector = createModuleGraphCollector(project, getModuleGraphEnvironment(project, testFilePath, viteEnvironment));
5208
+ const environment = findModuleGraphEnvironment(project, testFilePath, viteEnvironment);
5209
+ if (!environment) throw new Error(`Cannot find environment for ${testFilePath}`);
5210
+ const collector = createModuleGraphCollector(project, environment);
5179
5211
  const roots = collector.add(testFilePath);
5180
5212
  return {
5181
5213
  modules: collector.data.modules,
5182
5214
  roots
5183
5215
  };
5184
5216
  }
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;
5217
+ function findModuleGraphEnvironment(project, testFilePath, viteEnvironment) {
5218
+ if (viteEnvironment) return project.vite.environments[viteEnvironment];
5219
+ return project.config.experimental.viteModuleRunner === false ? project.vite.environments.__vitest__ : getTestFileEnvironment(project, testFilePath, project.config.browser.enabled);
5191
5220
  }
5192
5221
  function createModuleGraphCollector(project, environment) {
5193
5222
  const data = {
@@ -5274,7 +5303,14 @@ catch {}
5274
5303
  }
5275
5304
 
5276
5305
  function setup(ctx, _server) {
5277
- const wss = new WebSocketServer({ noServer: true });
5306
+ const wss = new WebSocketServer({
5307
+ noServer: true,
5308
+ // Emit one message per event loop, allowing the server to fairly distribute
5309
+ // received messages from clients in the main thread.
5310
+ // Otherwise, a client that floods its connection will saturate the main thread,
5311
+ // delaying message handling, leading to timeouts.
5312
+ allowSynchronousEvents: false
5313
+ });
5278
5314
  const clients = /* @__PURE__ */ new Map();
5279
5315
  (_server || ctx.vite).httpServer?.on("upgrade", (request, socket, head) => {
5280
5316
  if (!request.url) return;
@@ -5768,9 +5804,12 @@ class ProjectGraph {
5768
5804
  const imports = /* @__PURE__ */ new Set([...transformed.deps || [], ...transformed.dynamicDeps || []]);
5769
5805
  const dependencies = [];
5770
5806
  const watchedFiles = [];
5807
+ let failed = false;
5771
5808
  // ids keep the query, so `./file.txt?raw` is walked as its own module
5772
5809
  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);
5810
+ // a dynamic import of a missing file can be caught, a static one always fails
5811
+ if (isMissingFile(imported) && transformed.deps?.includes(imported.url)) failed = true;
5812
+ else if (imported.id && imported.file && this.resolver.isLocalSourceFile(imported.file)) (imports.has(imported.url) ? dependencies : watchedFiles).push(imported.id);
5774
5813
  });
5775
5814
  [...redirects, ...restored].forEach((file) => {
5776
5815
  if (this.resolver.isLocalSourceFile(file) && !dependencies.includes(file)) dependencies.push(file);
@@ -5779,10 +5818,15 @@ class ProjectGraph {
5779
5818
  dependencies,
5780
5819
  watchedFiles,
5781
5820
  mocked: new Set(Array.from(replaced, (mockedId) => cleanUrl(mockedId))),
5782
- restored: new Set(Array.from(restored, (restoredId) => cleanUrl(restoredId)))
5821
+ restored: new Set(Array.from(restored, (restoredId) => cleanUrl(restoredId))),
5822
+ failed
5783
5823
  };
5784
5824
  }
5785
5825
  }
5826
+ // in SSR, Vite keeps an import it can't resolve as is, a bare one can still be loaded by Node
5827
+ function isMissingFile(mod) {
5828
+ return mod.id?.[0] === "." || mod.meta?.["vite:alias"]?.noResolved === true;
5829
+ }
5786
5830
  /**
5787
5831
  * Walks the module graph once for every root, skipping a module only when every walk that reaches it mocks it.
5788
5832
  */
@@ -5911,7 +5955,7 @@ class FileSystemModuleCache {
5911
5955
  */
5912
5956
  rootCache;
5913
5957
  metadataFilePath;
5914
- version = "1.0.0-beta.8";
5958
+ version = "1.0.0-beta.9";
5915
5959
  fsCacheRoots = /* @__PURE__ */ new WeakMap();
5916
5960
  fsEnvironmentHashMap = /* @__PURE__ */ new WeakMap();
5917
5961
  fsCacheKeyGenerators = /* @__PURE__ */ new WeakMap();
@@ -5949,10 +5993,7 @@ class FileSystemModuleCache {
5949
5993
  const fsCachePaths = [this.rootCache, ...this.vitest.projects.map((r) => r.config.fsModuleCachePath || this.rootCache)];
5950
5994
  const uniquePaths = Array.from(new Set(fsCachePaths));
5951
5995
  uniquePaths.forEach(forgetCacheDirTag);
5952
- await Promise.all(uniquePaths.map((directory) => rm(directory, {
5953
- force: true,
5954
- recursive: true
5955
- })));
5996
+ await Promise.all(uniquePaths.map((directory) => removeDirectory(directory)));
5956
5997
  if (log) this.vitest.logger.log(`[cache] cleared fs module cache at ${uniquePaths.join(", ")}`);
5957
5998
  }
5958
5999
  readCachedFileConcurrently(cachedFilePath) {
@@ -5989,13 +6030,15 @@ class FileSystemModuleCache {
5989
6030
  moduleType: meta.moduleType,
5990
6031
  deps: meta.deps,
5991
6032
  dynamicDeps: meta.dynamicDeps,
5992
- staticMocks: meta.staticMocks
6033
+ staticMocks: meta.staticMocks,
6034
+ hasCoverageData: meta.hasCoverageData,
6035
+ coverageData: meta.hasCoverageData ? await readCoverageData(cachedFilePath) : void 0
5993
6036
  };
5994
6037
  }
5995
6038
  async saveCachedModule(cachedFilePath, fetchResult, transformResult, imports = {
5996
6039
  urls: [],
5997
6040
  ids: {}
5998
- }, mappings = false) {
6041
+ }, mappings = false, coverageData) {
5999
6042
  if ("code" in fetchResult) {
6000
6043
  const result = {
6001
6044
  file: fetchResult.file,
@@ -6005,12 +6048,24 @@ class FileSystemModuleCache {
6005
6048
  moduleType: fetchResult.moduleType,
6006
6049
  deps: transformResult?.deps,
6007
6050
  dynamicDeps: transformResult?.dynamicDeps,
6008
- staticMocks: transformResult?.__vitestStaticMocks
6051
+ staticMocks: transformResult?.__vitestStaticMocks,
6052
+ hasCoverageData: coverageData !== void 0
6009
6053
  };
6010
6054
  debugFs?.(`${$.yellow("[write]")} ${fetchResult.id} is cached in ${cachedFilePath}`);
6011
- await atomicWriteFile(cachedFilePath, `${fetchResult.code}${cacheComment}${this.toBase64(result)}`);
6055
+ await Promise.all([result.hasCoverageData && atomicWriteFile(getCoverageDataPath(cachedFilePath), JSON.stringify(coverageData)), atomicWriteFile(cachedFilePath, `${fetchResult.code}${cacheComment}${this.toBase64(result)}`)]);
6012
6056
  }
6013
6057
  }
6058
+ getCoverageData(environment, id) {
6059
+ const coverageProvider = this.vitest.coverageProvider;
6060
+ if (!this.vitest.config.coverage.enabled || !coverageProvider?.requiresTransform?.(id)) return;
6061
+ return coverageProvider.getModuleCacheData?.(environment, id);
6062
+ }
6063
+ /**
6064
+ * Passes the data of the coverage provider back to it when the cached module is used
6065
+ */
6066
+ restoreCoverageData(environment, id, data) {
6067
+ this.vitest.coverageProvider?.restoreModuleCacheData?.(environment, id, data);
6068
+ }
6014
6069
  toBase64(obj) {
6015
6070
  const json = stringify(obj);
6016
6071
  return Buffer.from(json).toString("base64");
@@ -6033,12 +6088,29 @@ class FileSystemModuleCache {
6033
6088
  else if (result === null) debugMemory?.(`${$.green("[read]")} ${id} was bailed out`);
6034
6089
  return result;
6035
6090
  }
6091
+ /** Returns null when the cache directory cannot be created. */
6092
+ getCacheRoot(vitestConfig) {
6093
+ if (this.fsCacheRoots.has(vitestConfig)) return this.fsCacheRoots.get(vitestConfig) ?? null;
6094
+ let cacheRoot = vitestConfig.fsModuleCachePath || this.rootCache;
6095
+ try {
6096
+ mkdirSync(cacheRoot, { recursive: true });
6097
+ tagCacheDir(cacheRoot);
6098
+ } catch (error) {
6099
+ const reason = error instanceof Error ? error.message : String(error);
6100
+ 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.`));
6101
+ cacheRoot = null;
6102
+ }
6103
+ this.fsCacheRoots.set(vitestConfig, cacheRoot);
6104
+ return cacheRoot;
6105
+ }
6036
6106
  generateCachePath(vitestConfig, environment, id, fileContent) {
6037
- // bail out if file has import.meta.glob because it depends on other files
6107
+ const cacheRoot = this.getCacheRoot(vitestConfig);
6108
+ if (cacheRoot == null) return null;
6109
+ // bail out if file has a glob import because it depends on other files
6038
6110
  // TODO: figure out a way to still support it
6039
- if (fileContent.includes("import.meta.glob(")) {
6111
+ if (hasGlobImport(fileContent, environment.config.consumer)) {
6040
6112
  this.saveMemoryCache(environment, id, null);
6041
- debugMemory?.(`${$.yellow("[write]")} ${id} was bailed out because it has "import.meta.glob"`);
6113
+ debugMemory?.(`${$.yellow("[write]")} ${id} was bailed out because it has a glob import`);
6042
6114
  return null;
6043
6115
  }
6044
6116
  let hashString = "";
@@ -6058,7 +6130,8 @@ class FileSystemModuleCache {
6058
6130
  const config = environment.config;
6059
6131
  // coverage provider is dynamic, so we also clear the whole cache if
6060
6132
  // vitest.enableCoverage/vitest.disableCoverage is called
6061
- const coverageAffectsCache = String(this.vitest.config.coverage.enabled && this.vitest.coverageProvider?.requiresTransform?.(id));
6133
+ const coverageProvider = this.vitest.coverageProvider;
6134
+ const coverageAffectsCache = this.vitest.config.coverage.enabled && coverageProvider?.requiresTransform?.(id) ? `${coverageProvider.name}@${coverageProvider.version}` : "false";
6062
6135
  let environmentHash = this.fsEnvironmentHashMap.get(environment);
6063
6136
  if (!environmentHash) {
6064
6137
  const cacheConfig = JSON.stringify({
@@ -6086,15 +6159,12 @@ class FileSystemModuleCache {
6086
6159
  environmentHash = hash("sha1", (process.env.NODE_ENV ?? "") + this.version + cacheConfig, "hex");
6087
6160
  this.fsEnvironmentHashMap.set(environment, environmentHash);
6088
6161
  }
6089
- hashString += id + fileContent + environmentHash + coverageAffectsCache;
6162
+ // cached code imports optimized deps from `cacheDir` with `?v=<browserHash>`;
6163
+ // read live because the optimizer can re-run after `environmentHash` is memoized
6164
+ const depsOptimizer = environment.depsOptimizer;
6165
+ const optimizerHash = depsOptimizer ? environment.config.cacheDir + depsOptimizer.metadata.browserHash : "";
6166
+ hashString += id + fileContent + environmentHash + coverageAffectsCache + optimizerHash;
6090
6167
  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
6168
  const fsResultPath = join(cacheRoot, cacheKey);
6099
6169
  debugMemory?.(`${$.yellow("[write]")} ${id} generated a cache in ${fsResultPath}`);
6100
6170
  this.saveMemoryCache(environment, id, fsResultPath);
@@ -6179,6 +6249,26 @@ async function atomicWriteFile(realFilePath, data) {
6179
6249
  } catch {}
6180
6250
  }
6181
6251
  }
6252
+ async function removeDirectory(directory) {
6253
+ // parallel processes can clear the same cache at once; moving it away first
6254
+ // keeps their removal from racing with another process recreating it
6255
+ const detachedPath = `${directory}.tmp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6256
+ try {
6257
+ await rename(directory, detachedPath);
6258
+ } catch (error) {
6259
+ if (error?.code === "ENOENT") return;
6260
+ // Windows can refuse to rename a directory with open files
6261
+ await rm(directory, {
6262
+ force: true,
6263
+ recursive: true
6264
+ });
6265
+ return;
6266
+ }
6267
+ await rm(detachedPath, {
6268
+ force: true,
6269
+ recursive: true
6270
+ });
6271
+ }
6182
6272
  // lockfile hash resolution taken from vite
6183
6273
  // since this is experimental, we don't ask to expose it
6184
6274
  const lockfileFormats = [
@@ -6263,6 +6353,14 @@ function lookupFile(dir, fileNames) {
6263
6353
  dir = parentDir;
6264
6354
  }
6265
6355
  }
6356
+ // Vite expands these templates into `import.meta.glob` calls
6357
+ const dynamicImportTemplateRE = /\bimport\s*\(\s*`[^`]*\$\{/;
6358
+ const newUrlTemplateRE = /\bnew\s+URL\s*\(\s*`[^`]*\$\{[^`]*`\s*,\s*import\.meta\.url\b/;
6359
+ function hasGlobImport(code, consumer) {
6360
+ if (code.includes("import.meta.glob")) return true;
6361
+ if (!code.includes("${")) return false;
6362
+ return dynamicImportTemplateRE.test(code) || consumer === "client" && newUrlTemplateRE.test(code);
6363
+ }
6266
6364
  function tryReadFileSync(file) {
6267
6365
  try {
6268
6366
  return readFileSync(file, "utf-8");
@@ -6276,6 +6374,14 @@ function tryStatSync(file) {
6276
6374
  return fs__default.statSync(file, { throwIfNoEntry: false });
6277
6375
  } catch {}
6278
6376
  }
6377
+ async function readCoverageData(cachedFilePath) {
6378
+ try {
6379
+ return JSON.parse(await readFile(getCoverageDataPath(cachedFilePath), "utf-8"));
6380
+ } catch {}
6381
+ }
6382
+ function getCoverageDataPath(cachedFilePath) {
6383
+ return `${cachedFilePath}.coverage.json`;
6384
+ }
6279
6385
 
6280
6386
  const debug$1 = createDebugger("vitest:cache:results");
6281
6387
  const RESULTS_VERSION = 1;
@@ -8104,6 +8210,145 @@ function padBenchRow(row, widths) {
8104
8210
  return row.map((v, i) => i === 0 ? v.padEnd(widths[i]) : v.padStart(widths[i]));
8105
8211
  }
8106
8212
 
8213
+ function getTraceAttemptKey(trace) {
8214
+ return `${trace.repeats}:${trace.retry}`;
8215
+ }
8216
+ function groupTraceAttempts(traces) {
8217
+ const grouped = /* @__PURE__ */ new Map();
8218
+ for (const trace of traces) {
8219
+ const key = getTraceAttemptKey(trace);
8220
+ const group = grouped.get(key);
8221
+ if (group) group.push(trace);
8222
+ else grouped.set(key, [trace]);
8223
+ }
8224
+ const merged = /* @__PURE__ */ new Map();
8225
+ for (const [key, traces] of grouped) merged.set(key, {
8226
+ ...traces[0],
8227
+ entries: normalizeTraceEntries(traces.flatMap((trace) => trace.entries))
8228
+ });
8229
+ return merged;
8230
+ }
8231
+ function normalizeTraceEntries(entries) {
8232
+ const merged = [];
8233
+ const startMap = /* @__PURE__ */ new Map();
8234
+ const parents = [];
8235
+ for (const entry of entries) {
8236
+ const range = entry.range;
8237
+ if (!range) {
8238
+ merged.push({
8239
+ ...entry,
8240
+ depth: parents.length
8241
+ });
8242
+ continue;
8243
+ }
8244
+ if (range.phase === "start") {
8245
+ startMap.set(range.id, merged.length);
8246
+ merged.push({
8247
+ ...entry,
8248
+ depth: parents.length
8249
+ });
8250
+ parents.push(range.id);
8251
+ continue;
8252
+ }
8253
+ // when range.phase === 'end'
8254
+ const index = startMap.get(range.id);
8255
+ if (index == null) {
8256
+ // unpaired range shouldn't happen but just leave it there
8257
+ merged.push({
8258
+ ...entry,
8259
+ depth: 0
8260
+ });
8261
+ continue;
8262
+ }
8263
+ // Keep the start timestamp for positioning, but derive display duration
8264
+ // from the end event timestamp.
8265
+ const start = merged[index];
8266
+ merged[index] = {
8267
+ ...start,
8268
+ ...entry,
8269
+ startTime: start.startTime,
8270
+ duration: entry.startTime - start.startTime
8271
+ };
8272
+ parents.pop();
8273
+ }
8274
+ return merged;
8275
+ }
8276
+
8277
+ function formatTraceTimeline(artifacts, { retryIndex, repeatIndex }, root) {
8278
+ const traces = artifacts.flatMap((artifact) => artifact.type === "internal:browserTrace" ? [artifact.data] : []);
8279
+ const attempt = groupTraceAttempts(traces).get(getTraceAttemptKey({
8280
+ retry: retryIndex,
8281
+ repeats: repeatIndex
8282
+ }));
8283
+ if (!attempt) return;
8284
+ // the test end is already shown by the error location
8285
+ const visible = attempt.entries.filter((step) => step.name !== "vitest:onAfterRetryTask");
8286
+ if (!visible.length) return;
8287
+ const shown = visible.slice(-10);
8288
+ const prefixes = getTreePrefixes(shown);
8289
+ const headerRow = { cells: [
8290
+ "step",
8291
+ "locator",
8292
+ "start",
8293
+ "duration",
8294
+ "location"
8295
+ ] };
8296
+ const rows = [headerRow, ...shown.map((step, i) => formatStep(step, prefixes[i], root))];
8297
+ const widths = headerRow.cells.map((_, i) => Math.max(...rows.map((row) => row.cells[i].length)));
8298
+ const hasLocator = shown.some((step) => step.element?.locator);
8299
+ const lines = rows.map((row) => {
8300
+ // the last column is left unpadded so rows have no trailing spaces inside its color codes
8301
+ 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]));
8302
+ if (row === headerRow) {
8303
+ const locatorColumn = hasLocator ? `${locator} ` : "";
8304
+ return $.dim(` ${name} ${locatorColumn}${start} ${duration} ${location}`);
8305
+ }
8306
+ const text = ` ${name} ${hasLocator ? `${colorCell(locator, $.cyan)} ` : ""}${start} ${colorCell(duration)} ${colorCell(location, $.dim)}`;
8307
+ return row.status === "fail" ? $.red(text) : text;
8308
+ });
8309
+ const omitted = visible.length - shown.length;
8310
+ if (omitted) lines.splice(1, 0, $.dim(` ... ${omitted} earlier ${omitted === 1 ? "step" : "steps"}`));
8311
+ const header = [];
8312
+ if (attempt.retry) header.push(`retry ${attempt.retry}`);
8313
+ if (attempt.repeats) header.push(`repeat ${attempt.repeats}`);
8314
+ return [`\n${header.length ? `Trace (${header.join(", ")}):` : "Trace:"}`, ...lines].join("\n");
8315
+ }
8316
+ function getTreePrefixes(steps) {
8317
+ const hasNextSibling = steps.map((step, i) => {
8318
+ return steps.slice(i + 1).find((other) => other.depth <= step.depth)?.depth === step.depth;
8319
+ });
8320
+ const lastAtDepth = [];
8321
+ return steps.map((step, i) => {
8322
+ lastAtDepth[step.depth] = i;
8323
+ if (step.depth === 0) return "";
8324
+ let prefix = "";
8325
+ for (let level = 1; level < step.depth; level++) prefix += hasNextSibling[lastAtDepth[level]] ? "│ " : " ";
8326
+ return `${prefix}${hasNextSibling[i] ? F_TREE_NODE_MIDDLE : F_TREE_NODE_END} `;
8327
+ });
8328
+ }
8329
+ function formatStep(step, prefix, root) {
8330
+ const location = step.location && `${relative(root, step.location.file)}:${step.location.line}:${step.location.column}`;
8331
+ return {
8332
+ cells: [
8333
+ `${prefix}${formatStepName(step.name)}`,
8334
+ step.element?.locator || "-",
8335
+ `+${formatMs(step.startTime)}`,
8336
+ step.duration == null ? "-" : formatMs(step.duration),
8337
+ location || "-"
8338
+ ],
8339
+ status: step.status
8340
+ };
8341
+ }
8342
+ function colorCell(cell, format = (text) => text) {
8343
+ return cell.trim() === "-" ? $.dim(cell) : format(cell);
8344
+ }
8345
+ function formatMs(ms) {
8346
+ return `${Math.round(ms)}ms`;
8347
+ }
8348
+ function formatStepName(name) {
8349
+ return name.startsWith("vitest:") ? name.slice(7) : name;
8350
+ }
8351
+
8107
8352
  const BADGE_PADDING = " ";
8108
8353
  class BaseReporter {
8109
8354
  start = 0;
@@ -8347,8 +8592,10 @@ class BaseReporter {
8347
8592
  else if (this.ctx.isCancelling) this.log(withLabel("red", "CANCELLED", "Test run cancelled. Watching for file changes..."));
8348
8593
  else this.log(withLabel("green", "PASS", "Waiting for file changes..."));
8349
8594
  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"));
8595
+ if (hasFailedSnapshot(files)) {
8596
+ hints.unshift($.dim("press ") + $.bold($.yellow("u")) + $.dim(" to update snapshot"));
8597
+ hints.unshift($.dim("press ") + $.bold($.yellow("i")) + $.dim(" to review snapshot fails"));
8598
+ } else hints.push($.dim("press ") + $.bold("q") + $.dim(" to quit"));
8352
8599
  this.log(BADGE_PADDING + hints.join($.dim(", ")));
8353
8600
  }
8354
8601
  onWatcherRerun(files, trigger) {
@@ -8875,42 +9122,54 @@ class BaseReporter {
8875
9122
  const errorsQueue = [];
8876
9123
  for (const task of tasks)
8877
9124
  // Merge identical errors
8878
- task.result?.errors?.forEach((error) => {
9125
+ for (const { error, attempt } of getErrorsWithAttempt(task)) {
8879
9126
  let previous;
8880
- if (error?.stack) previous = errorsQueue.find((i) => {
8881
- if (i[0]?.stack !== error.stack || i[0]?.diff !== error.diff) return false;
9127
+ if (error.stack) previous = errorsQueue.find((item) => {
9128
+ if (item.error.stack !== error.stack || item.error.diff !== error.diff) return false;
9129
+ const itemTask = item.sources[0].task;
8882
9130
  const currentProjectName = task?.projectName || task.file?.projectName || "";
8883
- const projectName = i[1][0]?.projectName || i[1][0].file?.projectName || "";
9131
+ const projectName = itemTask?.projectName || itemTask.file?.projectName || "";
8884
9132
  const currentAnnotations = task.type === "test" && task.annotations;
8885
- const itemAnnotations = i[1][0].type === "test" && i[1][0].annotations;
9133
+ const itemAnnotations = itemTask.type === "test" && itemTask.annotations;
8886
9134
  return projectName === currentProjectName && deepEqual(currentAnnotations, itemAnnotations);
8887
9135
  });
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) {
9136
+ if (previous) previous.sources.push({
9137
+ task,
9138
+ attempt
9139
+ });
9140
+ else errorsQueue.push({
9141
+ error,
9142
+ sources: [{
9143
+ task,
9144
+ attempt
9145
+ }]
9146
+ });
9147
+ }
9148
+ for (const { error, sources } of errorsQueue) {
9149
+ const tasks = sources.map(({ task }) => task);
9150
+ const attemptsByTask = /* @__PURE__ */ new Map();
9151
+ for (const { task, attempt } of sources) attemptsByTask.set(task, [...attemptsByTask.get(task) ?? [], attempt]);
9152
+ const screenshotPaths = [...attemptsByTask].flatMap(([task, attempts]) => [...new Set(attempts)].flatMap((attempt) => attempt ? getFailureScreenshotPaths(task, attempt) : []));
9153
+ for (const [task, attempts] of attemptsByTask) {
8893
9154
  const filepath = task?.filepath || "";
8894
9155
  const projectName = task?.projectName || task.file?.projectName || "";
8895
9156
  const project = this.ctx.projects.find((p) => p.name === projectName);
8896
9157
  let name = this.getFullName(task, separator);
9158
+ const attemptLabel = formatErrorAttempts(task, attempts);
9159
+ if (attemptLabel) name += $.dim(` (${attemptLabel})`);
8897
9160
  if (filepath) name += $.dim(` [ ${this.relative(filepath)} ]`);
8898
9161
  const label = this.ctx.state.blobs && task.file?.meta?.__vitest_label__;
8899
9162
  this.ctx.logger.error(`${$.bgRed($.bold(" FAIL "))} ${formatProjectName(project)}${label ? `${$.bgCyan($.bold(` ${label} `))} ` : ""}${name}`);
8900
9163
  }
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
9164
  this.ctx.logger.printError(error, {
8910
9165
  project: this.ctx.getProjectByName(tasks[0].file.projectName || ""),
8911
9166
  verbose: this.verbose,
8912
9167
  screenshotPaths
8913
9168
  });
9169
+ for (const [task, attempts] of attemptsByTask) for (const attempt of attempts) {
9170
+ const timeline = task.type === "test" && attempt && formatTraceTimeline(task.artifacts, attempt, this.ctx.config.root);
9171
+ if (timeline) this.error(`${timeline}\n`);
9172
+ }
8914
9173
  if (tasks[0].type === "test" && tasks[0].annotations.length) {
8915
9174
  const test = this.ctx.state.getReportedEntity(tasks[0]);
8916
9175
  this.printAnnotations(test, "error", 1);
@@ -8920,6 +9179,34 @@ class BaseReporter {
8920
9179
  }
8921
9180
  }
8922
9181
  }
9182
+ function formatErrorAttempts(task, attempts) {
9183
+ const showAttempt = (task.result?.attempts?.length ?? 0) > 1;
9184
+ return [...Map.groupBy(attempts, (attempt) => attempt)].map(([attempt, occurrences]) => {
9185
+ const label = showAttempt && attempt ? formatAttempt(attempt) : "";
9186
+ const count = occurrences.length > 1 ? `${occurrences.length} times` : "";
9187
+ return count && label ? `${count} in ${label}` : count || label;
9188
+ }).filter(Boolean).join(", ");
9189
+ }
9190
+ function formatAttempt({ repeatIndex, retryIndex }) {
9191
+ const repeat = repeatIndex ? `${ordinal(repeatIndex)} repeat` : "";
9192
+ const retry = retryIndex ? `${ordinal(retryIndex)} retry` : "";
9193
+ if (repeat && retry) return `${retry} of ${repeat}`;
9194
+ return repeat || retry || "initial run";
9195
+ }
9196
+ function getErrorsWithAttempt(task) {
9197
+ const attempts = task.result?.attempts;
9198
+ if (!attempts?.length) return (task.result?.errors ?? []).map((error) => ({ error }));
9199
+ return attempts.flatMap((attempt) => (attempt.errors ?? []).map((error) => ({
9200
+ error,
9201
+ attempt
9202
+ })));
9203
+ }
9204
+ function getFailureScreenshotPaths(task, attempt) {
9205
+ if (task.type !== "test") return [];
9206
+ const paths = [];
9207
+ 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);
9208
+ return paths;
9209
+ }
8923
9210
  function deepEqual(a, b) {
8924
9211
  if (a === b) return true;
8925
9212
  if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
@@ -11953,6 +12240,22 @@ class TestRun {
11953
12240
  return artifact;
11954
12241
  }
11955
12242
  if (Array.isArray(artifact.attachments)) await Promise.all(artifact.attachments.map((attachment) => this.resolveTestAttachment(testCase, attachment)));
12243
+ // TODO: resolve browser trace locations here too, using `project.browser.parseStacktrace`
12244
+ // like `syncUpdateStacks`, and drop the mapping in `__vitest_recordBrowserTrace`
12245
+ if (artifact.type === "internal:browserTrace" && testCase.task.file.pool !== "browser") {
12246
+ const { entries } = artifact.data;
12247
+ for (const entry of entries) if (entry.stack && !entry.location) {
12248
+ const [stack] = parseStacktrace(entry.stack, {
12249
+ firstOnly: true,
12250
+ getSourceMap: (file) => getExternalSourceMap(testCase.project, file)
12251
+ });
12252
+ if (stack) entry.location = {
12253
+ file: stack.file,
12254
+ line: stack.line,
12255
+ column: stack.column
12256
+ };
12257
+ }
12258
+ }
11956
12259
  testCase.task.artifacts.push(artifact);
11957
12260
  await this.vitest.report("onTestCaseArtifactRecord", testCase, artifact);
11958
12261
  return artifact;
@@ -12011,12 +12314,7 @@ class TestRun {
12011
12314
  if (isBrowser) error.stacks = project.browser?.parseErrorStacktrace(error, { frameFilter: project.config.onStackTrace }) || [];
12012
12315
  else error.stacks = parseErrorStacktrace(error, {
12013
12316
  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
- }
12317
+ getSourceMap: (file) => getExternalSourceMap(project, file)
12020
12318
  });
12021
12319
  });
12022
12320
  });
@@ -12094,6 +12392,12 @@ class TestRun {
12094
12392
  }
12095
12393
  }
12096
12394
  }
12395
+ function getExternalSourceMap(project, file) {
12396
+ if (!project.vite.moduleGraph.getModuleById(file)?.transformResult && existsSync(file)) {
12397
+ const code = readFileSync(file, "utf-8");
12398
+ return extractSourcemapFromFile(code, file)?.map;
12399
+ }
12400
+ }
12097
12401
 
12098
12402
  class GitVCSProvider {
12099
12403
  root;
@@ -12194,6 +12498,7 @@ class VitestWatcher {
12194
12498
  */
12195
12499
  changedTests = /* @__PURE__ */ new Set();
12196
12500
  _onRerun = [];
12501
+ trackers = /* @__PURE__ */ new Map();
12197
12502
  constructor(vitest) {
12198
12503
  this.vitest = vitest;
12199
12504
  }
@@ -12342,6 +12647,47 @@ class VitestWatcher {
12342
12647
  }
12343
12648
  return !!files.length;
12344
12649
  }
12650
+ createTracker() {
12651
+ const watcher = this.vitest.vite.watcher;
12652
+ watcher.on("all", this.handleTrackEvent);
12653
+ const stop = () => {
12654
+ watcher.off("all", this.handleTrackEvent);
12655
+ this.trackers.clear();
12656
+ };
12657
+ return {
12658
+ track: this.track,
12659
+ // @todo: implement [Symbol.dispose] when dropping support for Node 22
12660
+ stop
12661
+ };
12662
+ }
12663
+ track = (filepath, { timeout, type = "any" } = {}) => {
12664
+ const eventTrackers = this.trackers.get(type) ?? /* @__PURE__ */ new Map();
12665
+ if (eventTrackers.size === 0) this.trackers.set(type, eventTrackers);
12666
+ const normalizedFilepath = normalize(filepath);
12667
+ const fileTrackers = eventTrackers.get(normalizedFilepath) ?? /* @__PURE__ */ new Set();
12668
+ if (fileTrackers.size === 0) eventTrackers.set(normalizedFilepath, fileTrackers);
12669
+ const resolvers = Promise.withResolvers();
12670
+ if (timeout) {
12671
+ const timeoutId = setTimeout(resolvers.reject, timeout);
12672
+ resolvers.promise = resolvers.promise.then(() => {
12673
+ clearTimeout(timeoutId);
12674
+ }).catch(() => {});
12675
+ }
12676
+ resolvers.promise = resolvers.promise.finally(() => {
12677
+ fileTrackers.delete(resolvers);
12678
+ });
12679
+ fileTrackers.add(resolvers);
12680
+ return resolvers.promise;
12681
+ };
12682
+ handleTrackEvent = (eventName, path) => {
12683
+ this.resolveTrackEvent("any", path);
12684
+ this.resolveTrackEvent(eventName, path);
12685
+ };
12686
+ resolveTrackEvent(eventName, path) {
12687
+ const fileTrackers = this.trackers.get(eventName)?.get(path);
12688
+ if (fileTrackers === void 0) return;
12689
+ for (const resolvers of fileTrackers) resolvers.resolve();
12690
+ }
12345
12691
  }
12346
12692
  // files loaded outside of the test module graph that affect every test in the project
12347
12693
  function getProjectWatchedFiles(project) {
@@ -12551,7 +12897,7 @@ class Vitest {
12551
12897
  this._harness._prewarmedBrowsers = 0;
12552
12898
  // harness mimics `vitest` access like in `node/create.ts`
12553
12899
  this._harness.setVitest(void 0);
12554
- const config = await resolveConfig$1(this.config.cliOptions, this.config.viteOverrides, this._harness);
12900
+ const config = await resolveConfig$1(this.config.cliOptions, this.config.viteOverrides, this._harness, this.config._cliFilters);
12555
12901
  this._harness.setVitest(this);
12556
12902
  await this._start(config);
12557
12903
  }
@@ -12582,7 +12928,7 @@ class Vitest {
12582
12928
  if (resolved._containerConfigFiles?.length) server.watcher.add(resolved._containerConfigFiles);
12583
12929
  // since we set `server.hmr: false`, Vite does not auto restart itself
12584
12930
  server.watcher.on("change", async (file) => {
12585
- file = normalize(file);
12931
+ file = normalize$1(file);
12586
12932
  if (file === server.config.configFile || this.projects.some((p) => p.vite.config.configFile === file) || this.config._containerConfigFiles?.includes(file))
12587
12933
  // a floating rejection in an event handler would crash the process
12588
12934
  await this._restart("config").catch((error) => {
@@ -13589,7 +13935,7 @@ async function createVitest(modeOrOptions, optionsOrViteOverrides = {}, viteOver
13589
13935
  const logger = new Logger(vitestOptions.stdout, vitestOptions.stderr);
13590
13936
  const packageInstaller = vitestOptions.packageInstaller ?? new VitestPackageInstaller();
13591
13937
  const pluginHarness = new PluginHarness(logger, packageInstaller);
13592
- const config = await resolveConfig$1(options, viteOverrides, pluginHarness);
13938
+ const config = await resolveConfig$1(options, viteOverrides, pluginHarness, vitestOptions.cliFilters);
13593
13939
  const vitest = new Vitest(pluginHarness, config);
13594
13940
  try {
13595
13941
  await vitest._start(config);
@@ -13603,6 +13949,288 @@ catch (error) {
13603
13949
  }
13604
13950
  }
13605
13951
 
13952
+ function isCancelAction(str, key) {
13953
+ return str === "" || str === "\x1B" || !!key && key.ctrl === true && key.name === "c";
13954
+ }
13955
+
13956
+ class SnapshotReviewer {
13957
+ ctx;
13958
+ snapshots;
13959
+ #updates = {
13960
+ approved: [],
13961
+ rejected: []
13962
+ };
13963
+ constructor(ctx) {
13964
+ this.ctx = ctx;
13965
+ this.snapshots = this.#collectSnapshots();
13966
+ }
13967
+ #collectSnapshots() {
13968
+ const failedSnapshots = [];
13969
+ for (const files of this.ctx.state.getFiles()) {
13970
+ const project = this.ctx.getProjectByName(files.projectName ?? "");
13971
+ if (project.config.snapshotEnvironment !== void 0) continue;
13972
+ for (const test of getTests(files)) {
13973
+ if (test.result?.errors === void 0) continue;
13974
+ for (const error of test.result.errors) {
13975
+ const reviewableSnapshot = getReviewableSnapshot(error);
13976
+ if (reviewableSnapshot === null) continue;
13977
+ failedSnapshots.push({
13978
+ ...reviewableSnapshot,
13979
+ test,
13980
+ project
13981
+ });
13982
+ }
13983
+ }
13984
+ }
13985
+ return failedSnapshots;
13986
+ }
13987
+ #approve = (snapshot) => {
13988
+ this.#updates.approved.push(snapshot);
13989
+ };
13990
+ #reject = (snapshot) => {
13991
+ this.#updates.rejected.push(snapshot);
13992
+ };
13993
+ #review = async (render) => {
13994
+ for (const [index, snapshot] of this.snapshots.entries()) {
13995
+ const update = {
13996
+ ...snapshot.errorMeta.update,
13997
+ meta: { test: snapshot.test }
13998
+ };
13999
+ await render({
14000
+ snapshot,
14001
+ stats: {
14002
+ index,
14003
+ length: this.snapshots.length
14004
+ }
14005
+ }, () => this.#approve(update), () => this.#reject(update));
14006
+ }
14007
+ };
14008
+ async #updateSnapshots() {
14009
+ const snapshotEnvironment = await this.getEnvironment();
14010
+ const snapshotUpdates = /* @__PURE__ */ new Map([[snapshotEnvironment, this.#updates.approved]]);
14011
+ return saveSnapshotUpdates(snapshotUpdates);
14012
+ }
14013
+ async startReview() {
14014
+ this.ctx.watcher.unregisterWatcher();
14015
+ const tracker = this.ctx.watcher.createTracker();
14016
+ try {
14017
+ await this.collectReviews(this.#review);
14018
+ const fileUpdates = new Set(this.#updates.approved.map(({ file }) => file));
14019
+ const fsEvents = Promise.all(Array.from(fileUpdates).map((file) => tracker.track(file, {
14020
+ type: "change",
14021
+ timeout: 500
14022
+ })));
14023
+ await this.#updateSnapshots();
14024
+ for (const file of fileUpdates) {
14025
+ this.ctx.logger.clearHighlightCache(file);
14026
+ this.ctx.invalidateFile(file);
14027
+ }
14028
+ // @todo what should happen when there's no approved updates?
14029
+ await this.ctx.rerunFiles(Array.from(new Set(this.#updates.approved.map(({ meta }) => meta.test.file.filepath))), "interactive review done");
14030
+ // wait for fs events before enabling the watcher to not cause another re-run
14031
+ // in case some have not been dispatched/consumed yet
14032
+ await fsEvents;
14033
+ } catch (error) {
14034
+ console.error(error);
14035
+ } finally {
14036
+ tracker.stop();
14037
+ this.ctx.watcher.registerWatcher();
14038
+ }
14039
+ }
14040
+ get hasReviewableSnapshots() {
14041
+ return this.snapshots.length > 0;
14042
+ }
14043
+ }
14044
+ function getReviewableSnapshot(error) {
14045
+ const errorMeta = error.__vitest_error_context__?.meta;
14046
+ if (typeof error.diff !== "string" || !isMatchMeta(errorMeta)) return null;
14047
+ return {
14048
+ error: { diff: error.diff },
14049
+ errorMeta,
14050
+ frame: error.stacks?.[0] ?? null
14051
+ };
14052
+ }
14053
+ function isMatchMeta(meta) {
14054
+ return meta !== void 0 && Reflect.get(meta, "type") === "snapshot" && "update" in meta;
14055
+ }
14056
+ const REVIEW_KEYS = [[
14057
+ "a",
14058
+ "green",
14059
+ "accept",
14060
+ "keep the new snapshot"
14061
+ ], [
14062
+ "r",
14063
+ "red",
14064
+ "reject",
14065
+ "retain the old snapshot"
14066
+ ]];
14067
+ const REVIEW_DESCRIPTION_PADDING = Math.max(...REVIEW_KEYS.map((k) => k[2].length)) + 2;
14068
+ 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`;
14069
+ class NodeSnapshotReviewer extends SnapshotReviewer {
14070
+ #stdin;
14071
+ #stdout;
14072
+ #snapshotEnvironment = void 0;
14073
+ constructor(ctx, stdin, stdout) {
14074
+ super(ctx);
14075
+ this.#stdin = stdin;
14076
+ this.#stdout = stdout;
14077
+ }
14078
+ async getEnvironment() {
14079
+ if (this.#snapshotEnvironment === void 0) this.#snapshotEnvironment = new (await (import('./node.B9mkVmLH.js'))).VitestNodeSnapshotEnvironment();
14080
+ return this.#snapshotEnvironment;
14081
+ }
14082
+ async collectReviews(review) {
14083
+ const controls = this.#handleKeypress();
14084
+ try {
14085
+ await review(async ({ snapshot: { error, errorMeta, frame, project, test }, stats }, approve, reject) => {
14086
+ const { update } = errorMeta;
14087
+ // undo `column--` from `SnapshotState` to match the error's stack frame
14088
+ const source = update.type === "inline" ? {
14089
+ ...update,
14090
+ column: update.column + 1
14091
+ } : frame;
14092
+ this.ctx.logger.clearFullScreen();
14093
+ this.#stdout.write([
14094
+ $.bold(`Reviewing [${$.yellow(`${stats.index + 1}/${stats.length}`)}]`) + (project.name ? ` ${formatProjectName(project, ":")}` : ":"),
14095
+ source && `Source: ${$.cyan(`${relative(project.config.root, source.file)}${$.dim(`:${source.line}:${source.column}`)}`)} ${$.dim(`(${test.fullTestName})`)}`,
14096
+ `Snapshot: ${$.yellow(errorMeta.key)}`,
14097
+ update.type !== "inline" && `Snapshot file: ${$.cyan(relative(project.config.root, update.file))}`,
14098
+ formatDiff(error.diff),
14099
+ REVIEW_KEYS_HELP
14100
+ ].filter(Boolean).join("\n"));
14101
+ switch (await controls.waitForAction()) {
14102
+ case "approved":
14103
+ approve();
14104
+ break;
14105
+ case "rejected": reject();
14106
+ }
14107
+ });
14108
+ this.ctx.logger.clearFullScreen();
14109
+ } catch (error) {
14110
+ controls.cleanup();
14111
+ // `waitForAction` can reject when pressing cancel keys, no need to log that
14112
+ if (error) console.error(error);
14113
+ await this.ctx.exit(true);
14114
+ }
14115
+ controls.cleanup();
14116
+ }
14117
+ #handleKeypress() {
14118
+ let resolvers;
14119
+ const rl = readline.createInterface({
14120
+ input: this.#stdin,
14121
+ escapeCodeTimeout: 50
14122
+ });
14123
+ readline.emitKeypressEvents(this.#stdin, rl);
14124
+ if (this.#stdin.isTTY) this.#stdin.setRawMode(true);
14125
+ this.#stdin.on("keypress", handler);
14126
+ const cleanup = () => {
14127
+ rl.close();
14128
+ this.#stdin.removeListener("keypress", handler);
14129
+ if (this.#stdin.isTTY) this.#stdin.setRawMode(false);
14130
+ };
14131
+ function handler(str, key) {
14132
+ if (resolvers === void 0) return;
14133
+ const currentResolvers = resolvers;
14134
+ // reset the resolvers so a cancel key string won't change the exit code without rejecting
14135
+ resolvers = void 0;
14136
+ if (isCancelAction(str, key)) {
14137
+ process.exitCode = 130;
14138
+ cleanup();
14139
+ return currentResolvers.reject();
14140
+ }
14141
+ switch (key.name) {
14142
+ // accept
14143
+ case "a":
14144
+ currentResolvers.resolve("approved");
14145
+ break;
14146
+ // reject
14147
+ case "r":
14148
+ currentResolvers.resolve("rejected");
14149
+ break;
14150
+ // ignore other keys
14151
+ default:
14152
+ // restore resolvers as we didn't resolve the promise
14153
+ resolvers = currentResolvers;
14154
+ }
14155
+ }
14156
+ return {
14157
+ waitForAction() {
14158
+ resolvers = Promise.withResolvers();
14159
+ return resolvers.promise;
14160
+ },
14161
+ cleanup
14162
+ };
14163
+ }
14164
+ }
14165
+ const DIFF_HEADER = `${$.green("- Expected")}\n${$.red("+ Received")}`;
14166
+ const SEPARATOR_H = "─";
14167
+ const SEPARATOR_V = "│";
14168
+ const JUNCTION_T = "┬";
14169
+ const JUNCTION_M = "┼";
14170
+ const JUNCTION_B = "┴";
14171
+ const DIFF_COL_WIDTH = 5;
14172
+ const HUNK_RE = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
14173
+ function formatDiff(diff) {
14174
+ const width = getCols();
14175
+ let oldLine = 0;
14176
+ let newLine = 0;
14177
+ let inHunk = false;
14178
+ const separatorLeft = 12;
14179
+ const separatorRight = Math.max(0, width - separatorLeft - 1);
14180
+ const separator = `${SEPARATOR_H.repeat(separatorLeft)}${JUNCTION_M}${SEPARATOR_H.repeat(separatorRight)}`;
14181
+ const lines = normalizeDiff(diff);
14182
+ return [
14183
+ SEPARATOR_H.repeat(width),
14184
+ DIFF_HEADER,
14185
+ lines.map((line, index) => {
14186
+ const plain = stripVTControlCharacters(line);
14187
+ const hunk = HUNK_RE.exec(plain);
14188
+ if (hunk) {
14189
+ oldLine = Number(hunk[1]);
14190
+ newLine = Number(hunk[2]);
14191
+ inHunk = true;
14192
+ if (index === 0) return `${SEPARATOR_H.repeat(separatorLeft)}${JUNCTION_T}${SEPARATOR_H.repeat(separatorRight)}`;
14193
+ return separator;
14194
+ }
14195
+ if (!inHunk) return line;
14196
+ switch (plain[0]) {
14197
+ case "-": return `${padLineNumber(oldLine++, $.green)} ${padLineNumber()} ${SEPARATOR_V}${line}`;
14198
+ case "+": return `${padLineNumber()} ${padLineNumber(newLine++, $.red)} ${SEPARATOR_V}${line}`;
14199
+ default: return `${padLineNumber(oldLine++)} ${padLineNumber(newLine++)} ${SEPARATOR_V}${line}`;
14200
+ }
14201
+ }).join("\n"),
14202
+ `${SEPARATOR_H.repeat(separatorLeft)}${JUNCTION_B}${SEPARATOR_H.repeat(separatorRight)}`
14203
+ ].join("\n");
14204
+ }
14205
+ const INLINE_RE = /(Expected|Received):\s/;
14206
+ function inlineValue(raw) {
14207
+ return raw.replace(INLINE_RE, "");
14208
+ }
14209
+ const DIFF_START = 3;
14210
+ const EXPECTED_SYMBOL = $.green("-");
14211
+ const RECEIVED_SYMBOL = $.red("+");
14212
+ function normalizeDiff(input) {
14213
+ const lines = input.split(/\r?\n/);
14214
+ const plain = lines.slice(0, 2).map(stripVTControlCharacters);
14215
+ // Inline `Expected: "..." / Received: "..."`
14216
+ if (plain[0]?.startsWith("Expected:") && plain[1]?.startsWith("Received:")) return [
14217
+ "@@ -1 +1 @@",
14218
+ `${EXPECTED_SYMBOL} ${inlineValue(lines[0])}`,
14219
+ `${RECEIVED_SYMBOL} ${inlineValue(lines[1])}`
14220
+ ];
14221
+ // Diff without hunk headers
14222
+ if (!(typeof lines[DIFF_START] === "string" && HUNK_RE.test(stripVTControlCharacters(lines[DIFF_START]))) && plain[0] === "- Expected" && plain[1] === "+ Received") {
14223
+ lines.splice(0, DIFF_START, "@@ -1 +1 @@");
14224
+ return lines;
14225
+ }
14226
+ // Diff with hunk headers
14227
+ return lines.slice(DIFF_START);
14228
+ }
14229
+ function padLineNumber(line, color = $.white) {
14230
+ if (line === void 0) return " ".repeat(DIFF_COL_WIDTH);
14231
+ return $.dim(color(String(line).padStart(DIFF_COL_WIDTH)));
14232
+ }
14233
+
13606
14234
  const MAX_RESULT_COUNT = 10;
13607
14235
  const SELECTION_MAX_INDEX = 7;
13608
14236
  const ESC = "\x1B[";
@@ -13734,6 +14362,7 @@ const keys = [
13734
14362
  ["r", "rerun current pattern tests"],
13735
14363
  ["f", "rerun only failed tests"],
13736
14364
  ["u", "update snapshot"],
14365
+ ["i", "interactively review snapshot fails"],
13737
14366
  ["p", "filter by a filename"],
13738
14367
  ["t", "filter by a test name regex pattern"],
13739
14368
  ["w", "filter by a project name"],
@@ -13781,7 +14410,7 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout) {
13781
14410
  async function _keypressHandler(str, key) {
13782
14411
  // Cancel run and exit when ctrl-c or esc is pressed.
13783
14412
  // If cancelling takes long and key is pressed multiple times, exit forcefully.
13784
- if (str === "" || str === "\x1B" || key && key.ctrl && key.name === "c") {
14413
+ if (isCancelAction(str, key)) {
13785
14414
  if (!ctx.isCancelling) {
13786
14415
  ctx.logger.log($.red("Cancelling test run. Press CTRL+c again to exit forcefully.\n"));
13787
14416
  process.exitCode = 130;
@@ -13799,7 +14428,7 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout) {
13799
14428
  }
13800
14429
  const name = key?.name;
13801
14430
  if (ctx.runningPromise) {
13802
- if (cancelKeys.includes(name)) await ctx.cancelCurrentRun("keyboard-input");
14431
+ if (name && cancelKeys.includes(name)) await ctx.cancelCurrentRun("keyboard-input");
13803
14432
  return;
13804
14433
  }
13805
14434
  // quit
@@ -13808,6 +14437,8 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout) {
13808
14437
  if (name === "h") return printShortcutsHelp();
13809
14438
  // update snapshot
13810
14439
  if (name === "u") return ctx.updateSnapshot();
14440
+ // interactive review
14441
+ if (name === "i") return reviewSnapshots();
13811
14442
  // rerun all tests
13812
14443
  if (name === "a" || name === "return") {
13813
14444
  const files = await ctx._globTestFilepaths();
@@ -13827,6 +14458,13 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout) {
13827
14458
  async function keypressHandler(str, key) {
13828
14459
  await _keypressHandler(str, key);
13829
14460
  }
14461
+ async function reviewSnapshots() {
14462
+ off();
14463
+ const snapshotReviewer = new NodeSnapshotReviewer(ctx, stdin, stdout);
14464
+ if (snapshotReviewer.hasReviewableSnapshots) await snapshotReviewer.startReview();
14465
+ else ctx.logger.log($.yellow(`No snapshots to review. ${$.dim("Press ") + $.bold("r") + $.dim(" to run tests again.")}\n`));
14466
+ on();
14467
+ }
13830
14468
  async function inputNamePattern() {
13831
14469
  off();
13832
14470
  const filter = await new WatchFilter("Input test name pattern (RegExp)", stdin, stdout).filter((str) => {
@@ -13984,7 +14622,10 @@ async function prepareVitest(modeOrOptions, optionsOrViteOverrides, viteOverride
13984
14622
  if (options.standalone && (cliFilters?.length || 0) > 0) options.standalone = false;
13985
14623
  // this shouldn't affect _application root_ that can be changed inside config
13986
14624
  const root = resolve(options.root || process.cwd());
13987
- const ctx = await createVitest(options, viteOverrides, vitestOptions);
14625
+ const ctx = await createVitest(options, viteOverrides, {
14626
+ ...vitestOptions,
14627
+ cliFilters
14628
+ });
13988
14629
  const environmentPackage = getEnvPackageName(ctx.config.environment);
13989
14630
  if (environmentPackage && !await ctx.packageInstaller.ensureInstalled(environmentPackage, root)) {
13990
14631
  process.exitCode = 1;