vitest 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE.md +29 -0
  2. package/dist/browser.d.ts +3 -2
  3. package/dist/browser.js +2 -1
  4. package/dist/chunks/{api-setup.omeaEsoT.js → api-setup.Xh60JpeM.js} +27 -64
  5. package/dist/chunks/{integrations-globals.9QpVy4UR.js → integrations-globals.FlQVNhQx.js} +6 -6
  6. package/dist/chunks/{runtime-runBaseTests.S8ZSFig3.js → runtime-runBaseTests.0UwIvo_U.js} +9 -9
  7. package/dist/cli-wrapper.js +1 -1
  8. package/dist/cli.js +1314 -69
  9. package/dist/config.cjs +1 -1
  10. package/dist/config.d.ts +1 -1
  11. package/dist/coverage.d.ts +3 -3
  12. package/dist/environments.d.ts +1 -1
  13. package/dist/environments.js +1 -1
  14. package/dist/execute.d.ts +3 -3
  15. package/dist/execute.js +2 -2
  16. package/dist/index.d.ts +74 -78
  17. package/dist/index.js +7 -7
  18. package/dist/node.d.ts +3 -3
  19. package/dist/node.js +21 -21
  20. package/dist/{reporters-rzC174PQ.d.ts → reporters-QGe8gs4b.d.ts} +147 -56
  21. package/dist/reporters.d.ts +1 -1
  22. package/dist/reporters.js +20 -6
  23. package/dist/runners.d.ts +6 -6
  24. package/dist/runners.js +10 -10
  25. package/dist/{suite-MFRDkZcV.d.ts → suite-xGC-mxBC.d.ts} +1 -1
  26. package/dist/suite.d.ts +3 -3
  27. package/dist/suite.js +3 -3
  28. package/dist/vendor/{base.4sEqnqgY.js → base.RpormaJz.js} +2 -2
  29. package/dist/vendor/{base.QYERqzkH.js → base.knFzp7G3.js} +1 -1
  30. package/dist/vendor/{benchmark.IlKmJkUU.js → benchmark.eeqk2rd8.js} +1 -1
  31. package/dist/vendor/{node.p6h5JSuL.js → cli-api.RIYLcWhB.js} +1559 -3672
  32. package/dist/vendor/{constants.i1PoEnhr.js → constants.K-Wf1PUy.js} +3 -1
  33. package/dist/vendor/{execute.edwByI27.js → execute.aFSzc0Da.js} +26 -26
  34. package/dist/vendor/{index.cAUulNDf.js → index.8bPxjt7g.js} +6 -1
  35. package/dist/vendor/{index.kwCLJK4i.js → index.CKbXK54q.js} +7 -3
  36. package/dist/vendor/{environments.sU0TD7wX.js → index.GVFv9dZ0.js} +3 -0
  37. package/dist/vendor/index.QcWmThJv.js +4927 -0
  38. package/dist/vendor/{index.rJjbcrrp.js → index.ir9i0ywP.js} +1 -1
  39. package/dist/vendor/{index.vs_-lzuF.js → index.n-Ib4UWN.js} +4 -3
  40. package/dist/vendor/{rpc.w4v8oCkK.js → rpc.joBhAkyK.js} +10 -1
  41. package/dist/vendor/setup-common.NSpEdAQm.js +45 -0
  42. package/dist/vendor/{vi.Bw2UL9c9.js → vi.-Nr_x6dl.js} +8 -5
  43. package/dist/vendor/{vm.9N6CwTZh.js → vm.UmCkcXp-.js} +39 -12
  44. package/dist/worker.js +5 -10
  45. package/dist/workers/forks.js +3 -3
  46. package/dist/workers/runVmTests.js +13 -9
  47. package/dist/workers/threads.js +3 -3
  48. package/dist/workers/vmForks.js +4 -4
  49. package/dist/workers/vmThreads.js +4 -4
  50. package/dist/workers.d.ts +3 -3
  51. package/dist/workers.js +8 -8
  52. package/globals.d.ts +2 -0
  53. package/jsdom.d.ts +6 -0
  54. package/package.json +26 -22
  55. package/dist/vendor/reporters.cA9x-5v-.js +0 -2664
  56. package/dist/vendor/setup-common.4GIL70qB.js +0 -29
package/dist/cli.js CHANGED
@@ -1,89 +1,1357 @@
1
1
  import { normalize } from 'pathe';
2
- import cac from 'cac';
2
+ import { EventEmitter } from 'events';
3
3
  import c from 'picocolors';
4
- import { v as version, s as startVitest } from './vendor/node.p6h5JSuL.js';
5
- import './vendor/index.rJjbcrrp.js';
6
- import { d as divider } from './vendor/reporters.cA9x-5v-.js';
7
- import { t as toArray } from './vendor/base.QYERqzkH.js';
4
+ import { v as version, s as startVitest } from './vendor/cli-api.RIYLcWhB.js';
5
+ import './vendor/index.ir9i0ywP.js';
6
+ import { f as divider } from './vendor/index.QcWmThJv.js';
7
+ import { d as defaultPort, a as defaultBrowserPort } from './vendor/constants.K-Wf1PUy.js';
8
+ import { t as toArray } from './vendor/base.knFzp7G3.js';
9
+ import './vendor/coverage.E7sG1b3r.js';
10
+ import './vendor/index.GVFv9dZ0.js';
11
+ import 'node:console';
8
12
  import 'vite';
9
13
  import 'node:path';
10
14
  import 'node:url';
11
15
  import 'node:process';
12
16
  import 'node:fs';
13
- import './vendor/constants.i1PoEnhr.js';
14
17
  import './vendor/_commonjsHelpers.jjO7Zipk.js';
15
18
  import 'os';
16
19
  import 'path';
17
20
  import './vendor/index.xL8XjTLv.js';
18
21
  import 'util';
19
22
  import 'stream';
20
- import 'events';
21
23
  import 'fs';
22
24
  import 'vite-node/client';
23
25
  import '@vitest/snapshot/manager';
24
26
  import 'vite-node/server';
25
- import './vendor/coverage.E7sG1b3r.js';
26
27
  import './path.js';
27
28
  import 'node:v8';
28
29
  import 'node:os';
29
30
  import 'node:events';
30
31
  import 'tinypool';
31
- import './vendor/index.cAUulNDf.js';
32
+ import './vendor/index.8bPxjt7g.js';
32
33
  import 'node:worker_threads';
33
34
  import '@vitest/utils';
34
- import 'node:fs/promises';
35
- import 'node:perf_hooks';
36
- import 'execa';
37
- import '@vitest/utils/source-map';
38
- import 'module';
39
- import 'acorn-walk';
40
35
  import '@vitest/runner/utils';
41
36
  import 'local-pkg';
42
37
  import 'std-env';
43
38
  import 'node:crypto';
44
39
  import 'vite-node/utils';
45
- import 'assert';
46
40
  import 'magic-string';
41
+ import 'acorn-walk';
47
42
  import '@vitest/utils/ast';
48
43
  import 'strip-literal';
49
44
  import 'node:module';
50
- import './vendor/environments.sU0TD7wX.js';
51
- import 'node:console';
52
45
  import 'node:readline';
53
46
  import 'readline';
54
47
  import './vendor/global.CkGT_TMy.js';
48
+ import 'node:perf_hooks';
55
49
  import './chunks/runtime-console.Iloo9fIt.js';
56
50
  import 'node:stream';
57
51
  import './vendor/date.Ns1pGd_X.js';
58
52
  import './vendor/tasks.IknbGB2n.js';
