UNPKG

histoire

Version:

A fast story book powered by Vite

162 lines (161 loc) • 7.98 kB
import pc from 'picocolors'; import { ExecutionError } from '../runtime/execution-types.js'; import { cleanupVitestBrowserRun } from '../vitest-browser-cleanup.js'; import { assignVitestBrowserProjectOptions } from '../vitest-browser-config/index.js'; import { debugVitestBrowser } from './browser-debug.js'; import { prepareTestBrowser } from './collection-browser.js'; import { loadProjectVitest } from './project-vitest.js'; import { throwIfTestAborted, withTestAbort } from './test-abort.js'; import { CLEANUP_TIMEOUT } from './test-timeouts.js'; import { formatVitestError } from './vitest-errors.js'; import { shouldRetryVitestBrowserRun } from './vitest-retry.js'; import { runWithVitestStartTimeout } from './vitest-start-timeout.js'; /** Cancellation notification must precede RPC teardown; a stuck user import cannot hold it forever. */ async function cancelVitestBeforeCleanup(vitest) { let timer; const cancellation = Promise.resolve().then(() => vitest.cancelCurrentRun?.('keyboard-input')); void cancellation.catch(() => { }); try { await Promise.race([cancellation.catch(() => { }), new Promise((resolve) => { timer = setTimeout(resolve, 1000); })]); } finally { clearTimeout(timer); } } /** Upper bound for interrupted startup to acquire what cleanup must release. */ const INTERRUPTED_STARTUP_SETTLE_TIMEOUT = 5000; /** * Waits, bounded, for browser startup an abort or timeout race stopped observing. * * `withTestAbort` rejects immediately, but browser server and provider startup * keep running: a Playwright browser launched after cleanup captured providers * would outlive the run and keep the isolated worker process alive. Startup * never executes user code, unlike collection/start, which may hang forever. * @param work Interrupted browser startup, if it began. */ async function settleInterruptedStartup(work) { if (!work) return; let timer; try { await Promise.race([work.catch(() => { }), new Promise((resolve) => { timer = setTimeout(resolve, INTERRUPTED_STARTUP_SETTLE_TIMEOUT); })]); } finally { clearTimeout(timer); } } /** * Tear down a run. Controller-owned runs reject any unconfirmed cleanup; CLI * callers retain best-effort warnings. * * Strict cleanup failure blocks the shared execution lane even when assertions * finished successfully. Best-effort CLI cleanup warns and retains the original * run error so diagnostics and existing browser-crash retry remain useful. * @param vitest The Vitest instance to tear down. * @param label Human-readable name of the run. * @param originalError The error currently being handled, if any. * @param strict Require confirmed teardown for a long-lived shared execution lane. */ async function cleanupRun(vitest, label, originalError, strict = false, runId) { const started = performance.now(); try { const outcome = await cleanupVitestBrowserRun(vitest, { label, timeoutMs: CLEANUP_TIMEOUT }); if (strict && outcome?.status === 'unconfirmed') { throw new ExecutionError('CLEANUP_UNCONFIRMED', `${label} cleanup could not be confirmed`, originalError); } } catch (cleanupError) { if (strict) throw new ExecutionError('CLEANUP_UNCONFIRMED', `${label} cleanup could not be confirmed`, cleanupError); console.warn(pc.yellow(`${label} cleanup failed: ${formatVitestError(cleanupError)}`)); // Keep the teardown failure reachable for debugging, but never overwrite an // existing cause chain of the error that actually failed the run. if (originalError instanceof Error && originalError.cause === undefined) { originalError.cause = cleanupError; } } finally { debugVitestBrowser('collection:cleanup', { runId, label, duration: performance.now() - started }); } } /** * Runs a Vitest browser run, retrying it once when the browser crashed. * * Shared by the story collection and the test execution: both create a Vitest * instance from a freshly built config, start it under a safety timeout, read * the outcome and tear the instance down on every path. * @param options Run configuration (see {@link RunVitestAttemptsOptions}). */ export async function runVitestAttempts(options) { const maxRetries = options.maxRetries ?? 1; let retryCount = 0; while (true) { throwIfTestAborted(options.signal); const setupStarted = performance.now(); const setup = options.mode === 'collect' ? await withTestAbort(options.setup, options.signal) : await options.setup(); if (options.mode === 'collect') debugVitestBrowser('collection:config', { runId: options.runId, duration: performance.now() - setupStarted }); throwIfTestAborted(options.signal); const api = await loadProjectVitest(options.root); throwIfTestAborted(options.signal); let vitest; let cleanupStarted = false; let startup; try { // Observe late creation even after abort: only the acquired handle can confirm teardown. const acquired = performance.now(); vitest = await api.createVitest('test', setup.vitestOptions, setup.viteConfig); if (options.mode === 'collect') debugVitestBrowser('collection:startup', { runId: options.runId, duration: performance.now() - acquired }); throwIfTestAborted(options.signal); if (setup.browserProjectOptions) { assignVitestBrowserProjectOptions(vitest, setup.browserProjectOptions); } await runWithVitestStartTimeout(() => withTestAbort(async () => { if (options.mode === 'collect' || setup.prepareBrowser) { await (startup = prepareTestBrowser(vitest, options.runId, options.mode === 'collect')); throwIfTestAborted(options.signal); } if (options.mode === 'collect') { return vitest.collect(setup.filter ?? [], { staticParse: false }); } return vitest.start(setup.filter ?? []); }, options.signal), { timeoutMs: options.deadline === undefined ? setup.timeoutMs : Math.max(1, options.deadline - Date.now()), activity: setup.activity, message: setup.timeoutMessage, onTimeout: () => setup.onTimeout?.(vitest), }); throwIfTestAborted(options.signal); const result = await options.read(vitest, setup.context); throwIfTestAborted(options.signal); cleanupStarted = true; await cleanupRun(vitest, options.label, undefined, options.strictCleanup, options.runId); return result; } catch (error) { if (vitest && !cleanupStarted) { if (options.signal?.aborted || options.mode === 'collect') { // Vitest must stop queued testers before browser teardown. Otherwise // closing its RPC page is classified as a fatal run, and late pool // work can exit the isolated worker without a cleanup acknowledgement. // Resource release still waits for cleanupRun, even if cancellation fails. await cancelVitestBeforeCleanup(vitest); } await settleInterruptedStartup(startup); await cleanupRun(vitest, options.label, error, options.strictCleanup, options.runId); } throwIfTestAborted(options.signal); if (retryCount < maxRetries && shouldRetryVitestBrowserRun(error, vitest)) { retryCount++; console.warn(pc.yellow(options.retryMessage)); continue; } throw error; } } }