vitest 2.0.0-beta.1 → 2.0.0-beta.10

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 (52) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/browser.d.ts +22 -2
  3. package/dist/browser.js +3 -1
  4. package/dist/chunks/{integrations-globals.B5Jl0grA.js → integrations-globals.C6Ah-pUW.js} +3 -3
  5. package/dist/chunks/{runtime-console.CUES-L8X.js → runtime-console.DiVMr5d4.js} +54 -24
  6. package/dist/chunks/{runtime-runBaseTests._dXkRAZc.js → runtime-runBaseTests.Cukyr5-I.js} +5 -5
  7. package/dist/cli.js +2 -2
  8. package/dist/config.cjs +3 -3
  9. package/dist/config.d.ts +2 -2
  10. package/dist/config.js +3 -3
  11. package/dist/coverage.d.ts +1 -1
  12. package/dist/coverage.js +33 -7
  13. package/dist/environments.d.ts +1 -1
  14. package/dist/environments.js +1 -1
  15. package/dist/execute.d.ts +2 -2
  16. package/dist/execute.js +1 -1
  17. package/dist/index.d.ts +11 -47
  18. package/dist/index.js +3 -3
  19. package/dist/node.d.ts +7 -7
  20. package/dist/node.js +12 -10
  21. package/dist/{reporters-MGvT5U9f.d.ts → reporters-CYVC6LOl.d.ts} +424 -201
  22. package/dist/reporters.d.ts +1 -1
  23. package/dist/reporters.js +4 -4
  24. package/dist/runners.d.ts +4 -2
  25. package/dist/runners.js +9 -1
  26. package/dist/{suite-8WAe-urM.d.ts → suite-Dpu9EC_k.d.ts} +1 -1
  27. package/dist/suite.d.ts +2 -2
  28. package/dist/vendor/{base.VFkIJ66g.js → base.Dln9yllP.js} +2 -2
  29. package/dist/vendor/{cac.DzKZaJu2.js → cac.CtYFkoSJ.js} +65 -23
  30. package/dist/vendor/{cli-api.DTeni0Qq.js → cli-api.CUtJc4r3.js} +2425 -549
  31. package/dist/vendor/{constants.5SOfHUj0.js → constants.TCjCaw2D.js} +4 -3
  32. package/dist/vendor/{execute.CLLNVNnK.js → execute.BHj6OMh4.js} +3 -3
  33. package/dist/vendor/{index.BfoZyXD1.js → index.B5SKBLvV.js} +1 -1
  34. package/dist/vendor/{index.CRxYS9H3.js → index.BOMEjpjj.js} +271 -52
  35. package/dist/vendor/{index.DP-km6lF.js → index.CThipSqB.js} +2537 -2524
  36. package/dist/vendor/{index.CmILuxzC.js → index.D3hs2WiI.js} +1 -1
  37. package/dist/vendor/{index.DeR1hhfY.js → index.kpsSqFiz.js} +2 -1
  38. package/dist/vendor/{setup-common.XeoZAW8t.js → setup-common.DAu7t7mY.js} +1 -1
  39. package/dist/vendor/spy.Cf_4R5Oe.js +22 -0
  40. package/dist/vendor/{utils.D5gGkwyH.js → utils.YuQ3LT2a.js} +1 -1
  41. package/dist/vendor/{vi.ClD3hi7L.js → vi.hATFzZbX.js} +101 -46
  42. package/dist/vendor/{vm.Bi3bljci.js → vm.Ow-X2mkS.js} +2 -2
  43. package/dist/worker.js +1 -1
  44. package/dist/workers/forks.js +2 -2
  45. package/dist/workers/runVmTests.js +4 -4
  46. package/dist/workers/threads.js +2 -2
  47. package/dist/workers/vmForks.js +3 -3
  48. package/dist/workers/vmThreads.js +3 -3
  49. package/dist/workers.d.ts +1 -1
  50. package/dist/workers.js +5 -5
  51. package/package.json +20 -20
  52. package/suppress-warnings.cjs +2 -1
@@ -1,33 +1,35 @@
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';
1
+ import { join, resolve, relative, isAbsolute, dirname, normalize, basename, extname as extname$1, toNamespacedPath } from 'pathe';
2
+ import { A as API_PATH, e as extraInlineDeps, d as defaultPort, a as defaultBrowserPort, b as defaultInspectPort, B as BROWSER_API_PATH, E as EXIT_CODE_RESTART, w as workspacesFiles, C as CONFIG_NAMES, c as configFiles } from './constants.TCjCaw2D.js';
3
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';
4
+ import { g as getEnvPackageName } from './index.kpsSqFiz.js';
5
+ import { searchForWorkspaceRoot, version, isFileServingAllowed, parseAst, createServer, mergeConfig } from 'vite';
6
6
  import path$8, { win32 } from 'node:path';
7
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 as promises$1, existsSync, statSync as statSync$1, realpathSync, readFileSync } from 'node:fs';
9
+ import fs$8, { promises as promises$1, existsSync, statSync as statSync$1, realpathSync, readdirSync, readFileSync } from 'node:fs';
10
10
  import { MessageChannel, isMainThread } from 'node:worker_threads';
11
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.DP-km6lF.js';
15
- import require$$0$1 from 'stream';
16
- import require$$0$3 from 'events';
17
- import require$$0$2 from 'fs';
14
+ import require$$0$1 from 'util';
15
+ import { t as toRegexRange_1, p as picomatch$1, u as utils$h, m as mm } from './index.CThipSqB.js';
16
+ import require$$0$2 from 'stream';
17
+ import require$$0$4 from 'events';
18
+ import require$$0$3 from 'fs';
18
19
  import c from 'picocolors';
19
20
  import { ViteNodeRunner } from 'vite-node/client';
20
21
  import { SnapshotManager } from '@vitest/snapshot/manager';
