UNPKG

histoire

Version:

A fast story book powered by Vite

245 lines (244 loc) • 10.1 kB
// src/node/virtual/vitest-static-mock-runtime/module-ids.ts /** * Module-id string helpers shared by the static (build mode) mock resolution. * * In build mode there is no Vite dev server to ask, so mocked modules can only * be matched by comparing import specifiers found in the emitted chunks. */ /** Extracts static and dynamic import specifiers from Vite-built JavaScript. */ function getImportSpecifiers(source) { const result = /* @__PURE__ */ new Set(); for (const regexp of [ /\bimport\s*\(\s*(?:\/\*[\s\S]*?\*\/\s*)?["']([^"']+)["']/g, /\bfrom\s*["']([^"']+)["']/g, /\bimport\s*["']([^"']+)["']/g ]) while (true) { const match = regexp.exec(source); if (!match) break; result.add(match[1]); } return result; } /** Returns true for import specifiers that can be resolved in the current build. */ function isRelativeOrAbsoluteSpecifier(value) { return value.startsWith(".") || value.startsWith("/"); } /** Normalizes a source import id so it can be compared to a built chunk name. */ function getComparableModuleBase(id) { const segment = getLastPathSegment(id); return segment ? stripKnownExtensions(segment) : null; } /** Normalizes a Vite build chunk file name back to its source-like base name. */ function getComparableBuiltModuleBase(id) { return stripKnownExtensions(getLastPathSegment(id)).replace(/-(?=[\w-]*[A-Z0-9])[\w-]{8,12}$/, ""); } /** * Picks the candidate sharing the most trailing parent path segments with the * specifier. Returns null on a tie — a wrong pick would redirect a dynamic * import to a different module's mock. */ function pickByParentSegments(specifier, candidates) { const specifierParents = getParentSegments(specifier); let best = null; let bestScore = -1; let tied = false; for (const candidate of candidates) { const candidateParents = getParentSegments(candidate); let score = 0; while (score < specifierParents.length && score < candidateParents.length && specifierParents[specifierParents.length - 1 - score] === candidateParents[candidateParents.length - 1 - score]) score++; if (score > bestScore) { best = candidate; bestScore = score; tied = false; } else if (score === bestScore) tied = true; } return tied ? null : best; } /** Returns the path segments before the file name, without query or hash. */ function getParentSegments(id) { return id.split(/[?#]/)[0].split("/").filter(Boolean).slice(0, -1); } /** Returns the last path segment without query or hash. */ function getLastPathSegment(id) { return id.split(/[?#]/)[0].split("/").filter(Boolean).at(-1) ?? ""; } /** Removes source and build extensions that should not affect mock matching. */ function stripKnownExtensions(value) { let result = value; while (/\.(?:[cm]?[jt]sx?|vue|svelte)$/.test(result)) result = result.replace(/\.(?:[cm]?[jt]sx?|vue|svelte)$/, ""); return result; } // src/node/virtual/vitest-static-mock-runtime/mock-urls.ts var sourceCache = /* @__PURE__ */ new Map(); /** * Finds the built asset URL corresponding to a mocked raw import id. */ function findStaticMockImportUrl(source, rawId, importerUrl) { const rawBase = getComparableModuleBase(rawId); if (!rawBase) return null; const candidates = /* @__PURE__ */ new Set(); for (const specifier of getImportSpecifiers(source)) { if (!isRelativeOrAbsoluteSpecifier(specifier)) continue; const candidateUrl = new URL(specifier, importerUrl); if (getComparableBuiltModuleBase(candidateUrl.pathname) === rawBase) candidates.add(`${candidateUrl.pathname}${candidateUrl.search}${candidateUrl.hash}`); } if (candidates.size <= 1) return candidates.values().next().value ?? null; const match = pickByParentSegments(rawId, [...candidates]); if (match) return match; console.warn(`[histoire] Could not tell which built module "${rawId}" refers to: ${[...candidates].join(", ")} all match its file name. The Vitest mock was not applied to any of them.`); return null; } /** * Finds the registered mock URL referenced by a Vite dynamic import loader. */ function findStaticMockLoaderImportUrl(loaderSource, mockUrls) { const mockUrlsByBase = /* @__PURE__ */ new Map(); for (const mockUrl of mockUrls) { const base = getComparableBuiltModuleBase(mockUrl); const list = mockUrlsByBase.get(base) ?? []; list.push(mockUrl); mockUrlsByBase.set(base, list); } for (const specifier of getImportSpecifiers(loaderSource)) { const candidates = mockUrlsByBase.get(getComparableBuiltModuleBase(specifier)); if (!candidates?.length) continue; if (candidates.length === 1) return candidates[0]; const match = pickByParentSegments(specifier, candidates); if (match) return match; } return null; } /** Resolves a mocked source import to the hashed asset emitted by Vite build. */ async function resolveStaticMockUrl(rawId, importer) { const importerUrl = getImporterUrl(importer); if (!importerUrl) return null; const source = await readModuleSource(importerUrl).catch(() => null); return source ? findStaticMockImportUrl(source, rawId, importerUrl.href) : null; } /** Builds a best-effort URL when the transformed source does not expose a match. */ function resolveFallbackUrl(rawId, importer) { try { return new URL(rawId, getImporterUrl(importer) ?? window.location.href).pathname; } catch { return rawId; } } /** Adds a Vitest-style timestamp query that MSW strips when matching mocks. */ function getTimestampedMockUrl(url) { const resolved = new URL(url, window.location.href); resolved.searchParams.set("t", String(Date.now())); return `${resolved.pathname}${resolved.search}${resolved.hash}`; } /** Converts a stack-derived importer value into a fetchable URL. */ function getImporterUrl(importer) { if (!importer) return null; try { return new URL(importer, window.location.href); } catch { return null; } } /** Fetches and caches one built module source file. */ function readModuleSource(url) { const href = url.href; const cached = sourceCache.get(href); if (cached) return cached; const source = fetch(href).then(async (response) => { if (!response.ok) throw new Error(`Failed to read built module source ${href}: ${response.status}`); return await response.text(); }); sourceCache.set(href, source); return source; } // src/node/virtual/vitest-static-mock-runtime/service-worker.ts /** How long to wait for MSW's worker to claim the page before giving up (ms). */ var CONTROLLER_TIMEOUT = 1e3; /** * Returns MSW options scoped to the built Histoire base path. */ function createStaticPreviewMswOptions() { return { serviceWorker: { url: new URL("mockServiceWorker.js", window.location.href).pathname } }; } /** Waits until MSW's worker can intercept module script requests on this page. */ async function waitForServiceWorkerController() { if (!("serviceWorker" in navigator) || navigator.serviceWorker.controller) return; await navigator.serviceWorker.ready.catch(() => null); if (navigator.serviceWorker.controller) return; await new Promise((resolve) => { let timeout; const onControllerChange = () => { window.clearTimeout(timeout); resolve(); }; timeout = window.setTimeout(() => { navigator.serviceWorker.removeEventListener("controllerchange", onControllerChange); console.warn(`Histoire: the mock service worker did not claim this page within ${CONTROLLER_TIMEOUT}ms. Mocked modules may load unmocked.`); resolve(); }, CONTROLLER_TIMEOUT); navigator.serviceWorker.addEventListener("controllerchange", onControllerChange, { once: true }); }); } // src/node/virtual/vitest-static-mock-runtime/interception.ts /** Runs native dynamic import without Vite rewriting it through Vitest's wrapper. */ var nativeDynamicImport = new Function("url", "return import(url)"); /** * Extends Vitest's mock queue so imports wait for MSW to control the page. * * @param mocker Vitest's browser `ModuleMocker`, patched in place. */ function enableStaticPreviewMockInterception(mocker) { const originalQueueMock = mocker.queueMock.bind(mocker); const originalWrapDynamicImport = mocker.wrapDynamicImport.bind(mocker); mocker.queueMock = (...args) => { originalQueueMock(...args); const pendingRegistration = Array.from(mocker.queue).at(-1); if (!pendingRegistration) return; const controllerPromise = pendingRegistration.then(async () => { await waitForServiceWorkerController(); }).finally(() => { mocker.queue.delete(controllerPromise); }); mocker.queue.add(controllerPromise); }; mocker.wrapDynamicImport = (moduleFactory) => { const loaderSource = String(moduleFactory); const mockUrl = findStaticMockLoaderImportUrl(loaderSource, mocker.registry.keys()); if (mockUrl) return originalWrapDynamicImport(async () => { await waitForServiceWorkerController(); return await nativeDynamicImport(getTimestampedMockUrl(mockUrl)); }); if (!getImportSpecifiers(loaderSource).size) return moduleFactory(); return originalWrapDynamicImport(moduleFactory); }; } // src/node/virtual/vitest-static-mock-runtime/mock-rpc.ts /** * Creates the RPC shape consumed by Vitest's browser mocker in static previews. * * In dev the mocker talks to the Vite dev server over HMR; a built preview has * no server, so the same contract is answered from the emitted chunks instead. */ function createStaticPreviewMockRpc() { return { async resolveId(id, importer) { const resolvedUrl = await resolveStaticMockUrl(id, importer) ?? resolveFallbackUrl(id, importer); return { id: resolvedUrl, url: resolvedUrl, optimized: false }; }, async resolveMock(id, importer, options = {}) { const resolvedUrl = await resolveStaticMockUrl(id, importer) ?? resolveFallbackUrl(id, importer); return { mockType: options.mock === "factory" ? "manual" : options.mock === "spy" ? "autospy" : "automock", needsInterop: false, redirectUrl: null, resolvedId: resolvedUrl, resolvedUrl }; }, async invalidate() {} }; } export { createStaticPreviewMockRpc, createStaticPreviewMswOptions, enableStaticPreviewMockInterception, findStaticMockImportUrl, findStaticMockLoaderImportUrl };