UNPKG

histoire

Version:

A fast story book powered by Vite

1,367 lines • 54.5 kB
import { TEST_REGISTRY_KEY, collectHistoireTests, createHistoireTestSummary, createStoryExecutionOwner, getHistoireTestTaskCallbackTimeout, getStoryExecutionId, readHistoireTestData, registerHistoireTestTaskCallback, serializeTestDefinitions, serializeTestError } from "@histoire/shared";
import { isGeneratedStoryKnownEmpty } from "../../node/generated-story-metadata.js";
import { GenericMountStory, GenericRenderStory } from "@histoire/app/sandbox";
import FloatingVue from "@histoire/vendors/floating-vue";
import { createPinia } from "@histoire/vendors/pinia";
import { createApp, h, markRaw, nextTick, reactive } from "@histoire/vendors/vue";
// src/node/virtual/variant-test-session/definitions.ts
/**
* Builds the error reported when a collected definition has no runnable
* handler. Shared by the single-test and whole-variant run paths so both
* surface the exact same message.
* @param fullName Full name of the test that could not be resolved.
* @param storyId Story the test belongs to.
* @param variantId Variant the test belongs to.
*/
function createMissingHandlerError(fullName, storyId, variantId) {
	return /* @__PURE__ */ new Error(`Could not resolve histoire test "${fullName}" for ${storyId}:${variantId}`);
}
/**
* Removes semantically duplicated tests emitted when the same story setup runs
* once during bootstrap mounting and again during render mounting.
*
* Deduplication is occurrence-aware per GROUP (one group = one execution of
* the story setup, see `groupRegistrationsByExecution`): loop-generated tests
* inside a single group legitimately share name + handler source
* (`items.forEach(item => it('works', …))`) and must all be kept, while
* re-registrations of the same tests by a later group must be dropped. For each
* key, the final count is the maximum occurrence count observed in any single
* group.
*
* A dropped duplicate still hands its handler over to the kept definition: the
* groups are ordered by mount phase, so the LAST group that registered a test
* is the one whose closure belongs to the render mount — the only mount whose
* DOM the shared collection context (`canvas`) points at. Keeping an earlier
* mount's closure would assert against the bootstrap mount's setup scope, which
* never rendered the variant.
*
* Only a group the session itself mounted may hand its handler over: the
* ambient registry is process-wide, so a story copy mounted elsewhere (the
* visible preview re-rendering the same story) forms its own group after the
* render one, and its handlers close over a setup scope that belongs to another
* canvas entirely.
*/
function dedupeCollectedTestDefinitionGroups(groups) {
	const emitted = /* @__PURE__ */ new Map();
	const result = [];
	for (const group of groups) {
		const groupCounts = /* @__PURE__ */ new Map();
		for (const definition of group.definitions) {
			const key = `${definition.mode ?? "run"}\n${definition.fullName}\n${definition.handler?.toString() ?? ""}`;
			const occurrence = (groupCounts.get(key) ?? 0) + 1;
			groupCounts.set(key, occurrence);
			const previous = emitted.get(key) ?? [];
			if (occurrence > previous.length) {
				const entry = {
					...definition,
					id: String(result.length)
				};
				previous.push(entry);
				emitted.set(key, previous);
				result.push(entry);
				continue;
			}
			if (definition.handler && group.own) {
				previous[occurrence - 1].handler = definition.handler;
				previous[occurrence - 1].hookScopes = definition.hookScopes;
			}
		}
	}
	return result;
}
/**
* Resolves the live test definition that corresponds to a previously serialized
* one. Positional ids (`String(index)`) are only valid when the collect and run
* passes register tests in the exact same order; nondeterministic ordering would
* otherwise run the wrong handler. This matches by stable identity (fullName +
* mode) and only trusts the positional id when it also agrees on identity.
* @param definitions The freshly re-collected definitions for this variant.
* @param serialized The serialized definition captured during collection.
* @returns The matching live definition, or `undefined` for a genuine miss.
*/
function getMatchingDefinition(definitions, serialized) {
	const sameMode = (a, b) => (a ?? "run") === (b ?? "run");
	const byId = definitions.find((d) => d.id === serialized.id);
	if (byId && byId.fullName === serialized.fullName && sameMode(byId.mode, serialized.mode)) return byId;
	const matches = definitions.filter((d) => d.fullName === serialized.fullName && sameMode(d.mode, serialized.mode));
	return matches.length === 1 ? matches[0] : void 0;
}
// src/node/virtual/variant-test-session/exclusive.ts
/**
* Creates a one-at-a-time queue for session work.
*
* Overlapping collect/run flows would otherwise interleave their global
* test-registry save/restore (see `withRegistry`) and corrupt
* `__HST_TEST_REGISTRY__`. The preview runtime creates a single session object,
* so one chain per session is enough to guard the shared globalThis.
* @returns A `runExclusive(fn)` function resolving/rejecting with `fn`'s result.
*/
function createExclusiveQueue() {
	let chain = Promise.resolve();
	return function runExclusive(fn) {
		const result = chain.then(fn, fn);
		chain = result.then(() => void 0, () => void 0);
		return result;
	};
}
// src/node/virtual/variant-test-session/registry.ts
var TEST_FLAG_KEY = "__HST_TEST__";
/**
* Installs `registry` as the ambient test registry (and `testing` as the
* ambient test flag) for the duration of `fn`, then restores the previous
* values. Story setup code registers tests by pushing onto the global, so this
* is the only channel through which a mount phase's registrations are captured.
*
* The globals are shared process-wide, which is why session work is serialized
* (see `createExclusiveQueue`) instead of running concurrently.
* @param registry Array collecting the registrations emitted by `fn`.
* @param testing Value of the ambient `__HST_TEST__` flag during `fn`.
* @param fn The work to run with the registry installed.
*/
function withRegistry(registry, testing, fn) {
	const previousRegistry = globalThis[TEST_REGISTRY_KEY];
	const previousFlag = globalThis[TEST_FLAG_KEY];
	globalThis[TEST_REGISTRY_KEY] = registry;
	globalThis[TEST_FLAG_KEY] = testing;
	return Promise.resolve().then(fn).finally(() => {
		globalThis[TEST_REGISTRY_KEY] = previousRegistry;
		globalThis[TEST_FLAG_KEY] = previousFlag;
	});
}
// src/node/virtual/variant-test-session/expect-state.ts
var SHARED_EXPECT_KEY = Symbol.for("expect-global");
var STORY_EXPECT_KEY = Symbol.for("histoire:story-expect");
/** Reads the shared expect object installed by Vitest (or the preview shim). */
function getSharedExpect() {
	const globals = globalThis;
	return globals[STORY_EXPECT_KEY] ?? globals[SHARED_EXPECT_KEY];
}
/** Selects Vitest's context-local expect when a test requested it. */
function getTaskExpect(context) {
	return context?._local ? context.expect : getSharedExpect();
}
/**
* Resets the global expect bookkeeping (`assertionCalls`, `expect.assertions(n)`,
* `expect.hasAssertions()`) so they don't leak between consecutive test handlers
* inside the same iframe runtime.
*/
function resetSharedExpectState() {
	const sharedExpect = getSharedExpect();
	if (typeof sharedExpect?.setState !== "function") return;
	sharedExpect.setState({
		assertionCalls: 0,
		isExpectingAssertions: false,
		isExpectingAssertionsError: null,
		expectedAssertionsNumber: null,
		expectedAssertionsNumberErrorGen: null
	});
}
/**
* Mirrors Vitest's end-of-test assertion bookkeeping checks for the lightweight
* preview expect shim.
*/
function assertSharedExpectState(context) {
	const taskExpect = getTaskExpect(context);
	if (typeof taskExpect?.getState !== "function") return;
	const state = taskExpect.getState();
	const assertionCalls = state?.assertionCalls ?? 0;
	if (typeof state?.expectedAssertionsNumber === "number" && assertionCalls !== state.expectedAssertionsNumber) throw typeof state.expectedAssertionsNumberErrorGen === "function" ? state.expectedAssertionsNumberErrorGen() : /* @__PURE__ */ new Error(`expected number of assertions to be ${state.expectedAssertionsNumber}, but got ${assertionCalls}`);
	if (state?.isExpectingAssertions && assertionCalls === 0) throw state.isExpectingAssertionsError instanceof Error ? state.isExpectingAssertionsError : /* @__PURE__ */ new Error("expected any number of assertion, but got none");
}
/**
* Completes Vitest's body assertion check before teardown hooks can make more
* assertions. The real runner performs this check before `afterEach`; clearing
* the expectation also prevents its outer generated test from checking again.
*/
function assertAndClearSharedExpectState(context) {
	const taskExpect = getTaskExpect(context);
	try {
		assertSharedExpectState(context);
	} finally {
		taskExpect?.setState?.({
			isExpectingAssertions: false,
			isExpectingAssertionsError: null,
			expectedAssertionsNumber: null,
			expectedAssertionsNumberErrorGen: null
		});
	}
}
// src/node/virtual/variant-test-session/worker-state.ts
/** Reads the worker installed by Vitest or preview bootstrap. */
function getVitestWorkerState() {
	return globalThis.__vitest_worker__;
}
/** Only isolated browser specs with confirmed teardown can retain the discovery mount. */
function getVitestBrowserMountCleanups() {
	const state = globalThis.__vitest_browser_runner__;
	const config = state?.config;
	if (!Array.isArray(state?.cleanups) || !(config?.browser?.isolate ?? config?.isolate)) return;
	if (config.clearMocks || config.mockReset || config.restoreMocks || config.unstubEnvs || config.unstubGlobals) return;
	return state.cleanups;
}
// src/node/virtual/variant-test-session/timeouts.ts
var DEFAULT_HOOK_TIMEOUT = 1e4;
var DEFAULT_TEST_TIMEOUT = 5e3;
/** Reads a per-hook deadline, falling back to Vitest's configured default. */
function getHookTimeout(timeout) {
	return timeout ?? getVitestWorkerState()?.config?.hookTimeout ?? DEFAULT_HOOK_TIMEOUT;
}
/** Reads a per-test deadline, falling back to Vitest's configured default. */
function getTestTimeout(timeout) {
	return timeout ?? getVitestWorkerState()?.config?.testTimeout ?? DEFAULT_TEST_TIMEOUT;
}
/** Checks whether Vitest timeout handling is disabled. */
function isTimeoutDisabled(timeout) {
	return timeout <= 0 || timeout === Number.POSITIVE_INFINITY;
}
/** Builds Vitest's regular hook timeout error. */
function createHookTimeoutError(timeout) {
	return /* @__PURE__ */ new Error(`Hook timed out in ${timeout}ms.\nIf this is a long-running hook, pass a timeout value as the last argument or configure it globally with "hookTimeout".`);
}
/** Builds Vitest's regular test timeout error. */
function createTestTimeoutError(timeout) {
	return /* @__PURE__ */ new Error(`Test timed out in ${timeout}ms.\nIf this is a long-running test, pass a timeout value as the last argument or configure it globally with "testTimeout".`);
}
/** Applies a deadline while still handling later rejections from abandoned work. */
function withTimeout(promise, timeout, createError) {
	if (isTimeoutDisabled(timeout)) return promise;
	const start = Date.now();
	return new Promise((resolve, reject) => {
		let settled = false;
		const timer = setTimeout(() => {
			if (settled) return;
			settled = true;
			reject(createError());
		}, timeout);
		timer.unref?.();
		promise.then((value) => {
			if (settled) return;
			settled = true;
			clearTimeout(timer);
			if (Date.now() - start >= timeout) reject(createError());
			else resolve(value);
		}, (error) => {
			if (settled) return;
			settled = true;
			clearTimeout(timer);
			reject(error);
		});
	});
}
// src/node/virtual/variant-test-session/around-hooks.ts
/** Builds Vitest's around-hook phase timeout error. */
function createAroundHookTimeoutError(name, phase, timeout) {
	return /* @__PURE__ */ new Error(`The ${phase} phase of "${name}" hook timed out after ${timeout}ms.`);
}
/**
* Composes Vitest 4.1 around hooks with separate setup and teardown deadlines.
* A wrapper that resumes after setup timed out cannot enter later test work.
*/
async function runAroundHooks(hooks, runInner, context, hookName = "aroundEach") {
	let error;
	/** Retains first failure without blocking outer wrapper teardown. */
	function captureError(nextError) {
		error ??= nextError;
	}
	/** Runs one wrapper and then its nested wrapper. */
	async function dispatch(index) {
		const entry = hooks[index];
		if (!entry) {
			try {
				await runInner();
			} catch (innerError) {
				captureError(innerError);
			}
			return;
		}
		const timeout = getHookTimeout(entry.hook.timeout);
		let allowRun = true;
		let calls = 0;
		let innerPromise;
		let markRunCalled;
		const runCalled = new Promise((resolve) => {
			markRunCalled = resolve;
		});
		const run = async () => {
			if (!allowRun) return;
			calls++;
			if (calls > 1) {
				captureError(/* @__PURE__ */ new Error("Vitest around hook callback can only be called once."));
				return;
			}
			markRunCalled();
			innerPromise = dispatch(index + 1);
			await innerPromise;
		};
		const hookPromise = Promise.resolve().then(() => entry.hook.handler(run, context ?? {}, entry.suite));
		const setup = Promise.race([runCalled, hookPromise.then(() => {
			if (!calls) throw new Error("Vitest around hook did not call its run callback.");
		})]);
		try {
			await withTimeout(setup, timeout, () => createAroundHookTimeoutError(hookName, "setup", timeout));
		} catch (hookError) {
			allowRun = false;
			captureError(hookError);
			return;
		}
		await innerPromise;
		try {
			await withTimeout(hookPromise, timeout, () => createAroundHookTimeoutError(hookName, "teardown", timeout));
		} catch (hookError) {
			captureError(hookError);
		}
	}
	await dispatch(0);
	if (error) throw error;
}
/** Opens suite around hooks until their `runSuite` callback is reached. */
async function openAroundHooks(hooks, suite) {
	let release;
	let entered;
	const releasePromise = new Promise((resolve) => {
		release = resolve;
	});
	const enteredPromise = new Promise((resolve) => {
		entered = resolve;
	});
	const outcome = runAroundHooks(hooks.map((hook) => ({
		hook,
		suite
	})), async () => {
		entered();
		await releasePromise;
	}, void 0, "aroundAll").then(() => void 0, (error) => error);
	const openingError = await Promise.race([enteredPromise.then(() => void 0), outcome]);
	if (openingError) return { error: openingError };
	return { controller: { async close() {
		release();
		return await outcome;
	} } };
}
// src/node/virtual/variant-test-session/hooks.ts
/** Deadlines inherited by disposers returned from setup hooks. */
var cleanupTimeouts = /* @__PURE__ */ new WeakMap();
/** Remembers source-hook deadline for a cleanup Vitest runs later. */
function addCleanup(cleanups, cleanup, timeout) {
	if (!cleanups) return;
	const timedCleanup = async () => await cleanup();
	cleanupTimeouts.set(timedCleanup, timeout);
	cleanups.push(timedCleanup);
}
/** Runs hooks while preserving first error and optionally continuing cleanup. */
async function runHooks(hooks, context, suite, currentError, always = false, cleanups) {
	let error = currentError;
	for (const hook of hooks) {
		if (error && !always) break;
		try {
			if (typeof hook === "function") {
				const timeout = cleanupTimeouts.get(hook);
				if (timeout === void 0) await hook();
				else await withTimeout(Promise.resolve().then(hook), timeout, () => createHookTimeoutError(timeout));
				continue;
			}
			const timeout = getHookTimeout(hook.timeout);
			const cleanup = await withTimeout(Promise.resolve().then(() => hook.handler(context ?? {}, suite)), timeout, () => createHookTimeoutError(timeout));
			if (typeof cleanup === "function") addCleanup(cleanups, cleanup, timeout);
		} catch (hookError) {
			error ??= hookError;
		}
	}
	return error;
}
// src/node/virtual/variant-test-session/task-promises.ts
/**
* Drains assertions registered on a task, including ones added while draining.
* Ignore promises owned by the caller: a unit test may itself await this run
* through expect(...).rejects, which must never be awaited from inside the run.
*/
async function settleTestPromises(task, ignored = /* @__PURE__ */ new Set()) {
	const seen = new Set(ignored);
	const errors = [];
	if (!task) return errors;
	for (;;) {
		const pending = (task.promises ?? []).filter((promise) => !seen.has(promise));
		if (!pending.length) break;
		pending.forEach((promise) => seen.add(promise));
		const results = await Promise.allSettled(pending);
		for (const result of results) if (result.status === "rejected") errors.push(result.reason);
		task.promises = task.promises.filter((promise) => !pending.includes(promise));
	}
	return errors;
}
/**
* Detaches pending assertions after their owning test already failed or timed
* out. `allSettled` observes later rejections while allowing teardown to run.
*/
function discardTestPromises(task, ignored = /* @__PURE__ */ new Set()) {
	if (!task) return;
	const pending = (task.promises ?? []).filter((promise) => !ignored.has(promise));
	task.promises = task.promises?.filter((promise) => !pending.includes(promise));
	Promise.allSettled(pending);
}
// src/node/virtual/variant-test-session/test-task.ts
/** Tasks currently executing Histoire-collected story definitions. */
var histoireTasks = /* @__PURE__ */ new WeakSet();
/** Preview tasks report failures directly from their compatible task result. */
var previewTasks = /* @__PURE__ */ new WeakSet();
/** Marks a real Vitest task so nested lifecycle code can identify it safely. */
function enterHistoireTestTask(task) {
	if (!task || typeof task !== "object") return () => {};
	histoireTasks.add(task);
	return () => histoireTasks.delete(task);
}
/** Checks whether this task belongs to Histoire's embedded lifecycle. */
function isHistoireTestTask(task) {
	return !!task && typeof task === "object" && histoireTasks.has(task);
}
/** Creates the task and shared TestContext supplied to embedded callbacks. */
function createPreviewTestTask(definition, id, filepath) {
	const task = {
		id,
		type: "test",
		name: definition.name,
		fullTestName: definition.fullName,
		file: { filepath },
		meta: {},
		result: {
			state: "run",
			errors: []
		},
		onFailed: [],
		onFinished: [],
		context: {},
		promises: [],
		[STORY_EXPECT_KEY]: true
	};
	task.context = {
		task,
		expect: getSharedExpect(),
		onTestFailed: (callback, timeout) => registerHistoireTestTaskCallback(task, "onFailed", callback, timeout),
		onTestFinished: (callback, timeout) => registerHistoireTestTaskCallback(task, "onFinished", callback, timeout)
	};
	histoireTasks.add(task);
	previewTasks.add(task);
	return task;
}
/** Distinguishes tasks whose errors are read directly by the preview UI. */
function isPreviewTestTask(task) {
	return previewTasks.has(task);
}
// src/node/virtual/variant-test-session/run-definition.ts
/** Executes a test body, retaining a setup error instead of running the handler. */
async function runHandler(definition, storyId, variantId, context, task, callerPromises, error) {
	if (error) return error;
	try {
		if (!definition.handler) throw createMissingHandlerError(definition.fullName, storyId, variantId);
		const timeout = getTestTimeout(definition.timeout);
		await withTimeout(Promise.resolve().then(async () => {
			await definition.handler(context);
			const pendingErrors = await settleTestPromises(task, callerPromises);
			if (pendingErrors.length) throw pendingErrors.length === 1 ? pendingErrors[0] : new AggregateError(pendingErrors, "Pending assertions failed");
		}), timeout, () => createTestTimeoutError(timeout));
	} catch (handlerError) {
		discardTestPromises(task, callerPromises);
		return handlerError;
	}
}
/** Runs the shared per-test lifecycle, including disposers from successful setup hooks. */
async function runDefinitionWithHooks(definition, storyId, variantId, finish) {
	const scopes = definition.hookScopes ?? [];
	const task = getVitestWorkerState()?.current;
	const context = task?.context;
	const callerPromises = new Set(task?.promises ?? []);
	await runAroundHooks(scopes.flatMap((scope) => scope.aroundEach.map((hook) => ({
		hook,
		suite: scope.suite
	}))), async () => {
		const cleanups = [];
		let error;
		for (const scope of scopes) error = await runHooks(scope.beforeEach, context, scope.suite, error, false, cleanups);
		error = await runHandler(definition, storyId, variantId, context, task, callerPromises, error);
		if (!error && isHistoireTestTask(task)) try {
			assertAndClearSharedExpectState(context);
		} catch (assertionError) {
			error = assertionError;
		}
		for (const scope of [...scopes].reverse()) error = await runHooks([...scope.afterEach].reverse(), context, scope.suite, error, true);
		error = await runHooks(cleanups.reverse(), context, void 0, error, true);
		error = await finish?.(error) ?? error;
		if (error) throw error;
	}, context);
}
// src/node/virtual/variant-test-session/task-callbacks.ts
/**
* Runs story callbacks inside Histoire's lifecycle, before it releases mounts
* and wrapper resources. The outer Vitest runner only sees the final error;
* clearing its callback arrays prevents a second, too-late invocation.
*/
async function finishHistoireTestTask(task, initialError) {
	const errors = [];
	const taskErrors = task?.result ? task.result.errors ??= [] : void 0;
	const stagedTaskErrors = /* @__PURE__ */ new Set();
	/** Records failures for callbacks before the outer Vitest runner sees them. */
	function recordError(error) {
		if (error === void 0) return;
		errors.push(error);
		if (taskErrors && !taskErrors.includes(error)) {
			taskErrors.push(error);
			stagedTaskErrors.add(error);
		}
		if (task?.result) task.result.state = "fail";
	}
	/** Includes errors that Vitest's soft assertion plugin records directly. */
	function collectTaskErrors() {
		for (const error of task?.result?.errors ?? []) if (!errors.includes(error)) recordError(error);
	}
	/** Lets the outer runner append each returned lifecycle error exactly once. */
	function clearStagedTaskErrors() {
		if (task?.result && taskErrors && !isPreviewTestTask(task)) task.result.errors = taskErrors.filter((error) => !stagedTaskErrors.has(error));
	}
	/** Drains callbacks in Vitest's default LIFO order and settles their assertions. */
	async function runCallbacks(key) {
		const callbacks = task?.[key] ?? [];
		task[key] = void 0;
		for (const callback of [...callbacks].reverse()) try {
			const timeout = getHookTimeout(getHistoireTestTaskCallbackTimeout(callback));
			const pendingErrors = await withTimeout(Promise.resolve().then(async () => {
				await callback(task.context);
				return await settleTestPromises(task);
			}), timeout, () => createHookTimeoutError(timeout));
			for (const error of pendingErrors) recordError(error);
		} catch (error) {
			discardTestPromises(task);
			recordError(error);
		}
	}
	recordError(initialError);
	collectTaskErrors();
	if (!errors.length && task?.result) task.result.state = "pass";
	await runCallbacks("onFinished");
	collectTaskErrors();
	if (errors.length) await runCallbacks("onFailed");
	collectTaskErrors();
	clearStagedTaskErrors();
	if (!errors.length) return;
	return errors.length === 1 ? errors[0] : new AggregateError(errors, "Histoire test lifecycle failed");
}
// src/node/virtual/variant-test-session/run-single-definition.ts
/** Runs suite hooks around one isolated CLI test mount. */
async function runSingleDefinition(definition, storyId, variantId) {
	const scopes = definition.hookScopes ?? [];
	const task = getVitestWorkerState()?.current;
	let taskFinalized = false;
	/** Finalizes callbacks once, including setup failures that skip the test body. */
	async function finishTask(error) {
		if (!isHistoireTestTask(task) || taskFinalized) return error;
		taskFinalized = true;
		return await finishHistoireTestTask(task, error);
	}
	/** Enters one suite, guaranteeing cleanup before leaving its aroundAll wrapper. */
	async function runScope(index) {
		const scope = scopes[index];
		if (!scope) {
			await runDefinitionWithHooks(definition, storyId, variantId, finishTask);
			return;
		}
		await runAroundHooks(scope.aroundAll.map((hook) => ({
			hook,
			suite: scope.suite
		})), async () => {
			const cleanups = [];
			const context = getVitestWorkerState()?.current?.context;
			let error = await runHooks(scope.beforeAll, void 0, scope.suite, void 0, false, cleanups);
			if (!error) try {
				await runScope(index + 1);
			} catch (innerError) {
				error = innerError;
			}
			error = await finishTask(error) ?? error;
			error = await runHooks([...scope.afterAll].reverse(), void 0, scope.suite, error, true);
			error = await runHooks(cleanups.reverse(), context, void 0, error, true);
			if (error) throw error;
		}, void 0, "aroundAll");
	}
	try {
		await runScope(0);
	} catch (error) {
		throw await finishTask(error) ?? error;
	}
}
// src/node/virtual/variant-test-session/run-preview-definition.ts
/** Decides whether a definition must be reported without executing its body. */
function isSkipped$1(definition, hasFocusedTests) {
	return definition.mode === "skip" || definition.mode === "todo" || hasFocusedTests && definition.mode !== "only";
}
/** Builds the portable result returned from one hidden runtime document. */
function toResult$1(definition, state, errors, meta) {
	const data = readHistoireTestData(meta);
	return {
		id: definition.id,
		name: definition.name,
		fullName: definition.fullName,
		state,
		errors,
		...data ? { data } : {}
	};
}
/**
* Runs one collected definition in a fresh mounted session.
*
* Every hidden document owns one of these sessions. This intentionally runs
* suite-level hooks for each case, matching generated Vitest browser specs.
*/
async function runPreviewDefinition(session, storyId, variantId, serialized) {
	const definition = getMatchingDefinition(session.definitions, serialized);
	if (!definition) return createHistoireTestSummary(storyId, variantId, [toResult$1(serialized, "failed", [serializeTestError(createMissingHandlerError(serialized.fullName, storyId, variantId))])]);
	if (isSkipped$1(definition, session.definitions.some((item) => item.mode === "only"))) return createHistoireTestSummary(storyId, variantId, [toResult$1(definition, "skipped", [])]);
	const workerState = getVitestWorkerState();
	const previousCurrent = workerState?.current;
	const previousFilepath = workerState?.filepath;
	const filepath = session.file.story.file?.filePath ?? session.file.filePath;
	const task = createPreviewTestTask(definition, `${storyId}:${variantId}:${definition.id}`, filepath);
	if (workerState) {
		workerState.filepath = filepath;
		workerState.current = task;
	}
	try {
		resetSharedExpectState();
		await runSingleDefinition(definition, storyId, variantId);
	} catch (error) {
		if (!task.result.errors.includes(error)) task.result.errors.push(error);
		task.result.state = "fail";
	} finally {
		if (workerState) {
			workerState.current = previousCurrent;
			workerState.filepath = previousFilepath;
		}
	}
	const errors = task.result.errors.map(serializeTestError);
	return createHistoireTestSummary(storyId, variantId, [toResult$1(definition, errors.length ? "failed" : "passed", errors, task.meta)]);
}
// src/node/virtual/variant-test-session/run.ts
/** Decides whether a definition must be reported as skipped. */
function isSkipped(definition, hasFocusedTests) {
	return definition.mode === "skip" || definition.mode === "todo" || hasFocusedTests && definition.mode !== "only";
}
/** Builds one result entry reported to Histoire. */
function toResult(definition, state, errors) {
	return {
		id: definition.id,
		name: definition.name,
		fullName: definition.fullName,
		state,
		errors
	};
}
/** Returns count of identical leading suite scopes. */
function commonScopeCount(left, right) {
	let count = 0;
	while (left[count] && left[count] === right[count]) count++;
	return count;
}
/** Marks an already-created result failed because suite cleanup failed. */
function appendResultError(result, error) {
	if (!result || !error) return;
	result.state = "failed";
	result.errors.push(serializeTestError(error));
}
/** Executes all collected tests of one mounted variant session. */
async function runSessionTests(session, storyId, variantId) {
	const workerState = getVitestWorkerState();
	const hasFocusedTests = session.definitions.some((definition) => definition.mode === "only");
	const filepath = session.file.story.file?.filePath ?? session.file.filePath;
	const results = [];
	const scopeErrors = /* @__PURE__ */ new Map();
	const unopenedScopeErrors = /* @__PURE__ */ new Map();
	const suiteCleanups = /* @__PURE__ */ new Map();
	const aroundControllers = /* @__PURE__ */ new Map();
	let activeScopes = [];
	let lastRunnableResult;
	/** Unwinds a completed suite, including setup disposers and its aroundAll wrapper. */
	async function closeScope(scope, error) {
		error = await runHooks([...scope.afterAll].reverse(), void 0, scope.suite, error, true);
		error = await runHooks((suiteCleanups.get(scope) ?? []).reverse(), void 0, void 0, error, true);
		const aroundError = await aroundControllers.get(scope)?.close();
		suiteCleanups.delete(scope);
		aroundControllers.delete(scope);
		scopeErrors.delete(scope);
		return error ?? aroundError;
	}
	for (const [index, definition] of session.definitions.entries()) {
		if (isSkipped(definition, hasFocusedTests)) {
			results.push(toResult(definition, "skipped", []));
			continue;
		}
		const nextScopes = definition.hookScopes ?? [];
		const sharedCount = commonScopeCount(activeScopes, nextScopes);
		let transitionError;
		for (const scope of activeScopes.slice(sharedCount).reverse()) transitionError = await closeScope(scope, transitionError);
		appendResultError(lastRunnableResult, transitionError);
		activeScopes = activeScopes.slice(0, sharedCount);
		let blockedByAncestor = activeScopes.some((scope) => scopeErrors.has(scope));
		for (const scope of nextScopes.slice(sharedCount)) {
			if (blockedByAncestor || unopenedScopeErrors.has(scope)) {
				blockedByAncestor = true;
				break;
			}
			let openingError;
			if (scope.aroundAll.length) {
				const opened = await openAroundHooks(scope.aroundAll, scope.suite);
				if ("controller" in opened) aroundControllers.set(scope, opened.controller);
				else openingError = opened.error;
			}
			if (openingError) {
				unopenedScopeErrors.set(scope, openingError);
				blockedByAncestor = true;
				break;
			}
			const cleanups = [];
			suiteCleanups.set(scope, cleanups);
			const error = await runHooks(scope.beforeAll, void 0, scope.suite, void 0, false, cleanups);
			activeScopes.push(scope);
			if (error) {
				scopeErrors.set(scope, error);
				blockedByAncestor = true;
			}
		}
		const previousCurrent = workerState?.current;
		const previousFilepath = workerState?.filepath;
		const task = createPreviewTestTask(definition, `${storyId}:${variantId}:${index}`, filepath);
		if (workerState) {
			workerState.filepath = filepath;
			workerState.current = task;
		}
		try {
			resetSharedExpectState();
			let taskFinalized = false;
			let testError = nextScopes.map((scope) => scopeErrors.get(scope) ?? unopenedScopeErrors.get(scope)).find(Boolean);
			if (!testError) try {
				await runDefinitionWithHooks(definition, storyId, variantId, async (error) => {
					taskFinalized = true;
					return await finishHistoireTestTask(task, error);
				});
			} catch (error) {
				testError = error;
			}
			if (!taskFinalized) await finishHistoireTestTask(task, testError);
			else if (testError) {
				const errors = testError instanceof AggregateError ? testError.errors : [testError];
				for (const error of errors) if (!task.result.errors.includes(error)) task.result.errors.push(error);
				task.result.state = "fail";
			}
			const errors = task.result.errors;
			lastRunnableResult = toResult(definition, errors.length ? "failed" : "passed", errors.map(serializeTestError));
			results.push(lastRunnableResult);
		} finally {
			if (workerState) {
				workerState.current = previousCurrent;
				workerState.filepath = previousFilepath;
			}
		}
	}
	let finalError;
	for (const scope of [...activeScopes].reverse()) finalError = await closeScope(scope, finalError);
	appendResultError(lastRunnableResult, finalError);
	return createHistoireTestSummary(storyId, variantId, results);
}
// src/node/virtual/offscreen-host.ts
/**
* Moves a test mount host off the viewport without touching `display`,
* `visibility` or `opacity`: the host is the canvas user tests assert on, so
* it must keep real layout (sizes, scroll, responsive styles) and pass
* visibility checks like `toBeVisible()`. A fixed-position element outside
* the viewport cannot create scrollbars, so the mount stays invisible to the
* user without affecting the page.
* @param host The mount host element appended to the document body.
*/
function applyOffscreenHostStyle(host) {
	host.style.position = "fixed";
	host.style.top = "0px";
	host.style.left = "-10000px";
	host.style.width = "100vw";
	host.style.height = "100vh";
}
// src/node/virtual/variant-test-session/variant.ts
/**
* Resolves one catalog variant or preserves the collection mount's error.
* @param file The mapped story file with current catalog variants.
* @param variantId The requested variant identity.
* @returns The matching mapped variant.
*/
function getStoryVariant(file, variantId) {
	const variant = file.story.variants.find((item) => item.id === variantId);
	if (!variant) throw new Error(`Unknown histoire variant "${variantId}" in story "${file.story?.id}"`);
	return variant;
}
// src/node/virtual/variant-test-mount.ts
/**
* Mounts a test app and reports the story-setup executions it caused.
*
* Ownership follows the DOM subtree, so support plugins can report their real
* setup executions after asynchronous loading. A synchronous app.mount window
* only sees the generic wrapper and cannot identify those later story mounts.
* @param app The test app to mount.
* @param host Element the app is mounted into.
*/
function mountStoryApp(app, host) {
	const executions = createStoryExecutionOwner(host);
	app.mount(host);
	return executions;
}
/**
* Mounts the hidden story bootstrap tree and captures any test registrations
* emitted during setup before the render variant mounts.
*/
async function bootstrapVariant(file, variantId, withRegistry, timeoutMs) {
	const variant = getStoryVariant(file, variantId);
	const host = createHost();
	const registrations = [];
	const app = createTestApp(() => h("div", { class: "htw-sandbox-hidden" }, [h(GenericMountStory, { story: file.story })]));
	let ownExecutionIds = /* @__PURE__ */ new Set();
	try {
		await withRegistry(registrations, false, async () => {
			ownExecutionIds = mountStoryApp(app, host);
			await waitForVariantConfig(variant, timeoutMs);
			await nextTick();
		});
		return {
			registrations,
			ownExecutionIds,
			cleanup() {
				cleanupMountedApp(app, host);
			}
		};
	} catch (error) {
		cleanupMountedApp(app, host);
		throw error;
	}
}
async function mountRenderVariant(file, variantId, withRegistry, options) {
	const variant = getStoryVariant(file, variantId);
	const host = createHost();
	if (options.offscreen) applyOffscreenHostStyle(host);
	const registrations = [];
	let resolveReady;
	const ready = new Promise((resolve) => {
		resolveReady = resolve;
	});
	const app = createTestApp(() => h(GenericRenderStory, {
		class: "__histoire-test-render",
		story: file.story,
		variant,
		onReady: () => resolveReady()
	}));
	let ownExecutionIds = /* @__PURE__ */ new Set();
	try {
		await withRegistry(registrations, true, async () => {
			ownExecutionIds = mountStoryApp(app, host);
			let timeoutHandle;
			try {
				await Promise.race([ready, new Promise((_, reject) => {
					timeoutHandle = setTimeout(() => reject(/* @__PURE__ */ new Error(`Timed out waiting ${options.timeoutMs}ms for histoire variant "${variantId}" to render in story "${file.story?.id}". The RenderStory component never emitted "ready".`)), options.timeoutMs);
				})]);
			} finally {
				clearTimeout(timeoutHandle);
			}
			await nextTick();
		});
	} catch (error) {
		cleanupMountedApp(app, host);
		throw error;
	}
	return {
		story: file.story,
		variant,
		canvas: host.querySelector(".__histoire-test-render") ?? host,
		registrations,
		ownExecutionIds,
		cleanup() {
			cleanupMountedApp(app, host);
		}
	};
}
function createTestApp(render) {
	const app = createApp({ render });
	app.use(createPinia());
	app.use(FloatingVue, {
		overflowPadding: 4,
		arrowPadding: 8,
		themes: {
			tooltip: { distance: 8 },
			dropdown: {
				computeTransformOrigin: true,
				distance: 8
			}
		}
	});
	return app;
}
function createHost() {
	const host = document.createElement("div");
	document.body.appendChild(host);
	return host;
}
function cleanupMountedApp(app, host) {
	app.unmount();
	host.remove();
}
async function waitForVariantConfig(variant, timeoutMs) {
	if (variant.configReady) return;
	const start = Date.now();
	while (!variant.configReady) {
		if (Date.now() - start > timeoutMs) throw new Error(`Timed out waiting for histoire variant "${variant.id}" to finish bootstrap.`);
		await new Promise((resolve) => window.setTimeout(resolve, 16));
	}
}
// src/node/virtual/variant-test-session/registrations.ts
/**
* Splits the mount-phase registration lists into one group per execution of the
* story setup, dropping registrations that were already captured by an earlier
* phase (a registration function shared across phases must still run only once).
*
* A group has to mean "one execution of the story setup" for the occurrence-aware
* deduplication downstream to work: it keeps repeats WITHIN a group (genuinely
* loop-generated tests) and collapses repeats ACROSS groups (the same setup
* mounted again). Mount phases are NOT a safe proxy for executions — the ambient
* registry is a process-wide global, so any story mount happening elsewhere in
* the page while a phase's window is open (the preview iframe renders its own
* live copy of the story) lands in that phase's list too, and its tests would
* be counted as loop-generated repeats.
*
* Registrations tagged by {@link getStoryExecutionId} are therefore regrouped by
* their execution; untagged ones (a module-scope `onTest(...)`, or a support
* plugin that does not mark its mounts) keep their phase as the group, which is
* the previous behaviour.
*
* Groups keep first-appearance order, so the render mount's execution stays the
* last group of the story's own mounts and its handlers win the dedupe.
* @param groups Registration lists, ordered by mount phase.
* @returns One group per execution, in first-appearance order.
*/
function groupRegistrationsByExecution(groups) {
	const seen = /* @__PURE__ */ new Set();
	const groupsByKey = /* @__PURE__ */ new Map();
	const result = [];
	groups.forEach((group, phaseIndex) => {
		for (const registration of group) {
			if (seen.has(registration)) continue;
			seen.add(registration);
			const executionId = getStoryExecutionId(registration);
			const key = executionId === void 0 ? `phase:${phaseIndex}` : `execution:${executionId}`;
			let target = groupsByKey.get(key);
			if (!target) {
				target = {
					executionId,
					registrations: []
				};
				groupsByKey.set(key, target);
				result.push(target);
			}
			target.registrations.push(registration);
		}
	});
	return result;
}
// src/node/virtual/variant-test-session/session.ts
/**
* Mounts a variant (bootstrap mount, then render mount) and collects the tests
* every mount phase registered.
* @param storyFile The mapped story file and its import-time registrations.
* @param variantId The variant to mount.
* @param options Mount options for this session.
* @returns The mounted session; the caller MUST call `cleanup()`.
*/
async function createVariantSession(storyFile, variantId, options) {
	const { file, importedDefinitions } = storyFile;
	const bootstrap = await bootstrapVariant(file, variantId, withRegistry, options.mountTimeoutMs);
	let rendered;
	try {
		rendered = await mountRenderVariant(file, variantId, withRegistry, {
			offscreen: options.offscreenRenderMount,
			timeoutMs: options.mountTimeoutMs
		});
		const context = {
			story: rendered.story,
			variant: rendered.variant,
			canvas: rendered.canvas
		};
		const registrationGroups = groupRegistrationsByExecution([
			importedDefinitions,
			bootstrap.registrations,
			rendered.registrations
		]);
		const ownExecutionIds = /* @__PURE__ */ new Set([...bootstrap.ownExecutionIds, ...rendered.ownExecutionIds]);
		return {
			file,
			definitions: dedupeCollectedTestDefinitionGroups(registrationGroups.map((group) => ({
				definitions: collectHistoireTests(group.registrations, context),
				own: group.executionId === void 0 || ownExecutionIds.has(group.executionId)
			}))),
			cleanup() {
				rendered.cleanup();
				bootstrap.cleanup();
			}
		};
	} catch (error) {
		rendered?.cleanup();
		bootstrap.cleanup();
		throw error;
	}
}
// src/node/virtual/map-story-file.ts
var copiedFromExistingVariant = [
	"state",
	"slots",
	"source",
	"responsiveDisabled",
	"autoPropsDisabled",
	"setupApp",
	"configReady",
	"previewReady"
];
function createEmptySlots() {
	return {
		default: null,
		controls: null,
		source: null
	};
}
/**
* Maps a serialized story file into the reactive preview shape expected by the
* Histoire story runtime.
*/
function mapStoryFile(file, existingFile) {
	let result;
	if (existingFile) {
		result = existingFile;
		for (const key in file) if (key === "story") result.story = {
			...result.story,
			...file.story,
			file: result,
			variants: file.story.variants.map((variant) => mapStoryVariant(variant, existingFile.story.variants.find((item) => item.id === variant.id)))
		};
		else if (key !== "component") result[key] = file[key];
	} else {
		result = {
			...file,
			path: file.path ?? [],
			component: markRaw(file.component),
			story: {
				...file.story,
				title: file.story.title,
				file: null,
				variants: file.story.variants.map((variant) => mapStoryVariant(variant)),
				slots: createEmptySlots
			}
		};
		result.story.file = result;
	}
	return result;
}
/**
* Maps a story variant into the reactive preview shape expected by the
* Histoire story runtime.
*/
function mapStoryVariant(variant, existingVariant) {
	let result;
	if (existingVariant) {
		result = existingVariant;
		for (const key in variant) if (!copiedFromExistingVariant.includes(key)) result[key] = variant[key];
	} else result = {
		...variant,
		state: reactive({
			_hPropState: {},
			_hPropDefs: []
		}),
		setupApp: null,
		slots: createEmptySlots,
		previewReady: false
	};
	return result;
}
// src/node/virtual/variant-test-session/story-modules.ts
/**
* Looks up the baked metadata of a story by id.
* @throws When the runtime was built without that story.
*/
function getSerializedFile(files, storyId) {
	const file = files.find((item) => item.id === storyId);
	if (!file) throw new Error(`Unknown histoire story "${storyId}"`);
	return file;
}
/**
* Creates the cache that imports story modules once and hands the session a
* freshly mapped story file per collect/run flow.
*
* Importing a story executes its top-level code, which may already register
* tests — those registrations are captured here and replayed as their own
* group by the session.
* @param options Story metadata, module loaders and the dynamic-import wrapper.
*/
function createStoryModuleCache(options) {
	const importedStoryCache = /* @__PURE__ */ new Map();
	const storyModuleVersions = /* @__PURE__ */ new Map();
	/** One-time project setup imports are separate from variant state and survive story HMR. */
	const setupModuleRegistrations = /* @__PURE__ */ new Map();
	/**
	* Clears the cached imported story module for a specific story so the next
	* collection or run observes the latest HMR-updated module instance.
	*/
	function invalidateStory(storyId) {
		importedStoryCache.delete(storyId);
		storyModuleVersions.set(storyId, (storyModuleVersions.get(storyId) ?? 0) + 1);
	}
	/**
	* Version the story module is currently imported at, `undefined` until the
	* story is invalidated for the first time.
	*/
	function getStoryModuleVersion(storyId) {
		return storyModuleVersions.get(storyId);
	}
	/**
	* Retains test registrations emitted while lazily probing setup modules.
	* These virtual modules are native-import cached across story invalidation.
	* @param storyId Story whose collection first observed the registrations.
	* @param registrations Registrations emitted by the setup-module import.
	*/
	function rememberSetupModuleRegistrations(storyId, registrations) {
		const retained = setupModuleRegistrations.get(storyId) ?? [];
		const additions = registrations.filter((registration) => !retained.includes(registration));
		if (!additions.length) return;
		retained.push(...additions);
		setupModuleRegistrations.set(storyId, retained);
		importedStoryCache.get(storyId)?.definitions.push(...additions);
	}
	/**
	* Imports a story module (or returns the cached one), capturing the test
	* registrations emitted while its top-level code runs.
	*/
	async function loadImportedStory(storyId, testing) {
		await options.ensureEnvironment?.();
		if (importedStoryCache.has(storyId)) return importedStoryCache.get(storyId);
		await options.loadStoryEntry?.(storyId);
		const file = getSerializedFile(options.files, storyId);
		const loadModule = options.moduleLoaders[storyId];
		if (!loadModule) throw new Error(`Missing histoire story module loader for "${storyId}"`);
		const definitions = [];
		let component;
		const version = getStoryModuleVersion(storyId);
		await withRegistry(definitions, testing, async () => {
			component = (await options.runWithDynamicImport(() => loadModule(version))).default;
		});
		const result = {
			component,
			definitions: definitions.slice(),
			file
		};
		if (getStoryModuleVersion(storyId) === version) importedStoryCache.set(storyId, result);
		return result;
	}
	/**
	* Builds the mapped story file a variant session mounts, plus a copy of the
	* import-time registrations (the session mutates neither).
	*/
	async function createSessionStoryFile(storyId, testing = true) {
		const imported = await loadImportedStory(storyId, testing);
		const importedDefinitions = imported.definitions.slice();
		for (const registration of setupModuleRegistrations.get(storyId) ?? []) if (!importedDefinitions.includes(registration)) importedDefinitions.push(registration);
		return {
			file: mapStoryFile({
				...imported.file,
				component: imported.component,
				source: async () => ({ default: "" })
			}),
			importedDefinitions
		};
	}
	return {
		createSessionStoryFile,
		getStoryModuleVersion,
		invalidateStory,
		rememberSetupModuleRegistrations
	};
}
// src/node/virtual/variant-test-session/finished-specs.ts
/** Tab JS heap (bytes) above which a spec frees the documents of finished spec files first. */
var FINISHED_SPECS_GC_THRESHOLD = 256 * 1024 ** 2;
/**
* Frees the documents of finished spec files before this one runs. Vitest runs every spec file in
* a fresh iframe and drops the previous one, but Chromium collects removed documents only near its
* heap limit: each test tab otherwise grows by gigabytes of dead documents. Histoire launches its
* test browser with an exposed collector; anywhere else this is a no-op.
* @param scope Page globals.
*/
function releaseFinishedSpecs(scope = globalThis) {
	if (typeof scope.gc !== "function") return;
	const heap = scope.performance?.memory?.usedJSHeapSize;
	if (heap === void 0 || heap > FINISHED_SPECS_GC_THRESHOLD) scope.gc();
}
// src/node/virtual/variant-test-session/setup-hooks.ts
/**
* Whether project setup modules can add registrations during a vanilla mount.
* Missing generated metadata is inconclusive, so it blocks the shortcut.
* @param generatedSetup Generated global setup module namespace.
* @param configuredSetup Configured browser setup module namespace.
*/
function hasVanillaSetupHooks(generatedSetup, configuredSetup) {
	return generatedSetup?.hasSetupVanilla !== false || typeof configuredSetup?.setupVanilla === "function";
}
// src/node/virtual/variant-test-session/index.ts
/**
* Creates the browser-side session driving story test collection and execution.
*
* The same session object is reused for the whole lifetime of the preview
* iframe (or of the Vitest test harness), so it owns the story module cache and
* serializes its flows — collect and run both take over the global test
* registry while they mount a variant.
*
* Execution is split by ownership: run.ts walks preview suites once, while
* run-single-definition.ts wraps each CLI test in its own mounted suites.
* Both use run-definition.ts for the per-test lifecycle, hooks.ts and
* around-hooks.ts for setup/teardown, and task-callbacks.ts for final results.
* @param options Baked story metadata, module loaders and mount options.
*/
function createVariantTestSession(options) {
	const storyModules = createStoryModuleCache(options);
	const runExclusive = createExclusiveQueue();
	/** Mounts a variant and collects its tests; the caller owns the cleanup. */
	async function openVariantSession(storyId, variantId, storyFile) {
		return createVariantSession(storyFile ?? await storyModules.createSessionStoryFile(storyId), variantId, {
			offscreenRenderMount: options.offscreenRenderMount ?? false,
			mountTimeoutMs: options.mountTimeoutMs
		});
	}
	/** Loads the visible preview while retaining its module-scope registrations for tests. */
	async function loadStoryFile(storyId) {
		return runExclusive(async () => (await storyModules.createSessionStoryFile(storyId, false)).file);
	}
	/** Opens a discovery mount unless runtime evidence proves it cannot register tests. */
	async function openDiscoveryMount(storyId, variantId) {
		const storyFile = await storyModules.createSessionStoryFile(storyId);
		const setupProbe = options.canSkipKnownEmptyCollection;
		if (setupProbe && !storyFile.importedDefinitions.length && isGeneratedStoryKnownEmpty(storyFile.file.component) && !hasStorySetupApp(storyFile.file.component)) {
			const setupRegistrations = [];
			let canSkip = setupProbe === true;
			if (typeof setupProbe === "function") {
				try {
					await withRegistry(setupRegistrations, true, async () => {
						canSkip = await setupProbe();
					});
				} catch {
					canSkip = false;
				}
				if (setupRegistrations.length) {
					storyModules.rememberSetupModuleRegistrations(storyId, setupRegistrations);
					storyFile.importedDefinitions.push(...setupRegistrations);
				}
			}
			if (canSkip && !setupRegistrations.length) {
				getStoryVariant(storyFile.file, variantId);
				return;
			}
		}
		return openVariantSession(storyId, variantId, storyFile);
	}
	/** Collects definitions without retaining a live mount for definition-only callers. */
	async function collectVariantTests(storyId, variantId) {
		return runExclusive(async () => {
			const session = await openDiscoveryMount(storyId, variantId);
			if (!session) return [];
			try {
				return serializeTestDefinitions(session.definitions);
			} finally {
				session.cleanup();
			}
		});
	}
	/** Gives the first executed case the fresh discovery mount, at most once. */
	async function prepareVariantTestRun(storyId, variantId, cleanups) {
		if (!cleanups) return {
			definitions: await collectVariantTests(storyId, variantId),
			run: (definition) => runCollectedTest(storyId, variantId, definition)
		};
		return runExclusive(async () => {
			let mount = await openDiscoveryMount(storyId, variantId);
			/** Take ownership before executing or disposing, including concurrent cleanup. */
			function takeMount() {
				const current = mount;
				mount = void 0;
				return current;
			}
			try {
				const definitions = serializeTestDefinitions(mount?.definitions ?? []);
				if (definitions.some((definition) => definition.mode !== "skip" && definition.mode !== "todo")) cleanups.push(() => takeMount()?.cleanup());
				else takeMount()?.cleanup();
				return {
					definitions,
					run: (definition) => runCollectedTest(storyId, variantId, definition, takeMount)
				};
			} catch (error) {
				takeMount()?.cleanup();
				throw error;
			}
		});
	}
	/**
	* Runs a single previously collected test, re-resolving it against a freshly
	* mounted variant. Used by the Vitest test harness, which owns the reporting.
	*/
	async function runCollectedTest(storyId, variantId, definition, takeMount) {
		return runExclusive(async () => {
			const session = takeMount?.() ?? await openVariantSession(storyId, variantId);
			const leaveTask = enterHistoireTestTask(getVitestWorkerState()?.current);
			try {
				const currentDefinition = getMatchingDefinition(session.definitions, definition);
				if (currentDefinition?.mode === "skip" || currentDefinition?.mode === "todo") return;
				if (!currentDefinition) throw createMissingHandlerError(definition.fullName, storyId, variantId);
				await runSingleDefinition(currentDefinition, storyId, variantId);
			} finally {
				leaveTask();
				session.cleanup();
			}
		});
	}
	/** Runs every test of a variant and returns the summary shown by the host UI. */
	async function runVariantTests(storyId, variantId) {
		return runExclusive(async () => {
			const session = await openVariantSession(storyId, variantId);
			try {
				return await runSessionTests(session, storyId, variantId);
			} finally {
				session.cleanup();
			}
		});
	}
	/** Runs one case in a fresh hidden preview document. */
	async function runPreviewTestCase(storyId, variantId, definition) {
		return runExclusive(async () => {
			const session = await openVariantSession(storyId, variantId);
			try {
				return await runPreviewDefinition(session, storyId, variantId, definition);
			} finally {
				session.cleanup();
			}
		});
	}
	return {
		collectVariantTests,
		prepareVariantTestRun,
		loadStoryFile,
		getStoryModuleVersion: storyModules.getStoryModuleVersion,
		invalidateStory: storyModules.invalidateStory,
		runCollectedTest,
		runPreviewTestCase,
		runVariantTests
	};
}
/**
* Checks generated raw story options for setup callbacks that can register tests.
* @param component Imported story component object.
*/
function hasStorySetupApp(component) {
	if (!component || typeof component !== "object") return false;
	const story = component;
	return typeof story.setupApp === "function" || Boolean(story.variants?.some((variant) => typeof variant.setupApp === "function"));
}
export { createVariantTestSession, getMatchingDefinition, getVitestBrowserMountCleanups, hasVanillaSetupHooks, releaseFinishedSpecs };