This commit is contained in:
2026-08-14 16:03:47 +01:00
parent fd53e3f4fb
commit dfdc3b2840
2463 changed files with 186456 additions and 111315 deletions
+41 -30
View File
@@ -1,25 +1,8 @@
import { c as createSimpleStackTrace } from './chunk-helpers.js';
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) {
@@ -126,6 +109,8 @@ for (let i = 0; i < chars.length; i++) {
}
const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
function extractLocation(urlLike) {
// Fail-fast but return locations like "(native)"
if (!urlLike.includes(":")) {
@@ -150,6 +135,9 @@ function extractLocation(urlLike) {
const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
url = url.slice(isWindows ? 5 : 4);
}
if (url.includes("vitest=")) {
url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
}
return [
url,
parts[2] || undefined,
@@ -243,7 +231,7 @@ function parseSingleV8Stack(raw) {
// 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, "");
method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
}
return {
method,
@@ -254,7 +242,7 @@ function parseSingleV8Stack(raw) {
}
function createCompilerHints(options) {
const globalThisAccessor = (options === null || options === void 0 ? void 0 : options.globalThisKey) || "__vitest_mocker__";
const globalThisAccessor = options?.globalThisKey || "__vitest_mocker__";
function _mocker() {
// @ts-expect-error injected by the plugin
return typeof globalThis[globalThisAccessor] !== "undefined" ? globalThis[globalThisAccessor] : new Proxy({}, { get(_, name) {
@@ -310,7 +298,7 @@ function getImporter(name) {
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) || "";
return stack?.file || "";
}
const hot = import.meta.hot || {
@@ -385,7 +373,7 @@ class ModuleMocker {
throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`);
}
const ext = extname(resolved.id);
const url = new URL(resolved.url, location.href);
const url = new URL(resolved.url, this.getBaseUrl());
const query = `_vitest_original&ext${ext}`;
const actualUrl = `${url.pathname}${url.search ? `${url.search}&${query}` : `?${query}`}${url.hash}`;
return this.wrapDynamicImport(() => import(
@@ -397,12 +385,15 @@ class ModuleMocker {
}
// 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 : {
return m?.__esModule ? m : {
...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
default: m
};
});
}
getBaseUrl() {
return location.href;
}
async importMock(rawId, importer) {
await this.prepare();
const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" });
@@ -410,7 +401,7 @@ class ModuleMocker {
let mock = this.registry.get(mockUrl);
if (!mock) {
if (redirectUrl) {
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString();
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString();
mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect);
} else {
mock = new AutomockedModule(rawId, resolvedId, mockUrl);
@@ -420,7 +411,7 @@ class ModuleMocker {
return await mock.resolve();
}
if (mock.type === "automock" || mock.type === "autospy") {
const url = new URL(`/@id/${resolvedId}`, location.href);
const url = new URL(`/@id/${resolvedId}`, this.getBaseUrl());
const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`;
const moduleObject = await import(
/* @vite-ignore */
@@ -433,8 +424,16 @@ class ModuleMocker {
mock.redirect
);
}
mockObject(object, moduleType = "automock") {
return mockObject({
mockObject(object, mockExportsOrModuleType, moduleType) {
let mockExports;
if (mockExportsOrModuleType === "automock" || mockExportsOrModuleType === "autospy") {
moduleType = mockExportsOrModuleType;
mockExports = undefined;
} else {
mockExports = mockExportsOrModuleType;
}
moduleType ??= "automock";
const result = mockObject({
globalConstructors: {
Object,
Function,
@@ -444,10 +443,14 @@ class ModuleMocker {
},
createMockInstance: this.createMockInstance,
type: moduleType
}, object);
}, object, mockExports);
return result;
}
getMockContext() {
return { callstack: null };
}
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 promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : 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 () => {
@@ -456,7 +459,7 @@ class ModuleMocker {
// 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;
const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString() : null;
let module;
if (mockType === "manual") {
module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory);
@@ -500,6 +503,14 @@ class ModuleMocker {
}
return moduleFactory;
}
getMockedModuleById(id) {
return this.registry.getById(id);
}
reset() {
this.registry.clear();
this.mockedIds.clear();
this.queue.clear();
}
resolveMockPath(path) {
const config = this.config;
const fsRoot = join("/@fs/", config.root);