vitest 4.1.12 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE.md +192 -10
  2. package/browser/context.d.ts +7 -1
  3. package/browser/context.js +5 -5
  4. package/config.d.ts +0 -2
  5. package/dist/browser.d.ts +52 -21
  6. package/dist/browser.js +12 -13
  7. package/dist/chunks/{acorn.B2iPLyUM.js → acorn.C1kjbUFw.js} +30 -30
  8. package/dist/chunks/{base.B6Opl8PE.js → base.Cof-UHJf.js} +81 -52
  9. package/dist/chunks/{browser.d.BcoexmFG.d.ts → browser.d.C7tWgUvw.d.ts} +17 -14
  10. package/dist/chunks/{cac.DzDtg8hz.js → cac.BYbt0aJp.js} +143 -87
  11. package/dist/chunks/{cli-api.B0Pz1_R7.js → cli-api.COfZo8lK.js} +7160 -7189
  12. package/dist/chunks/config.d.B3YV4t0O.d.ts +3873 -0
  13. package/dist/chunks/{console.3WNpx0tS.js → console.CQZ877Hi.js} +69 -63
  14. package/dist/chunks/{constants.CPYnjOGj.js → constants.DLYM6cZY.js} +2 -2
  15. package/dist/chunks/coverage.9iqXE2gN.js +26 -0
  16. package/dist/chunks/{coverage.CTzCuANN.js → coverage.jGCktcGP.js} +7 -2
  17. package/dist/chunks/{creator.DgVhQm5q.js → creator.DHWmytIK.js} +65 -28
  18. package/dist/chunks/{defaults.9aQKnqFk.js → defaults.B1FCaFfh.js} +16 -9
  19. package/dist/chunks/display.BlTmubjj.js +194 -0
  20. package/dist/chunks/doctor.B-oPbwps.js +465 -0
  21. package/dist/chunks/{env.D4Lgay0q.js → env.BKKtU2WC.js} +2 -1
  22. package/dist/chunks/{environment.d.CrsxCzP1.d.ts → environment.d.BFQtFKdZ.d.ts} +9 -1
  23. package/dist/chunks/globals.ZKtKSkEf.js +29 -0
  24. package/dist/chunks/index.Bi0NXYPf.js +1708 -0
  25. package/dist/chunks/{index.CMESou6r.js → index.BoyTG_B7.js} +82 -81
  26. package/dist/chunks/index.CZzC1gGg.js +8501 -0
  27. package/dist/chunks/index.D0heQG4v.js +1318 -0
  28. package/dist/chunks/index.Di8au7q4.js +15665 -0
  29. package/dist/chunks/{index.Chj8NDwU.js → index.DmDMHCg8.js} +6 -12
  30. package/dist/chunks/{index.DXx9Dtk7.js → index.w_oBZ9N8.js} +25 -12
  31. package/dist/chunks/{init-forks.H5ZuobOQ.js → init-forks.BaDXQSD8.js} +7 -10
  32. package/dist/chunks/{init-threads.6kl1khcL.js → init-threads.ZX_Vov0z.js} +1 -1
  33. package/dist/chunks/{init.k9zZ9sLh.js → init.CO4AB7HZ.js} +113 -38
  34. package/dist/chunks/module-dependencies._2Eei3FO.js +71 -0
  35. package/dist/chunks/{native.DPzPHdi5.js → native.upB-V0CK.js} +50 -37
  36. package/dist/chunks/{nativeModuleMocker.BkNfQMkH.js → nativeModuleMocker.Dh5azSB4.js} +48 -19
  37. package/dist/chunks/{index.BCY_7LL2.js → nativeModuleRunner.9xPIMzi7.js} +110 -42
  38. package/dist/chunks/node.B9mkVmLH.js +47 -0
  39. package/dist/chunks/offset.Dy-5Fdfn.js +24 -0
  40. package/dist/chunks/pathe.M-eThtNZ.zq3TM4NT.js +492 -0
  41. package/dist/chunks/{reporters.d.DtoKVV2s.d.ts → plugin.d.LRFSN46m.d.ts} +2573 -1453
  42. package/dist/chunks/plugins.DPQHVT0p.js +37 -0
  43. package/dist/chunks/rawSnapshot.DqSiqIEx.js +356 -0
  44. package/dist/chunks/resolver.BzpmeQeT.js +48 -0
  45. package/dist/chunks/rpc.Uhkwr2NM.js +93 -0
  46. package/dist/chunks/rpc.d.3FOhdFx8.d.ts +75 -0
  47. package/dist/chunks/run.CjdgFZiW.js +4231 -0
  48. package/dist/chunks/setup-common.CqAQCXzx.js +36 -0
  49. package/dist/chunks/source-map.DakdQc29.js +1788 -0
  50. package/dist/chunks/source-map.d.BkG8YK_3.d.ts +89 -0
  51. package/dist/chunks/spy.DDMXghXv.js +509 -0
  52. package/dist/chunks/task-utils.d.D-gFPNFi.d.ts +144 -0
  53. package/dist/chunks/tinyrainbow.Do8I1XRG.js +88 -0
  54. package/dist/chunks/{utils.BS4fH3nR.js → utils.BBk_icFG.js} +50 -52
  55. package/dist/chunks/{utils.BX5Fg8C4.js → utils.DYj33du9.js} +1 -17
  56. package/dist/chunks/vm.b4MbCAJQ.js +1329 -0
  57. package/dist/chunks/{worker.d.ZpHpO4yb.d.ts → worker.d.CyJRpyfZ.d.ts} +34 -19
  58. package/dist/cli.js +5 -6
  59. package/dist/config.cjs +9 -6
  60. package/dist/config.d.ts +27 -25
  61. package/dist/config.js +3 -3
  62. package/dist/index.d.ts +471 -38
  63. package/dist/index.js +18 -19
  64. package/dist/module-evaluator.d.ts +64 -5
  65. package/dist/module-evaluator.js +122 -62
  66. package/dist/node.d.ts +355 -87
  67. package/dist/node.js +49 -73
  68. package/dist/runtime.d.ts +43 -6
  69. package/dist/runtime.js +7 -9
  70. package/dist/spy.js +1 -1
  71. package/dist/task-utils.js +290 -0
  72. package/dist/{chunks/traces.DT5aQ62U.js → traces.js} +3 -2
  73. package/dist/worker.d.ts +8 -10
  74. package/dist/worker.js +33 -43
  75. package/dist/workers/forks.js +30 -40
  76. package/dist/workers/runVmTests.js +66 -43
  77. package/dist/workers/threads.js +30 -40
  78. package/dist/workers/vmForks.js +19 -20
  79. package/dist/workers/vmThreads.js +19 -20
  80. package/globals.d.ts +19 -19
  81. package/index.cjs +3 -3
  82. package/optional-runtime-types.d.ts +1 -1
  83. package/optional-types.d.ts +1 -1
  84. package/package.json +59 -74
  85. package/suppress-warnings.cjs +1 -1
  86. package/dist/chunks/_commonjsHelpers.D26ty3Ew.js +0 -6
  87. package/dist/chunks/benchmark.CX_oY03V.js +0 -40
  88. package/dist/chunks/benchmark.d.DAaHLpsq.d.ts +0 -24
  89. package/dist/chunks/config.d.A1h_Y6Jt.d.ts +0 -232
  90. package/dist/chunks/coverage.DM_a_rWm.js +0 -1087
  91. package/dist/chunks/coverage.d.BZtK59WP.d.ts +0 -37
  92. package/dist/chunks/evaluatedModules.Dg1zASAC.js +0 -17
  93. package/dist/chunks/global.d.DVsSRdQ5.d.ts +0 -100
  94. package/dist/chunks/globals.Dj1TGiMC.js +0 -31
  95. package/dist/chunks/index.DC7d2Pf8.js +0 -729
  96. package/dist/chunks/index.DdgEv5B1.js +0 -42
  97. package/dist/chunks/index.UpGiHP7g.js +0 -4255
  98. package/dist/chunks/index.og1WyBLx.js +0 -6358
  99. package/dist/chunks/nativeModuleRunner.BIakptoF.js +0 -36
  100. package/dist/chunks/node.COQbm6gK.js +0 -14
  101. package/dist/chunks/plugin.d.DwFIiJ7i.d.ts +0 -38
  102. package/dist/chunks/rpc.MzXet3jl.js +0 -144
  103. package/dist/chunks/rpc.d.B_8sPU0w.d.ts +0 -30
  104. package/dist/chunks/setup-common.DYx3LtFI.js +0 -60
  105. package/dist/chunks/startVitestModuleRunner.DB-7oCpn.js +0 -740
  106. package/dist/chunks/suite.d.udJtyAgw.d.ts +0 -10
  107. package/dist/chunks/test.DNmyFkvJ.js +0 -4430
  108. package/dist/chunks/traces.d.D2T_R8rx.d.ts +0 -60
  109. package/dist/chunks/vm.CXMd5FHa.js +0 -785
  110. package/dist/coverage.d.ts +0 -123
  111. package/dist/coverage.js +0 -27
  112. package/dist/environments.d.ts +0 -22
  113. package/dist/environments.js +0 -5
  114. package/dist/reporters.d.ts +0 -27
  115. package/dist/reporters.js +0 -26
  116. package/dist/runners.d.ts +0 -70
  117. package/dist/runners.js +0 -19
  118. package/dist/snapshot.d.ts +0 -9
  119. package/dist/snapshot.js +0 -6
  120. package/dist/suite.d.ts +0 -5
  121. package/dist/suite.js +0 -8
