UNPKG

histoire

Version:

A fast story book powered by Vite

42 lines (41 loc) • 2.33 kB
import { randomUUID } from 'node:crypto'; import { getRuntimeCatalogForContext } from '../runtime/catalog/attachment.js'; import { getContextScreenshotSetup } from '../runtime/registry.js'; import { getDevPreviewHost } from '../vite/mcp-preview-html.js'; import { resolveVisualConfig } from './config.js'; const revisions = new WeakMap(); const listeners = new WeakMap(); /** Retire captures for every dependency HMR, even when catalog metadata is identical. */ export function retireVisualSource(server) { revisions.set(server, (revisions.get(server) ?? 0) + 1); for (const listener of listeners.get(server) ?? []) listener(); } /** Observe render retirement through existing server ownership. */ export function onVisualSourceRetired(server, listener) { const set = listeners.get(server) ?? new Set(); listeners.set(server, set); set.add(listener); return () => { set.delete(listener); }; } /** Bind one ready completed catalog revision; no second collector or launcher. */ export function resolveVisualSource(ctx, server, execution, active, epoch = randomUUID()) { const catalog = getRuntimeCatalogForContext(ctx)?.catalog; const snapshot = catalog?.current; const renderRevision = revisions.get(server) ?? 0; const executionRevision = catalog?.executionRevision; if (!active() || !snapshot || catalog.updating || !resolveVisualConfig(ctx.config.visual)) { throw new Error('Visual testing requires enabled configuration and a ready development source'); } return { ctx, server, execution, epoch, isActive: () => active() && (revisions.get(server) ?? 0) === renderRevision && catalog.executionRevision === executionRevision && catalog.current === snapshot && !catalog.updating }; } /** Exact private render input, independent of workbench preferences. */ export function visualSession(source, storyId, variantId, spec) { const address = source.server.resolvedUrls?.local[0]; if (!address || !source.isActive()) { throw new Error('Visual source changed'); } return { root: source.ctx.root, host: getDevPreviewHost(source.server), setupOwner: getContextScreenshotSetup(source.ctx), stableCapture: true, target: { origin: new URL(address).origin, epoch: source.epoch, storyId, variantId, ...spec, isActive: source.isActive } }; }