diff options
| author | Adam Mathes <adam@adammathes.com> | 2026-02-14 14:46:37 -0800 |
|---|---|---|
| committer | Adam Mathes <adam@adammathes.com> | 2026-02-14 14:46:37 -0800 |
| commit | afa87af01c79a9baa539f2992d32154d2a4739bd (patch) | |
| tree | 92c7416db734270a2fee1d72ee9cc119379ff8e1 /vanilla/node_modules/@vitest | |
| parent | 3b927e84d200402281f68181cd4253bc77e5528d (diff) | |
| download | neko-afa87af01c79a9baa539f2992d32154d2a4739bd.tar.gz neko-afa87af01c79a9baa539f2992d32154d2a4739bd.tar.bz2 neko-afa87af01c79a9baa539f2992d32154d2a4739bd.zip | |
task: delete vanilla js prototype\n\n- Removed vanilla/ directory and web/dist/vanilla directory\n- Updated Makefile, Dockerfile, and CI workflow to remove vanilla references\n- Cleaned up web/web.go to remove vanilla embed and routes\n- Verified build and tests pass\n\nCloses NK-2tcnmq
Diffstat (limited to 'vanilla/node_modules/@vitest')
110 files changed, 0 insertions, 20425 deletions
diff --git a/vanilla/node_modules/@vitest/coverage-v8/LICENSE b/vanilla/node_modules/@vitest/coverage-v8/LICENSE deleted file mode 100644 index 0e5771d..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/browser.d.ts b/vanilla/node_modules/@vitest/coverage-v8/dist/browser.d.ts deleted file mode 100644 index e6c7069..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/dist/browser.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { CoverageProviderModule } from 'vitest/node'; - -declare const mod: CoverageProviderModule; - -export { mod as default }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/browser.js b/vanilla/node_modules/@vitest/coverage-v8/dist/browser.js deleted file mode 100644 index a57a3e1..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/dist/browser.js +++ /dev/null @@ -1,58 +0,0 @@ -import { cdp } from 'vitest/browser'; -import { l as loadProvider } from './load-provider-CdgAx3rL.js'; - -const session = cdp(); -let enabled = false; -const mod = { - async startCoverage() { - if (enabled) { - return; - } - enabled = true; - await session.send("Profiler.enable"); - await session.send("Profiler.startPreciseCoverage", { - callCount: true, - detailed: true - }); - }, - async takeCoverage() { - const coverage = await session.send("Profiler.takePreciseCoverage"); - const result = []; - // Reduce amount of data sent over rpc by doing some early result filtering - for (const entry of coverage.result) { - if (filterResult(entry)) { - result.push({ - ...entry, - url: decodeURIComponent(entry.url.replace(window.location.origin, "")) - }); - } - } - return { result }; - }, - stopCoverage() { - // Browser mode should not stop coverage as same V8 instance is shared between tests - }, - async getProvider() { - return loadProvider(); - } -}; -function filterResult(coverage) { - if (!coverage.url.startsWith(window.location.origin)) { - return false; - } - if (coverage.url.includes("/node_modules/")) { - return false; - } - if (coverage.url.includes("__vitest_browser__")) { - return false; - } - if (coverage.url.includes("__vitest__/assets")) { - return false; - } - if (coverage.url === window.location.href) { - return false; - } - return true; -} - -export { mod as default }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/index.d.ts b/vanilla/node_modules/@vitest/coverage-v8/dist/index.d.ts deleted file mode 100644 index e6c7069..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/dist/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { CoverageProviderModule } from 'vitest/node'; - -declare const mod: CoverageProviderModule; - -export { mod as default }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/index.js b/vanilla/node_modules/@vitest/coverage-v8/dist/index.js deleted file mode 100644 index 85d9c9d..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/dist/index.js +++ /dev/null @@ -1,61 +0,0 @@ -import inspector from 'node:inspector/promises'; -import { fileURLToPath } from 'node:url'; -import { provider } from 'std-env'; -import { l as loadProvider } from './load-provider-CdgAx3rL.js'; -import { n as normalize } from './pathe.M-eThtNZ-BTaAGrLg.js'; - -const session = new inspector.Session(); -let enabled = false; -const mod = { - async startCoverage({ isolate }) { - if (isolate === false && enabled) { - return; - } - enabled = true; - session.connect(); - await session.post("Profiler.enable"); - await session.post("Profiler.startPreciseCoverage", { - callCount: true, - detailed: true - }); - }, - async takeCoverage(options) { - if (provider === "stackblitz") { - return { result: [] }; - } - const coverage = await session.post("Profiler.takePreciseCoverage"); - const result = []; - // Reduce amount of data sent over rpc by doing some early result filtering - for (const entry of coverage.result) { - if (filterResult(entry)) { - result.push({ - ...entry, - startOffset: options?.moduleExecutionInfo?.get(normalize(fileURLToPath(entry.url)))?.startOffset || 0 - }); - } - } - return { result }; - }, - async stopCoverage({ isolate }) { - if (isolate === false) { - return; - } - await session.post("Profiler.stopPreciseCoverage"); - await session.post("Profiler.disable"); - session.disconnect(); - }, - async getProvider() { - return loadProvider(); - } -}; -function filterResult(coverage) { - if (!coverage.url.startsWith("file://")) { - return false; - } - if (coverage.url.includes("/node_modules/")) { - return false; - } - return true; -} - -export { mod as default }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/load-provider-CdgAx3rL.js b/vanilla/node_modules/@vitest/coverage-v8/dist/load-provider-CdgAx3rL.js deleted file mode 100644 index 005a532..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/dist/load-provider-CdgAx3rL.js +++ /dev/null @@ -1,11 +0,0 @@ -// to not bundle the provider -const name = "./provider.js"; -async function loadProvider() { - const { V8CoverageProvider } = await import( - /* @vite-ignore */ - name -); - return new V8CoverageProvider(); -} - -export { loadProvider as l }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/pathe.M-eThtNZ-BTaAGrLg.js b/vanilla/node_modules/@vitest/coverage-v8/dist/pathe.M-eThtNZ-BTaAGrLg.js deleted file mode 100644 index 3f82a78..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/dist/pathe.M-eThtNZ-BTaAGrLg.js +++ /dev/null @@ -1,104 +0,0 @@ -const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; -function normalizeWindowsPath(input = "") { - if (!input) { - return input; - } - return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); -} - -const _UNC_REGEX = /^[/\\]{2}/; -const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; -const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; -const normalize = function(path) { - if (path.length === 0) { - return "."; - } - path = normalizeWindowsPath(path); - const isUNCPath = path.match(_UNC_REGEX); - const isPathAbsolute = isAbsolute(path); - const trailingSeparator = path[path.length - 1] === "/"; - path = normalizeString(path, !isPathAbsolute); - if (path.length === 0) { - if (isPathAbsolute) { - return "/"; - } - return trailingSeparator ? "./" : "."; - } - if (trailingSeparator) { - path += "/"; - } - if (_DRIVE_LETTER_RE.test(path)) { - path += "/"; - } - if (isUNCPath) { - if (!isPathAbsolute) { - return `//./${path}`; - } - return `//${path}`; - } - return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; -}; -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); -}; - -export { normalize as n }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/provider.d.ts b/vanilla/node_modules/@vitest/coverage-v8/dist/provider.d.ts deleted file mode 100644 index 4b9f969..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/dist/provider.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { CoverageMap } from 'istanbul-lib-coverage'; -import { ProxifiedModule } from 'magicast'; -import { Profiler } from 'node:inspector'; -import { ResolvedCoverageOptions, CoverageProvider, Vitest, ReportContext } from 'vitest/node'; -import { BaseCoverageProvider } from 'vitest/coverage'; - -interface ScriptCoverageWithOffset extends Profiler.ScriptCoverage { - startOffset: number; -} -declare class V8CoverageProvider extends BaseCoverageProvider<ResolvedCoverageOptions<"v8">> implements CoverageProvider { - name: "v8"; - version: string; - initialize(ctx: Vitest): void; - createCoverageMap(): CoverageMap; - generateCoverage({ allTestsRun }: ReportContext): Promise<CoverageMap>; - generateReports(coverageMap: CoverageMap, allTestsRun?: boolean): Promise<void>; - parseConfigModule(configFilePath: string): Promise<ProxifiedModule<any>>; - private getCoverageMapForUncoveredFiles; - private remapCoverage; - private getSources; - private convertCoverage; -} - -export { V8CoverageProvider }; -export type { ScriptCoverageWithOffset }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/dist/provider.js b/vanilla/node_modules/@vitest/coverage-v8/dist/provider.js deleted file mode 100644 index 4230309..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/dist/provider.js +++ /dev/null @@ -1,296 +0,0 @@ -import { existsSync, promises } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { mergeProcessCovs } from '@bcoe/v8-coverage'; -import astV8ToIstanbul from 'ast-v8-to-istanbul'; -import libCoverage from 'istanbul-lib-coverage'; -import libReport from 'istanbul-lib-report'; -import reports from 'istanbul-reports'; -import { parseModule } from 'magicast'; -import { createDebug } from 'obug'; -import { provider } from 'std-env'; -import c from 'tinyrainbow'; -import { BaseCoverageProvider } from 'vitest/coverage'; -import { parseAstAsync } from 'vitest/node'; -import { n as normalize } from './pathe.M-eThtNZ-BTaAGrLg.js'; - -var version = "4.0.18"; - -const FILE_PROTOCOL = "file://"; -const debug = createDebug("vitest:coverage"); -class V8CoverageProvider extends BaseCoverageProvider { - name = "v8"; - version = version; - initialize(ctx) { - this._initialize(ctx); - } - createCoverageMap() { - return libCoverage.createCoverageMap({}); - } - async generateCoverage({ allTestsRun }) { - const start = debug.enabled ? performance.now() : 0; - const coverageMap = this.createCoverageMap(); - let merged = { result: [] }; - await this.readCoverageFiles({ - onFileRead(coverage) { - merged = mergeProcessCovs([merged, coverage]); - // mergeProcessCovs sometimes loses startOffset, e.g. in vue - merged.result.forEach((result) => { - if (!result.startOffset) { - const original = coverage.result.find((r) => r.url === result.url); - result.startOffset = original?.startOffset || 0; - } - }); - }, - onFinished: async (project, environment) => { - // Source maps can change based on projectName and transform mode. - // Coverage transform re-uses source maps so we need to separate transforms from each other. - const converted = await this.convertCoverage(merged, project, environment); - coverageMap.merge(converted); - merged = { result: [] }; - }, - onDebug: debug - }); - // Include untested files when all tests were run (not a single file re-run) - // or if previous results are preserved by "cleanOnRerun: false" - if (this.options.include != null && (allTestsRun || !this.options.cleanOnRerun)) { - const coveredFiles = coverageMap.files(); - const untestedCoverage = await this.getCoverageMapForUncoveredFiles(coveredFiles); - coverageMap.merge(untestedCoverage); - } - coverageMap.filter((filename) => { - const exists = existsSync(filename); - if (this.options.excludeAfterRemap) { - return exists && this.isIncluded(filename); - } - return exists; - }); - if (debug.enabled) { - debug(`Generate coverage total time ${(performance.now() - start).toFixed()} ms`); - } - return coverageMap; - } - async generateReports(coverageMap, allTestsRun) { - if (provider === "stackblitz") { - this.ctx.logger.log(c.blue(" % ") + c.yellow("@vitest/coverage-v8 does not work on Stackblitz. Report will be empty.")); - } - const context = libReport.createContext({ - dir: this.options.reportsDirectory, - coverageMap, - watermarks: this.options.watermarks - }); - if (this.hasTerminalReporter(this.options.reporter)) { - this.ctx.logger.log(c.blue(" % ") + c.dim("Coverage report from ") + c.yellow(this.name)); - } - for (const reporter of this.options.reporter) { - // Type assertion required for custom reporters - reports.create(reporter[0], { - skipFull: this.options.skipFull, - projectRoot: this.ctx.config.root, - ...reporter[1] - }).execute(context); - } - if (this.options.thresholds) { - await this.reportThresholds(coverageMap, allTestsRun); - } - } - async parseConfigModule(configFilePath) { - return parseModule(await promises.readFile(configFilePath, "utf8")); - } - async getCoverageMapForUncoveredFiles(testedFiles) { - const transform = this.createUncoveredFileTransformer(this.ctx); - const uncoveredFiles = await this.getUntestedFiles(testedFiles); - let index = 0; - const coverageMap = this.createCoverageMap(); - for (const chunk of this.toSlices(uncoveredFiles, this.options.processingConcurrency)) { - if (debug.enabled) { - index += chunk.length; - debug("Uncovered files %d/%d", index, uncoveredFiles.length); - } - await Promise.all(chunk.map(async (filename) => { - let timeout; - let start; - if (debug.enabled) { - start = performance.now(); - timeout = setTimeout(() => debug(c.bgRed(`File "${filename}" is taking longer than 3s`)), 3e3); - } - // Do not use pathToFileURL to avoid encoding filename parts - const url = `file://${filename[0] === "/" ? "" : "/"}${filename}`; - const sources = await this.getSources(url, transform); - coverageMap.merge(await this.remapCoverage(url, 0, sources, [])); - if (debug.enabled) { - clearTimeout(timeout); - const diff = performance.now() - start; - const color = diff > 500 ? c.bgRed : c.bgGreen; - debug(`${color(` ${diff.toFixed()} ms `)} ${filename}`); - } - })); - } - return coverageMap; - } - async remapCoverage(filename, wrapperLength, result, functions) { - let ast; - try { - ast = await parseAstAsync(result.code); - } catch (error) { - this.ctx.logger.error(`Failed to parse ${filename}. Excluding it from coverage.\n`, error); - return {}; - } - return await astV8ToIstanbul({ - code: result.code, - sourceMap: result.map, - ast, - coverage: { - functions, - url: filename - }, - ignoreClassMethods: this.options.ignoreClassMethods, - wrapperLength, - ignoreNode: (node, type) => { - // SSR transformed imports - if (type === "statement" && node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.id.name.startsWith("__vite_ssr_import_")) { - return true; - } - // SSR transformed exports vite@>6.3.5 - if (type === "statement" && node.type === "ExpressionStatement" && node.expression.type === "AssignmentExpression" && node.expression.left.type === "MemberExpression" && node.expression.left.object.type === "Identifier" && node.expression.left.object.name === "__vite_ssr_exports__") { - return true; - } - // SSR transformed exports vite@^6.3.5 - if (type === "statement" && node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.id.name === "__vite_ssr_export_default__") { - return true; - } - // CJS imports as ternaries - e.g. - // const React = __vite__cjsImport0_react.__esModule ? __vite__cjsImport0_react.default : __vite__cjsImport0_react; - if (type === "branch" && node.type === "ConditionalExpression" && node.test.type === "MemberExpression" && node.test.object.type === "Identifier" && node.test.object.name.startsWith("__vite__cjsImport") && node.test.property.type === "Identifier" && node.test.property.name === "__esModule") { - return true; - } - // in-source test with "if (import.meta.vitest)" - if ((type === "branch" || type === "statement") && node.type === "IfStatement" && node.test.type === "MemberExpression" && node.test.property.type === "Identifier" && node.test.property.name === "vitest") { - // SSR - if (node.test.object.type === "Identifier" && node.test.object.name === "__vite_ssr_import_meta__") { - return "ignore-this-and-nested-nodes"; - } - // Web - if (node.test.object.type === "MetaProperty" && node.test.object.meta.name === "import" && node.test.object.property.name === "meta") { - return "ignore-this-and-nested-nodes"; - } - } - // Browser mode's "import.meta.env =" - if (type === "statement" && node.type === "ExpressionStatement" && node.expression.type === "AssignmentExpression" && node.expression.left.type === "MemberExpression" && node.expression.left.object.type === "MetaProperty" && node.expression.left.object.meta.name === "import" && node.expression.left.object.property.name === "meta" && node.expression.left.property.type === "Identifier" && node.expression.left.property.name === "env") { - return true; - } - // SSR mode's "import.meta.env =" - if (type === "statement" && node.type === "ExpressionStatement" && node.expression.type === "AssignmentExpression" && node.expression.left.type === "MemberExpression" && node.expression.left.object.type === "Identifier" && node.expression.left.object.name === "__vite_ssr_import_meta__") { - return true; - } - // SWC's decorators - if (type === "statement" && node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "_ts_decorate") { - return "ignore-this-and-nested-nodes"; - } - } - }); - } - async getSources(url, onTransform, functions = []) { - const transformResult = await onTransform(removeStartsWith(url, FILE_PROTOCOL)).catch(() => undefined); - const map = transformResult?.map; - const code = transformResult?.code; - if (code == null) { - const filePath = normalize(fileURLToPath(url)); - const original = await promises.readFile(filePath, "utf-8").catch(() => { - // If file does not exist construct a dummy source for it. - // These can be files that were generated dynamically during the test run and were removed after it. - const length = findLongestFunctionLength(functions); - return "/".repeat(length); - }); - return { code: original }; - } - // Vue needs special handling for "map.sources" - if (map) { - map.sources ||= []; - map.sources = map.sources.filter((source) => source != null).map((source) => new URL(source, url).href); - if (map.sources.length === 0) { - map.sources.push(url); - } - } - return { - code, - map - }; - } - async convertCoverage(coverage, project = this.ctx.getRootProject(), environment) { - if (environment === "__browser__" && !project.browser) { - throw new Error(`Cannot access browser module graph because it was torn down.`); - } - async function onTransform(filepath) { - if (environment === "__browser__" && project.browser) { - const result = await project.browser.vite.transformRequest(removeStartsWith(filepath, project.config.root)); - if (result) { - return { - ...result, - code: `${result.code}// <inline-source-map>` - }; - } - } - return project.vite.environments[environment].transformRequest(filepath); - } - const scriptCoverages = []; - for (const result of coverage.result) { - if (environment === "__browser__") { - if (result.url.startsWith("/@fs")) { - result.url = `${FILE_PROTOCOL}${removeStartsWith(result.url, "/@fs")}`; - } else if (result.url.startsWith(project.config.root)) { - result.url = `${FILE_PROTOCOL}${result.url}`; - } else { - result.url = `${FILE_PROTOCOL}${project.config.root}${result.url}`; - } - } - if (this.isIncluded(fileURLToPath(result.url))) { - scriptCoverages.push({ - ...result, - url: decodeURIComponent(result.url) - }); - } - } - const coverageMap = this.createCoverageMap(); - let index = 0; - for (const chunk of this.toSlices(scriptCoverages, this.options.processingConcurrency)) { - if (debug.enabled) { - index += chunk.length; - debug("Converting %d/%d", index, scriptCoverages.length); - } - await Promise.all(chunk.map(async ({ url, functions, startOffset }) => { - let timeout; - let start; - if (debug.enabled) { - start = performance.now(); - timeout = setTimeout(() => debug(c.bgRed(`File "${fileURLToPath(url)}" is taking longer than 3s`)), 3e3); - } - const sources = await this.getSources(url, onTransform, functions); - coverageMap.merge(await this.remapCoverage(url, startOffset, sources, functions)); - if (debug.enabled) { - clearTimeout(timeout); - const diff = performance.now() - start; - const color = diff > 500 ? c.bgRed : c.bgGreen; - debug(`${color(` ${diff.toFixed()} ms `)} ${fileURLToPath(url)}`); - } - })); - } - return coverageMap; - } -} -/** -* Find the function with highest `endOffset` to determine the length of the file -*/ -function findLongestFunctionLength(functions) { - return functions.reduce((previous, current) => { - const maxEndOffset = current.ranges.reduce((endOffset, range) => Math.max(endOffset, range.endOffset), 0); - return Math.max(previous, maxEndOffset); - }, 0); -} -function removeStartsWith(filepath, start) { - if (filepath.startsWith(start)) { - return filepath.slice(start.length); - } - return filepath; -} - -export { V8CoverageProvider }; diff --git a/vanilla/node_modules/@vitest/coverage-v8/package.json b/vanilla/node_modules/@vitest/coverage-v8/package.json deleted file mode 100644 index 4bb7283..0000000 --- a/vanilla/node_modules/@vitest/coverage-v8/package.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "name": "@vitest/coverage-v8", - "type": "module", - "version": "4.0.18", - "description": "V8 coverage provider for Vitest", - "author": "Anthony Fu <anthonyfu117@hotmail.com>", - "license": "MIT", - "funding": "https://opencollective.com/vitest", - "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/coverage-v8#readme", - "repository": { - "type": "git", - "url": "git+https://github.com/vitest-dev/vitest.git", - "directory": "packages/coverage-v8" - }, - "bugs": { - "url": "https://github.com/vitest-dev/vitest/issues" - }, - "keywords": [ - "vite", - "vitest", - "test", - "coverage", - "v8" - ], - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./browser": { - "types": "./dist/browser.d.ts", - "default": "./dist/browser.js" - }, - "./*": "./*" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "dist" - ], - "peerDependencies": { - "@vitest/browser": "4.0.18", - "vitest": "4.0.18" - }, - "peerDependenciesMeta": { - "@vitest/browser": { - "optional": true - } - }, - "dependencies": { - "@bcoe/v8-coverage": "^1.0.2", - "ast-v8-to-istanbul": "^0.3.10", - "istanbul-lib-coverage": "^3.2.2", - "istanbul-lib-report": "^3.0.1", - "istanbul-reports": "^3.2.0", - "magicast": "^0.5.1", - "obug": "^2.1.1", - "std-env": "^3.10.0", - "tinyrainbow": "^3.0.3", - "@vitest/utils": "4.0.18" - }, - "devDependencies": { - "@types/istanbul-lib-coverage": "^2.0.6", - "@types/istanbul-lib-report": "^3.0.3", - "@types/istanbul-reports": "^3.0.4", - "pathe": "^2.0.3", - "@vitest/browser": "4.0.18", - "vitest": "4.0.18" - }, - "scripts": { - "build": "premove dist && rollup -c", - "dev": "rollup -c --watch --watch.include 'src/**'" - } -}
\ No newline at end of file diff --git a/vanilla/node_modules/@vitest/expect/LICENSE b/vanilla/node_modules/@vitest/expect/LICENSE deleted file mode 100644 index 0e5771d..0000000 --- a/vanilla/node_modules/@vitest/expect/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vanilla/node_modules/@vitest/expect/README.md b/vanilla/node_modules/@vitest/expect/README.md deleted file mode 100644 index 4d7143b..0000000 --- a/vanilla/node_modules/@vitest/expect/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# @vitest/expect - -Jest's expect matchers as a Chai plugin. - -## Usage - -```js -import { - JestAsymmetricMatchers, - JestChaiExpect, - JestExtend, -} from '@vitest/expect' -import * as chai from 'chai' - -// allows using expect.extend instead of chai.use to extend plugins -chai.use(JestExtend) -// adds all jest matchers to expect -chai.use(JestChaiExpect) -// adds asymmetric matchers like stringContaining, objectContaining -chai.use(JestAsymmetricMatchers) -``` diff --git a/vanilla/node_modules/@vitest/expect/dist/index.d.ts b/vanilla/node_modules/@vitest/expect/dist/index.d.ts deleted file mode 100644 index a296d58..0000000 --- a/vanilla/node_modules/@vitest/expect/dist/index.d.ts +++ /dev/null @@ -1,806 +0,0 @@ -import { Test } from '@vitest/runner'; -import { MockInstance } from '@vitest/spy'; -import { Constructable } from '@vitest/utils'; -import { Formatter } from 'tinyrainbow'; -import { StandardSchemaV1 } from '@standard-schema/spec'; -import { diff, printDiffOrStringify } from '@vitest/utils/diff'; -export { DiffOptions } from '@vitest/utils/diff'; -import { stringify } from '@vitest/utils/display'; -import * as chai from 'chai'; -export { chai }; - -declare const MATCHERS_OBJECT: unique symbol; -declare const JEST_MATCHERS_OBJECT: unique symbol; -declare const GLOBAL_EXPECT: unique symbol; -declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol; - -interface AsymmetricMatcherInterface { - asymmetricMatch: (other: unknown, customTesters?: Array<Tester>) => boolean; - toString: () => string; - getExpectedType?: () => string; - toAsymmetricMatcher?: () => string; -} -declare abstract class AsymmetricMatcher< - T, - State extends MatcherState = MatcherState -> implements AsymmetricMatcherInterface { - protected sample: T; - protected inverse: boolean; - $$typeof: symbol; - constructor(sample: T, inverse?: boolean); - protected getMatcherContext(expect?: Chai.ExpectStatic): State; - abstract asymmetricMatch(other: unknown, customTesters?: Array<Tester>): boolean; - abstract toString(): string; - getExpectedType?(): string; - toAsymmetricMatcher?(): string; -} -declare class StringContaining extends AsymmetricMatcher<string> { - constructor(sample: string, inverse?: boolean); - asymmetricMatch(other: string): boolean; - toString(): string; - getExpectedType(): string; -} -declare class Anything extends AsymmetricMatcher<void> { - asymmetricMatch(other: unknown): boolean; - toString(): string; - toAsymmetricMatcher(): string; -} -declare class ObjectContaining extends AsymmetricMatcher<Record<string | symbol | number, unknown>> { - constructor(sample: Record<string, unknown>, inverse?: boolean); - getPrototype(obj: object): any; - hasProperty(obj: object | null, property: string | symbol): boolean; - getProperties(obj: object): (string | symbol)[]; - asymmetricMatch(other: any, customTesters?: Array<Tester>): boolean; - toString(): string; - getExpectedType(): string; -} -declare class ArrayContaining<T = unknown> extends AsymmetricMatcher<Array<T>> { - constructor(sample: Array<T>, inverse?: boolean); - asymmetricMatch(other: Array<T>, customTesters?: Array<Tester>): boolean; - toString(): string; - getExpectedType(): string; -} -declare class Any extends AsymmetricMatcher<any> { - constructor(sample: unknown); - fnNameFor(func: Function): string; - asymmetricMatch(other: unknown): boolean; - toString(): string; - getExpectedType(): string; - toAsymmetricMatcher(): string; -} -declare class StringMatching extends AsymmetricMatcher<RegExp> { - constructor(sample: string | RegExp, inverse?: boolean); - asymmetricMatch(other: string): boolean; - toString(): string; - getExpectedType(): string; -} -declare class SchemaMatching extends AsymmetricMatcher<StandardSchemaV1<unknown, unknown>> { - private result; - constructor(sample: StandardSchemaV1<unknown, unknown>, inverse?: boolean); - asymmetricMatch(other: unknown): boolean; - toString(): string; - getExpectedType(): string; - toAsymmetricMatcher(): string; -} -declare const JestAsymmetricMatchers: ChaiPlugin; - -declare function matcherHint(matcherName: string, received?: string, expected?: string, options?: MatcherHintOptions): string; -declare function printReceived(object: unknown): string; -declare function printExpected(value: unknown): string; -declare function getMatcherUtils(): { - EXPECTED_COLOR: Formatter; - RECEIVED_COLOR: Formatter; - INVERTED_COLOR: Formatter; - BOLD_WEIGHT: Formatter; - DIM_COLOR: Formatter; - diff: typeof diff; - matcherHint: typeof matcherHint; - printReceived: typeof printReceived; - printExpected: typeof printExpected; - printDiffOrStringify: typeof printDiffOrStringify; - printWithType: typeof printWithType; -}; -declare function printWithType<T>(name: string, value: T, print: (value: T) => string): string; -declare function addCustomEqualityTesters(newTesters: Array<Tester>): void; - -/** -* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -* -*/ - -type ChaiPlugin = Chai.ChaiPlugin; -type Tester = (this: TesterContext, a: any, b: any, customTesters: Array<Tester>) => boolean | undefined; -interface TesterContext { - equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean; -} - -interface MatcherHintOptions { - comment?: string; - expectedColor?: Formatter; - isDirectExpectCall?: boolean; - isNot?: boolean; - promise?: string; - receivedColor?: Formatter; - secondArgument?: string; - secondArgumentColor?: Formatter; -} -interface MatcherState { - customTesters: Array<Tester>; - assertionCalls: number; - currentTestName?: string; - dontThrow?: () => void; - error?: Error; - equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean; - expand?: boolean; - expectedAssertionsNumber?: number | null; - expectedAssertionsNumberErrorGen?: (() => Error) | null; - isExpectingAssertions?: boolean; - isExpectingAssertionsError?: Error | null; - isNot: boolean; - promise: string; - suppressedErrors: Array<Error>; - testPath?: string; - utils: ReturnType<typeof getMatcherUtils> & { - diff: typeof diff; - stringify: typeof stringify; - iterableEquality: Tester; - subsetEquality: Tester; - }; - soft?: boolean; - poll?: boolean; - task?: Readonly<Test>; -} -interface SyncExpectationResult { - pass: boolean; - message: () => string; - actual?: any; - expected?: any; -} -type AsyncExpectationResult = Promise<SyncExpectationResult>; -type ExpectationResult = SyncExpectationResult | AsyncExpectationResult; -interface RawMatcherFn< - T extends MatcherState = MatcherState, - E extends Array<any> = Array<any> -> { - (this: T, received: any, ...expected: E): ExpectationResult; -} -interface Matchers<T = any> {} -type MatchersObject<T extends MatcherState = MatcherState> = Record<string, RawMatcherFn<T>> & ThisType<T> & { [K in keyof Matchers<T>]? : RawMatcherFn<T, Parameters<Matchers<T>[K]>> }; -interface ExpectStatic extends Chai.ExpectStatic, Matchers, AsymmetricMatchersContaining { - <T>(actual: T, message?: string): Assertion<T>; - extend: (expects: MatchersObject) => void; - anything: () => any; - any: (constructor: unknown) => any; - getState: () => MatcherState; - setState: (state: Partial<MatcherState>) => void; - not: AsymmetricMatchersContaining; -} -interface CustomMatcher { - /** - * Checks that a value satisfies a custom matcher function. - * - * @param matcher - A function returning a boolean based on the custom condition - * @param message - Optional custom error message on failure - * - * @example - * expect(age).toSatisfy(val => val >= 18, 'Age must be at least 18'); - * expect(age).toEqual(expect.toSatisfy(val => val >= 18, 'Age must be at least 18')); - */ - toSatisfy: (matcher: (value: any) => boolean, message?: string) => any; - /** - * Matches if the received value is one of the values in the expected array or set. - * - * @example - * expect(1).toBeOneOf([1, 2, 3]) - * expect('foo').toBeOneOf([expect.any(String)]) - * expect({ a: 1 }).toEqual({ a: expect.toBeOneOf(['1', '2', '3']) }) - */ - toBeOneOf: <T>(sample: Array<T> | Set<T>) => any; -} -interface AsymmetricMatchersContaining extends CustomMatcher { - /** - * Matches if the received string contains the expected substring. - * - * @example - * expect('I have an apple').toEqual(expect.stringContaining('apple')); - * expect({ a: 'test string' }).toEqual({ a: expect.stringContaining('test') }); - */ - stringContaining: (expected: string) => any; - /** - * Matches if the received object contains all properties of the expected object. - * - * @example - * expect({ a: '1', b: 2 }).toEqual(expect.objectContaining({ a: '1' })) - */ - objectContaining: <T = any>(expected: DeeplyAllowMatchers<T>) => any; - /** - * Matches if the received array contains all elements in the expected array. - * - * @example - * expect(['a', 'b', 'c']).toEqual(expect.arrayContaining(['b', 'a'])); - */ - arrayContaining: <T = unknown>(expected: Array<DeeplyAllowMatchers<T>>) => any; - /** - * Matches if the received string or regex matches the expected pattern. - * - * @example - * expect('hello world').toEqual(expect.stringMatching(/^hello/)); - * expect('hello world').toEqual(expect.stringMatching('hello')); - */ - stringMatching: (expected: string | RegExp) => any; - /** - * Matches if the received number is within a certain precision of the expected number. - * - * @param precision - Optional decimal precision for comparison. Default is 2. - * - * @example - * expect(10.45).toEqual(expect.closeTo(10.5, 1)); - * expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision - */ - closeTo: (expected: number, precision?: number) => any; - /** - * Matches if the received value validates against a Standard Schema. - * - * @param schema - A Standard Schema V1 compatible schema object - * - * @example - * expect(user).toEqual(expect.schemaMatching(z.object({ name: z.string() }))) - * expect(['hello', 'world']).toEqual([expect.schemaMatching(z.string()), expect.schemaMatching(z.string())]) - */ - schemaMatching: (schema: unknown) => any; -} -type WithAsymmetricMatcher<T> = T | AsymmetricMatcher<unknown>; -type DeeplyAllowMatchers<T> = T extends Array<infer Element> ? WithAsymmetricMatcher<T> | DeeplyAllowMatchers<Element>[] : T extends object ? WithAsymmetricMatcher<T> | { [K in keyof T] : DeeplyAllowMatchers<T[K]> } : WithAsymmetricMatcher<T>; -interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher { - /** - * Used when you want to check that two objects have the same value. - * This matcher recursively checks the equality of all fields, rather than checking for object identity. - * - * @example - * expect(user).toEqual({ name: 'Alice', age: 30 }); - */ - toEqual: <E>(expected: E) => void; - /** - * Use to test that objects have the same types as well as structure. - * - * @example - * expect(user).toStrictEqual({ name: 'Alice', age: 30 }); - */ - toStrictEqual: <E>(expected: E) => void; - /** - * Checks that a value is what you expect. It calls `Object.is` to compare values. - * Don't use `toBe` with floating-point numbers. - * - * @example - * expect(result).toBe(42); - * expect(status).toBe(true); - */ - toBe: <E>(expected: E) => void; - /** - * Check that a string matches a regular expression. - * - * @example - * expect(message).toMatch(/hello/); - * expect(greeting).toMatch('world'); - */ - toMatch: (expected: string | RegExp) => void; - /** - * Used to check that a JavaScript object matches a subset of the properties of an object - * - * @example - * expect(user).toMatchObject({ - * name: 'Alice', - * address: { city: 'Wonderland' } - * }); - */ - toMatchObject: <E extends object | any[]>(expected: E) => void; - /** - * Used when you want to check that an item is in a list. - * For testing the items in the list, this uses `===`, a strict equality check. - * - * @example - * expect(items).toContain('apple'); - * expect(numbers).toContain(5); - */ - toContain: <E>(item: E) => void; - /** - * Used when you want to check that an item is in a list. - * For testing the items in the list, this matcher recursively checks the - * equality of all fields, rather than checking for object identity. - * - * @example - * expect(items).toContainEqual({ name: 'apple', quantity: 1 }); - */ - toContainEqual: <E>(item: E) => void; - /** - * Use when you don't care what a value is, you just want to ensure a value - * is true in a boolean context. In JavaScript, there are six falsy values: - * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. - * - * @example - * expect(user.isActive).toBeTruthy(); - */ - toBeTruthy: () => void; - /** - * When you don't care what a value is, you just want to - * ensure a value is false in a boolean context. - * - * @example - * expect(user.isActive).toBeFalsy(); - */ - toBeFalsy: () => void; - /** - * For comparing floating point numbers. - * - * @example - * expect(score).toBeGreaterThan(10); - */ - toBeGreaterThan: (num: number | bigint) => void; - /** - * For comparing floating point numbers. - * - * @example - * expect(score).toBeGreaterThanOrEqual(10); - */ - toBeGreaterThanOrEqual: (num: number | bigint) => void; - /** - * For comparing floating point numbers. - * - * @example - * expect(score).toBeLessThan(10); - */ - toBeLessThan: (num: number | bigint) => void; - /** - * For comparing floating point numbers. - * - * @example - * expect(score).toBeLessThanOrEqual(10); - */ - toBeLessThanOrEqual: (num: number | bigint) => void; - /** - * Used to check that a variable is NaN. - * - * @example - * expect(value).toBeNaN(); - */ - toBeNaN: () => void; - /** - * Used to check that a variable is undefined. - * - * @example - * expect(value).toBeUndefined(); - */ - toBeUndefined: () => void; - /** - * This is the same as `.toBe(null)` but the error messages are a bit nicer. - * So use `.toBeNull()` when you want to check that something is null. - * - * @example - * expect(value).toBeNull(); - */ - toBeNull: () => void; - /** - * Used to check that a variable is nullable (null or undefined). - * - * @example - * expect(value).toBeNullable(); - */ - toBeNullable: () => void; - /** - * Ensure that a variable is not undefined. - * - * @example - * expect(value).toBeDefined(); - */ - toBeDefined: () => void; - /** - * Ensure that an object is an instance of a class. - * This matcher uses `instanceof` underneath. - * - * @example - * expect(new Date()).toBeInstanceOf(Date); - */ - toBeInstanceOf: <E>(expected: E) => void; - /** - * Used to check that an object has a `.length` property - * and it is set to a certain numeric value. - * - * @example - * expect([1, 2, 3]).toHaveLength(3); - * expect('hello').toHaveLength(5); - */ - toHaveLength: (length: number) => void; - /** - * Use to check if a property at the specified path exists on an object. - * For checking deeply nested properties, you may use dot notation or an array containing - * the path segments for deep references. - * - * Optionally, you can provide a value to check if it matches the value present at the path - * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks - * the equality of all fields. - * - * @example - * expect(user).toHaveProperty('address.city', 'New York'); - * expect(config).toHaveProperty(['settings', 'theme'], 'dark'); - */ - toHaveProperty: <E>(property: string | (string | number)[], value?: E) => void; - /** - * Using exact equality with floating point numbers is a bad idea. - * Rounding means that intuitive things fail. - * The default for `numDigits` is 2. - * - * @example - * expect(price).toBeCloseTo(9.99, 2); - */ - toBeCloseTo: (number: number, numDigits?: number) => void; - /** - * Ensures that a mock function is called an exact number of times. - * - * Also under the alias `expect.toBeCalledTimes`. - * - * @example - * expect(mockFunc).toHaveBeenCalledTimes(2); - */ - toHaveBeenCalledTimes: (times: number) => void; - /** - * Ensures that a mock function is called an exact number of times. - * - * Alias for `expect.toHaveBeenCalledTimes`. - * - * @example - * expect(mockFunc).toBeCalledTimes(2); - */ - toBeCalledTimes: (times: number) => void; - /** - * Ensures that a mock function is called. - * - * Also under the alias `expect.toBeCalled`. - * - * @example - * expect(mockFunc).toHaveBeenCalled(); - */ - toHaveBeenCalled: () => void; - /** - * Ensures that a mock function is called. - * - * Alias for `expect.toHaveBeenCalled`. - * - * @example - * expect(mockFunc).toBeCalled(); - */ - toBeCalled: () => void; - /** - * Ensure that a mock function is called with specific arguments. - * - * Also under the alias `expect.toBeCalledWith`. - * - * @example - * expect(mockFunc).toHaveBeenCalledWith('arg1', 42); - */ - toHaveBeenCalledWith: <E extends any[]>(...args: E) => void; - /** - * Ensure that a mock function is called with specific arguments. - * - * Alias for `expect.toHaveBeenCalledWith`. - * - * @example - * expect(mockFunc).toBeCalledWith('arg1', 42); - */ - toBeCalledWith: <E extends any[]>(...args: E) => void; - /** - * Ensure that a mock function is called with specific arguments on an Nth call. - * - * Also under the alias `expect.nthCalledWith`. - * - * @example - * expect(mockFunc).toHaveBeenNthCalledWith(2, 'secondArg'); - */ - toHaveBeenNthCalledWith: <E extends any[]>(n: number, ...args: E) => void; - /** - * Ensure that a mock function is called with specific arguments on an Nth call. - * - * Alias for `expect.toHaveBeenNthCalledWith`. - * - * @example - * expect(mockFunc).nthCalledWith(2, 'secondArg'); - */ - nthCalledWith: <E extends any[]>(nthCall: number, ...args: E) => void; - /** - * If you have a mock function, you can use `.toHaveBeenLastCalledWith` - * to test what arguments it was last called with. - * - * Also under the alias `expect.lastCalledWith`. - * - * @example - * expect(mockFunc).toHaveBeenLastCalledWith('lastArg'); - */ - toHaveBeenLastCalledWith: <E extends any[]>(...args: E) => void; - /** - * If you have a mock function, you can use `.lastCalledWith` - * to test what arguments it was last called with. - * - * Alias for `expect.toHaveBeenLastCalledWith`. - * - * @example - * expect(mockFunc).lastCalledWith('lastArg'); - */ - lastCalledWith: <E extends any[]>(...args: E) => void; - /** - * Used to test that a function throws when it is called. - * - * Also under the alias `expect.toThrowError`. - * - * @example - * expect(() => functionWithError()).toThrow('Error message'); - * expect(() => parseJSON('invalid')).toThrow(SyntaxError); - */ - toThrow: (expected?: string | Constructable | RegExp | Error) => void; - /** - * Used to test that a function throws when it is called. - * - * Alias for `expect.toThrow`. - * - * @example - * expect(() => functionWithError()).toThrowError('Error message'); - * expect(() => parseJSON('invalid')).toThrowError(SyntaxError); - */ - toThrowError: (expected?: string | Constructable | RegExp | Error) => void; - /** - * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time - * - * Alias for `expect.toHaveReturned`. - * - * @example - * expect(mockFunc).toReturn(); - */ - toReturn: () => void; - /** - * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time - * - * Also under the alias `expect.toReturn`. - * - * @example - * expect(mockFunc).toHaveReturned(); - */ - toHaveReturned: () => void; - /** - * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. - * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. - * - * Alias for `expect.toHaveReturnedTimes`. - * - * @example - * expect(mockFunc).toReturnTimes(3); - */ - toReturnTimes: (times: number) => void; - /** - * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. - * Any calls to the mock function that throw an error are not counted toward the number of times the function returned. - * - * Also under the alias `expect.toReturnTimes`. - * - * @example - * expect(mockFunc).toHaveReturnedTimes(3); - */ - toHaveReturnedTimes: (times: number) => void; - /** - * Use to ensure that a mock function returned a specific value. - * - * Alias for `expect.toHaveReturnedWith`. - * - * @example - * expect(mockFunc).toReturnWith('returnValue'); - */ - toReturnWith: <E>(value: E) => void; - /** - * Use to ensure that a mock function returned a specific value. - * - * Also under the alias `expect.toReturnWith`. - * - * @example - * expect(mockFunc).toHaveReturnedWith('returnValue'); - */ - toHaveReturnedWith: <E>(value: E) => void; - /** - * Use to test the specific value that a mock function last returned. - * If the last call to the mock function threw an error, then this matcher will fail - * no matter what value you provided as the expected return value. - * - * Also under the alias `expect.lastReturnedWith`. - * - * @example - * expect(mockFunc).toHaveLastReturnedWith('lastValue'); - */ - toHaveLastReturnedWith: <E>(value: E) => void; - /** - * Use to test the specific value that a mock function last returned. - * If the last call to the mock function threw an error, then this matcher will fail - * no matter what value you provided as the expected return value. - * - * Alias for `expect.toHaveLastReturnedWith`. - * - * @example - * expect(mockFunc).lastReturnedWith('lastValue'); - */ - lastReturnedWith: <E>(value: E) => void; - /** - * Use to test the specific value that a mock function returned for the nth call. - * If the nth call to the mock function threw an error, then this matcher will fail - * no matter what value you provided as the expected return value. - * - * Also under the alias `expect.nthReturnedWith`. - * - * @example - * expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue'); - */ - toHaveNthReturnedWith: <E>(nthCall: number, value: E) => void; - /** - * Use to test the specific value that a mock function returned for the nth call. - * If the nth call to the mock function threw an error, then this matcher will fail - * no matter what value you provided as the expected return value. - * - * Alias for `expect.toHaveNthReturnedWith`. - * - * @example - * expect(mockFunc).nthReturnedWith(2, 'nthValue'); - */ - nthReturnedWith: <E>(nthCall: number, value: E) => void; -} -type VitestAssertion< - A, - T -> = { [K in keyof A] : A[K] extends Chai.Assertion ? Assertion<T> : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion<A[K], T> } & ((type: string, message?: string) => Assertion); -type Promisify<O> = { [K in keyof O] : O[K] extends (...args: infer A) => infer R ? Promisify<O[K]> & ((...args: A) => Promise<R>) : O[K] }; -type PromisifyAssertion<T> = Promisify<Assertion<T>>; -interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T>, Matchers<T> { - /** - * Ensures a value is of a specific type. - * - * @example - * expect(value).toBeTypeOf('string'); - * expect(number).toBeTypeOf('number'); - */ - toBeTypeOf: (expected: "bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol" | "undefined") => void; - /** - * Asserts that a mock function was called exactly once. - * - * @example - * expect(mockFunc).toHaveBeenCalledOnce(); - */ - toHaveBeenCalledOnce: () => void; - /** - * Ensure that a mock function is called with specific arguments and called - * exactly once. - * - * @example - * expect(mockFunc).toHaveBeenCalledExactlyOnceWith('arg1', 42); - */ - toHaveBeenCalledExactlyOnceWith: <E extends any[]>(...args: E) => void; - /** - * This assertion checks if a `Mock` was called before another `Mock`. - * @param mock - A mock function created by `vi.spyOn` or `vi.fn` - * @param failIfNoFirstInvocation - Fail if the first mock was never called - * @example - * const mock1 = vi.fn() - * const mock2 = vi.fn() - * - * mock1() - * mock2() - * mock1() - * - * expect(mock1).toHaveBeenCalledBefore(mock2) - */ - toHaveBeenCalledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; - /** - * This assertion checks if a `Mock` was called after another `Mock`. - * @param mock - A mock function created by `vi.spyOn` or `vi.fn` - * @param failIfNoFirstInvocation - Fail if the first mock was never called - * @example - * const mock1 = vi.fn() - * const mock2 = vi.fn() - * - * mock2() - * mock1() - * mock2() - * - * expect(mock1).toHaveBeenCalledAfter(mock2) - */ - toHaveBeenCalledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void; - /** - * Checks that a promise resolves successfully at least once. - * - * @example - * await expect(promise).toHaveResolved(); - */ - toHaveResolved: () => void; - /** - * Checks that a promise resolves to a specific value. - * - * @example - * await expect(promise).toHaveResolvedWith('success'); - */ - toHaveResolvedWith: <E>(value: E) => void; - /** - * Ensures a promise resolves a specific number of times. - * - * @example - * expect(mockAsyncFunc).toHaveResolvedTimes(3); - */ - toHaveResolvedTimes: (times: number) => void; - /** - * Asserts that the last resolved value of a promise matches an expected value. - * - * @example - * await expect(mockAsyncFunc).toHaveLastResolvedWith('finalResult'); - */ - toHaveLastResolvedWith: <E>(value: E) => void; - /** - * Ensures a specific value was returned by a promise on the nth resolution. - * - * @example - * await expect(mockAsyncFunc).toHaveNthResolvedWith(2, 'secondResult'); - */ - toHaveNthResolvedWith: <E>(nthCall: number, value: E) => void; - /** - * Verifies that a promise resolves. - * - * @example - * await expect(someAsyncFunc).resolves.toBe(42); - */ - resolves: PromisifyAssertion<T>; - /** - * Verifies that a promise rejects. - * - * @example - * await expect(someAsyncFunc).rejects.toThrow('error'); - */ - rejects: PromisifyAssertion<T>; -} -declare global { - namespace jest { - interface Matchers< - R, - T = {} - > {} - } -} - -declare const customMatchers: MatchersObject; - -declare const JestChaiExpect: ChaiPlugin; - -declare const JestExtend: ChaiPlugin; - -declare function equals(a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean): boolean; -declare function isAsymmetric(obj: any): obj is AsymmetricMatcher<any>; -declare function hasAsymmetric(obj: any, seen?: Set<any>): boolean; -declare function isA(typeName: string, value: unknown): boolean; -declare function fnNameFor(func: Function): string; -declare function hasProperty(obj: object | null, property: string): boolean; -declare function isImmutableUnorderedKeyed(maybeKeyed: any): boolean; -declare function isImmutableUnorderedSet(maybeSet: any): boolean; -declare function iterableEquality(a: any, b: any, customTesters?: Array<Tester>, aStack?: Array<any>, bStack?: Array<any>): boolean | undefined; -declare function subsetEquality(object: unknown, subset: unknown, customTesters?: Array<Tester>): boolean | undefined; -declare function typeEquality(a: any, b: any): boolean | undefined; -declare function arrayBufferEquality(a: unknown, b: unknown): boolean | undefined; -declare function sparseArrayEquality(a: unknown, b: unknown, customTesters?: Array<Tester>): boolean | undefined; -declare function generateToBeMessage(deepEqualityName: string, expected?: string, actual?: string): string; -declare function pluralize(word: string, count: number): string; -declare function getObjectKeys(object: object): Array<string | symbol>; -declare function getObjectSubset(object: any, subset: any, customTesters: Array<Tester>): { - subset: any; - stripped: number; -}; -/** -* Detects if an object is a Standard Schema V1 compatible schema -*/ -declare function isStandardSchema(obj: any): obj is StandardSchemaV1; - -declare function getState<State extends MatcherState = MatcherState>(expect: ExpectStatic): State; -declare function setState<State extends MatcherState = MatcherState>(state: Partial<State>, expect: ExpectStatic): void; - -export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality }; -export type { Assertion, AsymmetricMatcherInterface, AsymmetricMatchersContaining, AsyncExpectationResult, ChaiPlugin, DeeplyAllowMatchers, ExpectStatic, ExpectationResult, JestAssertion, MatcherHintOptions, MatcherState, Matchers, MatchersObject, PromisifyAssertion, RawMatcherFn, SyncExpectationResult, Tester, TesterContext }; diff --git a/vanilla/node_modules/@vitest/expect/dist/index.js b/vanilla/node_modules/@vitest/expect/dist/index.js deleted file mode 100644 index ec7e5f9..0000000 --- a/vanilla/node_modules/@vitest/expect/dist/index.js +++ /dev/null @@ -1,1875 +0,0 @@ -import { printDiffOrStringify, diff } from '@vitest/utils/diff'; -import { stringify } from '@vitest/utils/display'; -import { getType, isObject, noop, assertTypes } from '@vitest/utils/helpers'; -import c from 'tinyrainbow'; -import { isMockFunction } from '@vitest/spy'; -import { processError } from '@vitest/utils/error'; -import { use, util } from 'chai'; -import * as chai from 'chai'; -export { chai }; - -const MATCHERS_OBJECT = Symbol.for("matchers-object"); -const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object"); -const GLOBAL_EXPECT = Symbol.for("expect-global"); -const ASYMMETRIC_MATCHERS_OBJECT = Symbol.for("asymmetric-matchers-object"); - -// selectively ported from https://github.com/jest-community/jest-extended -const customMatchers = { - toSatisfy(actual, expected, message) { - const { printReceived, printExpected, matcherHint } = this.utils; - const pass = expected(actual); - return { - pass, - message: () => pass ? `\ -${matcherHint(".not.toSatisfy", "received", "")} - -Expected value to not satisfy: -${message || printExpected(expected)} -Received: -${printReceived(actual)}` : `\ -${matcherHint(".toSatisfy", "received", "")} - -Expected value to satisfy: -${message || printExpected(expected)} - -Received: -${printReceived(actual)}` - }; - }, - toBeOneOf(actual, expected) { - const { equals, customTesters } = this; - const { printReceived, printExpected, matcherHint } = this.utils; - let pass; - if (Array.isArray(expected)) { - pass = expected.length === 0 || expected.some((item) => equals(item, actual, customTesters)); - } else if (expected instanceof Set) { - pass = expected.size === 0 || expected.has(actual) || [...expected].some((item) => equals(item, actual, customTesters)); - } else { - throw new TypeError(`You must provide an array or set to ${matcherHint(".toBeOneOf")}, not '${typeof expected}'.`); - } - return { - pass, - message: () => pass ? `\ -${matcherHint(".not.toBeOneOf", "received", "")} - -Expected value to not be one of: -${printExpected(expected)} -Received: -${printReceived(actual)}` : `\ -${matcherHint(".toBeOneOf", "received", "")} - -Expected value to be one of: -${printExpected(expected)} - -Received: -${printReceived(actual)}` - }; - } -}; - -const EXPECTED_COLOR = c.green; -const RECEIVED_COLOR = c.red; -const INVERTED_COLOR = c.inverse; -const BOLD_WEIGHT = c.bold; -const DIM_COLOR = c.dim; -function matcherHint(matcherName, received = "received", expected = "expected", options = {}) { - const { comment = "", isDirectExpectCall = false, isNot = false, promise = "", secondArgument = "", expectedColor = EXPECTED_COLOR, receivedColor = RECEIVED_COLOR, secondArgumentColor = EXPECTED_COLOR } = options; - let hint = ""; - let dimString = "expect"; - if (!isDirectExpectCall && received !== "") { - hint += DIM_COLOR(`${dimString}(`) + receivedColor(received); - dimString = ")"; - } - if (promise !== "") { - hint += DIM_COLOR(`${dimString}.`) + promise; - dimString = ""; - } - if (isNot) { - hint += `${DIM_COLOR(`${dimString}.`)}not`; - dimString = ""; - } - if (matcherName.includes(".")) { - // Old format: for backward compatibility, - // especially without promise or isNot options - dimString += matcherName; - } else { - // New format: omit period from matcherName arg - hint += DIM_COLOR(`${dimString}.`) + matcherName; - dimString = ""; - } - if (expected === "") { - dimString += "()"; - } else { - hint += DIM_COLOR(`${dimString}(`) + expectedColor(expected); - if (secondArgument) { - hint += DIM_COLOR(", ") + secondArgumentColor(secondArgument); - } - dimString = ")"; - } - if (comment !== "") { - dimString += ` // ${comment}`; - } - if (dimString !== "") { - hint += DIM_COLOR(dimString); - } - return hint; -} -const SPACE_SYMBOL = "·"; -// Instead of inverse highlight which now implies a change, -// replace common spaces with middle dot at the end of any line. -function replaceTrailingSpaces(text) { - return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length)); -} -function printReceived(object) { - return RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); -} -function printExpected(value) { - return EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); -} -function getMatcherUtils() { - return { - EXPECTED_COLOR, - RECEIVED_COLOR, - INVERTED_COLOR, - BOLD_WEIGHT, - DIM_COLOR, - diff, - matcherHint, - printReceived, - printExpected, - printDiffOrStringify, - printWithType - }; -} -function printWithType(name, value, print) { - const type = getType(value); - const hasType = type !== "null" && type !== "undefined" ? `${name} has type: ${type}\n` : ""; - const hasValue = `${name} has value: ${print(value)}`; - return hasType + hasValue; -} -function addCustomEqualityTesters(newTesters) { - if (!Array.isArray(newTesters)) { - throw new TypeError(`expect.customEqualityTesters: Must be set to an array of Testers. Was given "${getType(newTesters)}"`); - } - globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters.push(...newTesters); -} -function getCustomEqualityTesters() { - return globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters; -} - -// Extracted out of jasmine 2.5.2 -function equals(a, b, customTesters, strictCheck) { - customTesters = customTesters || []; - return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey); -} -const functionToString = Function.prototype.toString; -function isAsymmetric(obj) { - return !!obj && typeof obj === "object" && "asymmetricMatch" in obj && isA("Function", obj.asymmetricMatch); -} -function hasAsymmetric(obj, seen = new Set()) { - if (seen.has(obj)) { - return false; - } - seen.add(obj); - if (isAsymmetric(obj)) { - return true; - } - if (Array.isArray(obj)) { - return obj.some((i) => hasAsymmetric(i, seen)); - } - if (obj instanceof Set) { - return Array.from(obj).some((i) => hasAsymmetric(i, seen)); - } - if (isObject(obj)) { - return Object.values(obj).some((v) => hasAsymmetric(v, seen)); - } - return false; -} -function asymmetricMatch(a, b, customTesters) { - const asymmetricA = isAsymmetric(a); - const asymmetricB = isAsymmetric(b); - if (asymmetricA && asymmetricB) { - return undefined; - } - if (asymmetricA) { - return a.asymmetricMatch(b, customTesters); - } - if (asymmetricB) { - return b.asymmetricMatch(a, customTesters); - } -} -// Equality function lovingly adapted from isEqual in -// [Underscore](http://underscorejs.org) -function eq(a, b, aStack, bStack, customTesters, hasKey) { - let result = true; - const asymmetricResult = asymmetricMatch(a, b, customTesters); - if (asymmetricResult !== undefined) { - return asymmetricResult; - } - const testerContext = { equals }; - for (let i = 0; i < customTesters.length; i++) { - const customTesterResult = customTesters[i].call(testerContext, a, b, customTesters); - if (customTesterResult !== undefined) { - return customTesterResult; - } - } - if (typeof URL === "function" && a instanceof URL && b instanceof URL) { - return a.href === b.href; - } - if (Object.is(a, b)) { - return true; - } - // A strict comparison is necessary because `null == undefined`. - if (a === null || b === null) { - return a === b; - } - const className = Object.prototype.toString.call(a); - if (className !== Object.prototype.toString.call(b)) { - return false; - } - switch (className) { - case "[object Boolean]": - case "[object String]": - case "[object Number]": if (typeof a !== typeof b) { - // One is a primitive, one a `new Primitive()` - return false; - } else if (typeof a !== "object" && typeof b !== "object") { - // both are proper primitives - return Object.is(a, b); - } else { - // both are `new Primitive()`s - return Object.is(a.valueOf(), b.valueOf()); - } - case "[object Date]": { - const numA = +a; - const numB = +b; - // Coerce dates to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are equivalent. - return numA === numB || Number.isNaN(numA) && Number.isNaN(numB); - } - case "[object RegExp]": return a.source === b.source && a.flags === b.flags; - case "[object Temporal.Instant]": - case "[object Temporal.ZonedDateTime]": - case "[object Temporal.PlainDateTime]": - case "[object Temporal.PlainDate]": - case "[object Temporal.PlainTime]": - case "[object Temporal.PlainYearMonth]": - case "[object Temporal.PlainMonthDay]": return a.equals(b); - case "[object Temporal.Duration]": return a.toString() === b.toString(); - } - if (typeof a !== "object" || typeof b !== "object") { - return false; - } - // Use DOM3 method isEqualNode (IE>=9) - if (isDomNode(a) && isDomNode(b)) { - return a.isEqualNode(b); - } - // Used to detect circular references. - let length = aStack.length; - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - // circular references at same depth are equal - // circular reference is not equal to non-circular one - if (aStack[length] === a) { - return bStack[length] === b; - } else if (bStack[length] === b) { - return false; - } - } - // Add the first object to the stack of traversed objects. - aStack.push(a); - bStack.push(b); - // Recursively compare objects and arrays. - // Compare array lengths to determine if a deep comparison is necessary. - if (className === "[object Array]" && a.length !== b.length) { - return false; - } - if (a instanceof Error && b instanceof Error) { - try { - return isErrorEqual(a, b, aStack, bStack, customTesters, hasKey); - } finally { - aStack.pop(); - bStack.pop(); - } - } - // Deep compare objects. - const aKeys = keys(a, hasKey); - let key; - let size = aKeys.length; - // Ensure that both objects contain the same number of properties before comparing deep equality. - if (keys(b, hasKey).length !== size) { - return false; - } - while (size--) { - key = aKeys[size]; - // Deep compare each member - result = hasKey(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey); - if (!result) { - return false; - } - } - // Remove the first object from the stack of traversed objects. - aStack.pop(); - bStack.pop(); - return result; -} -function isErrorEqual(a, b, aStack, bStack, customTesters, hasKey) { - // https://nodejs.org/docs/latest-v22.x/api/assert.html#comparison-details - // - [[Prototype]] of objects are compared using the === operator. - // - Only enumerable "own" properties are considered. - // - Error names, messages, causes, and errors are always compared, even if these are not enumerable properties. errors is also compared. - let result = Object.getPrototypeOf(a) === Object.getPrototypeOf(b) && a.name === b.name && a.message === b.message; - // check Error.cause asymmetrically - if (typeof b.cause !== "undefined") { - result && (result = eq(a.cause, b.cause, aStack, bStack, customTesters, hasKey)); - } - // AggregateError.errors - if (a instanceof AggregateError && b instanceof AggregateError) { - result && (result = eq(a.errors, b.errors, aStack, bStack, customTesters, hasKey)); - } - // spread to compare enumerable properties - result && (result = eq({ ...a }, { ...b }, aStack, bStack, customTesters, hasKey)); - return result; -} -function keys(obj, hasKey) { - const keys = []; - for (const key in obj) { - if (hasKey(obj, key)) { - keys.push(key); - } - } - return keys.concat(Object.getOwnPropertySymbols(obj).filter((symbol) => Object.getOwnPropertyDescriptor(obj, symbol).enumerable)); -} -function hasDefinedKey(obj, key) { - return hasKey(obj, key) && obj[key] !== undefined; -} -function hasKey(obj, key) { - return Object.hasOwn(obj, key); -} -function isA(typeName, value) { - return Object.prototype.toString.apply(value) === `[object ${typeName}]`; -} -function isDomNode(obj) { - return obj !== null && typeof obj === "object" && "nodeType" in obj && typeof obj.nodeType === "number" && "nodeName" in obj && typeof obj.nodeName === "string" && "isEqualNode" in obj && typeof obj.isEqualNode === "function"; -} -function fnNameFor(func) { - if (func.name) { - return func.name; - } - const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*(?:\*\s*)?([\w$]+)\s*\(/); - return matches ? matches[1] : "<anonymous>"; -} -function getPrototype(obj) { - if (Object.getPrototypeOf) { - return Object.getPrototypeOf(obj); - } - if (obj.constructor.prototype === obj) { - return null; - } - return obj.constructor.prototype; -} -function hasProperty(obj, property) { - if (!obj) { - return false; - } - if (Object.hasOwn(obj, property)) { - return true; - } - return hasProperty(getPrototype(obj), property); -} -// SENTINEL constants are from https://github.com/facebook/immutable-js -const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@"; -const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@"; -const IS_LIST_SENTINEL = "@@__IMMUTABLE_LIST__@@"; -const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@"; -const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@"; -function isImmutableUnorderedKeyed(maybeKeyed) { - return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL] && !maybeKeyed[IS_ORDERED_SENTINEL]); -} -function isImmutableUnorderedSet(maybeSet) { - return !!(maybeSet && maybeSet[IS_SET_SENTINEL] && !maybeSet[IS_ORDERED_SENTINEL]); -} -function isObjectLiteral(source) { - return source != null && typeof source === "object" && !Array.isArray(source); -} -function isImmutableList(source) { - return Boolean(source && isObjectLiteral(source) && source[IS_LIST_SENTINEL]); -} -function isImmutableOrderedKeyed(source) { - return Boolean(source && isObjectLiteral(source) && source[IS_KEYED_SENTINEL] && source[IS_ORDERED_SENTINEL]); -} -function isImmutableOrderedSet(source) { - return Boolean(source && isObjectLiteral(source) && source[IS_SET_SENTINEL] && source[IS_ORDERED_SENTINEL]); -} -function isImmutableRecord(source) { - return Boolean(source && isObjectLiteral(source) && source[IS_RECORD_SYMBOL]); -} -/** -* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -* -*/ -const IteratorSymbol = Symbol.iterator; -function hasIterator(object) { - return !!(object != null && object[IteratorSymbol]); -} -function iterableEquality(a, b, customTesters = [], aStack = [], bStack = []) { - if (typeof a !== "object" || typeof b !== "object" || Array.isArray(a) || Array.isArray(b) || !hasIterator(a) || !hasIterator(b)) { - return undefined; - } - if (a.constructor !== b.constructor) { - return false; - } - let length = aStack.length; - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - // circular references at same depth are equal - // circular reference is not equal to non-circular one - if (aStack[length] === a) { - return bStack[length] === b; - } - } - aStack.push(a); - bStack.push(b); - const filteredCustomTesters = [...customTesters.filter((t) => t !== iterableEquality), iterableEqualityWithStack]; - function iterableEqualityWithStack(a, b) { - return iterableEquality(a, b, [...customTesters], [...aStack], [...bStack]); - } - if (a.size !== undefined) { - if (a.size !== b.size) { - return false; - } else if (isA("Set", a) || isImmutableUnorderedSet(a)) { - let allFound = true; - for (const aValue of a) { - if (!b.has(aValue)) { - let has = false; - for (const bValue of b) { - const isEqual = equals(aValue, bValue, filteredCustomTesters); - if (isEqual === true) { - has = true; - } - } - if (has === false) { - allFound = false; - break; - } - } - } - // Remove the first value from the stack of traversed values. - aStack.pop(); - bStack.pop(); - return allFound; - } else if (isA("Map", a) || isImmutableUnorderedKeyed(a)) { - let allFound = true; - for (const aEntry of a) { - if (!b.has(aEntry[0]) || !equals(aEntry[1], b.get(aEntry[0]), filteredCustomTesters)) { - let has = false; - for (const bEntry of b) { - const matchedKey = equals(aEntry[0], bEntry[0], filteredCustomTesters); - let matchedValue = false; - if (matchedKey === true) { - matchedValue = equals(aEntry[1], bEntry[1], filteredCustomTesters); - } - if (matchedValue === true) { - has = true; - } - } - if (has === false) { - allFound = false; - break; - } - } - } - // Remove the first value from the stack of traversed values. - aStack.pop(); - bStack.pop(); - return allFound; - } - } - const bIterator = b[IteratorSymbol](); - for (const aValue of a) { - const nextB = bIterator.next(); - if (nextB.done || !equals(aValue, nextB.value, filteredCustomTesters)) { - return false; - } - } - if (!bIterator.next().done) { - return false; - } - if (!isImmutableList(a) && !isImmutableOrderedKeyed(a) && !isImmutableOrderedSet(a) && !isImmutableRecord(a)) { - const aEntries = Object.entries(a); - const bEntries = Object.entries(b); - if (!equals(aEntries, bEntries, filteredCustomTesters)) { - return false; - } - } - // Remove the first value from the stack of traversed values. - aStack.pop(); - bStack.pop(); - return true; -} -/** -* Checks if `hasOwnProperty(object, key)` up the prototype chain, stopping at `Object.prototype`. -*/ -function hasPropertyInObject(object, key) { - const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype; - if (shouldTerminate) { - return false; - } - return Object.hasOwn(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key); -} -function isObjectWithKeys(a) { - return isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date); -} -function subsetEquality(object, subset, customTesters = []) { - const filteredCustomTesters = customTesters.filter((t) => t !== subsetEquality); - // subsetEquality needs to keep track of the references - // it has already visited to avoid infinite loops in case - // there are circular references in the subset passed to it. - const subsetEqualityWithContext = (seenReferences = new WeakMap()) => (object, subset) => { - if (!isObjectWithKeys(subset)) { - return undefined; - } - return Object.keys(subset).every((key) => { - if (subset[key] != null && typeof subset[key] === "object") { - if (seenReferences.has(subset[key])) { - return equals(object[key], subset[key], filteredCustomTesters); - } - seenReferences.set(subset[key], true); - } - const result = object != null && hasPropertyInObject(object, key) && equals(object[key], subset[key], [...filteredCustomTesters, subsetEqualityWithContext(seenReferences)]); - // The main goal of using seenReference is to avoid circular node on tree. - // It will only happen within a parent and its child, not a node and nodes next to it (same level) - // We should keep the reference for a parent and its child only - // Thus we should delete the reference immediately so that it doesn't interfere - // other nodes within the same level on tree. - seenReferences.delete(subset[key]); - return result; - }); - }; - return subsetEqualityWithContext()(object, subset); -} -function typeEquality(a, b) { - if (a == null || b == null || a.constructor === b.constructor) { - return undefined; - } - return false; -} -function arrayBufferEquality(a, b) { - let dataViewA = a; - let dataViewB = b; - if (!(a instanceof DataView && b instanceof DataView)) { - if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) { - return undefined; - } - try { - dataViewA = new DataView(a); - dataViewB = new DataView(b); - } catch { - return undefined; - } - } - // Buffers are not equal when they do not have the same byte length - if (dataViewA.byteLength !== dataViewB.byteLength) { - return false; - } - // Check if every byte value is equal to each other - for (let i = 0; i < dataViewA.byteLength; i++) { - if (dataViewA.getUint8(i) !== dataViewB.getUint8(i)) { - return false; - } - } - return true; -} -function sparseArrayEquality(a, b, customTesters = []) { - if (!Array.isArray(a) || !Array.isArray(b)) { - return undefined; - } - // A sparse array [, , 1] will have keys ["2"] whereas [undefined, undefined, 1] will have keys ["0", "1", "2"] - const aKeys = Object.keys(a); - const bKeys = Object.keys(b); - const filteredCustomTesters = customTesters.filter((t) => t !== sparseArrayEquality); - return equals(a, b, filteredCustomTesters, true) && equals(aKeys, bKeys); -} -function generateToBeMessage(deepEqualityName, expected = "#{this}", actual = "#{exp}") { - const toBeMessage = `expected ${expected} to be ${actual} // Object.is equality`; - if (["toStrictEqual", "toEqual"].includes(deepEqualityName)) { - return `${toBeMessage}\n\nIf it should pass with deep equality, replace "toBe" with "${deepEqualityName}"\n\nExpected: ${expected}\nReceived: serializes to the same string\n`; - } - return toBeMessage; -} -function pluralize(word, count) { - return `${count} ${word}${count === 1 ? "" : "s"}`; -} -function getObjectKeys(object) { - return [...Object.keys(object), ...Object.getOwnPropertySymbols(object).filter((s) => { - var _Object$getOwnPropert; - return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(object, s)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.enumerable; - })]; -} -function getObjectSubset(object, subset, customTesters) { - let stripped = 0; - const getObjectSubsetWithContext = (seenReferences = new WeakMap()) => (object, subset) => { - if (Array.isArray(object)) { - if (Array.isArray(subset) && subset.length === object.length) { - // The map method returns correct subclass of subset. - return subset.map((sub, i) => getObjectSubsetWithContext(seenReferences)(object[i], sub)); - } - } else if (object instanceof Date) { - return object; - } else if (isObject(object) && isObject(subset)) { - if (equals(object, subset, [ - ...customTesters, - iterableEquality, - subsetEquality - ])) { - // return "expected" subset to avoid showing irrelevant toMatchObject diff - return subset; - } - const trimmed = {}; - seenReferences.set(object, trimmed); - // preserve constructor for toMatchObject diff - if (typeof object.constructor === "function" && typeof object.constructor.name === "string") { - Object.defineProperty(trimmed, "constructor", { - enumerable: false, - value: object.constructor - }); - } - for (const key of getObjectKeys(object)) { - if (hasPropertyInObject(subset, key)) { - trimmed[key] = seenReferences.has(object[key]) ? seenReferences.get(object[key]) : getObjectSubsetWithContext(seenReferences)(object[key], subset[key]); - } else { - if (!seenReferences.has(object[key])) { - stripped += 1; - if (isObject(object[key])) { - stripped += getObjectKeys(object[key]).length; - } - getObjectSubsetWithContext(seenReferences)(object[key], subset[key]); - } - } - } - if (getObjectKeys(trimmed).length > 0) { - return trimmed; - } - } - return object; - }; - return { - subset: getObjectSubsetWithContext()(object, subset), - stripped - }; -} -/** -* Detects if an object is a Standard Schema V1 compatible schema -*/ -function isStandardSchema(obj) { - return !!obj && (typeof obj === "object" || typeof obj === "function") && obj["~standard"] && typeof obj["~standard"].validate === "function"; -} - -if (!Object.hasOwn(globalThis, MATCHERS_OBJECT)) { - const globalState = new WeakMap(); - const matchers = Object.create(null); - const customEqualityTesters = []; - const asymmetricMatchers = Object.create(null); - Object.defineProperty(globalThis, MATCHERS_OBJECT, { get: () => globalState }); - Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, { - configurable: true, - get: () => ({ - state: globalState.get(globalThis[GLOBAL_EXPECT]), - matchers, - customEqualityTesters - }) - }); - Object.defineProperty(globalThis, ASYMMETRIC_MATCHERS_OBJECT, { get: () => asymmetricMatchers }); -} -function getState(expect) { - return globalThis[MATCHERS_OBJECT].get(expect); -} -function setState(state, expect) { - const map = globalThis[MATCHERS_OBJECT]; - const current = map.get(expect) || {}; - // so it keeps getters from `testPath` - const results = Object.defineProperties(current, { - ...Object.getOwnPropertyDescriptors(current), - ...Object.getOwnPropertyDescriptors(state) - }); - map.set(expect, results); -} - -class AsymmetricMatcher { - // should have "jest" to be compatible with its ecosystem - $$typeof = Symbol.for("jest.asymmetricMatcher"); - constructor(sample, inverse = false) { - this.sample = sample; - this.inverse = inverse; - } - getMatcherContext(expect) { - return { - ...getState(expect || globalThis[GLOBAL_EXPECT]), - equals, - isNot: this.inverse, - customTesters: getCustomEqualityTesters(), - utils: { - ...getMatcherUtils(), - diff, - stringify, - iterableEquality, - subsetEquality - } - }; - } -} -// implement custom chai/loupe inspect for better AssertionError.message formatting -// https://github.com/chaijs/loupe/blob/9b8a6deabcd50adc056a64fb705896194710c5c6/src/index.ts#L29 -// @ts-expect-error computed properties is not supported when isolatedDeclarations is enabled -// FIXME: https://github.com/microsoft/TypeScript/issues/61068 -AsymmetricMatcher.prototype[Symbol.for("chai/inspect")] = function(options) { - // minimal pretty-format with simple manual truncation - const result = stringify(this, options.depth, { min: true }); - if (result.length <= options.truncate) { - return result; - } - return `${this.toString()}{…}`; -}; -class StringContaining extends AsymmetricMatcher { - constructor(sample, inverse = false) { - if (!isA("String", sample)) { - throw new Error("Expected is not a string"); - } - super(sample, inverse); - } - asymmetricMatch(other) { - const result = isA("String", other) && other.includes(this.sample); - return this.inverse ? !result : result; - } - toString() { - return `String${this.inverse ? "Not" : ""}Containing`; - } - getExpectedType() { - return "string"; - } -} -class Anything extends AsymmetricMatcher { - asymmetricMatch(other) { - return other != null; - } - toString() { - return "Anything"; - } - toAsymmetricMatcher() { - return "Anything"; - } -} -class ObjectContaining extends AsymmetricMatcher { - constructor(sample, inverse = false) { - super(sample, inverse); - } - getPrototype(obj) { - if (Object.getPrototypeOf) { - return Object.getPrototypeOf(obj); - } - if (obj.constructor.prototype === obj) { - return null; - } - return obj.constructor.prototype; - } - hasProperty(obj, property) { - if (!obj) { - return false; - } - if (Object.hasOwn(obj, property)) { - return true; - } - return this.hasProperty(this.getPrototype(obj), property); - } - getProperties(obj) { - return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj).filter((s) => { - var _Object$getOwnPropert; - return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(obj, s)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.enumerable; - })]; - } - asymmetricMatch(other, customTesters) { - if (typeof this.sample !== "object") { - throw new TypeError(`You must provide an object to ${this.toString()}, not '${typeof this.sample}'.`); - } - let result = true; - const properties = this.getProperties(this.sample); - for (const property of properties) { - var _Object$getOwnPropert2, _Object$getOwnPropert3; - if (!this.hasProperty(other, property)) { - result = false; - break; - } - const value = ((_Object$getOwnPropert2 = Object.getOwnPropertyDescriptor(this.sample, property)) === null || _Object$getOwnPropert2 === void 0 ? void 0 : _Object$getOwnPropert2.value) ?? this.sample[property]; - const otherValue = ((_Object$getOwnPropert3 = Object.getOwnPropertyDescriptor(other, property)) === null || _Object$getOwnPropert3 === void 0 ? void 0 : _Object$getOwnPropert3.value) ?? other[property]; - if (!equals(value, otherValue, customTesters)) { - result = false; - break; - } - } - return this.inverse ? !result : result; - } - toString() { - return `Object${this.inverse ? "Not" : ""}Containing`; - } - getExpectedType() { - return "object"; - } -} -class ArrayContaining extends AsymmetricMatcher { - constructor(sample, inverse = false) { - super(sample, inverse); - } - asymmetricMatch(other, customTesters) { - if (!Array.isArray(this.sample)) { - throw new TypeError(`You must provide an array to ${this.toString()}, not '${typeof this.sample}'.`); - } - const result = this.sample.length === 0 || Array.isArray(other) && this.sample.every((item) => other.some((another) => equals(item, another, customTesters))); - return this.inverse ? !result : result; - } - toString() { - return `Array${this.inverse ? "Not" : ""}Containing`; - } - getExpectedType() { - return "array"; - } -} -class Any extends AsymmetricMatcher { - constructor(sample) { - if (typeof sample === "undefined") { - throw new TypeError("any() expects to be passed a constructor function. " + "Please pass one or use anything() to match any object."); - } - super(sample); - } - fnNameFor(func) { - if (func.name) { - return func.name; - } - const functionToString = Function.prototype.toString; - const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*(?:\*\s*)?([\w$]+)\s*\(/); - return matches ? matches[1] : "<anonymous>"; - } - asymmetricMatch(other) { - if (this.sample === String) { - return typeof other == "string" || other instanceof String; - } - if (this.sample === Number) { - return typeof other == "number" || other instanceof Number; - } - if (this.sample === Function) { - return typeof other == "function" || typeof other === "function"; - } - if (this.sample === Boolean) { - return typeof other == "boolean" || other instanceof Boolean; - } - if (this.sample === BigInt) { - return typeof other == "bigint" || other instanceof BigInt; - } - if (this.sample === Symbol) { - return typeof other == "symbol" || other instanceof Symbol; - } - if (this.sample === Object) { - return typeof other == "object"; - } - return other instanceof this.sample; - } - toString() { - return "Any"; - } - getExpectedType() { - if (this.sample === String) { - return "string"; - } - if (this.sample === Number) { - return "number"; - } - if (this.sample === Function) { - return "function"; - } - if (this.sample === Object) { - return "object"; - } - if (this.sample === Boolean) { - return "boolean"; - } - return this.fnNameFor(this.sample); - } - toAsymmetricMatcher() { - return `Any<${this.fnNameFor(this.sample)}>`; - } -} -class StringMatching extends AsymmetricMatcher { - constructor(sample, inverse = false) { - if (!isA("String", sample) && !isA("RegExp", sample)) { - throw new Error("Expected is not a String or a RegExp"); - } - super(new RegExp(sample), inverse); - } - asymmetricMatch(other) { - const result = isA("String", other) && this.sample.test(other); - return this.inverse ? !result : result; - } - toString() { - return `String${this.inverse ? "Not" : ""}Matching`; - } - getExpectedType() { - return "string"; - } -} -class CloseTo extends AsymmetricMatcher { - precision; - constructor(sample, precision = 2, inverse = false) { - if (!isA("Number", sample)) { - throw new Error("Expected is not a Number"); - } - if (!isA("Number", precision)) { - throw new Error("Precision is not a Number"); - } - super(sample); - this.inverse = inverse; - this.precision = precision; - } - asymmetricMatch(other) { - if (!isA("Number", other)) { - return false; - } - let result = false; - if (other === Number.POSITIVE_INFINITY && this.sample === Number.POSITIVE_INFINITY) { - result = true; - } else if (other === Number.NEGATIVE_INFINITY && this.sample === Number.NEGATIVE_INFINITY) { - result = true; - } else { - result = Math.abs(this.sample - other) < 10 ** -this.precision / 2; - } - return this.inverse ? !result : result; - } - toString() { - return `Number${this.inverse ? "Not" : ""}CloseTo`; - } - getExpectedType() { - return "number"; - } - toAsymmetricMatcher() { - return [ - this.toString(), - this.sample, - `(${pluralize("digit", this.precision)})` - ].join(" "); - } -} -class SchemaMatching extends AsymmetricMatcher { - result; - constructor(sample, inverse = false) { - if (!isStandardSchema(sample)) { - throw new TypeError("SchemaMatching expected to receive a Standard Schema."); - } - super(sample, inverse); - } - asymmetricMatch(other) { - const result = this.sample["~standard"].validate(other); - // Check if the result is a Promise (async validation) - if (result instanceof Promise) { - throw new TypeError("Async schema validation is not supported in asymmetric matchers."); - } - this.result = result; - const pass = !this.result.issues || this.result.issues.length === 0; - return this.inverse ? !pass : pass; - } - toString() { - return `Schema${this.inverse ? "Not" : ""}Matching`; - } - getExpectedType() { - return "object"; - } - toAsymmetricMatcher() { - var _this$result; - const { utils } = this.getMatcherContext(); - const issues = ((_this$result = this.result) === null || _this$result === void 0 ? void 0 : _this$result.issues) || []; - if (issues.length > 0) { - return `${this.toString()} ${utils.stringify(this.result, undefined, { printBasicPrototype: false })}`; - } - return this.toString(); - } -} -const JestAsymmetricMatchers = (chai, utils) => { - utils.addMethod(chai.expect, "anything", () => new Anything()); - utils.addMethod(chai.expect, "any", (expected) => new Any(expected)); - utils.addMethod(chai.expect, "stringContaining", (expected) => new StringContaining(expected)); - utils.addMethod(chai.expect, "objectContaining", (expected) => new ObjectContaining(expected)); - utils.addMethod(chai.expect, "arrayContaining", (expected) => new ArrayContaining(expected)); - utils.addMethod(chai.expect, "stringMatching", (expected) => new StringMatching(expected)); - utils.addMethod(chai.expect, "closeTo", (expected, precision) => new CloseTo(expected, precision)); - utils.addMethod(chai.expect, "schemaMatching", (expected) => new SchemaMatching(expected)); - // defineProperty does not work - chai.expect.not = { - stringContaining: (expected) => new StringContaining(expected, true), - objectContaining: (expected) => new ObjectContaining(expected, true), - arrayContaining: (expected) => new ArrayContaining(expected, true), - stringMatching: (expected) => new StringMatching(expected, true), - closeTo: (expected, precision) => new CloseTo(expected, precision, true), - schemaMatching: (expected) => new SchemaMatching(expected, true) - }; -}; - -function createAssertionMessage(util, assertion, hasArgs) { - const not = util.flag(assertion, "negate") ? "not." : ""; - const name = `${util.flag(assertion, "_name")}(${hasArgs ? "expected" : ""})`; - const promiseName = util.flag(assertion, "promise"); - const promise = promiseName ? `.${promiseName}` : ""; - return `expect(actual)${promise}.${not}${name}`; -} -function recordAsyncExpect(_test, promise, assertion, error) { - const test = _test; - // record promise for test, that resolves before test ends - if (test && promise instanceof Promise) { - // if promise is explicitly awaited, remove it from the list - promise = promise.finally(() => { - if (!test.promises) { - return; - } - const index = test.promises.indexOf(promise); - if (index !== -1) { - test.promises.splice(index, 1); - } - }); - // record promise - if (!test.promises) { - test.promises = []; - } - test.promises.push(promise); - let resolved = false; - test.onFinished ?? (test.onFinished = []); - test.onFinished.push(() => { - if (!resolved) { - var _vitest_worker__; - const processor = ((_vitest_worker__ = globalThis.__vitest_worker__) === null || _vitest_worker__ === void 0 ? void 0 : _vitest_worker__.onFilterStackTrace) || ((s) => s || ""); - const stack = processor(error.stack); - console.warn([ - `Promise returned by \`${assertion}\` was not awaited. `, - "Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ", - "Please remember to await the assertion.\n", - stack - ].join("")); - } - }); - return { - then(onFulfilled, onRejected) { - resolved = true; - return promise.then(onFulfilled, onRejected); - }, - catch(onRejected) { - return promise.catch(onRejected); - }, - finally(onFinally) { - return promise.finally(onFinally); - }, - [Symbol.toStringTag]: "Promise" - }; - } - return promise; -} -function handleTestError(test, err) { - var _test$result; - test.result || (test.result = { state: "fail" }); - test.result.state = "fail"; - (_test$result = test.result).errors || (_test$result.errors = []); - test.result.errors.push(processError(err)); -} -function wrapAssertion(utils, name, fn) { - return function(...args) { - // private - if (name !== "withTest") { - utils.flag(this, "_name", name); - } - if (!utils.flag(this, "soft")) { - return fn.apply(this, args); - } - const test = utils.flag(this, "vitest-test"); - if (!test) { - throw new Error("expect.soft() can only be used inside a test"); - } - try { - const result = fn.apply(this, args); - if (result && typeof result === "object" && typeof result.then === "function") { - return result.then(noop, (err) => { - handleTestError(test, err); - }); - } - return result; - } catch (err) { - handleTestError(test, err); - } - }; -} - -// Jest Expect Compact -const JestChaiExpect = (chai, utils) => { - const { AssertionError } = chai; - const customTesters = getCustomEqualityTesters(); - function def(name, fn) { - const addMethod = (n) => { - const softWrapper = wrapAssertion(utils, n, fn); - utils.addMethod(chai.Assertion.prototype, n, softWrapper); - utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, n, softWrapper); - }; - if (Array.isArray(name)) { - name.forEach((n) => addMethod(n)); - } else { - addMethod(name); - } - } - [ - "throw", - "throws", - "Throw" - ].forEach((m) => { - utils.overwriteMethod(chai.Assertion.prototype, m, (_super) => { - return function(...args) { - const promise = utils.flag(this, "promise"); - const object = utils.flag(this, "object"); - const isNot = utils.flag(this, "negate"); - if (promise === "rejects") { - utils.flag(this, "object", () => { - throw object; - }); - } else if (promise === "resolves" && typeof object !== "function") { - if (!isNot) { - const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't"; - const error = { showDiff: false }; - throw new AssertionError(message, error, utils.flag(this, "ssfi")); - } else { - return; - } - } - _super.apply(this, args); - }; - }); - }); - // @ts-expect-error @internal - def("withTest", function(test) { - utils.flag(this, "vitest-test", test); - return this; - }); - def("toEqual", function(expected) { - const actual = utils.flag(this, "object"); - const equal = equals(actual, expected, [...customTesters, iterableEquality]); - return this.assert(equal, "expected #{this} to deeply equal #{exp}", "expected #{this} to not deeply equal #{exp}", expected, actual); - }); - def("toStrictEqual", function(expected) { - const obj = utils.flag(this, "object"); - const equal = equals(obj, expected, [ - ...customTesters, - iterableEquality, - typeEquality, - sparseArrayEquality, - arrayBufferEquality - ], true); - return this.assert(equal, "expected #{this} to strictly equal #{exp}", "expected #{this} to not strictly equal #{exp}", expected, obj); - }); - def("toBe", function(expected) { - const actual = this._obj; - const pass = Object.is(actual, expected); - let deepEqualityName = ""; - if (!pass) { - const toStrictEqualPass = equals(actual, expected, [ - ...customTesters, - iterableEquality, - typeEquality, - sparseArrayEquality, - arrayBufferEquality - ], true); - if (toStrictEqualPass) { - deepEqualityName = "toStrictEqual"; - } else { - const toEqualPass = equals(actual, expected, [...customTesters, iterableEquality]); - if (toEqualPass) { - deepEqualityName = "toEqual"; - } - } - } - return this.assert(pass, generateToBeMessage(deepEqualityName), "expected #{this} not to be #{exp} // Object.is equality", expected, actual); - }); - def("toMatchObject", function(expected) { - const actual = this._obj; - const pass = equals(actual, expected, [ - ...customTesters, - iterableEquality, - subsetEquality - ]); - const isNot = utils.flag(this, "negate"); - const { subset: actualSubset, stripped } = getObjectSubset(actual, expected, customTesters); - if (pass && isNot || !pass && !isNot) { - const msg = utils.getMessage(this, [ - pass, - "expected #{this} to match object #{exp}", - "expected #{this} to not match object #{exp}", - expected, - actualSubset, - false - ]); - const message = stripped === 0 ? msg : `${msg}\n(${stripped} matching ${stripped === 1 ? "property" : "properties"} omitted from actual)`; - throw new AssertionError(message, { - showDiff: true, - expected, - actual: actualSubset - }); - } - }); - def("toMatch", function(expected) { - const actual = this._obj; - if (typeof actual !== "string") { - throw new TypeError(`.toMatch() expects to receive a string, but got ${typeof actual}`); - } - return this.assert(typeof expected === "string" ? actual.includes(expected) : actual.match(expected), `expected #{this} to match #{exp}`, `expected #{this} not to match #{exp}`, expected, actual); - }); - def("toContain", function(item) { - const actual = this._obj; - if (typeof Node !== "undefined" && actual instanceof Node) { - if (!(item instanceof Node)) { - throw new TypeError(`toContain() expected a DOM node as the argument, but got ${typeof item}`); - } - return this.assert(actual.contains(item), "expected #{this} to contain element #{exp}", "expected #{this} not to contain element #{exp}", item, actual); - } - if (typeof DOMTokenList !== "undefined" && actual instanceof DOMTokenList) { - assertTypes(item, "class name", ["string"]); - const isNot = utils.flag(this, "negate"); - const expectedClassList = isNot ? actual.value.replace(item, "").trim() : `${actual.value} ${item}`; - return this.assert(actual.contains(item), `expected "${actual.value}" to contain "${item}"`, `expected "${actual.value}" not to contain "${item}"`, expectedClassList, actual.value); - } - // handle simple case on our own using `this.assert` to include diff in error message - if (typeof actual === "string" && typeof item === "string") { - return this.assert(actual.includes(item), `expected #{this} to contain #{exp}`, `expected #{this} not to contain #{exp}`, item, actual); - } - // make "actual" indexable to have compatibility with jest - if (actual != null && typeof actual !== "string") { - utils.flag(this, "object", Array.from(actual)); - } - return this.contain(item); - }); - def("toContainEqual", function(expected) { - const obj = utils.flag(this, "object"); - const index = Array.from(obj).findIndex((item) => { - return equals(item, expected, customTesters); - }); - this.assert(index !== -1, "expected #{this} to deep equally contain #{exp}", "expected #{this} to not deep equally contain #{exp}", expected); - }); - def("toBeTruthy", function() { - const obj = utils.flag(this, "object"); - this.assert(Boolean(obj), "expected #{this} to be truthy", "expected #{this} to not be truthy", true, obj); - }); - def("toBeFalsy", function() { - const obj = utils.flag(this, "object"); - this.assert(!obj, "expected #{this} to be falsy", "expected #{this} to not be falsy", false, obj); - }); - def("toBeGreaterThan", function(expected) { - const actual = this._obj; - assertTypes(actual, "actual", ["number", "bigint"]); - assertTypes(expected, "expected", ["number", "bigint"]); - return this.assert(actual > expected, `expected ${actual} to be greater than ${expected}`, `expected ${actual} to be not greater than ${expected}`, expected, actual, false); - }); - def("toBeGreaterThanOrEqual", function(expected) { - const actual = this._obj; - assertTypes(actual, "actual", ["number", "bigint"]); - assertTypes(expected, "expected", ["number", "bigint"]); - return this.assert(actual >= expected, `expected ${actual} to be greater than or equal to ${expected}`, `expected ${actual} to be not greater than or equal to ${expected}`, expected, actual, false); - }); - def("toBeLessThan", function(expected) { - const actual = this._obj; - assertTypes(actual, "actual", ["number", "bigint"]); - assertTypes(expected, "expected", ["number", "bigint"]); - return this.assert(actual < expected, `expected ${actual} to be less than ${expected}`, `expected ${actual} to be not less than ${expected}`, expected, actual, false); - }); - def("toBeLessThanOrEqual", function(expected) { - const actual = this._obj; - assertTypes(actual, "actual", ["number", "bigint"]); - assertTypes(expected, "expected", ["number", "bigint"]); - return this.assert(actual <= expected, `expected ${actual} to be less than or equal to ${expected}`, `expected ${actual} to be not less than or equal to ${expected}`, expected, actual, false); - }); - def("toBeNaN", function() { - const obj = utils.flag(this, "object"); - this.assert(Number.isNaN(obj), "expected #{this} to be NaN", "expected #{this} not to be NaN", Number.NaN, obj); - }); - def("toBeUndefined", function() { - const obj = utils.flag(this, "object"); - this.assert(undefined === obj, "expected #{this} to be undefined", "expected #{this} not to be undefined", undefined, obj); - }); - def("toBeNull", function() { - const obj = utils.flag(this, "object"); - this.assert(obj === null, "expected #{this} to be null", "expected #{this} not to be null", null, obj); - }); - def("toBeNullable", function() { - const obj = utils.flag(this, "object"); - this.assert(obj == null, "expected #{this} to be nullish", "expected #{this} not to be nullish", null, obj); - }); - def("toBeDefined", function() { - const obj = utils.flag(this, "object"); - this.assert(typeof obj !== "undefined", "expected #{this} to be defined", "expected #{this} to be undefined", obj); - }); - def("toBeTypeOf", function(expected) { - const actual = typeof this._obj; - const equal = expected === actual; - return this.assert(equal, "expected #{this} to be type of #{exp}", "expected #{this} not to be type of #{exp}", expected, actual); - }); - def("toBeInstanceOf", function(obj) { - return this.instanceOf(obj); - }); - def("toHaveLength", function(length) { - return this.have.length(length); - }); - // destructuring, because it checks `arguments` inside, and value is passing as `undefined` - def("toHaveProperty", function(...args) { - if (Array.isArray(args[0])) { - args[0] = args[0].map((key) => String(key).replace(/([.[\]])/g, "\\$1")).join("."); - } - const actual = this._obj; - const [propertyName, expected] = args; - const getValue = () => { - const hasOwn = Object.hasOwn(actual, propertyName); - if (hasOwn) { - return { - value: actual[propertyName], - exists: true - }; - } - return utils.getPathInfo(actual, propertyName); - }; - const { value, exists } = getValue(); - const pass = exists && (args.length === 1 || equals(expected, value, customTesters)); - const valueString = args.length === 1 ? "" : ` with value ${utils.objDisplay(expected)}`; - return this.assert(pass, `expected #{this} to have property "${propertyName}"${valueString}`, `expected #{this} to not have property "${propertyName}"${valueString}`, expected, exists ? value : undefined); - }); - def("toBeCloseTo", function(received, precision = 2) { - const expected = this._obj; - let pass = false; - let expectedDiff = 0; - let receivedDiff = 0; - if (received === Number.POSITIVE_INFINITY && expected === Number.POSITIVE_INFINITY) { - pass = true; - } else if (received === Number.NEGATIVE_INFINITY && expected === Number.NEGATIVE_INFINITY) { - pass = true; - } else { - expectedDiff = 10 ** -precision / 2; - receivedDiff = Math.abs(expected - received); - pass = receivedDiff < expectedDiff; - } - return this.assert(pass, `expected #{this} to be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, `expected #{this} to not be close to #{exp}, received difference is ${receivedDiff}, but expected ${expectedDiff}`, received, expected, false); - }); - function assertIsMock(assertion) { - if (!isMockFunction(assertion._obj)) { - throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`); - } - } - function getSpy(assertion) { - assertIsMock(assertion); - return assertion._obj; - } - def(["toHaveBeenCalledTimes", "toBeCalledTimes"], function(number) { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const callCount = spy.mock.calls.length; - return this.assert(callCount === number, `expected "${spyName}" to be called #{exp} times, but got ${callCount} times`, `expected "${spyName}" to not be called #{exp} times`, number, callCount, false); - }); - def("toHaveBeenCalledOnce", function() { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const callCount = spy.mock.calls.length; - return this.assert(callCount === 1, `expected "${spyName}" to be called once, but got ${callCount} times`, `expected "${spyName}" to not be called once`, 1, callCount, false); - }); - def(["toHaveBeenCalled", "toBeCalled"], function() { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const callCount = spy.mock.calls.length; - const called = callCount > 0; - const isNot = utils.flag(this, "negate"); - let msg = utils.getMessage(this, [ - called, - `expected "${spyName}" to be called at least once`, - `expected "${spyName}" to not be called at all, but actually been called ${callCount} times`, - true, - called - ]); - if (called && isNot) { - msg = formatCalls(spy, msg); - } - if (called && isNot || !called && !isNot) { - throw new AssertionError(msg); - } - }); - // manually compare array elements since `jestEquals` cannot - // apply asymmetric matcher to `undefined` array element. - function equalsArgumentArray(a, b) { - return a.length === b.length && a.every((aItem, i) => equals(aItem, b[i], [...customTesters, iterableEquality])); - } - def(["toHaveBeenCalledWith", "toBeCalledWith"], function(...args) { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const pass = spy.mock.calls.some((callArg) => equalsArgumentArray(callArg, args)); - const isNot = utils.flag(this, "negate"); - const msg = utils.getMessage(this, [ - pass, - `expected "${spyName}" to be called with arguments: #{exp}`, - `expected "${spyName}" to not be called with arguments: #{exp}`, - args - ]); - if (pass && isNot || !pass && !isNot) { - throw new AssertionError(formatCalls(spy, msg, args)); - } - }); - def("toHaveBeenCalledExactlyOnceWith", function(...args) { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const callCount = spy.mock.calls.length; - const hasCallWithArgs = spy.mock.calls.some((callArg) => equalsArgumentArray(callArg, args)); - const pass = hasCallWithArgs && callCount === 1; - const isNot = utils.flag(this, "negate"); - const msg = utils.getMessage(this, [ - pass, - `expected "${spyName}" to be called once with arguments: #{exp}`, - `expected "${spyName}" to not be called once with arguments: #{exp}`, - args - ]); - if (pass && isNot || !pass && !isNot) { - throw new AssertionError(formatCalls(spy, msg, args)); - } - }); - def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const nthCall = spy.mock.calls[times - 1]; - const callCount = spy.mock.calls.length; - const isCalled = times <= callCount; - this.assert(nthCall && equalsArgumentArray(nthCall, args), `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}${isCalled ? `` : `, but called only ${callCount} times`}`, `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall, isCalled); - }); - def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const lastCall = spy.mock.calls.at(-1); - this.assert(lastCall && equalsArgumentArray(lastCall, args), `expected last "${spyName}" call to have been called with #{exp}`, `expected last "${spyName}" call to not have been called with #{exp}`, args, lastCall); - }); - /** - * Used for `toHaveBeenCalledBefore` and `toHaveBeenCalledAfter` to determine if the expected spy was called before the result spy. - */ - function isSpyCalledBeforeAnotherSpy(beforeSpy, afterSpy, failIfNoFirstInvocation) { - const beforeInvocationCallOrder = beforeSpy.mock.invocationCallOrder; - const afterInvocationCallOrder = afterSpy.mock.invocationCallOrder; - if (beforeInvocationCallOrder.length === 0) { - return !failIfNoFirstInvocation; - } - if (afterInvocationCallOrder.length === 0) { - return false; - } - return beforeInvocationCallOrder[0] < afterInvocationCallOrder[0]; - } - def(["toHaveBeenCalledBefore"], function(resultSpy, failIfNoFirstInvocation = true) { - const expectSpy = getSpy(this); - if (!isMockFunction(resultSpy)) { - throw new TypeError(`${utils.inspect(resultSpy)} is not a spy or a call to a spy`); - } - this.assert(isSpyCalledBeforeAnotherSpy(expectSpy, resultSpy, failIfNoFirstInvocation), `expected "${expectSpy.getMockName()}" to have been called before "${resultSpy.getMockName()}"`, `expected "${expectSpy.getMockName()}" to not have been called before "${resultSpy.getMockName()}"`, resultSpy, expectSpy); - }); - def(["toHaveBeenCalledAfter"], function(resultSpy, failIfNoFirstInvocation = true) { - const expectSpy = getSpy(this); - if (!isMockFunction(resultSpy)) { - throw new TypeError(`${utils.inspect(resultSpy)} is not a spy or a call to a spy`); - } - this.assert(isSpyCalledBeforeAnotherSpy(resultSpy, expectSpy, failIfNoFirstInvocation), `expected "${expectSpy.getMockName()}" to have been called after "${resultSpy.getMockName()}"`, `expected "${expectSpy.getMockName()}" to not have been called after "${resultSpy.getMockName()}"`, resultSpy, expectSpy); - }); - def(["toThrow", "toThrowError"], function(expected) { - if (typeof expected === "string" || typeof expected === "undefined" || expected instanceof RegExp) { - // Fixes the issue related to `chai` <https://github.com/vitest-dev/vitest/issues/6618> - return this.throws(expected === "" ? /^$/ : expected); - } - const obj = this._obj; - const promise = utils.flag(this, "promise"); - const isNot = utils.flag(this, "negate"); - let thrown = null; - if (promise === "rejects") { - thrown = obj; - } else if (promise === "resolves" && typeof obj !== "function") { - if (!isNot) { - const message = utils.flag(this, "message") || "expected promise to throw an error, but it didn't"; - const error = { showDiff: false }; - throw new AssertionError(message, error, utils.flag(this, "ssfi")); - } else { - return; - } - } else { - let isThrow = false; - try { - obj(); - } catch (err) { - isThrow = true; - thrown = err; - } - if (!isThrow && !isNot) { - const message = utils.flag(this, "message") || "expected function to throw an error, but it didn't"; - const error = { showDiff: false }; - throw new AssertionError(message, error, utils.flag(this, "ssfi")); - } - } - if (typeof expected === "function") { - const name = expected.name || expected.prototype.constructor.name; - return this.assert(thrown && thrown instanceof expected, `expected error to be instance of ${name}`, `expected error not to be instance of ${name}`, expected, thrown); - } - if (expected instanceof Error) { - const equal = equals(thrown, expected, [...customTesters, iterableEquality]); - return this.assert(equal, "expected a thrown error to be #{exp}", "expected a thrown error not to be #{exp}", expected, thrown); - } - if (typeof expected === "object" && "asymmetricMatch" in expected && typeof expected.asymmetricMatch === "function") { - const matcher = expected; - return this.assert(thrown && matcher.asymmetricMatch(thrown), "expected error to match asymmetric matcher", "expected error not to match asymmetric matcher", matcher, thrown); - } - throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`); - }); - [{ - name: "toHaveResolved", - condition: (spy) => spy.mock.settledResults.length > 0 && spy.mock.settledResults.some(({ type }) => type === "fulfilled"), - action: "resolved" - }, { - name: ["toHaveReturned", "toReturn"], - condition: (spy) => spy.mock.calls.length > 0 && spy.mock.results.some(({ type }) => type !== "throw"), - action: "called" - }].forEach(({ name, condition, action }) => { - def(name, function() { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const pass = condition(spy); - this.assert(pass, `expected "${spyName}" to be successfully ${action} at least once`, `expected "${spyName}" to not be successfully ${action}`, pass, !pass, false); - }); - }); - [{ - name: "toHaveResolvedTimes", - condition: (spy, times) => spy.mock.settledResults.reduce((s, { type }) => type === "fulfilled" ? ++s : s, 0) === times, - action: "resolved" - }, { - name: ["toHaveReturnedTimes", "toReturnTimes"], - condition: (spy, times) => spy.mock.results.reduce((s, { type }) => type === "throw" ? s : ++s, 0) === times, - action: "called" - }].forEach(({ name, condition, action }) => { - def(name, function(times) { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const pass = condition(spy, times); - this.assert(pass, `expected "${spyName}" to be successfully ${action} ${times} times`, `expected "${spyName}" to not be successfully ${action} ${times} times`, `expected resolved times: ${times}`, `received resolved times: ${pass}`, false); - }); - }); - [{ - name: "toHaveResolvedWith", - condition: (spy, value) => spy.mock.settledResults.some(({ type, value: result }) => type === "fulfilled" && equals(value, result)), - action: "resolve" - }, { - name: ["toHaveReturnedWith", "toReturnWith"], - condition: (spy, value) => spy.mock.results.some(({ type, value: result }) => type === "return" && equals(value, result)), - action: "return" - }].forEach(({ name, condition, action }) => { - def(name, function(value) { - const spy = getSpy(this); - const pass = condition(spy, value); - const isNot = utils.flag(this, "negate"); - if (pass && isNot || !pass && !isNot) { - const spyName = spy.getMockName(); - const msg = utils.getMessage(this, [ - pass, - `expected "${spyName}" to ${action} with: #{exp} at least once`, - `expected "${spyName}" to not ${action} with: #{exp}`, - value - ]); - const results = action === "return" ? spy.mock.results : spy.mock.settledResults; - throw new AssertionError(formatReturns(spy, results, msg, value)); - } - }); - }); - [{ - name: "toHaveLastResolvedWith", - condition: (spy, value) => { - const result = spy.mock.settledResults.at(-1); - return Boolean(result && result.type === "fulfilled" && equals(result.value, value)); - }, - action: "resolve" - }, { - name: ["toHaveLastReturnedWith", "lastReturnedWith"], - condition: (spy, value) => { - const result = spy.mock.results.at(-1); - return Boolean(result && result.type === "return" && equals(result.value, value)); - }, - action: "return" - }].forEach(({ name, condition, action }) => { - def(name, function(value) { - const spy = getSpy(this); - const results = action === "return" ? spy.mock.results : spy.mock.settledResults; - const result = results.at(-1); - const spyName = spy.getMockName(); - this.assert(condition(spy, value), `expected last "${spyName}" call to ${action} #{exp}`, `expected last "${spyName}" call to not ${action} #{exp}`, value, result === null || result === void 0 ? void 0 : result.value); - }); - }); - [{ - name: "toHaveNthResolvedWith", - condition: (spy, index, value) => { - const result = spy.mock.settledResults[index - 1]; - return result && result.type === "fulfilled" && equals(result.value, value); - }, - action: "resolve" - }, { - name: ["toHaveNthReturnedWith", "nthReturnedWith"], - condition: (spy, index, value) => { - const result = spy.mock.results[index - 1]; - return result && result.type === "return" && equals(result.value, value); - }, - action: "return" - }].forEach(({ name, condition, action }) => { - def(name, function(nthCall, value) { - const spy = getSpy(this); - const spyName = spy.getMockName(); - const results = action === "return" ? spy.mock.results : spy.mock.settledResults; - const result = results[nthCall - 1]; - const ordinalCall = `${ordinalOf(nthCall)} call`; - this.assert(condition(spy, nthCall, value), `expected ${ordinalCall} "${spyName}" call to ${action} #{exp}`, `expected ${ordinalCall} "${spyName}" call to not ${action} #{exp}`, value, result === null || result === void 0 ? void 0 : result.value); - }); - }); - // @ts-expect-error @internal - def("withContext", function(context) { - for (const key in context) { - utils.flag(this, key, context[key]); - } - return this; - }); - utils.addProperty(chai.Assertion.prototype, "resolves", function __VITEST_RESOLVES__() { - const error = new Error("resolves"); - utils.flag(this, "promise", "resolves"); - utils.flag(this, "error", error); - const test = utils.flag(this, "vitest-test"); - const obj = utils.flag(this, "object"); - if (utils.flag(this, "poll")) { - throw new SyntaxError(`expect.poll() is not supported in combination with .resolves`); - } - if (typeof (obj === null || obj === void 0 ? void 0 : obj.then) !== "function") { - throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`); - } - const proxy = new Proxy(this, { get: (target, key, receiver) => { - const result = Reflect.get(target, key, receiver); - if (typeof result !== "function") { - return result instanceof chai.Assertion ? proxy : result; - } - return (...args) => { - utils.flag(this, "_name", key); - const promise = obj.then((value) => { - utils.flag(this, "object", value); - return result.call(this, ...args); - }, (err) => { - const _error = new AssertionError(`promise rejected "${utils.inspect(err)}" instead of resolving`, { showDiff: false }); - _error.cause = err; - _error.stack = error.stack.replace(error.message, _error.message); - throw _error; - }); - return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error); - }; - } }); - return proxy; - }); - utils.addProperty(chai.Assertion.prototype, "rejects", function __VITEST_REJECTS__() { - const error = new Error("rejects"); - utils.flag(this, "promise", "rejects"); - utils.flag(this, "error", error); - const test = utils.flag(this, "vitest-test"); - const obj = utils.flag(this, "object"); - const wrapper = typeof obj === "function" ? obj() : obj; - if (utils.flag(this, "poll")) { - throw new SyntaxError(`expect.poll() is not supported in combination with .rejects`); - } - if (typeof (wrapper === null || wrapper === void 0 ? void 0 : wrapper.then) !== "function") { - throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`); - } - const proxy = new Proxy(this, { get: (target, key, receiver) => { - const result = Reflect.get(target, key, receiver); - if (typeof result !== "function") { - return result instanceof chai.Assertion ? proxy : result; - } - return (...args) => { - utils.flag(this, "_name", key); - const promise = wrapper.then((value) => { - const _error = new AssertionError(`promise resolved "${utils.inspect(value)}" instead of rejecting`, { - showDiff: true, - expected: new Error("rejected promise"), - actual: value - }); - _error.stack = error.stack.replace(error.message, _error.message); - throw _error; - }, (err) => { - utils.flag(this, "object", err); - return result.call(this, ...args); - }); - return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error); - }; - } }); - return proxy; - }); -}; -function ordinalOf(i) { - const j = i % 10; - const k = i % 100; - if (j === 1 && k !== 11) { - return `${i}st`; - } - if (j === 2 && k !== 12) { - return `${i}nd`; - } - if (j === 3 && k !== 13) { - return `${i}rd`; - } - return `${i}th`; -} -function formatCalls(spy, msg, showActualCall) { - if (spy.mock.calls.length) { - msg += c.gray(`\n\nReceived: \n\n${spy.mock.calls.map((callArg, i) => { - let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call:\n\n`); - if (showActualCall) { - methodCall += diff(showActualCall, callArg, { omitAnnotationLines: true }); - } else { - methodCall += stringify(callArg).split("\n").map((line) => ` ${line}`).join("\n"); - } - methodCall += "\n"; - return methodCall; - }).join("\n")}`); - } - msg += c.gray(`\n\nNumber of calls: ${c.bold(spy.mock.calls.length)}\n`); - return msg; -} -function formatReturns(spy, results, msg, showActualReturn) { - if (results.length) { - msg += c.gray(`\n\nReceived: \n\n${results.map((callReturn, i) => { - let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call return:\n\n`); - if (showActualReturn) { - methodCall += diff(showActualReturn, callReturn.value, { omitAnnotationLines: true }); - } else { - methodCall += stringify(callReturn).split("\n").map((line) => ` ${line}`).join("\n"); - } - methodCall += "\n"; - return methodCall; - }).join("\n")}`); - } - msg += c.gray(`\n\nNumber of calls: ${c.bold(spy.mock.calls.length)}\n`); - return msg; -} - -function getMatcherState(assertion, expect) { - const obj = assertion._obj; - const isNot = util.flag(assertion, "negate"); - const promise = util.flag(assertion, "promise") || ""; - const customMessage = util.flag(assertion, "message"); - const jestUtils = { - ...getMatcherUtils(), - diff, - stringify, - iterableEquality, - subsetEquality - }; - let task = util.flag(assertion, "vitest-test"); - const currentTestName = (task === null || task === void 0 ? void 0 : task.fullTestName) ?? ""; - if ((task === null || task === void 0 ? void 0 : task.type) !== "test") { - task = undefined; - } - const matcherState = { - ...getState(expect), - task, - currentTestName, - customTesters: getCustomEqualityTesters(), - isNot, - utils: jestUtils, - promise, - equals, - suppressedErrors: [], - soft: util.flag(assertion, "soft"), - poll: util.flag(assertion, "poll") - }; - return { - state: matcherState, - isNot, - obj, - customMessage - }; -} -class JestExtendError extends Error { - constructor(message, actual, expected) { - super(message); - this.actual = actual; - this.expected = expected; - } -} -function JestExtendPlugin(c, expect, matchers) { - return (_, utils) => { - Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => { - function expectWrapper(...args) { - const { state, isNot, obj, customMessage } = getMatcherState(this, expect); - const result = expectAssertion.call(state, obj, ...args); - if (result && typeof result === "object" && typeof result.then === "function") { - const thenable = result; - return thenable.then(({ pass, message, actual, expected }) => { - if (pass && isNot || !pass && !isNot) { - const errorMessage = customMessage != null ? customMessage : message(); - throw new JestExtendError(errorMessage, actual, expected); - } - }); - } - const { pass, message, actual, expected } = result; - if (pass && isNot || !pass && !isNot) { - const errorMessage = customMessage != null ? customMessage : message(); - throw new JestExtendError(errorMessage, actual, expected); - } - } - const softWrapper = wrapAssertion(utils, expectAssertionName, expectWrapper); - utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, softWrapper); - utils.addMethod(c.Assertion.prototype, expectAssertionName, softWrapper); - class CustomMatcher extends AsymmetricMatcher { - constructor(inverse = false, ...sample) { - super(sample, inverse); - } - asymmetricMatch(other) { - const { pass } = expectAssertion.call(this.getMatcherContext(expect), other, ...this.sample); - return this.inverse ? !pass : pass; - } - toString() { - return `${this.inverse ? "not." : ""}${expectAssertionName}`; - } - getExpectedType() { - return "any"; - } - toAsymmetricMatcher() { - return `${this.toString()}<${this.sample.map((item) => stringify(item)).join(", ")}>`; - } - } - const customMatcher = (...sample) => new CustomMatcher(false, ...sample); - Object.defineProperty(expect, expectAssertionName, { - configurable: true, - enumerable: true, - value: customMatcher, - writable: true - }); - Object.defineProperty(expect.not, expectAssertionName, { - configurable: true, - enumerable: true, - value: (...sample) => new CustomMatcher(true, ...sample), - writable: true - }); - // keep track of asymmetric matchers on global so that it can be copied over to local context's `expect`. - // note that the negated variant is automatically shared since it's assigned on the single `expect.not` object. - Object.defineProperty(globalThis[ASYMMETRIC_MATCHERS_OBJECT], expectAssertionName, { - configurable: true, - enumerable: true, - value: customMatcher, - writable: true - }); - }); - }; -} -const JestExtend = (chai, utils) => { - utils.addMethod(chai.expect, "extend", (expect, expects) => { - use(JestExtendPlugin(chai, expect, expects)); - }); -}; - -export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality }; diff --git a/vanilla/node_modules/@vitest/expect/package.json b/vanilla/node_modules/@vitest/expect/package.json deleted file mode 100644 index 14c0b9e..0000000 --- a/vanilla/node_modules/@vitest/expect/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "@vitest/expect", - "type": "module", - "version": "4.0.18", - "description": "Jest's expect matchers as a Chai plugin", - "license": "MIT", - "funding": "https://opencollective.com/vitest", - "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/expect#readme", - "repository": { - "type": "git", - "url": "git+https://github.com/vitest-dev/vitest.git", - "directory": "packages/expect" - }, - "bugs": { - "url": "https://github.com/vitest-dev/vitest/issues" - }, - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./*": "./*" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "dist" - ], - "dependencies": { - "@standard-schema/spec": "^1.0.0", - "@types/chai": "^5.2.2", - "chai": "^6.2.1", - "tinyrainbow": "^3.0.3", - "@vitest/spy": "4.0.18", - "@vitest/utils": "4.0.18" - }, - "devDependencies": { - "@vitest/runner": "4.0.18" - }, - "scripts": { - "build": "premove dist && rollup -c", - "dev": "rollup -c --watch" - } -}
\ No newline at end of file diff --git a/vanilla/node_modules/@vitest/mocker/LICENSE b/vanilla/node_modules/@vitest/mocker/LICENSE deleted file mode 100644 index 0e5771d..0000000 --- a/vanilla/node_modules/@vitest/mocker/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vanilla/node_modules/@vitest/mocker/README.md b/vanilla/node_modules/@vitest/mocker/README.md deleted file mode 100644 index f23202d..0000000 --- a/vanilla/node_modules/@vitest/mocker/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# @vitest/mocker - -Vitest's module mocker implementation. - -[GitHub](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/EXPORTS.md) diff --git a/vanilla/node_modules/@vitest/mocker/dist/auto-register.d.ts b/vanilla/node_modules/@vitest/mocker/dist/auto-register.d.ts deleted file mode 100644 index 04fa25e..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/auto-register.d.ts +++ /dev/null @@ -1,2 +0,0 @@ - -export { }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/auto-register.js b/vanilla/node_modules/@vitest/mocker/dist/auto-register.js deleted file mode 100644 index 8da252b..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/auto-register.js +++ /dev/null @@ -1,9 +0,0 @@ -import { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js'; -import { registerModuleMocker } from './register.js'; -import './chunk-mocker.js'; -import './index.js'; -import './chunk-registry.js'; -import './chunk-pathe.M-eThtNZ.js'; -import '@vitest/spy'; - -registerModuleMocker(() => new ModuleMockerServerInterceptor()); diff --git a/vanilla/node_modules/@vitest/mocker/dist/automock.d.ts b/vanilla/node_modules/@vitest/mocker/dist/automock.d.ts deleted file mode 100644 index e453d22..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/automock.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import MagicString from 'magic-string'; - -interface AutomockOptions { - /** - * @default "__vitest_mocker__" - */ - globalThisAccessor?: string; -} -declare function automockModule(code: string, mockType: "automock" | "autospy", parse: (code: string) => any, options?: AutomockOptions): MagicString; - -export { automockModule }; -export type { AutomockOptions }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/automock.js b/vanilla/node_modules/@vitest/mocker/dist/automock.js deleted file mode 100644 index c2e2d96..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/automock.js +++ /dev/null @@ -1,3 +0,0 @@ -import 'magic-string'; -export { a as automockModule } from './chunk-automock.js'; -import 'estree-walker'; diff --git a/vanilla/node_modules/@vitest/mocker/dist/browser.d.ts b/vanilla/node_modules/@vitest/mocker/dist/browser.d.ts deleted file mode 100644 index 7048b29..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/browser.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { M as ModuleMockerInterceptor } from './mocker.d-TnKRhz7N.js'; -export { C as CompilerHintsOptions, b as ModuleMocker, a as ModuleMockerCompilerHints, d as ModuleMockerConfig, e as ModuleMockerRPC, R as ResolveIdResult, f as ResolveMockResult, c as createCompilerHints } from './mocker.d-TnKRhz7N.js'; -import { StartOptions, SetupWorker } from 'msw/browser'; -import { M as MockerRegistry, a as MockedModule } from './types.d-B8CCKmHt.js'; -import '@vitest/spy'; -import './index.d-C-sLYZi-.js'; - -interface ModuleMockerMSWInterceptorOptions { - /** - * The identifier to access the globalThis object in the worker. - * This will be injected into the script as is, so make sure it's a valid JS expression. - * @example - * ```js - * // globalThisAccessor: '__my_variable__' produces: - * globalThis[__my_variable__] - * // globalThisAccessor: 'Symbol.for('secret:mocks')' produces: - * globalThis[Symbol.for('secret:mocks')] - * // globalThisAccessor: '"__vitest_mocker__"' (notice quotes) produces: - * globalThis["__vitest_mocker__"] - * ``` - * @default `"__vitest_mocker__"` - */ - globalThisAccessor?: string; - /** - * Options passed down to `msw.setupWorker().start(options)` - */ - mswOptions?: StartOptions; - /** - * A pre-configured `msw.setupWorker` instance. - */ - mswWorker?: SetupWorker; -} -declare class ModuleMockerMSWInterceptor implements ModuleMockerInterceptor { - private readonly options; - protected readonly mocks: MockerRegistry; - private startPromise; - private worker; - constructor(options?: ModuleMockerMSWInterceptorOptions); - register(module: MockedModule): Promise<void>; - delete(url: string): Promise<void>; - invalidate(): Promise<void>; - private resolveManualMock; - protected init(): Promise<SetupWorker>; -} - -declare class ModuleMockerServerInterceptor implements ModuleMockerInterceptor { - register(module: MockedModule): Promise<void>; - delete(id: string): Promise<void>; - invalidate(): Promise<void>; -} - -export { ModuleMockerInterceptor, ModuleMockerMSWInterceptor, ModuleMockerServerInterceptor }; -export type { ModuleMockerMSWInterceptorOptions }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/browser.js b/vanilla/node_modules/@vitest/mocker/dist/browser.js deleted file mode 100644 index 3e83247..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/browser.js +++ /dev/null @@ -1,91 +0,0 @@ -export { M as ModuleMocker, c as createCompilerHints } from './chunk-mocker.js'; -import { M as MockerRegistry } from './chunk-registry.js'; -import { c as createManualModuleSource, a as cleanUrl } from './chunk-utils.js'; -export { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js'; -import './index.js'; -import './chunk-pathe.M-eThtNZ.js'; - -class ModuleMockerMSWInterceptor { - mocks = new MockerRegistry(); - startPromise; - worker; - constructor(options = {}) { - this.options = options; - if (!options.globalThisAccessor) { - options.globalThisAccessor = "\"__vitest_mocker__\""; - } - } - async register(module) { - await this.init(); - this.mocks.add(module); - } - async delete(url) { - await this.init(); - this.mocks.delete(url); - } - async invalidate() { - this.mocks.clear(); - } - async resolveManualMock(mock) { - const exports$1 = Object.keys(await mock.resolve()); - const text = createManualModuleSource(mock.url, exports$1, this.options.globalThisAccessor); - return new Response(text, { headers: { "Content-Type": "application/javascript" } }); - } - async init() { - if (this.worker) { - return this.worker; - } - if (this.startPromise) { - return this.startPromise; - } - const worker = this.options.mswWorker; - this.startPromise = Promise.all([worker ? { setupWorker(handler) { - worker.use(handler); - return worker; - } } : import('msw/browser'), import('msw/core/http')]).then(([{ setupWorker }, { http }]) => { - const worker = setupWorker(http.get(/.+/, async ({ request }) => { - const path = cleanQuery(request.url.slice(location.origin.length)); - if (!this.mocks.has(path)) { - return passthrough(); - } - const mock = this.mocks.get(path); - switch (mock.type) { - case "manual": return this.resolveManualMock(mock); - case "automock": - case "autospy": return Response.redirect(injectQuery(path, `mock=${mock.type}`)); - case "redirect": return Response.redirect(mock.redirect); - default: throw new Error(`Unknown mock type: ${mock.type}`); - } - })); - return worker.start(this.options.mswOptions).then(() => worker); - }).finally(() => { - this.worker = worker; - this.startPromise = undefined; - }); - return await this.startPromise; - } -} -const trailingSeparatorRE = /[?&]$/; -const timestampRE = /\bt=\d{13}&?\b/; -const versionRE = /\bv=\w{8}&?\b/; -function cleanQuery(url) { - return url.replace(timestampRE, "").replace(versionRE, "").replace(trailingSeparatorRE, ""); -} -function passthrough() { - return new Response(null, { - status: 302, - statusText: "Passthrough", - headers: { "x-msw-intention": "passthrough" } - }); -} -const replacePercentageRE = /%/g; -function injectQuery(url, queryToInject) { - // encode percents for consistent behavior with pathToFileURL - // see #2614 for details - const resolvedUrl = new URL(url.replace(replacePercentageRE, "%25"), location.href); - const { search, hash } = resolvedUrl; - const pathname = cleanUrl(url); - return `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`; -} - -export { ModuleMockerMSWInterceptor }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-automock.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-automock.js deleted file mode 100644 index 135ceaf..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/chunk-automock.js +++ /dev/null @@ -1,354 +0,0 @@ -import MagicString from 'magic-string'; -import { walk } from 'estree-walker'; - -const isNodeInPatternWeakSet = new WeakSet(); -function setIsNodeInPattern(node) { - return isNodeInPatternWeakSet.add(node); -} -function isNodeInPattern(node) { - return isNodeInPatternWeakSet.has(node); -} -/** -* Same logic from \@vue/compiler-core & \@vue/compiler-sfc -* Except this is using acorn AST -*/ -function esmWalker(root, { onIdentifier, onImportMeta, onDynamicImport, onCallExpression }) { - const parentStack = []; - const varKindStack = []; - const scopeMap = new WeakMap(); - const identifiers = []; - const setScope = (node, name) => { - let scopeIds = scopeMap.get(node); - if (scopeIds && scopeIds.has(name)) { - return; - } - if (!scopeIds) { - scopeIds = new Set(); - scopeMap.set(node, scopeIds); - } - scopeIds.add(name); - }; - function isInScope(name, parents) { - return parents.some((node) => { - var _scopeMap$get; - return node && ((_scopeMap$get = scopeMap.get(node)) === null || _scopeMap$get === void 0 ? void 0 : _scopeMap$get.has(name)); - }); - } - function handlePattern(p, parentScope) { - if (p.type === "Identifier") { - setScope(parentScope, p.name); - } else if (p.type === "RestElement") { - handlePattern(p.argument, parentScope); - } else if (p.type === "ObjectPattern") { - p.properties.forEach((property) => { - if (property.type === "RestElement") { - setScope(parentScope, property.argument.name); - } else { - handlePattern(property.value, parentScope); - } - }); - } else if (p.type === "ArrayPattern") { - p.elements.forEach((element) => { - if (element) { - handlePattern(element, parentScope); - } - }); - } else if (p.type === "AssignmentPattern") { - handlePattern(p.left, parentScope); - } else { - setScope(parentScope, p.name); - } - } - walk(root, { - enter(node, parent) { - if (node.type === "ImportDeclaration") { - return this.skip(); - } - // track parent stack, skip for "else-if"/"else" branches as acorn nests - // the ast within "if" nodes instead of flattening them - if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) { - parentStack.unshift(parent); - } - // track variable declaration kind stack used by VariableDeclarator - if (node.type === "VariableDeclaration") { - varKindStack.unshift(node.kind); - } - if (node.type === "CallExpression") { - onCallExpression === null || onCallExpression === void 0 ? void 0 : onCallExpression(node); - } - if (node.type === "MetaProperty" && node.meta.name === "import") { - onImportMeta === null || onImportMeta === void 0 ? void 0 : onImportMeta(node); - } else if (node.type === "ImportExpression") { - onDynamicImport === null || onDynamicImport === void 0 ? void 0 : onDynamicImport(node); - } - if (node.type === "Identifier") { - if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) { - // record the identifier, for DFS -> BFS - identifiers.push([node, parentStack.slice(0)]); - } - } else if (node.type === "ClassDeclaration" && node.id) { - // A class declaration name could shadow an import, so add its name to the parent scope - const parentScope = findParentScope(parentStack); - if (parentScope) { - setScope(parentScope, node.id.name); - } - } else if (node.type === "ClassExpression" && node.id) { - // A class expression name could shadow an import, so add its name to the scope - setScope(node, node.id.name); - } else if (isFunctionNode(node)) { - // If it is a function declaration, it could be shadowing an import - // Add its name to the scope so it won't get replaced - if (node.type === "FunctionDeclaration") { - const parentScope = findParentScope(parentStack); - if (parentScope) { - setScope(parentScope, node.id.name); - } - } - // walk function expressions and add its arguments to known identifiers - // so that we don't prefix them - node.params.forEach((p) => { - if (p.type === "ObjectPattern" || p.type === "ArrayPattern") { - handlePattern(p, node); - return; - } - walk(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) { - // skip params default value of destructure - if ((parent === null || parent === void 0 ? void 0 : parent.type) === "AssignmentPattern" && (parent === null || parent === void 0 ? void 0 : parent.right) === child) { - return this.skip(); - } - if (child.type !== "Identifier") { - return; - } - // do not record as scope variable if is a destructuring keyword - if (isStaticPropertyKey(child, parent)) { - return; - } - // do not record if this is a default value - // assignment of a destructuring variable - if ((parent === null || parent === void 0 ? void 0 : parent.type) === "TemplateLiteral" && (parent === null || parent === void 0 ? void 0 : parent.expressions.includes(child)) || (parent === null || parent === void 0 ? void 0 : parent.type) === "CallExpression" && (parent === null || parent === void 0 ? void 0 : parent.callee) === child) { - return; - } - setScope(node, child.name); - } }); - }); - } else if (node.type === "Property" && parent.type === "ObjectPattern") { - // mark property in destructuring pattern - setIsNodeInPattern(node); - } else if (node.type === "VariableDeclarator") { - const parentFunction = findParentScope(parentStack, varKindStack[0] === "var"); - if (parentFunction) { - handlePattern(node.id, parentFunction); - } - } else if (node.type === "CatchClause" && node.param) { - handlePattern(node.param, node); - } - }, - leave(node, parent) { - // untrack parent stack from above - if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) { - parentStack.shift(); - } - if (node.type === "VariableDeclaration") { - varKindStack.shift(); - } - } - }); - // emit the identifier events in BFS so the hoisted declarations - // can be captured correctly - identifiers.forEach(([node, stack]) => { - if (!isInScope(node.name, stack)) { - const parent = stack[0]; - const grandparent = stack[1]; - const hasBindingShortcut = isStaticProperty(parent) && parent.shorthand && (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)); - const classDeclaration = parent.type === "PropertyDefinition" && (grandparent === null || grandparent === void 0 ? void 0 : grandparent.type) === "ClassBody" || parent.type === "ClassDeclaration" && node === parent.superClass; - const classExpression = parent.type === "ClassExpression" && node === parent.id; - onIdentifier === null || onIdentifier === void 0 ? void 0 : onIdentifier(node, { - hasBindingShortcut, - classDeclaration, - classExpression - }, stack); - } - }); -} -function isRefIdentifier(id, parent, parentStack) { - // declaration id - if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) { - return false; - } - if (isFunctionNode(parent)) { - // function declaration/expression id - if (parent.id === id) { - return false; - } - // params list - if (parent.params.includes(id)) { - return false; - } - } - // class method name - if (parent.type === "MethodDefinition" && !parent.computed) { - return false; - } - // property key - if (isStaticPropertyKey(id, parent)) { - return false; - } - // object destructuring pattern - if (isNodeInPattern(parent) && parent.value === id) { - return false; - } - // non-assignment array destructuring pattern - if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) { - return false; - } - // member expression property - if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) { - return false; - } - if (parent.type === "ExportSpecifier") { - return false; - } - // is a special keyword but parsed as identifier - if (id.name === "arguments") { - return false; - } - return true; -} -function isStaticProperty(node) { - return node && node.type === "Property" && !node.computed; -} -function isStaticPropertyKey(node, parent) { - return isStaticProperty(parent) && parent.key === node; -} -const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/; -function isFunctionNode(node) { - return functionNodeTypeRE.test(node.type); -} -const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/; -function isBlock(node) { - return blockNodeTypeRE.test(node.type); -} -function findParentScope(parentStack, isVar = false) { - return parentStack.find(isVar ? isFunctionNode : isBlock); -} -function isInDestructuringAssignment(parent, parentStack) { - if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) { - return parentStack.some((i) => i.type === "AssignmentExpression"); - } - return false; -} -function getArbitraryModuleIdentifier(node) { - return node.type === "Identifier" ? node.name : node.raw; -} - -// TODO: better source map replacement -function automockModule(code, mockType, parse, options = {}) { - const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\""; - const ast = parse(code); - const m = new MagicString(code); - const allSpecifiers = []; - let importIndex = 0; - for (const _node of ast.body) { - if (_node.type === "ExportAllDeclaration") { - throw new Error(`automocking files with \`export *\` is not supported in browser mode because it cannot be statically analysed`); - } - if (_node.type === "ExportNamedDeclaration") { - const node = _node; - const declaration = node.declaration; - function traversePattern(expression) { - // export const test = '1' - if (expression.type === "Identifier") { - allSpecifiers.push({ name: expression.name }); - } else if (expression.type === "ArrayPattern") { - expression.elements.forEach((element) => { - if (!element) { - return; - } - traversePattern(element); - }); - } else if (expression.type === "ObjectPattern") { - expression.properties.forEach((property) => { - // export const { ...rest } = {} - if (property.type === "RestElement") { - traversePattern(property); - } else if (property.type === "Property") { - traversePattern(property.value); - } else ; - }); - } else if (expression.type === "RestElement") { - traversePattern(expression.argument); - } else if (expression.type === "AssignmentPattern") { - throw new Error(`AssignmentPattern is not supported. Please open a new bug report.`); - } else if (expression.type === "MemberExpression") { - throw new Error(`MemberExpression is not supported. Please open a new bug report.`); - } else ; - } - if (declaration) { - if (declaration.type === "FunctionDeclaration") { - allSpecifiers.push({ name: declaration.id.name }); - } else if (declaration.type === "VariableDeclaration") { - declaration.declarations.forEach((declaration) => { - traversePattern(declaration.id); - }); - } else if (declaration.type === "ClassDeclaration") { - allSpecifiers.push({ name: declaration.id.name }); - } else ; - m.remove(node.start, declaration.start); - } - const specifiers = node.specifiers || []; - const source = node.source; - if (!source && specifiers.length) { - specifiers.forEach((specifier) => { - allSpecifiers.push({ - alias: getArbitraryModuleIdentifier(specifier.exported), - name: getArbitraryModuleIdentifier(specifier.local) - }); - }); - m.remove(node.start, node.end); - } else if (source && specifiers.length) { - const importNames = []; - specifiers.forEach((specifier) => { - const importedName = `__vitest_imported_${importIndex++}__`; - importNames.push([getArbitraryModuleIdentifier(specifier.local), importedName]); - allSpecifiers.push({ - name: importedName, - alias: getArbitraryModuleIdentifier(specifier.exported) - }); - }); - const importString = `import { ${importNames.map(([name, alias]) => `${name} as ${alias}`).join(", ")} } from '${source.value}'`; - m.overwrite(node.start, node.end, importString); - } - } - if (_node.type === "ExportDefaultDeclaration") { - const node = _node; - const declaration = node.declaration; - allSpecifiers.push({ - name: "__vitest_default", - alias: "default" - }); - m.overwrite(node.start, declaration.start, `const __vitest_default = `); - } - } - const moduleObject = ` -const __vitest_current_es_module__ = { - __esModule: true, - ${allSpecifiers.map(({ name }) => `["${name}"]: ${name},`).join("\n ")} -} -const __vitest_mocked_module__ = globalThis[${globalThisAccessor}].mockObject(__vitest_current_es_module__, "${mockType}") -`; - const assigning = allSpecifiers.map(({ name }, index) => { - return `const __vitest_mocked_${index}__ = __vitest_mocked_module__["${name}"]`; - }).join("\n"); - const redeclarations = allSpecifiers.map(({ name, alias }, index) => { - return ` __vitest_mocked_${index}__ as ${alias || name},`; - }).join("\n"); - const specifiersExports = ` -export { -${redeclarations} -} -`; - m.append(moduleObject + assigning + specifiersExports); - return m; -} - -export { automockModule as a, esmWalker as e }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js deleted file mode 100644 index 4b472cc..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/chunk-interceptor-native.js +++ /dev/null @@ -1,15 +0,0 @@ -import { r as rpc } from './chunk-mocker.js'; - -class ModuleMockerServerInterceptor { - async register(module) { - await rpc("vitest:interceptor:register", module.toJSON()); - } - async delete(id) { - await rpc("vitest:interceptor:delete", id); - } - async invalidate() { - await rpc("vitest:interceptor:invalidate"); - } -} - -export { ModuleMockerServerInterceptor as M }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-mocker.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-mocker.js deleted file mode 100644 index d86b758..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/chunk-mocker.js +++ /dev/null @@ -1,521 +0,0 @@ -import { mockObject } from './index.js'; -import { M as MockerRegistry, R as RedirectedModule, A as AutomockedModule } from './chunk-registry.js'; -import { e as extname, j as join } from './chunk-pathe.M-eThtNZ.js'; - -/** -* Get original stacktrace without source map support the most performant way. -* - Create only 1 stack frame. -* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). -*/ -function createSimpleStackTrace(options) { - const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {}; - const limit = Error.stackTraceLimit; - const prepareStackTrace = Error.prepareStackTrace; - Error.stackTraceLimit = stackTraceLimit; - Error.prepareStackTrace = (e) => e.stack; - const err = new Error(message); - const stackTrace = err.stack || ""; - Error.prepareStackTrace = prepareStackTrace; - Error.stackTraceLimit = limit; - return stackTrace; -} - -const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; -function normalizeWindowsPath(input = "") { - if (!input) { - return input; - } - return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); -} -const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; -function cwd() { - if (typeof process !== "undefined" && typeof process.cwd === "function") { - 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); -}; - -var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var intToChar = new Uint8Array(64); -var charToInt = new Uint8Array(128); -for (let i = 0; i < chars.length; i++) { - const c = chars.charCodeAt(i); - intToChar[i] = c; - charToInt[c] = i; -} -const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m; -const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/; -function extractLocation(urlLike) { - // Fail-fast but return locations like "(native)" - if (!urlLike.includes(":")) { - return [urlLike]; - } - const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; - const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); - if (!parts) { - return [urlLike]; - } - let url = parts[1]; - if (url.startsWith("async ")) { - url = url.slice(6); - } - if (url.startsWith("http:") || url.startsWith("https:")) { - const urlObj = new URL(url); - urlObj.searchParams.delete("import"); - urlObj.searchParams.delete("browserv"); - url = urlObj.pathname + urlObj.hash + urlObj.search; - } - if (url.startsWith("/@fs/")) { - const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url); - url = url.slice(isWindows ? 5 : 4); - } - return [ - url, - parts[2] || undefined, - parts[3] || undefined - ]; -} -function parseSingleFFOrSafariStack(raw) { - let line = raw.trim(); - if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { - return null; - } - if (line.includes(" > eval")) { - line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); - } - // Early return for lines that don't look like Firefox/Safari stack traces - // Firefox/Safari stack traces must contain '@' and should have location info after it - if (!line.includes("@")) { - return null; - } - // Find the correct @ that separates function name from location - // For cases like '@https://@fs/path' or 'functionName@https://@fs/path' - // we need to find the first @ that precedes a valid location (containing :) - let atIndex = -1; - let locationPart = ""; - let functionName; - // Try each @ from left to right to find the one that gives us a valid location - for (let i = 0; i < line.length; i++) { - if (line[i] === "@") { - const candidateLocation = line.slice(i + 1); - // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1") - if (candidateLocation.includes(":") && candidateLocation.length >= 3) { - atIndex = i; - locationPart = candidateLocation; - functionName = i > 0 ? line.slice(0, i) : undefined; - break; - } - } - } - // Validate we found a valid location with minimum length (filename:line format) - if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) { - return null; - } - const [url, lineNumber, columnNumber] = extractLocation(locationPart); - if (!url || !lineNumber || !columnNumber) { - return null; - } - return { - file: url, - method: functionName || "", - line: Number.parseInt(lineNumber), - column: Number.parseInt(columnNumber) - }; -} -function parseSingleStack(raw) { - const line = raw.trim(); - if (!CHROME_IE_STACK_REGEXP.test(line)) { - return parseSingleFFOrSafariStack(line); - } - return parseSingleV8Stack(line); -} -// Based on https://github.com/stacktracejs/error-stack-parser -// Credit to stacktracejs -function parseSingleV8Stack(raw) { - let line = raw.trim(); - if (!CHROME_IE_STACK_REGEXP.test(line)) { - return null; - } - 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+/, ""); - // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in - // case it has spaces in it, as the string is split on \s+ later on - const location = sanitizedLine.match(/ (\(.+\)$)/); - // remove the parenthesized location from the line, if it was matched - sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; - // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine - // because this line doesn't have function name - const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); - let method = location && sanitizedLine || ""; - let file = url && ["eval", "<anonymous>"].includes(url) ? undefined : url; - if (!file || !lineNumber || !columnNumber) { - return null; - } - if (method.startsWith("async ")) { - method = method.slice(6); - } - if (file.startsWith("file://")) { - file = file.slice(7); - } - // normalize Windows path (\ -> /) - file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file); - if (method) { - method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, ""); - } - return { - method, - file, - line: Number.parseInt(lineNumber), - column: Number.parseInt(columnNumber) - }; -} - -function createCompilerHints(options) { - const globalThisAccessor = (options === null || options === void 0 ? void 0 : options.globalThisKey) || "__vitest_mocker__"; - function _mocker() { - // @ts-expect-error injected by the plugin - return typeof globalThis[globalThisAccessor] !== "undefined" ? globalThis[globalThisAccessor] : new Proxy({}, { get(_, name) { - throw new Error("Vitest mocker was not initialized in this environment. " + `vi.${String(name)}() is forbidden.`); - } }); - } - return { - hoisted(factory) { - if (typeof factory !== "function") { - throw new TypeError(`vi.hoisted() expects a function, but received a ${typeof factory}`); - } - return factory(); - }, - mock(path, factory) { - if (typeof path !== "string") { - throw new TypeError(`vi.mock() expects a string path, but received a ${typeof path}`); - } - const importer = getImporter("mock"); - _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory); - }, - unmock(path) { - if (typeof path !== "string") { - throw new TypeError(`vi.unmock() expects a string path, but received a ${typeof path}`); - } - _mocker().queueUnmock(path, getImporter("unmock")); - }, - doMock(path, factory) { - if (typeof path !== "string") { - throw new TypeError(`vi.doMock() expects a string path, but received a ${typeof path}`); - } - const importer = getImporter("doMock"); - _mocker().queueMock(path, importer, typeof factory === "function" ? () => factory(() => _mocker().importActual(path, importer)) : factory); - }, - doUnmock(path) { - if (typeof path !== "string") { - throw new TypeError(`vi.doUnmock() expects a string path, but received a ${typeof path}`); - } - _mocker().queueUnmock(path, getImporter("doUnmock")); - }, - async importActual(path) { - return _mocker().importActual(path, getImporter("importActual")); - }, - async importMock(path) { - return _mocker().importMock(path, getImporter("importMock")); - } - }; -} -function getImporter(name) { - const stackTrace = /* @__PURE__ */ createSimpleStackTrace({ stackTraceLimit: 5 }); - const stackArray = stackTrace.split("\n"); - // if there is no message in a stack trace, use the item - 1 - const importerStackIndex = stackArray.findIndex((stack) => { - return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`); - }); - const stack = /* @__PURE__ */ parseSingleStack(stackArray[importerStackIndex + 1]); - return (stack === null || stack === void 0 ? void 0 : stack.file) || ""; -} - -const hot = import.meta.hot || { - on: warn, - off: warn, - send: warn -}; -function warn() { - console.warn("Vitest mocker cannot work if Vite didn't establish WS connection."); -} -function rpc(event, data) { - hot.send(event, data); - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - reject(new Error(`Failed to resolve ${event} in time`)); - }, 5e3); - hot.on(`${event}:result`, function r(data) { - resolve(data); - clearTimeout(timeout); - hot.off(`${event}:result`, r); - }); - }); -} - -const { now } = Date; -class ModuleMocker { - registry = new MockerRegistry(); - queue = new Set(); - mockedIds = new Set(); - constructor(interceptor, rpc, createMockInstance, config) { - this.interceptor = interceptor; - this.rpc = rpc; - this.createMockInstance = createMockInstance; - this.config = config; - } - async prepare() { - if (!this.queue.size) { - return; - } - await Promise.all([...this.queue.values()]); - } - async resolveFactoryModule(id) { - const mock = this.registry.get(id); - if (!mock || mock.type !== "manual") { - throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`); - } - const result = await mock.resolve(); - return result; - } - getFactoryModule(id) { - const mock = this.registry.get(id); - if (!mock || mock.type !== "manual") { - throw new Error(`Mock ${id} wasn't registered. This is probably a Vitest error. Please, open a new issue with reproduction.`); - } - if (!mock.cache) { - throw new Error(`Mock ${id} wasn't resolved. This is probably a Vitest error. Please, open a new issue with reproduction.`); - } - return mock.cache; - } - async invalidate() { - const ids = Array.from(this.mockedIds); - if (!ids.length) { - return; - } - await this.rpc.invalidate(ids); - await this.interceptor.invalidate(); - this.registry.clear(); - } - async importActual(id, importer) { - const resolved = await this.rpc.resolveId(id, importer); - if (resolved == null) { - throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`); - } - const ext = extname(resolved.id); - const url = new URL(resolved.url, location.href); - const query = `_vitest_original&ext${ext}`; - const actualUrl = `${url.pathname}${url.search ? `${url.search}&${query}` : `?${query}`}${url.hash}`; - return this.wrapDynamicImport(() => import( - /* @vite-ignore */ - actualUrl -)).then((mod) => { - if (!resolved.optimized || typeof mod.default === "undefined") { - return mod; - } - // vite injects this helper for optimized modules, so we try to follow the same behavior - const m = mod.default; - return (m === null || m === void 0 ? void 0 : m.__esModule) ? m : { - ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, - default: m - }; - }); - } - async importMock(rawId, importer) { - await this.prepare(); - const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" }); - const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl)); - let mock = this.registry.get(mockUrl); - if (!mock) { - if (redirectUrl) { - const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString(); - mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect); - } else { - mock = new AutomockedModule(rawId, resolvedId, mockUrl); - } - } - if (mock.type === "manual") { - return await mock.resolve(); - } - if (mock.type === "automock" || mock.type === "autospy") { - const url = new URL(`/@id/${resolvedId}`, location.href); - const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`; - const moduleObject = await import( - /* @vite-ignore */ - `${url.pathname}${query}&mock=${mock.type}${url.hash}` -); - return this.mockObject(moduleObject, mock.type); - } - return import( - /* @vite-ignore */ - mock.redirect -); - } - mockObject(object, moduleType = "automock") { - return mockObject({ - globalConstructors: { - Object, - Function, - Array, - Map, - RegExp - }, - createMockInstance: this.createMockInstance, - type: moduleType - }, object); - } - queueMock(rawId, importer, factoryOrOptions) { - const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : (factoryOrOptions === null || factoryOrOptions === void 0 ? void 0 : factoryOrOptions.spy) ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => { - const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl)); - this.mockedIds.add(resolvedId); - const factory = typeof factoryOrOptions === "function" ? async () => { - const data = await factoryOrOptions(); - // vite wraps all external modules that have "needsInterop" in a function that - // merges all exports from default into the module object - return needsInterop ? { default: data } : data; - } : undefined; - const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString() : null; - let module; - if (mockType === "manual") { - module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory); - } else if (mockType === "autospy") { - module = this.registry.register("autospy", rawId, resolvedId, mockUrl); - } else if (mockType === "redirect") { - module = this.registry.register("redirect", rawId, resolvedId, mockUrl, mockRedirect); - } else { - module = this.registry.register("automock", rawId, resolvedId, mockUrl); - } - await this.interceptor.register(module); - }).finally(() => { - this.queue.delete(promise); - }); - this.queue.add(promise); - } - queueUnmock(id, importer) { - const promise = this.rpc.resolveId(id, importer).then(async (resolved) => { - if (!resolved) { - return; - } - const mockUrl = this.resolveMockPath(cleanVersion(resolved.url)); - this.mockedIds.add(resolved.id); - this.registry.delete(mockUrl); - await this.interceptor.delete(mockUrl); - }).finally(() => { - this.queue.delete(promise); - }); - this.queue.add(promise); - } - // We need to await mock registration before importing the actual module - // In case there is a mocked module in the import chain - wrapDynamicImport(moduleFactory) { - if (typeof moduleFactory === "function") { - const promise = new Promise((resolve, reject) => { - this.prepare().finally(() => { - moduleFactory().then(resolve, reject); - }); - }); - return promise; - } - return moduleFactory; - } - resolveMockPath(path) { - const config = this.config; - const fsRoot = join("/@fs/", config.root); - // URL can be /file/path.js, but path is resolved to /file/path - if (path.startsWith(config.root)) { - return path.slice(config.root.length); - } - if (path.startsWith(fsRoot)) { - return path.slice(fsRoot.length); - } - return path; - } -} -const versionRegexp = /(\?|&)v=\w{8}/; -function cleanVersion(url) { - return url.replace(versionRegexp, ""); -} - -export { ModuleMocker as M, createCompilerHints as c, hot as h, rpc as r }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js deleted file mode 100644 index 11a98f0..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/chunk-pathe.M-eThtNZ.js +++ /dev/null @@ -1,174 +0,0 @@ -const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; -function normalizeWindowsPath(input = "") { - if (!input) { - return input; - } - return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); -} - -const _UNC_REGEX = /^[/\\]{2}/; -const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; -const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; -const _EXTNAME_RE = /.(\.[^./]+|\.)$/; -const normalize = function(path) { - if (path.length === 0) { - return "."; - } - path = normalizeWindowsPath(path); - const isUNCPath = path.match(_UNC_REGEX); - const isPathAbsolute = isAbsolute(path); - const trailingSeparator = path[path.length - 1] === "/"; - path = normalizeString(path, !isPathAbsolute); - if (path.length === 0) { - if (isPathAbsolute) { - return "/"; - } - return trailingSeparator ? "./" : "."; - } - if (trailingSeparator) { - path += "/"; - } - if (_DRIVE_LETTER_RE.test(path)) { - path += "/"; - } - if (isUNCPath) { - if (!isPathAbsolute) { - return `//./${path}`; - } - return `//${path}`; - } - return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; -}; -const join = function(...segments) { - let path = ""; - for (const seg of segments) { - if (!seg) { - continue; - } - if (path.length > 0) { - const pathTrailing = path[path.length - 1] === "/"; - const segLeading = seg[0] === "/"; - const both = pathTrailing && segLeading; - if (both) { - path += seg.slice(1); - } else { - path += pathTrailing || segLeading ? seg : `/${seg}`; - } - } else { - path += seg; - } - } - return normalize(path); -}; -function cwd() { - if (typeof process !== "undefined" && typeof process.cwd === "function") { - 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 extname = function(p) { - if (p === "..") return ""; - const match = _EXTNAME_RE.exec(normalizeWindowsPath(p)); - return match && match[1] || ""; -}; -const dirname = function(p) { - const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); - if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { - segments[0] += "/"; - } - return segments.join("/") || (isAbsolute(p) ? "/" : "."); -}; -const basename = function(p, extension) { - const segments = normalizeWindowsPath(p).split("/"); - let lastSegment = ""; - for (let i = segments.length - 1; i >= 0; i--) { - const val = segments[i]; - if (val) { - lastSegment = val; - break; - } - } - return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; -}; - -export { basename as b, dirname as d, extname as e, isAbsolute as i, join as j, resolve as r }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-registry.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-registry.js deleted file mode 100644 index fe0e803..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/chunk-registry.js +++ /dev/null @@ -1,185 +0,0 @@ -class MockerRegistry { - registryByUrl = new Map(); - registryById = new Map(); - clear() { - this.registryByUrl.clear(); - this.registryById.clear(); - } - keys() { - return this.registryByUrl.keys(); - } - add(mock) { - this.registryByUrl.set(mock.url, mock); - this.registryById.set(mock.id, mock); - } - register(typeOrEvent, raw, id, url, factoryOrRedirect) { - const type = typeof typeOrEvent === "object" ? typeOrEvent.type : typeOrEvent; - if (typeof typeOrEvent === "object") { - const event = typeOrEvent; - if (event instanceof AutomockedModule || event instanceof AutospiedModule || event instanceof ManualMockedModule || event instanceof RedirectedModule) { - throw new TypeError(`[vitest] Cannot register a mock that is already defined. ` + `Expected a JSON representation from \`MockedModule.toJSON\`, instead got "${event.type}". ` + `Use "registry.add()" to update a mock instead.`); - } - if (event.type === "automock") { - const module = AutomockedModule.fromJSON(event); - this.add(module); - return module; - } else if (event.type === "autospy") { - const module = AutospiedModule.fromJSON(event); - this.add(module); - return module; - } else if (event.type === "redirect") { - const module = RedirectedModule.fromJSON(event); - this.add(module); - return module; - } else if (event.type === "manual") { - throw new Error(`Cannot set serialized manual mock. Define a factory function manually with \`ManualMockedModule.fromJSON()\`.`); - } else { - throw new Error(`Unknown mock type: ${event.type}`); - } - } - if (typeof raw !== "string") { - throw new TypeError("[vitest] Mocks require a raw string."); - } - if (typeof url !== "string") { - throw new TypeError("[vitest] Mocks require a url string."); - } - if (typeof id !== "string") { - throw new TypeError("[vitest] Mocks require an id string."); - } - if (type === "manual") { - if (typeof factoryOrRedirect !== "function") { - throw new TypeError("[vitest] Manual mocks require a factory function."); - } - const mock = new ManualMockedModule(raw, id, url, factoryOrRedirect); - this.add(mock); - return mock; - } else if (type === "automock" || type === "autospy") { - const mock = type === "automock" ? new AutomockedModule(raw, id, url) : new AutospiedModule(raw, id, url); - this.add(mock); - return mock; - } else if (type === "redirect") { - if (typeof factoryOrRedirect !== "string") { - throw new TypeError("[vitest] Redirect mocks require a redirect string."); - } - const mock = new RedirectedModule(raw, id, url, factoryOrRedirect); - this.add(mock); - return mock; - } else { - throw new Error(`[vitest] Unknown mock type: ${type}`); - } - } - delete(id) { - this.registryByUrl.delete(id); - } - deleteById(id) { - this.registryById.delete(id); - } - get(id) { - return this.registryByUrl.get(id); - } - getById(id) { - return this.registryById.get(id); - } - has(id) { - return this.registryByUrl.has(id); - } -} -class AutomockedModule { - type = "automock"; - constructor(raw, id, url) { - this.raw = raw; - this.id = id; - this.url = url; - } - static fromJSON(data) { - return new AutospiedModule(data.raw, data.id, data.url); - } - toJSON() { - return { - type: this.type, - url: this.url, - raw: this.raw, - id: this.id - }; - } -} -class AutospiedModule { - type = "autospy"; - constructor(raw, id, url) { - this.raw = raw; - this.id = id; - this.url = url; - } - static fromJSON(data) { - return new AutospiedModule(data.raw, data.id, data.url); - } - toJSON() { - return { - type: this.type, - url: this.url, - id: this.id, - raw: this.raw - }; - } -} -class RedirectedModule { - type = "redirect"; - constructor(raw, id, url, redirect) { - this.raw = raw; - this.id = id; - this.url = url; - this.redirect = redirect; - } - static fromJSON(data) { - return new RedirectedModule(data.raw, data.id, data.url, data.redirect); - } - toJSON() { - return { - type: this.type, - url: this.url, - raw: this.raw, - id: this.id, - redirect: this.redirect - }; - } -} -class ManualMockedModule { - cache; - type = "manual"; - constructor(raw, id, url, factory) { - this.raw = raw; - this.id = id; - this.url = url; - this.factory = factory; - } - async resolve() { - if (this.cache) { - return this.cache; - } - let exports$1; - try { - exports$1 = await this.factory(); - } catch (err) { - const vitestError = new Error("[vitest] There was an error when mocking a module. " + "If you are using \"vi.mock\" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. " + "Read more: https://vitest.dev/api/vi.html#vi-mock"); - vitestError.cause = err; - throw vitestError; - } - if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) { - throw new TypeError(`[vitest] vi.mock("${this.raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`); - } - return this.cache = exports$1; - } - static fromJSON(data, factory) { - return new ManualMockedModule(data.raw, data.id, data.url, factory); - } - toJSON() { - return { - type: this.type, - url: this.url, - id: this.id, - raw: this.raw - }; - } -} - -export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, ManualMockedModule as a, AutospiedModule as b }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/chunk-utils.js b/vanilla/node_modules/@vitest/mocker/dist/chunk-utils.js deleted file mode 100644 index de1b7e4..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/chunk-utils.js +++ /dev/null @@ -1,16 +0,0 @@ -const postfixRE = /[?#].*$/; -function cleanUrl(url) { - return url.replace(postfixRE, ""); -} -function createManualModuleSource(moduleUrl, exports$1, globalAccessor = "\"__vitest_mocker__\"") { - const source = `const module = globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}");`; - const keys = exports$1.map((name) => { - if (name === "default") { - return `export default module["default"];`; - } - return `export const ${name} = module["${name}"];`; - }).join("\n"); - return `${source}\n${keys}`; -} - -export { cleanUrl as a, createManualModuleSource as c }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts b/vanilla/node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts deleted file mode 100644 index cad0899..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/index.d-C-sLYZi-.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import './types.d-B8CCKmHt.js'; - -type Key = string | symbol; -type CreateMockInstanceProcedure = (options?: { - prototypeMembers?: (string | symbol)[]; - name?: string | symbol; - originalImplementation?: (...args: any[]) => any; - keepMembersImplementation?: boolean; -}) => any; -interface MockObjectOptions { - type: "automock" | "autospy"; - globalConstructors: GlobalConstructors; - createMockInstance: CreateMockInstanceProcedure; -} -declare function mockObject(options: MockObjectOptions, object: Record<Key, any>, mockExports?: Record<Key, any>): Record<Key, any>; -interface GlobalConstructors { - Object: ObjectConstructor; - Function: FunctionConstructor; - RegExp: RegExpConstructor; - Array: ArrayConstructor; - Map: MapConstructor; -} - -export { mockObject as m }; -export type { CreateMockInstanceProcedure as C, GlobalConstructors as G, MockObjectOptions as M }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/index.d.ts b/vanilla/node_modules/@vitest/mocker/dist/index.d.ts deleted file mode 100644 index 107b5fb..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-C-sLYZi-.js'; -export { A as AutomockedModule, h as AutomockedModuleSerialized, f as AutospiedModule, i as AutospiedModuleSerialized, g as ManualMockedModule, j as ManualMockedModuleSerialized, a as MockedModule, k as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, l as RedirectedModuleSerialized, e as ServerIdResolution, S as ServerMockResolution } from './types.d-B8CCKmHt.js'; diff --git a/vanilla/node_modules/@vitest/mocker/dist/index.js b/vanilla/node_modules/@vitest/mocker/dist/index.js deleted file mode 100644 index 79c5c9a..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/index.js +++ /dev/null @@ -1,185 +0,0 @@ -export { A as AutomockedModule, b as AutospiedModule, a as ManualMockedModule, M as MockerRegistry, R as RedirectedModule } from './chunk-registry.js'; - -function mockObject(options, object, mockExports = {}) { - const finalizers = new Array(); - const refs = new RefTracker(); - const define = (container, key, value) => { - try { - container[key] = value; - return true; - } catch { - return false; - } - }; - const createMock = (currentValue) => { - if (!options.createMockInstance) { - throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction."); - } - const createMockInstance = options.createMockInstance; - const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : []; - return createMockInstance({ - name: currentValue.name, - prototypeMembers, - originalImplementation: options.type === "autospy" ? currentValue : undefined, - keepMembersImplementation: options.type === "autospy" - }); - }; - const mockPropertiesOf = (container, newContainer) => { - const containerType = getType(container); - const isModule = containerType === "Module" || !!container.__esModule; - for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) { - // Modules define their exports as getters. We want to process those. - if (!isModule && descriptor.get) { - try { - if (options.type === "autospy") { - Object.defineProperty(newContainer, property, descriptor); - } else { - Object.defineProperty(newContainer, property, { - configurable: descriptor.configurable, - enumerable: descriptor.enumerable, - get: () => {}, - set: descriptor.set ? () => {} : undefined - }); - } - } catch {} - continue; - } - // Skip special read-only props, we don't want to mess with those. - if (isReadonlyProp(container[property], property)) { - continue; - } - const value = container[property]; - // Special handling of references we've seen before to prevent infinite - // recursion in circular objects. - const refId = refs.getId(value); - if (refId !== undefined) { - finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId))); - continue; - } - const type = getType(value); - if (Array.isArray(value)) { - if (options.type === "automock") { - define(newContainer, property, []); - } else { - const array = value.map((value) => { - if (value && typeof value === "object") { - const newObject = {}; - mockPropertiesOf(value, newObject); - return newObject; - } - if (typeof value === "function") { - return createMock(value); - } - return value; - }); - define(newContainer, property, array); - } - continue; - } - const isFunction = type.includes("Function") && typeof value === "function"; - if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") { - define(newContainer, property, value); - continue; - } - // Sometimes this assignment fails for some unknown reason. If it does, - // just move along. - if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) { - continue; - } - if (isFunction) { - const mock = createMock(newContainer[property]); - newContainer[property] = mock; - } - refs.track(value, newContainer[property]); - mockPropertiesOf(value, newContainer[property]); - } - }; - const mockedObject = mockExports; - mockPropertiesOf(object, mockedObject); - // Plug together refs - for (const finalizer of finalizers) { - finalizer(); - } - return mockedObject; -} -class RefTracker { - idMap = new Map(); - mockedValueMap = new Map(); - getId(value) { - return this.idMap.get(value); - } - getMockedValue(id) { - return this.mockedValueMap.get(id); - } - track(originalValue, mockedValue) { - const newId = this.idMap.size; - this.idMap.set(originalValue, newId); - this.mockedValueMap.set(newId, mockedValue); - return newId; - } -} -function getType(value) { - return Object.prototype.toString.apply(value).slice(8, -1); -} -function isReadonlyProp(object, prop) { - if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") { - const typeName = getType(object); - return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction"; - } - if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") { - return getType(object) === "RegExp"; - } - return false; -} -function getAllMockableProperties(obj, isModule, constructors) { - const { Map, Object, Function, RegExp, Array } = constructors; - const allProps = new Map(); - let curr = obj; - do { - // we don't need properties from these - if (curr === Object.prototype || curr === Function.prototype || curr === RegExp.prototype) { - break; - } - collectOwnProperties(curr, (key) => { - const descriptor = Object.getOwnPropertyDescriptor(curr, key); - if (descriptor) { - allProps.set(key, { - key, - descriptor - }); - } - }); - } while (curr = Object.getPrototypeOf(curr)); - // default is not specified in ownKeys, if module is interoped - if (isModule && !allProps.has("default") && "default" in obj) { - const descriptor = Object.getOwnPropertyDescriptor(obj, "default"); - if (descriptor) { - allProps.set("default", { - key: "default", - descriptor - }); - } - } - return Array.from(allProps.values()); -} -function collectOwnProperties(obj, collector) { - const collect = typeof collector === "function" ? collector : (key) => collector.add(key); - Object.getOwnPropertyNames(obj).forEach(collect); - Object.getOwnPropertySymbols(obj).forEach(collect); -} -function collectFunctionProperties(prototype) { - const properties = new Set(); - collectOwnProperties(prototype, (prop) => { - const descriptor = Object.getOwnPropertyDescriptor(prototype, prop); - if (!descriptor || descriptor.get) { - return; - } - const type = getType(descriptor.value); - if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) { - properties.add(prop); - } - }); - return Array.from(properties); -} - -export { mockObject }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts b/vanilla/node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts deleted file mode 100644 index db47e96..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/mocker.d-TnKRhz7N.d.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { MaybeMockedDeep } from '@vitest/spy'; -import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, M as MockerRegistry, d as MockedModuleType } from './types.d-B8CCKmHt.js'; -import { C as CreateMockInstanceProcedure } from './index.d-C-sLYZi-.js'; - -interface CompilerHintsOptions { - /** - * This is the key used to access the globalThis object in the worker. - * Unlike `globalThisAccessor` in other APIs, this is not injected into the script. - * ```ts - * // globalThisKey: '__my_variable__' produces: - * globalThis['__my_variable__'] - * // globalThisKey: '"__my_variable__"' produces: - * globalThis['"__my_variable__"'] // notice double quotes - * ``` - * @default '__vitest_mocker__' - */ - globalThisKey?: string; -} -interface ModuleMockerCompilerHints { - hoisted: <T>(factory: () => T) => T; - mock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void; - unmock: (path: string | Promise<unknown>) => void; - doMock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void; - doUnmock: (path: string | Promise<unknown>) => void; - importActual: <T>(path: string) => Promise<T>; - importMock: <T>(path: string) => Promise<MaybeMockedDeep<T>>; -} -declare function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints; - -interface ModuleMockerInterceptor { - register: (module: MockedModule) => Promise<void>; - delete: (url: string) => Promise<void>; - invalidate: () => Promise<void>; -} - -declare class ModuleMocker { - private interceptor; - private rpc; - private createMockInstance; - private config; - protected registry: MockerRegistry; - private queue; - private mockedIds; - constructor(interceptor: ModuleMockerInterceptor, rpc: ModuleMockerRPC, createMockInstance: CreateMockInstanceProcedure, config: ModuleMockerConfig); - prepare(): Promise<void>; - resolveFactoryModule(id: string): Promise<Record<string | symbol, any>>; - getFactoryModule(id: string): any; - invalidate(): Promise<void>; - importActual<T>(id: string, importer: string): Promise<T>; - importMock<T>(rawId: string, importer: string): Promise<T>; - mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>; - queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void; - queueUnmock(id: string, importer: string): void; - wrapDynamicImport<T>(moduleFactory: () => Promise<T>): Promise<T>; - private resolveMockPath; -} -interface ResolveIdResult { - id: string; - url: string; - optimized: boolean; -} -interface ResolveMockResult { - mockType: MockedModuleType; - resolvedId: string; - resolvedUrl: string; - redirectUrl?: string | null; - needsInterop?: boolean; -} -interface ModuleMockerRPC { - invalidate: (ids: string[]) => Promise<void>; - resolveId: (id: string, importer: string) => Promise<ResolveIdResult | null>; - resolveMock: (id: string, importer: string, options: { - mock: "spy" | "factory" | "auto"; - }) => Promise<ResolveMockResult>; -} -interface ModuleMockerConfig { - root: string; -} - -export { ModuleMocker as b, createCompilerHints as c }; -export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as d, ModuleMockerRPC as e, ResolveMockResult as f }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/node.d.ts b/vanilla/node_modules/@vitest/mocker/dist/node.d.ts deleted file mode 100644 index 2f9b27c..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/node.d.ts +++ /dev/null @@ -1,800 +0,0 @@ -import { AutomockOptions } from './automock.js'; -export { automockModule } from './automock.js'; -import { Plugin, Rollup, ViteDevServer } from 'vite'; -import { SourceMap } from 'magic-string'; -import { M as MockerRegistry, S as ServerMockResolution, e as ServerIdResolution } from './types.d-B8CCKmHt.js'; -export { findMockRedirect } from './redirect.js'; - -declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string; - -declare function automockPlugin(options?: AutomockOptions): Plugin; - -interface DynamicImportPluginOptions { - /** - * @default `"__vitest_mocker__"` - */ - globalThisAccessor?: string; - filter?: (id: string) => boolean; -} -declare function dynamicImportPlugin(options?: DynamicImportPluginOptions): Plugin; - -// This definition file follows a somewhat unusual format. ESTree allows -// runtime type checks based on the `type` parameter. In order to explain this -// to typescript we want to use discriminated union types: -// https://github.com/Microsoft/TypeScript/pull/9163 -// -// For ESTree this is a bit tricky because the high level interfaces like -// Node or Function are pulling double duty. We want to pass common fields down -// to the interfaces that extend them (like Identifier or -// ArrowFunctionExpression), but you can't extend a type union or enforce -// common fields on them. So we've split the high level interfaces into two -// types, a base type which passes down inherited fields, and a type union of -// all types which extend the base type. Only the type union is exported, and -// the union is how other types refer to the collection of inheriting types. -// -// This makes the definitions file here somewhat more difficult to maintain, -// but it has the notable advantage of making ESTree much easier to use as -// an end user. - -interface BaseNodeWithoutComments { - // Every leaf interface that extends BaseNode must specify a type property. - // The type property should be a string literal. For example, Identifier - // has: `type: "Identifier"` - type: string; - loc?: SourceLocation | null | undefined; - range?: [number, number] | undefined; -} - -interface BaseNode extends BaseNodeWithoutComments { - leadingComments?: Comment[] | undefined; - trailingComments?: Comment[] | undefined; -} - -interface NodeMap { - AssignmentProperty: AssignmentProperty; - CatchClause: CatchClause; - Class: Class; - ClassBody: ClassBody; - Expression: Expression; - Function: Function; - Identifier: Identifier; - Literal: Literal; - MethodDefinition: MethodDefinition; - ModuleDeclaration: ModuleDeclaration; - ModuleSpecifier: ModuleSpecifier; - Pattern: Pattern; - PrivateIdentifier: PrivateIdentifier; - Program: Program; - Property: Property; - PropertyDefinition: PropertyDefinition; - SpreadElement: SpreadElement; - Statement: Statement; - Super: Super; - SwitchCase: SwitchCase; - TemplateElement: TemplateElement; - VariableDeclarator: VariableDeclarator; -} - -type Node$1 = NodeMap[keyof NodeMap]; - -interface Comment extends BaseNodeWithoutComments { - type: "Line" | "Block"; - value: string; -} - -interface SourceLocation { - source?: string | null | undefined; - start: Position; - end: Position; -} - -interface Position { - /** >= 1 */ - line: number; - /** >= 0 */ - column: number; -} - -interface Program extends BaseNode { - type: "Program"; - sourceType: "script" | "module"; - body: Array<Directive | Statement | ModuleDeclaration>; - comments?: Comment[] | undefined; -} - -interface Directive extends BaseNode { - type: "ExpressionStatement"; - expression: Literal; - directive: string; -} - -interface BaseFunction extends BaseNode { - params: Pattern[]; - generator?: boolean | undefined; - async?: boolean | undefined; - // The body is either BlockStatement or Expression because arrow functions - // can have a body that's either. FunctionDeclarations and - // FunctionExpressions have only BlockStatement bodies. - body: BlockStatement | Expression; -} - -type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; - -type Statement = - | ExpressionStatement - | BlockStatement - | StaticBlock - | EmptyStatement - | DebuggerStatement - | WithStatement - | ReturnStatement - | LabeledStatement - | BreakStatement - | ContinueStatement - | IfStatement - | SwitchStatement - | ThrowStatement - | TryStatement - | WhileStatement - | DoWhileStatement - | ForStatement - | ForInStatement - | ForOfStatement - | Declaration; - -interface BaseStatement extends BaseNode {} - -interface EmptyStatement extends BaseStatement { - type: "EmptyStatement"; -} - -interface BlockStatement extends BaseStatement { - type: "BlockStatement"; - body: Statement[]; - innerComments?: Comment[] | undefined; -} - -interface StaticBlock extends Omit<BlockStatement, "type"> { - type: "StaticBlock"; -} - -interface ExpressionStatement extends BaseStatement { - type: "ExpressionStatement"; - expression: Expression; -} - -interface IfStatement extends BaseStatement { - type: "IfStatement"; - test: Expression; - consequent: Statement; - alternate?: Statement | null | undefined; -} - -interface LabeledStatement extends BaseStatement { - type: "LabeledStatement"; - label: Identifier; - body: Statement; -} - -interface BreakStatement extends BaseStatement { - type: "BreakStatement"; - label?: Identifier | null | undefined; -} - -interface ContinueStatement extends BaseStatement { - type: "ContinueStatement"; - label?: Identifier | null | undefined; -} - -interface WithStatement extends BaseStatement { - type: "WithStatement"; - object: Expression; - body: Statement; -} - -interface SwitchStatement extends BaseStatement { - type: "SwitchStatement"; - discriminant: Expression; - cases: SwitchCase[]; -} - -interface ReturnStatement extends BaseStatement { - type: "ReturnStatement"; - argument?: Expression | null | undefined; -} - -interface ThrowStatement extends BaseStatement { - type: "ThrowStatement"; - argument: Expression; -} - -interface TryStatement extends BaseStatement { - type: "TryStatement"; - block: BlockStatement; - handler?: CatchClause | null | undefined; - finalizer?: BlockStatement | null | undefined; -} - -interface WhileStatement extends BaseStatement { - type: "WhileStatement"; - test: Expression; - body: Statement; -} - -interface DoWhileStatement extends BaseStatement { - type: "DoWhileStatement"; - body: Statement; - test: Expression; -} - -interface ForStatement extends BaseStatement { - type: "ForStatement"; - init?: VariableDeclaration | Expression | null | undefined; - test?: Expression | null | undefined; - update?: Expression | null | undefined; - body: Statement; -} - -interface BaseForXStatement extends BaseStatement { - left: VariableDeclaration | Pattern; - right: Expression; - body: Statement; -} - -interface ForInStatement extends BaseForXStatement { - type: "ForInStatement"; -} - -interface DebuggerStatement extends BaseStatement { - type: "DebuggerStatement"; -} - -type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; - -interface BaseDeclaration extends BaseStatement {} - -interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { - type: "FunctionDeclaration"; - /** It is null when a function declaration is a part of the `export default function` statement */ - id: Identifier | null; - body: BlockStatement; -} - -interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { - id: Identifier; -} - -interface VariableDeclaration extends BaseDeclaration { - type: "VariableDeclaration"; - declarations: VariableDeclarator[]; - kind: "var" | "let" | "const" | "using" | "await using"; -} - -interface VariableDeclarator extends BaseNode { - type: "VariableDeclarator"; - id: Pattern; - init?: Expression | null | undefined; -} - -interface ExpressionMap { - ArrayExpression: ArrayExpression; - ArrowFunctionExpression: ArrowFunctionExpression; - AssignmentExpression: AssignmentExpression; - AwaitExpression: AwaitExpression; - BinaryExpression: BinaryExpression; - CallExpression: CallExpression; - ChainExpression: ChainExpression; - ClassExpression: ClassExpression; - ConditionalExpression: ConditionalExpression; - FunctionExpression: FunctionExpression; - Identifier: Identifier; - ImportExpression: ImportExpression; - Literal: Literal; - LogicalExpression: LogicalExpression; - MemberExpression: MemberExpression; - MetaProperty: MetaProperty; - NewExpression: NewExpression; - ObjectExpression: ObjectExpression; - SequenceExpression: SequenceExpression; - TaggedTemplateExpression: TaggedTemplateExpression; - TemplateLiteral: TemplateLiteral; - ThisExpression: ThisExpression; - UnaryExpression: UnaryExpression; - UpdateExpression: UpdateExpression; - YieldExpression: YieldExpression; -} - -type Expression = ExpressionMap[keyof ExpressionMap]; - -interface BaseExpression extends BaseNode {} - -type ChainElement = SimpleCallExpression | MemberExpression; - -interface ChainExpression extends BaseExpression { - type: "ChainExpression"; - expression: ChainElement; -} - -interface ThisExpression extends BaseExpression { - type: "ThisExpression"; -} - -interface ArrayExpression extends BaseExpression { - type: "ArrayExpression"; - elements: Array<Expression | SpreadElement | null>; -} - -interface ObjectExpression extends BaseExpression { - type: "ObjectExpression"; - properties: Array<Property | SpreadElement>; -} - -interface PrivateIdentifier extends BaseNode { - type: "PrivateIdentifier"; - name: string; -} - -interface Property extends BaseNode { - type: "Property"; - key: Expression | PrivateIdentifier; - value: Expression | Pattern; // Could be an AssignmentProperty - kind: "init" | "get" | "set"; - method: boolean; - shorthand: boolean; - computed: boolean; -} - -interface PropertyDefinition extends BaseNode { - type: "PropertyDefinition"; - key: Expression | PrivateIdentifier; - value?: Expression | null | undefined; - computed: boolean; - static: boolean; -} - -interface FunctionExpression extends BaseFunction, BaseExpression { - id?: Identifier | null | undefined; - type: "FunctionExpression"; - body: BlockStatement; -} - -interface SequenceExpression extends BaseExpression { - type: "SequenceExpression"; - expressions: Expression[]; -} - -interface UnaryExpression extends BaseExpression { - type: "UnaryExpression"; - operator: UnaryOperator; - prefix: true; - argument: Expression; -} - -interface BinaryExpression extends BaseExpression { - type: "BinaryExpression"; - operator: BinaryOperator; - left: Expression | PrivateIdentifier; - right: Expression; -} - -interface AssignmentExpression extends BaseExpression { - type: "AssignmentExpression"; - operator: AssignmentOperator; - left: Pattern | MemberExpression; - right: Expression; -} - -interface UpdateExpression extends BaseExpression { - type: "UpdateExpression"; - operator: UpdateOperator; - argument: Expression; - prefix: boolean; -} - -interface LogicalExpression extends BaseExpression { - type: "LogicalExpression"; - operator: LogicalOperator; - left: Expression; - right: Expression; -} - -interface ConditionalExpression extends BaseExpression { - type: "ConditionalExpression"; - test: Expression; - alternate: Expression; - consequent: Expression; -} - -interface BaseCallExpression extends BaseExpression { - callee: Expression | Super; - arguments: Array<Expression | SpreadElement>; -} -type CallExpression = SimpleCallExpression | NewExpression; - -interface SimpleCallExpression extends BaseCallExpression { - type: "CallExpression"; - optional: boolean; -} - -interface NewExpression extends BaseCallExpression { - type: "NewExpression"; -} - -interface MemberExpression extends BaseExpression, BasePattern { - type: "MemberExpression"; - object: Expression | Super; - property: Expression | PrivateIdentifier; - computed: boolean; - optional: boolean; -} - -type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; - -interface BasePattern extends BaseNode {} - -interface SwitchCase extends BaseNode { - type: "SwitchCase"; - test?: Expression | null | undefined; - consequent: Statement[]; -} - -interface CatchClause extends BaseNode { - type: "CatchClause"; - param: Pattern | null; - body: BlockStatement; -} - -interface Identifier extends BaseNode, BaseExpression, BasePattern { - type: "Identifier"; - name: string; -} - -type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; - -interface SimpleLiteral extends BaseNode, BaseExpression { - type: "Literal"; - value: string | boolean | number | null; - raw?: string | undefined; -} - -interface RegExpLiteral extends BaseNode, BaseExpression { - type: "Literal"; - value?: RegExp | null | undefined; - regex: { - pattern: string; - flags: string; - }; - raw?: string | undefined; -} - -interface BigIntLiteral extends BaseNode, BaseExpression { - type: "Literal"; - value?: bigint | null | undefined; - bigint: string; - raw?: string | undefined; -} - -type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; - -type BinaryOperator = - | "==" - | "!=" - | "===" - | "!==" - | "<" - | "<=" - | ">" - | ">=" - | "<<" - | ">>" - | ">>>" - | "+" - | "-" - | "*" - | "/" - | "%" - | "**" - | "|" - | "^" - | "&" - | "in" - | "instanceof"; - -type LogicalOperator = "||" | "&&" | "??"; - -type AssignmentOperator = - | "=" - | "+=" - | "-=" - | "*=" - | "/=" - | "%=" - | "**=" - | "<<=" - | ">>=" - | ">>>=" - | "|=" - | "^=" - | "&=" - | "||=" - | "&&=" - | "??="; - -type UpdateOperator = "++" | "--"; - -interface ForOfStatement extends BaseForXStatement { - type: "ForOfStatement"; - await: boolean; -} - -interface Super extends BaseNode { - type: "Super"; -} - -interface SpreadElement extends BaseNode { - type: "SpreadElement"; - argument: Expression; -} - -interface ArrowFunctionExpression extends BaseExpression, BaseFunction { - type: "ArrowFunctionExpression"; - expression: boolean; - body: BlockStatement | Expression; -} - -interface YieldExpression extends BaseExpression { - type: "YieldExpression"; - argument?: Expression | null | undefined; - delegate: boolean; -} - -interface TemplateLiteral extends BaseExpression { - type: "TemplateLiteral"; - quasis: TemplateElement[]; - expressions: Expression[]; -} - -interface TaggedTemplateExpression extends BaseExpression { - type: "TaggedTemplateExpression"; - tag: Expression; - quasi: TemplateLiteral; -} - -interface TemplateElement extends BaseNode { - type: "TemplateElement"; - tail: boolean; - value: { - /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ - cooked?: string | null | undefined; - raw: string; - }; -} - -interface AssignmentProperty extends Property { - value: Pattern; - kind: "init"; - method: boolean; // false -} - -interface ObjectPattern extends BasePattern { - type: "ObjectPattern"; - properties: Array<AssignmentProperty | RestElement>; -} - -interface ArrayPattern extends BasePattern { - type: "ArrayPattern"; - elements: Array<Pattern | null>; -} - -interface RestElement extends BasePattern { - type: "RestElement"; - argument: Pattern; -} - -interface AssignmentPattern extends BasePattern { - type: "AssignmentPattern"; - left: Pattern; - right: Expression; -} - -type Class = ClassDeclaration | ClassExpression; -interface BaseClass extends BaseNode { - superClass?: Expression | null | undefined; - body: ClassBody; -} - -interface ClassBody extends BaseNode { - type: "ClassBody"; - body: Array<MethodDefinition | PropertyDefinition | StaticBlock>; -} - -interface MethodDefinition extends BaseNode { - type: "MethodDefinition"; - key: Expression | PrivateIdentifier; - value: FunctionExpression; - kind: "constructor" | "method" | "get" | "set"; - computed: boolean; - static: boolean; -} - -interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { - type: "ClassDeclaration"; - /** It is null when a class declaration is a part of the `export default class` statement */ - id: Identifier | null; -} - -interface ClassDeclaration extends MaybeNamedClassDeclaration { - id: Identifier; -} - -interface ClassExpression extends BaseClass, BaseExpression { - type: "ClassExpression"; - id?: Identifier | null | undefined; -} - -interface MetaProperty extends BaseExpression { - type: "MetaProperty"; - meta: Identifier; - property: Identifier; -} - -type ModuleDeclaration = - | ImportDeclaration - | ExportNamedDeclaration - | ExportDefaultDeclaration - | ExportAllDeclaration; -interface BaseModuleDeclaration extends BaseNode {} - -type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; -interface BaseModuleSpecifier extends BaseNode { - local: Identifier; -} - -interface ImportDeclaration extends BaseModuleDeclaration { - type: "ImportDeclaration"; - specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>; - attributes: ImportAttribute[]; - source: Literal; -} - -interface ImportSpecifier extends BaseModuleSpecifier { - type: "ImportSpecifier"; - imported: Identifier | Literal; -} - -interface ImportAttribute extends BaseNode { - type: "ImportAttribute"; - key: Identifier | Literal; - value: Literal; -} - -interface ImportExpression extends BaseExpression { - type: "ImportExpression"; - source: Expression; - options?: Expression | null | undefined; -} - -interface ImportDefaultSpecifier extends BaseModuleSpecifier { - type: "ImportDefaultSpecifier"; -} - -interface ImportNamespaceSpecifier extends BaseModuleSpecifier { - type: "ImportNamespaceSpecifier"; -} - -interface ExportNamedDeclaration extends BaseModuleDeclaration { - type: "ExportNamedDeclaration"; - declaration?: Declaration | null | undefined; - specifiers: ExportSpecifier[]; - attributes: ImportAttribute[]; - source?: Literal | null | undefined; -} - -interface ExportSpecifier extends Omit<BaseModuleSpecifier, "local"> { - type: "ExportSpecifier"; - local: Identifier | Literal; - exported: Identifier | Literal; -} - -interface ExportDefaultDeclaration extends BaseModuleDeclaration { - type: "ExportDefaultDeclaration"; - declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; -} - -interface ExportAllDeclaration extends BaseModuleDeclaration { - type: "ExportAllDeclaration"; - exported: Identifier | Literal | null; - attributes: ImportAttribute[]; - source: Literal; -} - -interface AwaitExpression extends BaseExpression { - type: "AwaitExpression"; - argument: Expression; -} - -type Positioned<T> = T & { - start: number; - end: number; -}; -type Node = Positioned<Node$1>; - -interface HoistMocksOptions { - /** - * List of modules that should always be imported before compiler hints. - * @default 'vitest' - */ - hoistedModule?: string; - /** - * @default ["vi", "vitest"] - */ - utilsObjectNames?: string[]; - /** - * @default ["mock", "unmock"] - */ - hoistableMockMethodNames?: string[]; - /** - * @default ["mock", "unmock", "doMock", "doUnmock"] - */ - dynamicImportMockMethodNames?: string[]; - /** - * @default ["hoisted"] - */ - hoistedMethodNames?: string[]; - regexpHoistable?: RegExp; - codeFrameGenerator?: CodeFrameGenerator; -} -interface HoistMocksPluginOptions extends Omit<HoistMocksOptions, "regexpHoistable"> { - include?: string | RegExp | (string | RegExp)[]; - exclude?: string | RegExp | (string | RegExp)[]; - /** - * overrides include/exclude options - */ - filter?: (id: string) => boolean; -} -declare function hoistMocksPlugin(options?: HoistMocksPluginOptions): Plugin; -interface HoistMocksResult { - code: string; - map: SourceMap; -} -interface CodeFrameGenerator { - (node: Positioned<Node>, id: string, code: string): string; -} -declare function hoistMocks(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined; - -interface InterceptorPluginOptions { - /** - * @default "__vitest_mocker__" - */ - globalThisAccessor?: string; - registry?: MockerRegistry; -} -declare function interceptorPlugin(options?: InterceptorPluginOptions): Plugin; - -interface MockerPluginOptions extends AutomockOptions { - hoistMocks?: HoistMocksPluginOptions; -} -declare function mockerPlugin(options?: MockerPluginOptions): Plugin[]; - -interface ServerResolverOptions { - /** - * @default ['/node_modules/'] - */ - moduleDirectories?: string[]; -} -declare class ServerMockResolver { - private server; - private options; - constructor(server: ViteDevServer, options?: ServerResolverOptions); - resolveMock(rawId: string, importer: string, options: { - mock: "spy" | "factory" | "auto"; - }): Promise<ServerMockResolution>; - invalidate(ids: string[]): void; - resolveId(id: string, importer?: string): Promise<ServerIdResolution | null>; - private normalizeResolveIdToUrl; - private resolveMockId; - private resolveModule; -} - -export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, createManualModuleSource, dynamicImportPlugin, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin }; -export type { HoistMocksPluginOptions, HoistMocksResult, InterceptorPluginOptions, ServerResolverOptions }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/node.js b/vanilla/node_modules/@vitest/mocker/dist/node.js deleted file mode 100644 index f2ca242..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/node.js +++ /dev/null @@ -1,967 +0,0 @@ -import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js'; -import { a as automockModule, e as esmWalker } from './chunk-automock.js'; -import MagicString from 'magic-string'; -import { createFilter } from 'vite'; -import { readFile } from 'node:fs/promises'; -import { join } from 'node:path/posix'; -import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js'; -import { fileURLToPath } from 'node:url'; -import { existsSync, readFileSync } from 'node:fs'; -import { findMockRedirect } from './redirect.js'; -import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js'; -import 'estree-walker'; -import 'node:module'; - -function automockPlugin(options = {}) { - return { - name: "vitest:automock", - enforce: "post", - transform(code, id) { - if (id.includes("mock=automock") || id.includes("mock=autospy")) { - const mockType = id.includes("mock=automock") ? "automock" : "autospy"; - const ms = automockModule(code, mockType, this.parse, options); - return { - code: ms.toString(), - map: ms.generateMap({ - hires: "boundary", - source: cleanUrl(id) - }) - }; - } - } - }; -} - -const regexDynamicImport = /import\s*\(/; -function dynamicImportPlugin(options = {}) { - return { - name: "vitest:browser:esm-injector", - enforce: "post", - transform(source, id) { - // TODO: test is not called for static imports - if (!regexDynamicImport.test(source)) { - return; - } - if (options.filter && !options.filter(id)) { - return; - } - return injectDynamicImport(source, id, this.parse, options); - } - }; -} -function injectDynamicImport(code, id, parse, options = {}) { - const s = new MagicString(code); - let ast; - try { - ast = parse(code); - } catch (err) { - console.error(`Cannot parse ${id}:\n${err.message}`); - return; - } - // 3. convert references to import bindings & import.meta references - esmWalker(ast, { - onImportMeta() { - // s.update(node.start, node.end, viImportMetaKey) - }, - onDynamicImport(node) { - const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\""; - const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`; - const importSubstring = code.substring(node.start, node.end); - const hasIgnore = importSubstring.includes("/* @vite-ignore */"); - s.overwrite(node.start, node.source.start, replaceString + (hasIgnore ? "/* @vite-ignore */ " : "")); - s.overwrite(node.end - 1, node.end, "))"); - } - }); - return { - code: s.toString(), - map: s.generateMap({ - hires: "boundary", - source: id - }) - }; -} - -// AST walker module for ESTree compatible trees - - -function makeTest(test) { - if (typeof test === "string") - { return function (type) { return type === test; } } - else if (!test) - { return function () { return true; } } - else - { return test } -} - -var Found = function Found(node, state) { this.node = node; this.state = state; }; - -// Find the innermost node of a given type that contains the given -// position. Interface similar to findNodeAt. -function findNodeAround(node, pos, test, baseVisitor, state) { - test = makeTest(test); - if (!baseVisitor) { baseVisitor = base; } - try { - (function c(node, st, override) { - var type = override || node.type; - if (node.start > pos || node.end < pos) { return } - baseVisitor[type](node, st, c); - if (test(type, node)) { throw new Found(node, st) } - })(node, state); - } catch (e) { - if (e instanceof Found) { return e } - throw e - } -} - -function skipThrough(node, st, c) { c(node, st); } -function ignore(_node, _st, _c) {} - -// Node walkers. - -var base = {}; - -base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) { - for (var i = 0, list = node.body; i < list.length; i += 1) - { - var stmt = list[i]; - - c(stmt, st, "Statement"); - } -}; -base.Statement = skipThrough; -base.EmptyStatement = ignore; -base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = - function (node, st, c) { return c(node.expression, st, "Expression"); }; -base.IfStatement = function (node, st, c) { - c(node.test, st, "Expression"); - c(node.consequent, st, "Statement"); - if (node.alternate) { c(node.alternate, st, "Statement"); } -}; -base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; -base.BreakStatement = base.ContinueStatement = ignore; -base.WithStatement = function (node, st, c) { - c(node.object, st, "Expression"); - c(node.body, st, "Statement"); -}; -base.SwitchStatement = function (node, st, c) { - c(node.discriminant, st, "Expression"); - for (var i = 0, list = node.cases; i < list.length; i += 1) { - var cs = list[i]; - - c(cs, st); - } -}; -base.SwitchCase = function (node, st, c) { - if (node.test) { c(node.test, st, "Expression"); } - for (var i = 0, list = node.consequent; i < list.length; i += 1) - { - var cons = list[i]; - - c(cons, st, "Statement"); - } -}; -base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { - if (node.argument) { c(node.argument, st, "Expression"); } -}; -base.ThrowStatement = base.SpreadElement = - function (node, st, c) { return c(node.argument, st, "Expression"); }; -base.TryStatement = function (node, st, c) { - c(node.block, st, "Statement"); - if (node.handler) { c(node.handler, st); } - if (node.finalizer) { c(node.finalizer, st, "Statement"); } -}; -base.CatchClause = function (node, st, c) { - if (node.param) { c(node.param, st, "Pattern"); } - c(node.body, st, "Statement"); -}; -base.WhileStatement = base.DoWhileStatement = function (node, st, c) { - c(node.test, st, "Expression"); - c(node.body, st, "Statement"); -}; -base.ForStatement = function (node, st, c) { - if (node.init) { c(node.init, st, "ForInit"); } - if (node.test) { c(node.test, st, "Expression"); } - if (node.update) { c(node.update, st, "Expression"); } - c(node.body, st, "Statement"); -}; -base.ForInStatement = base.ForOfStatement = function (node, st, c) { - c(node.left, st, "ForInit"); - c(node.right, st, "Expression"); - c(node.body, st, "Statement"); -}; -base.ForInit = function (node, st, c) { - if (node.type === "VariableDeclaration") { c(node, st); } - else { c(node, st, "Expression"); } -}; -base.DebuggerStatement = ignore; - -base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; -base.VariableDeclaration = function (node, st, c) { - for (var i = 0, list = node.declarations; i < list.length; i += 1) - { - var decl = list[i]; - - c(decl, st); - } -}; -base.VariableDeclarator = function (node, st, c) { - c(node.id, st, "Pattern"); - if (node.init) { c(node.init, st, "Expression"); } -}; - -base.Function = function (node, st, c) { - if (node.id) { c(node.id, st, "Pattern"); } - for (var i = 0, list = node.params; i < list.length; i += 1) - { - var param = list[i]; - - c(param, st, "Pattern"); - } - c(node.body, st, node.expression ? "Expression" : "Statement"); -}; - -base.Pattern = function (node, st, c) { - if (node.type === "Identifier") - { c(node, st, "VariablePattern"); } - else if (node.type === "MemberExpression") - { c(node, st, "MemberPattern"); } - else - { c(node, st); } -}; -base.VariablePattern = ignore; -base.MemberPattern = skipThrough; -base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; -base.ArrayPattern = function (node, st, c) { - for (var i = 0, list = node.elements; i < list.length; i += 1) { - var elt = list[i]; - - if (elt) { c(elt, st, "Pattern"); } - } -}; -base.ObjectPattern = function (node, st, c) { - for (var i = 0, list = node.properties; i < list.length; i += 1) { - var prop = list[i]; - - if (prop.type === "Property") { - if (prop.computed) { c(prop.key, st, "Expression"); } - c(prop.value, st, "Pattern"); - } else if (prop.type === "RestElement") { - c(prop.argument, st, "Pattern"); - } - } -}; - -base.Expression = skipThrough; -base.ThisExpression = base.Super = base.MetaProperty = ignore; -base.ArrayExpression = function (node, st, c) { - for (var i = 0, list = node.elements; i < list.length; i += 1) { - var elt = list[i]; - - if (elt) { c(elt, st, "Expression"); } - } -}; -base.ObjectExpression = function (node, st, c) { - for (var i = 0, list = node.properties; i < list.length; i += 1) - { - var prop = list[i]; - - c(prop, st); - } -}; -base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; -base.SequenceExpression = function (node, st, c) { - for (var i = 0, list = node.expressions; i < list.length; i += 1) - { - var expr = list[i]; - - c(expr, st, "Expression"); - } -}; -base.TemplateLiteral = function (node, st, c) { - for (var i = 0, list = node.quasis; i < list.length; i += 1) - { - var quasi = list[i]; - - c(quasi, st); - } - - for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) - { - var expr = list$1[i$1]; - - c(expr, st, "Expression"); - } -}; -base.TemplateElement = ignore; -base.UnaryExpression = base.UpdateExpression = function (node, st, c) { - c(node.argument, st, "Expression"); -}; -base.BinaryExpression = base.LogicalExpression = function (node, st, c) { - c(node.left, st, "Expression"); - c(node.right, st, "Expression"); -}; -base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { - c(node.left, st, "Pattern"); - c(node.right, st, "Expression"); -}; -base.ConditionalExpression = function (node, st, c) { - c(node.test, st, "Expression"); - c(node.consequent, st, "Expression"); - c(node.alternate, st, "Expression"); -}; -base.NewExpression = base.CallExpression = function (node, st, c) { - c(node.callee, st, "Expression"); - if (node.arguments) - { for (var i = 0, list = node.arguments; i < list.length; i += 1) - { - var arg = list[i]; - - c(arg, st, "Expression"); - } } -}; -base.MemberExpression = function (node, st, c) { - c(node.object, st, "Expression"); - if (node.computed) { c(node.property, st, "Expression"); } -}; -base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { - if (node.declaration) - { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } - if (node.source) { c(node.source, st, "Expression"); } -}; -base.ExportAllDeclaration = function (node, st, c) { - if (node.exported) - { c(node.exported, st); } - c(node.source, st, "Expression"); -}; -base.ImportDeclaration = function (node, st, c) { - for (var i = 0, list = node.specifiers; i < list.length; i += 1) - { - var spec = list[i]; - - c(spec, st); - } - c(node.source, st, "Expression"); -}; -base.ImportExpression = function (node, st, c) { - c(node.source, st, "Expression"); -}; -base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; - -base.TaggedTemplateExpression = function (node, st, c) { - c(node.tag, st, "Expression"); - c(node.quasi, st, "Expression"); -}; -base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; -base.Class = function (node, st, c) { - if (node.id) { c(node.id, st, "Pattern"); } - if (node.superClass) { c(node.superClass, st, "Expression"); } - c(node.body, st); -}; -base.ClassBody = function (node, st, c) { - for (var i = 0, list = node.body; i < list.length; i += 1) - { - var elt = list[i]; - - c(elt, st); - } -}; -base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) { - if (node.computed) { c(node.key, st, "Expression"); } - if (node.value) { c(node.value, st, "Expression"); } -}; - -function hoistMocksPlugin(options = {}) { - const filter = options.filter || createFilter(options.include, options.exclude); - const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [ - "mock", - "unmock", - "doMock", - "doUnmock" - ], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"] } = options; - const methods = new Set([ - ...hoistableMockMethodNames, - ...hoistedMethodNames, - ...dynamicImportMockMethodNames - ]); - const regexpHoistable = new RegExp(`\\b(?:${utilsObjectNames.join("|")})\\s*\.\\s*(?:${Array.from(methods).join("|")})\\s*\\(`); - return { - name: "vitest:mocks", - enforce: "post", - transform(code, id) { - if (!filter(id)) { - return; - } - return hoistMocks(code, id, this.parse, { - regexpHoistable, - hoistableMockMethodNames, - hoistedMethodNames, - utilsObjectNames, - dynamicImportMockMethodNames, - ...options - }); - } - }; -} -const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API. -You may encounter this issue when importing the mocks API from another module other than 'vitest'. -To fix this issue you can either: -- import the mocks API directly from 'vitest' -- enable the 'globals' options`; -function API_NOT_FOUND_CHECK(names) { - return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`; -} -function isIdentifier(node) { - return node.type === "Identifier"; -} -function getNodeTail(code, node) { - let end = node.end; - if (code[node.end] === ";") { - end += 1; - } - if (code[node.end] === "\n") { - return end + 1; - } - if (code[node.end + 1] === "\n") { - end += 1; - } - return end; -} -const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/; -const hashbangRE = /^#!.*\n/; -// this is a fork of Vite SSR transform -function hoistMocks(code, id, parse, options = {}) { - var _hashbangRE$exec; - const needHoisting = (options.regexpHoistable || regexpHoistable).test(code); - if (!needHoisting) { - return; - } - const s = new MagicString(code); - let ast; - try { - ast = parse(code); - } catch (err) { - console.error(`Cannot parse ${id}:\n${err.message}.`); - return; - } - const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [ - "mock", - "unmock", - "doMock", - "doUnmock" - ], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options; - // hoist at the start of the file, after the hashbang - let hoistIndex = ((_hashbangRE$exec = hashbangRE.exec(code)) === null || _hashbangRE$exec === void 0 ? void 0 : _hashbangRE$exec[0].length) ?? 0; - let hoistedModuleImported = false; - let uid = 0; - const idToImportMap = new Map(); - const imports = []; - // this will transform import statements into dynamic ones, if there are imports - // it will keep the import as is, if we don't need to mock anything - // in browser environment it will wrap the module value with "vitest_wrap_module" function - // that returns a proxy to the module so that named exports can be mocked - function defineImport(importNode) { - const source = importNode.source.value; - // always hoist vitest import to top of the file, so - // "vi" helpers can access it - if (hoistedModule === source) { - hoistedModuleImported = true; - return; - } - const importId = `__vi_import_${uid++}__`; - imports.push({ - id: importId, - node: importNode - }); - return importId; - } - // 1. check all import statements and record id -> importName map - for (const node of ast.body) { - // import foo from 'foo' --> foo -> __import_foo__.default - // import { baz } from 'foo' --> baz -> __import_foo__.baz - // import * as ok from 'foo' --> ok -> __import_foo__ - if (node.type === "ImportDeclaration") { - const importId = defineImport(node); - if (!importId) { - continue; - } - for (const spec of node.specifiers) { - if (spec.type === "ImportSpecifier") { - if (spec.imported.type === "Identifier") { - idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`); - } else { - idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`); - } - } else if (spec.type === "ImportDefaultSpecifier") { - idToImportMap.set(spec.local.name, `${importId}.default`); - } else { - // namespace specifier - idToImportMap.set(spec.local.name, importId); - } - } - } - } - const declaredConst = new Set(); - const hoistedNodes = []; - function createSyntaxError(node, message) { - const _error = new SyntaxError(message); - Error.captureStackTrace(_error, createSyntaxError); - const serializedError = { - name: "SyntaxError", - message: _error.message, - stack: _error.stack - }; - if (options.codeFrameGenerator) { - serializedError.frame = options.codeFrameGenerator(node, id, code); - } - return serializedError; - } - function assertNotDefaultExport(node, error) { - var _findNodeAround; - const defaultExport = (_findNodeAround = findNodeAround(ast, node.start, "ExportDefaultDeclaration")) === null || _findNodeAround === void 0 ? void 0 : _findNodeAround.node; - if ((defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration) === node || (defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration.type) === "AwaitExpression" && defaultExport.declaration.argument === node) { - throw createSyntaxError(defaultExport, error); - } - } - function assertNotNamedExport(node, error) { - var _findNodeAround2; - const nodeExported = (_findNodeAround2 = findNodeAround(ast, node.start, "ExportNamedDeclaration")) === null || _findNodeAround2 === void 0 ? void 0 : _findNodeAround2.node; - if ((nodeExported === null || nodeExported === void 0 ? void 0 : nodeExported.declaration) === node) { - throw createSyntaxError(nodeExported, error); - } - } - function getVariableDeclaration(node) { - var _findNodeAround3, _declarationNode$decl; - const declarationNode = (_findNodeAround3 = findNodeAround(ast, node.start, "VariableDeclaration")) === null || _findNodeAround3 === void 0 ? void 0 : _findNodeAround3.node; - const init = declarationNode === null || declarationNode === void 0 || (_declarationNode$decl = declarationNode.declarations[0]) === null || _declarationNode$decl === void 0 ? void 0 : _declarationNode$decl.init; - if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) { - return declarationNode; - } - } - const usedUtilityExports = new Set(); - esmWalker(ast, { - onIdentifier(id, info, parentStack) { - const binding = idToImportMap.get(id.name); - if (!binding) { - return; - } - if (info.hasBindingShortcut) { - s.appendLeft(id.end, `: ${binding}`); - } else if (info.classDeclaration) { - if (!declaredConst.has(id.name)) { - declaredConst.add(id.name); - // locate the top-most node containing the class declaration - const topNode = parentStack[parentStack.length - 2]; - s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`); - } - } else if (!info.classExpression) { - s.update(id.start, id.end, binding); - } - }, - onCallExpression(node) { - if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) { - const methodName = node.callee.property.name; - usedUtilityExports.add(node.callee.object.name); - if (hoistableMockMethodNames.includes(methodName)) { - const method = `${node.callee.object.name}.${methodName}`; - assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`); - const declarationNode = getVariableDeclaration(node); - if (declarationNode) { - assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`); - } - // rewrite vi.mock(import('..')) into vi.mock('..') - if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) { - const moduleInfo = node.arguments[0]; - // vi.mock(import('./path')) -> vi.mock('./path') - if (moduleInfo.type === "ImportExpression") { - const source = moduleInfo.source; - s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); - } - // vi.mock(await import('./path')) -> vi.mock('./path') - if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") { - const source = moduleInfo.argument.source; - s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); - } - } - hoistedNodes.push(node); - } else if (dynamicImportMockMethodNames.includes(methodName)) { - const moduleInfo = node.arguments[0]; - let source = null; - if (moduleInfo.type === "ImportExpression") { - source = moduleInfo.source; - } - if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") { - source = moduleInfo.argument.source; - } - if (source) { - s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end)); - } - } - if (hoistedMethodNames.includes(methodName)) { - assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first."); - const declarationNode = getVariableDeclaration(node); - if (declarationNode) { - assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first."); - // hoist "const variable = vi.hoisted(() => {})" - hoistedNodes.push(declarationNode); - } else { - var _findNodeAround4; - const awaitedExpression = (_findNodeAround4 = findNodeAround(ast, node.start, "AwaitExpression")) === null || _findNodeAround4 === void 0 ? void 0 : _findNodeAround4.node; - // hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})" - const moveNode = (awaitedExpression === null || awaitedExpression === void 0 ? void 0 : awaitedExpression.argument) === node ? awaitedExpression : node; - hoistedNodes.push(moveNode); - } - } - } - } - }); - function getNodeName(node) { - const callee = node.callee || {}; - if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) { - return `${callee.object.name}.${callee.property.name}()`; - } - return "\"hoisted method\""; - } - function getNodeCall(node) { - if (node.type === "CallExpression") { - return node; - } - if (node.type === "VariableDeclaration") { - const { declarations } = node; - const init = declarations[0].init; - if (init) { - return getNodeCall(init); - } - } - if (node.type === "AwaitExpression") { - const { argument } = node; - if (argument.type === "CallExpression") { - return getNodeCall(argument); - } - } - return node; - } - function createError(outsideNode, insideNode) { - const outsideCall = getNodeCall(outsideNode); - const insideCall = getNodeCall(insideNode); - throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`); - } - // validate hoistedNodes doesn't have nodes inside other nodes - for (let i = 0; i < hoistedNodes.length; i++) { - const node = hoistedNodes[i]; - for (let j = i + 1; j < hoistedNodes.length; j++) { - const otherNode = hoistedNodes[j]; - if (node.start >= otherNode.start && node.end <= otherNode.end) { - throw createError(otherNode, node); - } - if (otherNode.start >= node.start && otherNode.end <= node.end) { - throw createError(node, otherNode); - } - } - } - // hoist vi.mock/vi.hoisted - for (const node of hoistedNodes) { - const end = getNodeTail(code, node); - // don't hoist into itself if it's already at the top - if (hoistIndex === end || hoistIndex === node.start) { - hoistIndex = end; - } else { - s.move(node.start, end, hoistIndex); - } - } - // hoist actual dynamic imports last so they are inserted after all hoisted mocks - for (const { node: importNode, id: importId } of imports) { - const source = importNode.source.value; - s.update(importNode.start, importNode.end, `const ${importId} = await import(${JSON.stringify(source)});\n`); - if (importNode.start === hoistIndex) { - // no need to hoist, but update hoistIndex to keep the order - hoistIndex = importNode.end; - } else { - // There will be an error if the module is called before it is imported, - // so the module import statement is hoisted to the top - s.move(importNode.start, importNode.end, hoistIndex); - } - } - if (!hoistedModuleImported && hoistedNodes.length) { - const utilityImports = [...usedUtilityExports]; - // "vi" or "vitest" is imported from a module other than "vitest" - if (utilityImports.some((name) => idToImportMap.has(name))) { - s.prepend(API_NOT_FOUND_CHECK(utilityImports)); - } else if (utilityImports.length) { - s.prepend(`import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`); - } - } - return { - code: s.toString(), - map: s.generateMap({ - hires: "boundary", - source: id - }) - }; -} - -function interceptorPlugin(options = {}) { - const registry = options.registry || new MockerRegistry(); - return { - name: "vitest:mocks:interceptor", - enforce: "pre", - load: { - order: "pre", - async handler(id) { - const mock = registry.getById(id); - if (!mock) { - return; - } - if (mock.type === "manual") { - const exports$1 = Object.keys(await mock.resolve()); - const accessor = options.globalThisAccessor || "\"__vitest_mocker__\""; - return createManualModuleSource(mock.url, exports$1, accessor); - } - if (mock.type === "redirect") { - return readFile(mock.redirect, "utf-8"); - } - } - }, - transform: { - order: "post", - handler(code, id) { - const mock = registry.getById(id); - if (!mock) { - return; - } - if (mock.type === "automock" || mock.type === "autospy") { - const m = automockModule(code, mock.type, this.parse, { globalThisAccessor: options.globalThisAccessor }); - return { - code: m.toString(), - map: m.generateMap({ - hires: "boundary", - source: cleanUrl(id) - }) - }; - } - } - }, - configureServer(server) { - server.ws.on("vitest:interceptor:register", (event) => { - if (event.type === "manual") { - const module = ManualMockedModule.fromJSON(event, async () => { - const keys = await getFactoryExports(event.url); - return Object.fromEntries(keys.map((key) => [key, null])); - }); - registry.add(module); - } else { - if (event.type === "redirect") { - const redirectUrl = new URL(event.redirect); - event.redirect = join(server.config.root, redirectUrl.pathname); - } - registry.register(event); - } - server.ws.send("vitest:interceptor:register:result"); - }); - server.ws.on("vitest:interceptor:delete", (id) => { - registry.delete(id); - server.ws.send("vitest:interceptor:delete:result"); - }); - server.ws.on("vitest:interceptor:invalidate", () => { - registry.clear(); - server.ws.send("vitest:interceptor:invalidate:result"); - }); - function getFactoryExports(url) { - server.ws.send("vitest:interceptor:resolve", url); - let timeout; - return new Promise((resolve, reject) => { - timeout = setTimeout(() => { - reject(new Error(`Timeout while waiting for factory exports of ${url}`)); - }, 1e4); - server.ws.on("vitest:interceptor:resolved", ({ url: resolvedUrl, keys }) => { - if (resolvedUrl === url) { - clearTimeout(timeout); - resolve(keys); - } - }); - }); - } - } - }; -} - -const VALID_ID_PREFIX = "/@id/"; -class ServerMockResolver { - constructor(server, options = {}) { - this.server = server; - this.options = options; - } - async resolveMock(rawId, importer, options) { - const { id, fsPath, external } = await this.resolveMockId(rawId, importer); - const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url; - if (options.mock === "factory") { - var _manifest$fsPath; - const manifest = getViteDepsManifest(this.server.config); - const needsInterop = (manifest === null || manifest === void 0 || (_manifest$fsPath = manifest[fsPath]) === null || _manifest$fsPath === void 0 ? void 0 : _manifest$fsPath.needsInterop) ?? false; - return { - mockType: "manual", - resolvedId: id, - resolvedUrl, - needsInterop - }; - } - if (options.mock === "spy") { - return { - mockType: "autospy", - resolvedId: id, - resolvedUrl - }; - } - const redirectUrl = findMockRedirect(this.server.config.root, fsPath, external); - return { - mockType: redirectUrl === null ? "automock" : "redirect", - redirectUrl, - resolvedId: id, - resolvedUrl - }; - } - invalidate(ids) { - ids.forEach((id) => { - const moduleGraph = this.server.moduleGraph; - const module = moduleGraph.getModuleById(id); - if (module) { - module.transformResult = null; - } - }); - } - async resolveId(id, importer) { - const resolved = await this.server.pluginContainer.resolveId(id, importer, { ssr: false }); - if (!resolved) { - return null; - } - return this.normalizeResolveIdToUrl(resolved); - } - normalizeResolveIdToUrl(resolved) { - const isOptimized = resolved.id.startsWith(withTrailingSlash(this.server.config.cacheDir)); - let url; - // normalise the URL to be acceptable by the browser - // https://github.com/vitejs/vite/blob/14027b0f2a9b01c14815c38aab22baf5b29594bb/packages/vite/src/node/plugins/importAnalysis.ts#L103 - const root = this.server.config.root; - if (resolved.id.startsWith(withTrailingSlash(root))) { - url = resolved.id.slice(root.length); - } else if (resolved.id !== "/@react-refresh" && isAbsolute(resolved.id) && existsSync(cleanUrl(resolved.id))) { - url = join$1("/@fs/", resolved.id); - } else { - url = resolved.id; - } - if (url[0] !== "." && url[0] !== "/") { - url = resolved.id.startsWith(VALID_ID_PREFIX) ? resolved.id : VALID_ID_PREFIX + resolved.id.replace("\0", "__x00__"); - } - return { - id: resolved.id, - url, - optimized: isOptimized - }; - } - async resolveMockId(rawId, importer) { - if (!this.server.moduleGraph.getModuleById(importer) && !importer.startsWith(this.server.config.root)) { - importer = join$1(this.server.config.root, importer); - } - const resolved = await this.server.pluginContainer.resolveId(rawId, importer, { ssr: false }); - return this.resolveModule(rawId, resolved); - } - resolveModule(rawId, resolved) { - const id = (resolved === null || resolved === void 0 ? void 0 : resolved.id) || rawId; - const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null; - return { - id, - fsPath: cleanUrl(id), - external - }; - } -} -function isModuleDirectory(config, path) { - const moduleDirectories = config.moduleDirectories || ["/node_modules/"]; - return moduleDirectories.some((dir) => path.includes(dir)); -} -const metadata = new WeakMap(); -function getViteDepsManifest(config) { - if (metadata.has(config)) { - return metadata.get(config); - } - const cacheDirPath = getDepsCacheDir(config); - const metadataPath = resolve(cacheDirPath, "_metadata.json"); - if (!existsSync(metadataPath)) { - return null; - } - const { optimized } = JSON.parse(readFileSync(metadataPath, "utf-8")); - const newManifest = {}; - for (const name in optimized) { - const dep = optimized[name]; - const file = resolve(cacheDirPath, dep.file); - newManifest[file] = { - hash: dep.fileHash, - needsInterop: dep.needsInterop - }; - } - metadata.set(config, newManifest); - return newManifest; -} -function getDepsCacheDir(config) { - return resolve(config.cacheDir, "deps"); -} -function withTrailingSlash(path) { - if (path.at(-1) !== "/") { - return `${path}/`; - } - return path; -} - -// this is an implementation for public usage -// vitest doesn't use this plugin directly -function mockerPlugin(options = {}) { - let server; - const registerPath = resolve(fileURLToPath(new URL("./register.js", import.meta.url))); - return [ - { - name: "vitest:mocker:ws-rpc", - config(_, { command }) { - if (command !== "serve") { - return; - } - return { - server: { preTransformRequests: false }, - optimizeDeps: { exclude: ["@vitest/mocker/register", "@vitest/mocker/browser"] } - }; - }, - configureServer(server_) { - server = server_; - const mockResolver = new ServerMockResolver(server); - server.ws.on("vitest:mocks:resolveId", async ({ id, importer }) => { - const resolved = await mockResolver.resolveId(id, importer); - server.ws.send("vitest:mocks:resolvedId:result", resolved); - }); - server.ws.on("vitest:mocks:resolveMock", async ({ id, importer, options }) => { - const resolved = await mockResolver.resolveMock(id, importer, options); - server.ws.send("vitest:mocks:resolveMock:result", resolved); - }); - server.ws.on("vitest:mocks:invalidate", async ({ ids }) => { - mockResolver.invalidate(ids); - server.ws.send("vitest:mocks:invalidate:result"); - }); - }, - async load(id) { - if (id !== registerPath) { - return; - } - if (!server) { - // mocker doesn't work during build - return "export {}"; - } - const content = await readFile(registerPath, "utf-8"); - const result = content.replace(/__VITEST_GLOBAL_THIS_ACCESSOR__/g, options.globalThisAccessor ?? "\"__vitest_mocker__\"").replace("__VITEST_MOCKER_ROOT__", JSON.stringify(server.config.root)); - return result; - } - }, - hoistMocksPlugin(options.hoistMocks), - interceptorPlugin(options), - automockPlugin(options), - dynamicImportPlugin(options) - ]; -} - -export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/redirect.d.ts b/vanilla/node_modules/@vitest/mocker/dist/redirect.d.ts deleted file mode 100644 index 1f8256b..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/redirect.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare function findMockRedirect(root: string, mockPath: string, external: string | null): string | null; - -export { findMockRedirect }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/redirect.js b/vanilla/node_modules/@vitest/mocker/dist/redirect.js deleted file mode 100644 index 0071819..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/redirect.js +++ /dev/null @@ -1,79 +0,0 @@ -import fs from 'node:fs'; -import nodeModule from 'node:module'; -import { d as dirname, j as join, b as basename, r as resolve, e as extname } from './chunk-pathe.M-eThtNZ.js'; - -const { existsSync, readdirSync, statSync } = fs; -function findMockRedirect(root, mockPath, external) { - const path = external || mockPath; - // it's a node_module alias - // all mocks should be inside <root>/__mocks__ - if (external || isNodeBuiltin(mockPath) || !existsSync(mockPath)) { - const mockDirname = dirname(path); - const mockFolder = join(root, "__mocks__", mockDirname); - if (!existsSync(mockFolder)) { - return null; - } - const baseOriginal = basename(path); - function findFile(mockFolder, baseOriginal) { - const files = readdirSync(mockFolder); - for (const file of files) { - const baseFile = basename(file, extname(file)); - if (baseFile === baseOriginal) { - const path = resolve(mockFolder, file); - // if the same name, return the file - if (statSync(path).isFile()) { - return path; - } else { - // find folder/index.{js,ts} - const indexFile = findFile(path, "index"); - if (indexFile) { - return indexFile; - } - } - } - } - return null; - } - return findFile(mockFolder, baseOriginal); - } - const dir = dirname(path); - const baseId = basename(path); - const fullPath = resolve(dir, "__mocks__", baseId); - return existsSync(fullPath) ? fullPath : null; -} -const builtins = new Set([ - ...nodeModule.builtinModules, - "assert/strict", - "diagnostics_channel", - "dns/promises", - "fs/promises", - "path/posix", - "path/win32", - "readline/promises", - "stream/consumers", - "stream/promises", - "stream/web", - "timers/promises", - "util/types", - "wasi" -]); -// https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix -const prefixedBuiltins = new Set([ - "node:sea", - "node:sqlite", - "node:test", - "node:test/reporters" -]); -const NODE_BUILTIN_NAMESPACE = "node:"; -function isNodeBuiltin(id) { - // Added in v18.6.0 - if (nodeModule.isBuiltin) { - return nodeModule.isBuiltin(id); - } - if (prefixedBuiltins.has(id)) { - return true; - } - return builtins.has(id.startsWith(NODE_BUILTIN_NAMESPACE) ? id.slice(NODE_BUILTIN_NAMESPACE.length) : id); -} - -export { findMockRedirect }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/register.d.ts b/vanilla/node_modules/@vitest/mocker/dist/register.d.ts deleted file mode 100644 index 73e6207..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/register.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-TnKRhz7N.js'; -import '@vitest/spy'; -import './types.d-B8CCKmHt.js'; -import './index.d-C-sLYZi-.js'; - -declare function registerModuleMocker(interceptor: (accessor: string) => ModuleMockerInterceptor): ModuleMockerCompilerHints; -declare function registerNativeFactoryResolver(mocker: ModuleMocker): void; - -export { registerModuleMocker, registerNativeFactoryResolver }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/register.js b/vanilla/node_modules/@vitest/mocker/dist/register.js deleted file mode 100644 index 841b687..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/register.js +++ /dev/null @@ -1,41 +0,0 @@ -import { createMockInstance } from '@vitest/spy'; -import { M as ModuleMocker, r as rpc, c as createCompilerHints, h as hot } from './chunk-mocker.js'; -import './index.js'; -import './chunk-registry.js'; -import './chunk-pathe.M-eThtNZ.js'; - -function registerModuleMocker(interceptor) { - const mocker = new ModuleMocker(interceptor(__VITEST_GLOBAL_THIS_ACCESSOR__), { - resolveId(id, importer) { - return rpc("vitest:mocks:resolveId", { - id, - importer - }); - }, - resolveMock(id, importer, options) { - return rpc("vitest:mocks:resolveMock", { - id, - importer, - options - }); - }, - async invalidate(ids) { - return rpc("vitest:mocks:invalidate", { ids }); - } - }, createMockInstance, { root: __VITEST_MOCKER_ROOT__ }); - globalThis[__VITEST_GLOBAL_THIS_ACCESSOR__] = mocker; - registerNativeFactoryResolver(mocker); - return createCompilerHints({ globalThisKey: __VITEST_GLOBAL_THIS_ACCESSOR__ }); -} -function registerNativeFactoryResolver(mocker) { - hot.on("vitest:interceptor:resolve", async (url) => { - const exports$1 = await mocker.resolveFactoryModule(url); - const keys = Object.keys(exports$1); - hot.send("vitest:interceptor:resolved", { - url, - keys - }); - }); -} - -export { registerModuleMocker, registerNativeFactoryResolver }; diff --git a/vanilla/node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts b/vanilla/node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts deleted file mode 100644 index a99816f..0000000 --- a/vanilla/node_modules/@vitest/mocker/dist/types.d-B8CCKmHt.d.ts +++ /dev/null @@ -1,107 +0,0 @@ -declare class MockerRegistry { - private readonly registryByUrl; - private readonly registryById; - clear(): void; - keys(): IterableIterator<string>; - add(mock: MockedModule): void; - register(json: MockedModuleSerialized): MockedModule; - register(type: "redirect", raw: string, id: string, url: string, redirect: string): RedirectedModule; - register(type: "manual", raw: string, id: string, url: string, factory: () => any): ManualMockedModule; - register(type: "automock", raw: string, id: string, url: string): AutomockedModule; - register(type: "autospy", id: string, raw: string, url: string): AutospiedModule; - delete(id: string): void; - deleteById(id: string): void; - get(id: string): MockedModule | undefined; - getById(id: string): MockedModule | undefined; - has(id: string): boolean; -} -type MockedModule = AutomockedModule | AutospiedModule | ManualMockedModule | RedirectedModule; -type MockedModuleType = "automock" | "autospy" | "manual" | "redirect"; -type MockedModuleSerialized = AutomockedModuleSerialized | AutospiedModuleSerialized | ManualMockedModuleSerialized | RedirectedModuleSerialized; -declare class AutomockedModule { - raw: string; - id: string; - url: string; - readonly type = "automock"; - constructor(raw: string, id: string, url: string); - static fromJSON(data: AutomockedModuleSerialized): AutospiedModule; - toJSON(): AutomockedModuleSerialized; -} -interface AutomockedModuleSerialized { - type: "automock"; - url: string; - raw: string; - id: string; -} -declare class AutospiedModule { - raw: string; - id: string; - url: string; - readonly type = "autospy"; - constructor(raw: string, id: string, url: string); - static fromJSON(data: AutospiedModuleSerialized): AutospiedModule; - toJSON(): AutospiedModuleSerialized; -} -interface AutospiedModuleSerialized { - type: "autospy"; - url: string; - raw: string; - id: string; -} -declare class RedirectedModule { - raw: string; - id: string; - url: string; - redirect: string; - readonly type = "redirect"; - constructor(raw: string, id: string, url: string, redirect: string); - static fromJSON(data: RedirectedModuleSerialized): RedirectedModule; - toJSON(): RedirectedModuleSerialized; -} -interface RedirectedModuleSerialized { - type: "redirect"; - url: string; - id: string; - raw: string; - redirect: string; -} -declare class ManualMockedModule { - raw: string; - id: string; - url: string; - factory: () => any; - cache: Record<string | symbol, any> | undefined; - readonly type = "manual"; - constructor(raw: string, id: string, url: string, factory: () => any); - resolve(): Promise<Record<string | symbol, any>>; - static fromJSON(data: ManualMockedModuleSerialized, factory: () => any): ManualMockedModule; - toJSON(): ManualMockedModuleSerialized; -} -interface ManualMockedModuleSerialized { - type: "manual"; - url: string; - id: string; - raw: string; -} - -type Awaitable<T> = T | PromiseLike<T>; -type ModuleMockFactoryWithHelper<M = unknown> = (importOriginal: <T extends M = M>() => Promise<T>) => Awaitable<Partial<M>>; -type ModuleMockFactory = () => any; -interface ModuleMockOptions { - spy?: boolean; -} -interface ServerMockResolution { - mockType: "manual" | "redirect" | "automock" | "autospy"; - resolvedId: string; - resolvedUrl: string; - needsInterop?: boolean; - redirectUrl?: string | null; -} -interface ServerIdResolution { - id: string; - url: string; - optimized: boolean; -} - -export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as f, ManualMockedModule as g }; -export type { ServerMockResolution as S, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ServerIdResolution as e, AutomockedModuleSerialized as h, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as j, MockedModuleSerialized as k, RedirectedModuleSerialized as l, ModuleMockFactory as m }; diff --git a/vanilla/node_modules/@vitest/mocker/package.json b/vanilla/node_modules/@vitest/mocker/package.json deleted file mode 100644 index 1bd814c..0000000 --- a/vanilla/node_modules/@vitest/mocker/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "name": "@vitest/mocker", - "type": "module", - "version": "4.0.18", - "description": "Vitest module mocker implementation", - "license": "MIT", - "funding": "https://opencollective.com/vitest", - "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker#readme", - "repository": { - "type": "git", - "url": "git+https://github.com/vitest-dev/vitest.git", - "directory": "packages/mocker" - }, - "bugs": { - "url": "https://github.com/vitest-dev/vitest/issues" - }, - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./node": { - "types": "./dist/node.d.ts", - "default": "./dist/node.js" - }, - "./browser": { - "types": "./dist/browser.d.ts", - "default": "./dist/browser.js" - }, - "./redirect": { - "types": "./dist/redirect.d.ts", - "default": "./dist/redirect.js" - }, - "./automock": { - "types": "./dist/automock.d.ts", - "default": "./dist/automock.js" - }, - "./register": { - "types": "./dist/register.d.ts", - "default": "./dist/register.js" - }, - "./auto-register": { - "types": "./dist/register.d.ts", - "default": "./dist/register.js" - }, - "./*": "./*" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "*.d.ts", - "dist" - ], - "peerDependencies": { - "msw": "^2.4.9", - "vite": "^6.0.0 || ^7.0.0-0" - }, - "peerDependenciesMeta": { - "msw": { - "optional": true - }, - "vite": { - "optional": true - } - }, - "dependencies": { - "estree-walker": "^3.0.3", - "magic-string": "^0.30.21", - "@vitest/spy": "4.0.18" - }, - "devDependencies": { - "@types/estree": "^1.0.8", - "acorn-walk": "^8.3.4", - "msw": "^2.12.3", - "pathe": "^2.0.3", - "vite": "^6.3.5", - "@vitest/spy": "4.0.18", - "@vitest/utils": "4.0.18" - }, - "scripts": { - "build": "premove dist && rollup -c", - "dev": "rollup -c --watch" - } -}
\ No newline at end of file diff --git a/vanilla/node_modules/@vitest/pretty-format/LICENSE b/vanilla/node_modules/@vitest/pretty-format/LICENSE deleted file mode 100644 index 0e5771d..0000000 --- a/vanilla/node_modules/@vitest/pretty-format/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vanilla/node_modules/@vitest/pretty-format/dist/index.d.ts b/vanilla/node_modules/@vitest/pretty-format/dist/index.d.ts deleted file mode 100644 index a229bcf..0000000 --- a/vanilla/node_modules/@vitest/pretty-format/dist/index.d.ts +++ /dev/null @@ -1,124 +0,0 @@ -/** -* Copyright (c) Meta Platforms, Inc. and affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -interface Colors { - comment: { - close: string; - open: string; - }; - content: { - close: string; - open: string; - }; - prop: { - close: string; - open: string; - }; - tag: { - close: string; - open: string; - }; - value: { - close: string; - open: string; - }; -} -type Indent = (arg0: string) => string; -type Refs = Array<unknown>; -type Print = (arg0: unknown) => string; -type Theme = Required<{ - comment?: string; - content?: string; - prop?: string; - tag?: string; - value?: string; -}>; -/** -* compare function used when sorting object keys, `null` can be used to skip over sorting. -*/ -type CompareKeys = ((a: string, b: string) => number) | null | undefined; -type RequiredOptions = Required<PrettyFormatOptions>; -interface Options extends Omit<RequiredOptions, "compareKeys" | "theme"> { - compareKeys: CompareKeys; - theme: Theme; -} -interface PrettyFormatOptions { - callToJSON?: boolean; - escapeRegex?: boolean; - escapeString?: boolean; - highlight?: boolean; - indent?: number; - maxDepth?: number; - maxWidth?: number; - min?: boolean; - printBasicPrototype?: boolean; - printFunctionName?: boolean; - printShadowRoot?: boolean; - compareKeys?: CompareKeys; - plugins?: Plugins; -} -type OptionsReceived = PrettyFormatOptions; -interface Config { - callToJSON: boolean; - compareKeys: CompareKeys; - colors: Colors; - escapeRegex: boolean; - escapeString: boolean; - indent: string; - maxDepth: number; - maxWidth: number; - min: boolean; - plugins: Plugins; - printBasicPrototype: boolean; - printFunctionName: boolean; - printShadowRoot: boolean; - spacingInner: string; - spacingOuter: string; -} -type Printer = (val: unknown, config: Config, indentation: string, depth: number, refs: Refs, hasCalledToJSON?: boolean) => string; -type Test = (arg0: any) => boolean; -interface NewPlugin { - serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string; - test: Test; -} -interface PluginOptions { - edgeSpacing: string; - min: boolean; - spacing: string; -} -interface OldPlugin { - print: (val: unknown, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string; - test: Test; -} -type Plugin = NewPlugin | OldPlugin; -type Plugins = Array<Plugin>; - -/** -* Copyright (c) Meta Platforms, Inc. and affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -declare const DEFAULT_OPTIONS: Options; -/** -* Returns a presentation string of your `val` object -* @param val any potential JavaScript object -* @param options Custom settings -*/ -declare function format(val: unknown, options?: OptionsReceived): string; -declare const plugins: { - AsymmetricMatcher: NewPlugin; - DOMCollection: NewPlugin; - DOMElement: NewPlugin; - Immutable: NewPlugin; - ReactElement: NewPlugin; - ReactTestComponent: NewPlugin; - Error: NewPlugin; -}; - -export { DEFAULT_OPTIONS, format, plugins }; -export type { Colors, CompareKeys, Config, NewPlugin, OldPlugin, Options, OptionsReceived, Plugin, Plugins, PrettyFormatOptions, Printer, Refs, Theme }; diff --git a/vanilla/node_modules/@vitest/pretty-format/dist/index.js b/vanilla/node_modules/@vitest/pretty-format/dist/index.js deleted file mode 100644 index f134477..0000000 --- a/vanilla/node_modules/@vitest/pretty-format/dist/index.js +++ /dev/null @@ -1,1022 +0,0 @@ -import styles from 'tinyrainbow'; - -function _mergeNamespaces(n, m) { - m.forEach(function (e) { - e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { - if (k !== 'default' && !(k in n)) { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); - }); - return Object.freeze(n); -} - -function getKeysOfEnumerableProperties(object, compareKeys) { - const rawKeys = Object.keys(object); - const keys = compareKeys === null ? rawKeys : rawKeys.sort(compareKeys); - if (Object.getOwnPropertySymbols) { - for (const symbol of Object.getOwnPropertySymbols(object)) { - if (Object.getOwnPropertyDescriptor(object, symbol).enumerable) { - keys.push(symbol); - } - } - } - return keys; -} -/** -* Return entries (for example, of a map) -* with spacing, indentation, and comma -* without surrounding punctuation (for example, braces) -*/ -function printIteratorEntries(iterator, config, indentation, depth, refs, printer, separator = ": ") { - let result = ""; - let width = 0; - let current = iterator.next(); - if (!current.done) { - result += config.spacingOuter; - const indentationNext = indentation + config.indent; - while (!current.done) { - result += indentationNext; - if (width++ === config.maxWidth) { - result += "…"; - break; - } - const name = printer(current.value[0], config, indentationNext, depth, refs); - const value = printer(current.value[1], config, indentationNext, depth, refs); - result += name + separator + value; - current = iterator.next(); - if (!current.done) { - result += `,${config.spacingInner}`; - } else if (!config.min) { - result += ","; - } - } - result += config.spacingOuter + indentation; - } - return result; -} -/** -* Return values (for example, of a set) -* with spacing, indentation, and comma -* without surrounding punctuation (braces or brackets) -*/ -function printIteratorValues(iterator, config, indentation, depth, refs, printer) { - let result = ""; - let width = 0; - let current = iterator.next(); - if (!current.done) { - result += config.spacingOuter; - const indentationNext = indentation + config.indent; - while (!current.done) { - result += indentationNext; - if (width++ === config.maxWidth) { - result += "…"; - break; - } - result += printer(current.value, config, indentationNext, depth, refs); - current = iterator.next(); - if (!current.done) { - result += `,${config.spacingInner}`; - } else if (!config.min) { - result += ","; - } - } - result += config.spacingOuter + indentation; - } - return result; -} -/** -* Return items (for example, of an array) -* with spacing, indentation, and comma -* without surrounding punctuation (for example, brackets) -*/ -function printListItems(list, config, indentation, depth, refs, printer) { - let result = ""; - list = list instanceof ArrayBuffer ? new DataView(list) : list; - const isDataView = (l) => l instanceof DataView; - const length = isDataView(list) ? list.byteLength : list.length; - if (length > 0) { - result += config.spacingOuter; - const indentationNext = indentation + config.indent; - for (let i = 0; i < length; i++) { - result += indentationNext; - if (i === config.maxWidth) { - result += "…"; - break; - } - if (isDataView(list) || i in list) { - result += printer(isDataView(list) ? list.getInt8(i) : list[i], config, indentationNext, depth, refs); - } - if (i < length - 1) { - result += `,${config.spacingInner}`; - } else if (!config.min) { - result += ","; - } - } - result += config.spacingOuter + indentation; - } - return result; -} -/** -* Return properties of an object -* with spacing, indentation, and comma -* without surrounding punctuation (for example, braces) -*/ -function printObjectProperties(val, config, indentation, depth, refs, printer) { - let result = ""; - const keys = getKeysOfEnumerableProperties(val, config.compareKeys); - if (keys.length > 0) { - result += config.spacingOuter; - const indentationNext = indentation + config.indent; - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const name = printer(key, config, indentationNext, depth, refs); - const value = printer(val[key], config, indentationNext, depth, refs); - result += `${indentationNext + name}: ${value}`; - if (i < keys.length - 1) { - result += `,${config.spacingInner}`; - } else if (!config.min) { - result += ","; - } - } - result += config.spacingOuter + indentation; - } - return result; -} - -const asymmetricMatcher = typeof Symbol === "function" && Symbol.for ? Symbol.for("jest.asymmetricMatcher") : 1267621; -const SPACE$2 = " "; -const serialize$5 = (val, config, indentation, depth, refs, printer) => { - const stringedValue = val.toString(); - if (stringedValue === "ArrayContaining" || stringedValue === "ArrayNotContaining") { - if (++depth > config.maxDepth) { - return `[${stringedValue}]`; - } - return `${stringedValue + SPACE$2}[${printListItems(val.sample, config, indentation, depth, refs, printer)}]`; - } - if (stringedValue === "ObjectContaining" || stringedValue === "ObjectNotContaining") { - if (++depth > config.maxDepth) { - return `[${stringedValue}]`; - } - return `${stringedValue + SPACE$2}{${printObjectProperties(val.sample, config, indentation, depth, refs, printer)}}`; - } - if (stringedValue === "StringMatching" || stringedValue === "StringNotMatching") { - return stringedValue + SPACE$2 + printer(val.sample, config, indentation, depth, refs); - } - if (stringedValue === "StringContaining" || stringedValue === "StringNotContaining") { - return stringedValue + SPACE$2 + printer(val.sample, config, indentation, depth, refs); - } - if (typeof val.toAsymmetricMatcher !== "function") { - throw new TypeError(`Asymmetric matcher ${val.constructor.name} does not implement toAsymmetricMatcher()`); - } - return val.toAsymmetricMatcher(); -}; -const test$5 = (val) => val && val.$$typeof === asymmetricMatcher; -const plugin$5 = { - serialize: serialize$5, - test: test$5 -}; - -const SPACE$1 = " "; -const OBJECT_NAMES = new Set(["DOMStringMap", "NamedNodeMap"]); -const ARRAY_REGEXP = /^(?:HTML\w*Collection|NodeList)$/; -function testName(name) { - return OBJECT_NAMES.has(name) || ARRAY_REGEXP.test(name); -} -const test$4 = (val) => val && val.constructor && !!val.constructor.name && testName(val.constructor.name); -function isNamedNodeMap(collection) { - return collection.constructor.name === "NamedNodeMap"; -} -const serialize$4 = (collection, config, indentation, depth, refs, printer) => { - const name = collection.constructor.name; - if (++depth > config.maxDepth) { - return `[${name}]`; - } - return (config.min ? "" : name + SPACE$1) + (OBJECT_NAMES.has(name) ? `{${printObjectProperties(isNamedNodeMap(collection) ? [...collection].reduce((props, attribute) => { - props[attribute.name] = attribute.value; - return props; - }, {}) : { ...collection }, config, indentation, depth, refs, printer)}}` : `[${printListItems([...collection], config, indentation, depth, refs, printer)}]`); -}; -const plugin$4 = { - serialize: serialize$4, - test: test$4 -}; - -/** -* Copyright (c) Meta Platforms, Inc. and affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -function escapeHTML(str) { - return str.replaceAll("<", "<").replaceAll(">", ">"); -} - -// Return empty string if keys is empty. -function printProps(keys, props, config, indentation, depth, refs, printer) { - const indentationNext = indentation + config.indent; - const colors = config.colors; - return keys.map((key) => { - const value = props[key]; - // hidden injected value that should not be printed - if (typeof value === "string" && value[0] === "_" && value.startsWith("__vitest_") && value.match(/__vitest_\d+__/)) { - return ""; - } - let printed = printer(value, config, indentationNext, depth, refs); - if (typeof value !== "string") { - if (printed.includes("\n")) { - printed = config.spacingOuter + indentationNext + printed + config.spacingOuter + indentation; - } - printed = `{${printed}}`; - } - return `${config.spacingInner + indentation + colors.prop.open + key + colors.prop.close}=${colors.value.open}${printed}${colors.value.close}`; - }).join(""); -} -// Return empty string if children is empty. -function printChildren(children, config, indentation, depth, refs, printer) { - return children.map((child) => config.spacingOuter + indentation + (typeof child === "string" ? printText(child, config) : printer(child, config, indentation, depth, refs))).join(""); -} -function printShadowRoot(children, config, indentation, depth, refs, printer) { - if (config.printShadowRoot === false) { - return ""; - } - return [`${config.spacingOuter + indentation}#shadow-root`, printChildren(children, config, indentation + config.indent, depth, refs, printer)].join(""); -} -function printText(text, config) { - const contentColor = config.colors.content; - return contentColor.open + escapeHTML(text) + contentColor.close; -} -function printComment(comment, config) { - const commentColor = config.colors.comment; - return `${commentColor.open}<!--${escapeHTML(comment)}-->${commentColor.close}`; -} -// Separate the functions to format props, children, and element, -// so a plugin could override a particular function, if needed. -// Too bad, so sad: the traditional (but unnecessary) space -// in a self-closing tagColor requires a second test of printedProps. -function printElement(type, printedProps, printedChildren, config, indentation) { - const tagColor = config.colors.tag; - return `${tagColor.open}<${type}${printedProps && tagColor.close + printedProps + config.spacingOuter + indentation + tagColor.open}${printedChildren ? `>${tagColor.close}${printedChildren}${config.spacingOuter}${indentation}${tagColor.open}</${type}` : `${printedProps && !config.min ? "" : " "}/`}>${tagColor.close}`; -} -function printElementAsLeaf(type, config) { - const tagColor = config.colors.tag; - return `${tagColor.open}<${type}${tagColor.close} …${tagColor.open} />${tagColor.close}`; -} - -const ELEMENT_NODE = 1; -const TEXT_NODE = 3; -const COMMENT_NODE = 8; -const FRAGMENT_NODE = 11; -const ELEMENT_REGEXP = /^(?:(?:HTML|SVG)\w*)?Element$/; -function testHasAttribute(val) { - try { - return typeof val.hasAttribute === "function" && val.hasAttribute("is"); - } catch { - return false; - } -} -function testNode(val) { - const constructorName = val.constructor.name; - const { nodeType, tagName } = val; - const isCustomElement = typeof tagName === "string" && tagName.includes("-") || testHasAttribute(val); - return nodeType === ELEMENT_NODE && (ELEMENT_REGEXP.test(constructorName) || isCustomElement) || nodeType === TEXT_NODE && constructorName === "Text" || nodeType === COMMENT_NODE && constructorName === "Comment" || nodeType === FRAGMENT_NODE && constructorName === "DocumentFragment"; -} -const test$3 = (val) => val?.constructor?.name && testNode(val); -function nodeIsText(node) { - return node.nodeType === TEXT_NODE; -} -function nodeIsComment(node) { - return node.nodeType === COMMENT_NODE; -} -function nodeIsFragment(node) { - return node.nodeType === FRAGMENT_NODE; -} -const serialize$3 = (node, config, indentation, depth, refs, printer) => { - if (nodeIsText(node)) { - return printText(node.data, config); - } - if (nodeIsComment(node)) { - return printComment(node.data, config); - } - const type = nodeIsFragment(node) ? "DocumentFragment" : node.tagName.toLowerCase(); - if (++depth > config.maxDepth) { - return printElementAsLeaf(type, config); - } - return printElement(type, printProps(nodeIsFragment(node) ? [] : Array.from(node.attributes, (attr) => attr.name).sort(), nodeIsFragment(node) ? {} : [...node.attributes].reduce((props, attribute) => { - props[attribute.name] = attribute.value; - return props; - }, {}), config, indentation + config.indent, depth, refs, printer), (nodeIsFragment(node) || !node.shadowRoot ? "" : printShadowRoot(Array.prototype.slice.call(node.shadowRoot.children), config, indentation + config.indent, depth, refs, printer)) + printChildren(Array.prototype.slice.call(node.childNodes || node.children), config, indentation + config.indent, depth, refs, printer), config, indentation); -}; -const plugin$3 = { - serialize: serialize$3, - test: test$3 -}; - -// SENTINEL constants are from https://github.com/facebook/immutable-js -const IS_ITERABLE_SENTINEL = "@@__IMMUTABLE_ITERABLE__@@"; -const IS_LIST_SENTINEL = "@@__IMMUTABLE_LIST__@@"; -const IS_KEYED_SENTINEL = "@@__IMMUTABLE_KEYED__@@"; -const IS_MAP_SENTINEL = "@@__IMMUTABLE_MAP__@@"; -const IS_ORDERED_SENTINEL = "@@__IMMUTABLE_ORDERED__@@"; -const IS_RECORD_SENTINEL = "@@__IMMUTABLE_RECORD__@@"; -const IS_SEQ_SENTINEL = "@@__IMMUTABLE_SEQ__@@"; -const IS_SET_SENTINEL = "@@__IMMUTABLE_SET__@@"; -const IS_STACK_SENTINEL = "@@__IMMUTABLE_STACK__@@"; -const getImmutableName = (name) => `Immutable.${name}`; -const printAsLeaf = (name) => `[${name}]`; -const SPACE = " "; -const LAZY = "…"; -function printImmutableEntries(val, config, indentation, depth, refs, printer, type) { - return ++depth > config.maxDepth ? printAsLeaf(getImmutableName(type)) : `${getImmutableName(type) + SPACE}{${printIteratorEntries(val.entries(), config, indentation, depth, refs, printer)}}`; -} -// Record has an entries method because it is a collection in immutable v3. -// Return an iterator for Immutable Record from version v3 or v4. -function getRecordEntries(val) { - let i = 0; - return { next() { - if (i < val._keys.length) { - const key = val._keys[i++]; - return { - done: false, - value: [key, val.get(key)] - }; - } - return { - done: true, - value: undefined - }; - } }; -} -function printImmutableRecord(val, config, indentation, depth, refs, printer) { - // _name property is defined only for an Immutable Record instance - // which was constructed with a second optional descriptive name arg - const name = getImmutableName(val._name || "Record"); - return ++depth > config.maxDepth ? printAsLeaf(name) : `${name + SPACE}{${printIteratorEntries(getRecordEntries(val), config, indentation, depth, refs, printer)}}`; -} -function printImmutableSeq(val, config, indentation, depth, refs, printer) { - const name = getImmutableName("Seq"); - if (++depth > config.maxDepth) { - return printAsLeaf(name); - } - if (val[IS_KEYED_SENTINEL]) { - return `${name + SPACE}{${val._iter || val._object ? printIteratorEntries(val.entries(), config, indentation, depth, refs, printer) : LAZY}}`; - } - return `${name + SPACE}[${val._iter || val._array || val._collection || val._iterable ? printIteratorValues(val.values(), config, indentation, depth, refs, printer) : LAZY}]`; -} -function printImmutableValues(val, config, indentation, depth, refs, printer, type) { - return ++depth > config.maxDepth ? printAsLeaf(getImmutableName(type)) : `${getImmutableName(type) + SPACE}[${printIteratorValues(val.values(), config, indentation, depth, refs, printer)}]`; -} -const serialize$2 = (val, config, indentation, depth, refs, printer) => { - if (val[IS_MAP_SENTINEL]) { - return printImmutableEntries(val, config, indentation, depth, refs, printer, val[IS_ORDERED_SENTINEL] ? "OrderedMap" : "Map"); - } - if (val[IS_LIST_SENTINEL]) { - return printImmutableValues(val, config, indentation, depth, refs, printer, "List"); - } - if (val[IS_SET_SENTINEL]) { - return printImmutableValues(val, config, indentation, depth, refs, printer, val[IS_ORDERED_SENTINEL] ? "OrderedSet" : "Set"); - } - if (val[IS_STACK_SENTINEL]) { - return printImmutableValues(val, config, indentation, depth, refs, printer, "Stack"); - } - if (val[IS_SEQ_SENTINEL]) { - return printImmutableSeq(val, config, indentation, depth, refs, printer); - } - // For compatibility with immutable v3 and v4, let record be the default. - return printImmutableRecord(val, config, indentation, depth, refs, printer); -}; -// Explicitly comparing sentinel properties to true avoids false positive -// when mock identity-obj-proxy returns the key as the value for any key. -const test$2 = (val) => val && (val[IS_ITERABLE_SENTINEL] === true || val[IS_RECORD_SENTINEL] === true); -const plugin$2 = { - serialize: serialize$2, - test: test$2 -}; - -function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; -} - -var reactIs$1 = {exports: {}}; - -var reactIs_production = {}; - -/** - * @license React - * react-is.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredReactIs_production; - -function requireReactIs_production () { - if (hasRequiredReactIs_production) return reactIs_production; - hasRequiredReactIs_production = 1; - var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), - REACT_PORTAL_TYPE = Symbol.for("react.portal"), - REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), - REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), - REACT_PROFILER_TYPE = Symbol.for("react.profiler"), - REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), - REACT_CONTEXT_TYPE = Symbol.for("react.context"), - REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), - REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), - REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), - REACT_MEMO_TYPE = Symbol.for("react.memo"), - REACT_LAZY_TYPE = Symbol.for("react.lazy"), - REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), - REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"); - function typeOf(object) { - if ("object" === typeof object && null !== object) { - var $$typeof = object.$$typeof; - switch ($$typeof) { - case REACT_ELEMENT_TYPE: - switch (((object = object.type), object)) { - case REACT_FRAGMENT_TYPE: - case REACT_PROFILER_TYPE: - case REACT_STRICT_MODE_TYPE: - case REACT_SUSPENSE_TYPE: - case REACT_SUSPENSE_LIST_TYPE: - case REACT_VIEW_TRANSITION_TYPE: - return object; - default: - switch (((object = object && object.$$typeof), object)) { - case REACT_CONTEXT_TYPE: - case REACT_FORWARD_REF_TYPE: - case REACT_LAZY_TYPE: - case REACT_MEMO_TYPE: - return object; - case REACT_CONSUMER_TYPE: - return object; - default: - return $$typeof; - } - } - case REACT_PORTAL_TYPE: - return $$typeof; - } - } - } - reactIs_production.ContextConsumer = REACT_CONSUMER_TYPE; - reactIs_production.ContextProvider = REACT_CONTEXT_TYPE; - reactIs_production.Element = REACT_ELEMENT_TYPE; - reactIs_production.ForwardRef = REACT_FORWARD_REF_TYPE; - reactIs_production.Fragment = REACT_FRAGMENT_TYPE; - reactIs_production.Lazy = REACT_LAZY_TYPE; - reactIs_production.Memo = REACT_MEMO_TYPE; - reactIs_production.Portal = REACT_PORTAL_TYPE; - reactIs_production.Profiler = REACT_PROFILER_TYPE; - reactIs_production.StrictMode = REACT_STRICT_MODE_TYPE; - reactIs_production.Suspense = REACT_SUSPENSE_TYPE; - reactIs_production.SuspenseList = REACT_SUSPENSE_LIST_TYPE; - reactIs_production.isContextConsumer = function (object) { - return typeOf(object) === REACT_CONSUMER_TYPE; - }; - reactIs_production.isContextProvider = function (object) { - return typeOf(object) === REACT_CONTEXT_TYPE; - }; - reactIs_production.isElement = function (object) { - return ( - "object" === typeof object && - null !== object && - object.$$typeof === REACT_ELEMENT_TYPE - ); - }; - reactIs_production.isForwardRef = function (object) { - return typeOf(object) === REACT_FORWARD_REF_TYPE; - }; - reactIs_production.isFragment = function (object) { - return typeOf(object) === REACT_FRAGMENT_TYPE; - }; - reactIs_production.isLazy = function (object) { - return typeOf(object) === REACT_LAZY_TYPE; - }; - reactIs_production.isMemo = function (object) { - return typeOf(object) === REACT_MEMO_TYPE; - }; - reactIs_production.isPortal = function (object) { - return typeOf(object) === REACT_PORTAL_TYPE; - }; - reactIs_production.isProfiler = function (object) { - return typeOf(object) === REACT_PROFILER_TYPE; - }; - reactIs_production.isStrictMode = function (object) { - return typeOf(object) === REACT_STRICT_MODE_TYPE; - }; - reactIs_production.isSuspense = function (object) { - return typeOf(object) === REACT_SUSPENSE_TYPE; - }; - reactIs_production.isSuspenseList = function (object) { - return typeOf(object) === REACT_SUSPENSE_LIST_TYPE; - }; - reactIs_production.isValidElementType = function (type) { - return "string" === typeof type || - "function" === typeof type || - type === REACT_FRAGMENT_TYPE || - type === REACT_PROFILER_TYPE || - type === REACT_STRICT_MODE_TYPE || - type === REACT_SUSPENSE_TYPE || - type === REACT_SUSPENSE_LIST_TYPE || - ("object" === typeof type && - null !== type && - (type.$$typeof === REACT_LAZY_TYPE || - type.$$typeof === REACT_MEMO_TYPE || - type.$$typeof === REACT_CONTEXT_TYPE || - type.$$typeof === REACT_CONSUMER_TYPE || - type.$$typeof === REACT_FORWARD_REF_TYPE || - type.$$typeof === REACT_CLIENT_REFERENCE || - void 0 !== type.getModuleId)) - ? true - : false; - }; - reactIs_production.typeOf = typeOf; - return reactIs_production; -} - -var hasRequiredReactIs$1; - -function requireReactIs$1 () { - if (hasRequiredReactIs$1) return reactIs$1.exports; - hasRequiredReactIs$1 = 1; - - { - reactIs$1.exports = requireReactIs_production(); - } - return reactIs$1.exports; -} - -var reactIsExports$1 = requireReactIs$1(); -var index$1 = /*@__PURE__*/getDefaultExportFromCjs(reactIsExports$1); - -var ReactIs19 = /*#__PURE__*/_mergeNamespaces({ - __proto__: null, - default: index$1 -}, [reactIsExports$1]); - -var reactIs = {exports: {}}; - -var reactIs_production_min = {}; - -/** - * @license React - * react-is.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var hasRequiredReactIs_production_min; - -function requireReactIs_production_min () { - if (hasRequiredReactIs_production_min) return reactIs_production_min; - hasRequiredReactIs_production_min = 1; -var b=Symbol.for("react.element"),c=Symbol.for("react.portal"),d=Symbol.for("react.fragment"),e=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),g=Symbol.for("react.provider"),h=Symbol.for("react.context"),k=Symbol.for("react.server_context"),l=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),n=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),q=Symbol.for("react.lazy"),t=Symbol.for("react.offscreen"),u;u=Symbol.for("react.module.reference"); - function v(a){if("object"===typeof a&&null!==a){var r=a.$$typeof;switch(r){case b:switch(a=a.type,a){case d:case f:case e:case m:case n:return a;default:switch(a=a&&a.$$typeof,a){case k:case h:case l:case q:case p:case g:return a;default:return r}}case c:return r}}}reactIs_production_min.ContextConsumer=h;reactIs_production_min.ContextProvider=g;reactIs_production_min.Element=b;reactIs_production_min.ForwardRef=l;reactIs_production_min.Fragment=d;reactIs_production_min.Lazy=q;reactIs_production_min.Memo=p;reactIs_production_min.Portal=c;reactIs_production_min.Profiler=f;reactIs_production_min.StrictMode=e;reactIs_production_min.Suspense=m; - reactIs_production_min.SuspenseList=n;reactIs_production_min.isAsyncMode=function(){return false};reactIs_production_min.isConcurrentMode=function(){return false};reactIs_production_min.isContextConsumer=function(a){return v(a)===h};reactIs_production_min.isContextProvider=function(a){return v(a)===g};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===b};reactIs_production_min.isForwardRef=function(a){return v(a)===l};reactIs_production_min.isFragment=function(a){return v(a)===d};reactIs_production_min.isLazy=function(a){return v(a)===q};reactIs_production_min.isMemo=function(a){return v(a)===p}; - reactIs_production_min.isPortal=function(a){return v(a)===c};reactIs_production_min.isProfiler=function(a){return v(a)===f};reactIs_production_min.isStrictMode=function(a){return v(a)===e};reactIs_production_min.isSuspense=function(a){return v(a)===m};reactIs_production_min.isSuspenseList=function(a){return v(a)===n}; - reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===d||a===f||a===e||a===m||a===n||a===t||"object"===typeof a&&null!==a&&(a.$$typeof===q||a.$$typeof===p||a.$$typeof===g||a.$$typeof===h||a.$$typeof===l||a.$$typeof===u||void 0!==a.getModuleId)?true:false};reactIs_production_min.typeOf=v; - return reactIs_production_min; -} - -var hasRequiredReactIs; - -function requireReactIs () { - if (hasRequiredReactIs) return reactIs.exports; - hasRequiredReactIs = 1; - - { - reactIs.exports = requireReactIs_production_min(); - } - return reactIs.exports; -} - -var reactIsExports = requireReactIs(); -var index = /*@__PURE__*/getDefaultExportFromCjs(reactIsExports); - -var ReactIs18 = /*#__PURE__*/_mergeNamespaces({ - __proto__: null, - default: index -}, [reactIsExports]); - -const reactIsMethods = [ - "isAsyncMode", - "isConcurrentMode", - "isContextConsumer", - "isContextProvider", - "isElement", - "isForwardRef", - "isFragment", - "isLazy", - "isMemo", - "isPortal", - "isProfiler", - "isStrictMode", - "isSuspense", - "isSuspenseList", - "isValidElementType" -]; -const ReactIs = Object.fromEntries(reactIsMethods.map((m) => [m, (v) => ReactIs18[m](v) || ReactIs19[m](v)])); -// Given element.props.children, or subtree during recursive traversal, -// return flattened array of children. -function getChildren(arg, children = []) { - if (Array.isArray(arg)) { - for (const item of arg) { - getChildren(item, children); - } - } else if (arg != null && arg !== false && arg !== "") { - children.push(arg); - } - return children; -} -function getType(element) { - const type = element.type; - if (typeof type === "string") { - return type; - } - if (typeof type === "function") { - return type.displayName || type.name || "Unknown"; - } - if (ReactIs.isFragment(element)) { - return "React.Fragment"; - } - if (ReactIs.isSuspense(element)) { - return "React.Suspense"; - } - if (typeof type === "object" && type !== null) { - if (ReactIs.isContextProvider(element)) { - return "Context.Provider"; - } - if (ReactIs.isContextConsumer(element)) { - return "Context.Consumer"; - } - if (ReactIs.isForwardRef(element)) { - if (type.displayName) { - return type.displayName; - } - const functionName = type.render.displayName || type.render.name || ""; - return functionName === "" ? "ForwardRef" : `ForwardRef(${functionName})`; - } - if (ReactIs.isMemo(element)) { - const functionName = type.displayName || type.type.displayName || type.type.name || ""; - return functionName === "" ? "Memo" : `Memo(${functionName})`; - } - } - return "UNDEFINED"; -} -function getPropKeys$1(element) { - const { props } = element; - return Object.keys(props).filter((key) => key !== "children" && props[key] !== undefined).sort(); -} -const serialize$1 = (element, config, indentation, depth, refs, printer) => ++depth > config.maxDepth ? printElementAsLeaf(getType(element), config) : printElement(getType(element), printProps(getPropKeys$1(element), element.props, config, indentation + config.indent, depth, refs, printer), printChildren(getChildren(element.props.children), config, indentation + config.indent, depth, refs, printer), config, indentation); -const test$1 = (val) => val != null && ReactIs.isElement(val); -const plugin$1 = { - serialize: serialize$1, - test: test$1 -}; - -const testSymbol = typeof Symbol === "function" && Symbol.for ? Symbol.for("react.test.json") : 245830487; -function getPropKeys(object) { - const { props } = object; - return props ? Object.keys(props).filter((key) => props[key] !== undefined).sort() : []; -} -const serialize = (object, config, indentation, depth, refs, printer) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement(object.type, object.props ? printProps(getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer) : "", object.children ? printChildren(object.children, config, indentation + config.indent, depth, refs, printer) : "", config, indentation); -const test = (val) => val && val.$$typeof === testSymbol; -const plugin = { - serialize, - test -}; - -const toString = Object.prototype.toString; -const toISOString = Date.prototype.toISOString; -const errorToString = Error.prototype.toString; -const regExpToString = RegExp.prototype.toString; -/** -* Explicitly comparing typeof constructor to function avoids undefined as name -* when mock identity-obj-proxy returns the key as the value for any key. -*/ -function getConstructorName(val) { - return typeof val.constructor === "function" && val.constructor.name || "Object"; -} -/** Is val is equal to global window object? Works even if it does not exist :) */ -function isWindow(val) { - return typeof window !== "undefined" && val === window; -} -// eslint-disable-next-line regexp/no-super-linear-backtracking -const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; -const NEWLINE_REGEXP = /\n/g; -class PrettyFormatPluginError extends Error { - constructor(message, stack) { - super(message); - this.stack = stack; - this.name = this.constructor.name; - } -} -function isToStringedArrayType(toStringed) { - return toStringed === "[object Array]" || toStringed === "[object ArrayBuffer]" || toStringed === "[object DataView]" || toStringed === "[object Float32Array]" || toStringed === "[object Float64Array]" || toStringed === "[object Int8Array]" || toStringed === "[object Int16Array]" || toStringed === "[object Int32Array]" || toStringed === "[object Uint8Array]" || toStringed === "[object Uint8ClampedArray]" || toStringed === "[object Uint16Array]" || toStringed === "[object Uint32Array]"; -} -function printNumber(val) { - return Object.is(val, -0) ? "-0" : String(val); -} -function printBigInt(val) { - return String(`${val}n`); -} -function printFunction(val, printFunctionName) { - if (!printFunctionName) { - return "[Function]"; - } - return `[Function ${val.name || "anonymous"}]`; -} -function printSymbol(val) { - return String(val).replace(SYMBOL_REGEXP, "Symbol($1)"); -} -function printError(val) { - return `[${errorToString.call(val)}]`; -} -/** -* The first port of call for printing an object, handles most of the -* data-types in JS. -*/ -function printBasicValue(val, printFunctionName, escapeRegex, escapeString) { - if (val === true || val === false) { - return `${val}`; - } - if (val === undefined) { - return "undefined"; - } - if (val === null) { - return "null"; - } - const typeOf = typeof val; - if (typeOf === "number") { - return printNumber(val); - } - if (typeOf === "bigint") { - return printBigInt(val); - } - if (typeOf === "string") { - if (escapeString) { - return `"${val.replaceAll(/"|\\/g, "\\$&")}"`; - } - return `"${val}"`; - } - if (typeOf === "function") { - return printFunction(val, printFunctionName); - } - if (typeOf === "symbol") { - return printSymbol(val); - } - const toStringed = toString.call(val); - if (toStringed === "[object WeakMap]") { - return "WeakMap {}"; - } - if (toStringed === "[object WeakSet]") { - return "WeakSet {}"; - } - if (toStringed === "[object Function]" || toStringed === "[object GeneratorFunction]") { - return printFunction(val, printFunctionName); - } - if (toStringed === "[object Symbol]") { - return printSymbol(val); - } - if (toStringed === "[object Date]") { - return Number.isNaN(+val) ? "Date { NaN }" : toISOString.call(val); - } - if (toStringed === "[object Error]") { - return printError(val); - } - if (toStringed === "[object RegExp]") { - if (escapeRegex) { - // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js - return regExpToString.call(val).replaceAll(/[$()*+.?[\\\]^{|}]/g, "\\$&"); - } - return regExpToString.call(val); - } - if (val instanceof Error) { - return printError(val); - } - return null; -} -/** -* Handles more complex objects ( such as objects with circular references. -* maps and sets etc ) -*/ -function printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON) { - if (refs.includes(val)) { - return "[Circular]"; - } - refs = [...refs]; - refs.push(val); - const hitMaxDepth = ++depth > config.maxDepth; - const min = config.min; - if (config.callToJSON && !hitMaxDepth && val.toJSON && typeof val.toJSON === "function" && !hasCalledToJSON) { - return printer(val.toJSON(), config, indentation, depth, refs, true); - } - const toStringed = toString.call(val); - if (toStringed === "[object Arguments]") { - return hitMaxDepth ? "[Arguments]" : `${min ? "" : "Arguments "}[${printListItems(val, config, indentation, depth, refs, printer)}]`; - } - if (isToStringedArrayType(toStringed)) { - return hitMaxDepth ? `[${val.constructor.name}]` : `${min ? "" : !config.printBasicPrototype && val.constructor.name === "Array" ? "" : `${val.constructor.name} `}[${printListItems(val, config, indentation, depth, refs, printer)}]`; - } - if (toStringed === "[object Map]") { - return hitMaxDepth ? "[Map]" : `Map {${printIteratorEntries(val.entries(), config, indentation, depth, refs, printer, " => ")}}`; - } - if (toStringed === "[object Set]") { - return hitMaxDepth ? "[Set]" : `Set {${printIteratorValues(val.values(), config, indentation, depth, refs, printer)}}`; - } - // Avoid failure to serialize global window object in jsdom test environment. - // For example, not even relevant if window is prop of React element. - return hitMaxDepth || isWindow(val) ? `[${getConstructorName(val)}]` : `${min ? "" : !config.printBasicPrototype && getConstructorName(val) === "Object" ? "" : `${getConstructorName(val)} `}{${printObjectProperties(val, config, indentation, depth, refs, printer)}}`; -} -const ErrorPlugin = { - test: (val) => val && val instanceof Error, - serialize(val, config, indentation, depth, refs, printer) { - if (refs.includes(val)) { - return "[Circular]"; - } - refs = [...refs, val]; - const hitMaxDepth = ++depth > config.maxDepth; - const { message, cause, ...rest } = val; - const entries = { - message, - ...typeof cause !== "undefined" ? { cause } : {}, - ...val instanceof AggregateError ? { errors: val.errors } : {}, - ...rest - }; - const name = val.name !== "Error" ? val.name : getConstructorName(val); - return hitMaxDepth ? `[${name}]` : `${name} {${printIteratorEntries(Object.entries(entries).values(), config, indentation, depth, refs, printer)}}`; - } -}; -function isNewPlugin(plugin) { - return plugin.serialize != null; -} -function printPlugin(plugin, val, config, indentation, depth, refs) { - let printed; - try { - printed = isNewPlugin(plugin) ? plugin.serialize(val, config, indentation, depth, refs, printer) : plugin.print(val, (valChild) => printer(valChild, config, indentation, depth, refs), (str) => { - const indentationNext = indentation + config.indent; - return indentationNext + str.replaceAll(NEWLINE_REGEXP, `\n${indentationNext}`); - }, { - edgeSpacing: config.spacingOuter, - min: config.min, - spacing: config.spacingInner - }, config.colors); - } catch (error) { - throw new PrettyFormatPluginError(error.message, error.stack); - } - if (typeof printed !== "string") { - throw new TypeError(`pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`); - } - return printed; -} -function findPlugin(plugins, val) { - for (const plugin of plugins) { - try { - if (plugin.test(val)) { - return plugin; - } - } catch (error) { - throw new PrettyFormatPluginError(error.message, error.stack); - } - } - return null; -} -function printer(val, config, indentation, depth, refs, hasCalledToJSON) { - const plugin = findPlugin(config.plugins, val); - if (plugin !== null) { - return printPlugin(plugin, val, config, indentation, depth, refs); - } - const basicResult = printBasicValue(val, config.printFunctionName, config.escapeRegex, config.escapeString); - if (basicResult !== null) { - return basicResult; - } - return printComplexValue(val, config, indentation, depth, refs, hasCalledToJSON); -} -const DEFAULT_THEME = { - comment: "gray", - content: "reset", - prop: "yellow", - tag: "cyan", - value: "green" -}; -const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME); -const DEFAULT_OPTIONS = { - callToJSON: true, - compareKeys: undefined, - escapeRegex: false, - escapeString: true, - highlight: false, - indent: 2, - maxDepth: Number.POSITIVE_INFINITY, - maxWidth: Number.POSITIVE_INFINITY, - min: false, - plugins: [], - printBasicPrototype: true, - printFunctionName: true, - printShadowRoot: true, - theme: DEFAULT_THEME -}; -function validateOptions(options) { - for (const key of Object.keys(options)) { - if (!Object.hasOwn(DEFAULT_OPTIONS, key)) { - throw new Error(`pretty-format: Unknown option "${key}".`); - } - } - if (options.min && options.indent !== undefined && options.indent !== 0) { - throw new Error("pretty-format: Options \"min\" and \"indent\" cannot be used together."); - } -} -function getColorsHighlight() { - return DEFAULT_THEME_KEYS.reduce((colors, key) => { - const value = DEFAULT_THEME[key]; - const color = value && styles[value]; - if (color && typeof color.close === "string" && typeof color.open === "string") { - colors[key] = color; - } else { - throw new Error(`pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`); - } - return colors; - }, Object.create(null)); -} -function getColorsEmpty() { - return DEFAULT_THEME_KEYS.reduce((colors, key) => { - colors[key] = { - close: "", - open: "" - }; - return colors; - }, Object.create(null)); -} -function getPrintFunctionName(options) { - return options?.printFunctionName ?? DEFAULT_OPTIONS.printFunctionName; -} -function getEscapeRegex(options) { - return options?.escapeRegex ?? DEFAULT_OPTIONS.escapeRegex; -} -function getEscapeString(options) { - return options?.escapeString ?? DEFAULT_OPTIONS.escapeString; -} -function getConfig(options) { - return { - callToJSON: options?.callToJSON ?? DEFAULT_OPTIONS.callToJSON, - colors: options?.highlight ? getColorsHighlight() : getColorsEmpty(), - compareKeys: typeof options?.compareKeys === "function" || options?.compareKeys === null ? options.compareKeys : DEFAULT_OPTIONS.compareKeys, - escapeRegex: getEscapeRegex(options), - escapeString: getEscapeString(options), - indent: options?.min ? "" : createIndent(options?.indent ?? DEFAULT_OPTIONS.indent), - maxDepth: options?.maxDepth ?? DEFAULT_OPTIONS.maxDepth, - maxWidth: options?.maxWidth ?? DEFAULT_OPTIONS.maxWidth, - min: options?.min ?? DEFAULT_OPTIONS.min, - plugins: options?.plugins ?? DEFAULT_OPTIONS.plugins, - printBasicPrototype: options?.printBasicPrototype ?? true, - printFunctionName: getPrintFunctionName(options), - printShadowRoot: options?.printShadowRoot ?? true, - spacingInner: options?.min ? " " : "\n", - spacingOuter: options?.min ? "" : "\n" - }; -} -function createIndent(indent) { - return Array.from({ length: indent + 1 }).join(" "); -} -/** -* Returns a presentation string of your `val` object -* @param val any potential JavaScript object -* @param options Custom settings -*/ -function format(val, options) { - if (options) { - validateOptions(options); - if (options.plugins) { - const plugin = findPlugin(options.plugins, val); - if (plugin !== null) { - return printPlugin(plugin, val, getConfig(options), "", 0, []); - } - } - } - const basicResult = printBasicValue(val, getPrintFunctionName(options), getEscapeRegex(options), getEscapeString(options)); - if (basicResult !== null) { - return basicResult; - } - return printComplexValue(val, getConfig(options), "", 0, []); -} -const plugins = { - AsymmetricMatcher: plugin$5, - DOMCollection: plugin$4, - DOMElement: plugin$3, - Immutable: plugin$2, - ReactElement: plugin$1, - ReactTestComponent: plugin, - Error: ErrorPlugin -}; - -export { DEFAULT_OPTIONS, format, plugins }; diff --git a/vanilla/node_modules/@vitest/pretty-format/package.json b/vanilla/node_modules/@vitest/pretty-format/package.json deleted file mode 100644 index 44a0098..0000000 --- a/vanilla/node_modules/@vitest/pretty-format/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "@vitest/pretty-format", - "type": "module", - "version": "4.0.18", - "description": "Fork of pretty-format with support for ESM", - "license": "MIT", - "funding": "https://opencollective.com/vitest", - "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils#readme", - "repository": { - "type": "git", - "url": "git+https://github.com/vitest-dev/vitest.git", - "directory": "packages/pretty-format" - }, - "bugs": { - "url": "https://github.com/vitest-dev/vitest/issues" - }, - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./*": "./*" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "*.d.ts", - "dist" - ], - "dependencies": { - "tinyrainbow": "^3.0.3" - }, - "devDependencies": { - "@types/react-is": "^19.2.0", - "react-is": "^19.2.0", - "react-is-18": "npm:react-is@18.3.1" - }, - "scripts": { - "build": "premove dist && rollup -c", - "dev": "rollup -c --watch" - } -}
\ No newline at end of file diff --git a/vanilla/node_modules/@vitest/runner/LICENSE b/vanilla/node_modules/@vitest/runner/LICENSE deleted file mode 100644 index 0e5771d..0000000 --- a/vanilla/node_modules/@vitest/runner/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vanilla/node_modules/@vitest/runner/README.md b/vanilla/node_modules/@vitest/runner/README.md deleted file mode 100644 index 2796b6a..0000000 --- a/vanilla/node_modules/@vitest/runner/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# @vitest/runner - -Vitest mechanism to collect and run tasks. - -[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/advanced/runner) diff --git a/vanilla/node_modules/@vitest/runner/dist/chunk-tasks.js b/vanilla/node_modules/@vitest/runner/dist/chunk-tasks.js deleted file mode 100644 index a66af35..0000000 --- a/vanilla/node_modules/@vitest/runner/dist/chunk-tasks.js +++ /dev/null @@ -1,340 +0,0 @@ -import { processError } from '@vitest/utils/error'; -import { parseSingleStack } from '@vitest/utils/source-map'; -import { relative } from 'pathe'; -import { toArray } from '@vitest/utils/helpers'; - -function createChainable(keys, fn) { - function create(context) { - const chain = function(...args) { - return fn.apply(context, args); - }; - Object.assign(chain, fn); - chain.withContext = () => chain.bind(context); - chain.setContext = (key, value) => { - context[key] = value; - }; - chain.mergeContext = (ctx) => { - Object.assign(context, ctx); - }; - for (const key of keys) { - Object.defineProperty(chain, key, { get() { - return create({ - ...context, - [key]: true - }); - } }); - } - return chain; - } - const chain = create({}); - chain.fn = fn; - return chain; -} - -/** -* If any tasks been marked as `only`, mark all other tasks as `skip`. -*/ -function interpretTaskModes(file, namePattern, testLocations, onlyMode, parentIsOnly, allowOnly) { - const matchedLocations = []; - const traverseSuite = (suite, parentIsOnly, parentMatchedWithLocation) => { - const suiteIsOnly = parentIsOnly || suite.mode === "only"; - // Check if any tasks in this suite have `.only` - if so, only those should run - const hasSomeTasksOnly = onlyMode && suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t)); - suite.tasks.forEach((t) => { - // Check if either the parent suite or the task itself are marked as included - // If there are tasks with `.only` in this suite, only include those (not all tasks from describe.only) - const includeTask = hasSomeTasksOnly ? t.mode === "only" || t.type === "suite" && someTasksAreOnly(t) : suiteIsOnly || t.mode === "only"; - if (onlyMode) { - if (t.type === "suite" && (includeTask || someTasksAreOnly(t))) { - // Don't skip this suite - if (t.mode === "only") { - checkAllowOnly(t, allowOnly); - t.mode = "run"; - } - } else if (t.mode === "run" && !includeTask) { - t.mode = "skip"; - } else if (t.mode === "only") { - checkAllowOnly(t, allowOnly); - t.mode = "run"; - } - } - let hasLocationMatch = parentMatchedWithLocation; - // Match test location against provided locations, only run if present - // in `testLocations`. Note: if `includeTaskLocations` is not enabled, - // all test will be skipped. - if (testLocations !== undefined && testLocations.length !== 0) { - if (t.location && (testLocations === null || testLocations === void 0 ? void 0 : testLocations.includes(t.location.line))) { - t.mode = "run"; - matchedLocations.push(t.location.line); - hasLocationMatch = true; - } else if (parentMatchedWithLocation) { - t.mode = "run"; - } else if (t.type === "test") { - t.mode = "skip"; - } - } - if (t.type === "test") { - if (namePattern && !getTaskFullName(t).match(namePattern)) { - t.mode = "skip"; - } - } else if (t.type === "suite") { - if (t.mode === "skip") { - skipAllTasks(t); - } else if (t.mode === "todo") { - todoAllTasks(t); - } else { - traverseSuite(t, includeTask, hasLocationMatch); - } - } - }); - // if all subtasks are skipped, mark as skip - if (suite.mode === "run" || suite.mode === "queued") { - if (suite.tasks.length && suite.tasks.every((i) => i.mode !== "run" && i.mode !== "queued")) { - suite.mode = "skip"; - } - } - }; - traverseSuite(file, parentIsOnly, false); - const nonMatching = testLocations === null || testLocations === void 0 ? void 0 : testLocations.filter((loc) => !matchedLocations.includes(loc)); - if (nonMatching && nonMatching.length !== 0) { - const message = nonMatching.length === 1 ? `line ${nonMatching[0]}` : `lines ${nonMatching.join(", ")}`; - if (file.result === undefined) { - file.result = { - state: "fail", - errors: [] - }; - } - if (file.result.errors === undefined) { - file.result.errors = []; - } - file.result.errors.push(processError(new Error(`No test found in ${file.name} in ${message}`))); - } -} -function getTaskFullName(task) { - return `${task.suite ? `${getTaskFullName(task.suite)} ` : ""}${task.name}`; -} -function someTasksAreOnly(suite) { - return suite.tasks.some((t) => t.mode === "only" || t.type === "suite" && someTasksAreOnly(t)); -} -function skipAllTasks(suite) { - suite.tasks.forEach((t) => { - if (t.mode === "run" || t.mode === "queued") { - t.mode = "skip"; - if (t.type === "suite") { - skipAllTasks(t); - } - } - }); -} -function todoAllTasks(suite) { - suite.tasks.forEach((t) => { - if (t.mode === "run" || t.mode === "queued") { - t.mode = "todo"; - if (t.type === "suite") { - todoAllTasks(t); - } - } - }); -} -function checkAllowOnly(task, allowOnly) { - if (allowOnly) { - return; - } - const error = processError(new Error("[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error")); - task.result = { - state: "fail", - errors: [error] - }; -} -/* @__NO_SIDE_EFFECTS__ */ -function generateHash(str) { - let hash = 0; - if (str.length === 0) { - return `${hash}`; - } - for (let i = 0; i < str.length; i++) { - const char = str.charCodeAt(i); - hash = (hash << 5) - hash + char; - hash = hash & hash; - } - return `${hash}`; -} -function calculateSuiteHash(parent) { - parent.tasks.forEach((t, idx) => { - t.id = `${parent.id}_${idx}`; - if (t.type === "suite") { - calculateSuiteHash(t); - } - }); -} -function createFileTask(filepath, root, projectName, pool, viteEnvironment) { - const path = relative(root, filepath); - const file = { - id: generateFileHash(path, projectName), - name: path, - fullName: path, - type: "suite", - mode: "queued", - filepath, - tasks: [], - meta: Object.create(null), - projectName, - file: undefined, - pool, - viteEnvironment - }; - file.file = file; - return file; -} -/** -* Generate a unique ID for a file based on its path and project name -* @param file File relative to the root of the project to keep ID the same between different machines -* @param projectName The name of the test project -*/ -/* @__NO_SIDE_EFFECTS__ */ -function generateFileHash(file, projectName) { - return /* @__PURE__ */ generateHash(`${file}${projectName || ""}`); -} -function findTestFileStackTrace(testFilePath, error) { - // first line is the error message - const lines = error.split("\n").slice(1); - for (const line of lines) { - const stack = parseSingleStack(line); - if (stack && stack.file === testFilePath) { - return stack; - } - } -} - -/** -* Return a function for running multiple async operations with limited concurrency. -*/ -function limitConcurrency(concurrency = Infinity) { - // The number of currently active + pending tasks. - let count = 0; - // The head and tail of the pending task queue, built using a singly linked list. - // Both head and tail are initially undefined, signifying an empty queue. - // They both become undefined again whenever there are no pending tasks. - let head; - let tail; - // A bookkeeping function executed whenever a task has been run to completion. - const finish = () => { - count--; - // Check if there are further pending tasks in the queue. - if (head) { - // Allow the next pending task to run and pop it from the queue. - head[0](); - head = head[1]; - // The head may now be undefined if there are no further pending tasks. - // In that case, set tail to undefined as well. - tail = head && tail; - } - }; - return (func, ...args) => { - // Create a promise chain that: - // 1. Waits for its turn in the task queue (if necessary). - // 2. Runs the task. - // 3. Allows the next pending task (if any) to run. - return new Promise((resolve) => { - if (count++ < concurrency) { - // No need to queue if fewer than maxConcurrency tasks are running. - resolve(); - } else if (tail) { - // There are pending tasks, so append to the queue. - tail = tail[1] = [resolve]; - } else { - // No other pending tasks, initialize the queue with a new tail and head. - head = tail = [resolve]; - } - }).then(() => { - // Running func here ensures that even a non-thenable result or an - // immediately thrown error gets wrapped into a Promise. - return func(...args); - }).finally(finish); - }; -} - -/** -* Partition in tasks groups by consecutive concurrent -*/ -function partitionSuiteChildren(suite) { - let tasksGroup = []; - const tasksGroups = []; - for (const c of suite.tasks) { - if (tasksGroup.length === 0 || c.concurrent === tasksGroup[0].concurrent) { - tasksGroup.push(c); - } else { - tasksGroups.push(tasksGroup); - tasksGroup = [c]; - } - } - if (tasksGroup.length > 0) { - tasksGroups.push(tasksGroup); - } - return tasksGroups; -} - -function isTestCase(s) { - return s.type === "test"; -} -function getTests(suite) { - const tests = []; - const arraySuites = toArray(suite); - for (const s of arraySuites) { - if (isTestCase(s)) { - tests.push(s); - } else { - for (const task of s.tasks) { - if (isTestCase(task)) { - tests.push(task); - } else { - const taskTests = getTests(task); - for (const test of taskTests) { - tests.push(test); - } - } - } - } - } - return tests; -} -function getTasks(tasks = []) { - return toArray(tasks).flatMap((s) => isTestCase(s) ? [s] : [s, ...getTasks(s.tasks)]); -} -function getSuites(suite) { - return toArray(suite).flatMap((s) => s.type === "suite" ? [s, ...getSuites(s.tasks)] : []); -} -function hasTests(suite) { - return toArray(suite).some((s) => s.tasks.some((c) => isTestCase(c) || hasTests(c))); -} -function hasFailed(suite) { - return toArray(suite).some((s) => { - var _s$result; - return ((_s$result = s.result) === null || _s$result === void 0 ? void 0 : _s$result.state) === "fail" || s.type === "suite" && hasFailed(s.tasks); - }); -} -function getNames(task) { - const names = [task.name]; - let current = task; - while (current === null || current === void 0 ? void 0 : current.suite) { - current = current.suite; - if (current === null || current === void 0 ? void 0 : current.name) { - names.unshift(current.name); - } - } - if (current !== task.file) { - names.unshift(task.file.name); - } - return names; -} -function getFullName(task, separator = " > ") { - return getNames(task).join(separator); -} -function getTestName(task, separator = " > ") { - return getNames(task).slice(1).join(separator); -} -function createTaskName(names, separator = " > ") { - return names.filter((name) => name !== undefined).join(separator); -} - -export { calculateSuiteHash as a, createFileTask as b, createChainable as c, generateHash as d, createTaskName as e, findTestFileStackTrace as f, generateFileHash as g, getFullName as h, interpretTaskModes as i, getNames as j, getSuites as k, limitConcurrency as l, getTasks as m, getTestName as n, getTests as o, partitionSuiteChildren as p, hasFailed as q, hasTests as r, someTasksAreOnly as s, isTestCase as t }; diff --git a/vanilla/node_modules/@vitest/runner/dist/index.d.ts b/vanilla/node_modules/@vitest/runner/dist/index.d.ts deleted file mode 100644 index 2038f8f..0000000 --- a/vanilla/node_modules/@vitest/runner/dist/index.d.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { b as TestArtifact, a as Test, S as Suite, d as SuiteHooks, F as File, e as TaskUpdateEvent, T as Task, f as TestAPI, g as SuiteAPI, h as SuiteCollector } from './tasks.d-C7UxawJ9.js'; -export { A as AfterAllListener, n as AfterEachListener, B as BeforeAllListener, p as BeforeEachListener, q as Fixture, r as FixtureFn, s as FixtureOptions, t as Fixtures, I as ImportDuration, u as InferFixturesTypes, O as OnTestFailedHandler, v as OnTestFinishedHandler, R as RunMode, w as RuntimeContext, x as SequenceHooks, y as SequenceSetupFiles, z as SuiteFactory, D as TaskBase, E as TaskCustomOptions, G as TaskEventPack, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, M as TaskResultPack, N as TaskState, P as TestAnnotation, Q as TestAnnotationArtifact, U as TestAnnotationLocation, V as TestArtifactBase, W as TestArtifactLocation, X as TestArtifactRegistry, Y as TestAttachment, Z as TestContext, _ as TestFunction, $ as TestOptions, a0 as Use, a1 as VisualRegressionArtifact, i as afterAll, j as afterEach, k as beforeAll, l as beforeEach, o as onTestFailed, m as onTestFinished } from './tasks.d-C7UxawJ9.js'; -import { Awaitable } from '@vitest/utils'; -import { FileSpecification, VitestRunner } from './types.js'; -export { CancelReason, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource } from './types.js'; -import '@vitest/utils/diff'; - -/** -* @experimental -* @advanced -* -* Records a custom test artifact during test execution. -* -* This function allows you to attach structured data, files, or metadata to a test. -* -* Vitest automatically injects the source location where the artifact was created and manages any attachments you include. -* -* @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests -* @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase} -* -* @returns A promise that resolves to the recorded artifact with location injected -* -* @throws {Error} If called after the test has finished running -* @throws {Error} If the test runner doesn't support artifacts -* -* @example -* ```ts -* // In a custom assertion -* async function toHaveValidSchema(this: MatcherState, actual: unknown) { -* const validation = validateSchema(actual) -* -* await recordArtifact(this.task, { -* type: 'my-plugin:schema-validation', -* passed: validation.valid, -* errors: validation.errors, -* }) -* -* return { pass: validation.valid, message: () => '...' } -* } -* ``` -*/ -declare function recordArtifact<Artifact extends TestArtifact>(task: Test, artifact: Artifact): Promise<Artifact>; - -declare function setFn(key: Test, fn: () => Awaitable<void>): void; -declare function getFn<Task = Test>(key: Task): () => Awaitable<void>; -declare function setHooks(key: Suite, hooks: SuiteHooks): void; -declare function getHooks(key: Suite): SuiteHooks; - -declare function updateTask(event: TaskUpdateEvent, task: Task, runner: VitestRunner): void; -declare function startTests(specs: string[] | FileSpecification[], runner: VitestRunner): Promise<File[]>; -declare function publicCollect(specs: string[] | FileSpecification[], runner: VitestRunner): Promise<File[]>; - -/** -* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. -* Suites can contain both tests and other suites, enabling complex test structures. -* -* @param {string} name - The name of the suite, used for identification and reporting. -* @param {Function} fn - A function that defines the tests and suites within this suite. -* @example -* ```ts -* // Define a suite with two tests -* suite('Math operations', () => { -* test('should add two numbers', () => { -* expect(add(1, 2)).toBe(3); -* }); -* -* test('should subtract two numbers', () => { -* expect(subtract(5, 2)).toBe(3); -* }); -* }); -* ``` -* @example -* ```ts -* // Define nested suites -* suite('String operations', () => { -* suite('Trimming', () => { -* test('should trim whitespace from start and end', () => { -* expect(' hello '.trim()).toBe('hello'); -* }); -* }); -* -* suite('Concatenation', () => { -* test('should concatenate two strings', () => { -* expect('hello' + ' ' + 'world').toBe('hello world'); -* }); -* }); -* }); -* ``` -*/ -declare const suite: SuiteAPI; -/** -* Defines a test case with a given name and test function. The test function can optionally be configured with test options. -* -* @param {string | Function} name - The name of the test or a function that will be used as a test name. -* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. -* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. -* @throws {Error} If called inside another test function. -* @example -* ```ts -* // Define a simple test -* test('should add two numbers', () => { -* expect(add(1, 2)).toBe(3); -* }); -* ``` -* @example -* ```ts -* // Define a test with options -* test('should subtract two numbers', { retry: 3 }, () => { -* expect(subtract(5, 2)).toBe(3); -* }); -* ``` -*/ -declare const test: TestAPI; -/** -* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. -* Suites can contain both tests and other suites, enabling complex test structures. -* -* @param {string} name - The name of the suite, used for identification and reporting. -* @param {Function} fn - A function that defines the tests and suites within this suite. -* @example -* ```ts -* // Define a suite with two tests -* describe('Math operations', () => { -* test('should add two numbers', () => { -* expect(add(1, 2)).toBe(3); -* }); -* -* test('should subtract two numbers', () => { -* expect(subtract(5, 2)).toBe(3); -* }); -* }); -* ``` -* @example -* ```ts -* // Define nested suites -* describe('String operations', () => { -* describe('Trimming', () => { -* test('should trim whitespace from start and end', () => { -* expect(' hello '.trim()).toBe('hello'); -* }); -* }); -* -* describe('Concatenation', () => { -* test('should concatenate two strings', () => { -* expect('hello' + ' ' + 'world').toBe('hello world'); -* }); -* }); -* }); -* ``` -*/ -declare const describe: SuiteAPI; -/** -* Defines a test case with a given name and test function. The test function can optionally be configured with test options. -* -* @param {string | Function} name - The name of the test or a function that will be used as a test name. -* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. -* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. -* @throws {Error} If called inside another test function. -* @example -* ```ts -* // Define a simple test -* it('adds two numbers', () => { -* expect(add(1, 2)).toBe(3); -* }); -* ``` -* @example -* ```ts -* // Define a test with options -* it('subtracts two numbers', { retry: 3 }, () => { -* expect(subtract(5, 2)).toBe(3); -* }); -* ``` -*/ -declare const it: TestAPI; -declare function getCurrentSuite<ExtraContext = object>(): SuiteCollector<ExtraContext>; -declare function createTaskCollector(fn: (...args: any[]) => any, context?: Record<string, unknown>): TestAPI; - -declare function getCurrentTest<T extends Test | undefined>(): T; - -export { File, FileSpecification, Suite, SuiteAPI, SuiteCollector, SuiteHooks, Task, TaskUpdateEvent, Test, TestAPI, TestArtifact, VitestRunner, publicCollect as collectTests, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, recordArtifact, setFn, setHooks, startTests, suite, test, updateTask }; diff --git a/vanilla/node_modules/@vitest/runner/dist/index.js b/vanilla/node_modules/@vitest/runner/dist/index.js deleted file mode 100644 index c6403f4..0000000 --- a/vanilla/node_modules/@vitest/runner/dist/index.js +++ /dev/null @@ -1,2114 +0,0 @@ -import { processError } from '@vitest/utils/error'; -import { isObject, createDefer, assertTypes, toArray, isNegativeNaN, objectAttr, shuffle } from '@vitest/utils/helpers'; -import { getSafeTimers } from '@vitest/utils/timers'; -import { format, formatRegExp, objDisplay } from '@vitest/utils/display'; -import { c as createChainable, e as createTaskName, f as findTestFileStackTrace, b as createFileTask, a as calculateSuiteHash, s as someTasksAreOnly, i as interpretTaskModes, l as limitConcurrency, p as partitionSuiteChildren, r as hasTests, q as hasFailed } from './chunk-tasks.js'; -import '@vitest/utils/source-map'; -import 'pathe'; - -class PendingError extends Error { - code = "VITEST_PENDING"; - taskId; - constructor(message, task, note) { - super(message); - this.message = message; - this.note = note; - this.taskId = task.id; - } -} -class TestRunAbortError extends Error { - name = "TestRunAbortError"; - reason; - constructor(message, reason) { - super(message); - this.reason = reason; - } -} - -// use WeakMap here to make the Test and Suite object serializable -const fnMap = new WeakMap(); -const testFixtureMap = new WeakMap(); -const hooksMap = new WeakMap(); -function setFn(key, fn) { - fnMap.set(key, fn); -} -function getFn(key) { - return fnMap.get(key); -} -function setTestFixture(key, fixture) { - testFixtureMap.set(key, fixture); -} -function getTestFixture(key) { - return testFixtureMap.get(key); -} -function setHooks(key, hooks) { - hooksMap.set(key, hooks); -} -function getHooks(key) { - return hooksMap.get(key); -} - -function mergeScopedFixtures(testFixtures, scopedFixtures) { - const scopedFixturesMap = scopedFixtures.reduce((map, fixture) => { - map[fixture.prop] = fixture; - return map; - }, {}); - const newFixtures = {}; - testFixtures.forEach((fixture) => { - const useFixture = scopedFixturesMap[fixture.prop] || { ...fixture }; - newFixtures[useFixture.prop] = useFixture; - }); - for (const fixtureKep in newFixtures) { - var _fixture$deps; - const fixture = newFixtures[fixtureKep]; - // if the fixture was define before the scope, then its dep - // will reference the original fixture instead of the scope - fixture.deps = (_fixture$deps = fixture.deps) === null || _fixture$deps === void 0 ? void 0 : _fixture$deps.map((dep) => newFixtures[dep.prop]); - } - return Object.values(newFixtures); -} -function mergeContextFixtures(fixtures, context, runner) { - const fixtureOptionKeys = [ - "auto", - "injected", - "scope" - ]; - const fixtureArray = Object.entries(fixtures).map(([prop, value]) => { - const fixtureItem = { value }; - if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) { - var _runner$injectValue; - // fixture with options - Object.assign(fixtureItem, value[1]); - const userValue = value[0]; - fixtureItem.value = fixtureItem.injected ? ((_runner$injectValue = runner.injectValue) === null || _runner$injectValue === void 0 ? void 0 : _runner$injectValue.call(runner, prop)) ?? userValue : userValue; - } - fixtureItem.scope = fixtureItem.scope || "test"; - if (fixtureItem.scope === "worker" && !runner.getWorkerContext) { - fixtureItem.scope = "file"; - } - fixtureItem.prop = prop; - fixtureItem.isFn = typeof fixtureItem.value === "function"; - return fixtureItem; - }); - if (Array.isArray(context.fixtures)) { - context.fixtures = context.fixtures.concat(fixtureArray); - } else { - context.fixtures = fixtureArray; - } - // Update dependencies of fixture functions - fixtureArray.forEach((fixture) => { - if (fixture.isFn) { - const usedProps = getUsedProps(fixture.value); - if (usedProps.length) { - fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop)); - } - // test can access anything, so we ignore it - if (fixture.scope !== "test") { - var _fixture$deps2; - (_fixture$deps2 = fixture.deps) === null || _fixture$deps2 === void 0 ? void 0 : _fixture$deps2.forEach((dep) => { - if (!dep.isFn) { - // non fn fixtures are always resolved and available to anyone - return; - } - // worker scope can only import from worker scope - if (fixture.scope === "worker" && dep.scope === "worker") { - return; - } - // file scope an import from file and worker scopes - if (fixture.scope === "file" && dep.scope !== "test") { - return; - } - throw new SyntaxError(`cannot use the ${dep.scope} fixture "${dep.prop}" inside the ${fixture.scope} fixture "${fixture.prop}"`); - }); - } - } - }); - return context; -} -const fixtureValueMaps = new Map(); -const cleanupFnArrayMap = new Map(); -async function callFixtureCleanup(context) { - const cleanupFnArray = cleanupFnArrayMap.get(context) ?? []; - for (const cleanup of cleanupFnArray.reverse()) { - await cleanup(); - } - cleanupFnArrayMap.delete(context); -} -function withFixtures(runner, fn, testContext) { - return (hookContext) => { - const context = hookContext || testContext; - if (!context) { - return fn({}); - } - const fixtures = getTestFixture(context); - if (!(fixtures === null || fixtures === void 0 ? void 0 : fixtures.length)) { - return fn(context); - } - const usedProps = getUsedProps(fn); - const hasAutoFixture = fixtures.some(({ auto }) => auto); - if (!usedProps.length && !hasAutoFixture) { - return fn(context); - } - if (!fixtureValueMaps.get(context)) { - fixtureValueMaps.set(context, new Map()); - } - const fixtureValueMap = fixtureValueMaps.get(context); - if (!cleanupFnArrayMap.has(context)) { - cleanupFnArrayMap.set(context, []); - } - const cleanupFnArray = cleanupFnArrayMap.get(context); - const usedFixtures = fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop)); - const pendingFixtures = resolveDeps(usedFixtures); - if (!pendingFixtures.length) { - return fn(context); - } - async function resolveFixtures() { - for (const fixture of pendingFixtures) { - // fixture could be already initialized during "before" hook - if (fixtureValueMap.has(fixture)) { - continue; - } - const resolvedValue = await resolveFixtureValue(runner, fixture, context, cleanupFnArray); - context[fixture.prop] = resolvedValue; - fixtureValueMap.set(fixture, resolvedValue); - if (fixture.scope === "test") { - cleanupFnArray.unshift(() => { - fixtureValueMap.delete(fixture); - }); - } - } - } - return resolveFixtures().then(() => fn(context)); - }; -} -const globalFixturePromise = new WeakMap(); -function resolveFixtureValue(runner, fixture, context, cleanupFnArray) { - var _runner$getWorkerCont; - const fileContext = getFileContext(context.task.file); - const workerContext = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner); - if (!fixture.isFn) { - var _fixture$prop; - fileContext[_fixture$prop = fixture.prop] ?? (fileContext[_fixture$prop] = fixture.value); - if (workerContext) { - var _fixture$prop2; - workerContext[_fixture$prop2 = fixture.prop] ?? (workerContext[_fixture$prop2] = fixture.value); - } - return fixture.value; - } - if (fixture.scope === "test") { - return resolveFixtureFunction(fixture.value, context, cleanupFnArray); - } - // in case the test runs in parallel - if (globalFixturePromise.has(fixture)) { - return globalFixturePromise.get(fixture); - } - let fixtureContext; - if (fixture.scope === "worker") { - if (!workerContext) { - throw new TypeError("[@vitest/runner] The worker context is not available in the current test runner. Please, provide the `getWorkerContext` method when initiating the runner."); - } - fixtureContext = workerContext; - } else { - fixtureContext = fileContext; - } - if (fixture.prop in fixtureContext) { - return fixtureContext[fixture.prop]; - } - if (!cleanupFnArrayMap.has(fixtureContext)) { - cleanupFnArrayMap.set(fixtureContext, []); - } - const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext); - const promise = resolveFixtureFunction(fixture.value, fixtureContext, cleanupFnFileArray).then((value) => { - fixtureContext[fixture.prop] = value; - globalFixturePromise.delete(fixture); - return value; - }); - globalFixturePromise.set(fixture, promise); - return promise; -} -async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) { - // wait for `use` call to extract fixture value - const useFnArgPromise = createDefer(); - let isUseFnArgResolved = false; - const fixtureReturn = fixtureFn(context, async (useFnArg) => { - // extract `use` argument - isUseFnArgResolved = true; - useFnArgPromise.resolve(useFnArg); - // suspend fixture teardown by holding off `useReturnPromise` resolution until cleanup - const useReturnPromise = createDefer(); - cleanupFnArray.push(async () => { - // start teardown by resolving `use` Promise - useReturnPromise.resolve(); - // wait for finishing teardown - await fixtureReturn; - }); - await useReturnPromise; - }).catch((e) => { - // treat fixture setup error as test failure - if (!isUseFnArgResolved) { - useFnArgPromise.reject(e); - return; - } - // otherwise re-throw to avoid silencing error during cleanup - throw e; - }); - return useFnArgPromise; -} -function resolveDeps(fixtures, depSet = new Set(), pendingFixtures = []) { - fixtures.forEach((fixture) => { - if (pendingFixtures.includes(fixture)) { - return; - } - if (!fixture.isFn || !fixture.deps) { - pendingFixtures.push(fixture); - return; - } - if (depSet.has(fixture)) { - throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`); - } - depSet.add(fixture); - resolveDeps(fixture.deps, depSet, pendingFixtures); - pendingFixtures.push(fixture); - depSet.clear(); - }); - return pendingFixtures; -} -function getUsedProps(fn) { - let fnString = filterOutComments(fn.toString()); - // match lowered async function and strip it off - // example code on esbuild-try https://esbuild.github.io/try/#YgAwLjI0LjAALS1zdXBwb3J0ZWQ6YXN5bmMtYXdhaXQ9ZmFsc2UAZQBlbnRyeS50cwBjb25zdCBvID0gewogIGYxOiBhc3luYyAoKSA9PiB7fSwKICBmMjogYXN5bmMgKGEpID0+IHt9LAogIGYzOiBhc3luYyAoYSwgYikgPT4ge30sCiAgZjQ6IGFzeW5jIGZ1bmN0aW9uKGEpIHt9LAogIGY1OiBhc3luYyBmdW5jdGlvbiBmZihhKSB7fSwKICBhc3luYyBmNihhKSB7fSwKCiAgZzE6IGFzeW5jICgpID0+IHt9LAogIGcyOiBhc3luYyAoeyBhIH0pID0+IHt9LAogIGczOiBhc3luYyAoeyBhIH0sIGIpID0+IHt9LAogIGc0OiBhc3luYyBmdW5jdGlvbiAoeyBhIH0pIHt9LAogIGc1OiBhc3luYyBmdW5jdGlvbiBnZyh7IGEgfSkge30sCiAgYXN5bmMgZzYoeyBhIH0pIHt9LAoKICBoMTogYXN5bmMgKCkgPT4ge30sCiAgLy8gY29tbWVudCBiZXR3ZWVuCiAgaDI6IGFzeW5jIChhKSA9PiB7fSwKfQ - // __async(this, null, function* - // __async(this, arguments, function* - // __async(this, [_0, _1], function* - if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) { - fnString = fnString.split(/__async\((?:this|null),/)[1]; - } - const match = fnString.match(/[^(]*\(([^)]*)/); - if (!match) { - return []; - } - const args = splitByComma(match[1]); - if (!args.length) { - return []; - } - let first = args[0]; - if ("__VITEST_FIXTURE_INDEX__" in fn) { - first = args[fn.__VITEST_FIXTURE_INDEX__]; - if (!first) { - return []; - } - } - if (!(first[0] === "{" && first.endsWith("}"))) { - throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`); - } - const _first = first.slice(1, -1).replace(/\s/g, ""); - const props = splitByComma(_first).map((prop) => { - return prop.replace(/:.*|=.*/g, ""); - }); - const last = props.at(-1); - if (last && last.startsWith("...")) { - throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`); - } - return props; -} -function filterOutComments(s) { - const result = []; - let commentState = "none"; - for (let i = 0; i < s.length; ++i) { - if (commentState === "singleline") { - if (s[i] === "\n") { - commentState = "none"; - } - } else if (commentState === "multiline") { - if (s[i - 1] === "*" && s[i] === "/") { - commentState = "none"; - } - } else if (commentState === "none") { - if (s[i] === "/" && s[i + 1] === "/") { - commentState = "singleline"; - } else if (s[i] === "/" && s[i + 1] === "*") { - commentState = "multiline"; - i += 2; - } else { - result.push(s[i]); - } - } - } - return result.join(""); -} -function splitByComma(s) { - const result = []; - const stack = []; - let start = 0; - for (let i = 0; i < s.length; i++) { - if (s[i] === "{" || s[i] === "[") { - stack.push(s[i] === "{" ? "}" : "]"); - } else if (s[i] === stack.at(-1)) { - stack.pop(); - } else if (!stack.length && s[i] === ",") { - const token = s.substring(start, i).trim(); - if (token) { - result.push(token); - } - start = i + 1; - } - } - const lastToken = s.substring(start).trim(); - if (lastToken) { - result.push(lastToken); - } - return result; -} - -let _test; -function setCurrentTest(test) { - _test = test; -} -function getCurrentTest() { - return _test; -} -const tests = []; -function addRunningTest(test) { - tests.push(test); - return () => { - tests.splice(tests.indexOf(test)); - }; -} -function getRunningTests() { - return tests; -} - -function getDefaultHookTimeout() { - return getRunner().config.hookTimeout; -} -const CLEANUP_TIMEOUT_KEY = Symbol.for("VITEST_CLEANUP_TIMEOUT"); -const CLEANUP_STACK_TRACE_KEY = Symbol.for("VITEST_CLEANUP_STACK_TRACE"); -function getBeforeHookCleanupCallback(hook, result, context) { - if (typeof result === "function") { - const timeout = CLEANUP_TIMEOUT_KEY in hook && typeof hook[CLEANUP_TIMEOUT_KEY] === "number" ? hook[CLEANUP_TIMEOUT_KEY] : getDefaultHookTimeout(); - const stackTraceError = CLEANUP_STACK_TRACE_KEY in hook && hook[CLEANUP_STACK_TRACE_KEY] instanceof Error ? hook[CLEANUP_STACK_TRACE_KEY] : undefined; - return withTimeout(result, timeout, true, stackTraceError, (_, error) => { - if (context) { - abortContextSignal(context, error); - } - }); - } -} -/** -* Registers a callback function to be executed once before all tests within the current suite. -* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment. -* -* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed before all tests. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @returns {void} -* @example -* ```ts -* // Example of using beforeAll to set up a database connection -* beforeAll(async () => { -* await database.connect(); -* }); -* ``` -*/ -function beforeAll(fn, timeout = getDefaultHookTimeout()) { - assertTypes(fn, "\"beforeAll\" callback", ["function"]); - const stackTraceError = new Error("STACK_TRACE_ERROR"); - return getCurrentSuite().on("beforeAll", Object.assign(withTimeout(fn, timeout, true, stackTraceError), { - [CLEANUP_TIMEOUT_KEY]: timeout, - [CLEANUP_STACK_TRACE_KEY]: stackTraceError - })); -} -/** -* Registers a callback function to be executed once after all tests within the current suite have completed. -* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files. -* -* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed after all tests. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @returns {void} -* @example -* ```ts -* // Example of using afterAll to close a database connection -* afterAll(async () => { -* await database.disconnect(); -* }); -* ``` -*/ -function afterAll(fn, timeout) { - assertTypes(fn, "\"afterAll\" callback", ["function"]); - return getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"))); -} -/** -* Registers a callback function to be executed before each test within the current suite. -* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. -* -* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @returns {void} -* @example -* ```ts -* // Example of using beforeEach to reset a database state -* beforeEach(async () => { -* await database.reset(); -* }); -* ``` -*/ -function beforeEach(fn, timeout = getDefaultHookTimeout()) { - assertTypes(fn, "\"beforeEach\" callback", ["function"]); - const stackTraceError = new Error("STACK_TRACE_ERROR"); - const runner = getRunner(); - return getCurrentSuite().on("beforeEach", Object.assign(withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, stackTraceError, abortIfTimeout), { - [CLEANUP_TIMEOUT_KEY]: timeout, - [CLEANUP_STACK_TRACE_KEY]: stackTraceError - })); -} -/** -* Registers a callback function to be executed after each test within the current suite has completed. -* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. -* -* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @returns {void} -* @example -* ```ts -* // Example of using afterEach to delete temporary files created during a test -* afterEach(async () => { -* await fileSystem.deleteTempFiles(); -* }); -* ``` -*/ -function afterEach(fn, timeout) { - assertTypes(fn, "\"afterEach\" callback", ["function"]); - const runner = getRunner(); - return getCurrentSuite().on("afterEach", withTimeout(withFixtures(runner, fn), timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); -} -/** -* Registers a callback function to be executed when a test fails within the current suite. -* This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics. -* -* **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors). -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @throws {Error} Throws an error if the function is not called within a test. -* @returns {void} -* @example -* ```ts -* // Example of using onTestFailed to log failure details -* onTestFailed(({ errors }) => { -* console.log(`Test failed: ${test.name}`, errors); -* }); -* ``` -*/ -const onTestFailed = createTestHook("onTestFailed", (test, handler, timeout) => { - test.onFailed || (test.onFailed = []); - test.onFailed.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); -}); -/** -* Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail). -* This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources. -* -* This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`. -* -* **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. -* -* **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call. -* -* @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @throws {Error} Throws an error if the function is not called within a test. -* @returns {void} -* @example -* ```ts -* // Example of using onTestFinished for cleanup -* const db = await connectToDatabase(); -* onTestFinished(async () => { -* await db.disconnect(); -* }); -* ``` -*/ -const onTestFinished = createTestHook("onTestFinished", (test, handler, timeout) => { - test.onFinished || (test.onFinished = []); - test.onFinished.push(withTimeout(handler, timeout ?? getDefaultHookTimeout(), true, new Error("STACK_TRACE_ERROR"), abortIfTimeout)); -}); -function createTestHook(name, handler) { - return (fn, timeout) => { - assertTypes(fn, `"${name}" callback`, ["function"]); - const current = getCurrentTest(); - if (!current) { - throw new Error(`Hook ${name}() can only be called inside a test`); - } - return handler(current, fn, timeout); - }; -} - -/** -* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. -* Suites can contain both tests and other suites, enabling complex test structures. -* -* @param {string} name - The name of the suite, used for identification and reporting. -* @param {Function} fn - A function that defines the tests and suites within this suite. -* @example -* ```ts -* // Define a suite with two tests -* suite('Math operations', () => { -* test('should add two numbers', () => { -* expect(add(1, 2)).toBe(3); -* }); -* -* test('should subtract two numbers', () => { -* expect(subtract(5, 2)).toBe(3); -* }); -* }); -* ``` -* @example -* ```ts -* // Define nested suites -* suite('String operations', () => { -* suite('Trimming', () => { -* test('should trim whitespace from start and end', () => { -* expect(' hello '.trim()).toBe('hello'); -* }); -* }); -* -* suite('Concatenation', () => { -* test('should concatenate two strings', () => { -* expect('hello' + ' ' + 'world').toBe('hello world'); -* }); -* }); -* }); -* ``` -*/ -const suite = createSuite(); -/** -* Defines a test case with a given name and test function. The test function can optionally be configured with test options. -* -* @param {string | Function} name - The name of the test or a function that will be used as a test name. -* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. -* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. -* @throws {Error} If called inside another test function. -* @example -* ```ts -* // Define a simple test -* test('should add two numbers', () => { -* expect(add(1, 2)).toBe(3); -* }); -* ``` -* @example -* ```ts -* // Define a test with options -* test('should subtract two numbers', { retry: 3 }, () => { -* expect(subtract(5, 2)).toBe(3); -* }); -* ``` -*/ -const test = createTest(function(name, optionsOrFn, optionsOrTest) { - if (getCurrentTest()) { - throw new Error("Calling the test function inside another test function is not allowed. Please put it inside \"describe\" or \"suite\" so it can be properly collected."); - } - getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest); -}); -/** -* Creates a suite of tests, allowing for grouping and hierarchical organization of tests. -* Suites can contain both tests and other suites, enabling complex test structures. -* -* @param {string} name - The name of the suite, used for identification and reporting. -* @param {Function} fn - A function that defines the tests and suites within this suite. -* @example -* ```ts -* // Define a suite with two tests -* describe('Math operations', () => { -* test('should add two numbers', () => { -* expect(add(1, 2)).toBe(3); -* }); -* -* test('should subtract two numbers', () => { -* expect(subtract(5, 2)).toBe(3); -* }); -* }); -* ``` -* @example -* ```ts -* // Define nested suites -* describe('String operations', () => { -* describe('Trimming', () => { -* test('should trim whitespace from start and end', () => { -* expect(' hello '.trim()).toBe('hello'); -* }); -* }); -* -* describe('Concatenation', () => { -* test('should concatenate two strings', () => { -* expect('hello' + ' ' + 'world').toBe('hello world'); -* }); -* }); -* }); -* ``` -*/ -const describe = suite; -/** -* Defines a test case with a given name and test function. The test function can optionally be configured with test options. -* -* @param {string | Function} name - The name of the test or a function that will be used as a test name. -* @param {TestOptions | TestFunction} [optionsOrFn] - Optional. The test options or the test function if no explicit name is provided. -* @param {number | TestOptions | TestFunction} [optionsOrTest] - Optional. The test function or options, depending on the previous parameters. -* @throws {Error} If called inside another test function. -* @example -* ```ts -* // Define a simple test -* it('adds two numbers', () => { -* expect(add(1, 2)).toBe(3); -* }); -* ``` -* @example -* ```ts -* // Define a test with options -* it('subtracts two numbers', { retry: 3 }, () => { -* expect(subtract(5, 2)).toBe(3); -* }); -* ``` -*/ -const it = test; -let runner; -let defaultSuite; -let currentTestFilepath; -function assert(condition, message) { - if (!condition) { - throw new Error(`Vitest failed to find ${message}. One of the following is possible:` + "\n- \"vitest\" is imported directly without running \"vitest\" command" + "\n- \"vitest\" is imported inside \"globalSetup\" (to fix this, use \"setupFiles\" instead, because \"globalSetup\" runs in a different context)" + "\n- \"vitest\" is imported inside Vite / Vitest config file" + "\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n"); - } -} -function getDefaultSuite() { - assert(defaultSuite, "the default suite"); - return defaultSuite; -} -function getRunner() { - assert(runner, "the runner"); - return runner; -} -function createDefaultSuite(runner) { - const config = runner.config.sequence; - const collector = suite("", { concurrent: config.concurrent }, () => {}); - // no parent suite for top-level tests - delete collector.suite; - return collector; -} -function clearCollectorContext(file, currentRunner) { - if (!defaultSuite) { - defaultSuite = createDefaultSuite(currentRunner); - } - defaultSuite.file = file; - runner = currentRunner; - currentTestFilepath = file.filepath; - collectorContext.tasks.length = 0; - defaultSuite.clear(); - collectorContext.currentSuite = defaultSuite; -} -function getCurrentSuite() { - const currentSuite = collectorContext.currentSuite || defaultSuite; - assert(currentSuite, "the current suite"); - return currentSuite; -} -function createSuiteHooks() { - return { - beforeAll: [], - afterAll: [], - beforeEach: [], - afterEach: [] - }; -} -function parseArguments(optionsOrFn, timeoutOrTest) { - if (timeoutOrTest != null && typeof timeoutOrTest === "object") { - throw new TypeError(`Signature "test(name, fn, { ... })" was deprecated in Vitest 3 and removed in Vitest 4. Please, provide options as a second argument instead.`); - } - let options = {}; - let fn; - // it('', () => {}, 1000) - if (typeof timeoutOrTest === "number") { - options = { timeout: timeoutOrTest }; - } else if (typeof optionsOrFn === "object") { - options = optionsOrFn; - } - if (typeof optionsOrFn === "function") { - if (typeof timeoutOrTest === "function") { - throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options."); - } - fn = optionsOrFn; - } else if (typeof timeoutOrTest === "function") { - fn = timeoutOrTest; - } - return { - options, - handler: fn - }; -} -// implementations -function createSuiteCollector(name, factory = () => {}, mode, each, suiteOptions, parentCollectorFixtures) { - const tasks = []; - let suite; - initSuite(true); - const task = function(name = "", options = {}) { - var _collectorContext$cur, _collectorContext$cur2, _collectorContext$cur3; - const timeout = (options === null || options === void 0 ? void 0 : options.timeout) ?? runner.config.testTimeout; - const currentSuite = (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.suite; - const task = { - id: "", - name, - fullName: createTaskName([(currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullName) ?? ((_collectorContext$cur2 = collectorContext.currentSuite) === null || _collectorContext$cur2 === void 0 || (_collectorContext$cur2 = _collectorContext$cur2.file) === null || _collectorContext$cur2 === void 0 ? void 0 : _collectorContext$cur2.fullName), name]), - fullTestName: createTaskName([currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullTestName, name]), - suite: currentSuite, - each: options.each, - fails: options.fails, - context: undefined, - type: "test", - file: (currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.file) ?? ((_collectorContext$cur3 = collectorContext.currentSuite) === null || _collectorContext$cur3 === void 0 ? void 0 : _collectorContext$cur3.file), - timeout, - retry: options.retry ?? runner.config.retry, - repeats: options.repeats, - mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run", - meta: options.meta ?? Object.create(null), - annotations: [], - artifacts: [] - }; - const handler = options.handler; - if (task.mode === "run" && !handler) { - task.mode = "todo"; - } - if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) { - task.concurrent = true; - } - task.shuffle = suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle; - const context = createTestContext(task, runner); - // create test context - Object.defineProperty(task, "context", { - value: context, - enumerable: false - }); - setTestFixture(context, options.fixtures); - // custom can be called from any place, let's assume the limit is 15 stacks - const limit = Error.stackTraceLimit; - Error.stackTraceLimit = 15; - const stackTraceError = new Error("STACK_TRACE_ERROR"); - Error.stackTraceLimit = limit; - if (handler) { - setFn(task, withTimeout(withAwaitAsyncAssertions(withFixtures(runner, handler, context), task), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error))); - } - if (runner.config.includeTaskLocation) { - const error = stackTraceError.stack; - const stack = findTestFileStackTrace(currentTestFilepath, error); - if (stack) { - task.location = { - line: stack.line, - column: stack.column - }; - } - } - tasks.push(task); - return task; - }; - const test = createTest(function(name, optionsOrFn, timeoutOrTest) { - let { options, handler } = parseArguments(optionsOrFn, timeoutOrTest); - // inherit repeats, retry, timeout from suite - if (typeof suiteOptions === "object") { - options = Object.assign({}, suiteOptions, options); - } - // inherit concurrent / sequential from suite - options.concurrent = this.concurrent || !this.sequential && (options === null || options === void 0 ? void 0 : options.concurrent); - options.sequential = this.sequential || !this.concurrent && (options === null || options === void 0 ? void 0 : options.sequential); - const test = task(formatName(name), { - ...this, - ...options, - handler - }); - test.type = "test"; - }); - let collectorFixtures = parentCollectorFixtures; - const collector = { - type: "collector", - name, - mode, - suite, - options: suiteOptions, - test, - tasks, - collect, - task, - clear, - on: addHook, - fixtures() { - return collectorFixtures; - }, - scoped(fixtures) { - const parsed = mergeContextFixtures(fixtures, { fixtures: collectorFixtures }, runner); - if (parsed.fixtures) { - collectorFixtures = parsed.fixtures; - } - } - }; - function addHook(name, ...fn) { - getHooks(suite)[name].push(...fn); - } - function initSuite(includeLocation) { - var _collectorContext$cur4, _collectorContext$cur5, _collectorContext$cur6; - if (typeof suiteOptions === "number") { - suiteOptions = { timeout: suiteOptions }; - } - const currentSuite = (_collectorContext$cur4 = collectorContext.currentSuite) === null || _collectorContext$cur4 === void 0 ? void 0 : _collectorContext$cur4.suite; - suite = { - id: "", - type: "suite", - name, - fullName: createTaskName([(currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullName) ?? ((_collectorContext$cur5 = collectorContext.currentSuite) === null || _collectorContext$cur5 === void 0 || (_collectorContext$cur5 = _collectorContext$cur5.file) === null || _collectorContext$cur5 === void 0 ? void 0 : _collectorContext$cur5.fullName), name]), - fullTestName: createTaskName([currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fullTestName, name]), - suite: currentSuite, - mode, - each, - file: (currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.file) ?? ((_collectorContext$cur6 = collectorContext.currentSuite) === null || _collectorContext$cur6 === void 0 ? void 0 : _collectorContext$cur6.file), - shuffle: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle, - tasks: [], - meta: Object.create(null), - concurrent: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.concurrent - }; - if (runner && includeLocation && runner.config.includeTaskLocation) { - const limit = Error.stackTraceLimit; - Error.stackTraceLimit = 15; - const error = new Error("stacktrace").stack; - Error.stackTraceLimit = limit; - const stack = findTestFileStackTrace(currentTestFilepath, error); - if (stack) { - suite.location = { - line: stack.line, - column: stack.column - }; - } - } - setHooks(suite, createSuiteHooks()); - } - function clear() { - tasks.length = 0; - initSuite(false); - } - async function collect(file) { - if (!file) { - throw new TypeError("File is required to collect tasks."); - } - if (factory) { - await runWithSuite(collector, () => factory(test)); - } - const allChildren = []; - for (const i of tasks) { - allChildren.push(i.type === "collector" ? await i.collect(file) : i); - } - suite.tasks = allChildren; - return suite; - } - collectTask(collector); - return collector; -} -function withAwaitAsyncAssertions(fn, task) { - return (async (...args) => { - const fnResult = await fn(...args); - // some async expect will be added to this array, in case user forget to await them - if (task.promises) { - const result = await Promise.allSettled(task.promises); - const errors = result.map((r) => r.status === "rejected" ? r.reason : undefined).filter(Boolean); - if (errors.length) { - throw errors; - } - } - return fnResult; - }); -} -function createSuite() { - function suiteFn(name, factoryOrOptions, optionsOrFactory) { - var _currentSuite$options; - if (getCurrentTest()) { - throw new Error("Calling the suite function inside test function is not allowed. It can be only called at the top level or inside another suite function."); - } - let mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run"; - const currentSuite = collectorContext.currentSuite || defaultSuite; - let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory); - if (mode === "run" && !factory) { - mode = "todo"; - } - const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false; - const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false; - // inherit options from current suite - options = { - ...currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.options, - ...options, - shuffle: this.shuffle ?? options.shuffle ?? (currentSuite === null || currentSuite === void 0 || (_currentSuite$options = currentSuite.options) === null || _currentSuite$options === void 0 ? void 0 : _currentSuite$options.shuffle) ?? (runner === null || runner === void 0 ? void 0 : runner.config.sequence.shuffle) - }; - // inherit concurrent / sequential from suite - const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified; - const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified; - options.concurrent = isConcurrent && !isSequential; - options.sequential = isSequential && !isConcurrent; - return createSuiteCollector(formatName(name), factory, mode, this.each, options, currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fixtures()); - } - suiteFn.each = function(cases, ...args) { - const suite = this.withContext(); - this.setContext("each", true); - if (Array.isArray(cases) && args.length) { - cases = formatTemplateString(cases, args); - } - return (name, optionsOrFn, fnOrOptions) => { - const _name = formatName(name); - const arrayOnlyCases = cases.every(Array.isArray); - const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); - const fnFirst = typeof optionsOrFn === "function"; - cases.forEach((i, idx) => { - const items = Array.isArray(i) ? i : [i]; - if (fnFirst) { - if (arrayOnlyCases) { - suite(formatTitle(_name, items, idx), handler ? () => handler(...items) : undefined, options.timeout); - } else { - suite(formatTitle(_name, items, idx), handler ? () => handler(i) : undefined, options.timeout); - } - } else { - if (arrayOnlyCases) { - suite(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : undefined); - } else { - suite(formatTitle(_name, items, idx), options, handler ? () => handler(i) : undefined); - } - } - }); - this.setContext("each", undefined); - }; - }; - suiteFn.for = function(cases, ...args) { - if (Array.isArray(cases) && args.length) { - cases = formatTemplateString(cases, args); - } - return (name, optionsOrFn, fnOrOptions) => { - const name_ = formatName(name); - const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); - cases.forEach((item, idx) => { - suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : undefined); - }); - }; - }; - suiteFn.skipIf = (condition) => condition ? suite.skip : suite; - suiteFn.runIf = (condition) => condition ? suite : suite.skip; - return createChainable([ - "concurrent", - "sequential", - "shuffle", - "skip", - "only", - "todo" - ], suiteFn); -} -function createTaskCollector(fn, context) { - const taskFn = fn; - taskFn.each = function(cases, ...args) { - const test = this.withContext(); - this.setContext("each", true); - if (Array.isArray(cases) && args.length) { - cases = formatTemplateString(cases, args); - } - return (name, optionsOrFn, fnOrOptions) => { - const _name = formatName(name); - const arrayOnlyCases = cases.every(Array.isArray); - const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); - const fnFirst = typeof optionsOrFn === "function"; - cases.forEach((i, idx) => { - const items = Array.isArray(i) ? i : [i]; - if (fnFirst) { - if (arrayOnlyCases) { - test(formatTitle(_name, items, idx), handler ? () => handler(...items) : undefined, options.timeout); - } else { - test(formatTitle(_name, items, idx), handler ? () => handler(i) : undefined, options.timeout); - } - } else { - if (arrayOnlyCases) { - test(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : undefined); - } else { - test(formatTitle(_name, items, idx), options, handler ? () => handler(i) : undefined); - } - } - }); - this.setContext("each", undefined); - }; - }; - taskFn.for = function(cases, ...args) { - const test = this.withContext(); - if (Array.isArray(cases) && args.length) { - cases = formatTemplateString(cases, args); - } - return (name, optionsOrFn, fnOrOptions) => { - const _name = formatName(name); - const { options, handler } = parseArguments(optionsOrFn, fnOrOptions); - cases.forEach((item, idx) => { - // monkey-patch handler to allow parsing fixture - const handlerWrapper = handler ? (ctx) => handler(item, ctx) : undefined; - if (handlerWrapper) { - handlerWrapper.__VITEST_FIXTURE_INDEX__ = 1; - handlerWrapper.toString = () => handler.toString(); - } - test(formatTitle(_name, toArray(item), idx), options, handlerWrapper); - }); - }; - }; - taskFn.skipIf = function(condition) { - return condition ? this.skip : this; - }; - taskFn.runIf = function(condition) { - return condition ? this : this.skip; - }; - taskFn.scoped = function(fixtures) { - const collector = getCurrentSuite(); - collector.scoped(fixtures); - }; - taskFn.extend = function(fixtures) { - const _context = mergeContextFixtures(fixtures, context || {}, runner); - const originalWrapper = fn; - return createTest(function(name, optionsOrFn, optionsOrTest) { - const collector = getCurrentSuite(); - const scopedFixtures = collector.fixtures(); - const context = { ...this }; - if (scopedFixtures) { - context.fixtures = mergeScopedFixtures(context.fixtures || [], scopedFixtures); - } - originalWrapper.call(context, formatName(name), optionsOrFn, optionsOrTest); - }, _context); - }; - taskFn.beforeEach = beforeEach; - taskFn.afterEach = afterEach; - taskFn.beforeAll = beforeAll; - taskFn.afterAll = afterAll; - const _test = createChainable([ - "concurrent", - "sequential", - "skip", - "only", - "todo", - "fails" - ], taskFn); - if (context) { - _test.mergeContext(context); - } - return _test; -} -function createTest(fn, context) { - return createTaskCollector(fn, context); -} -function formatName(name) { - return typeof name === "string" ? name : typeof name === "function" ? name.name || "<anonymous>" : String(name); -} -function formatTitle(template, items, idx) { - if (template.includes("%#") || template.includes("%$")) { - // '%#' match index of the test case - template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%"); - } - const count = template.split("%").length - 1; - if (template.includes("%f")) { - const placeholders = template.match(/%f/g) || []; - placeholders.forEach((_, i) => { - if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) { - // Replace the i-th occurrence of '%f' with '-%f' - let occurrence = 0; - template = template.replace(/%f/g, (match) => { - occurrence++; - return occurrence === i + 1 ? "-%f" : match; - }); - } - }); - } - const isObjectItem = isObject(items[0]); - function formatAttribute(s) { - return s.replace(/\$([$\w.]+)/g, (_, key) => { - var _runner$config; - const isArrayKey = /^\d+$/.test(key); - if (!isObjectItem && !isArrayKey) { - return `$${key}`; - } - const arrayElement = isArrayKey ? objectAttr(items, key) : undefined; - const value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement; - return objDisplay(value, { truncate: runner === null || runner === void 0 || (_runner$config = runner.config) === null || _runner$config === void 0 || (_runner$config = _runner$config.chaiConfig) === null || _runner$config === void 0 ? void 0 : _runner$config.truncateThreshold }); - }); - } - let output = ""; - let i = 0; - handleRegexMatch( - template, - formatRegExp, - // format "%" - (match) => { - if (i < count) { - output += format(match[0], items[i++]); - } else { - output += match[0]; - } - }, - // format "$" - (nonMatch) => { - output += formatAttribute(nonMatch); - } - ); - return output; -} -// based on https://github.com/unocss/unocss/blob/2e74b31625bbe3b9c8351570749aa2d3f799d919/packages/autocomplete/src/parse.ts#L11 -function handleRegexMatch(input, regex, onMatch, onNonMatch) { - let lastIndex = 0; - for (const m of input.matchAll(regex)) { - if (lastIndex < m.index) { - onNonMatch(input.slice(lastIndex, m.index)); - } - onMatch(m); - lastIndex = m.index + m[0].length; - } - if (lastIndex < input.length) { - onNonMatch(input.slice(lastIndex)); - } -} -function formatTemplateString(cases, args) { - const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0]; - const res = []; - for (let i = 0; i < Math.floor(args.length / header.length); i++) { - const oneCase = {}; - for (let j = 0; j < header.length; j++) { - oneCase[header[j]] = args[i * header.length + j]; - } - res.push(oneCase); - } - return res; -} - -const now$2 = Date.now; -const collectorContext = { - tasks: [], - currentSuite: null -}; -function collectTask(task) { - var _collectorContext$cur; - (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.tasks.push(task); -} -async function runWithSuite(suite, fn) { - const prev = collectorContext.currentSuite; - collectorContext.currentSuite = suite; - await fn(); - collectorContext.currentSuite = prev; -} -function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) { - if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) { - return fn; - } - const { setTimeout, clearTimeout } = getSafeTimers(); - // this function name is used to filter error in test/cli/test/fails.test.ts - return (function runWithTimeout(...args) { - const startTime = now$2(); - const runner = getRunner(); - runner._currentTaskStartTime = startTime; - runner._currentTaskTimeout = timeout; - return new Promise((resolve_, reject_) => { - var _timer$unref; - const timer = setTimeout(() => { - clearTimeout(timer); - rejectTimeoutError(); - }, timeout); - // `unref` might not exist in browser - (_timer$unref = timer.unref) === null || _timer$unref === void 0 ? void 0 : _timer$unref.call(timer); - function rejectTimeoutError() { - const error = makeTimeoutError(isHook, timeout, stackTraceError); - onTimeout === null || onTimeout === void 0 ? void 0 : onTimeout(args, error); - reject_(error); - } - function resolve(result) { - runner._currentTaskStartTime = undefined; - runner._currentTaskTimeout = undefined; - clearTimeout(timer); - // if test/hook took too long in microtask, setTimeout won't be triggered, - // but we still need to fail the test, see - // https://github.com/vitest-dev/vitest/issues/2920 - if (now$2() - startTime >= timeout) { - rejectTimeoutError(); - return; - } - resolve_(result); - } - function reject(error) { - runner._currentTaskStartTime = undefined; - runner._currentTaskTimeout = undefined; - clearTimeout(timer); - reject_(error); - } - // sync test/hook will be caught by try/catch - try { - const result = fn(...args); - // the result is a thenable, we don't wrap this in Promise.resolve - // to avoid creating new promises - if (typeof result === "object" && result != null && typeof result.then === "function") { - result.then(resolve, reject); - } else { - resolve(result); - } - } - // user sync test/hook throws an error -catch (error) { - reject(error); - } - }); - }); -} -const abortControllers = new WeakMap(); -function abortIfTimeout([context], error) { - if (context) { - abortContextSignal(context, error); - } -} -function abortContextSignal(context, error) { - const abortController = abortControllers.get(context); - abortController === null || abortController === void 0 ? void 0 : abortController.abort(error); -} -function createTestContext(test, runner) { - var _runner$extendTaskCon; - const context = function() { - throw new Error("done() callback is deprecated, use promise instead"); - }; - let abortController = abortControllers.get(context); - if (!abortController) { - abortController = new AbortController(); - abortControllers.set(context, abortController); - } - context.signal = abortController.signal; - context.task = test; - context.skip = (condition, note) => { - if (condition === false) { - // do nothing - return undefined; - } - test.result ?? (test.result = { state: "skip" }); - test.result.pending = true; - throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note); - }; - context.annotate = ((message, type, attachment) => { - if (test.result && test.result.state !== "run") { - throw new Error(`Cannot annotate tests outside of the test run. The test "${test.name}" finished running with the "${test.result.state}" state already.`); - } - const annotation = { - message, - type: typeof type === "object" || type === undefined ? "notice" : type - }; - const annotationAttachment = typeof type === "object" ? type : attachment; - if (annotationAttachment) { - annotation.attachment = annotationAttachment; - manageArtifactAttachment(annotation.attachment); - } - return recordAsyncOperation(test, recordArtifact(test, { - type: "internal:annotation", - annotation - }).then(async ({ annotation }) => { - if (!runner.onTestAnnotate) { - throw new Error(`Test runner doesn't support test annotations.`); - } - await finishSendTasksUpdate(runner); - const resolvedAnnotation = await runner.onTestAnnotate(test, annotation); - test.annotations.push(resolvedAnnotation); - return resolvedAnnotation; - })); - }); - context.onTestFailed = (handler, timeout) => { - test.onFailed || (test.onFailed = []); - test.onFailed.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error))); - }; - context.onTestFinished = (handler, timeout) => { - test.onFinished || (test.onFinished = []); - test.onFinished.push(withTimeout(handler, timeout ?? runner.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error))); - }; - return ((_runner$extendTaskCon = runner.extendTaskContext) === null || _runner$extendTaskCon === void 0 ? void 0 : _runner$extendTaskCon.call(runner, context)) || context; -} -function makeTimeoutError(isHook, timeout, stackTraceError) { - const message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.\nIf this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`; - const error = new Error(message); - if (stackTraceError === null || stackTraceError === void 0 ? void 0 : stackTraceError.stack) { - error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message); - } - return error; -} -const fileContexts = new WeakMap(); -function getFileContext(file) { - const context = fileContexts.get(file); - if (!context) { - throw new Error(`Cannot find file context for ${file.name}`); - } - return context; -} -function setFileContext(file, context) { - fileContexts.set(file, context); -} - -async function runSetupFiles(config, files, runner) { - if (config.sequence.setupFiles === "parallel") { - await Promise.all(files.map(async (fsPath) => { - await runner.importFile(fsPath, "setup"); - })); - } else { - for (const fsPath of files) { - await runner.importFile(fsPath, "setup"); - } - } -} - -const now$1 = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now; -async function collectTests(specs, runner) { - const files = []; - const config = runner.config; - const $ = runner.trace; - for (const spec of specs) { - const filepath = typeof spec === "string" ? spec : spec.filepath; - await $("collect_spec", { "code.file.path": filepath }, async () => { - var _runner$onCollectStar; - const testLocations = typeof spec === "string" ? undefined : spec.testLocations; - const file = createFileTask(filepath, config.root, config.name, runner.pool, runner.viteEnvironment); - setFileContext(file, Object.create(null)); - file.shuffle = config.sequence.shuffle; - (_runner$onCollectStar = runner.onCollectStart) === null || _runner$onCollectStar === void 0 ? void 0 : _runner$onCollectStar.call(runner, file); - clearCollectorContext(file, runner); - try { - var _runner$getImportDura; - const setupFiles = toArray(config.setupFiles); - if (setupFiles.length) { - const setupStart = now$1(); - await runSetupFiles(config, setupFiles, runner); - const setupEnd = now$1(); - file.setupDuration = setupEnd - setupStart; - } else { - file.setupDuration = 0; - } - const collectStart = now$1(); - await runner.importFile(filepath, "collect"); - const durations = (_runner$getImportDura = runner.getImportDurations) === null || _runner$getImportDura === void 0 ? void 0 : _runner$getImportDura.call(runner); - if (durations) { - file.importDurations = durations; - } - const defaultTasks = await getDefaultSuite().collect(file); - const fileHooks = createSuiteHooks(); - mergeHooks(fileHooks, getHooks(defaultTasks)); - for (const c of [...defaultTasks.tasks, ...collectorContext.tasks]) { - if (c.type === "test" || c.type === "suite") { - file.tasks.push(c); - } else if (c.type === "collector") { - const suite = await c.collect(file); - if (suite.name || suite.tasks.length) { - mergeHooks(fileHooks, getHooks(suite)); - file.tasks.push(suite); - } - } else { - // check that types are exhausted - c; - } - } - setHooks(file, fileHooks); - file.collectDuration = now$1() - collectStart; - } catch (e) { - var _runner$getImportDura2; - const error = processError(e); - file.result = { - state: "fail", - errors: [error] - }; - const durations = (_runner$getImportDura2 = runner.getImportDurations) === null || _runner$getImportDura2 === void 0 ? void 0 : _runner$getImportDura2.call(runner); - if (durations) { - file.importDurations = durations; - } - } - calculateSuiteHash(file); - const hasOnlyTasks = someTasksAreOnly(file); - interpretTaskModes(file, config.testNamePattern, testLocations, hasOnlyTasks, false, config.allowOnly); - if (file.mode === "queued") { - file.mode = "run"; - } - files.push(file); - }); - } - return files; -} -function mergeHooks(baseHooks, hooks) { - for (const _key in hooks) { - const key = _key; - baseHooks[key].push(...hooks[key]); - } - return baseHooks; -} - -const now = globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now; -const unixNow = Date.now; -const { clearTimeout, setTimeout } = getSafeTimers(); -function updateSuiteHookState(task, name, state, runner) { - if (!task.result) { - task.result = { state: "run" }; - } - if (!task.result.hooks) { - task.result.hooks = {}; - } - const suiteHooks = task.result.hooks; - if (suiteHooks) { - suiteHooks[name] = state; - let event = state === "run" ? "before-hook-start" : "before-hook-end"; - if (name === "afterAll" || name === "afterEach") { - event = state === "run" ? "after-hook-start" : "after-hook-end"; - } - updateTask(event, task, runner); - } -} -function getSuiteHooks(suite, name, sequence) { - const hooks = getHooks(suite)[name]; - if (sequence === "stack" && (name === "afterAll" || name === "afterEach")) { - return hooks.slice().reverse(); - } - return hooks; -} -async function callTestHooks(runner, test, hooks, sequence) { - if (sequence === "stack") { - hooks = hooks.slice().reverse(); - } - if (!hooks.length) { - return; - } - const context = test.context; - const onTestFailed = test.context.onTestFailed; - const onTestFinished = test.context.onTestFinished; - context.onTestFailed = () => { - throw new Error(`Cannot call "onTestFailed" inside a test hook.`); - }; - context.onTestFinished = () => { - throw new Error(`Cannot call "onTestFinished" inside a test hook.`); - }; - if (sequence === "parallel") { - try { - await Promise.all(hooks.map((fn) => fn(test.context))); - } catch (e) { - failTask(test.result, e, runner.config.diffOptions); - } - } else { - for (const fn of hooks) { - try { - await fn(test.context); - } catch (e) { - failTask(test.result, e, runner.config.diffOptions); - } - } - } - context.onTestFailed = onTestFailed; - context.onTestFinished = onTestFinished; -} -async function callSuiteHook(suite, currentTask, name, runner, args) { - const sequence = runner.config.sequence.hooks; - const callbacks = []; - // stop at file level - const parentSuite = "filepath" in suite ? null : suite.suite || suite.file; - if (name === "beforeEach" && parentSuite) { - callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args)); - } - const hooks = getSuiteHooks(suite, name, sequence); - if (hooks.length > 0) { - updateSuiteHookState(currentTask, name, "run", runner); - } - async function runHook(hook) { - return getBeforeHookCleanupCallback(hook, await hook(...args), name === "beforeEach" ? args[0] : undefined); - } - if (sequence === "parallel") { - callbacks.push(...await Promise.all(hooks.map((hook) => runHook(hook)))); - } else { - for (const hook of hooks) { - callbacks.push(await runHook(hook)); - } - } - if (hooks.length > 0) { - updateSuiteHookState(currentTask, name, "pass", runner); - } - if (name === "afterEach" && parentSuite) { - callbacks.push(...await callSuiteHook(parentSuite, currentTask, name, runner, args)); - } - return callbacks; -} -const packs = new Map(); -const eventsPacks = []; -const pendingTasksUpdates = []; -function sendTasksUpdate(runner) { - if (packs.size) { - var _runner$onTaskUpdate; - const taskPacks = Array.from(packs).map(([id, task]) => { - return [ - id, - task[0], - task[1] - ]; - }); - const p = (_runner$onTaskUpdate = runner.onTaskUpdate) === null || _runner$onTaskUpdate === void 0 ? void 0 : _runner$onTaskUpdate.call(runner, taskPacks, eventsPacks); - if (p) { - pendingTasksUpdates.push(p); - // remove successful promise to not grow array indefnitely, - // but keep rejections so finishSendTasksUpdate can handle them - p.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p), 1), () => {}); - } - eventsPacks.length = 0; - packs.clear(); - } -} -async function finishSendTasksUpdate(runner) { - sendTasksUpdate(runner); - await Promise.all(pendingTasksUpdates); -} -function throttle(fn, ms) { - let last = 0; - let pendingCall; - return function call(...args) { - const now = unixNow(); - if (now - last > ms) { - last = now; - clearTimeout(pendingCall); - pendingCall = undefined; - return fn.apply(this, args); - } - // Make sure fn is still called even if there are no further calls - pendingCall ?? (pendingCall = setTimeout(() => call.bind(this)(...args), ms)); - }; -} -// throttle based on summary reporter's DURATION_UPDATE_INTERVAL_MS -const sendTasksUpdateThrottled = throttle(sendTasksUpdate, 100); -function updateTask(event, task, runner) { - eventsPacks.push([ - task.id, - event, - undefined - ]); - packs.set(task.id, [task.result, task.meta]); - sendTasksUpdateThrottled(runner); -} -async function callCleanupHooks(runner, cleanups) { - const sequence = runner.config.sequence.hooks; - if (sequence === "stack") { - cleanups = cleanups.slice().reverse(); - } - if (sequence === "parallel") { - await Promise.all(cleanups.map(async (fn) => { - if (typeof fn !== "function") { - return; - } - await fn(); - })); - } else { - for (const fn of cleanups) { - if (typeof fn !== "function") { - continue; - } - await fn(); - } - } -} -async function runTest(test, runner) { - var _runner$onBeforeRunTa, _test$result, _runner$onAfterRunTas; - await ((_runner$onBeforeRunTa = runner.onBeforeRunTask) === null || _runner$onBeforeRunTa === void 0 ? void 0 : _runner$onBeforeRunTa.call(runner, test)); - if (test.mode !== "run" && test.mode !== "queued") { - updateTask("test-prepare", test, runner); - updateTask("test-finished", test, runner); - return; - } - if (((_test$result = test.result) === null || _test$result === void 0 ? void 0 : _test$result.state) === "fail") { - // should not be possible to get here, I think this is just copy pasted from suite - // TODO: maybe someone fails tests in `beforeAll` hooks? - // https://github.com/vitest-dev/vitest/pull/7069 - updateTask("test-failed-early", test, runner); - return; - } - const start = now(); - test.result = { - state: "run", - startTime: unixNow(), - retryCount: 0 - }; - updateTask("test-prepare", test, runner); - const cleanupRunningTest = addRunningTest(test); - setCurrentTest(test); - const suite = test.suite || test.file; - const $ = runner.trace; - const repeats = test.repeats ?? 0; - for (let repeatCount = 0; repeatCount <= repeats; repeatCount++) { - const retry = test.retry ?? 0; - for (let retryCount = 0; retryCount <= retry; retryCount++) { - var _test$onFinished, _test$onFailed, _runner$onAfterRetryT, _test$result2, _test$result3; - let beforeEachCleanups = []; - try { - var _runner$onBeforeTryTa, _runner$onAfterTryTas; - await ((_runner$onBeforeTryTa = runner.onBeforeTryTask) === null || _runner$onBeforeTryTa === void 0 ? void 0 : _runner$onBeforeTryTa.call(runner, test, { - retry: retryCount, - repeats: repeatCount - })); - test.result.repeatCount = repeatCount; - beforeEachCleanups = await $("test.beforeEach", () => callSuiteHook(suite, test, "beforeEach", runner, [test.context, suite])); - if (runner.runTask) { - await $("test.callback", () => runner.runTask(test)); - } else { - const fn = getFn(test); - if (!fn) { - throw new Error("Test function is not found. Did you add it using `setFn`?"); - } - await $("test.callback", () => fn()); - } - await ((_runner$onAfterTryTas = runner.onAfterTryTask) === null || _runner$onAfterTryTas === void 0 ? void 0 : _runner$onAfterTryTas.call(runner, test, { - retry: retryCount, - repeats: repeatCount - })); - if (test.result.state !== "fail") { - if (!test.repeats) { - test.result.state = "pass"; - } else if (test.repeats && retry === retryCount) { - test.result.state = "pass"; - } - } - } catch (e) { - failTask(test.result, e, runner.config.diffOptions); - } - try { - var _runner$onTaskFinishe; - await ((_runner$onTaskFinishe = runner.onTaskFinished) === null || _runner$onTaskFinishe === void 0 ? void 0 : _runner$onTaskFinishe.call(runner, test)); - } catch (e) { - failTask(test.result, e, runner.config.diffOptions); - } - try { - await $("test.afterEach", () => callSuiteHook(suite, test, "afterEach", runner, [test.context, suite])); - if (beforeEachCleanups.length) { - await $("test.cleanup", () => callCleanupHooks(runner, beforeEachCleanups)); - } - await callFixtureCleanup(test.context); - } catch (e) { - failTask(test.result, e, runner.config.diffOptions); - } - if ((_test$onFinished = test.onFinished) === null || _test$onFinished === void 0 ? void 0 : _test$onFinished.length) { - await $("test.onFinished", () => callTestHooks(runner, test, test.onFinished, "stack")); - } - if (test.result.state === "fail" && ((_test$onFailed = test.onFailed) === null || _test$onFailed === void 0 ? void 0 : _test$onFailed.length)) { - await $("test.onFailed", () => callTestHooks(runner, test, test.onFailed, runner.config.sequence.hooks)); - } - test.onFailed = undefined; - test.onFinished = undefined; - await ((_runner$onAfterRetryT = runner.onAfterRetryTask) === null || _runner$onAfterRetryT === void 0 ? void 0 : _runner$onAfterRetryT.call(runner, test, { - retry: retryCount, - repeats: repeatCount - })); - // skipped with new PendingError - if (((_test$result2 = test.result) === null || _test$result2 === void 0 ? void 0 : _test$result2.pending) || ((_test$result3 = test.result) === null || _test$result3 === void 0 ? void 0 : _test$result3.state) === "skip") { - var _test$result4; - test.mode = "skip"; - test.result = { - state: "skip", - note: (_test$result4 = test.result) === null || _test$result4 === void 0 ? void 0 : _test$result4.note, - pending: true, - duration: now() - start - }; - updateTask("test-finished", test, runner); - setCurrentTest(undefined); - cleanupRunningTest(); - return; - } - if (test.result.state === "pass") { - break; - } - if (retryCount < retry) { - // reset state when retry test - test.result.state = "run"; - test.result.retryCount = (test.result.retryCount ?? 0) + 1; - } - // update retry info - updateTask("test-retried", test, runner); - } - } - // if test is marked to be failed, flip the result - if (test.fails) { - if (test.result.state === "pass") { - const error = processError(new Error("Expect test to fail")); - test.result.state = "fail"; - test.result.errors = [error]; - } else { - test.result.state = "pass"; - test.result.errors = undefined; - } - } - cleanupRunningTest(); - setCurrentTest(undefined); - test.result.duration = now() - start; - await ((_runner$onAfterRunTas = runner.onAfterRunTask) === null || _runner$onAfterRunTas === void 0 ? void 0 : _runner$onAfterRunTas.call(runner, test)); - updateTask("test-finished", test, runner); -} -function failTask(result, err, diffOptions) { - if (err instanceof PendingError) { - result.state = "skip"; - result.note = err.note; - result.pending = true; - return; - } - result.state = "fail"; - const errors = Array.isArray(err) ? err : [err]; - for (const e of errors) { - const error = processError(e, diffOptions); - result.errors ?? (result.errors = []); - result.errors.push(error); - } -} -function markTasksAsSkipped(suite, runner) { - suite.tasks.forEach((t) => { - t.mode = "skip"; - t.result = { - ...t.result, - state: "skip" - }; - updateTask("test-finished", t, runner); - if (t.type === "suite") { - markTasksAsSkipped(t, runner); - } - }); -} -async function runSuite(suite, runner) { - var _runner$onBeforeRunSu, _suite$result; - await ((_runner$onBeforeRunSu = runner.onBeforeRunSuite) === null || _runner$onBeforeRunSu === void 0 ? void 0 : _runner$onBeforeRunSu.call(runner, suite)); - if (((_suite$result = suite.result) === null || _suite$result === void 0 ? void 0 : _suite$result.state) === "fail") { - markTasksAsSkipped(suite, runner); - // failed during collection - updateTask("suite-failed-early", suite, runner); - return; - } - const start = now(); - const mode = suite.mode; - suite.result = { - state: mode === "skip" || mode === "todo" ? mode : "run", - startTime: unixNow() - }; - const $ = runner.trace; - updateTask("suite-prepare", suite, runner); - let beforeAllCleanups = []; - if (suite.mode === "skip") { - suite.result.state = "skip"; - updateTask("suite-finished", suite, runner); - } else if (suite.mode === "todo") { - suite.result.state = "todo"; - updateTask("suite-finished", suite, runner); - } else { - var _runner$onAfterRunSui; - try { - try { - beforeAllCleanups = await $("suite.beforeAll", () => callSuiteHook(suite, suite, "beforeAll", runner, [suite])); - } catch (e) { - markTasksAsSkipped(suite, runner); - throw e; - } - if (runner.runSuite) { - await runner.runSuite(suite); - } else { - for (let tasksGroup of partitionSuiteChildren(suite)) { - if (tasksGroup[0].concurrent === true) { - await Promise.all(tasksGroup.map((c) => runSuiteChild(c, runner))); - } else { - const { sequence } = runner.config; - if (suite.shuffle) { - // run describe block independently from tests - const suites = tasksGroup.filter((group) => group.type === "suite"); - const tests = tasksGroup.filter((group) => group.type === "test"); - const groups = shuffle([suites, tests], sequence.seed); - tasksGroup = groups.flatMap((group) => shuffle(group, sequence.seed)); - } - for (const c of tasksGroup) { - await runSuiteChild(c, runner); - } - } - } - } - } catch (e) { - failTask(suite.result, e, runner.config.diffOptions); - } - try { - await $("suite.afterAll", () => callSuiteHook(suite, suite, "afterAll", runner, [suite])); - if (beforeAllCleanups.length) { - await $("suite.cleanup", () => callCleanupHooks(runner, beforeAllCleanups)); - } - if (suite.file === suite) { - const context = getFileContext(suite); - await callFixtureCleanup(context); - } - } catch (e) { - failTask(suite.result, e, runner.config.diffOptions); - } - if (suite.mode === "run" || suite.mode === "queued") { - if (!runner.config.passWithNoTests && !hasTests(suite)) { - var _suite$result$errors; - suite.result.state = "fail"; - if (!((_suite$result$errors = suite.result.errors) === null || _suite$result$errors === void 0 ? void 0 : _suite$result$errors.length)) { - const error = processError(new Error(`No test found in suite ${suite.name}`)); - suite.result.errors = [error]; - } - } else if (hasFailed(suite)) { - suite.result.state = "fail"; - } else { - suite.result.state = "pass"; - } - } - suite.result.duration = now() - start; - await ((_runner$onAfterRunSui = runner.onAfterRunSuite) === null || _runner$onAfterRunSui === void 0 ? void 0 : _runner$onAfterRunSui.call(runner, suite)); - updateTask("suite-finished", suite, runner); - } -} -let limitMaxConcurrency; -async function runSuiteChild(c, runner) { - const $ = runner.trace; - if (c.type === "test") { - return limitMaxConcurrency(() => { - var _c$location, _c$location2; - return $("run.test", { - "vitest.test.id": c.id, - "vitest.test.name": c.name, - "vitest.test.mode": c.mode, - "vitest.test.timeout": c.timeout, - "code.file.path": c.file.filepath, - "code.line.number": (_c$location = c.location) === null || _c$location === void 0 ? void 0 : _c$location.line, - "code.column.number": (_c$location2 = c.location) === null || _c$location2 === void 0 ? void 0 : _c$location2.column - }, () => runTest(c, runner)); - }); - } else if (c.type === "suite") { - var _c$location3, _c$location4; - return $("run.suite", { - "vitest.suite.id": c.id, - "vitest.suite.name": c.name, - "vitest.suite.mode": c.mode, - "code.file.path": c.file.filepath, - "code.line.number": (_c$location3 = c.location) === null || _c$location3 === void 0 ? void 0 : _c$location3.line, - "code.column.number": (_c$location4 = c.location) === null || _c$location4 === void 0 ? void 0 : _c$location4.column - }, () => runSuite(c, runner)); - } -} -async function runFiles(files, runner) { - limitMaxConcurrency ?? (limitMaxConcurrency = limitConcurrency(runner.config.maxConcurrency)); - for (const file of files) { - if (!file.tasks.length && !runner.config.passWithNoTests) { - var _file$result; - if (!((_file$result = file.result) === null || _file$result === void 0 || (_file$result = _file$result.errors) === null || _file$result === void 0 ? void 0 : _file$result.length)) { - const error = processError(new Error(`No test suite found in file ${file.filepath}`)); - file.result = { - state: "fail", - errors: [error] - }; - } - } - await runner.trace("run.spec", { - "code.file.path": file.filepath, - "vitest.suite.tasks.length": file.tasks.length - }, () => runSuite(file, runner)); - } -} -const workerRunners = new WeakSet(); -function defaultTrace(_, attributes, cb) { - if (typeof attributes === "function") { - return attributes(); - } - return cb(); -} -async function startTests(specs, runner) { - var _runner$cancel; - runner.trace ?? (runner.trace = defaultTrace); - const cancel = (_runner$cancel = runner.cancel) === null || _runner$cancel === void 0 ? void 0 : _runner$cancel.bind(runner); - // Ideally, we need to have an event listener for this, but only have a runner here. - // Adding another onCancel felt wrong (maybe it needs to be refactored) - runner.cancel = (reason) => { - // We intentionally create only one error since there is only one test run that can be cancelled - const error = new TestRunAbortError("The test run was aborted by the user.", reason); - getRunningTests().forEach((test) => abortContextSignal(test.context, error)); - return cancel === null || cancel === void 0 ? void 0 : cancel(reason); - }; - if (!workerRunners.has(runner)) { - var _runner$onCleanupWork; - (_runner$onCleanupWork = runner.onCleanupWorkerContext) === null || _runner$onCleanupWork === void 0 ? void 0 : _runner$onCleanupWork.call(runner, async () => { - var _runner$getWorkerCont; - const context = (_runner$getWorkerCont = runner.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner); - if (context) { - await callFixtureCleanup(context); - } - }); - workerRunners.add(runner); - } - try { - var _runner$onBeforeColle, _runner$onCollected, _runner$onBeforeRunFi, _runner$onAfterRunFil; - const paths = specs.map((f) => typeof f === "string" ? f : f.filepath); - await ((_runner$onBeforeColle = runner.onBeforeCollect) === null || _runner$onBeforeColle === void 0 ? void 0 : _runner$onBeforeColle.call(runner, paths)); - const files = await collectTests(specs, runner); - await ((_runner$onCollected = runner.onCollected) === null || _runner$onCollected === void 0 ? void 0 : _runner$onCollected.call(runner, files)); - await ((_runner$onBeforeRunFi = runner.onBeforeRunFiles) === null || _runner$onBeforeRunFi === void 0 ? void 0 : _runner$onBeforeRunFi.call(runner, files)); - await runFiles(files, runner); - await ((_runner$onAfterRunFil = runner.onAfterRunFiles) === null || _runner$onAfterRunFil === void 0 ? void 0 : _runner$onAfterRunFil.call(runner, files)); - await finishSendTasksUpdate(runner); - return files; - } finally { - runner.cancel = cancel; - } -} -async function publicCollect(specs, runner) { - var _runner$onBeforeColle2, _runner$onCollected2; - runner.trace ?? (runner.trace = defaultTrace); - const paths = specs.map((f) => typeof f === "string" ? f : f.filepath); - await ((_runner$onBeforeColle2 = runner.onBeforeCollect) === null || _runner$onBeforeColle2 === void 0 ? void 0 : _runner$onBeforeColle2.call(runner, paths)); - const files = await collectTests(specs, runner); - await ((_runner$onCollected2 = runner.onCollected) === null || _runner$onCollected2 === void 0 ? void 0 : _runner$onCollected2.call(runner, files)); - return files; -} - -/** -* @experimental -* @advanced -* -* Records a custom test artifact during test execution. -* -* This function allows you to attach structured data, files, or metadata to a test. -* -* Vitest automatically injects the source location where the artifact was created and manages any attachments you include. -* -* @param task - The test task context, typically accessed via `this.task` in custom matchers or `context.task` in tests -* @param artifact - The artifact to record. Must extend {@linkcode TestArtifactBase} -* -* @returns A promise that resolves to the recorded artifact with location injected -* -* @throws {Error} If called after the test has finished running -* @throws {Error} If the test runner doesn't support artifacts -* -* @example -* ```ts -* // In a custom assertion -* async function toHaveValidSchema(this: MatcherState, actual: unknown) { -* const validation = validateSchema(actual) -* -* await recordArtifact(this.task, { -* type: 'my-plugin:schema-validation', -* passed: validation.valid, -* errors: validation.errors, -* }) -* -* return { pass: validation.valid, message: () => '...' } -* } -* ``` -*/ -async function recordArtifact(task, artifact) { - const runner = getRunner(); - if (task.result && task.result.state !== "run") { - throw new Error(`Cannot record a test artifact outside of the test run. The test "${task.name}" finished running with the "${task.result.state}" state already.`); - } - const stack = findTestFileStackTrace(task.file.filepath, new Error("STACK_TRACE").stack); - if (stack) { - artifact.location = { - file: stack.file, - line: stack.line, - column: stack.column - }; - if (artifact.type === "internal:annotation") { - artifact.annotation.location = artifact.location; - } - } - if (Array.isArray(artifact.attachments)) { - for (const attachment of artifact.attachments) { - manageArtifactAttachment(attachment); - } - } - // annotations won't resolve as artifacts for backwards compatibility until next major - if (artifact.type === "internal:annotation") { - return artifact; - } - if (!runner.onTestArtifactRecord) { - throw new Error(`Test runner doesn't support test artifacts.`); - } - await finishSendTasksUpdate(runner); - const resolvedArtifact = await runner.onTestArtifactRecord(task, artifact); - task.artifacts.push(resolvedArtifact); - return resolvedArtifact; -} -const table = []; -for (let i = 65; i < 91; i++) { - table.push(String.fromCharCode(i)); -} -for (let i = 97; i < 123; i++) { - table.push(String.fromCharCode(i)); -} -for (let i = 0; i < 10; i++) { - table.push(i.toString(10)); -} -table.push("+", "/"); -function encodeUint8Array(bytes) { - let base64 = ""; - const len = bytes.byteLength; - for (let i = 0; i < len; i += 3) { - if (len === i + 1) { - const a = (bytes[i] & 252) >> 2; - const b = (bytes[i] & 3) << 4; - base64 += table[a]; - base64 += table[b]; - base64 += "=="; - } else if (len === i + 2) { - const a = (bytes[i] & 252) >> 2; - const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4; - const c = (bytes[i + 1] & 15) << 2; - base64 += table[a]; - base64 += table[b]; - base64 += table[c]; - base64 += "="; - } else { - const a = (bytes[i] & 252) >> 2; - const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4; - const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6; - const d = bytes[i + 2] & 63; - base64 += table[a]; - base64 += table[b]; - base64 += table[c]; - base64 += table[d]; - } - } - return base64; -} -/** -* Records an async operation associated with a test task. -* -* This function tracks promises that should be awaited before a test completes. -* The promise is automatically removed from the test's promise list once it settles. -*/ -function recordAsyncOperation(test, promise) { - // if promise is explicitly awaited, remove it from the list - promise = promise.finally(() => { - if (!test.promises) { - return; - } - const index = test.promises.indexOf(promise); - if (index !== -1) { - test.promises.splice(index, 1); - } - }); - // record promise - if (!test.promises) { - test.promises = []; - } - test.promises.push(promise); - return promise; -} -/** -* Validates and prepares a test attachment for serialization. -* -* This function ensures attachments have either `body` or `path` set (but not both), and converts `Uint8Array` bodies to base64-encoded strings for easier serialization. -* -* @param attachment - The attachment to validate and prepare -* -* @throws {TypeError} If neither `body` nor `path` is provided -* @throws {TypeError} If both `body` and `path` are provided -*/ -function manageArtifactAttachment(attachment) { - if (attachment.body == null && !attachment.path) { - throw new TypeError(`Test attachment requires "body" or "path" to be set. Both are missing.`); - } - if (attachment.body && attachment.path) { - throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`); - } - // convert to a string so it's easier to serialise - if (attachment.body instanceof Uint8Array) { - attachment.body = encodeUint8Array(attachment.body); - } -} - -export { afterAll, afterEach, beforeAll, beforeEach, publicCollect as collectTests, createTaskCollector, describe, getCurrentSuite, getCurrentTest, getFn, getHooks, it, onTestFailed, onTestFinished, recordArtifact, setFn, setHooks, startTests, suite, test, updateTask }; diff --git a/vanilla/node_modules/@vitest/runner/dist/tasks.d-C7UxawJ9.d.ts b/vanilla/node_modules/@vitest/runner/dist/tasks.d-C7UxawJ9.d.ts deleted file mode 100644 index a0b07a1..0000000 --- a/vanilla/node_modules/@vitest/runner/dist/tasks.d-C7UxawJ9.d.ts +++ /dev/null @@ -1,834 +0,0 @@ -import { TestError, Awaitable } from '@vitest/utils'; - -interface FixtureItem extends FixtureOptions { - prop: string; - value: any; - scope: "test" | "file" | "worker"; - /** - * Indicates whether the fixture is a function - */ - isFn: boolean; - /** - * The dependencies(fixtures) of current fixture function. - */ - deps?: FixtureItem[]; -} - -/** -* Registers a callback function to be executed once before all tests within the current suite. -* This hook is useful for scenarios where you need to perform setup operations that are common to all tests in a suite, such as initializing a database connection or setting up a test environment. -* -* **Note:** The `beforeAll` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed before all tests. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @returns {void} -* @example -* ```ts -* // Example of using beforeAll to set up a database connection -* beforeAll(async () => { -* await database.connect(); -* }); -* ``` -*/ -declare function beforeAll(fn: BeforeAllListener, timeout?: number): void; -/** -* Registers a callback function to be executed once after all tests within the current suite have completed. -* This hook is useful for scenarios where you need to perform cleanup operations after all tests in a suite have run, such as closing database connections or cleaning up temporary files. -* -* **Note:** The `afterAll` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed after all tests. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @returns {void} -* @example -* ```ts -* // Example of using afterAll to close a database connection -* afterAll(async () => { -* await database.disconnect(); -* }); -* ``` -*/ -declare function afterAll(fn: AfterAllListener, timeout?: number): void; -/** -* Registers a callback function to be executed before each test within the current suite. -* This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. -* -* **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @returns {void} -* @example -* ```ts -* // Example of using beforeEach to reset a database state -* beforeEach(async () => { -* await database.reset(); -* }); -* ``` -*/ -declare function beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void; -/** -* Registers a callback function to be executed after each test within the current suite has completed. -* This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. -* -* **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @returns {void} -* @example -* ```ts -* // Example of using afterEach to delete temporary files created during a test -* afterEach(async () => { -* await fileSystem.deleteTempFiles(); -* }); -* ``` -*/ -declare function afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void; -/** -* Registers a callback function to be executed when a test fails within the current suite. -* This function allows for custom actions to be performed in response to test failures, such as logging, cleanup, or additional diagnostics. -* -* **Note:** The `onTestFailed` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. -* -* @param {Function} fn - The callback function to be executed upon a test failure. The function receives the test result (including errors). -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @throws {Error} Throws an error if the function is not called within a test. -* @returns {void} -* @example -* ```ts -* // Example of using onTestFailed to log failure details -* onTestFailed(({ errors }) => { -* console.log(`Test failed: ${test.name}`, errors); -* }); -* ``` -*/ -declare const onTestFailed: TaskHook<OnTestFailedHandler>; -/** -* Registers a callback function to be executed when the current test finishes, regardless of the outcome (pass or fail). -* This function is ideal for performing actions that should occur after every test execution, such as cleanup, logging, or resetting shared resources. -* -* This hook is useful if you have access to a resource in the test itself and you want to clean it up after the test finishes. It is a more compact way to clean up resources than using the combination of `beforeEach` and `afterEach`. -* -* **Note:** The `onTestFinished` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file. -* -* **Note:** The `onTestFinished` hook is not called if the test is canceled with a dynamic `ctx.skip()` call. -* -* @param {Function} fn - The callback function to be executed after a test finishes. The function can receive parameters providing details about the completed test, including its success or failure status. -* @param {number} [timeout] - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used. -* @throws {Error} Throws an error if the function is not called within a test. -* @returns {void} -* @example -* ```ts -* // Example of using onTestFinished for cleanup -* const db = await connectToDatabase(); -* onTestFinished(async () => { -* await db.disconnect(); -* }); -* ``` -*/ -declare const onTestFinished: TaskHook<OnTestFinishedHandler>; - -type ChainableFunction< - T extends string, - F extends (...args: any) => any, - C = object -> = F & { [x in T] : ChainableFunction<T, F, C> } & { - fn: (this: Record<T, any>, ...args: Parameters<F>) => ReturnType<F>; -} & C; -declare function createChainable< - T extends string, - Args extends any[], - R = any ->(keys: T[], fn: (this: Record<T, any>, ...args: Args) => R): ChainableFunction<T, (...args: Args) => R>; - -type RunMode = "run" | "skip" | "only" | "todo" | "queued"; -type TaskState = RunMode | "pass" | "fail"; -interface TaskBase { - /** - * Unique task identifier. Based on the file id and the position of the task. - * The id of the file task is based on the file path relative to root and project name. - * It will not change between runs. - * @example `1201091390`, `1201091390_0`, `1201091390_0_1` - */ - id: string; - /** - * Task name provided by the user. If no name was provided, it will be an empty string. - */ - name: string; - /** - * Full name including the file path, any parent suites, and this task's name. - * - * Uses ` > ` as the separator between levels. - * - * @example - * // file - * 'test/task-names.test.ts' - * @example - * // suite - * 'test/task-names.test.ts > meal planning' - * 'test/task-names.test.ts > meal planning > grocery lists' - * @example - * // test - * 'test/task-names.test.ts > meal planning > grocery lists > calculates ingredients' - */ - fullName: string; - /** - * Full name excluding the file path, including any parent suites and this task's name. `undefined` for file tasks. - * - * Uses ` > ` as the separator between levels. - * - * @example - * // file - * undefined - * @example - * // suite - * 'meal planning' - * 'meal planning > grocery lists' - * @example - * // test - * 'meal planning > grocery lists > calculates ingredients' - */ - fullTestName?: string; - /** - * Task mode. - * - **skip**: task is skipped - * - **only**: only this task and other tasks with `only` mode will run - * - **todo**: task is marked as a todo, alias for `skip` - * - **run**: task will run or already ran - * - **queued**: task will start running next. It can only exist on the File - */ - mode: RunMode; - /** - * Custom metadata for the task. JSON reporter will save this data. - */ - meta: TaskMeta; - /** - * Whether the task was produced with `.each()` method. - */ - each?: boolean; - /** - * Whether the task should run concurrently with other tasks. - */ - concurrent?: boolean; - /** - * Whether the tasks of the suite run in a random order. - */ - shuffle?: boolean; - /** - * Suite that this task is part of. File task or the global suite will have no parent. - */ - suite?: Suite; - /** - * Result of the task. Suite and file tasks will only have the result if there - * was an error during collection or inside `afterAll`/`beforeAll`. - */ - result?: TaskResult; - /** - * The amount of times the task should be retried if it fails. - * @default 0 - */ - retry?: number; - /** - * The amount of times the task should be repeated after the successful run. - * If the task fails, it will not be retried unless `retry` is specified. - * @default 0 - */ - repeats?: number; - /** - * Location of the task in the file. This field is populated only if - * `includeTaskLocation` option is set. It is generated by calling `new Error` - * and parsing the stack trace, so the location might differ depending on the runtime. - */ - location?: { - line: number; - column: number; - }; - /** - * If the test was collected by parsing the file AST, and the name - * is not a static string, this property will be set to `true`. - * @experimental - */ - dynamic?: boolean; -} -interface TaskPopulated extends TaskBase { - /** - * File task. It's the root task of the file. - */ - file: File; - /** - * Whether the task should succeed if it fails. If the task fails, it will be marked as passed. - */ - fails?: boolean; - /** - * Store promises (from async expects) to wait for them before finishing the test - */ - promises?: Promise<any>[]; -} -/** -* Custom metadata that can be used in reporters. -*/ -interface TaskMeta {} -/** -* The result of calling a task. -*/ -interface TaskResult { - /** - * State of the task. Inherits the `task.mode` during collection. - * When the task has finished, it will be changed to `pass` or `fail`. - * - **pass**: task ran successfully - * - **fail**: task failed - */ - state: TaskState; - /** - * Errors that occurred during the task execution. It is possible to have several errors - * if `expect.soft()` failed multiple times or `retry` was triggered. - */ - errors?: TestError[]; - /** - * How long in milliseconds the task took to run. - */ - duration?: number; - /** - * Time in milliseconds when the task started running. - */ - startTime?: number; - /** - * Heap size in bytes after the task finished. - * Only available if `logHeapUsage` option is set and `process.memoryUsage` is defined. - */ - heap?: number; - /** - * State of related to this task hooks. Useful during reporting. - */ - hooks?: Partial<Record<keyof SuiteHooks, TaskState>>; - /** - * The amount of times the task was retried. The task is retried only if it - * failed and `retry` option is set. - */ - retryCount?: number; - /** - * The amount of times the task was repeated. The task is repeated only if - * `repeats` option is set. This number also contains `retryCount`. - */ - repeatCount?: number; -} -/** The time spent importing & executing a non-externalized file. */ -interface ImportDuration { - /** The time spent importing & executing the file itself, not counting all non-externalized imports that the file does. */ - selfTime: number; - /** The time spent importing & executing the file and all its imports. */ - totalTime: number; - /** Will be set to `true`, if the module was externalized. In this case totalTime and selfTime are identical. */ - external?: boolean; - /** Which module imported this module first. All subsequent imports are cached. */ - importer?: string; -} -/** -* The tuple representing a single task update. -* Usually reported after the task finishes. -*/ -type TaskResultPack = [id: string, result: TaskResult | undefined, meta: TaskMeta]; -interface TaskEventData { - annotation?: TestAnnotation | undefined; - artifact?: TestArtifact | undefined; -} -type TaskEventPack = [id: string, event: TaskUpdateEvent, data: TaskEventData | undefined]; -type TaskUpdateEvent = "test-failed-early" | "suite-failed-early" | "test-prepare" | "test-finished" | "test-retried" | "suite-prepare" | "suite-finished" | "before-hook-start" | "before-hook-end" | "after-hook-start" | "after-hook-end" | "test-annotation" | "test-artifact"; -interface Suite extends TaskBase { - type: "suite"; - /** - * File task. It's the root task of the file. - */ - file: File; - /** - * An array of tasks that are part of the suite. - */ - tasks: Task[]; -} -interface File extends Suite { - /** - * The name of the pool that the file belongs to. - * @default 'forks' - */ - pool?: string; - /** - * The environment that processes the file on the server. - */ - viteEnvironment?: string; - /** - * The path to the file in UNIX format. - */ - filepath: string; - /** - * The name of the workspace project the file belongs to. - */ - projectName: string | undefined; - /** - * The time it took to collect all tests in the file. - * This time also includes importing all the file dependencies. - */ - collectDuration?: number; - /** - * The time it took to import the setup file. - */ - setupDuration?: number; - /** The time spent importing every non-externalized dependency that Vitest has processed. */ - importDurations?: Record<string, ImportDuration>; -} -interface Test<ExtraContext = object> extends TaskPopulated { - type: "test"; - /** - * Test context that will be passed to the test function. - */ - context: TestContext & ExtraContext; - /** - * The test timeout in milliseconds. - */ - timeout: number; - /** - * An array of custom annotations. - */ - annotations: TestAnnotation[]; - /** - * An array of artifacts produced by the test. - * - * @experimental - */ - artifacts: TestArtifact[]; - fullTestName: string; -} -type Task = Test | Suite | File; -type TestFunction<ExtraContext = object> = (context: TestContext & ExtraContext) => Awaitable<any> | void; -type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = { - 1: [T[0]]; - 2: [T[0], T[1]]; - 3: [T[0], T[1], T[2]]; - 4: [T[0], T[1], T[2], T[3]]; - 5: [T[0], T[1], T[2], T[3], T[4]]; - 6: [T[0], T[1], T[2], T[3], T[4], T[5]]; - 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]]; - 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]]; - 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]]; - 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]]; - fallback: Array<T extends ReadonlyArray<infer U> ? U : any>; -}[T extends Readonly<[any]> ? 1 : T extends Readonly<[any, any]> ? 2 : T extends Readonly<[any, any, any]> ? 3 : T extends Readonly<[any, any, any, any]> ? 4 : T extends Readonly<[any, any, any, any, any]> ? 5 : T extends Readonly<[any, any, any, any, any, any]> ? 6 : T extends Readonly<[any, any, any, any, any, any, any]> ? 7 : T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8 : T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10 : "fallback"]; -interface EachFunctionReturn<T extends any[]> { - (name: string | Function, fn: (...args: T) => Awaitable<void>, options?: number): void; - (name: string | Function, options: TestCollectorOptions, fn: (...args: T) => Awaitable<void>): void; -} -interface TestEachFunction { - <T extends any[] | [any]>(cases: ReadonlyArray<T>): EachFunctionReturn<T>; - <T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): EachFunctionReturn<ExtractEachCallbackArgs<T>>; - <T>(cases: ReadonlyArray<T>): EachFunctionReturn<T[]>; - (...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>; -} -interface TestForFunctionReturn< - Arg, - Context -> { - (name: string | Function, fn: (arg: Arg, context: Context) => Awaitable<void>): void; - (name: string | Function, options: TestCollectorOptions, fn: (args: Arg, context: Context) => Awaitable<void>): void; -} -interface TestForFunction<ExtraContext> { - <T>(cases: ReadonlyArray<T>): TestForFunctionReturn<T, TestContext & ExtraContext>; - (strings: TemplateStringsArray, ...values: any[]): TestForFunctionReturn<any, TestContext & ExtraContext>; -} -interface SuiteForFunction { - <T>(cases: ReadonlyArray<T>): EachFunctionReturn<[T]>; - (...args: [TemplateStringsArray, ...any]): EachFunctionReturn<any[]>; -} -interface TestCollectorCallable<C = object> { - <ExtraContext extends C>(name: string | Function, fn?: TestFunction<ExtraContext>, options?: number): void; - <ExtraContext extends C>(name: string | Function, options?: TestCollectorOptions, fn?: TestFunction<ExtraContext>): void; -} -type ChainableTestAPI<ExtraContext = object> = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "fails", TestCollectorCallable<ExtraContext>, { - each: TestEachFunction; - for: TestForFunction<ExtraContext>; -}>; -type TestCollectorOptions = Omit<TestOptions, "shuffle">; -interface TestOptions { - /** - * Test timeout. - */ - timeout?: number; - /** - * Times to retry the test if fails. Useful for making flaky tests more stable. - * When retries is up, the last test error will be thrown. - * - * @default 0 - */ - retry?: number; - /** - * How many times the test will run again. - * Only inner tests will repeat if set on `describe()`, nested `describe()` will inherit parent's repeat by default. - * - * @default 0 - */ - repeats?: number; - /** - * Whether suites and tests run concurrently. - * Tests inherit `concurrent` from `describe()` and nested `describe()` will inherit from parent's `concurrent`. - */ - concurrent?: boolean; - /** - * Whether tests run sequentially. - * Tests inherit `sequential` from `describe()` and nested `describe()` will inherit from parent's `sequential`. - */ - sequential?: boolean; - /** - * Whether the tasks of the suite run in a random order. - */ - shuffle?: boolean; - /** - * Whether the test should be skipped. - */ - skip?: boolean; - /** - * Should this test be the only one running in a suite. - */ - only?: boolean; - /** - * Whether the test should be skipped and marked as a todo. - */ - todo?: boolean; - /** - * Whether the test is expected to fail. If it does, the test will pass, otherwise it will fail. - */ - fails?: boolean; -} -interface ExtendedAPI<ExtraContext> { - skipIf: (condition: any) => ChainableTestAPI<ExtraContext>; - runIf: (condition: any) => ChainableTestAPI<ExtraContext>; -} -interface Hooks<ExtraContext> { - beforeAll: typeof beforeAll; - afterAll: typeof afterAll; - beforeEach: typeof beforeEach<ExtraContext>; - afterEach: typeof afterEach<ExtraContext>; -} -type TestAPI<ExtraContext = object> = ChainableTestAPI<ExtraContext> & ExtendedAPI<ExtraContext> & Hooks<ExtraContext> & { - extend: <T extends Record<string, any> = object>(fixtures: Fixtures<T, ExtraContext>) => TestAPI<{ [K in keyof T | keyof ExtraContext] : K extends keyof T ? T[K] : K extends keyof ExtraContext ? ExtraContext[K] : never }>; - scoped: (fixtures: Partial<Fixtures<ExtraContext>>) => void; -}; -interface FixtureOptions { - /** - * Whether to automatically set up current fixture, even though it's not being used in tests. - * @default false - */ - auto?: boolean; - /** - * Indicated if the injected value from the config should be preferred over the fixture value - */ - injected?: boolean; - /** - * When should the fixture be set up. - * - **test**: fixture will be set up before every test - * - **worker**: fixture will be set up once per worker - * - **file**: fixture will be set up once per file - * - * **Warning:** The `vmThreads` and `vmForks` pools initiate worker fixtures once per test file. - * @default 'test' - */ - scope?: "test" | "worker" | "file"; -} -type Use<T> = (value: T) => Promise<void>; -type FixtureFn< - T, - K extends keyof T, - ExtraContext -> = (context: Omit<T, K> & ExtraContext, use: Use<T[K]>) => Promise<void>; -type Fixture< - T, - K extends keyof T, - ExtraContext = object -> = ((...args: any) => any) extends T[K] ? T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never : T[K] | (T[K] extends any ? FixtureFn<T, K, Omit<ExtraContext, Exclude<keyof T, K>>> : never); -type Fixtures< - T, - ExtraContext = object -> = { [K in keyof T] : Fixture<T, K, ExtraContext & TestContext> | [Fixture<T, K, ExtraContext & TestContext>, FixtureOptions?] }; -type InferFixturesTypes<T> = T extends TestAPI<infer C> ? C : T; -interface SuiteCollectorCallable<ExtraContext = object> { - <OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, fn?: SuiteFactory<OverrideExtraContext>, options?: number): SuiteCollector<OverrideExtraContext>; - <OverrideExtraContext extends ExtraContext = ExtraContext>(name: string | Function, options: TestOptions, fn?: SuiteFactory<OverrideExtraContext>): SuiteCollector<OverrideExtraContext>; -} -type ChainableSuiteAPI<ExtraContext = object> = ChainableFunction<"concurrent" | "sequential" | "only" | "skip" | "todo" | "shuffle", SuiteCollectorCallable<ExtraContext>, { - each: TestEachFunction; - for: SuiteForFunction; -}>; -type SuiteAPI<ExtraContext = object> = ChainableSuiteAPI<ExtraContext> & { - skipIf: (condition: any) => ChainableSuiteAPI<ExtraContext>; - runIf: (condition: any) => ChainableSuiteAPI<ExtraContext>; -}; -interface BeforeAllListener { - (suite: Readonly<Suite | File>): Awaitable<unknown>; -} -interface AfterAllListener { - (suite: Readonly<Suite | File>): Awaitable<unknown>; -} -interface BeforeEachListener<ExtraContext = object> { - (context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>; -} -interface AfterEachListener<ExtraContext = object> { - (context: TestContext & ExtraContext, suite: Readonly<Suite>): Awaitable<unknown>; -} -interface SuiteHooks<ExtraContext = object> { - beforeAll: BeforeAllListener[]; - afterAll: AfterAllListener[]; - beforeEach: BeforeEachListener<ExtraContext>[]; - afterEach: AfterEachListener<ExtraContext>[]; -} -interface TaskCustomOptions extends TestOptions { - /** - * Whether the task was produced with `.each()` method. - */ - each?: boolean; - /** - * Custom metadata for the task that will be assigned to `task.meta`. - */ - meta?: Record<string, unknown>; - /** - * Task fixtures. - */ - fixtures?: FixtureItem[]; - /** - * Function that will be called when the task is executed. - * If nothing is provided, the runner will try to get the function using `getFn(task)`. - * If the runner cannot find the function, the task will be marked as failed. - */ - handler?: (context: TestContext) => Awaitable<void>; -} -interface SuiteCollector<ExtraContext = object> { - readonly name: string; - readonly mode: RunMode; - options?: TestOptions; - type: "collector"; - test: TestAPI<ExtraContext>; - tasks: (Suite | Test<ExtraContext> | SuiteCollector<ExtraContext>)[]; - scoped: (fixtures: Fixtures<any, ExtraContext>) => void; - fixtures: () => FixtureItem[] | undefined; - file?: File; - suite?: Suite; - task: (name: string, options?: TaskCustomOptions) => Test<ExtraContext>; - collect: (file: File) => Promise<Suite>; - clear: () => void; - on: <T extends keyof SuiteHooks<ExtraContext>>(name: T, ...fn: SuiteHooks<ExtraContext>[T]) => void; -} -type SuiteFactory<ExtraContext = object> = (test: TestAPI<ExtraContext>) => Awaitable<void>; -interface RuntimeContext { - tasks: (SuiteCollector | Test)[]; - currentSuite: SuiteCollector | null; -} -/** -* User's custom test context. -*/ -interface TestContext { - /** - * Metadata of the current test - */ - readonly task: Readonly<Test>; - /** - * An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that will be aborted if the test times out or - * the test run was cancelled. - * @see {@link https://vitest.dev/guide/test-context#signal} - */ - readonly signal: AbortSignal; - /** - * Register a callback to run when this specific test fails. - * Useful when tests run concurrently. - * @see {@link https://vitest.dev/guide/test-context#ontestfailed} - */ - readonly onTestFailed: (fn: OnTestFailedHandler, timeout?: number) => void; - /** - * Register a callback to run when this specific test finishes. - * Useful when tests run concurrently. - * @see {@link https://vitest.dev/guide/test-context#ontestfinished} - */ - readonly onTestFinished: (fn: OnTestFinishedHandler, timeout?: number) => void; - /** - * Mark tests as skipped. All execution after this call will be skipped. - * This function throws an error, so make sure you are not catching it accidentally. - * @see {@link https://vitest.dev/guide/test-context#skip} - */ - readonly skip: { - (note?: string): never; - (condition: boolean, note?: string): void; - }; - /** - * Add a test annotation that will be displayed by your reporter. - * @see {@link https://vitest.dev/guide/test-context#annotate} - */ - readonly annotate: { - (message: string, type?: string, attachment?: TestAttachment): Promise<TestAnnotation>; - (message: string, attachment?: TestAttachment): Promise<TestAnnotation>; - }; -} -type OnTestFailedHandler = (context: TestContext) => Awaitable<void>; -type OnTestFinishedHandler = (context: TestContext) => Awaitable<void>; -interface TaskHook<HookListener> { - (fn: HookListener, timeout?: number): void; -} -type SequenceHooks = "stack" | "list" | "parallel"; -type SequenceSetupFiles = "list" | "parallel"; -/** -* Represents a file or data attachment associated with a test artifact. -* -* Attachments can be either file-based (via `path`) or inline content (via `body`). -* The `contentType` helps consumers understand how to interpret the attachment data. -*/ -interface TestAttachment { - /** MIME type of the attachment (e.g., 'image/png', 'text/plain') */ - contentType?: string; - /** File system path to the attachment */ - path?: string; - /** Inline attachment content as a string or raw binary data */ - body?: string | Uint8Array; -} -/** -* Source code location information for a test artifact. -* -* Indicates where in the source code the artifact originated from. -*/ -interface TestArtifactLocation { - /** Line number in the source file (1-indexed) */ - line: number; - /** Column number in the line (1-indexed) */ - column: number; - /** Path to the source file */ - file: string; -} -/** -* @experimental -* -* Base interface for all test artifacts. -* -* Extend this interface when creating custom test artifacts. Vitest automatically manages the `attachments` array and injects the `location` property to indicate where the artifact was created in your test code. -*/ -interface TestArtifactBase { - /** File or data attachments associated with this artifact */ - attachments?: TestAttachment[]; - /** Source location where this artifact was created */ - location?: TestArtifactLocation; -} -/** -* @deprecated Use {@linkcode TestArtifactLocation} instead. -* -* Kept for backwards compatibility. -*/ -type TestAnnotationLocation = TestArtifactLocation; -interface TestAnnotation { - message: string; - type: string; - location?: TestArtifactLocation; - attachment?: TestAttachment; -} -/** -* @experimental -* -* Artifact type for test annotations. -*/ -interface TestAnnotationArtifact extends TestArtifactBase { - type: "internal:annotation"; - annotation: TestAnnotation; -} -interface VisualRegressionArtifactAttachment extends TestAttachment { - name: "reference" | "actual" | "diff"; - width: number; - height: number; -} -/** -* @experimental -* -* Artifact type for visual regressions. -*/ -interface VisualRegressionArtifact extends TestArtifactBase { - type: "internal:toMatchScreenshot"; - kind: "visual-regression"; - message: string; - attachments: VisualRegressionArtifactAttachment[]; -} -/** -* @experimental -* @advanced -* -* Registry for custom test artifact types. -* -* Augment this interface to register custom artifact types that your tests can produce. -* -* Each custom artifact should extend {@linkcode TestArtifactBase} and include a unique `type` discriminator property. -* -* @remarks -* - Use a `Symbol` as the **registry key** to guarantee uniqueness -* - The `type` property should follow the pattern `'package-name:artifact-name'`, `'internal:'` is a reserved prefix -* - Use `attachments` to include files or data; extend {@linkcode TestAttachment} for custom metadata -* - `location` property is automatically injected to indicate where the artifact was created -* -* @example -* ```ts -* // Define custom attachment type for generated PDF -* interface PDFAttachment extends TestAttachment { -* contentType: 'application/pdf' -* body: Uint8Array -* pageCount: number -* fileSize: number -* } -* -* interface PDFGenerationArtifact extends TestArtifactBase { -* type: 'my-plugin:pdf-generation' -* templateName: string -* isValid: boolean -* attachments: [PDFAttachment] -* } -* -* // Use a symbol to guarantee key uniqueness -* const pdfKey = Symbol('pdf-generation') -* -* declare module 'vitest' { -* interface TestArtifactRegistry { -* [pdfKey]: PDFGenerationArtifact -* } -* } -* -* // Custom assertion for PDF generation -* async function toGenerateValidPDF( -* this: MatcherState, -* actual: PDFTemplate, -* data: Record<string, unknown> -* ): AsyncExpectationResult { -* const pdfBuffer = await actual.render(data) -* const validation = await validatePDF(pdfBuffer) -* -* await recordArtifact(this.task, { -* type: 'my-plugin:pdf-generation', -* templateName: actual.name, -* isValid: validation.success, -* attachments: [{ -* contentType: 'application/pdf', -* body: pdfBuffer, -* pageCount: validation.pageCount, -* fileSize: pdfBuffer.byteLength -* }] -* }) -* -* return { -* pass: validation.success, -* message: () => validation.success -* ? `Generated valid PDF with ${validation.pageCount} pages` -* : `Invalid PDF: ${validation.error}` -* } -* } -* ``` -*/ -interface TestArtifactRegistry {} -/** -* @experimental -* -* Union type of all test artifacts, including built-in and custom registered artifacts. -* -* This type automatically includes all artifacts registered via {@link TestArtifactRegistry}. -*/ -type TestArtifact = TestAnnotationArtifact | VisualRegressionArtifact | TestArtifactRegistry[keyof TestArtifactRegistry]; - -export { createChainable as c, afterAll as i, afterEach as j, beforeAll as k, beforeEach as l, onTestFinished as m, onTestFailed as o }; -export type { TestOptions as $, AfterAllListener as A, BeforeAllListener as B, ChainableFunction as C, TaskBase as D, TaskCustomOptions as E, File as F, TaskEventPack as G, TaskHook as H, ImportDuration as I, TaskMeta as J, TaskPopulated as K, TaskResult as L, TaskResultPack as M, TaskState as N, OnTestFailedHandler as O, TestAnnotation as P, TestAnnotationArtifact as Q, RunMode as R, Suite as S, Task as T, TestAnnotationLocation as U, TestArtifactBase as V, TestArtifactLocation as W, TestArtifactRegistry as X, TestAttachment as Y, TestContext as Z, TestFunction as _, Test as a, Use as a0, VisualRegressionArtifact as a1, TestArtifact as b, SuiteHooks as d, TaskUpdateEvent as e, TestAPI as f, SuiteAPI as g, SuiteCollector as h, AfterEachListener as n, BeforeEachListener as p, Fixture as q, FixtureFn as r, FixtureOptions as s, Fixtures as t, InferFixturesTypes as u, OnTestFinishedHandler as v, RuntimeContext as w, SequenceHooks as x, SequenceSetupFiles as y, SuiteFactory as z }; diff --git a/vanilla/node_modules/@vitest/runner/dist/types.d.ts b/vanilla/node_modules/@vitest/runner/dist/types.d.ts deleted file mode 100644 index aefc0b8..0000000 --- a/vanilla/node_modules/@vitest/runner/dist/types.d.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { DiffOptions } from '@vitest/utils/diff'; -import { F as File, a as Test, S as Suite, M as TaskResultPack, G as TaskEventPack, P as TestAnnotation, b as TestArtifact, Z as TestContext, I as ImportDuration, x as SequenceHooks, y as SequenceSetupFiles } from './tasks.d-C7UxawJ9.js'; -export { A as AfterAllListener, n as AfterEachListener, B as BeforeAllListener, p as BeforeEachListener, q as Fixture, r as FixtureFn, s as FixtureOptions, t as Fixtures, u as InferFixturesTypes, O as OnTestFailedHandler, v as OnTestFinishedHandler, R as RunMode, w as RuntimeContext, g as SuiteAPI, h as SuiteCollector, z as SuiteFactory, d as SuiteHooks, T as Task, D as TaskBase, E as TaskCustomOptions, H as TaskHook, J as TaskMeta, K as TaskPopulated, L as TaskResult, N as TaskState, e as TaskUpdateEvent, f as TestAPI, Q as TestAnnotationArtifact, U as TestAnnotationLocation, V as TestArtifactBase, W as TestArtifactLocation, X as TestArtifactRegistry, Y as TestAttachment, _ as TestFunction, $ as TestOptions, a0 as Use, a1 as VisualRegressionArtifact } from './tasks.d-C7UxawJ9.js'; -import '@vitest/utils'; - -/** -* This is a subset of Vitest config that's required for the runner to work. -*/ -interface VitestRunnerConfig { - root: string; - setupFiles: string[]; - name?: string; - passWithNoTests: boolean; - testNamePattern?: RegExp; - allowOnly?: boolean; - sequence: { - shuffle?: boolean; - concurrent?: boolean; - seed: number; - hooks: SequenceHooks; - setupFiles: SequenceSetupFiles; - }; - chaiConfig?: { - truncateThreshold?: number; - }; - maxConcurrency: number; - testTimeout: number; - hookTimeout: number; - retry: number; - includeTaskLocation?: boolean; - diffOptions?: DiffOptions; -} -/** -* Possible options to run a single file in a test. -*/ -interface FileSpecification { - filepath: string; - testLocations: number[] | undefined; -} -type VitestRunnerImportSource = "collect" | "setup"; -interface VitestRunnerConstructor { - new (config: VitestRunnerConfig): VitestRunner; -} -type CancelReason = "keyboard-input" | "test-failure" | (string & Record<string, never>); -interface VitestRunner { - /** - * First thing that's getting called before actually collecting and running tests. - */ - onBeforeCollect?: (paths: string[]) => unknown; - /** - * Called after the file task was created but not collected yet. - */ - onCollectStart?: (file: File) => unknown; - /** - * Called after collecting tests and before "onBeforeRun". - */ - onCollected?: (files: File[]) => unknown; - /** - * Called when test runner should cancel next test runs. - * Runner should listen for this method and mark tests and suites as skipped in - * "onBeforeRunSuite" and "onBeforeRunTask" when called. - */ - cancel?: (reason: CancelReason) => unknown; - /** - * Called before running a single test. Doesn't have "result" yet. - */ - onBeforeRunTask?: (test: Test) => unknown; - /** - * Called before actually running the test function. Already has "result" with "state" and "startTime". - */ - onBeforeTryTask?: (test: Test, options: { - retry: number; - repeats: number; - }) => unknown; - /** - * When the task has finished running, but before cleanup hooks are called - */ - onTaskFinished?: (test: Test) => unknown; - /** - * Called after result and state are set. - */ - onAfterRunTask?: (test: Test) => unknown; - /** - * Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws. - */ - onAfterTryTask?: (test: Test, options: { - retry: number; - repeats: number; - }) => unknown; - /** - * Called after the retry resolution happend. Unlike `onAfterTryTask`, the test now has a new state. - * All `after` hooks were also called by this point. - */ - onAfterRetryTask?: (test: Test, options: { - retry: number; - repeats: number; - }) => unknown; - /** - * Called before running a single suite. Doesn't have "result" yet. - */ - onBeforeRunSuite?: (suite: Suite) => unknown; - /** - * Called after running a single suite. Has state and result. - */ - onAfterRunSuite?: (suite: Suite) => unknown; - /** - * If defined, will be called instead of usual Vitest suite partition and handling. - * "before" and "after" hooks will not be ignored. - */ - runSuite?: (suite: Suite) => Promise<void>; - /** - * If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function. - * "before" and "after" hooks will not be ignored. - */ - runTask?: (test: Test) => Promise<void>; - /** - * Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests. - */ - onTaskUpdate?: (task: TaskResultPack[], events: TaskEventPack[]) => Promise<void>; - /** - * Called when annotation is added via the `context.annotate` method. - */ - onTestAnnotate?: (test: Test, annotation: TestAnnotation) => Promise<TestAnnotation>; - /** - * @experimental - * - * Called when artifacts are recorded on tests via the `recordArtifact` utility. - */ - onTestArtifactRecord?: <Artifact extends TestArtifact>(test: Test, artifact: Artifact) => Promise<Artifact>; - /** - * Called before running all tests in collected paths. - */ - onBeforeRunFiles?: (files: File[]) => unknown; - /** - * Called right after running all tests in collected paths. - */ - onAfterRunFiles?: (files: File[]) => unknown; - /** - * Called when new context for a test is defined. Useful if you want to add custom properties to the context. - * If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead. - * - * @see https://vitest.dev/advanced/runner#your-task-function - */ - extendTaskContext?: (context: TestContext) => TestContext; - /** - * Called when test and setup files are imported. Can be called in two situations: when collecting tests and when importing setup files. - */ - importFile: (filepath: string, source: VitestRunnerImportSource) => unknown; - /** - * Function that is called when the runner attempts to get the value when `test.extend` is used with `{ injected: true }` - */ - injectValue?: (key: string) => unknown; - /** - * Gets the time spent importing each individual non-externalized file that Vitest collected. - */ - getImportDurations?: () => Record<string, ImportDuration>; - /** - * Publicly available configuration. - */ - config: VitestRunnerConfig; - /** - * The name of the current pool. Can affect how stack trace is inferred on the server side. - */ - pool?: string; - /** - * The current Vite environment that processes the files on the server. - */ - viteEnvironment?: string; - /** - * Return the worker context for fixtures specified with `scope: 'worker'` - */ - getWorkerContext?: () => Record<string, unknown>; - onCleanupWorkerContext?: (cleanup: () => unknown) => void; - trace?<T>(name: string, cb: () => T): T; - trace?<T>(name: string, attributes: Record<string, any>, cb: () => T): T; - /** @private */ - _currentTaskStartTime?: number; - /** @private */ - _currentTaskTimeout?: number; -} - -export { File, ImportDuration, SequenceHooks, SequenceSetupFiles, Suite, TaskEventPack, TaskResultPack, Test, TestAnnotation, TestArtifact, TestContext }; -export type { CancelReason, FileSpecification, VitestRunner, VitestRunnerConfig, VitestRunnerConstructor, VitestRunnerImportSource }; diff --git a/vanilla/node_modules/@vitest/runner/dist/types.js b/vanilla/node_modules/@vitest/runner/dist/types.js deleted file mode 100644 index 8b13789..0000000 --- a/vanilla/node_modules/@vitest/runner/dist/types.js +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vanilla/node_modules/@vitest/runner/dist/utils.d.ts b/vanilla/node_modules/@vitest/runner/dist/utils.d.ts deleted file mode 100644 index 8d3757d..0000000 --- a/vanilla/node_modules/@vitest/runner/dist/utils.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { S as Suite, F as File, T as Task, a as Test } from './tasks.d-C7UxawJ9.js'; -export { C as ChainableFunction, c as createChainable } from './tasks.d-C7UxawJ9.js'; -import { ParsedStack, Arrayable } from '@vitest/utils'; - -/** -* If any tasks been marked as `only`, mark all other tasks as `skip`. -*/ -declare function interpretTaskModes(file: Suite, namePattern?: string | RegExp, testLocations?: number[] | undefined, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean): void; -declare function someTasksAreOnly(suite: Suite): boolean; -declare function generateHash(str: string): string; -declare function calculateSuiteHash(parent: Suite): void; -declare function createFileTask(filepath: string, root: string, projectName: string | undefined, pool?: string, viteEnvironment?: string): File; -/** -* Generate a unique ID for a file based on its path and project name -* @param file File relative to the root of the project to keep ID the same between different machines -* @param projectName The name of the test project -*/ -declare function generateFileHash(file: string, projectName: string | undefined): string; -declare function findTestFileStackTrace(testFilePath: string, error: string): ParsedStack | undefined; - -/** -* Return a function for running multiple async operations with limited concurrency. -*/ -declare function limitConcurrency(concurrency?: number): < - Args extends unknown[], - T ->(func: (...args: Args) => PromiseLike<T> | T, ...args: Args) => Promise<T>; - -/** -* Partition in tasks groups by consecutive concurrent -*/ -declare function partitionSuiteChildren(suite: Suite): Task[][]; - -declare function isTestCase(s: Task): s is Test; -declare function getTests(suite: Arrayable<Task>): Test[]; -declare function getTasks(tasks?: Arrayable<Task>): Task[]; -declare function getSuites(suite: Arrayable<Task>): Suite[]; -declare function hasTests(suite: Arrayable<Suite>): boolean; -declare function hasFailed(suite: Arrayable<Task>): boolean; -declare function getNames(task: Task): string[]; -declare function getFullName(task: Task, separator?: string): string; -declare function getTestName(task: Task, separator?: string): string; -declare function createTaskName(names: readonly (string | undefined)[], separator?: string): string; - -export { calculateSuiteHash, createFileTask, createTaskName, findTestFileStackTrace, generateFileHash, generateHash, getFullName, getNames, getSuites, getTasks, getTestName, getTests, hasFailed, hasTests, interpretTaskModes, isTestCase, limitConcurrency, partitionSuiteChildren, someTasksAreOnly }; diff --git a/vanilla/node_modules/@vitest/runner/dist/utils.js b/vanilla/node_modules/@vitest/runner/dist/utils.js deleted file mode 100644 index 24362a4..0000000 --- a/vanilla/node_modules/@vitest/runner/dist/utils.js +++ /dev/null @@ -1,5 +0,0 @@ -export { a as calculateSuiteHash, c as createChainable, b as createFileTask, e as createTaskName, f as findTestFileStackTrace, g as generateFileHash, d as generateHash, h as getFullName, j as getNames, k as getSuites, m as getTasks, n as getTestName, o as getTests, q as hasFailed, r as hasTests, i as interpretTaskModes, t as isTestCase, l as limitConcurrency, p as partitionSuiteChildren, s as someTasksAreOnly } from './chunk-tasks.js'; -import '@vitest/utils/error'; -import '@vitest/utils/source-map'; -import 'pathe'; -import '@vitest/utils/helpers'; diff --git a/vanilla/node_modules/@vitest/runner/package.json b/vanilla/node_modules/@vitest/runner/package.json deleted file mode 100644 index 0cc2165..0000000 --- a/vanilla/node_modules/@vitest/runner/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "@vitest/runner", - "type": "module", - "version": "4.0.18", - "description": "Vitest test runner", - "license": "MIT", - "funding": "https://opencollective.com/vitest", - "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/runner#readme", - "repository": { - "type": "git", - "url": "git+https://github.com/vitest-dev/vitest.git", - "directory": "packages/runner" - }, - "bugs": { - "url": "https://github.com/vitest-dev/vitest/issues" - }, - "sideEffects": true, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./utils": { - "types": "./dist/utils.d.ts", - "default": "./dist/utils.js" - }, - "./types": { - "types": "./dist/types.d.ts", - "default": "./dist/types.js" - }, - "./*": "./*" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "*.d.ts", - "dist" - ], - "dependencies": { - "pathe": "^2.0.3", - "@vitest/utils": "4.0.18" - }, - "scripts": { - "build": "premove dist && rollup -c", - "dev": "rollup -c --watch" - } -}
\ No newline at end of file diff --git a/vanilla/node_modules/@vitest/runner/types.d.ts b/vanilla/node_modules/@vitest/runner/types.d.ts deleted file mode 100644 index 26a1254..0000000 --- a/vanilla/node_modules/@vitest/runner/types.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './dist/types.js' diff --git a/vanilla/node_modules/@vitest/runner/utils.d.ts b/vanilla/node_modules/@vitest/runner/utils.d.ts deleted file mode 100644 index e3f344e..0000000 --- a/vanilla/node_modules/@vitest/runner/utils.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './dist/utils.js' diff --git a/vanilla/node_modules/@vitest/snapshot/LICENSE b/vanilla/node_modules/@vitest/snapshot/LICENSE deleted file mode 100644 index 0e5771d..0000000 --- a/vanilla/node_modules/@vitest/snapshot/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vanilla/node_modules/@vitest/snapshot/README.md b/vanilla/node_modules/@vitest/snapshot/README.md deleted file mode 100644 index edf0817..0000000 --- a/vanilla/node_modules/@vitest/snapshot/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# @vitest/snapshot - -Lightweight implementation of Jest's snapshots. - -## Usage - -```js -import { SnapshotClient } from '@vitest/snapshot' -import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment' -import { SnapshotManager } from '@vitest/snapshot/manager' - -const client = new SnapshotClient({ - // you need to provide your own equality check implementation if you use it - // this function is called when `.toMatchSnapshot({ property: 1 })` is called - isEqual: (received, expected) => - equals(received, expected, [iterableEquality, subsetEquality]), -}) - -// class that implements snapshot saving and reading -// by default uses fs module, but you can provide your own implementation depending on the environment -const environment = new NodeSnapshotEnvironment() - -// you need to implement this yourselves, -// this depends on your runner -function getCurrentFilepath() { - return '/file.spec.js' -} -function getCurrentTestName() { - return 'test1' -} - -// example for inline snapshots, nothing is required to support regular snapshots, -// just call `assert` with `isInline: false` -function wrapper(received) { - function __INLINE_SNAPSHOT__(inlineSnapshot, message) { - client.assert({ - received, - message, - isInline: true, - inlineSnapshot, - filepath: getCurrentFilepath(), - name: getCurrentTestName(), - }) - } - return { - // the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2) - // you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor - toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args), - } -} - -const options = { - updateSnapshot: 'new', - snapshotEnvironment: environment, -} - -await client.startCurrentRun( - getCurrentFilepath(), - getCurrentTestName(), - options -) - -// this will save snapshot to a file which is returned by "snapshotEnvironment.resolvePath" -client.assert({ - received: 'some text', - isInline: false, -}) - -// uses "pretty-format", so it requires quotes -// also naming is hard-coded when parsing test files -wrapper('text 1').toMatchInlineSnapshot() -wrapper('text 2').toMatchInlineSnapshot('"text 2"') - -const result = await client.finishCurrentRun() // this saves files and returns SnapshotResult - -// you can use manager to manage several clients -const manager = new SnapshotManager(options) -manager.add(result) - -// do something -// and then read the summary - -console.log(manager.summary) -``` diff --git a/vanilla/node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts deleted file mode 100644 index 435ae4f..0000000 --- a/vanilla/node_modules/@vitest/snapshot/dist/environment.d-DHdQ1Csl.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -interface ParsedStack { - method: string; - file: string; - line: number; - column: number; -} - -interface SnapshotEnvironment { - getVersion: () => string; - getHeader: () => string; - resolvePath: (filepath: string) => Promise<string>; - resolveRawPath: (testPath: string, rawPath: string) => Promise<string>; - saveSnapshotFile: (filepath: string, snapshot: string) => Promise<void>; - readSnapshotFile: (filepath: string) => Promise<string | null>; - removeSnapshotFile: (filepath: string) => Promise<void>; - processStackTrace?: (stack: ParsedStack) => ParsedStack; -} -interface SnapshotEnvironmentOptions { - snapshotsDirName?: string; -} - -export type { ParsedStack as P, SnapshotEnvironment as S, SnapshotEnvironmentOptions as a }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/environment.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/environment.d.ts deleted file mode 100644 index efa86bc..0000000 --- a/vanilla/node_modules/@vitest/snapshot/dist/environment.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { S as SnapshotEnvironment, a as SnapshotEnvironmentOptions } from './environment.d-DHdQ1Csl.js'; - -declare class NodeSnapshotEnvironment implements SnapshotEnvironment { - private options; - constructor(options?: SnapshotEnvironmentOptions); - getVersion(): string; - getHeader(): string; - resolveRawPath(testPath: string, rawPath: string): Promise<string>; - resolvePath(filepath: string): Promise<string>; - prepareDirectory(dirPath: string): Promise<void>; - saveSnapshotFile(filepath: string, snapshot: string): Promise<void>; - readSnapshotFile(filepath: string): Promise<string | null>; - removeSnapshotFile(filepath: string): Promise<void>; -} - -export { NodeSnapshotEnvironment, SnapshotEnvironment }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/environment.js b/vanilla/node_modules/@vitest/snapshot/dist/environment.js deleted file mode 100644 index 079b478..0000000 --- a/vanilla/node_modules/@vitest/snapshot/dist/environment.js +++ /dev/null @@ -1,40 +0,0 @@ -import { promises, existsSync } from 'node:fs'; -import { resolve, isAbsolute, dirname, join, basename } from 'pathe'; - -class NodeSnapshotEnvironment { - constructor(options = {}) { - this.options = options; - } - getVersion() { - return "1"; - } - getHeader() { - return `// Snapshot v${this.getVersion()}`; - } - async resolveRawPath(testPath, rawPath) { - return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath); - } - async resolvePath(filepath) { - return join(join(dirname(filepath), this.options.snapshotsDirName ?? "__snapshots__"), `${basename(filepath)}.snap`); - } - async prepareDirectory(dirPath) { - await promises.mkdir(dirPath, { recursive: true }); - } - async saveSnapshotFile(filepath, snapshot) { - await promises.mkdir(dirname(filepath), { recursive: true }); - await promises.writeFile(filepath, snapshot, "utf-8"); - } - async readSnapshotFile(filepath) { - if (!existsSync(filepath)) { - return null; - } - return promises.readFile(filepath, "utf-8"); - } - async removeSnapshotFile(filepath) { - if (existsSync(filepath)) { - await promises.unlink(filepath); - } - } -} - -export { NodeSnapshotEnvironment }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/index.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/index.d.ts deleted file mode 100644 index 260d8ed..0000000 --- a/vanilla/node_modules/@vitest/snapshot/dist/index.d.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './rawSnapshot.d-lFsMJFUd.js'; -export { c as SnapshotData, d as SnapshotSerializer, e as SnapshotSummary, f as SnapshotUpdateState, U as UncheckedSnapshot } from './rawSnapshot.d-lFsMJFUd.js'; -import { S as SnapshotEnvironment, P as ParsedStack } from './environment.d-DHdQ1Csl.js'; -import { Plugin, Plugins } from '@vitest/pretty-format'; - -/** -* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -declare class DefaultMap< - K, - V -> extends Map<K, V> { - private defaultFn; - constructor(defaultFn: (key: K) => V, entries?: Iterable<readonly [K, V]>); - get(key: K): V; -} -declare class CounterMap<K> extends DefaultMap<K, number> { - constructor(); - _total: number | undefined; - valueOf(): number; - increment(key: K): void; - total(): number; -} - -interface SnapshotReturnOptions { - actual: string; - count: number; - expected?: string; - key: string; - pass: boolean; -} -interface SaveStatus { - deleted: boolean; - saved: boolean; -} -declare class SnapshotState { - testFilePath: string; - snapshotPath: string; - private _counters; - private _dirty; - private _updateSnapshot; - private _snapshotData; - private _initialData; - private _inlineSnapshots; - private _inlineSnapshotStacks; - private _testIdToKeys; - private _rawSnapshots; - private _uncheckedKeys; - private _snapshotFormat; - private _environment; - private _fileExists; - expand: boolean; - private _added; - private _matched; - private _unmatched; - private _updated; - get added(): CounterMap<string>; - set added(value: number); - get matched(): CounterMap<string>; - set matched(value: number); - get unmatched(): CounterMap<string>; - set unmatched(value: number); - get updated(): CounterMap<string>; - set updated(value: number); - private constructor(); - static create(testFilePath: string, options: SnapshotStateOptions): Promise<SnapshotState>; - get environment(): SnapshotEnvironment; - markSnapshotsAsCheckedForTest(testName: string): void; - clearTest(testId: string): void; - protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null; - private _addSnapshot; - save(): Promise<SaveStatus>; - getUncheckedCount(): number; - getUncheckedKeys(): Array<string>; - removeUncheckedKeys(): void; - match({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot }: SnapshotMatchOptions): SnapshotReturnOptions; - pack(): Promise<SnapshotResult>; -} - -interface AssertOptions { - received: unknown; - filepath: string; - name: string; - /** - * Not required but needed for `SnapshotClient.clearTest` to implement test-retry behavior. - * @default name - */ - testId?: string; - message?: string; - isInline?: boolean; - properties?: object; - inlineSnapshot?: string; - error?: Error; - errorMessage?: string; - rawSnapshot?: RawSnapshotInfo; -} -interface SnapshotClientOptions { - isEqual?: (received: unknown, expected: unknown) => boolean; -} -declare class SnapshotClient { - private options; - snapshotStateMap: Map<string, SnapshotState>; - constructor(options?: SnapshotClientOptions); - setup(filepath: string, options: SnapshotStateOptions): Promise<void>; - finish(filepath: string): Promise<SnapshotResult>; - skipTest(filepath: string, testName: string): void; - clearTest(filepath: string, testId: string): void; - getSnapshotState(filepath: string): SnapshotState; - assert(options: AssertOptions): void; - assertRaw(options: AssertOptions): Promise<void>; - clear(): void; -} - -declare function stripSnapshotIndentation(inlineSnapshot: string): string; - -/** -* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -declare function addSerializer(plugin: Plugin): void; -declare function getSerializers(): Plugins; - -export { SnapshotClient, SnapshotEnvironment, SnapshotMatchOptions, SnapshotResult, SnapshotState, SnapshotStateOptions, addSerializer, getSerializers, stripSnapshotIndentation }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/index.js b/vanilla/node_modules/@vitest/snapshot/dist/index.js deleted file mode 100644 index 40d564e..0000000 --- a/vanilla/node_modules/@vitest/snapshot/dist/index.js +++ /dev/null @@ -1,1437 +0,0 @@ -import { resolve } from 'pathe'; -import { plugins, format } from '@vitest/pretty-format'; - -// src/vlq.ts -var comma = ",".charCodeAt(0); -var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var intToChar = new Uint8Array(64); -var charToInt = new Uint8Array(128); -for (let i = 0; i < chars.length; i++) { - const c = chars.charCodeAt(i); - intToChar[i] = c; - charToInt[c] = i; -} -function decodeInteger(reader, relative) { - let value = 0; - let shift = 0; - let integer = 0; - do { - const c = reader.next(); - integer = charToInt[c]; - value |= (integer & 31) << shift; - shift += 5; - } while (integer & 32); - const shouldNegate = value & 1; - value >>>= 1; - if (shouldNegate) { - value = -2147483648 | -value; - } - return relative + value; -} -function hasMoreVlq(reader, max) { - if (reader.pos >= max) return false; - return reader.peek() !== comma; -} -var StringReader = class { - constructor(buffer) { - this.pos = 0; - this.buffer = buffer; - } - next() { - return this.buffer.charCodeAt(this.pos++); - } - peek() { - return this.buffer.charCodeAt(this.pos); - } - indexOf(char) { - const { buffer, pos } = this; - const idx = buffer.indexOf(char, pos); - return idx === -1 ? buffer.length : idx; - } -}; - -// src/sourcemap-codec.ts -function decode(mappings) { - const { length } = mappings; - const reader = new StringReader(mappings); - const decoded = []; - let genColumn = 0; - let sourcesIndex = 0; - let sourceLine = 0; - let sourceColumn = 0; - let namesIndex = 0; - do { - const semi = reader.indexOf(";"); - const line = []; - let sorted = true; - let lastCol = 0; - genColumn = 0; - while (reader.pos < semi) { - let seg; - genColumn = decodeInteger(reader, genColumn); - if (genColumn < lastCol) sorted = false; - lastCol = genColumn; - if (hasMoreVlq(reader, semi)) { - sourcesIndex = decodeInteger(reader, sourcesIndex); - sourceLine = decodeInteger(reader, sourceLine); - sourceColumn = decodeInteger(reader, sourceColumn); - if (hasMoreVlq(reader, semi)) { - namesIndex = decodeInteger(reader, namesIndex); - seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; - } else { - seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; - } - } else { - seg = [genColumn]; - } - line.push(seg); - reader.pos++; - } - if (!sorted) sort(line); - decoded.push(line); - reader.pos = semi + 1; - } while (reader.pos <= length); - return decoded; -} -function sort(line) { - line.sort(sortComparator); -} -function sortComparator(a, b) { - return a[0] - b[0]; -} - -// src/trace-mapping.ts - -// src/sourcemap-segment.ts -var COLUMN = 0; -var SOURCES_INDEX = 1; -var SOURCE_LINE = 2; -var SOURCE_COLUMN = 3; -var NAMES_INDEX = 4; - -// src/binary-search.ts -var found = false; -function binarySearch(haystack, needle, low, high) { - while (low <= high) { - const mid = low + (high - low >> 1); - const cmp = haystack[mid][COLUMN] - needle; - if (cmp === 0) { - found = true; - return mid; - } - if (cmp < 0) { - low = mid + 1; - } else { - high = mid - 1; - } - } - found = false; - return low - 1; -} -function upperBound(haystack, needle, index) { - for (let i = index + 1; i < haystack.length; index = i++) { - if (haystack[i][COLUMN] !== needle) break; - } - return index; -} -function lowerBound(haystack, needle, index) { - for (let i = index - 1; i >= 0; index = i--) { - if (haystack[i][COLUMN] !== needle) break; - } - return index; -} -function memoizedBinarySearch(haystack, needle, state, key) { - const { lastKey, lastNeedle, lastIndex } = state; - let low = 0; - let high = haystack.length - 1; - if (key === lastKey) { - if (needle === lastNeedle) { - found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; - return lastIndex; - } - if (needle >= lastNeedle) { - low = lastIndex === -1 ? 0 : lastIndex; - } else { - high = lastIndex; - } - } - state.lastKey = key; - state.lastNeedle = needle; - return state.lastIndex = binarySearch(haystack, needle, low, high); -} - -// src/trace-mapping.ts -var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; -var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; -var LEAST_UPPER_BOUND = -1; -var GREATEST_LOWER_BOUND = 1; -function cast(map) { - return map; -} -function decodedMappings(map) { - var _a; - return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded)); -} -function originalPositionFor(map, needle) { - let { line, column, bias } = needle; - line--; - if (line < 0) throw new Error(LINE_GTR_ZERO); - if (column < 0) throw new Error(COL_GTR_EQ_ZERO); - const decoded = decodedMappings(map); - if (line >= decoded.length) return OMapping(null, null, null, null); - const segments = decoded[line]; - const index = traceSegmentInternal( - segments, - cast(map)._decodedMemo, - line, - column, - bias || GREATEST_LOWER_BOUND - ); - if (index === -1) return OMapping(null, null, null, null); - const segment = segments[index]; - if (segment.length === 1) return OMapping(null, null, null, null); - const { names, resolvedSources } = map; - return OMapping( - resolvedSources[segment[SOURCES_INDEX]], - segment[SOURCE_LINE] + 1, - segment[SOURCE_COLUMN], - segment.length === 5 ? names[segment[NAMES_INDEX]] : null - ); -} -function OMapping(source, line, column, name) { - return { source, line, column, name }; -} -function traceSegmentInternal(segments, memo, line, column, bias) { - let index = memoizedBinarySearch(segments, column, memo, line); - if (found) { - index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); - } else if (bias === LEAST_UPPER_BOUND) index++; - if (index === -1 || index === segments.length) return -1; - return index; -} - -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); -} -/** -* If code starts with a function call, will return its last index, respecting arguments. -* This will return 25 - last ending character of toMatch ")" -* Also works with callbacks -* ``` -* toMatch({ test: '123' }); -* toBeAliased('123') -* ``` -*/ -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; -} - -const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m; -const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/; -const stackIgnorePatterns = [ - "node:internal", - /\/packages\/\w+\/dist\//, - /\/@vitest\/\w+\/dist\//, - "/vitest/dist/", - "/vitest/src/", - "/node_modules/chai/", - "/node_modules/tinyspy/", - "/vite/dist/node/module-runner", - "/rolldown-vite/dist/node/module-runner", - "/deps/chunk-", - "/deps/@vitest", - "/deps/loupe", - "/deps/chai", - "/browser-playwright/dist/locators.js", - "/browser-webdriverio/dist/locators.js", - "/browser-preview/dist/locators.js", - /node:\w+/, - /__vitest_test__/, - /__vitest_browser__/, - /\/deps\/vitest_/ -]; -function extractLocation(urlLike) { - // Fail-fast but return locations like "(native)" - if (!urlLike.includes(":")) { - return [urlLike]; - } - const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; - const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); - if (!parts) { - return [urlLike]; - } - let url = parts[1]; - if (url.startsWith("async ")) { - url = url.slice(6); - } - if (url.startsWith("http:") || url.startsWith("https:")) { - const urlObj = new URL(url); - urlObj.searchParams.delete("import"); - urlObj.searchParams.delete("browserv"); - url = urlObj.pathname + urlObj.hash + urlObj.search; - } - if (url.startsWith("/@fs/")) { - const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url); - url = url.slice(isWindows ? 5 : 4); - } - return [ - url, - parts[2] || undefined, - parts[3] || undefined - ]; -} -function parseSingleFFOrSafariStack(raw) { - let line = raw.trim(); - if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { - return null; - } - if (line.includes(" > eval")) { - line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); - } - // Early return for lines that don't look like Firefox/Safari stack traces - // Firefox/Safari stack traces must contain '@' and should have location info after it - if (!line.includes("@")) { - return null; - } - // Find the correct @ that separates function name from location - // For cases like '@https://@fs/path' or 'functionName@https://@fs/path' - // we need to find the first @ that precedes a valid location (containing :) - let atIndex = -1; - let locationPart = ""; - let functionName; - // Try each @ from left to right to find the one that gives us a valid location - for (let i = 0; i < line.length; i++) { - if (line[i] === "@") { - const candidateLocation = line.slice(i + 1); - // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1") - if (candidateLocation.includes(":") && candidateLocation.length >= 3) { - atIndex = i; - locationPart = candidateLocation; - functionName = i > 0 ? line.slice(0, i) : undefined; - break; - } - } - } - // Validate we found a valid location with minimum length (filename:line format) - if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) { - return null; - } - const [url, lineNumber, columnNumber] = extractLocation(locationPart); - if (!url || !lineNumber || !columnNumber) { - return null; - } - return { - file: url, - method: functionName || "", - line: Number.parseInt(lineNumber), - column: Number.parseInt(columnNumber) - }; -} -// Based on https://github.com/stacktracejs/error-stack-parser -// Credit to stacktracejs -function parseSingleV8Stack(raw) { - let line = raw.trim(); - if (!CHROME_IE_STACK_REGEXP.test(line)) { - return null; - } - 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+/, ""); - // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in - // case it has spaces in it, as the string is split on \s+ later on - const location = sanitizedLine.match(/ (\(.+\)$)/); - // remove the parenthesized location from the line, if it was matched - sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; - // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine - // because this line doesn't have function name - const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); - let method = location && sanitizedLine || ""; - let file = url && ["eval", "<anonymous>"].includes(url) ? undefined : url; - if (!file || !lineNumber || !columnNumber) { - return null; - } - if (method.startsWith("async ")) { - method = method.slice(6); - } - if (file.startsWith("file://")) { - file = file.slice(7); - } - // normalize Windows path (\ -> /) - file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file); - if (method) { - method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, ""); - } - return { - method, - file, - line: Number.parseInt(lineNumber), - column: Number.parseInt(columnNumber) - }; -} -function parseStacktrace(stack, options = {}) { - const { ignoreStackEntries = stackIgnorePatterns } = options; - const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack); - return stacks.map((stack) => { - var _options$getSourceMap; - if (options.getUrlId) { - stack.file = options.getUrlId(stack.file); - } - const map = (_options$getSourceMap = options.getSourceMap) === null || _options$getSourceMap === void 0 ? void 0 : _options$getSourceMap.call(options, stack.file); - if (!map || typeof map !== "object" || !map.version) { - return shouldFilter(ignoreStackEntries, stack.file) ? null : stack; - } - const traceMap = new DecodedMap(map, stack.file); - const position = getOriginalPosition(traceMap, stack); - if (!position) { - return stack; - } - const { line, column, source, name } = position; - let file = source || stack.file; - if (file.match(/\/\w:\//)) { - file = file.slice(1); - } - if (shouldFilter(ignoreStackEntries, file)) { - return null; - } - if (line != null && column != null) { - return { - line, - column, - file, - method: name || stack.method - }; - } - return stack; - }).filter((s) => s != null); -} -function shouldFilter(ignoreStackEntries, file) { - return ignoreStackEntries.some((p) => file.match(p)); -} -function parseFFOrSafariStackTrace(stack) { - return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish); -} -function parseV8Stacktrace(stack) { - return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish); -} -function parseErrorStacktrace(e, options = {}) { - if (!e || isPrimitive(e)) { - return []; - } - if ("stacks" in e && e.stacks) { - return e.stacks; - } - const stackStr = e.stack || ""; - // if "stack" property was overwritten at runtime to be something else, - // ignore the value because we don't know how to process it - let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : []; - if (!stackFrames.length) { - const e_ = e; - if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) { - stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options); - } - if (e_.sourceURL != null && e_.line != null && e_._column != null) { - stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options); - } - } - if (options.frameFilter) { - stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false); - } - e.stacks = stackFrames; - return stackFrames; -} -class DecodedMap { - _encoded; - _decoded; - _decodedMemo; - url; - version; - names = []; - resolvedSources; - constructor(map, from) { - this.map = map; - const { mappings, names, sources } = map; - this.version = map.version; - this.names = names || []; - this._encoded = mappings || ""; - this._decodedMemo = memoizedState(); - this.url = from; - this.resolvedSources = (sources || []).map((s) => resolve(s || "", from)); - } -} -function memoizedState() { - return { - lastKey: -1, - lastNeedle: -1, - lastIndex: -1 - }; -} -function getOriginalPosition(map, needle) { - const result = originalPositionFor(map, needle); - if (result.column == null) { - return null; - } - return result; -} - -const lineSplitRE = /\r?\n/; -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 i = 0; i < lineNumber - 1; i++) { - start += lines[i].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; -} - -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*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*\{/; -function replaceObjectSnap(code, s, index, newSnap) { - let _code = code.slice(index); - const startMatch = startObjectRegex.exec(_code); - if (!startMatch) { - return false; - } - _code = _code.slice(startMatch.index); - let callEnd = getCallLastIndex(_code); - if (callEnd === null) { - return false; - } - callEnd += index + startMatch.index; - const shapeStart = index + startMatch.index + startMatch[0].length; - const shapeEnd = getObjectShapeEndIndex(code, shapeStart); - const snap = `, ${prepareSnapString(newSnap, code, index)}`; - if (shapeEnd === callEnd) { - // toMatchInlineSnapshot({ foo: expect.any(String) }) - s.appendLeft(callEnd, snap); - } else { - // toMatchInlineSnapshot({ foo: expect.any(String) }, ``) - s.overwrite(shapeEnd, callEnd, snap); - } - return true; -} -function getObjectShapeEndIndex(code, index) { - let startBraces = 1; - let endBraces = 0; - while (startBraces !== endBraces && index < code.length) { - const s = code[index++]; - if (s === "{") { - startBraces++; - } else if (s === "}") { - endBraces++; - } - } - return index; -} -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}\t` : `${indent} `; - const lines = snap.trim().replace(/\\/g, "\\\\").split(/\n/g); - const isOneline = lines.length <= 1; - const quote = "`"; - if (isOneline) { - return `${quote}${lines.join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}${quote}`; - } - return `${quote}\n${lines.map((i) => i ? indentNext + i : "").join("\n").replace(/`/g, "\\`").replace(/\$\{/g, "\\${")}\n${indent}${quote}`; -} -const toMatchInlineName = "toMatchInlineSnapshot"; -const toThrowErrorMatchingInlineName = "toThrowErrorMatchingInlineSnapshot"; -// on webkit, the line number is at the end of the method, not at the start -function getCodeStartingAtIndex(code, index) { - const indexInline = index - toMatchInlineName.length; - if (code.slice(indexInline, index) === toMatchInlineName) { - return { - code: code.slice(indexInline), - index: indexInline - }; - } - const indexThrowInline = index - toThrowErrorMatchingInlineName.length; - if (code.slice(index - indexThrowInline, index) === toThrowErrorMatchingInlineName) { - return { - code: code.slice(index - indexThrowInline), - index: index - indexThrowInline - }; - } - return { - code: code.slice(index), - index - }; -} -const startRegex = /(?:toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot)\s*\(\s*(?:\/\*[\s\S]*\*\/\s*|\/\/.*(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]))*[\w$]*(['"`)])/; -function replaceInlineSnap(code, s, currentIndex, newSnap) { - const { code: codeStartingAtIndex, index } = getCodeStartingAtIndex(code, currentIndex); - const startMatch = startRegex.exec(codeStartingAtIndex); - const firstKeywordMatch = /toMatchInlineSnapshot|toThrowErrorMatchingInlineSnapshot/.exec(codeStartingAtIndex); - if (!startMatch || startMatch.index !== (firstKeywordMatch === null || firstKeywordMatch === void 0 ? void 0 : firstKeywordMatch.index)) { - 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) { - var _lines$at; - // Find indentation if exists. - const match = inlineSnapshot.match(INDENTATION_REGEX); - if (!match || !match[1]) { - // No indentation. - return inlineSnapshot; - } - const indentation = match[1]; - const lines = inlineSnapshot.split(/\n/g); - if (lines.length <= 2) { - // Must be at least 3 lines. - return inlineSnapshot; - } - if (lines[0].trim() !== "" || ((_lines$at = lines.at(-1)) === null || _lines$at === void 0 ? void 0 : _lines$at.trim()) !== "") { - // If not blank first and last lines, abort. - return inlineSnapshot; - } - for (let i = 1; i < lines.length - 1; i++) { - if (lines[i] !== "") { - if (lines[i].indexOf(indentation) !== 0) { - // All lines except first and last should either be blank or have the same - // indent as the first line (or more). If this isn't the case we don't - // want to touch the snapshot at all. - return inlineSnapshot; - } - lines[i] = lines[i].substring(indentation.length); - } - } - // Last line is a special case because it won't have the same indent as others - // but may still have been given some indent to line up. - lines[lines.length - 1] = ""; - // Return inline snapshot, now at indent 0. - 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); - } - })); -} - -function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; -} - -var naturalCompare$1 = {exports: {}}; - -var hasRequiredNaturalCompare; - -function requireNaturalCompare () { - if (hasRequiredNaturalCompare) return naturalCompare$1.exports; - hasRequiredNaturalCompare = 1; - /* - * @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$1.exports = naturalCompare; - } catch (e) { - String.naturalCompare = naturalCompare; - } - return naturalCompare$1.exports; -} - -var naturalCompareExports = requireNaturalCompare(); -var naturalCompare = /*@__PURE__*/getDefaultExportFromCjs(naturalCompareExports); - -const serialize$1 = (val, config, indentation, depth, refs, printer) => { - // Serialize a non-default name, even if config.printFunctionName is false. - 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; -} - -// TODO: rewrite and clean up -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 = Object.create(null); - let snapshotContents = ""; - let dirty = false; - if (content != null) { - try { - snapshotContents = content; - // eslint-disable-next-line no-new-func - const populate = new Function("exports", snapshotContents); - populate(data); - } catch {} - } - // const validationResult = validateSnapshotVersion(snapshotContents) - const isInvalid = snapshotContents; - // if (update === 'none' && isInvalid) - // throw validationResult - if ((update === "all" || update === "new") && isInvalid) { - dirty = true; - } - return { - data, - dirty - }; -} -// Add extra line breaks at beginning and end of multiline snapshot -// to make the content easier to read. -function addExtraLineBreaks(string) { - return string.includes("\n") ? `\n${string}\n` : string; -} -// Remove extra line breaks at beginning and end of multiline snapshot. -// Instead of trim, which can remove additional newlines or spaces -// at beginning or end of the content from a custom serializer. -function removeExtraLineBreaks(string) { - return string.length > 2 && string[0] === "\n" && string.endsWith("\n") ? string.slice(1, -1) : string; -} -// export const removeLinesBeforeExternalMatcherTrap = (stack: string): string => { -// const lines = stack.split('\n') -// for (let i = 0; i < lines.length; i += 1) { -// // It's a function name specified in `packages/expect/src/index.ts` -// // for external custom matchers. -// if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__')) -// return lines.slice(i + 1).join('\n') -// } -// return stack -// } -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)}\``; -} -function normalizeNewlines(string) { - return string.replace(/\r\n|\r/g, "\n"); -} -async function saveSnapshotFile(environment, snapshotData, snapshotPath) { - const snapshots = Object.keys(snapshotData).sort(naturalCompare).map((key) => `exports[${printBacktickString(key)}] = ${printBacktickString(normalizeNewlines(snapshotData[key]))};`); - const content = `${environment.getHeader()}\n\n${snapshots.join("\n\n")}\n`; - const oldContent = await environment.readSnapshotFile(snapshotPath); - const skipWriting = oldContent != null && oldContent === content; - if (skipWriting) { - return; - } - await environment.saveSnapshotFile(snapshotPath, content); -} -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 { - // Source does not exist in target or target is primitive and cannot be deep merged - mergedOutput[index] = sourceElement; - } - }); - return mergedOutput; -} -/** -* Deep merge, but considers asymmetric matchers. Unlike base util's deep merge, -* will merge any object-like instance. -* Compatible with Jest's snapshot matcher. Should not be used outside of snapshot. -* -* @example -* ```ts -* toMatchSnapshot({ -* name: expect.stringContaining('text') -* }) -* ``` -*/ -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; -} -class DefaultMap extends Map { - constructor(defaultFn, entries) { - super(entries); - this.defaultFn = defaultFn; - } - get(key) { - if (!this.has(key)) { - this.set(key, this.defaultFn(key)); - } - return super.get(key); - } -} -class CounterMap extends DefaultMap { - constructor() { - super(() => 0); - } - // compat for jest-image-snapshot https://github.com/vitest-dev/vitest/issues/7322 - // `valueOf` and `Snapshot.added` setter allows - // snapshotState.added = snapshotState.added + 1 - // to function as - // snapshotState.added.total_ = snapshotState.added.total() + 1 - _total; - valueOf() { - return this._total = this.total(); - } - increment(key) { - if (typeof this._total !== "undefined") { - this._total++; - } - this.set(key, this.get(key) + 1); - } - total() { - if (typeof this._total !== "undefined") { - return this._total; - } - let total = 0; - for (const x of this.values()) { - total += x; - } - return total; - } -} - -function isSameStackPosition(x, y) { - return x.file === y.file && x.column === y.column && x.line === y.line; -} -class SnapshotState { - _counters = new CounterMap(); - _dirty; - _updateSnapshot; - _snapshotData; - _initialData; - _inlineSnapshots; - _inlineSnapshotStacks; - _testIdToKeys = new DefaultMap(() => []); - _rawSnapshots; - _uncheckedKeys; - _snapshotFormat; - _environment; - _fileExists; - expand; - // getter/setter for jest-image-snapshot compat - // https://github.com/vitest-dev/vitest/issues/7322 - _added = new CounterMap(); - _matched = new CounterMap(); - _unmatched = new CounterMap(); - _updated = new CounterMap(); - get added() { - return this._added; - } - set added(value) { - this._added._total = value; - } - get matched() { - return this._matched; - } - set matched(value) { - this._matched._total = value; - } - get unmatched() { - return this._unmatched; - } - set unmatched(value) { - this._unmatched._total = value; - } - get updated() { - return this._updated; - } - set updated(value) { - this._updated._total = value; - } - 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._inlineSnapshotStacks = []; - this._rawSnapshots = []; - this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); - this.expand = options.expand || false; - this._updateSnapshot = options.updateSnapshot; - this._snapshotFormat = { - printBasicPrototype: false, - escapeString: false, - ...options.snapshotFormat - }; - this._environment = options.snapshotEnvironment; - } - 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) => { - // skip snapshots with following keys - // testName n - // testName > xxx n (this is for toMatchSnapshot("xxx") API) - if (/ \d+$| > /.test(uncheckedKey.slice(testName.length))) { - this._uncheckedKeys.delete(uncheckedKey); - } - }); - } - clearTest(testId) { - // clear inline - this._inlineSnapshots = this._inlineSnapshots.filter((s) => s.testId !== testId); - this._inlineSnapshotStacks = this._inlineSnapshotStacks.filter((s) => s.testId !== testId); - // clear file - for (const key of this._testIdToKeys.get(testId)) { - const name = keyToTestName(key); - const count = this._counters.get(name); - if (count > 0) { - if (key in this._snapshotData || key in this._initialData) { - this._snapshotData[key] = this._initialData[key]; - } - this._counters.set(name, count - 1); - } - } - this._testIdToKeys.delete(testId); - // clear stats - this.added.delete(testId); - this.updated.delete(testId); - this.matched.delete(testId); - this.unmatched.delete(testId); - } - _inferInlineSnapshotStack(stacks) { - // if called inside resolves/rejects, stacktrace is different - const promiseIndex = stacks.findIndex((i) => i.method.match(/__VITEST_(RESOLVES|REJECTS)__/)); - if (promiseIndex !== -1) { - return stacks[promiseIndex + 3]; - } - // inline snapshot function is called __INLINE_SNAPSHOT__ - // in integrations/snapshot/chai.ts - 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.stack) { - this._inlineSnapshots.push({ - snapshot: receivedSerialized, - testId: options.testId, - ...options.stack - }); - } else if (options.rawSnapshot) { - this._rawSnapshots.push({ - ...options.rawSnapshot, - snapshot: receivedSerialized - }); - } else { - this._snapshotData[key] = receivedSerialized; - } - } - 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({ testId, testName, received, key, inlineSnapshot, isInline, error, rawSnapshot }) { - // this also increments counter for inline snapshots. maybe we shouldn't? - this._counters.increment(testName); - const count = this._counters.get(testName); - if (!key) { - key = testNameToKey(testName, count); - } - this._testIdToKeys.get(testId).push(key); - // Do not mark the snapshot as "checked" if the snapshot is inline and - // there's an external snapshot. This way the external snapshot can be - // removed with `--updateSnapshot`. - if (!(isInline && this._snapshotData[key] !== undefined)) { - this._uncheckedKeys.delete(key); - } - let receivedSerialized = rawSnapshot && typeof received === "string" ? received : serialize(received, undefined, this._snapshotFormat); - if (!rawSnapshot) { - receivedSerialized = addExtraLineBreaks(receivedSerialized); - } - if (rawSnapshot) { - // normalize EOL when snapshot contains CRLF but received is LF - 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 = rawSnapshot ? expected : expected === null || expected === void 0 ? void 0 : expected.trim(); - const pass = expectedTrimmed === (rawSnapshot ? receivedSerialized : receivedSerialized.trim()); - const hasSnapshot = expected !== undefined; - const snapshotIsPersisted = isInline || this._fileExists || rawSnapshot && rawSnapshot.content != null; - if (pass && !isInline && !rawSnapshot) { - // Executing a snapshot file as JavaScript and writing the strings back - // when other snapshots have changed loses the proper escaping for some - // characters. Since we check every snapshot in every test, use the newly - // generated formatted string. - // Note that this is only relevant when a snapshot is added and the dirty - // flag is set. - this._snapshotData[key] = receivedSerialized; - } - // find call site of toMatchInlineSnapshot - let stack; - if (isInline) { - var _this$environment$pro, _this$environment; - const stacks = parseErrorStacktrace(error || new Error("snapshot"), { ignoreStackEntries: [] }); - const _stack = this._inferInlineSnapshotStack(stacks); - if (!_stack) { - throw new Error(`@vitest/snapshot: Couldn't infer stack frame for inline snapshot.\n${JSON.stringify(stacks)}`); - } - 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; - // removing 1 column, because source map points to the wrong - // location for js files, but `column-1` points to the same in both js/ts - // https://github.com/vitejs/vite/issues/8657 - stack.column--; - // reject multiple inline snapshots at the same location if snapshot is different - const snapshotsWithSameStack = this._inlineSnapshotStacks.filter((s) => isSameStackPosition(s, stack)); - if (snapshotsWithSameStack.length > 0) { - // ensure only one snapshot will be written at the same location - this._inlineSnapshots = this._inlineSnapshots.filter((s) => !isSameStackPosition(s, stack)); - const differentSnapshot = snapshotsWithSameStack.find((s) => s.snapshot !== receivedSerialized); - if (differentSnapshot) { - throw Object.assign(new Error("toMatchInlineSnapshot with different snapshots cannot be called at the same location"), { - actual: receivedSerialized, - expected: differentSnapshot.snapshot - }); - } - } - this._inlineSnapshotStacks.push({ - ...stack, - testId, - snapshot: receivedSerialized - }); - } - // These are the conditions on when to write snapshots: - // * There's no snapshot file in a non-CI environment. - // * There is a snapshot file and we decided to update the snapshot. - // * There is a snapshot file, but it doesn't have this snapshot. - // These are the conditions on when not to write snapshots: - // * The update flag is set to 'none'. - // * There's no snapshot file or a file without this snapshot on a CI environment. - if (hasSnapshot && this._updateSnapshot === "all" || (!hasSnapshot || !snapshotIsPersisted) && (this._updateSnapshot === "new" || this._updateSnapshot === "all")) { - if (this._updateSnapshot === "all") { - if (!pass) { - if (hasSnapshot) { - this.updated.increment(testId); - } else { - this.added.increment(testId); - } - this._addSnapshot(key, receivedSerialized, { - stack, - testId, - rawSnapshot - }); - } else { - this.matched.increment(testId); - } - } else { - this._addSnapshot(key, receivedSerialized, { - stack, - testId, - rawSnapshot - }); - this.added.increment(testId); - } - return { - actual: "", - count, - expected: "", - key, - pass: true - }; - } else { - if (!pass) { - this.unmatched.increment(testId); - return { - actual: rawSnapshot ? receivedSerialized : removeExtraLineBreaks(receivedSerialized), - count, - expected: expectedTrimmed !== undefined ? rawSnapshot ? expectedTrimmed : removeExtraLineBreaks(expectedTrimmed) : undefined, - key, - pass: false - }; - } else { - this.matched.increment(testId); - 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.total(); - snapshot.matched = this.matched.total(); - snapshot.unmatched = this.unmatched.total(); - snapshot.updated = this.updated.total(); - snapshot.unchecked = !status.deleted ? uncheckedCount : 0; - snapshot.uncheckedKeys = Array.from(uncheckedKeys); - return snapshot; - } -} - -function createMismatchError(message, expand, 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 - }); - Object.defineProperty(error, "diffOptions", { value: { expand } }); - return error; -} -class SnapshotClient { - snapshotStateMap = new Map(); - constructor(options = {}) { - this.options = options; - } - async setup(filepath, options) { - if (this.snapshotStateMap.has(filepath)) { - return; - } - this.snapshotStateMap.set(filepath, await SnapshotState.create(filepath, options)); - } - async finish(filepath) { - const state = this.getSnapshotState(filepath); - const result = await state.pack(); - this.snapshotStateMap.delete(filepath); - return result; - } - skipTest(filepath, testName) { - const state = this.getSnapshotState(filepath); - state.markSnapshotsAsCheckedForTest(testName); - } - clearTest(filepath, testId) { - const state = this.getSnapshotState(filepath); - state.clearTest(testId); - } - getSnapshotState(filepath) { - const state = this.snapshotStateMap.get(filepath); - if (!state) { - throw new Error(`The snapshot state for '${filepath}' is not found. Did you call 'SnapshotClient.setup()'?`); - } - return state; - } - assert(options) { - const { filepath, name, testId = 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"); - } - const snapshotState = this.getSnapshotState(filepath); - if (typeof properties === "object") { - if (typeof received !== "object" || !received) { - throw new Error("Received value must be an object when the matcher has properties"); - } - try { - var _this$options$isEqual, _this$options; - 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; - // const pass = equals(received, properties, [iterableEquality, subsetEquality]) - if (!pass) { - throw createMismatchError("Snapshot properties mismatched", snapshotState.expand, received, properties); - } else { - received = deepMergeSnapshot(received, properties); - } - } catch (err) { - err.message = errorMessage || "Snapshot mismatched"; - throw err; - } - } - const testName = [name, ...message ? [message] : []].join(" > "); - const { actual, expected, key, pass } = snapshotState.match({ - testId, - testName, - received, - isInline, - error, - inlineSnapshot, - rawSnapshot - }); - if (!pass) { - 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()); - } - } - async assertRaw(options) { - if (!options.rawSnapshot) { - throw new Error("Raw snapshot is required"); - } - const { filepath, rawSnapshot } = options; - if (rawSnapshot.content == null) { - if (!filepath) { - throw new Error("Snapshot cannot be used outside of test"); - } - const snapshotState = this.getSnapshotState(filepath); - // save the filepath, so it don't lose even if the await make it out-of-context - options.filepath || (options.filepath = filepath); - // resolve and read the raw snapshot file - rawSnapshot.file = await snapshotState.environment.resolveRawPath(filepath, rawSnapshot.file); - rawSnapshot.content = await snapshotState.environment.readSnapshotFile(rawSnapshot.file) ?? undefined; - } - return this.assert(options); - } - clear() { - this.snapshotStateMap.clear(); - } -} - -export { SnapshotClient, SnapshotState, addSerializer, getSerializers, stripSnapshotIndentation }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/manager.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/manager.d.ts deleted file mode 100644 index a782935..0000000 --- a/vanilla/node_modules/@vitest/snapshot/dist/manager.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { S as SnapshotStateOptions, e as SnapshotSummary, b as SnapshotResult } from './rawSnapshot.d-lFsMJFUd.js'; -import '@vitest/pretty-format'; -import './environment.d-DHdQ1Csl.js'; - -declare class SnapshotManager { - options: Omit<SnapshotStateOptions, "snapshotEnvironment">; - summary: SnapshotSummary; - extension: string; - constructor(options: Omit<SnapshotStateOptions, "snapshotEnvironment">); - clear(): void; - add(result: SnapshotResult): void; - resolvePath<T = any>(testPath: string, context?: T): string; - resolveRawPath(testPath: string, rawPath: string): string; -} -declare function emptySummary(options: Omit<SnapshotStateOptions, "snapshotEnvironment">): SnapshotSummary; -declare function addSnapshotResult(summary: SnapshotSummary, result: SnapshotResult): void; - -export { SnapshotManager, addSnapshotResult, emptySummary }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/manager.js b/vanilla/node_modules/@vitest/snapshot/dist/manager.js deleted file mode 100644 index 90a36a3..0000000 --- a/vanilla/node_modules/@vitest/snapshot/dist/manager.js +++ /dev/null @@ -1,73 +0,0 @@ -import { join, dirname, basename, resolve, isAbsolute } from 'pathe'; - -class SnapshotManager { - summary; - extension = ".snap"; - constructor(options) { - this.options = options; - this.clear(); - } - clear() { - this.summary = emptySummary(this.options); - } - add(result) { - addSnapshotResult(this.summary, result); - } - resolvePath(testPath, context) { - const resolver = this.options.resolveSnapshotPath || (() => { - return join(join(dirname(testPath), "__snapshots__"), `${basename(testPath)}${this.extension}`); - }); - const path = resolver(testPath, this.extension, context); - return path; - } - resolveRawPath(testPath, rawPath) { - return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath); - } -} -function emptySummary(options) { - const summary = { - added: 0, - failure: false, - filesAdded: 0, - filesRemoved: 0, - filesRemovedList: [], - filesUnmatched: 0, - filesUpdated: 0, - matched: 0, - total: 0, - unchecked: 0, - uncheckedKeysByFile: [], - unmatched: 0, - updated: 0, - didUpdate: options.updateSnapshot === "all" - }; - return summary; -} -function addSnapshotResult(summary, result) { - if (result.added) { - summary.filesAdded++; - } - if (result.fileDeleted) { - summary.filesRemoved++; - } - if (result.unmatched) { - summary.filesUnmatched++; - } - if (result.updated) { - summary.filesUpdated++; - } - summary.added += result.added; - summary.matched += result.matched; - summary.unchecked += result.unchecked; - if (result.uncheckedKeys && result.uncheckedKeys.length > 0) { - summary.uncheckedKeysByFile.push({ - filePath: result.filepath, - keys: result.uncheckedKeys - }); - } - summary.unmatched += result.unmatched; - summary.updated += result.updated; - summary.total += result.added + result.matched + result.unmatched + result.updated; -} - -export { SnapshotManager, addSnapshotResult, emptySummary }; diff --git a/vanilla/node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts b/vanilla/node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts deleted file mode 100644 index 96fa2dd..0000000 --- a/vanilla/node_modules/@vitest/snapshot/dist/rawSnapshot.d-lFsMJFUd.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { OptionsReceived, Plugin } from '@vitest/pretty-format'; -import { S as SnapshotEnvironment } from './environment.d-DHdQ1Csl.js'; - -type SnapshotData = Record<string, string>; -type SnapshotUpdateState = "all" | "new" | "none"; -type SnapshotSerializer = Plugin; -interface SnapshotStateOptions { - updateSnapshot: SnapshotUpdateState; - snapshotEnvironment: SnapshotEnvironment; - expand?: boolean; - snapshotFormat?: OptionsReceived; - resolveSnapshotPath?: (path: string, extension: string, context?: any) => string; -} -interface SnapshotMatchOptions { - testId: string; - testName: string; - received: unknown; - key?: string; - inlineSnapshot?: string; - isInline: boolean; - error?: Error; - rawSnapshot?: RawSnapshotInfo; -} -interface SnapshotResult { - filepath: string; - added: number; - fileDeleted: boolean; - matched: number; - unchecked: number; - uncheckedKeys: Array<string>; - unmatched: number; - updated: number; -} -interface UncheckedSnapshot { - filePath: string; - keys: Array<string>; -} -interface SnapshotSummary { - added: number; - didUpdate: boolean; - failure: boolean; - filesAdded: number; - filesRemoved: number; - filesRemovedList: Array<string>; - filesUnmatched: number; - filesUpdated: number; - matched: number; - total: number; - unchecked: number; - uncheckedKeysByFile: Array<UncheckedSnapshot>; - unmatched: number; - updated: number; -} - -interface RawSnapshotInfo { - file: string; - readonly?: boolean; - content?: string; -} - -export type { RawSnapshotInfo as R, SnapshotStateOptions as S, UncheckedSnapshot as U, SnapshotMatchOptions as a, SnapshotResult as b, SnapshotData as c, SnapshotSerializer as d, SnapshotSummary as e, SnapshotUpdateState as f }; diff --git a/vanilla/node_modules/@vitest/snapshot/environment.d.ts b/vanilla/node_modules/@vitest/snapshot/environment.d.ts deleted file mode 100644 index 855f0d1..0000000 --- a/vanilla/node_modules/@vitest/snapshot/environment.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './dist/environment.js' diff --git a/vanilla/node_modules/@vitest/snapshot/manager.d.ts b/vanilla/node_modules/@vitest/snapshot/manager.d.ts deleted file mode 100644 index f3e8077..0000000 --- a/vanilla/node_modules/@vitest/snapshot/manager.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './dist/manager.js' diff --git a/vanilla/node_modules/@vitest/snapshot/package.json b/vanilla/node_modules/@vitest/snapshot/package.json deleted file mode 100644 index 41c347e..0000000 --- a/vanilla/node_modules/@vitest/snapshot/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@vitest/snapshot", - "type": "module", - "version": "4.0.18", - "description": "Vitest snapshot manager", - "license": "MIT", - "funding": "https://opencollective.com/vitest", - "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/snapshot#readme", - "repository": { - "type": "git", - "url": "git+https://github.com/vitest-dev/vitest.git", - "directory": "packages/snapshot" - }, - "bugs": { - "url": "https://github.com/vitest-dev/vitest/issues" - }, - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./environment": { - "types": "./dist/environment.d.ts", - "default": "./dist/environment.js" - }, - "./manager": { - "types": "./dist/manager.d.ts", - "default": "./dist/manager.js" - }, - "./*": "./*" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "*.d.ts", - "dist" - ], - "dependencies": { - "magic-string": "^0.30.21", - "pathe": "^2.0.3", - "@vitest/pretty-format": "4.0.18" - }, - "devDependencies": { - "@types/natural-compare": "^1.4.3", - "natural-compare": "^1.4.0", - "@vitest/utils": "4.0.18" - }, - "scripts": { - "build": "premove dist && rollup -c", - "dev": "rollup -c --watch" - } -}
\ No newline at end of file diff --git a/vanilla/node_modules/@vitest/spy/LICENSE b/vanilla/node_modules/@vitest/spy/LICENSE deleted file mode 100644 index 0e5771d..0000000 --- a/vanilla/node_modules/@vitest/spy/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vanilla/node_modules/@vitest/spy/README.md b/vanilla/node_modules/@vitest/spy/README.md deleted file mode 100644 index 5d23c87..0000000 --- a/vanilla/node_modules/@vitest/spy/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# @vitest/spy - -Lightweight Jest compatible spy implementation. diff --git a/vanilla/node_modules/@vitest/spy/dist/index.d.ts b/vanilla/node_modules/@vitest/spy/dist/index.d.ts deleted file mode 100644 index 408aeca..0000000 --- a/vanilla/node_modules/@vitest/spy/dist/index.d.ts +++ /dev/null @@ -1,384 +0,0 @@ -interface MockResultReturn<T> { - type: "return"; - /** - * The value that was returned from the function. If function returned a Promise, then this will be a resolved value. - */ - value: T; -} -interface MockResultIncomplete { - type: "incomplete"; - value: undefined; -} -interface MockResultThrow { - type: "throw"; - /** - * An error that was thrown during function execution. - */ - value: any; -} -interface MockSettledResultIncomplete { - type: "incomplete"; - value: undefined; -} -interface MockSettledResultFulfilled<T> { - type: "fulfilled"; - value: T; -} -interface MockSettledResultRejected { - type: "rejected"; - value: any; -} -type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete; -type MockSettledResult<T> = MockSettledResultFulfilled<T> | MockSettledResultRejected | MockSettledResultIncomplete; -type MockParameters<T extends Procedure | Constructable> = T extends Constructable ? ConstructorParameters<T> : T extends Procedure ? Parameters<T> : never; -type MockReturnType<T extends Procedure | Constructable> = T extends Constructable ? void : T extends Procedure ? ReturnType<T> : never; -type MockProcedureContext<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : ThisParameterType<T>; -interface MockContext<T extends Procedure | Constructable = Procedure> { - /** - * This is an array containing all arguments for each call. One item of the array is the arguments of that call. - * - * @see https://vitest.dev/api/mock#mock-calls - * @example - * const fn = vi.fn() - * - * fn('arg1', 'arg2') - * fn('arg3') - * - * fn.mock.calls === [ - * ['arg1', 'arg2'], // first call - * ['arg3'], // second call - * ] - */ - calls: MockParameters<T>[]; - /** - * This is an array containing all instances that were instantiated when mock was called with a `new` keyword. Note that this is an actual context (`this`) of the function, not a return value. - * @see https://vitest.dev/api/mock#mock-instances - */ - instances: MockProcedureContext<T>[]; - /** - * An array of `this` values that were used during each call to the mock function. - * @see https://vitest.dev/api/mock#mock-contexts - */ - contexts: MockProcedureContext<T>[]; - /** - * The order of mock's execution. This returns an array of numbers which are shared between all defined mocks. - * - * @see https://vitest.dev/api/mock#mock-invocationcallorder - * @example - * const fn1 = vi.fn() - * const fn2 = vi.fn() - * - * fn1() - * fn2() - * fn1() - * - * fn1.mock.invocationCallOrder === [1, 3] - * fn2.mock.invocationCallOrder === [2] - */ - invocationCallOrder: number[]; - /** - * This is an array containing all values that were `returned` from the function. - * - * The `value` property contains the returned value or thrown error. If the function returned a `Promise`, then `result` will always be `'return'` even if the promise was rejected. - * - * @see https://vitest.dev/api/mock#mock-results - * @example - * const fn = vi.fn() - * .mockReturnValueOnce('result') - * .mockImplementationOnce(() => { throw new Error('thrown error') }) - * - * const result = fn() - * - * try { - * fn() - * } - * catch {} - * - * fn.mock.results === [ - * { - * type: 'return', - * value: 'result', - * }, - * { - * type: 'throw', - * value: Error, - * }, - * ] - */ - results: MockResult<MockReturnType<T>>[]; - /** - * An array containing all values that were `resolved` or `rejected` from the function. - * - * This array will be empty if the function was never resolved or rejected. - * - * @see https://vitest.dev/api/mock#mock-settledresults - * @example - * const fn = vi.fn().mockResolvedValueOnce('result') - * - * const result = fn() - * - * fn.mock.settledResults === [ - * { - * type: 'incomplete', - * value: undefined, - * } - * ] - * fn.mock.results === [ - * { - * type: 'return', - * value: Promise<'result'>, - * }, - * ] - * - * await result - * - * fn.mock.settledResults === [ - * { - * type: 'fulfilled', - * value: 'result', - * }, - * ] - */ - settledResults: MockSettledResult<Awaited<MockReturnType<T>>>[]; - /** - * This contains the arguments of the last call. If spy wasn't called, will return `undefined`. - * @see https://vitest.dev/api/mock#mock-lastcall - */ - lastCall: MockParameters<T> | undefined; -} -type Procedure = (...args: any[]) => any; -type NormalizedProcedure<T extends Procedure | Constructable> = T extends Constructable ? ({ - new (...args: ConstructorParameters<T>): InstanceType<T>; -}) | ({ - (this: InstanceType<T>, ...args: ConstructorParameters<T>): void; -}) : T extends Procedure ? (...args: Parameters<T>) => ReturnType<T> : never; -type Methods<T> = keyof { [K in keyof T as T[K] extends Procedure ? K : never] : T[K] }; -type Properties<T> = { [K in keyof T] : T[K] extends Procedure ? never : K }[keyof T] & (string | symbol); -type Classes<T> = { [K in keyof T] : T[K] extends new (...args: any[]) => any ? K : never }[keyof T] & (string | symbol); -interface MockInstance<T extends Procedure | Constructable = Procedure> extends Disposable { - /** - * Use it to return the name assigned to the mock with the `.mockName(name)` method. By default, it will return `vi.fn()`. - * @see https://vitest.dev/api/mock#getmockname - */ - getMockName(): string; - /** - * Sets the internal mock name. This is useful for identifying the mock when an assertion fails. - * @see https://vitest.dev/api/mock#mockname - */ - mockName(name: string): this; - /** - * Current context of the mock. It stores information about all invocation calls, instances, and results. - */ - mock: MockContext<T>; - /** - * Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions. - * - * To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/#clearmocks) setting in the configuration. - * @see https://vitest.dev/api/mock#mockclear - */ - mockClear(): this; - /** - * Does what `mockClear` does and resets inner implementation to the original function. This also resets all "once" implementations. - * - * Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. - * Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state. - * - * To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/#mockreset) setting in the configuration. - * @see https://vitest.dev/api/mock#mockreset - */ - mockReset(): this; - /** - * Does what `mockReset` does and restores original descriptors of spied-on objects. - * @see https://vitest.dev/api/mock#mockrestore - */ - mockRestore(): void; - /** - * Returns current permanent mock implementation if there is one. - * - * If mock was created with `vi.fn`, it will consider passed down method as a mock implementation. - * - * If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided. - */ - getMockImplementation(): NormalizedProcedure<T> | undefined; - /** - * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. - * @see https://vitest.dev/api/mock#mockimplementation - * @example - * const increment = vi.fn().mockImplementation(count => count + 1); - * expect(increment(3)).toBe(4); - */ - mockImplementation(fn: NormalizedProcedure<T>): this; - /** - * Accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. This method can be chained to produce different results for multiple function calls. - * - * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called. - * @see https://vitest.dev/api/mock#mockimplementationonce - * @example - * const fn = vi.fn(count => count).mockImplementationOnce(count => count + 1); - * expect(fn(3)).toBe(4); - * expect(fn(3)).toBe(3); - */ - mockImplementationOnce(fn: NormalizedProcedure<T>): this; - /** - * Overrides the original mock implementation temporarily while the callback is being executed. - * - * Note that this method takes precedence over the [`mockImplementationOnce`](https://vitest.dev/api/mock#mockimplementationonce). - * @see https://vitest.dev/api/mock#withimplementation - * @example - * const myMockFn = vi.fn(() => 'original') - * - * myMockFn.withImplementation(() => 'temp', () => { - * myMockFn() // 'temp' - * }) - * - * myMockFn() // 'original' - */ - withImplementation(fn: NormalizedProcedure<T>, cb: () => Promise<unknown>): Promise<this>; - withImplementation(fn: NormalizedProcedure<T>, cb: () => unknown): this; - /** - * Use this if you need to return the `this` context from the method without invoking the actual implementation. - * @see https://vitest.dev/api/mock#mockreturnthis - */ - mockReturnThis(): this; - /** - * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function. - * @see https://vitest.dev/api/mock#mockreturnvalue - * @example - * const mock = vi.fn() - * mock.mockReturnValue(42) - * mock() // 42 - * mock.mockReturnValue(43) - * mock() // 43 - */ - mockReturnValue(value: MockReturnType<T>): this; - /** - * Accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function. - * - * When the mocked function runs out of implementations, it will invoke the default implementation set with `vi.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called. - * @example - * const myMockFn = vi - * .fn() - * .mockReturnValue('default') - * .mockReturnValueOnce('first call') - * .mockReturnValueOnce('second call') - * - * // 'first call', 'second call', 'default' - * console.log(myMockFn(), myMockFn(), myMockFn()) - */ - mockReturnValueOnce(value: MockReturnType<T>): this; - /** - * Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function. - * @example - * const asyncMock = vi.fn().mockResolvedValue(42) - * asyncMock() // Promise<42> - */ - mockResolvedValue(value: Awaited<MockReturnType<T>>): this; - /** - * Accepts a value that will be resolved during the next function call. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value. - * @example - * const myMockFn = vi - * .fn() - * .mockResolvedValue('default') - * .mockResolvedValueOnce('first call') - * .mockResolvedValueOnce('second call') - * - * // Promise<'first call'>, Promise<'second call'>, Promise<'default'> - * console.log(myMockFn(), myMockFn(), myMockFn()) - */ - mockResolvedValueOnce(value: Awaited<MockReturnType<T>>): this; - /** - * Accepts an error that will be rejected when async function is called. - * @example - * const asyncMock = vi.fn().mockRejectedValue(new Error('Async error')) - * await asyncMock() // throws Error<'Async error'> - */ - mockRejectedValue(error: unknown): this; - /** - * Accepts a value that will be rejected during the next function call. If chained, each consecutive call will reject the specified value. - * @example - * const asyncMock = vi - * .fn() - * .mockResolvedValueOnce('first call') - * .mockRejectedValueOnce(new Error('Async error')) - * - * await asyncMock() // first call - * await asyncMock() // throws Error<'Async error'> - */ - mockRejectedValueOnce(error: unknown): this; -} -type Mock<T extends Procedure | Constructable = Procedure> = MockInstance<T> & (T extends Constructable ? (T extends Procedure ? { - new (...args: ConstructorParameters<T>): InstanceType<T>; - (...args: Parameters<T>): ReturnType<T>; -} : { - new (...args: ConstructorParameters<T>): InstanceType<T>; -}) : { - new (...args: MockParameters<T>): MockReturnType<T>; - (...args: MockParameters<T>): MockReturnType<T>; -}) & { [P in keyof T] : T[P] }; -type PartialMaybePromise<T> = T extends Promise<Awaited<T>> ? Promise<Partial<Awaited<T>>> : Partial<T>; -type PartialResultFunction<T> = T extends Constructable ? ({ - new (...args: ConstructorParameters<T>): InstanceType<T>; -}) | ({ - (this: InstanceType<T>, ...args: ConstructorParameters<T>): void; -}) : T extends Procedure ? (...args: Parameters<T>) => PartialMaybePromise<ReturnType<T>> : T; -type PartialMock<T extends Procedure | Constructable = Procedure> = Mock<PartialResultFunction<T extends Mock ? NonNullable<ReturnType<T["getMockImplementation"]>> : T>>; -type MaybeMockedConstructor<T> = T extends Constructable ? Mock<T> : T; -type MockedFunction<T extends Procedure | Constructable> = Mock<T> & { [K in keyof T] : T[K] }; -type PartiallyMockedFunction<T extends Procedure | Constructable> = PartialMock<T> & { [K in keyof T] : T[K] }; -type MockedFunctionDeep<T extends Procedure | Constructable> = Mock<T> & MockedObjectDeep<T>; -type PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = PartialMock<T> & MockedObjectDeep<T>; -type MockedObject<T> = MaybeMockedConstructor<T> & { [K in Methods<T>] : T[K] extends Procedure ? MockedFunction<T[K]> : T[K] } & { [K in Properties<T>] : T[K] }; -type MockedObjectDeep<T> = MaybeMockedConstructor<T> & { [K in Methods<T>] : T[K] extends Procedure ? MockedFunctionDeep<T[K]> : T[K] } & { [K in Properties<T>] : MaybeMockedDeep<T[K]> }; -type MaybeMockedDeep<T> = T extends Procedure | Constructable ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T; -type MaybePartiallyMockedDeep<T> = T extends Procedure | Constructable ? PartiallyMockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T; -type MaybeMocked<T> = T extends Procedure | Constructable ? MockedFunction<T> : T extends object ? MockedObject<T> : T; -type MaybePartiallyMocked<T> = T extends Procedure | Constructable ? PartiallyMockedFunction<T> : T extends object ? MockedObject<T> : T; -interface Constructable { - new (...args: any[]): any; -} -type MockedClass<T extends Constructable> = MockInstance<T> & { - prototype: T extends { - prototype: any; - } ? Mocked<T["prototype"]> : never; -} & T; -type Mocked<T> = { [P in keyof T] : T[P] extends Procedure ? MockInstance<T[P]> : T[P] extends Constructable ? MockedClass<T[P]> : T[P] } & T; -interface MockConfig { - mockImplementation: Procedure | Constructable | undefined; - mockOriginal: Procedure | Constructable | undefined; - mockName: string; - onceMockImplementations: Array<Procedure | Constructable>; -} -interface MockInstanceOption { - originalImplementation?: Procedure | Constructable; - mockImplementation?: Procedure | Constructable; - resetToMockImplementation?: boolean; - restore?: () => void; - prototypeMembers?: (string | symbol)[]; - keepMembersImplementation?: boolean; - prototypeState?: MockContext; - prototypeConfig?: MockConfig; - resetToMockName?: boolean; - name?: string | symbol; -} - -declare function isMockFunction(fn: any): fn is Mock; -declare function createMockInstance(options?: MockInstanceOption): Mock<Procedure | Constructable>; -declare function fn<T extends Procedure | Constructable = Procedure>(originalImplementation?: T): Mock<T>; -declare function spyOn< - T extends object, - S extends Properties<Required<T>> ->(object: T, key: S, accessor: "get"): Mock<() => T[S]>; -declare function spyOn< - T extends object, - G extends Properties<Required<T>> ->(object: T, key: G, accessor: "set"): Mock<(arg: T[G]) => void>; -declare function spyOn< - T extends object, - M extends Classes<Required<T>> | Methods<Required<T>> ->(object: T, key: M): Required<T>[M] extends Constructable | Procedure ? Mock<Required<T>[M]> : never; -declare function restoreAllMocks(): void; -declare function clearAllMocks(): void; -declare function resetAllMocks(): void; - -export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn }; -export type { Constructable, MaybeMocked, MaybeMockedConstructor, MaybeMockedDeep, MaybePartiallyMocked, MaybePartiallyMockedDeep, Mock, MockContext, MockInstance, MockInstanceOption, MockParameters, MockProcedureContext, MockResult, MockResultIncomplete, MockResultReturn, MockResultThrow, MockReturnType, MockSettledResult, MockSettledResultFulfilled, MockSettledResultIncomplete, MockSettledResultRejected, Mocked, MockedClass, MockedFunction, MockedFunctionDeep, MockedObject, MockedObjectDeep, PartialMock, PartiallyMockedFunction, PartiallyMockedFunctionDeep, Procedure }; diff --git a/vanilla/node_modules/@vitest/spy/dist/index.js b/vanilla/node_modules/@vitest/spy/dist/index.js deleted file mode 100644 index 96f9784..0000000 --- a/vanilla/node_modules/@vitest/spy/dist/index.js +++ /dev/null @@ -1,433 +0,0 @@ -function isMockFunction(fn) { - return typeof fn === "function" && "_isMockFunction" in fn && fn._isMockFunction === true; -} -const MOCK_RESTORE = new Set(); -// Jest keeps the state in a separate WeakMap which is good for memory, -// but it makes the state slower to access and return different values -// if you stored it before calling `mockClear` where it will be recreated -const REGISTERED_MOCKS = new Set(); -const MOCK_CONFIGS = new WeakMap(); -function createMockInstance(options = {}) { - var _ref; - const { originalImplementation, restore, mockImplementation, resetToMockImplementation, resetToMockName } = options; - if (restore) { - MOCK_RESTORE.add(restore); - } - const config = getDefaultConfig(originalImplementation); - const state = getDefaultState(); - const mock = createMock({ - config, - state, - ...options - }); - const mockLength = ((_ref = mockImplementation || originalImplementation) === null || _ref === void 0 ? void 0 : _ref.length) ?? 0; - Object.defineProperty(mock, "length", { - writable: true, - enumerable: false, - value: mockLength, - configurable: true - }); - // inherit the default name so it appears in snapshots and logs - // this is used by `vi.spyOn()` for better debugging. - // when `vi.fn()` is called, we just use the default string - if (resetToMockName) { - config.mockName = mock.name || "vi.fn()"; - } - MOCK_CONFIGS.set(mock, config); - REGISTERED_MOCKS.add(mock); - mock._isMockFunction = true; - mock.getMockImplementation = () => { - // Jest only returns `config.mockImplementation` here, - // but we think it makes sense to return what the next function will be called - return config.onceMockImplementations[0] || config.mockImplementation; - }; - Object.defineProperty(mock, "mock", { - configurable: false, - enumerable: true, - writable: false, - value: state - }); - mock.mockImplementation = function mockImplementation(implementation) { - config.mockImplementation = implementation; - return mock; - }; - mock.mockImplementationOnce = function mockImplementationOnce(implementation) { - config.onceMockImplementations.push(implementation); - return mock; - }; - mock.withImplementation = function withImplementation(implementation, callback) { - const previousImplementation = config.mockImplementation; - const previousOnceImplementations = config.onceMockImplementations; - const reset = () => { - config.mockImplementation = previousImplementation; - config.onceMockImplementations = previousOnceImplementations; - }; - config.mockImplementation = implementation; - config.onceMockImplementations = []; - const returnValue = callback(); - if (typeof returnValue === "object" && typeof (returnValue === null || returnValue === void 0 ? void 0 : returnValue.then) === "function") { - return returnValue.then(() => { - reset(); - return mock; - }); - } else { - reset(); - } - return mock; - }; - mock.mockReturnThis = function mockReturnThis() { - return mock.mockImplementation(function() { - return this; - }); - }; - mock.mockReturnValue = function mockReturnValue(value) { - return mock.mockImplementation(() => value); - }; - mock.mockReturnValueOnce = function mockReturnValueOnce(value) { - return mock.mockImplementationOnce(() => value); - }; - mock.mockResolvedValue = function mockResolvedValue(value) { - return mock.mockImplementation(() => Promise.resolve(value)); - }; - mock.mockResolvedValueOnce = function mockResolvedValueOnce(value) { - return mock.mockImplementationOnce(() => Promise.resolve(value)); - }; - mock.mockRejectedValue = function mockRejectedValue(value) { - return mock.mockImplementation(() => Promise.reject(value)); - }; - mock.mockRejectedValueOnce = function mockRejectedValueOnce(value) { - return mock.mockImplementationOnce(() => Promise.reject(value)); - }; - mock.mockClear = function mockClear() { - state.calls = []; - state.contexts = []; - state.instances = []; - state.invocationCallOrder = []; - state.results = []; - state.settledResults = []; - return mock; - }; - mock.mockReset = function mockReset() { - mock.mockClear(); - config.mockImplementation = resetToMockImplementation ? mockImplementation : undefined; - config.mockName = resetToMockName ? mock.name || "vi.fn()" : "vi.fn()"; - config.onceMockImplementations = []; - return mock; - }; - mock.mockRestore = function mockRestore() { - mock.mockReset(); - return restore === null || restore === void 0 ? void 0 : restore(); - }; - mock.mockName = function mockName(name) { - if (typeof name === "string") { - config.mockName = name; - } - return mock; - }; - mock.getMockName = function getMockName() { - return config.mockName || "vi.fn()"; - }; - if (Symbol.dispose) { - mock[Symbol.dispose] = () => mock.mockRestore(); - } - if (mockImplementation) { - mock.mockImplementation(mockImplementation); - } - return mock; -} -function fn(originalImplementation) { - // if the function is already a mock, just return the same function, - // simillarly to how vi.spyOn() works - if (originalImplementation != null && isMockFunction(originalImplementation)) { - return originalImplementation; - } - return createMockInstance({ - mockImplementation: originalImplementation, - resetToMockImplementation: true - }); -} -function spyOn(object, key, accessor) { - assert(object != null, "The vi.spyOn() function could not find an object to spy upon. The first argument must be defined."); - assert(typeof object === "object" || typeof object === "function", "Vitest cannot spy on a primitive value."); - const [originalDescriptorObject, originalDescriptor] = getDescriptor(object, key) || []; - assert(originalDescriptor || key in object, `The property "${String(key)}" is not defined on the ${typeof object}.`); - let accessType = accessor || "value"; - let ssr = false; - // vite ssr support - actual function is stored inside a getter - if (accessType === "value" && originalDescriptor && originalDescriptor.value == null && originalDescriptor.get) { - accessType = "get"; - ssr = true; - } - let original; - if (originalDescriptor) { - original = originalDescriptor[accessType]; - } else if (accessType !== "value") { - original = () => object[key]; - } else { - original = object[key]; - } - const originalImplementation = ssr && original ? original() : original; - const originalType = typeof originalImplementation; - assert( - // allow only functions - originalType === "function" || accessType !== "value" && original == null, - `vi.spyOn() can only spy on a function. Received ${originalType}.` - ); - if (isMockFunction(originalImplementation)) { - return originalImplementation; - } - const reassign = (cb) => { - const { value, ...desc } = originalDescriptor || { - configurable: true, - writable: true - }; - if (accessType !== "value") { - delete desc.writable; - } - desc[accessType] = cb; - Object.defineProperty(object, key, desc); - }; - const restore = () => { - // if method is defined on the prototype, we can just remove it from - // the current object instead of redefining a copy of it - if (originalDescriptorObject !== object) { - Reflect.deleteProperty(object, key); - } else if (originalDescriptor && !original) { - Object.defineProperty(object, key, originalDescriptor); - } else { - reassign(original); - } - }; - const mock = createMockInstance({ - restore, - originalImplementation, - resetToMockName: true - }); - try { - reassign(ssr ? () => mock : mock); - } catch (error) { - if (error instanceof TypeError && Symbol.toStringTag && object[Symbol.toStringTag] === "Module" && (error.message.includes("Cannot redefine property") || error.message.includes("Cannot replace module namespace") || error.message.includes("can't redefine non-configurable property"))) { - throw new TypeError(`Cannot spy on export "${String(key)}". Module namespace is not configurable in ESM. See: https://vitest.dev/guide/browser/#limitations`, { cause: error }); - } - throw error; - } - return mock; -} -function getDescriptor(obj, method) { - const objDescriptor = Object.getOwnPropertyDescriptor(obj, method); - if (objDescriptor) { - return [obj, objDescriptor]; - } - let currentProto = Object.getPrototypeOf(obj); - while (currentProto !== null) { - const descriptor = Object.getOwnPropertyDescriptor(currentProto, method); - if (descriptor) { - return [currentProto, descriptor]; - } - currentProto = Object.getPrototypeOf(currentProto); - } -} -function assert(condition, message) { - if (!condition) { - throw new Error(message); - } -} -let invocationCallCounter = 1; -function createMock({ state, config, name: mockName, prototypeState, prototypeConfig, keepMembersImplementation, mockImplementation, prototypeMembers = [] }) { - const original = config.mockOriginal; - const pseudoOriginal = mockImplementation; - const name = mockName || (original === null || original === void 0 ? void 0 : original.name) || "Mock"; - const namedObject = { [name]: (function(...args) { - registerCalls(args, state, prototypeState); - registerInvocationOrder(invocationCallCounter++, state, prototypeState); - const result = { - type: "incomplete", - value: undefined - }; - const settledResult = { - type: "incomplete", - value: undefined - }; - registerResult(result, state, prototypeState); - registerSettledResult(settledResult, state, prototypeState); - const context = new.target ? undefined : this; - const [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState); - const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState); - const implementation = config.onceMockImplementations.shift() || config.mockImplementation || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.onceMockImplementations.shift()) || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockImplementation) || original || function() {}; - let returnValue; - let thrownValue; - let didThrow = false; - try { - if (new.target) { - returnValue = Reflect.construct(implementation, args, new.target); - // jest calls this before the implementation, but we have to resolve this _after_ - // because we cannot do it before the `Reflect.construct` called the custom implementation. - // fortunetly, the constructor is always an empty functon because `prototypeMethods` - // are only used by the automocker, so this doesn't matter - for (const prop of prototypeMembers) { - const prototypeMock = returnValue[prop]; - // the method was overidden because of inheritence, ignore it - // eslint-disable-next-line ts/no-use-before-define - if (prototypeMock !== mock.prototype[prop]) { - continue; - } - const isMock = isMockFunction(prototypeMock); - const prototypeState = isMock ? prototypeMock.mock : undefined; - const prototypeConfig = isMock ? MOCK_CONFIGS.get(prototypeMock) : undefined; - returnValue[prop] = createMockInstance({ - originalImplementation: keepMembersImplementation ? prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockOriginal : undefined, - prototypeState, - prototypeConfig, - keepMembersImplementation - }); - } - } else { - returnValue = implementation.apply(this, args); - } - } catch (error) { - thrownValue = error; - didThrow = true; - if (error instanceof TypeError && error.message.includes("is not a constructor")) { - console.warn(`[vitest] The ${namedObject[name].getMockName()} mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.`); - } - throw error; - } finally { - if (didThrow) { - result.type = "throw"; - result.value = thrownValue; - settledResult.type = "rejected"; - settledResult.value = thrownValue; - } else { - result.type = "return"; - result.value = returnValue; - if (new.target) { - state.contexts[contextIndex - 1] = returnValue; - state.instances[instanceIndex - 1] = returnValue; - if (contextPrototypeIndex != null && prototypeState) { - prototypeState.contexts[contextPrototypeIndex - 1] = returnValue; - } - if (instancePrototypeIndex != null && prototypeState) { - prototypeState.instances[instancePrototypeIndex - 1] = returnValue; - } - } - if (returnValue instanceof Promise) { - returnValue.then((settledValue) => { - settledResult.type = "fulfilled"; - settledResult.value = settledValue; - }, (rejectedValue) => { - settledResult.type = "rejected"; - settledResult.value = rejectedValue; - }); - } else { - settledResult.type = "fulfilled"; - settledResult.value = returnValue; - } - } - } - return returnValue; - }) }; - const mock = namedObject[name]; - const copyPropertiesFrom = original || pseudoOriginal; - if (copyPropertiesFrom) { - copyOriginalStaticProperties(mock, copyPropertiesFrom); - } - return mock; -} -function registerCalls(args, state, prototypeState) { - state.calls.push(args); - prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.calls.push(args); -} -function registerInvocationOrder(order, state, prototypeState) { - state.invocationCallOrder.push(order); - prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.invocationCallOrder.push(order); -} -function registerResult(result, state, prototypeState) { - state.results.push(result); - prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.results.push(result); -} -function registerSettledResult(result, state, prototypeState) { - state.settledResults.push(result); - prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.settledResults.push(result); -} -function registerInstance(instance, state, prototypeState) { - const instanceIndex = state.instances.push(instance); - const instancePrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.instances.push(instance); - return [instanceIndex, instancePrototypeIndex]; -} -function registerContext(context, state, prototypeState) { - const contextIndex = state.contexts.push(context); - const contextPrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.contexts.push(context); - return [contextIndex, contextPrototypeIndex]; -} -function copyOriginalStaticProperties(mock, original) { - const { properties, descriptors } = getAllProperties(original); - for (const key of properties) { - const descriptor = descriptors[key]; - const mockDescriptor = getDescriptor(mock, key); - if (mockDescriptor) { - continue; - } - Object.defineProperty(mock, key, descriptor); - } -} -const ignoreProperties = new Set([ - "length", - "name", - "prototype", - Symbol.for("nodejs.util.promisify.custom") -]); -function getAllProperties(original) { - const properties = new Set(); - const descriptors = {}; - while (original && original !== Object.prototype && original !== Function.prototype) { - const ownProperties = [...Object.getOwnPropertyNames(original), ...Object.getOwnPropertySymbols(original)]; - for (const prop of ownProperties) { - if (descriptors[prop] || ignoreProperties.has(prop)) { - continue; - } - properties.add(prop); - descriptors[prop] = Object.getOwnPropertyDescriptor(original, prop); - } - original = Object.getPrototypeOf(original); - } - return { - properties, - descriptors - }; -} -function getDefaultConfig(original) { - return { - mockImplementation: undefined, - mockOriginal: original, - mockName: "vi.fn()", - onceMockImplementations: [] - }; -} -function getDefaultState() { - const state = { - calls: [], - contexts: [], - instances: [], - invocationCallOrder: [], - settledResults: [], - results: [], - get lastCall() { - return state.calls.at(-1); - } - }; - return state; -} -function restoreAllMocks() { - for (const restore of MOCK_RESTORE) { - restore(); - } - MOCK_RESTORE.clear(); -} -function clearAllMocks() { - REGISTERED_MOCKS.forEach((mock) => mock.mockClear()); -} -function resetAllMocks() { - REGISTERED_MOCKS.forEach((mock) => mock.mockReset()); -} - -export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn }; diff --git a/vanilla/node_modules/@vitest/spy/package.json b/vanilla/node_modules/@vitest/spy/package.json deleted file mode 100644 index 5564c28..0000000 --- a/vanilla/node_modules/@vitest/spy/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "@vitest/spy", - "type": "module", - "version": "4.0.18", - "description": "Lightweight Jest compatible spy implementation", - "license": "MIT", - "funding": "https://opencollective.com/vitest", - "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/spy#readme", - "repository": { - "type": "git", - "url": "git+https://github.com/vitest-dev/vitest.git", - "directory": "packages/spy" - }, - "bugs": { - "url": "https://github.com/vitest-dev/vitest/issues" - }, - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./*": "./*" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "files": [ - "dist" - ], - "scripts": { - "build": "premove dist && rollup -c", - "dev": "rollup -c --watch" - } -}
\ No newline at end of file diff --git a/vanilla/node_modules/@vitest/utils/LICENSE b/vanilla/node_modules/@vitest/utils/LICENSE deleted file mode 100644 index 0e5771d..0000000 --- a/vanilla/node_modules/@vitest/utils/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vanilla/node_modules/@vitest/utils/diff.d.ts b/vanilla/node_modules/@vitest/utils/diff.d.ts deleted file mode 100644 index 0a66b86..0000000 --- a/vanilla/node_modules/@vitest/utils/diff.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './dist/diff.js' diff --git a/vanilla/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js b/vanilla/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js deleted file mode 100644 index c9366dd..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +++ /dev/null @@ -1,5 +0,0 @@ -function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; -} - -export { getDefaultExportFromCjs as g }; diff --git a/vanilla/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js b/vanilla/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js deleted file mode 100644 index 74d0dab..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +++ /dev/null @@ -1,156 +0,0 @@ -const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; -function normalizeWindowsPath(input = "") { - if (!input) { - return input; - } - return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); -} - -const _UNC_REGEX = /^[/\\]{2}/; -const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; -const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; -const normalize = function(path) { - if (path.length === 0) { - return "."; - } - path = normalizeWindowsPath(path); - const isUNCPath = path.match(_UNC_REGEX); - const isPathAbsolute = isAbsolute(path); - const trailingSeparator = path[path.length - 1] === "/"; - path = normalizeString(path, !isPathAbsolute); - if (path.length === 0) { - if (isPathAbsolute) { - return "/"; - } - return trailingSeparator ? "./" : "."; - } - if (trailingSeparator) { - path += "/"; - } - if (_DRIVE_LETTER_RE.test(path)) { - path += "/"; - } - if (isUNCPath) { - if (!isPathAbsolute) { - return `//./${path}`; - } - return `//${path}`; - } - return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; -}; -const join = function(...segments) { - let path = ""; - for (const seg of segments) { - if (!seg) { - continue; - } - if (path.length > 0) { - const pathTrailing = path[path.length - 1] === "/"; - const segLeading = seg[0] === "/"; - const both = pathTrailing && segLeading; - if (both) { - path += seg.slice(1); - } else { - path += pathTrailing || segLeading ? seg : `/${seg}`; - } - } else { - path += seg; - } - } - return normalize(path); -}; -function cwd() { - if (typeof process !== "undefined" && typeof process.cwd === "function") { - 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 dirname = function(p) { - const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); - if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { - segments[0] += "/"; - } - return segments.join("/") || (isAbsolute(p) ? "/" : "."); -}; - -export { dirname as d, join as j, resolve as r }; diff --git a/vanilla/node_modules/@vitest/utils/dist/constants.d.ts b/vanilla/node_modules/@vitest/utils/dist/constants.d.ts deleted file mode 100644 index bd5ad65..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/constants.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -declare const KNOWN_ASSET_TYPES: string[]; -declare const KNOWN_ASSET_RE: RegExp; -declare const CSS_LANGS_RE: RegExp; -/** -* Prefix for resolved Ids that are not valid browser import specifiers -*/ -declare const VALID_ID_PREFIX = "/@id/"; -/** -* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the -* module ID with `\0`, a convention from the rollup ecosystem. -* This prevents other plugins from trying to process the id (like node resolution), -* and core features like sourcemaps can use this info to differentiate between -* virtual modules and regular files. -* `\0` is not a permitted char in import URLs so we have to replace them during -* import analysis. The id will be decoded back before entering the plugins pipeline. -* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual -* modules in the browser end up encoded as `/@id/__x00__{id}` -*/ -declare const NULL_BYTE_PLACEHOLDER = "__x00__"; - -export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX }; diff --git a/vanilla/node_modules/@vitest/utils/dist/constants.js b/vanilla/node_modules/@vitest/utils/dist/constants.js deleted file mode 100644 index 385045b..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/constants.js +++ /dev/null @@ -1,49 +0,0 @@ -// TODO: this is all copy pasted from Vite - can they expose a module that exports only constants? -const KNOWN_ASSET_TYPES = [ - "apng", - "bmp", - "png", - "jpe?g", - "jfif", - "pjpeg", - "pjp", - "gif", - "svg", - "ico", - "webp", - "avif", - "mp4", - "webm", - "ogg", - "mp3", - "wav", - "flac", - "aac", - "woff2?", - "eot", - "ttf", - "otf", - "webmanifest", - "pdf", - "txt" -]; -const KNOWN_ASSET_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`); -const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; -/** -* Prefix for resolved Ids that are not valid browser import specifiers -*/ -const VALID_ID_PREFIX = `/@id/`; -/** -* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the -* module ID with `\0`, a convention from the rollup ecosystem. -* This prevents other plugins from trying to process the id (like node resolution), -* and core features like sourcemaps can use this info to differentiate between -* virtual modules and regular files. -* `\0` is not a permitted char in import URLs so we have to replace them during -* import analysis. The id will be decoded back before entering the plugins pipeline. -* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual -* modules in the browser end up encoded as `/@id/__x00__{id}` -*/ -const NULL_BYTE_PLACEHOLDER = `__x00__`; - -export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX }; diff --git a/vanilla/node_modules/@vitest/utils/dist/diff.d.ts b/vanilla/node_modules/@vitest/utils/dist/diff.d.ts deleted file mode 100644 index 603569d..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/diff.d.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { D as DiffOptions } from './types.d-BCElaP-c.js'; -export { a as DiffOptionsColor, S as SerializedDiffOptions } from './types.d-BCElaP-c.js'; -import '@vitest/pretty-format'; - -/** -* Diff Match and Patch -* Copyright 2018 The diff-match-patch Authors. -* https://github.com/google/diff-match-patch -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -/** -* @fileoverview Computes the difference between two texts to create a patch. -* Applies the patch onto another text, allowing for errors. -* @author fraser@google.com (Neil Fraser) -*/ -/** -* CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: -* -* 1. Delete anything not needed to use diff_cleanupSemantic method -* 2. Convert from prototype properties to var declarations -* 3. Convert Diff to class from constructor and prototype -* 4. Add type annotations for arguments and return values -* 5. Add exports -*/ -/** -* The data structure representing a diff is an array of tuples: -* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] -* which means: delete 'Hello', add 'Goodbye' and keep ' world.' -*/ -declare const DIFF_DELETE = -1; -declare const DIFF_INSERT = 1; -declare const DIFF_EQUAL = 0; -/** -* Class representing one diff tuple. -* Attempts to look like a two-element array (which is what this used to be). -* @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. -* @param {string} text Text to be deleted, inserted, or retained. -* @constructor -*/ -declare class Diff { - 0: number; - 1: string; - constructor(op: number, text: string); -} - -/** -* Copyright (c) Meta Platforms, Inc. and affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -declare function diffLinesUnified(aLines: Array<string>, bLines: Array<string>, options?: DiffOptions): string; -declare function diffLinesUnified2(aLinesDisplay: Array<string>, bLinesDisplay: Array<string>, aLinesCompare: Array<string>, bLinesCompare: Array<string>, options?: DiffOptions): string; -declare function diffLinesRaw(aLines: Array<string>, bLines: Array<string>, options?: DiffOptions): [Array<Diff>, boolean]; - -/** -* Copyright (c) Meta Platforms, Inc. and affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -declare function diffStringsUnified(a: string, b: string, options?: DiffOptions): string; -declare function diffStringsRaw(a: string, b: string, cleanup: boolean, options?: DiffOptions): [Array<Diff>, boolean]; - -/** -* @param a Expected value -* @param b Received value -* @param options Diff options -* @returns {string | null} a string diff -*/ -declare function diff(a: any, b: any, options?: DiffOptions): string | undefined; -declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions): string | undefined; -declare function replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced?: WeakSet<WeakKey>, expectedReplaced?: WeakSet<WeakKey>): { - replacedActual: any; - replacedExpected: any; -}; -type PrintLabel = (string: string) => string; -declare function getLabelPrinter(...strings: Array<string>): PrintLabel; - -export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher }; diff --git a/vanilla/node_modules/@vitest/utils/dist/diff.js b/vanilla/node_modules/@vitest/utils/dist/diff.js deleted file mode 100644 index 415a4f1..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/diff.js +++ /dev/null @@ -1,2199 +0,0 @@ -import { plugins, format } from '@vitest/pretty-format'; -import c from 'tinyrainbow'; -import { stringify } from './display.js'; -import { deepClone, getOwnProperties, getType as getType$1 } from './helpers.js'; -import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js'; -import './constants.js'; - -/** -* Diff Match and Patch -* Copyright 2018 The diff-match-patch Authors. -* https://github.com/google/diff-match-patch -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -/** -* @fileoverview Computes the difference between two texts to create a patch. -* Applies the patch onto another text, allowing for errors. -* @author fraser@google.com (Neil Fraser) -*/ -/** -* CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: -* -* 1. Delete anything not needed to use diff_cleanupSemantic method -* 2. Convert from prototype properties to var declarations -* 3. Convert Diff to class from constructor and prototype -* 4. Add type annotations for arguments and return values -* 5. Add exports -*/ -/** -* The data structure representing a diff is an array of tuples: -* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] -* which means: delete 'Hello', add 'Goodbye' and keep ' world.' -*/ -const DIFF_DELETE = -1; -const DIFF_INSERT = 1; -const DIFF_EQUAL = 0; -/** -* Class representing one diff tuple. -* Attempts to look like a two-element array (which is what this used to be). -* @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. -* @param {string} text Text to be deleted, inserted, or retained. -* @constructor -*/ -class Diff { - 0; - 1; - constructor(op, text) { - this[0] = op; - this[1] = text; - } -} -/** -* Determine the common prefix of two strings. -* @param {string} text1 First string. -* @param {string} text2 Second string. -* @return {number} The number of characters common to the start of each -* string. -*/ -function diff_commonPrefix(text1, text2) { - // Quick check for common null cases. - if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { - return 0; - } - // Binary search. - // Performance analysis: https://neil.fraser.name/news/2007/10/09/ - let pointermin = 0; - let pointermax = Math.min(text1.length, text2.length); - let pointermid = pointermax; - let pointerstart = 0; - while (pointermin < pointermid) { - if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { - pointermin = pointermid; - pointerstart = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - return pointermid; -} -/** -* Determine the common suffix of two strings. -* @param {string} text1 First string. -* @param {string} text2 Second string. -* @return {number} The number of characters common to the end of each string. -*/ -function diff_commonSuffix(text1, text2) { - // Quick check for common null cases. - if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { - return 0; - } - // Binary search. - // Performance analysis: https://neil.fraser.name/news/2007/10/09/ - let pointermin = 0; - let pointermax = Math.min(text1.length, text2.length); - let pointermid = pointermax; - let pointerend = 0; - while (pointermin < pointermid) { - if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { - pointermin = pointermid; - pointerend = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - return pointermid; -} -/** -* Determine if the suffix of one string is the prefix of another. -* @param {string} text1 First string. -* @param {string} text2 Second string. -* @return {number} The number of characters common to the end of the first -* string and the start of the second string. -* @private -*/ -function diff_commonOverlap_(text1, text2) { - // Cache the text lengths to prevent multiple calls. - const text1_length = text1.length; - const text2_length = text2.length; - // Eliminate the null case. - if (text1_length === 0 || text2_length === 0) { - return 0; - } - // Truncate the longer string. - if (text1_length > text2_length) { - text1 = text1.substring(text1_length - text2_length); - } else if (text1_length < text2_length) { - text2 = text2.substring(0, text1_length); - } - const text_length = Math.min(text1_length, text2_length); - // Quick check for the worst case. - if (text1 === text2) { - return text_length; - } - // Start by looking for a single character match - // and increase length until no match is found. - // Performance analysis: https://neil.fraser.name/news/2010/11/04/ - let best = 0; - let length = 1; - while (true) { - const pattern = text1.substring(text_length - length); - const found = text2.indexOf(pattern); - if (found === -1) { - return best; - } - length += found; - if (found === 0 || text1.substring(text_length - length) === text2.substring(0, length)) { - best = length; - length++; - } - } -} -/** -* Reduce the number of edits by eliminating semantically trivial equalities. -* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. -*/ -function diff_cleanupSemantic(diffs) { - let changes = false; - const equalities = []; - let equalitiesLength = 0; - /** @type {?string} */ - let lastEquality = null; - // Always equal to diffs[equalities[equalitiesLength - 1]][1] - let pointer = 0; - // Number of characters that changed prior to the equality. - let length_insertions1 = 0; - let length_deletions1 = 0; - // Number of characters that changed after the equality. - let length_insertions2 = 0; - let length_deletions2 = 0; - while (pointer < diffs.length) { - if (diffs[pointer][0] === DIFF_EQUAL) { - // Equality found. - equalities[equalitiesLength++] = pointer; - length_insertions1 = length_insertions2; - length_deletions1 = length_deletions2; - length_insertions2 = 0; - length_deletions2 = 0; - lastEquality = diffs[pointer][1]; - } else { - // An insertion or deletion. - if (diffs[pointer][0] === DIFF_INSERT) { - length_insertions2 += diffs[pointer][1].length; - } else { - length_deletions2 += diffs[pointer][1].length; - } - // Eliminate an equality that is smaller or equal to the edits on both - // sides of it. - if (lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2)) { - // Duplicate record. - diffs.splice(equalities[equalitiesLength - 1], 0, new Diff(DIFF_DELETE, lastEquality)); - // Change second copy to insert. - diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; - // Throw away the equality we just deleted. - equalitiesLength--; - // Throw away the previous equality (it needs to be reevaluated). - equalitiesLength--; - pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; - length_insertions1 = 0; - length_deletions1 = 0; - length_insertions2 = 0; - length_deletions2 = 0; - lastEquality = null; - changes = true; - } - } - pointer++; - } - // Normalize the diff. - if (changes) { - diff_cleanupMerge(diffs); - } - diff_cleanupSemanticLossless(diffs); - // Find any overlaps between deletions and insertions. - // e.g: <del>abcxxx</del><ins>xxxdef</ins> - // -> <del>abc</del>xxx<ins>def</ins> - // e.g: <del>xxxabc</del><ins>defxxx</ins> - // -> <ins>def</ins>xxx<del>abc</del> - // Only extract an overlap if it is as big as the edit ahead or behind it. - pointer = 1; - while (pointer < diffs.length) { - if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) { - const deletion = diffs[pointer - 1][1]; - const insertion = diffs[pointer][1]; - const overlap_length1 = diff_commonOverlap_(deletion, insertion); - const overlap_length2 = diff_commonOverlap_(insertion, deletion); - if (overlap_length1 >= overlap_length2) { - if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { - // Overlap found. Insert an equality and trim the surrounding edits. - diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1))); - diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); - diffs[pointer + 1][1] = insertion.substring(overlap_length1); - pointer++; - } - } else { - if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { - // Reverse overlap found. - // Insert an equality and swap and trim the surrounding edits. - diffs.splice(pointer, 0, new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2))); - diffs[pointer - 1][0] = DIFF_INSERT; - diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); - diffs[pointer + 1][0] = DIFF_DELETE; - diffs[pointer + 1][1] = deletion.substring(overlap_length2); - pointer++; - } - } - pointer++; - } - pointer++; - } -} -// Define some regex patterns for matching boundaries. -const nonAlphaNumericRegex_ = /[^a-z0-9]/i; -const whitespaceRegex_ = /\s/; -const linebreakRegex_ = /[\r\n]/; -const blanklineEndRegex_ = /\n\r?\n$/; -const blanklineStartRegex_ = /^\r?\n\r?\n/; -/** -* Look for single edits surrounded on both sides by equalities -* which can be shifted sideways to align the edit to a word boundary. -* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. -* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. -*/ -function diff_cleanupSemanticLossless(diffs) { - let pointer = 1; - // Intentionally ignore the first and last element (don't need checking). - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { - // This is a single edit surrounded by equalities. - let equality1 = diffs[pointer - 1][1]; - let edit = diffs[pointer][1]; - let equality2 = diffs[pointer + 1][1]; - // First, shift the edit as far left as possible. - const commonOffset = diff_commonSuffix(equality1, edit); - if (commonOffset) { - const commonString = edit.substring(edit.length - commonOffset); - equality1 = equality1.substring(0, equality1.length - commonOffset); - edit = commonString + edit.substring(0, edit.length - commonOffset); - equality2 = commonString + equality2; - } - // Second, step character by character right, looking for the best fit. - let bestEquality1 = equality1; - let bestEdit = edit; - let bestEquality2 = equality2; - let bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); - while (edit.charAt(0) === equality2.charAt(0)) { - equality1 += edit.charAt(0); - edit = edit.substring(1) + equality2.charAt(0); - equality2 = equality2.substring(1); - const score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); - // The >= encourages trailing rather than leading whitespace on edits. - if (score >= bestScore) { - bestScore = score; - bestEquality1 = equality1; - bestEdit = edit; - bestEquality2 = equality2; - } - } - if (diffs[pointer - 1][1] !== bestEquality1) { - // We have an improvement, save it back to the diff. - if (bestEquality1) { - diffs[pointer - 1][1] = bestEquality1; - } else { - diffs.splice(pointer - 1, 1); - pointer--; - } - diffs[pointer][1] = bestEdit; - if (bestEquality2) { - diffs[pointer + 1][1] = bestEquality2; - } else { - diffs.splice(pointer + 1, 1); - pointer--; - } - } - } - pointer++; - } -} -/** -* Reorder and merge like edit sections. Merge equalities. -* Any edit section can move as long as it doesn't cross an equality. -* @param {!Array.<!diff_match_patch.Diff>} diffs Array of diff tuples. -*/ -function diff_cleanupMerge(diffs) { - var _diffs$at; - // Add a dummy entry at the end. - diffs.push(new Diff(DIFF_EQUAL, "")); - let pointer = 0; - let count_delete = 0; - let count_insert = 0; - let text_delete = ""; - let text_insert = ""; - let commonlength; - while (pointer < diffs.length) { - switch (diffs[pointer][0]) { - case DIFF_INSERT: - count_insert++; - text_insert += diffs[pointer][1]; - pointer++; - break; - case DIFF_DELETE: - count_delete++; - text_delete += diffs[pointer][1]; - pointer++; - break; - case DIFF_EQUAL: - // Upon reaching an equality, check for prior redundancies. - if (count_delete + count_insert > 1) { - if (count_delete !== 0 && count_insert !== 0) { - // Factor out any common prefixes. - commonlength = diff_commonPrefix(text_insert, text_delete); - if (commonlength !== 0) { - if (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] === DIFF_EQUAL) { - diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); - } else { - diffs.splice(0, 0, new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength))); - pointer++; - } - text_insert = text_insert.substring(commonlength); - text_delete = text_delete.substring(commonlength); - } - // Factor out any common suffixes. - commonlength = diff_commonSuffix(text_insert, text_delete); - if (commonlength !== 0) { - diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; - text_insert = text_insert.substring(0, text_insert.length - commonlength); - text_delete = text_delete.substring(0, text_delete.length - commonlength); - } - } - // Delete the offending records and add the merged ones. - pointer -= count_delete + count_insert; - diffs.splice(pointer, count_delete + count_insert); - if (text_delete.length) { - diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)); - pointer++; - } - if (text_insert.length) { - diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)); - pointer++; - } - pointer++; - } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { - // Merge this equality with the previous one. - diffs[pointer - 1][1] += diffs[pointer][1]; - diffs.splice(pointer, 1); - } else { - pointer++; - } - count_insert = 0; - count_delete = 0; - text_delete = ""; - text_insert = ""; - break; - } - } - if (((_diffs$at = diffs.at(-1)) === null || _diffs$at === void 0 ? void 0 : _diffs$at[1]) === "") { - diffs.pop(); - } - // Second pass: look for single edits surrounded on both sides by equalities - // which can be shifted sideways to eliminate an equality. - // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC - let changes = false; - pointer = 1; - // Intentionally ignore the first and last element (don't need checking). - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { - // This is a single edit surrounded by equalities. - if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { - // Shift the edit over the previous equality. - diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); - diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; - diffs.splice(pointer - 1, 1); - changes = true; - } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { - // Shift the edit over the next equality. - diffs[pointer - 1][1] += diffs[pointer + 1][1]; - diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; - diffs.splice(pointer + 1, 1); - changes = true; - } - } - pointer++; - } - // If shifts were made, the diff needs reordering and another shift sweep. - if (changes) { - diff_cleanupMerge(diffs); - } -} -/** -* Given two strings, compute a score representing whether the internal -* boundary falls on logical boundaries. -* Scores range from 6 (best) to 0 (worst). -* Closure, but does not reference any external variables. -* @param {string} one First string. -* @param {string} two Second string. -* @return {number} The score. -* @private -*/ -function diff_cleanupSemanticScore_(one, two) { - if (!one || !two) { - // Edges are the best. - return 6; - } - // Each port of this function behaves slightly differently due to - // subtle differences in each language's definition of things like - // 'whitespace'. Since this function's purpose is largely cosmetic, - // the choice has been made to use each language's native features - // rather than force total conformity. - const char1 = one.charAt(one.length - 1); - const char2 = two.charAt(0); - const nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); - const nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); - const whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); - const whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); - const lineBreak1 = whitespace1 && char1.match(linebreakRegex_); - const lineBreak2 = whitespace2 && char2.match(linebreakRegex_); - const blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); - const blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); - if (blankLine1 || blankLine2) { - // Five points for blank lines. - return 5; - } else if (lineBreak1 || lineBreak2) { - // Four points for line breaks. - return 4; - } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { - // Three points for end of sentences. - return 3; - } else if (whitespace1 || whitespace2) { - // Two points for whitespace. - return 2; - } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { - // One point for non-alphanumeric. - return 1; - } - return 0; -} - -/** -* Copyright (c) Meta Platforms, Inc. and affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -const NO_DIFF_MESSAGE = "Compared values have no visual difference."; -const SIMILAR_MESSAGE = "Compared values serialize to the same structure.\n" + "Printing internal object structure without calling `toJSON` instead."; - -var build = {}; - -var hasRequiredBuild; - -function requireBuild () { - if (hasRequiredBuild) return build; - hasRequiredBuild = 1; - - Object.defineProperty(build, '__esModule', { - value: true - }); - build.default = diffSequence; - /** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - */ - - // This diff-sequences package implements the linear space variation in - // An O(ND) Difference Algorithm and Its Variations by Eugene W. Myers - - // Relationship in notation between Myers paper and this package: - // A is a - // N is aLength, aEnd - aStart, and so on - // x is aIndex, aFirst, aLast, and so on - // B is b - // M is bLength, bEnd - bStart, and so on - // y is bIndex, bFirst, bLast, and so on - // Δ = N - M is negative of baDeltaLength = bLength - aLength - // D is d - // k is kF - // k + Δ is kF = kR - baDeltaLength - // V is aIndexesF or aIndexesR (see comment below about Indexes type) - // index intervals [1, N] and [1, M] are [0, aLength) and [0, bLength) - // starting point in forward direction (0, 0) is (-1, -1) - // starting point in reverse direction (N + 1, M + 1) is (aLength, bLength) - - // The “edit graph” for sequences a and b corresponds to items: - // in a on the horizontal axis - // in b on the vertical axis - // - // Given a-coordinate of a point in a diagonal, you can compute b-coordinate. - // - // Forward diagonals kF: - // zero diagonal intersects top left corner - // positive diagonals intersect top edge - // negative diagonals insersect left edge - // - // Reverse diagonals kR: - // zero diagonal intersects bottom right corner - // positive diagonals intersect right edge - // negative diagonals intersect bottom edge - - // The graph contains a directed acyclic graph of edges: - // horizontal: delete an item from a - // vertical: insert an item from b - // diagonal: common item in a and b - // - // The algorithm solves dual problems in the graph analogy: - // Find longest common subsequence: path with maximum number of diagonal edges - // Find shortest edit script: path with minimum number of non-diagonal edges - - // Input callback function compares items at indexes in the sequences. - - // Output callback function receives the number of adjacent items - // and starting indexes of each common subsequence. - // Either original functions or wrapped to swap indexes if graph is transposed. - // Indexes in sequence a of last point of forward or reverse paths in graph. - // Myers algorithm indexes by diagonal k which for negative is bad deopt in V8. - // This package indexes by iF and iR which are greater than or equal to zero. - // and also updates the index arrays in place to cut memory in half. - // kF = 2 * iF - d - // kR = d - 2 * iR - // Division of index intervals in sequences a and b at the middle change. - // Invariant: intervals do not have common items at the start or end. - const pkg = 'diff-sequences'; // for error messages - const NOT_YET_SET = 0; // small int instead of undefined to avoid deopt in V8 - - // Return the number of common items that follow in forward direction. - // The length of what Myers paper calls a “snake” in a forward path. - const countCommonItemsF = (aIndex, aEnd, bIndex, bEnd, isCommon) => { - let nCommon = 0; - while (aIndex < aEnd && bIndex < bEnd && isCommon(aIndex, bIndex)) { - aIndex += 1; - bIndex += 1; - nCommon += 1; - } - return nCommon; - }; - - // Return the number of common items that precede in reverse direction. - // The length of what Myers paper calls a “snake” in a reverse path. - const countCommonItemsR = (aStart, aIndex, bStart, bIndex, isCommon) => { - let nCommon = 0; - while (aStart <= aIndex && bStart <= bIndex && isCommon(aIndex, bIndex)) { - aIndex -= 1; - bIndex -= 1; - nCommon += 1; - } - return nCommon; - }; - - // A simple function to extend forward paths from (d - 1) to d changes - // when forward and reverse paths cannot yet overlap. - const extendPathsF = ( - d, - aEnd, - bEnd, - bF, - isCommon, - aIndexesF, - iMaxF // return the value because optimization might decrease it - ) => { - // Unroll the first iteration. - let iF = 0; - let kF = -d; // kF = 2 * iF - d - let aFirst = aIndexesF[iF]; // in first iteration always insert - let aIndexPrev1 = aFirst; // prev value of [iF - 1] in next iteration - aIndexesF[iF] += countCommonItemsF( - aFirst + 1, - aEnd, - bF + aFirst - kF + 1, - bEnd, - isCommon - ); - - // Optimization: skip diagonals in which paths cannot ever overlap. - const nF = d < iMaxF ? d : iMaxF; - - // The diagonals kF are odd when d is odd and even when d is even. - for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) { - // To get first point of path segment, move one change in forward direction - // from last point of previous path segment in an adjacent diagonal. - // In last possible iteration when iF === d and kF === d always delete. - if (iF !== d && aIndexPrev1 < aIndexesF[iF]) { - aFirst = aIndexesF[iF]; // vertical to insert from b - } else { - aFirst = aIndexPrev1 + 1; // horizontal to delete from a - - if (aEnd <= aFirst) { - // Optimization: delete moved past right of graph. - return iF - 1; - } - } - - // To get last point of path segment, move along diagonal of common items. - aIndexPrev1 = aIndexesF[iF]; - aIndexesF[iF] = - aFirst + - countCommonItemsF(aFirst + 1, aEnd, bF + aFirst - kF + 1, bEnd, isCommon); - } - return iMaxF; - }; - - // A simple function to extend reverse paths from (d - 1) to d changes - // when reverse and forward paths cannot yet overlap. - const extendPathsR = ( - d, - aStart, - bStart, - bR, - isCommon, - aIndexesR, - iMaxR // return the value because optimization might decrease it - ) => { - // Unroll the first iteration. - let iR = 0; - let kR = d; // kR = d - 2 * iR - let aFirst = aIndexesR[iR]; // in first iteration always insert - let aIndexPrev1 = aFirst; // prev value of [iR - 1] in next iteration - aIndexesR[iR] -= countCommonItemsR( - aStart, - aFirst - 1, - bStart, - bR + aFirst - kR - 1, - isCommon - ); - - // Optimization: skip diagonals in which paths cannot ever overlap. - const nR = d < iMaxR ? d : iMaxR; - - // The diagonals kR are odd when d is odd and even when d is even. - for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) { - // To get first point of path segment, move one change in reverse direction - // from last point of previous path segment in an adjacent diagonal. - // In last possible iteration when iR === d and kR === -d always delete. - if (iR !== d && aIndexesR[iR] < aIndexPrev1) { - aFirst = aIndexesR[iR]; // vertical to insert from b - } else { - aFirst = aIndexPrev1 - 1; // horizontal to delete from a - - if (aFirst < aStart) { - // Optimization: delete moved past left of graph. - return iR - 1; - } - } - - // To get last point of path segment, move along diagonal of common items. - aIndexPrev1 = aIndexesR[iR]; - aIndexesR[iR] = - aFirst - - countCommonItemsR( - aStart, - aFirst - 1, - bStart, - bR + aFirst - kR - 1, - isCommon - ); - } - return iMaxR; - }; - - // A complete function to extend forward paths from (d - 1) to d changes. - // Return true if a path overlaps reverse path of (d - 1) changes in its diagonal. - const extendOverlappablePathsF = ( - d, - aStart, - aEnd, - bStart, - bEnd, - isCommon, - aIndexesF, - iMaxF, - aIndexesR, - iMaxR, - division // update prop values if return true - ) => { - const bF = bStart - aStart; // bIndex = bF + aIndex - kF - const aLength = aEnd - aStart; - const bLength = bEnd - bStart; - const baDeltaLength = bLength - aLength; // kF = kR - baDeltaLength - - // Range of diagonals in which forward and reverse paths might overlap. - const kMinOverlapF = -baDeltaLength - (d - 1); // -(d - 1) <= kR - const kMaxOverlapF = -baDeltaLength + (d - 1); // kR <= (d - 1) - - let aIndexPrev1 = NOT_YET_SET; // prev value of [iF - 1] in next iteration - - // Optimization: skip diagonals in which paths cannot ever overlap. - const nF = d < iMaxF ? d : iMaxF; - - // The diagonals kF = 2 * iF - d are odd when d is odd and even when d is even. - for (let iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) { - // To get first point of path segment, move one change in forward direction - // from last point of previous path segment in an adjacent diagonal. - // In first iteration when iF === 0 and kF === -d always insert. - // In last possible iteration when iF === d and kF === d always delete. - const insert = iF === 0 || (iF !== d && aIndexPrev1 < aIndexesF[iF]); - const aLastPrev = insert ? aIndexesF[iF] : aIndexPrev1; - const aFirst = insert - ? aLastPrev // vertical to insert from b - : aLastPrev + 1; // horizontal to delete from a - - // To get last point of path segment, move along diagonal of common items. - const bFirst = bF + aFirst - kF; - const nCommonF = countCommonItemsF( - aFirst + 1, - aEnd, - bFirst + 1, - bEnd, - isCommon - ); - const aLast = aFirst + nCommonF; - aIndexPrev1 = aIndexesF[iF]; - aIndexesF[iF] = aLast; - if (kMinOverlapF <= kF && kF <= kMaxOverlapF) { - // Solve for iR of reverse path with (d - 1) changes in diagonal kF: - // kR = kF + baDeltaLength - // kR = (d - 1) - 2 * iR - const iR = (d - 1 - (kF + baDeltaLength)) / 2; - - // If this forward path overlaps the reverse path in this diagonal, - // then this is the middle change of the index intervals. - if (iR <= iMaxR && aIndexesR[iR] - 1 <= aLast) { - // Unlike the Myers algorithm which finds only the middle “snake” - // this package can find two common subsequences per division. - // Last point of previous path segment is on an adjacent diagonal. - const bLastPrev = bF + aLastPrev - (insert ? kF + 1 : kF - 1); - - // Because of invariant that intervals preceding the middle change - // cannot have common items at the end, - // move in reverse direction along a diagonal of common items. - const nCommonR = countCommonItemsR( - aStart, - aLastPrev, - bStart, - bLastPrev, - isCommon - ); - const aIndexPrevFirst = aLastPrev - nCommonR; - const bIndexPrevFirst = bLastPrev - nCommonR; - const aEndPreceding = aIndexPrevFirst + 1; - const bEndPreceding = bIndexPrevFirst + 1; - division.nChangePreceding = d - 1; - if (d - 1 === aEndPreceding + bEndPreceding - aStart - bStart) { - // Optimization: number of preceding changes in forward direction - // is equal to number of items in preceding interval, - // therefore it cannot contain any common items. - division.aEndPreceding = aStart; - division.bEndPreceding = bStart; - } else { - division.aEndPreceding = aEndPreceding; - division.bEndPreceding = bEndPreceding; - } - division.nCommonPreceding = nCommonR; - if (nCommonR !== 0) { - division.aCommonPreceding = aEndPreceding; - division.bCommonPreceding = bEndPreceding; - } - division.nCommonFollowing = nCommonF; - if (nCommonF !== 0) { - division.aCommonFollowing = aFirst + 1; - division.bCommonFollowing = bFirst + 1; - } - const aStartFollowing = aLast + 1; - const bStartFollowing = bFirst + nCommonF + 1; - division.nChangeFollowing = d - 1; - if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) { - // Optimization: number of changes in reverse direction - // is equal to number of items in following interval, - // therefore it cannot contain any common items. - division.aStartFollowing = aEnd; - division.bStartFollowing = bEnd; - } else { - division.aStartFollowing = aStartFollowing; - division.bStartFollowing = bStartFollowing; - } - return true; - } - } - } - return false; - }; - - // A complete function to extend reverse paths from (d - 1) to d changes. - // Return true if a path overlaps forward path of d changes in its diagonal. - const extendOverlappablePathsR = ( - d, - aStart, - aEnd, - bStart, - bEnd, - isCommon, - aIndexesF, - iMaxF, - aIndexesR, - iMaxR, - division // update prop values if return true - ) => { - const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR - const aLength = aEnd - aStart; - const bLength = bEnd - bStart; - const baDeltaLength = bLength - aLength; // kR = kF + baDeltaLength - - // Range of diagonals in which forward and reverse paths might overlap. - const kMinOverlapR = baDeltaLength - d; // -d <= kF - const kMaxOverlapR = baDeltaLength + d; // kF <= d - - let aIndexPrev1 = NOT_YET_SET; // prev value of [iR - 1] in next iteration - - // Optimization: skip diagonals in which paths cannot ever overlap. - const nR = d < iMaxR ? d : iMaxR; - - // The diagonals kR = d - 2 * iR are odd when d is odd and even when d is even. - for (let iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) { - // To get first point of path segment, move one change in reverse direction - // from last point of previous path segment in an adjacent diagonal. - // In first iteration when iR === 0 and kR === d always insert. - // In last possible iteration when iR === d and kR === -d always delete. - const insert = iR === 0 || (iR !== d && aIndexesR[iR] < aIndexPrev1); - const aLastPrev = insert ? aIndexesR[iR] : aIndexPrev1; - const aFirst = insert - ? aLastPrev // vertical to insert from b - : aLastPrev - 1; // horizontal to delete from a - - // To get last point of path segment, move along diagonal of common items. - const bFirst = bR + aFirst - kR; - const nCommonR = countCommonItemsR( - aStart, - aFirst - 1, - bStart, - bFirst - 1, - isCommon - ); - const aLast = aFirst - nCommonR; - aIndexPrev1 = aIndexesR[iR]; - aIndexesR[iR] = aLast; - if (kMinOverlapR <= kR && kR <= kMaxOverlapR) { - // Solve for iF of forward path with d changes in diagonal kR: - // kF = kR - baDeltaLength - // kF = 2 * iF - d - const iF = (d + (kR - baDeltaLength)) / 2; - - // If this reverse path overlaps the forward path in this diagonal, - // then this is a middle change of the index intervals. - if (iF <= iMaxF && aLast - 1 <= aIndexesF[iF]) { - const bLast = bFirst - nCommonR; - division.nChangePreceding = d; - if (d === aLast + bLast - aStart - bStart) { - // Optimization: number of changes in reverse direction - // is equal to number of items in preceding interval, - // therefore it cannot contain any common items. - division.aEndPreceding = aStart; - division.bEndPreceding = bStart; - } else { - division.aEndPreceding = aLast; - division.bEndPreceding = bLast; - } - division.nCommonPreceding = nCommonR; - if (nCommonR !== 0) { - // The last point of reverse path segment is start of common subsequence. - division.aCommonPreceding = aLast; - division.bCommonPreceding = bLast; - } - division.nChangeFollowing = d - 1; - if (d === 1) { - // There is no previous path segment. - division.nCommonFollowing = 0; - division.aStartFollowing = aEnd; - division.bStartFollowing = bEnd; - } else { - // Unlike the Myers algorithm which finds only the middle “snake” - // this package can find two common subsequences per division. - // Last point of previous path segment is on an adjacent diagonal. - const bLastPrev = bR + aLastPrev - (insert ? kR - 1 : kR + 1); - - // Because of invariant that intervals following the middle change - // cannot have common items at the start, - // move in forward direction along a diagonal of common items. - const nCommonF = countCommonItemsF( - aLastPrev, - aEnd, - bLastPrev, - bEnd, - isCommon - ); - division.nCommonFollowing = nCommonF; - if (nCommonF !== 0) { - // The last point of reverse path segment is start of common subsequence. - division.aCommonFollowing = aLastPrev; - division.bCommonFollowing = bLastPrev; - } - const aStartFollowing = aLastPrev + nCommonF; // aFirstPrev - const bStartFollowing = bLastPrev + nCommonF; // bFirstPrev - - if (d - 1 === aEnd + bEnd - aStartFollowing - bStartFollowing) { - // Optimization: number of changes in forward direction - // is equal to number of items in following interval, - // therefore it cannot contain any common items. - division.aStartFollowing = aEnd; - division.bStartFollowing = bEnd; - } else { - division.aStartFollowing = aStartFollowing; - division.bStartFollowing = bStartFollowing; - } - } - return true; - } - } - } - return false; - }; - - // Given index intervals and input function to compare items at indexes, - // divide at the middle change. - // - // DO NOT CALL if start === end, because interval cannot contain common items - // and because this function will throw the “no overlap” error. - const divide = ( - nChange, - aStart, - aEnd, - bStart, - bEnd, - isCommon, - aIndexesF, - aIndexesR, - division // output - ) => { - const bF = bStart - aStart; // bIndex = bF + aIndex - kF - const bR = bEnd - aEnd; // bIndex = bR + aIndex - kR - const aLength = aEnd - aStart; - const bLength = bEnd - bStart; - - // Because graph has square or portrait orientation, - // length difference is minimum number of items to insert from b. - // Corresponding forward and reverse diagonals in graph - // depend on length difference of the sequences: - // kF = kR - baDeltaLength - // kR = kF + baDeltaLength - const baDeltaLength = bLength - aLength; - - // Optimization: max diagonal in graph intersects corner of shorter side. - let iMaxF = aLength; - let iMaxR = aLength; - - // Initialize no changes yet in forward or reverse direction: - aIndexesF[0] = aStart - 1; // at open start of interval, outside closed start - aIndexesR[0] = aEnd; // at open end of interval - - if (baDeltaLength % 2 === 0) { - // The number of changes in paths is 2 * d if length difference is even. - const dMin = (nChange || baDeltaLength) / 2; - const dMax = (aLength + bLength) / 2; - for (let d = 1; d <= dMax; d += 1) { - iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); - if (d < dMin) { - iMaxR = extendPathsR(d, aStart, bStart, bR, isCommon, aIndexesR, iMaxR); - } else if ( - // If a reverse path overlaps a forward path in the same diagonal, - // return a division of the index intervals at the middle change. - extendOverlappablePathsR( - d, - aStart, - aEnd, - bStart, - bEnd, - isCommon, - aIndexesF, - iMaxF, - aIndexesR, - iMaxR, - division - ) - ) { - return; - } - } - } else { - // The number of changes in paths is 2 * d - 1 if length difference is odd. - const dMin = ((nChange || baDeltaLength) + 1) / 2; - const dMax = (aLength + bLength + 1) / 2; - - // Unroll first half iteration so loop extends the relevant pairs of paths. - // Because of invariant that intervals have no common items at start or end, - // and limitation not to call divide with empty intervals, - // therefore it cannot be called if a forward path with one change - // would overlap a reverse path with no changes, even if dMin === 1. - let d = 1; - iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); - for (d += 1; d <= dMax; d += 1) { - iMaxR = extendPathsR( - d - 1, - aStart, - bStart, - bR, - isCommon, - aIndexesR, - iMaxR - ); - if (d < dMin) { - iMaxF = extendPathsF(d, aEnd, bEnd, bF, isCommon, aIndexesF, iMaxF); - } else if ( - // If a forward path overlaps a reverse path in the same diagonal, - // return a division of the index intervals at the middle change. - extendOverlappablePathsF( - d, - aStart, - aEnd, - bStart, - bEnd, - isCommon, - aIndexesF, - iMaxF, - aIndexesR, - iMaxR, - division - ) - ) { - return; - } - } - } - - /* istanbul ignore next */ - throw new Error( - `${pkg}: no overlap aStart=${aStart} aEnd=${aEnd} bStart=${bStart} bEnd=${bEnd}` - ); - }; - - // Given index intervals and input function to compare items at indexes, - // return by output function the number of adjacent items and starting indexes - // of each common subsequence. Divide and conquer with only linear space. - // - // The index intervals are half open [start, end) like array slice method. - // DO NOT CALL if start === end, because interval cannot contain common items - // and because divide function will throw the “no overlap” error. - const findSubsequences = ( - nChange, - aStart, - aEnd, - bStart, - bEnd, - transposed, - callbacks, - aIndexesF, - aIndexesR, - division // temporary memory, not input nor output - ) => { - if (bEnd - bStart < aEnd - aStart) { - // Transpose graph so it has portrait instead of landscape orientation. - // Always compare shorter to longer sequence for consistency and optimization. - transposed = !transposed; - if (transposed && callbacks.length === 1) { - // Lazily wrap callback functions to swap args if graph is transposed. - const {foundSubsequence, isCommon} = callbacks[0]; - callbacks[1] = { - foundSubsequence: (nCommon, bCommon, aCommon) => { - foundSubsequence(nCommon, aCommon, bCommon); - }, - isCommon: (bIndex, aIndex) => isCommon(aIndex, bIndex) - }; - } - const tStart = aStart; - const tEnd = aEnd; - aStart = bStart; - aEnd = bEnd; - bStart = tStart; - bEnd = tEnd; - } - const {foundSubsequence, isCommon} = callbacks[transposed ? 1 : 0]; - - // Divide the index intervals at the middle change. - divide( - nChange, - aStart, - aEnd, - bStart, - bEnd, - isCommon, - aIndexesF, - aIndexesR, - division - ); - const { - nChangePreceding, - aEndPreceding, - bEndPreceding, - nCommonPreceding, - aCommonPreceding, - bCommonPreceding, - nCommonFollowing, - aCommonFollowing, - bCommonFollowing, - nChangeFollowing, - aStartFollowing, - bStartFollowing - } = division; - - // Unless either index interval is empty, they might contain common items. - if (aStart < aEndPreceding && bStart < bEndPreceding) { - // Recursely find and return common subsequences preceding the division. - findSubsequences( - nChangePreceding, - aStart, - aEndPreceding, - bStart, - bEndPreceding, - transposed, - callbacks, - aIndexesF, - aIndexesR, - division - ); - } - - // Return common subsequences that are adjacent to the middle change. - if (nCommonPreceding !== 0) { - foundSubsequence(nCommonPreceding, aCommonPreceding, bCommonPreceding); - } - if (nCommonFollowing !== 0) { - foundSubsequence(nCommonFollowing, aCommonFollowing, bCommonFollowing); - } - - // Unless either index interval is empty, they might contain common items. - if (aStartFollowing < aEnd && bStartFollowing < bEnd) { - // Recursely find and return common subsequences following the division. - findSubsequences( - nChangeFollowing, - aStartFollowing, - aEnd, - bStartFollowing, - bEnd, - transposed, - callbacks, - aIndexesF, - aIndexesR, - division - ); - } - }; - const validateLength = (name, arg) => { - if (typeof arg !== 'number') { - throw new TypeError(`${pkg}: ${name} typeof ${typeof arg} is not a number`); - } - if (!Number.isSafeInteger(arg)) { - throw new RangeError(`${pkg}: ${name} value ${arg} is not a safe integer`); - } - if (arg < 0) { - throw new RangeError(`${pkg}: ${name} value ${arg} is a negative integer`); - } - }; - const validateCallback = (name, arg) => { - const type = typeof arg; - if (type !== 'function') { - throw new TypeError(`${pkg}: ${name} typeof ${type} is not a function`); - } - }; - - // Compare items in two sequences to find a longest common subsequence. - // Given lengths of sequences and input function to compare items at indexes, - // return by output function the number of adjacent items and starting indexes - // of each common subsequence. - function diffSequence(aLength, bLength, isCommon, foundSubsequence) { - validateLength('aLength', aLength); - validateLength('bLength', bLength); - validateCallback('isCommon', isCommon); - validateCallback('foundSubsequence', foundSubsequence); - - // Count common items from the start in the forward direction. - const nCommonF = countCommonItemsF(0, aLength, 0, bLength, isCommon); - if (nCommonF !== 0) { - foundSubsequence(nCommonF, 0, 0); - } - - // Unless both sequences consist of common items only, - // find common items in the half-trimmed index intervals. - if (aLength !== nCommonF || bLength !== nCommonF) { - // Invariant: intervals do not have common items at the start. - // The start of an index interval is closed like array slice method. - const aStart = nCommonF; - const bStart = nCommonF; - - // Count common items from the end in the reverse direction. - const nCommonR = countCommonItemsR( - aStart, - aLength - 1, - bStart, - bLength - 1, - isCommon - ); - - // Invariant: intervals do not have common items at the end. - // The end of an index interval is open like array slice method. - const aEnd = aLength - nCommonR; - const bEnd = bLength - nCommonR; - - // Unless one sequence consists of common items only, - // therefore the other trimmed index interval consists of changes only, - // find common items in the trimmed index intervals. - const nCommonFR = nCommonF + nCommonR; - if (aLength !== nCommonFR && bLength !== nCommonFR) { - const nChange = 0; // number of change items is not yet known - const transposed = false; // call the original unwrapped functions - const callbacks = [ - { - foundSubsequence, - isCommon - } - ]; - - // Indexes in sequence a of last points in furthest reaching paths - // from outside the start at top left in the forward direction: - const aIndexesF = [NOT_YET_SET]; - // from the end at bottom right in the reverse direction: - const aIndexesR = [NOT_YET_SET]; - - // Initialize one object as output of all calls to divide function. - const division = { - aCommonFollowing: NOT_YET_SET, - aCommonPreceding: NOT_YET_SET, - aEndPreceding: NOT_YET_SET, - aStartFollowing: NOT_YET_SET, - bCommonFollowing: NOT_YET_SET, - bCommonPreceding: NOT_YET_SET, - bEndPreceding: NOT_YET_SET, - bStartFollowing: NOT_YET_SET, - nChangeFollowing: NOT_YET_SET, - nChangePreceding: NOT_YET_SET, - nCommonFollowing: NOT_YET_SET, - nCommonPreceding: NOT_YET_SET - }; - - // Find and return common subsequences in the trimmed index intervals. - findSubsequences( - nChange, - aStart, - aEnd, - bStart, - bEnd, - transposed, - callbacks, - aIndexesF, - aIndexesR, - division - ); - } - if (nCommonR !== 0) { - foundSubsequence(nCommonR, aEnd, bEnd); - } - } - } - return build; -} - -var buildExports = /*@__PURE__*/ requireBuild(); -var diffSequences = /*@__PURE__*/getDefaultExportFromCjs(buildExports); - -function formatTrailingSpaces(line, trailingSpaceFormatter) { - return line.replace(/\s+$/, (match) => trailingSpaceFormatter(match)); -} -function printDiffLine(line, isFirstOrLast, color, indicator, trailingSpaceFormatter, emptyFirstOrLastLinePlaceholder) { - return line.length !== 0 ? color(`${indicator} ${formatTrailingSpaces(line, trailingSpaceFormatter)}`) : indicator !== " " ? color(indicator) : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 ? color(`${indicator} ${emptyFirstOrLastLinePlaceholder}`) : ""; -} -function printDeleteLine(line, isFirstOrLast, { aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { - return printDiffLine(line, isFirstOrLast, aColor, aIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); -} -function printInsertLine(line, isFirstOrLast, { bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { - return printDiffLine(line, isFirstOrLast, bColor, bIndicator, changeLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); -} -function printCommonLine(line, isFirstOrLast, { commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder }) { - return printDiffLine(line, isFirstOrLast, commonColor, commonIndicator, commonLineTrailingSpaceColor, emptyFirstOrLastLinePlaceholder); -} -// In GNU diff format, indexes are one-based instead of zero-based. -function createPatchMark(aStart, aEnd, bStart, bEnd, { patchColor }) { - return patchColor(`@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@`); -} -// jest --no-expand -// -// Given array of aligned strings with inverse highlight formatting, -// return joined lines with diff formatting (and patch marks, if needed). -function joinAlignedDiffsNoExpand(diffs, options) { - const iLength = diffs.length; - const nContextLines = options.contextLines; - const nContextLines2 = nContextLines + nContextLines; - // First pass: count output lines and see if it has patches. - let jLength = iLength; - let hasExcessAtStartOrEnd = false; - let nExcessesBetweenChanges = 0; - let i = 0; - while (i !== iLength) { - const iStart = i; - while (i !== iLength && diffs[i][0] === DIFF_EQUAL) { - i += 1; - } - if (iStart !== i) { - if (iStart === 0) { - // at start - if (i > nContextLines) { - jLength -= i - nContextLines; - hasExcessAtStartOrEnd = true; - } - } else if (i === iLength) { - // at end - const n = i - iStart; - if (n > nContextLines) { - jLength -= n - nContextLines; - hasExcessAtStartOrEnd = true; - } - } else { - // between changes - const n = i - iStart; - if (n > nContextLines2) { - jLength -= n - nContextLines2; - nExcessesBetweenChanges += 1; - } - } - } - while (i !== iLength && diffs[i][0] !== DIFF_EQUAL) { - i += 1; - } - } - const hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd; - if (nExcessesBetweenChanges !== 0) { - jLength += nExcessesBetweenChanges + 1; - } else if (hasExcessAtStartOrEnd) { - jLength += 1; - } - const jLast = jLength - 1; - const lines = []; - let jPatchMark = 0; - if (hasPatch) { - lines.push(""); - } - // Indexes of expected or received lines in current patch: - let aStart = 0; - let bStart = 0; - let aEnd = 0; - let bEnd = 0; - const pushCommonLine = (line) => { - const j = lines.length; - lines.push(printCommonLine(line, j === 0 || j === jLast, options)); - aEnd += 1; - bEnd += 1; - }; - const pushDeleteLine = (line) => { - const j = lines.length; - lines.push(printDeleteLine(line, j === 0 || j === jLast, options)); - aEnd += 1; - }; - const pushInsertLine = (line) => { - const j = lines.length; - lines.push(printInsertLine(line, j === 0 || j === jLast, options)); - bEnd += 1; - }; - // Second pass: push lines with diff formatting (and patch marks, if needed). - i = 0; - while (i !== iLength) { - let iStart = i; - while (i !== iLength && diffs[i][0] === DIFF_EQUAL) { - i += 1; - } - if (iStart !== i) { - if (iStart === 0) { - // at beginning - if (i > nContextLines) { - iStart = i - nContextLines; - aStart = iStart; - bStart = iStart; - aEnd = aStart; - bEnd = bStart; - } - for (let iCommon = iStart; iCommon !== i; iCommon += 1) { - pushCommonLine(diffs[iCommon][1]); - } - } else if (i === iLength) { - // at end - const iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; - for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { - pushCommonLine(diffs[iCommon][1]); - } - } else { - // between changes - const nCommon = i - iStart; - if (nCommon > nContextLines2) { - const iEnd = iStart + nContextLines; - for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { - pushCommonLine(diffs[iCommon][1]); - } - lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); - jPatchMark = lines.length; - lines.push(""); - const nOmit = nCommon - nContextLines2; - aStart = aEnd + nOmit; - bStart = bEnd + nOmit; - aEnd = aStart; - bEnd = bStart; - for (let iCommon = i - nContextLines; iCommon !== i; iCommon += 1) { - pushCommonLine(diffs[iCommon][1]); - } - } else { - for (let iCommon = iStart; iCommon !== i; iCommon += 1) { - pushCommonLine(diffs[iCommon][1]); - } - } - } - } - while (i !== iLength && diffs[i][0] === DIFF_DELETE) { - pushDeleteLine(diffs[i][1]); - i += 1; - } - while (i !== iLength && diffs[i][0] === DIFF_INSERT) { - pushInsertLine(diffs[i][1]); - i += 1; - } - } - if (hasPatch) { - lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); - } - return lines.join("\n"); -} -// jest --expand -// -// Given array of aligned strings with inverse highlight formatting, -// return joined lines with diff formatting. -function joinAlignedDiffsExpand(diffs, options) { - return diffs.map((diff, i, diffs) => { - const line = diff[1]; - const isFirstOrLast = i === 0 || i === diffs.length - 1; - switch (diff[0]) { - case DIFF_DELETE: return printDeleteLine(line, isFirstOrLast, options); - case DIFF_INSERT: return printInsertLine(line, isFirstOrLast, options); - default: return printCommonLine(line, isFirstOrLast, options); - } - }).join("\n"); -} - -const noColor = (string) => string; -const DIFF_CONTEXT_DEFAULT = 5; -const DIFF_TRUNCATE_THRESHOLD_DEFAULT = 0; -function getDefaultOptions() { - return { - aAnnotation: "Expected", - aColor: c.green, - aIndicator: "-", - bAnnotation: "Received", - bColor: c.red, - bIndicator: "+", - changeColor: c.inverse, - changeLineTrailingSpaceColor: noColor, - commonColor: c.dim, - commonIndicator: " ", - commonLineTrailingSpaceColor: noColor, - compareKeys: undefined, - contextLines: DIFF_CONTEXT_DEFAULT, - emptyFirstOrLastLinePlaceholder: "", - expand: false, - includeChangeCounts: false, - omitAnnotationLines: false, - patchColor: c.yellow, - printBasicPrototype: false, - truncateThreshold: DIFF_TRUNCATE_THRESHOLD_DEFAULT, - truncateAnnotation: "... Diff result is truncated", - truncateAnnotationColor: noColor - }; -} -function getCompareKeys(compareKeys) { - return compareKeys && typeof compareKeys === "function" ? compareKeys : undefined; -} -function getContextLines(contextLines) { - return typeof contextLines === "number" && Number.isSafeInteger(contextLines) && contextLines >= 0 ? contextLines : DIFF_CONTEXT_DEFAULT; -} -// Pure function returns options with all properties. -function normalizeDiffOptions(options = {}) { - return { - ...getDefaultOptions(), - ...options, - compareKeys: getCompareKeys(options.compareKeys), - contextLines: getContextLines(options.contextLines) - }; -} - -function isEmptyString(lines) { - return lines.length === 1 && lines[0].length === 0; -} -function countChanges(diffs) { - let a = 0; - let b = 0; - diffs.forEach((diff) => { - switch (diff[0]) { - case DIFF_DELETE: - a += 1; - break; - case DIFF_INSERT: - b += 1; - break; - } - }); - return { - a, - b - }; -} -function printAnnotation({ aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator, includeChangeCounts, omitAnnotationLines }, changeCounts) { - if (omitAnnotationLines) { - return ""; - } - let aRest = ""; - let bRest = ""; - if (includeChangeCounts) { - const aCount = String(changeCounts.a); - const bCount = String(changeCounts.b); - // Padding right aligns the ends of the annotations. - const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length; - const aAnnotationPadding = " ".repeat(Math.max(0, baAnnotationLengthDiff)); - const bAnnotationPadding = " ".repeat(Math.max(0, -baAnnotationLengthDiff)); - // Padding left aligns the ends of the counts. - const baCountLengthDiff = bCount.length - aCount.length; - const aCountPadding = " ".repeat(Math.max(0, baCountLengthDiff)); - const bCountPadding = " ".repeat(Math.max(0, -baCountLengthDiff)); - aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`; - bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`; - } - const a = `${aIndicator} ${aAnnotation}${aRest}`; - const b = `${bIndicator} ${bAnnotation}${bRest}`; - return `${aColor(a)}\n${bColor(b)}\n\n`; -} -function printDiffLines(diffs, truncated, options) { - return printAnnotation(options, countChanges(diffs)) + (options.expand ? joinAlignedDiffsExpand(diffs, options) : joinAlignedDiffsNoExpand(diffs, options)) + (truncated ? options.truncateAnnotationColor(`\n${options.truncateAnnotation}`) : ""); -} -// Compare two arrays of strings line-by-line. Format as comparison lines. -function diffLinesUnified(aLines, bLines, options) { - const normalizedOptions = normalizeDiffOptions(options); - const [diffs, truncated] = diffLinesRaw(isEmptyString(aLines) ? [] : aLines, isEmptyString(bLines) ? [] : bLines, normalizedOptions); - return printDiffLines(diffs, truncated, normalizedOptions); -} -// Given two pairs of arrays of strings: -// Compare the pair of comparison arrays line-by-line. -// Format the corresponding lines in the pair of displayable arrays. -function diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options) { - if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { - aLinesDisplay = []; - aLinesCompare = []; - } - if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { - bLinesDisplay = []; - bLinesCompare = []; - } - if (aLinesDisplay.length !== aLinesCompare.length || bLinesDisplay.length !== bLinesCompare.length) { - // Fall back to diff of display lines. - return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); - } - const [diffs, truncated] = diffLinesRaw(aLinesCompare, bLinesCompare, options); - // Replace comparison lines with displayable lines. - let aIndex = 0; - let bIndex = 0; - diffs.forEach((diff) => { - switch (diff[0]) { - case DIFF_DELETE: - diff[1] = aLinesDisplay[aIndex]; - aIndex += 1; - break; - case DIFF_INSERT: - diff[1] = bLinesDisplay[bIndex]; - bIndex += 1; - break; - default: - diff[1] = bLinesDisplay[bIndex]; - aIndex += 1; - bIndex += 1; - } - }); - return printDiffLines(diffs, truncated, normalizeDiffOptions(options)); -} -// Compare two arrays of strings line-by-line. -function diffLinesRaw(aLines, bLines, options) { - const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false; - const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0); - const aLength = truncate ? Math.min(aLines.length, truncateThreshold) : aLines.length; - const bLength = truncate ? Math.min(bLines.length, truncateThreshold) : bLines.length; - const truncated = aLength !== aLines.length || bLength !== bLines.length; - const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex]; - const diffs = []; - let aIndex = 0; - let bIndex = 0; - const foundSubsequence = (nCommon, aCommon, bCommon) => { - for (; aIndex !== aCommon; aIndex += 1) { - diffs.push(new Diff(DIFF_DELETE, aLines[aIndex])); - } - for (; bIndex !== bCommon; bIndex += 1) { - diffs.push(new Diff(DIFF_INSERT, bLines[bIndex])); - } - for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) { - diffs.push(new Diff(DIFF_EQUAL, bLines[bIndex])); - } - }; - diffSequences(aLength, bLength, isCommon, foundSubsequence); - // After the last common subsequence, push remaining change items. - for (; aIndex !== aLength; aIndex += 1) { - diffs.push(new Diff(DIFF_DELETE, aLines[aIndex])); - } - for (; bIndex !== bLength; bIndex += 1) { - diffs.push(new Diff(DIFF_INSERT, bLines[bIndex])); - } - return [diffs, truncated]; -} - -// get the type of a value with handling the edge cases like `typeof []` -// and `typeof null` -function getType(value) { - if (value === undefined) { - return "undefined"; - } else if (value === null) { - return "null"; - } else if (Array.isArray(value)) { - return "array"; - } else if (typeof value === "boolean") { - return "boolean"; - } else if (typeof value === "function") { - return "function"; - } else if (typeof value === "number") { - return "number"; - } else if (typeof value === "string") { - return "string"; - } else if (typeof value === "bigint") { - return "bigint"; - } else if (typeof value === "object") { - if (value != null) { - if (value.constructor === RegExp) { - return "regexp"; - } else if (value.constructor === Map) { - return "map"; - } else if (value.constructor === Set) { - return "set"; - } else if (value.constructor === Date) { - return "date"; - } - } - return "object"; - } else if (typeof value === "symbol") { - return "symbol"; - } - throw new Error(`value of unknown type: ${value}`); -} - -// platforms compatible -function getNewLineSymbol(string) { - return string.includes("\r\n") ? "\r\n" : "\n"; -} -function diffStrings(a, b, options) { - const truncate = (options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? false; - const truncateThreshold = Math.max(Math.floor((options === null || options === void 0 ? void 0 : options.truncateThreshold) ?? 0), 0); - let aLength = a.length; - let bLength = b.length; - if (truncate) { - const aMultipleLines = a.includes("\n"); - const bMultipleLines = b.includes("\n"); - const aNewLineSymbol = getNewLineSymbol(a); - const bNewLineSymbol = getNewLineSymbol(b); - // multiple-lines string expects a newline to be appended at the end - const _a = aMultipleLines ? `${a.split(aNewLineSymbol, truncateThreshold).join(aNewLineSymbol)}\n` : a; - const _b = bMultipleLines ? `${b.split(bNewLineSymbol, truncateThreshold).join(bNewLineSymbol)}\n` : b; - aLength = _a.length; - bLength = _b.length; - } - const truncated = aLength !== a.length || bLength !== b.length; - const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex]; - let aIndex = 0; - let bIndex = 0; - const diffs = []; - const foundSubsequence = (nCommon, aCommon, bCommon) => { - if (aIndex !== aCommon) { - diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex, aCommon))); - } - if (bIndex !== bCommon) { - diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex, bCommon))); - } - aIndex = aCommon + nCommon; - bIndex = bCommon + nCommon; - diffs.push(new Diff(DIFF_EQUAL, b.slice(bCommon, bIndex))); - }; - diffSequences(aLength, bLength, isCommon, foundSubsequence); - // After the last common subsequence, push remaining change items. - if (aIndex !== aLength) { - diffs.push(new Diff(DIFF_DELETE, a.slice(aIndex))); - } - if (bIndex !== bLength) { - diffs.push(new Diff(DIFF_INSERT, b.slice(bIndex))); - } - return [diffs, truncated]; -} - -// Given change op and array of diffs, return concatenated string: -// * include common strings -// * include change strings which have argument op with changeColor -// * exclude change strings which have opposite op -function concatenateRelevantDiffs(op, diffs, changeColor) { - return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op && diff[1].length !== 0 ? changeColor(diff[1]) : ""), ""); -} -// Encapsulate change lines until either a common newline or the end. -class ChangeBuffer { - op; - line; - lines; - changeColor; - constructor(op, changeColor) { - this.op = op; - this.line = []; - this.lines = []; - this.changeColor = changeColor; - } - pushSubstring(substring) { - this.pushDiff(new Diff(this.op, substring)); - } - pushLine() { - // Assume call only if line has at least one diff, - // therefore an empty line must have a diff which has an empty string. - // If line has multiple diffs, then assume it has a common diff, - // therefore change diffs have change color; - // otherwise then it has line color only. - this.lines.push(this.line.length !== 1 ? new Diff(this.op, concatenateRelevantDiffs(this.op, this.line, this.changeColor)) : this.line[0][0] === this.op ? this.line[0] : new Diff(this.op, this.line[0][1])); - this.line.length = 0; - } - isLineEmpty() { - return this.line.length === 0; - } - // Minor input to buffer. - pushDiff(diff) { - this.line.push(diff); - } - // Main input to buffer. - align(diff) { - const string = diff[1]; - if (string.includes("\n")) { - const substrings = string.split("\n"); - const iLast = substrings.length - 1; - substrings.forEach((substring, i) => { - if (i < iLast) { - // The first substring completes the current change line. - // A middle substring is a change line. - this.pushSubstring(substring); - this.pushLine(); - } else if (substring.length !== 0) { - // The last substring starts a change line, if it is not empty. - // Important: This non-empty condition also automatically omits - // the newline appended to the end of expected and received strings. - this.pushSubstring(substring); - } - }); - } else { - // Append non-multiline string to current change line. - this.pushDiff(diff); - } - } - // Output from buffer. - moveLinesTo(lines) { - if (!this.isLineEmpty()) { - this.pushLine(); - } - lines.push(...this.lines); - this.lines.length = 0; - } -} -// Encapsulate common and change lines. -class CommonBuffer { - deleteBuffer; - insertBuffer; - lines; - constructor(deleteBuffer, insertBuffer) { - this.deleteBuffer = deleteBuffer; - this.insertBuffer = insertBuffer; - this.lines = []; - } - pushDiffCommonLine(diff) { - this.lines.push(diff); - } - pushDiffChangeLines(diff) { - const isDiffEmpty = diff[1].length === 0; - // An empty diff string is redundant, unless a change line is empty. - if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) { - this.deleteBuffer.pushDiff(diff); - } - if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) { - this.insertBuffer.pushDiff(diff); - } - } - flushChangeLines() { - this.deleteBuffer.moveLinesTo(this.lines); - this.insertBuffer.moveLinesTo(this.lines); - } - // Input to buffer. - align(diff) { - const op = diff[0]; - const string = diff[1]; - if (string.includes("\n")) { - const substrings = string.split("\n"); - const iLast = substrings.length - 1; - substrings.forEach((substring, i) => { - if (i === 0) { - const subdiff = new Diff(op, substring); - if (this.deleteBuffer.isLineEmpty() && this.insertBuffer.isLineEmpty()) { - // If both current change lines are empty, - // then the first substring is a common line. - this.flushChangeLines(); - this.pushDiffCommonLine(subdiff); - } else { - // If either current change line is non-empty, - // then the first substring completes the change lines. - this.pushDiffChangeLines(subdiff); - this.flushChangeLines(); - } - } else if (i < iLast) { - // A middle substring is a common line. - this.pushDiffCommonLine(new Diff(op, substring)); - } else if (substring.length !== 0) { - // The last substring starts a change line, if it is not empty. - // Important: This non-empty condition also automatically omits - // the newline appended to the end of expected and received strings. - this.pushDiffChangeLines(new Diff(op, substring)); - } - }); - } else { - // Append non-multiline string to current change lines. - // Important: It cannot be at the end following empty change lines, - // because newline appended to the end of expected and received strings. - this.pushDiffChangeLines(diff); - } - } - // Output from buffer. - getLines() { - this.flushChangeLines(); - return this.lines; - } -} -// Given diffs from expected and received strings, -// return new array of diffs split or joined into lines. -// -// To correctly align a change line at the end, the algorithm: -// * assumes that a newline was appended to the strings -// * omits the last newline from the output array -// -// Assume the function is not called: -// * if either expected or received is empty string -// * if neither expected nor received is multiline string -function getAlignedDiffs(diffs, changeColor) { - const deleteBuffer = new ChangeBuffer(DIFF_DELETE, changeColor); - const insertBuffer = new ChangeBuffer(DIFF_INSERT, changeColor); - const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); - diffs.forEach((diff) => { - switch (diff[0]) { - case DIFF_DELETE: - deleteBuffer.align(diff); - break; - case DIFF_INSERT: - insertBuffer.align(diff); - break; - default: commonBuffer.align(diff); - } - }); - return commonBuffer.getLines(); -} - -function hasCommonDiff(diffs, isMultiline) { - if (isMultiline) { - // Important: Ignore common newline that was appended to multiline strings! - const iLast = diffs.length - 1; - return diffs.some((diff, i) => diff[0] === DIFF_EQUAL && (i !== iLast || diff[1] !== "\n")); - } - return diffs.some((diff) => diff[0] === DIFF_EQUAL); -} -// Compare two strings character-by-character. -// Format as comparison lines in which changed substrings have inverse colors. -function diffStringsUnified(a, b, options) { - if (a !== b && a.length !== 0 && b.length !== 0) { - const isMultiline = a.includes("\n") || b.includes("\n"); - // getAlignedDiffs assumes that a newline was appended to the strings. - const [diffs, truncated] = diffStringsRaw(isMultiline ? `${a}\n` : a, isMultiline ? `${b}\n` : b, true, options); - if (hasCommonDiff(diffs, isMultiline)) { - const optionsNormalized = normalizeDiffOptions(options); - const lines = getAlignedDiffs(diffs, optionsNormalized.changeColor); - return printDiffLines(lines, truncated, optionsNormalized); - } - } - // Fall back to line-by-line diff. - return diffLinesUnified(a.split("\n"), b.split("\n"), options); -} -// Compare two strings character-by-character. -// Optionally clean up small common substrings, also known as chaff. -function diffStringsRaw(a, b, cleanup, options) { - const [diffs, truncated] = diffStrings(a, b, options); - if (cleanup) { - diff_cleanupSemantic(diffs); - } - return [diffs, truncated]; -} - -function getCommonMessage(message, options) { - const { commonColor } = normalizeDiffOptions(options); - return commonColor(message); -} -const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins; -const PLUGINS = [ - ReactTestComponent, - ReactElement, - DOMElement, - DOMCollection, - Immutable, - AsymmetricMatcher, - plugins.Error -]; -const FORMAT_OPTIONS = { - maxDepth: 20, - plugins: PLUGINS -}; -const FALLBACK_FORMAT_OPTIONS = { - callToJSON: false, - maxDepth: 8, - plugins: PLUGINS -}; -// Generate a string that will highlight the difference between two values -// with green and red. (similar to how github does code diffing) -/** -* @param a Expected value -* @param b Received value -* @param options Diff options -* @returns {string | null} a string diff -*/ -function diff(a, b, options) { - if (Object.is(a, b)) { - return ""; - } - const aType = getType(a); - let expectedType = aType; - let omitDifference = false; - if (aType === "object" && typeof a.asymmetricMatch === "function") { - if (a.$$typeof !== Symbol.for("jest.asymmetricMatcher")) { - // Do not know expected type of user-defined asymmetric matcher. - return undefined; - } - if (typeof a.getExpectedType !== "function") { - // For example, expect.anything() matches either null or undefined - return undefined; - } - expectedType = a.getExpectedType(); - // Primitive types boolean and number omit difference below. - // For example, omit difference for expect.stringMatching(regexp) - omitDifference = expectedType === "string"; - } - if (expectedType !== getType(b)) { - const { aAnnotation, aColor, aIndicator, bAnnotation, bColor, bIndicator } = normalizeDiffOptions(options); - const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); - let aDisplay = format(a, formatOptions); - let bDisplay = format(b, formatOptions); - // even if prettyFormat prints successfully big objects, - // large string can choke later on (concatenation? RPC?), - // so truncate it to a reasonable length here. - // (For example, playwright's ElementHandle can become about 200_000_000 length string) - const MAX_LENGTH = 1e5; - function truncate(s) { - return s.length <= MAX_LENGTH ? s : `${s.slice(0, MAX_LENGTH)}...`; - } - aDisplay = truncate(aDisplay); - bDisplay = truncate(bDisplay); - const aDiff = `${aColor(`${aIndicator} ${aAnnotation}:`)} \n${aDisplay}`; - const bDiff = `${bColor(`${bIndicator} ${bAnnotation}:`)} \n${bDisplay}`; - return `${aDiff}\n\n${bDiff}`; - } - if (omitDifference) { - return undefined; - } - switch (aType) { - case "string": return diffLinesUnified(a.split("\n"), b.split("\n"), options); - case "boolean": - case "number": return comparePrimitive(a, b, options); - case "map": return compareObjects(sortMap(a), sortMap(b), options); - case "set": return compareObjects(sortSet(a), sortSet(b), options); - default: return compareObjects(a, b, options); - } -} -function comparePrimitive(a, b, options) { - const aFormat = format(a, FORMAT_OPTIONS); - const bFormat = format(b, FORMAT_OPTIONS); - return aFormat === bFormat ? "" : diffLinesUnified(aFormat.split("\n"), bFormat.split("\n"), options); -} -function sortMap(map) { - return new Map(Array.from(map.entries()).sort()); -} -function sortSet(set) { - return new Set(Array.from(set.values()).sort()); -} -function compareObjects(a, b, options) { - let difference; - let hasThrown = false; - try { - const formatOptions = getFormatOptions(FORMAT_OPTIONS, options); - difference = getObjectsDifference(a, b, formatOptions, options); - } catch { - hasThrown = true; - } - const noDiffMessage = getCommonMessage(NO_DIFF_MESSAGE, options); - // If the comparison yields no results, compare again but this time - // without calling `toJSON`. It's also possible that toJSON might throw. - if (difference === undefined || difference === noDiffMessage) { - const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); - difference = getObjectsDifference(a, b, formatOptions, options); - if (difference !== noDiffMessage && !hasThrown) { - difference = `${getCommonMessage(SIMILAR_MESSAGE, options)}\n\n${difference}`; - } - } - return difference; -} -function getFormatOptions(formatOptions, options) { - const { compareKeys, printBasicPrototype, maxDepth } = normalizeDiffOptions(options); - return { - ...formatOptions, - compareKeys, - printBasicPrototype, - maxDepth: maxDepth ?? formatOptions.maxDepth - }; -} -function getObjectsDifference(a, b, formatOptions, options) { - const formatOptionsZeroIndent = { - ...formatOptions, - indent: 0 - }; - const aCompare = format(a, formatOptionsZeroIndent); - const bCompare = format(b, formatOptionsZeroIndent); - if (aCompare === bCompare) { - return getCommonMessage(NO_DIFF_MESSAGE, options); - } else { - const aDisplay = format(a, formatOptions); - const bDisplay = format(b, formatOptions); - return diffLinesUnified2(aDisplay.split("\n"), bDisplay.split("\n"), aCompare.split("\n"), bCompare.split("\n"), options); - } -} -const MAX_DIFF_STRING_LENGTH = 2e4; -function isAsymmetricMatcher(data) { - const type = getType$1(data); - return type === "Object" && typeof data.asymmetricMatch === "function"; -} -function isReplaceable(obj1, obj2) { - const obj1Type = getType$1(obj1); - const obj2Type = getType$1(obj2); - return obj1Type === obj2Type && (obj1Type === "Object" || obj1Type === "Array"); -} -function printDiffOrStringify(received, expected, options) { - const { aAnnotation, bAnnotation } = normalizeDiffOptions(options); - if (typeof expected === "string" && typeof received === "string" && expected.length > 0 && received.length > 0 && expected.length <= MAX_DIFF_STRING_LENGTH && received.length <= MAX_DIFF_STRING_LENGTH && expected !== received) { - if (expected.includes("\n") || received.includes("\n")) { - return diffStringsUnified(expected, received, options); - } - const [diffs] = diffStringsRaw(expected, received, true); - const hasCommonDiff = diffs.some((diff) => diff[0] === DIFF_EQUAL); - const printLabel = getLabelPrinter(aAnnotation, bAnnotation); - const expectedLine = printLabel(aAnnotation) + printExpected(getCommonAndChangedSubstrings(diffs, DIFF_DELETE, hasCommonDiff)); - const receivedLine = printLabel(bAnnotation) + printReceived(getCommonAndChangedSubstrings(diffs, DIFF_INSERT, hasCommonDiff)); - return `${expectedLine}\n${receivedLine}`; - } - // if (isLineDiffable(expected, received)) { - const clonedExpected = deepClone(expected, { forceWritable: true }); - const clonedReceived = deepClone(received, { forceWritable: true }); - const { replacedExpected, replacedActual } = replaceAsymmetricMatcher(clonedReceived, clonedExpected); - const difference = diff(replacedExpected, replacedActual, options); - return difference; - // } - // const printLabel = getLabelPrinter(aAnnotation, bAnnotation) - // const expectedLine = printLabel(aAnnotation) + printExpected(expected) - // const receivedLine - // = printLabel(bAnnotation) - // + (stringify(expected) === stringify(received) - // ? 'serializes to the same string' - // : printReceived(received)) - // return `${expectedLine}\n${receivedLine}` -} -function replaceAsymmetricMatcher(actual, expected, actualReplaced = new WeakSet(), expectedReplaced = new WeakSet()) { - // handle asymmetric Error.cause diff - if (actual instanceof Error && expected instanceof Error && typeof actual.cause !== "undefined" && typeof expected.cause === "undefined") { - delete actual.cause; - return { - replacedActual: actual, - replacedExpected: expected - }; - } - if (!isReplaceable(actual, expected)) { - return { - replacedActual: actual, - replacedExpected: expected - }; - } - if (actualReplaced.has(actual) || expectedReplaced.has(expected)) { - return { - replacedActual: actual, - replacedExpected: expected - }; - } - actualReplaced.add(actual); - expectedReplaced.add(expected); - getOwnProperties(expected).forEach((key) => { - const expectedValue = expected[key]; - const actualValue = actual[key]; - if (isAsymmetricMatcher(expectedValue)) { - if (expectedValue.asymmetricMatch(actualValue)) { - // When matcher matches, replace expected with actual value - // so they appear the same in the diff - expected[key] = actualValue; - } else if ("sample" in expectedValue && expectedValue.sample !== undefined && isReplaceable(actualValue, expectedValue.sample)) { - // For container matchers (ArrayContaining, ObjectContaining), unwrap and recursively process - // Matcher doesn't match: unwrap but keep structure to show mismatch - const replaced = replaceAsymmetricMatcher(actualValue, expectedValue.sample, actualReplaced, expectedReplaced); - actual[key] = replaced.replacedActual; - expected[key] = replaced.replacedExpected; - } - } else if (isAsymmetricMatcher(actualValue)) { - if (actualValue.asymmetricMatch(expectedValue)) { - actual[key] = expectedValue; - } else if ("sample" in actualValue && actualValue.sample !== undefined && isReplaceable(actualValue.sample, expectedValue)) { - const replaced = replaceAsymmetricMatcher(actualValue.sample, expectedValue, actualReplaced, expectedReplaced); - actual[key] = replaced.replacedActual; - expected[key] = replaced.replacedExpected; - } - } else if (isReplaceable(actualValue, expectedValue)) { - const replaced = replaceAsymmetricMatcher(actualValue, expectedValue, actualReplaced, expectedReplaced); - actual[key] = replaced.replacedActual; - expected[key] = replaced.replacedExpected; - } - }); - return { - replacedActual: actual, - replacedExpected: expected - }; -} -function getLabelPrinter(...strings) { - const maxLength = strings.reduce((max, string) => string.length > max ? string.length : max, 0); - return (string) => `${string}: ${" ".repeat(maxLength - string.length)}`; -} -const SPACE_SYMBOL = "·"; -function replaceTrailingSpaces(text) { - return text.replace(/\s+$/gm, (spaces) => SPACE_SYMBOL.repeat(spaces.length)); -} -function printReceived(object) { - return c.red(replaceTrailingSpaces(stringify(object))); -} -function printExpected(value) { - return c.green(replaceTrailingSpaces(stringify(value))); -} -function getCommonAndChangedSubstrings(diffs, op, hasCommonDiff) { - return diffs.reduce((reduced, diff) => reduced + (diff[0] === DIFF_EQUAL ? diff[1] : diff[0] === op ? hasCommonDiff ? c.inverse(diff[1]) : diff[1] : ""), ""); -} - -export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher }; diff --git a/vanilla/node_modules/@vitest/utils/dist/display.d.ts b/vanilla/node_modules/@vitest/utils/dist/display.d.ts deleted file mode 100644 index 576fa4c..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/display.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { PrettyFormatOptions } from '@vitest/pretty-format'; - -type Inspect = (value: unknown, options: Options) => string; -interface Options { - showHidden: boolean; - depth: number; - colors: boolean; - customInspect: boolean; - showProxy: boolean; - maxArrayLength: number; - breakLength: number; - truncate: number; - seen: unknown[]; - inspect: Inspect; - stylize: (value: string, styleType: string) => string; -} -type LoupeOptions = Partial<Options>; -interface StringifyOptions extends PrettyFormatOptions { - maxLength?: number; -} -declare function stringify(object: unknown, maxDepth?: number, { maxLength, ...options }?: StringifyOptions): string; -declare const formatRegExp: RegExp; -declare function format(...args: unknown[]): string; -declare function browserFormat(...args: unknown[]): string; -declare function inspect(obj: unknown, options?: LoupeOptions): string; -declare function objDisplay(obj: unknown, options?: LoupeOptions): string; - -export { browserFormat, format, formatRegExp, inspect, objDisplay, stringify }; -export type { LoupeOptions, StringifyOptions }; diff --git a/vanilla/node_modules/@vitest/utils/dist/display.js b/vanilla/node_modules/@vitest/utils/dist/display.js deleted file mode 100644 index 414e9c9..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/display.js +++ /dev/null @@ -1,742 +0,0 @@ -import { plugins, format as format$1 } from '@vitest/pretty-format'; - -const ansiColors = { - bold: ['1', '22'], - dim: ['2', '22'], - italic: ['3', '23'], - underline: ['4', '24'], - // 5 & 6 are blinking - inverse: ['7', '27'], - hidden: ['8', '28'], - strike: ['9', '29'], - // 10-20 are fonts - // 21-29 are resets for 1-9 - black: ['30', '39'], - red: ['31', '39'], - green: ['32', '39'], - yellow: ['33', '39'], - blue: ['34', '39'], - magenta: ['35', '39'], - cyan: ['36', '39'], - white: ['37', '39'], - brightblack: ['30;1', '39'], - brightred: ['31;1', '39'], - brightgreen: ['32;1', '39'], - brightyellow: ['33;1', '39'], - brightblue: ['34;1', '39'], - brightmagenta: ['35;1', '39'], - brightcyan: ['36;1', '39'], - brightwhite: ['37;1', '39'], - grey: ['90', '39'], -}; -const styles = { - special: 'cyan', - number: 'yellow', - bigint: 'yellow', - boolean: 'yellow', - undefined: 'grey', - null: 'bold', - string: 'green', - symbol: 'green', - date: 'magenta', - regexp: 'red', -}; -const truncator = '…'; -function colorise(value, styleType) { - const color = ansiColors[styles[styleType]] || ansiColors[styleType] || ''; - if (!color) { - return String(value); - } - return `\u001b[${color[0]}m${String(value)}\u001b[${color[1]}m`; -} -function normaliseOptions({ showHidden = false, depth = 2, colors = false, customInspect = true, showProxy = false, maxArrayLength = Infinity, breakLength = Infinity, seen = [], -// eslint-disable-next-line no-shadow -truncate = Infinity, stylize = String, } = {}, inspect) { - const options = { - showHidden: Boolean(showHidden), - depth: Number(depth), - colors: Boolean(colors), - customInspect: Boolean(customInspect), - showProxy: Boolean(showProxy), - maxArrayLength: Number(maxArrayLength), - breakLength: Number(breakLength), - truncate: Number(truncate), - seen, - inspect, - stylize, - }; - if (options.colors) { - options.stylize = colorise; - } - return options; -} -function isHighSurrogate(char) { - return char >= '\ud800' && char <= '\udbff'; -} -function truncate(string, length, tail = truncator) { - string = String(string); - const tailLength = tail.length; - const stringLength = string.length; - if (tailLength > length && stringLength > tailLength) { - return tail; - } - if (stringLength > length && stringLength > tailLength) { - let end = length - tailLength; - if (end > 0 && isHighSurrogate(string[end - 1])) { - end = end - 1; - } - return `${string.slice(0, end)}${tail}`; - } - return string; -} -// eslint-disable-next-line complexity -function inspectList(list, options, inspectItem, separator = ', ') { - inspectItem = inspectItem || options.inspect; - const size = list.length; - if (size === 0) - return ''; - const originalLength = options.truncate; - let output = ''; - let peek = ''; - let truncated = ''; - for (let i = 0; i < size; i += 1) { - const last = i + 1 === list.length; - const secondToLast = i + 2 === list.length; - truncated = `${truncator}(${list.length - i})`; - const value = list[i]; - // If there is more than one remaining we need to account for a separator of `, ` - options.truncate = originalLength - output.length - (last ? 0 : separator.length); - const string = peek || inspectItem(value, options) + (last ? '' : separator); - const nextLength = output.length + string.length; - const truncatedLength = nextLength + truncated.length; - // If this is the last element, and adding it would - // take us over length, but adding the truncator wouldn't - then break now - if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) { - break; - } - // If this isn't the last or second to last element to scan, - // but the string is already over length then break here - if (!last && !secondToLast && truncatedLength > originalLength) { - break; - } - // Peek at the next string to determine if we should - // break early before adding this item to the output - peek = last ? '' : inspectItem(list[i + 1], options) + (secondToLast ? '' : separator); - // If we have one element left, but this element and - // the next takes over length, the break early - if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) { - break; - } - output += string; - // If the next element takes us to length - - // but there are more after that, then we should truncate now - if (!last && !secondToLast && nextLength + peek.length >= originalLength) { - truncated = `${truncator}(${list.length - i - 1})`; - break; - } - truncated = ''; - } - return `${output}${truncated}`; -} -function quoteComplexKey(key) { - if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { - return key; - } - return JSON.stringify(key) - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); -} -function inspectProperty([key, value], options) { - options.truncate -= 2; - if (typeof key === 'string') { - key = quoteComplexKey(key); - } - else if (typeof key !== 'number') { - key = `[${options.inspect(key, options)}]`; - } - options.truncate -= key.length; - value = options.inspect(value, options); - return `${key}: ${value}`; -} - -function inspectArray(array, options) { - // Object.keys will always output the Array indices first, so we can slice by - // `array.length` to get non-index properties - const nonIndexProperties = Object.keys(array).slice(array.length); - if (!array.length && !nonIndexProperties.length) - return '[]'; - options.truncate -= 4; - const listContents = inspectList(array, options); - options.truncate -= listContents.length; - let propertyContents = ''; - if (nonIndexProperties.length) { - propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty); - } - return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ''} ]`; -} - -const getArrayName = (array) => { - // We need to special case Node.js' Buffers, which report to be Uint8Array - // @ts-ignore - if (typeof Buffer === 'function' && array instanceof Buffer) { - return 'Buffer'; - } - if (array[Symbol.toStringTag]) { - return array[Symbol.toStringTag]; - } - return array.constructor.name; -}; -function inspectTypedArray(array, options) { - const name = getArrayName(array); - options.truncate -= name.length + 4; - // Object.keys will always output the Array indices first, so we can slice by - // `array.length` to get non-index properties - const nonIndexProperties = Object.keys(array).slice(array.length); - if (!array.length && !nonIndexProperties.length) - return `${name}[]`; - // As we know TypedArrays only contain Unsigned Integers, we can skip inspecting each one and simply - // stylise the toString() value of them - let output = ''; - for (let i = 0; i < array.length; i++) { - const string = `${options.stylize(truncate(array[i], options.truncate), 'number')}${i === array.length - 1 ? '' : ', '}`; - options.truncate -= string.length; - if (array[i] !== array.length && options.truncate <= 3) { - output += `${truncator}(${array.length - array[i] + 1})`; - break; - } - output += string; - } - let propertyContents = ''; - if (nonIndexProperties.length) { - propertyContents = inspectList(nonIndexProperties.map(key => [key, array[key]]), options, inspectProperty); - } - return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ''} ]`; -} - -function inspectDate(dateObject, options) { - const stringRepresentation = dateObject.toJSON(); - if (stringRepresentation === null) { - return 'Invalid Date'; - } - const split = stringRepresentation.split('T'); - const date = split[0]; - // If we need to - truncate the time portion, but never the date - return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, 'date'); -} - -function inspectFunction(func, options) { - const functionType = func[Symbol.toStringTag] || 'Function'; - const name = func.name; - if (!name) { - return options.stylize(`[${functionType}]`, 'special'); - } - return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, 'special'); -} - -function inspectMapEntry([key, value], options) { - options.truncate -= 4; - key = options.inspect(key, options); - options.truncate -= key.length; - value = options.inspect(value, options); - return `${key} => ${value}`; -} -// IE11 doesn't support `map.entries()` -function mapToEntries(map) { - const entries = []; - map.forEach((value, key) => { - entries.push([key, value]); - }); - return entries; -} -function inspectMap(map, options) { - if (map.size === 0) - return 'Map{}'; - options.truncate -= 7; - return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`; -} - -const isNaN = Number.isNaN || (i => i !== i); // eslint-disable-line no-self-compare -function inspectNumber(number, options) { - if (isNaN(number)) { - return options.stylize('NaN', 'number'); - } - if (number === Infinity) { - return options.stylize('Infinity', 'number'); - } - if (number === -Infinity) { - return options.stylize('-Infinity', 'number'); - } - if (number === 0) { - return options.stylize(1 / number === Infinity ? '+0' : '-0', 'number'); - } - return options.stylize(truncate(String(number), options.truncate), 'number'); -} - -function inspectBigInt(number, options) { - let nums = truncate(number.toString(), options.truncate - 1); - if (nums !== truncator) - nums += 'n'; - return options.stylize(nums, 'bigint'); -} - -function inspectRegExp(value, options) { - const flags = value.toString().split('/')[2]; - const sourceLength = options.truncate - (2 + flags.length); - const source = value.source; - return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, 'regexp'); -} - -// IE11 doesn't support `Array.from(set)` -function arrayFromSet(set) { - const values = []; - set.forEach(value => { - values.push(value); - }); - return values; -} -function inspectSet(set, options) { - if (set.size === 0) - return 'Set{}'; - options.truncate -= 7; - return `Set{ ${inspectList(arrayFromSet(set), options)} }`; -} - -const stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5" + - '\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]', 'g'); -const escapeCharacters = { - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - "'": "\\'", - '\\': '\\\\', -}; -const hex = 16; -function escape(char) { - return (escapeCharacters[char] || - `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-4)}`); -} -function inspectString(string, options) { - if (stringEscapeChars.test(string)) { - string = string.replace(stringEscapeChars, escape); - } - return options.stylize(`'${truncate(string, options.truncate - 2)}'`, 'string'); -} - -function inspectSymbol(value) { - if ('description' in Symbol.prototype) { - return value.description ? `Symbol(${value.description})` : 'Symbol()'; - } - return value.toString(); -} - -const getPromiseValue = () => 'Promise{…}'; - -function inspectObject$1(object, options) { - const properties = Object.getOwnPropertyNames(object); - const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : []; - if (properties.length === 0 && symbols.length === 0) { - return '{}'; - } - options.truncate -= 4; - options.seen = options.seen || []; - if (options.seen.includes(object)) { - return '[Circular]'; - } - options.seen.push(object); - const propertyContents = inspectList(properties.map(key => [key, object[key]]), options, inspectProperty); - const symbolContents = inspectList(symbols.map(key => [key, object[key]]), options, inspectProperty); - options.seen.pop(); - let sep = ''; - if (propertyContents && symbolContents) { - sep = ', '; - } - return `{ ${propertyContents}${sep}${symbolContents} }`; -} - -const toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag ? Symbol.toStringTag : false; -function inspectClass(value, options) { - let name = ''; - if (toStringTag && toStringTag in value) { - name = value[toStringTag]; - } - name = name || value.constructor.name; - // Babel transforms anonymous classes to the name `_class` - if (!name || name === '_class') { - name = '<Anonymous Class>'; - } - options.truncate -= name.length; - return `${name}${inspectObject$1(value, options)}`; -} - -function inspectArguments(args, options) { - if (args.length === 0) - return 'Arguments[]'; - options.truncate -= 13; - return `Arguments[ ${inspectList(args, options)} ]`; -} - -const errorKeys = [ - 'stack', - 'line', - 'column', - 'name', - 'message', - 'fileName', - 'lineNumber', - 'columnNumber', - 'number', - 'description', - 'cause', -]; -function inspectObject(error, options) { - const properties = Object.getOwnPropertyNames(error).filter(key => errorKeys.indexOf(key) === -1); - const name = error.name; - options.truncate -= name.length; - let message = ''; - if (typeof error.message === 'string') { - message = truncate(error.message, options.truncate); - } - else { - properties.unshift('message'); - } - message = message ? `: ${message}` : ''; - options.truncate -= message.length + 5; - options.seen = options.seen || []; - if (options.seen.includes(error)) { - return '[Circular]'; - } - options.seen.push(error); - const propertyContents = inspectList(properties.map(key => [key, error[key]]), options, inspectProperty); - return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ''}`; -} - -function inspectAttribute([key, value], options) { - options.truncate -= 3; - if (!value) { - return `${options.stylize(String(key), 'yellow')}`; - } - return `${options.stylize(String(key), 'yellow')}=${options.stylize(`"${value}"`, 'string')}`; -} -function inspectNodeCollection(collection, options) { - return inspectList(collection, options, inspectNode, '\n'); -} -function inspectNode(node, options) { - switch (node.nodeType) { - case 1: - return inspectHTML(node, options); - case 3: - return options.inspect(node.data, options); - default: - return options.inspect(node, options); - } -} -// @ts-ignore (Deno doesn't have Element) -function inspectHTML(element, options) { - const properties = element.getAttributeNames(); - const name = element.tagName.toLowerCase(); - const head = options.stylize(`<${name}`, 'special'); - const headClose = options.stylize(`>`, 'special'); - const tail = options.stylize(`</${name}>`, 'special'); - options.truncate -= name.length * 2 + 5; - let propertyContents = ''; - if (properties.length > 0) { - propertyContents += ' '; - propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, ' '); - } - options.truncate -= propertyContents.length; - const truncate = options.truncate; - let children = inspectNodeCollection(element.children, options); - if (children && children.length > truncate) { - children = `${truncator}(${element.children.length})`; - } - return `${head}${propertyContents}${headClose}${children}${tail}`; -} - -/* ! - * loupe - * Copyright(c) 2013 Jake Luer <jake@alogicalparadox.com> - * MIT Licensed - */ -const symbolsSupported = typeof Symbol === 'function' && typeof Symbol.for === 'function'; -const chaiInspect = symbolsSupported ? Symbol.for('chai/inspect') : '@@chai/inspect'; -const nodeInspect = Symbol.for('nodejs.util.inspect.custom'); -const constructorMap = new WeakMap(); -const stringTagMap = {}; -const baseTypesMap = { - undefined: (value, options) => options.stylize('undefined', 'undefined'), - null: (value, options) => options.stylize('null', 'null'), - boolean: (value, options) => options.stylize(String(value), 'boolean'), - Boolean: (value, options) => options.stylize(String(value), 'boolean'), - number: inspectNumber, - Number: inspectNumber, - bigint: inspectBigInt, - BigInt: inspectBigInt, - string: inspectString, - String: inspectString, - function: inspectFunction, - Function: inspectFunction, - symbol: inspectSymbol, - // A Symbol polyfill will return `Symbol` not `symbol` from typedetect - Symbol: inspectSymbol, - Array: inspectArray, - Date: inspectDate, - Map: inspectMap, - Set: inspectSet, - RegExp: inspectRegExp, - Promise: getPromiseValue, - // WeakSet, WeakMap are totally opaque to us - WeakSet: (value, options) => options.stylize('WeakSet{…}', 'special'), - WeakMap: (value, options) => options.stylize('WeakMap{…}', 'special'), - Arguments: inspectArguments, - Int8Array: inspectTypedArray, - Uint8Array: inspectTypedArray, - Uint8ClampedArray: inspectTypedArray, - Int16Array: inspectTypedArray, - Uint16Array: inspectTypedArray, - Int32Array: inspectTypedArray, - Uint32Array: inspectTypedArray, - Float32Array: inspectTypedArray, - Float64Array: inspectTypedArray, - Generator: () => '', - DataView: () => '', - ArrayBuffer: () => '', - Error: inspectObject, - HTMLCollection: inspectNodeCollection, - NodeList: inspectNodeCollection, -}; -// eslint-disable-next-line complexity -const inspectCustom = (value, options, type, inspectFn) => { - if (chaiInspect in value && typeof value[chaiInspect] === 'function') { - return value[chaiInspect](options); - } - if (nodeInspect in value && typeof value[nodeInspect] === 'function') { - return value[nodeInspect](options.depth, options, inspectFn); - } - if ('inspect' in value && typeof value.inspect === 'function') { - return value.inspect(options.depth, options); - } - if ('constructor' in value && constructorMap.has(value.constructor)) { - return constructorMap.get(value.constructor)(value, options); - } - if (stringTagMap[type]) { - return stringTagMap[type](value, options); - } - return ''; -}; -const toString = Object.prototype.toString; -// eslint-disable-next-line complexity -function inspect$1(value, opts = {}) { - const options = normaliseOptions(opts, inspect$1); - const { customInspect } = options; - let type = value === null ? 'null' : typeof value; - if (type === 'object') { - type = toString.call(value).slice(8, -1); - } - // If it is a base value that we already support, then use Loupe's inspector - if (type in baseTypesMap) { - return baseTypesMap[type](value, options); - } - // If `options.customInspect` is set to true then try to use the custom inspector - if (customInspect && value) { - const output = inspectCustom(value, options, type, inspect$1); - if (output) { - if (typeof output === 'string') - return output; - return inspect$1(output, options); - } - } - const proto = value ? Object.getPrototypeOf(value) : false; - // If it's a plain Object then use Loupe's inspector - if (proto === Object.prototype || proto === null) { - return inspectObject$1(value, options); - } - // Specifically account for HTMLElements - // @ts-ignore - if (value && typeof HTMLElement === 'function' && value instanceof HTMLElement) { - return inspectHTML(value, options); - } - if ('constructor' in value) { - // If it is a class, inspect it like an object but add the constructor name - if (value.constructor !== Object) { - return inspectClass(value, options); - } - // If it is an object with an anonymous prototype, display it as an object. - return inspectObject$1(value, options); - } - // last chance to check if it's an object - if (value === Object(value)) { - return inspectObject$1(value, options); - } - // We have run out of options! Just stringify the value - return options.stylize(String(value), type); -} - -const { AsymmetricMatcher, DOMCollection, DOMElement, Immutable, ReactElement, ReactTestComponent } = plugins; -const PLUGINS = [ - ReactTestComponent, - ReactElement, - DOMElement, - DOMCollection, - Immutable, - AsymmetricMatcher -]; -function stringify(object, maxDepth = 10, { maxLength, ...options } = {}) { - const MAX_LENGTH = maxLength ?? 1e4; - let result; - try { - result = format$1(object, { - maxDepth, - escapeString: false, - plugins: PLUGINS, - ...options - }); - } catch { - result = format$1(object, { - callToJSON: false, - maxDepth, - escapeString: false, - plugins: PLUGINS, - ...options - }); - } - // Prevents infinite loop https://github.com/vitest-dev/vitest/issues/7249 - return result.length >= MAX_LENGTH && maxDepth > 1 ? stringify(object, Math.floor(Math.min(maxDepth, Number.MAX_SAFE_INTEGER) / 2), { - maxLength, - ...options - }) : result; -} -const formatRegExp = /%[sdjifoOc%]/g; -function baseFormat(args, options = {}) { - const formatArg = (item, inspecOptions) => { - if (options.prettifyObject) { - return stringify(item, undefined, { - printBasicPrototype: false, - escapeString: false - }); - } - return inspect(item, inspecOptions); - }; - if (typeof args[0] !== "string") { - const objects = []; - for (let i = 0; i < args.length; i++) { - objects.push(formatArg(args[i], { - depth: 0, - colors: false - })); - } - return objects.join(" "); - } - const len = args.length; - let i = 1; - const template = args[0]; - let str = String(template).replace(formatRegExp, (x) => { - if (x === "%%") { - return "%"; - } - if (i >= len) { - return x; - } - switch (x) { - case "%s": { - const value = args[i++]; - if (typeof value === "bigint") { - return `${value.toString()}n`; - } - if (typeof value === "number" && value === 0 && 1 / value < 0) { - return "-0"; - } - if (typeof value === "object" && value !== null) { - if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) { - return value.toString(); - } - return formatArg(value, { - depth: 0, - colors: false - }); - } - return String(value); - } - case "%d": { - const value = args[i++]; - if (typeof value === "bigint") { - return `${value.toString()}n`; - } - return Number(value).toString(); - } - case "%i": { - const value = args[i++]; - if (typeof value === "bigint") { - return `${value.toString()}n`; - } - return Number.parseInt(String(value)).toString(); - } - case "%f": return Number.parseFloat(String(args[i++])).toString(); - case "%o": return formatArg(args[i++], { - showHidden: true, - showProxy: true - }); - case "%O": return formatArg(args[i++]); - case "%c": { - i++; - return ""; - } - case "%j": try { - return JSON.stringify(args[i++]); - } catch (err) { - const m = err.message; - if (m.includes("circular structure") || m.includes("cyclic structures") || m.includes("cyclic object")) { - return "[Circular]"; - } - throw err; - } - default: return x; - } - }); - for (let x = args[i]; i < len; x = args[++i]) { - if (x === null || typeof x !== "object") { - str += ` ${x}`; - } else { - str += ` ${formatArg(x)}`; - } - } - return str; -} -function format(...args) { - return baseFormat(args); -} -function browserFormat(...args) { - return baseFormat(args, { prettifyObject: true }); -} -function inspect(obj, options = {}) { - if (options.truncate === 0) { - options.truncate = Number.POSITIVE_INFINITY; - } - return inspect$1(obj, options); -} -function objDisplay(obj, options = {}) { - if (typeof options.truncate === "undefined") { - options.truncate = 40; - } - const str = inspect(obj, options); - const type = Object.prototype.toString.call(obj); - if (options.truncate && str.length >= options.truncate) { - if (type === "[object Function]") { - const fn = obj; - return !fn.name ? "[Function]" : `[Function: ${fn.name}]`; - } else if (type === "[object Array]") { - return `[ Array(${obj.length}) ]`; - } else if (type === "[object Object]") { - const keys = Object.keys(obj); - const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(", ")}, ...` : keys.join(", "); - return `{ Object (${kstr}) }`; - } else { - return str; - } - } - return str; -} - -export { browserFormat, format, formatRegExp, inspect, objDisplay, stringify }; diff --git a/vanilla/node_modules/@vitest/utils/dist/error.d.ts b/vanilla/node_modules/@vitest/utils/dist/error.d.ts deleted file mode 100644 index ad5d628..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/error.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { D as DiffOptions } from './types.d-BCElaP-c.js'; -export { serializeValue as serializeError } from './serialize.js'; -import '@vitest/pretty-format'; - -declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): any; - -export { processError }; diff --git a/vanilla/node_modules/@vitest/utils/dist/error.js b/vanilla/node_modules/@vitest/utils/dist/error.js deleted file mode 100644 index 14886d0..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/error.js +++ /dev/null @@ -1,42 +0,0 @@ -import { printDiffOrStringify } from './diff.js'; -import { stringify } from './display.js'; -import { serializeValue } from './serialize.js'; -import '@vitest/pretty-format'; -import 'tinyrainbow'; -import './helpers.js'; -import './constants.js'; -import './chunk-_commonjsHelpers.js'; - -function processError(_err, diffOptions, seen = new WeakSet()) { - if (!_err || typeof _err !== "object") { - return { message: String(_err) }; - } - const err = _err; - if (err.showDiff || err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined) { - err.diff = printDiffOrStringify(err.actual, err.expected, { - ...diffOptions, - ...err.diffOptions - }); - } - if ("expected" in err && typeof err.expected !== "string") { - err.expected = stringify(err.expected, 10); - } - if ("actual" in err && typeof err.actual !== "string") { - err.actual = stringify(err.actual, 10); - } - // some Error implementations may not allow rewriting cause - // in most cases, the assignment will lead to "err.cause = err.cause" - try { - if (!seen.has(err) && typeof err.cause === "object") { - seen.add(err); - err.cause = processError(err.cause, diffOptions, seen); - } - } catch {} - try { - return serializeValue(err); - } catch (e) { - return serializeValue(new Error(`Failed to fully serialize error: ${e === null || e === void 0 ? void 0 : e.message}\nInner error message: ${err === null || err === void 0 ? void 0 : err.message}`)); - } -} - -export { processError, serializeValue as serializeError }; diff --git a/vanilla/node_modules/@vitest/utils/dist/helpers.d.ts b/vanilla/node_modules/@vitest/utils/dist/helpers.d.ts deleted file mode 100644 index 493817b..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/helpers.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { Nullable, Arrayable } from './types.js'; - -declare function nanoid(size?: number): string; - -declare function shuffle<T>(array: T[], seed?: number): T[]; - -interface CloneOptions { - forceWritable?: boolean; -} -interface ErrorOptions { - message?: string; - stackTraceLimit?: number; -} - -/** -* Get original stacktrace without source map support the most performant way. -* - Create only 1 stack frame. -* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). -*/ -declare function createSimpleStackTrace(options?: ErrorOptions): string; -declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>; -declare function assertTypes(value: unknown, name: string, types: string[]): void; -declare function isPrimitive(value: unknown): boolean; -declare function slash(path: string): string; -declare function cleanUrl(url: string): string; -declare const isExternalUrl: (url: string) => boolean; -/** -* Prepend `/@id/` and replace null byte so the id is URL-safe. -* This is prepended to resolved ids that are not valid browser -* import specifiers by the importAnalysis plugin. -*/ -declare function wrapId(id: string): string; -/** -* Undo {@link wrapId}'s `/@id/` and null byte replacements. -*/ -declare function unwrapId(id: string): string; -declare function withTrailingSlash(path: string): string; -declare function isBareImport(id: string): boolean; -declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>; -declare function isObject(item: unknown): boolean; -declare function getType(value: unknown): string; -declare function getOwnProperties(obj: any): (string | symbol)[]; -declare function deepClone<T>(val: T, options?: CloneOptions): T; -declare function clone<T>(val: T, seen: WeakMap<any, any>, options?: CloneOptions): T; -declare function noop(): void; -declare function objectAttr(source: any, path: string, defaultValue?: undefined): any; -type DeferPromise<T> = Promise<T> & { - resolve: (value: T | PromiseLike<T>) => void; - reject: (reason?: any) => void; -}; -declare function createDefer<T>(): DeferPromise<T>; -/** -* If code starts with a function call, will return its last index, respecting arguments. -* This will return 25 - last ending character of toMatch ")" -* Also works with callbacks -* ``` -* toMatch({ test: '123' }); -* toBeAliased('123') -* ``` -*/ -declare function getCallLastIndex(code: string): number | null; -declare function isNegativeNaN(val: number): boolean; -/** -* Deep merge :P -* -* Will merge objects only if they are plain -* -* Do not merge types - it is very expensive and usually it's better to case a type here -*/ -declare function deepMerge<T extends object = object>(target: T, ...sources: any[]): T; - -export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId }; -export type { DeferPromise }; diff --git a/vanilla/node_modules/@vitest/utils/dist/helpers.js b/vanilla/node_modules/@vitest/utils/dist/helpers.js deleted file mode 100644 index b19970a..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/helpers.js +++ /dev/null @@ -1,295 +0,0 @@ -import { VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER } from './constants.js'; - -// port from nanoid -// https://github.com/ai/nanoid -const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"; -function nanoid(size = 21) { - let id = ""; - let i = size; - while (i--) { - id += urlAlphabet[Math.random() * 64 | 0]; - } - return id; -} - -const RealDate = Date; -function random(seed) { - const x = Math.sin(seed++) * 1e4; - return x - Math.floor(x); -} -function shuffle(array, seed = RealDate.now()) { - let length = array.length; - while (length) { - const index = Math.floor(random(seed) * length--); - const previous = array[length]; - array[length] = array[index]; - array[index] = previous; - ++seed; - } - return array; -} - -/** -* Get original stacktrace without source map support the most performant way. -* - Create only 1 stack frame. -* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms). -*/ -function createSimpleStackTrace(options) { - const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {}; - const limit = Error.stackTraceLimit; - const prepareStackTrace = Error.prepareStackTrace; - Error.stackTraceLimit = stackTraceLimit; - Error.prepareStackTrace = (e) => e.stack; - const err = new Error(message); - const stackTrace = err.stack || ""; - Error.prepareStackTrace = prepareStackTrace; - Error.stackTraceLimit = limit; - return stackTrace; -} -function notNullish(v) { - return v != null; -} -function assertTypes(value, name, types) { - const receivedType = typeof value; - const pass = types.includes(receivedType); - if (!pass) { - throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`); - } -} -function isPrimitive(value) { - return value === null || typeof value !== "function" && typeof value !== "object"; -} -function slash(path) { - return path.replace(/\\/g, "/"); -} -const postfixRE = /[?#].*$/; -function cleanUrl(url) { - return url.replace(postfixRE, ""); -} -const externalRE = /^(?:[a-z]+:)?\/\//; -const isExternalUrl = (url) => externalRE.test(url); -/** -* Prepend `/@id/` and replace null byte so the id is URL-safe. -* This is prepended to resolved ids that are not valid browser -* import specifiers by the importAnalysis plugin. -*/ -function wrapId(id) { - return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); -} -/** -* Undo {@link wrapId}'s `/@id/` and null byte replacements. -*/ -function unwrapId(id) { - return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id; -} -function withTrailingSlash(path) { - if (path.at(-1) !== "/") { - return `${path}/`; - } - return path; -} -const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i; -function isBareImport(id) { - return bareImportRE.test(id); -} -function toArray(array) { - if (array === null || array === undefined) { - array = []; - } - if (Array.isArray(array)) { - return array; - } - return [array]; -} -function isObject(item) { - return item != null && typeof item === "object" && !Array.isArray(item); -} -function isFinalObj(obj) { - return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype; -} -function getType(value) { - return Object.prototype.toString.apply(value).slice(8, -1); -} -function collectOwnProperties(obj, collector) { - const collect = typeof collector === "function" ? collector : (key) => collector.add(key); - Object.getOwnPropertyNames(obj).forEach(collect); - Object.getOwnPropertySymbols(obj).forEach(collect); -} -function getOwnProperties(obj) { - const ownProps = new Set(); - if (isFinalObj(obj)) { - return []; - } - collectOwnProperties(obj, ownProps); - return Array.from(ownProps); -} -const defaultCloneOptions = { forceWritable: false }; -function deepClone(val, options = defaultCloneOptions) { - const seen = new WeakMap(); - return clone(val, seen, options); -} -function clone(val, seen, options = defaultCloneOptions) { - let k, out; - if (seen.has(val)) { - return seen.get(val); - } - if (Array.isArray(val)) { - out = Array.from({ length: k = val.length }); - seen.set(val, out); - while (k--) { - out[k] = clone(val[k], seen, options); - } - return out; - } - if (Object.prototype.toString.call(val) === "[object Object]") { - out = Object.create(Object.getPrototypeOf(val)); - seen.set(val, out); - // we don't need properties from prototype - const props = getOwnProperties(val); - for (const k of props) { - const descriptor = Object.getOwnPropertyDescriptor(val, k); - if (!descriptor) { - continue; - } - const cloned = clone(val[k], seen, options); - if (options.forceWritable) { - Object.defineProperty(out, k, { - enumerable: descriptor.enumerable, - configurable: true, - writable: true, - value: cloned - }); - } else if ("get" in descriptor) { - Object.defineProperty(out, k, { - ...descriptor, - get() { - return cloned; - } - }); - } else { - Object.defineProperty(out, k, { - ...descriptor, - value: cloned - }); - } - } - return out; - } - return val; -} -function noop() {} -function objectAttr(source, path, defaultValue = undefined) { - // a[3].b -> a.3.b - const paths = path.replace(/\[(\d+)\]/g, ".$1").split("."); - let result = source; - for (const p of paths) { - result = new Object(result)[p]; - if (result === undefined) { - return defaultValue; - } - } - return result; -} -function createDefer() { - let resolve = null; - let reject = null; - const p = new Promise((_resolve, _reject) => { - resolve = _resolve; - reject = _reject; - }); - p.resolve = resolve; - p.reject = reject; - return p; -} -/** -* If code starts with a function call, will return its last index, respecting arguments. -* This will return 25 - last ending character of toMatch ")" -* Also works with callbacks -* ``` -* toMatch({ test: '123' }); -* toBeAliased('123') -* ``` -*/ -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; -} -function isNegativeNaN(val) { - if (!Number.isNaN(val)) { - return false; - } - const f64 = new Float64Array(1); - f64[0] = val; - const u32 = new Uint32Array(f64.buffer); - const isNegative = u32[1] >>> 31 === 1; - return isNegative; -} -function toString(v) { - return Object.prototype.toString.call(v); -} -function isPlainObject(val) { - return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object"); -} -function isMergeableObject(item) { - return isPlainObject(item) && !Array.isArray(item); -} -/** -* Deep merge :P -* -* Will merge objects only if they are plain -* -* Do not merge types - it is very expensive and usually it's better to case a type here -*/ -function deepMerge(target, ...sources) { - if (!sources.length) { - return target; - } - const source = sources.shift(); - if (source === undefined) { - return target; - } - if (isMergeableObject(target) && isMergeableObject(source)) { - Object.keys(source).forEach((key) => { - const _source = source; - if (isMergeableObject(_source[key])) { - if (!target[key]) { - target[key] = {}; - } - deepMerge(target[key], _source[key]); - } else { - target[key] = _source[key]; - } - }); - } - return deepMerge(target, ...sources); -} - -export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId }; diff --git a/vanilla/node_modules/@vitest/utils/dist/highlight.d.ts b/vanilla/node_modules/@vitest/utils/dist/highlight.d.ts deleted file mode 100644 index b3420de..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/highlight.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Colors } from 'tinyrainbow'; - -interface HighlightOptions { - jsx?: boolean; - colors?: Colors; -} -declare function highlight(code: string, options?: HighlightOptions): string; - -export { highlight }; diff --git a/vanilla/node_modules/@vitest/utils/dist/highlight.js b/vanilla/node_modules/@vitest/utils/dist/highlight.js deleted file mode 100644 index 1250062..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/highlight.js +++ /dev/null @@ -1,538 +0,0 @@ -import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js'; -import c from 'tinyrainbow'; - -var jsTokens_1; -var hasRequiredJsTokens; - -function requireJsTokens () { - if (hasRequiredJsTokens) return jsTokens_1; - hasRequiredJsTokens = 1; - // Copyright 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Simon Lydell - // License: MIT. - var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace; - RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\\]).|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu; - Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y; - Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu; - StringLiteral = /(['"])(?:(?!\1)[^\\\n\r]|\\(?:\r\n|[^]))*(\1)?/y; - NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y; - Template = /[`}](?:[^`\\$]|\\[^]|\$(?!\{))*(`|\$\{)?/y; - WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu; - LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y; - MultiLineComment = /\/\*(?:[^*]|\*(?!\/))*(\*\/)?/y; - SingleLineComment = /\/\/.*/y; - JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y; - JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu; - JSXString = /(['"])(?:(?!\1)[^])*(\1)?/y; - JSXText = /[^<>{}]+/y; - TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/; - TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/; - KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/; - KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/; - Newline = RegExp(LineTerminatorSequence.source); - jsTokens_1 = function*(input, {jsx = false} = {}) { - var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack; - ({length} = input); - lastIndex = 0; - lastSignificantToken = ""; - stack = [ - {tag: "JS"} - ]; - braces = []; - parenNesting = 0; - postfixIncDec = false; - while (lastIndex < length) { - mode = stack[stack.length - 1]; - switch (mode.tag) { - case "JS": - case "JSNonExpressionParen": - case "InterpolationInTemplate": - case "InterpolationInJSX": - if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { - RegularExpressionLiteral.lastIndex = lastIndex; - if (match = RegularExpressionLiteral.exec(input)) { - lastIndex = RegularExpressionLiteral.lastIndex; - lastSignificantToken = match[0]; - postfixIncDec = true; - yield ({ - type: "RegularExpressionLiteral", - value: match[0], - closed: match[1] !== void 0 && match[1] !== "\\" - }); - continue; - } - } - Punctuator.lastIndex = lastIndex; - if (match = Punctuator.exec(input)) { - punctuator = match[0]; - nextLastIndex = Punctuator.lastIndex; - nextLastSignificantToken = punctuator; - switch (punctuator) { - case "(": - if (lastSignificantToken === "?NonExpressionParenKeyword") { - stack.push({ - tag: "JSNonExpressionParen", - nesting: parenNesting - }); - } - parenNesting++; - postfixIncDec = false; - break; - case ")": - parenNesting--; - postfixIncDec = true; - if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) { - stack.pop(); - nextLastSignificantToken = "?NonExpressionParenEnd"; - postfixIncDec = false; - } - break; - case "{": - Punctuator.lastIndex = 0; - isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken)); - braces.push(isExpression); - postfixIncDec = false; - break; - case "}": - switch (mode.tag) { - case "InterpolationInTemplate": - if (braces.length === mode.nesting) { - Template.lastIndex = lastIndex; - match = Template.exec(input); - lastIndex = Template.lastIndex; - lastSignificantToken = match[0]; - if (match[1] === "${") { - lastSignificantToken = "?InterpolationInTemplate"; - postfixIncDec = false; - yield ({ - type: "TemplateMiddle", - value: match[0] - }); - } else { - stack.pop(); - postfixIncDec = true; - yield ({ - type: "TemplateTail", - value: match[0], - closed: match[1] === "`" - }); - } - continue; - } - break; - case "InterpolationInJSX": - if (braces.length === mode.nesting) { - stack.pop(); - lastIndex += 1; - lastSignificantToken = "}"; - yield ({ - type: "JSXPunctuator", - value: "}" - }); - continue; - } - } - postfixIncDec = braces.pop(); - nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}"; - break; - case "]": - postfixIncDec = true; - break; - case "++": - case "--": - nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec"; - break; - case "<": - if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) { - stack.push({tag: "JSXTag"}); - lastIndex += 1; - lastSignificantToken = "<"; - yield ({ - type: "JSXPunctuator", - value: punctuator - }); - continue; - } - postfixIncDec = false; - break; - default: - postfixIncDec = false; - } - lastIndex = nextLastIndex; - lastSignificantToken = nextLastSignificantToken; - yield ({ - type: "Punctuator", - value: punctuator - }); - continue; - } - Identifier.lastIndex = lastIndex; - if (match = Identifier.exec(input)) { - lastIndex = Identifier.lastIndex; - nextLastSignificantToken = match[0]; - switch (match[0]) { - case "for": - case "if": - case "while": - case "with": - if (lastSignificantToken !== "." && lastSignificantToken !== "?.") { - nextLastSignificantToken = "?NonExpressionParenKeyword"; - } - } - lastSignificantToken = nextLastSignificantToken; - postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]); - yield ({ - type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName", - value: match[0] - }); - continue; - } - StringLiteral.lastIndex = lastIndex; - if (match = StringLiteral.exec(input)) { - lastIndex = StringLiteral.lastIndex; - lastSignificantToken = match[0]; - postfixIncDec = true; - yield ({ - type: "StringLiteral", - value: match[0], - closed: match[2] !== void 0 - }); - continue; - } - NumericLiteral.lastIndex = lastIndex; - if (match = NumericLiteral.exec(input)) { - lastIndex = NumericLiteral.lastIndex; - lastSignificantToken = match[0]; - postfixIncDec = true; - yield ({ - type: "NumericLiteral", - value: match[0] - }); - continue; - } - Template.lastIndex = lastIndex; - if (match = Template.exec(input)) { - lastIndex = Template.lastIndex; - lastSignificantToken = match[0]; - if (match[1] === "${") { - lastSignificantToken = "?InterpolationInTemplate"; - stack.push({ - tag: "InterpolationInTemplate", - nesting: braces.length - }); - postfixIncDec = false; - yield ({ - type: "TemplateHead", - value: match[0] - }); - } else { - postfixIncDec = true; - yield ({ - type: "NoSubstitutionTemplate", - value: match[0], - closed: match[1] === "`" - }); - } - continue; - } - break; - case "JSXTag": - case "JSXTagEnd": - JSXPunctuator.lastIndex = lastIndex; - if (match = JSXPunctuator.exec(input)) { - lastIndex = JSXPunctuator.lastIndex; - nextLastSignificantToken = match[0]; - switch (match[0]) { - case "<": - stack.push({tag: "JSXTag"}); - break; - case ">": - stack.pop(); - if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") { - nextLastSignificantToken = "?JSX"; - postfixIncDec = true; - } else { - stack.push({tag: "JSXChildren"}); - } - break; - case "{": - stack.push({ - tag: "InterpolationInJSX", - nesting: braces.length - }); - nextLastSignificantToken = "?InterpolationInJSX"; - postfixIncDec = false; - break; - case "/": - if (lastSignificantToken === "<") { - stack.pop(); - if (stack[stack.length - 1].tag === "JSXChildren") { - stack.pop(); - } - stack.push({tag: "JSXTagEnd"}); - } - } - lastSignificantToken = nextLastSignificantToken; - yield ({ - type: "JSXPunctuator", - value: match[0] - }); - continue; - } - JSXIdentifier.lastIndex = lastIndex; - if (match = JSXIdentifier.exec(input)) { - lastIndex = JSXIdentifier.lastIndex; - lastSignificantToken = match[0]; - yield ({ - type: "JSXIdentifier", - value: match[0] - }); - continue; - } - JSXString.lastIndex = lastIndex; - if (match = JSXString.exec(input)) { - lastIndex = JSXString.lastIndex; - lastSignificantToken = match[0]; - yield ({ - type: "JSXString", - value: match[0], - closed: match[2] !== void 0 - }); - continue; - } - break; - case "JSXChildren": - JSXText.lastIndex = lastIndex; - if (match = JSXText.exec(input)) { - lastIndex = JSXText.lastIndex; - lastSignificantToken = match[0]; - yield ({ - type: "JSXText", - value: match[0] - }); - continue; - } - switch (input[lastIndex]) { - case "<": - stack.push({tag: "JSXTag"}); - lastIndex++; - lastSignificantToken = "<"; - yield ({ - type: "JSXPunctuator", - value: "<" - }); - continue; - case "{": - stack.push({ - tag: "InterpolationInJSX", - nesting: braces.length - }); - lastIndex++; - lastSignificantToken = "?InterpolationInJSX"; - postfixIncDec = false; - yield ({ - type: "JSXPunctuator", - value: "{" - }); - continue; - } - } - WhiteSpace.lastIndex = lastIndex; - if (match = WhiteSpace.exec(input)) { - lastIndex = WhiteSpace.lastIndex; - yield ({ - type: "WhiteSpace", - value: match[0] - }); - continue; - } - LineTerminatorSequence.lastIndex = lastIndex; - if (match = LineTerminatorSequence.exec(input)) { - lastIndex = LineTerminatorSequence.lastIndex; - postfixIncDec = false; - if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { - lastSignificantToken = "?NoLineTerminatorHere"; - } - yield ({ - type: "LineTerminatorSequence", - value: match[0] - }); - continue; - } - MultiLineComment.lastIndex = lastIndex; - if (match = MultiLineComment.exec(input)) { - lastIndex = MultiLineComment.lastIndex; - if (Newline.test(match[0])) { - postfixIncDec = false; - if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) { - lastSignificantToken = "?NoLineTerminatorHere"; - } - } - yield ({ - type: "MultiLineComment", - value: match[0], - closed: match[1] !== void 0 - }); - continue; - } - SingleLineComment.lastIndex = lastIndex; - if (match = SingleLineComment.exec(input)) { - lastIndex = SingleLineComment.lastIndex; - postfixIncDec = false; - yield ({ - type: "SingleLineComment", - value: match[0] - }); - continue; - } - firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex)); - lastIndex += firstCodePoint.length; - lastSignificantToken = firstCodePoint; - postfixIncDec = false; - yield ({ - type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid", - value: firstCodePoint - }); - } - return void 0; - }; - return jsTokens_1; -} - -var jsTokensExports = /*@__PURE__*/ requireJsTokens(); -var jsTokens = /*@__PURE__*/getDefaultExportFromCjs(jsTokensExports); - -// src/index.ts -var reservedWords = { - keyword: [ - "break", - "case", - "catch", - "continue", - "debugger", - "default", - "do", - "else", - "finally", - "for", - "function", - "if", - "return", - "switch", - "throw", - "try", - "var", - "const", - "while", - "with", - "new", - "this", - "super", - "class", - "extends", - "export", - "import", - "null", - "true", - "false", - "in", - "instanceof", - "typeof", - "void", - "delete" - ], - strict: [ - "implements", - "interface", - "let", - "package", - "private", - "protected", - "public", - "static", - "yield" - ] -}, keywords = new Set(reservedWords.keyword), reservedWordsStrictSet = new Set(reservedWords.strict), sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]); -function isReservedWord(word) { - return word === "await" || word === "enum"; -} -function isStrictReservedWord(word) { - return isReservedWord(word) || reservedWordsStrictSet.has(word); -} -function isKeyword(word) { - return keywords.has(word); -} -var BRACKET = /^[()[\]{}]$/, getTokenType = function(token) { - if (token.type === "IdentifierName") { - if (isKeyword(token.value) || isStrictReservedWord(token.value) || sometimesKeywords.has(token.value)) - return "Keyword"; - if (token.value[0] && token.value[0] !== token.value[0].toLowerCase()) - return "IdentifierCapitalized"; - } - return token.type === "Punctuator" && BRACKET.test(token.value) ? "Bracket" : token.type === "Invalid" && (token.value === "@" || token.value === "#") ? "Punctuator" : token.type; -}; -function getCallableType(token) { - if (token.type === "IdentifierName") - return "IdentifierCallable"; - if (token.type === "PrivateIdentifier") - return "PrivateIdentifierCallable"; - throw new Error("Not a callable token"); -} -var colorize = (defs, type, value) => { - let colorize2 = defs[type]; - return colorize2 ? colorize2(value) : value; -}, highlightTokens = (defs, text, jsx) => { - let highlighted = "", lastPotentialCallable = null, stackedHighlight = ""; - for (let token of jsTokens(text, { jsx })) { - let type = getTokenType(token); - if (type === "IdentifierName" || type === "PrivateIdentifier") { - lastPotentialCallable && (highlighted += colorize(defs, getTokenType(lastPotentialCallable), lastPotentialCallable.value) + stackedHighlight, stackedHighlight = ""), lastPotentialCallable = token; - continue; - } - if (lastPotentialCallable && (token.type === "WhiteSpace" || token.type === "LineTerminatorSequence" || token.type === "Punctuator" && (token.value === "?." || token.value === "!"))) { - stackedHighlight += colorize(defs, type, token.value); - continue; - } - if (stackedHighlight && !lastPotentialCallable && (highlighted += stackedHighlight, stackedHighlight = ""), lastPotentialCallable) { - let type2 = token.type === "Punctuator" && token.value === "(" ? getCallableType(lastPotentialCallable) : getTokenType(lastPotentialCallable); - highlighted += colorize(defs, type2, lastPotentialCallable.value) + stackedHighlight, stackedHighlight = "", lastPotentialCallable = null; - } - highlighted += colorize(defs, type, token.value); - } - return highlighted; -}; -function highlight$1(code, options = { jsx: false, colors: {} }) { - return code && highlightTokens(options.colors || {}, code, options.jsx); -} - -function getDefs(c) { - const Invalid = (text) => c.white(c.bgRed(c.bold(text))); - return { - Keyword: c.magenta, - IdentifierCapitalized: c.yellow, - Punctuator: c.yellow, - StringLiteral: c.green, - NoSubstitutionTemplate: c.green, - MultiLineComment: c.gray, - SingleLineComment: c.gray, - RegularExpressionLiteral: c.cyan, - NumericLiteral: c.blue, - TemplateHead: (text) => c.green(text.slice(0, text.length - 2)) + c.cyan(text.slice(-2)), - TemplateTail: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1)), - TemplateMiddle: (text) => c.cyan(text.slice(0, 1)) + c.green(text.slice(1, text.length - 2)) + c.cyan(text.slice(-2)), - IdentifierCallable: c.blue, - PrivateIdentifierCallable: (text) => `#${c.blue(text.slice(1))}`, - Invalid, - JSXString: c.green, - JSXIdentifier: c.yellow, - JSXInvalid: Invalid, - JSXPunctuator: c.yellow - }; -} -function highlight(code, options = { jsx: false }) { - return highlight$1(code, { - jsx: options.jsx, - colors: getDefs(options.colors || c) - }); -} - -export { highlight }; diff --git a/vanilla/node_modules/@vitest/utils/dist/index.d.ts b/vanilla/node_modules/@vitest/utils/dist/index.d.ts deleted file mode 100644 index d4435cc..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export { LoupeOptions, StringifyOptions } from './display.js'; -export { DeferPromise } from './helpers.js'; -export { SafeTimers } from './timers.js'; -export { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError } from './types.js'; -import '@vitest/pretty-format'; diff --git a/vanilla/node_modules/@vitest/utils/dist/index.js b/vanilla/node_modules/@vitest/utils/dist/index.js deleted file mode 100644 index 8b13789..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/index.js +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vanilla/node_modules/@vitest/utils/dist/offset.d.ts b/vanilla/node_modules/@vitest/utils/dist/offset.d.ts deleted file mode 100644 index ae65386..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/offset.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -declare const lineSplitRE: RegExp; -declare function positionToOffset(source: string, lineNumber: number, columnNumber: number): number; -declare function offsetToLineNumber(source: string, offset: number): number; - -export { lineSplitRE, offsetToLineNumber, positionToOffset }; diff --git a/vanilla/node_modules/@vitest/utils/dist/offset.js b/vanilla/node_modules/@vitest/utils/dist/offset.js deleted file mode 100644 index d8cb08d..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/offset.js +++ /dev/null @@ -1,32 +0,0 @@ -const lineSplitRE = /\r?\n/; -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 i = 0; i < lineNumber - 1; i++) { - start += lines[i].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; -} - -export { lineSplitRE, offsetToLineNumber, positionToOffset }; diff --git a/vanilla/node_modules/@vitest/utils/dist/resolver.d.ts b/vanilla/node_modules/@vitest/utils/dist/resolver.d.ts deleted file mode 100644 index 71ebc63..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/resolver.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -declare function findNearestPackageData(basedir: string): { - type?: "module" | "commonjs"; -}; -declare function getCachedData<T>(cache: Map<string, T>, basedir: string, originalBasedir: string): NonNullable<T> | undefined; -declare function setCacheData<T>(cache: Map<string, T>, data: T, basedir: string, originalBasedir: string): void; - -export { findNearestPackageData, getCachedData, setCacheData }; diff --git a/vanilla/node_modules/@vitest/utils/dist/resolver.js b/vanilla/node_modules/@vitest/utils/dist/resolver.js deleted file mode 100644 index 83bd3c1..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/resolver.js +++ /dev/null @@ -1,71 +0,0 @@ -import fs from 'node:fs'; -import { j as join, d as dirname } from './chunk-pathe.M-eThtNZ.js'; - -const packageCache = new Map(); -function findNearestPackageData(basedir) { - const originalBasedir = basedir; - while (basedir) { - var _tryStatSync; - const cached = getCachedData(packageCache, basedir, originalBasedir); - if (cached) { - return cached; - } - const pkgPath = join(basedir, "package.json"); - if ((_tryStatSync = tryStatSync(pkgPath)) === null || _tryStatSync === void 0 ? void 0 : _tryStatSync.isFile()) { - const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8"))); - if (packageCache) { - setCacheData(packageCache, pkgData, basedir, originalBasedir); - } - return pkgData; - } - const nextBasedir = dirname(basedir); - if (nextBasedir === basedir) { - break; - } - basedir = nextBasedir; - } - return {}; -} -function stripBomTag(content) { - if (content.charCodeAt(0) === 65279) { - return content.slice(1); - } - return content; -} -function tryStatSync(file) { - try { - // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist - return fs.statSync(file, { throwIfNoEntry: false }); - } catch {} -} -function getCachedData(cache, basedir, originalBasedir) { - const pkgData = cache.get(getFnpdCacheKey(basedir)); - if (pkgData) { - traverseBetweenDirs(originalBasedir, basedir, (dir) => { - cache.set(getFnpdCacheKey(dir), pkgData); - }); - return pkgData; - } -} -function setCacheData(cache, data, basedir, originalBasedir) { - cache.set(getFnpdCacheKey(basedir), data); - traverseBetweenDirs(originalBasedir, basedir, (dir) => { - cache.set(getFnpdCacheKey(dir), data); - }); -} -function getFnpdCacheKey(basedir) { - return `fnpd_${basedir}`; -} -/** -* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir. -* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz` -* @param shorterDir Shorter dir path, e.g. `/User/foo` -*/ -function traverseBetweenDirs(longerDir, shorterDir, cb) { - while (longerDir !== shorterDir) { - cb(longerDir); - longerDir = dirname(longerDir); - } -} - -export { findNearestPackageData, getCachedData, setCacheData }; diff --git a/vanilla/node_modules/@vitest/utils/dist/serialize.d.ts b/vanilla/node_modules/@vitest/utils/dist/serialize.d.ts deleted file mode 100644 index dd8ee7d..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/serialize.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare function serializeValue(val: any, seen?: WeakMap<WeakKey, any>): any; - -export { serializeValue }; diff --git a/vanilla/node_modules/@vitest/utils/dist/serialize.js b/vanilla/node_modules/@vitest/utils/dist/serialize.js deleted file mode 100644 index f3ad0ad..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/serialize.js +++ /dev/null @@ -1,118 +0,0 @@ -const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@"; -const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@"; -function isImmutable(v) { - return v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]); -} -const OBJECT_PROTO = Object.getPrototypeOf({}); -function getUnserializableMessage(err) { - if (err instanceof Error) { - return `<unserializable>: ${err.message}`; - } - if (typeof err === "string") { - return `<unserializable>: ${err}`; - } - return "<unserializable>"; -} -// https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm -function serializeValue(val, seen = new WeakMap()) { - if (!val || typeof val === "string") { - return val; - } - if (val instanceof Error && "toJSON" in val && typeof val.toJSON === "function") { - const jsonValue = val.toJSON(); - if (jsonValue && jsonValue !== val && typeof jsonValue === "object") { - if (typeof val.message === "string") { - safe(() => jsonValue.message ?? (jsonValue.message = normalizeErrorMessage(val.message))); - } - if (typeof val.stack === "string") { - safe(() => jsonValue.stack ?? (jsonValue.stack = val.stack)); - } - if (typeof val.name === "string") { - safe(() => jsonValue.name ?? (jsonValue.name = val.name)); - } - if (val.cause != null) { - safe(() => jsonValue.cause ?? (jsonValue.cause = serializeValue(val.cause, seen))); - } - } - return serializeValue(jsonValue, seen); - } - if (typeof val === "function") { - return `Function<${val.name || "anonymous"}>`; - } - if (typeof val === "symbol") { - return val.toString(); - } - if (typeof val !== "object") { - return val; - } - if (typeof Buffer !== "undefined" && val instanceof Buffer) { - return `<Buffer(${val.length}) ...>`; - } - if (typeof Uint8Array !== "undefined" && val instanceof Uint8Array) { - return `<Uint8Array(${val.length}) ...>`; - } - // cannot serialize immutables as immutables - if (isImmutable(val)) { - return serializeValue(val.toJSON(), seen); - } - if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction") { - return "Promise"; - } - if (typeof Element !== "undefined" && val instanceof Element) { - return val.tagName; - } - if (typeof val.toJSON === "function") { - return serializeValue(val.toJSON(), seen); - } - if (seen.has(val)) { - return seen.get(val); - } - if (Array.isArray(val)) { - // eslint-disable-next-line unicorn/no-new-array -- we need to keep sparse arrays ([1,,3]) - const clone = new Array(val.length); - seen.set(val, clone); - val.forEach((e, i) => { - try { - clone[i] = serializeValue(e, seen); - } catch (err) { - clone[i] = getUnserializableMessage(err); - } - }); - return clone; - } else { - // Objects with `Error` constructors appear to cause problems during worker communication - // using `MessagePort`, so the serialized error object is being recreated as plain object. - const clone = Object.create(null); - seen.set(val, clone); - let obj = val; - while (obj && obj !== OBJECT_PROTO) { - Object.getOwnPropertyNames(obj).forEach((key) => { - if (key in clone) { - return; - } - try { - clone[key] = serializeValue(val[key], seen); - } catch (err) { - // delete in case it has a setter from prototype that might throw - delete clone[key]; - clone[key] = getUnserializableMessage(err); - } - }); - obj = Object.getPrototypeOf(obj); - } - if (val instanceof Error) { - safe(() => val.message = normalizeErrorMessage(val.message)); - } - return clone; - } -} -function safe(fn) { - try { - return fn(); - } catch {} -} -function normalizeErrorMessage(message) { - return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, ""); -} - -export { serializeValue }; diff --git a/vanilla/node_modules/@vitest/utils/dist/source-map.d.ts b/vanilla/node_modules/@vitest/utils/dist/source-map.d.ts deleted file mode 100644 index 582d24f..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/source-map.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { TestError, ParsedStack } from './types.js'; - -type OriginalMapping = { - source: string | null; - line: number; - column: number; - name: string | null; -}; - -interface StackTraceParserOptions { - ignoreStackEntries?: (RegExp | string)[]; - getSourceMap?: (file: string) => unknown; - getUrlId?: (id: string) => string; - frameFilter?: (error: TestError, frame: ParsedStack) => boolean | void; -} -declare const stackIgnorePatterns: (string | RegExp)[]; - -declare function parseSingleFFOrSafariStack(raw: string): ParsedStack | null; -declare function parseSingleStack(raw: string): ParsedStack | null; -declare function parseSingleV8Stack(raw: string): ParsedStack | null; -declare function createStackString(stacks: ParsedStack[]): string; -declare function parseStacktrace(stack: string, options?: StackTraceParserOptions): ParsedStack[]; -declare function parseErrorStacktrace(e: TestError | Error, options?: StackTraceParserOptions): ParsedStack[]; -interface SourceMapLike { - version: number; - mappings?: string; - names?: string[]; - sources?: string[]; - sourcesContent?: string[]; - sourceRoot?: string; -} -interface Needle { - line: number; - column: number; -} -declare class DecodedMap { - map: SourceMapLike; - _encoded: string; - _decoded: undefined | number[][][]; - _decodedMemo: Stats; - url: string; - version: number; - names: string[]; - resolvedSources: string[]; - constructor(map: SourceMapLike, from: string); -} -interface Stats { - lastKey: number; - lastNeedle: number; - lastIndex: number; -} -declare function getOriginalPosition(map: DecodedMap, needle: Needle): OriginalMapping | null; - -export { DecodedMap, createStackString, stackIgnorePatterns as defaultStackIgnorePatterns, getOriginalPosition, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace }; -export type { StackTraceParserOptions }; diff --git a/vanilla/node_modules/@vitest/utils/dist/source-map.js b/vanilla/node_modules/@vitest/utils/dist/source-map.js deleted file mode 100644 index b435c91..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/source-map.js +++ /dev/null @@ -1,478 +0,0 @@ -import { isPrimitive, notNullish } from './helpers.js'; -import { r as resolve } from './chunk-pathe.M-eThtNZ.js'; -import './constants.js'; - -// src/vlq.ts -var comma = ",".charCodeAt(0); -var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var intToChar = new Uint8Array(64); -var charToInt = new Uint8Array(128); -for (let i = 0; i < chars.length; i++) { - const c = chars.charCodeAt(i); - intToChar[i] = c; - charToInt[c] = i; -} -function decodeInteger(reader, relative) { - let value = 0; - let shift = 0; - let integer = 0; - do { - const c = reader.next(); - integer = charToInt[c]; - value |= (integer & 31) << shift; - shift += 5; - } while (integer & 32); - const shouldNegate = value & 1; - value >>>= 1; - if (shouldNegate) { - value = -2147483648 | -value; - } - return relative + value; -} -function hasMoreVlq(reader, max) { - if (reader.pos >= max) return false; - return reader.peek() !== comma; -} -var StringReader = class { - constructor(buffer) { - this.pos = 0; - this.buffer = buffer; - } - next() { - return this.buffer.charCodeAt(this.pos++); - } - peek() { - return this.buffer.charCodeAt(this.pos); - } - indexOf(char) { - const { buffer, pos } = this; - const idx = buffer.indexOf(char, pos); - return idx === -1 ? buffer.length : idx; - } -}; - -// src/sourcemap-codec.ts -function decode(mappings) { - const { length } = mappings; - const reader = new StringReader(mappings); - const decoded = []; - let genColumn = 0; - let sourcesIndex = 0; - let sourceLine = 0; - let sourceColumn = 0; - let namesIndex = 0; - do { - const semi = reader.indexOf(";"); - const line = []; - let sorted = true; - let lastCol = 0; - genColumn = 0; - while (reader.pos < semi) { - let seg; - genColumn = decodeInteger(reader, genColumn); - if (genColumn < lastCol) sorted = false; - lastCol = genColumn; - if (hasMoreVlq(reader, semi)) { - sourcesIndex = decodeInteger(reader, sourcesIndex); - sourceLine = decodeInteger(reader, sourceLine); - sourceColumn = decodeInteger(reader, sourceColumn); - if (hasMoreVlq(reader, semi)) { - namesIndex = decodeInteger(reader, namesIndex); - seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; - } else { - seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; - } - } else { - seg = [genColumn]; - } - line.push(seg); - reader.pos++; - } - if (!sorted) sort(line); - decoded.push(line); - reader.pos = semi + 1; - } while (reader.pos <= length); - return decoded; -} -function sort(line) { - line.sort(sortComparator); -} -function sortComparator(a, b) { - return a[0] - b[0]; -} - -// src/trace-mapping.ts - -// src/sourcemap-segment.ts -var COLUMN = 0; -var SOURCES_INDEX = 1; -var SOURCE_LINE = 2; -var SOURCE_COLUMN = 3; -var NAMES_INDEX = 4; - -// src/binary-search.ts -var found = false; -function binarySearch(haystack, needle, low, high) { - while (low <= high) { - const mid = low + (high - low >> 1); - const cmp = haystack[mid][COLUMN] - needle; - if (cmp === 0) { - found = true; - return mid; - } - if (cmp < 0) { - low = mid + 1; - } else { - high = mid - 1; - } - } - found = false; - return low - 1; -} -function upperBound(haystack, needle, index) { - for (let i = index + 1; i < haystack.length; index = i++) { - if (haystack[i][COLUMN] !== needle) break; - } - return index; -} -function lowerBound(haystack, needle, index) { - for (let i = index - 1; i >= 0; index = i--) { - if (haystack[i][COLUMN] !== needle) break; - } - return index; -} -function memoizedBinarySearch(haystack, needle, state, key) { - const { lastKey, lastNeedle, lastIndex } = state; - let low = 0; - let high = haystack.length - 1; - if (key === lastKey) { - if (needle === lastNeedle) { - found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; - return lastIndex; - } - if (needle >= lastNeedle) { - low = lastIndex === -1 ? 0 : lastIndex; - } else { - high = lastIndex; - } - } - state.lastKey = key; - state.lastNeedle = needle; - return state.lastIndex = binarySearch(haystack, needle, low, high); -} - -// src/trace-mapping.ts -var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; -var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; -var LEAST_UPPER_BOUND = -1; -var GREATEST_LOWER_BOUND = 1; -function cast(map) { - return map; -} -function decodedMappings(map) { - var _a; - return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded)); -} -function originalPositionFor(map, needle) { - let { line, column, bias } = needle; - line--; - if (line < 0) throw new Error(LINE_GTR_ZERO); - if (column < 0) throw new Error(COL_GTR_EQ_ZERO); - const decoded = decodedMappings(map); - if (line >= decoded.length) return OMapping(null, null, null, null); - const segments = decoded[line]; - const index = traceSegmentInternal( - segments, - cast(map)._decodedMemo, - line, - column, - bias || GREATEST_LOWER_BOUND - ); - if (index === -1) return OMapping(null, null, null, null); - const segment = segments[index]; - if (segment.length === 1) return OMapping(null, null, null, null); - const { names, resolvedSources } = map; - return OMapping( - resolvedSources[segment[SOURCES_INDEX]], - segment[SOURCE_LINE] + 1, - segment[SOURCE_COLUMN], - segment.length === 5 ? names[segment[NAMES_INDEX]] : null - ); -} -function OMapping(source, line, column, name) { - return { source, line, column, name }; -} -function traceSegmentInternal(segments, memo, line, column, bias) { - let index = memoizedBinarySearch(segments, column, memo, line); - if (found) { - index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); - } else if (bias === LEAST_UPPER_BOUND) index++; - if (index === -1 || index === segments.length) return -1; - return index; -} - -const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m; -const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/; -const stackIgnorePatterns = [ - "node:internal", - /\/packages\/\w+\/dist\//, - /\/@vitest\/\w+\/dist\//, - "/vitest/dist/", - "/vitest/src/", - "/node_modules/chai/", - "/node_modules/tinyspy/", - "/vite/dist/node/module-runner", - "/rolldown-vite/dist/node/module-runner", - "/deps/chunk-", - "/deps/@vitest", - "/deps/loupe", - "/deps/chai", - "/browser-playwright/dist/locators.js", - "/browser-webdriverio/dist/locators.js", - "/browser-preview/dist/locators.js", - /node:\w+/, - /__vitest_test__/, - /__vitest_browser__/, - /\/deps\/vitest_/ -]; -function extractLocation(urlLike) { - // Fail-fast but return locations like "(native)" - if (!urlLike.includes(":")) { - return [urlLike]; - } - const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/; - const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, "")); - if (!parts) { - return [urlLike]; - } - let url = parts[1]; - if (url.startsWith("async ")) { - url = url.slice(6); - } - if (url.startsWith("http:") || url.startsWith("https:")) { - const urlObj = new URL(url); - urlObj.searchParams.delete("import"); - urlObj.searchParams.delete("browserv"); - url = urlObj.pathname + urlObj.hash + urlObj.search; - } - if (url.startsWith("/@fs/")) { - const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url); - url = url.slice(isWindows ? 5 : 4); - } - return [ - url, - parts[2] || undefined, - parts[3] || undefined - ]; -} -function parseSingleFFOrSafariStack(raw) { - let line = raw.trim(); - if (SAFARI_NATIVE_CODE_REGEXP.test(line)) { - return null; - } - if (line.includes(" > eval")) { - line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1"); - } - // Early return for lines that don't look like Firefox/Safari stack traces - // Firefox/Safari stack traces must contain '@' and should have location info after it - if (!line.includes("@")) { - return null; - } - // Find the correct @ that separates function name from location - // For cases like '@https://@fs/path' or 'functionName@https://@fs/path' - // we need to find the first @ that precedes a valid location (containing :) - let atIndex = -1; - let locationPart = ""; - let functionName; - // Try each @ from left to right to find the one that gives us a valid location - for (let i = 0; i < line.length; i++) { - if (line[i] === "@") { - const candidateLocation = line.slice(i + 1); - // Minimum length 3 for valid location: 1 for filename + 1 for colon + 1 for line number (e.g., "a:1") - if (candidateLocation.includes(":") && candidateLocation.length >= 3) { - atIndex = i; - locationPart = candidateLocation; - functionName = i > 0 ? line.slice(0, i) : undefined; - break; - } - } - } - // Validate we found a valid location with minimum length (filename:line format) - if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) { - return null; - } - const [url, lineNumber, columnNumber] = extractLocation(locationPart); - if (!url || !lineNumber || !columnNumber) { - return null; - } - return { - file: url, - method: functionName || "", - line: Number.parseInt(lineNumber), - column: Number.parseInt(columnNumber) - }; -} -function parseSingleStack(raw) { - const line = raw.trim(); - if (!CHROME_IE_STACK_REGEXP.test(line)) { - return parseSingleFFOrSafariStack(line); - } - return parseSingleV8Stack(line); -} -// Based on https://github.com/stacktracejs/error-stack-parser -// Credit to stacktracejs -function parseSingleV8Stack(raw) { - let line = raw.trim(); - if (!CHROME_IE_STACK_REGEXP.test(line)) { - return null; - } - 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+/, ""); - // capture and preserve the parenthesized location "(/foo/my bar.js:12:87)" in - // case it has spaces in it, as the string is split on \s+ later on - const location = sanitizedLine.match(/ (\(.+\)$)/); - // remove the parenthesized location from the line, if it was matched - sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine; - // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine - // because this line doesn't have function name - const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine); - let method = location && sanitizedLine || ""; - let file = url && ["eval", "<anonymous>"].includes(url) ? undefined : url; - if (!file || !lineNumber || !columnNumber) { - return null; - } - if (method.startsWith("async ")) { - method = method.slice(6); - } - if (file.startsWith("file://")) { - file = file.slice(7); - } - // normalize Windows path (\ -> /) - file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file); - if (method) { - method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, ""); - } - return { - method, - file, - line: Number.parseInt(lineNumber), - column: Number.parseInt(columnNumber) - }; -} -function createStackString(stacks) { - return stacks.map((stack) => { - const line = `${stack.file}:${stack.line}:${stack.column}`; - if (stack.method) { - return ` at ${stack.method}(${line})`; - } - return ` at ${line}`; - }).join("\n"); -} -function parseStacktrace(stack, options = {}) { - const { ignoreStackEntries = stackIgnorePatterns } = options; - const stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack); - return stacks.map((stack) => { - var _options$getSourceMap; - if (options.getUrlId) { - stack.file = options.getUrlId(stack.file); - } - const map = (_options$getSourceMap = options.getSourceMap) === null || _options$getSourceMap === void 0 ? void 0 : _options$getSourceMap.call(options, stack.file); - if (!map || typeof map !== "object" || !map.version) { - return shouldFilter(ignoreStackEntries, stack.file) ? null : stack; - } - const traceMap = new DecodedMap(map, stack.file); - const position = getOriginalPosition(traceMap, stack); - if (!position) { - return stack; - } - const { line, column, source, name } = position; - let file = source || stack.file; - if (file.match(/\/\w:\//)) { - file = file.slice(1); - } - if (shouldFilter(ignoreStackEntries, file)) { - return null; - } - if (line != null && column != null) { - return { - line, - column, - file, - method: name || stack.method - }; - } - return stack; - }).filter((s) => s != null); -} -function shouldFilter(ignoreStackEntries, file) { - return ignoreStackEntries.some((p) => file.match(p)); -} -function parseFFOrSafariStackTrace(stack) { - return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish); -} -function parseV8Stacktrace(stack) { - return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish); -} -function parseErrorStacktrace(e, options = {}) { - if (!e || isPrimitive(e)) { - return []; - } - if ("stacks" in e && e.stacks) { - return e.stacks; - } - const stackStr = e.stack || ""; - // if "stack" property was overwritten at runtime to be something else, - // ignore the value because we don't know how to process it - let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : []; - if (!stackFrames.length) { - const e_ = e; - if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) { - stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options); - } - if (e_.sourceURL != null && e_.line != null && e_._column != null) { - stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options); - } - } - if (options.frameFilter) { - stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false); - } - e.stacks = stackFrames; - return stackFrames; -} -class DecodedMap { - _encoded; - _decoded; - _decodedMemo; - url; - version; - names = []; - resolvedSources; - constructor(map, from) { - this.map = map; - const { mappings, names, sources } = map; - this.version = map.version; - this.names = names || []; - this._encoded = mappings || ""; - this._decodedMemo = memoizedState(); - this.url = from; - this.resolvedSources = (sources || []).map((s) => resolve(s || "", from)); - } -} -function memoizedState() { - return { - lastKey: -1, - lastNeedle: -1, - lastIndex: -1 - }; -} -function getOriginalPosition(map, needle) { - const result = originalPositionFor(map, needle); - if (result.column == null) { - return null; - } - return result; -} - -export { DecodedMap, createStackString, stackIgnorePatterns as defaultStackIgnorePatterns, getOriginalPosition, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace }; diff --git a/vanilla/node_modules/@vitest/utils/dist/timers.d.ts b/vanilla/node_modules/@vitest/utils/dist/timers.d.ts deleted file mode 100644 index 8dd6025..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/timers.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -interface SafeTimers { - nextTick?: (cb: () => void) => void; - setImmediate?: { - <TArgs extends any[]>(callback: (...args: TArgs) => void, ...args: TArgs): any; - __promisify__: <T = void>(value?: T, options?: any) => Promise<T>; - }; - clearImmediate?: (immediateId: any) => void; - setTimeout: typeof setTimeout; - setInterval: typeof setInterval; - clearInterval: typeof clearInterval; - clearTimeout: typeof clearTimeout; - queueMicrotask: typeof queueMicrotask; -} -declare function getSafeTimers(): SafeTimers; -declare function setSafeTimers(): void; -/** -* Returns a promise that resolves after the specified duration. -* -* @param timeout - Delay in milliseconds -* @param scheduler - Timer function to use, defaults to `setTimeout`. Useful for mocked timers. -* -* @example -* await delay(100) -* -* @example -* // With mocked timers -* const { setTimeout } = getSafeTimers() -* await delay(100, setTimeout) -*/ -declare function delay(timeout: number, scheduler?: typeof setTimeout): Promise<void>; - -export { delay, getSafeTimers, setSafeTimers }; -export type { SafeTimers }; diff --git a/vanilla/node_modules/@vitest/utils/dist/timers.js b/vanilla/node_modules/@vitest/utils/dist/timers.js deleted file mode 100644 index 29229e5..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/timers.js +++ /dev/null @@ -1,49 +0,0 @@ -const SAFE_TIMERS_SYMBOL = Symbol("vitest:SAFE_TIMERS"); -function getSafeTimers() { - const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis; - const { nextTick: safeNextTick } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis.process || {}; - return { - nextTick: safeNextTick, - setTimeout: safeSetTimeout, - setInterval: safeSetInterval, - clearInterval: safeClearInterval, - clearTimeout: safeClearTimeout, - setImmediate: safeSetImmediate, - clearImmediate: safeClearImmediate, - queueMicrotask: safeQueueMicrotask - }; -} -function setSafeTimers() { - const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis; - const { nextTick: safeNextTick } = globalThis.process || {}; - const timers = { - nextTick: safeNextTick, - setTimeout: safeSetTimeout, - setInterval: safeSetInterval, - clearInterval: safeClearInterval, - clearTimeout: safeClearTimeout, - setImmediate: safeSetImmediate, - clearImmediate: safeClearImmediate, - queueMicrotask: safeQueueMicrotask - }; - globalThis[SAFE_TIMERS_SYMBOL] = timers; -} -/** -* Returns a promise that resolves after the specified duration. -* -* @param timeout - Delay in milliseconds -* @param scheduler - Timer function to use, defaults to `setTimeout`. Useful for mocked timers. -* -* @example -* await delay(100) -* -* @example -* // With mocked timers -* const { setTimeout } = getSafeTimers() -* await delay(100, setTimeout) -*/ -function delay(timeout, scheduler = setTimeout) { - return new Promise((resolve) => scheduler(resolve, timeout)); -} - -export { delay, getSafeTimers, setSafeTimers }; diff --git a/vanilla/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts b/vanilla/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts deleted file mode 100644 index cba06c6..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/types.d-BCElaP-c.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { CompareKeys } from '@vitest/pretty-format'; - -/** -* Copyright (c) Meta Platforms, Inc. and affiliates. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -type DiffOptionsColor = (arg: string) => string; -interface DiffOptions { - aAnnotation?: string; - aColor?: DiffOptionsColor; - aIndicator?: string; - bAnnotation?: string; - bColor?: DiffOptionsColor; - bIndicator?: string; - changeColor?: DiffOptionsColor; - changeLineTrailingSpaceColor?: DiffOptionsColor; - commonColor?: DiffOptionsColor; - commonIndicator?: string; - commonLineTrailingSpaceColor?: DiffOptionsColor; - contextLines?: number; - emptyFirstOrLastLinePlaceholder?: string; - expand?: boolean; - includeChangeCounts?: boolean; - omitAnnotationLines?: boolean; - patchColor?: DiffOptionsColor; - printBasicPrototype?: boolean; - maxDepth?: number; - compareKeys?: CompareKeys; - truncateThreshold?: number; - truncateAnnotation?: string; - truncateAnnotationColor?: DiffOptionsColor; -} -interface SerializedDiffOptions { - aAnnotation?: string; - aIndicator?: string; - bAnnotation?: string; - bIndicator?: string; - commonIndicator?: string; - contextLines?: number; - emptyFirstOrLastLinePlaceholder?: string; - expand?: boolean; - includeChangeCounts?: boolean; - omitAnnotationLines?: boolean; - printBasicPrototype?: boolean; - maxDepth?: number; - truncateThreshold?: number; - truncateAnnotation?: string; -} - -export type { DiffOptions as D, SerializedDiffOptions as S, DiffOptionsColor as a }; diff --git a/vanilla/node_modules/@vitest/utils/dist/types.d.ts b/vanilla/node_modules/@vitest/utils/dist/types.d.ts deleted file mode 100644 index 4e6d810..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/types.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -type Awaitable<T> = T | PromiseLike<T>; -type Nullable<T> = T | null | undefined; -type Arrayable<T> = T | Array<T>; -type ArgumentsType<T> = T extends (...args: infer U) => any ? U : never; -type MergeInsertions<T> = T extends object ? { [K in keyof T] : MergeInsertions<T[K]> } : T; -type DeepMerge< - F, - S -> = MergeInsertions<{ [K in keyof F | keyof S] : K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never }>; -interface Constructable { - new (...args: any[]): any; -} -interface ParsedStack { - method: string; - file: string; - line: number; - column: number; -} -interface SerializedError { - message: string; - stacks?: ParsedStack[]; - stack?: string; - name?: string; - cause?: SerializedError; - [key: string]: unknown; -} -interface TestError extends SerializedError { - cause?: TestError; - diff?: string; - actual?: string; - expected?: string; -} - -export type { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError }; diff --git a/vanilla/node_modules/@vitest/utils/dist/types.js b/vanilla/node_modules/@vitest/utils/dist/types.js deleted file mode 100644 index 8b13789..0000000 --- a/vanilla/node_modules/@vitest/utils/dist/types.js +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vanilla/node_modules/@vitest/utils/error.d.ts b/vanilla/node_modules/@vitest/utils/error.d.ts deleted file mode 100644 index 9329baa..0000000 --- a/vanilla/node_modules/@vitest/utils/error.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './dist/error.js' diff --git a/vanilla/node_modules/@vitest/utils/helpers.d.ts b/vanilla/node_modules/@vitest/utils/helpers.d.ts deleted file mode 100644 index 0add1d0..0000000 --- a/vanilla/node_modules/@vitest/utils/helpers.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './dist/helpers.js' diff --git a/vanilla/node_modules/@vitest/utils/package.json b/vanilla/node_modules/@vitest/utils/package.json deleted file mode 100644 index 1b8b19d..0000000 --- a/vanilla/node_modules/@vitest/utils/package.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "name": "@vitest/utils", - "type": "module", - "version": "4.0.18", - "description": "Shared Vitest utility functions", - "license": "MIT", - "funding": "https://opencollective.com/vitest", - "homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/utils#readme", - "repository": { - "type": "git", - "url": "git+https://github.com/vitest-dev/vitest.git", - "directory": "packages/utils" - }, - "bugs": { - "url": "https://github.com/vitest-dev/vitest/issues" - }, - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "./diff": { - "types": "./dist/diff.d.ts", - "default": "./dist/diff.js" - }, - "./resolver": { - "types": "./dist/resolver.d.ts", - "default": "./dist/resolver.js" - }, - "./error": { - "types": "./dist/error.d.ts", - "default": "./dist/error.js" - }, - "./helpers": { - "types": "./dist/helpers.d.ts", - "default": "./dist/helpers.js" - }, - "./offset": { - "types": "./dist/offset.d.ts", - "default": "./dist/offset.js" - }, - "./constants": { - "types": "./dist/constants.d.ts", - "default": "./dist/constants.js" - }, - "./timers": { - "types": "./dist/timers.d.ts", - "default": "./dist/timers.js" - }, - "./display": { - "types": "./dist/display.d.ts", - "default": "./dist/display.js" - }, - "./highlight": { - "types": "./dist/highlight.d.ts", - "default": "./dist/highlight.js" - }, - "./source-map": { - "types": "./dist/source-map.d.ts", - "default": "./dist/source-map.js" - }, - "./serialize": { - "types": "./dist/serialize.d.ts", - "default": "./dist/serialize.js" - }, - "./*": "./*" - }, - "main": "./dist/index.js", - "module": "./dist/index.js", - "types": "./dist/index.d.ts", - "typesVersions": { - "*": { - "source-map": [ - "dist/source-map.d.ts" - ] - } - }, - "files": [ - "*.d.ts", - "dist" - ], - "dependencies": { - "tinyrainbow": "^3.0.3", - "@vitest/pretty-format": "4.0.18" - }, - "devDependencies": { - "@jridgewell/trace-mapping": "0.3.31", - "@types/estree": "^1.0.8", - "diff-sequences": "^29.6.3", - "loupe": "^3.2.1", - "tinyhighlight": "^0.3.2" - }, - "scripts": { - "build": "premove dist && rollup -c", - "dev": "rollup -c --watch" - } -}
\ No newline at end of file |
