import { join, dirname } from 'pathe'; import { plugins, format } from 'pretty-format'; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var naturalCompare$2 = {exports: {}}; /* * @version 1.4.0 * @date 2015-10-26 * @stability 3 - Stable * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite) * @license MIT License */ var naturalCompare = function(a, b) { var i, codeA , codeB = 1 , posA = 0 , posB = 0 , alphabet = String.alphabet; function getCode(str, pos, code) { if (code) { for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i; return +str.slice(pos - 1, i) } code = alphabet && alphabet.indexOf(str.charAt(pos)); return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code : code < 46 ? 65 // - : code < 48 ? code - 1 : code < 58 ? code + 18 // 0-9 : code < 65 ? code - 11 : code < 91 ? code + 11 // A-Z : code < 97 ? code - 37 : code < 123 ? code + 5 // a-z : code - 63 } if ((a+="") != (b+="")) for (;codeB;) { codeA = getCode(a, posA++); codeB = getCode(b, posB++); if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) { codeA = getCode(a, posA, posA); codeB = getCode(b, posB, posA = i); posB = i; } if (codeA != codeB) return (codeA < codeB) ? -1 : 1 } return 0 }; try { naturalCompare$2.exports = naturalCompare; } catch (e) { String.naturalCompare = naturalCompare; } var naturalCompareExports = naturalCompare$2.exports; var naturalCompare$1 = /*@__PURE__*/getDefaultExportFromCjs(naturalCompareExports); function notNullish(v) { return v != null; } function isPrimitive(value) { return value === null || typeof value !== "function" && typeof value !== "object"; } function isObject(item) { return item != null && typeof item === "object" && !Array.isArray(item); } function getCallLastIndex(code) { let charIndex = -1; let inString = null; let startedBracers = 0; let endedBracers = 0; let beforeChar = null; while (charIndex <= code.length) { beforeChar = code[charIndex]; charIndex++; const char = code[charIndex]; const isCharString = char === '"' || char === "'" || char === "`"; if (isCharString && beforeChar !== "\\") { if (inString === char) inString = null; else if (!inString) inString = char; } if (!inString) { if (char === "(") startedBracers++; if (char === ")") endedBracers++; } if (startedBracers && endedBracers && startedBracers === endedBracers) return charIndex; } return null; } let getPromiseValue = () => 'Promise{…}'; try { const { getPromiseDetails, kPending, kRejected } = process.binding('util'); if (Array.isArray(getPromiseDetails(Promise.resolve()))) { getPromiseValue = (value, options) => { const [state, innerValue] = getPromiseDetails(value); if (state === kPending) { return 'Promise{}' } return `Promise${state === kRejected ? '!' : ''}{${options.inspect(innerValue, options)}}` }; } } catch (notNode) { /* ignore */ } /* ! * loupe * Copyright(c) 2013 Jake Luer * MIT Licensed */ let nodeInspect = false; try { // eslint-disable-next-line global-require const nodeUtil = require('util'); nodeInspect = nodeUtil.inspect ? nodeUtil.inspect.custom : false; } catch (noNodeInspect) { nodeInspect = false; } function normalizeWindowsPath(input = "") { if (!input || !input.includes("\\")) { return input; } return input.replace(/\\/g, "/"); } const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; function cwd() { if (typeof process !== "undefined") { return process.cwd().replace(/\\/g, "/"); } return "/"; } const resolve = function(...arguments_) { arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); let resolvedPath = ""; let resolvedAbsolute = false; for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { const path = index >= 0 ? arguments_[index] : cwd(); if (!path || path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = isAbsolute(path); } resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); if (resolvedAbsolute && !isAbsolute(resolvedPath)) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : "."; }; function normalizeString(path, allowAboveRoot) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let char = null; for (let index = 0; index <= path.length; ++index) { if (index < path.length) { char = path[index]; } else if (char === "/") { break; } else { char = "/"; } if (char === "/") { if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf("/"); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); } lastSlash = index; dots = 0; continue; } else if (res.length > 0) { res = ""; lastSegmentLength = 0; lastSlash = index; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? "/.." : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `/${path.slice(lastSlash + 1, index)}`; } else { res = path.slice(lastSlash + 1, index); } lastSegmentLength = index - lastSlash - 1; } lastSlash = index; dots = 0; } else if (char === "." && dots !== -1) { ++dots; } else { dots = -1; } } return res; } const isAbsolute = function(p) { return _IS_ABSOLUTE_RE.test(p); }; const lineSplitRE = /\r?\n/; const stackIgnorePatterns = [ "node:internal", /\/packages\/\w+\/dist\//, /\/@vitest\/\w+\/dist\//, "/vitest/dist/", "/vitest/src/", "/vite-node/dist/", "/vite-node/src/", "/node_modules/chai/", "/node_modules/tinypool/", "/node_modules/tinyspy/" ]; function extractLocation(urlLike) { if (!urlLike.includes(":")) return [urlLike]; const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); if (!parts) return [urlLike]; return [parts[1], parts[2] || void 0, parts[3] || void 0]; } function parseSingleStack(raw) { let line = raw.trim(); if (line.includes("(eval ")) line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, ""); let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, ""); const location = sanitizedLine.match(/ (\(.+\)$)/); sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); let method = location && sanitizedLine || ""; let file = url && ["eval", ""].includes(url) ? void 0 : url; if (!file || !lineNumber || !columnNumber) return null; if (method.startsWith("async ")) method = method.slice(6); if (file.startsWith("file://")) file = file.slice(7); file = resolve(file); return { method, file, line: Number.parseInt(lineNumber), column: Number.parseInt(columnNumber) }; } function parseStacktrace(stack, ignore = stackIgnorePatterns) { const stackFrames = stack.split("\n").map((raw) => { const stack2 = parseSingleStack(raw); if (!stack2 || ignore.length && ignore.some((p) => stack2.file.match(p))) return null; return stack2; }).filter(notNullish); return stackFrames; } function parseErrorStacktrace(e, ignore = stackIgnorePatterns) { if (!e || isPrimitive(e)) return []; if (e.stacks) return e.stacks; const stackStr = e.stack || e.stackStr || ""; const stackFrames = parseStacktrace(stackStr, ignore); e.stacks = stackFrames; return stackFrames; } function positionToOffset(source, lineNumber, columnNumber) { const lines = source.split(lineSplitRE); const nl = /\r\n/.test(source) ? 2 : 1; let start = 0; if (lineNumber > lines.length) return source.length; for (let i2 = 0; i2 < lineNumber - 1; i2++) start += lines[i2].length + nl; return start + columnNumber; } function offsetToLineNumber(source, offset) { if (offset > source.length) { throw new Error( `offset is longer than source length! offset ${offset} > length ${source.length}` ); } const lines = source.split(lineSplitRE); const nl = /\r\n/.test(source) ? 2 : 1; let counted = 0; let line = 0; for (; line < lines.length; line++) { const lineLength = lines[line].length + nl; if (counted + lineLength >= offset) break; counted += lineLength; } return line + 1; } const serialize$1 = (val, config, indentation, depth, refs, printer) => { const name = val.getMockName(); const nameString = name === "vi.fn()" ? "" : ` ${name}`; let callsString = ""; if (val.mock.calls.length !== 0) { const indentationNext = indentation + config.indent; 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}}`; } return `[MockFunction${nameString}]${callsString}`; }; const test = (val) => val && !!val._isMockFunction; const plugin = { serialize: serialize$1, test }; const { DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent, AsymmetricMatcher } = plugins; let PLUGINS = [ ReactTestComponent, ReactElement, DOMElement, DOMCollection, Immutable, AsymmetricMatcher, plugin ]; function addSerializer(plugin) { PLUGINS = [plugin].concat(PLUGINS); } function getSerializers() { return PLUGINS; } function testNameToKey(testName, count) { return `${testName} ${count}`; } function keyToTestName(key) { if (!/ \d+$/.test(key)) throw new Error("Snapshot keys must end with a number."); return key.replace(/ \d+$/, ""); } function getSnapshotData(content, options) { const update = options.updateSnapshot; const data = /* @__PURE__ */ Object.create(null); let snapshotContents = ""; let dirty = false; if (content != null) { try { snapshotContents = content; const populate = new Function("exports", snapshotContents); populate(data); } catch { } } const isInvalid = snapshotContents; if ((update === "all" || update === "new") && isInvalid) dirty = true; return { data, dirty }; } function addExtraLineBreaks(string) { return string.includes("\n") ? ` ${string} ` : string; } function removeExtraLineBreaks(string) { return string.length > 2 && string.startsWith("\n") && string.endsWith("\n") ? string.slice(1, -1) : string; } const escapeRegex = true; const printFunctionName = false; function serialize(val, indent = 2, formatOverrides = {}) { return normalizeNewlines( format(val, { escapeRegex, indent, plugins: getSerializers(), printFunctionName, ...formatOverrides }) ); } function escapeBacktickString(str) { return str.replace(/`|\\|\${/g, "\\$&"); } function printBacktickString(str) { return `\`${escapeBacktickString(str)}\``; } async function ensureDirectoryExists(environment, filePath) { try { await environment.prepareDirectory(join(dirname(filePath))); } catch { } } function normalizeNewlines(string) { return string.replace(/\r\n|\r/g, "\n"); } async function saveSnapshotFile(environment, snapshotData, snapshotPath) { const snapshots = Object.keys(snapshotData).sort(naturalCompare$1).map( (key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};` ); const content = `${environment.getHeader()} ${snapshots.join("\n\n")} `; const oldContent = await environment.readSnapshotFile(snapshotPath); const skipWriting = oldContent != null && oldContent === content; if (skipWriting) return; await ensureDirectoryExists(environment, snapshotPath); await environment.saveSnapshotFile( snapshotPath, content ); } function prepareExpected(expected) { function findStartIndent() { var _a, _b; const matchObject = /^( +)}\s+$/m.exec(expected || ""); const objectIndent = (_a = matchObject == null ? void 0 : matchObject[1]) == null ? void 0 : _a.length; if (objectIndent) return objectIndent; const matchText = /^\n( +)"/.exec(expected || ""); return ((_b = matchText == null ? void 0 : matchText[1]) == null ? void 0 : _b.length) || 0; } const startIndent = findStartIndent(); let expectedTrimmed = expected == null ? void 0 : expected.trim(); if (startIndent) { expectedTrimmed = expectedTrimmed == null ? void 0 : expectedTrimmed.replace(new RegExp(`^${" ".repeat(startIndent)}`, "gm"), "").replace(/ +}$/, "}"); } return expectedTrimmed; } function deepMergeArray(target = [], source = []) { const mergedOutput = Array.from(target); source.forEach((sourceElement, index) => { const targetElement = mergedOutput[index]; if (Array.isArray(target[index])) { mergedOutput[index] = deepMergeArray(target[index], sourceElement); } else if (isObject(targetElement)) { mergedOutput[index] = deepMergeSnapshot(target[index], sourceElement); } else { mergedOutput[index] = sourceElement; } }); return mergedOutput; } function deepMergeSnapshot(target, source) { if (isObject(target) && isObject(source)) { const mergedOutput = { ...target }; Object.keys(source).forEach((key) => { if (isObject(source[key]) && !source[key].$$typeof) { if (!(key in target)) Object.assign(mergedOutput, { [key]: source[key] }); else mergedOutput[key] = deepMergeSnapshot(target[key], source[key]); } else if (Array.isArray(source[key])) { mergedOutput[key] = deepMergeArray(target[key], source[key]); } else { Object.assign(mergedOutput, { [key]: source[key] }); } }); return mergedOutput; } else if (Array.isArray(target) && Array.isArray(source)) { return deepMergeArray(target, source); } return target; } async function saveInlineSnapshots(environment, snapshots) { const MagicString = (await import('magic-string')).default; const files = new Set(snapshots.map((i) => i.file)); await Promise.all(Array.from(files).map(async (file) => { const snaps = snapshots.filter((i) => i.file === file); const code = await environment.readSnapshotFile(file); const s = new MagicString(code); for (const snap of snaps) { const index = positionToOffset(code, snap.line, snap.column); replaceInlineSnap(code, s, index, snap.snapshot); } const transformed = s.toString(); if (transformed !== code) await environment.saveSnapshotFile(file, transformed); })); } const startObjectRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\S\s]*\*\/\s*|\/\/.*\s+)*\s*({)/m; function replaceObjectSnap(code, s, index, newSnap) { code = code.slice(index); const startMatch = startObjectRegex.exec(code); if (!startMatch) return false; code = code.slice(startMatch.index); const charIndex = getCallLastIndex(code); if (charIndex === null) return false; s.appendLeft(index + startMatch.index + charIndex, `, ${prepareSnapString(newSnap, code, index)}`); return true; } function prepareSnapString(snap, source, index) { const lineNumber = offsetToLineNumber(source, index); const line = source.split(lineSplitRE)[lineNumber - 1]; const indent = line.match(/^\s*/)[0] || ""; const indentNext = indent.includes(" ") ? `${indent} ` : `${indent} `; const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g); const isOneline = lines.length <= 1; const quote = isOneline ? "'" : "`"; if (isOneline) return `'${lines.join("\n").replace(/'/g, "\\'")}'`; else return `${quote} ${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\${/g, "\\${")} ${indent}${quote}`; } const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\S\s]*\*\/\s*|\/\/.*\s+)*\s*[\w_$]*(['"`\)])/m; function replaceInlineSnap(code, s, index, newSnap) { const startMatch = startRegex.exec(code.slice(index)); if (!startMatch) return replaceObjectSnap(code, s, index, newSnap); const quote = startMatch[1]; const startIndex = index + startMatch.index + startMatch[0].length; const snapString = prepareSnapString(newSnap, code, index); if (quote === ")") { s.appendRight(startIndex - 1, snapString); return true; } const quoteEndRE = new RegExp(`(?:^|[^\\\\])${quote}`); const endMatch = quoteEndRE.exec(code.slice(startIndex)); if (!endMatch) return false; const endIndex = startIndex + endMatch.index + endMatch[0].length; s.overwrite(startIndex - 1, endIndex, snapString); return true; } const INDENTATION_REGEX = /^([^\S\n]*)\S/m; function stripSnapshotIndentation(inlineSnapshot) { const match = inlineSnapshot.match(INDENTATION_REGEX); if (!match || !match[1]) { return inlineSnapshot; } const indentation = match[1]; const lines = inlineSnapshot.split(/\n/g); if (lines.length <= 2) { return inlineSnapshot; } if (lines[0].trim() !== "" || lines[lines.length - 1].trim() !== "") { return inlineSnapshot; } for (let i = 1; i < lines.length - 1; i++) { if (lines[i] !== "") { if (lines[i].indexOf(indentation) !== 0) { return inlineSnapshot; } lines[i] = lines[i].substring(indentation.length); } } lines[lines.length - 1] = ""; inlineSnapshot = lines.join("\n"); return inlineSnapshot; } async function saveRawSnapshots(environment, snapshots) { await Promise.all(snapshots.map(async (snap) => { if (!snap.readonly) await environment.saveSnapshotFile(snap.file, snap.snapshot); })); } class SnapshotState { constructor(testFilePath, snapshotPath, snapshotContent, options) { this.testFilePath = testFilePath; this.snapshotPath = snapshotPath; const { data, dirty } = getSnapshotData( snapshotContent, options ); this._fileExists = snapshotContent != null; this._initialData = data; this._snapshotData = data; this._dirty = dirty; this._inlineSnapshots = []; this._rawSnapshots = []; this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); this._counters = /* @__PURE__ */ new Map(); this.expand = options.expand || false; this.added = 0; this.matched = 0; this.unmatched = 0; this._updateSnapshot = options.updateSnapshot; this.updated = 0; this._snapshotFormat = { printBasicPrototype: false, ...options.snapshotFormat }; this._environment = options.snapshotEnvironment; } _counters; _dirty; _updateSnapshot; _snapshotData; _initialData; _inlineSnapshots; _rawSnapshots; _uncheckedKeys; _snapshotFormat; _environment; _fileExists; added; expand; matched; unmatched; updated; static async create(testFilePath, options) { const snapshotPath = await options.snapshotEnvironment.resolvePath(testFilePath); const content = await options.snapshotEnvironment.readSnapshotFile(snapshotPath); return new SnapshotState(testFilePath, snapshotPath, content, options); } get environment() { return this._environment; } markSnapshotsAsCheckedForTest(testName) { this._uncheckedKeys.forEach((uncheckedKey) => { if (keyToTestName(uncheckedKey) === testName) this._uncheckedKeys.delete(uncheckedKey); }); } _inferInlineSnapshotStack(stacks) { const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/)); if (promiseIndex !== -1) return stacks[promiseIndex + 3]; const stackIndex = stacks.findIndex((i) => i.method.includes("__INLINE_SNAPSHOT__")); return stackIndex !== -1 ? stacks[stackIndex + 2] : null; } _addSnapshot(key, receivedSerialized, options) { this._dirty = true; if (options.isInline) { const stacks = parseErrorStacktrace(options.error || new Error("snapshot"), []); const stack = this._inferInlineSnapshotStack(stacks); if (!stack) { throw new Error( `@vitest/snapshot: Couldn't infer stack frame for inline snapshot. ${JSON.stringify(stacks)}` ); } stack.column--; this._inlineSnapshots.push({ snapshot: receivedSerialized, ...stack }); } else if (options.rawSnapshot) { this._rawSnapshots.push({ ...options.rawSnapshot, snapshot: receivedSerialized }); } else { this._snapshotData[key] = receivedSerialized; } } clear() { this._snapshotData = this._initialData; this._counters = /* @__PURE__ */ new Map(); this.added = 0; this.matched = 0; this.unmatched = 0; this.updated = 0; this._dirty = false; } async save() { const hasExternalSnapshots = Object.keys(this._snapshotData).length; const hasInlineSnapshots = this._inlineSnapshots.length; const hasRawSnapshots = this._rawSnapshots.length; const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots && !hasRawSnapshots; const status = { deleted: false, saved: false }; if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { if (hasExternalSnapshots) { await saveSnapshotFile(this._environment, this._snapshotData, this.snapshotPath); this._fileExists = true; } if (hasInlineSnapshots) await saveInlineSnapshots(this._environment, this._inlineSnapshots); if (hasRawSnapshots) await saveRawSnapshots(this._environment, this._rawSnapshots); status.saved = true; } else if (!hasExternalSnapshots && this._fileExists) { if (this._updateSnapshot === "all") { await this._environment.removeSnapshotFile(this.snapshotPath); this._fileExists = false; } status.deleted = true; } return status; } getUncheckedCount() { return this._uncheckedKeys.size || 0; } getUncheckedKeys() { return Array.from(this._uncheckedKeys); } removeUncheckedKeys() { if (this._updateSnapshot === "all" && this._uncheckedKeys.size) { this._dirty = true; this._uncheckedKeys.forEach((key) => delete this._snapshotData[key]); this._uncheckedKeys.clear(); } } match({ testName, received, key, inlineSnapshot, isInline, error, rawSnapshot }) { this._counters.set(testName, (this._counters.get(testName) || 0) + 1); const count = Number(this._counters.get(testName)); if (!key) key = testNameToKey(testName, count); if (!(isInline && this._snapshotData[key] !== void 0)) this._uncheckedKeys.delete(key); let receivedSerialized = rawSnapshot && typeof received === "string" ? received : serialize(received, void 0, this._snapshotFormat); if (!rawSnapshot) receivedSerialized = addExtraLineBreaks(receivedSerialized); if (rawSnapshot) { if (rawSnapshot.content && rawSnapshot.content.match(/\r\n/) && !receivedSerialized.match(/\r\n/)) rawSnapshot.content = normalizeNewlines(rawSnapshot.content); } const expected = isInline ? inlineSnapshot : rawSnapshot ? rawSnapshot.content : this._snapshotData[key]; const expectedTrimmed = prepareExpected(expected); const pass = expectedTrimmed === prepareExpected(receivedSerialized); const hasSnapshot = expected !== void 0; const snapshotIsPersisted = isInline || this._fileExists || rawSnapshot && rawSnapshot.content != null; if (pass && !isInline && !rawSnapshot) { this._snapshotData[key] = receivedSerialized; } if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) { if (this._updateSnapshot === "all") { if (!pass) { if (hasSnapshot) this.updated++; else this.added++; this._addSnapshot(key, receivedSerialized, { error, isInline, rawSnapshot }); } else { this.matched++; } } else { this._addSnapshot(key, receivedSerialized, { error, isInline, rawSnapshot }); this.added++; } return { actual: "", count, expected: "", key, pass: true }; } else { if (!pass) { this.unmatched++; return { actual: removeExtraLineBreaks(receivedSerialized), count, expected: expectedTrimmed !== void 0 ? removeExtraLineBreaks(expectedTrimmed) : void 0, key, pass: false }; } else { this.matched++; return { actual: "", count, expected: "", key, pass: true }; } } } async pack() { const snapshot = { filepath: this.testFilePath, added: 0, fileDeleted: false, matched: 0, unchecked: 0, uncheckedKeys: [], unmatched: 0, updated: 0 }; const uncheckedCount = this.getUncheckedCount(); const uncheckedKeys = this.getUncheckedKeys(); if (uncheckedCount) this.removeUncheckedKeys(); const status = await this.save(); snapshot.fileDeleted = status.deleted; snapshot.added = this.added; snapshot.matched = this.matched; snapshot.unmatched = this.unmatched; snapshot.updated = this.updated; snapshot.unchecked = !status.deleted ? uncheckedCount : 0; snapshot.uncheckedKeys = Array.from(uncheckedKeys); return snapshot; } } function createMismatchError(message, actual, expected) { const error = new Error(message); Object.defineProperty(error, "actual", { value: actual, enumerable: true, configurable: true, writable: true }); Object.defineProperty(error, "expected", { value: expected, enumerable: true, configurable: true, writable: true }); return error; } class SnapshotClient { constructor(Service = SnapshotState) { this.Service = Service; } filepath; name; snapshotState; snapshotStateMap = /* @__PURE__ */ new Map(); async setTest(filepath, name, options) { var _a; this.filepath = filepath; this.name = name; if (((_a = this.snapshotState) == null ? void 0 : _a.testFilePath) !== filepath) { this.resetCurrent(); if (!this.getSnapshotState(filepath)) { this.snapshotStateMap.set( filepath, await this.Service.create( filepath, options ) ); } this.snapshotState = this.getSnapshotState(filepath); } } getSnapshotState(filepath) { return this.snapshotStateMap.get(filepath); } clearTest() { this.filepath = void 0; this.name = void 0; } skipTestSnapshots(name) { var _a; (_a = this.snapshotState) == null ? void 0 : _a.markSnapshotsAsCheckedForTest(name); } /** * Should be overridden by the consumer. * * Vitest checks equality with @vitest/expect. */ equalityCheck(received, expected) { return received === expected; } assert(options) { const { filepath = this.filepath, name = this.name, message, isInline = false, properties, inlineSnapshot, error, errorMessage, rawSnapshot } = options; let { received } = options; if (!filepath) throw new Error("Snapshot cannot be used outside of test"); if (typeof properties === "object") { if (typeof received !== "object" || !received) throw new Error("Received value must be an object when the matcher has properties"); try { const pass2 = this.equalityCheck(received, properties); if (!pass2) throw createMismatchError("Snapshot properties mismatched", received, properties); else received = deepMergeSnapshot(received, properties); } catch (err) { err.message = errorMessage || "Snapshot mismatched"; throw err; } } const testName = [ name, ...message ? [message] : [] ].join(" > "); const snapshotState = this.getSnapshotState(filepath); const { actual, expected, key, pass } = snapshotState.match({ testName, received, isInline, error, inlineSnapshot, rawSnapshot }); if (!pass) throw createMismatchError(`Snapshot \`${key || "unknown"}\` mismatched`, actual == null ? void 0 : actual.trim(), expected == null ? void 0 : expected.trim()); } async assertRaw(options) { if (!options.rawSnapshot) throw new Error("Raw snapshot is required"); const { filepath = this.filepath, rawSnapshot } = options; if (rawSnapshot.content == null) { if (!filepath) throw new Error("Snapshot cannot be used outside of test"); const snapshotState = this.getSnapshotState(filepath); options.filepath || (options.filepath = filepath); rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file); rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) || void 0; } return this.assert(options); } async resetCurrent() { if (!this.snapshotState) return null; const result = await this.snapshotState.pack(); this.snapshotState = void 0; return result; } clear() { this.snapshotStateMap.clear(); } } export { SnapshotClient, SnapshotState, addSerializer, getSerializers, stripSnapshotIndentation };