53
+ import '@vitest/utils/source-map';
54
+ import 'node:fs/promises';
55
+ import 'execa';
56
+ import 'module';
57
+ import 'assert';
58
+
59
+ function toArr(any) {
60
+ return any == null ? [] : Array.isArray(any) ? any : [any];
61
+ }
62
+
63
+ function toVal(out, key, val, opts) {
64
+ var x, old=out[key], nxt=(
65
+ !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
66
+ : typeof val === 'boolean' ? val
67
+ : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
68
+ : (x = +val,x * 0 === 0) ? x : val
69
+ );
70
+ out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
71
+ }
72
+
73
+ function mri2 (args, opts) {
74
+ args = args || [];
75
+ opts = opts || {};
76
+
77
+ var k, arr, arg, name, val, out={ _:[] };
78
+ var i=0, j=0, idx=0, len=args.length;
79
+
80
+ const alibi = opts.alias !== void 0;
81
+ const strict = opts.unknown !== void 0;
82
+ const defaults = opts.default !== void 0;
83
+
84
+ opts.alias = opts.alias || {};
85
+ opts.string = toArr(opts.string);
86
+ opts.boolean = toArr(opts.boolean);
87
+
88
+ if (alibi) {
89
+ for (k in opts.alias) {
90
+ arr = opts.alias[k] = toArr(opts.alias[k]);
91
+ for (i=0; i < arr.length; i++) {
92
+ (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
93
+ }
94
+ }
95
+ }
96
+
97
+ for (i=opts.boolean.length; i-- > 0;) {
98
+ arr = opts.alias[opts.boolean[i]] || [];
99
+ for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
100
+ }
101
+
102
+ for (i=opts.string.length; i-- > 0;) {
103
+ arr = opts.alias[opts.string[i]] || [];
104
+ for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
105
+ }
106
+
107
+ if (defaults) {
108
+ for (k in opts.default) {
109
+ name = typeof opts.default[k];
110
+ arr = opts.alias[k] = opts.alias[k] || [];
111
+ if (opts[name] !== void 0) {
112
+ opts[name].push(k);
113
+ for (i=0; i < arr.length; i++) {
114
+ opts[name].push(arr[i]);
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ const keys = strict ? Object.keys(opts.alias) : [];
121
+
122
+ for (i=0; i < len; i++) {
123
+ arg = args[i];
124
+
125
+ if (arg === '--') {
126
+ out._ = out._.concat(args.slice(++i));
127
+ break;
128
+ }
129
+
130
+ for (j=0; j < arg.length; j++) {
131
+ if (arg.charCodeAt(j) !== 45) break; // "-"
132
+ }
133
+
134
+ if (j === 0) {
135
+ out._.push(arg);
136
+ } else if (arg.substring(j, j + 3) === 'no-') {
137
+ name = arg.substring(j + 3);
138
+ if (strict && !~keys.indexOf(name)) {
139
+ return opts.unknown(arg);
140
+ }
141
+ out[name] = false;
142
+ } else {
143
+ for (idx=j+1; idx < arg.length; idx++) {
144
+ if (arg.charCodeAt(idx) === 61) break; // "="
145
+ }
146
+
147
+ name = arg.substring(j, idx);
148
+ val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
149
+ arr = (j === 2 ? [name] : name);
59
150
 
60
- const cli = cac("vitest");
61
- cli.version(version).option("-r, --root <path>", "Root path").option("-c, --config <path>", "Path to config file").option("-u, --update", "Update snapshot").option("-w, --watch", "Enable watch mode").option("-t, --testNamePattern <pattern>", "Run tests with full names matching the specified regexp pattern").option("--dir <path>", "Base directory to scan for the test files").option("--ui", "Enable UI").option("--open", "Open UI automatically (default: !process.env.CI))").option("--api [api]", "Serve API, available options: --api.port <port>, --api.host [host] and --api.strictPort").option("--silent", "Silent console output from tests").option("--hideSkippedTests", "Hide logs for skipped tests").option("--reporter <name>", "Specify reporters").option("--outputFile <filename/-s>", "Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters").option("--coverage", "Enable coverage report").option("--coverage.all", "Whether to include all files, including the untested ones into report", { default: true }).option("--run", "Disable watch mode").option("--mode <name>", "Override Vite mode (default: test)").option("--workspace <path>", "Path to a workspace configuration file").option("--isolate", "Run every test file in isolation. To disable isolation, use --no-isolate (default: true)").option("--globals", "Inject apis globally").option("--dom", "Mock browser API with happy-dom").option("--browser [options]", "Run tests in the browser (default: false)").option("--pool <pool>", "Specify pool, if not running in the browser (default: threads)").option("--poolOptions <options>", "Specify pool options").option("--poolOptions.threads.isolate", "Isolate tests in threads pool (default: true)").option("--poolOptions.forks.isolate", "Isolate tests in forks pool (default: true)").option("--fileParallelism", "Should all test files run in parallel. Use --no-file-parallelism to disable (default: true)").option("--maxWorkers <workers>", "Maximum number of workers to run tests in").option("--minWorkers <workers>", "Minimum number of workers to run tests in").option("--environment <env>", "Specify runner environment, if not running in the browser (default: node)").option("--passWithNoTests", "Pass when no tests found").option("--logHeapUsage", "Show the size of heap for each test").option("--allowOnly", "Allow tests and suites that are marked as only (default: !process.env.CI)").option("--dangerouslyIgnoreUnhandledErrors", "Ignore any unhandled errors that occur").option("--shard <shard>", "Test suite shard to execute in a format of <index>/<count>").option("--changed [since]", "Run tests that are affected by the changed files (default: false)").option("--sequence <options>", "Define in what order to run tests (use --sequence.shuffle to run tests in random order, use --sequence.concurrent to run tests in parallel)").option("--segfaultRetry <times>", "Return tests on segment fault (default: 0)", { default: 0 }).option("--no-color", "Removes colors from the console output").option("--inspect", "Enable Node.js inspector").option("--inspect-brk", "Enable Node.js inspector with break").option("--test-timeout <time>", "Default timeout of a test in milliseconds (default: 5000)").option("--bail <number>", "Stop test execution when given number of tests have failed (default: 0)").option("--retry <times>", "Retry the test specific number of times if it fails (default: 0)").option("--diff <path>", "Path to a diff config that will be used to generate diff interface").option("--exclude <glob>", "Additional file globs to be excluded from test").option("--expand-snapshot-diff", "Show full diff when snapshot fails").option("--disable-console-intercept", "Disable automatic interception of console logging (default: `false`)").option("--typecheck [options]", "Custom options for typecheck pool").option("--typecheck.enabled", "Enable typechecking alongside tests (default: false)").option("--typecheck.only", "Run only typecheck tests. This automatically enables typecheck (default: false)").option("--project <name>", "The name of the project to run if you are using Vitest workspace feature. This can be repeated for multiple projects: --project=1 --project=2").help();
62
- cli.command("run [...filters]").action(run);
63
- cli.command("related [...filters]").action(runRelated);
64
- cli.command("watch [...filters]").action(watch);
65
- cli.command("dev [...filters]").action(watch);
66
- cli.command("bench [...filters]").action(benchmark);
67
- cli.command("typecheck [...filters]").action(() => {
68
- throw new Error(`Running typecheck via "typecheck" command is removed. Please use "--typecheck" to run your regular tests alongside typechecking, or "--typecheck.only" to run only typecheck tests.`);
151
+ for (idx=0; idx < arr.length; idx++) {
152
+ name = arr[idx];
153
+ if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
154
+ toVal(out, name, (idx + 1 < arr.length) || val, opts);
155
+ }
156
+ }
157
+ }
158
+
159
+ if (defaults) {
160
+ for (k in opts.default) {
161
+ if (out[k] === void 0) {
162
+ out[k] = opts.default[k];
163
+ }
164
+ }
165
+ }
166
+
167
+ if (alibi) {
168
+ for (k in out) {
169
+ arr = opts.alias[k] || [];
170
+ while (arr.length > 0) {
171
+ out[arr.shift()] = out[k];
172
+ }
173
+ }
174
+ }
175
+
176
+ return out;
177
+ }
178
+
179
+ const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
180
+ const findAllBrackets = (v) => {
181
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
182
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
183
+ const res = [];
184
+ const parse = (match) => {
185
+ let variadic = false;
186
+ let value = match[1];
187
+ if (value.startsWith("...")) {
188
+ value = value.slice(3);
189
+ variadic = true;
190
+ }
191
+ return {
192
+ required: match[0].startsWith("<"),
193
+ value,
194
+ variadic
195
+ };
196
+ };
197
+ let angledMatch;
198
+ while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
199
+ res.push(parse(angledMatch));
200
+ }
201
+ let squareMatch;
202
+ while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
203
+ res.push(parse(squareMatch));
204
+ }
205
+ return res;
206
+ };
207
+ const getMriOptions = (options) => {
208
+ const result = {alias: {}, boolean: []};
209
+ for (const [index, option] of options.entries()) {
210
+ if (option.names.length > 1) {
211
+ result.alias[option.names[0]] = option.names.slice(1);
212
+ }
213
+ if (option.isBoolean) {
214
+ if (option.negated) {
215
+ const hasStringTypeOption = options.some((o, i) => {
216
+ return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
217
+ });
218
+ if (!hasStringTypeOption) {
219
+ result.boolean.push(option.names[0]);
220
+ }
221
+ } else {
222
+ result.boolean.push(option.names[0]);
223
+ }
224
+ }
225
+ }
226
+ return result;
227
+ };
228
+ const findLongest = (arr) => {
229
+ return arr.sort((a, b) => {
230
+ return a.length > b.length ? -1 : 1;
231
+ })[0];
232
+ };
233
+ const padRight = (str, length) => {
234
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
235
+ };
236
+ const camelcase = (input) => {
237
+ return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
238
+ return p1 + p2.toUpperCase();
239
+ });
240
+ };
241
+ const setDotProp = (obj, keys, val, transforms) => {
242
+ let i = 0;
243
+ let length = keys.length;
244
+ let t = obj;
245
+ let x;
246
+ let convertKey = (i) => {
247
+ let key = keys[i];
248
+ i--;
249
+ while(i >= 0) {
250
+ key = keys[i] + '.' + key;
251
+ i--;
252
+ }
253
+ return key
254
+ };
255
+ for (; i < length; ++i) {
256
+ x = t[keys[i]];
257
+ const transform = transforms[convertKey(i)] || ((v) => v);
258
+ t = t[keys[i]] = transform(i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : []);
259
+ }
260
+ };
261
+ const getFileName = (input) => {
262
+ const m = /([^\\\/]+)$/.exec(input);
263
+ return m ? m[1] : "";
264
+ };
265
+ const camelcaseOptionName = (name) => {
266
+ return name.split(".").map((v, i) => {
267
+ return i === 0 ? camelcase(v) : v;
268
+ }).join(".");
269
+ };
270
+ class CACError extends Error {
271
+ constructor(message) {
272
+ super(message);
273
+ this.name = this.constructor.name;
274
+ if (typeof Error.captureStackTrace === "function") {
275
+ Error.captureStackTrace(this, this.constructor);
276
+ } else {
277
+ this.stack = new Error(message).stack;
278
+ }
279
+ }
280
+ }
281
+
282
+ class Option {
283
+ constructor(rawName, description, config) {
284
+ this.rawName = rawName;
285
+ this.description = description;
286
+ this.config = Object.assign({}, config);
287
+ rawName = rawName.replace(/\.\*/g, "");
288
+ this.negated = false;
289
+ this.names = removeBrackets(rawName).split(",").map((v) => {
290
+ let name = v.trim().replace(/^-{1,2}/, "");
291
+ if (name.startsWith("no-")) {
292
+ this.negated = true;
293
+ name = name.replace(/^no-/, "");
294
+ }
295
+ return camelcaseOptionName(name);
296
+ }).sort((a, b) => a.length > b.length ? 1 : -1);
297
+ this.name = this.names[this.names.length - 1];
298
+ if (this.negated && this.config.default == null) {
299
+ this.config.default = true;
300
+ }
301
+ if (rawName.includes("<")) {
302
+ this.required = true;
303
+ } else if (rawName.includes("[")) {
304
+ this.required = false;
305
+ } else {
306
+ this.isBoolean = true;
307
+ }
308
+ }
309
+ }
310
+
311
+ const processArgs = process.argv;
312
+ const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
313
+
314
+ class Command {
315
+ constructor(rawName, description, config = {}, cli) {
316
+ this.rawName = rawName;
317
+ this.description = description;
318
+ this.config = config;
319
+ this.cli = cli;
320
+ this.options = [];
321
+ this.aliasNames = [];
322
+ this.name = removeBrackets(rawName);
323
+ this.args = findAllBrackets(rawName);
324
+ this.examples = [];
325
+ }
326
+ usage(text) {
327
+ this.usageText = text;
328
+ return this;
329
+ }
330
+ allowUnknownOptions() {
331
+ this.config.allowUnknownOptions = true;
332
+ return this;
333
+ }
334
+ ignoreOptionDefaultValue() {
335
+ this.config.ignoreOptionDefaultValue = true;
336
+ return this;
337
+ }
338
+ version(version, customFlags = "-v, --version") {
339
+ this.versionNumber = version;
340
+ this.option(customFlags, "Display version number");
341
+ return this;
342
+ }
343
+ example(example) {
344
+ this.examples.push(example);
345
+ return this;
346
+ }
347
+ option(rawName, description, config) {
348
+ const option = new Option(rawName, description, config);
349
+ this.options.push(option);
350
+ return this;
351
+ }
352
+ alias(name) {
353
+ this.aliasNames.push(name);
354
+ return this;
355
+ }
356
+ action(callback) {
357
+ this.commandAction = callback;
358
+ return this;
359
+ }
360
+ isMatched(name) {
361
+ return this.name === name || this.aliasNames.includes(name);
362
+ }
363
+ get isDefaultCommand() {
364
+ return this.name === "" || this.aliasNames.includes("!");
365
+ }
366
+ get isGlobalCommand() {
367
+ return this instanceof GlobalCommand;
368
+ }
369
+ hasOption(name) {
370
+ name = name.split(".")[0];
371
+ return this.options.find((option) => {
372
+ return option.names.includes(name);
373
+ });
374
+ }
375
+ outputHelp() {
376
+ const {name, commands} = this.cli;
377
+ const {
378
+ versionNumber,
379
+ options: globalOptions,
380
+ helpCallback
381
+ } = this.cli.globalCommand;
382
+ let sections = [
383
+ {
384
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
385
+ }
386
+ ];
387
+ sections.push({
388
+ title: "Usage",
389
+ body: ` $ ${name} ${this.usageText || this.rawName}`
390
+ });
391
+ const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
392
+ if (showCommands) {
393
+ const longestCommandName = findLongest(commands.map((command) => command.rawName));
394
+ sections.push({
395
+ title: "Commands",
396
+ body: commands.map((command) => {
397
+ return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
398
+ }).join("\n")
399
+ });
400
+ sections.push({
401
+ title: `For more info, run any command with the \`--help\` flag`,
402
+ body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
403
+ });
404
+ }
405
+ let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
406
+ if (!this.isGlobalCommand && !this.isDefaultCommand) {
407
+ options = options.filter((option) => option.name !== "version");
408
+ }
409
+ if (options.length > 0) {
410
+ const longestOptionName = findLongest(options.map((option) => option.rawName));
411
+ sections.push({
412
+ title: "Options",
413
+ body: options.map((option) => {
414
+ return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
415
+ }).join("\n")
416
+ });
417
+ }
418
+ if (this.examples.length > 0) {
419
+ sections.push({
420
+ title: "Examples",
421
+ body: this.examples.map((example) => {
422
+ if (typeof example === "function") {
423
+ return example(name);
424
+ }
425
+ return example;
426
+ }).join("\n")
427
+ });
428
+ }
429
+ if (helpCallback) {
430
+ sections = helpCallback(sections) || sections;
431
+ }
432
+ console.log(sections.map((section) => {
433
+ return section.title ? `${section.title}:
434
+ ${section.body}` : section.body;
435
+ }).join("\n\n"));
436
+ }
437
+ outputVersion() {
438
+ const {name} = this.cli;
439
+ const {versionNumber} = this.cli.globalCommand;
440
+ if (versionNumber) {
441
+ console.log(`${name}/${versionNumber} ${platformInfo}`);
442
+ }
443
+ }
444
+ checkRequiredArgs() {
445
+ const minimalArgsCount = this.args.filter((arg) => arg.required).length;
446
+ if (this.cli.args.length < minimalArgsCount) {
447
+ throw new CACError(`missing required args for command \`${this.rawName}\``);
448
+ }
449
+ }
450
+ checkUnknownOptions() {
451
+ const {options, globalCommand} = this.cli;
452
+ if (!this.config.allowUnknownOptions) {
453
+ for (const name of Object.keys(options)) {
454
+ if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
455
+ throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
456
+ }
457
+ }
458
+ }
459
+ }
460
+ checkOptionValue() {
461
+ const {options: parsedOptions, globalCommand} = this.cli;
462
+ const options = [...globalCommand.options, ...this.options];
463
+ for (const option of options) {
464
+ // skip dot names because only top level options are required
465
+ if (option.name.includes('.')) {
466
+ continue;
467
+ }
468
+ const value = parsedOptions[option.name];
469
+ if (option.required) {
470
+ const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
471
+ if (value === true || value === false && !hasNegated) {
472
+ throw new CACError(`option \`${option.rawName}\` value is missing`);
473
+ }
474
+ }
475
+ }
476
+ }
477
+ }
478
+ class GlobalCommand extends Command {
479
+ constructor(cli) {
480
+ super("@@global@@", "", {}, cli);
481
+ }
482
+ }
483
+
484
+ var __assign = Object.assign;
485
+ class CAC extends EventEmitter {
486
+ constructor(name = "") {
487
+ super();
488
+ this.name = name;
489
+ this.commands = [];
490
+ this.rawArgs = [];
491
+ this.args = [];
492
+ this.options = {};
493
+ this.globalCommand = new GlobalCommand(this);
494
+ this.globalCommand.usage("<command> [options]");
495
+ }
496
+ usage(text) {
497
+ this.globalCommand.usage(text);
498
+ return this;
499
+ }
500
+ command(rawName, description, config) {
501
+ const command = new Command(rawName, description || "", config, this);
502
+ command.globalCommand = this.globalCommand;
503
+ this.commands.push(command);
504
+ return command;
505
+ }
506
+ option(rawName, description, config) {
507
+ this.globalCommand.option(rawName, description, config);
508
+ return this;
509
+ }
510
+ help(callback) {
511
+ this.globalCommand.option("-h, --help", "Display this message");
512
+ this.globalCommand.helpCallback = callback;
513
+ this.showHelpOnExit = true;
514
+ return this;
515
+ }
516
+ version(version, customFlags = "-v, --version") {
517
+ this.globalCommand.version(version, customFlags);
518
+ this.showVersionOnExit = true;
519
+ return this;
520
+ }
521
+ example(example) {
522
+ this.globalCommand.example(example);
523
+ return this;
524
+ }
525
+ outputHelp() {
526
+ if (this.matchedCommand) {
527
+ this.matchedCommand.outputHelp();
528
+ } else {
529
+ this.globalCommand.outputHelp();
530
+ }
531
+ }
532
+ outputVersion() {
533
+ this.globalCommand.outputVersion();
534
+ }
535
+ setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
536
+ this.args = args;
537
+ this.options = options;
538
+ if (matchedCommand) {
539
+ this.matchedCommand = matchedCommand;
540
+ }
541
+ if (matchedCommandName) {
542
+ this.matchedCommandName = matchedCommandName;
543
+ }
544
+ return this;
545
+ }
546
+ unsetMatchedCommand() {
547
+ this.matchedCommand = void 0;
548
+ this.matchedCommandName = void 0;
549
+ }
550
+ parse(argv = processArgs, {
551
+ run = true
552
+ } = {}) {
553
+ this.rawArgs = argv;
554
+ if (!this.name) {
555
+ this.name = argv[1] ? getFileName(argv[1]) : "cli";
556
+ }
557
+ let shouldParse = true;
558
+ for (const command of this.commands) {
559
+ const parsed = this.mri(argv.slice(2), command);
560
+ const commandName = parsed.args[0];
561
+ if (command.isMatched(commandName)) {
562
+ shouldParse = false;
563
+ const parsedInfo = __assign(__assign({}, parsed), {
564
+ args: parsed.args.slice(1)
565
+ });
566
+ this.setParsedInfo(parsedInfo, command, commandName);
567
+ this.emit(`command:${commandName}`, command);
568
+ }
569
+ }
570
+ if (shouldParse) {
571
+ for (const command of this.commands) {
572
+ if (command.name === "") {
573
+ shouldParse = false;
574
+ const parsed = this.mri(argv.slice(2), command);
575
+ this.setParsedInfo(parsed, command);
576
+ this.emit(`command:!`, command);
577
+ }
578
+ }
579
+ }
580
+ if (shouldParse) {
581
+ const parsed = this.mri(argv.slice(2));
582
+ this.setParsedInfo(parsed);
583
+ }
584
+ if (this.options.help && this.showHelpOnExit) {
585
+ this.outputHelp();
586
+ run = false;
587
+ this.unsetMatchedCommand();
588
+ }
589
+ if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
590
+ this.outputVersion();
591
+ run = false;
592
+ this.unsetMatchedCommand();
593
+ }
594
+ const parsedArgv = {args: this.args, options: this.options};
595
+ if (run) {
596
+ this.runMatchedCommand();
597
+ }
598
+ if (!this.matchedCommand && this.args[0]) {
599
+ this.emit("command:*");
600
+ }
601
+ return parsedArgv;
602
+ }
603
+ mri(argv, command) {
604
+ const cliOptions = [
605
+ ...this.globalCommand.options,
606
+ ...command ? command.options : []
607
+ ];
608
+ const mriOptions = getMriOptions(cliOptions);
609
+ let argsAfterDoubleDashes = [];
610
+ const doubleDashesIndex = argv.indexOf("--");
611
+ if (doubleDashesIndex > -1) {
612
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
613
+ argv = argv.slice(0, doubleDashesIndex);
614
+ }
615
+ let parsed = mri2(argv, mriOptions);
616
+ parsed = Object.keys(parsed).reduce((res, name) => {
617
+ return __assign(__assign({}, res), {
618
+ [camelcaseOptionName(name)]: parsed[name]
619
+ });
620
+ }, {_: []});
621
+ const args = parsed._;
622
+ const options = {
623
+ "--": argsAfterDoubleDashes
624
+ };
625
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
626
+ let transforms = Object.create(null);
627
+ for (const cliOption of cliOptions) {
628
+ if (!ignoreDefault && cliOption.config.default !== void 0) {
629
+ for (const name of cliOption.names) {
630
+ options[name] = cliOption.config.default;
631
+ }
632
+ }
633
+ if (cliOption.config.type != null) {
634
+ if (transforms[cliOption.name] === void 0) {
635
+ transforms[cliOption.name] = cliOption.config.type;
636
+ }
637
+ }
638
+ }
639
+ for (const key of Object.keys(parsed)) {
640
+ if (key !== "_") {
641
+ const keys = key.split(".");
642
+ setDotProp(options, keys, parsed[key], transforms);
643
+ // setByType(options, transforms);
644
+ }
645
+ }
646
+ return {
647
+ args,
648
+ options
649
+ };
650
+ }
651
+ runMatchedCommand() {
652
+ const {args, options, matchedCommand: command} = this;
653
+ if (!command || !command.commandAction)
654
+ return;
655
+ command.checkUnknownOptions();
656
+ command.checkOptionValue();
657
+ command.checkRequiredArgs();
658
+ const actionArgs = [];
659
+ command.args.forEach((arg, index) => {
660
+ if (arg.variadic) {
661
+ actionArgs.push(args.slice(index));
662
+ } else {
663
+ actionArgs.push(args[index]);
664
+ }
665
+ });
666
+ actionArgs.push(options);
667
+ return command.commandAction.apply(this, actionArgs);
668
+ }
669
+ }
670
+
671
+ const cac = (name = "") => new CAC(name);
672
+
673
+ const apiConfig = (port) => ({
674
+ port: {
675
+ description: `Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. If true will be set to ${port}`,
676
+ argument: "[port]"
677
+ },
678
+ host: {
679
+ description: "Specify which IP addresses the server should listen on. Set this to 0.0.0.0 or true to listen on all addresses, including LAN and public addresses",
680
+ argument: "[host]"
681
+ },
682
+ strictPort: {
683
+ description: "Set to true to exit if port is already in use, instead of automatically trying the next available port"
684
+ },
685
+ middlewareMode: null
69
686
  });
