@vitest/snapshot 4.1.0-beta.3 → 4.1.0-beta.4

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.
@@ -1,9 +1,4 @@
1
- interface ParsedStack {
2
- method: string;
3
- file: string;
4
- line: number;
5
- column: number;
6
- }
1
+ import { ParsedStack } from '@vitest/utils';
7
2
 
8
3
  interface SnapshotEnvironment {
9
4
  getVersion: () => string;
@@ -19,4 +14,4 @@ interface SnapshotEnvironmentOptions {
19
14
  snapshotsDirName?: string;
20
15
  }
21
16
 
22
- export type { ParsedStack as P, SnapshotEnvironment as S, SnapshotEnvironmentOptions as a };
17
+ export type { SnapshotEnvironment as S, SnapshotEnvironmentOptions as a };
@@ -1,4 +1,5 @@
1
- import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment.d-DHdQ1Csl.js';
1
+ import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment.d-DOJxxZV9.js';
2
+ import '@vitest/utils';
2
3
 
3
4
  declare class NodeSnapshotEnvironment implements SnapshotEnvironment {
4
5
  private options;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './rawSnapshot.d-lFsMJFUd.js';
2
- export { c as SnapshotData, d as SnapshotSerializer, e as SnapshotSummary, f as SnapshotUpdateState, U as UncheckedSnapshot } from './rawSnapshot.d-lFsMJFUd.js';
3
- import { S as SnapshotEnvironment, P as ParsedStack } from './environment.d-DHdQ1Csl.js';
1
+ import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './rawSnapshot.d-U2kJUxDr.js';
2
+ export { c as SnapshotData, d as SnapshotSerializer, e as SnapshotSummary, f as SnapshotUpdateState, U as UncheckedSnapshot } from './rawSnapshot.d-U2kJUxDr.js';
3
+ import { ParsedStack } from '@vitest/utils';
4
+ import { S as SnapshotEnvironment } from './environment.d-DOJxxZV9.js';
4
5
  import { Plugin, Plugins } from '@vitest/pretty-format';
5
6
 
6
7
  /**
package/dist/index.js CHANGED
@@ -1,551 +1,8 @@
1
- import { resolve } from 'pathe';
1
+ import { parseErrorStacktrace } from '@vitest/utils/source-map';
2
+ import { getCallLastIndex, isObject } from '@vitest/utils/helpers';
3
+ import { positionToOffset, offsetToLineNumber, lineSplitRE } from '@vitest/utils/offset';
2
4
  import { plugins, format } from '@vitest/pretty-format';
3
5
 
4
- // src/vlq.ts
5
- var comma = ",".charCodeAt(0);
6
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
7
- var intToChar = new Uint8Array(64);
8
- var charToInt = new Uint8Array(128);
9
- for (let i = 0; i < chars.length; i++) {
10
- const c = chars.charCodeAt(i);
11
- intToChar[i] = c;
12
- charToInt[c] = i;
13
- }
14
- function decodeInteger(reader, relative) {
15
- let value = 0;
16
- let shift = 0;
17
- let integer = 0;
18
- do {
19
- const c = reader.next();
20
- integer = charToInt[c];
21
- value |= (integer & 31) << shift;
22
- shift += 5;
23
- } while (integer & 32);
24
- const shouldNegate = value & 1;
25
- value >>>= 1;
26
- if (shouldNegate) {
27
- value = -2147483648 | -value;
28
- }
29
- return relative + value;
30
- }
31
- function hasMoreVlq(reader, max) {
32
- if (reader.pos >= max) return false;
33
- return reader.peek() !== comma;
34
- }
35
- var StringReader = class {
36
- constructor(buffer) {
37
- this.pos = 0;
38
- this.buffer = buffer;
39
- }
40
- next() {
41
- return this.buffer.charCodeAt(this.pos++);
42
- }
43
- peek() {
44
- return this.buffer.charCodeAt(this.pos);
45
- }
46
- indexOf(char) {
47
- const { buffer, pos } = this;
48
- const idx = buffer.indexOf(char, pos);
49
- return idx === -1 ? buffer.length : idx;
50
- }
51
- };
52
-
53
- // src/sourcemap-codec.ts
54
- function decode(mappings) {
55
- const { length } = mappings;
56
- const reader = new StringReader(mappings);
57
- const decoded = [];
58
- let genColumn = 0;
59
- let sourcesIndex = 0;
60
- let sourceLine = 0;
61
- let sourceColumn = 0;
62
- let namesIndex = 0;
63
- do {
64
- const semi = reader.indexOf(";");
65
- const line = [];
66
- let sorted = true;
67
- let lastCol = 0;
68
- genColumn = 0;
69
- while (reader.pos < semi) {
70
- let seg;
71
- genColumn = decodeInteger(reader, genColumn);
72
- if (genColumn < lastCol) sorted = false;
73
- lastCol = genColumn;
74
- if (hasMoreVlq(reader, semi)) {
75
- sourcesIndex = decodeInteger(reader, sourcesIndex);
76
- sourceLine = decodeInteger(reader, sourceLine);
77
- sourceColumn = decodeInteger(reader, sourceColumn);
78
- if (hasMoreVlq(reader, semi)) {
79
- namesIndex = decodeInteger(reader, namesIndex);
80
- seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
81
- } else {
82
- seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
83
- }
84
- } else {
85
- seg = [genColumn];
86
- }
87
- line.push(seg);
88
- reader.pos++;
89
- }
90
- if (!sorted) sort(line);
91
- decoded.push(line);
92
- reader.pos = semi + 1;
93
- } while (reader.pos <= length);
94
- return decoded;
95
- }
96
- function sort(line) {
97
- line.sort(sortComparator);
98
- }
99
- function sortComparator(a, b) {
100
- return a[0] - b[0];
101
- }
102
-
103
- // src/trace-mapping.ts
104
-
105
- // src/sourcemap-segment.ts
106
- var COLUMN = 0;
107
- var SOURCES_INDEX = 1;
108
- var SOURCE_LINE = 2;
109
- var SOURCE_COLUMN = 3;
110
- var NAMES_INDEX = 4;
111
-
112
- // src/binary-search.ts
113
- var found = false;
114
- function binarySearch(haystack, needle, low, high) {
115
- while (low <= high) {
116
- const mid = low + (high - low >> 1);
117
- const cmp = haystack[mid][COLUMN] - needle;
118
- if (cmp === 0) {
119
- found = true;
120
- return mid;
121
- }
122
- if (cmp < 0) {
123
- low = mid + 1;
124
- } else {
125
- high = mid - 1;
126
- }
127
- }
128
- found = false;
129
- return low - 1;
130
- }
131
- function upperBound(haystack, needle, index) {
132
- for (let i = index + 1; i < haystack.length; index = i++) {
133
- if (haystack[i][COLUMN] !== needle) break;
134
- }
135
- return index;
136
- }
137
- function lowerBound(haystack, needle, index) {
138
- for (let i = index - 1; i >= 0; index = i--) {
139
- if (haystack[i][COLUMN] !== needle) break;
140
- }
141
- return index;
142
- }
143
- function memoizedBinarySearch(haystack, needle, state, key) {
144
- const { lastKey, lastNeedle, lastIndex } = state;
145
- let low = 0;
146
- let high = haystack.length - 1;
147
- if (key === lastKey) {
148
- if (needle === lastNeedle) {
149
- found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
150
- return lastIndex;
151
- }
152
- if (needle >= lastNeedle) {
153
- low = lastIndex === -1 ? 0 : lastIndex;
154
- } else {
155
- high = lastIndex;
156
- }
157
- }
158
- state.lastKey = key;
159
- state.lastNeedle = needle;
160
- return state.lastIndex = binarySearch(haystack, needle, low, high);
161
- }
162
-
163
- // src/trace-mapping.ts
164
- var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
165
- var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
166
- var LEAST_UPPER_BOUND = -1;
167
- var GREATEST_LOWER_BOUND = 1;
168
- function cast(map) {
169
- return map;
170
- }
171
- function decodedMappings(map) {
172
- var _a;
173
- return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
174
- }
175
- function originalPositionFor(map, needle) {
176
- let { line, column, bias } = needle;
177
- line--;
178
- if (line < 0) throw new Error(LINE_GTR_ZERO);
179
- if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
180
- const decoded = decodedMappings(map);
181
- if (line >= decoded.length) return OMapping(null, null, null, null);
182
- const segments = decoded[line];
183
- const index = traceSegmentInternal(
184
- segments,
185
- cast(map)._decodedMemo,
186
- line,
187
- column,
188
- bias || GREATEST_LOWER_BOUND
189
- );
190
- if (index === -1) return OMapping(null, null, null, null);
191
- const segment = segments[index];
192
- if (segment.length === 1) return OMapping(null, null, null, null);
193
- const { names, resolvedSources } = map;
194
- return OMapping(
195
- resolvedSources[segment[SOURCES_INDEX]],
196
- segment[SOURCE_LINE] + 1,
197
- segment[SOURCE_COLUMN],
198
- segment.length === 5 ? names[segment[NAMES_INDEX]] : null
199
- );
200
- }
201
- function OMapping(source, line, column, name) {
202
- return { source, line, column, name };
203
- }
204
- function traceSegmentInternal(segments, memo, line, column, bias) {
205
- let index = memoizedBinarySearch(segments, column, memo, line);
206
- if (found) {
207
- index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
208
- } else if (bias === LEAST_UPPER_BOUND) index++;
209
- if (index === -1 || index === segments.length) return -1;
210
- return index;
211
- }
212
-
213
- function notNullish(v) {
214
- return v != null;
215
- }
216
- function isPrimitive(value) {
217
- return value === null || typeof value !== "function" && typeof value !== "object";
218
- }
219
- function isObject(item) {
220
- return item != null && typeof item === "object" && !Array.isArray(item);
221
- }
222
- /**
223
- * If code starts with a function call, will return its last index, respecting arguments.
224
- * This will return 25 - last ending character of toMatch ")"
225
- * Also works with callbacks
226
- * ```
227
- * toMatch({ test: '123' });
228
- * toBeAliased('123')
229
- * ```
230
- */
231
- function getCallLastIndex(code) {
232
- let charIndex = -1;
233
- let inString = null;
234
- let startedBracers = 0;
235
- let endedBracers = 0;
236
- let beforeChar = null;
237
- while (charIndex <= code.length) {
238
- beforeChar = code[charIndex];
239
- charIndex++;
240
- const char = code[charIndex];
241
- const isCharString = char === "\"" || char === "'" || char === "`";
242
- if (isCharString && beforeChar !== "\\") {
243
- if (inString === char) {
244
- inString = null;
245
- } else if (!inString) {
246
- inString = char;
247
- }
248
- }
249
- if (!inString) {
250
- if (char === "(") {
251
- startedBracers++;
252
- }
253
- if (char === ")") {
254
- endedBracers++;
255
- }
256
- }
257
- if (startedBracers && endedBracers && startedBracers === endedBracers) {
258
- return charIndex;
259
- }
260
- }
261
- return null;
262
- }
263
-
264
- const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
265
- const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
266
- const stackIgnorePatterns = [
267
- "node:internal",
268
- /\/packages\/\w+\/dist\//,
269
- /\/@vitest\/\w+\/dist\//,
270
- "/vitest/dist/",
271
- "/vitest/src/",
272
- "/node_modules/chai/",
273
- "/node_modules/tinyspy/",
274
- "/vite/dist/node/module-runner",
275
- "/rolldown-vite/dist/node/module-runner",
276
- "/deps/chunk-",
277
- "/deps/@vitest",
278
- "/deps/loupe",
279
- "/deps/chai",
280
- "/browser-playwright/dist/locators.js",
281
- "/browser-webdriverio/dist/locators.js",
282
- "/browser-preview/dist/locators.js",
283
- /node:\w+/,
284
- /__vitest_test__/,
285
- /__vitest_browser__/,
286
- "/@id/__x00__vitest/browser",
287
- /\/deps\/vitest_/
288
- ];
289
- const NOW_LENGTH = Date.now().toString().length;
290
- const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
291
- function extractLocation(urlLike) {
292
- // Fail-fast but return locations like "(native)"
293
- if (!urlLike.includes(":")) {
294
- return [urlLike];
295
- }
296
- const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
297
- const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, ""));
298
- if (!parts) {
299
- return [urlLike];
300
- }
301
- let url = parts[1];
302
- if (url.startsWith("async ")) {
303
- url = url.slice(6);
304
- }
305
- if (url.startsWith("http:") || url.startsWith("https:")) {
306
- const urlObj = new URL(url);
307
- urlObj.searchParams.delete("import");
308
- urlObj.searchParams.delete("browserv");
309
- url = urlObj.pathname + urlObj.hash + urlObj.search;
310
- }
311
- if (url.startsWith("/@fs/")) {
312
- const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
313
- url = url.slice(isWindows ? 5 : 4);
314
- }
315
- if (url.includes("vitest=")) {
316
- url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
317
- }
318
- return [
319
- url,
320
- parts[2] || undefined,
321
- parts[3] || undefined
322
- ];
323
- }
324
- function parseSingleFFOrSafariStack(raw) {
325
- let line = raw.trim();
326
- if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
327
- return null;
328
- }
329
- if (line.includes(" > eval")) {
330
- line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
331
- }
332
- // Early return for lines that don't look like Firefox/Safari stack traces
333
- // Firefox/Safari stack traces must contain '@' and should have location info after it
334
- if (!line.includes("@")) {
335
- return null;
336
- }
337
- // Find the correct @ that separates function name from location
338
- // For cases like '@https://@fs/path' or 'functionName@https://@fs/path'
339
- // we need to find the first @ that precedes a valid location (containing :)
340
- let atIndex = -1;
341
- let locationPart = "";
342
- let functionName;
343
- // Try each @ from left to right to find the one that gives us a valid location
344
- for (let i = 0; i < line.length; i++) {
345
- if (line[i] === "@") {
346
- const candidateLocation = line.slice(i + 1);
347
- // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1")
348
- if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
349
- atIndex = i;
350
- locationPart = candidateLocation;
351
- functionName = i > 0 ? line.slice(0, i) : undefined;
352
- break;
353
- }
354
- }
355
- }
356
- // Validate we found a valid location with minimum length (filename:line format)
357
- if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) {
358
- return null;
359
- }
360
- const [url, lineNumber, columnNumber] = extractLocation(locationPart);
361
- if (!url || !lineNumber || !columnNumber) {
362
- return null;
363
- }
364
- return {
365
- file: url,
366
- method: functionName || "",
367
- line: Number.parseInt(lineNumber),
368
- column: Number.parseInt(columnNumber)
369
- };
370
- }
371
- // Based on https://github.com/stacktracejs/error-stack-parser
372
- // Credit to stacktracejs
373
- function parseSingleV8Stack(raw) {
374
- let line = raw.trim();
375
- if (!CHROME_IE_STACK_REGEXP.test(line)) {
376
- return null;
377
- }
378
- if (line.includes("(eval ")) {
379
- line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
380
- }
381
- let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
382
- // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in
383
- // case it has spaces in it, as the string is split on \s+ later on
384
- const location = sanitizedLine.match(/ (\(.+\)$)/);
385
- // remove the parenthesized location from the line, if it was matched
386
- sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
387
- // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
388
- // because this line doesn't have function name
389
- const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
390
- let method = location && sanitizedLine || "";
391
- let file = url && ["eval", "<anonymous>"].includes(url) ? undefined : url;
392
- if (!file || !lineNumber || !columnNumber) {
393
- return null;
394
- }
395
- if (method.startsWith("async ")) {
396
- method = method.slice(6);
397
- }
398
- if (file.startsWith("file://")) {
399
- file = file.slice(7);
400
- }
401
- // normalize Windows path (\ -> /)
402
- file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
403
- if (method) {
404
- method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
405
- }
406
- return {
407
- method,
408
- file,
409
- line: Number.parseInt(lineNumber),
410
- column: Number.parseInt(columnNumber)
411
- };
412
- }
413
- function parseStacktrace(stack, options = {}) {
414
- const { ignoreStackEntries = stackIgnorePatterns } = options;
415
- const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
416
- return stacks.map((stack) => {
417
- var _options$getSourceMap;
418
- if (options.getUrlId) {
419
- stack.file = options.getUrlId(stack.file);
420
- }
421
- const map = (_options$getSourceMap = options.getSourceMap) === null || _options$getSourceMap === void 0 ? void 0 : _options$getSourceMap.call(options, stack.file);
422
- if (!map || typeof map !== "object" || !map.version) {
423
- return shouldFilter(ignoreStackEntries, stack.file) ? null : stack;
424
- }
425
- const traceMap = new DecodedMap(map, stack.file);
426
- const position = getOriginalPosition(traceMap, stack);
427
- if (!position) {
428
- return stack;
429
- }
430
- const { line, column, source, name } = position;
431
- let file = source || stack.file;
432
- if (file.match(/\/\w:\//)) {
433
- file = file.slice(1);
434
- }
435
- if (shouldFilter(ignoreStackEntries, file)) {
436
- return null;
437
- }
438
- if (line != null && column != null) {
439
- return {
440
- line,
441
- column,
442
- file,
443
- method: name || stack.method
444
- };
445
- }
446
- return stack;
447
- }).filter((s) => s != null);
448
- }
449
- function shouldFilter(ignoreStackEntries, file) {
450
- return ignoreStackEntries.some((p) => file.match(p));
451
- }
452
- function parseFFOrSafariStackTrace(stack) {
453
- return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
454
- }
455
- function parseV8Stacktrace(stack) {
456
- return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish);
457
- }
458
- function parseErrorStacktrace(e, options = {}) {
459
- if (!e || isPrimitive(e)) {
460
- return [];
461
- }
462
- if ("stacks" in e && e.stacks) {
463
- return e.stacks;
464
- }
465
- const stackStr = e.stack || "";
466
- // if "stack" property was overwritten at runtime to be something else,
467
- // ignore the value because we don't know how to process it
468
- let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : [];
469
- if (!stackFrames.length) {
470
- const e_ = e;
471
- if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) {
472
- stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options);
473
- }
474
- if (e_.sourceURL != null && e_.line != null && e_._column != null) {
475
- stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options);
476
- }
477
- }
478
- if (options.frameFilter) {
479
- stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false);
480
- }
481
- e.stacks = stackFrames;
482
- return stackFrames;
483
- }
484
- class DecodedMap {
485
- _encoded;
486
- _decoded;
487
- _decodedMemo;
488
- url;
489
- version;
490
- names = [];
491
- resolvedSources;
492
- constructor(map, from) {
493
- this.map = map;
494
- const { mappings, names, sources } = map;
495
- this.version = map.version;
496
- this.names = names || [];
497
- this._encoded = mappings || "";
498
- this._decodedMemo = memoizedState();
499
- this.url = from;
500
- this.resolvedSources = (sources || []).map((s) => resolve(s || "", from));
501
- }
502
- }
503
- function memoizedState() {
504
- return {
505
- lastKey: -1,
506
- lastNeedle: -1,
507
- lastIndex: -1
508
- };
509
- }
510
- function getOriginalPosition(map, needle) {
511
- const result = originalPositionFor(map, needle);
512
- if (result.column == null) {
513
- return null;
514
- }
515
- return result;
516
- }
517
-
518
- const lineSplitRE = /\r?\n/;
519
- function positionToOffset(source, lineNumber, columnNumber) {
520
- const lines = source.split(lineSplitRE);
521
- const nl = /\r\n/.test(source) ? 2 : 1;
522
- let start = 0;
523
- if (lineNumber > lines.length) {
524
- return source.length;
525
- }
526
- for (let i = 0; i < lineNumber - 1; i++) {
527
- start += lines[i].length + nl;
528
- }
529
- return start + columnNumber;
530
- }
531
- function offsetToLineNumber(source, offset) {
532
- if (offset > source.length) {
533
- throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
534
- }
535
- const lines = source.split(lineSplitRE);
536
- const nl = /\r\n/.test(source) ? 2 : 1;
537
- let counted = 0;
538
- let line = 0;
539
- for (; line < lines.length; line++) {
540
- const lineLength = lines[line].length + nl;
541
- if (counted + lineLength >= offset) {
542
- break;
543
- }
544
- counted += lineLength;
545
- }
546
- return line + 1;
547
- }
548
-
549
6
  async function saveInlineSnapshots(environment, snapshots) {
550
7
  const MagicString = (await import('magic-string')).default;
551
8
  const files = new Set(snapshots.map((i) => i.file));
@@ -645,7 +102,7 @@ function replaceInlineSnap(code, s, currentIndex, newSnap) {
645
102
  const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex);
646
103
  const startMatch = startRegex.exec(codeStartingAtIndex);
647
104
  const firstKeywordMatch = /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/.exec(codeStartingAtIndex);
648
- if (!startMatch || startMatch.index !== (firstKeywordMatch === null || firstKeywordMatch === void 0 ? void 0 : firstKeywordMatch.index)) {
105
+ if (!startMatch || startMatch.index !== firstKeywordMatch?.index) {
649
106
  return replaceObjectSnap(code, s, index, newSnap);
650
107
  }
651
108
  const quote = startMatch[1];
@@ -666,7 +123,6 @@ function replaceInlineSnap(code, s, currentIndex, newSnap) {
666
123
  }
667
124
  const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
668
125
  function stripSnapshotIndentation(inlineSnapshot) {
669
- var _lines$at;
670
126
  // Find indentation if exists.
671
127
  const match = inlineSnapshot.match(INDENTATION_REGEX);
672
128
  if (!match || !match[1]) {
@@ -679,7 +135,7 @@ function stripSnapshotIndentation(inlineSnapshot) {
679
135
  // Must be at least 3 lines.
680
136
  return inlineSnapshot;
681
137
  }
682
- if (lines[0].trim() !== "" || ((_lines$at = lines.at(-1)) === null || _lines$at === void 0 ? void 0 : _lines$at.trim()) !== "") {
138
+ if (lines[0].trim() !== "" || lines.at(-1)?.trim() !== "") {
683
139
  // If not blank first and last lines, abort.
684
140
  return inlineSnapshot;
685
141
  }
@@ -1108,6 +564,14 @@ class SnapshotState {
1108
564
  if (promiseIndex !== -1) {
1109
565
  return stacks[promiseIndex + 3];
1110
566
  }
567
+ // inline snapshot function can be named __INLINE_SNAPSHOT_OFFSET_<n>__
568
+ // to specify a custom stack offset
569
+ for (let i = 0; i < stacks.length; i++) {
570
+ const match = stacks[i].method.match(/__INLINE_SNAPSHOT_OFFSET_(\d+)__/);
571
+ if (match) {
572
+ return stacks[i + Number(match[1])] ?? null;
573
+ }
574
+ }
1111
575
  // inline snapshot function is called __INLINE_SNAPSHOT__
1112
576
  // in integrations/snapshot/chai.ts
1113
577
  const stackIndex = stacks.findIndex((i) => i.method.includes("__INLINE_SNAPSHOT__"));
@@ -1198,7 +662,7 @@ class SnapshotState {
1198
662
  }
1199
663
  }
1200
664
  const expected = isInline ? inlineSnapshot : rawSnapshot ? rawSnapshot.content : this._snapshotData[key];
1201
- const expectedTrimmed = rawSnapshot ? expected : expected === null || expected === void 0 ? void 0 : expected.trim();
665
+ const expectedTrimmed = rawSnapshot ? expected : expected?.trim();
1202
666
  const pass = expectedTrimmed === (rawSnapshot ? receivedSerialized : receivedSerialized.trim());
1203
667
  const hasSnapshot = expected !== undefined;
1204
668
  const snapshotIsPersisted = isInline || this._fileExists || rawSnapshot && rawSnapshot.content != null;
@@ -1214,13 +678,12 @@ class SnapshotState {
1214
678
  // find call site of toMatchInlineSnapshot
1215
679
  let stack;
1216
680
  if (isInline) {
1217
- var _this$environment$pro, _this$environment;
1218
681
  const stacks = parseErrorStacktrace(error || new Error("snapshot"), { ignoreStackEntries: [] });
1219
682
  const _stack = this._inferInlineSnapshotStack(stacks);
1220
683
  if (!_stack) {
1221
684
  throw new Error(`@vitest/snapshot: Couldn't infer stack frame for inline snapshot.\n${JSON.stringify(stacks)}`);
1222
685
  }
1223
- stack = ((_this$environment$pro = (_this$environment = this.environment).processStackTrace) === null || _this$environment$pro === void 0 ? void 0 : _this$environment$pro.call(_this$environment, _stack)) || _stack;
686
+ stack = this.environment.processStackTrace?.(_stack) || _stack;
1224
687
  // removing 1 column, because source map points to the wrong
1225
688
  // location for js files, but `column-1` points to the same in both js/ts
1226
689
  // https://github.com/vitejs/vite/issues/8657
@@ -1393,8 +856,7 @@ class SnapshotClient {
1393
856
  throw new Error("Received value must be an object when the matcher has properties");
1394
857
  }
1395
858
  try {
1396
- var _this$options$isEqual, _this$options;
1397
- const pass = ((_this$options$isEqual = (_this$options = this.options).isEqual) === null || _this$options$isEqual === void 0 ? void 0 : _this$options$isEqual.call(_this$options, received, properties)) ?? false;
859
+ const pass = this.options.isEqual?.(received, properties) ?? false;
1398
860
  // const pass = equals(received, properties, [iterableEquality, subsetEquality])
1399
861
  if (!pass) {
1400
862
  throw createMismatchError("Snapshot properties mismatched", snapshotState.expand, received, properties);
@@ -1417,7 +879,7 @@ class SnapshotClient {
1417
879
  rawSnapshot
1418
880
  });
1419
881
  if (!pass) {
1420
- throw createMismatchError(`Snapshot \`${key || "unknown"}\` mismatched`, snapshotState.expand, rawSnapshot ? actual : actual === null || actual === void 0 ? void 0 : actual.trim(), rawSnapshot ? expected : expected === null || expected === void 0 ? void 0 : expected.trim());
882
+ throw createMismatchError(`Snapshot \`${key || "unknown"}\` mismatched`, snapshotState.expand, rawSnapshot ? actual : actual?.trim(), rawSnapshot ? expected : expected?.trim());
1421
883
  }
1422
884
  }
1423
885
  async assertRaw(options) {
@@ -1431,7 +893,7 @@ class SnapshotClient {
1431
893
  }
1432
894
  const snapshotState = this.getSnapshotState(filepath);
1433
895
  // save the filepath, so it don't lose even if the await make it out-of-context
1434
- options.filepath || (options.filepath = filepath);
896
+ options.filepath ||= filepath;
1435
897
  // resolve and read the raw snapshot file
1436
898
  rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file);
1437
899
  rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) ?? undefined;
package/dist/manager.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { S as SnapshotStateOptions, e as SnapshotSummary, b as SnapshotResult } from './rawSnapshot.d-lFsMJFUd.js';
1
+ import { S as SnapshotStateOptions, e as SnapshotSummary, b as SnapshotResult } from './rawSnapshot.d-U2kJUxDr.js';
2
2
  import '@vitest/pretty-format';
3
- import './environment.d-DHdQ1Csl.js';
3
+ import './environment.d-DOJxxZV9.js';
4
+ import '@vitest/utils';
4
5
 
5
6
  declare class SnapshotManager {
6
7
  options: Omit<SnapshotStateOptions, "snapshotEnvironment">;
@@ -1,5 +1,5 @@
1
1
  import { OptionsReceived, Plugin } from '@vitest/pretty-format';
2
- import { S as SnapshotEnvironment } from './environment.d-DHdQ1Csl.js';
2
+ import { S as SnapshotEnvironment } from './environment.d-DOJxxZV9.js';
3
3
 
4
4
  type SnapshotData = Record<string, string>;
5
5
  type SnapshotUpdateState = "all" | "new" | "none";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vitest/snapshot",
3
3
  "type": "module",
4
- "version": "4.1.0-beta.3",
4
+ "version": "4.1.0-beta.4",
5
5
  "description": "Vitest snapshot manager",
6
6
  "license": "MIT",
7
7
  "funding": "https://opencollective.com/vitest",
@@ -40,12 +40,12 @@
40
40
  "dependencies": {
41
41
  "magic-string": "^0.30.21",
42
42
  "pathe": "^2.0.3",
43
- "@vitest/pretty-format": "4.1.0-beta.3"
43
+ "@vitest/pretty-format": "4.1.0-beta.4",
44
+ "@vitest/utils": "4.1.0-beta.4"
44
45
  },
45
46
  "devDependencies": {
46
47
  "@types/natural-compare": "^1.4.3",
47
- "natural-compare": "^1.4.0",
48
- "@vitest/utils": "4.1.0-beta.3"
48
+ "natural-compare": "^1.4.0"
49
49
  },
50
50
  "scripts": {
51
51
  "build": "premove dist && rollup -c",