@@ -0,0 +1,37 @@
1
+ import { p as plugins } from './index.D0heQG4v.js';
2
+
3
+ const serialize = (val, config, indentation, depth, refs, printer) => {
4
+ // Serialize a non-default name, even if config.printFunctionName is false.
5
+ const name = val.getMockName();
6
+ const nameString = name === "vi.fn()" ? "" : ` ${name}`;
7
+ let callsString = "";
8
+ if (val.mock.calls.length !== 0) {
9
+ const indentationNext = indentation + config.indent;
10
+ callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(val.mock.calls, config, indentationNext, depth, refs)}${config.min ? ", " : ","}${config.spacingOuter}${indentationNext}"results": ${printer(val.mock.results, config, indentationNext, depth, refs)}${config.min ? "" : ","}${config.spacingOuter}${indentation}}`;
11
+ }
12
+ return `[MockFunction${nameString}]${callsString}`;
13
+ };
14
+ const test = (val) => val && !!val._isMockFunction;
15
+ const plugin = {
16
+ serialize,
17
+ test
18
+ };
19
+
20
+ const { DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent, AsymmetricMatcher } = plugins;
21
+ let PLUGINS = [
22
+ ReactTestComponent,
23
+ ReactElement,
24
+ DOMElement,
25
+ DOMCollection,
26
+ Immutable,
27
+ AsymmetricMatcher,
28
+ plugin
29
+ ];
30
+ function addSerializer(plugin) {
31
+ PLUGINS = [plugin].concat(PLUGINS);
32
+ }
33
+ function getSerializers() {
34
+ return PLUGINS;
35
+ }
36
+
37
+ export { addSerializer as a, getSerializers as g };
@@ -0,0 +1,356 @@
1
+ import { f as isObject, h as getCallLastIndex } from './pathe.M-eThtNZ.zq3TM4NT.js';
2
+ import { p as positionToOffset, o as offsetToLineNumber, l as lineSplitRE } from './offset.Dy-5Fdfn.js';
3
+ import { g as getDefaultExportFromCjs, f as format } from './index.D0heQG4v.js';
4
+ import { g as getSerializers } from './plugins.DPQHVT0p.js';
5
+
6
+ var naturalCompare$1 = {exports: {}};
7
+
8
+ var hasRequiredNaturalCompare;
9
+
10
+ function requireNaturalCompare () {
11
+ if (hasRequiredNaturalCompare) return naturalCompare$1.exports;
12
+ hasRequiredNaturalCompare = 1;
13
+ /*
14
+ * @version 1.4.0
15
+ * @date 2015-10-26
16
+ * @stability 3 - Stable
17
+ * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite)
18
+ * @license MIT License
19
+ */
20
+
21
+
22
+ var naturalCompare = function(a, b) {
23
+ var i, codeA
24
+ , codeB = 1
25
+ , posA = 0
26
+ , posB = 0
27
+ , alphabet = String.alphabet;
28
+
29
+ function getCode(str, pos, code) {
30
+ if (code) {
31
+ for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i;
32
+ return +str.slice(pos - 1, i)
33
+ }
34
+ code = alphabet && alphabet.indexOf(str.charAt(pos));
35
+ return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code
36
+ : code < 46 ? 65 // -
37
+ : code < 48 ? code - 1
38
+ : code < 58 ? code + 18 // 0-9
39
+ : code < 65 ? code - 11
40
+ : code < 91 ? code + 11 // A-Z
41
+ : code < 97 ? code - 37
42
+ : code < 123 ? code + 5 // a-z
43
+ : code - 63
44
+ }
45
+
46
+
47
+ if ((a+="") != (b+="")) for (;codeB;) {
48
+ codeA = getCode(a, posA++);
49
+ codeB = getCode(b, posB++);
50
+
51
+ if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) {
52
+ codeA = getCode(a, posA, posA);
53
+ codeB = getCode(b, posB, posA = i);
54
+ posB = i;
55
+ }
56
+
57
+ if (codeA != codeB) return (codeA < codeB) ? -1 : 1
58
+ }
59
+ return 0
60
+ };
61
+
62
+ try {
63
+ naturalCompare$1.exports = naturalCompare;
64
+ } catch (e) {
65
+ String.naturalCompare = naturalCompare;
66
+ }
67
+ return naturalCompare$1.exports;
68
+ }
69
+
70
+ var naturalCompareExports = requireNaturalCompare();
71
+ var naturalCompare = /*@__PURE__*/getDefaultExportFromCjs(naturalCompareExports);
72
+
73
+ // TODO: rewrite and clean up
74
+ function testNameToKey(testName, count) {
75
+ return `${testName} ${count}`;
76
+ }
77
+ function keyToTestName(key) {
78
+ if (!/ \d+$/.test(key)) throw new Error("Snapshot keys must end with a number.");
79
+ return key.replace(/ \d+$/, "");
80
+ }
81
+ // Evaluate a snapshot file's content into its snapshot key/value pairs.
82
+ function evaluateSnapshotFile(filepath, content) {
83
+ const data = Object.create(null);
84
+ try {
85
+ new Function("exports", content)(data);
86
+ } catch (cause) {
87
+ throw new Error(`Invalid snapshot file, please manually fix or delete it: ${filepath}`, { cause });
88
+ }
89
+ return data;
90
+ }
91
+ // Add extra line breaks at beginning and end of multiline snapshot
92
+ // to make the content easier to read.
93
+ function addExtraLineBreaks(string) {
94
+ return string.includes("\n") ? `\n${string}\n` : string;
95
+ }
96
+ // Remove extra line breaks at beginning and end of multiline snapshot.
97
+ // Instead of trim, which can remove additional newlines or spaces
98
+ // at beginning or end of the content from a custom serializer.
99
+ function removeExtraLineBreaks(string) {
100
+ return string.length > 2 && string[0] === "\n" && string.endsWith("\n") ? string.slice(1, -1) : string;
101
+ }
102
+ // export const removeLinesBeforeExternalMatcherTrap = (stack: string): string => {
103
+ // const lines = stack.split('\n')
104
+ // for (let i = 0; i < lines.length; i += 1) {
105
+ // // It's a function name specified in `packages/expect/src/index.ts`
106
+ // // for external custom matchers.
107
+ // if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__'))
108
+ // return lines.slice(i + 1).join('\n')
109
+ // }
110
+ // return stack
111
+ // }
112
+ const escapeRegex = true;
113
+ const printFunctionName = false;
114
+ function serialize(val, indent = 2, formatOverrides = {}) {
115
+ return normalizeNewlines(format(val, {
116
+ escapeRegex,
117
+ indent,
118
+ plugins: getSerializers(),
119
+ printFunctionName,
120
+ ...formatOverrides
121
+ }));
122
+ }
123
+ function escapeBacktickString(str) {
124
+ // a raw CR inside a template literal is read back as LF
125
+ return str.replace(/`|\\|\$\{/g, "\\$&").replace(/\r/g, "\\r");
126
+ }
127
+ function printBacktickString(str) {
128
+ return `\`${escapeBacktickString(str)}\``;
129
+ }
130
+ function normalizeNewlines(string) {
131
+ return string.replace(/\r\n|\r/g, "\n");
132
+ }
133
+ async function saveSnapshotFile(environment, snapshotData, snapshotPath) {
134
+ const snapshots = Object.keys(snapshotData).sort(naturalCompare).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`);
135
+ const content = `${environment.getHeader()}\n\n${snapshots.join("\n\n")}\n`;
136
+ const oldContent = await environment.readSnapshotFile(snapshotPath);
137
+ if (oldContent != null && oldContent === content) return;
138
+ await environment.saveSnapshotFile(snapshotPath, content);
139
+ }
140
+ function deepMergeArray(target = [], source = []) {
141
+ const mergedOutput = Array.from(target);
142
+ source.forEach((sourceElement, index) => {
143
+ const targetElement = mergedOutput[index];
144
+ if (Array.isArray(target[index])) mergedOutput[index] = deepMergeArray(target[index], sourceElement);
145
+ else if (isObject(targetElement)) mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement);
146
+ else
147
+ // Source does not exist in target or target is primitive and cannot be deep merged
148
+ mergedOutput[index] = sourceElement;
149
+ });
150
+ return mergedOutput;
151
+ }
152
+ /**
153
+ * Deep merge, but considers asymmetric matchers. Unlike base util's deep merge,
154
+ * will merge any object-like instance.
155
+ * Compatible with Jest's snapshot matcher. Should not be used outside of snapshot.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * toMatchSnapshot({
160
+ * name: expect.stringContaining('text')
161
+ * })
162
+ * ```
163
+ */
164
+ function deepMergeSnapshot(target, source) {
165
+ if (isObject(target) && isObject(source)) {
166
+ const mergedOutput = { ...target };
167
+ Object.keys(source).forEach((key) => {
168
+ if (isObject(source[key]) && !source[key].$$typeof) {
169
+ if (!(key in target)) Object.assign(mergedOutput, { [key]: source[key] });
170
+ else mergedOutput[key] = deepMergeSnapshot(target[key], source[key]);
171
+ } else if (Array.isArray(source[key])) mergedOutput[key] = deepMergeArray(target[key], source[key]);
172
+ else Object.assign(mergedOutput, { [key]: source[key] });
173
+ });
174
+ return mergedOutput;
175
+ } else if (Array.isArray(target) && Array.isArray(source)) return deepMergeArray(target, source);
176
+ return target;
177
+ }
178
+ class DefaultMap extends Map {
179
+ defaultFn;
180
+ constructor(defaultFn, entries) {
181
+ super(entries);
182
+ this.defaultFn = defaultFn;
183
+ }
184
+ get(key) {
185
+ if (!this.has(key)) this.set(key, this.defaultFn(key));
186
+ return super.get(key);
187
+ }
188
+ }
189
+ class CounterMap extends DefaultMap {
190
+ constructor() {
191
+ super(() => 0);
192
+ }
193
+ // compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322
194
+ // `valueOf` and `Snapshot.added` setter allows
195
+ // snapshotState.added = snapshotState.added + 1
196
+ // to function as
197
+ // snapshotState.added.total_ = snapshotState.added.total() + 1
198
+ _total;
199
+ valueOf() {
200
+ return this._total = this.total();
201
+ }
202
+ increment(key) {
203
+ if (typeof this._total !== "undefined") this._total++;
204
+ this.set(key, this.get(key) + 1);
205
+ }
206
+ total() {
207
+ if (typeof this._total !== "undefined") return this._total;
208
+ let total = 0;
209
+ for (const x of this.values()) total += x;
210
+ return total;
211
+ }
212
+ }
213
+ /* @__NO_SIDE_EFFECTS__ */
214
+ function memo(fn) {
215
+ const cache = /* @__PURE__ */ new Map();
216
+ return (arg) => {
217
+ if (!cache.has(arg)) cache.set(arg, fn(arg));
218
+ return cache.get(arg);
219
+ };
220
+ }
221
+
222
+ async function saveInlineSnapshots(environment, snapshots) {
223
+ const MagicString = (await import('magic-string')).default;
224
+ const files = new Set(snapshots.map((i) => i.file));
225
+ await Promise.all(Array.from(files).map(async (file) => {
226
+ const snaps = snapshots.filter((i) => i.file === file);
227
+ const code = await environment.readSnapshotFile(file);
228
+ if (code == null) throw new Error(`cannot read ${file} when saving inline snapshot`);
229
+ const s = new MagicString(code);
230
+ for (const snap of snaps) replaceInlineSnap(code, s, positionToOffset(code, snap.line, snap.column), snap.snapshot, snap.assertionName);
231
+ const transformed = s.toString();
232
+ if (transformed !== code) await environment.saveSnapshotFile(file, transformed);
233
+ }));
234
+ }
235
+ const defaultStartObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/;
236
+ function escapeRegExp(s) {
237
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
238
+ }
239
+ const buildStartObjectRegex = memo((assertionName) => {
240
+ const replaced = defaultStartObjectRegex.source.replace("toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot", escapeRegExp(assertionName));
241
+ return new RegExp(replaced);
242
+ });
243
+ function replaceObjectSnap(code, s, index, newSnap, assertionName) {
244
+ let _code = code.slice(index);
245
+ const startMatch = (assertionName ? buildStartObjectRegex(assertionName) : defaultStartObjectRegex).exec(_code);
246
+ if (!startMatch) return false;
247
+ _code = _code.slice(startMatch.index);
248
+ let callEnd = getCallLastIndex(_code);
249
+ if (callEnd === null) return false;
250
+ callEnd += index + startMatch.index;
251
+ const shapeEnd = getObjectShapeEndIndex(code, index + startMatch.index + startMatch[0].length);
252
+ const snap = `, ${prepareSnapString(newSnap, code, index)}`;
253
+ if (shapeEnd === callEnd)
254
+ // toMatchInlineSnapshot({ foo: expect.any(String) })
255
+ s.appendLeft(callEnd, snap);
256
+ else
257
+ // toMatchInlineSnapshot({ foo: expect.any(String) }, ``)
258
+ s.overwrite(shapeEnd, callEnd, snap);
259
+ return true;
260
+ }
261
+ function getObjectShapeEndIndex(code, index) {
262
+ let startBraces = 1;
263
+ let endBraces = 0;
264
+ while (startBraces !== endBraces && index < code.length) {
265
+ const s = code[index++];
266
+ if (s === "{") startBraces++;
267
+ else if (s === "}") endBraces++;
268
+ }
269
+ return index;
270
+ }
271
+ function prepareSnapString(snap, source, index) {
272
+ const lineNumber = offsetToLineNumber(source, index);
273
+ const indent = source.split(lineSplitRE)[lineNumber - 1].match(/^\s*/)[0] || "";
274
+ const indentNext = indent.includes(" ") ? `${indent}\t` : `${indent} `;
275
+ const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g);
276
+ const isOneline = lines.length <= 1;
277
+ const quote = "`";
278
+ if (isOneline) return `${quote}${lines.join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}${quote}`;
279
+ return `${quote}\n${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}\n${indent}${quote}`;
280
+ }
281
+ const defaultMethodNames = ["toMatchInlineSnapshot", "toThrowErrorMatchingInlineSnapshot"];
282
+ // on webkit, the line number is at the end of the method, not at the start
283
+ function getCodeStartingAtIndex(code, index, methodNames) {
284
+ for (const name of methodNames) {
285
+ const adjusted = index - name.length;
286
+ if (adjusted >= 0 && code.slice(adjusted, index) === name) return {
287
+ code: code.slice(adjusted),
288
+ index: adjusted
289
+ };
290
+ }
291
+ return {
292
+ code: code.slice(index),
293
+ index
294
+ };
295
+ }
296
+ const defaultStartRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/;
297
+ const buildStartRegex = memo((assertionName) => {
298
+ const replaced = defaultStartRegex.source.replace("toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot", escapeRegExp(assertionName));
299
+ return new RegExp(replaced);
300
+ });
301
+ function replaceInlineSnap(code, s, currentIndex, newSnap, assertionName) {
302
+ const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex, assertionName ? [assertionName] : defaultMethodNames);
303
+ const startMatch = (assertionName ? buildStartRegex(assertionName) : defaultStartRegex).exec(codeStartingAtIndex);
304
+ const firstKeywordMatch = (assertionName ? new RegExp(escapeRegExp(assertionName)) : /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/).exec(codeStartingAtIndex);
305
+ if (!startMatch || startMatch.index !== firstKeywordMatch?.index) return replaceObjectSnap(code, s, index, newSnap, assertionName);
306
+ const quote = startMatch[1];
307
+ const startIndex = index + startMatch.index + startMatch[0].length;
308
+ const snapString = prepareSnapString(newSnap, code, index);
309
+ if (quote === ")") {
310
+ s.appendRight(startIndex - 1, snapString);
311
+ return true;
312
+ }
313
+ const endMatch = new RegExp(`(?:^|[^\\\\])${quote}`).exec(code.slice(startIndex));
314
+ if (!endMatch) return false;
315
+ const endIndex = startIndex + endMatch.index + endMatch[0].length;
316
+ s.overwrite(startIndex - 1, endIndex, snapString);
317
+ return true;
318
+ }
319
+ const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
320
+ function stripSnapshotIndentation(inlineSnapshot) {
321
+ // Find indentation if exists.
322
+ const match = inlineSnapshot.match(INDENTATION_REGEX);
323
+ if (!match || !match[1])
324
+ // No indentation.
325
+ return inlineSnapshot;
326
+ const indentation = match[1];
327
+ const lines = inlineSnapshot.split(/\n/g);
328
+ if (lines.length <= 2)
329
+ // Must be at least 3 lines.
330
+ return inlineSnapshot;
331
+ if (lines[0].trim() !== "" || lines.at(-1)?.trim() !== "")
332
+ // If not blank first and last lines, abort.
333
+ return inlineSnapshot;
334
+ for (let i = 1; i < lines.length - 1; i++) if (lines[i] !== "") {
335
+ if (lines[i].indexOf(indentation) !== 0)
336
+ // All lines except first and last should either be blank or have the same
337
+ // indent as the first line (or more). If this isn't the case we don't
338
+ // want to touch the snapshot at all.
339
+ return inlineSnapshot;
340
+ lines[i] = lines[i].substring(indentation.length);
341
+ }
342
+ // Last line is a special case because it won't have the same indent as others
343
+ // but may still have been given some indent to line up.
344
+ lines[lines.length - 1] = "";
345
+ // Return inline snapshot, now at indent 0.
346
+ inlineSnapshot = lines.join("\n");
347
+ return inlineSnapshot;
348
+ }
349
+
350
+ async function saveRawSnapshots(environment, snapshots) {
351
+ await Promise.all(snapshots.map(async (snap) => {
352
+ if (!snap.readonly) await environment.saveSnapshotFile(snap.file, snap.snapshot);
353
+ }));
354
+ }
355
+
356
+ export { CounterMap as C, DefaultMap as D, saveInlineSnapshots as a, saveRawSnapshots as b, serialize as c, addExtraLineBreaks as d, evaluateSnapshotFile as e, deepMergeSnapshot as f, stripSnapshotIndentation as g, keyToTestName as k, normalizeNewlines as n, removeExtraLineBreaks as r, saveSnapshotFile as s, testNameToKey as t };
@@ -0,0 +1,48 @@
1
+ import fs__default from 'node:fs';
2
+ import { b as basename, j as join, d as dirname } from './pathe.M-eThtNZ.zq3TM4NT.js';
3
+
4
+ const packageScopeTypeCache = /* @__PURE__ */ new Map();
5
+ // mirrors LOOKUP_PACKAGE_SCOPE from the ESM resolution algorithm:
6
+ // the lookup stops at the first package.json and never crosses
7
+ // the "node_modules" boundary, so typeless dependencies don't
8
+ // inherit the `type` field of the user's project
9
+ function lookupPackageScopeType(directory) {
10
+ const visited = [];
11
+ let result = "none";
12
+ let current = directory;
13
+ while (current) {
14
+ const cached = packageScopeTypeCache.get(current);
15
+ if (cached) {
16
+ result = cached;
17
+ break;
18
+ }
19
+ if (basename(current) === "node_modules") break;
20
+ visited.push(current);
21
+ const packageJsonPath = join(current, "package.json");
22
+ if (tryStatSync(packageJsonPath)?.isFile()) {
23
+ try {
24
+ const packageJson = JSON.parse(stripBomTag(fs__default.readFileSync(packageJsonPath, "utf8")));
25
+ if (packageJson.type === "module") result = "esm";
26
+ else if (packageJson.type === "commonjs") result = "cjs";
27
+ } catch {}
28
+ break;
29
+ }
30
+ const parent = dirname(current);
31
+ if (parent === current) break;
32
+ current = parent;
33
+ }
34
+ visited.forEach((dir) => packageScopeTypeCache.set(dir, result));
35
+ return result;
36
+ }
37
+ function stripBomTag(content) {
38
+ if (content.charCodeAt(0) === 65279) return content.slice(1);
39
+ return content;
40
+ }
41
+ function tryStatSync(file) {
42
+ try {
43
+ // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
44
+ return fs__default.statSync(file, { throwIfNoEntry: false });
45
+ } catch {}
46
+ }
47
+
48
+ export { lookupPackageScopeType as l };
@@ -0,0 +1,93 @@
1
+ import { EvaluatedModules } from 'vite/module-runner';
2
+ import { d as dirname, r as resolve } from './pathe.M-eThtNZ.zq3TM4NT.js';
3
+ import { a as getSafeTimers } from './source-map.DakdQc29.js';
4
+ import { c as createBirpc } from './index.DmDMHCg8.js';
5
+ import { g as getWorkerState } from './utils.DYj33du9.js';
6
+
7
+ // TODO: this is not needed in Vite 7.2+
8
+ class VitestEvaluatedModules extends EvaluatedModules {
9
+ getModuleSourceMapById(id) {
10
+ /** the return type is not exposed by Vite */
11
+ const map = super.getModuleSourceMapById(id);
12
+ if (map != null && !("_patched" in map)) {
13
+ map._patched = true;
14
+ const dir = dirname(map.url);
15
+ map.resolvedSources = (map.map.sources || []).map((s) => resolve(dir, s || ""));
16
+ }
17
+ return map;
18
+ }
19
+ }
20
+
21
+ const { get } = Reflect;
22
+ const globalProcess = globalThis.process;
23
+ function withSafeTimers(fn) {
24
+ const { setTimeout, clearTimeout, nextTick, setImmediate, clearImmediate } = getSafeTimers();
25
+ const currentSetTimeout = globalThis.setTimeout;
26
+ const currentClearTimeout = globalThis.clearTimeout;
27
+ const currentSetImmediate = globalThis.setImmediate;
28
+ const currentClearImmediate = globalThis.clearImmediate;
29
+ const currentNextTick = globalProcess?.nextTick;
30
+ try {
31
+ globalThis.setTimeout = setTimeout;
32
+ globalThis.clearTimeout = clearTimeout;
33
+ if (setImmediate) globalThis.setImmediate = setImmediate;
34
+ if (clearImmediate) globalThis.clearImmediate = clearImmediate;
35
+ if (globalProcess && nextTick) globalProcess.nextTick = nextTick;
36
+ return fn();
37
+ } finally {
38
+ globalThis.setTimeout = currentSetTimeout;
39
+ globalThis.clearTimeout = currentClearTimeout;
40
+ globalThis.setImmediate = currentSetImmediate;
41
+ globalThis.clearImmediate = currentClearImmediate;
42
+ if (globalProcess && nextTick) nextTick(() => {
43
+ globalProcess.nextTick = currentNextTick;
44
+ });
45
+ }
46
+ }
47
+ const promises = /* @__PURE__ */ new Set();
48
+ async function rpcDone() {
49
+ if (!promises.size) return;
50
+ const awaitable = Array.from(promises);
51
+ return Promise.all(awaitable);
52
+ }
53
+ const onCancelCallbacks = [];
54
+ function onCancel(callback) {
55
+ onCancelCallbacks.push(callback);
56
+ return () => {
57
+ const index = onCancelCallbacks.indexOf(callback);
58
+ if (index !== -1) onCancelCallbacks.splice(index, 1);
59
+ };
60
+ }
61
+ function createRuntimeRpc(options) {
62
+ return createSafeRpc(createBirpc({ async onCancel(reason) {
63
+ await Promise.all(onCancelCallbacks.map((fn) => fn(reason)));
64
+ } }, {
65
+ eventNames: ["onCancel"],
66
+ timeout: -1,
67
+ ...options
68
+ }));
69
+ }
70
+ function createSafeRpc(rpc) {
71
+ return new Proxy(rpc, { get(target, p, handler) {
72
+ // keep $rejectPendingCalls as sync function
73
+ if (p === "$rejectPendingCalls") return rpc.$rejectPendingCalls;
74
+ const sendCall = get(target, p, handler);
75
+ const safeSendCall = (...args) => withSafeTimers(async () => {
76
+ const result = sendCall(...args);
77
+ promises.add(result);
78
+ try {
79
+ return await result;
80
+ } finally {
81
+ promises.delete(result);
82
+ }
83
+ });
84
+ safeSendCall.asEvent = sendCall.asEvent;
85
+ return safeSendCall;
86
+ } });
87
+ }
88
+ function rpc() {
89
+ const { rpc } = getWorkerState();
90
+ return rpc;
91
+ }
92
+
93
+ export { VitestEvaluatedModules as V, rpcDone as a, createRuntimeRpc as c, onCancel as o, rpc as r };
@@ -0,0 +1,75 @@
1
+ import { bw as FetchCachedFileSystemResult, bx as ResolveFunctionResult, U as UserConsoleLog, bo as AsyncLeak, a as File, a3 as AfterSuiteRunMeta, b2 as TestBenchmark, j as TestArtifact, k as TaskResultPack, l as TaskEventPack, Z as CancelReason, aO as SnapshotResult, a6 as BaselineData } from './config.d.B3YV4t0O.js';
2
+ import { FetchFunctionOptions, FetchResult } from 'vite/module-runner';
3
+
4
+ interface OTELCarrier {
5
+ traceparent?: string;
6
+ tracestate?: string;
7
+ }
8
+ interface TracesOptions {
9
+ enabled: boolean;
10
+ watchMode?: boolean;
11
+ sdkPath?: string;
12
+ tracerName?: string;
13
+ }
14
+ declare class Traces {
15
+ #private;
16
+ constructor(options: TracesOptions);
17
+ isEnabled(): boolean;
18
+ }
19
+
20
+ declare class GetterTracker {
21
+ static EXPORTS_MAX_INVOCATIONS: number;
22
+ private invocations;
23
+ private excessiveInvocations;
24
+ createTracker(moduleId: string, defineExport: (name: string, getter: () => unknown) => void): (name: string, getter: () => unknown) => void;
25
+ resetInvocations(): void;
26
+ getExcessiveInvocations(): GetterTrackerExport[];
27
+ }
28
+ interface GetterTrackerExport {
29
+ moduleId: string;
30
+ exportName: string;
31
+ }
32
+
33
+ interface RuntimeRPC {
34
+ fetch: (id: string, importer: string | undefined, environment: string, options?: FetchFunctionOptions, otelCarrier?: OTELCarrier) => Promise<FetchResult | FetchCachedFileSystemResult>;
35
+ resolve: (id: string, importer: string | undefined, environment: string) => Promise<ResolveFunctionResult | null>;
36
+ /**
37
+ * Returns the modules of the given test files' import graphs that the server
38
+ * has already processed, so a fresh worker can load them from disk without
39
+ * paying a `fetch` round-trip per module.
40
+ */
41
+ fetchWarmModules: (environment: string, files: string[]) => Promise<Record<string, FetchResult | FetchCachedFileSystemResult>>;
42
+ /**
43
+ * Transforms the import graphs of the given test files ahead of the
44
+ * worker's own fetches. Fired by vm pool workers before their environment
45
+ * setup, so the server transforms modules while the worker is busy
46
+ * importing its environment package.
47
+ */
48
+ prewarmModuleGraph: (environment: string, files: string[]) => Promise<void>;
49
+ transform: (id: string) => Promise<{
50
+ code?: string;
51
+ }>;
52
+ onUserConsoleLog: (log: UserConsoleLog) => void;
53
+ onUnhandledError: (err: unknown, type: string) => void;
54
+ onAsyncLeaks: (leak: AsyncLeak[]) => void;
55
+ onTestModuleDependencies: (filepath: string, dependencies: string[]) => void;
56
+ onQueued: (file: File) => void;
57
+ onCollected: (files: File[]) => Promise<void>;
58
+ onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void;
59
+ onTestBenchmark: (testId: string, bench: TestBenchmark) => void;
60
+ onTaskArtifactRecord: <Artifact extends TestArtifact>(testId: string, artifact: Artifact) => Promise<Artifact>;
61
+ onTaskUpdate: (pack: TaskResultPack[], events: TaskEventPack[]) => Promise<void>;
62
+ onCancel: (reason: CancelReason) => void;
63
+ getCountOfFailedTests: () => number;
64
+ snapshotSaved: (snapshot: SnapshotResult) => void;
65
+ resolveSnapshotPath: (testPath: string) => string;
66
+ readBenchmarkResult: (relativePath: string) => Promise<BaselineData | null>;
67
+ writeBenchmarkResult: (relativePath: string, data: BaselineData) => Promise<void>;
68
+ ensureModuleGraphEntry: (id: string, importer: string) => void;
69
+ }
70
+ interface RunnerRPC {
71
+ onCancel: (reason: CancelReason) => void;
72
+ }
73
+
74
+ export { GetterTracker as G, Traces as T };
75
+ export type { OTELCarrier as O, RunnerRPC as R, RuntimeRPC as a };