vitest 1.5.3 → 2.0.0-beta.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 (74) hide show
  1. package/LICENSE.md +172 -0
  2. package/dist/browser.d.ts +1 -1
  3. package/dist/browser.js +4 -4
  4. package/dist/chunks/environments-node.39w4gmlF.js +19 -0
  5. package/dist/chunks/{install-pkg.LE8oaA1t.js → install-pkg.DNUmWFkO.js} +2 -2
  6. package/dist/chunks/integrations-globals.B5Jl0grA.js +31 -0
  7. package/dist/chunks/{runtime-console.EO5ha7qv.js → runtime-console.CUES-L8X.js} +9 -9
  8. package/dist/chunks/{runtime-runBaseTests.l6qXp5eU.js → runtime-runBaseTests._dXkRAZc.js} +21 -22
  9. package/dist/cli.js +3 -3
  10. package/dist/config.cjs +2 -3
  11. package/dist/config.d.ts +1 -1
  12. package/dist/config.js +2 -3
  13. package/dist/coverage.d.ts +1 -1
  14. package/dist/coverage.js +2 -2
  15. package/dist/environments.d.ts +1 -1
  16. package/dist/environments.js +1 -1
  17. package/dist/execute.d.ts +7 -4
  18. package/dist/execute.js +3 -3
  19. package/dist/index.d.ts +770 -21
  20. package/dist/index.js +12 -12
  21. package/dist/node.d.ts +2 -2
  22. package/dist/node.js +21 -22
  23. package/dist/{reporters-BXNXFKfg.d.ts → reporters-MGvT5U9f.d.ts} +128 -55
  24. package/dist/reporters.d.ts +1 -1
  25. package/dist/reporters.js +11 -12
  26. package/dist/runners.d.ts +1 -1
  27. package/dist/runners.js +17 -18
  28. package/dist/snapshot.d.ts +9 -0
  29. package/dist/snapshot.js +8 -0
  30. package/dist/{suite-KPWE530F.d.ts → suite-8WAe-urM.d.ts} +1 -1
  31. package/dist/suite.d.ts +2 -2
  32. package/dist/suite.js +4 -4
  33. package/dist/vendor/{base.oIzAvGLe.js → base.VFkIJ66g.js} +3 -3
  34. package/dist/vendor/{base.Xt0Omgh7.js → base._gnK9Slw.js} +8 -1
  35. package/dist/vendor/{benchmark.yGkUTKnC.js → benchmark.BNLebNi5.js} +1 -1
  36. package/dist/vendor/{cac.RDd_SGOd.js → cac.DzKZaJu2.js} +39 -17
  37. package/dist/vendor/{cli-api.AmIc1Dmz.js → cli-api.DTeni0Qq.js} +3201 -404
  38. package/dist/vendor/{execute.2_yoIC01.js → execute.CLLNVNnK.js} +8 -3
  39. package/dist/vendor/{index.Fm6OikHU.js → index.BfoZyXD1.js} +20 -21
  40. package/dist/vendor/{index.8bPxjt7g.js → index.BpSiYbpB.js} +5 -1
  41. package/dist/vendor/{index.X7lgIMc_.js → index.CRxYS9H3.js} +586 -230
  42. package/dist/vendor/{index.QVcwRDVW.js → index.CmILuxzC.js} +8 -6
  43. package/dist/vendor/{index.xL8XjTLv.js → index.DP-km6lF.js} +1 -1
  44. package/dist/vendor/{index.SMVOaj7F.js → index._7XLd8Kd.js} +2 -2
  45. package/dist/vendor/{rpc.joBhAkyK.js → rpc.DRDE9Pu1.js} +2 -2
  46. package/dist/vendor/{run-once.Olz_Zkd8.js → run-once.DLomgGUH.js} +1 -1
  47. package/dist/vendor/{setup-common.5nUd4r76.js → setup-common.XeoZAW8t.js} +2 -2
  48. package/dist/vendor/{tasks.IknbGB2n.js → tasks.WC7M-K-v.js} +4 -1
  49. package/dist/vendor/{utils.VYmeMh-u.js → utils.D5gGkwyH.js} +1 -1
  50. package/dist/vendor/{vi.Y_w82WR8.js → vi.ClD3hi7L.js} +23 -10
  51. package/dist/vendor/{vm.i4FO5N37.js → vm.Bi3bljci.js} +132 -54
  52. package/dist/worker.js +13 -7
  53. package/dist/workers/forks.js +6 -6
  54. package/dist/workers/runVmTests.js +22 -20
  55. package/dist/workers/threads.js +6 -6
  56. package/dist/workers/vmForks.js +9 -9
  57. package/dist/workers/vmThreads.js +9 -9
  58. package/dist/workers.d.ts +1 -1
  59. package/dist/workers.js +14 -14
  60. package/package.json +33 -29
  61. package/snapshot.d.ts +1 -0
  62. package/vitest.mjs +1 -1
  63. package/dist/chunks/integrations-globals.Hr6znn-f.js +0 -31
  64. package/dist/cli-wrapper.js +0 -119
  65. /package/dist/chunks/{node-git.Hw101KjS.js → node-git.CCI8evVZ.js} +0 -0
  66. /package/dist/vendor/{_commonjsHelpers.jjO7Zipk.js → _commonjsHelpers.BFTU3MAI.js} +0 -0
  67. /package/dist/vendor/{constants.5J7I254_.js → constants.5SOfHUj0.js} +0 -0
  68. /package/dist/vendor/{coverage.E7sG1b3r.js → coverage.ChSqD-qS.js} +0 -0
  69. /package/dist/vendor/{date.Ns1pGd_X.js → date.BKM1wewY.js} +0 -0
  70. /package/dist/vendor/{env.AtSIuHFg.js → env.bmJgw1qP.js} +0 -0
  71. /package/dist/vendor/{global.CkGT_TMy.js → global.7bFbnyXl.js} +0 -0
  72. /package/dist/vendor/{index.GVFv9dZ0.js → index.DeR1hhfY.js} +0 -0
  73. /package/dist/vendor/{inspector.IgLX3ur5.js → inspector.hPQncR7V.js} +0 -0
  74. /package/dist/vendor/{utils.0uYuCbzo.js → utils.CUjzkRH7.js} +0 -0
@@ -1,17 +1,17 @@
1
- import { dirname, resolve, relative, normalize, join, basename, toNamespacedPath, isAbsolute } from 'pathe';
2
- import { A as API_PATH, d as defaultPort, e as extraInlineDeps, a as defaultBrowserPort, b as defaultInspectPort, E as EXIT_CODE_RESTART, w as workspacesFiles, C as CONFIG_NAMES, c as configFiles } from './constants.5J7I254_.js';
3
- import { g as getCoverageProvider, C as CoverageProviderMap } from './coverage.E7sG1b3r.js';
4
- import { g as getEnvPackageName } from './index.GVFv9dZ0.js';
5
- import { isFileServingAllowed, searchForWorkspaceRoot, version as version$1, createServer, mergeConfig } from 'vite';
6
- import path$8 from 'node:path';
7
- import url, { fileURLToPath } from 'node:url';
1
+ import { dirname, join, resolve, relative, isAbsolute, normalize, basename, toNamespacedPath } from 'pathe';
2
+ import { A as API_PATH, d as defaultPort, e as extraInlineDeps, a as defaultBrowserPort, b as defaultInspectPort, E as EXIT_CODE_RESTART, w as workspacesFiles, C as CONFIG_NAMES, c as configFiles } from './constants.5SOfHUj0.js';
3
+ import { g as getCoverageProvider, C as CoverageProviderMap } from './coverage.ChSqD-qS.js';
4
+ import { g as getEnvPackageName } from './index.DeR1hhfY.js';
5
+ import { isFileServingAllowed, searchForWorkspaceRoot, version, createServer, mergeConfig } from 'vite';
6
+ import path$8, { win32 } from 'node:path';
7
+ import url, { fileURLToPath as fileURLToPath$1, pathToFileURL as pathToFileURL$1, URL as URL$2 } from 'node:url';
8
8
  import process$1 from 'node:process';
9
- import fs$8, { promises, existsSync, readFileSync } from 'node:fs';
9
+ import fs$8, { promises as promises$1, existsSync, statSync as statSync$1, realpathSync, readFileSync } from 'node:fs';
10
10
  import { MessageChannel, isMainThread } from 'node:worker_threads';
11
- import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './_commonjsHelpers.jjO7Zipk.js';
11
+ import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './_commonjsHelpers.BFTU3MAI.js';
12
12
  import require$$0 from 'os';
13
13
  import p from 'path';
14
- import { a as micromatch_1, m as mm } from './index.xL8XjTLv.js';
14
+ import { a as micromatch_1, m as mm } from './index.DP-km6lF.js';
15
15
  import require$$0$1 from 'stream';
16
16
  import require$$0$3 from 'events';
17
17
  import require$$0$2 from 'fs';
@@ -19,12 +19,13 @@ import c from 'picocolors';
19
19
  import { ViteNodeRunner } from 'vite-node/client';
20
20
  import { SnapshotManager } from '@vitest/snapshot/manager';
21
21
  import { ViteNodeServer } from 'vite-node/server';
22
- import { hasFailed, getTests } from '@vitest/runner/utils';
23
- import { n as noop$2, b as isPrimitive, c as groupBy, A as AggregateErrorPonyfill, a as slash$1, t as toArray, d as deepMerge, w as wildcardPatternToRegExp, e as stdout } from './base.Xt0Omgh7.js';
22
+ import { v as version$1 } from './cac.DzKZaJu2.js';
23
+ import { hasFailed, getTasks, getTests } from '@vitest/runner/utils';
24
+ import { n as noop$2, b as isPrimitive, c as groupBy, A as AggregateErrorPonyfill, a as slash$1, t as toArray, d as deepMerge, e as nanoid, w as wildcardPatternToRegExp, f as stdout } from './base._gnK9Slw.js';
24
25
  import { createDefer, toArray as toArray$1, notNullish } from '@vitest/utils';
25
- import { a as isWindows } from './env.AtSIuHFg.js';
26
+ import { a as isWindows } from './env.bmJgw1qP.js';
26
27
  import { rootDir } from '../path.js';
27
- import { c as createBirpc } from './index.8bPxjt7g.js';
28
+ import { c as createBirpc } from './index.BpSiYbpB.js';
28
29
  import require$$0$4 from 'zlib';
29
30
  import require$$0$5 from 'buffer';
30
31
  import require$$1 from 'crypto';
@@ -36,22 +37,21 @@ import require$$7 from 'url';
36
37
  import { parseErrorStacktrace } from '@vitest/utils/source-map';
37
38
  import v8 from 'node:v8';
38
39
  import * as nodeos from 'node:os';
39
- import nodeos__default from 'node:os';
40
+ import nodeos__default, { tmpdir } from 'node:os';
40
41
  import EventEmitter$2 from 'node:events';
41
42
  import Tinypool$1, { Tinypool } from 'tinypool';
42
- import { w as wrapSerializableConfig, f as Typechecker, R as ReportersMap, e as BenchmarkReportsMap, g as RandomSequencer, B as BaseSequencer, h as generateCodeFrame, i as highlightCode, L as Logger } from './index.X7lgIMc_.js';
43
- import { resolveModule, isPackageExists } from 'local-pkg';
44
- import { isCI, provider as provider$1 } from 'std-env';
43
+ import { w as wrapSerializableConfig, f as Typechecker, R as ReportersMap, e as BenchmarkReportsMap, g as RandomSequencer, B as BaseSequencer, h as findNodeAround, i as generateCodeFrame, j as highlightCode, L as Logger } from './index.CRxYS9H3.js';
45
44
  import crypto, { createHash as createHash$2 } from 'node:crypto';
46
- import { v as version } from './cac.RDd_SGOd.js';
45
+ import { mkdir, writeFile, rm } from 'node:fs/promises';
46
+ import { builtinModules, createRequire } from 'node:module';
47
+ import assert from 'node:assert';
48
+ import { format as format$2, inspect } from 'node:util';
49
+ import { isCI, provider as provider$1 } from 'std-env';
47
50
  import { normalizeRequestId, cleanUrl } from 'vite-node/utils';
48
51
  import MagicString from 'magic-string';
49
- import { findNodeAround } from 'acorn-walk';
50
52
  import { esmWalker } from '@vitest/utils/ast';
51
- import { stripLiteral } from 'strip-literal';
52
- import { d as divider, s as stripAnsi } from './utils.VYmeMh-u.js';
53
- import { createRequire } from 'node:module';
54
- import { a as removeUndefinedValues } from './index.SMVOaj7F.js';
53
+ import { d as divider, s as stripAnsi } from './utils.D5gGkwyH.js';
54
+ import { a as removeUndefinedValues } from './index._7XLd8Kd.js';
55
55
  import readline from 'node:readline';
56
56
  import require$$0$6 from 'readline';
57
57
 