70
- cli.command("[...filters]").action((filters, options) => start("test", filters, options));
71
- try {
72
- cli.parse();
73
- } catch (originalError) {
74
- const fullArguments = cli.rawArgs.join(" ");
75
- const conflictingArgs = [];
76
- for (const arg of cli.rawArgs) {
77
- if (arg.startsWith("--") && !arg.includes(".") && fullArguments.includes(`${arg}.`)) {
78
- const dotArgs = cli.rawArgs.filter((rawArg) => rawArg.startsWith(arg) && rawArg.includes("."));
79
- conflictingArgs.push({ arg, dotArgs });
80
- }
81
- }
82
- if (conflictingArgs.length === 0)
83
- throw originalError;
84
- const error = conflictingArgs.map(({ arg, dotArgs }) => `A boolean argument "${arg}" was used with dot notation arguments "${dotArgs.join(" ")}".
85
- Please specify the "${arg}" argument with dot notation as well: "${arg}.enabled"`).join("\n");
86
- throw new Error(error);
687
+ const poolThreadsCommands = {
688
+ isolate: {
689
+ description: "Isolate tests in threads pool (default: true)"
690
+ },
691
+ singleThread: {
692
+ description: "Run tests inside a single thread (default: false)"
693
+ },
694
+ maxThreads: {
695
+ description: "Maximum number of threads to run tests in",
696
+ argument: "<workers>"
697
+ },
698
+ minThreads: {
699
+ description: "Minimum number of threads to run tests in",
700
+ argument: "<workers>"
701
+ },
702
+ useAtomics: {
703
+ description: "Use Atomics to synchronize threads. This can improve performance in some cases, but might cause segfault in older Node versions (default: false)"
704
+ },
705
+ execArgv: null
706
+ };
707
+ const poolForksCommands = {
708
+ isolate: {
709
+ description: "Isolate tests in threads pool (default: true)"
710
+ },
711
+ singleFork: {
712
+ description: "Run tests inside a single child_process (default: false)"
713
+ },
714
+ maxForks: {
715
+ description: "Maximum number of processes to run tests in",
716
+ argument: "<workers>"
717
+ },
718
+ minForks: {
719
+ description: "Minimum number of processes to run tests in",
720
+ argument: "<workers>"
721
+ },
722
+ execArgv: null
723
+ };
724
+ function watermarkTransform(value) {
725
+ if (typeof value === "string")
726
+ return value.split(",").map(Number);
727
+ return value;
728
+ }
729
+ function transformNestedBoolean(value) {
730
+ if (typeof value === "boolean")
731
+ return { enabled: value };
732
+ return value;
733
+ }
734
+ const cliOptionsConfig = {
735
+ root: {
736
+ description: "Root path",
737
+ shorthand: "r",
738
+ argument: "<path>",
739
+ normalize: true
740
+ },
741
+ config: {
742
+ shorthand: "c",
743
+ description: "Path to config file",
744
+ argument: "<path>",
745
+ normalize: true
746
+ },
747
+ update: {
748
+ shorthand: "u",
749
+ description: "Update snapshot"
750
+ },
751
+ watch: {
752
+ shorthand: "w",
753
+ description: "Enable watch mode"
754
+ },
755
+ testNamePattern: {
756
+ description: "Run tests with full names matching the specified regexp pattern",
757
+ argument: "<pattern>",
758
+ shorthand: "t"
759
+ },
760
+ dir: {
761
+ description: "Base directory to scan for the test files",
762
+ argument: "<path>",
763
+ normalize: true
764
+ },
765
+ ui: {
766
+ description: "Enable UI"
767
+ },
768
+ open: {
769
+ description: "Open UI automatically (default: !process.env.CI)"
770
+ },
771
+ api: {
772
+ argument: "[port]",
773
+ description: `Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. If true will be set to ${defaultPort}`,
774
+ subcommands: apiConfig(defaultPort)
775
+ },
776
+ silent: {
777
+ description: "Silent console output from tests"
778
+ },
779
+ hideSkippedTests: {
780
+ description: "Hide logs for skipped tests"
781
+ },
782
+ reporters: {
783
+ alias: "reporter",
784
+ description: "Specify reporters",
785
+ argument: "<name>",
786
+ subcommands: null,
787
+ // don't support custom objects
788
+ array: true
789
+ },
790
+ outputFile: {
791
+ argument: "<filename/-s>",
792
+ description: "Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters (example: --outputFile.tap=./tap.txt)",
793
+ subcommands: null
794
+ },
795
+ coverage: {
796
+ description: "Enable coverage report",
797
+ argument: "",
798
+ // empty string means boolean
799
+ transform: transformNestedBoolean,
800
+ subcommands: {
801
+ all: {
802
+ description: "Whether to include all files, including the untested ones into report",
803
+ default: true
804
+ },
805
+ provider: {
806
+ description: 'Select the tool for coverage collection, available values are: "v8", "istanbul" and "custom"',
807
+ argument: "<name>"
808
+ },
809
+ enabled: {
810
+ description: "Enables coverage collection. Can be overridden using the --coverage CLI option (default: false)"
811
+ },
812
+ include: {
813
+ description: "Files included in coverage as glob patterns. May be specified more than once when using multiple patterns (default: **)",
814
+ argument: "<pattern>",
815
+ array: true
816
+ },
817
+ exclude: {
818
+ description: "Files to be excluded in coverage. May be specified more than once when using multiple extensions (default: Visit https://vitest.dev/config/#coverage-exclude)",
819
+ argument: "<pattern>",
820
+ array: true
821
+ },
822
+ extension: {
823
+ description: 'Extension to be included in coverage. May be specified more than once when using multiple extensions (default: [".js", ".cjs", ".mjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".vue", ".svelte"])',
824
+ argument: "<extension>",
825
+ array: true
826
+ },
827
+ clean: {
828
+ description: "Clean coverage results before running tests (default: true)"
829
+ },
830
+ cleanOnRerun: {
831
+ description: "Clean coverage report on watch rerun (default: true)"
832
+ },
833
+ reportsDirectory: {
834
+ description: "Directory to write coverage report to (default: ./coverage)",
835
+ argument: "<path>",
836
+ normalize: true
837
+ },
838
+ reporter: {
839
+ description: 'Coverage reporters to use. Visit https://vitest.dev/config/#coverage-reporter for more information (default: ["text", "html", "clover", "json"])',
840
+ argument: "<name>",
841
+ subcommands: null,
842
+ // don't support custom objects
843
+ array: true
844
+ },
845
+ reportOnFailure: {
846
+ description: "Generate coverage report even when tests fail (default: false)"
847
+ },
848
+ allowExternal: {
849
+ description: "Collect coverage of files outside the project root (default: false)"
850
+ },
851
+ skipFull: {
852
+ description: "Do not show files with 100% statement, branch, and function coverage (default: false)"
853
+ },
854
+ thresholds: {
855
+ description: null,
856
+ argument: "",
857
+ // no displayed
858
+ subcommands: {
859
+ perFile: {
860
+ description: "Check thresholds per file. See --coverage.thresholds.lines, --coverage.thresholds.functions, --coverage.thresholds.branches and --coverage.thresholds.statements for the actual thresholds (default: false)"
861
+ },
862
+ autoUpdate: {
863
+ description: 'Update threshold values: "lines", "functions", "branches" and "statements" to configuration file when current coverage is above the configured thresholds (default: false)'
864
+ },
865
+ lines: {
866
+ description: "Threshold for lines. Visit https://github.com/istanbuljs/nyc#coverage-thresholds for more information. This option is not available for custom providers",
867
+ argument: "<number>"
868
+ },
869
+ functions: {
870
+ description: "Threshold for functions. Visit https://github.com/istanbuljs/nyc#coverage-thresholds for more information. This option is not available for custom providers",
871
+ argument: "<number>"
872
+ },
873
+ branches: {
874
+ description: "Threshold for branches. Visit https://github.com/istanbuljs/nyc#coverage-thresholds for more information. This option is not available for custom providers",
875
+ argument: "<number>"
876
+ },
877
+ statements: {
878
+ description: "Threshold for statements. Visit https://github.com/istanbuljs/nyc#coverage-thresholds for more information. This option is not available for custom providers",
879
+ argument: "<number>"
880
+ },
881
+ 100: {
882
+ description: "Shortcut to set all coverage thresholds to 100 (default: false)"
883
+ }
884
+ }
885
+ },
886
+ ignoreClassMethods: {
887
+ description: "Array of class method names to ignore for coverage. Visit https://github.com/istanbuljs/nyc#ignoring-methods for more information. This option is only available for the istanbul providers (default: [])",
888
+ argument: "<name>",
889
+ array: true
890
+ },
891
+ processingConcurrency: {
892
+ description: "Concurrency limit used when processing the coverage results. (default min between 20 and the number of CPUs)",
893
+ argument: "<number>"
894
+ },
895
+ customProviderModule: {
896
+ description: "Specifies the module name or path for the custom coverage provider module. Visit https://vitest.dev/guide/coverage.html#custom-coverage-provider for more information. This option is only available for custom providers",
897
+ argument: "<path>",
898
+ normalize: true
899
+ },
900
+ watermarks: {
901
+ description: null,
902
+ argument: "",
903
+ // no displayed
904
+ subcommands: {
905
+ statements: {
906
+ description: "High and low watermarks for statements in the format of <high>,<low>",
907
+ argument: "<watermarks>",
908
+ transform: watermarkTransform
909
+ },
910
+ lines: {
911
+ description: "High and low watermarks for lines in the format of <high>,<low>",
912
+ argument: "<watermarks>",
913
+ transform: watermarkTransform
914
+ },
915
+ branches: {
916
+ description: "High and low watermarks for branches in the format of <high>,<low>",
917
+ argument: "<watermarks>",
918
+ transform: watermarkTransform
919
+ },
920
+ functions: {
921
+ description: "High and low watermarks for functions in the format of <high>,<low>",
922
+ argument: "<watermarks>",
923
+ transform: watermarkTransform
924
+ }
925
+ }
926
+ }
927
+ }
928
+ },
929
+ mode: {
930
+ description: "Override Vite mode (default: test or benchmark)",
931
+ argument: "<name>"
932
+ },
933
+ workspace: {
934
+ description: "Path to a workspace configuration file",
935
+ argument: "<path>",
936
+ normalize: true
937
+ },
938
+ isolate: {
939
+ description: "Run every test file in isolation. To disable isolation, use --no-isolate (default: true)"
940
+ },
941
+ globals: {
942
+ description: "Inject apis globally"
943
+ },
944
+ dom: {
945
+ description: "Mock browser API with happy-dom"
946
+ },
947
+ browser: {
948
+ description: "Run tests in the browser. Equivalent to --browser.enabled (default: false)",
949
+ argument: "<name>",
950
+ transform(browser) {
951
+ if (typeof browser === "boolean")
952
+ return { enabled: browser };
953
+ if (browser === "true" || browser === "false")
954
+ return { enabled: browser !== "false" };
955
+ if (typeof browser === "string")
956
+ return { enabled: true, name: browser };
957
+ return browser;
958
+ },
959
+ subcommands: {
960
+ enabled: {
961
+ description: "Run tests in the browser. Equivalent to --browser.enabled (default: false)"
962
+ },
963
+ name: {
964
+ description: "Run all tests in a specific browser. Some browsers are only available for specific providers (see --browser.provider). Visit https://vitest.dev/config/#browser-name for more information",
965
+ argument: "<name>"
966
+ },
967
+ headless: {
968
+ description: "Run the browser in headless mode (i.e. without opening the GUI (Graphical User Interface)). If you are running Vitest in CI, it will be enabled by default (default: process.env.CI)"
969
+ },
970
+ api: {
971
+ description: "Specify options for the browser API server. Does not affect the --api option",
972
+ argument: "[port]",
973
+ subcommands: apiConfig(defaultBrowserPort)
974
+ },
975
+ provider: {
976
+ description: 'Provider used to run browser tests. Some browsers are only available for specific providers. Can be "webdriverio", "playwright", or the path to a custom provider. Visit https://vitest.dev/config/#browser-provider for more information (default: "webdriverio")',
977
+ argument: "<name>",
978
+ subcommands: null
979
+ // don't support custom objects
980
+ },
981
+ providerOptions: {
982
+ description: "Options that are passed down to a browser provider. Visit https://vitest.dev/config/#browser-provideroptions-1-0-0 for more information",
983
+ argument: "<options>",
984
+ subcommands: null
985
+ // don't support custom objects
986
+ },
987
+ slowHijackESM: {
988
+ description: "Let Vitest use its own module resolution on the browser to enable APIs such as vi.mock and vi.spyOn. Visit https://vitest.dev/config/#browser-slowhijackesm for more information (default: false)"
989
+ },
990
+ isolate: {
991
+ description: "Run every browser test file in isolation. To disable isolation, use --browser.isolate=false (default: true)"
992
+ },
993
+ fileParallelism: {
994
+ description: "Should all test files run in parallel. Use --browser.file-parallelism=false to disable (default: same as --file-parallelism)"
995
+ }
996
+ }
997
+ },
998
+ pool: {
999
+ description: "Specify pool, if not running in the browser (default: threads)",
1000
+ argument: "<pool>",
1001
+ subcommands: null
1002
+ // don't support custom objects
1003
+ },
1004
+ poolOptions: {
1005
+ description: "Specify pool options",
1006
+ argument: "<options>",
1007
+ // we use casting here because TypeScript (for some reason) makes this into CLIOption<unknown>
1008
+ // even when using casting, these types fail if the new option is added which is good
1009
+ subcommands: {
1010
+ threads: {
1011
+ description: "Specify threads pool options",
1012
+ argument: "<options>",
1013
+ subcommands: poolThreadsCommands
1014
+ },
1015
+ vmThreads: {
1016
+ description: "Specify VM threads pool options",
1017
+ argument: "<options>",
1018
+ subcommands: {
1019
+ ...poolThreadsCommands,
1020
+ memoryLimit: {
1021
+ description: "Memory limit for VM threads pool. If you see memory leaks, try to tinker this value.",
1022
+ argument: "<limit>"
1023
+ }
1024
+ }
1025
+ },
1026
+ forks: {
1027
+ description: "Specify forks pool options",
1028
+ argument: "<options>",
1029
+ subcommands: poolForksCommands
1030
+ },
1031
+ vmForks: {
1032
+ description: "Specify VM forks pool options",
1033
+ argument: "<options>",
1034
+ subcommands: {
1035
+ ...poolForksCommands,
1036
+ memoryLimit: {
1037
+ description: "Memory limit for VM forks pool. If you see memory leaks, try to tinker this value.",
1038
+ argument: "<limit>"
1039
+ }
1040
+ }
1041
+ }
1042
+ }
1043
+ },
1044
+ fileParallelism: {
1045
+ description: "Should all test files run in parallel. Use --no-file-parallelism to disable (default: true)"
1046
+ },
1047
+ maxWorkers: {
1048
+ description: "Maximum number of workers to run tests in",
1049
+ argument: "<workers>"
1050
+ },
1051
+ minWorkers: {
1052
+ description: "Minimum number of workers to run tests in",
1053
+ argument: "<workers>"
1054
+ },
1055
+ environment: {
1056
+ description: "Specify runner environment, if not running in the browser (default: node)",
1057
+ argument: "<name>",
1058
+ subcommands: null
1059
+ // don't support custom objects
1060
+ },
1061
+ passWithNoTests: {
1062
+ description: "Pass when no tests are found"
1063
+ },
1064
+ logHeapUsage: {
1065
+ description: "Show the size of heap for each test when running in node"
1066
+ },
1067
+ allowOnly: {
1068
+ description: "Allow tests and suites that are marked as only (default: !process.env.CI)"
1069
+ },
1070
+ dangerouslyIgnoreUnhandledErrors: {
1071
+ description: "Ignore any unhandled errors that occur"
1072
+ },
1073
+ shard: {
1074
+ description: "Test suite shard to execute in a format of <index>/<count>",
1075
+ argument: "<shards>"
1076
+ },
1077
+ changed: {
1078
+ description: "Run tests that are affected by the changed files (default: false)",
1079
+ argument: "[since]"
1080
+ },
1081
+ sequence: {
1082
+ description: "Options for how tests should be sorted",
1083
+ argument: "<options>",
1084
+ subcommands: {
1085
+ shuffle: {
1086
+ description: "Run tests in a random order. Enabling this option will impact Vitest's cache and have a performance impact. May be useful to find tests that accidentally depend on another run previously (default: false)"
1087
+ },
1088
+ concurrent: {
1089
+ description: "Make tests run in parallel (default: false)"
1090
+ },
1091
+ seed: {
1092
+ description: "Set the randomization seed. This option will have no effect if --sequence.shuffle is falsy. Visit https://en.wikipedia.org/wiki/Random_seed for more information",
1093
+ argument: "<seed>"
1094
+ },
1095
+ hooks: {
1096
+ description: 'Changes the order in which hooks are executed. Accepted values are: "stack", "list" and "parallel". Visit https://vitest.dev/config/#sequence-hooks for more information (default: "parallel")',
1097
+ argument: "<order>"
1098
+ },
1099
+ setupFiles: {
1100
+ description: 'Changes the order in which setup files are executed. Accepted values are: "list" and "parallel". If set to "list", will run setup files in the order they are defined. If set to "parallel", will run setup files in parallel (default: "parallel")',
1101
+ argument: "<order>"
1102
+ }
1103
+ }
1104
+ },
1105
+ inspect: {
1106
+ description: "Enable Node.js inspector"
1107
+ },
1108
+ inspectBrk: {
1109
+ description: "Enable Node.js inspector with break"
1110
+ },
1111
+ testTimeout: {
1112
+ description: "Default timeout of a test in milliseconds (default: 5000)",
1113
+ argument: "<timeout>"
1114
+ },
1115
+ hookTimeout: {
1116
+ description: "Default hook timeout in milliseconds (default: 10000)",
1117
+ argument: "<timeout>"
1118
+ },
1119
+ bail: {
1120
+ description: "Stop test execution when given number of tests have failed (default: 0)",
1121
+ argument: "<number>"
1122
+ },
1123
+ retry: {
1124
+ description: "Retry the test specific number of times if it fails (default: 0)",
1125
+ argument: "<times>"
1126
+ },
1127
+ diff: {
1128
+ description: "Path to a diff config that will be used to generate diff interface",
1129
+ argument: "<path>",
1130
+ normalize: true
1131
+ },
1132
+ exclude: {
1133
+ description: "Additional file globs to be excluded from test",
1134
+ argument: "<glob>"
1135
+ },
1136
+ expandSnapshotDiff: {
1137
+ description: "Show full diff when snapshot fails"
1138
+ },
1139
+ disableConsoleIntercept: {
1140
+ description: "Disable automatic interception of console logging (default: false)"
1141
+ },
1142
+ typecheck: {
1143
+ description: "Enable typechecking alongside tests (default: false)",
1144
+ argument: "",
1145
+ // allow boolean
1146
+ transform: transformNestedBoolean,
1147
+ subcommands: {
1148
+ enabled: {
1149
+ description: "Enable typechecking alongside tests (default: false)"
1150
+ },
1151
+ only: {
1152
+ description: "Run only typecheck tests. This automatically enables typecheck (default: false)"
1153
+ },
1154
+ checker: {
1155
+ description: 'Specify the typechecker to use. Available values are: "tcs" and "vue-tsc" and a path to an executable (default: "tsc")',
1156
+ argument: "<name>",
1157
+ subcommands: null
1158
+ },
1159
+ allowJs: {
1160
+ description: "Allow JavaScript files to be typechecked. By default takes the value from tsconfig.json"
1161
+ },
1162
+ ignoreSourceErrors: {
1163
+ description: "Ignore type errors from source files"
1164
+ },
1165
+ tsconfig: {
1166
+ description: "Path to a custom tsconfig file",
1167
+ argument: "<path>",
1168
+ normalize: true
1169
+ },
1170
+ include: null,
1171
+ exclude: null
1172
+ }
1173
+ },
1174
+ project: {
1175
+ description: "The name of the project to run if you are using Vitest workspace feature. This can be repeated for multiple projects: --project=1 --project=2",
1176
+ argument: "<name>"
1177
+ },
1178
+ slowTestThreshold: {
1179
+ description: "Threshold in milliseconds for a test to be considered slow (default: 300)",
1180
+ argument: "<threshold>"
1181
+ },
1182
+ teardownTimeout: {
1183
+ description: "Default timeout of a teardown function in milliseconds (default: 10000)",
1184
+ argument: "<timeout>"
1185
+ },
1186
+ cache: {
1187
+ description: "Enable cache",
1188
+ argument: "",
1189
+ // allow only boolean
1190
+ subcommands: {
1191
+ dir: {
1192
+ description: "Path to the cache directory",
1193
+ argument: "<path>",
1194
+ normalize: true
1195
+ }
1196
+ },
1197
+ // cache can only be "false" or an object
1198
+ transform(cache) {
1199
+ if (cache)
1200
+ return {};
1201
+ return cache;
1202
+ }
1203
+ },
1204
+ maxConcurrency: {
1205
+ description: "Maximum number of concurrent tests in a suite (default: 5)",
1206
+ argument: "<number>"
1207
+ },
1208
+ // CLI only options
1209
+ run: {
1210
+ description: "Disable watch mode"
1211
+ },
1212
+ segfaultRetry: {
1213
+ description: "Retry the test suite if it crashes due to a segfault (default: true)",
1214
+ argument: "<times>",
1215
+ default: 0
1216
+ },
1217
+ color: {
1218
+ description: "Removes colors from the console output",
1219
+ alias: "no-color"
1220
+ },
1221
+ // disable CLI options
1222
+ cliExclude: null,
1223
+ server: null,
1224
+ setupFiles: null,
1225
+ globalSetup: null,
1226
+ snapshotFormat: null,
1227
+ snapshotSerializers: null,
1228
+ includeSource: null,
1229
+ watchExclude: null,
1230
+ alias: null,
1231
+ env: null,
1232
+ environmentMatchGlobs: null,
1233
+ environmentOptions: null,
1234
+ unstubEnvs: null,
1235
+ related: null,
1236
+ restoreMocks: null,
1237
+ runner: null,
1238
+ mockReset: null,
1239
+ forceRerunTriggers: null,
1240
+ unstubGlobals: null,
1241
+ uiBase: null,
1242
+ benchmark: null,
1243
+ include: null,
1244
+ testTransformMode: null,
1245
+ fakeTimers: null,
1246
+ chaiConfig: null,
1247
+ clearMocks: null,
1248
+ css: null,
1249
+ poolMatchGlobs: null,
1250
+ deps: null,
1251
+ name: null
1252
+ };
1253
+
1254
+ function addCommand(cli, name, option) {
1255
+ const commandName = option.alias || name;
1256
+ let command = option.shorthand ? `-${option.shorthand}, --${commandName}` : `--${commandName}`;
1257
+ if ("argument" in option)
1258
+ command += ` ${option.argument}`;
1259
+ function transform(value) {
1260
+ if (!option.array && Array.isArray(value)) {
1261
+ const received = value.map((s) => typeof s === "string" ? `"${s}"` : s).join(", ");
1262
+ throw new Error(
1263
+ `Expected a single value for option "${command}", received [${received}]`
1264
+ );
1265
+ }
1266
+ if (option.transform)
1267
+ return option.transform(value);
1268
+ if (option.array)
1269
+ return toArray(value);
1270
+ if (option.normalize)
1271
+ return normalize(String(value));
1272
+ return value;
1273
+ }
1274
+ const hasSubcommands = "subcommands" in option && option.subcommands;
1275
+ if (option.description) {
1276
+ let description = option.description;
1277
+ if (hasSubcommands)
1278
+ description += `. Use '--help --${commandName}' for more info.`;
1279
+ cli.option(command, description, {
1280
+ type: transform
1281
+ });
1282
+ }
1283
+ if (hasSubcommands) {
1284
+ for (const commandName2 in option.subcommands) {
1285
+ const subcommand = option.subcommands[commandName2];
1286
+ if (subcommand)
1287
+ addCommand(cli, `${name}.${commandName2}`, subcommand);
1288
+ }
1289
+ }
1290
+ }
1291
+ function createCLI() {
1292
+ const cli = cac("vitest");
1293
+ cli.version(version);
1294
+ for (const optionName in cliOptionsConfig) {
1295
+ const option = cliOptionsConfig[optionName];
1296
+ if (option)
1297
+ addCommand(cli, optionName, option);
1298
+ }
1299
+ cli.help((info) => {
1300
+ const helpSection = info.find((current) => {
1301
+ var _a;
1302
+ return (_a = current.title) == null ? void 0 : _a.startsWith("For more info, run any command");
1303
+ });
1304
+ if (helpSection)
1305
+ helpSection.body += "\n $ vitest --help --expand-help";
1306
+ const options = info.find((current) => current.title === "Options");
1307
+ if (typeof options !== "object")
1308
+ return info;
1309
+ const helpIndex = process.argv.findIndex((arg) => arg === "--help");
1310
+ const subcommands = process.argv.slice(helpIndex + 1);
1311
+ const defaultOutput = options.body.split("\n").filter((line) => /^\s+--\S+\./.test(line) === false).join("\n");
1312
+ if (subcommands.length === 0) {
1313
+ options.body = defaultOutput;
1314
+ return info;
1315
+ }
1316
+ if (subcommands.length === 1 && (subcommands[0] === "--expand-help" || subcommands[0] === "--expandHelp"))
1317
+ return info;
1318
+ const subcommandMarker = "$SUB_COMMAND_MARKER$";
1319
+ const banner = info.find((current) => /^vitest\/[0-9]+\.[0-9]+\.[0-9]+$/.test(current.body));
1320
+ function addBannerWarning(warning) {
1321
+ if (typeof (banner == null ? void 0 : banner.body) === "string") {
1322
+ if (banner == null ? void 0 : banner.body.includes(warning))
1323
+ return;
1324
+ banner.body = `${banner.body}
1325
+ WARN: ${warning}`;
1326
+ }
1327
+ }
1328
+ for (let i = 0; i < subcommands.length; i++) {
1329
+ const subcommand = subcommands[i];
1330
+ if (subcommand === "--expand-help" || subcommand === "--expandHelp") {
1331
+ addBannerWarning("--expand-help subcommand ignored because, when used with --help, it must be the only subcommand");
1332
+ continue;
1333
+ }
1334
+ if (subcommand.startsWith("--")) {
1335
+ options.body = options.body.split("\n").map((line) => line.trim().startsWith(subcommand) ? `${subcommandMarker}${line}` : line).join("\n");
1336
+ }
1337
+ }
1338
+ options.body = options.body.split("\n").map((line) => line.startsWith(subcommandMarker) ? line.split(subcommandMarker)[1] : "").filter((line) => line.length !== 0).join("\n");
1339
+ if (!options.body) {
1340
+ addBannerWarning("no options were found for your subcommands so we printed the whole output");
1341
+ options.body = defaultOutput;
1342
+ }
1343
+ return info;
1344
+ });
1345
+ cli.command("run [...filters]").action(run);
1346
+ cli.command("related [...filters]").action(runRelated);
1347
+ cli.command("watch [...filters]").action(watch);
1348
+ cli.command("dev [...filters]").action(watch);
1349
+ cli.command("bench [...filters]").action(benchmark);
1350
+ cli.command("typecheck [...filters]").action(() => {
1351
+ throw new Error(`Running typecheck via "typecheck" command is removed. Please use "--typecheck" to run your regular tests alongside typechecking, or "--typecheck.only" to run only typecheck tests.`);
1352
+ });
1353
+ cli.command("[...filters]").action((filters, options) => start("test", filters, options));
1354
+ return cli;
87
1355
  }
88
1356
  async function runRelated(relatedFiles, argv) {
89
1357
  argv.related = relatedFiles;
@@ -103,35 +1371,10 @@ async function benchmark(cliFilters, options) {
103
1371
  await start("benchmark", cliFilters, options);
104
1372
  }
105
1373
  function normalizeCliOptions(argv) {
106
- if (argv.root)
107
- argv.root = normalize(argv.root);
108
- else
109
- delete argv.root;
110
- if (argv.config)
111
- argv.config = normalize(argv.config);
112
- else
113
- delete argv.config;
114
- if (argv.workspace)
115
- argv.workspace = normalize(argv.workspace);
116
- else
117
- delete argv.workspace;
118
- if (argv.dir)
119
- argv.dir = normalize(argv.dir);
120
- else
121
- delete argv.dir;
122
1374
  if (argv.exclude) {
123
1375
  argv.cliExclude = toArray(argv.exclude);
124
1376
  delete argv.exclude;
125
1377
  }
126
- if (argv.coverage) {
127
- const coverage = argv.coverage;
128
- if (coverage.exclude)
129
- coverage.exclude = toArray(coverage.exclude);
130
- if (coverage.include)
131
- coverage.include = toArray(coverage.include);
132
- if (coverage.ignoreClassMethods)
133
- coverage.ignoreClassMethods = toArray(coverage.ignoreClassMethods);
134
- }
135
1378
  return argv;
136
1379
  }
137
1380
  async function start(mode, cliFilters, options) {
@@ -152,3 +1395,5 @@ ${c.red(divider(c.bold(c.inverse(" Unhandled Error "))))}`);
152
1395
  process.exit(1);
153
1396
  }
154
1397
  }
1398
+
1399
+ createCLI().parse();