vitest 0.33.0 → 0.34.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 (49) hide show
  1. package/LICENSE.md +0 -83
  2. package/dist/browser.d.ts +3 -2
  3. package/dist/browser.js +4 -8
  4. package/dist/child.js +43 -29
  5. package/dist/{chunk-api-setup.8f785c4a.js → chunk-api-setup.644415c3.js} +13 -7
  6. package/dist/{chunk-install-pkg.23da664c.js → chunk-install-pkg.dd40cbef.js} +14 -13
  7. package/dist/{chunk-integrations-globals.0093e2ed.js → chunk-integrations-globals.877c84db.js} +7 -6
  8. package/dist/chunk-runtime-console.ea222ffb.js +108 -0
  9. package/dist/cli.js +14 -15
  10. package/dist/config.cjs +4 -3
  11. package/dist/config.d.ts +15 -19
  12. package/dist/config.js +4 -3
  13. package/dist/coverage.d.ts +3 -2
  14. package/dist/entry-vm.js +60 -0
  15. package/dist/entry.js +34 -213
  16. package/dist/environments.d.ts +3 -2
  17. package/dist/environments.js +4 -2
  18. package/dist/execute.js +15 -0
  19. package/dist/index.d.ts +12 -7
  20. package/dist/index.js +8 -7
  21. package/dist/loader.js +6 -4
  22. package/dist/node.d.ts +6 -53
  23. package/dist/node.js +16 -19
  24. package/dist/runners.d.ts +3 -2
  25. package/dist/runners.js +6 -5
  26. package/dist/{types-198fd1d9.d.ts → types-3c7dbfa5.d.ts} +139 -121
  27. package/dist/vendor-base.9c08bbd0.js +96 -0
  28. package/dist/{vendor-coverage.2e41927a.js → vendor-coverage.78040316.js} +1 -2
  29. package/dist/vendor-date.6e993429.js +50 -0
  30. package/dist/{vendor-environments.392ddf08.js → vendor-environments.443ecd82.js} +199 -3
  31. package/dist/vendor-execute.9ab1c1a7.js +978 -0
  32. package/dist/{vendor-global.6795f91f.js → vendor-global.97e4527c.js} +2 -1
  33. package/dist/{vendor-index.23ac4e13.js → vendor-index.087d1af7.js} +2 -20
  34. package/dist/vendor-index.9378c9a4.js +89 -0
  35. package/dist/vendor-index.b271ebe4.js +92 -0
  36. package/dist/{vendor-index.2af39fbb.js → vendor-index.eff408fd.js} +2 -3
  37. package/dist/{vendor-cli-api.bf4b62a8.js → vendor-node.caa511fc.js} +539 -836
  38. package/dist/{vendor-rpc.ad5b08c7.js → vendor-rpc.cbd8e972.js} +7 -4
  39. package/dist/{vendor-run-once.1fa85ba7.js → vendor-run-once.3e5ef7d7.js} +1 -2
  40. package/dist/vendor-source-map.e6c1997b.js +747 -0
  41. package/dist/{vendor-vi.dd6706cb.js → vendor-vi.271667ef.js} +26 -59
  42. package/dist/vm.js +114 -0
  43. package/dist/worker.js +39 -27
  44. package/execute.d.ts +1 -0
  45. package/package.json +12 -9
  46. package/suppress-warnings.cjs +2 -0
  47. package/dist/vendor-execute.3576af13.js +0 -421
  48. package/dist/vendor-index.cc463d9e.js +0 -189
  49. package/dist/vendor-tasks.f9d75aed.js +0 -14
@@ -1,16 +1,10 @@
1
- import { resolve as resolve$2, relative, isAbsolute, dirname, basename, normalize, join, extname, toNamespacedPath } from 'pathe';
2
- import { E as EXIT_CODE_RESTART, c as configFiles, d as defaultPort, a as defaultBrowserPort, w as workspacesFiles, C as CONFIG_NAMES } from './vendor-constants.538d9b49.js';
3
- import { g as getCoverageProvider, C as CoverageProviderMap } from './vendor-coverage.2e41927a.js';
4
- import { g as getEnvPackageName } from './vendor-environments.392ddf08.js';
5
- import url, { fileURLToPath, pathToFileURL } from 'node:url';
6
- import c from 'picocolors';
7
- import { isPackageExists, resolveModule } from 'local-pkg';
8
- import { a as isNode, b as relativePath, c as removeUndefinedValues, d as isWindows } from './vendor-index.23ac4e13.js';
9
- import { isCI } from 'std-env';
1
+ import { resolve, relative, isAbsolute, dirname, basename, normalize, join, extname, toNamespacedPath } from 'pathe';
10
2
  import { loadConfigFromFile, createServer, version as version$2, mergeConfig } from 'vite';
11
3
  import path$a from 'node:path';
4
+ import url, { fileURLToPath, pathToFileURL } from 'node:url';
12
5
  import process$1 from 'node:process';
13
6
  import fs$8, { promises, existsSync, readFileSync } from 'node:fs';
7
+ import { E as EXIT_CODE_RESTART, c as configFiles, d as defaultPort, a as defaultBrowserPort, w as workspacesFiles, C as CONFIG_NAMES } from './vendor-constants.538d9b49.js';
14
8
  import { g as getDefaultExportFromCjs, c as commonjsGlobal } from './vendor-_commonjsHelpers.7d1333e8.js';
15
9
  import require$$0 from 'os';
16
10
  import f$1 from 'path';
@@ -18,20 +12,26 @@ import require$$2 from 'util';
18
12
  import require$$0$1 from 'stream';
19
13
  import require$$2$1 from 'events';
20
14
  import $ from 'fs';
15
+ import c from 'picocolors';
21
16
  import { slash as slash$2, normalizeRequestId, cleanUrl } from 'vite-node/utils';
22
17
  import { ViteNodeRunner } from 'vite-node/client';
23
18
  import { SnapshotManager } from '@vitest/snapshot/manager';
24
19
  import { ViteNodeServer } from 'vite-node/server';
20
+ import { a as isNode, r as relativePath, b as removeUndefinedValues, c as isWindows } from './vendor-index.087d1af7.js';
21
+ import { g as getCoverageProvider, C as CoverageProviderMap } from './vendor-coverage.78040316.js';
25
22
  import { d as distDir, r as rootDir } from './vendor-paths.84fc7a99.js';
26
23
  import v8 from 'node:v8';
27
24
  import { fork } from 'node:child_process';
28
- import { a as groupBy, b as getEnvironmentTransformMode, c as createBirpc, A as AggregateErrorPonyfill, s as slash$1, t as toArray, i as isPrimitive, d as deepMerge, n as noop$1, e as stdout } from './vendor-index.cc463d9e.js';
25
+ import { c as createBirpc } from './vendor-index.b271ebe4.js';
26
+ import { g as groupBy, A as AggregateErrorPonyfill, s as slash$1, t as toArray, i as isPrimitive, d as deepMerge, n as noop$1, a as stdout } from './vendor-base.9c08bbd0.js';
29
27
  import { MessageChannel } from 'node:worker_threads';
30
- import { cpus, hostname } from 'node:os';
28
+ import { cpus, hostname, totalmem } from 'node:os';
31
29
  import Tinypool from 'tinypool';
32
- import { createDefer, getSafeTimers, notNullish, parseErrorStacktrace, shuffle, stringify as stringify$5, positionToOffset, lineSplitRE } from '@vitest/utils';
30
+ import { createDefer, getSafeTimers, notNullish, shuffle, inspect, positionToOffset, lineSplitRE } from '@vitest/utils';
31
+ import { isPackageExists, resolveModule } from 'local-pkg';
32
+ import { isCI } from 'std-env';
33
33
  import { performance } from 'node:perf_hooks';
34
- import { g as getFullName, h as hasFailedSnapshot } from './vendor-tasks.f9d75aed.js';
34
+ import { g as getFullName, h as hasFailedSnapshot, p as parseErrorStacktrace, T as TraceMap, b as generatedPositionFor } from './vendor-source-map.e6c1997b.js';
35
35
  import { getTests, hasFailed, getSuites, generateHash, calculateSuiteHash, someTasksAreOnly, interpretTaskModes, getTasks } from '@vitest/runner/utils';
36
36
  import { createRequire, builtinModules } from 'node:module';
37
37
  import { createHash } from 'node:crypto';
@@ -42,6 +42,7 @@ import { parse as parse$4 } from 'acorn';
42
42
  import { ancestor, simple, findNodeAround } from 'acorn-walk';
43
43
  import MagicString from 'magic-string';
44
44
  import { stripLiteral } from 'strip-literal';
45
+ import { g as getEnvPackageName } from './vendor-environments.443ecd82.js';
45
46
  import readline from 'node:readline';
46
47
  import require$$0$2 from 'readline';
47
48
 
@@ -60,15 +61,13 @@ function _mergeNamespaces(n, m) {
60
61
  return Object.freeze(n);
61
62
  }
62
63
 
63
- var version$1 = "0.33.0";
64
+ var version$1 = "0.34.1";
64
65
 
65
66
  const __dirname$1 = url.fileURLToPath(new URL(".", import.meta.url));