21
22
  import { ViteNodeServer } from 'vite-node/server';
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';
23
+ import { v as version$1 } from './cac.CtYFkoSJ.js';
24
+ import { hasFailed, createFileTask, getTasks, getTests } from '@vitest/runner/utils';
25
+ import { n as noop$1, 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';
25
26
  import { createDefer, toArray as toArray$1, notNullish } from '@vitest/utils';
26
27
  import { a as isWindows } from './env.bmJgw1qP.js';
27
- import { rootDir } from '../path.js';
28
+ import { rootDir, distDir } from '../path.js';
28
29
  import { c as createBirpc } from './index.BpSiYbpB.js';
29
- import require$$0$4 from 'zlib';
30
- import require$$0$5 from 'buffer';
30
+ import { s as stringify$5, p as parse$5, 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, k as BlobReporter, r as readBlobs } from './index.BOMEjpjj.js';
31
+ import require$$0$5 from 'zlib';
32
+ import require$$0$6 from 'buffer';
31
33
  import require$$1 from 'crypto';
32
34
  import require$$1$1 from 'https';
33
35
  import require$$2 from 'http';
@@ -40,20 +42,21 @@ import * as nodeos from 'node:os';
40
42
  import nodeos__default, { tmpdir } from 'node:os';
41
43
  import EventEmitter$2 from 'node:events';
42
44
  import Tinypool$1, { Tinypool } from 'tinypool';
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';
44
45
  import crypto, { createHash as createHash$2 } from 'node:crypto';
45
46
  import { mkdir, writeFile, rm } from 'node:fs/promises';
47
+ import createDebug from 'debug';
46
48
  import { builtinModules, createRequire } from 'node:module';
47
49
  import assert from 'node:assert';
48
50
  import { format as format$2, inspect } from 'node:util';
49
51
  import { isCI, provider as provider$1 } from 'std-env';
50
- import { normalizeRequestId, cleanUrl } from 'vite-node/utils';
52
+ import { normalizeRequestId, isNodeBuiltin, cleanUrl } from 'vite-node/utils';
51
53
  import MagicString from 'magic-string';
52
54
  import { esmWalker } from '@vitest/utils/ast';
53
- import { d as divider, s as stripAnsi } from './utils.D5gGkwyH.js';
55
+ import remapping from '@ampproject/remapping';
54
56
  import { a as removeUndefinedValues } from './index._7XLd8Kd.js';
55
57
  import readline from 'node:readline';
56
- import require$$0$6 from 'readline';
58
+ import require$$0$7 from 'readline';
59
+ import { s as stripAnsi } from './utils.YuQ3LT2a.js';
57
60
 
58
61
  function _mergeNamespaces(n, m) {
59
62
  m.forEach(function (e) {
@@ -70,21 +73,25 @@ function _mergeNamespaces(n, m) {
70
73
  return Object.freeze(n);
71
74
  }
72
75
 
73
- async function getModuleGraph(ctx, id) {
76
+ async function getModuleGraph(ctx, projectName, id, browser = false) {
74
77
  const graph = {};
75
78
  const externalized = /* @__PURE__ */ new Set();
76
79
  const inlined = /* @__PURE__ */ new Set();
80
+ const project = ctx.getProjectByName(projectName);
77
81
  function clearId(id2) {
78
82
  return (id2 == null ? void 0 : id2.replace(/\?v=\w+$/, "")) || "";
79
83
  }
80
84
  async function get(mod, seen = /* @__PURE__ */ new Map()) {
85
+ var _a;
81
86
  if (!mod || !mod.id)
82
87
  return;
88
+ if (mod.id === "\0@vitest/browser/context")
89
+ return;
83
90
  if (seen.has(mod))
84
91
  return seen.get(mod);
85
92
  let id2 = clearId(mod.id);
86
93
  seen.set(mod, id2);
87
- const rewrote = await ctx.vitenode.shouldExternalize(id2);
94
+ const rewrote = browser ? ((_a = mod.file) == null ? void 0 : _a.includes(project.browser.config.cacheDir)) ? mod.id : false : await project.vitenode.shouldExternalize(id2);
88
95
  if (rewrote) {
89
96
  id2 = rewrote;
90
97
  externalized.add(id2);
@@ -96,7 +103,10 @@ async function getModuleGraph(ctx, id) {
96
103
  graph[id2] = (await Promise.all(mods.map((m) => get(m, seen)))).filter(Boolean);
97
104
  return id2;
98
105
  }
99
- await get(ctx.server.moduleGraph.getModuleById(id));
106
+ if (browser && project.browser)
107
+ await get(project.browser.moduleGraph.getModuleById(id));
108
+ else
109
+ await get(project.server.moduleGraph.getModuleById(id));
100
110
  return {
101
111
  graph,
102
112
  externalized: Array.from(externalized),
@@ -111,10 +121,17 @@ function cloneByOwnProperties(value) {
111
121
  }), {});
112
122
  }
113
123
  function stringifyReplace(key, value) {
114
- if (value instanceof Error)
115
- return cloneByOwnProperties(value);
116
- else
124
+ if (value instanceof Error) {
125
+ const cloned = cloneByOwnProperties(value);
126
+ return {
127
+ name: value.name,
128
+ message: value.message,
129
+ stack: value.stack,
130
+ ...cloned
131
+ };
132
+ } else {
117
133
  return value;
134
+ }
118
135
  }
119
136
 
120
137
  /*
@@ -396,7 +413,7 @@ async function findUp(name, options = {}) {
396
413
 
397
414
  var tasks = {};
398
415
 
399
- var utils$b = {};
416
+ var utils$g = {};
400
417
 
401
418
  var array$1 = {};
402
419
 
@@ -608,135 +625,1717 @@ var strictCheck = function(str) {
608
625
  }
609
626
  }
610
627
 
611
- if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
612
- if (pipeIndex < index) {
613
- pipeIndex = str.indexOf('|', index);
614
- }
615
- if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
616
- closeParenIndex = str.indexOf(')', pipeIndex);
617
- if (closeParenIndex > pipeIndex) {
618
- backSlashIndex = str.indexOf('\\', pipeIndex);
619
- if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
620
- return true;
621
- }
622
- }
623
- }
628
+ if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
629
+ if (pipeIndex < index) {
630
+ pipeIndex = str.indexOf('|', index);
631
+ }
632
+ if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
633
+ closeParenIndex = str.indexOf(')', pipeIndex);
634
+ if (closeParenIndex > pipeIndex) {
635
+ backSlashIndex = str.indexOf('\\', pipeIndex);
636
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
637
+ return true;
638
+ }
639
+ }
640
+ }
641
+ }
642
+
643
+ if (str[index] === '\\') {
644
+ var open = str[index + 1];
645
+ index += 2;
646
+ var close = chars[open];
647
+
648
+ if (close) {
649
+ var n = str.indexOf(close, index);
650
+ if (n !== -1) {
651
+ index = n + 1;
652
+ }
653
+ }
654
+
655
+ if (str[index] === '!') {
656
+ return true;
657
+ }
658
+ } else {
659
+ index++;
660
+ }
661
+ }
662
+ return false;
663
+ };
664
+
665
+ var relaxedCheck = function(str) {
666
+ if (str[0] === '!') {
667
+ return true;
668
+ }
669
+ var index = 0;
670
+ while (index < str.length) {
671
+ if (/[*?{}()[\]]/.test(str[index])) {
672
+ return true;
673
+ }
674
+
675
+ if (str[index] === '\\') {
676
+ var open = str[index + 1];
677
+ index += 2;
678
+ var close = chars[open];
679
+
680
+ if (close) {
681
+ var n = str.indexOf(close, index);
682
+ if (n !== -1) {
683
+ index = n + 1;
684
+ }
685
+ }
686
+
687
+ if (str[index] === '!') {
688
+ return true;
689
+ }
690
+ } else {
691
+ index++;
692
+ }
693
+ }
694
+ return false;
695
+ };
696
+
697
+ var isGlob$1 = function isGlob(str, options) {
698
+ if (typeof str !== 'string' || str === '') {
699
+ return false;
700
+ }
701
+
702
+ if (isExtglob(str)) {
703
+ return true;
704
+ }
705
+
706
+ var check = strictCheck;
707
+
708
+ // optionally relax check
709
+ if (options && options.strict === false) {
710
+ check = relaxedCheck;
711
+ }
712
+
713
+ return check(str);
714
+ };
715
+
716
+ var isGlob = isGlob$1;
717
+ var pathPosixDirname = p.posix.dirname;
718
+ var isWin32 = require$$0.platform() === 'win32';
719
+
720
+ var slash = '/';
721
+ var backslash = /\\/g;
722
+ var enclosure = /[\{\[].*[\}\]]$/;
723
+ var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
724
+ var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
725
+
726
+ /**
727
+ * @param {string} str
728
+ * @param {Object} opts
729
+ * @param {boolean} [opts.flipBackslashes=true]
730
+ * @returns {string}
731
+ */
732
+ var globParent$1 = function globParent(str, opts) {
733
+ var options = Object.assign({ flipBackslashes: true }, opts);
734
+
735
+ // flip windows path separators
736
+ if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
737
+ str = str.replace(backslash, slash);
738
+ }
739
+
740
+ // special case for strings ending in enclosure containing path separator
741
+ if (enclosure.test(str)) {
742
+ str += slash;
743
+ }
744
+
745
+ // preserves full path in case of trailing path separator
746
+ str += 'a';
747
+
748
+ // remove path parts that are globby
749
+ do {
750
+ str = pathPosixDirname(str);
751
+ } while (isGlob(str) || globby.test(str));
752
+
753
+ // remove escape chars and return result
754
+ return str.replace(escaped, '$1');
755
+ };
756
+
757
+ var utils$f = {};
758
+
759
+ (function (exports) {
760
+
761
+ exports.isInteger = num => {
762
+ if (typeof num === 'number') {
763
+ return Number.isInteger(num);
764
+ }
765
+ if (typeof num === 'string' && num.trim() !== '') {
766
+ return Number.isInteger(Number(num));
767
+ }
768
+ return false;
769
+ };
770
+
771
+ /**
772
+ * Find a node of the given type
773
+ */
774
+
775
+ exports.find = (node, type) => node.nodes.find(node => node.type === type);
776
+
777
+ /**
778
+ * Find a node of the given type
779
+ */
780
+
781
+ exports.exceedsLimit = (min, max, step = 1, limit) => {
782
+ if (limit === false) return false;
783
+ if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
784
+ return ((Number(max) - Number(min)) / Number(step)) >= limit;
785
+ };
786
+
787
+ /**
788
+ * Escape the given node with '\\' before node.value
789
+ */
790
+
791
+ exports.escapeNode = (block, n = 0, type) => {
792
+ let node = block.nodes[n];
793
+ if (!node) return;
794
+
795
+ if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
796
+ if (node.escaped !== true) {
797
+ node.value = '\\' + node.value;
798
+ node.escaped = true;
799
+ }
800
+ }
801
+ };
802
+
803
+ /**
804
+ * Returns true if the given brace node should be enclosed in literal braces
805
+ */
806
+
807
+ exports.encloseBrace = node => {
808
+ if (node.type !== 'brace') return false;
809
+ if ((node.commas >> 0 + node.ranges >> 0) === 0) {
810
+ node.invalid = true;
811
+ return true;
812
+ }
813
+ return false;
814
+ };
815
+
816
+ /**
817
+ * Returns true if a brace node is invalid.
818
+ */
819
+
820
+ exports.isInvalidBrace = block => {
821
+ if (block.type !== 'brace') return false;
822
+ if (block.invalid === true || block.dollar) return true;
823
+ if ((block.commas >> 0 + block.ranges >> 0) === 0) {
824
+ block.invalid = true;
825
+ return true;
826
+ }
827
+ if (block.open !== true || block.close !== true) {
828
+ block.invalid = true;
829
+ return true;
830
+ }
831
+ return false;
832
+ };
833
+
834
+ /**
835
+ * Returns true if a node is an open or close node
836
+ */
837
+
838
+ exports.isOpenOrClose = node => {
839
+ if (node.type === 'open' || node.type === 'close') {
840
+ return true;
841
+ }
842
+ return node.open === true || node.close === true;
843
+ };
844
+
845
+ /**
846
+ * Reduce an array of text nodes.
847
+ */
848
+
849
+ exports.reduce = nodes => nodes.reduce((acc, node) => {
850
+ if (node.type === 'text') acc.push(node.value);
851
+ if (node.type === 'range') node.type = 'text';
852
+ return acc;
853
+ }, []);
854
+
855
+ /**
856
+ * Flatten an array
857
+ */
858
+
859
+ exports.flatten = (...args) => {
860
+ const result = [];
861
+ const flat = arr => {
862
+ for (let i = 0; i < arr.length; i++) {
863
+ let ele = arr[i];
864
+ Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
865
+ }
866
+ return result;
867
+ };
868
+ flat(args);
869
+ return result;
870
+ };
871
+ } (utils$f));
872
+
873
+ const utils$e = utils$f;
874
+
875
+ var stringify$4 = (ast, options = {}) => {
876
+ let stringify = (node, parent = {}) => {
877
+ let invalidBlock = options.escapeInvalid && utils$e.isInvalidBrace(parent);
878
+ let invalidNode = node.invalid === true && options.escapeInvalid === true;
879
+ let output = '';
880
+
881
+ if (node.value) {
882
+ if ((invalidBlock || invalidNode) && utils$e.isOpenOrClose(node)) {
883
+ return '\\' + node.value;
884
+ }
885
+ return node.value;
886
+ }
887
+
888
+ if (node.value) {
889
+ return node.value;
890
+ }
891
+
892
+ if (node.nodes) {
893
+ for (let child of node.nodes) {
894
+ output += stringify(child);
895
+ }
896
+ }
897
+ return output;
898
+ };
899
+
900
+ return stringify(ast);
901
+ };
902
+
903
+ /*!
904
+ * fill-range <https://github.com/jonschlinkert/fill-range>
905
+ *
906
+ * Copyright (c) 2014-present, Jon Schlinkert.
907
+ * Licensed under the MIT License.
908
+ */
909
+
910
+ const util$3 = require$$0$1;
911
+ const toRegexRange = toRegexRange_1;
912
+
913
+ const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
914
+
915
+ const transform = toNumber => {
916
+ return value => toNumber === true ? Number(value) : String(value);
917
+ };
918
+
919
+ const isValidValue = value => {
920
+ return typeof value === 'number' || (typeof value === 'string' && value !== '');
921
+ };
922
+
923
+ const isNumber = num => Number.isInteger(+num);
924
+
925
+ const zeros = input => {
926
+ let value = `${input}`;
927
+ let index = -1;
928
+ if (value[0] === '-') value = value.slice(1);
929
+ if (value === '0') return false;
930
+ while (value[++index] === '0');
931
+ return index > 0;
932
+ };
933
+
934
+ const stringify$3 = (start, end, options) => {
935
+ if (typeof start === 'string' || typeof end === 'string') {
936
+ return true;
937
+ }
938
+ return options.stringify === true;
939
+ };
940
+
941
+ const pad = (input, maxLength, toNumber) => {
942
+ if (maxLength > 0) {
943
+ let dash = input[0] === '-' ? '-' : '';
944
+ if (dash) input = input.slice(1);
945
+ input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
946
+ }
947
+ if (toNumber === false) {
948
+ return String(input);
949
+ }
950
+ return input;
951
+ };
952
+
953
+ const toMaxLen = (input, maxLength) => {
954
+ let negative = input[0] === '-' ? '-' : '';
955
+ if (negative) {
956
+ input = input.slice(1);
957
+ maxLength--;
958
+ }
959
+ while (input.length < maxLength) input = '0' + input;
960
+ return negative ? ('-' + input) : input;
961
+ };
962
+
963
+ const toSequence = (parts, options) => {
964
+ parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
965
+ parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
966
+
967
+ let prefix = options.capture ? '' : '?:';
968
+ let positives = '';
969
+ let negatives = '';
970
+ let result;
971
+
972
+ if (parts.positives.length) {
973
+ positives = parts.positives.join('|');
974
+ }
975
+
976
+ if (parts.negatives.length) {
977
+ negatives = `-(${prefix}${parts.negatives.join('|')})`;
978
+ }
979
+
980
+ if (positives && negatives) {
981
+ result = `${positives}|${negatives}`;
982
+ } else {
983
+ result = positives || negatives;
984
+ }
985
+
986
+ if (options.wrap) {
987
+ return `(${prefix}${result})`;
988
+ }
989
+
990
+ return result;
991
+ };
992
+
993
+ const toRange = (a, b, isNumbers, options) => {
994
+ if (isNumbers) {
995
+ return toRegexRange(a, b, { wrap: false, ...options });
996
+ }
997
+
998
+ let start = String.fromCharCode(a);
999
+ if (a === b) return start;
1000
+
1001
+ let stop = String.fromCharCode(b);
1002
+ return `[${start}-${stop}]`;
1003
+ };
1004
+
1005
+ const toRegex = (start, end, options) => {
1006
+ if (Array.isArray(start)) {
1007
+ let wrap = options.wrap === true;
1008
+ let prefix = options.capture ? '' : '?:';
1009
+ return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
1010
+ }
1011
+ return toRegexRange(start, end, options);
1012
+ };
1013
+
1014
+ const rangeError = (...args) => {
1015
+ return new RangeError('Invalid range arguments: ' + util$3.inspect(...args));
1016
+ };
1017
+
1018
+ const invalidRange = (start, end, options) => {
1019
+ if (options.strictRanges === true) throw rangeError([start, end]);
1020
+ return [];
1021
+ };
1022
+
1023
+ const invalidStep = (step, options) => {
1024
+ if (options.strictRanges === true) {
1025
+ throw new TypeError(`Expected step "${step}" to be a number`);
1026
+ }
1027
+ return [];
1028
+ };
1029
+
1030
+ const fillNumbers = (start, end, step = 1, options = {}) => {
1031
+ let a = Number(start);
1032
+ let b = Number(end);
1033
+
1034
+ if (!Number.isInteger(a) || !Number.isInteger(b)) {
1035
+ if (options.strictRanges === true) throw rangeError([start, end]);
1036
+ return [];
1037
+ }
1038
+
1039
+ // fix negative zero
1040
+ if (a === 0) a = 0;
1041
+ if (b === 0) b = 0;
1042
+
1043
+ let descending = a > b;
1044
+ let startString = String(start);
1045
+ let endString = String(end);
1046
+ let stepString = String(step);
1047
+ step = Math.max(Math.abs(step), 1);
1048
+
1049
+ let padded = zeros(startString) || zeros(endString) || zeros(stepString);
1050
+ let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
1051
+ let toNumber = padded === false && stringify$3(start, end, options) === false;
1052
+ let format = options.transform || transform(toNumber);
1053
+
1054
+ if (options.toRegex && step === 1) {
1055
+ return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
1056
+ }
1057
+
1058
+ let parts = { negatives: [], positives: [] };
1059
+ let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
1060
+ let range = [];
1061
+ let index = 0;
1062
+
1063
+ while (descending ? a >= b : a <= b) {
1064
+ if (options.toRegex === true && step > 1) {
1065
+ push(a);
1066
+ } else {
1067
+ range.push(pad(format(a, index), maxLen, toNumber));
1068
+ }
1069
+ a = descending ? a - step : a + step;
1070
+ index++;
1071
+ }
1072
+
1073
+ if (options.toRegex === true) {
1074
+ return step > 1
1075
+ ? toSequence(parts, options)
1076
+ : toRegex(range, null, { wrap: false, ...options });
1077
+ }
1078
+
1079
+ return range;
1080
+ };
1081
+
1082
+ const fillLetters = (start, end, step = 1, options = {}) => {
1083
+ if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
1084
+ return invalidRange(start, end, options);
1085
+ }
1086
+
1087
+
1088
+ let format = options.transform || (val => String.fromCharCode(val));
1089
+ let a = `${start}`.charCodeAt(0);
1090
+ let b = `${end}`.charCodeAt(0);
1091
+
1092
+ let descending = a > b;
1093
+ let min = Math.min(a, b);
1094
+ let max = Math.max(a, b);
1095
+
1096
+ if (options.toRegex && step === 1) {
1097
+ return toRange(min, max, false, options);
1098
+ }
1099
+
1100
+ let range = [];
1101
+ let index = 0;
1102
+
1103
+ while (descending ? a >= b : a <= b) {
1104
+ range.push(format(a, index));
1105
+ a = descending ? a - step : a + step;
1106
+ index++;
1107
+ }
1108
+
1109
+ if (options.toRegex === true) {
1110
+ return toRegex(range, null, { wrap: false, options });
1111
+ }
1112
+
1113
+ return range;
1114
+ };
1115
+
1116
+ const fill$2 = (start, end, step, options = {}) => {
1117
+ if (end == null && isValidValue(start)) {
1118
+ return [start];
1119
+ }
1120
+
1121
+ if (!isValidValue(start) || !isValidValue(end)) {
1122
+ return invalidRange(start, end, options);
1123
+ }
1124
+
1125
+ if (typeof step === 'function') {
1126
+ return fill$2(start, end, 1, { transform: step });
1127
+ }
1128
+
1129
+ if (isObject(step)) {
1130
+ return fill$2(start, end, 0, step);
1131
+ }
1132
+
1133
+ let opts = { ...options };
1134
+ if (opts.capture === true) opts.wrap = true;
1135
+ step = step || opts.step || 1;
1136
+
1137
+ if (!isNumber(step)) {
1138
+ if (step != null && !isObject(step)) return invalidStep(step, opts);
1139
+ return fill$2(start, end, 1, step);
1140
+ }
1141
+
1142
+ if (isNumber(start) && isNumber(end)) {
1143
+ return fillNumbers(start, end, step, opts);
1144
+ }
1145
+
1146
+ return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
1147
+ };
1148
+
1149
+ var fillRange = fill$2;
1150
+
1151
+ const fill$1 = fillRange;
1152
+ const utils$d = utils$f;
1153
+
1154
+ const compile$1 = (ast, options = {}) => {
1155
+ let walk = (node, parent = {}) => {
1156
+ let invalidBlock = utils$d.isInvalidBrace(parent);
1157
+ let invalidNode = node.invalid === true && options.escapeInvalid === true;
1158
+ let invalid = invalidBlock === true || invalidNode === true;
1159
+ let prefix = options.escapeInvalid === true ? '\\' : '';
1160
+ let output = '';
1161
+
1162
+ if (node.isOpen === true) {
1163
+ return prefix + node.value;
1164
+ }
1165
+ if (node.isClose === true) {
1166
+ return prefix + node.value;
1167
+ }
1168
+
1169
+ if (node.type === 'open') {
1170
+ return invalid ? (prefix + node.value) : '(';
1171
+ }
1172
+
1173
+ if (node.type === 'close') {
1174
+ return invalid ? (prefix + node.value) : ')';
1175
+ }
1176
+
1177
+ if (node.type === 'comma') {
1178
+ return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
1179
+ }
1180
+
1181
+ if (node.value) {
1182
+ return node.value;
1183
+ }
1184
+
1185
+ if (node.nodes && node.ranges > 0) {
1186
+ let args = utils$d.reduce(node.nodes);
1187
+ let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
1188
+
1189
+ if (range.length !== 0) {
1190
+ return args.length > 1 && range.length > 1 ? `(${range})` : range;
1191
+ }
1192
+ }
1193
+
1194
+ if (node.nodes) {
1195
+ for (let child of node.nodes) {
1196
+ output += walk(child, node);
1197
+ }
1198
+ }
1199
+ return output;
1200
+ };
1201
+
1202
+ return walk(ast);
1203
+ };
1204
+
1205
+ var compile_1 = compile$1;
1206
+
1207
+ const fill = fillRange;
1208
+ const stringify$2 = stringify$4;
1209
+ const utils$c = utils$f;
1210
+
1211
+ const append = (queue = '', stash = '', enclose = false) => {
1212
+ let result = [];
1213
+
1214
+ queue = [].concat(queue);
1215
+ stash = [].concat(stash);
1216
+
1217
+ if (!stash.length) return queue;
1218
+ if (!queue.length) {
1219
+ return enclose ? utils$c.flatten(stash).map(ele => `{${ele}}`) : stash;
1220
+ }
1221
+
1222
+ for (let item of queue) {
1223
+ if (Array.isArray(item)) {
1224
+ for (let value of item) {
1225
+ result.push(append(value, stash, enclose));
1226
+ }
1227
+ } else {
1228
+ for (let ele of stash) {
1229
+ if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
1230
+ result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
1231
+ }
1232
+ }
1233
+ }
1234
+ return utils$c.flatten(result);
1235
+ };
1236
+
1237
+ const expand$1 = (ast, options = {}) => {
1238
+ let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
1239
+
1240
+ let walk = (node, parent = {}) => {
1241
+ node.queue = [];
1242
+
1243
+ let p = parent;
1244
+ let q = parent.queue;
1245
+
1246
+ while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
1247
+ p = p.parent;
1248
+ q = p.queue;
1249
+ }
1250
+
1251
+ if (node.invalid || node.dollar) {
1252
+ q.push(append(q.pop(), stringify$2(node, options)));
1253
+ return;
1254
+ }
1255
+
1256
+ if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
1257
+ q.push(append(q.pop(), ['{}']));
1258
+ return;
1259
+ }
1260
+
1261
+ if (node.nodes && node.ranges > 0) {
1262
+ let args = utils$c.reduce(node.nodes);
1263
+
1264
+ if (utils$c.exceedsLimit(...args, options.step, rangeLimit)) {
1265
+ throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
1266
+ }
1267
+
1268
+ let range = fill(...args, options);
1269
+ if (range.length === 0) {
1270
+ range = stringify$2(node, options);
1271
+ }
1272
+
1273
+ q.push(append(q.pop(), range));
1274
+ node.nodes = [];
1275
+ return;
1276
+ }
1277
+
1278
+ let enclose = utils$c.encloseBrace(node);
1279
+ let queue = node.queue;
1280
+ let block = node;
1281
+
1282
+ while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
1283
+ block = block.parent;
1284
+ queue = block.queue;
1285
+ }
1286
+
1287
+ for (let i = 0; i < node.nodes.length; i++) {
1288
+ let child = node.nodes[i];
1289
+
1290
+ if (child.type === 'comma' && node.type === 'brace') {
1291
+ if (i === 1) queue.push('');
1292
+ queue.push('');
1293
+ continue;
1294
+ }
1295
+
1296
+ if (child.type === 'close') {
1297
+ q.push(append(q.pop(), queue, enclose));
1298
+ continue;
1299
+ }
1300
+
1301
+ if (child.value && child.type !== 'open') {
1302
+ queue.push(append(queue.pop(), child.value));
1303
+ continue;
1304
+ }
1305
+
1306
+ if (child.nodes) {
1307
+ walk(child, node);
1308
+ }
1309
+ }
1310
+
1311
+ return queue;
1312
+ };
1313
+
1314
+ return utils$c.flatten(walk(ast));
1315
+ };
1316
+
1317
+ var expand_1 = expand$1;
1318
+
1319
+ var constants$2 = {
1320
+ MAX_LENGTH: 1024 * 64,
1321
+
1322
+ // Digits
1323
+ CHAR_0: '0', /* 0 */
1324
+ CHAR_9: '9', /* 9 */
1325
+
1326
+ // Alphabet chars.
1327
+ CHAR_UPPERCASE_A: 'A', /* A */
1328
+ CHAR_LOWERCASE_A: 'a', /* a */
1329
+ CHAR_UPPERCASE_Z: 'Z', /* Z */
1330
+ CHAR_LOWERCASE_Z: 'z', /* z */
1331
+
1332
+ CHAR_LEFT_PARENTHESES: '(', /* ( */
1333
+ CHAR_RIGHT_PARENTHESES: ')', /* ) */
1334
+
1335
+ CHAR_ASTERISK: '*', /* * */
1336
+
1337
+ // Non-alphabetic chars.
1338
+ CHAR_AMPERSAND: '&', /* & */
1339
+ CHAR_AT: '@', /* @ */
1340
+ CHAR_BACKSLASH: '\\', /* \ */
1341
+ CHAR_BACKTICK: '`', /* ` */
1342
+ CHAR_CARRIAGE_RETURN: '\r', /* \r */
1343
+ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
1344
+ CHAR_COLON: ':', /* : */
1345
+ CHAR_COMMA: ',', /* , */
1346
+ CHAR_DOLLAR: '$', /* . */
1347
+ CHAR_DOT: '.', /* . */
1348
+ CHAR_DOUBLE_QUOTE: '"', /* " */
1349
+ CHAR_EQUAL: '=', /* = */
1350
+ CHAR_EXCLAMATION_MARK: '!', /* ! */
1351
+ CHAR_FORM_FEED: '\f', /* \f */
1352
+ CHAR_FORWARD_SLASH: '/', /* / */
1353
+ CHAR_HASH: '#', /* # */
1354
+ CHAR_HYPHEN_MINUS: '-', /* - */
1355
+ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
1356
+ CHAR_LEFT_CURLY_BRACE: '{', /* { */
1357
+ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
1358
+ CHAR_LINE_FEED: '\n', /* \n */
1359
+ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
1360
+ CHAR_PERCENT: '%', /* % */
1361
+ CHAR_PLUS: '+', /* + */
1362
+ CHAR_QUESTION_MARK: '?', /* ? */
1363
+ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
1364
+ CHAR_RIGHT_CURLY_BRACE: '}', /* } */
1365
+ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
1366
+ CHAR_SEMICOLON: ';', /* ; */
1367
+ CHAR_SINGLE_QUOTE: '\'', /* ' */
1368
+ CHAR_SPACE: ' ', /* */
1369
+ CHAR_TAB: '\t', /* \t */
1370
+ CHAR_UNDERSCORE: '_', /* _ */
1371
+ CHAR_VERTICAL_LINE: '|', /* | */
1372
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
1373
+ };
1374
+
1375
+ const stringify$1 = stringify$4;
1376
+
1377
+ /**
1378
+ * Constants
1379
+ */
1380
+
1381
+ const {
1382
+ MAX_LENGTH,
1383
+ CHAR_BACKSLASH, /* \ */
1384
+ CHAR_BACKTICK, /* ` */
1385
+ CHAR_COMMA, /* , */
1386
+ CHAR_DOT, /* . */
1387
+ CHAR_LEFT_PARENTHESES, /* ( */
1388
+ CHAR_RIGHT_PARENTHESES, /* ) */
1389
+ CHAR_LEFT_CURLY_BRACE, /* { */
1390
+ CHAR_RIGHT_CURLY_BRACE, /* } */
1391
+ CHAR_LEFT_SQUARE_BRACKET, /* [ */
1392
+ CHAR_RIGHT_SQUARE_BRACKET, /* ] */
1393
+ CHAR_DOUBLE_QUOTE, /* " */
1394
+ CHAR_SINGLE_QUOTE, /* ' */
1395
+ CHAR_NO_BREAK_SPACE,
1396
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE
1397
+ } = constants$2;
1398
+
1399
+ /**
1400
+ * parse
1401
+ */
1402
+
1403
+ const parse$4 = (input, options = {}) => {
1404
+ if (typeof input !== 'string') {
1405
+ throw new TypeError('Expected a string');
1406
+ }
1407
+
1408
+ let opts = options || {};
1409
+ let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1410
+ if (input.length > max) {
1411
+ throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
1412
+ }
1413
+
1414
+ let ast = { type: 'root', input, nodes: [] };
1415
+ let stack = [ast];
1416
+ let block = ast;
1417
+ let prev = ast;
1418
+ let brackets = 0;
1419
+ let length = input.length;
1420
+ let index = 0;
1421
+ let depth = 0;
1422
+ let value;
1423
+
1424
+ /**
1425
+ * Helpers
1426
+ */
1427
+
1428
+ const advance = () => input[index++];
1429
+ const push = node => {
1430
+ if (node.type === 'text' && prev.type === 'dot') {
1431
+ prev.type = 'text';
1432
+ }
1433
+
1434
+ if (prev && prev.type === 'text' && node.type === 'text') {
1435
+ prev.value += node.value;
1436
+ return;
1437
+ }
1438
+
1439
+ block.nodes.push(node);
1440
+ node.parent = block;
1441
+ node.prev = prev;
1442
+ prev = node;
1443
+ return node;
1444
+ };
1445
+
1446
+ push({ type: 'bos' });
1447
+
1448
+ while (index < length) {
1449
+ block = stack[stack.length - 1];
1450
+ value = advance();
1451
+
1452
+ /**
1453
+ * Invalid chars
1454
+ */
1455
+
1456
+ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
1457
+ continue;
1458
+ }
1459
+
1460
+ /**
1461
+ * Escaped chars
1462
+ */
1463
+
1464
+ if (value === CHAR_BACKSLASH) {
1465
+ push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
1466
+ continue;
1467
+ }
1468
+
1469
+ /**
1470
+ * Right square bracket (literal): ']'
1471
+ */
1472
+
1473
+ if (value === CHAR_RIGHT_SQUARE_BRACKET) {
1474
+ push({ type: 'text', value: '\\' + value });
1475
+ continue;
1476
+ }
1477
+
1478
+ /**
1479
+ * Left square bracket: '['
1480
+ */
1481
+
1482
+ if (value === CHAR_LEFT_SQUARE_BRACKET) {
1483
+ brackets++;
1484
+ let next;
1485
+
1486
+ while (index < length && (next = advance())) {
1487
+ value += next;
1488
+
1489
+ if (next === CHAR_LEFT_SQUARE_BRACKET) {
1490
+ brackets++;
1491
+ continue;
1492
+ }
1493
+
1494
+ if (next === CHAR_BACKSLASH) {
1495
+ value += advance();
1496
+ continue;
1497
+ }
1498
+
1499
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
1500
+ brackets--;
1501
+
1502
+ if (brackets === 0) {
1503
+ break;
1504
+ }
1505
+ }
1506
+ }
1507
+
1508
+ push({ type: 'text', value });
1509
+ continue;
1510
+ }
1511
+
1512
+ /**
1513
+ * Parentheses
1514
+ */
1515
+
1516
+ if (value === CHAR_LEFT_PARENTHESES) {
1517
+ block = push({ type: 'paren', nodes: [] });
1518
+ stack.push(block);
1519
+ push({ type: 'text', value });
1520
+ continue;
1521
+ }
1522
+
1523
+ if (value === CHAR_RIGHT_PARENTHESES) {
1524
+ if (block.type !== 'paren') {
1525
+ push({ type: 'text', value });
1526
+ continue;
1527
+ }
1528
+ block = stack.pop();
1529
+ push({ type: 'text', value });
1530
+ block = stack[stack.length - 1];
1531
+ continue;
1532
+ }
1533
+
1534
+ /**
1535
+ * Quotes: '|"|`
1536
+ */
1537
+
1538
+ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
1539
+ let open = value;
1540
+ let next;
1541
+
1542
+ if (options.keepQuotes !== true) {
1543
+ value = '';
1544
+ }
1545
+
1546
+ while (index < length && (next = advance())) {
1547
+ if (next === CHAR_BACKSLASH) {
1548
+ value += next + advance();
1549
+ continue;
1550
+ }
1551
+
1552
+ if (next === open) {
1553
+ if (options.keepQuotes === true) value += next;
1554
+ break;
1555
+ }
1556
+
1557
+ value += next;
1558
+ }
1559
+
1560
+ push({ type: 'text', value });
1561
+ continue;
1562
+ }
1563
+
1564
+ /**
1565
+ * Left curly brace: '{'
1566
+ */
1567
+
1568
+ if (value === CHAR_LEFT_CURLY_BRACE) {
1569
+ depth++;
1570
+
1571
+ let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
1572
+ let brace = {
1573
+ type: 'brace',
1574
+ open: true,
1575
+ close: false,
1576
+ dollar,
1577
+ depth,
1578
+ commas: 0,
1579
+ ranges: 0,
1580
+ nodes: []
1581
+ };
1582
+
1583
+ block = push(brace);
1584
+ stack.push(block);
1585
+ push({ type: 'open', value });
1586
+ continue;
1587
+ }
1588
+
1589
+ /**
1590
+ * Right curly brace: '}'
1591
+ */
1592
+
1593
+ if (value === CHAR_RIGHT_CURLY_BRACE) {
1594
+ if (block.type !== 'brace') {
1595
+ push({ type: 'text', value });
1596
+ continue;
1597
+ }
1598
+
1599
+ let type = 'close';
1600
+ block = stack.pop();
1601
+ block.close = true;
1602
+
1603
+ push({ type, value });
1604
+ depth--;
1605
+
1606
+ block = stack[stack.length - 1];
1607
+ continue;
1608
+ }
1609
+
1610
+ /**
1611
+ * Comma: ','
1612
+ */
1613
+
1614
+ if (value === CHAR_COMMA && depth > 0) {
1615
+ if (block.ranges > 0) {
1616
+ block.ranges = 0;
1617
+ let open = block.nodes.shift();
1618
+ block.nodes = [open, { type: 'text', value: stringify$1(block) }];
1619
+ }
1620
+
1621
+ push({ type: 'comma', value });
1622
+ block.commas++;
1623
+ continue;
1624
+ }
1625
+
1626
+ /**
1627
+ * Dot: '.'
1628
+ */
1629
+
1630
+ if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
1631
+ let siblings = block.nodes;
1632
+
1633
+ if (depth === 0 || siblings.length === 0) {
1634
+ push({ type: 'text', value });
1635
+ continue;
1636
+ }
1637
+
1638
+ if (prev.type === 'dot') {
1639
+ block.range = [];
1640
+ prev.value += value;
1641
+ prev.type = 'range';
1642
+
1643
+ if (block.nodes.length !== 3 && block.nodes.length !== 5) {
1644
+ block.invalid = true;
1645
+ block.ranges = 0;
1646
+ prev.type = 'text';
1647
+ continue;
1648
+ }
1649
+
1650
+ block.ranges++;
1651
+ block.args = [];
1652
+ continue;
1653
+ }
1654
+
1655
+ if (prev.type === 'range') {
1656
+ siblings.pop();
1657
+
1658
+ let before = siblings[siblings.length - 1];
1659
+ before.value += prev.value + value;
1660
+ prev = before;
1661
+ block.ranges--;
1662
+ continue;
1663
+ }
1664
+
1665
+ push({ type: 'dot', value });
1666
+ continue;
1667
+ }
1668
+
1669
+ /**
1670
+ * Text
1671
+ */
1672
+
1673
+ push({ type: 'text', value });
1674
+ }
1675
+
1676
+ // Mark imbalanced braces and brackets as invalid
1677
+ do {
1678
+ block = stack.pop();
1679
+
1680
+ if (block.type !== 'root') {
1681
+ block.nodes.forEach(node => {
1682
+ if (!node.nodes) {
1683
+ if (node.type === 'open') node.isOpen = true;
1684
+ if (node.type === 'close') node.isClose = true;
1685
+ if (!node.nodes) node.type = 'text';
1686
+ node.invalid = true;
1687
+ }
1688
+ });
1689
+
1690
+ // get the location of the block on parent.nodes (block's siblings)
1691
+ let parent = stack[stack.length - 1];
1692
+ let index = parent.nodes.indexOf(block);
1693
+ // replace the (invalid) block with it's nodes
1694
+ parent.nodes.splice(index, 1, ...block.nodes);
1695
+ }
1696
+ } while (stack.length > 0);
1697
+
1698
+ push({ type: 'eos' });
1699
+ return ast;
1700
+ };
1701
+
1702
+ var parse_1 = parse$4;
1703
+
1704
+ const stringify = stringify$4;
1705
+ const compile = compile_1;
1706
+ const expand = expand_1;
1707
+ const parse$3 = parse_1;
1708
+
1709
+ /**
1710
+ * Expand the given pattern or create a regex-compatible string.
1711
+ *
1712
+ * ```js
1713
+ * const braces = require('braces');
1714
+ * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
1715
+ * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
1716
+ * ```
1717
+ * @param {String} `str`
1718
+ * @param {Object} `options`
1719
+ * @return {String}
1720
+ * @api public
1721
+ */
1722
+
1723
+ const braces$1 = (input, options = {}) => {
1724
+ let output = [];
1725
+
1726
+ if (Array.isArray(input)) {
1727
+ for (let pattern of input) {
1728
+ let result = braces$1.create(pattern, options);
1729
+ if (Array.isArray(result)) {
1730
+ output.push(...result);
1731
+ } else {
1732
+ output.push(result);
1733
+ }
1734
+ }
1735
+ } else {
1736
+ output = [].concat(braces$1.create(input, options));
1737
+ }
1738
+
1739
+ if (options && options.expand === true && options.nodupes === true) {
1740
+ output = [...new Set(output)];
1741
+ }
1742
+ return output;
1743
+ };
1744
+
1745
+ /**
1746
+ * Parse the given `str` with the given `options`.
1747
+ *
1748
+ * ```js
1749
+ * // braces.parse(pattern, [, options]);
1750
+ * const ast = braces.parse('a/{b,c}/d');
1751
+ * console.log(ast);
1752
+ * ```
1753
+ * @param {String} pattern Brace pattern to parse
1754
+ * @param {Object} options
1755
+ * @return {Object} Returns an AST
1756
+ * @api public
1757
+ */
1758
+
1759
+ braces$1.parse = (input, options = {}) => parse$3(input, options);
1760
+
1761
+ /**
1762
+ * Creates a braces string from an AST, or an AST node.
1763
+ *
1764
+ * ```js
1765
+ * const braces = require('braces');
1766
+ * let ast = braces.parse('foo/{a,b}/bar');
1767
+ * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
1768
+ * ```
1769
+ * @param {String} `input` Brace pattern or AST.
1770
+ * @param {Object} `options`
1771
+ * @return {Array} Returns an array of expanded values.
1772
+ * @api public
1773
+ */
1774
+
1775
+ braces$1.stringify = (input, options = {}) => {
1776
+ if (typeof input === 'string') {
1777
+ return stringify(braces$1.parse(input, options), options);
1778
+ }
1779
+ return stringify(input, options);
1780
+ };
1781
+
1782
+ /**
1783
+ * Compiles a brace pattern into a regex-compatible, optimized string.
1784
+ * This method is called by the main [braces](#braces) function by default.
1785
+ *
1786
+ * ```js
1787
+ * const braces = require('braces');
1788
+ * console.log(braces.compile('a/{b,c}/d'));
1789
+ * //=> ['a/(b|c)/d']
1790
+ * ```
1791
+ * @param {String} `input` Brace pattern or AST.
1792
+ * @param {Object} `options`
1793
+ * @return {Array} Returns an array of expanded values.
1794
+ * @api public
1795
+ */
1796
+
1797
+ braces$1.compile = (input, options = {}) => {
1798
+ if (typeof input === 'string') {
1799
+ input = braces$1.parse(input, options);
1800
+ }
1801
+ return compile(input, options);
1802
+ };
1803
+
1804
+ /**
1805
+ * Expands a brace pattern into an array. This method is called by the
1806
+ * main [braces](#braces) function when `options.expand` is true. Before
1807
+ * using this method it's recommended that you read the [performance notes](#performance))
1808
+ * and advantages of using [.compile](#compile) instead.
1809
+ *
1810
+ * ```js
1811
+ * const braces = require('braces');
1812
+ * console.log(braces.expand('a/{b,c}/d'));
1813
+ * //=> ['a/b/d', 'a/c/d'];
1814
+ * ```
1815
+ * @param {String} `pattern` Brace pattern
1816
+ * @param {Object} `options`
1817
+ * @return {Array} Returns an array of expanded values.
1818
+ * @api public
1819
+ */
1820
+
1821
+ braces$1.expand = (input, options = {}) => {
1822
+ if (typeof input === 'string') {
1823
+ input = braces$1.parse(input, options);
1824
+ }
1825
+
1826
+ let result = expand(input, options);
1827
+
1828
+ // filter out empty strings if specified
1829
+ if (options.noempty === true) {
1830
+ result = result.filter(Boolean);
1831
+ }
1832
+
1833
+ // filter out duplicates if specified
1834
+ if (options.nodupes === true) {
1835
+ result = [...new Set(result)];
1836
+ }
1837
+
1838
+ return result;
1839
+ };
1840
+
1841
+ /**
1842
+ * Processes a brace pattern and returns either an expanded array
1843
+ * (if `options.expand` is true), a highly optimized regex-compatible string.
1844
+ * This method is called by the main [braces](#braces) function.
1845
+ *
1846
+ * ```js
1847
+ * const braces = require('braces');
1848
+ * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
1849
+ * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
1850
+ * ```
1851
+ * @param {String} `pattern` Brace pattern
1852
+ * @param {Object} `options`
1853
+ * @return {Array} Returns an array of expanded values.
1854
+ * @api public
1855
+ */
1856
+
1857
+ braces$1.create = (input, options = {}) => {
1858
+ if (input === '' || input.length < 3) {
1859
+ return [input];
1860
+ }
1861
+
1862
+ return options.expand !== true
1863
+ ? braces$1.compile(input, options)
1864
+ : braces$1.expand(input, options);
1865
+ };
1866
+
1867
+ /**
1868
+ * Expose "braces"
1869
+ */
1870
+
1871
+ var braces_1 = braces$1;
1872
+
1873
+ const util$2 = require$$0$1;
1874
+ const braces = braces_1;
1875
+ const picomatch = picomatch$1;
1876
+ const utils$b = utils$h;
1877
+ const isEmptyString = val => val === '' || val === './';
1878
+
1879
+ /**
1880
+ * Returns an array of strings that match one or more glob patterns.
1881
+ *
1882
+ * ```js
1883
+ * const mm = require('micromatch');
1884
+ * // mm(list, patterns[, options]);
1885
+ *
1886
+ * console.log(mm(['a.js', 'a.txt'], ['*.js']));
1887
+ * //=> [ 'a.js' ]
1888
+ * ```
1889
+ * @param {String|Array<string>} `list` List of strings to match.
1890
+ * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
1891
+ * @param {Object} `options` See available [options](#options)
1892
+ * @return {Array} Returns an array of matches
1893
+ * @summary false
1894
+ * @api public
1895
+ */
1896
+
1897
+ const micromatch$1 = (list, patterns, options) => {
1898
+ patterns = [].concat(patterns);
1899
+ list = [].concat(list);
1900
+
1901
+ let omit = new Set();
1902
+ let keep = new Set();
1903
+ let items = new Set();
1904
+ let negatives = 0;
1905
+
1906
+ let onResult = state => {
1907
+ items.add(state.output);
1908
+ if (options && options.onResult) {
1909
+ options.onResult(state);
1910
+ }
1911
+ };
1912
+
1913
+ for (let i = 0; i < patterns.length; i++) {
1914
+ let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true);
1915
+ let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
1916
+ if (negated) negatives++;
1917
+
1918
+ for (let item of list) {
1919
+ let matched = isMatch(item, true);
1920
+
1921
+ let match = negated ? !matched.isMatch : matched.isMatch;
1922
+ if (!match) continue;
1923
+
1924
+ if (negated) {
1925
+ omit.add(matched.output);
1926
+ } else {
1927
+ omit.delete(matched.output);
1928
+ keep.add(matched.output);
1929
+ }
1930
+ }
1931
+ }
1932
+
1933
+ let result = negatives === patterns.length ? [...items] : [...keep];
1934
+ let matches = result.filter(item => !omit.has(item));
1935
+
1936
+ if (options && matches.length === 0) {
1937
+ if (options.failglob === true) {
1938
+ throw new Error(`No matches found for "${patterns.join(', ')}"`);
624
1939
  }
625
1940
 
626
- if (str[index] === '\\') {
627
- var open = str[index + 1];
628
- index += 2;
629
- var close = chars[open];
1941
+ if (options.nonull === true || options.nullglob === true) {
1942
+ return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
1943
+ }
1944
+ }
630
1945
 
631
- if (close) {
632
- var n = str.indexOf(close, index);
633
- if (n !== -1) {
634
- index = n + 1;
635
- }
636
- }
1946
+ return matches;
1947
+ };
637
1948
 
