UNPKG

histoire

Version:

A fast story book powered by Vite

52 lines (51 loc) • 3.08 kB
import { randomUUID } from 'node:crypto'; import { sanitizeMcpTestSummary } from '../operations/test-results.js'; import { McpDomainError } from '../protocol/errors.js'; import { mcpTestSummarySchema } from '../protocol/test-schema.js'; /** Fixed protocol command; never repeats effect after timeout or navigation. */ async function request(ready, command, timeout) { const dispatched = await ready.page.evaluate(command => window.__HST_MCP_PREVIEW__?.tests?.request(command) === true, command); if (!dispatched) throw new McpDomainError('PREVIEW_NOT_READY', 'Compiled preview lost its document authority'); try { await ready.page.waitForFunction(command => window.__HST_MCP_PREVIEW__?.tests?.settled(command), command, { timeout }); } catch (error) { if (error.name === 'TimeoutError') throw new McpDomainError('TIMEOUT', 'Compiled test response exceeded its recorded deadline', true); throw error; } const result = await ready.page.evaluate(command => window.__HST_MCP_PREVIEW__?.tests?.take(command), command); if (!result) throw new McpDomainError('PREVIEW_NOT_READY', 'Compiled preview changed during test execution'); if (result.oversized) throw new McpDomainError('RESULT_TOO_LARGE', 'Compiled preview result exceeds 4 MiB limit'); if (result.malformed) throw new McpDomainError('PREVIEW_NOT_READY', 'Compiled preview returned malformed test results'); return result; } /** Collect and run existing embedded session against one exact ready document. */ export async function runCompiledPreviewTests(options) { const { session, ready, target } = options; const identity = { ...target, nonce: ready.nonce, documentId: ready.documentId }; const collection = await request(ready, { ...identity, kind: 'collect', id: randomUUID() }, Math.min(session.remaining(), options.collectTimeoutMs)); if (!Number.isSafeInteger(collection.count) || collection.count < 0) throw new McpDomainError('COLLECTION_FAILED', 'Compiled preview could not collect test definitions'); if (collection.error) throw new McpDomainError('COLLECTION_FAILED', 'Compiled preview test collection failed'); const result = await request(ready, { ...identity, kind: 'run', id: randomUUID() }, session.remaining()); // The existing embedded runner owns modifiers, hooks, assertions and deadlines. // Reuse common sanitizer before strict wire validation to discard raw causes. let summary; try { summary = mcpTestSummarySchema.parse(sanitizeMcpTestSummary(result.summary, options.sanitize)); } catch (error) { if (error instanceof McpDomainError) throw error; throw new McpDomainError('PREVIEW_NOT_READY', 'Compiled preview returned malformed test summary'); } if (summary.tests.some(test => test.storyId !== target.storyId || test.variantId !== target.variantId)) throw new McpDomainError('PREVIEW_NOT_READY', 'Compiled preview returned another test target'); return summary; }