66
- async function ensurePackageInstalled(dependency, root, errorMessage) {
67
+ async function ensurePackageInstalled(dependency, root) {
67
68
  if (isPackageExists(dependency, { paths: [root, __dirname$1] }))
68
69
  return true;
69
70
  const promptInstall = !isCI && process.stdout.isTTY;
70
- if (errorMessage)
71
- process.stderr.write(c.red(errorMessage));
72
71
  process.stderr.write(c.red(`${c.inverse(c.red(" MISSING DEP "))} Can not find dependency '${dependency}'
73
72
 
74
73
  `));
@@ -81,7 +80,7 @@ async function ensurePackageInstalled(dependency, root, errorMessage) {
81
80
  message: c.reset(`Do you want to install ${c.green(dependency)}?`)
82
81
  });
83
82
  if (install) {
84
- await (await import('./chunk-install-pkg.23da664c.js')).installPackage(dependency, { dev: true });
83
+ await (await import('./chunk-install-pkg.dd40cbef.js')).installPackage(dependency, { dev: true });
85
84
  process.stderr.write(c.yellow(`
86
85
  Package ${dependency} installed, re-run the command to start.
87
86
  `));
@@ -527,7 +526,7 @@ var isExtglob$1 = function isExtglob(str) {
527
526
  */
528
527
 
529
528
  var isExtglob = isExtglob$1;
530
- var chars$1 = { '{': '}', '(': ')', '[': ']'};
529
+ var chars = { '{': '}', '(': ')', '[': ']'};
531
530
  var strictCheck = function(str) {
532
531
  if (str[0] === '!') {
533
532
  return true;
@@ -600,7 +599,7 @@ var strictCheck = function(str) {
600
599
  if (str[index] === '\\') {
601
600
  var open = str[index + 1];
602
601
  index += 2;
603
- var close = chars$1[open];
602
+ var close = chars[open];
604
603
 
605
604
  if (close) {
606
605
  var n = str.indexOf(close, index);
@@ -632,7 +631,7 @@ var relaxedCheck = function(str) {
632
631
  if (str[index] === '\\') {
633
632
  var open = str[index + 1];
634
633
  index += 2;
635
- var close = chars$1[open];
634
+ var close = chars[open];
636
635
 
637
636
  if (close) {
638
637
  var n = str.indexOf(close, index);
@@ -7063,6 +7062,13 @@ const envsOrder = [
7063
7062
  "happy-dom",
7064
7063
  "edge-runtime"
7065
7064
  ];
7065
+ function getTransformMode(patterns, filename) {
7066
+ if (patterns.web && mm.isMatch(filename, patterns.web))
7067
+ return "web";
7068
+ if (patterns.ssr && mm.isMatch(filename, patterns.ssr))
7069
+ return "ssr";
7070
+ return void 0;
7071
+ }
7066
7072
  async function groupFilesByEnv(files) {
7067
7073
  const filesWithEnv = await Promise.all(files.map(async ([project, file]) => {
7068
7074
  var _a, _b;
@@ -7077,12 +7083,14 @@ async function groupFilesByEnv(files) {
7077
7083
  }
7078
7084
  }
7079
7085
  env || (env = project.config.environment || "node");
7086
+ const transformMode = getTransformMode(project.config.testTransformMode, file);
7080
7087
  const envOptions = JSON.parse(((_b = code.match(/@(?:vitest|jest)-environment-options\s+?(.+)/)) == null ? void 0 : _b[1]) || "null");
7081
7088
  return {
7082
7089
  file,
7083
7090
  project,
7084
7091
  environment: {
7085
7092
  name: env,
7093
+ transformMode,
7086
7094
  options: envOptions ? { [env]: envOptions } : null
7087
7095
  }
7088
7096
  };
@@ -7094,7 +7102,7 @@ function createMethodsRPC(project) {
7094
7102
  const ctx = project.ctx;
7095
7103
  return {
7096
7104
  async onWorkerExit(error, code) {
7097
- await ctx.logger.printError(error, false, "Unexpected Exit");
7105
+ await ctx.logger.printError(error, { type: "Unexpected Exit" });
7098
7106
  process.exit(code || 1);
7099
7107
  },
7100
7108
  snapshotSaved(snapshot) {
@@ -7112,12 +7120,10 @@ function createMethodsRPC(project) {
7112
7120
  const r = await project.vitenode.transformRequest(id);
7113
7121
  return r == null ? void 0 : r.map;
7114
7122
  },
7115
- fetch(id, environment) {
7116
- const transformMode = getEnvironmentTransformMode(project.config, environment);
7123
+ fetch(id, transformMode) {
7117
7124
  return project.vitenode.fetchModule(id, transformMode);
7118
7125
  },
7119
- resolveId(id, importer, environment) {
7120
- const transformMode = getEnvironmentTransformMode(project.config, environment);
7126
+ resolveId(id, importer, transformMode) {
7121
7127
  return project.vitenode.resolveId(id, importer, transformMode);
7122
7128
  },
7123
7129
  onPathsCollected(paths) {
@@ -7155,7 +7161,7 @@ function createMethodsRPC(project) {
7155
7161
  };
7156
7162
  }
7157
7163
 
7158
- const childPath = fileURLToPath(pathToFileURL(resolve$2(distDir, "./child.js")).href);
7164
+ const childPath = fileURLToPath(pathToFileURL(resolve(distDir, "./child.js")).href);
7159
7165
  function setupChildProcessChannel(project, fork2) {
7160
7166
  const rpc = createBirpc(
7161
7167
  createMethodsRPC(project),
@@ -7202,6 +7208,8 @@ function createChildProcessPool(ctx, { execArgv, env }) {
7202
7208
  const child = fork(childPath, [], {
7203
7209
  execArgv,
7204
7210
  env
7211
+ // TODO: investigate
7212
+ // serialization: 'advanced',
7205
7213
  });
7206
7214
  children.add(child);
7207
7215
  setupChildProcessChannel(project, child);
@@ -7232,7 +7240,7 @@ function createChildProcessPool(ctx, { execArgv, env }) {
7232
7240
  const files = filesByEnv[env2];
7233
7241
  if (!(files == null ? void 0 : files.length))
7234
7242
  continue;
7235
- const filesByOptions = groupBy(files, ({ project, environment }) => project.getName() + JSON.stringify(environment.options));
7243
+ const filesByOptions = groupBy(files, ({ project, environment }) => project.getName() + JSON.stringify(environment.options) + environment.transformMode);
7236
7244
  for (const option in filesByOptions) {
7237
7245
  const files2 = filesByOptions[option];
7238
7246
  if (files2 == null ? void 0 : files2.length) {
@@ -7254,8 +7262,8 @@ function createChildProcessPool(ctx, { execArgv, env }) {
7254
7262
  };
7255
7263
  }
7256
7264
 
7257
- const workerPath = pathToFileURL(resolve$2(distDir, "./worker.js")).href;
7258
- function createWorkerChannel(project) {
7265
+ const workerPath$1 = pathToFileURL(resolve(distDir, "./worker.js")).href;
7266
+ function createWorkerChannel$1(project) {
7259
7267
  const channel = new MessageChannel();
7260
7268
  const port = channel.port2;
7261
7269
  const workerPort = channel.port1;
@@ -7279,7 +7287,7 @@ function createThreadsPool(ctx, { execArgv, env }) {
7279
7287
  const maxThreads = ctx.config.maxThreads ?? threadsCount;
7280
7288
  const minThreads = ctx.config.minThreads ?? threadsCount;
7281
7289
  const options = {
7282
- filename: workerPath,
7290
+ filename: workerPath$1,
7283
7291
  // TODO: investigate further
7284
7292
  // It seems atomics introduced V8 Fatal Error https://github.com/vitest-dev/vitest/issues/1191
7285
7293
  useAtomics: ctx.config.useAtomics ?? false,
@@ -7303,7 +7311,7 @@ function createThreadsPool(ctx, { execArgv, env }) {
7303
7311
  let id = 0;
7304
7312
  async function runFiles(project, config, files, environment, invalidates = []) {
7305
7313
  ctx.state.clearFiles(project, files);
7306
- const { workerPort, port } = createWorkerChannel(project);
7314
+ const { workerPort, port } = createWorkerChannel$1(project);
7307
7315
  const workerId = ++id;
7308
7316
  const data = {
7309
7317
  port: workerPort,
@@ -7353,8 +7361,18 @@ function createThreadsPool(ctx, { execArgv, env }) {
7353
7361
  const multipleThreads = specs.filter(([project]) => !project.config.singleThread);
7354
7362
  if (multipleThreads.length) {
7355
7363
  const filesByEnv = await groupFilesByEnv(multipleThreads);
7356
- const promises = Object.values(filesByEnv).flat();
7357
- const results = await Promise.allSettled(promises.map(({ file, environment, project }) => runFiles(project, getConfig(project), [file], environment, invalidates)));
7364
+ const files = Object.values(filesByEnv).flat();
7365
+ const results = [];
7366
+ if (ctx.config.isolate) {
7367
+ results.push(...await Promise.allSettled(files.map(({ file, environment, project }) => runFiles(project, getConfig(project), [file], environment, invalidates))));
7368
+ } else {
7369
+ const grouped = groupBy(files, ({ project, environment }) => project.getName() + environment.name + JSON.stringify(environment.options));
7370
+ for (const group of Object.values(grouped)) {
7371
+ results.push(...await Promise.allSettled(group.map(({ file, environment, project }) => runFiles(project, getConfig(project), [file], environment, invalidates))));
7372
+ await new Promise((resolve2) => pool.queueSize === 0 ? resolve2() : pool.once("drain", resolve2));
7373
+ await pool.recycleWorkers();
7374
+ }
7375
+ }
7358
7376
  const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
7359
7377
  if (errors.length > 0)
7360
7378
  throw new AggregateErrorPonyfill(errors, "Errors occurred while running tests. For more information, see serialized error.");
@@ -7369,11 +7387,11 @@ function createThreadsPool(ctx, { execArgv, env }) {
7369
7387
  if (!(files == null ? void 0 : files.length))
7370
7388
  continue;
7371
7389
  const filesByOptions = groupBy(files, ({ project, environment }) => project.getName() + JSON.stringify(environment.options));
7372
- const promises = Object.values(filesByOptions).map(async (files2) => {
7390
+ for (const files2 of Object.values(filesByOptions)) {
7391
+ await pool.recycleWorkers();
7373
7392
  const filenames = files2.map((f) => f.file);
7374
7393
  await runFiles(files2[0].project, getConfig(files2[0].project), filenames, files2[0].environment, invalidates);
7375
- });
7376
- await Promise.all(promises);
7394
+ }
7377
7395
  }
7378
7396
  }
7379
7397
  };
@@ -7460,17 +7478,131 @@ function createBrowserPool(ctx) {
7460
7478
  };
7461
7479
  }
7462
7480
 
7463
- const loaderPath = pathToFileURL(resolve$2(distDir, "./loader.js")).href;
7464
- const suppressLoaderWarningsPath = resolve$2(rootDir, "./suppress-warnings.cjs");
7481
+ const workerPath = pathToFileURL(resolve(distDir, "./vm.js")).href;
7482
+ const suppressLoaderWarningsPath$1 = resolve(rootDir, "./suppress-warnings.cjs");
7483
+ function createWorkerChannel(project) {
7484
+ const channel = new MessageChannel();
7485
+ const port = channel.port2;
7486
+ const workerPort = channel.port1;
7487
+ const rpc = createBirpc(
7488
+ createMethodsRPC(project),
7489
+ {
7490
+ eventNames: ["onCancel"],
7491
+ post(v) {
7492
+ port.postMessage(v);
7493
+ },
7494
+ on(fn) {
7495
+ port.on("message", fn);
7496
+ }
7497
+ }
7498
+ );
7499
+ project.ctx.onCancel((reason) => rpc.onCancel(reason));
7500
+ return { workerPort, port };
7501
+ }
7502
+ function createVmThreadsPool(ctx, { execArgv, env }) {
7503
+ const threadsCount = ctx.config.watch ? Math.max(Math.floor(cpus().length / 2), 1) : Math.max(cpus().length - 1, 1);
7504
+ const maxThreads = ctx.config.maxThreads ?? threadsCount;
7505
+ const minThreads = ctx.config.minThreads ?? threadsCount;
7506
+ const options = {
7507
+ filename: workerPath,
7508
+ // TODO: investigate further
7509
+ // It seems atomics introduced V8 Fatal Error https://github.com/vitest-dev/vitest/issues/1191
7510
+ useAtomics: ctx.config.useAtomics ?? false,
7511
+ maxThreads,
7512
+ minThreads,
7513
+ env,
7514
+ execArgv: [
7515
+ "--experimental-import-meta-resolve",
7516
+ "--experimental-vm-modules",
7517
+ "--require",
7518
+ suppressLoaderWarningsPath$1,
7519
+ ...execArgv
7520
+ ],
7521
+ terminateTimeout: ctx.config.teardownTimeout,
7522
+ maxMemoryLimitBeforeRecycle: ctx.config.experimentalVmWorkerMemoryLimit || void 0
7523
+ };
7524
+ if (ctx.config.singleThread) {
7525
+ options.concurrentTasksPerWorker = 1;
7526
+ options.maxThreads = 1;
7527
+ options.minThreads = 1;
7528
+ }
7529
+ const pool = new Tinypool(options);
7530
+ const runWithFiles = (name) => {
7531
+ let id = 0;
7532
+ async function runFiles(project, config, files, environment, invalidates = []) {
7533
+ ctx.state.clearFiles(project, files);
7534
+ const { workerPort, port } = createWorkerChannel(project);
7535
+ const workerId = ++id;
7536
+ const data = {
7537
+ port: workerPort,
7538
+ config,
7539
+ files,
7540
+ invalidates,
7541
+ environment,
7542
+ workerId
7543
+ };
7544
+ try {
7545
+ await pool.run(data, { transferList: [workerPort], name });
7546
+ } catch (error) {
7547
+ if (error instanceof Error && /Failed to terminate worker/.test(error.message))
7548
+ ctx.state.addProcessTimeoutCause(`Failed to terminate worker while running ${files.join(", ")}.`);
7549
+ else if (ctx.isCancelling && error instanceof Error && /The task has been cancelled/.test(error.message))
7550
+ ctx.state.cancelFiles(files, ctx.config.root);
7551
+ else
7552
+ throw error;
7553
+ } finally {
7554
+ port.close();
7555
+ workerPort.close();
7556
+ }
7557
+ }
7558
+ const Sequencer = ctx.config.sequence.sequencer;
7559
+ const sequencer = new Sequencer(ctx);
7560
+ return async (specs, invalidates) => {
7561
+ const configs = /* @__PURE__ */ new Map();
7562
+ const getConfig = (project) => {
7563
+ if (configs.has(project))
7564
+ return configs.get(project);
7565
+ const config = project.getSerializableConfig();
7566
+ configs.set(project, config);
7567
+ return config;
7568
+ };
7569
+ const { shard } = ctx.config;
7570
+ if (shard)
7571
+ specs = await sequencer.shard(specs);
7572
+ specs = await sequencer.sort(specs);
7573
+ const filesByEnv = await groupFilesByEnv(specs);
7574
+ const promises = Object.values(filesByEnv).flat();
7575
+ const results = await Promise.allSettled(promises.map(({ file, environment, project }) => runFiles(project, getConfig(project), [file], environment, invalidates)));
7576
+ const errors = results.filter((r) => r.status === "rejected").map((r) => r.reason);
7577
+ if (errors.length > 0)
7578
+ throw new AggregateErrorPonyfill(errors, "Errors occurred while running tests. For more information, see serialized error.");
7579
+ };
7580
+ };
7581
+ return {
7582
+ runTests: runWithFiles("run"),
7583
+ close: async () => {
7584
+ var _a;
7585
+ const nodeVersion = Number((_a = process.version.match(/v(\d+)\.(\d+)/)) == null ? void 0 : _a[0].slice(1));
7586
+ if (nodeVersion >= 16.17)
7587
+ await pool.destroy();
7588
+ }
7589
+ };
7590
+ }
7591
+
7592
+ const loaderPath = pathToFileURL(resolve(distDir, "./loader.js")).href;
7593
+ const suppressLoaderWarningsPath = resolve(rootDir, "./suppress-warnings.cjs");
7465
7594
  function createPool(ctx) {
7466
7595
  const pools = {
7467
7596
  child_process: null,
7468
7597
  threads: null,
7469
- browser: null
7598
+ browser: null,
7599
+ experimentalVmThreads: null
7470
7600
  };
7471
7601
  function getDefaultPoolName(project) {
7472
7602
  if (project.config.browser.enabled)
7473
7603
  return "browser";
7604
+ if (project.config.experimentalVmThreads)
7605
+ return "experimentalVmThreads";
7474
7606
  if (project.config.threads)
7475
7607
  return "threads";
7476
7608
  return "child_process";
@@ -7496,7 +7628,8 @@ function createPool(ctx) {
7496
7628
  "--require",
7497
7629
  suppressLoaderWarningsPath,
7498
7630
  "--experimental-loader",
7499
- loaderPath
7631
+ loaderPath,
7632
+ ...conditions
7500
7633
  ] : [
7501
7634
  ...execArgv,
7502
7635
  ...conditions
@@ -7513,10 +7646,13 @@ function createPool(ctx) {
7513
7646
  const filesByPool = {
7514
7647
  child_process: [],
7515
7648
  threads: [],
7516
- browser: []
7649
+ browser: [],
7650
+ experimentalVmThreads: []
7517
7651
  };
7518
7652
  for (const spec of files) {
7519
7653
  const pool = getPoolName(spec);
7654
+ if (!(pool in filesByPool))
7655
+ throw new Error(`Unknown pool name "${pool}" for ${spec[1]}. Available pools: ${Object.keys(filesByPool).join(", ")}`);
7520
7656
  filesByPool[pool].push(spec);
7521
7657
  }
7522
7658
  await Promise.all(Object.entries(filesByPool).map(([pool, files2]) => {
@@ -7526,6 +7662,10 @@ function createPool(ctx) {
7526
7662
  pools.browser ?? (pools.browser = createBrowserPool(ctx));
7527
7663
  return pools.browser.runTests(files2, invalidate);
7528
7664
  }
7665
+ if (pool === "experimentalVmThreads") {
7666
+ pools.experimentalVmThreads ?? (pools.experimentalVmThreads = createVmThreadsPool(ctx, options));
7667
+ return pools.experimentalVmThreads.runTests(files2, invalidate);
7668
+ }
7529
7669
  if (pool === "threads") {
7530
7670
  pools.threads ?? (pools.threads = createThreadsPool(ctx, options));
7531
7671
  return pools.threads.runTests(files2, invalidate);
@@ -8037,8 +8177,13 @@ ${c.cyan(c.inverse(c.bold(" BENCH ")))} ${c.cyan("Summary")}
8037
8177
  for (const task of tasks) {
8038
8178
  (_b = (_a2 = task.result) == null ? void 0 : _a2.errors) == null ? void 0 : _b.forEach((error) => {
8039
8179
  const errorItem = (error == null ? void 0 : error.stackStr) && errorsQueue.find((i) => {
8040
- var _a3;
8041
- return ((_a3 = i[0]) == null ? void 0 : _a3.stackStr) === error.stackStr;
8180
+ var _a3, _b2, _c2, _d;
8181
+ const hasStr = ((_a3 = i[0]) == null ? void 0 : _a3.stackStr) === error.stackStr;
8182
+ if (!hasStr)
8183
+ return false;
8184
+ const currentProjectName = (task == null ? void 0 : task.projectName) || ((_b2 = task.file) == null ? void 0 : _b2.projectName);
8185
+ const projectName = ((_c2 = i[1][0]) == null ? void 0 : _c2.projectName) || ((_d = i[1][0].file) == null ? void 0 : _d.projectName);
8186
+ return projectName === currentProjectName;
8042
8187
  });
8043
8188
  if (errorItem)
8044
8189
  errorItem[1].push(task);
@@ -8055,7 +8200,8 @@ ${c.cyan(c.inverse(c.bold(" BENCH ")))} ${c.cyan("Summary")}
8055
8200
  name = `${name} ${c.dim(`[ ${this.relative(filepath)} ]`)}`;
8056
8201
  this.ctx.logger.error(`${c.red(c.bold(c.inverse(" FAIL ")))} ${formatProjectName(projectName)}${name}`);
8057
8202
  }
8058
- await this.ctx.logger.printError(error);
8203
+ const project = this.ctx.getProjectByTaskId(tasks2[0].id);
8204
+ await this.ctx.logger.printError(error, { project });
8059
8205
  errorDivider();
8060
8206
  await Promise.resolve();
8061
8207
  }
@@ -8063,7 +8209,7 @@ ${c.cyan(c.inverse(c.bold(" BENCH ")))} ${c.cyan("Summary")}
8063
8209
  registerUnhandledRejection() {
8064
8210
  process.on("unhandledRejection", async (err) => {
8065
8211
  process.exitCode = 1;
8066
- await this.ctx.logger.printError(err, true, "Unhandled Rejection");
8212
+ await this.ctx.logger.printError(err, { fullStack: true, type: "Unhandled Rejection" });
8067
8213
  this.ctx.logger.error("\n\n");
8068
8214
  process.exit(1);
8069
8215
  });
@@ -9415,7 +9561,7 @@ let JsonReporter$1 = class JsonReporter {
9415
9561
  async writeReport(report) {
9416
9562
  const outputFile = getOutputFile(this.ctx.config, "json");
9417
9563
  if (outputFile) {
9418
- const reportFile = resolve$2(this.ctx.config.root, outputFile);
9564
+ const reportFile = resolve(this.ctx.config.root, outputFile);
9419
9565
  const outputDirectory = dirname(reportFile);
9420
9566
  if (!existsSync(outputDirectory))
9421
9567
  await promises.mkdir(outputDirectory, { recursive: true });
@@ -9430,7 +9576,10 @@ let JsonReporter$1 = class JsonReporter {
9430
9576
  const error = (_b = (_a = test.result) == null ? void 0 : _a.errors) == null ? void 0 : _b[0];
9431
9577
  if (!error)
9432
9578
  return;
9433
- const stack = parseErrorStacktrace(error);
9579
+ const project = this.ctx.getProjectByTaskId(test.id);
9580
+ const stack = parseErrorStacktrace(error, {
9581
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
9582
+ });
9434
9583
  const frame = stack[0];
9435
9584
  if (!frame)
9436
9585
  return;
@@ -9529,10 +9678,13 @@ class TapReporter {
9529
9678
  this.logger.log("}");
9530
9679
  } else {
9531
9680
  this.logger.log(`${ok} ${id} - ${tapString(task.name)}${comment}`);
9681
+ const project = this.ctx.getProjectByTaskId(task.id);
9532
9682
  if (((_b = task.result) == null ? void 0 : _b.state) === "fail" && task.result.errors) {
9533
9683
  this.logger.indent();
9534
9684
  task.result.errors.forEach((error) => {
9535
- const stacks = parseErrorStacktrace(error);
9685
+ const stacks = parseErrorStacktrace(error, {
9686
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
9687
+ });
9536
9688
  const stack = stacks[0];
9537
9689
  this.logger.log("---");
9538
9690
  this.logger.log("error:");
@@ -9606,7 +9758,7 @@ class JUnitReporter {
9606
9758
  this.ctx = ctx;
9607
9759
  const outputFile = getOutputFile(this.ctx.config, "junit");
9608
9760
  if (outputFile) {
9609
- this.reportFile = resolve$2(this.ctx.config.root, outputFile);
9761
+ this.reportFile = resolve(this.ctx.config.root, outputFile);
9610
9762
  const outputDirectory = dirname(this.reportFile);
9611
9763
  if (!existsSync(outputDirectory))
9612
9764
  await promises.mkdir(outputDirectory, { recursive: true });
@@ -9638,11 +9790,14 @@ class JUnitReporter {
9638
9790
  this.logger.unindent();
9639
9791
  await this.logger.log(`</${name}>`);
9640
9792
  }
9641
- async writeErrorDetails(error) {
9793
+ async writeErrorDetails(task, error) {
9642
9794
  const errorName = error.name ?? error.nameStr ?? "Unknown Error";
9643
9795
  const errorDetails = `${errorName}: ${error.message}`;
9644
9796
  await this.baseLog(escapeXML(errorDetails));
9645
- const stack = parseErrorStacktrace(error);
9797
+ const project = this.ctx.getProjectByTaskId(task.id);
9798
+ const stack = parseErrorStacktrace(error, {
9799
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
9800
+ });
9646
9801
  for (const frame of stack) {
9647
9802
  const path = relative(this.ctx.config.root, frame.file);
9648
9803
  await this.baseLog(escapeXML(` ${F_POINTER} ${[frame.method, `${path}:${frame.line}:${frame.column}`].filter(Boolean).join(" ")}`));
@@ -9665,7 +9820,7 @@ class JUnitReporter {
9665
9820
  async writeTasks(tasks, filename) {
9666
9821
  for (const task of tasks) {
9667
9822
  await this.writeElement("testcase", {
9668
- classname: filename,
9823
+ classname: process.env.VITEST_JUNIT_CLASSNAME ?? filename,
9669
9824
  name: task.name,
9670
9825
  time: getDuration(task)
9671
9826
  }, async () => {
@@ -9683,7 +9838,7 @@ class JUnitReporter {
9683
9838
  }, async () => {
9684
9839
  if (!error)
9685
9840
  return;
9686
- await this.writeErrorDetails(error);
9841
+ await this.writeErrorDetails(task, error);
9687
9842
  });
9688
9843
  }
9689
9844
  }
@@ -9835,7 +9990,7 @@ class JsonReporter {
9835
9990
  async writeReport(report) {
9836
9991
  const outputFile = getOutputFile(this.ctx.config.benchmark, "json");
9837
9992
  if (outputFile) {
9838
- const reportFile = resolve$2(this.ctx.config.root, outputFile);
9993
+ const reportFile = resolve(this.ctx.config.root, outputFile);
9839
9994
  const outputDirectory = dirname(reportFile);
9840
9995
  if (!existsSync(outputDirectory))
9841
9996
  await promises.mkdir(outputDirectory, { recursive: true });
@@ -10134,7 +10289,6 @@ function isAggregateError(err) {
10134
10289
  class StateManager {
10135
10290
  filesMap = /* @__PURE__ */ new Map();
10136
10291
  pathsSet = /* @__PURE__ */ new Set();
10137
- collectingPromise = void 0;
10138
10292
  browserTestPromises = /* @__PURE__ */ new Map();
10139
10293
  idMap = /* @__PURE__ */ new Map();
10140
10294
  taskFileMap = /* @__PURE__ */ new WeakMap();
@@ -10192,7 +10346,9 @@ class StateManager {
10192
10346
  this.updateId(file);
10193
10347
  });
10194
10348
  }
10195
- clearFiles(project, paths = []) {
10349
+ // this file is reused by ws-client, and shoult not rely on heavy dependencies like workspace
10350
+ clearFiles(_project, paths = []) {
10351
+ const project = _project;
10196
10352
  paths.forEach((path) => {
10197
10353
  const files = this.filesMap.get(path);
10198
10354
  if (!files)
@@ -10267,6 +10423,9 @@ const defaultCoverageExcludes = [
10267
10423
  "dist/**",
10268
10424
  "packages/*/test?(s)/**",
10269
10425
  "**/*.d.ts",
10426
+ "**/virtual:*",
10427
+ "**/__x00__*",
10428
+ "**/\0*",
10270
10429
  "cypress/**",
10271
10430
  "test?(s)/**",
10272
10431
  "test?(-*).?(c|m)[jt]s?(x)",
@@ -10282,10 +10441,8 @@ const coverageConfigDefaults = {
10282
10441
  cleanOnRerun: true,
10283
10442
  reportsDirectory: "./coverage",
10284
10443
  exclude: defaultCoverageExcludes,
10285
- reportOnFailure: true,
10444
+ reportOnFailure: false,
10286
10445
  reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
10287
- // default extensions used by c8, plus '.vue' and '.svelte'
10288
- // see https://github.com/istanbuljs/schema/blob/master/default-extension.js
10289
10446
  extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"]
10290
10447
  };
10291
10448
  const fakeTimersDefaults = {
@@ -10345,6 +10502,66 @@ const config = {
10345
10502
  };
10346
10503
  const configDefaults = Object.freeze(config);
10347
10504
 
10505
+ function getDefaultThreadsCount(config) {
10506
+ return config.watch ? Math.max(Math.floor(cpus().length / 2), 1) : Math.max(cpus().length - 1, 1);
10507
+ }
10508
+ function getWorkerMemoryLimit(config) {
10509
+ if (config.experimentalVmWorkerMemoryLimit)
10510
+ return config.experimentalVmWorkerMemoryLimit;
10511
+ return 1 / (config.maxThreads ?? getDefaultThreadsCount(config));
10512
+ }
10513
+ function stringToBytes(input, percentageReference) {
10514
+ if (input === null || input === void 0)
10515
+ return input;
10516
+ if (typeof input === "string") {
10517
+ if (Number.isNaN(Number.parseFloat(input.slice(-1)))) {
10518
+ let [, numericString, trailingChars] = input.match(/(.*?)([^0-9.-]+)$/i) || [];
10519
+ if (trailingChars && numericString) {
10520
+ const numericValue = Number.parseFloat(numericString);
10521
+ trailingChars = trailingChars.toLowerCase();
10522
+ switch (trailingChars) {
10523
+ case "%":
10524
+ input = numericValue / 100;
10525
+ break;
10526
+ case "kb":
10527
+ case "k":
10528
+ return numericValue * 1e3;
10529
+ case "kib":
10530
+ return numericValue * 1024;
10531
+ case "mb":
10532
+ case "m":
10533
+ return numericValue * 1e3 * 1e3;
10534
+ case "mib":
10535
+ return numericValue * 1024 * 1024;
10536
+ case "gb":
10537
+ case "g":
10538
+ return numericValue * 1e3 * 1e3 * 1e3;
10539
+ case "gib":
10540
+ return numericValue * 1024 * 1024 * 1024;
10541
+ }
10542
+ }
10543
+ } else {
10544
+ input = Number.parseFloat(input);
10545
+ }
10546
+ }
10547
+ if (typeof input === "number") {
10548
+ if (input <= 1 && input > 0) {
10549
+ if (percentageReference) {
10550
+ return Math.floor(input * percentageReference);
10551
+ } else {
10552
+ throw new Error(
10553
+ "For a percentage based memory limit a percentageReference must be supplied"
10554
+ );
10555
+ }
10556
+ } else if (input > 1) {
10557
+ return Math.floor(input);
10558
+ } else {
10559
+ throw new Error('Unexpected numerical input for "experimentalVmWorkerMemoryLimit"');
10560
+ }
10561
+ }
10562
+ return null;
10563
+ }
10564
+
10348
10565
  class FilesStatsCache {
10349
10566
  cache = /* @__PURE__ */ new Map();
10350
10567
  getStats(key) {
@@ -10383,7 +10600,7 @@ class ResultsCache {
10383
10600
  setConfig(root, config) {
10384
10601
  this.root = root;
10385
10602
  if (config)
10386
- this.cachePath = resolve$2(config.dir, "results.json");
10603
+ this.cachePath = resolve(config.dir, "results.json");
10387
10604
  }
10388
10605
  getResults(key) {
10389
10606
  return this.cache.get(key);
@@ -10450,12 +10667,12 @@ class VitestCache {
10450
10667
  return this.stats.getStats(key);
10451
10668
  }
10452
10669
  static resolveCacheDir(root, dir) {
10453
- return resolve$2(root, slash$1(dir || "node_modules/.vitest"));
10670
+ return resolve(root, slash$1(dir || "node_modules/.vitest"));
10454
10671
  }
10455
10672
  static async clearCache(options) {
10456
10673
  var _a, _b;
10457
- const root = resolve$2(options.root || process.cwd());
10458
- const configPath = options.config === false ? false : options.config ? resolve$2(root, options.config) : await findUp(configFiles, { cwd: root });
10674
+ const root = resolve(options.root || process.cwd());
10675
+ const configPath = options.config === false ? false : options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
10459
10676
  const config = configPath ? (_a = await loadConfigFromFile({ command: "serve", mode: "test" }, configPath)) == null ? void 0 : _a.config : void 0;
10460
10677
  const cache = (_b = config == null ? void 0 : config.test) == null ? void 0 : _b.cache;
10461
10678
  if (cache === false)
@@ -10483,7 +10700,7 @@ class BaseSequencer {
10483
10700
  const shardStart = shardSize * (index - 1);
10484
10701
  const shardEnd = shardSize * index;
10485
10702
  return [...files].map((spec) => {
10486
- const fullPath = resolve$2(slash$2(config.root), slash$2(spec[1]));
10703
+ const fullPath = resolve(slash$2(config.root), slash$2(spec[1]));
10487
10704
  const specPath = fullPath == null ? void 0 : fullPath.slice(config.root.length);
10488
10705
  return {
10489
10706
  spec,
@@ -10557,7 +10774,7 @@ function resolveApiServerConfig(options) {
10557
10774
  return api;
10558
10775
  }
10559
10776
  function resolveConfig(mode, options, viteConfig) {
10560
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
10777
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
10561
10778
  if (options.dom) {
10562
10779
  if (((_a = viteConfig.test) == null ? void 0 : _a.environment) != null && viteConfig.test.environment !== "happy-dom") {
10563
10780
  console.warn(
@@ -10597,21 +10814,12 @@ function resolveConfig(mode, options, viteConfig) {
10597
10814
  throw new Error(`You cannot use ${inspectOption} without "threads: false" or "singleThread: true"`);
10598
10815
  }
10599
10816
  }
10600
- if (resolved.coverage.provider === "c8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
10601
- throw new Error("@vitest/coverage-c8 does not work with --browser. Use @vitest/coverage-istanbul instead");
10817
+ if (resolved.coverage.provider === "c8")
10818
+ throw new Error('"coverage.provider: c8" is not supported anymore. Use "coverage.provider: v8" instead');
10602
10819
  if (resolved.coverage.provider === "v8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
10603
10820
  throw new Error("@vitest/coverage-v8 does not work with --browser. Use @vitest/coverage-istanbul instead");
10604
- resolved.deps = resolved.deps || {};
10605
- if (resolved.deps.inline !== true) {
10606
- const ssrOptions = viteConfig.ssr;
10607
- if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.deps.inline == null) {
10608
- resolved.deps.inline = true;
10609
- } else {
10610
- (_b = resolved.deps).inline ?? (_b.inline = []);
10611
- resolved.deps.inline.push(...extraInlineDeps);
10612
- }
10613
- }
10614
- (_c = resolved.deps).moduleDirectories ?? (_c.moduleDirectories = ["/node_modules/"]);
10821
+ resolved.deps ?? (resolved.deps = {});
10822
+ (_b = resolved.deps).moduleDirectories ?? (_b.moduleDirectories = []);
10615
10823
  resolved.deps.moduleDirectories = resolved.deps.moduleDirectories.map((dir) => {
10616
10824
  if (!dir.startsWith("/"))
10617
10825
  dir = `/${dir}`;
@@ -10619,10 +10827,49 @@ function resolveConfig(mode, options, viteConfig) {
10619
10827
  dir += "/";
10620
10828
  return normalize(dir);
10621
10829
  });
10830
+ if (!resolved.deps.moduleDirectories.includes("/node_modules/"))
10831
+ resolved.deps.moduleDirectories.push("/node_modules/");
10832
+ resolved.server ?? (resolved.server = {});
10833
+ (_c = resolved.server).deps ?? (_c.deps = {});
10834
+ const deprecatedDepsOptions = ["inline", "external", "fallbackCJS"];
10835
+ deprecatedDepsOptions.forEach((option) => {
10836
+ if (resolved.deps[option] === void 0)
10837
+ return;
10838
+ if (option === "fallbackCJS") {
10839
+ console.warn(c.yellow(`${c.inverse(c.yellow(" Vitest "))} "deps.${option}" is deprecated. Use "server.deps.${option}" instead`));
10840
+ } else {
10841
+ const transformMode = resolved.environment === "happy-dom" || resolved.environment === "jsdom" ? "web" : "ssr";
10842
+ console.warn(
10843
+ c.yellow(
10844
+ `${c.inverse(c.yellow(" Vitest "))} "deps.${option}" is deprecated. If you rely on vite-node directly, use "server.deps.${option}" instead. Otherwise, consider using "deps.optimizer.${transformMode}.${option === "external" ? "exclude" : "include"}"`
10845
+ )
10846
+ );
10847
+ }
10848
+ if (resolved.server.deps[option] === void 0)
10849
+ resolved.server.deps[option] = resolved.deps[option];
10850
+ });
10851
+ if (resolved.server.deps.inline !== true) {
10852
+ const ssrOptions = viteConfig.ssr;
10853
+ if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.server.deps.inline == null) {
10854
+ resolved.server.deps.inline = true;
10855
+ } else {
10856
+ (_d = resolved.server.deps).inline ?? (_d.inline = []);
10857
+ resolved.server.deps.inline.push(...extraInlineDeps);
10858
+ }
10859
+ }
10860
+ (_e = resolved.server.deps).moduleDirectories ?? (_e.moduleDirectories = []);
10861
+ resolved.server.deps.moduleDirectories.push(...resolved.deps.moduleDirectories);
10622
10862
  if (resolved.runner) {
10623
- resolved.runner = resolveModule(resolved.runner, { paths: [resolved.root] }) ?? resolve$2(resolved.root, resolved.runner);
10863
+ resolved.runner = resolveModule(resolved.runner, { paths: [resolved.root] }) ?? resolve(resolved.root, resolved.runner);
10864
+ }
10865
+ if (resolved.deps.registerNodeLoader) {
10866
+ const transformMode = resolved.environment === "happy-dom" || resolved.environment === "jsdom" ? "web" : "ssr";
10867
+ console.warn(
10868
+ c.yellow(
10869
+ `${c.inverse(c.yellow(" Vitest "))} "deps.registerNodeLoader" is deprecated.If you rely on aliases inside external packages, use "deps.optimizer.${transformMode}.include" instead.`
10870
+ )
10871
+ );
10624
10872
  }
10625
- (_d = resolved.deps).registerNodeLoader ?? (_d.registerNodeLoader = false);
10626
10873
  resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
10627
10874
  const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT;
10628
10875
  resolved.snapshotOptions = {
@@ -10632,6 +10879,10 @@ function resolveConfig(mode, options, viteConfig) {
10632
10879
  // resolved inside the worker
10633
10880
  snapshotEnvironment: null
10634
10881
  };
10882
+ resolved.experimentalVmWorkerMemoryLimit = stringToBytes(
10883
+ getWorkerMemoryLimit(resolved),
10884
+ totalmem()
10885
+ );
10635
10886
  if (options.resolveSnapshotPath)
10636
10887
  delete resolved.resolveSnapshotPath;
10637
10888
  if (process.env.VITEST_MAX_THREADS)
@@ -10661,7 +10912,7 @@ function resolveConfig(mode, options, viteConfig) {
10661
10912
  }
10662
10913
  resolved.setupFiles = toArray(resolved.setupFiles || []).map(
10663
10914
  (file) => normalize(
10664
- resolveModule(file, { paths: [resolved.root] }) ?? resolve$2(resolved.root, file)
10915
+ resolveModule(file, { paths: [resolved.root] }) ?? resolve(resolved.root, file)
10665
10916
  )
10666
10917
  );
10667
10918
  resolved.coverage.exclude.push(...resolved.setupFiles.map((file) => relative(resolved.root, file)));
@@ -10671,11 +10922,11 @@ function resolveConfig(mode, options, viteConfig) {
10671
10922
  ];
10672
10923
  resolved.api = resolveApiServerConfig(options);
10673
10924
  if (options.related)
10674
- resolved.related = toArray(options.related).map((file) => resolve$2(resolved.root, file));
10925
+ resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file));
10675
10926
  if (mode !== "benchmark") {
10676
10927
  const cliReporters = toArray(resolved.reporter || []).map((reporter) => {
10677
10928
  if (/^\.\.?\//.test(reporter))
10678
- return resolve$2(process.cwd(), reporter);
10929
+ return resolve(process.cwd(), reporter);
10679
10930
  return reporter;
10680
10931
  });
10681
10932
  const reporters = cliReporters.length ? cliReporters : resolved.reporters;
@@ -10687,35 +10938,36 @@ function resolveConfig(mode, options, viteConfig) {
10687
10938
  resolved.passWithNoTests ?? (resolved.passWithNoTests = true);
10688
10939
  resolved.css ?? (resolved.css = {});
10689
10940
  if (typeof resolved.css === "object") {
10690
- (_e = resolved.css).modules ?? (_e.modules = {});
10691
- (_f = resolved.css.modules).classNameStrategy ?? (_f.classNameStrategy = "stable");
10941
+ (_f = resolved.css).modules ?? (_f.modules = {});
10942
+ (_g = resolved.css.modules).classNameStrategy ?? (_g.classNameStrategy = "stable");
10692
10943
  }
10693
10944
  resolved.cache ?? (resolved.cache = { dir: "" });
10694
10945
  if (resolved.cache)
10695
10946
  resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir);
10696
10947
  resolved.sequence ?? (resolved.sequence = {});
10697
- if (!((_g = resolved.sequence) == null ? void 0 : _g.sequencer)) {
10948
+ if (!((_h = resolved.sequence) == null ? void 0 : _h.sequencer)) {
10698
10949
  resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
10699
10950
  }
10700
- (_h = resolved.sequence).hooks ?? (_h.hooks = "parallel");
10951
+ (_i = resolved.sequence).hooks ?? (_i.hooks = "parallel");
10701
10952
  if (resolved.sequence.sequencer === RandomSequencer)
10702
- (_i = resolved.sequence).seed ?? (_i.seed = Date.now());
10953
+ (_j = resolved.sequence).seed ?? (_j.seed = Date.now());
10703
10954
  resolved.typecheck = {
10704
10955
  ...configDefaults.typecheck,
10705
10956
  ...resolved.typecheck
10706
10957
  };
10707
- resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map((i) => [resolve$2(resolved.root, i[0]), i[1]]);
10958
+ resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map((i) => [resolve(resolved.root, i[0]), i[1]]);
10708
10959
  if (mode === "typecheck") {
10709
10960
  resolved.include = resolved.typecheck.include;
10710
10961
  resolved.exclude = resolved.typecheck.exclude;
10711
10962
  }
10712
10963
  resolved.browser ?? (resolved.browser = {});
10713
- (_j = resolved.browser).enabled ?? (_j.enabled = false);
10714
- (_k = resolved.browser).headless ?? (_k.headless = isCI);
10715
- (_l = resolved.browser).slowHijackESM ?? (_l.slowHijackESM = true);
10964
+ (_k = resolved.browser).enabled ?? (_k.enabled = false);
10965
+ (_l = resolved.browser).headless ?? (_l.headless = isCI);
10966
+ (_m = resolved.browser).slowHijackESM ?? (_m.slowHijackESM = true);
10716
10967
  resolved.browser.api = resolveApiServerConfig(resolved.browser) || {
10717
10968
  port: defaultBrowserPort
10718
10969
  };
10970
+ resolved.testTransformMode ?? (resolved.testTransformMode = {});
10719
10971
  return resolved;
10720
10972
  }
10721
10973
  function isBrowserEnabled(config) {
@@ -10725,7 +10977,7 @@ function isBrowserEnabled(config) {
10725
10977
  return ((_b = config.poolMatchGlobs) == null ? void 0 : _b.length) && config.poolMatchGlobs.some(([, pool]) => pool === "browser");
10726
10978
  }
10727
10979
 
10728
- const ESC = '\u001B[';
10980
+ const ESC$1 = '\u001B[';
10729
10981
  const OSC = '\u001B]';
10730
10982
  const BEL = '\u0007';
10731
10983
  const SEP = ';';
@@ -10739,10 +10991,10 @@ ansiEscapes.cursorTo = (x, y) => {
10739
10991
  }
10740
10992
 
10741
10993
  if (typeof y !== 'number') {
10742
- return ESC + (x + 1) + 'G';
10994
+ return ESC$1 + (x + 1) + 'G';
10743
10995
  }
10744
10996
 
10745
- return ESC + (y + 1) + ';' + (x + 1) + 'H';
10997
+ return ESC$1 + (y + 1) + ';' + (x + 1) + 'H';
10746
10998
  };
10747
10999
 
10748
11000
  ansiEscapes.cursorMove = (x, y) => {
@@ -10753,33 +11005,33 @@ ansiEscapes.cursorMove = (x, y) => {
10753
11005
  let returnValue = '';
10754
11006
 
10755
11007
  if (x < 0) {
10756
- returnValue += ESC + (-x) + 'D';
11008
+ returnValue += ESC$1 + (-x) + 'D';
10757
11009
  } else if (x > 0) {
10758
- returnValue += ESC + x + 'C';
11010
+ returnValue += ESC$1 + x + 'C';
10759
11011
  }
10760
11012
 
10761
11013
  if (y < 0) {
10762
- returnValue += ESC + (-y) + 'A';
11014
+ returnValue += ESC$1 + (-y) + 'A';
10763
11015
  } else if (y > 0) {
10764
- returnValue += ESC + y + 'B';
11016
+ returnValue += ESC$1 + y + 'B';
10765
11017
  }
10766
11018
 
10767
11019
  return returnValue;
10768
11020
  };
10769
11021
 
10770
- ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A';
10771
- ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B';
10772
- ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C';
10773
- ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D';
11022
+ ansiEscapes.cursorUp = (count = 1) => ESC$1 + count + 'A';
11023
+ ansiEscapes.cursorDown = (count = 1) => ESC$1 + count + 'B';
11024
+ ansiEscapes.cursorForward = (count = 1) => ESC$1 + count + 'C';
11025
+ ansiEscapes.cursorBackward = (count = 1) => ESC$1 + count + 'D';
10774
11026
 
10775
- ansiEscapes.cursorLeft = ESC + 'G';
10776
- ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's';
10777
- ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u';
10778
- ansiEscapes.cursorGetPosition = ESC + '6n';
10779
- ansiEscapes.cursorNextLine = ESC + 'E';
10780
- ansiEscapes.cursorPrevLine = ESC + 'F';
10781
- ansiEscapes.cursorHide = ESC + '?25l';
10782
- ansiEscapes.cursorShow = ESC + '?25h';
11027
+ ansiEscapes.cursorLeft = ESC$1 + 'G';
11028
+ ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC$1 + 's';
11029
+ ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC$1 + 'u';
11030
+ ansiEscapes.cursorGetPosition = ESC$1 + '6n';
11031
+ ansiEscapes.cursorNextLine = ESC$1 + 'E';
11032
+ ansiEscapes.cursorPrevLine = ESC$1 + 'F';
11033
+ ansiEscapes.cursorHide = ESC$1 + '?25l';
11034
+ ansiEscapes.cursorShow = ESC$1 + '?25h';
10783
11035
 
10784
11036
  ansiEscapes.eraseLines = count => {
10785
11037
  let clear = '';
@@ -10795,24 +11047,24 @@ ansiEscapes.eraseLines = count => {
10795
11047
  return clear;
10796
11048
  };
10797
11049
 
10798
- ansiEscapes.eraseEndLine = ESC + 'K';
10799
- ansiEscapes.eraseStartLine = ESC + '1K';
10800
- ansiEscapes.eraseLine = ESC + '2K';
10801
- ansiEscapes.eraseDown = ESC + 'J';
10802
- ansiEscapes.eraseUp = ESC + '1J';
10803
- ansiEscapes.eraseScreen = ESC + '2J';
10804
- ansiEscapes.scrollUp = ESC + 'S';
10805
- ansiEscapes.scrollDown = ESC + 'T';
11050
+ ansiEscapes.eraseEndLine = ESC$1 + 'K';
11051
+ ansiEscapes.eraseStartLine = ESC$1 + '1K';
11052
+ ansiEscapes.eraseLine = ESC$1 + '2K';
11053
+ ansiEscapes.eraseDown = ESC$1 + 'J';
11054
+ ansiEscapes.eraseUp = ESC$1 + '1J';
11055
+ ansiEscapes.eraseScreen = ESC$1 + '2J';
11056
+ ansiEscapes.scrollUp = ESC$1 + 'S';
11057
+ ansiEscapes.scrollDown = ESC$1 + 'T';
10806
11058
 
10807
11059
  ansiEscapes.clearScreen = '\u001Bc';
10808
11060
 
10809
11061
  ansiEscapes.clearTerminal = process.platform === 'win32' ?
10810
- `${ansiEscapes.eraseScreen}${ESC}0f` :
11062
+ `${ansiEscapes.eraseScreen}${ESC$1}0f` :
10811
11063
  // 1. Erases the screen (Only done in case `2` is not supported)
10812
11064
  // 2. Erases the whole screen including scrollback buffer
10813
11065
  // 3. Moves cursor to the top-left position
10814
11066
  // More info: https://www.real-world-systems.com/docs/ANSIcode.html
10815
- `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`;
11067
+ `${ansiEscapes.eraseScreen}${ESC$1}3J${ESC$1}H`;
10816
11068
 
10817
11069
  ansiEscapes.beep = BEL;
10818
11070
 
@@ -11276,633 +11528,7 @@ createLogUpdate(process$1.stdout);
11276
11528
 
11277
11529
  createLogUpdate(process$1.stderr);
11278
11530
 
11279
- var version = "0.33.0";
11280
-
11281
- const comma = ','.charCodeAt(0);
11282
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
11283
- const intToChar = new Uint8Array(64); // 64 possible chars.
11284
- const charToInt = new Uint8Array(128); // z is 122 in ASCII
11285
- for (let i = 0; i < chars.length; i++) {
11286
- const c = chars.charCodeAt(i);
11287
- intToChar[i] = c;
11288
- charToInt[c] = i;
11289
- }
11290
- function decode(mappings) {
11291
- const state = new Int32Array(5);
11292
- const decoded = [];
11293
- let index = 0;
11294
- do {
11295
- const semi = indexOf(mappings, index);
11296
- const line = [];
11297
- let sorted = true;
11298
- let lastCol = 0;
11299
- state[0] = 0;
11300
- for (let i = index; i < semi; i++) {
11301
- let seg;
11302
- i = decodeInteger(mappings, i, state, 0); // genColumn
11303
- const col = state[0];
11304
- if (col < lastCol)
11305
- sorted = false;
11306
- lastCol = col;
11307
- if (hasMoreVlq(mappings, i, semi)) {
11308
- i = decodeInteger(mappings, i, state, 1); // sourcesIndex
11309
- i = decodeInteger(mappings, i, state, 2); // sourceLine
11310
- i = decodeInteger(mappings, i, state, 3); // sourceColumn
11311
- if (hasMoreVlq(mappings, i, semi)) {
11312
- i = decodeInteger(mappings, i, state, 4); // namesIndex
11313
- seg = [col, state[1], state[2], state[3], state[4]];
11314
- }
11315
- else {
11316
- seg = [col, state[1], state[2], state[3]];
11317
- }
11318
- }
11319
- else {
11320
- seg = [col];
11321
- }
11322
- line.push(seg);
11323
- }
11324
- if (!sorted)
11325
- sort(line);
11326
- decoded.push(line);
11327
- index = semi + 1;
11328
- } while (index <= mappings.length);
11329
- return decoded;
11330
- }
11331
- function indexOf(mappings, index) {
11332
- const idx = mappings.indexOf(';', index);
11333
- return idx === -1 ? mappings.length : idx;
11334
- }
11335
- function decodeInteger(mappings, pos, state, j) {
11336
- let value = 0;
11337
- let shift = 0;
11338
- let integer = 0;
11339
- do {
11340
- const c = mappings.charCodeAt(pos++);
11341
- integer = charToInt[c];
11342
- value |= (integer & 31) << shift;
11343
- shift += 5;
11344
- } while (integer & 32);
11345
- const shouldNegate = value & 1;
11346
- value >>>= 1;
11347
- if (shouldNegate) {
11348
- value = -0x80000000 | -value;
11349
- }
11350
- state[j] += value;
11351
- return pos;
11352
- }
11353
- function hasMoreVlq(mappings, i, length) {
11354
- if (i >= length)
11355
- return false;
11356
- return mappings.charCodeAt(i) !== comma;
11357
- }
11358
- function sort(line) {
11359
- line.sort(sortComparator$1);
11360
- }
11361
- function sortComparator$1(a, b) {
11362
- return a[0] - b[0];
11363
- }
11364
-
11365
- // Matches the scheme of a URL, eg "http://"
11366
- const schemeRegex = /^[\w+.-]+:\/\//;
11367
- /**
11368
- * Matches the parts of a URL:
11369
- * 1. Scheme, including ":", guaranteed.
11370
- * 2. User/password, including "@", optional.
11371
- * 3. Host, guaranteed.
11372
- * 4. Port, including ":", optional.
11373
- * 5. Path, including "/", optional.
11374
- * 6. Query, including "?", optional.
11375
- * 7. Hash, including "#", optional.
11376
- */
11377
- const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
11378
- /**
11379
- * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
11380
- * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
11381
- *
11382
- * 1. Host, optional.
11383
- * 2. Path, which may include "/", guaranteed.
11384
- * 3. Query, including "?", optional.
11385
- * 4. Hash, including "#", optional.
11386
- */
11387
- const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
11388
- var UrlType;
11389
- (function (UrlType) {
11390
- UrlType[UrlType["Empty"] = 1] = "Empty";
11391
- UrlType[UrlType["Hash"] = 2] = "Hash";
11392
- UrlType[UrlType["Query"] = 3] = "Query";
11393
- UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
11394
- UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
11395
- UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
11396
- UrlType[UrlType["Absolute"] = 7] = "Absolute";
11397
- })(UrlType || (UrlType = {}));
11398
- function isAbsoluteUrl(input) {
11399
- return schemeRegex.test(input);
11400
- }
11401
- function isSchemeRelativeUrl(input) {
11402
- return input.startsWith('//');
11403
- }
11404
- function isAbsolutePath(input) {
11405
- return input.startsWith('/');
11406
- }
11407
- function isFileUrl(input) {
11408
- return input.startsWith('file:');
11409
- }
11410
- function isRelative(input) {
11411
- return /^[.?#]/.test(input);
11412
- }
11413
- function parseAbsoluteUrl(input) {
11414
- const match = urlRegex.exec(input);
11415
- return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
11416
- }
11417
- function parseFileUrl(input) {
11418
- const match = fileRegex.exec(input);
11419
- const path = match[2];
11420
- return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
11421
- }
11422
- function makeUrl(scheme, user, host, port, path, query, hash) {
11423
- return {
11424
- scheme,
11425
- user,
11426
- host,
11427
- port,
11428
- path,
11429
- query,
11430
- hash,
11431
- type: UrlType.Absolute,
11432
- };
11433
- }
11434
- function parseUrl(input) {
11435
- if (isSchemeRelativeUrl(input)) {
11436
- const url = parseAbsoluteUrl('http:' + input);
11437
- url.scheme = '';
11438
- url.type = UrlType.SchemeRelative;
11439
- return url;
11440
- }
11441
- if (isAbsolutePath(input)) {
11442
- const url = parseAbsoluteUrl('http://foo.com' + input);
11443
- url.scheme = '';
11444
- url.host = '';
11445
- url.type = UrlType.AbsolutePath;
11446
- return url;
11447
- }
11448
- if (isFileUrl(input))
11449
- return parseFileUrl(input);
11450
- if (isAbsoluteUrl(input))
11451
- return parseAbsoluteUrl(input);
11452
- const url = parseAbsoluteUrl('http://foo.com/' + input);
11453
- url.scheme = '';
11454
- url.host = '';
11455
- url.type = input
11456
- ? input.startsWith('?')
11457
- ? UrlType.Query
11458
- : input.startsWith('#')
11459
- ? UrlType.Hash
11460
- : UrlType.RelativePath
11461
- : UrlType.Empty;
11462
- return url;
11463
- }
11464
- function stripPathFilename(path) {
11465
- // If a path ends with a parent directory "..", then it's a relative path with excess parent
11466
- // paths. It's not a file, so we can't strip it.
11467
- if (path.endsWith('/..'))
11468
- return path;
11469
- const index = path.lastIndexOf('/');
11470
- return path.slice(0, index + 1);
11471
- }
11472
- function mergePaths(url, base) {
11473
- normalizePath(base, base.type);
11474
- // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
11475
- // path).
11476
- if (url.path === '/') {
11477
- url.path = base.path;
11478
- }
11479
- else {
11480
- // Resolution happens relative to the base path's directory, not the file.
11481
- url.path = stripPathFilename(base.path) + url.path;
11482
- }
11483
- }
11484
- /**
11485
- * The path can have empty directories "//", unneeded parents "foo/..", or current directory
11486
- * "foo/.". We need to normalize to a standard representation.
11487
- */
11488
- function normalizePath(url, type) {
11489
- const rel = type <= UrlType.RelativePath;
11490
- const pieces = url.path.split('/');
11491
- // We need to preserve the first piece always, so that we output a leading slash. The item at
11492
- // pieces[0] is an empty string.
11493
- let pointer = 1;
11494
- // Positive is the number of real directories we've output, used for popping a parent directory.
11495
- // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
11496
- let positive = 0;
11497
- // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
11498
- // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
11499
- // real directory, we won't need to append, unless the other conditions happen again.
11500
- let addTrailingSlash = false;
11501
- for (let i = 1; i < pieces.length; i++) {
11502
- const piece = pieces[i];
11503
- // An empty directory, could be a trailing slash, or just a double "//" in the path.
11504
- if (!piece) {
11505
- addTrailingSlash = true;
11506
- continue;
11507
- }
11508
- // If we encounter a real directory, then we don't need to append anymore.
11509
- addTrailingSlash = false;
11510
- // A current directory, which we can always drop.
11511
- if (piece === '.')
11512
- continue;
11513
- // A parent directory, we need to see if there are any real directories we can pop. Else, we
11514
- // have an excess of parents, and we'll need to keep the "..".
11515
- if (piece === '..') {
11516
- if (positive) {
11517
- addTrailingSlash = true;
11518
- positive--;
11519
- pointer--;
11520
- }
11521
- else if (rel) {
11522
- // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
11523
- // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
11524
- pieces[pointer++] = piece;
11525
- }
11526
- continue;
11527
- }
11528
- // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
11529
- // any popped or dropped directories.
11530
- pieces[pointer++] = piece;
11531
- positive++;
11532
- }
11533
- let path = '';
11534
- for (let i = 1; i < pointer; i++) {
11535
- path += '/' + pieces[i];
11536
- }
11537
- if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
11538
- path += '/';
11539
- }
11540
- url.path = path;
11541
- }
11542
- /**
11543
- * Attempts to resolve `input` URL/path relative to `base`.
11544
- */
11545
- function resolve$1(input, base) {
11546
- if (!input && !base)
11547
- return '';
11548
- const url = parseUrl(input);
11549
- let inputType = url.type;
11550
- if (base && inputType !== UrlType.Absolute) {
11551
- const baseUrl = parseUrl(base);
11552
- const baseType = baseUrl.type;
11553
- switch (inputType) {
11554
- case UrlType.Empty:
11555
- url.hash = baseUrl.hash;
11556
- // fall through
11557
- case UrlType.Hash:
11558
- url.query = baseUrl.query;
11559
- // fall through
11560
- case UrlType.Query:
11561
- case UrlType.RelativePath:
11562
- mergePaths(url, baseUrl);
11563
- // fall through
11564
- case UrlType.AbsolutePath:
11565
- // The host, user, and port are joined, you can't copy one without the others.
11566
- url.user = baseUrl.user;
11567
- url.host = baseUrl.host;
11568
- url.port = baseUrl.port;
11569
- // fall through
11570
- case UrlType.SchemeRelative:
11571
- // The input doesn't have a schema at least, so we need to copy at least that over.
11572
- url.scheme = baseUrl.scheme;
11573
- }
11574
- if (baseType > inputType)
11575
- inputType = baseType;
11576
- }
11577
- normalizePath(url, inputType);
11578
- const queryHash = url.query + url.hash;
11579
- switch (inputType) {
11580
- // This is impossible, because of the empty checks at the start of the function.
11581
- // case UrlType.Empty:
11582
- case UrlType.Hash:
11583
- case UrlType.Query:
11584
- return queryHash;
11585
- case UrlType.RelativePath: {
11586
- // The first char is always a "/", and we need it to be relative.
11587
- const path = url.path.slice(1);
11588
- if (!path)
11589
- return queryHash || '.';
11590
- if (isRelative(base || input) && !isRelative(path)) {
11591
- // If base started with a leading ".", or there is no base and input started with a ".",
11592
- // then we need to ensure that the relative path starts with a ".". We don't know if
11593
- // relative starts with a "..", though, so check before prepending.
11594
- return './' + path + queryHash;
11595
- }
11596
- return path + queryHash;
11597
- }
11598
- case UrlType.AbsolutePath:
11599
- return url.path + queryHash;
11600
- default:
11601
- return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
11602
- }
11603
- }
11604
-
11605
- function resolve(input, base) {
11606
- // The base is always treated as a directory, if it's not empty.
11607
- // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
11608
- // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
11609
- if (base && !base.endsWith('/'))
11610
- base += '/';
11611
- return resolve$1(input, base);
11612
- }
11613
-
11614
- /**
11615
- * Removes everything after the last "/", but leaves the slash.
11616
- */
11617
- function stripFilename(path) {
11618
- if (!path)
11619
- return '';
11620
- const index = path.lastIndexOf('/');
11621
- return path.slice(0, index + 1);
11622
- }
11623
-
11624
- const COLUMN = 0;
11625
- const SOURCES_INDEX = 1;
11626
- const SOURCE_LINE = 2;
11627
- const SOURCE_COLUMN = 3;
11628
- const REV_GENERATED_LINE = 1;
11629
- const REV_GENERATED_COLUMN = 2;
11630
-
11631
- function maybeSort(mappings, owned) {
11632
- const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
11633
- if (unsortedIndex === mappings.length)
11634
- return mappings;
11635
- // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
11636
- // not, we do not want to modify the consumer's input array.
11637
- if (!owned)
11638
- mappings = mappings.slice();
11639
- for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
11640
- mappings[i] = sortSegments(mappings[i], owned);
11641
- }
11642
- return mappings;
11643
- }
11644
- function nextUnsortedSegmentLine(mappings, start) {
11645
- for (let i = start; i < mappings.length; i++) {
11646
- if (!isSorted(mappings[i]))
11647
- return i;
11648
- }
11649
- return mappings.length;
11650
- }
11651
- function isSorted(line) {
11652
- for (let j = 1; j < line.length; j++) {
11653
- if (line[j][COLUMN] < line[j - 1][COLUMN]) {
11654
- return false;
11655
- }
11656
- }
11657
- return true;
11658
- }
11659
- function sortSegments(line, owned) {
11660
- if (!owned)
11661
- line = line.slice();
11662
- return line.sort(sortComparator);
11663
- }
11664
- function sortComparator(a, b) {
11665
- return a[COLUMN] - b[COLUMN];
11666
- }
11667
-
11668
- let found = false;
11669
- /**
11670
- * A binary search implementation that returns the index if a match is found.
11671
- * If no match is found, then the left-index (the index associated with the item that comes just
11672
- * before the desired index) is returned. To maintain proper sort order, a splice would happen at
11673
- * the next index:
11674
- *
11675
- * ```js
11676
- * const array = [1, 3];
11677
- * const needle = 2;
11678
- * const index = binarySearch(array, needle, (item, needle) => item - needle);
11679
- *
11680
- * assert.equal(index, 0);
11681
- * array.splice(index + 1, 0, needle);
11682
- * assert.deepEqual(array, [1, 2, 3]);
11683
- * ```
11684
- */
11685
- function binarySearch(haystack, needle, low, high) {
11686
- while (low <= high) {
11687
- const mid = low + ((high - low) >> 1);
11688
- const cmp = haystack[mid][COLUMN] - needle;
11689
- if (cmp === 0) {
11690
- found = true;
11691
- return mid;
11692
- }
11693
- if (cmp < 0) {
11694
- low = mid + 1;
11695
- }
11696
- else {
11697
- high = mid - 1;
11698
- }
11699
- }
11700
- found = false;
11701
- return low - 1;
11702
- }
11703
- function upperBound(haystack, needle, index) {
11704
- for (let i = index + 1; i < haystack.length; index = i++) {
11705
- if (haystack[i][COLUMN] !== needle)
11706
- break;
11707
- }
11708
- return index;
11709
- }
11710
- function lowerBound(haystack, needle, index) {
11711
- for (let i = index - 1; i >= 0; index = i--) {
11712
- if (haystack[i][COLUMN] !== needle)
11713
- break;
11714
- }
11715
- return index;
11716
- }
11717
- function memoizedState() {
11718
- return {
11719
- lastKey: -1,
11720
- lastNeedle: -1,
11721
- lastIndex: -1,
11722
- };
11723
- }
11724
- /**
11725
- * This overly complicated beast is just to record the last tested line/column and the resulting
11726
- * index, allowing us to skip a few tests if mappings are monotonically increasing.
11727
- */
11728
- function memoizedBinarySearch(haystack, needle, state, key) {
11729
- const { lastKey, lastNeedle, lastIndex } = state;
11730
- let low = 0;
11731
- let high = haystack.length - 1;
11732
- if (key === lastKey) {
11733
- if (needle === lastNeedle) {
11734
- found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
11735
- return lastIndex;
11736
- }
11737
- if (needle >= lastNeedle) {
11738
- // lastIndex may be -1 if the previous needle was not found.
11739
- low = lastIndex === -1 ? 0 : lastIndex;
11740
- }
11741
- else {
11742
- high = lastIndex;
11743
- }
11744
- }
11745
- state.lastKey = key;
11746
- state.lastNeedle = needle;
11747
- return (state.lastIndex = binarySearch(haystack, needle, low, high));
11748
- }
11749
-
11750
- // Rebuilds the original source files, with mappings that are ordered by source line/column instead
11751
- // of generated line/column.
11752
- function buildBySources(decoded, memos) {
11753
- const sources = memos.map(buildNullArray);
11754
- for (let i = 0; i < decoded.length; i++) {
11755
- const line = decoded[i];
11756
- for (let j = 0; j < line.length; j++) {
11757
- const seg = line[j];
11758
- if (seg.length === 1)
11759
- continue;
11760
- const sourceIndex = seg[SOURCES_INDEX];
11761
- const sourceLine = seg[SOURCE_LINE];
11762
- const sourceColumn = seg[SOURCE_COLUMN];
11763
- const originalSource = sources[sourceIndex];
11764
- const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = []));
11765
- const memo = memos[sourceIndex];
11766
- // The binary search either found a match, or it found the left-index just before where the
11767
- // segment should go. Either way, we want to insert after that. And there may be multiple
11768
- // generated segments associated with an original location, so there may need to move several
11769
- // indexes before we find where we need to insert.
11770
- const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine));
11771
- insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);
11772
- }
11773
- }
11774
- return sources;
11775
- }
11776
- function insert(array, index, value) {
11777
- for (let i = array.length; i > index; i--) {
11778
- array[i] = array[i - 1];
11779
- }
11780
- array[index] = value;
11781
- }
11782
- // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like
11783
- // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.
11784
- // Numeric properties on objects are magically sorted in ascending order by the engine regardless of
11785
- // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending
11786
- // order when iterating with for-in.
11787
- function buildNullArray() {
11788
- return { __proto__: null };
11789
- }
11790
-
11791
- const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
11792
- const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
11793
- const LEAST_UPPER_BOUND = -1;
11794
- const GREATEST_LOWER_BOUND = 1;
11795
- /**
11796
- * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
11797
- */
11798
- let decodedMappings;
11799
- /**
11800
- * Finds the generated line/column position of the provided source/line/column source position.
11801
- */
11802
- let generatedPositionFor;
11803
- class TraceMap {
11804
- constructor(map, mapUrl) {
11805
- const isString = typeof map === 'string';
11806
- if (!isString && map._decodedMemo)
11807
- return map;
11808
- const parsed = (isString ? JSON.parse(map) : map);
11809
- const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
11810
- this.version = version;
11811
- this.file = file;
11812
- this.names = names;
11813
- this.sourceRoot = sourceRoot;
11814
- this.sources = sources;
11815
- this.sourcesContent = sourcesContent;
11816
- const from = resolve(sourceRoot || '', stripFilename(mapUrl));
11817
- this.resolvedSources = sources.map((s) => resolve(s || '', from));
11818
- const { mappings } = parsed;
11819
- if (typeof mappings === 'string') {
11820
- this._encoded = mappings;
11821
- this._decoded = undefined;
11822
- }
11823
- else {
11824
- this._encoded = undefined;
11825
- this._decoded = maybeSort(mappings, isString);
11826
- }
11827
- this._decodedMemo = memoizedState();
11828
- this._bySources = undefined;
11829
- this._bySourceMemos = undefined;
11830
- }
11831
- }
11832
- (() => {
11833
- decodedMappings = (map) => {
11834
- return (map._decoded || (map._decoded = decode(map._encoded)));
11835
- };
11836
- generatedPositionFor = (map, { source, line, column, bias }) => {
11837
- return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);
11838
- };
11839
- function generatedPosition(map, source, line, column, bias, all) {
11840
- line--;
11841
- if (line < 0)
11842
- throw new Error(LINE_GTR_ZERO);
11843
- if (column < 0)
11844
- throw new Error(COL_GTR_EQ_ZERO);
11845
- const { sources, resolvedSources } = map;
11846
- let sourceIndex = sources.indexOf(source);
11847
- if (sourceIndex === -1)
11848
- sourceIndex = resolvedSources.indexOf(source);
11849
- if (sourceIndex === -1)
11850
- return all ? [] : GMapping(null, null);
11851
- const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState)))));
11852
- const segments = generated[sourceIndex][line];
11853
- if (segments == null)
11854
- return all ? [] : GMapping(null, null);
11855
- const memo = map._bySourceMemos[sourceIndex];
11856
- if (all)
11857
- return sliceGeneratedPositions(segments, memo, line, column, bias);
11858
- const index = traceSegmentInternal(segments, memo, line, column, bias);
11859
- if (index === -1)
11860
- return GMapping(null, null);
11861
- const segment = segments[index];
11862
- return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
11863
- }
11864
- })();
11865
- function GMapping(line, column) {
11866
- return { line, column };
11867
- }
11868
- function traceSegmentInternal(segments, memo, line, column, bias) {
11869
- let index = memoizedBinarySearch(segments, column, memo, line);
11870
- if (found) {
11871
- index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
11872
- }
11873
- else if (bias === LEAST_UPPER_BOUND)
11874
- index++;
11875
- if (index === -1 || index === segments.length)
11876
- return -1;
11877
- return index;
11878
- }
11879
- function sliceGeneratedPositions(segments, memo, line, column, bias) {
11880
- let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);
11881
- // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in
11882
- // insertion order) segment that matched. Even if we did respect the bias when tracing, we would
11883
- // still need to call `lowerBound()` to find the first segment, which is slower than just looking
11884
- // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the
11885
- // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to
11886
- // match LEAST_UPPER_BOUND.
11887
- if (!found && bias === LEAST_UPPER_BOUND)
11888
- min++;
11889
- if (min === -1 || min === segments.length)
11890
- return [];
11891
- // We may have found the segment that started at an earlier column. If this is the case, then we
11892
- // need to slice all generated segments that match _that_ column, because all such segments span
11893
- // to our desired column.
11894
- const matchedColumn = found ? column : segments[min][COLUMN];
11895
- // The binary search is not guaranteed to find the lower bound when a match wasn't found.
11896
- if (!found)
11897
- min = lowerBound(segments, matchedColumn, min);
11898
- const max = upperBound(segments, matchedColumn, min);
11899
- const result = [];
11900
- for (; min <= max; min++) {
11901
- const segment = segments[min];
11902
- result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));
11903
- }
11904
- return result;
11905
- }
11531
+ var version = "0.34.1";
11906
11532
 
11907
11533
  const A=r=>r!==null&&typeof r=="object",a=(r,t)=>Object.assign(new Error(`[${r}]: ${t}`),{code:r}),_$1="ERR_INVALID_PACKAGE_CONFIG",E="ERR_INVALID_PACKAGE_TARGET",I="ERR_PACKAGE_PATH_NOT_EXPORTED",R$1=/^\d+$/,O=/^(\.{1,2}|node_modules)$/i,w=/\/|\\/;var h=(r=>(r.Export="exports",r.Import="imports",r))(h||{});const f=(r,t,e,o,c)=>{if(t==null)return [];if(typeof t=="string"){const[n,...i]=t.split(w);if(n===".."||i.some(l=>O.test(l)))throw a(E,`Invalid "${r}" target "${t}" defined in the package config`);return [c?t.replace(/\*/g,c):t]}if(Array.isArray(t))return t.flatMap(n=>f(r,n,e,o,c));if(A(t)){for(const n of Object.keys(t)){if(R$1.test(n))throw a(_$1,"Cannot contain numeric property keys");if(n==="default"||o.includes(n))return f(r,t[n],e,o,c)}return []}throw a(E,`Invalid "${r}" target "${t}"`)},s="*",m=(r,t)=>{const e=r.indexOf(s),o=t.indexOf(s);return e===o?t.length>r.length:o>e};function d$1(r,t){if(!t.includes(s)&&r.hasOwnProperty(t))return [t];let e,o;for(const c of Object.keys(r))if(c.includes(s)){const[n,i,l]=c.split(s);if(l===void 0&&t.startsWith(n)&&t.endsWith(i)){const g=t.slice(n.length,-i.length||void 0);g&&(!e||m(e,c))&&(e=c,o=g);}}return [e,o]}const p=r=>Object.keys(r).reduce((t,e)=>{const o=e===""||e[0]!==".";if(t===void 0||t===o)return o;throw a(_$1,'"exports" cannot contain some keys starting with "." and some not')},void 0),u=/^\w+:/,v=(r,t,e)=>{if(!r)throw new Error('"exports" is required');t=t===""?".":`./${t}`,(typeof r=="string"||Array.isArray(r)||A(r)&&p(r))&&(r={".":r});const[o,c]=d$1(r,t),n=f(h.Export,r[o],t,e,c);if(n.length===0)throw a(I,t==="."?'No "exports" main defined':`Package subpath '${t}' is not defined by "exports"`);for(const i of n)if(!i.startsWith("./")&&!u.test(i))throw a(E,`Invalid "exports" target "${i}" defined in the package config`);return n};
11908
11534
 
@@ -11947,7 +11573,7 @@ async function makeTscErrorInfo(errInfo) {
11947
11573
  }
11948
11574
  async function getTsconfig(root, config) {
11949
11575
  const configName = config.tsconfig ? basename(config.tsconfig) : void 0;
11950
- const configSearchPath = config.tsconfig ? dirname(resolve$2(root, config.tsconfig)) : root;
11576
+ const configSearchPath = config.tsconfig ? dirname(resolve(root, config.tsconfig)) : root;
11951
11577
  const tsconfig = Te(configSearchPath, configName);
11952
11578
  if (!tsconfig)
11953
11579
  throw new Error("no tsconfig.json found");
@@ -12270,7 +11896,7 @@ class Typechecker {
12270
11896
  const errorsMap = await getRawErrsMapFromTsCompile(output);
12271
11897
  const typesErrors = /* @__PURE__ */ new Map();
12272
11898
  errorsMap.forEach((errors, path) => {
12273
- const filepath = resolve$2(this.ctx.config.root, path);
11899
+ const filepath = resolve(this.ctx.config.root, path);
12274
11900
  const suiteErrors = errors.map((info) => {
12275
11901
  const limit = Error.stackTraceLimit;
12276
11902
  Error.stackTraceLimit = 0;
@@ -12379,8 +12005,9 @@ class Typechecker {
12379
12005
  }
12380
12006
  }
12381
12007
 
12382
- async function printError(error, ctx, options = {}) {
12008
+ async function printError(error, project, options) {
12383
12009
  const { showCodeFrame = true, fullStack = false, type } = options;
12010
+ const logger = options.logger;
12384
12011
  let e = error;
12385
12012
  if (isPrimitive(e)) {
12386
12013
  e = {
@@ -12395,25 +12022,31 @@ async function printError(error, ctx, options = {}) {
12395
12022
  stack: error2.stack
12396
12023
  };
12397
12024
  }
12398
- if (!ctx.config)
12399
- return printErrorMessage(e, ctx.logger);
12400
- const stacks = parseErrorStacktrace(e, fullStack ? [] : void 0);
12025
+ if (!project)
12026
+ return printErrorMessage(e, logger);
12027
+ const parserOptions = {
12028
+ // only browser stack traces require remapping
12029
+ getSourceMap: (file) => project.getBrowserSourceMapModuleById(file)
12030
+ };
12031
+ if (fullStack)
12032
+ parserOptions.ignoreStackEntries = [];
12033
+ const stacks = parseErrorStacktrace(e, parserOptions);
12401
12034
  const nearest = error instanceof TypeCheckError ? error.stacks[0] : stacks.find(
12402
- (stack) => ctx.getModuleProjects(stack.file).length && existsSync(stack.file)
12035
+ (stack) => project.getModuleById(stack.file) && existsSync(stack.file)
12403
12036
  );
12404
12037
  const errorProperties = getErrorProperties(e);
12405
12038
  if (type)
12406
- printErrorType(type, ctx);
12407
- printErrorMessage(e, ctx.logger);
12039
+ printErrorType(type, project.ctx);
12040
+ printErrorMessage(e, logger);
12408
12041
  if (e.diff)
12409
- displayDiff(e.diff, ctx.logger.console);
12042
+ displayDiff(e.diff, logger.console);
12410
12043
  if (e.frame) {
12411
- ctx.logger.error(c.yellow(e.frame));
12044
+ logger.error(c.yellow(e.frame));
12412
12045
  } else {
12413
- printStack(ctx, stacks, nearest, errorProperties, (s) => {
12046
+ printStack(project, stacks, nearest, errorProperties, (s) => {
12414
12047
  if (showCodeFrame && s === nearest && nearest) {
12415
12048
  const sourceCode = readFileSync(nearest.file, "utf-8");
12416
- ctx.logger.error(generateCodeFrame(sourceCode, 4, s.line, s.column));
12049
+ logger.error(generateCodeFrame(sourceCode, 4, s.line, s.column));
12417
12050
  }
12418
12051
  });
12419
12052
  }
@@ -12421,20 +12054,20 @@ async function printError(error, ctx, options = {}) {
12421
12054
  const testName = e.VITEST_TEST_NAME;
12422
12055
  const afterEnvTeardown = e.VITEST_AFTER_ENV_TEARDOWN;
12423
12056
  if (testPath)
12424
- ctx.logger.error(c.red(`This error originated in "${c.bold(testPath)}" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.`));
12057
+ logger.error(c.red(`This error originated in "${c.bold(testPath)}" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.`));
12425
12058
  if (testName) {
12426
- ctx.logger.error(c.red(`The latest test that might've caused the error is "${c.bold(testName)}". It might mean one of the following:
12059
+ logger.error(c.red(`The latest test that might've caused the error is "${c.bold(testName)}". It might mean one of the following:
12427
12060
  - The error was thrown, while Vitest was running this test.
12428
12061
  - This was the last recorded test before the error was thrown, if error originated after test finished its execution.`));
12429
12062
  }
12430
12063
  if (afterEnvTeardown) {
12431
- ctx.logger.error(c.red("This error was caught after test environment was torn down. Make sure to cancel any running tasks before test finishes:\n- cancel timeouts using clearTimeout and clearInterval\n- wait for promises to resolve using the await keyword"));
12064
+ logger.error(c.red("This error was caught after test environment was torn down. Make sure to cancel any running tasks before test finishes:\n- cancel timeouts using clearTimeout and clearInterval\n- wait for promises to resolve using the await keyword"));
12432
12065
  }
12433
12066
  if (typeof e.cause === "object" && e.cause && "name" in e.cause) {
12434
12067
  e.cause.name = `Caused by: ${e.cause.name}`;
12435
- await printError(e.cause, ctx, { fullStack, showCodeFrame: false });
12068
+ await printError(e.cause, project, { fullStack, showCodeFrame: false, logger: options.logger });
12436
12069
  }
12437
- handleImportOutsideModuleError(e.stack || e.stackStr || "", ctx);
12070
+ handleImportOutsideModuleError(e.stack || e.stackStr || "", logger);
12438
12071
  }
12439
12072
  function printErrorType(type, ctx) {
12440
12073
  ctx.logger.error(`
@@ -12471,7 +12104,7 @@ const esmErrors = [
12471
12104
  "Cannot use import statement outside a module",
12472
12105
  "Unexpected token 'export'"
12473
12106
  ];
12474
- function handleImportOutsideModuleError(stack, ctx) {
12107
+ function handleImportOutsideModuleError(stack, logger) {
12475
12108
  if (!esmErrors.some((e) => stack.includes(e)))
12476
12109
  return;
12477
12110
  const path = normalize(stack.split("\n")[0].trim());
@@ -12481,9 +12114,9 @@ function handleImportOutsideModuleError(stack, ctx) {
12481
12114
  else
12482
12115
  name = name.split("/")[0];
12483
12116
  if (name)
12484
- printModuleWarningForPackage(ctx.logger, path, name);
12117
+ printModuleWarningForPackage(logger, path, name);
12485
12118
  else
12486
- printModuleWarningForSourceCode(ctx.logger, path);
12119
+ printModuleWarningForSourceCode(logger, path);
12487
12120
  }
12488
12121
  function printModuleWarningForPackage(logger, path, name) {
12489
12122
  logger.error(c.yellow(
@@ -12516,17 +12149,21 @@ ${diff}
12516
12149
  }
12517
12150
  function printErrorMessage(error, logger) {
12518
12151
  const errorName = error.name || error.nameStr || "Unknown Error";
12152
+ if (!error.message) {
12153
+ logger.error(error);
12154
+ return;
12155
+ }
12519
12156
  if (error.message.length > 5e3) {
12520
12157
  logger.error(`${c.red(c.bold(errorName))}: ${error.message}`);
12521
12158
  } else {
12522
12159
  logger.error(c.red(`${c.bold(errorName)}: ${error.message}`));
12523
12160
  }
12524
12161
  }
12525
- function printStack(ctx, stack, highlight, errorProperties, onStack) {
12526
- const logger = ctx.logger;
12162
+ function printStack(project, stack, highlight, errorProperties, onStack) {
12163
+ const logger = project.ctx.logger;
12527
12164
  for (const frame of stack) {
12528
12165
  const color = frame === highlight ? c.cyan : c.gray;
12529
- const path = relative(ctx.config.root, frame.file);
12166
+ const path = relative(project.config.root, frame.file);
12530
12167
  logger.error(color(` ${c.dim(F_POINTER)} ${[frame.method, `${path}:${c.dim(`${frame.line}:${frame.column}`)}`].filter(Boolean).join(" ")}`));
12531
12168
  onStack == null ? void 0 : onStack(frame);
12532
12169
  }
@@ -12535,7 +12172,7 @@ function printStack(ctx, stack, highlight, errorProperties, onStack) {
12535
12172
  const hasProperties = Object.keys(errorProperties).length > 0;
12536
12173
  if (hasProperties) {
12537
12174
  logger.error(c.red(c.dim(divider())));
12538
- const propertiesString = stringify$5(errorProperties, 10, { printBasicPrototype: false });
12175
+ const propertiesString = inspect(errorProperties);
12539
12176
  logger.error(c.red(c.bold("Serialized Error:")), c.gray(propertiesString));
12540
12177
  }
12541
12178
  }
@@ -12580,6 +12217,11 @@ function generateCodeFrame(source, indent = 0, lineNumber, columnNumber, range =
12580
12217
  return res.join("\n");
12581
12218
  }
12582
12219
 
12220
+ const ESC = "\x1B[";
12221
+ const ERASE_DOWN = `${ESC}J`;
12222
+ const ERASE_SCROLLBACK = `${ESC}3J`;
12223
+ const CURSOR_TO_START = `${ESC}1;1H`;
12224
+ const CLEAR_SCREEN = "\x1Bc";
12583
12225
  class Logger {
12584
12226
  constructor(ctx, console = globalThis.console) {
12585
12227
  this.ctx = ctx;
@@ -12606,7 +12248,7 @@ class Logger {
12606
12248
  this.console.log(message);
12607
12249
  return;
12608
12250
  }
12609
- this.console.log(`\x1Bc${message}`);
12251
+ this.console.log(`${ERASE_SCROLLBACK}${CLEAR_SCREEN}${message}`);
12610
12252
  }
12611
12253
  clearScreen(message, force = false) {
12612
12254
  if (this.ctx.server.config.clearScreen === false) {
@@ -12622,16 +12264,20 @@ class Logger {
12622
12264
  return;
12623
12265
  const log = this._clearScreenPending;
12624
12266
  this._clearScreenPending = void 0;
12625
- this.console.log(`\x1B[1;1H\x1B[J${log}`);
12267
+ this.console.log(`${CURSOR_TO_START}${ERASE_DOWN}${log}`);
12626
12268
  }
12627
- printError(err, fullStack = false, type) {
12628
- return printError(err, this.ctx, {
12269
+ printError(err, options = {}) {
12270
+ const { fullStack = false, type } = options;
12271
+ const project = options.project ?? this.ctx.getCoreWorkspaceProject() ?? this.ctx.projects[0];
12272
+ return printError(err, project, {
12629
12273
  fullStack,
12630
12274
  type,
12631
- showCodeFrame: true
12275
+ showCodeFrame: true,
12276
+ logger: this
12632
12277
  });
12633
12278
  }
12634
12279
  printNoTestFound(filters) {
12280
+ var _a;
12635
12281
  const config = this.ctx.config;
12636
12282
  const comma = c.dim(", ");
12637
12283
  if (filters == null ? void 0 : filters.length)
@@ -12642,12 +12288,17 @@ class Logger {
12642
12288
  this.console.error(c.dim("exclude: ") + c.yellow(config.exclude.join(comma)));
12643
12289
  if (config.watchExclude)
12644
12290
  this.console.error(c.dim("watch exclude: ") + c.yellow(config.watchExclude.join(comma)));
12645
- if (config.passWithNoTests)
12646
- this.log(`No ${config.mode} files found, exiting with code 0
12291
+ if (config.watch && (config.changed || ((_a = config.related) == null ? void 0 : _a.length))) {
12292
+ this.log(`No affected ${config.mode} files found
12647
12293
  `);
12648
- else
12649
- this.error(c.red(`
12294
+ } else {
12295
+ if (config.passWithNoTests)
12296
+ this.log(`No ${config.mode} files found, exiting with code 0
12297
+ `);
12298
+ else
12299
+ this.error(c.red(`
12650
12300
  No ${config.mode} files found, exiting with code 1`));
12301
+ }
12651
12302
  }
12652
12303
  printBanner() {
12653
12304
  var _a, _b;
@@ -12682,7 +12333,7 @@ This might cause false positive tests. Resolve unhandled errors to make sure you
12682
12333
  this.log(c.red(divider(c.bold(c.inverse(" Unhandled Errors ")))));
12683
12334
  this.log(errorMessage);
12684
12335
  await Promise.all(errors.map(async (err) => {
12685
- await this.printError(err, true, err.type || "Unhandled Error");
12336
+ await this.printError(err, { fullStack: true, type: err.type || "Unhandled Error" });
12686
12337
  }));
12687
12338
  this.log(c.red(divider()));
12688
12339
  }
@@ -12694,7 +12345,7 @@ Vitest found ${errors.length} error${errors.length > 1 ? "s" : ""} not related t
12694
12345
  this.log(c.red(divider(c.bold(c.inverse(" Source Errors ")))));
12695
12346
  this.log(errorMessage);
12696
12347
  await Promise.all(errors.map(async (err) => {
12697
- await this.printError(err, true);
12348
+ await this.printError(err, { fullStack: true });
12698
12349
  }));
12699
12350
  this.log(c.red(divider()));
12700
12351
  }
@@ -12853,7 +12504,7 @@ function MocksPlugin() {
12853
12504
  async function createBrowserServer(project, options) {
12854
12505
  const root = project.config.root;
12855
12506
  await ensurePackageInstalled("@vitest/browser", root);
12856
- const configPath = options.config === false ? false : options.config ? resolve$2(root, options.config) : await findUp(configFiles, { cwd: root });
12507
+ const configPath = options.config === false ? false : options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
12857
12508
  const server = await createServer({
12858
12509
  logLevel: "error",
12859
12510
  mode: project.config.mode,
@@ -12891,7 +12542,7 @@ async function createBrowserServer(project, options) {
12891
12542
  });
12892
12543
  await server.listen();
12893
12544
  await server.watcher.close();
12894
- (await import('./chunk-api-setup.8f785c4a.js')).setup(project, server);
12545
+ (await import('./chunk-api-setup.644415c3.js')).setup(project, server);
12895
12546
  return server;
12896
12547
  }
12897
12548
 
@@ -13094,21 +12745,29 @@ function CSSEnablerPlugin(ctx) {
13094
12745
  ];
13095
12746
  }
13096
12747
 
13097
- function EnvReplacerPlugin() {
12748
+ function SsrReplacerPlugin() {
13098
12749
  return {
13099
12750
  name: "vitest:env-replacer",
13100
12751
  enforce: "pre",
13101
12752
  transform(code, id) {
13102
- if (!/\bimport\.meta\.env\b/g.test(code))
12753
+ if (!/\bimport\.meta\.env\b/.test(code) && !/\bimport\.meta\.url\b/.test(code))
13103
12754
  return null;
13104
12755
  let s = null;
13105
- const envs = stripLiteral(code).matchAll(/\bimport\.meta\.env\b/g);
12756
+ const cleanCode = stripLiteral(code);
12757
+ const envs = cleanCode.matchAll(/\bimport\.meta\.env\b/g);
13106
12758
  for (const env of envs) {
13107
12759
  s || (s = new MagicString(code));
13108
12760
  const startIndex = env.index;
13109
12761
  const endIndex = startIndex + env[0].length;
13110
12762
  s.overwrite(startIndex, endIndex, "process.env");
13111
12763
  }
12764
+ const urls = cleanCode.matchAll(/\bimport\.meta\.url\b/g);
12765
+ for (const env of urls) {
12766
+ s || (s = new MagicString(code));
12767
+ const startIndex = env.index;
12768
+ const endIndex = startIndex + env[0].length;
12769
+ s.overwrite(startIndex, endIndex, "__vite_ssr_import_meta__.url");
12770
+ }
13112
12771
  if (s) {
13113
12772
  return {
13114
12773
  code: s.toString(),
@@ -13192,14 +12851,17 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
13192
12851
  };
13193
12852
  }
13194
12853
 
13195
- function resolveOptimizerConfig(testOptionc, viteOptions, testConfig) {
12854
+ function resolveOptimizerConfig(_testOptions, viteOptions, testConfig) {
13196
12855
  var _a;
12856
+ const testOptions = _testOptions || {};
13197
12857
  const newConfig = {};
13198
12858
  const [major, minor] = version$2.split(".").map(Number);
13199
12859
  const allowed = major >= 5 || major === 4 && minor >= 3;
13200
- if (!allowed && (testOptionc == null ? void 0 : testOptionc.enabled) === true)
12860
+ if (!allowed && (testOptions == null ? void 0 : testOptions.enabled) === true)
13201
12861
  console.warn(`Vitest: "deps.optimizer" is only available in Vite >= 4.3.0, current Vite version: ${version$2}`);
13202
- if (!allowed || (testOptionc == null ? void 0 : testOptionc.enabled) !== true) {
12862
+ else
12863
+ testOptions.enabled ?? (testOptions.enabled = true);
12864
+ if (!allowed || (testOptions == null ? void 0 : testOptions.enabled) !== true) {
13203
12865
  newConfig.cacheDir = void 0;
13204
12866
  newConfig.optimizeDeps = {
13205
12867
  // experimental in Vite >2.9.2, entries remains to help with older versions
@@ -13211,12 +12873,12 @@ function resolveOptimizerConfig(testOptionc, viteOptions, testConfig) {
13211
12873
  newConfig.cacheDir = cacheDir ?? "node_modules/.vitest";
13212
12874
  newConfig.optimizeDeps = {
13213
12875
  ...viteOptions,
13214
- ...testOptionc,
12876
+ ...testOptions,
13215
12877
  noDiscovery: true,
13216
12878
  disabled: false,
13217
12879
  entries: [],
13218
- exclude: ["vitest", ...builtinModules, ...testOptionc.exclude || (viteOptions == null ? void 0 : viteOptions.exclude) || []],
13219
- include: (testOptionc.include || (viteOptions == null ? void 0 : viteOptions.include) || []).filter((n) => n !== "vitest")
12880
+ exclude: ["vitest", ...builtinModules, ...testOptions.exclude || (viteOptions == null ? void 0 : viteOptions.exclude) || []],
12881
+ include: (testOptions.include || (viteOptions == null ? void 0 : viteOptions.include) || []).filter((n) => n !== "vitest")
13220
12882
  };
13221
12883
  }
13222
12884
  return newConfig;
@@ -13334,8 +12996,8 @@ function WorkspaceVitestPlugin(project, options) {
13334
12996
  };
13335
12997
  }
13336
12998
  }
13337
- const webOptimizer = resolveOptimizerConfig((_e = (_d = testConfig.deps) == null ? void 0 : _d.experimentalOptimizer) == null ? void 0 : _e.web, viteConfig.optimizeDeps, testConfig);
13338
- const ssrOptimizer = resolveOptimizerConfig((_g = (_f = testConfig.deps) == null ? void 0 : _f.experimentalOptimizer) == null ? void 0 : _g.ssr, (_h = viteConfig.ssr) == null ? void 0 : _h.optimizeDeps, testConfig);
12999
+ const webOptimizer = resolveOptimizerConfig((_e = (_d = testConfig.deps) == null ? void 0 : _d.optimizer) == null ? void 0 : _e.web, viteConfig.optimizeDeps, testConfig);
13000
+ const ssrOptimizer = resolveOptimizerConfig((_g = (_f = testConfig.deps) == null ? void 0 : _f.optimizer) == null ? void 0 : _g.ssr, (_h = viteConfig.ssr) == null ? void 0 : _h.optimizeDeps, testConfig);
13339
13001
  config.cacheDir = webOptimizer.cacheDir || ssrOptimizer.cacheDir || config.cacheDir;
13340
13002
  config.optimizeDeps = webOptimizer.optimizeDeps;
13341
13003
  config.ssr = {
@@ -13352,13 +13014,13 @@ function WorkspaceVitestPlugin(project, options) {
13352
13014
  );
13353
13015
  await project.setServer(options2, server);
13354
13016
  } catch (err) {
13355
- await project.ctx.logger.printError(err, true);
13017
+ await project.ctx.logger.printError(err, { fullStack: true });
13356
13018
  process.exit(1);
13357
13019
  }
13358
13020
  await server.watcher.close();
13359
13021
  }
13360
13022
  },
13361
- EnvReplacerPlugin(),
13023
+ SsrReplacerPlugin(),
13362
13024
  ...CSSEnablerPlugin(project),
13363
13025
  CoverageTransform(project.ctx),
13364
13026
  GlobalSetupPlugin(project, project.ctx.logger),
@@ -13370,7 +13032,7 @@ function WorkspaceVitestPlugin(project, options) {
13370
13032
  async function initializeProject(workspacePath, ctx, options) {
13371
13033
  var _a, _b, _c, _d, _e, _f, _g;
13372
13034
  const project = new WorkspaceProject(workspacePath, ctx);
13373
- const configFile = options.extends ? resolve$2(dirname(options.workspaceConfigPath), options.extends) : typeof workspacePath === "number" || workspacePath.endsWith("/") ? false : workspacePath;
13035
+ const configFile = options.extends ? resolve(dirname(options.workspaceConfigPath), options.extends) : typeof workspacePath === "number" || workspacePath.endsWith("/") ? false : workspacePath;
13374
13036
  const root = options.root || (typeof workspacePath === "number" ? void 0 : dirname(workspacePath));
13375
13037
  const config = {
13376
13038
  ...options,
@@ -13385,7 +13047,7 @@ async function initializeProject(workspacePath, ctx, options) {
13385
13047
  ]
13386
13048
  };
13387
13049
  const server = await createServer(config);
13388
- if (((_a = ctx.config.api) == null ? void 0 : _a.port) || ((_d = (_c = (_b = project.config.deps) == null ? void 0 : _b.experimentalOptimizer) == null ? void 0 : _c.web) == null ? void 0 : _d.enabled) || ((_g = (_f = (_e = project.config.deps) == null ? void 0 : _e.experimentalOptimizer) == null ? void 0 : _f.ssr) == null ? void 0 : _g.enabled))
13050
+ if (((_a = ctx.config.api) == null ? void 0 : _a.port) || ((_d = (_c = (_b = project.config.deps) == null ? void 0 : _b.optimizer) == null ? void 0 : _c.web) == null ? void 0 : _d.enabled) || ((_g = (_f = (_e = project.config.deps) == null ? void 0 : _e.optimizer) == null ? void 0 : _f.ssr) == null ? void 0 : _g.enabled))
13389
13051
  await server.listen();
13390
13052
  else
13391
13053
  await server.pluginContainer.buildStart({});
@@ -13401,16 +13063,30 @@ class WorkspaceProject {
13401
13063
  server;
13402
13064
  vitenode;
13403
13065
  runner;
13404
- browser = void 0;
13066
+ browser;
13405
13067
  typechecker;
13406
13068
  closingPromise;
13407
13069
  browserProvider;
13070
+ testFilesList = [];
13408
13071
  getName() {
13409
13072
  return this.config.name || "";
13410
13073
  }
13411
13074
  isCore() {
13412
13075
  return this.ctx.getCoreWorkspaceProject() === this;
13413
13076
  }
13077
+ getModuleById(id) {
13078
+ var _a;
13079
+ return this.server.moduleGraph.getModuleById(id) || ((_a = this.browser) == null ? void 0 : _a.moduleGraph.getModuleById(id));
13080
+ }
13081
+ getSourceMapModuleById(id) {
13082
+ var _a, _b;
13083
+ const mod = this.server.moduleGraph.getModuleById(id);
13084
+ return ((_a = mod == null ? void 0 : mod.ssrTransformResult) == null ? void 0 : _a.map) || ((_b = mod == null ? void 0 : mod.transformResult) == null ? void 0 : _b.map);
13085
+ }
13086
+ getBrowserSourceMapModuleById(id) {
13087
+ var _a, _b, _c;
13088
+ return (_c = (_b = (_a = this.browser) == null ? void 0 : _a.moduleGraph.getModuleById(id)) == null ? void 0 : _b.transformResult) == null ? void 0 : _c.map;
13089
+ }
13414
13090
  get reporters() {
13415
13091
  return this.ctx.reporters;
13416
13092
  }
@@ -13434,8 +13110,12 @@ class WorkspaceProject {
13434
13110
  }
13435
13111
  }));
13436
13112
  }
13113
+ this.testFilesList = testFiles;
13437
13114
  return testFiles;
13438
13115
  }
13116
+ isTestFile(id) {
13117
+ return this.testFilesList.includes(id);
13118
+ }
13439
13119
  async globFiles(include, exclude, cwd) {
13440
13120
  const globOptions = {
13441
13121
  absolute: true,
@@ -13572,10 +13252,10 @@ class WorkspaceProject {
13572
13252
  ...this.config.deps,
13573
13253
  optimizer: {
13574
13254
  web: {
13575
- enabled: ((_c = (_b = (_a = this.config.deps) == null ? void 0 : _a.experimentalOptimizer) == null ? void 0 : _b.web) == null ? void 0 : _c.enabled) ?? false
13255
+ enabled: ((_c = (_b = (_a = this.config.deps) == null ? void 0 : _a.optimizer) == null ? void 0 : _b.web) == null ? void 0 : _c.enabled) ?? false
13576
13256
  },
13577
13257
  ssr: {
13578
- enabled: ((_f = (_e = (_d = this.config.deps) == null ? void 0 : _d.experimentalOptimizer) == null ? void 0 : _e.ssr) == null ? void 0 : _f.enabled) ?? false
13258
+ enabled: ((_f = (_e = (_d = this.config.deps) == null ? void 0 : _d.optimizer) == null ? void 0 : _e.ssr) == null ? void 0 : _f.enabled) ?? false
13579
13259
  }
13580
13260
  }
13581
13261
  },
@@ -13677,7 +13357,7 @@ class Vitest {
13677
13357
  this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions });
13678
13358
  if (this.config.watch && this.mode !== "typecheck")
13679
13359
  this.registerWatcher();
13680
- this.vitenode = new ViteNodeServer(server, this.config);
13360
+ this.vitenode = new ViteNodeServer(server, this.config.server);
13681
13361
  const node = this.vitenode;
13682
13362
  this.runner = new ViteNodeRunner({
13683
13363
  root: server.config.root,
@@ -13727,6 +13407,12 @@ class Vitest {
13727
13407
  getCoreWorkspaceProject() {
13728
13408
  return this.coreWorkspace || null;
13729
13409
  }
13410
+ getProjectByTaskId(taskId) {
13411
+ var _a;
13412
+ const task = this.state.idMap.get(taskId);
13413
+ const projectName = task.projectName || ((_a = task == null ? void 0 : task.file) == null ? void 0 : _a.projectName);
13414
+ return this.projects.find((p) => p.getName() === projectName) || this.getCoreWorkspaceProject() || this.projects[0];
13415
+ }
13730
13416
  async resolveWorkspace(options, cliOptions) {
13731
13417
  const configDir = this.server.config.configFile ? dirname(this.server.config.configFile) : this.config.root;
13732
13418
  const rootFiles = await promises.readdir(configDir);
@@ -13826,7 +13512,7 @@ class Vitest {
13826
13512
  return Promise.all(this.projects.map((project) => project.typecheck(filters)));
13827
13513
  }
13828
13514
  async start(filters) {
13829
- var _a;
13515
+ var _a, _b;
13830
13516
  if (this.mode === "typecheck") {
13831
13517
  await this.typecheck(filters);
13832
13518
  return;
@@ -13842,32 +13528,40 @@ class Vitest {
13842
13528
  await this.globTestFiles(filters)
13843
13529
  );
13844
13530
  if (!files.length) {
13845
- const exitCode = this.config.passWithNoTests ? 0 : 1;
13846
13531
  await this.reportCoverage(true);
13847
13532
  this.logger.printNoTestFound(filters);
13848
- process.exit(exitCode);
13533
+ if (!this.config.watch || !(this.config.changed || ((_b = this.config.related) == null ? void 0 : _b.length))) {
13534
+ const exitCode = this.config.passWithNoTests ? 0 : 1;
13535
+ process.exit(exitCode);
13536
+ }
13537
+ }
13538
+ this.config.changed = false;
13539
+ this.config.related = void 0;
13540
+ if (files.length) {
13541
+ await this.cache.stats.populateStats(this.config.root, files);
13542
+ await this.runFiles(files);
13849
13543
  }
13850
- await this.cache.stats.populateStats(this.config.root, files);
13851
- await this.runFiles(files);
13852
13544
  await this.reportCoverage(true);
13853
13545
  if (this.config.watch)
13854
13546
  await this.report("onWatcherStart");
13855
13547
  }
13856
- async getTestDependencies(filepath) {
13857
- const deps = /* @__PURE__ */ new Set();
13548
+ async getTestDependencies(filepath, deps = /* @__PURE__ */ new Set()) {
13858
13549
  const addImports = async ([project, filepath2]) => {
13859
- const transformed = await project.vitenode.transformRequest(filepath2);
13550
+ if (deps.has(filepath2))
13551
+ return;
13552
+ const mod = project.server.moduleGraph.getModuleById(filepath2);
13553
+ const transformed = (mod == null ? void 0 : mod.ssrTransformResult) || await project.vitenode.transformRequest(filepath2);
13860
13554
  if (!transformed)
13861
13555
  return;
13862
13556
  const dependencies = [...transformed.deps || [], ...transformed.dynamicDeps || []];
13863
- for (const dep of dependencies) {
13557
+ await Promise.all(dependencies.map(async (dep) => {
13864
13558
  const path = await this.server.pluginContainer.resolveId(dep, filepath2, { ssr: true });
13865
13559
  const fsPath = path && !path.external && path.id.split("?")[0];
13866
13560
  if (fsPath && !fsPath.includes("node_modules") && !deps.has(fsPath) && existsSync(fsPath)) {
13867
13561
  deps.add(fsPath);
13868
13562
  await addImports([project, fsPath]);
13869
13563
  }
13870
- }
13564
+ }));
13871
13565
  };
13872
13566
  await addImports(filepath);
13873
13567
  return deps;
@@ -13891,7 +13585,7 @@ class Vitest {
13891
13585
  const forceRerunTriggers = this.config.forceRerunTriggers;
13892
13586
  if (forceRerunTriggers.length && mm(related, forceRerunTriggers).length)
13893
13587
  return specs;
13894
- if (!related.length)
13588
+ if (!this.config.watch && !related.length)
13895
13589
  return [];
13896
13590
  const testGraphs = await Promise.all(
13897
13591
  specs.map(async (spec) => {
@@ -14027,8 +13721,7 @@ class Vitest {
14027
13721
  }
14028
13722
  getModuleProjects(id) {
14029
13723
  return this.projects.filter((project) => {
14030
- var _a, _b, _c;
14031
- return project.server.moduleGraph.getModuleById(id) || ((_a = project.browser) == null ? void 0 : _a.moduleGraph.getModuleById(id)) || ((_c = (_b = project.browser) == null ? void 0 : _b.moduleGraph.getModulesByFile(id)) == null ? void 0 : _c.size);
13724
+ return project.getModuleById(id);
14032
13725
  });
14033
13726
  }
14034
13727
  unregisterWatcher = noop$1;
@@ -14095,13 +13788,14 @@ class Vitest {
14095
13788
  return [];
14096
13789
  if (mm.isMatch(id, this.config.forceRerunTriggers)) {
14097
13790
  this.state.getFilepaths().forEach((file) => this.changedTests.add(file));
14098
- return [];
13791
+ return [id];
14099
13792
  }
14100
13793
  const projects = this.getModuleProjects(id);
14101
13794
  if (!projects.length)
14102
13795
  return [];
14103
13796
  const files = [];
14104
- for (const { server, browser } of projects) {
13797
+ for (const project of projects) {
13798
+ const { server, browser } = project;
14105
13799
  const mod = server.moduleGraph.getModuleById(id) || (browser == null ? void 0 : browser.moduleGraph.getModuleById(id));
14106
13800
  if (!mod) {
14107
13801
  const mods = browser == null ? void 0 : browser.moduleGraph.getModulesByFile(id);
@@ -14118,7 +13812,7 @@ class Vitest {
14118
13812
  }
14119
13813
  id = normalizeRequestId(id, server.config.base);
14120
13814
  this.invalidates.add(id);
14121
- if (this.state.filesMap.has(id)) {
13815
+ if (this.state.filesMap.has(id) || project.isTestFile(id)) {
14122
13816
  this.changedTests.add(id);
14123
13817
  files.push(id);
14124
13818
  continue;
@@ -14283,6 +13977,10 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14283
13977
  preTransformRequests: false
14284
13978
  }
14285
13979
  };
13980
+ if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
13981
+ config.server.watch.useFsEvents = false;
13982
+ config.server.watch.usePolling = false;
13983
+ }
14286
13984
  const classNameStrategy = typeof testConfig.css !== "boolean" && ((_c = (_b = testConfig.css) == null ? void 0 : _b.modules) == null ? void 0 : _c.classNameStrategy) || "stable";
14287
13985
  if (classNameStrategy !== "scoped") {
14288
13986
  config.css ?? (config.css = {});
@@ -14294,8 +13992,8 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14294
13992
  };
14295
13993
  }
14296
13994
  }
14297
- const webOptimizer = resolveOptimizerConfig((_f = (_e = testConfig.deps) == null ? void 0 : _e.experimentalOptimizer) == null ? void 0 : _f.web, viteConfig.optimizeDeps, testConfig);
14298
- const ssrOptimizer = resolveOptimizerConfig((_h = (_g = testConfig.deps) == null ? void 0 : _g.experimentalOptimizer) == null ? void 0 : _h.ssr, (_i = viteConfig.ssr) == null ? void 0 : _i.optimizeDeps, testConfig);
13995
+ const webOptimizer = resolveOptimizerConfig((_f = (_e = testConfig.deps) == null ? void 0 : _e.optimizer) == null ? void 0 : _f.web, viteConfig.optimizeDeps, testConfig);
13996
+ const ssrOptimizer = resolveOptimizerConfig((_h = (_g = testConfig.deps) == null ? void 0 : _g.optimizer) == null ? void 0 : _h.ssr, (_i = viteConfig.ssr) == null ? void 0 : _i.optimizeDeps, testConfig);
14299
13997
  config.cacheDir = webOptimizer.cacheDir || ssrOptimizer.cacheDir || config.cacheDir;
14300
13998
  config.optimizeDeps = webOptimizer.optimizeDeps;
14301
13999
  config.ssr = {
@@ -14332,19 +14030,24 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14332
14030
  }
14333
14031
  },
14334
14032
  async configureServer(server) {
14033
+ if (options.watch && process.env.VITE_TEST_WATCHER_DEBUG) {
14034
+ server.watcher.on("ready", () => {
14035
+ console.log("[debug] watcher is ready");
14036
+ });
14037
+ }
14335
14038
  try {
14336
14039
  await ctx.setServer(options, server, userConfig);
14337
14040
  if (options.api && options.watch)
14338
- (await import('./chunk-api-setup.8f785c4a.js')).setup(ctx);
14041
+ (await import('./chunk-api-setup.644415c3.js')).setup(ctx);
14339
14042
  } catch (err) {
14340
- await ctx.logger.printError(err, true);
14043
+ await ctx.logger.printError(err, { fullStack: true });
14341
14044
  process.exit(1);
14342
14045
  }
14343
14046
  if (!options.watch)
14344
14047
  await server.watcher.close();
14345
14048
  }
14346
14049
  },
14347
- EnvReplacerPlugin(),
14050
+ SsrReplacerPlugin(),
14348
14051
  GlobalSetupPlugin(ctx, ctx.logger),
14349
14052
  ...CSSEnablerPlugin(ctx),
14350
14053
  CoverageTransform(ctx),
@@ -14357,8 +14060,8 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14357
14060
  async function createVitest(mode, options, viteOverrides = {}) {
14358
14061
  var _a, _b, _c, _d, _e, _f, _g;
14359
14062
  const ctx = new Vitest(mode);
14360
- const root = resolve$2(options.root || process.cwd());
14361
- const configPath = options.config === false ? false : options.config ? resolve$2(root, options.config) : await findUp(configFiles, { cwd: root });
14063
+ const root = resolve(options.root || process.cwd());
14064
+ const configPath = options.config === false ? false : options.config ? resolve(root, options.config) : await findUp(configFiles, { cwd: root });
14362
14065
  const config = {
14363
14066
  logLevel: "error",
14364
14067
  configFile: configPath,
@@ -14367,7 +14070,7 @@ async function createVitest(mode, options, viteOverrides = {}) {
14367
14070
  plugins: await VitestPlugin(options, ctx)
14368
14071
  };
14369
14072
  const server = await createServer(mergeConfig(config, mergeConfig(viteOverrides, { root: options.root })));
14370
- if (((_a = ctx.config.api) == null ? void 0 : _a.port) || ((_d = (_c = (_b = ctx.config.deps) == null ? void 0 : _b.experimentalOptimizer) == null ? void 0 : _c.web) == null ? void 0 : _d.enabled) || ((_g = (_f = (_e = ctx.config.deps) == null ? void 0 : _e.experimentalOptimizer) == null ? void 0 : _f.ssr) == null ? void 0 : _g.enabled))
14073
+ if (((_a = ctx.config.api) == null ? void 0 : _a.port) || ((_d = (_c = (_b = ctx.config.deps) == null ? void 0 : _b.optimizer) == null ? void 0 : _c.web) == null ? void 0 : _d.enabled) || ((_g = (_f = (_e = ctx.config.deps) == null ? void 0 : _e.optimizer) == null ? void 0 : _f.ssr) == null ? void 0 : _g.enabled))
14371
14074
  await server.listen();
14372
14075
  else
14373
14076
  await server.pluginContainer.buildStart({});
@@ -20761,13 +20464,13 @@ function registerConsoleShortcuts(ctx) {
20761
20464
  }
20762
20465
 
20763
20466
  async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
20764
- var _a, _b, _c, _d;
20467
+ var _a;
20765
20468
  process.env.TEST = "true";
20766
20469
  process.env.VITEST = "true";
20767
20470
  (_a = process.env).NODE_ENV ?? (_a.NODE_ENV = options.mode || "test");
20768
20471
  if (options.run)
20769
20472
  options.watch = false;
20770
- const root = resolve$2(options.root || process.cwd());
20473
+ const root = resolve(options.root || process.cwd());
20771
20474
  if (!await ensurePackageInstalled("vite", root)) {
20772
20475
  process.exitCode = 1;
20773
20476
  return;
@@ -20780,14 +20483,14 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
20780
20483
  options.browser = { enabled: true, name: options.browser };
20781
20484
  if (typeof options.browser === "object" && !("enabled" in options.browser))
20782
20485
  options.browser.enabled = true;
20486
+ if ("threads" in options && options.experimentalVmThreads)
20487
+ throw new Error('Cannot use both "threads" (or "no-threads") and "experimentalVmThreads" at the same time.');
20783
20488
  const ctx = await createVitest(mode, options, viteOverrides);
20784
20489
  if (mode === "test" && ctx.config.coverage.enabled) {
20785
20490
  const provider = ctx.config.coverage.provider || "v8";
20786
20491
  const requiredPackages = CoverageProviderMap[provider];
20787
20492
  if (requiredPackages) {
20788
- const defaultProviderInfo = 'Default coverage provider has changed from "c8" to "v8". New package is required to be installed. To use the old deprecated coverage provider use "--coverage.provider c8" option.\nSee https://github.com/vitest-dev/vitest/pull/3339 for more information.\n\n';
20789
- const isUsingDefaultProvider = ((_c = (_b = ctx.server.config.test) == null ? void 0 : _b.coverage) == null ? void 0 : _c.provider) === void 0 && ((_d = options.coverage) == null ? void 0 : _d.provider) === void 0;
20790
- if (!await ensurePackageInstalled(requiredPackages, root, isUsingDefaultProvider ? defaultProviderInfo : void 0)) {
20493
+ if (!await ensurePackageInstalled(requiredPackages, root)) {
20791
20494
  process.exitCode = 1;
20792
20495
  return ctx;
20793
20496
  }
@@ -20813,7 +20516,7 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides) {
20813
20516
  await ctx.start(cliFilters);
20814
20517
  } catch (e) {
20815
20518
  process.exitCode = 1;
20816
- await ctx.logger.printError(e, true, "Unhandled Error");
20519
+ await ctx.logger.printError(e, { fullStack: true, type: "Unhandled Error" });
20817
20520
  ctx.logger.error("\n\n");
20818
20521
  return ctx;
20819
20522
  }