638
- if (str[index] === '!') {
639
- return true;
640
- }
641
- } else {
642
- index++;
1949
+ /**
1950
+ * Backwards compatibility
1951
+ */
1952
+
1953
+ micromatch$1.match = micromatch$1;
1954
+
1955
+ /**
1956
+ * Returns a matcher function from the given glob `pattern` and `options`.
1957
+ * The returned function takes a string to match as its only argument and returns
1958
+ * true if the string is a match.
1959
+ *
1960
+ * ```js
1961
+ * const mm = require('micromatch');
1962
+ * // mm.matcher(pattern[, options]);
1963
+ *
1964
+ * const isMatch = mm.matcher('*.!(*a)');
1965
+ * console.log(isMatch('a.a')); //=> false
1966
+ * console.log(isMatch('a.b')); //=> true
1967
+ * ```
1968
+ * @param {String} `pattern` Glob pattern
1969
+ * @param {Object} `options`
1970
+ * @return {Function} Returns a matcher function.
1971
+ * @api public
1972
+ */
1973
+
1974
+ micromatch$1.matcher = (pattern, options) => picomatch(pattern, options);
1975
+
1976
+ /**
1977
+ * Returns true if **any** of the given glob `patterns` match the specified `string`.
1978
+ *
1979
+ * ```js
1980
+ * const mm = require('micromatch');
1981
+ * // mm.isMatch(string, patterns[, options]);
1982
+ *
1983
+ * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
1984
+ * console.log(mm.isMatch('a.a', 'b.*')); //=> false
1985
+ * ```
1986
+ * @param {String} `str` The string to test.
1987
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
1988
+ * @param {Object} `[options]` See available [options](#options).
1989
+ * @return {Boolean} Returns true if any patterns match `str`
1990
+ * @api public
1991
+ */
1992
+
1993
+ micromatch$1.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
1994
+
1995
+ /**
1996
+ * Backwards compatibility
1997
+ */
1998
+
1999
+ micromatch$1.any = micromatch$1.isMatch;
2000
+
2001
+ /**
2002
+ * Returns a list of strings that _**do not match any**_ of the given `patterns`.
2003
+ *
2004
+ * ```js
2005
+ * const mm = require('micromatch');
2006
+ * // mm.not(list, patterns[, options]);
2007
+ *
2008
+ * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
2009
+ * //=> ['b.b', 'c.c']
2010
+ * ```
2011
+ * @param {Array} `list` Array of strings to match.
2012
+ * @param {String|Array} `patterns` One or more glob pattern to use for matching.
2013
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
2014
+ * @return {Array} Returns an array of strings that **do not match** the given patterns.
2015
+ * @api public
2016
+ */
2017
+
2018
+ micromatch$1.not = (list, patterns, options = {}) => {
2019
+ patterns = [].concat(patterns).map(String);
2020
+ let result = new Set();
2021
+ let items = [];
2022
+
2023
+ let onResult = state => {
2024
+ if (options.onResult) options.onResult(state);
2025
+ items.push(state.output);
2026
+ };
2027
+
2028
+ let matches = new Set(micromatch$1(list, patterns, { ...options, onResult }));
2029
+
2030
+ for (let item of items) {
2031
+ if (!matches.has(item)) {
2032
+ result.add(item);
643
2033
  }
644
2034
  }
645
- return false;
2035
+ return [...result];
646
2036
  };
647
2037
 
648
- var relaxedCheck = function(str) {
649
- if (str[0] === '!') {
650
- return true;
2038
+ /**
2039
+ * Returns true if the given `string` contains the given pattern. Similar
2040
+ * to [.isMatch](#isMatch) but the pattern can match any part of the string.
2041
+ *
2042
+ * ```js
2043
+ * var mm = require('micromatch');
2044
+ * // mm.contains(string, pattern[, options]);
2045
+ *
2046
+ * console.log(mm.contains('aa/bb/cc', '*b'));
2047
+ * //=> true
2048
+ * console.log(mm.contains('aa/bb/cc', '*d'));
2049
+ * //=> false
2050
+ * ```
2051
+ * @param {String} `str` The string to match.
2052
+ * @param {String|Array} `patterns` Glob pattern to use for matching.
2053
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
2054
+ * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
2055
+ * @api public
2056
+ */
2057
+
2058
+ micromatch$1.contains = (str, pattern, options) => {
2059
+ if (typeof str !== 'string') {
2060
+ throw new TypeError(`Expected a string: "${util$2.inspect(str)}"`);
651
2061
  }
652
- var index = 0;
653
- while (index < str.length) {
654
- if (/[*?{}()[\]]/.test(str[index])) {
2062
+
2063
+ if (Array.isArray(pattern)) {
2064
+ return pattern.some(p => micromatch$1.contains(str, p, options));
2065
+ }
2066
+
2067
+ if (typeof pattern === 'string') {
2068
+ if (isEmptyString(str) || isEmptyString(pattern)) {
2069
+ return false;
2070
+ }
2071
+
2072
+ if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
655
2073
  return true;
656
2074
  }
2075
+ }
657
2076
 
658
- if (str[index] === '\\') {
659
- var open = str[index + 1];
660
- index += 2;
661
- var close = chars[open];
2077
+ return micromatch$1.isMatch(str, pattern, { ...options, contains: true });
2078
+ };
662
2079
 
663
- if (close) {
664
- var n = str.indexOf(close, index);
665
- if (n !== -1) {
666
- index = n + 1;
667
- }
668
- }
2080
+ /**
2081
+ * Filter the keys of the given object with the given `glob` pattern
2082
+ * and `options`. Does not attempt to match nested keys. If you need this feature,
2083
+ * use [glob-object][] instead.
2084
+ *
2085
+ * ```js
2086
+ * const mm = require('micromatch');
2087
+ * // mm.matchKeys(object, patterns[, options]);
2088
+ *
2089
+ * const obj = { aa: 'a', ab: 'b', ac: 'c' };
2090
+ * console.log(mm.matchKeys(obj, '*b'));
2091
+ * //=> { ab: 'b' }
2092
+ * ```
2093
+ * @param {Object} `object` The object with keys to filter.
2094
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
2095
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
2096
+ * @return {Object} Returns an object with only keys that match the given patterns.
2097
+ * @api public
2098
+ */
669
2099
 
670
- if (str[index] === '!') {
671
- return true;
672
- }
673
- } else {
674
- index++;
2100
+ micromatch$1.matchKeys = (obj, patterns, options) => {
2101
+ if (!utils$b.isObject(obj)) {
2102
+ throw new TypeError('Expected the first argument to be an object');
2103
+ }
2104
+ let keys = micromatch$1(Object.keys(obj), patterns, options);
2105
+ let res = {};
2106
+ for (let key of keys) res[key] = obj[key];
2107
+ return res;
2108
+ };
2109
+
2110
+ /**
2111
+ * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
2112
+ *
2113
+ * ```js
2114
+ * const mm = require('micromatch');
2115
+ * // mm.some(list, patterns[, options]);
2116
+ *
2117
+ * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
2118
+ * // true
2119
+ * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
2120
+ * // false
2121
+ * ```
2122
+ * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
2123
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
2124
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
2125
+ * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
2126
+ * @api public
2127
+ */
2128
+
2129
+ micromatch$1.some = (list, patterns, options) => {
2130
+ let items = [].concat(list);
2131
+
2132
+ for (let pattern of [].concat(patterns)) {
2133
+ let isMatch = picomatch(String(pattern), options);
2134
+ if (items.some(item => isMatch(item))) {
2135
+ return true;
675
2136
  }
676
2137
  }
677
2138
  return false;
678
2139
  };
679
2140
 
680
- var isGlob$1 = function isGlob(str, options) {
681
- if (typeof str !== 'string' || str === '') {
682
- return false;
683
- }
2141
+ /**
2142
+ * Returns true if every string in the given `list` matches
2143
+ * any of the given glob `patterns`.
2144
+ *
2145
+ * ```js
2146
+ * const mm = require('micromatch');
2147
+ * // mm.every(list, patterns[, options]);
2148
+ *
2149
+ * console.log(mm.every('foo.js', ['foo.js']));
2150
+ * // true
2151
+ * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
2152
+ * // true
2153
+ * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
2154
+ * // false
2155
+ * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
2156
+ * // false
2157
+ * ```
2158
+ * @param {String|Array} `list` The string or array of strings to test.
2159
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
2160
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
2161
+ * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
2162
+ * @api public
2163
+ */
684
2164
 
685
- if (isExtglob(str)) {
686
- return true;
2165
+ micromatch$1.every = (list, patterns, options) => {
2166
+ let items = [].concat(list);
2167
+
2168
+ for (let pattern of [].concat(patterns)) {
2169
+ let isMatch = picomatch(String(pattern), options);
2170
+ if (!items.every(item => isMatch(item))) {
2171
+ return false;
2172
+ }
687
2173
  }
2174
+ return true;
2175
+ };
688
2176
 
689
- var check = strictCheck;
2177
+ /**
2178
+ * Returns true if **all** of the given `patterns` match
2179
+ * the specified string.
2180
+ *
2181
+ * ```js
2182
+ * const mm = require('micromatch');
2183
+ * // mm.all(string, patterns[, options]);
2184
+ *
2185
+ * console.log(mm.all('foo.js', ['foo.js']));
2186
+ * // true
2187
+ *
2188
+ * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
2189
+ * // false
2190
+ *
2191
+ * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
2192
+ * // true
2193
+ *
2194
+ * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
2195
+ * // true
2196
+ * ```
2197
+ * @param {String|Array} `str` The string to test.
2198
+ * @param {String|Array} `patterns` One or more glob patterns to use for matching.
2199
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
2200
+ * @return {Boolean} Returns true if any patterns match `str`
2201
+ * @api public
2202
+ */
690
2203
 
691
- // optionally relax check
692
- if (options && options.strict === false) {
693
- check = relaxedCheck;
2204
+ micromatch$1.all = (str, patterns, options) => {
2205
+ if (typeof str !== 'string') {
2206
+ throw new TypeError(`Expected a string: "${util$2.inspect(str)}"`);
694
2207
  }
695
2208
 
696
- return check(str);
2209
+ return [].concat(patterns).every(p => picomatch(p, options)(str));
697
2210
  };
698
2211
 
699
- var isGlob = isGlob$1;
700
- var pathPosixDirname = p.posix.dirname;
701
- var isWin32 = require$$0.platform() === 'win32';
2212
+ /**
2213
+ * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
2214
+ *
2215
+ * ```js
2216
+ * const mm = require('micromatch');
2217
+ * // mm.capture(pattern, string[, options]);
2218
+ *
2219
+ * console.log(mm.capture('test/*.js', 'test/foo.js'));
2220
+ * //=> ['foo']
2221
+ * console.log(mm.capture('test/*.js', 'foo/bar.css'));
2222
+ * //=> null
2223
+ * ```
2224
+ * @param {String} `glob` Glob pattern to use for matching.
2225
+ * @param {String} `input` String to match
2226
+ * @param {Object} `options` See available [options](#options) for changing how matches are performed
2227
+ * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
2228
+ * @api public
2229
+ */
702
2230
 
703
- var slash = '/';
704
- var backslash = /\\/g;
705
- var enclosure = /[\{\[].*[\}\]]$/;
706
- var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
707
- var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
2231
+ micromatch$1.capture = (glob, input, options) => {
2232
+ let posix = utils$b.isWindows(options);
2233
+ let regex = picomatch.makeRe(String(glob), { ...options, capture: true });
2234
+ let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input);
2235
+
2236
+ if (match) {
2237
+ return match.slice(1).map(v => v === void 0 ? '' : v);
2238
+ }
2239
+ };
708
2240
 
709
2241
  /**
710
- * @param {string} str
711
- * @param {Object} opts
712
- * @param {boolean} [opts.flipBackslashes=true]
713
- * @returns {string}
2242
+ * Create a regular expression from the given glob `pattern`.
2243
+ *
2244
+ * ```js
2245
+ * const mm = require('micromatch');
2246
+ * // mm.makeRe(pattern[, options]);
2247
+ *
2248
+ * console.log(mm.makeRe('*.js'));
2249
+ * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
2250
+ * ```
2251
+ * @param {String} `pattern` A glob pattern to convert to regex.
2252
+ * @param {Object} `options`
2253
+ * @return {RegExp} Returns a regex created from the given pattern.
2254
+ * @api public
714
2255
  */
715
- var globParent$1 = function globParent(str, opts) {
716
- var options = Object.assign({ flipBackslashes: true }, opts);
717
2256
 
718
- // flip windows path separators
719
- if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
720
- str = str.replace(backslash, slash);
721
- }
2257
+ micromatch$1.makeRe = (...args) => picomatch.makeRe(...args);
722
2258
 
723
- // special case for strings ending in enclosure containing path separator
724
- if (enclosure.test(str)) {
725
- str += slash;
2259
+ /**
2260
+ * Scan a glob pattern to separate the pattern into segments. Used
2261
+ * by the [split](#split) method.
2262
+ *
2263
+ * ```js
2264
+ * const mm = require('micromatch');
2265
+ * const state = mm.scan(pattern[, options]);
2266
+ * ```
2267
+ * @param {String} `pattern`
2268
+ * @param {Object} `options`
2269
+ * @return {Object} Returns an object with
2270
+ * @api public
2271
+ */
2272
+
2273
+ micromatch$1.scan = (...args) => picomatch.scan(...args);
2274
+
2275
+ /**
2276
+ * Parse a glob pattern to create the source string for a regular
2277
+ * expression.
2278
+ *
2279
+ * ```js
2280
+ * const mm = require('micromatch');
2281
+ * const state = mm.parse(pattern[, options]);
2282
+ * ```
2283
+ * @param {String} `glob`
2284
+ * @param {Object} `options`
2285
+ * @return {Object} Returns an object with useful properties and output to be used as regex source string.
2286
+ * @api public
2287
+ */
2288
+
2289
+ micromatch$1.parse = (patterns, options) => {
2290
+ let res = [];
2291
+ for (let pattern of [].concat(patterns || [])) {
2292
+ for (let str of braces(String(pattern), options)) {
2293
+ res.push(picomatch.parse(str, options));
2294
+ }
726
2295
  }
2296
+ return res;
2297
+ };
727
2298
 
728
- // preserves full path in case of trailing path separator
729
- str += 'a';
2299
+ /**
2300
+ * Process the given brace `pattern`.
2301
+ *
2302
+ * ```js
2303
+ * const { braces } = require('micromatch');
2304
+ * console.log(braces('foo/{a,b,c}/bar'));
2305
+ * //=> [ 'foo/(a|b|c)/bar' ]
2306
+ *
2307
+ * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
2308
+ * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
2309
+ * ```
2310
+ * @param {String} `pattern` String with brace pattern to process.
2311
+ * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
2312
+ * @return {Array}
2313
+ * @api public
2314
+ */
730
2315
 
731
- // remove path parts that are globby
732
- do {
733
- str = pathPosixDirname(str);
734
- } while (isGlob(str) || globby.test(str));
2316
+ micromatch$1.braces = (pattern, options) => {
2317
+ if (typeof pattern !== 'string') throw new TypeError('Expected a string');
2318
+ if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
2319
+ return [pattern];
2320
+ }
2321
+ return braces(pattern, options);
2322
+ };
735
2323
 
736
- // remove escape chars and return result
737
- return str.replace(escaped, '$1');
2324
+ /**
2325
+ * Expand braces
2326
+ */
2327
+
2328
+ micromatch$1.braceExpand = (pattern, options) => {
2329
+ if (typeof pattern !== 'string') throw new TypeError('Expected a string');
2330
+ return micromatch$1.braces(pattern, { ...options, expand: true });
738
2331
  };
739
2332
 
2333
+ /**
2334
+ * Expose micromatch
2335
+ */
2336
+
2337
+ var micromatch_1 = micromatch$1;
2338
+
740
2339
  Object.defineProperty(pattern$1, "__esModule", { value: true });
741
2340
  pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
742
2341
  const path$5 = p;
@@ -934,7 +2533,7 @@ var stream$4 = {};
934
2533
  * Copyright (c) 2014-2020 Teambition
935
2534
  * Licensed under the MIT license.
936
2535
  */
937
- const Stream = require$$0$1;
2536
+ const Stream = require$$0$2;
938
2537
  const PassThrough = Stream.PassThrough;
939
2538
  const slice = Array.prototype.slice;
940
2539
 
@@ -1101,26 +2700,26 @@ function isEmpty(input) {
1101
2700
  }
1102
2701
  string$1.isEmpty = isEmpty;
1103
2702
 
1104
- Object.defineProperty(utils$b, "__esModule", { value: true });
1105
- utils$b.string = utils$b.stream = utils$b.pattern = utils$b.path = utils$b.fs = utils$b.errno = utils$b.array = void 0;
2703
+ Object.defineProperty(utils$g, "__esModule", { value: true });
2704
+ utils$g.string = utils$g.stream = utils$g.pattern = utils$g.path = utils$g.fs = utils$g.errno = utils$g.array = void 0;
1106
2705
  const array = array$1;
1107
- utils$b.array = array;
2706
+ utils$g.array = array;
1108
2707
  const errno = errno$1;
1109
- utils$b.errno = errno;
2708
+ utils$g.errno = errno;
1110
2709
  const fs$6 = fs$7;
1111
- utils$b.fs = fs$6;
2710
+ utils$g.fs = fs$6;
1112
2711
  const path$4 = path$7;
1113
- utils$b.path = path$4;
2712
+ utils$g.path = path$4;
1114
2713
  const pattern = pattern$1;
1115
- utils$b.pattern = pattern;
2714
+ utils$g.pattern = pattern;
1116
2715
  const stream$3 = stream$4;
1117
- utils$b.stream = stream$3;
2716
+ utils$g.stream = stream$3;
1118
2717
  const string = string$1;
1119
- utils$b.string = string;
2718
+ utils$g.string = string;
1120
2719
 
1121
2720
  Object.defineProperty(tasks, "__esModule", { value: true });
1122
2721
  tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
1123
- const utils$a = utils$b;
2722
+ const utils$a = utils$g;
1124
2723
  function generate(input, settings) {
1125
2724
  const patterns = processPatterns(input, settings);
1126
2725
  const ignore = processPatterns(settings.ignore, settings);
@@ -1314,7 +2913,7 @@ var fs$5 = {};
1314
2913
  (function (exports) {
1315
2914
  Object.defineProperty(exports, "__esModule", { value: true });
1316
2915
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
1317
- const fs = require$$0$2;
2916
+ const fs = require$$0$3;
1318
2917
  exports.FILE_SYSTEM_ADAPTER = {
1319
2918
  lstat: fs.lstat,
1320
2919
  stat: fs.stat,
@@ -1665,7 +3264,7 @@ var fs$1 = {};
1665
3264
  (function (exports) {
1666
3265
  Object.defineProperty(exports, "__esModule", { value: true });
1667
3266
  exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
1668
- const fs = require$$0$2;
3267
+ const fs = require$$0$3;
1669
3268
  exports.FILE_SYSTEM_ADAPTER = {
1670
3269
  lstat: fs.lstat,
1671
3270
  stat: fs.stat,
@@ -1790,8 +3389,8 @@ function fastqueue (context, worker, concurrency) {
1790
3389
 
1791
3390
  var self = {
1792
3391
  push: push,
1793
- drain: noop$1,
1794
- saturated: noop$1,
3392
+ drain: noop,
3393
+ saturated: noop,
1795
3394
  pause: pause,
1796
3395
  paused: false,
1797
3396
  concurrency: concurrency,
@@ -1801,7 +3400,7 @@ function fastqueue (context, worker, concurrency) {
1801
3400
  length: length,
1802
3401
  getQueue: getQueue,
1803
3402
  unshift: unshift,
1804
- empty: noop$1,
3403
+ empty: noop,
1805
3404
  kill: kill,
1806
3405
  killAndDrain: killAndDrain,
1807
3406
  error: error
@@ -1860,7 +3459,7 @@ function fastqueue (context, worker, concurrency) {
1860
3459
  current.context = context;
1861
3460
  current.release = release;
1862
3461
  current.value = value;
1863
- current.callback = done || noop$1;
3462
+ current.callback = done || noop;
1864
3463
  current.errorHandler = errorHandler;
1865
3464
 
1866
3465
  if (_running === self.concurrency || self.paused) {
@@ -1884,7 +3483,7 @@ function fastqueue (context, worker, concurrency) {
1884
3483
  current.context = context;
1885
3484
  current.release = release;
1886
3485
  current.value = value;
1887
- current.callback = done || noop$1;
3486
+ current.callback = done || noop;
1888
3487
 
1889
3488
  if (_running === self.concurrency || self.paused) {
1890
3489
  if (queueHead) {
@@ -1928,14 +3527,14 @@ function fastqueue (context, worker, concurrency) {
1928
3527
  function kill () {
1929
3528
  queueHead = null;
1930
3529
  queueTail = null;
1931
- self.drain = noop$1;
3530
+ self.drain = noop;
1932
3531
  }
1933
3532
 
1934
3533
  function killAndDrain () {
1935
3534
  queueHead = null;
1936
3535
  queueTail = null;
1937
3536
  self.drain();
1938
- self.drain = noop$1;
3537
+ self.drain = noop;
1939
3538
  }
1940
3539
 
1941
3540
  function error (handler) {
@@ -1943,13 +3542,13 @@ function fastqueue (context, worker, concurrency) {
1943
3542
  }
1944
3543
  }
1945
3544
 
1946
- function noop$1 () {}
3545
+ function noop () {}
1947
3546
 
1948
3547
  function Task () {
1949
3548
  this.value = null;
1950
- this.callback = noop$1;
3549
+ this.callback = noop;
1951
3550
  this.next = null;
1952
- this.release = noop$1;
3551
+ this.release = noop;
1953
3552
  this.context = null;
1954
3553
  this.errorHandler = null;
1955
3554
 
@@ -1960,7 +3559,7 @@ function Task () {
1960
3559
  var errorHandler = self.errorHandler;
1961
3560
  var val = self.value;
1962
3561
  self.value = null;
1963
- self.callback = noop$1;
3562
+ self.callback = noop;
1964
3563
  if (self.errorHandler) {
1965
3564
  errorHandler(err, val);
1966
3565
  }
@@ -2008,7 +3607,7 @@ function queueAsPromised (context, worker, concurrency) {
2008
3607
  // Let's fork the promise chain to
2009
3608
  // make the error bubble up to the user but
2010
3609
  // not lead to a unhandledRejection
2011
- p.catch(noop$1);
3610
+ p.catch(noop);
2012
3611
 
2013
3612
  return p
2014
3613
  }
@@ -2027,7 +3626,7 @@ function queueAsPromised (context, worker, concurrency) {
2027
3626
  // Let's fork the promise chain to
2028
3627
  // make the error bubble up to the user but
2029
3628
  // not lead to a unhandledRejection
2030
- p.catch(noop$1);
3629
+ p.catch(noop);
2031
3630
 
2032
3631
  return p
2033
3632
  }
@@ -2098,7 +3697,7 @@ let Reader$1 = class Reader {
2098
3697
  reader$1.default = Reader$1;
2099
3698
 
2100
3699
  Object.defineProperty(async$4, "__esModule", { value: true });
2101
- const events_1 = require$$0$3;
3700
+ const events_1 = require$$0$4;
2102
3701
  const fsScandir$2 = out$2;
2103
3702
  const fastq = queueExports;
2104
3703
  const common$1 = common$3;
@@ -2227,7 +3826,7 @@ function callSuccessCallback(callback, entries) {
2227
3826
  var stream$2 = {};
2228
3827
 
2229
3828
  Object.defineProperty(stream$2, "__esModule", { value: true });
2230
- const stream_1$5 = require$$0$1;
3829
+ const stream_1$5 = require$$0$2;
2231
3830
  const async_1$3 = async$4;
2232
3831
  class StreamProvider {
2233
3832
  constructor(_root, _settings) {
@@ -2404,7 +4003,7 @@ var reader = {};
2404
4003
  Object.defineProperty(reader, "__esModule", { value: true });
2405
4004
  const path$1 = p;
2406
4005
  const fsStat$2 = out$1;
2407
- const utils$6 = utils$b;
4006
+ const utils$6 = utils$g;
2408
4007
  class Reader {
2409
4008
  constructor(_settings) {
2410
4009
  this._settings = _settings;
@@ -2437,7 +4036,7 @@ reader.default = Reader;
2437
4036
  var stream$1 = {};
2438
4037
 
2439
4038
  Object.defineProperty(stream$1, "__esModule", { value: true });
2440
- const stream_1$3 = require$$0$1;
4039
+ const stream_1$3 = require$$0$2;
2441
4040
  const fsStat$1 = out$1;
2442
4041
  const fsWalk$2 = out$3;
2443
4042
  const reader_1$2 = reader;
@@ -2535,7 +4134,7 @@ var partial = {};
2535
4134
  var matcher = {};
2536
4135
 
2537
4136
  Object.defineProperty(matcher, "__esModule", { value: true });
2538
- const utils$5 = utils$b;
4137
+ const utils$5 = utils$g;
2539
4138
  class Matcher {
2540
4139
  constructor(_patterns, _settings, _micromatchOptions) {
2541
4140
  this._patterns = _patterns;
@@ -2618,7 +4217,7 @@ class PartialMatcher extends matcher_1.default {
2618
4217
  partial.default = PartialMatcher;
2619
4218
 
2620
4219
  Object.defineProperty(deep, "__esModule", { value: true });
2621
- const utils$4 = utils$b;
4220
+ const utils$4 = utils$g;
2622
4221
  const partial_1 = partial;
2623
4222
  class DeepFilter {
2624
4223
  constructor(_settings, _micromatchOptions) {
@@ -2682,7 +4281,7 @@ deep.default = DeepFilter;
2682
4281
  var entry$1 = {};
2683
4282
 
2684
4283
  Object.defineProperty(entry$1, "__esModule", { value: true });
2685
- const utils$3 = utils$b;
4284
+ const utils$3 = utils$g;
2686
4285
  class EntryFilter {
2687
4286
  constructor(_settings, _micromatchOptions) {
2688
4287
  this._settings = _settings;
@@ -2747,7 +4346,7 @@ entry$1.default = EntryFilter;
2747
4346
  var error = {};
2748
4347
 
2749
4348
  Object.defineProperty(error, "__esModule", { value: true });
2750
- const utils$2 = utils$b;
4349
+ const utils$2 = utils$g;
2751
4350
  class ErrorFilter {
2752
4351
  constructor(_settings) {
2753
4352
  this._settings = _settings;
@@ -2764,7 +4363,7 @@ error.default = ErrorFilter;
2764
4363
  var entry = {};
2765
4364
 
2766
4365
  Object.defineProperty(entry, "__esModule", { value: true });
2767
- const utils$1 = utils$b;
4366
+ const utils$1 = utils$g;
2768
4367
  class EntryTransformer {
2769
4368
  constructor(_settings) {
2770
4369
  this._settings = _settings;
@@ -2863,7 +4462,7 @@ async$7.default = ProviderAsync;
2863
4462
  var stream = {};
2864
4463
 
2865
4464
  Object.defineProperty(stream, "__esModule", { value: true });
2866
- const stream_1$1 = require$$0$1;
4465
+ const stream_1$1 = require$$0$2;
2867
4466
  const stream_2 = stream$1;
2868
4467
  const provider_1$1 = provider;
2869
4468
  class ProviderStream extends provider_1$1.default {
@@ -2968,7 +4567,7 @@ var settings = {};
2968
4567
  (function (exports) {
2969
4568
  Object.defineProperty(exports, "__esModule", { value: true });
2970
4569
  exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
2971
- const fs = require$$0$2;
4570
+ const fs = require$$0$3;
2972
4571
  const os = require$$0;
2973
4572
  /**
2974
4573
  * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
@@ -3031,7 +4630,7 @@ const async_1 = async$7;
3031
4630
  const stream_1 = stream;
3032
4631
  const sync_1 = sync$1;
3033
4632
  const settings_1 = settings;
3034
- const utils = utils$b;
4633
+ const utils = utils$g;
3035
4634
  async function FastGlob(source, options) {
3036
4635
  assertPatternsInput(source);
3037
4636
  const works = getWorks(source, async_1.default, options);
@@ -3128,113 +4727,6 @@ var out = FastGlob;
3128
4727
 
3129
4728
  var fg = /*@__PURE__*/getDefaultExportFromCjs(out);
3130
4729
 
3131
- /// <reference types="../types/index.d.ts" />
3132
-
3133
- // (c) 2020-present Andrea Giammarchi
3134
-
3135
- const {parse: $parse, stringify: $stringify} = JSON;
3136
- const {keys: keys$1} = Object;
3137
-
3138
- const Primitive = String; // it could be Number
3139
- const primitive = 'string'; // it could be 'number'
3140
-
3141
- const ignore = {};
3142
- const object = 'object';
3143
-
3144
- const noop = (_, value) => value;
3145
-
3146
- const primitives = value => (
3147
- value instanceof Primitive ? Primitive(value) : value
3148
- );
3149
-
3150
- const Primitives = (_, value) => (
3151
- typeof value === primitive ? new Primitive(value) : value
3152
- );
3153
-
3154
- const revive = (input, parsed, output, $) => {
3155
- const lazy = [];
3156
- for (let ke = keys$1(output), {length} = ke, y = 0; y < length; y++) {
3157
- const k = ke[y];
3158
- const value = output[k];
3159
- if (value instanceof Primitive) {
3160
- const tmp = input[value];
3161
- if (typeof tmp === object && !parsed.has(tmp)) {
3162
- parsed.add(tmp);
3163
- output[k] = ignore;
3164
- lazy.push({k, a: [input, parsed, tmp, $]});
3165
- }
3166
- else
3167
- output[k] = $.call(output, k, tmp);
3168
- }
3169
- else if (output[k] !== ignore)
3170
- output[k] = $.call(output, k, value);
3171
- }
3172
- for (let {length} = lazy, i = 0; i < length; i++) {
3173
- const {k, a} = lazy[i];
3174
- output[k] = $.call(output, k, revive.apply(null, a));
3175
- }
3176
- return output;
3177
- };
3178
-
3179
- const set = (known, input, value) => {
3180
- const index = Primitive(input.push(value) - 1);
3181
- known.set(value, index);
3182
- return index;
3183
- };
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
- */
3191
- const parse$3 = (text, reviver) => {
3192
- const input = $parse(text, Primitives).map(primitives);
3193
- const value = input[0];
3194
- const $ = reviver || noop;
3195
- const tmp = typeof value === object && value ?
3196
- revive(input, new Set, value, $) :
3197
- value;
3198
- return $.call({'': tmp}, '', tmp);
3199
- };
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
- */
3208
- const stringify = (value, replacer, space) => {
3209
- const $ = replacer && typeof replacer === object ?
3210
- (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) :
3211
- (replacer || noop);
3212
- const known = new Map;
3213
- const input = [];
3214
- const output = [];
3215
- let i = +set(known, input, $.call({'': value}, '', value));
3216
- let firstRun = !i;
3217
- while (i < input.length) {
3218
- firstRun = true;
3219
- output[i] = $stringify(input[i++], replace, space);
3220
- }
3221
- return '[' + output.join(',') + ']';
3222
- function replace(key, value) {
3223
- if (firstRun) {
3224
- firstRun = !firstRun;
3225
- return value;
3226
- }
3227
- const after = $.call(this, key, value);
3228
- switch (typeof after) {
3229
- case object:
3230
- if (after === null) return after;
3231
- case primitive:
3232
- return known.get(after) || set(known, input, after);
3233
- }
3234
- return after;
3235
- }
3236
- };
3237
-
3238
4730
  var bufferUtil$1 = {exports: {}};
3239
4731
 
3240
4732
  var constants = {
@@ -3437,7 +4929,7 @@ let Limiter$1 = class Limiter {
3437
4929
 
3438
4930
  var limiter = Limiter$1;
3439
4931
 
3440
- const zlib = require$$0$4;
4932
+ const zlib = require$$0$5;
3441
4933
 
3442
4934
  const bufferUtil = bufferUtilExports;
3443
4935
  const Limiter = limiter;
@@ -3954,7 +5446,7 @@ var validation = {exports: {}};
3954
5446
 
3955
5447
  var isValidUTF8_1;
3956
5448
 
3957
- const { isUtf8 } = require$$0$5;
5449
+ const { isUtf8 } = require$$0$6;
3958
5450
 
3959
5451
  //
3960
5452
  // Allowed token characters:
@@ -4085,7 +5577,7 @@ if (isUtf8) {
4085
5577
 
4086
5578
  var validationExports = validation.exports;
4087
5579
 
4088
- const { Writable } = require$$0$1;
5580
+ const { Writable } = require$$0$2;
4089
5581
 
4090
5582
  const PerMessageDeflate$3 = permessageDeflate;
4091
5583
  const {
@@ -5757,7 +7249,7 @@ var extension$1 = { format: format$1, parse: parse$2 };
5757
7249
 
5758
7250
  /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */
5759
7251
 
5760
- const EventEmitter$1 = require$$0$3;
7252
+ const EventEmitter$1 = require$$0$4;
5761
7253
  const https = require$$1$1;
5762
7254
  const http$1 = require$$2;
5763
7255
  const net = require$$3;
@@ -7152,7 +8644,7 @@ var subprotocol$1 = { parse };
7152
8644
 
7153
8645
  /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
7154
8646
 
7155
- const EventEmitter = require$$0$3;
8647
+ const EventEmitter = require$$0$4;
7156
8648
  const http = require$$2;
7157
8649
  const { createHash } = require$$1;
7158
8650
 
@@ -7689,9 +9181,8 @@ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
7689
9181
 
7690
9182
  var WebSocketServer$1 = /*@__PURE__*/getDefaultExportFromCjs(websocketServer);
7691
9183
 
7692
- function setup(vitestOrWorkspace, _server) {
9184
+ function setup(ctx, _server) {
7693
9185
  var _a;
7694
- const ctx = "ctx" in vitestOrWorkspace ? vitestOrWorkspace.ctx : vitestOrWorkspace;
7695
9186
  const wss = new WebSocketServer$1({ noServer: true });
7696
9187
  const clients = /* @__PURE__ */ new Map();
7697
9188
  const server = _server || ctx.server;
@@ -7706,16 +9197,9 @@ function setup(vitestOrWorkspace, _server) {
7706
9197
  setupClient(ws);
7707
9198
  });
7708
9199
  });
7709
- function checkFileAccess(path) {
7710
- if (!isFileServingAllowed(path, server))
7711
- throw new Error(`Access denied to "${path}". See Vite config documentation for "server.fs": https://vitejs.dev/config/server-options.html#server-fs-strict.`);
7712
- }
7713
9200
  function setupClient(ws) {
7714
9201
  const rpc = createBirpc(
7715
9202
  {
7716
- async onUnhandledError(error, type) {
7717
- ctx.state.catchError(error, type);
7718
- },
7719
9203
  async onCollected(files) {
7720
9204
  ctx.state.collectFiles(files);
7721
9205
  await ctx.report("onCollected", files);
@@ -7724,30 +9208,11 @@ function setup(vitestOrWorkspace, _server) {
7724
9208
  ctx.state.updateTasks(packs);
7725
9209
  await ctx.report("onTaskUpdate", packs);
7726
9210
  },
7727
- onAfterSuiteRun(meta) {
7728
- var _a2;
7729
- (_a2 = ctx.coverageProvider) == null ? void 0 : _a2.onAfterSuiteRun(meta);
7730
- },
7731
- getFiles() {
7732
- return ctx.state.getFiles();
7733
- },
7734
- getPaths() {
7735
- return ctx.state.getPaths();
7736
- },
7737
- sendLog(log) {
7738
- return ctx.report("onUserConsoleLog", log);
7739
- },
7740
- resolveSnapshotPath(testPath) {
7741
- return ctx.snapshot.resolvePath(testPath);
7742
- },
7743
- resolveSnapshotRawPath(testPath, rawPath) {
7744
- return ctx.snapshot.resolveRawPath(testPath, rawPath);
9211
+ getFiles() {
9212
+ return ctx.state.getFiles();
7745
9213
  },
7746
- async readSnapshotFile(snapshotPath) {
7747
- checkFileAccess(snapshotPath);
7748
- if (!existsSync(snapshotPath))
7749
- return null;
7750
- return promises$1.readFile(snapshotPath, "utf-8");
9214
+ getPaths() {
9215
+ return ctx.state.getPaths();
7751
9216
  },
7752
9217
  async readTestFile(id) {
7753
9218
  if (!ctx.state.filesMap.has(id) || !existsSync(id))
@@ -7759,35 +9224,15 @@ function setup(vitestOrWorkspace, _server) {
7759
9224
  throw new Error(`Test file "${id}" was not registered, so it cannot be updated using the API.`);
7760
9225
  return promises$1.writeFile(id, content, "utf-8");
7761
9226
  },
7762
- async saveSnapshotFile(id, content) {
7763
- checkFileAccess(id);
7764
- await promises$1.mkdir(dirname(id), { recursive: true });
7765
- return promises$1.writeFile(id, content, "utf-8");
7766
- },
7767
- async removeSnapshotFile(id) {
7768
- checkFileAccess(id);
7769
- if (!existsSync(id))
7770
- throw new Error(`Snapshot file "${id}" does not exist.`);
7771
- return promises$1.unlink(id);
7772
- },
7773
- snapshotSaved(snapshot) {
7774
- ctx.snapshot.add(snapshot);
7775
- },
7776
9227
  async rerun(files) {
7777
9228
  await ctx.rerunFiles(files);
7778
9229
  },
7779
9230
  getConfig() {
7780
- return vitestOrWorkspace.config;
7781
- },
7782
- async getBrowserFileSourceMap(id) {
7783
- var _a2, _b;
7784
- if (!("ctx" in vitestOrWorkspace))
7785
- return void 0;
7786
- const mod = (_a2 = vitestOrWorkspace.browser) == null ? void 0 : _a2.moduleGraph.getModuleById(id);
7787
- return (_b = mod == null ? void 0 : mod.transformResult) == null ? void 0 : _b.map;
9231
+ return ctx.config;
7788
9232
  },
7789
- async getTransformResult(id) {
7790
- const result = await ctx.vitenode.transformRequest(id);
9233
+ async getTransformResult(projectName, id, browser = false) {
9234
+ const project = ctx.getProjectByName(projectName);
9235
+ const result = browser ? await project.browser.transformRequest(id) : await project.vitenode.transformRequest(id);
7791
9236
  if (result) {
7792
9237
  try {
7793
9238
  result.source = result.source || await promises$1.readFile(id, "utf-8");
@@ -7796,59 +9241,36 @@ function setup(vitestOrWorkspace, _server) {
7796
9241
  return result;
7797
9242
  }
7798
9243
  },
7799
- async getModuleGraph(id) {
7800
- return getModuleGraph(ctx, id);
9244
+ async getModuleGraph(project, id, browser) {
9245
+ return getModuleGraph(ctx, project, id, browser);
7801
9246
  },
7802
9247
  updateSnapshot(file) {
7803
9248
  if (!file)
7804
9249
  return ctx.updateSnapshot();
7805
9250
  return ctx.updateSnapshot([file.filepath]);
7806
9251
  },
7807
- onCancel(reason) {
7808
- ctx.cancelCurrentRun(reason);
7809
- },
7810
- debug(...args) {
7811
- ctx.logger.console.debug(...args);
7812
- },
7813
- getCountOfFailedTests() {
7814
- return ctx.state.getCountOfFailedTests();
7815
- },
7816
9252
  getUnhandledErrors() {
7817
9253
  return ctx.state.getUnhandledErrors();
7818
9254
  },
7819
- // TODO: have a separate websocket conection for private browser API
7820
- getBrowserFiles() {
7821
- var _a2;
7822
- if (!("ctx" in vitestOrWorkspace))
7823
- throw new Error("`getBrowserTestFiles` is only available in the browser API");
7824
- return ((_a2 = vitestOrWorkspace.browserState) == null ? void 0 : _a2.files) ?? [];
7825
- },
7826
- finishBrowserTests() {
7827
- var _a2;
7828
- if (!("ctx" in vitestOrWorkspace))
7829
- throw new Error("`finishBrowserTests` is only available in the browser API");
7830
- return (_a2 = vitestOrWorkspace.browserState) == null ? void 0 : _a2.resolve();
7831
- },
7832
- getProvidedContext() {
7833
- return "ctx" in vitestOrWorkspace ? vitestOrWorkspace.getProvidedContext() : {};
7834
- },
7835
9255
  async getTestFiles() {
7836
9256
  const spec = await ctx.globTestFiles();
7837
- return spec.map(([project, file]) => [project.getName(), file]);
9257
+ return spec.map(([project, file]) => [{
9258
+ name: project.config.name,
9259
+ root: project.config.root
9260
+ }, file]);
7838
9261
  }
7839
9262
  },
7840
9263
  {
7841
9264
  post: (msg) => ws.send(msg),
7842
9265
  on: (fn) => ws.on("message", fn),
7843
- eventNames: ["onUserConsoleLog", "onFinished", "onFinishedReportCoverage", "onCollected", "onCancel", "onTaskUpdate"],
7844
- serialize: (data) => stringify(data, stringifyReplace),
7845
- deserialize: parse$3,
9266
+ eventNames: ["onUserConsoleLog", "onFinished", "onFinishedReportCoverage", "onCollected", "onTaskUpdate"],
9267
+ serialize: (data) => stringify$5(data, stringifyReplace),
9268
+ deserialize: parse$5,
7846
9269
  onTimeoutError(functionName) {
7847
9270
  throw new Error(`[vitest-api]: Timeout calling "${functionName}"`);
7848
9271
  }
7849
9272
  }
7850
9273
  );
7851
- ctx.onCancel((reason) => rpc.onCancel(reason));
7852
9274
  clients.set(ws, rpc);
7853
9275
  ws.on("close", () => {
7854
9276
  clients.delete(ws);
@@ -7867,7 +9289,15 @@ class WebSocketReporter {
7867
9289
  return;
7868
9290
  this.clients.forEach((client) => {
7869
9291
  var _a, _b, _c;
7870
- (_c = (_b = (_a = client.onCollected) == null ? void 0 : _a.call(client, files)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
9292
+ (_c = (_b = (_a = client.onCollected) == null ? void 0 : _a.call(client, files)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
9293
+ });
9294
+ }
9295
+ onSpecsCollected(specs) {
9296
+ if (this.clients.size === 0)
9297
+ return;
9298
+ this.clients.forEach((client) => {
9299
+ var _a, _b, _c;
9300
+ (_c = (_b = (_a = client.onSpecsCollected) == null ? void 0 : _a.call(client, specs)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7871
9301
  });
7872
9302
  }
7873
9303
  async onTaskUpdate(packs) {
@@ -7886,25 +9316,25 @@ class WebSocketReporter {
7886
9316
  });
7887
9317
  this.clients.forEach((client) => {
7888
9318
  var _a, _b, _c;
7889
- (_c = (_b = (_a = client.onTaskUpdate) == null ? void 0 : _a.call(client, packs)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
9319
+ (_c = (_b = (_a = client.onTaskUpdate) == null ? void 0 : _a.call(client, packs)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7890
9320
  });
7891
9321
  }
7892
9322
  onFinished(files, errors) {
7893
9323
  this.clients.forEach((client) => {
7894
9324
  var _a, _b, _c;
7895
- (_c = (_b = (_a = client.onFinished) == null ? void 0 : _a.call(client, files, errors)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
9325
+ (_c = (_b = (_a = client.onFinished) == null ? void 0 : _a.call(client, files, errors)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7896
9326
  });
7897
9327
  }
7898
9328
  onFinishedReportCoverage() {
7899
9329
  this.clients.forEach((client) => {
7900
9330
  var _a, _b, _c;
7901
- (_c = (_b = (_a = client.onFinishedReportCoverage) == null ? void 0 : _a.call(client)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
9331
+ (_c = (_b = (_a = client.onFinishedReportCoverage) == null ? void 0 : _a.call(client)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7902
9332
  });
7903
9333
  }
7904
9334
  onUserConsoleLog(log) {
7905
9335
  this.clients.forEach((client) => {
7906
9336
  var _a, _b, _c;
7907
- (_c = (_b = (_a = client.onUserConsoleLog) == null ? void 0 : _a.call(client, log)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$2);
9337
+ (_c = (_b = (_a = client.onUserConsoleLog) == null ? void 0 : _a.call(client, log)) == null ? void 0 : _b.catch) == null ? void 0 : _c.call(_b, noop$1);
7908
9338
  });
7909
9339
  }
7910
9340
  }
@@ -7932,7 +9362,7 @@ async function groupFilesByEnv(files) {
7932
9362
  const filesWithEnv = await Promise.all(files.map(async ([project, file]) => {
7933
9363
  var _a, _b;
7934
9364
  const code = await promises$1.readFile(file, "utf-8");
7935
- let env = (_a = code.match(/@(?:vitest|jest)-environment\s+?([\w-]+)\b/)) == null ? void 0 : _a[1];
9365
+ let env = (_a = code.match(/@(?:vitest|jest)-environment\s+([\w-]+)\b/)) == null ? void 0 : _a[1];
7936
9366
  if (!env) {
7937
9367
  for (const [glob, target] of project.config.environmentMatchGlobs || []) {
7938
9368
  if (mm.isMatch(file, glob, { cwd: project.config.root })) {
@@ -8355,34 +9785,78 @@ See https://vitest.dev/guide/common-errors.html#failed-to-terminate-worker for t
8355
9785
  };
8356
9786
  }
8357
9787
 
9788
+ function createDebugger(namespace) {
9789
+ const debug = createDebug(namespace);
9790
+ if (debug.enabled)
9791
+ return debug;
9792
+ }
9793
+
9794
+ const debug$1 = createDebugger("vitest:browser:pool");
8358
9795
  function createBrowserPool(ctx) {
8359
9796
  const providers = /* @__PURE__ */ new Set();
8360
- const waitForTests = async (project, files) => {
8361
- var _a;
9797
+ const waitForTests = async (contextId, project, files) => {
8362
9798
  const defer = createDefer();
8363
- (_a = project.browserState) == null ? void 0 : _a.resolve();
8364
- project.browserState = {
9799
+ project.browserState.set(contextId, {
8365
9800
  files,
8366
9801
  resolve: () => {
8367
9802
  defer.resolve();
8368
- project.browserState = void 0;
9803
+ project.browserState.delete(contextId);
8369
9804
  },
8370
9805
  reject: defer.reject
8371
- };
9806
+ });
8372
9807
  return await defer;
8373
9808
  };
8374
9809
  const runTests = async (project, files) => {
8375
9810
  var _a;
8376
9811
  ctx.state.clearFiles(project, files);
9812
+ const threadsCount = getThreadsCount(project);
8377
9813
  const provider = project.browserProvider;
8378
9814
  providers.add(provider);
8379
9815
  const resolvedUrls = (_a = project.browser) == null ? void 0 : _a.resolvedUrls;
8380
9816
  const origin = (resolvedUrls == null ? void 0 : resolvedUrls.local[0]) ?? (resolvedUrls == null ? void 0 : resolvedUrls.network[0]);
8381
9817
  if (!origin)
8382
9818
  throw new Error(`Can't find browser origin URL for project "${project.config.name}"`);
8383
- const promise = waitForTests(project, files);
8384
- await provider.openPage(new URL("/", origin).toString());
8385
- await promise;
9819
+ const filesPerThread = Math.ceil(files.length / threadsCount);
9820
+ const chunks = [];
9821
+ for (let i = 0; i < files.length; i += filesPerThread) {
9822
+ const chunk = files.slice(i, i + filesPerThread);
9823
+ chunks.push(chunk);
9824
+ }
9825
+ debug$1 == null ? void 0 : debug$1(
9826
+ `[%s] Running %s tests in %s chunks (%s threads)`,
9827
+ project.getName() || "core",
9828
+ files.length,
9829
+ chunks.length,
9830
+ threadsCount
9831
+ );
9832
+ const orchestrators = [...project.browserRpc.orchestrators.entries()];
9833
+ const promises = [];
9834
+ chunks.forEach((files2, index) => {
9835
+ if (orchestrators[index]) {
9836
+ const [contextId, orchestrator] = orchestrators[index];
9837
+ debug$1 == null ? void 0 : debug$1(
9838
+ "Reusing orchestrator (context %s) for files: %s",
9839
+ contextId,
9840
+ [...files2.map((f) => relative(project.config.root, f))].join(", ")
9841
+ );
9842
+ const promise = waitForTests(contextId, project, files2);
9843
+ promises.push(promise);
9844
+ orchestrator.createTesters(files2);
9845
+ } else {
9846
+ const contextId = crypto.randomUUID();
9847
+ const waitPromise = waitForTests(contextId, project, files2);
9848
+ debug$1 == null ? void 0 : debug$1(
9849
+ "Opening a new context %s for files: %s",
9850
+ contextId,
9851
+ [...files2.map((f) => relative(project.config.root, f))].join(", ")
9852
+ );
9853
+ const url = new URL("/", origin);
9854
+ url.searchParams.set("contextId", contextId);
9855
+ const page = provider.openPage(contextId, url.toString()).then(() => waitPromise);
9856
+ promises.push(page);
9857
+ }
9858
+ });
9859
+ await Promise.all(promises);
8386
9860
  };
8387
9861
  const runWorkspaceTests = async (specs) => {
8388
9862
  const groupedFiles = /* @__PURE__ */ new Map();
@@ -8394,6 +9868,15 @@ function createBrowserPool(ctx) {
8394
9868
  for (const [project, files] of groupedFiles.entries())
8395
9869
  await runTests(project, files);
8396
9870
  };
9871
+ const numCpus = typeof nodeos.availableParallelism === "function" ? nodeos.availableParallelism() : nodeos.cpus().length;
9872
+ function getThreadsCount(project) {
9873
+ const config = project.config.browser;
9874
+ if (!config.headless || !project.browserProvider.supportsParallelism)
9875
+ return 1;
9876
+ if (!config.fileParallelism)
9877
+ return 1;
9878
+ return ctx.config.watch ? Math.max(Math.floor(numCpus / 2), 1) : Math.max(numCpus - 1, 1);
9879
+ }
8397
9880
  return {
8398
9881
  name: "browser",
8399
9882
  async close() {
@@ -8420,7 +9903,7 @@ function stringToBytes(input, percentageReference) {
8420
9903
  return input;
8421
9904
  if (typeof input === "string") {
8422
9905
  if (Number.isNaN(Number.parseFloat(input.slice(-1)))) {
8423
- let [, numericString, trailingChars] = input.match(/(.*?)([^0-9.-]+)$/i) || [];
9906
+ let [, numericString, trailingChars] = input.match(/(.*?)([^0-9.-]+)$/) || [];
8424
9907
  if (trailingChars && numericString) {
8425
9908
  const numericValue = Number.parseFloat(numericString);
8426
9909
  trailingChars = trailingChars.toLowerCase();
@@ -8821,6 +10304,26 @@ function getMemoryLimit(config) {
8821
10304
  }
8822
10305
 
8823
10306
  const builtinPools = ["forks", "threads", "browser", "vmThreads", "vmForks", "typescript"];
10307
+ function getDefaultPoolName(project, file) {
10308
+ if (project.config.typecheck.enabled) {
10309
+ for (const glob of project.config.typecheck.include) {
10310
+ if (mm.isMatch(file, glob, { cwd: project.config.root }))
10311
+ return "typescript";
10312
+ }
10313
+ }
10314
+ if (project.config.browser.enabled)
10315
+ return "browser";
10316
+ return project.config.pool;
10317
+ }
10318
+ function getFilePoolName(project, file) {
10319
+ for (const [glob, pool] of project.config.poolMatchGlobs) {
10320
+ if (pool === "browser")
10321
+ throw new Error('Since Vitest 0.31.0 "browser" pool is not supported in "poolMatchGlobs". You can create a workspace to run some of your tests in browser in parallel. Read more: https://vitest.dev/guide/workspace');
10322
+ if (mm.isMatch(file, glob, { cwd: project.config.root }))
10323
+ return pool;
10324
+ }
10325
+ return getDefaultPoolName(project, file);
10326
+ }
8824
10327
  function createPool(ctx) {
8825
10328
  const pools = {
8826
10329
  forks: null,
@@ -8830,26 +10333,6 @@ function createPool(ctx) {
8830
10333
  vmForks: null,
8831
10334
  typescript: null
8832
10335
  };
8833
- function getDefaultPoolName(project, file) {
8834
- if (project.config.typecheck.enabled) {
8835
- for (const glob of project.config.typecheck.include) {
8836
- if (mm.isMatch(file, glob, { cwd: project.config.root }))
8837
- return "typescript";
8838
- }
8839
- }
8840
- if (project.config.browser.enabled)
8841
- return "browser";
8842
- return project.config.pool;
8843
- }
8844
- function getPoolName([project, file]) {
8845
- for (const [glob, pool] of project.config.poolMatchGlobs) {
8846
- if (pool === "browser")
8847
- throw new Error('Since Vitest 0.31.0 "browser" pool is not supported in "poolMatchGlobs". You can create a workspace to run some of your tests in browser in parallel. Read more: https://vitest.dev/guide/workspace');
8848
- if (mm.isMatch(file, glob, { cwd: project.config.root }))
8849
- return pool;
8850
- }
8851
- return getDefaultPoolName(project, file);
8852
- }
8853
10336
  const potentialConditions = /* @__PURE__ */ new Set(["production", "development", ...ctx.server.config.resolve.conditions]);
8854
10337
  const conditions = [...potentialConditions].filter((condition) => {
8855
10338
  if (condition === "production")
@@ -8912,7 +10395,7 @@ function createPool(ctx) {
8912
10395
  typescript: () => createTypecheckPool(ctx)
8913
10396
  };
8914
10397
  for (const spec of files) {
8915
- const pool = getPoolName(spec);
10398
+ const pool = getFilePoolName(spec[0], spec[1]);
8916
10399
  filesByPool[pool] ?? (filesByPool[pool] = []);
8917
10400
  filesByPool[pool].push(spec);
8918
10401
  }
@@ -9068,6 +10551,9 @@ class StateManager {
9068
10551
  files.forEach((file) => {
9069
10552
  const existing = this.filesMap.get(file.filepath) || [];
9070
10553
  const otherProject = existing.filter((i) => i.projectName !== file.projectName);
10554
+ const currentFile = existing.find((i) => i.projectName === file.projectName);
10555
+ if (currentFile)
10556
+ file.logs = currentFile.logs;
9071
10557
  otherProject.push(file);
9072
10558
  this.filesMap.set(file.filepath, otherProject);
9073
10559
  this.updateId(file);
@@ -9078,13 +10564,21 @@ class StateManager {
9078
10564
  const project = _project;
9079
10565
  paths.forEach((path) => {
9080
10566
  const files = this.filesMap.get(path);
9081
- if (!files)
10567
+ const fileTask = createFileTask(path, project.config.root, project.config.name);
10568
+ this.idMap.set(fileTask.id, fileTask);
10569
+ if (!files) {
10570
+ this.filesMap.set(path, [fileTask]);
9082
10571
  return;
10572
+ }
9083
10573
  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);
10574
+ if (!filtered.length) {
10575
+ this.filesMap.set(path, [fileTask]);
10576
+ } else {
10577
+ this.filesMap.set(path, [
10578
+ ...filtered,
10579
+ fileTask
10580
+ ]);
10581
+ }
9088
10582
  });
9089
10583
  }
9090
10584
  updateId(task) {
@@ -9123,25 +10617,7 @@ class StateManager {
9123
10617
  }).length;
9124
10618
  }
9125
10619
  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
- }));
10620
+ this.collectFiles(files.map((filepath) => createFileTask(filepath, root, projectName)));
9145
10621
  }
9146
10622
  }
9147
10623
 
@@ -11313,7 +12789,7 @@ const config = {
11313
12789
  watch: !isCI,
11314
12790
  globals: false,
11315
12791
  environment: "node",
11316
- pool: "threads",
12792
+ pool: "forks",
11317
12793
  clearMocks: false,
11318
12794
  restoreMocks: false,
11319
12795
  mockReset: false,
@@ -11484,12 +12960,12 @@ function parseInspector(inspect) {
11484
12960
  return { host };
11485
12961
  return { host, port: Number(port) || defaultInspectPort };
11486
12962
  }
11487
- function resolveApiServerConfig(options) {
12963
+ function resolveApiServerConfig(options, defaultPort2) {
11488
12964
  let api;
11489
12965
  if (options.ui && !options.api)
11490
- api = { port: defaultPort };
12966
+ api = { port: defaultPort2 };
11491
12967
  else if (options.api === true)
11492
- api = { port: defaultPort };
12968
+ api = { port: defaultPort2 };
11493
12969
  else if (typeof options.api === "number")
11494
12970
  api = { port: options.api };
11495
12971
  if (typeof options.api === "object") {
@@ -11506,14 +12982,14 @@ function resolveApiServerConfig(options) {
11506
12982
  }
11507
12983
  if (api) {
11508
12984
  if (!api.port && !api.middlewareMode)
11509
- api.port = defaultPort;
12985
+ api.port = defaultPort2;
11510
12986
  } else {
11511
12987
  api = { middlewareMode: true };
11512
12988
  }
11513
12989
  return api;
11514
12990
  }
11515
12991
  function resolveConfig(mode, options, viteConfig, logger) {
11516
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M;
12992
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P;
11517
12993
  if (options.dom) {
11518
12994
  if (((_a = viteConfig.test) == null ? void 0 : _a.environment) != null && viteConfig.test.environment !== "happy-dom") {
11519
12995
  logger.console.warn(
@@ -11554,27 +13030,26 @@ function resolveConfig(mode, options, viteConfig, logger) {
11554
13030
  }
11555
13031
  if (resolved.standalone && !resolved.watch)
11556
13032
  throw new Error(`Vitest standalone mode requires --watch`);
13033
+ if (resolved.mergeReports && resolved.watch)
13034
+ throw new Error(`Cannot merge reports with --watch enabled`);
11557
13035
  if (resolved.maxWorkers)
11558
13036
  resolved.maxWorkers = Number(resolved.maxWorkers);
11559
13037
  if (resolved.minWorkers)
11560
13038
  resolved.minWorkers = Number(resolved.minWorkers);
11561
13039
  resolved.browser ?? (resolved.browser = {});
11562
- (_c = resolved.browser).fileParallelism ?? (_c.fileParallelism = resolved.fileParallelism ?? false);
11563
13040
  resolved.fileParallelism ?? (resolved.fileParallelism = mode !== "benchmark");
11564
13041
  if (!resolved.fileParallelism) {
11565
13042
  resolved.maxWorkers = 1;
11566
13043
  resolved.minWorkers = 1;
11567
13044
  }
11568
13045
  if (resolved.inspect || resolved.inspectBrk) {
11569
- const isSingleThread = resolved.pool === "threads" && ((_e = (_d = resolved.poolOptions) == null ? void 0 : _d.threads) == null ? void 0 : _e.singleThread);
11570
- const isSingleFork = resolved.pool === "forks" && ((_g = (_f = resolved.poolOptions) == null ? void 0 : _f.forks) == null ? void 0 : _g.singleFork);
13046
+ const isSingleThread = resolved.pool === "threads" && ((_d = (_c = resolved.poolOptions) == null ? void 0 : _c.threads) == null ? void 0 : _d.singleThread);
13047
+ const isSingleFork = resolved.pool === "forks" && ((_f = (_e = resolved.poolOptions) == null ? void 0 : _e.forks) == null ? void 0 : _f.singleFork);
11571
13048
  if (resolved.fileParallelism && !isSingleThread && !isSingleFork) {
11572
13049
  const inspectOption = `--inspect${resolved.inspectBrk ? "-brk" : ""}`;
11573
13050
  throw new Error(`You cannot use ${inspectOption} without "--no-file-parallelism", "poolOptions.threads.singleThread" or "poolOptions.forks.singleFork"`);
11574
13051
  }
11575
13052
  }
11576
- if (resolved.coverage.provider === "c8")
11577
- throw new Error('"coverage.provider: c8" is not supported anymore. Use "coverage.provider: v8" instead');
11578
13053
  if (resolved.coverage.provider === "v8" && resolved.coverage.enabled && isBrowserEnabled(resolved))
11579
13054
  throw new Error("@vitest/coverage-v8 does not work with --browser. Use @vitest/coverage-istanbul instead");
11580
13055
  if (resolved.coverage.enabled && resolved.coverage.reportsDirectory) {
@@ -11582,8 +13057,9 @@ function resolveConfig(mode, options, viteConfig, logger) {
11582
13057
  if (reportsDirectory === resolved.root || reportsDirectory === process.cwd())
11583
13058
  throw new Error(`You cannot set "coverage.reportsDirectory" as ${reportsDirectory}. Vitest needs to be able to remove this directory before test run`);
11584
13059
  }
13060
+ resolved.expect ?? (resolved.expect = {});
11585
13061
  resolved.deps ?? (resolved.deps = {});
11586
- (_h = resolved.deps).moduleDirectories ?? (_h.moduleDirectories = []);
13062
+ (_g = resolved.deps).moduleDirectories ?? (_g.moduleDirectories = []);
11587
13063
  resolved.deps.moduleDirectories = resolved.deps.moduleDirectories.map((dir) => {
11588
13064
  if (!dir.startsWith("/"))
11589
13065
  dir = `/${dir}`;
@@ -11593,17 +13069,17 @@ function resolveConfig(mode, options, viteConfig, logger) {
11593
13069
  });
11594
13070
  if (!resolved.deps.moduleDirectories.includes("/node_modules/"))
11595
13071
  resolved.deps.moduleDirectories.push("/node_modules/");
11596
- (_i = resolved.deps).optimizer ?? (_i.optimizer = {});
11597
- (_j = resolved.deps.optimizer).ssr ?? (_j.ssr = {});
11598
- (_k = resolved.deps.optimizer.ssr).enabled ?? (_k.enabled = true);
11599
- (_l = resolved.deps.optimizer).web ?? (_l.web = {});
11600
- (_m = resolved.deps.optimizer.web).enabled ?? (_m.enabled = true);
11601
- (_n = resolved.deps).web ?? (_n.web = {});
11602
- (_o = resolved.deps.web).transformAssets ?? (_o.transformAssets = true);
11603
- (_p = resolved.deps.web).transformCss ?? (_p.transformCss = true);
11604
- (_q = resolved.deps.web).transformGlobPattern ?? (_q.transformGlobPattern = []);
13072
+ (_h = resolved.deps).optimizer ?? (_h.optimizer = {});
13073
+ (_i = resolved.deps.optimizer).ssr ?? (_i.ssr = {});
13074
+ (_j = resolved.deps.optimizer.ssr).enabled ?? (_j.enabled = true);
13075
+ (_k = resolved.deps.optimizer).web ?? (_k.web = {});
13076
+ (_l = resolved.deps.optimizer.web).enabled ?? (_l.enabled = true);
13077
+ (_m = resolved.deps).web ?? (_m.web = {});
13078
+ (_n = resolved.deps.web).transformAssets ?? (_n.transformAssets = true);
13079
+ (_o = resolved.deps.web).transformCss ?? (_o.transformCss = true);
13080
+ (_p = resolved.deps.web).transformGlobPattern ?? (_p.transformGlobPattern = []);
11605
13081
  resolved.server ?? (resolved.server = {});
11606
- (_r = resolved.server).deps ?? (_r.deps = {});
13082
+ (_q = resolved.server).deps ?? (_q.deps = {});
11607
13083
  const deprecatedDepsOptions = ["inline", "external", "fallbackCJS"];
11608
13084
  deprecatedDepsOptions.forEach((option) => {
11609
13085
  if (resolved.deps[option] === void 0)
@@ -11628,11 +13104,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11628
13104
  if ((ssrOptions == null ? void 0 : ssrOptions.noExternal) === true && resolved.server.deps.inline == null) {
11629
13105
  resolved.server.deps.inline = true;
11630
13106
  } else {
11631
- (_s = resolved.server.deps).inline ?? (_s.inline = []);
13107
+ (_r = resolved.server.deps).inline ?? (_r.inline = []);
11632
13108
  resolved.server.deps.inline.push(...extraInlineDeps);
11633
13109
  }
11634
13110
  }
11635
- (_t = resolved.server.deps).moduleDirectories ?? (_t.moduleDirectories = []);
13111
+ (_s = resolved.server.deps).moduleDirectories ?? (_s.moduleDirectories = []);
11636
13112
  resolved.server.deps.moduleDirectories.push(...resolved.deps.moduleDirectories);
11637
13113
  if (resolved.runner)
11638
13114
  resolved.runner = resolvePath(resolved.runner, resolved.root);
@@ -11662,11 +13138,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11662
13138
  resolved.poolOptions = {
11663
13139
  ...resolved.poolOptions,
11664
13140
  threads: {
11665
- ...(_u = resolved.poolOptions) == null ? void 0 : _u.threads,
13141
+ ...(_t = resolved.poolOptions) == null ? void 0 : _t.threads,
11666
13142
  maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
11667
13143
  },
11668
13144
  vmThreads: {
11669
- ...(_v = resolved.poolOptions) == null ? void 0 : _v.vmThreads,
13145
+ ...(_u = resolved.poolOptions) == null ? void 0 : _u.vmThreads,
11670
13146
  maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS)
11671
13147
  }
11672
13148
  };
@@ -11675,11 +13151,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11675
13151
  resolved.poolOptions = {
11676
13152
  ...resolved.poolOptions,
11677
13153
  threads: {
11678
- ...(_w = resolved.poolOptions) == null ? void 0 : _w.threads,
13154
+ ...(_v = resolved.poolOptions) == null ? void 0 : _v.threads,
11679
13155
  minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
11680
13156
  },
11681
13157
  vmThreads: {
11682
- ...(_x = resolved.poolOptions) == null ? void 0 : _x.vmThreads,
13158
+ ...(_w = resolved.poolOptions) == null ? void 0 : _w.vmThreads,
11683
13159
  minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS)
11684
13160
  }
11685
13161
  };
@@ -11688,11 +13164,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11688
13164
  resolved.poolOptions = {
11689
13165
  ...resolved.poolOptions,
11690
13166
  forks: {
11691
- ...(_y = resolved.poolOptions) == null ? void 0 : _y.forks,
13167
+ ...(_x = resolved.poolOptions) == null ? void 0 : _x.forks,
11692
13168
  maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS)
11693
13169
  },
11694
13170
  vmForks: {
11695
- ...(_z = resolved.poolOptions) == null ? void 0 : _z.vmForks,
13171
+ ...(_y = resolved.poolOptions) == null ? void 0 : _y.vmForks,
11696
13172
  maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS)
11697
13173
  }
11698
13174
  };
@@ -11701,11 +13177,11 @@ function resolveConfig(mode, options, viteConfig, logger) {
11701
13177
  resolved.poolOptions = {
11702
13178
  ...resolved.poolOptions,
11703
13179
  forks: {
11704
- ...(_A = resolved.poolOptions) == null ? void 0 : _A.forks,
13180
+ ...(_z = resolved.poolOptions) == null ? void 0 : _z.forks,
11705
13181
  minForks: Number.parseInt(process.env.VITEST_MIN_FORKS)
11706
13182
  },
11707
13183
  vmForks: {
11708
- ...(_B = resolved.poolOptions) == null ? void 0 : _B.vmForks,
13184
+ ...(_A = resolved.poolOptions) == null ? void 0 : _A.vmForks,
11709
13185
  minForks: Number.parseInt(process.env.VITEST_MIN_FORKS)
11710
13186
  }
11711
13187
  };
@@ -11760,7 +13236,7 @@ function resolveConfig(mode, options, viteConfig, logger) {
11760
13236
  resolved.diff = resolvePath(resolved.diff, resolved.root);
11761
13237
  resolved.forceRerunTriggers.push(resolved.diff);
11762
13238
  }
11763
- resolved.api = resolveApiServerConfig(options);
13239
+ resolved.api = resolveApiServerConfig(options, defaultPort);
11764
13240
  if (options.related)
11765
13241
  resolved.related = toArray(options.related).map((file) => resolve(resolved.root, file));
11766
13242
  if (options.reporters) {
@@ -11801,8 +13277,8 @@ function resolveConfig(mode, options, viteConfig, logger) {
11801
13277
  resolved.passWithNoTests ?? (resolved.passWithNoTests = true);
11802
13278
  resolved.css ?? (resolved.css = {});
11803
13279
  if (typeof resolved.css === "object") {
11804
- (_C = resolved.css).modules ?? (_C.modules = {});
11805
- (_D = resolved.css.modules).classNameStrategy ?? (_D.classNameStrategy = "stable");
13280
+ (_B = resolved.css).modules ?? (_B.modules = {});
13281
+ (_C = resolved.css.modules).classNameStrategy ?? (_C.classNameStrategy = "stable");
11806
13282
  }
11807
13283
  if (resolved.cache !== false) {
11808
13284
  let cacheDir = VitestCache.resolveCacheDir("", resolve(viteConfig.cacheDir, "vitest"), resolved.name);
@@ -11819,32 +13295,40 @@ function resolveConfig(mode, options, viteConfig, logger) {
11819
13295
  resolved.sequence ?? (resolved.sequence = {});
11820
13296
  if (resolved.sequence.shuffle && typeof resolved.sequence.shuffle === "object") {
11821
13297
  const { files, tests } = resolved.sequence.shuffle;
11822
- (_E = resolved.sequence).sequencer ?? (_E.sequencer = files ? RandomSequencer : BaseSequencer);
13298
+ (_D = resolved.sequence).sequencer ?? (_D.sequencer = files ? RandomSequencer : BaseSequencer);
11823
13299
  resolved.sequence.shuffle = tests;
11824
13300
  }
11825
- if (!((_F = resolved.sequence) == null ? void 0 : _F.sequencer)) {
13301
+ if (!((_E = resolved.sequence) == null ? void 0 : _E.sequencer)) {
11826
13302
  resolved.sequence.sequencer = resolved.sequence.shuffle ? RandomSequencer : BaseSequencer;
11827
13303
  }
11828
- (_G = resolved.sequence).hooks ?? (_G.hooks = "stack");
13304
+ (_F = resolved.sequence).hooks ?? (_F.hooks = "stack");
11829
13305
  if (resolved.sequence.sequencer === RandomSequencer)
11830
- (_H = resolved.sequence).seed ?? (_H.seed = Date.now());
13306
+ (_G = resolved.sequence).seed ?? (_G.seed = Date.now());
11831
13307
  resolved.typecheck = {
11832
13308
  ...configDefaults.typecheck,
11833
13309
  ...resolved.typecheck
11834
13310
  };
11835
- resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map((i) => [resolve(resolved.root, i[0]), i[1]]);
13311
+ resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map(
13312
+ (i) => [resolve(resolved.root, i[0]), i[1]]
13313
+ );
11836
13314
  resolved.typecheck ?? (resolved.typecheck = {});
11837
- (_I = resolved.typecheck).enabled ?? (_I.enabled = false);
13315
+ (_H = resolved.typecheck).enabled ?? (_H.enabled = false);
11838
13316
  if (resolved.typecheck.enabled)
11839
13317
  logger.console.warn(c.yellow("Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest's version when using it."));
11840
13318
  resolved.browser ?? (resolved.browser = {});
11841
- (_J = resolved.browser).enabled ?? (_J.enabled = false);
11842
- (_K = resolved.browser).headless ?? (_K.headless = isCI);
11843
- (_L = resolved.browser).slowHijackESM ?? (_L.slowHijackESM = false);
11844
- (_M = resolved.browser).isolate ?? (_M.isolate = true);
13319
+ (_I = resolved.browser).enabled ?? (_I.enabled = false);
13320
+ (_J = resolved.browser).headless ?? (_J.headless = isCI);
13321
+ (_K = resolved.browser).isolate ?? (_K.isolate = true);
13322
+ (_L = resolved.browser).fileParallelism ?? (_L.fileParallelism = options.fileParallelism ?? mode !== "benchmark");
13323
+ (_M = resolved.browser).ui ?? (_M.ui = resolved.browser.headless === true ? false : !isCI);
13324
+ if (resolved.browser.screenshotDirectory)
13325
+ resolved.browser.screenshotDirectory = resolve(resolved.root, resolved.browser.screenshotDirectory);
13326
+ (_N = resolved.browser).viewport ?? (_N.viewport = {});
13327
+ (_O = resolved.browser.viewport).width ?? (_O.width = 414);
13328
+ (_P = resolved.browser.viewport).height ?? (_P.height = 896);
11845
13329
  if (resolved.browser.enabled && provider$1 === "stackblitz")
11846
- resolved.browser.provider = "none";
11847
- resolved.browser.api = resolveApiServerConfig(resolved.browser) || {
13330
+ resolved.browser.provider = "preview";
13331
+ resolved.browser.api = resolveApiServerConfig(resolved.browser, defaultBrowserPort) || {
11848
13332
  port: defaultBrowserPort
11849
13333
  };
11850
13334
  resolved.testTransformMode ?? (resolved.testTransformMode = {});
@@ -11901,7 +13385,7 @@ function getBetterEnd(code, node) {
11901
13385
  end += 1;
11902
13386
  return end;
11903
13387
  }
11904
- const regexpHoistable = /\b(vi|vitest)\s*\.\s*(mock|unmock|hoisted|doMock|doUnmock)\(/;
13388
+ const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\(/;
11905
13389
  const hashbangRE = /^#!.*\n/;
11906
13390
  function hoistMocks(code, id, parse, colors) {
11907
13391
  var _a;
@@ -12151,6 +13635,8 @@ function MocksPlugin() {
12151
13635
  name: "vitest:mocks",
12152
13636
  enforce: "post",
12153
13637
  transform(code, id) {
13638
+ if (id.includes(distDir))
13639
+ return;
12154
13640
  return hoistMocks(code, id, this.parse);
12155
13641
  }
12156
13642
  };
@@ -12253,6 +13739,287 @@ function resolveFsAllow(projectRoot, rootConfigFile) {
12253
13739
  return [dirname(rootConfigFile), searchForWorkspaceRoot(projectRoot), rootDir];
12254
13740
  }
12255
13741
 
13742
+ function automockModule(code, parse) {
13743
+ const ast = parse(code);
13744
+ const m = new MagicString(code);
13745
+ const allSpecifiers = [];
13746
+ let importIndex = 0;
13747
+ for (const _node of ast.body) {
13748
+ if (_node.type === "ExportAllDeclaration") {
13749
+ throw new Error(
13750
+ `automocking files with \`export *\` is not supported in browser mode because it cannot be statically analysed`
13751
+ );
13752
+ }
13753
+ if (_node.type === "ExportNamedDeclaration") {
13754
+ let traversePattern2 = function(expression) {
13755
+ if (expression.type === "Identifier") {
13756
+ allSpecifiers.push({ name: expression.name });
13757
+ } else if (expression.type === "ArrayPattern") {
13758
+ expression.elements.forEach((element) => {
13759
+ if (!element)
13760
+ return;
13761
+ traversePattern2(element);
13762
+ });
13763
+ } else if (expression.type === "ObjectPattern") {
13764
+ expression.properties.forEach((property) => {
13765
+ if (property.type === "RestElement")
13766
+ traversePattern2(property);
13767
+ else if (property.type === "Property")
13768
+ traversePattern2(property.value);
13769
+ else
13770
+ ;
13771
+ });
13772
+ } else if (expression.type === "RestElement") {
13773
+ traversePattern2(expression.argument);
13774
+ } else if (expression.type === "AssignmentPattern") {
13775
+ throw new Error(`AssignmentPattern is not supported. Please open a new bug report.`);
13776
+ } else if (expression.type === "MemberExpression") {
13777
+ throw new Error(`MemberExpression is not supported. Please open a new bug report.`);
13778
+ } else ;
13779
+ };
13780
+ const node = _node;
13781
+ const declaration = node.declaration;
13782
+ if (declaration) {
13783
+ if (declaration.type === "FunctionDeclaration") {
13784
+ allSpecifiers.push({ name: declaration.id.name });
13785
+ } else if (declaration.type === "VariableDeclaration") {
13786
+ declaration.declarations.forEach((declaration2) => {
13787
+ traversePattern2(declaration2.id);
13788
+ });
13789
+ } else if (declaration.type === "ClassDeclaration") {
13790
+ allSpecifiers.push({ name: declaration.id.name });
13791
+ } else ;
13792
+ m.remove(node.start, declaration.start);
13793
+ }
13794
+ const specifiers = node.specifiers || [];
13795
+ const source = node.source;
13796
+ if (!source && specifiers.length) {
13797
+ specifiers.forEach((specifier) => {
13798
+ const exported = specifier.exported;
13799
+ allSpecifiers.push({
13800
+ alias: exported.type === "Literal" ? exported.raw : exported.name,
13801
+ name: specifier.local.name
13802
+ });
13803
+ });
13804
+ m.remove(node.start, node.end);
13805
+ } else if (source && specifiers.length) {
13806
+ const importNames = [];
13807
+ specifiers.forEach((specifier) => {
13808
+ const importedName = `__vitest_imported_${importIndex++}__`;
13809
+ const exported = specifier.exported;
13810
+ importNames.push([specifier.local.name, importedName]);
13811
+ allSpecifiers.push({
13812
+ name: importedName,
13813
+ alias: exported.type === "Literal" ? exported.raw : exported.name
13814
+ });
13815
+ });
13816
+ const importString = `import { ${importNames.map(([name, alias]) => `${name} as ${alias}`).join(", ")} } from '${source.value}'`;
13817
+ m.overwrite(node.start, node.end, importString);
13818
+ }
13819
+ }
13820
+ if (_node.type === "ExportDefaultDeclaration") {
13821
+ const node = _node;
13822
+ const declaration = node.declaration;
13823
+ allSpecifiers.push({ name: "__vitest_default", alias: "default" });
13824
+ m.overwrite(node.start, declaration.start, `const __vitest_default = `);
13825
+ }
13826
+ }
13827
+ const moduleObject = `
13828
+ const __vitest_es_current_module__ = {
13829
+ __esModule: true,
13830
+ ${allSpecifiers.map(({ name }) => `["${name}"]: ${name},`).join("\n ")}
13831
+ }
13832
+ const __vitest_mocked_module__ = __vitest_mocker__.mockObject(__vitest_es_current_module__)
13833
+ `;
13834
+ const assigning = allSpecifiers.map(({ name }, index) => {
13835
+ return `const __vitest_mocked_${index}__ = __vitest_mocked_module__["${name}"]`;
13836
+ }).join("\n");
13837
+ const redeclarations = allSpecifiers.map(({ name, alias }, index) => {
13838
+ return ` __vitest_mocked_${index}__ as ${alias || name},`;
13839
+ }).join("\n");
13840
+ const specifiersExports = `
13841
+ export {
13842
+ ${redeclarations}
13843
+ }
13844
+ `;
13845
+ m.append(moduleObject + assigning + specifiersExports);
13846
+ return m;
13847
+ }
13848
+
13849
+ const debug = createDebugger("vitest:browser:api");
13850
+ function setupBrowserRpc(project, server) {
13851
+ var _a;
13852
+ const ctx = project.ctx;
13853
+ const wss = new WebSocketServer$1({ noServer: true });
13854
+ (_a = server.httpServer) == null ? void 0 : _a.on("upgrade", (request, socket, head) => {
13855
+ if (!request.url)
13856
+ return;
13857
+ const { pathname, searchParams } = new URL(request.url, "http://localhost");
13858
+ if (pathname !== BROWSER_API_PATH)
13859
+ return;
13860
+ const type = searchParams.get("type") ?? "tester";
13861
+ const sessionId = searchParams.get("sessionId") ?? "0";
13862
+ wss.handleUpgrade(request, socket, head, (ws) => {
13863
+ wss.emit("connection", ws, request);
13864
+ const rpc = setupClient(sessionId, ws);
13865
+ const rpcs = project.browserRpc;
13866
+ const clients = type === "tester" ? rpcs.testers : rpcs.orchestrators;
13867
+ clients.set(sessionId, rpc);
13868
+ debug == null ? void 0 : debug("[%s] Browser API connected to %s", sessionId, type);
13869
+ ws.on("close", () => {
13870
+ debug == null ? void 0 : debug("[%s] Browser API disconnected from %s", sessionId, type);
13871
+ clients.delete(sessionId);
13872
+ });
13873
+ });
13874
+ });
13875
+ function checkFileAccess(path) {
13876
+ if (!isFileServingAllowed(path, server))
13877
+ throw new Error(`Access denied to "${path}". See Vite config documentation for "server.fs": https://vitejs.dev/config/server-options.html#server-fs-strict.`);
13878
+ }
13879
+ function setupClient(sessionId, ws) {
13880
+ const rpc = createBirpc(
13881
+ {
13882
+ async onUnhandledError(error, type) {
13883
+ ctx.state.catchError(error, type);
13884
+ },
13885
+ async onCollected(files) {
13886
+ ctx.state.collectFiles(files);
13887
+ await ctx.report("onCollected", files);
13888
+ },
13889
+ async onTaskUpdate(packs) {
13890
+ ctx.state.updateTasks(packs);
13891
+ await ctx.report("onTaskUpdate", packs);
13892
+ },
13893
+ onAfterSuiteRun(meta) {
13894
+ var _a2;
13895
+ (_a2 = ctx.coverageProvider) == null ? void 0 : _a2.onAfterSuiteRun(meta);
13896
+ },
13897
+ sendLog(log) {
13898
+ return ctx.report("onUserConsoleLog", log);
13899
+ },
13900
+ resolveSnapshotPath(testPath) {
13901
+ return ctx.snapshot.resolvePath(testPath);
13902
+ },
13903
+ resolveSnapshotRawPath(testPath, rawPath) {
13904
+ return ctx.snapshot.resolveRawPath(testPath, rawPath);
13905
+ },
13906
+ snapshotSaved(snapshot) {
13907
+ ctx.snapshot.add(snapshot);
13908
+ },
13909
+ async readSnapshotFile(snapshotPath) {
13910
+ checkFileAccess(snapshotPath);
13911
+ if (!existsSync(snapshotPath))
13912
+ return null;
13913
+ return promises$1.readFile(snapshotPath, "utf-8");
13914
+ },
13915
+ async saveSnapshotFile(id, content) {
13916
+ checkFileAccess(id);
13917
+ await promises$1.mkdir(dirname(id), { recursive: true });
13918
+ return promises$1.writeFile(id, content, "utf-8");
13919
+ },
13920
+ async removeSnapshotFile(id) {
13921
+ checkFileAccess(id);
13922
+ if (!existsSync(id))
13923
+ throw new Error(`Snapshot file "${id}" does not exist.`);
13924
+ return promises$1.unlink(id);
13925
+ },
13926
+ async getBrowserFileSourceMap(id) {
13927
+ var _a2, _b;
13928
+ const mod = (_a2 = project.browser) == null ? void 0 : _a2.moduleGraph.getModuleById(id);
13929
+ return (_b = mod == null ? void 0 : mod.transformResult) == null ? void 0 : _b.map;
13930
+ },
13931
+ onCancel(reason) {
13932
+ ctx.cancelCurrentRun(reason);
13933
+ },
13934
+ async resolveId(id, importer) {
13935
+ const result = await project.server.pluginContainer.resolveId(id, importer, {
13936
+ ssr: false
13937
+ });
13938
+ return result;
13939
+ },
13940
+ debug(...args) {
13941
+ ctx.logger.console.debug(...args);
13942
+ },
13943
+ getCountOfFailedTests() {
13944
+ return ctx.state.getCountOfFailedTests();
13945
+ },
13946
+ async triggerCommand(contextId, command, testPath, payload) {
13947
+ var _a2;
13948
+ debug == null ? void 0 : debug('[%s] Triggering command "%s"', contextId, command);
13949
+ const provider = project.browserProvider;
13950
+ if (!provider)
13951
+ throw new Error("Commands are only available for browser tests.");
13952
+ const commands = (_a2 = project.config.browser) == null ? void 0 : _a2.commands;
13953
+ if (!commands || !commands[command])
13954
+ throw new Error(`Unknown command "${command}".`);
13955
+ if (provider.beforeCommand)
13956
+ await provider.beforeCommand(command, payload);
13957
+ const context = Object.assign({
13958
+ testPath,
13959
+ project,
13960
+ provider,
13961
+ contextId
13962
+ }, provider.getCommandsContext(contextId));
13963
+ let result;
13964
+ try {
13965
+ result = await commands[command](context, ...payload);
13966
+ } finally {
13967
+ if (provider.afterCommand)
13968
+ await provider.afterCommand(command, payload);
13969
+ }
13970
+ return result;
13971
+ },
13972
+ finishBrowserTests(contextId) {
13973
+ var _a2;
13974
+ debug == null ? void 0 : debug("[%s] Finishing browser tests for context", contextId);
13975
+ return (_a2 = project.browserState.get(contextId)) == null ? void 0 : _a2.resolve();
13976
+ },
13977
+ getProvidedContext() {
13978
+ return "ctx" in project ? project.getProvidedContext() : {};
13979
+ },
13980
+ // TODO: cache this automock result
13981
+ async automock(id) {
13982
+ const result = await project.browser.transformRequest(id);
13983
+ if (!result)
13984
+ throw new Error(`Module "${id}" not found.`);
13985
+ const ms = automockModule(result.code, parseAst);
13986
+ const code = ms.toString();
13987
+ const sourcemap = ms.generateMap({ hires: "boundary", source: id });
13988
+ const combinedMap = result.map && result.map.mappings ? remapping(
13989
+ [{ ...sourcemap, version: 3 }, result.map],
13990
+ () => null
13991
+ ) : sourcemap;
13992
+ return `${code}
13993
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(JSON.stringify(combinedMap)).toString("base64")}`;
13994
+ },
13995
+ resolveMock(rawId, importer, hasFactory) {
13996
+ return project.browserMocker.resolveMock(rawId, importer, hasFactory);
13997
+ },
13998
+ invalidate(ids) {
13999
+ ids.forEach((id) => {
14000
+ const moduleGraph = project.browser.moduleGraph;
14001
+ const module = moduleGraph.getModuleById(id);
14002
+ if (module)
14003
+ moduleGraph.invalidateModule(module, /* @__PURE__ */ new Set(), Date.now(), true);
14004
+ });
14005
+ }
14006
+ },
14007
+ {
14008
+ post: (msg) => ws.send(msg),
14009
+ on: (fn) => ws.on("message", fn),
14010
+ eventNames: ["onCancel"],
14011
+ serialize: (data) => stringify$5(data, stringifyReplace),
14012
+ deserialize: parse$5,
14013
+ onTimeoutError(functionName) {
14014
+ throw new Error(`[vitest-api]: Timeout calling "${functionName}"`);
14015
+ }
14016
+ }
14017
+ );
14018
+ ctx.onCancel((reason) => rpc.onCancel(reason));
14019
+ return rpc;
14020
+ }
14021
+ }
14022
+
12256
14023
  async function createBrowserServer(project, configFile) {
12257
14024
  var _a;
12258
14025
  const root = project.config.root;
@@ -12261,18 +14028,19 @@ async function createBrowserServer(project, configFile) {
12261
14028
  const server = await createServer({
12262
14029
  ...project.options,
12263
14030
  // spread project config inlined in root workspace config
14031
+ base: "/",
12264
14032
  logLevel: "error",
12265
14033
  mode: project.config.mode,
12266
14034
  configFile: configPath,
12267
14035
  // watch is handled by Vitest
12268
14036
  server: {
12269
14037
  hmr: false,
12270
- watch: {
12271
- ignored: ["**/**"]
12272
- }
14038
+ watch: null,
14039
+ preTransformRequests: false
12273
14040
  },
12274
14041
  plugins: [
12275
14042
  ...((_a = project.options) == null ? void 0 : _a.plugins) || [],
14043
+ MocksPlugin(),
12276
14044
  (await import('@vitest/browser')).default(project, "/"),
12277
14045
  CoverageTransform(project.ctx),
12278
14046
  {
@@ -12280,13 +14048,14 @@ async function createBrowserServer(project, configFile) {
12280
14048
  name: "vitest:browser:config",
12281
14049
  async config(config) {
12282
14050
  var _a2, _b, _c;
12283
- const server2 = resolveApiServerConfig(((_a2 = config.test) == null ? void 0 : _a2.browser) || {}) || {
14051
+ const server2 = resolveApiServerConfig(((_a2 = config.test) == null ? void 0 : _a2.browser) || {}, defaultBrowserPort) || {
12284
14052
  port: defaultBrowserPort
12285
14053
  };
12286
14054
  server2.middlewareMode = false;
12287
14055
  config.server = {
12288
14056
  ...config.server,
12289
- ...server2
14057
+ ...server2,
14058
+ open: false
12290
14059
  };
12291
14060
  (_b = config.server).fs ?? (_b.fs = {});
12292
14061
  config.server.fs.allow = config.server.fs.allow || [];
@@ -12299,27 +14068,25 @@ async function createBrowserServer(project, configFile) {
12299
14068
  return {
12300
14069
  resolve: {
12301
14070
  alias: (_c = config.test) == null ? void 0 : _c.alias
12302
- },
12303
- server: {
12304
- watch: null
12305
14071
  }
12306
14072
  };
12307
14073
  }
12308
- },
12309
- MocksPlugin()
14074
+ }
12310
14075
  ]
12311
14076
  });
12312
14077
  await server.listen();
12313
- (await Promise.resolve().then(function () { return setup$1; })).setup(project, server);
14078
+ setupBrowserRpc(project, server);
14079
+ if (project.config.browser.ui)
14080
+ setup(project.ctx, server);
12314
14081
  return server;
12315
14082
  }
12316
14083
 
12317
- const builtinProviders = ["webdriverio", "playwright", "none"];
14084
+ const builtinProviders = ["webdriverio", "playwright", "preview"];
12318
14085
  async function getBrowserProvider(options, project) {
12319
14086
  if (options.provider == null || builtinProviders.includes(options.provider)) {
12320
14087
  await project.ctx.packageInstaller.ensureInstalled("@vitest/browser", project.config.root);
12321
14088
  const providers = await project.runner.executeId("@vitest/browser/providers");
12322
- const provider = options.provider || "webdriverio";
14089
+ const provider = options.provider || "preview";
12323
14090
  return providers[provider];
12324
14091
  }
12325
14092
  let customProviderModule;
@@ -12333,6 +14100,69 @@ async function getBrowserProvider(options, project) {
12333
14100
  return customProviderModule.default;
12334
14101
  }
12335
14102
 
14103
+ var __defProp = Object.defineProperty;
14104
+ var __typeError = (msg) => {
14105
+ throw TypeError(msg);
14106
+ };
14107
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14108
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
14109
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
14110
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
14111
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
14112
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
14113
+ var _project;
14114
+ class VitestBrowserServerMocker {
14115
+ constructor(project) {
14116
+ // string means it will read from __mocks__ folder
14117
+ // undefined means there is a factory mock that will be called on the server
14118
+ // null means it should be auto mocked
14119
+ __publicField(this, "mocks", /* @__PURE__ */ new Map());
14120
+ // private because the typecheck fails on build if it's exposed
14121
+ // due to a self reference
14122
+ __privateAdd(this, _project);
14123
+ __privateSet(this, _project, project);
14124
+ }
14125
+ async resolveMock(rawId, importer, hasFactory) {
14126
+ const { id, fsPath, external } = await this.resolveId(rawId, importer);
14127
+ if (hasFactory)
14128
+ return { type: "factory", resolvedId: id };
14129
+ const mockPath = this.resolveMockPath(fsPath, external);
14130
+ return {
14131
+ type: mockPath === null ? "automock" : "redirect",
14132
+ mockPath,
14133
+ resolvedId: id
14134
+ };
14135
+ }
14136
+ async resolveId(rawId, importer) {
14137
+ const resolved = await __privateGet(this, _project).browser.pluginContainer.resolveId(rawId, importer, {
14138
+ ssr: false
14139
+ });
14140
+ return __privateGet(this, _project).vitenode.resolveModule(rawId, resolved);
14141
+ }
14142
+ resolveMockPath(mockPath, external) {
14143
+ const path = external || mockPath;
14144
+ if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) {
14145
+ const mockDirname = dirname(path);
14146
+ const mockFolder = join(__privateGet(this, _project).config.root, "__mocks__", mockDirname);
14147
+ if (!existsSync(mockFolder))
14148
+ return null;
14149
+ const files = readdirSync(mockFolder);
14150
+ const baseOriginal = basename(path);
14151
+ for (const file of files) {
14152
+ const baseFile = basename(file, extname$1(file));
14153
+ if (baseFile === baseOriginal)
14154
+ return resolve(mockFolder, file);
14155
+ }
14156
+ return null;
14157
+ }
14158
+ const dir = dirname(path);
14159
+ const baseId = basename(path);
14160
+ const fullPath = resolve(dir, "__mocks__", baseId);
14161
+ return existsSync(fullPath) ? fullPath : null;
14162
+ }
14163
+ }
14164
+ _project = new WeakMap();
14165
+
12336
14166
  function generateCssFilenameHash(filepath) {
12337
14167
  return createHash$2("md5").update(filepath).digest("hex").slice(0, 6);
12338
14168
  }
@@ -12345,10 +14175,10 @@ function generateScopedClassName(strategy, name, filename) {
12345
14175
  return `_${name}_${hash}`;
12346
14176
  }
12347
14177
 
12348
- const cssLangs = "\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)";
14178
+ const cssLangs = "\\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)(?:$|\\?)";
12349
14179
  const cssLangRE = new RegExp(cssLangs);
12350
14180
  const cssModuleRE = new RegExp(`\\.module${cssLangs}`);
12351
- const cssInlineRE = /[?&]inline(&|$)/;
14181
+ const cssInlineRE = /[?&]inline(?:&|$)/;
12352
14182
  function isCSS(id) {
12353
14183
  return cssLangRE.test(id);
12354
14184
  }
@@ -12960,7 +14790,7 @@ function NormalizeURLPlugin() {
12960
14790
  if (ssr || !code.includes("new URL") || !code.includes("import.meta.url"))
12961
14791
  return;
12962
14792
  const cleanString = stripLiteral(code);
12963
- const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g;
14793
+ const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*(?:'[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/g;
12964
14794
  let updatedCode = code;
12965
14795
  let match;
12966
14796
  while (match = assetImportMetaUrlRE.exec(cleanString)) {
@@ -13053,17 +14883,12 @@ function WorkspaceVitestPlugin(project, options) {
13053
14883
  hijackVitePluginInject(viteConfig);
13054
14884
  },
13055
14885
  async configureServer(server) {
13056
- try {
13057
- const options2 = deepMerge(
13058
- {},
13059
- configDefaults,
13060
- server.config.test || {}
13061
- );
13062
- await project.setServer(options2, server);
13063
- } catch (err) {
13064
- project.ctx.logger.printError(err, { fullStack: true });
13065
- process.exit(1);
13066
- }
14886
+ const options2 = deepMerge(
14887
+ {},
14888
+ configDefaults,
14889
+ server.config.test || {}
14890
+ );
14891
+ await project.setServer(options2, server);
13067
14892
  await server.watcher.close();
13068
14893
  }
13069
14894
  },
@@ -13152,8 +14977,15 @@ class WorkspaceProject {
13152
14977
  browser;
13153
14978
  typechecker;
13154
14979
  closingPromise;
14980
+ // TODO: abstract browser related things and move to @vitest/browser
13155
14981
  browserProvider;
13156
- browserState;
14982
+ browserMocker = new VitestBrowserServerMocker(this);
14983
+ // TODO: I mean, we really need to abstract it
14984
+ browserRpc = {
14985
+ orchestrators: /* @__PURE__ */ new Map(),
14986
+ testers: /* @__PURE__ */ new Map()
14987
+ };
14988
+ browserState = /* @__PURE__ */ new Map();
13157
14989
  testFilesList = null;
13158
14990
  id = nanoid();
13159
14991
  tmpDir = join(tmpdir(), this.id);
@@ -13188,35 +15020,21 @@ class WorkspaceProject {
13188
15020
  if (this._globalSetups)
13189
15021
  return;
13190
15022
  this._globalSetups = await loadGlobalSetupFiles(this.runner, this.config.globalSetup);
13191
- try {
13192
- for (const globalSetupFile of this._globalSetups) {
13193
- const teardown = await ((_a = globalSetupFile.setup) == null ? void 0 : _a.call(globalSetupFile, { provide: this.provide, config: this.config }));
13194
- if (teardown == null || !!globalSetupFile.teardown)
13195
- continue;
13196
- if (typeof teardown !== "function")
13197
- throw new Error(`invalid return value in globalSetup file ${globalSetupFile.file}. Must return a function`);
13198
- globalSetupFile.teardown = teardown;
13199
- }
13200
- } catch (e) {
13201
- this.logger.error(`
13202
- ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
13203
- this.logger.printError(e);
13204
- process.exit(1);
15023
+ for (const globalSetupFile of this._globalSetups) {
15024
+ const teardown = await ((_a = globalSetupFile.setup) == null ? void 0 : _a.call(globalSetupFile, { provide: this.provide, config: this.config }));
15025
+ if (teardown == null || !!globalSetupFile.teardown)
15026
+ continue;
15027
+ if (typeof teardown !== "function")
15028
+ throw new Error(`invalid return value in globalSetup file ${globalSetupFile.file}. Must return a function`);
15029
+ globalSetupFile.teardown = teardown;
13205
15030
  }
13206
15031
  }
13207
15032
  async teardownGlobalSetup() {
13208
15033
  var _a;
13209
15034
  if (!this._globalSetups)
13210
15035
  return;
13211
- for (const globalSetupFile of [...this._globalSetups].reverse()) {
13212
- try {
13213
- await ((_a = globalSetupFile.teardown) == null ? void 0 : _a.call(globalSetupFile));
13214
- } catch (error) {
13215
- this.logger.error(`error during global teardown of ${globalSetupFile.file}`, error);
13216
- this.logger.printError(error);
13217
- process.exitCode = 1;
13218
- }
13219
- }
15036
+ for (const globalSetupFile of [...this._globalSetups].reverse())
15037
+ await ((_a = globalSetupFile.teardown) == null ? void 0 : _a.call(globalSetupFile));
13220
15038
  }
13221
15039
  get logger() {
13222
15040
  return this.ctx.logger;
@@ -13419,7 +15237,14 @@ ${c.red(divider(c.bold(c.inverse(" Error during global setup "))))}`);
13419
15237
  env: {
13420
15238
  ...(_v = this.server) == null ? void 0 : _v.config.env,
13421
15239
  ...this.config.env
13422
- }
15240
+ },
15241
+ browser: {
15242
+ ...this.ctx.config.browser,
15243
+ orchestratorScripts: [],
15244
+ testerScripts: [],
15245
+ commands: {}
15246
+ },
15247
+ printConsoleTrace: this.config.printConsoleTrace ?? this.ctx.config.printConsoleTrace
13423
15248
  }, this.ctx.configOverride || {});
13424
15249
  }
13425
15250
  close() {
@@ -13617,9 +15442,12 @@ class Vitest {
13617
15442
  getProjectByTaskId(taskId) {
13618
15443
  var _a;
13619
15444
  const task = this.state.idMap.get(taskId);
13620
- const projectName = task.projectName || ((_a = task == null ? void 0 : task.file) == null ? void 0 : _a.projectName);
15445
+ const projectName = task.projectName || ((_a = task == null ? void 0 : task.file) == null ? void 0 : _a.projectName) || "";
13621
15446
  return this.projects.find((p) => p.getName() === projectName) || this.getCoreWorkspaceProject() || this.projects[0];
13622
15447
  }
15448
+ getProjectByName(name = "") {
15449
+ return this.projects.find((p) => p.getName() === name) || this.getCoreWorkspaceProject() || this.projects[0];
15450
+ }
13623
15451
  async getWorkspaceConfigPath() {
13624
15452
  if (this.config.workspace)
13625
15453
  return this.config.workspace;
@@ -13707,7 +15535,8 @@ class Vitest {
13707
15535
  "testNamePattern",
13708
15536
  "passWithNoTests",
13709
15537
  "bail",
13710
- "isolate"
15538
+ "isolate",
15539
+ "printConsoleTrace"
13711
15540
  ];
13712
15541
  const cliOverrides = overridesOptions.reduce((acc, name) => {
13713
15542
  if (name in cliOptions)
@@ -13766,8 +15595,52 @@ class Vitest {
13766
15595
  async initBrowserProviders() {
13767
15596
  return Promise.all(this.projects.map((w) => w.initBrowserProvider()));
13768
15597
  }
13769
- async start(filters) {
15598
+ async mergeReports() {
13770
15599
  var _a, _b;
15600
+ if (this.reporters.some((r) => r instanceof BlobReporter))
15601
+ throw new Error("Cannot merge reports when `--reporter=blob` is used. Remove blob reporter from the config first.");
15602
+ const { files, errors, coverages } = await readBlobs(this.config.mergeReports, this.projects);
15603
+ await this.report("onInit", this);
15604
+ await this.report("onPathsCollected", files.flatMap((f) => f.filepath));
15605
+ const workspaceSpecs = /* @__PURE__ */ new Map();
15606
+ for (const file of files) {
15607
+ const project = this.getProjectByName(file.projectName);
15608
+ const specs = workspaceSpecs.get(project) || [];
15609
+ specs.push(file);
15610
+ workspaceSpecs.set(project, specs);
15611
+ }
15612
+ for (const [project, files2] of workspaceSpecs) {
15613
+ const filepaths = files2.map((f) => f.filepath);
15614
+ this.state.clearFiles(project, filepaths);
15615
+ files2.forEach((file) => {
15616
+ var _a2;
15617
+ (_a2 = file.logs) == null ? void 0 : _a2.forEach((log) => this.state.updateUserLog(log));
15618
+ });
15619
+ this.state.collectFiles(files2);
15620
+ }
15621
+ await this.report("onCollected", files).catch(noop$1);
15622
+ for (const file of files) {
15623
+ const logs = [];
15624
+ const taskPacks = [];
15625
+ const tasks = getTasks(file);
15626
+ for (const task of tasks) {
15627
+ if (task.logs)
15628
+ logs.push(...task.logs);
15629
+ taskPacks.push([task.id, task.result, task.meta]);
15630
+ }
15631
+ logs.sort((log1, log2) => log1.time - log2.time);
15632
+ for (const log of logs)
15633
+ await this.report("onUserConsoleLog", log).catch(noop$1);
15634
+ await this.report("onTaskUpdate", taskPacks).catch(noop$1);
15635
+ }
15636
+ if (hasFailed(files))
15637
+ process.exitCode = 1;
15638
+ await this.report("onFinished", files, errors);
15639
+ await this.initCoverageProvider();
15640
+ await ((_b = (_a = this.coverageProvider) == null ? void 0 : _a.mergeReports) == null ? void 0 : _b.call(_a, coverages));
15641
+ }
15642
+ async start(filters) {
15643
+ var _a, _b, _c, _d;
13771
15644
  this._onClose = [];
13772
15645
  try {
13773
15646
  await this.initCoverageProvider();
@@ -13780,9 +15653,10 @@ class Vitest {
13780
15653
  await this.globTestFiles(filters)
13781
15654
  );
13782
15655
  if (!files.length) {
13783
- await this.reportCoverage(true);
15656
+ const coverage = await ((_c = (_b = this.coverageProvider) == null ? void 0 : _b.generateCoverage) == null ? void 0 : _c.call(_b, { allTestsRun: true }));
15657
+ await this.reportCoverage(coverage, true);
13784
15658
  this.logger.printNoTestFound(filters);
13785
- if (!this.config.watch || !(this.config.changed || ((_b = this.config.related) == null ? void 0 : _b.length))) {
15659
+ if (!this.config.watch || !(this.config.changed || ((_d = this.config.related) == null ? void 0 : _d.length))) {
13786
15660
  const exitCode = this.config.passWithNoTests ? 0 : 1;
13787
15661
  process.exit(exitCode);
13788
15662
  }
@@ -13884,11 +15758,14 @@ class Vitest {
13884
15758
  const vitestDir = projectVitestPath ? resolve(projectVitestPath.id, "../..") : rootDir;
13885
15759
  this.distPath = join(vitestDir, "dist");
13886
15760
  }
13887
- async runFiles(paths, allTestsRun) {
15761
+ async runFiles(specs, allTestsRun) {
13888
15762
  await this.initializeDistPath();
13889
- const filepaths = paths.map(([, file]) => file);
15763
+ const filepaths = specs.map(([, file]) => file);
13890
15764
  this.state.collectPaths(filepaths);
13891
15765
  await this.report("onPathsCollected", filepaths);
15766
+ await this.report("onSpecsCollected", specs.map(
15767
+ ([project, file]) => [{ name: project.config.name, root: project.config.root }, file]
15768
+ ));
13892
15769
  await this.runningPromise;
13893
15770
  this._onCancelListeners = [];
13894
15771
  this.isCancelling = false;
@@ -13902,9 +15779,9 @@ class Vitest {
13902
15779
  this.state.clearErrors();
13903
15780
  if (!this.isFirstRun && this.config.coverage.cleanOnRerun)
13904
15781
  await ((_a = this.coverageProvider) == null ? void 0 : _a.clean());
13905
- await this.initializeGlobalSetup(paths);
15782
+ await this.initializeGlobalSetup(specs);
13906
15783
  try {
13907
- await this.pool.runTests(paths, invalidates);
15784
+ await this.pool.runTests(specs, invalidates);
13908
15785
  } catch (err) {
13909
15786
  this.state.catchError(err, "Unhandled Error");
13910
15787
  }
@@ -13914,9 +15791,11 @@ class Vitest {
13914
15791
  this.cache.results.updateResults(files);
13915
15792
  await this.cache.results.writeToCache();
13916
15793
  })().finally(async () => {
13917
- const specs = Array.from(new Set(paths.map(([, p]) => p)));
13918
- await this.report("onFinished", this.state.getFiles(specs), this.state.getUnhandledErrors());
13919
- await this.reportCoverage(allTestsRun);
15794
+ var _a;
15795
+ const files = Array.from(new Set(specs.map(([, p]) => p)));
15796
+ const coverage = await ((_a = this.coverageProvider) == null ? void 0 : _a.generateCoverage({ allTestsRun }));
15797
+ await this.report("onFinished", this.state.getFiles(files), this.state.getUnhandledErrors(), coverage);
15798
+ await this.reportCoverage(coverage, allTestsRun);
13920
15799
  this.runningPromise = void 0;
13921
15800
  this.isFirstRun = false;
13922
15801
  this.config.changed = false;
@@ -14037,7 +15916,7 @@ class Vitest {
14037
15916
  tests.map((test) => slash$1(test))
14038
15917
  );
14039
15918
  }
14040
- unregisterWatcher = noop$2;
15919
+ unregisterWatcher = noop$1;
14041
15920
  registerWatcher() {
14042
15921
  const updateLastChanged = (filepath) => {
14043
15922
  const projects = this.getModuleProjects(filepath);
@@ -14101,7 +15980,7 @@ class Vitest {
14101
15980
  watcher.off("change", onChange);
14102
15981
  watcher.off("unlink", onUnlink);
14103
15982
  watcher.off("add", onAdd);
14104
- this.unregisterWatcher = noop$2;
15983
+ this.unregisterWatcher = noop$1;
14105
15984
  };
14106
15985
  }
14107
15986
  /**
@@ -14148,11 +16027,11 @@ class Vitest {
14148
16027
  }
14149
16028
  return Array.from(new Set(files));
14150
16029
  }
14151
- async reportCoverage(allTestsRun) {
16030
+ async reportCoverage(coverage, allTestsRun) {
14152
16031
  if (!this.config.coverage.reportOnFailure && this.state.getCountOfFailedTests() > 0)
14153
16032
  return;
14154
16033
  if (this.coverageProvider) {
14155
- await this.coverageProvider.reportCoverage({ allTestsRun });
16034
+ await this.coverageProvider.reportCoverage(coverage, { allTestsRun });
14156
16035
  for (const reporter of this.reporters) {
14157
16036
  if (reporter instanceof WebSocketReporter)
14158
16037
  reporter.onFinishedReportCoverage();
@@ -14285,7 +16164,7 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14285
16164
  removeUndefinedValues(viteConfig.test ?? {}),
14286
16165
  options
14287
16166
  );
14288
- testConfig.api = resolveApiServerConfig(testConfig);
16167
+ testConfig.api = resolveApiServerConfig(testConfig, defaultPort);
14289
16168
  const defines = deleteDefineConfig(viteConfig);
14290
16169
  options.defines = defines;
14291
16170
  let open = false;
@@ -14329,7 +16208,7 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14329
16208
  isolate: ((_c = (_b = options.poolOptions) == null ? void 0 : _b.threads) == null ? void 0 : _c.isolate) ?? options.isolate ?? ((_e = (_d = testConfig.poolOptions) == null ? void 0 : _d.threads) == null ? void 0 : _e.isolate) ?? ((_f = viteConfig.test) == null ? void 0 : _f.isolate)
14330
16209
  },
14331
16210
  forks: {
14332
- isolate: ((_h = (_g = options.poolOptions) == null ? void 0 : _g.threads) == null ? void 0 : _h.isolate) ?? options.isolate ?? ((_j = (_i = testConfig.poolOptions) == null ? void 0 : _i.threads) == null ? void 0 : _j.isolate) ?? ((_k = viteConfig.test) == null ? void 0 : _k.isolate)
16211
+ isolate: ((_h = (_g = options.poolOptions) == null ? void 0 : _g.forks) == null ? void 0 : _h.isolate) ?? options.isolate ?? ((_j = (_i = testConfig.poolOptions) == null ? void 0 : _i.forks) == null ? void 0 : _j.isolate) ?? ((_k = viteConfig.test) == null ? void 0 : _k.isolate)
14333
16212
  }
14334
16213
  }
14335
16214
  }
@@ -14380,7 +16259,7 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14380
16259
  viteConfigTest,
14381
16260
  options
14382
16261
  );
14383
- options.api = resolveApiServerConfig(options);
16262
+ options.api = resolveApiServerConfig(options, defaultPort);
14384
16263
  const { PROD, DEV, ...envs } = viteConfig.env;
14385
16264
  (_a = process.env).PROD ?? (_a.PROD = PROD ? "1" : "");
14386
16265
  (_b = process.env).DEV ?? (_b.DEV = DEV ? "1" : "");
@@ -14396,14 +16275,9 @@ async function VitestPlugin(options = {}, ctx = new Vitest("test")) {
14396
16275
  console.log("[debug] watcher is ready");
14397
16276
  });
14398
16277
  }
14399
- try {
14400
- await ctx.setServer(options, server, userConfig);
14401
- if (options.api && options.watch)
14402
- (await Promise.resolve().then(function () { return setup$1; })).setup(ctx);
14403
- } catch (err) {
14404
- ctx.logger.printError(err, { fullStack: true });
14405
- process.exit(1);
14406
- }
16278
+ await ctx.setServer(options, server, userConfig);
16279
+ if (options.api && options.watch)
16280
+ (await Promise.resolve().then(function () { return setup$1; })).setup(ctx);
14407
16281
  if (!options.watch)
14408
16282
  await server.watcher.close();
14409
16283
  }
@@ -14930,12 +16804,12 @@ function requirePrompt$1 () {
14930
16804
  if (hasRequiredPrompt$1) return prompt$2;
14931
16805
  hasRequiredPrompt$1 = 1;
14932
16806
 
14933
- const readline = require$$0$6;
16807
+ const readline = require$$0$7;
14934
16808
 
14935
16809
  const _require = requireUtil$1(),
14936
16810
  action = _require.action;
14937
16811
 
14938
- const EventEmitter = require$$0$3;
16812
+ const EventEmitter = require$$0$4;
14939
16813
 
14940
16814
  const _require2 = requireSrc(),
14941
16815
  beep = _require2.beep,
@@ -18095,9 +19969,9 @@ function requirePrompt () {
18095
19969
  if (hasRequiredPrompt) return prompt$1;
18096
19970
  hasRequiredPrompt = 1;
18097
19971
 
18098
- const readline = require$$0$6;
19972
+ const readline = require$$0$7;
18099
19973
  const { action } = requireUtil();
18100
- const EventEmitter = require$$0$3;
19974
+ const EventEmitter = require$$0$4;
18101
19975
  const { beep, cursor } = requireSrc();
18102
19976
  const color = requireKleur();
18103
19977
 
@@ -21038,13 +22912,15 @@ async function startVitest(mode, cliFilters = [], options = {}, viteOverrides, v
21038
22912
  ctx.start(cliFilters);
21039
22913
  });
21040
22914
  try {
21041
- if (ctx.config.standalone)
22915
+ if (ctx.config.mergeReports)
22916
+ await ctx.mergeReports();
22917
+ else if (ctx.config.standalone)
21042
22918
  await ctx.init();
21043
22919
  else
21044
22920
  await ctx.start(cliFilters);
21045
22921
  } catch (e) {
21046
22922
  process.exitCode = 1;
21047
- await ctx.logger.printError(e, { fullStack: true, type: "Unhandled Error" });
22923
+ ctx.logger.printError(e, { fullStack: true, type: "Unhandled Error" });
21048
22924
  ctx.logger.error("\n\n");
21049
22925
  return ctx;
21050
22926
  }
@@ -21060,4 +22936,4 @@ var cliApi = /*#__PURE__*/Object.freeze({
21060
22936
  startVitest: startVitest
21061
22937
  });
21062
22938
 
21063
- export { VitestPlugin as V, createMethodsRPC as a, VitestPackageInstaller as b, createVitest as c, cliApi as d, registerConsoleShortcuts as r, startVitest as s };
22939
+ export { VitestPlugin as V, createMethodsRPC as a, VitestPackageInstaller as b, createVitest as c, cliApi as d, getFilePoolName as g, registerConsoleShortcuts as r, startVitest as s };