@@ -314,7 +314,7 @@ function checkType(type) {
314
314
 
315
315
  const matchType = (type, stat) => stat[typeMappings[type]]();
316
316
 
317
- const toPath$1 = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
317
+ const toPath$1 = urlOrPath => urlOrPath instanceof URL ? fileURLToPath$1(urlOrPath) : urlOrPath;
318
318
 
319
319
  async function locatePath(
320
320
  paths,
@@ -329,7 +329,7 @@ async function locatePath(
329
329
  checkType(type);
330
330
  cwd = toPath$1(cwd);
331
331
 
332
- const statFunction = allowSymlinks ? promises.stat : promises.lstat;
332
+ const statFunction = allowSymlinks ? promises$1.stat : promises$1.lstat;
333
333
 
334
334
  return pLocate(paths, async path_ => {
335
335
  try {
@@ -341,7 +341,7 @@ async function locatePath(
341
341
  }, {concurrency, preserveOrder});
342
342
  }
343
343
 
344
- const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
344
+ const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath$1(urlOrPath) : urlOrPath;
345
345
 
346
346
  const findUpStop = Symbol('findUpStop');
347
347
 
@@ -1248,7 +1248,7 @@ var async$2 = {};
1248
1248
 
1249
1249
  Object.defineProperty(async$2, "__esModule", { value: true });
1250
1250
  async$2.read = void 0;
1251
- function read$3(path, settings, callback) {
1251
+ function read$4(path, settings, callback) {
1252
1252
  settings.fs.lstat(path, (lstatError, lstat) => {
1253
1253
  if (lstatError !== null) {
1254
1254
  callFailureCallback$2(callback, lstatError);
@@ -1274,7 +1274,7 @@ function read$3(path, settings, callback) {
1274
1274
  });
1275
1275
  });
1276
1276
  }
1277
- async$2.read = read$3;
1277
+ async$2.read = read$4;
1278
1278
  function callFailureCallback$2(callback, error) {
1279
1279
  callback(error);
1280
1280
  }
@@ -1286,7 +1286,7 @@ var sync$7 = {};
1286
1286
 
1287
1287
  Object.defineProperty(sync$7, "__esModule", { value: true });
1288
1288
  sync$7.read = void 0;
1289
- function read$2(path, settings) {
1289
+ function read$3(path, settings) {
1290
1290
  const lstat = settings.fs.lstatSync(path);
1291
1291
  if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
1292
1292
  return lstat;
@@ -1305,7 +1305,7 @@ function read$2(path, settings) {
1305
1305
  throw error;
1306
1306
  }
1307
1307
  }
1308
- sync$7.read = read$2;
1308
+ sync$7.read = read$3;
1309
1309
 
1310
1310
  var settings$3 = {};
1311
1311
 
@@ -1374,12 +1374,12 @@ function getSettings$2(settingsOrOptions = {}) {
1374
1374
 
1375
1375
  /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
1376
1376
 
1377
- let promise$1;
1377
+ let promise;
1378
1378
 
1379
1379
  var queueMicrotask_1 = typeof queueMicrotask === 'function'
1380
1380
  ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
1381
1381
  // reuse resolved promise, and allocate it lazily
1382
- : cb => (promise$1 || (promise$1 = Promise.resolve()))
1382
+ : cb => (promise || (promise = Promise.resolve()))
1383
1383
  .then(cb)
1384
1384
  .catch(err => setTimeout(() => { throw err }, 0));
1385
1385
 
@@ -1505,14 +1505,14 @@ const rpl = runParallel_1;
1505
1505
  const constants_1$1 = constants$1;
1506
1506
  const utils$8 = utils$9;
1507
1507
  const common$5 = common$6;
1508
- function read$1(directory, settings, callback) {
1508
+ function read$2(directory, settings, callback) {
1509
1509
  if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
1510
1510
  readdirWithFileTypes$1(directory, settings, callback);
1511
1511
  return;
1512
1512
  }
1513
1513
  readdir$1(directory, settings, callback);
1514
1514
  }
1515
- async$3.read = read$1;
1515
+ async$3.read = read$2;
1516
1516
  function readdirWithFileTypes$1(directory, settings, callback) {
1517
1517
  settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
1518
1518
  if (readdirError !== null) {
@@ -1610,13 +1610,13 @@ const fsStat$4 = out$1;
1610
1610
  const constants_1 = constants$1;
1611
1611
  const utils$7 = utils$9;
1612
1612
  const common$4 = common$6;
1613
- function read(directory, settings) {
1613
+ function read$1(directory, settings) {
1614
1614
  if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
1615
1615
  return readdirWithFileTypes(directory, settings);
1616
1616
  }
1617
1617
  return readdir(directory, settings);
1618
1618
  }
1619
- sync$5.read = read;
1619
+ sync$5.read = read$1;
1620
1620
  function readdirWithFileTypes(directory, settings) {
1621
1621
  const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
1622
1622
  return dirents.map((dirent) => {
@@ -2744,9 +2744,9 @@ class EntryFilter {
2744
2744
  }
2745
2745
  entry$1.default = EntryFilter;
2746
2746
 
2747
- var error$1 = {};
2747
+ var error = {};
2748
2748
 
2749
- Object.defineProperty(error$1, "__esModule", { value: true });
2749
+ Object.defineProperty(error, "__esModule", { value: true });
2750
2750
  const utils$2 = utils$b;
2751
2751
  class ErrorFilter {
2752
2752
  constructor(_settings) {
@@ -2759,7 +2759,7 @@ class ErrorFilter {
2759
2759
  return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
2760
2760
  }
2761
2761
  }
2762
- error$1.default = ErrorFilter;
2762
+ error.default = ErrorFilter;
2763
2763
 
2764
2764
  var entry = {};
2765
2765
 
@@ -2793,7 +2793,7 @@ Object.defineProperty(provider, "__esModule", { value: true });
2793
2793
  const path = p;
2794
2794
  const deep_1 = deep;
2795
2795
  const entry_1 = entry$1;
2796
- const error_1 = error$1;
2796
+ const error_1 = error;
2797
2797
  const entry_2 = entry;
2798
2798
  class Provider {
2799
2799
  constructor(_settings) {
@@ -3128,7 +3128,9 @@ var out = FastGlob;
3128
3128
 
3129
3129
  var fg = /*@__PURE__*/getDefaultExportFromCjs(out);
3130
3130
 
3131
- /*! (c) 2020 Andrea Giammarchi */
3131
+ /// <reference types="../types/index.d.ts" />
3132
+
3133
+ // (c) 2020-present Andrea Giammarchi
3132
3134
 
3133
3135
  const {parse: $parse, stringify: $stringify} = JSON;
3134
3136
  const {keys: keys$1} = Object;
@@ -3180,6 +3182,12 @@ const set = (known, input, value) => {
3180
3182
  return index;
3181
3183
  };
3182
3184
 
3185
+ /**
3186
+ * Converts a specialized flatted string into a JS value.
3187
+ * @param {string} text
3188
+ * @param {(this: any, key: string, value: any) => any} [reviver]
3189
+ * @returns {any}
3190
+ */
3183
3191
  const parse$3 = (text, reviver) => {
3184
3192
  const input = $parse(text, Primitives).map(primitives);
3185
3193
  const value = input[0];
@@ -3190,6 +3198,13 @@ const parse$3 = (text, reviver) => {
3190
3198
  return $.call({'': tmp}, '', tmp);
3191
3199
  };
3192
3200
 
3201
+ /**
3202
+ * Converts a JS value into a specialized flatted string.
3203
+ * @param {any} value
3204
+ * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer]
3205
+ * @param {string | number | undefined} [space]
3206
+ * @returns {string}
3207
+ */
3193
3208
  const stringify = (value, replacer, space) => {
3194
3209
  const $ = replacer && typeof replacer === object ?
3195
3210
  (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) :
@@ -4083,13 +4098,6 @@ const { concat, toArrayBuffer, unmask } = bufferUtilExports;
4083
4098
  const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports;
4084
4099
 
4085
4100
  const FastBuffer = Buffer[Symbol.species];
4086
- const promise = Promise.resolve();
4087
-
4088
- //
4089
- // `queueMicrotask()` is not available in Node.js < 11.
4090
- //
4091
- const queueTask =
4092
- typeof queueMicrotask === 'function' ? queueMicrotask : queueMicrotaskShim;
4093
4101
 
4094
4102
  const GET_INFO = 0;
4095
4103
  const GET_PAYLOAD_LENGTH_16 = 1;
@@ -4097,7 +4105,7 @@ const GET_PAYLOAD_LENGTH_64 = 2;
4097
4105
  const GET_MASK = 3;
4098
4106
  const GET_DATA = 4;
4099
4107
  const INFLATING = 5;
4100
- const WAIT_MICROTASK = 6;
4108
+ const DEFER_EVENT = 6;
4101
4109
 
4102
4110
  /**
4103
4111
  * HyBi Receiver implementation.
@@ -4109,6 +4117,9 @@ let Receiver$1 = class Receiver extends Writable {
4109
4117
  * Creates a Receiver instance.
4110
4118
  *
4111
4119
  * @param {Object} [options] Options object
4120
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
4121
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
4122
+ * multiple times in the same tick
4112
4123
  * @param {String} [options.binaryType=nodebuffer] The type for binary data
4113
4124
  * @param {Object} [options.extensions] An object containing the negotiated
4114
4125
  * extensions
@@ -4121,6 +4132,10 @@ let Receiver$1 = class Receiver extends Writable {
4121
4132
  constructor(options = {}) {
4122
4133
  super();
4123
4134
 
4135
+ this._allowSynchronousEvents =
4136
+ options.allowSynchronousEvents !== undefined
4137
+ ? options.allowSynchronousEvents
4138
+ : true;
4124
4139
  this._binaryType = options.binaryType || BINARY_TYPES$1[0];
4125
4140
  this._extensions = options.extensions || {};
4126
4141
  this._isServer = !!options.isServer;
@@ -4143,8 +4158,9 @@ let Receiver$1 = class Receiver extends Writable {
4143
4158
  this._messageLength = 0;
4144
4159
  this._fragments = [];
4145
4160
 
4146
- this._state = GET_INFO;
4161
+ this._errored = false;
4147
4162
  this._loop = false;
4163
+ this._state = GET_INFO;
4148
4164
  }
4149
4165
 
4150
4166
  /**
@@ -4216,53 +4232,42 @@ let Receiver$1 = class Receiver extends Writable {
4216
4232
  * @private
4217
4233
  */
4218
4234
  startLoop(cb) {
4219
- let err;
4220
4235
  this._loop = true;
4221
4236
 
4222
4237
  do {
4223
4238
  switch (this._state) {
4224
4239
  case GET_INFO:
4225
- err = this.getInfo();
4240
+ this.getInfo(cb);
4226
4241
  break;
4227
4242
  case GET_PAYLOAD_LENGTH_16:
4228
- err = this.getPayloadLength16();
4243
+ this.getPayloadLength16(cb);
4229
4244
  break;
4230
4245
  case GET_PAYLOAD_LENGTH_64:
4231
- err = this.getPayloadLength64();
4246
+ this.getPayloadLength64(cb);
4232
4247
  break;
4233
4248
  case GET_MASK:
4234
4249
  this.getMask();
4235
4250
  break;
4236
4251
  case GET_DATA:
4237
- err = this.getData(cb);
4252
+ this.getData(cb);
4238
4253
  break;
4239
4254
  case INFLATING:
4255
+ case DEFER_EVENT:
4240
4256
  this._loop = false;
4241
4257
  return;
4242
- default:
4243
- //
4244
- // `WAIT_MICROTASK`.
4245
- //
4246
- this._loop = false;
4247
-
4248
- queueTask(() => {
4249
- this._state = GET_INFO;
4250
- this.startLoop(cb);
4251
- });
4252
- return;
4253
4258
  }
4254
4259
  } while (this._loop);
4255
4260
 
4256
- cb(err);
4261
+ if (!this._errored) cb();
4257
4262
  }
4258
4263
 
4259
4264
  /**
4260
4265
  * Reads the first two bytes of a frame.
4261
4266
  *
4262
- * @return {(RangeError|undefined)} A possible error
4267
+ * @param {Function} cb Callback
4263
4268
  * @private
4264
4269
  */
4265
- getInfo() {
4270
+ getInfo(cb) {
4266
4271
  if (this._bufferedBytes < 2) {
4267
4272
  this._loop = false;
4268
4273
  return;
@@ -4271,27 +4276,31 @@ let Receiver$1 = class Receiver extends Writable {
4271
4276
  const buf = this.consume(2);
4272
4277
 
4273
4278
  if ((buf[0] & 0x30) !== 0x00) {
4274
- this._loop = false;
4275
- return error(
4279
+ const error = this.createError(
4276
4280
  RangeError,
4277
4281
  'RSV2 and RSV3 must be clear',
4278
4282
  true,
4279
4283
  1002,
4280
4284
  'WS_ERR_UNEXPECTED_RSV_2_3'
4281
4285
  );
4286
+
4287
+ cb(error);
4288
+ return;
4282
4289
  }
4283
4290
 
4284
4291
  const compressed = (buf[0] & 0x40) === 0x40;
4285
4292
 
4286
4293
  if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
4287
- this._loop = false;
4288
- return error(
4294
+ const error = this.createError(
4289
4295
  RangeError,
4290
4296
  'RSV1 must be clear',
4291
4297
  true,
4292
4298
  1002,
4293
4299
  'WS_ERR_UNEXPECTED_RSV_1'
4294
4300
  );
4301
+
4302
+ cb(error);
4303
+ return;
4295
4304
  }
4296
4305
 
4297
4306
  this._fin = (buf[0] & 0x80) === 0x80;
@@ -4300,86 +4309,100 @@ let Receiver$1 = class Receiver extends Writable {
4300
4309
 
4301
4310
  if (this._opcode === 0x00) {
4302
4311
  if (compressed) {
4303
- this._loop = false;
4304
- return error(
4312
+ const error = this.createError(
4305
4313
  RangeError,
4306
4314
  'RSV1 must be clear',
4307
4315
  true,
4308
4316
  1002,
4309
4317
  'WS_ERR_UNEXPECTED_RSV_1'
4310
4318
  );
4319
+
4320
+ cb(error);
4321
+ return;
4311
4322
  }
4312
4323
 
4313
4324
  if (!this._fragmented) {
4314
- this._loop = false;
4315
- return error(
4325
+ const error = this.createError(
4316
4326
  RangeError,
4317
4327
  'invalid opcode 0',
4318
4328
  true,
4319
4329
  1002,
4320
4330
  'WS_ERR_INVALID_OPCODE'
4321
4331
  );
4332
+
4333
+ cb(error);
4334
+ return;
4322
4335
  }
4323
4336
 
4324
4337
  this._opcode = this._fragmented;
4325
4338
  } else if (this._opcode === 0x01 || this._opcode === 0x02) {
4326
4339
  if (this._fragmented) {
4327
- this._loop = false;
4328
- return error(
4340
+ const error = this.createError(
4329
4341
  RangeError,
4330
4342
  `invalid opcode ${this._opcode}`,
4331
4343
  true,
4332
4344
  1002,
4333
4345
  'WS_ERR_INVALID_OPCODE'
4334
4346
  );
4347
+
4348
+ cb(error);
4349
+ return;
4335
4350
  }
4336
4351
 
4337
4352
  this._compressed = compressed;
4338
4353
  } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
4339
4354
  if (!this._fin) {
4340
- this._loop = false;
4341
- return error(
4355
+ const error = this.createError(
4342
4356
  RangeError,
4343
4357
  'FIN must be set',
4344
4358
  true,
4345
4359
  1002,
4346
4360
  'WS_ERR_EXPECTED_FIN'
4347
4361
  );
4362
+
4363
+ cb(error);
4364
+ return;
4348
4365
  }
4349
4366
 
4350
4367
  if (compressed) {
4351
- this._loop = false;
4352
- return error(
4368
+ const error = this.createError(
4353
4369
  RangeError,
4354
4370
  'RSV1 must be clear',
4355
4371
  true,
4356
4372
  1002,
4357
4373
  'WS_ERR_UNEXPECTED_RSV_1'
4358
4374
  );
4375
+
4376
+ cb(error);
4377
+ return;
4359
4378
  }
4360
4379
 
4361
4380
  if (
4362
4381
  this._payloadLength > 0x7d ||
4363
4382
  (this._opcode === 0x08 && this._payloadLength === 1)
4364
4383
  ) {
4365
- this._loop = false;
4366
- return error(
4384
+ const error = this.createError(
4367
4385
  RangeError,
4368
4386
  `invalid payload length ${this._payloadLength}`,
4369
4387
  true,
4370
4388
  1002,
4371
4389
  'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
4372
4390
  );
4391
+
4392
+ cb(error);
4393
+ return;
4373
4394
  }
4374
4395
  } else {
4375
- this._loop = false;
4376
- return error(
4396
+ const error = this.createError(
4377
4397
  RangeError,
4378
4398
  `invalid opcode ${this._opcode}`,
4379
4399
  true,
4380
4400
  1002,
4381
4401
  'WS_ERR_INVALID_OPCODE'
4382
4402
  );
4403
+
4404
+ cb(error);
4405
+ return;
4383
4406
  }
4384
4407
 
4385
4408
  if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
@@ -4387,54 +4410,58 @@ let Receiver$1 = class Receiver extends Writable {
4387
4410
 
4388
4411
  if (this._isServer) {
4389
4412
  if (!this._masked) {
4390
- this._loop = false;
4391
- return error(
4413
+ const error = this.createError(
4392
4414
  RangeError,
4393
4415
  'MASK must be set',
4394
4416
  true,
4395
4417
  1002,
4396
4418
  'WS_ERR_EXPECTED_MASK'
4397
4419
  );
4420
+
4421
+ cb(error);
4422
+ return;
4398
4423
  }
4399
4424
  } else if (this._masked) {
4400
- this._loop = false;
4401
- return error(
4425
+ const error = this.createError(
4402
4426
  RangeError,
4403
4427
  'MASK must be clear',
4404
4428
  true,
4405
4429
  1002,
4406
4430
  'WS_ERR_UNEXPECTED_MASK'
4407
4431
  );
4432
+
4433
+ cb(error);
4434
+ return;
4408
4435
  }
4409
4436
 
4410
4437
  if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
4411
4438
  else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
4412
- else return this.haveLength();
4439
+ else this.haveLength(cb);
4413
4440
  }
4414
4441
 
4415
4442
  /**
4416
4443
  * Gets extended payload length (7+16).
4417
4444
  *
4418
- * @return {(RangeError|undefined)} A possible error
4445
+ * @param {Function} cb Callback
4419
4446
  * @private
4420
4447
  */
4421
- getPayloadLength16() {
4448
+ getPayloadLength16(cb) {
4422
4449
  if (this._bufferedBytes < 2) {
4423
4450
  this._loop = false;
4424
4451
  return;
4425
4452
  }
4426
4453
 
4427
4454
  this._payloadLength = this.consume(2).readUInt16BE(0);
4428
- return this.haveLength();
4455
+ this.haveLength(cb);
4429
4456
  }
4430
4457
 
4431
4458
  /**
4432
4459
  * Gets extended payload length (7+64).
4433
4460
  *
4434
- * @return {(RangeError|undefined)} A possible error
4461
+ * @param {Function} cb Callback
4435
4462
  * @private
4436
4463
  */
4437
- getPayloadLength64() {
4464
+ getPayloadLength64(cb) {
4438
4465
  if (this._bufferedBytes < 8) {
4439
4466
  this._loop = false;
4440
4467
  return;
@@ -4448,38 +4475,42 @@ let Receiver$1 = class Receiver extends Writable {
4448
4475
  // if payload length is greater than this number.
4449
4476
  //
4450
4477
  if (num > Math.pow(2, 53 - 32) - 1) {
4451
- this._loop = false;
4452
- return error(
4478
+ const error = this.createError(
4453
4479
  RangeError,
4454
4480
  'Unsupported WebSocket frame: payload length > 2^53 - 1',
4455
4481
  false,
4456
4482
  1009,
4457
4483
  'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
4458
4484
  );
4485
+
4486
+ cb(error);
4487
+ return;
4459
4488
  }
4460
4489
 
4461
4490
  this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
4462
- return this.haveLength();
4491
+ this.haveLength(cb);
4463
4492
  }
4464
4493
 
4465
4494
  /**
4466
4495
  * Payload length has been read.
4467
4496
  *
4468
- * @return {(RangeError|undefined)} A possible error
4497
+ * @param {Function} cb Callback
4469
4498
  * @private
4470
4499
  */
4471
- haveLength() {
4500
+ haveLength(cb) {
4472
4501
  if (this._payloadLength && this._opcode < 0x08) {
4473
4502
  this._totalPayloadLength += this._payloadLength;
4474
4503
  if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
4475
- this._loop = false;
4476
- return error(
4504
+ const error = this.createError(
4477
4505
  RangeError,
4478
4506
  'Max payload size exceeded',
4479
4507
  false,
4480
4508
  1009,
4481
4509
  'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
4482
4510
  );
4511
+
4512
+ cb(error);
4513
+ return;
4483
4514
  }
4484
4515
  }
4485
4516
 
@@ -4506,7 +4537,6 @@ let Receiver$1 = class Receiver extends Writable {
4506
4537
  * Reads data bytes.
4507
4538
  *
4508
4539
  * @param {Function} cb Callback
4509
- * @return {(Error|RangeError|undefined)} A possible error
4510
4540
  * @private
4511
4541
  */
4512
4542
  getData(cb) {
@@ -4528,7 +4558,10 @@ let Receiver$1 = class Receiver extends Writable {
4528
4558
  }
4529
4559
  }
4530
4560
 
4531
- if (this._opcode > 0x07) return this.controlMessage(data);
4561
+ if (this._opcode > 0x07) {
4562
+ this.controlMessage(data, cb);
4563
+ return;
4564
+ }
4532
4565
 
4533
4566
  if (this._compressed) {
4534
4567
  this._state = INFLATING;
@@ -4545,7 +4578,7 @@ let Receiver$1 = class Receiver extends Writable {
4545
4578
  this._fragments.push(data);
4546
4579
  }
4547
4580
 
4548
- return this.dataMessage();
4581
+ this.dataMessage(cb);
4549
4582
  }
4550
4583
 
4551
4584
  /**
@@ -4564,74 +4597,96 @@ let Receiver$1 = class Receiver extends Writable {
4564
4597
  if (buf.length) {
4565
4598
  this._messageLength += buf.length;
4566
4599
  if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
4567
- return cb(
4568
- error(
4569
- RangeError,
4570
- 'Max payload size exceeded',
4571
- false,
4572
- 1009,
4573
- 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
4574
- )
4600
+ const error = this.createError(
4601
+ RangeError,
4602
+ 'Max payload size exceeded',
4603
+ false,
4604
+ 1009,
4605
+ 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
4575
4606
  );
4607
+
4608
+ cb(error);
4609
+ return;
4576
4610
  }
4577
4611
 
4578
4612
  this._fragments.push(buf);
4579
4613
  }
4580
4614
 
4581
- const er = this.dataMessage();
4582
- if (er) return cb(er);
4583
-
4584
- this.startLoop(cb);
4615
+ this.dataMessage(cb);
4616
+ if (this._state === GET_INFO) this.startLoop(cb);
4585
4617
  });
4586
4618
  }
4587
4619
 
4588
4620
  /**
4589
4621
  * Handles a data message.
4590
4622
  *
4591
- * @return {(Error|undefined)} A possible error
4623
+ * @param {Function} cb Callback
4592
4624
  * @private
4593
4625
  */
4594
- dataMessage() {
4595
- if (this._fin) {
4596
- const messageLength = this._messageLength;
4597
- const fragments = this._fragments;
4598
-
4599
- this._totalPayloadLength = 0;
4600
- this._messageLength = 0;
4601
- this._fragmented = 0;
4602
- this._fragments = [];
4603
-
4604
- if (this._opcode === 2) {
4605
- let data;
4606
-
4607
- if (this._binaryType === 'nodebuffer') {
4608
- data = concat(fragments, messageLength);
4609
- } else if (this._binaryType === 'arraybuffer') {
4610
- data = toArrayBuffer(concat(fragments, messageLength));
4611
- } else {
4612
- data = fragments;
4613
- }
4626
+ dataMessage(cb) {
4627
+ if (!this._fin) {
4628
+ this._state = GET_INFO;
4629
+ return;
4630
+ }
4631
+
4632
+ const messageLength = this._messageLength;
4633
+ const fragments = this._fragments;
4634
+
4635
+ this._totalPayloadLength = 0;
4636
+ this._messageLength = 0;
4637
+ this._fragmented = 0;
4638
+ this._fragments = [];
4639
+
4640
+ if (this._opcode === 2) {
4641
+ let data;
4614
4642
 
4643
+ if (this._binaryType === 'nodebuffer') {
4644
+ data = concat(fragments, messageLength);
4645
+ } else if (this._binaryType === 'arraybuffer') {
4646
+ data = toArrayBuffer(concat(fragments, messageLength));
4647
+ } else {
4648
+ data = fragments;
4649
+ }
4650
+
4651
+ if (this._allowSynchronousEvents) {
4615
4652
  this.emit('message', data, true);
4653
+ this._state = GET_INFO;
4616
4654
  } else {
4617
- const buf = concat(fragments, messageLength);
4655
+ this._state = DEFER_EVENT;
4656
+ setImmediate(() => {
4657
+ this.emit('message', data, true);
4658
+ this._state = GET_INFO;
4659
+ this.startLoop(cb);
4660
+ });
4661
+ }
4662
+ } else {
4663
+ const buf = concat(fragments, messageLength);
4618
4664
 
4619
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
4620
- this._loop = false;
4621
- return error(
4622
- Error,
4623
- 'invalid UTF-8 sequence',
4624
- true,
4625
- 1007,
4626
- 'WS_ERR_INVALID_UTF8'
4627
- );
4628
- }
4665
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
4666
+ const error = this.createError(
4667
+ Error,
4668
+ 'invalid UTF-8 sequence',
4669
+ true,
4670
+ 1007,
4671
+ 'WS_ERR_INVALID_UTF8'
4672
+ );
4673
+
4674
+ cb(error);
4675
+ return;
4676
+ }
4629
4677
 
4678
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
4630
4679
  this.emit('message', buf, false);
4680
+ this._state = GET_INFO;
4681
+ } else {
4682
+ this._state = DEFER_EVENT;
4683
+ setImmediate(() => {
4684
+ this.emit('message', buf, false);
4685
+ this._state = GET_INFO;
4686
+ this.startLoop(cb);
4687
+ });
4631
4688
  }
4632
4689
  }
4633
-
4634
- this._state = WAIT_MICROTASK;
4635
4690
  }
4636
4691
 
4637
4692
  /**
@@ -4641,26 +4696,26 @@ let Receiver$1 = class Receiver extends Writable {
4641
4696
  * @return {(Error|RangeError|undefined)} A possible error
4642
4697
  * @private
4643
4698
  */
4644
- controlMessage(data) {
4699
+ controlMessage(data, cb) {
4645
4700
  if (this._opcode === 0x08) {
4646
- this._loop = false;
4647
-
4648
4701
  if (data.length === 0) {
4702
+ this._loop = false;
4649
4703
  this.emit('conclude', 1005, EMPTY_BUFFER$2);
4650
4704
  this.end();
4651
-
4652
- this._state = GET_INFO;
4653
4705
  } else {
4654
4706
  const code = data.readUInt16BE(0);
4655
4707
 
4656
4708
  if (!isValidStatusCode$1(code)) {
4657
- return error(
4709
+ const error = this.createError(
4658
4710
  RangeError,
4659
4711
  `invalid status code ${code}`,
4660
4712
  true,
4661
4713
  1002,
4662
4714
  'WS_ERR_INVALID_CLOSE_CODE'
4663
4715
  );
4716
+
4717
+ cb(error);
4718
+ return;
4664
4719
  }
4665
4720
 
4666
4721
  const buf = new FastBuffer(
@@ -4670,83 +4725,68 @@ let Receiver$1 = class Receiver extends Writable {
4670
4725
  );
4671
4726
 
4672
4727
  if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
4673
- return error(
4728
+ const error = this.createError(
4674
4729
  Error,
4675
4730
  'invalid UTF-8 sequence',
4676
4731
  true,
4677
4732
  1007,
4678
4733
  'WS_ERR_INVALID_UTF8'
4679
4734
  );
4735
+
4736
+ cb(error);
4737
+ return;
4680
4738
  }
4681
4739
 
4740
+ this._loop = false;
4682
4741
  this.emit('conclude', code, buf);
4683
4742
  this.end();
4684
-
4685
- this._state = GET_INFO;
4686
4743
  }
4687
- } else if (this._opcode === 0x09) {
4688
- this.emit('ping', data);
4689
- this._state = WAIT_MICROTASK;
4744
+
4745
+ this._state = GET_INFO;
4746
+ return;
4747
+ }
4748
+
4749
+ if (this._allowSynchronousEvents) {
4750
+ this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
4751
+ this._state = GET_INFO;
4690
4752
  } else {
4691
- this.emit('pong', data);
4692
- this._state = WAIT_MICROTASK;
4753
+ this._state = DEFER_EVENT;
4754
+ setImmediate(() => {
4755
+ this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
4756
+ this._state = GET_INFO;
4757
+ this.startLoop(cb);
4758
+ });
4693
4759
  }
4694
4760
  }
4695
- };
4696
-
4697
- var receiver = Receiver$1;
4698
4761
 
4699
- /**
4700
- * Builds an error object.
4701
- *
4702
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
4703
- * @param {String} message The error message
4704
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
4705
- * `message`
4706
- * @param {Number} statusCode The status code
4707
- * @param {String} errorCode The exposed error code
4708
- * @return {(Error|RangeError)} The error
4709
- * @private
4710
- */
4711
- function error(ErrorCtor, message, prefix, statusCode, errorCode) {
4712
- const err = new ErrorCtor(
4713
- prefix ? `Invalid WebSocket frame: ${message}` : message
4714
- );
4715
-
4716
- Error.captureStackTrace(err, error);
4717
- err.code = errorCode;
4718
- err[kStatusCode$1] = statusCode;
4719
- return err;
4720
- }
4762
+ /**
4763
+ * Builds an error object.
4764
+ *
4765
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
4766
+ * @param {String} message The error message
4767
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
4768
+ * `message`
4769
+ * @param {Number} statusCode The status code
4770
+ * @param {String} errorCode The exposed error code
4771
+ * @return {(Error|RangeError)} The error
4772
+ * @private
4773
+ */
4774
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
4775
+ this._loop = false;
4776
+ this._errored = true;
4721
4777
 
4722
- /**
4723
- * A shim for `queueMicrotask()`.
4724
- *
4725
- * @param {Function} cb Callback
4726
- */
4727
- function queueMicrotaskShim(cb) {
4728
- promise.then(cb).catch(throwErrorNextTick);
4729
- }
4778
+ const err = new ErrorCtor(
4779
+ prefix ? `Invalid WebSocket frame: ${message}` : message
4780
+ );
4730
4781
 
4731
- /**
4732
- * Throws an error.
4733
- *
4734
- * @param {Error} err The error to throw
4735
- * @private
4736
- */
4737
- function throwError(err) {
4738
- throw err;
4739
- }
4782
+ Error.captureStackTrace(err, this.createError);
4783
+ err.code = errorCode;
4784
+ err[kStatusCode$1] = statusCode;
4785
+ return err;
4786
+ }
4787
+ };
4740
4788
 
4741
- /**
4742
- * Throws an error in the next tick.
4743
- *
4744
- * @param {Error} err The error to throw
4745
- * @private
4746
- */
4747
- function throwErrorNextTick(err) {
4748
- process.nextTick(throwError, err);
4749
- }
4789
+ var receiver = Receiver$1;
4750
4790
 
4751
4791
  /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */
4752
4792
  const { randomFillSync } = require$$1;
@@ -5715,7 +5755,7 @@ function format$1(extensions) {
5715
5755
 
5716
5756
  var extension$1 = { format: format$1, parse: parse$2 };
5717
5757
 
5718
- /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$" }] */
5758
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */
5719
5759
 
5720
5760
  const EventEmitter$1 = require$$0$3;
5721
5761
  const https = require$$1$1;
@@ -5798,6 +5838,7 @@ let WebSocket$1 = class WebSocket extends EventEmitter$1 {
5798
5838
 
5799
5839
  initAsClient(this, address, protocols, options);
5800
5840
  } else {
5841
+ this._autoPong = options.autoPong;
5801
5842
  this._isServer = true;
5802
5843
  }
5803
5844
  }
@@ -5906,6 +5947,9 @@ let WebSocket$1 = class WebSocket extends EventEmitter$1 {
5906
5947
  * @param {Duplex} socket The network socket between the server and client
5907
5948
  * @param {Buffer} head The first packet of the upgraded stream
5908
5949
  * @param {Object} options Options object
5950
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
5951
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
5952
+ * multiple times in the same tick
5909
5953
  * @param {Function} [options.generateMask] The function used to generate the
5910
5954
  * masking key
5911
5955
  * @param {Number} [options.maxPayload=0] The maximum allowed message size
@@ -5915,6 +5959,7 @@ let WebSocket$1 = class WebSocket extends EventEmitter$1 {
5915
5959
  */
5916
5960
  setSocket(socket, head, options) {
5917
5961
  const receiver = new Receiver({
5962
+ allowSynchronousEvents: options.allowSynchronousEvents,
5918
5963
  binaryType: this.binaryType,
5919
5964
  extensions: this._extensions,
5920
5965
  isServer: this._isServer,
@@ -6332,6 +6377,13 @@ var websocket = WebSocket$1;
6332
6377
  * @param {(String|URL)} address The URL to which to connect
6333
6378
  * @param {Array} protocols The subprotocols
6334
6379
  * @param {Object} [options] Connection options
6380
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
6381
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
6382
+ * times in the same tick
6383
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
6384
+ * automatically send a pong in response to a ping
6385
+ * @param {Function} [options.finishRequest] A function which can be used to
6386
+ * customize the headers of each http request before it is sent
6335
6387
  * @param {Boolean} [options.followRedirects=false] Whether or not to follow
6336
6388
  * redirects
6337
6389
  * @param {Function} [options.generateMask] The function used to generate the
@@ -6354,6 +6406,8 @@ var websocket = WebSocket$1;
6354
6406
  */
6355
6407
  function initAsClient(websocket, address, protocols, options) {
6356
6408
  const opts = {
6409
+ allowSynchronousEvents: true,
6410
+ autoPong: true,
6357
6411
  protocolVersion: protocolVersions[1],
6358
6412
  maxPayload: 100 * 1024 * 1024,
6359
6413
  skipUTF8Validation: false,
@@ -6361,7 +6415,6 @@ function initAsClient(websocket, address, protocols, options) {
6361
6415
  followRedirects: false,
6362
6416
  maxRedirects: 10,
6363
6417
  ...options,
6364
- createConnection: undefined,
6365
6418
  socketPath: undefined,
6366
6419
  hostname: undefined,
6367
6420
  protocol: undefined,
@@ -6372,6 +6425,8 @@ function initAsClient(websocket, address, protocols, options) {
6372
6425
  port: undefined
6373
6426
  };
6374
6427
 
6428
+ websocket._autoPong = opts.autoPong;
6429
+
6375
6430
  if (!protocolVersions.includes(opts.protocolVersion)) {
6376
6431
  throw new RangeError(
6377
6432
  `Unsupported protocol version: ${opts.protocolVersion} ` +
@@ -6430,7 +6485,8 @@ function initAsClient(websocket, address, protocols, options) {
6430
6485
  const protocolSet = new Set();
6431
6486
  let perMessageDeflate;
6432
6487
 
6433
- opts.createConnection = isSecure ? tlsConnect : netConnect;
6488
+ opts.createConnection =
6489
+ opts.createConnection || (isSecure ? tlsConnect : netConnect);
6434
6490
  opts.defaultPort = opts.defaultPort || defaultPort;
6435
6491
  opts.port = parsedUrl.port || defaultPort;
6436
6492
  opts.host = parsedUrl.hostname.startsWith('[')
@@ -6520,8 +6576,8 @@ function initAsClient(websocket, address, protocols, options) {
6520
6576
  ? opts.socketPath === websocket._originalHostOrSocketPath
6521
6577
  : false
6522
6578
  : websocket._originalIpc
6523
- ? false
6524
- : parsedUrl.host === websocket._originalHostOrSocketPath;
6579
+ ? false
6580
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
6525
6581
 
6526
6582
  if (!isSameHost || (websocket._originalSecure && !isSecure)) {
6527
6583
  //
@@ -6705,6 +6761,7 @@ function initAsClient(websocket, address, protocols, options) {
6705
6761
  }
6706
6762
 
6707
6763
  websocket.setSocket(socket, head, {
6764
+ allowSynchronousEvents: opts.allowSynchronousEvents,
6708
6765
  generateMask: opts.generateMask,
6709
6766
  maxPayload: opts.maxPayload,
6710
6767
  skipUTF8Validation: opts.skipUTF8Validation
@@ -6915,7 +6972,7 @@ function receiverOnMessage(data, isBinary) {
6915
6972
  function receiverOnPing(data) {
6916
6973
  const websocket = this[kWebSocket$1];
6917
6974
 
6918
- websocket.pong(data, !websocket._isServer, NOOP);
6975
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
6919
6976
  websocket.emit('ping', data);
6920
6977
  }
6921
6978
 
@@ -7093,7 +7150,7 @@ function parse(header) {
7093
7150
 
7094
7151
  var subprotocol$1 = { parse };
7095
7152
 
7096
- /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$" }] */
7153
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
7097
7154
 
7098
7155
  const EventEmitter = require$$0$3;
7099
7156
  const http = require$$2;
@@ -7121,6 +7178,11 @@ class WebSocketServer extends EventEmitter {
7121
7178
  * Create a `WebSocketServer` instance.
7122
7179
  *
7123
7180
  * @param {Object} options Configuration options
7181
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
7182
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
7183
+ * multiple times in the same tick
7184
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
7185
+ * automatically send a pong in response to a ping
7124
7186
  * @param {Number} [options.backlog=511] The maximum length of the queue of
7125
7187
  * pending connections
7126
7188
  * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
@@ -7147,6 +7209,8 @@ class WebSocketServer extends EventEmitter {
7147
7209
  super();
7148
7210
 
7149
7211
  options = {
7212
+ allowSynchronousEvents: true,
7213
+ autoPong: true,
7150
7214
  maxPayload: 100 * 1024 * 1024,
7151
7215
  skipUTF8Validation: false,
7152
7216
  perMessageDeflate: false,
@@ -7467,7 +7531,7 @@ class WebSocketServer extends EventEmitter {
7467
7531
  `Sec-WebSocket-Accept: ${digest}`
7468
7532
  ];
7469
7533
 
7470
- const ws = new this.options.WebSocket(null);
7534
+ const ws = new this.options.WebSocket(null, undefined, this.options);
7471
7535
 
7472
7536
  if (protocols.size) {
7473
7537
  //
@@ -7501,6 +7565,7 @@ class WebSocketServer extends EventEmitter {
7501
7565
  socket.removeListener('error', socketOnError);
7502
7566
 
7503
7567
  ws.setSocket(socket, head, {
7568
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
7504
7569
  maxPayload: this.options.maxPayload,
7505
7570
  skipUTF8Validation: this.options.skipUTF8Validation
7506
7571
  });
@@ -7682,28 +7747,28 @@ function setup(vitestOrWorkspace, _server) {
7682
7747
  checkFileAccess(snapshotPath);
7683
7748
  if (!existsSync(snapshotPath))
7684
7749
  return null;
7685
- return promises.readFile(snapshotPath, "utf-8");
7750
+ return promises$1.readFile(snapshotPath, "utf-8");
7686
7751
  },
7687
7752
  async readTestFile(id) {
7688
7753
  if (!ctx.state.filesMap.has(id) || !existsSync(id))
7689
7754
  return null;
7690
- return promises.readFile(id, "utf-8");
7755
+ return promises$1.readFile(id, "utf-8");
7691
7756
  },
7692
7757
  async saveTestFile(id, content) {
7693
7758
  if (!ctx.state.filesMap.has(id) || !existsSync(id))
7694
7759
  throw new Error(`Test file "${id}" was not registered, so it cannot be updated using the API.`);
7695
- return promises.writeFile(id, content, "utf-8");
7760
+ return promises$1.writeFile(id, content, "utf-8");
7696
7761
  },
7697
7762
  async saveSnapshotFile(id, content) {
7698
7763
  checkFileAccess(id);
7699
- await promises.mkdir(dirname(id), { recursive: true });
7700
- return promises.writeFile(id, content, "utf-8");
7764
+ await promises$1.mkdir(dirname(id), { recursive: true });
7765
+ return promises$1.writeFile(id, content, "utf-8");
7701
7766
  },
7702
7767
  async removeSnapshotFile(id) {
7703
7768
  checkFileAccess(id);
7704
7769
  if (!existsSync(id))
7705
7770
  throw new Error(`Snapshot file "${id}" does not exist.`);
7706
- return promises.unlink(id);
7771
+ return promises$1.unlink(id);
7707
7772
  },
7708
7773
  snapshotSaved(snapshot) {
7709
7774
  ctx.snapshot.add(snapshot);
@@ -7725,7 +7790,7 @@ function setup(vitestOrWorkspace, _server) {
7725
7790
  const result = await ctx.vitenode.transformRequest(id);
7726
7791
  if (result) {
7727
7792
  try {
7728
- result.source = result.source || await promises.readFile(id, "utf-8");
7793
+ result.source = result.source || await promises$1.readFile(id, "utf-8");
7729
7794
  } catch {
7730
7795
  }
7731
7796
  return result;
@@ -7766,6 +7831,10 @@ function setup(vitestOrWorkspace, _server) {
7766
7831
  },
7767
7832
  getProvidedContext() {
7768
7833
  return "ctx" in vitestOrWorkspace ? vitestOrWorkspace.getProvidedContext() : {};
7834
+ },
7835
+ async getTestFiles() {
7836
+ const spec = await ctx.globTestFiles();
7837
+ return spec.map(([project, file]) => [project.getName(), file]);
7769
7838
  }
7770
7839
  },
7771
7840
  {
@@ -7862,7 +7931,7 @@ function getTransformMode(patterns, filename) {
7862
7931
  async function groupFilesByEnv(files) {
7863
7932
  const filesWithEnv = await Promise.all(files.map(async ([project, file]) => {
7864
7933
  var _a, _b;
7865
- const code = await promises.readFile(file, "utf-8");
7934
+ const code = await promises$1.readFile(file, "utf-8");
7866
7935
  let env = (_a = code.match(/@(?:vitest|jest)-environment\s+?([\w-]+)\b/)) == null ? void 0 : _a[1];
7867
7936
  if (!env) {
7868
7937
  for (const [glob, target] of project.config.environmentMatchGlobs || []) {
@@ -7890,6 +7959,8 @@ async function groupFilesByEnv(files) {
7890
7959
  return groupBy(filesWithEnv, ({ environment }) => environment.name);
7891
7960
  }
7892
7961
 
7962
+ const created = /* @__PURE__ */ new Set();
7963
+ const promises = /* @__PURE__ */ new Map();
7893
7964
  function createMethodsRPC(project) {
7894
7965
  const ctx = project.ctx;
7895
7966
  return {
@@ -7908,8 +7979,30 @@ function createMethodsRPC(project) {
7908
7979
  const r = await project.vitenode.transformRequest(id);
7909
7980
  return r == null ? void 0 : r.map;
7910
7981
  },
7911
- fetch(id, transformMode) {
7912
- return project.vitenode.fetchModule(id, transformMode);
7982
+ async fetch(id, transformMode) {
7983
+ const result = await project.vitenode.fetchResult(id, transformMode);
7984
+ const code = result.code;
7985
+ if (result.externalize)
7986
+ return result;
7987
+ if ("id" in result && typeof result.id === "string")
7988
+ return { id: result.id };
7989
+ if (code == null)
7990
+ throw new Error(`Failed to fetch module ${id}`);
7991
+ const dir = join(project.tmpDir, transformMode);
7992
+ const name = createHash$2("sha1").update(id).digest("hex");
7993
+ const tmp = join(dir, name);
7994
+ if (promises.has(tmp)) {
7995
+ await promises.get(tmp);
7996
+ return { id: tmp };
7997
+ }
7998
+ if (!created.has(dir)) {
7999
+ await mkdir(dir, { recursive: true });
8000
+ created.add(dir);
8001
+ }
8002
+ promises.set(tmp, writeFile(tmp, code, "utf-8").finally(() => promises.delete(tmp)));
8003
+ await promises.get(tmp);
8004
+ Object.assign(result, { id: tmp });
8005
+ return { id: tmp };
7913
8006
  },
7914
8007
  resolveId(id, importer, transformMode) {
7915
8008
  return project.vitenode.resolveId(id, importer, transformMode);
@@ -8906,144 +8999,2256 @@ function createBenchmarkReporters(reporterReferences, runner) {
8906
8999
  return Promise.all(promisedReporters);
8907
9000
  }
8908
9001
 
8909
- function isAggregateError(err) {
8910
- if (typeof AggregateError !== "undefined" && err instanceof AggregateError)
8911
- return true;
8912
- return err instanceof Error && "errors" in err;
9002
+ function isAggregateError(err) {
9003
+ if (typeof AggregateError !== "undefined" && err instanceof AggregateError)
9004
+ return true;
9005
+ return err instanceof Error && "errors" in err;
9006
+ }
9007
+ class StateManager {
9008
+ filesMap = /* @__PURE__ */ new Map();
9009
+ pathsSet = /* @__PURE__ */ new Set();
9010
+ idMap = /* @__PURE__ */ new Map();
9011
+ taskFileMap = /* @__PURE__ */ new WeakMap();
9012
+ errorsSet = /* @__PURE__ */ new Set();
9013
+ processTimeoutCauses = /* @__PURE__ */ new Set();
9014
+ catchError(err, type) {
9015
+ if (isAggregateError(err))
9016
+ return err.errors.forEach((error) => this.catchError(error, type));
9017
+ if (err === Object(err))
9018
+ err.type = type;
9019
+ else
9020
+ err = { type, message: err };
9021
+ const _err = err;
9022
+ if (_err && typeof _err === "object" && _err.code === "VITEST_PENDING") {
9023
+ const task = this.idMap.get(_err.taskId);
9024
+ if (task) {
9025
+ task.mode = "skip";
9026
+ task.result ?? (task.result = { state: "skip" });
9027
+ task.result.state = "skip";
9028
+ }
9029
+ return;
9030
+ }
9031
+ this.errorsSet.add(err);
9032
+ }
9033
+ clearErrors() {
9034
+ this.errorsSet.clear();
9035
+ }
9036
+ getUnhandledErrors() {
9037
+ return Array.from(this.errorsSet.values());
9038
+ }
9039
+ addProcessTimeoutCause(cause) {
9040
+ this.processTimeoutCauses.add(cause);
9041
+ }
9042
+ getProcessTimeoutCauses() {
9043
+ return Array.from(this.processTimeoutCauses.values());
9044
+ }
9045
+ getPaths() {
9046
+ return Array.from(this.pathsSet);
9047
+ }
9048
+ getFiles(keys) {
9049
+ if (keys)
9050
+ return keys.map((key) => this.filesMap.get(key)).filter(Boolean).flat();
9051
+ return Array.from(this.filesMap.values()).flat();
9052
+ }
9053
+ getFilepaths() {
9054
+ return Array.from(this.filesMap.keys());
9055
+ }
9056
+ getFailedFilepaths() {
9057
+ return this.getFiles().filter((i) => {
9058
+ var _a;
9059
+ return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
9060
+ }).map((i) => i.filepath);
9061
+ }
9062
+ collectPaths(paths = []) {
9063
+ paths.forEach((path) => {
9064
+ this.pathsSet.add(path);
9065
+ });
9066
+ }
9067
+ collectFiles(files = []) {
9068
+ files.forEach((file) => {
9069
+ const existing = this.filesMap.get(file.filepath) || [];
9070
+ const otherProject = existing.filter((i) => i.projectName !== file.projectName);
9071
+ otherProject.push(file);
9072
+ this.filesMap.set(file.filepath, otherProject);
9073
+ this.updateId(file);
9074
+ });
9075
+ }
9076
+ // this file is reused by ws-client, and shoult not rely on heavy dependencies like workspace
9077
+ clearFiles(_project, paths = []) {
9078
+ const project = _project;
9079
+ paths.forEach((path) => {
9080
+ const files = this.filesMap.get(path);
9081
+ if (!files)
9082
+ return;
9083
+ const filtered = files.filter((file) => file.projectName !== project.config.name);
9084
+ if (!filtered.length)
9085
+ this.filesMap.delete(path);
9086
+ else
9087
+ this.filesMap.set(path, filtered);
9088
+ });
9089
+ }
9090
+ updateId(task) {
9091
+ if (this.idMap.get(task.id) === task)
9092
+ return;
9093
+ this.idMap.set(task.id, task);
9094
+ if (task.type === "suite") {
9095
+ task.tasks.forEach((task2) => {
9096
+ this.updateId(task2);
9097
+ });
9098
+ }
9099
+ }
9100
+ updateTasks(packs) {
9101
+ for (const [id, result, meta] of packs) {
9102
+ const task = this.idMap.get(id);
9103
+ if (task) {
9104
+ task.result = result;
9105
+ task.meta = meta;
9106
+ if ((result == null ? void 0 : result.state) === "skip")
9107
+ task.mode = "skip";
9108
+ }
9109
+ }
9110
+ }
9111
+ updateUserLog(log) {
9112
+ const task = log.taskId && this.idMap.get(log.taskId);
9113
+ if (task) {
9114
+ if (!task.logs)
9115
+ task.logs = [];
9116
+ task.logs.push(log);
9117
+ }
9118
+ }
9119
+ getCountOfFailedTests() {
9120
+ return Array.from(this.idMap.values()).filter((t) => {
9121
+ var _a;
9122
+ return ((_a = t.result) == null ? void 0 : _a.state) === "fail";
9123
+ }).length;
9124
+ }
9125
+ cancelFiles(files, root, projectName) {
9126
+ this.collectFiles(files.map((filepath) => {
9127
+ const file = {
9128
+ filepath,
9129
+ name: relative(root, filepath),
9130
+ id: filepath,
9131
+ mode: "skip",
9132
+ type: "suite",
9133
+ result: {
9134
+ state: "skip"
9135
+ },
9136
+ meta: {},
9137
+ // Cancelled files have not yet collected tests
9138
+ tasks: [],
9139
+ projectName,
9140
+ file: null
9141
+ };
9142
+ file.file = file;
9143
+ return file;
9144
+ }));
9145
+ }
9146
+ }
9147
+
9148
+ const JOIN_LEADING_SLASH_RE = /^\.?\//;
9149
+ function withTrailingSlash(input = "", respectQueryAndFragment) {
9150
+ {
9151
+ return input.endsWith("/") ? input : input + "/";
9152
+ }
9153
+ }
9154
+ function isNonEmptyURL(url) {
9155
+ return url && url !== "/";
9156
+ }
9157
+ function joinURL(base, ...input) {
9158
+ let url = base || "";
9159
+ for (const segment of input.filter((url2) => isNonEmptyURL(url2))) {
9160
+ if (url) {
9161
+ const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
9162
+ url = withTrailingSlash(url) + _segment;
9163
+ } else {
9164
+ url = segment;
9165
+ }
9166
+ }
9167
+ return url;
9168
+ }
9169
+
9170
+ const BUILTIN_MODULES = new Set(builtinModules);
9171
+ function normalizeSlash(path) {
9172
+ return path.replace(/\\/g, "/");
9173
+ }
9174
+
9175
+ /**
9176
+ * @typedef ErrnoExceptionFields
9177
+ * @property {number | undefined} [errnode]
9178
+ * @property {string | undefined} [code]
9179
+ * @property {string | undefined} [path]
9180
+ * @property {string | undefined} [syscall]
9181
+ * @property {string | undefined} [url]
9182
+ *
9183
+ * @typedef {Error & ErrnoExceptionFields} ErrnoException
9184
+ */
9185
+
9186
+
9187
+ const own$1 = {}.hasOwnProperty;
9188
+
9189
+ const classRegExp = /^([A-Z][a-z\d]*)+$/;
9190
+ // Sorted by a rough estimate on most frequently used entries.
9191
+ const kTypes = new Set([
9192
+ 'string',
9193
+ 'function',
9194
+ 'number',
9195
+ 'object',
9196
+ // Accept 'Function' and 'Object' as alternative to the lower cased version.
9197
+ 'Function',
9198
+ 'Object',
9199
+ 'boolean',
9200
+ 'bigint',
9201
+ 'symbol'
9202
+ ]);
9203
+
9204
+ const codes = {};
9205
+
9206
+ /**
9207
+ * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
9208
+ * We cannot use Intl.ListFormat because it's not available in
9209
+ * --without-intl builds.
9210
+ *
9211
+ * @param {Array<string>} array
9212
+ * An array of strings.
9213
+ * @param {string} [type]
9214
+ * The list type to be inserted before the last element.
9215
+ * @returns {string}
9216
+ */
9217
+ function formatList(array, type = 'and') {
9218
+ return array.length < 3
9219
+ ? array.join(` ${type} `)
9220
+ : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
9221
+ }
9222
+
9223
+ /** @type {Map<string, MessageFunction | string>} */
9224
+ const messages = new Map();
9225
+ const nodeInternalPrefix = '__node_internal_';
9226
+ /** @type {number} */
9227
+ let userStackTraceLimit;
9228
+
9229
+ codes.ERR_INVALID_ARG_TYPE = createError(
9230
+ 'ERR_INVALID_ARG_TYPE',
9231
+ /**
9232
+ * @param {string} name
9233
+ * @param {Array<string> | string} expected
9234
+ * @param {unknown} actual
9235
+ */
9236
+ (name, expected, actual) => {
9237
+ assert(typeof name === 'string', "'name' must be a string");
9238
+ if (!Array.isArray(expected)) {
9239
+ expected = [expected];
9240
+ }
9241
+
9242
+ let message = 'The ';
9243
+ if (name.endsWith(' argument')) {
9244
+ // For cases like 'first argument'
9245
+ message += `${name} `;
9246
+ } else {
9247
+ const type = name.includes('.') ? 'property' : 'argument';
9248
+ message += `"${name}" ${type} `;
9249
+ }
9250
+
9251
+ message += 'must be ';
9252
+
9253
+ /** @type {Array<string>} */
9254
+ const types = [];
9255
+ /** @type {Array<string>} */
9256
+ const instances = [];
9257
+ /** @type {Array<string>} */
9258
+ const other = [];
9259
+
9260
+ for (const value of expected) {
9261
+ assert(
9262
+ typeof value === 'string',
9263
+ 'All expected entries have to be of type string'
9264
+ );
9265
+
9266
+ if (kTypes.has(value)) {
9267
+ types.push(value.toLowerCase());
9268
+ } else if (classRegExp.exec(value) === null) {
9269
+ assert(
9270
+ value !== 'object',
9271
+ 'The value "object" should be written as "Object"'
9272
+ );
9273
+ other.push(value);
9274
+ } else {
9275
+ instances.push(value);
9276
+ }
9277
+ }
9278
+
9279
+ // Special handle `object` in case other instances are allowed to outline
9280
+ // the differences between each other.
9281
+ if (instances.length > 0) {
9282
+ const pos = types.indexOf('object');
9283
+ if (pos !== -1) {
9284
+ types.slice(pos, 1);
9285
+ instances.push('Object');
9286
+ }
9287
+ }
9288
+
9289
+ if (types.length > 0) {
9290
+ message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
9291
+ types,
9292
+ 'or'
9293
+ )}`;
9294
+ if (instances.length > 0 || other.length > 0) message += ' or ';
9295
+ }
9296
+
9297
+ if (instances.length > 0) {
9298
+ message += `an instance of ${formatList(instances, 'or')}`;
9299
+ if (other.length > 0) message += ' or ';
9300
+ }
9301
+
9302
+ if (other.length > 0) {
9303
+ if (other.length > 1) {
9304
+ message += `one of ${formatList(other, 'or')}`;
9305
+ } else {
9306
+ if (other[0].toLowerCase() !== other[0]) message += 'an ';
9307
+ message += `${other[0]}`;
9308
+ }
9309
+ }
9310
+
9311
+ message += `. Received ${determineSpecificType(actual)}`;
9312
+
9313
+ return message
9314
+ },
9315
+ TypeError
9316
+ );
9317
+
9318
+ codes.ERR_INVALID_MODULE_SPECIFIER = createError(
9319
+ 'ERR_INVALID_MODULE_SPECIFIER',
9320
+ /**
9321
+ * @param {string} request
9322
+ * @param {string} reason
9323
+ * @param {string} [base]
9324
+ */
9325
+ (request, reason, base = undefined) => {
9326
+ return `Invalid module "${request}" ${reason}${
9327
+ base ? ` imported from ${base}` : ''
9328
+ }`
9329
+ },
9330
+ TypeError
9331
+ );
9332
+
9333
+ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
9334
+ 'ERR_INVALID_PACKAGE_CONFIG',
9335
+ /**
9336
+ * @param {string} path
9337
+ * @param {string} [base]
9338
+ * @param {string} [message]
9339
+ */
9340
+ (path, base, message) => {
9341
+ return `Invalid package config ${path}${
9342
+ base ? ` while importing ${base}` : ''
9343
+ }${message ? `. ${message}` : ''}`
9344
+ },
9345
+ Error
9346
+ );
9347
+
9348
+ codes.ERR_INVALID_PACKAGE_TARGET = createError(
9349
+ 'ERR_INVALID_PACKAGE_TARGET',
9350
+ /**
9351
+ * @param {string} packagePath
9352
+ * @param {string} key
9353
+ * @param {unknown} target
9354
+ * @param {boolean} [isImport=false]
9355
+ * @param {string} [base]
9356
+ */
9357
+ (packagePath, key, target, isImport = false, base = undefined) => {
9358
+ const relatedError =
9359
+ typeof target === 'string' &&
9360
+ !isImport &&
9361
+ target.length > 0 &&
9362
+ !target.startsWith('./');
9363
+ if (key === '.') {
9364
+ assert(isImport === false);
9365
+ return (
9366
+ `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
9367
+ `in the package config ${packagePath}package.json${
9368
+ base ? ` imported from ${base}` : ''
9369
+ }${relatedError ? '; targets must start with "./"' : ''}`
9370
+ )
9371
+ }
9372
+
9373
+ return `Invalid "${
9374
+ isImport ? 'imports' : 'exports'
9375
+ }" target ${JSON.stringify(
9376
+ target
9377
+ )} defined for '${key}' in the package config ${packagePath}package.json${
9378
+ base ? ` imported from ${base}` : ''
9379
+ }${relatedError ? '; targets must start with "./"' : ''}`
9380
+ },
9381
+ Error
9382
+ );
9383
+
9384
+ codes.ERR_MODULE_NOT_FOUND = createError(
9385
+ 'ERR_MODULE_NOT_FOUND',
9386
+ /**
9387
+ * @param {string} path
9388
+ * @param {string} base
9389
+ * @param {boolean} [exactUrl]
9390
+ */
9391
+ (path, base, exactUrl = false) => {
9392
+ return `Cannot find ${
9393
+ exactUrl ? 'module' : 'package'
9394
+ } '${path}' imported from ${base}`
9395
+ },
9396
+ Error
9397
+ );
9398
+
9399
+ codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
9400
+ 'ERR_NETWORK_IMPORT_DISALLOWED',
9401
+ "import of '%s' by %s is not supported: %s",
9402
+ Error
9403
+ );
9404
+
9405
+ codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
9406
+ 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
9407
+ /**
9408
+ * @param {string} specifier
9409
+ * @param {string} packagePath
9410
+ * @param {string} base
9411
+ */
9412
+ (specifier, packagePath, base) => {
9413
+ return `Package import specifier "${specifier}" is not defined${
9414
+ packagePath ? ` in package ${packagePath}package.json` : ''
9415
+ } imported from ${base}`
9416
+ },
9417
+ TypeError
9418
+ );
9419
+
9420
+ codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
9421
+ 'ERR_PACKAGE_PATH_NOT_EXPORTED',
9422
+ /**
9423
+ * @param {string} packagePath
9424
+ * @param {string} subpath
9425
+ * @param {string} [base]
9426
+ */
9427
+ (packagePath, subpath, base = undefined) => {
9428
+ if (subpath === '.')
9429
+ return `No "exports" main defined in ${packagePath}package.json${
9430
+ base ? ` imported from ${base}` : ''
9431
+ }`
9432
+ return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${
9433
+ base ? ` imported from ${base}` : ''
9434
+ }`
9435
+ },
9436
+ Error
9437
+ );
9438
+
9439
+ codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
9440
+ 'ERR_UNSUPPORTED_DIR_IMPORT',
9441
+ "Directory import '%s' is not supported " +
9442
+ 'resolving ES modules imported from %s',
9443
+ Error
9444
+ );
9445
+
9446
+ codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(
9447
+ 'ERR_UNSUPPORTED_RESOLVE_REQUEST',
9448
+ 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
9449
+ TypeError
9450
+ );
9451
+
9452
+ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
9453
+ 'ERR_UNKNOWN_FILE_EXTENSION',
9454
+ /**
9455
+ * @param {string} extension
9456
+ * @param {string} path
9457
+ */
9458
+ (extension, path) => {
9459
+ return `Unknown file extension "${extension}" for ${path}`
9460
+ },
9461
+ TypeError
9462
+ );
9463
+
9464
+ codes.ERR_INVALID_ARG_VALUE = createError(
9465
+ 'ERR_INVALID_ARG_VALUE',
9466
+ /**
9467
+ * @param {string} name
9468
+ * @param {unknown} value
9469
+ * @param {string} [reason='is invalid']
9470
+ */
9471
+ (name, value, reason = 'is invalid') => {
9472
+ let inspected = inspect(value);
9473
+
9474
+ if (inspected.length > 128) {
9475
+ inspected = `${inspected.slice(0, 128)}...`;
9476
+ }
9477
+
9478
+ const type = name.includes('.') ? 'property' : 'argument';
9479
+
9480
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`
9481
+ },
9482
+ TypeError
9483
+ // Note: extra classes have been shaken out.
9484
+ // , RangeError
9485
+ );
9486
+
9487
+ /**
9488
+ * Utility function for registering the error codes. Only used here. Exported
9489
+ * *only* to allow for testing.
9490
+ * @param {string} sym
9491
+ * @param {MessageFunction | string} value
9492
+ * @param {ErrorConstructor} constructor
9493
+ * @returns {new (...parameters: Array<any>) => Error}
9494
+ */
9495
+ function createError(sym, value, constructor) {
9496
+ // Special case for SystemError that formats the error message differently
9497
+ // The SystemErrors only have SystemError as their base classes.
9498
+ messages.set(sym, value);
9499
+
9500
+ return makeNodeErrorWithCode(constructor, sym)
9501
+ }
9502
+
9503
+ /**
9504
+ * @param {ErrorConstructor} Base
9505
+ * @param {string} key
9506
+ * @returns {ErrorConstructor}
9507
+ */
9508
+ function makeNodeErrorWithCode(Base, key) {
9509
+ // @ts-expect-error It’s a Node error.
9510
+ return NodeError
9511
+ /**
9512
+ * @param {Array<unknown>} parameters
9513
+ */
9514
+ function NodeError(...parameters) {
9515
+ const limit = Error.stackTraceLimit;
9516
+ if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
9517
+ const error = new Base();
9518
+ // Reset the limit and setting the name property.
9519
+ if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
9520
+ const message = getMessage(key, parameters, error);
9521
+ Object.defineProperties(error, {
9522
+ // Note: no need to implement `kIsNodeError` symbol, would be hard,
9523
+ // probably.
9524
+ message: {
9525
+ value: message,
9526
+ enumerable: false,
9527
+ writable: true,
9528
+ configurable: true
9529
+ },
9530
+ toString: {
9531
+ /** @this {Error} */
9532
+ value() {
9533
+ return `${this.name} [${key}]: ${this.message}`
9534
+ },
9535
+ enumerable: false,
9536
+ writable: true,
9537
+ configurable: true
9538
+ }
9539
+ });
9540
+
9541
+ captureLargerStackTrace(error);
9542
+ // @ts-expect-error It’s a Node error.
9543
+ error.code = key;
9544
+ return error
9545
+ }
9546
+ }
9547
+
9548
+ /**
9549
+ * @returns {boolean}
9550
+ */
9551
+ function isErrorStackTraceLimitWritable() {
9552
+ // Do no touch Error.stackTraceLimit as V8 would attempt to install
9553
+ // it again during deserialization.
9554
+ try {
9555
+ if (v8.startupSnapshot.isBuildingSnapshot()) {
9556
+ return false
9557
+ }
9558
+ } catch {}
9559
+
9560
+ const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
9561
+ if (desc === undefined) {
9562
+ return Object.isExtensible(Error)
9563
+ }
9564
+
9565
+ return own$1.call(desc, 'writable') && desc.writable !== undefined
9566
+ ? desc.writable
9567
+ : desc.set !== undefined
9568
+ }
9569
+
9570
+ /**
9571
+ * This function removes unnecessary frames from Node.js core errors.
9572
+ * @template {(...parameters: unknown[]) => unknown} T
9573
+ * @param {T} wrappedFunction
9574
+ * @returns {T}
9575
+ */
9576
+ function hideStackFrames(wrappedFunction) {
9577
+ // We rename the functions that will be hidden to cut off the stacktrace
9578
+ // at the outermost one
9579
+ const hidden = nodeInternalPrefix + wrappedFunction.name;
9580
+ Object.defineProperty(wrappedFunction, 'name', {value: hidden});
9581
+ return wrappedFunction
9582
+ }
9583
+
9584
+ const captureLargerStackTrace = hideStackFrames(
9585
+ /**
9586
+ * @param {Error} error
9587
+ * @returns {Error}
9588
+ */
9589
+ // @ts-expect-error: fine
9590
+ function (error) {
9591
+ const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
9592
+ if (stackTraceLimitIsWritable) {
9593
+ userStackTraceLimit = Error.stackTraceLimit;
9594
+ Error.stackTraceLimit = Number.POSITIVE_INFINITY;
9595
+ }
9596
+
9597
+ Error.captureStackTrace(error);
9598
+
9599
+ // Reset the limit
9600
+ if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
9601
+
9602
+ return error
9603
+ }
9604
+ );
9605
+
9606
+ /**
9607
+ * @param {string} key
9608
+ * @param {Array<unknown>} parameters
9609
+ * @param {Error} self
9610
+ * @returns {string}
9611
+ */
9612
+ function getMessage(key, parameters, self) {
9613
+ const message = messages.get(key);
9614
+ assert(message !== undefined, 'expected `message` to be found');
9615
+
9616
+ if (typeof message === 'function') {
9617
+ assert(
9618
+ message.length <= parameters.length, // Default options do not count.
9619
+ `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
9620
+ `match the required ones (${message.length}).`
9621
+ );
9622
+ return Reflect.apply(message, self, parameters)
9623
+ }
9624
+
9625
+ const regex = /%[dfijoOs]/g;
9626
+ let expectedLength = 0;
9627
+ while (regex.exec(message) !== null) expectedLength++;
9628
+ assert(
9629
+ expectedLength === parameters.length,
9630
+ `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
9631
+ `match the required ones (${expectedLength}).`
9632
+ );
9633
+ if (parameters.length === 0) return message
9634
+
9635
+ parameters.unshift(message);
9636
+ return Reflect.apply(format$2, null, parameters)
9637
+ }
9638
+
9639
+ /**
9640
+ * Determine the specific type of a value for type-mismatch errors.
9641
+ * @param {unknown} value
9642
+ * @returns {string}
9643
+ */
9644
+ function determineSpecificType(value) {
9645
+ if (value === null || value === undefined) {
9646
+ return String(value)
9647
+ }
9648
+
9649
+ if (typeof value === 'function' && value.name) {
9650
+ return `function ${value.name}`
9651
+ }
9652
+
9653
+ if (typeof value === 'object') {
9654
+ if (value.constructor && value.constructor.name) {
9655
+ return `an instance of ${value.constructor.name}`
9656
+ }
9657
+
9658
+ return `${inspect(value, {depth: -1})}`
9659
+ }
9660
+
9661
+ let inspected = inspect(value, {colors: false});
9662
+
9663
+ if (inspected.length > 28) {
9664
+ inspected = `${inspected.slice(0, 25)}...`;
9665
+ }
9666
+
9667
+ return `type ${typeof value} (${inspected})`
9668
+ }
9669
+
9670
+ // Manually “tree shaken” from:
9671
+ // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/package_json_reader.js>
9672
+ // Last checked on: Apr 29, 2023.
9673
+ // Removed the native dependency.
9674
+ // Also: no need to cache, we do that in resolve already.
9675
+
9676
+
9677
+ const hasOwnProperty$1 = {}.hasOwnProperty;
9678
+
9679
+ const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes;
9680
+
9681
+ /** @type {Map<string, PackageConfig>} */
9682
+ const cache = new Map();
9683
+
9684
+ /**
9685
+ * @param {string} jsonPath
9686
+ * @param {{specifier: URL | string, base?: URL}} options
9687
+ * @returns {PackageConfig}
9688
+ */
9689
+ function read(jsonPath, {base, specifier}) {
9690
+ const existing = cache.get(jsonPath);
9691
+
9692
+ if (existing) {
9693
+ return existing
9694
+ }
9695
+
9696
+ /** @type {string | undefined} */
9697
+ let string;
9698
+
9699
+ try {
9700
+ string = fs$8.readFileSync(path$8.toNamespacedPath(jsonPath), 'utf8');
9701
+ } catch (error) {
9702
+ const exception = /** @type {ErrnoException} */ (error);
9703
+
9704
+ if (exception.code !== 'ENOENT') {
9705
+ throw exception
9706
+ }
9707
+ }
9708
+
9709
+ /** @type {PackageConfig} */
9710
+ const result = {
9711
+ exists: false,
9712
+ pjsonPath: jsonPath,
9713
+ main: undefined,
9714
+ name: undefined,
9715
+ type: 'none', // Ignore unknown types for forwards compatibility
9716
+ exports: undefined,
9717
+ imports: undefined
9718
+ };
9719
+
9720
+ if (string !== undefined) {
9721
+ /** @type {Record<string, unknown>} */
9722
+ let parsed;
9723
+
9724
+ try {
9725
+ parsed = JSON.parse(string);
9726
+ } catch (error_) {
9727
+ const cause = /** @type {ErrnoException} */ (error_);
9728
+ const error = new ERR_INVALID_PACKAGE_CONFIG$1(
9729
+ jsonPath,
9730
+ (base ? `"${specifier}" from ` : '') + fileURLToPath$1(base || specifier),
9731
+ cause.message
9732
+ );
9733
+ error.cause = cause;
9734
+ throw error
9735
+ }
9736
+
9737
+ result.exists = true;
9738
+
9739
+ if (
9740
+ hasOwnProperty$1.call(parsed, 'name') &&
9741
+ typeof parsed.name === 'string'
9742
+ ) {
9743
+ result.name = parsed.name;
9744
+ }
9745
+
9746
+ if (
9747
+ hasOwnProperty$1.call(parsed, 'main') &&
9748
+ typeof parsed.main === 'string'
9749
+ ) {
9750
+ result.main = parsed.main;
9751
+ }
9752
+
9753
+ if (hasOwnProperty$1.call(parsed, 'exports')) {
9754
+ // @ts-expect-error: assume valid.
9755
+ result.exports = parsed.exports;
9756
+ }
9757
+
9758
+ if (hasOwnProperty$1.call(parsed, 'imports')) {
9759
+ // @ts-expect-error: assume valid.
9760
+ result.imports = parsed.imports;
9761
+ }
9762
+
9763
+ // Ignore unknown types for forwards compatibility
9764
+ if (
9765
+ hasOwnProperty$1.call(parsed, 'type') &&
9766
+ (parsed.type === 'commonjs' || parsed.type === 'module')
9767
+ ) {
9768
+ result.type = parsed.type;
9769
+ }
9770
+ }
9771
+
9772
+ cache.set(jsonPath, result);
9773
+
9774
+ return result
9775
+ }
9776
+
9777
+ /**
9778
+ * @param {URL | string} resolved
9779
+ * @returns {PackageConfig}
9780
+ */
9781
+ function getPackageScopeConfig(resolved) {
9782
+ // Note: in Node, this is now a native module.
9783
+ let packageJSONUrl = new URL('package.json', resolved);
9784
+
9785
+ while (true) {
9786
+ const packageJSONPath = packageJSONUrl.pathname;
9787
+ if (packageJSONPath.endsWith('node_modules/package.json')) {
9788
+ break
9789
+ }
9790
+
9791
+ const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
9792
+ specifier: resolved
9793
+ });
9794
+
9795
+ if (packageConfig.exists) {
9796
+ return packageConfig
9797
+ }
9798
+
9799
+ const lastPackageJSONUrl = packageJSONUrl;
9800
+ packageJSONUrl = new URL('../package.json', packageJSONUrl);
9801
+
9802
+ // Terminates at root where ../package.json equals ../../package.json
9803
+ // (can't just check "/package.json" for Windows support).
9804
+ if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
9805
+ break
9806
+ }
9807
+ }
9808
+
9809
+ const packageJSONPath = fileURLToPath$1(packageJSONUrl);
9810
+ // ^^ Note: in Node, this is now a native module.
9811
+
9812
+ return {
9813
+ pjsonPath: packageJSONPath,
9814
+ exists: false,
9815
+ type: 'none'
9816
+ }
9817
+ }
9818
+
9819
+ /**
9820
+ * Returns the package type for a given URL.
9821
+ * @param {URL} url - The URL to get the package type for.
9822
+ * @returns {PackageType}
9823
+ */
9824
+ function getPackageType(url) {
9825
+ // To do @anonrig: Write a C++ function that returns only "type".
9826
+ return getPackageScopeConfig(url).type
9827
+ }
9828
+
9829
+ // Manually “tree shaken” from:
9830
+ // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/esm/get_format.js>
9831
+ // Last checked on: Apr 29, 2023.
9832
+
9833
+
9834
+ const {ERR_UNKNOWN_FILE_EXTENSION} = codes;
9835
+
9836
+ const hasOwnProperty = {}.hasOwnProperty;
9837
+
9838
+ /** @type {Record<string, string>} */
9839
+ const extensionFormatMap = {
9840
+ // @ts-expect-error: hush.
9841
+ __proto__: null,
9842
+ '.cjs': 'commonjs',
9843
+ '.js': 'module',
9844
+ '.json': 'json',
9845
+ '.mjs': 'module'
9846
+ };
9847
+
9848
+ /**
9849
+ * @param {string | null} mime
9850
+ * @returns {string | null}
9851
+ */
9852
+ function mimeToFormat(mime) {
9853
+ if (
9854
+ mime &&
9855
+ /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)
9856
+ )
9857
+ return 'module'
9858
+ if (mime === 'application/json') return 'json'
9859
+ return null
9860
+ }
9861
+
9862
+ /**
9863
+ * @callback ProtocolHandler
9864
+ * @param {URL} parsed
9865
+ * @param {{parentURL: string, source?: Buffer}} context
9866
+ * @param {boolean} ignoreErrors
9867
+ * @returns {string | null | void}
9868
+ */
9869
+
9870
+ /**
9871
+ * @type {Record<string, ProtocolHandler>}
9872
+ */
9873
+ const protocolHandlers = {
9874
+ // @ts-expect-error: hush.
9875
+ __proto__: null,
9876
+ 'data:': getDataProtocolModuleFormat,
9877
+ 'file:': getFileProtocolModuleFormat,
9878
+ 'http:': getHttpProtocolModuleFormat,
9879
+ 'https:': getHttpProtocolModuleFormat,
9880
+ 'node:'() {
9881
+ return 'builtin'
9882
+ }
9883
+ };
9884
+
9885
+ /**
9886
+ * @param {URL} parsed
9887
+ */
9888
+ function getDataProtocolModuleFormat(parsed) {
9889
+ const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
9890
+ parsed.pathname
9891
+ ) || [null, null, null];
9892
+ return mimeToFormat(mime)
9893
+ }
9894
+
9895
+ /**
9896
+ * Returns the file extension from a URL.
9897
+ *
9898
+ * Should give similar result to
9899
+ * `require('node:path').extname(require('node:url').fileURLToPath(url))`
9900
+ * when used with a `file:` URL.
9901
+ *
9902
+ * @param {URL} url
9903
+ * @returns {string}
9904
+ */
9905
+ function extname(url) {
9906
+ const pathname = url.pathname;
9907
+ let index = pathname.length;
9908
+
9909
+ while (index--) {
9910
+ const code = pathname.codePointAt(index);
9911
+
9912
+ if (code === 47 /* `/` */) {
9913
+ return ''
9914
+ }
9915
+
9916
+ if (code === 46 /* `.` */) {
9917
+ return pathname.codePointAt(index - 1) === 47 /* `/` */
9918
+ ? ''
9919
+ : pathname.slice(index)
9920
+ }
9921
+ }
9922
+
9923
+ return ''
9924
+ }
9925
+
9926
+ /**
9927
+ * @type {ProtocolHandler}
9928
+ */
9929
+ function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
9930
+ const value = extname(url);
9931
+
9932
+ if (value === '.js') {
9933
+ const packageType = getPackageType(url);
9934
+
9935
+ if (packageType !== 'none') {
9936
+ return packageType
9937
+ }
9938
+
9939
+ return 'commonjs'
9940
+ }
9941
+
9942
+ if (value === '') {
9943
+ const packageType = getPackageType(url);
9944
+
9945
+ // Legacy behavior
9946
+ if (packageType === 'none' || packageType === 'commonjs') {
9947
+ return 'commonjs'
9948
+ }
9949
+
9950
+ // Note: we don’t implement WASM, so we don’t need
9951
+ // `getFormatOfExtensionlessFile` from `formats`.
9952
+ return 'module'
9953
+ }
9954
+
9955
+ const format = extensionFormatMap[value];
9956
+ if (format) return format
9957
+
9958
+ // Explicit undefined return indicates load hook should rerun format check
9959
+ if (ignoreErrors) {
9960
+ return undefined
9961
+ }
9962
+
9963
+ const filepath = fileURLToPath$1(url);
9964
+ throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath)
9965
+ }
9966
+
9967
+ function getHttpProtocolModuleFormat() {
9968
+ // To do: HTTPS imports.
9969
+ }
9970
+
9971
+ /**
9972
+ * @param {URL} url
9973
+ * @param {{parentURL: string}} context
9974
+ * @returns {string | null}
9975
+ */
9976
+ function defaultGetFormatWithoutErrors(url, context) {
9977
+ const protocol = url.protocol;
9978
+
9979
+ if (!hasOwnProperty.call(protocolHandlers, protocol)) {
9980
+ return null
9981
+ }
9982
+
9983
+ return protocolHandlers[protocol](url, context, true) || null
9984
+ }
9985
+
9986
+ // Manually “tree shaken” from:
9987
+ // <https://github.com/nodejs/node/blob/81a9a97/lib/internal/modules/esm/resolve.js>
9988
+ // Last checked on: Apr 29, 2023.
9989
+
9990
+
9991
+ const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
9992
+
9993
+ const {
9994
+ ERR_NETWORK_IMPORT_DISALLOWED,
9995
+ ERR_INVALID_MODULE_SPECIFIER,
9996
+ ERR_INVALID_PACKAGE_CONFIG,
9997
+ ERR_INVALID_PACKAGE_TARGET,
9998
+ ERR_MODULE_NOT_FOUND,
9999
+ ERR_PACKAGE_IMPORT_NOT_DEFINED,
10000
+ ERR_PACKAGE_PATH_NOT_EXPORTED,
10001
+ ERR_UNSUPPORTED_DIR_IMPORT,
10002
+ ERR_UNSUPPORTED_RESOLVE_REQUEST
10003
+ } = codes;
10004
+
10005
+ const own = {}.hasOwnProperty;
10006
+
10007
+ const invalidSegmentRegEx =
10008
+ /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
10009
+ const deprecatedInvalidSegmentRegEx =
10010
+ /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
10011
+ const invalidPackageNameRegEx = /^\.|%|\\/;
10012
+ const patternRegEx = /\*/g;
10013
+ const encodedSeparatorRegEx = /%2f|%5c/i;
10014
+ /** @type {Set<string>} */
10015
+ const emittedPackageWarnings = new Set();
10016
+
10017
+ const doubleSlashRegEx = /[/\\]{2}/;
10018
+
10019
+ /**
10020
+ *
10021
+ * @param {string} target
10022
+ * @param {string} request
10023
+ * @param {string} match
10024
+ * @param {URL} packageJsonUrl
10025
+ * @param {boolean} internal
10026
+ * @param {URL} base
10027
+ * @param {boolean} isTarget
10028
+ */
10029
+ function emitInvalidSegmentDeprecation(
10030
+ target,
10031
+ request,
10032
+ match,
10033
+ packageJsonUrl,
10034
+ internal,
10035
+ base,
10036
+ isTarget
10037
+ ) {
10038
+ // @ts-expect-error: apparently it does exist, TS.
10039
+ if (process$1.noDeprecation) {
10040
+ return
10041
+ }
10042
+
10043
+ const pjsonPath = fileURLToPath$1(packageJsonUrl);
10044
+ const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
10045
+ process$1.emitWarning(
10046
+ `Use of deprecated ${
10047
+ double ? 'double slash' : 'leading or trailing slash matching'
10048
+ } resolving "${target}" for module ` +
10049
+ `request "${request}" ${
10050
+ request === match ? '' : `matched to "${match}" `
10051
+ }in the "${
10052
+ internal ? 'imports' : 'exports'
10053
+ }" field module resolution of the package at ${pjsonPath}${
10054
+ base ? ` imported from ${fileURLToPath$1(base)}` : ''
10055
+ }.`,
10056
+ 'DeprecationWarning',
10057
+ 'DEP0166'
10058
+ );
10059
+ }
10060
+
10061
+ /**
10062
+ * @param {URL} url
10063
+ * @param {URL} packageJsonUrl
10064
+ * @param {URL} base
10065
+ * @param {string} [main]
10066
+ * @returns {void}
10067
+ */
10068
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
10069
+ // @ts-expect-error: apparently it does exist, TS.
10070
+ if (process$1.noDeprecation) {
10071
+ return
10072
+ }
10073
+
10074
+ const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});
10075
+ if (format !== 'module') return
10076
+ const urlPath = fileURLToPath$1(url.href);
10077
+ const packagePath = fileURLToPath$1(new URL$2('.', packageJsonUrl));
10078
+ const basePath = fileURLToPath$1(base);
10079
+ if (!main) {
10080
+ process$1.emitWarning(
10081
+ `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
10082
+ packagePath.length
10083
+ )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
10084
+ 'DeprecationWarning',
10085
+ 'DEP0151'
10086
+ );
10087
+ } else if (path$8.resolve(packagePath, main) !== urlPath) {
10088
+ process$1.emitWarning(
10089
+ `Package ${packagePath} has a "main" field set to "${main}", ` +
10090
+ `excluding the full filename and extension to the resolved file at "${urlPath.slice(
10091
+ packagePath.length
10092
+ )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` +
10093
+ 'deprecated for ES modules.',
10094
+ 'DeprecationWarning',
10095
+ 'DEP0151'
10096
+ );
10097
+ }
10098
+ }
10099
+
10100
+ /**
10101
+ * @param {string} path
10102
+ * @returns {Stats | undefined}
10103
+ */
10104
+ function tryStatSync(path) {
10105
+ // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
10106
+ try {
10107
+ return statSync$1(path)
10108
+ } catch {
10109
+ // Note: in Node code this returns `new Stats`,
10110
+ // but in Node 22 that’s marked as a deprecated internal API.
10111
+ // Which, well, we kinda are, but still to prevent that warning,
10112
+ // just yield `undefined`.
10113
+ }
10114
+ }
10115
+
10116
+ /**
10117
+ * Legacy CommonJS main resolution:
10118
+ * 1. let M = pkg_url + (json main field)
10119
+ * 2. TRY(M, M.js, M.json, M.node)
10120
+ * 3. TRY(M/index.js, M/index.json, M/index.node)
10121
+ * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
10122
+ * 5. NOT_FOUND
10123
+ *
10124
+ * @param {URL} url
10125
+ * @returns {boolean}
10126
+ */
10127
+ function fileExists(url) {
10128
+ const stats = statSync$1(url, {throwIfNoEntry: false});
10129
+ const isFile = stats ? stats.isFile() : undefined;
10130
+ return isFile === null || isFile === undefined ? false : isFile
10131
+ }
10132
+
10133
+ /**
10134
+ * @param {URL} packageJsonUrl
10135
+ * @param {PackageConfig} packageConfig
10136
+ * @param {URL} base
10137
+ * @returns {URL}
10138
+ */
10139
+ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
10140
+ /** @type {URL | undefined} */
10141
+ let guess;
10142
+ if (packageConfig.main !== undefined) {
10143
+ guess = new URL$2(packageConfig.main, packageJsonUrl);
10144
+ // Note: fs check redundances will be handled by Descriptor cache here.
10145
+ if (fileExists(guess)) return guess
10146
+
10147
+ const tries = [
10148
+ `./${packageConfig.main}.js`,
10149
+ `./${packageConfig.main}.json`,
10150
+ `./${packageConfig.main}.node`,
10151
+ `./${packageConfig.main}/index.js`,
10152
+ `./${packageConfig.main}/index.json`,
10153
+ `./${packageConfig.main}/index.node`
10154
+ ];
10155
+ let i = -1;
10156
+
10157
+ while (++i < tries.length) {
10158
+ guess = new URL$2(tries[i], packageJsonUrl);
10159
+ if (fileExists(guess)) break
10160
+ guess = undefined;
10161
+ }
10162
+
10163
+ if (guess) {
10164
+ emitLegacyIndexDeprecation(
10165
+ guess,
10166
+ packageJsonUrl,
10167
+ base,
10168
+ packageConfig.main
10169
+ );
10170
+ return guess
10171
+ }
10172
+ // Fallthrough.
10173
+ }
10174
+
10175
+ const tries = ['./index.js', './index.json', './index.node'];
10176
+ let i = -1;
10177
+
10178
+ while (++i < tries.length) {
10179
+ guess = new URL$2(tries[i], packageJsonUrl);
10180
+ if (fileExists(guess)) break
10181
+ guess = undefined;
10182
+ }
10183
+
10184
+ if (guess) {
10185
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
10186
+ return guess
10187
+ }
10188
+
10189
+ // Not found.
10190
+ throw new ERR_MODULE_NOT_FOUND(
10191
+ fileURLToPath$1(new URL$2('.', packageJsonUrl)),
10192
+ fileURLToPath$1(base)
10193
+ )
10194
+ }
10195
+
10196
+ /**
10197
+ * @param {URL} resolved
10198
+ * @param {URL} base
10199
+ * @param {boolean} [preserveSymlinks]
10200
+ * @returns {URL}
10201
+ */
10202
+ function finalizeResolution(resolved, base, preserveSymlinks) {
10203
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
10204
+ throw new ERR_INVALID_MODULE_SPECIFIER(
10205
+ resolved.pathname,
10206
+ 'must not include encoded "/" or "\\" characters',
10207
+ fileURLToPath$1(base)
10208
+ )
10209
+ }
10210
+
10211
+ /** @type {string} */
10212
+ let filePath;
10213
+
10214
+ try {
10215
+ filePath = fileURLToPath$1(resolved);
10216
+ } catch (error) {
10217
+ const cause = /** @type {ErrnoException} */ (error);
10218
+ Object.defineProperty(cause, 'input', {value: String(resolved)});
10219
+ Object.defineProperty(cause, 'module', {value: String(base)});
10220
+ throw cause
10221
+ }
10222
+
10223
+ const stats = tryStatSync(
10224
+ filePath.endsWith('/') ? filePath.slice(-1) : filePath
10225
+ );
10226
+
10227
+ if (stats && stats.isDirectory()) {
10228
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
10229
+ // @ts-expect-error Add this for `import.meta.resolve`.
10230
+ error.url = String(resolved);
10231
+ throw error
10232
+ }
10233
+
10234
+ if (!stats || !stats.isFile()) {
10235
+ const error = new ERR_MODULE_NOT_FOUND(
10236
+ filePath || resolved.pathname,
10237
+ base && fileURLToPath$1(base),
10238
+ true
10239
+ );
10240
+ // @ts-expect-error Add this for `import.meta.resolve`.
10241
+ error.url = String(resolved);
10242
+ throw error
10243
+ }
10244
+
10245
+ {
10246
+ const real = realpathSync(filePath);
10247
+ const {search, hash} = resolved;
10248
+ resolved = pathToFileURL$1(real + (filePath.endsWith(path$8.sep) ? '/' : ''));
10249
+ resolved.search = search;
10250
+ resolved.hash = hash;
10251
+ }
10252
+
10253
+ return resolved
10254
+ }
10255
+
10256
+ /**
10257
+ * @param {string} specifier
10258
+ * @param {URL | undefined} packageJsonUrl
10259
+ * @param {URL} base
10260
+ * @returns {Error}
10261
+ */
10262
+ function importNotDefined(specifier, packageJsonUrl, base) {
10263
+ return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
10264
+ specifier,
10265
+ packageJsonUrl && fileURLToPath$1(new URL$2('.', packageJsonUrl)),
10266
+ fileURLToPath$1(base)
10267
+ )
10268
+ }
10269
+
10270
+ /**
10271
+ * @param {string} subpath
10272
+ * @param {URL} packageJsonUrl
10273
+ * @param {URL} base
10274
+ * @returns {Error}
10275
+ */
10276
+ function exportsNotFound(subpath, packageJsonUrl, base) {
10277
+ return new ERR_PACKAGE_PATH_NOT_EXPORTED(
10278
+ fileURLToPath$1(new URL$2('.', packageJsonUrl)),
10279
+ subpath,
10280
+ base && fileURLToPath$1(base)
10281
+ )
10282
+ }
10283
+
10284
+ /**
10285
+ * @param {string} request
10286
+ * @param {string} match
10287
+ * @param {URL} packageJsonUrl
10288
+ * @param {boolean} internal
10289
+ * @param {URL} [base]
10290
+ * @returns {never}
10291
+ */
10292
+ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
10293
+ const reason = `request is not a valid match in pattern "${match}" for the "${
10294
+ internal ? 'imports' : 'exports'
10295
+ }" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
10296
+ throw new ERR_INVALID_MODULE_SPECIFIER(
10297
+ request,
10298
+ reason,
10299
+ base && fileURLToPath$1(base)
10300
+ )
10301
+ }
10302
+
10303
+ /**
10304
+ * @param {string} subpath
10305
+ * @param {unknown} target
10306
+ * @param {URL} packageJsonUrl
10307
+ * @param {boolean} internal
10308
+ * @param {URL} [base]
10309
+ * @returns {Error}
10310
+ */
10311
+ function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
10312
+ target =
10313
+ typeof target === 'object' && target !== null
10314
+ ? JSON.stringify(target, null, '')
10315
+ : `${target}`;
10316
+
10317
+ return new ERR_INVALID_PACKAGE_TARGET(
10318
+ fileURLToPath$1(new URL$2('.', packageJsonUrl)),
10319
+ subpath,
10320
+ target,
10321
+ internal,
10322
+ base && fileURLToPath$1(base)
10323
+ )
10324
+ }
10325
+
10326
+ /**
10327
+ * @param {string} target
10328
+ * @param {string} subpath
10329
+ * @param {string} match
10330
+ * @param {URL} packageJsonUrl
10331
+ * @param {URL} base
10332
+ * @param {boolean} pattern
10333
+ * @param {boolean} internal
10334
+ * @param {boolean} isPathMap
10335
+ * @param {Set<string> | undefined} conditions
10336
+ * @returns {URL}
10337
+ */
10338
+ function resolvePackageTargetString(
10339
+ target,
10340
+ subpath,
10341
+ match,
10342
+ packageJsonUrl,
10343
+ base,
10344
+ pattern,
10345
+ internal,
10346
+ isPathMap,
10347
+ conditions
10348
+ ) {
10349
+ if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
10350
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
10351
+
10352
+ if (!target.startsWith('./')) {
10353
+ if (internal && !target.startsWith('../') && !target.startsWith('/')) {
10354
+ let isURL = false;
10355
+
10356
+ try {
10357
+ new URL$2(target);
10358
+ isURL = true;
10359
+ } catch {
10360
+ // Continue regardless of error.
10361
+ }
10362
+
10363
+ if (!isURL) {
10364
+ const exportTarget = pattern
10365
+ ? RegExpPrototypeSymbolReplace.call(
10366
+ patternRegEx,
10367
+ target,
10368
+ () => subpath
10369
+ )
10370
+ : target + subpath;
10371
+
10372
+ return packageResolve(exportTarget, packageJsonUrl, conditions)
10373
+ }
10374
+ }
10375
+
10376
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
10377
+ }
10378
+
10379
+ if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
10380
+ if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
10381
+ if (!isPathMap) {
10382
+ const request = pattern
10383
+ ? match.replace('*', () => subpath)
10384
+ : match + subpath;
10385
+ const resolvedTarget = pattern
10386
+ ? RegExpPrototypeSymbolReplace.call(
10387
+ patternRegEx,
10388
+ target,
10389
+ () => subpath
10390
+ )
10391
+ : target;
10392
+ emitInvalidSegmentDeprecation(
10393
+ resolvedTarget,
10394
+ request,
10395
+ match,
10396
+ packageJsonUrl,
10397
+ internal,
10398
+ base,
10399
+ true
10400
+ );
10401
+ }
10402
+ } else {
10403
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
10404
+ }
10405
+ }
10406
+
10407
+ const resolved = new URL$2(target, packageJsonUrl);
10408
+ const resolvedPath = resolved.pathname;
10409
+ const packagePath = new URL$2('.', packageJsonUrl).pathname;
10410
+
10411
+ if (!resolvedPath.startsWith(packagePath))
10412
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
10413
+
10414
+ if (subpath === '') return resolved
10415
+
10416
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
10417
+ const request = pattern
10418
+ ? match.replace('*', () => subpath)
10419
+ : match + subpath;
10420
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
10421
+ if (!isPathMap) {
10422
+ const resolvedTarget = pattern
10423
+ ? RegExpPrototypeSymbolReplace.call(
10424
+ patternRegEx,
10425
+ target,
10426
+ () => subpath
10427
+ )
10428
+ : target;
10429
+ emitInvalidSegmentDeprecation(
10430
+ resolvedTarget,
10431
+ request,
10432
+ match,
10433
+ packageJsonUrl,
10434
+ internal,
10435
+ base,
10436
+ false
10437
+ );
10438
+ }
10439
+ } else {
10440
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
10441
+ }
10442
+ }
10443
+
10444
+ if (pattern) {
10445
+ return new URL$2(
10446
+ RegExpPrototypeSymbolReplace.call(
10447
+ patternRegEx,
10448
+ resolved.href,
10449
+ () => subpath
10450
+ )
10451
+ )
10452
+ }
10453
+
10454
+ return new URL$2(subpath, resolved)
10455
+ }
10456
+
10457
+ /**
10458
+ * @param {string} key
10459
+ * @returns {boolean}
10460
+ */
10461
+ function isArrayIndex(key) {
10462
+ const keyNumber = Number(key);
10463
+ if (`${keyNumber}` !== key) return false
10464
+ return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff
10465
+ }
10466
+
10467
+ /**
10468
+ * @param {URL} packageJsonUrl
10469
+ * @param {unknown} target
10470
+ * @param {string} subpath
10471
+ * @param {string} packageSubpath
10472
+ * @param {URL} base
10473
+ * @param {boolean} pattern
10474
+ * @param {boolean} internal
10475
+ * @param {boolean} isPathMap
10476
+ * @param {Set<string> | undefined} conditions
10477
+ * @returns {URL | null}
10478
+ */
10479
+ function resolvePackageTarget(
10480
+ packageJsonUrl,
10481
+ target,
10482
+ subpath,
10483
+ packageSubpath,
10484
+ base,
10485
+ pattern,
10486
+ internal,
10487
+ isPathMap,
10488
+ conditions
10489
+ ) {
10490
+ if (typeof target === 'string') {
10491
+ return resolvePackageTargetString(
10492
+ target,
10493
+ subpath,
10494
+ packageSubpath,
10495
+ packageJsonUrl,
10496
+ base,
10497
+ pattern,
10498
+ internal,
10499
+ isPathMap,
10500
+ conditions
10501
+ )
10502
+ }
10503
+
10504
+ if (Array.isArray(target)) {
10505
+ /** @type {Array<unknown>} */
10506
+ const targetList = target;
10507
+ if (targetList.length === 0) return null
10508
+
10509
+ /** @type {ErrnoException | null | undefined} */
10510
+ let lastException;
10511
+ let i = -1;
10512
+
10513
+ while (++i < targetList.length) {
10514
+ const targetItem = targetList[i];
10515
+ /** @type {URL | null} */
10516
+ let resolveResult;
10517
+ try {
10518
+ resolveResult = resolvePackageTarget(
10519
+ packageJsonUrl,
10520
+ targetItem,
10521
+ subpath,
10522
+ packageSubpath,
10523
+ base,
10524
+ pattern,
10525
+ internal,
10526
+ isPathMap,
10527
+ conditions
10528
+ );
10529
+ } catch (error) {
10530
+ const exception = /** @type {ErrnoException} */ (error);
10531
+ lastException = exception;
10532
+ if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue
10533
+ throw error
10534
+ }
10535
+
10536
+ if (resolveResult === undefined) continue
10537
+
10538
+ if (resolveResult === null) {
10539
+ lastException = null;
10540
+ continue
10541
+ }
10542
+
10543
+ return resolveResult
10544
+ }
10545
+
10546
+ if (lastException === undefined || lastException === null) {
10547
+ return null
10548
+ }
10549
+
10550
+ throw lastException
10551
+ }
10552
+
10553
+ if (typeof target === 'object' && target !== null) {
10554
+ const keys = Object.getOwnPropertyNames(target);
10555
+ let i = -1;
10556
+
10557
+ while (++i < keys.length) {
10558
+ const key = keys[i];
10559
+ if (isArrayIndex(key)) {
10560
+ throw new ERR_INVALID_PACKAGE_CONFIG(
10561
+ fileURLToPath$1(packageJsonUrl),
10562
+ base,
10563
+ '"exports" cannot contain numeric property keys.'
10564
+ )
10565
+ }
10566
+ }
10567
+
10568
+ i = -1;
10569
+
10570
+ while (++i < keys.length) {
10571
+ const key = keys[i];
10572
+ if (key === 'default' || (conditions && conditions.has(key))) {
10573
+ // @ts-expect-error: indexable.
10574
+ const conditionalTarget = /** @type {unknown} */ (target[key]);
10575
+ const resolveResult = resolvePackageTarget(
10576
+ packageJsonUrl,
10577
+ conditionalTarget,
10578
+ subpath,
10579
+ packageSubpath,
10580
+ base,
10581
+ pattern,
10582
+ internal,
10583
+ isPathMap,
10584
+ conditions
10585
+ );
10586
+ if (resolveResult === undefined) continue
10587
+ return resolveResult
10588
+ }
10589
+ }
10590
+
10591
+ return null
10592
+ }
10593
+
10594
+ if (target === null) {
10595
+ return null
10596
+ }
10597
+
10598
+ throw invalidPackageTarget(
10599
+ packageSubpath,
10600
+ target,
10601
+ packageJsonUrl,
10602
+ internal,
10603
+ base
10604
+ )
10605
+ }
10606
+
10607
+ /**
10608
+ * @param {unknown} exports
10609
+ * @param {URL} packageJsonUrl
10610
+ * @param {URL} base
10611
+ * @returns {boolean}
10612
+ */
10613
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
10614
+ if (typeof exports === 'string' || Array.isArray(exports)) return true
10615
+ if (typeof exports !== 'object' || exports === null) return false
10616
+
10617
+ const keys = Object.getOwnPropertyNames(exports);
10618
+ let isConditionalSugar = false;
10619
+ let i = 0;
10620
+ let keyIndex = -1;
10621
+ while (++keyIndex < keys.length) {
10622
+ const key = keys[keyIndex];
10623
+ const currentIsConditionalSugar = key === '' || key[0] !== '.';
10624
+ if (i++ === 0) {
10625
+ isConditionalSugar = currentIsConditionalSugar;
10626
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
10627
+ throw new ERR_INVALID_PACKAGE_CONFIG(
10628
+ fileURLToPath$1(packageJsonUrl),
10629
+ base,
10630
+ '"exports" cannot contain some keys starting with \'.\' and some not.' +
10631
+ ' The exports object must either be an object of package subpath keys' +
10632
+ ' or an object of main entry condition name keys only.'
10633
+ )
10634
+ }
10635
+ }
10636
+
10637
+ return isConditionalSugar
10638
+ }
10639
+
10640
+ /**
10641
+ * @param {string} match
10642
+ * @param {URL} pjsonUrl
10643
+ * @param {URL} base
10644
+ */
10645
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
10646
+ // @ts-expect-error: apparently it does exist, TS.
10647
+ if (process$1.noDeprecation) {
10648
+ return
10649
+ }
10650
+
10651
+ const pjsonPath = fileURLToPath$1(pjsonUrl);
10652
+ if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
10653
+ emittedPackageWarnings.add(pjsonPath + '|' + match);
10654
+ process$1.emitWarning(
10655
+ `Use of deprecated trailing slash pattern mapping "${match}" in the ` +
10656
+ `"exports" field module resolution of the package at ${pjsonPath}${
10657
+ base ? ` imported from ${fileURLToPath$1(base)}` : ''
10658
+ }. Mapping specifiers ending in "/" is no longer supported.`,
10659
+ 'DeprecationWarning',
10660
+ 'DEP0155'
10661
+ );
10662
+ }
10663
+
10664
+ /**
10665
+ * @param {URL} packageJsonUrl
10666
+ * @param {string} packageSubpath
10667
+ * @param {Record<string, unknown>} packageConfig
10668
+ * @param {URL} base
10669
+ * @param {Set<string> | undefined} conditions
10670
+ * @returns {URL}
10671
+ */
10672
+ function packageExportsResolve(
10673
+ packageJsonUrl,
10674
+ packageSubpath,
10675
+ packageConfig,
10676
+ base,
10677
+ conditions
10678
+ ) {
10679
+ let exports = packageConfig.exports;
10680
+
10681
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
10682
+ exports = {'.': exports};
10683
+ }
10684
+
10685
+ if (
10686
+ own.call(exports, packageSubpath) &&
10687
+ !packageSubpath.includes('*') &&
10688
+ !packageSubpath.endsWith('/')
10689
+ ) {
10690
+ // @ts-expect-error: indexable.
10691
+ const target = exports[packageSubpath];
10692
+ const resolveResult = resolvePackageTarget(
10693
+ packageJsonUrl,
10694
+ target,
10695
+ '',
10696
+ packageSubpath,
10697
+ base,
10698
+ false,
10699
+ false,
10700
+ false,
10701
+ conditions
10702
+ );
10703
+ if (resolveResult === null || resolveResult === undefined) {
10704
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
10705
+ }
10706
+
10707
+ return resolveResult
10708
+ }
10709
+
10710
+ let bestMatch = '';
10711
+ let bestMatchSubpath = '';
10712
+ const keys = Object.getOwnPropertyNames(exports);
10713
+ let i = -1;
10714
+
10715
+ while (++i < keys.length) {
10716
+ const key = keys[i];
10717
+ const patternIndex = key.indexOf('*');
10718
+
10719
+ if (
10720
+ patternIndex !== -1 &&
10721
+ packageSubpath.startsWith(key.slice(0, patternIndex))
10722
+ ) {
10723
+ // When this reaches EOL, this can throw at the top of the whole function:
10724
+ //
10725
+ // if (StringPrototypeEndsWith(packageSubpath, '/'))
10726
+ // throwInvalidSubpath(packageSubpath)
10727
+ //
10728
+ // To match "imports" and the spec.
10729
+ if (packageSubpath.endsWith('/')) {
10730
+ emitTrailingSlashPatternDeprecation(
10731
+ packageSubpath,
10732
+ packageJsonUrl,
10733
+ base
10734
+ );
10735
+ }
10736
+
10737
+ const patternTrailer = key.slice(patternIndex + 1);
10738
+
10739
+ if (
10740
+ packageSubpath.length >= key.length &&
10741
+ packageSubpath.endsWith(patternTrailer) &&
10742
+ patternKeyCompare(bestMatch, key) === 1 &&
10743
+ key.lastIndexOf('*') === patternIndex
10744
+ ) {
10745
+ bestMatch = key;
10746
+ bestMatchSubpath = packageSubpath.slice(
10747
+ patternIndex,
10748
+ packageSubpath.length - patternTrailer.length
10749
+ );
10750
+ }
10751
+ }
10752
+ }
10753
+
10754
+ if (bestMatch) {
10755
+ // @ts-expect-error: indexable.
10756
+ const target = /** @type {unknown} */ (exports[bestMatch]);
10757
+ const resolveResult = resolvePackageTarget(
10758
+ packageJsonUrl,
10759
+ target,
10760
+ bestMatchSubpath,
10761
+ bestMatch,
10762
+ base,
10763
+ true,
10764
+ false,
10765
+ packageSubpath.endsWith('/'),
10766
+ conditions
10767
+ );
10768
+
10769
+ if (resolveResult === null || resolveResult === undefined) {
10770
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
10771
+ }
10772
+
10773
+ return resolveResult
10774
+ }
10775
+
10776
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
10777
+ }
10778
+
10779
+ /**
10780
+ * @param {string} a
10781
+ * @param {string} b
10782
+ */
10783
+ function patternKeyCompare(a, b) {
10784
+ const aPatternIndex = a.indexOf('*');
10785
+ const bPatternIndex = b.indexOf('*');
10786
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
10787
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
10788
+ if (baseLengthA > baseLengthB) return -1
10789
+ if (baseLengthB > baseLengthA) return 1
10790
+ if (aPatternIndex === -1) return 1
10791
+ if (bPatternIndex === -1) return -1
10792
+ if (a.length > b.length) return -1
10793
+ if (b.length > a.length) return 1
10794
+ return 0
10795
+ }
10796
+
10797
+ /**
10798
+ * @param {string} name
10799
+ * @param {URL} base
10800
+ * @param {Set<string>} [conditions]
10801
+ * @returns {URL}
10802
+ */
10803
+ function packageImportsResolve(name, base, conditions) {
10804
+ if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {
10805
+ const reason = 'is not a valid internal imports specifier name';
10806
+ throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base))
10807
+ }
10808
+
10809
+ /** @type {URL | undefined} */
10810
+ let packageJsonUrl;
10811
+
10812
+ const packageConfig = getPackageScopeConfig(base);
10813
+
10814
+ if (packageConfig.exists) {
10815
+ packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
10816
+ const imports = packageConfig.imports;
10817
+ if (imports) {
10818
+ if (own.call(imports, name) && !name.includes('*')) {
10819
+ const resolveResult = resolvePackageTarget(
10820
+ packageJsonUrl,
10821
+ imports[name],
10822
+ '',
10823
+ name,
10824
+ base,
10825
+ false,
10826
+ true,
10827
+ false,
10828
+ conditions
10829
+ );
10830
+ if (resolveResult !== null && resolveResult !== undefined) {
10831
+ return resolveResult
10832
+ }
10833
+ } else {
10834
+ let bestMatch = '';
10835
+ let bestMatchSubpath = '';
10836
+ const keys = Object.getOwnPropertyNames(imports);
10837
+ let i = -1;
10838
+
10839
+ while (++i < keys.length) {
10840
+ const key = keys[i];
10841
+ const patternIndex = key.indexOf('*');
10842
+
10843
+ if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
10844
+ const patternTrailer = key.slice(patternIndex + 1);
10845
+ if (
10846
+ name.length >= key.length &&
10847
+ name.endsWith(patternTrailer) &&
10848
+ patternKeyCompare(bestMatch, key) === 1 &&
10849
+ key.lastIndexOf('*') === patternIndex
10850
+ ) {
10851
+ bestMatch = key;
10852
+ bestMatchSubpath = name.slice(
10853
+ patternIndex,
10854
+ name.length - patternTrailer.length
10855
+ );
10856
+ }
10857
+ }
10858
+ }
10859
+
10860
+ if (bestMatch) {
10861
+ const target = imports[bestMatch];
10862
+ const resolveResult = resolvePackageTarget(
10863
+ packageJsonUrl,
10864
+ target,
10865
+ bestMatchSubpath,
10866
+ bestMatch,
10867
+ base,
10868
+ true,
10869
+ true,
10870
+ false,
10871
+ conditions
10872
+ );
10873
+
10874
+ if (resolveResult !== null && resolveResult !== undefined) {
10875
+ return resolveResult
10876
+ }
10877
+ }
10878
+ }
10879
+ }
10880
+ }
10881
+
10882
+ throw importNotDefined(name, packageJsonUrl, base)
10883
+ }
10884
+
10885
+ /**
10886
+ * @param {string} specifier
10887
+ * @param {URL} base
10888
+ */
10889
+ function parsePackageName(specifier, base) {
10890
+ let separatorIndex = specifier.indexOf('/');
10891
+ let validPackageName = true;
10892
+ let isScoped = false;
10893
+ if (specifier[0] === '@') {
10894
+ isScoped = true;
10895
+ if (separatorIndex === -1 || specifier.length === 0) {
10896
+ validPackageName = false;
10897
+ } else {
10898
+ separatorIndex = specifier.indexOf('/', separatorIndex + 1);
10899
+ }
10900
+ }
10901
+
10902
+ const packageName =
10903
+ separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
10904
+
10905
+ // Package name cannot have leading . and cannot have percent-encoding or
10906
+ // \\ separators.
10907
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
10908
+ validPackageName = false;
10909
+ }
10910
+
10911
+ if (!validPackageName) {
10912
+ throw new ERR_INVALID_MODULE_SPECIFIER(
10913
+ specifier,
10914
+ 'is not a valid package name',
10915
+ fileURLToPath$1(base)
10916
+ )
10917
+ }
10918
+
10919
+ const packageSubpath =
10920
+ '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
10921
+
10922
+ return {packageName, packageSubpath, isScoped}
10923
+ }
10924
+
10925
+ /**
10926
+ * @param {string} specifier
10927
+ * @param {URL} base
10928
+ * @param {Set<string> | undefined} conditions
10929
+ * @returns {URL}
10930
+ */
10931
+ function packageResolve(specifier, base, conditions) {
10932
+ if (builtinModules.includes(specifier)) {
10933
+ return new URL$2('node:' + specifier)
10934
+ }
10935
+
10936
+ const {packageName, packageSubpath, isScoped} = parsePackageName(
10937
+ specifier,
10938
+ base
10939
+ );
10940
+
10941
+ // ResolveSelf
10942
+ const packageConfig = getPackageScopeConfig(base);
10943
+
10944
+ // Can’t test.
10945
+ /* c8 ignore next 16 */
10946
+ if (packageConfig.exists) {
10947
+ const packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
10948
+ if (
10949
+ packageConfig.name === packageName &&
10950
+ packageConfig.exports !== undefined &&
10951
+ packageConfig.exports !== null
10952
+ ) {
10953
+ return packageExportsResolve(
10954
+ packageJsonUrl,
10955
+ packageSubpath,
10956
+ packageConfig,
10957
+ base,
10958
+ conditions
10959
+ )
10960
+ }
10961
+ }
10962
+
10963
+ let packageJsonUrl = new URL$2(
10964
+ './node_modules/' + packageName + '/package.json',
10965
+ base
10966
+ );
10967
+ let packageJsonPath = fileURLToPath$1(packageJsonUrl);
10968
+ /** @type {string} */
10969
+ let lastPath;
10970
+ do {
10971
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
10972
+ if (!stat || !stat.isDirectory()) {
10973
+ lastPath = packageJsonPath;
10974
+ packageJsonUrl = new URL$2(
10975
+ (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
10976
+ packageName +
10977
+ '/package.json',
10978
+ packageJsonUrl
10979
+ );
10980
+ packageJsonPath = fileURLToPath$1(packageJsonUrl);
10981
+ continue
10982
+ }
10983
+
10984
+ // Package match.
10985
+ const packageConfig = read(packageJsonPath, {base, specifier});
10986
+ if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
10987
+ return packageExportsResolve(
10988
+ packageJsonUrl,
10989
+ packageSubpath,
10990
+ packageConfig,
10991
+ base,
10992
+ conditions
10993
+ )
10994
+ }
10995
+
10996
+ if (packageSubpath === '.') {
10997
+ return legacyMainResolve(packageJsonUrl, packageConfig, base)
10998
+ }
10999
+
11000
+ return new URL$2(packageSubpath, packageJsonUrl)
11001
+ // Cross-platform root check.
11002
+ } while (packageJsonPath.length !== lastPath.length)
11003
+
11004
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false)
11005
+ }
11006
+
11007
+ /**
11008
+ * @param {string} specifier
11009
+ * @returns {boolean}
11010
+ */
11011
+ function isRelativeSpecifier(specifier) {
11012
+ if (specifier[0] === '.') {
11013
+ if (specifier.length === 1 || specifier[1] === '/') return true
11014
+ if (
11015
+ specifier[1] === '.' &&
11016
+ (specifier.length === 2 || specifier[2] === '/')
11017
+ ) {
11018
+ return true
11019
+ }
11020
+ }
11021
+
11022
+ return false
11023
+ }
11024
+
11025
+ /**
11026
+ * @param {string} specifier
11027
+ * @returns {boolean}
11028
+ */
11029
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
11030
+ if (specifier === '') return false
11031
+ if (specifier[0] === '/') return true
11032
+ return isRelativeSpecifier(specifier)
8913
11033
  }
8914
- class StateManager {
8915
- filesMap = /* @__PURE__ */ new Map();
8916
- pathsSet = /* @__PURE__ */ new Set();
8917
- idMap = /* @__PURE__ */ new Map();
8918
- taskFileMap = /* @__PURE__ */ new WeakMap();
8919
- errorsSet = /* @__PURE__ */ new Set();
8920
- processTimeoutCauses = /* @__PURE__ */ new Set();
8921
- catchError(err, type) {
8922
- if (isAggregateError(err))
8923
- return err.errors.forEach((error) => this.catchError(error, type));
8924
- if (err === Object(err))
8925
- err.type = type;
8926
- else
8927
- err = { type, message: err };
8928
- const _err = err;
8929
- if (_err && typeof _err === "object" && _err.code === "VITEST_PENDING") {
8930
- const task = this.idMap.get(_err.taskId);
8931
- if (task) {
8932
- task.mode = "skip";
8933
- task.result ?? (task.result = { state: "skip" });
8934
- task.result.state = "skip";
11034
+
11035
+ /**
11036
+ * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
11037
+ * sync and slightly lower-level than `resolve`).
11038
+ *
11039
+ * @param {string} specifier
11040
+ * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
11041
+ * @param {URL} base
11042
+ * Full URL (to a file) that `specifier` is resolved relative from.
11043
+ * @param {Set<string>} [conditions]
11044
+ * Conditions.
11045
+ * @param {boolean} [preserveSymlinks]
11046
+ * Keep symlinks instead of resolving them.
11047
+ * @returns {URL}
11048
+ * A URL object to the found thing.
11049
+ */
11050
+ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
11051
+ // Note: The Node code supports `base` as a string (in this internal API) too,
11052
+ // we don’t.
11053
+ const protocol = base.protocol;
11054
+ const isData = protocol === 'data:';
11055
+ const isRemote = isData || protocol === 'http:' || protocol === 'https:';
11056
+ // Order swapped from spec for minor perf gain.
11057
+ // Ok since relative URLs cannot parse as URLs.
11058
+ /** @type {URL | undefined} */
11059
+ let resolved;
11060
+
11061
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
11062
+ try {
11063
+ resolved = new URL$2(specifier, base);
11064
+ } catch (error_) {
11065
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
11066
+ error.cause = error_;
11067
+ throw error
11068
+ }
11069
+ } else if (protocol === 'file:' && specifier[0] === '#') {
11070
+ resolved = packageImportsResolve(specifier, base, conditions);
11071
+ } else {
11072
+ try {
11073
+ resolved = new URL$2(specifier);
11074
+ } catch (error_) {
11075
+ // Note: actual code uses `canBeRequiredWithoutScheme`.
11076
+ if (isRemote && !builtinModules.includes(specifier)) {
11077
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
11078
+ error.cause = error_;
11079
+ throw error
8935
11080
  }
8936
- return;
11081
+
11082
+ resolved = packageResolve(specifier, base, conditions);
8937
11083
  }
8938
- this.errorsSet.add(err);
8939
11084
  }
8940
- clearErrors() {
8941
- this.errorsSet.clear();
11085
+
11086
+ assert(resolved !== undefined, 'expected to be defined');
11087
+
11088
+ if (resolved.protocol !== 'file:') {
11089
+ return resolved
8942
11090
  }
8943
- getUnhandledErrors() {
8944
- return Array.from(this.errorsSet.values());
11091
+
11092
+ return finalizeResolution(resolved, base)
11093
+ }
11094
+
11095
+ function fileURLToPath(id) {
11096
+ if (typeof id === "string" && !id.startsWith("file://")) {
11097
+ return normalizeSlash(id);
8945
11098
  }
8946
- addProcessTimeoutCause(cause) {
8947
- this.processTimeoutCauses.add(cause);
11099
+ return normalizeSlash(fileURLToPath$1(id));
11100
+ }
11101
+ function pathToFileURL(id) {
11102
+ return pathToFileURL$1(fileURLToPath(id)).toString();
11103
+ }
11104
+ function normalizeid(id) {
11105
+ if (typeof id !== "string") {
11106
+ id = id.toString();
8948
11107
  }
8949
- getProcessTimeoutCauses() {
8950
- return Array.from(this.processTimeoutCauses.values());
11108
+ if (/(node|data|http|https|file):/.test(id)) {
11109
+ return id;
8951
11110
  }
8952
- getPaths() {
8953
- return Array.from(this.pathsSet);
11111
+ if (BUILTIN_MODULES.has(id)) {
11112
+ return "node:" + id;
8954
11113
  }
8955
- getFiles(keys) {
8956
- if (keys)
8957
- return keys.map((key) => this.filesMap.get(key)).filter(Boolean).flat();
8958
- return Array.from(this.filesMap.values()).flat();
11114
+ return "file://" + encodeURI(normalizeSlash(id));
11115
+ }
11116
+
11117
+ const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
11118
+ const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
11119
+ const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
11120
+ "ERR_MODULE_NOT_FOUND",
11121
+ "ERR_UNSUPPORTED_DIR_IMPORT",
11122
+ "MODULE_NOT_FOUND",
11123
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
11124
+ ]);
11125
+ function _tryModuleResolve(id, url, conditions) {
11126
+ try {
11127
+ return moduleResolve(id, url, conditions);
11128
+ } catch (error) {
11129
+ if (!NOT_FOUND_ERRORS.has(error?.code)) {
11130
+ throw error;
11131
+ }
8959
11132
  }
8960
- getFilepaths() {
8961
- return Array.from(this.filesMap.keys());
11133
+ }
11134
+ function _resolve$1(id, options = {}) {
11135
+ if (typeof id !== "string") {
11136
+ if (id instanceof URL) {
11137
+ id = fileURLToPath(id);
11138
+ } else {
11139
+ throw new TypeError("input must be a `string` or `URL`");
11140
+ }
8962
11141
  }
8963
- getFailedFilepaths() {
8964
- return this.getFiles().filter((i) => {
8965
- var _a;
8966
- return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
8967
- }).map((i) => i.filepath);
11142
+ if (/(node|data|http|https):/.test(id)) {
11143
+ return id;
8968
11144
  }
8969
- collectPaths(paths = []) {
8970
- paths.forEach((path) => {
8971
- this.pathsSet.add(path);
8972
- });
11145
+ if (BUILTIN_MODULES.has(id)) {
11146
+ return "node:" + id;
8973
11147
  }
8974
- collectFiles(files = []) {
8975
- files.forEach((file) => {
8976
- const existing = this.filesMap.get(file.filepath) || [];
8977
- const otherProject = existing.filter((i) => i.projectName !== file.projectName);
8978
- otherProject.push(file);
8979
- this.filesMap.set(file.filepath, otherProject);
8980
- this.updateId(file);
8981
- });
11148
+ if (id.startsWith("file://")) {
11149
+ id = fileURLToPath(id);
8982
11150
  }
8983
- // this file is reused by ws-client, and shoult not rely on heavy dependencies like workspace
8984
- clearFiles(_project, paths = []) {
8985
- const project = _project;
8986
- paths.forEach((path) => {
8987
- const files = this.filesMap.get(path);
8988
- if (!files)
8989
- return;
8990
- const filtered = files.filter((file) => file.projectName !== project.config.name);
8991
- if (!filtered.length)
8992
- this.filesMap.delete(path);
8993
- else
8994
- this.filesMap.set(path, filtered);
8995
- });
11151
+ if (isAbsolute(id)) {
11152
+ try {
11153
+ const stat = statSync$1(id);
11154
+ if (stat.isFile()) {
11155
+ return pathToFileURL(id);
11156
+ }
11157
+ } catch (error) {
11158
+ if (error?.code !== "ENOENT") {
11159
+ throw error;
11160
+ }
11161
+ }
8996
11162
  }
8997
- updateId(task) {
8998
- if (this.idMap.get(task.id) === task)
8999
- return;
9000
- this.idMap.set(task.id, task);
9001
- if (task.type === "suite") {
9002
- task.tasks.forEach((task2) => {
9003
- this.updateId(task2);
9004
- });
11163
+ const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
11164
+ const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
11165
+ if (_urls.length === 0) {
11166
+ _urls.push(new URL(pathToFileURL(process.cwd())));
11167
+ }
11168
+ const urls = [..._urls];
11169
+ for (const url of _urls) {
11170
+ if (url.protocol === "file:") {
11171
+ urls.push(
11172
+ new URL("./", url),
11173
+ // If url is directory
11174
+ new URL(joinURL(url.pathname, "_index.js"), url),
11175
+ // TODO: Remove in next major version?
11176
+ new URL("node_modules", url)
11177
+ );
9005
11178
  }
9006
11179
  }
9007
- updateTasks(packs) {
9008
- for (const [id, result, meta] of packs) {
9009
- const task = this.idMap.get(id);
9010
- if (task) {
9011
- task.result = result;
9012
- task.meta = meta;
9013
- if ((result == null ? void 0 : result.state) === "skip")
9014
- task.mode = "skip";
11180
+ let resolved;
11181
+ for (const url of urls) {
11182
+ resolved = _tryModuleResolve(id, url, conditionsSet);
11183
+ if (resolved) {
11184
+ break;
11185
+ }
11186
+ for (const prefix of ["", "/index"]) {
11187
+ for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
11188
+ resolved = _tryModuleResolve(
11189
+ id + prefix + extension,
11190
+ url,
11191
+ conditionsSet
11192
+ );
11193
+ if (resolved) {
11194
+ break;
11195
+ }
11196
+ }
11197
+ if (resolved) {
11198
+ break;
9015
11199
  }
9016
11200
  }
9017
- }
9018
- updateUserLog(log) {
9019
- const task = log.taskId && this.idMap.get(log.taskId);
9020
- if (task) {
9021
- if (!task.logs)
9022
- task.logs = [];
9023
- task.logs.push(log);
11201
+ if (resolved) {
11202
+ break;
9024
11203
  }
9025
11204
  }
9026
- getCountOfFailedTests() {
9027
- return Array.from(this.idMap.values()).filter((t) => {
9028
- var _a;
9029
- return ((_a = t.result) == null ? void 0 : _a.state) === "fail";
9030
- }).length;
11205
+ if (!resolved) {
11206
+ const error = new Error(
11207
+ `Cannot find module ${id} imported from ${urls.join(", ")}`
11208
+ );
11209
+ error.code = "ERR_MODULE_NOT_FOUND";
11210
+ throw error;
9031
11211
  }
9032
- cancelFiles(files, root, projectName) {
9033
- this.collectFiles(files.map((filepath) => ({
9034
- filepath,
9035
- name: relative(root, filepath),
9036
- id: filepath,
9037
- mode: "skip",
9038
- type: "suite",
9039
- result: {
9040
- state: "skip"
9041
- },
9042
- meta: {},
9043
- // Cancelled files have not yet collected tests
9044
- tasks: [],
9045
- projectName
9046
- })));
11212
+ return pathToFileURL(resolved);
11213
+ }
11214
+ function resolveSync(id, options) {
11215
+ return _resolve$1(id, options);
11216
+ }
11217
+ function resolvePathSync(id, options) {
11218
+ return fileURLToPath(resolveSync(id, options));
11219
+ }
11220
+
11221
+ function _resolve(path, options = {}) {
11222
+ if (options.platform === "auto" || !options.platform)
11223
+ options.platform = process$1.platform === "win32" ? "win32" : "posix";
11224
+ const modulePath = resolvePathSync(path, {
11225
+ url: options.paths
11226
+ });
11227
+ if (options.platform === "win32")
11228
+ return win32.normalize(modulePath);
11229
+ return modulePath;
11230
+ }
11231
+ function resolveModule(name, options = {}) {
11232
+ try {
11233
+ return _resolve(name, options);
11234
+ } catch (e) {
11235
+ return void 0;
11236
+ }
11237
+ }
11238
+ function isPackageExists(name, options = {}) {
11239
+ return !!resolvePackage(name, options);
11240
+ }
11241
+ function resolvePackage(name, options = {}) {
11242
+ try {
11243
+ return _resolve(`${name}/package.json`, options);
11244
+ } catch {
11245
+ }
11246
+ try {
11247
+ return _resolve(name, options);
11248
+ } catch (e) {
11249
+ if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND")
11250
+ console.error(e);
11251
+ return false;
9047
11252
  }
9048
11253
  }
9049
11254
 
@@ -9068,7 +11273,7 @@ const defaultCoverageExcludes = [
9068
11273
  "cypress/**",
9069
11274
  "test?(s)/**",
9070
11275
  "test?(-*).?(c|m)[jt]s?(x)",
9071
- "**/*{.,-}{test,spec}.?(c|m)[jt]s?(x)",
11276
+ "**/*{.,-}{test,spec}?(-d).?(c|m)[jt]s?(x)",
9072
11277
  "**/__tests__/**",
9073
11278
  "**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*",
9074
11279
  "**/vitest.{workspace,projects}.[jt]s?(on)",
@@ -9086,7 +11291,7 @@ const coverageConfigDefaults = {
9086
11291
  reporter: [["text", {}], ["html", {}], ["clover", {}], ["json", {}]],
9087
11292
  extension: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte", ".marko"],
9088
11293
  allowExternal: false,
9089
- ignoreEmptyLines: false,
11294
+ ignoreEmptyLines: true,
9090
11295
  processingConcurrency: Math.min(20, ((_b = (_a = nodeos__default).availableParallelism) == null ? void 0 : _b.call(_a)) ?? nodeos__default.cpus().length)
9091
11296
  };
9092
11297
  const fakeTimersDefaults = {
@@ -9117,7 +11322,6 @@ const config = {
9117
11322
  testTimeout: 5e3,
9118
11323
  hookTimeout: 1e4,
9119
11324
  teardownTimeout: 1e4,
9120
- watchExclude: ["**/node_modules/**", "**/dist/**"],
9121
11325
  forceRerunTriggers: [
9122
11326
  "**/package.json/**",
9123
11327
  "**/{vitest,vite}.config.*/**"
@@ -9177,8 +11381,11 @@ class ResultsCache {
9177
11381
  cache = /* @__PURE__ */ new Map();
9178
11382
  workspacesKeyMap = /* @__PURE__ */ new Map();
9179
11383
  cachePath = null;
9180
- version = version;
11384
+ version;
9181
11385
  root = "/";
11386
+ constructor(version) {
11387
+ this.version = version;
11388
+ }
9182
11389
  getCachePath() {
9183
11390
  return this.cachePath;
9184
11391
  }
@@ -9196,10 +11403,10 @@ class ResultsCache {
9196
11403
  if (!fs$8.existsSync(this.cachePath))
9197
11404
  return;
9198
11405
  const resultsCache = await fs$8.promises.readFile(this.cachePath, "utf8");
9199
- const { results, version: version2 } = JSON.parse(resultsCache || "[]");
9200
- if (Number(version2.split(".")[1]) >= 30) {
11406
+ const { results, version } = JSON.parse(resultsCache || "[]");
11407
+ if (Number(version.split(".")[1]) >= 30) {
9201
11408
  this.cache = new Map(results);
9202
- this.version = version2;
11409
+ this.version = version;
9203
11410
  results.forEach(([spec]) => {
9204
11411
  const [projectName, relativePath] = spec.split(":");
9205
11412
  const keyMap = this.workspacesKeyMap.get(relativePath) || [];
@@ -9243,8 +11450,11 @@ class ResultsCache {
9243
11450
  }
9244
11451
 
9245
11452
  class VitestCache {
9246
- results = new ResultsCache();
11453
+ results;
9247
11454
  stats = new FilesStatsCache();
11455
+ constructor(version) {
11456
+ this.results = new ResultsCache(version);
11457
+ }
9248
11458
  getFileTestResults(key) {
9249
11459
  return this.results.getResults(key);
9250
11460
  }
@@ -9259,7 +11469,7 @@ class VitestCache {
9259
11469
 
9260
11470
  function resolvePath(path, root) {
9261
11471
  return normalize(
9262
- resolveModule(path, { paths: [root] }) ?? resolve(root, path)
11472
+ /* @__PURE__ */ resolveModule(path, { paths: [root] }) ?? resolve(root, path)
9263
11473
  );
9264
11474
  }
9265
11475
  function parseInspector(inspect) {
@@ -9342,6 +11552,8 @@ function resolveConfig(mode, options, viteConfig, logger) {
9342
11552
  throw new Error("--shard <index> must be a positive number less then <count>");
9343
11553
  resolved.shard = { index, count };
9344
11554
  }
11555
+ if (resolved.standalone && !resolved.watch)
11556
+ throw new Error(`Vitest standalone mode requires --watch`);
9345
11557
  if (resolved.maxWorkers)
9346
11558
  resolved.maxWorkers = Number(resolved.maxWorkers);
9347
11559
  if (resolved.minWorkers)
@@ -9424,6 +11636,8 @@ function resolveConfig(mode, options, viteConfig, logger) {
9424
11636
  resolved.server.deps.moduleDirectories.push(...resolved.deps.moduleDirectories);
9425
11637
  if (resolved.runner)
9426
11638
  resolved.runner = resolvePath(resolved.runner, resolved.root);
11639
+ if (resolved.snapshotEnvironment)
11640
+ resolved.snapshotEnvironment = resolvePath(resolved.snapshotEnvironment, resolved.root);
9427
11641
  resolved.testNamePattern = resolved.testNamePattern ? resolved.testNamePattern instanceof RegExp ? resolved.testNamePattern : new RegExp(resolved.testNamePattern) : void 0;
9428
11642
  if (resolved.snapshotFormat && "plugins" in resolved.snapshotFormat)
9429
11643
  resolved.snapshotFormat.plugins = [];
@@ -9526,6 +11740,10 @@ function resolveConfig(mode, options, viteConfig, logger) {
9526
11740
  resolved.benchmark.reporters = ["default"];
9527
11741
  if (options.outputFile)
9528
11742
  resolved.benchmark.outputFile = options.outputFile;
11743
+ if (options.compare)
11744
+ resolved.benchmark.compare = options.compare;
11745
+ if (options.outputJson)
11746
+ resolved.benchmark.outputJson = options.outputJson;
9529
11747
  }
9530
11748
  resolved.setupFiles = toArray(resolved.setupFiles || []).map(
9531
11749
  (file) => resolvePath(file, resolved.root)
@@ -9607,7 +11825,7 @@ function resolveConfig(mode, options, viteConfig, logger) {
9607
11825
  if (!((_F = resolved.sequence) == null ? void 0 : _F.sequencer)) {
9608
11826
  resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
9609
11827
  }
9610
- (_G = resolved.sequence).hooks ?? (_G.hooks = "parallel");
11828
+ (_G = resolved.sequence).hooks ?? (_G.hooks = "stack");
9611
11829
  if (resolved.sequence.sequencer === RandomSequencer)
9612
11830
  (_H = resolved.sequence).seed ?? (_H.seed = Date.now());
9613
11831
  resolved.typecheck = {
@@ -9683,7 +11901,7 @@ function getBetterEnd(code, node) {
9683
11901
  end += 1;
9684
11902
  return end;
9685
11903
  }
9686
- const regexpHoistable = /\b(vi|vitest)\s*\.\s*(mock|unmock|hoisted)\(/;
11904
+ const regexpHoistable = /\b(vi|vitest)\s*\.\s*(mock|unmock|hoisted|doMock|doUnmock)\(/;
9687
11905
  const hashbangRE = /^#!.*\n/;
9688
11906
  function hoistMocks(code, id, parse, colors) {
9689
11907
  var _a;
@@ -9758,7 +11976,7 @@ ${err.message}`);
9758
11976
  name: "SyntaxError",
9759
11977
  message: _error.message,
9760
11978
  stack: _error.stack,
9761
- frame: generateCodeFrame(highlightCode(id, code, colors), 4, node.start + 1)
11979
+ frame: generateCodeFrame(highlightCode(id, code), 4, node.start + 1)
9762
11980
  };
9763
11981
  }
9764
11982
  function assertNotDefaultExport(node, error) {
@@ -9813,6 +12031,21 @@ ${err.message}`);
9813
12031
  assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn't return anything.`);
9814
12032
  hoistedNodes.push(node);
9815
12033
  }
12034
+ if (methodName === "doMock" || methodName === "doUnmock") {
12035
+ const moduleInfo = node.arguments[0];
12036
+ let source = null;
12037
+ if (moduleInfo.type === "ImportExpression")
12038
+ source = moduleInfo.source;
12039
+ if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression")
12040
+ source = moduleInfo.argument.source;
12041
+ if (source) {
12042
+ s.overwrite(
12043
+ moduleInfo.start,
12044
+ moduleInfo.end,
12045
+ s.slice(source.start, source.end)
12046
+ );
12047
+ }
12048
+ }
9816
12049
  if (methodName === "hoisted") {
9817
12050
  assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
9818
12051
  const declarationNode = getVariableDeclaration(node);
@@ -9857,6 +12090,13 @@ ${err.message}`);
9857
12090
  `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`
9858
12091
  );
9859
12092
  }
12093
+ function rewriteMockDynamicImport(nodeCode, moduleInfo, expressionStart, expressionEnd, mockStart) {
12094
+ const source = moduleInfo.source;
12095
+ const importPath = s.slice(source.start, source.end);
12096
+ const nodeCodeStart = expressionStart - mockStart;
12097
+ const nodeCodeEnd = expressionEnd - mockStart;
12098
+ return nodeCode.slice(0, nodeCodeStart) + importPath + nodeCode.slice(nodeCodeEnd);
12099
+ }
9860
12100
  for (let i = 0; i < hoistedNodes.length; i++) {
9861
12101
  const node = hoistedNodes[i];
9862
12102
  for (let j = i + 1; j < hoistedNodes.length; j++) {
@@ -9869,7 +12109,28 @@ ${err.message}`);
9869
12109
  }
9870
12110
  const hoistedCode = hoistedNodes.map((node) => {
9871
12111
  const end = getBetterEnd(code, node);
9872
- const nodeCode = s.slice(node.start, end);
12112
+ let nodeCode = s.slice(node.start, end);
12113
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && (node.callee.property.name === "mock" || node.callee.property.name === "unmock")) {
12114
+ const moduleInfo = node.arguments[0];
12115
+ if (moduleInfo.type === "ImportExpression") {
12116
+ nodeCode = rewriteMockDynamicImport(
12117
+ nodeCode,
12118
+ moduleInfo,
12119
+ moduleInfo.start,
12120
+ moduleInfo.end,
12121
+ node.start
12122
+ );
12123
+ }
12124
+ if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
12125
+ nodeCode = rewriteMockDynamicImport(
12126
+ nodeCode,
12127
+ moduleInfo.argument,
12128
+ moduleInfo.start,
12129
+ moduleInfo.end,
12130
+ node.start
12131
+ );
12132
+ }
12133
+ }
9873
12134
  s.remove(node.start, end);
9874
12135
  return `${nodeCode}${nodeCode.endsWith("\n") ? "" : "\n"}`;
9875
12136
  }).join("");
@@ -9899,10 +12160,10 @@ function resolveOptimizerConfig(_testOptions, viteOptions, testConfig) {
9899
12160
  var _a;
9900
12161
  const testOptions = _testOptions || {};
9901
12162
  const newConfig = {};
9902
- const [major, minor, fix] = version$1.split(".").map(Number);
12163
+ const [major, minor, fix] = version.split(".").map(Number);
9903
12164
  const allowed = major >= 5 || major === 4 && minor >= 4 || major === 4 && minor === 3 && fix >= 2;
9904
12165
  if (!allowed && (testOptions == null ? void 0 : testOptions.enabled) === true)
9905
- console.warn(`Vitest: "deps.optimizer" is only available in Vite >= 4.3.2, current Vite version: ${version$1}`);
12166
+ console.warn(`Vitest: "deps.optimizer" is only available in Vite >= 4.3.2, current Vite version: ${version}`);
9906
12167
  else
9907
12168
  testOptions.enabled ?? (testOptions.enabled = false);
9908
12169
  if (!allowed || (testOptions == null ? void 0 : testOptions.enabled) !== true) {
@@ -10148,6 +12409,481 @@ function CSSEnablerPlugin(ctx) {
10148
12409
  ];
10149
12410
  }
10150
12411
 
12412
+ // Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell
12413
+ // License: MIT.
12414
+ var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
12415
+ RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]|[^\/\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
12416
+ Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
12417
+ Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
12418
+ StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
12419
+ NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
12420
+ Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
12421
+ WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
12422
+ LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
12423
+ MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
12424
+ SingleLineComment = /\/\/.*/y;
12425
+ HashbangComment = /^#!.*/;
12426
+ JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
12427
+ JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
12428
+ JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
12429
+ JSXText = /[^<>{}]+/y;
12430
+ TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
12431
+ TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
12432
+ KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
12433
+ KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
12434
+ Newline = RegExp(LineTerminatorSequence.source);
12435
+ var jsTokens_1 = function*(input, {jsx = false} = {}) {
12436
+ var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
12437
+ ({length} = input);
12438
+ lastIndex = 0;
12439
+ lastSignificantToken = "";
12440
+ stack = [
12441
+ {tag: "JS"}
12442
+ ];
12443
+ braces = [];
12444
+ parenNesting = 0;
12445
+ postfixIncDec = false;
12446
+ if (match = HashbangComment.exec(input)) {
12447
+ yield ({
12448
+ type: "HashbangComment",
12449
+ value: match[0]
12450
+ });
12451
+ lastIndex = match[0].length;
12452
+ }
12453
+ while (lastIndex < length) {
12454
+ mode = stack[stack.length - 1];
12455
+ switch (mode.tag) {
12456
+ case "JS":
12457
+ case "JSNonExpressionParen":
12458
+ case "InterpolationInTemplate":
12459
+ case "InterpolationInJSX":
12460
+ if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
12461
+ RegularExpressionLiteral.lastIndex = lastIndex;
12462
+ if (match = RegularExpressionLiteral.exec(input)) {
12463
+ lastIndex = RegularExpressionLiteral.lastIndex;
12464
+ lastSignificantToken = match[0];
12465
+ postfixIncDec = true;
12466
+ yield ({
12467
+ type: "RegularExpressionLiteral",
12468
+ value: match[0],
12469
+ closed: match[1] !== void 0 && match[1] !== "\\"
12470
+ });
12471
+ continue;
12472
+ }
12473
+ }
12474
+ Punctuator.lastIndex = lastIndex;
12475
+ if (match = Punctuator.exec(input)) {
12476
+ punctuator = match[0];
12477
+ nextLastIndex = Punctuator.lastIndex;
12478
+ nextLastSignificantToken = punctuator;
12479
+ switch (punctuator) {
12480
+ case "(":
12481
+ if (lastSignificantToken === "?NonExpressionParenKeyword") {
12482
+ stack.push({
12483
+ tag: "JSNonExpressionParen",
12484
+ nesting: parenNesting
12485
+ });
12486
+ }
12487
+ parenNesting++;
12488
+ postfixIncDec = false;
12489
+ break;
12490
+ case ")":
12491
+ parenNesting--;
12492
+ postfixIncDec = true;
12493
+ if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
12494
+ stack.pop();
12495
+ nextLastSignificantToken = "?NonExpressionParenEnd";
12496
+ postfixIncDec = false;
12497
+ }
12498
+ break;
12499
+ case "{":
12500
+ Punctuator.lastIndex = 0;
12501
+ isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
12502
+ braces.push(isExpression);
12503
+ postfixIncDec = false;
12504
+ break;
12505
+ case "}":
12506
+ switch (mode.tag) {
12507
+ case "InterpolationInTemplate":
12508
+ if (braces.length === mode.nesting) {
12509
+ Template.lastIndex = lastIndex;
12510
+ match = Template.exec(input);
12511
+ lastIndex = Template.lastIndex;
12512
+ lastSignificantToken = match[0];
12513
+ if (match[1] === "${") {
12514
+ lastSignificantToken = "?InterpolationInTemplate";
12515
+ postfixIncDec = false;
12516
+ yield ({
12517
+ type: "TemplateMiddle",
12518
+ value: match[0]
12519
+ });
12520
+ } else {
12521
+ stack.pop();
12522
+ postfixIncDec = true;
12523
+ yield ({
12524
+ type: "TemplateTail",
12525
+ value: match[0],
12526
+ closed: match[1] === "`"
12527
+ });
12528
+ }
12529
+ continue;
12530
+ }
12531
+ break;
12532
+ case "InterpolationInJSX":
12533
+ if (braces.length === mode.nesting) {
12534
+ stack.pop();
12535
+ lastIndex += 1;
12536
+ lastSignificantToken = "}";
12537
+ yield ({
12538
+ type: "JSXPunctuator",
12539
+ value: "}"
12540
+ });
12541
+ continue;
12542
+ }
12543
+ }
12544
+ postfixIncDec = braces.pop();
12545
+ nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
12546
+ break;
12547
+ case "]":
12548
+ postfixIncDec = true;
12549
+ break;
12550
+ case "++":
12551
+ case "--":
12552
+ nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
12553
+ break;
12554
+ case "<":
12555
+ if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
12556
+ stack.push({tag: "JSXTag"});
12557
+ lastIndex += 1;
12558
+ lastSignificantToken = "<";
12559
+ yield ({
12560
+ type: "JSXPunctuator",
12561
+ value: punctuator
12562
+ });
12563
+ continue;
12564
+ }
12565
+ postfixIncDec = false;
12566
+ break;
12567
+ default:
12568
+ postfixIncDec = false;
12569
+ }
12570
+ lastIndex = nextLastIndex;
12571
+ lastSignificantToken = nextLastSignificantToken;
12572
+ yield ({
12573
+ type: "Punctuator",
12574
+ value: punctuator
12575
+ });
12576
+ continue;
12577
+ }
12578
+ Identifier.lastIndex = lastIndex;
12579
+ if (match = Identifier.exec(input)) {
12580
+ lastIndex = Identifier.lastIndex;
12581
+ nextLastSignificantToken = match[0];
12582
+ switch (match[0]) {
12583
+ case "for":
12584
+ case "if":
12585
+ case "while":
12586
+ case "with":
12587
+ if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
12588
+ nextLastSignificantToken = "?NonExpressionParenKeyword";
12589
+ }
12590
+ }
12591
+ lastSignificantToken = nextLastSignificantToken;
12592
+ postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
12593
+ yield ({
12594
+ type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
12595
+ value: match[0]
12596
+ });
12597
+ continue;
12598
+ }
12599
+ StringLiteral.lastIndex = lastIndex;
12600
+ if (match = StringLiteral.exec(input)) {
12601
+ lastIndex = StringLiteral.lastIndex;
12602
+ lastSignificantToken = match[0];
12603
+ postfixIncDec = true;
12604
+ yield ({
12605
+ type: "StringLiteral",
12606
+ value: match[0],
12607
+ closed: match[2] !== void 0
12608
+ });
12609
+ continue;
12610
+ }
12611
+ NumericLiteral.lastIndex = lastIndex;
12612
+ if (match = NumericLiteral.exec(input)) {
12613
+ lastIndex = NumericLiteral.lastIndex;
12614
+ lastSignificantToken = match[0];
12615
+ postfixIncDec = true;
12616
+ yield ({
12617
+ type: "NumericLiteral",
12618
+ value: match[0]
12619
+ });
12620
+ continue;
12621
+ }
12622
+ Template.lastIndex = lastIndex;
12623
+ if (match = Template.exec(input)) {
12624
+ lastIndex = Template.lastIndex;
12625
+ lastSignificantToken = match[0];
12626
+ if (match[1] === "${") {
12627
+ lastSignificantToken = "?InterpolationInTemplate";
12628
+ stack.push({
12629
+ tag: "InterpolationInTemplate",
12630
+ nesting: braces.length
12631
+ });
12632
+ postfixIncDec = false;
12633
+ yield ({
12634
+ type: "TemplateHead",
12635
+ value: match[0]
12636
+ });
12637
+ } else {
12638
+ postfixIncDec = true;
12639
+ yield ({
12640
+ type: "NoSubstitutionTemplate",
12641
+ value: match[0],
12642
+ closed: match[1] === "`"
12643
+ });
12644
+ }
12645
+ continue;
12646
+ }
12647
+ break;
12648
+ case "JSXTag":
12649
+ case "JSXTagEnd":
12650
+ JSXPunctuator.lastIndex = lastIndex;
12651
+ if (match = JSXPunctuator.exec(input)) {
12652
+ lastIndex = JSXPunctuator.lastIndex;
12653
+ nextLastSignificantToken = match[0];
12654
+ switch (match[0]) {
12655
+ case "<":
12656
+ stack.push({tag: "JSXTag"});
12657
+ break;
12658
+ case ">":
12659
+ stack.pop();
12660
+ if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
12661
+ nextLastSignificantToken = "?JSX";
12662
+ postfixIncDec = true;
12663
+ } else {
12664
+ stack.push({tag: "JSXChildren"});
12665
+ }
12666
+ break;
12667
+ case "{":
12668
+ stack.push({
12669
+ tag: "InterpolationInJSX",
12670
+ nesting: braces.length
12671
+ });
12672
+ nextLastSignificantToken = "?InterpolationInJSX";
12673
+ postfixIncDec = false;
12674
+ break;
12675
+ case "/":
12676
+ if (lastSignificantToken === "<") {
12677
+ stack.pop();
12678
+ if (stack[stack.length - 1].tag === "JSXChildren") {
12679
+ stack.pop();
12680
+ }
12681
+ stack.push({tag: "JSXTagEnd"});
12682
+ }
12683
+ }
12684
+ lastSignificantToken = nextLastSignificantToken;
12685
+ yield ({
12686
+ type: "JSXPunctuator",
12687
+ value: match[0]
12688
+ });
12689
+ continue;
12690
+ }
12691
+ JSXIdentifier.lastIndex = lastIndex;
12692
+ if (match = JSXIdentifier.exec(input)) {
12693
+ lastIndex = JSXIdentifier.lastIndex;
12694
+ lastSignificantToken = match[0];
12695
+ yield ({
12696
+ type: "JSXIdentifier",
12697
+ value: match[0]
12698
+ });
12699
+ continue;
12700
+ }
12701
+ JSXString.lastIndex = lastIndex;
12702
+ if (match = JSXString.exec(input)) {
12703
+ lastIndex = JSXString.lastIndex;
12704
+ lastSignificantToken = match[0];
12705
+ yield ({
12706
+ type: "JSXString",
12707
+ value: match[0],
12708
+ closed: match[2] !== void 0
12709
+ });
12710
+ continue;
12711
+ }
12712
+ break;
12713
+ case "JSXChildren":
12714
+ JSXText.lastIndex = lastIndex;
12715
+ if (match = JSXText.exec(input)) {
12716
+ lastIndex = JSXText.lastIndex;
12717
+ lastSignificantToken = match[0];
12718
+ yield ({
12719
+ type: "JSXText",
12720
+ value: match[0]
12721
+ });
12722
+ continue;
12723
+ }
12724
+ switch (input[lastIndex]) {
12725
+ case "<":
12726
+ stack.push({tag: "JSXTag"});
12727
+ lastIndex++;
12728
+ lastSignificantToken = "<";
12729
+ yield ({
12730
+ type: "JSXPunctuator",
12731
+ value: "<"
12732
+ });
12733
+ continue;
12734
+ case "{":
12735
+ stack.push({
12736
+ tag: "InterpolationInJSX",
12737
+ nesting: braces.length
12738
+ });
12739
+ lastIndex++;
12740
+ lastSignificantToken = "?InterpolationInJSX";
12741
+ postfixIncDec = false;
12742
+ yield ({
12743
+ type: "JSXPunctuator",
12744
+ value: "{"
12745
+ });
12746
+ continue;
12747
+ }
12748
+ }
12749
+ WhiteSpace.lastIndex = lastIndex;
12750
+ if (match = WhiteSpace.exec(input)) {
12751
+ lastIndex = WhiteSpace.lastIndex;
12752
+ yield ({
12753
+ type: "WhiteSpace",
12754
+ value: match[0]
12755
+ });
12756
+ continue;
12757
+ }
12758
+ LineTerminatorSequence.lastIndex = lastIndex;
12759
+ if (match = LineTerminatorSequence.exec(input)) {
12760
+ lastIndex = LineTerminatorSequence.lastIndex;
12761
+ postfixIncDec = false;
12762
+ if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
12763
+ lastSignificantToken = "?NoLineTerminatorHere";
12764
+ }
12765
+ yield ({
12766
+ type: "LineTerminatorSequence",
12767
+ value: match[0]
12768
+ });
12769
+ continue;
12770
+ }
12771
+ MultiLineComment.lastIndex = lastIndex;
12772
+ if (match = MultiLineComment.exec(input)) {
12773
+ lastIndex = MultiLineComment.lastIndex;
12774
+ if (Newline.test(match[0])) {
12775
+ postfixIncDec = false;
12776
+ if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
12777
+ lastSignificantToken = "?NoLineTerminatorHere";
12778
+ }
12779
+ }
12780
+ yield ({
12781
+ type: "MultiLineComment",
12782
+ value: match[0],
12783
+ closed: match[1] !== void 0
12784
+ });
12785
+ continue;
12786
+ }
12787
+ SingleLineComment.lastIndex = lastIndex;
12788
+ if (match = SingleLineComment.exec(input)) {
12789
+ lastIndex = SingleLineComment.lastIndex;
12790
+ postfixIncDec = false;
12791
+ yield ({
12792
+ type: "SingleLineComment",
12793
+ value: match[0]
12794
+ });
12795
+ continue;
12796
+ }
12797
+ firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
12798
+ lastIndex += firstCodePoint.length;
12799
+ lastSignificantToken = firstCodePoint;
12800
+ postfixIncDec = false;
12801
+ yield ({
12802
+ type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
12803
+ value: firstCodePoint
12804
+ });
12805
+ }
12806
+ return void 0;
12807
+ };
12808
+
12809
+ var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokens_1);
12810
+
12811
+ function stripLiteralJsTokens(code, options) {
12812
+ const FILL = " ";
12813
+ const FILL_COMMENT = " ";
12814
+ let result = "";
12815
+ const tokens = [];
12816
+ for (const token of jsTokens(code, { jsx: false })) {
12817
+ tokens.push(token);
12818
+ if (token.type === "SingleLineComment") {
12819
+ result += FILL_COMMENT.repeat(token.value.length);
12820
+ continue;
12821
+ }
12822
+ if (token.type === "MultiLineComment") {
12823
+ result += token.value.replace(/[^\n]/g, FILL_COMMENT);
12824
+ continue;
12825
+ }
12826
+ if (token.type === "StringLiteral") {
12827
+ if (!token.closed) {
12828
+ result += token.value;
12829
+ continue;
12830
+ }
12831
+ const body = token.value.slice(1, -1);
12832
+ {
12833
+ result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
12834
+ continue;
12835
+ }
12836
+ }
12837
+ if (token.type === "NoSubstitutionTemplate") {
12838
+ const body = token.value.slice(1, -1);
12839
+ {
12840
+ result += `\`${body.replace(/[^\n]/g, FILL)}\``;
12841
+ continue;
12842
+ }
12843
+ }
12844
+ if (token.type === "RegularExpressionLiteral") {
12845
+ const body = token.value;
12846
+ {
12847
+ result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
12848
+ continue;
12849
+ }
12850
+ }
12851
+ if (token.type === "TemplateHead") {
12852
+ const body = token.value.slice(1, -2);
12853
+ {
12854
+ result += `\`${body.replace(/[^\n]/g, FILL)}\${`;
12855
+ continue;
12856
+ }
12857
+ }
12858
+ if (token.type === "TemplateTail") {
12859
+ const body = token.value.slice(0, -2);
12860
+ {
12861
+ result += `}${body.replace(/[^\n]/g, FILL)}\``;
12862
+ continue;
12863
+ }
12864
+ }
12865
+ if (token.type === "TemplateMiddle") {
12866
+ const body = token.value.slice(1, -2);
12867
+ {
12868
+ result += `}${body.replace(/[^\n]/g, FILL)}\${`;
12869
+ continue;
12870
+ }
12871
+ }
12872
+ result += token.value;
12873
+ }
12874
+ return {
12875
+ result,
12876
+ tokens
12877
+ };
12878
+ }
12879
+
12880
+ function stripLiteral(code, options) {
12881
+ return stripLiteralDetailed(code).result;
12882
+ }
12883
+ function stripLiteralDetailed(code, options) {
12884
+ return stripLiteralJsTokens(code);
12885
+ }
12886
+
10151
12887
  function SsrReplacerPlugin() {
10152
12888
  return {
10153
12889
  name: "vitest:ssr-replacer",
@@ -10325,7 +13061,7 @@ function WorkspaceVitestPlugin(project, options) {
10325
13061
  );
10326
13062
  await project.setServer(options2, server);
10327
13063
  } catch (err) {
10328
- await project.ctx.logger.printError(err, { fullStack: true });
13064
+ project.ctx.logger.printError(err, { fullStack: true });
10329
13065
  process.exit(1);
10330
13066
  }
10331
13067
  await server.watcher.close();
@@ -10419,6 +13155,8 @@ class WorkspaceProject {
10419
13155
  browserProvider;
10420
13156
  browserState;
10421
13157
  testFilesList = null;
13158
+ id = nanoid();
13159
+ tmpDir = join(tmpdir(), this.id);
10422
13160
  _globalSetups;
10423
13161
  _provided = {};
10424
13162
  getName() {
@@ -10462,7 +13200,7 @@ class WorkspaceProject {
10462
13200
  } catch (e) {
10463
13201
  this.logger.error(`
10464
13202
  ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10465
- await this.logger.printError(e);
13203
+ this.logger.printError(e);
10466
13204
  process.exit(1);
10467
13205
  }
10468
13206
  }
@@ -10475,7 +13213,7 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10475
13213
  await ((_a = globalSetupFile.teardown) == null ? void 0 : _a.call(globalSetupFile));
10476
13214
  } catch (error) {
10477
13215
  this.logger.error(`error during global teardown of ${globalSetupFile.file}`, error);
10478
- await this.logger.printError(error);
13216
+ this.logger.printError(error);
10479
13217
  process.exitCode = 1;
10480
13218
  }
10481
13219
  }
@@ -10523,7 +13261,7 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10523
13261
  const files = await this.globFiles(includeSource, exclude, cwd);
10524
13262
  await Promise.all(files.map(async (file) => {
10525
13263
  try {
10526
- const code = await promises.readFile(file, "utf-8");
13264
+ const code = await promises$1.readFile(file, "utf-8");
10527
13265
  if (this.isInSourceTestFile(code))
10528
13266
  testFiles.push(file);
10529
13267
  } catch {
@@ -10554,7 +13292,7 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10554
13292
  if (mm.isMatch(relativeId, this.config.include))
10555
13293
  return true;
10556
13294
  if (((_a = this.config.includeSource) == null ? void 0 : _a.length) && mm.isMatch(relativeId, this.config.includeSource)) {
10557
- source = source || await promises.readFile(id, "utf-8");
13295
+ source = source || await promises$1.readFile(id, "utf-8");
10558
13296
  return this.isInSourceTestFile(source);
10559
13297
  }
10560
13298
  return false;
@@ -10690,11 +13428,18 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
10690
13428
  this.closingPromise = Promise.all([
10691
13429
  this.server.close(),
10692
13430
  (_a = this.typechecker) == null ? void 0 : _a.stop(),
10693
- (_b = this.browser) == null ? void 0 : _b.close()
13431
+ (_b = this.browser) == null ? void 0 : _b.close(),
13432
+ this.clearTmpDir()
10694
13433
  ].filter(Boolean)).then(() => this._provided = {});
10695
13434
  }
10696
13435
  return this.closingPromise;
10697
13436
  }
13437
+ async clearTmpDir() {
13438
+ try {
13439
+ await rm(this.tmpDir, { force: true, recursive: true });
13440
+ } catch {
13441
+ }
13442
+ }
10698
13443
  async initBrowserProvider() {
10699
13444
  if (!this.isBrowserEnabled())
10700
13445
  return;
@@ -10726,7 +13471,7 @@ class VitestPackageInstaller {
10726
13471
  } catch (error) {
10727
13472
  }
10728
13473
  }
10729
- if (isPackageExists(dependency, { paths: [root, __dirname] }))
13474
+ if (/* @__PURE__ */ isPackageExists(dependency, { paths: [root, __dirname] }))
10730
13475
  return true;
10731
13476
  const promptInstall = !isCI && process.stdout.isTTY;
10732
13477
  process.stderr.write(c.red(`${c.inverse(c.red(" MISSING DEPENDENCY "))} Cannot find dependency '${dependency}'
@@ -10741,7 +13486,7 @@ class VitestPackageInstaller {
10741
13486
  message: c.reset(`Do you want to install ${c.green(dependency)}?`)
10742
13487
  });
10743
13488
  if (install) {
10744
- await (await import('../chunks/install-pkg.LE8oaA1t.js')).installPackage(dependency, { dev: true });
13489
+ await (await import('../chunks/install-pkg.DNUmWFkO.js')).installPackage(dependency, { dev: true });
10745
13490
  process.stderr.write(c.yellow(`
10746
13491
  Package ${dependency} installed, re-run the command to start.
10747
13492
  `));
@@ -10759,6 +13504,7 @@ class Vitest {
10759
13504
  this.logger = new Logger(this, options.stdout, options.stderr);
10760
13505
  this.packageInstaller = options.packageInstaller || new VitestPackageInstaller();
10761
13506
  }
13507
+ version = version$1;
10762
13508
  config = void 0;
10763
13509
  configOverride = {};
10764
13510
  server = void 0;
@@ -10799,19 +13545,17 @@ class Vitest {
10799
13545
  this.pool = void 0;
10800
13546
  this.coverageProvider = void 0;
10801
13547
  this.runningPromise = void 0;
13548
+ this.distPath = void 0;
10802
13549
  this.projectsTestFiles.clear();
10803
13550
  const resolved = resolveConfig(this.mode, options, server.config, this.logger);
10804
13551
  this.server = server;
10805
13552
  this.config = resolved;
10806
13553
  this.state = new StateManager();
10807
- this.cache = new VitestCache();
13554
+ this.cache = new VitestCache(this.version);
10808
13555
  this.snapshot = new SnapshotManager({ ...resolved.snapshotOptions });
10809
13556
  if (this.config.watch)
10810
13557
  this.registerWatcher();
10811
13558
  this.vitenode = new ViteNodeServer(server, this.config.server);
10812
- const projectVitestPath = await this.vitenode.resolveId("vitest");
10813
- const vitestDir = projectVitestPath ? resolve(projectVitestPath.id, "../..") : rootDir;
10814
- this.distPath = join(vitestDir, "dist");
10815
13559
  const node = this.vitenode;
10816
13560
  this.runner = new ViteNodeRunner({
10817
13561
  root: server.config.root,
@@ -10880,7 +13624,7 @@ class Vitest {
10880
13624
  if (this.config.workspace)
10881
13625
  return this.config.workspace;
10882
13626
  const configDir = this.server.config.configFile ? dirname(this.server.config.configFile) : this.config.root;
10883
- const rootFiles = await promises.readdir(configDir);
13627
+ const rootFiles = await promises$1.readdir(configDir);
10884
13628
  const workspaceConfigName = workspacesFiles.find((configFile) => {
10885
13629
  return rootFiles.includes(configFile);
10886
13630
  });
@@ -10931,7 +13675,7 @@ class Vitest {
10931
13675
  return CONFIG_NAMES.some((configName) => filename.startsWith(configName));
10932
13676
  }).map(async (filepath) => {
10933
13677
  if (filepath.endsWith("/")) {
10934
- const filesInside = await promises.readdir(filepath);
13678
+ const filesInside = await promises$1.readdir(filepath);
10935
13679
  const configFile = configFiles.find((config) => filesInside.includes(config));
10936
13680
  return configFile ? join(filepath, configFile) : filepath;
10937
13681
  }
@@ -11050,6 +13794,20 @@ class Vitest {
11050
13794
  if (this.config.watch)
11051
13795
  await this.report("onWatcherStart");
11052
13796
  }
13797
+ async init() {
13798
+ var _a;
13799
+ this._onClose = [];
13800
+ try {
13801
+ await this.initCoverageProvider();
13802
+ await ((_a = this.coverageProvider) == null ? void 0 : _a.clean(this.config.coverage.clean));
13803
+ await this.initBrowserProviders();
13804
+ } finally {
13805
+ await this.report("onInit", this);
13806
+ }
13807
+ await this.globTestFiles();
13808
+ if (this.config.watch)
13809
+ await this.report("onWatcherStart");
13810
+ }
11053
13811
  async getTestDependencies(filepath, deps = /* @__PURE__ */ new Set()) {
11054
13812
  const addImports = async ([project, filepath2]) => {
11055
13813
  if (deps.has(filepath2))
@@ -11073,7 +13831,7 @@ class Vitest {
11073
13831
  }
11074
13832
  async filterTestsBySource(specs) {
11075
13833
  if (this.config.changed && !this.config.related) {
11076
- const { VitestGit } = await import('../chunks/node-git.Hw101KjS.js');
13834
+ const { VitestGit } = await import('../chunks/node-git.CCI8evVZ.js');
11077
13835
  const vitestGit = new VitestGit(this.config.root);
11078
13836
  const related2 = await vitestGit.findChangedFiles({
11079
13837
  changedSince: this.config.changed
@@ -11119,7 +13877,15 @@ class Vitest {
11119
13877
  for await (const project of projects)
11120
13878
  await project.initializeGlobalSetup();
11121
13879
  }
13880
+ async initializeDistPath() {
13881
+ if (this.distPath)
13882
+ return;
13883
+ const projectVitestPath = await this.vitenode.resolveId("vitest");
13884
+ const vitestDir = projectVitestPath ? resolve(projectVitestPath.id, "../..") : rootDir;
13885
+ this.distPath = join(vitestDir, "dist");
13886
+ }
11122
13887
  async runFiles(paths, allTestsRun) {
13888
+ await this.initializeDistPath();
11123
13889
  const filepaths = paths.map(([, file]) => file);
11124
13890
  this.state.collectPaths(filepaths);
11125
13891
  await this.report("onPathsCollected", filepaths);
@@ -11183,12 +13949,21 @@ class Vitest {
11183
13949
  async changeNamePattern(pattern, files = this.state.getFilepaths(), trigger) {
11184
13950
  if (pattern === "")
11185
13951
  this.filenamePattern = void 0;
11186
- this.configOverride.testNamePattern = pattern ? new RegExp(pattern) : void 0;
13952
+ const testNamePattern = pattern ? new RegExp(pattern) : void 0;
13953
+ this.configOverride.testNamePattern = testNamePattern;
13954
+ if (testNamePattern) {
13955
+ files = files.filter((filepath) => {
13956
+ const files2 = this.state.getFiles([filepath]);
13957
+ return !files2.length || files2.some((file) => {
13958
+ const tasks = getTasks(file);
13959
+ return !tasks.length || tasks.some((task) => testNamePattern.test(task.name));
13960
+ });
13961
+ });
13962
+ }
11187
13963
  await this.rerunFiles(files, trigger);
11188
13964
  }
11189
- async changeFilenamePattern(pattern) {
13965
+ async changeFilenamePattern(pattern, files = this.state.getFilepaths()) {
11190
13966
  this.filenamePattern = pattern;
11191
- const files = this.state.getFilepaths();
11192
13967
  const trigger = this.filenamePattern ? "change filename pattern" : "reset filename pattern";
11193
13968
  await this.rerunFiles(files, trigger);
11194
13969
  }
@@ -11300,8 +14075,11 @@ class Vitest {
11300
14075
  updateLastChanged(id);
11301
14076
  const matchingProjects = [];
11302
14077
  await Promise.all(this.projects.map(async (project) => {
11303
- if (await project.isTargetFile(id))
14078
+ var _a;
14079
+ if (await project.isTargetFile(id)) {
11304
14080
  matchingProjects.push(project);
14081
+ (_a = project.testFilesList) == null ? void 0 : _a.push(id);
14082
+ }
11305
14083
  }));
11306
14084
  if (matchingProjects.length > 0) {
11307
14085
  this.projectsTestFiles.set(id, new Set(matchingProjects));
@@ -11316,7 +14094,6 @@ class Vitest {
11316
14094
  const watcher = this.server.watcher;
11317
14095
  if (this.config.forceRerunTriggers.length)
11318
14096
  watcher.add(this.config.forceRerunTriggers);
11319
- watcher.unwatch(this.config.watchExclude);
11320
14097
  watcher.on("change", onChange);
11321
14098
  watcher.on("unlink", onUnlink);
11322
14099
  watcher.on("add", onAdd);
@@ -11445,6 +14222,9 @@ class Vitest {
11445
14222
  );
11446
14223
  }));
11447
14224
  }
14225
+ async getTestFilepaths() {
14226
+ return this.globTestFiles().then((files) => files.map(([, file]) => file));
14227
+ }
11448
14228
  async globTestFiles(filters = []) {
11449
14229
  const files = [];
11450
14230
  await Promise.all(this.projects.map(async (project) => {
@@ -11527,9 +14307,6 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
11527
14307
  },
11528
14308
  server: {
11529
14309
  ...testConfig.api,
11530
- watch: {
11531
- ignored: testConfig.watchExclude
11532
- },
11533
14310
  open,
11534
14311
  hmr: false,
11535
14312
  preTransformRequests: false,
@@ -11571,8 +14348,11 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
11571
14348
  }
11572
14349
  }
11573
14350
  if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
11574
- config.server.watch.useFsEvents = false;
11575
- config.server.watch.usePolling = false;
14351
+ const watch = config.server.watch;
14352
+ if (watch) {
14353
+ watch.useFsEvents = false;
14354
+ watch.usePolling = false;
14355
+ }
11576
14356
  }
11577
14357
  const classNameStrategy = typeof testConfig.css !== "boolean" && ((_q = (_p = testConfig.css) == null ? void 0 : _p.modules) == null ? void 0 : _q.classNameStrategy) || "stable";
11578
14358
  if (classNameStrategy !== "scoped") {
@@ -11621,7 +14401,7 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
11621
14401
  if (options.api && options.watch)
11622
14402
  (await Promise.resolve().then(function () { return setup$1; })).setup(ctx);
11623
14403
  } catch (err) {
11624
- await ctx.logger.printError(err, { fullStack: true });
14404
+ ctx.logger.printError(err, { fullStack: true });
11625
14405
  process.exit(1);
11626
14406
  }
11627
14407
  if (!options.watch)
@@ -11906,7 +14686,7 @@ function requireClear$1 () {
11906
14686
  if (hasRequiredClear$1) return clear$1;
11907
14687
  hasRequiredClear$1 = 1;
11908
14688
 
11909
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
14689
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike ) { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
11910
14690
 
11911
14691
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
11912
14692
 
@@ -14865,7 +17645,7 @@ function requireDist () {
14865
17645
 
14866
17646
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
14867
17647
 
14868
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
17648
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike ) { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
14869
17649
 
14870
17650
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
14871
17651
 
@@ -18073,6 +20853,9 @@ ${resultBody}`;
18073
20853
  write(data) {
18074
20854
  this.stdout.write(data);
18075
20855
  }
20856
+ getLastResults() {
20857
+ return this.results;
20858
+ }
18076
20859
  }
18077
20860
 
18078
20861
  const keys = [
@@ -18124,8 +20907,10 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout2) {
18124
20907
  return printShortcutsHelp();
18125
20908
  if (name === "u")
18126
20909
  return ctx.updateSnapshot();
18127
- if (name === "a" || name === "return")
18128
- return ctx.changeNamePattern("");
20910
+ if (name === "a" || name === "return") {
20911
+ const files = await ctx.getTestFilepaths();
20912
+ return ctx.changeNamePattern("", files, "rerun all tests");
20913
+ }
18129
20914
  if (name === "r")
18130
20915
  return ctx.rerunFiles();
18131
20916
  if (name === "f")
@@ -18144,8 +20929,8 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout2) {
18144
20929
  off();
18145
20930
  const watchFilter = new WatchFilter("Input test name pattern (RegExp)", stdin, stdout2);
18146
20931
  const filter = await watchFilter.filter((str) => {
18147
- const files = ctx.state.getFiles();
18148
- const tests = getTests(files);
20932
+ const files2 = ctx.state.getFiles();
20933
+ const tests = getTests(files2);
18149
20934
  try {
18150
20935
  const reg = new RegExp(str);
18151
20936
  return tests.map((test) => test.name).filter((testName) => testName.match(reg));
@@ -18154,7 +20939,9 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout2) {
18154
20939
  }
18155
20940
  });
18156
20941
  on();
18157
- await ctx.changeNamePattern((filter == null ? void 0 : filter.trim()) || "", void 0, "change pattern");
20942
+ const files = ctx.state.getFilepaths();
20943
+ const cliFiles = ctx.config.standalone && !files.length ? await ctx.getTestFilepaths() : void 0;
20944
+ await ctx.changeNamePattern((filter == null ? void 0 : filter.trim()) || "", cliFiles, "change pattern");
18158
20945
  }
18159
20946
  async function inputProjectName() {
18160
20947
  off();
@@ -18178,7 +20965,11 @@ function registerConsoleShortcuts(ctx, stdin = process.stdin, stdout2) {
18178
20965
  });
18179
20966
  on();
18180
20967
  latestFilename = (filter == null ? void 0 : filter.trim()) || "";
18181
- await ctx.changeFilenamePattern(latestFilename);
20968
+ const lastResults = watchFilter.getLastResults();
20969
+ await ctx.changeFilenamePattern(
20970
+ latestFilename,
20971
+ filter && lastResults.length ? lastResults.map((i) => resolve(ctx.config.root, i)) : void 0
20972
+ );
18182
20973
  }
18183
20974
  let rl;
18184
20975
  function on() {
@@ -18241,10 +21032,16 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides, v
18241
21032
  process.exit(EXIT_CODE_RESTART);
18242
21033
  });
18243
21034
  ctx.onAfterSetServer(() => {
18244
- ctx.start(cliFilters);
21035
+ if (ctx.config.standalone)
21036
+ ctx.init();
21037
+ else
21038
+ ctx.start(cliFilters);
18245
21039
  });
18246
21040
  try {
18247
- await ctx.start(cliFilters);
21041
+ if (ctx.config.standalone)
21042
+ await ctx.init();
21043
+ else
21044
+ await ctx.start(cliFilters);
18248
21045
  } catch (e) {
18249
21046
  process.exitCode = 1;
18250
21047
  await ctx.logger.printError(e, { fullStack: true, type: "Unhandled Error" });