histoire
Version:
A fast story book powered by Vite
74 lines (73 loc) • 4.68 kB
JavaScript
import { createHash } from 'node:crypto';
import { PreviewError } from './errors.js';
import { CAPTURE_LIMITS } from './limits.js';
import { readPngDimensions } from './png.js';
import { createPreviewSession } from './session.js';
import { encodeScreenshotWebp } from './webp.js';
export { readPngDimensions } from './png.js';
/** Factory acquires nothing; default PNG output remains the MCP contract. */
export function createScreenshotTask(options, encoding = { format: 'png' }) {
// Queueing captures target scalars/globals, never a caller's mutable options.
options = { ...options, target: { ...options.target, globals: options.target.globals && { ...options.target.globals }, propsOverride: options.target.propsOverride && structuredClone(options.target.propsOverride) } };
const session = createPreviewSession({ ...options, deterministicCapture: true });
return {
async run(signal) {
try {
let ready = await session.open(signal);
let previous;
for (;;) {
let artifact;
try {
artifact = await ready.page.locator('#histoire-mcp-preview').screenshot({ type: 'png', animations: 'disabled', scale: 'device', omitBackground: options.target.backgroundColor === 'transparent', timeout: session.remaining() });
}
catch (error) {
if (await session.isDocumentReady(ready.documentId))
throw error;
previous = undefined;
ready = await session.waitForReady();
continue;
}
// A cold Vite optimizer may reload the iframe during capture. Never
// retain pixels from a document whose readiness authority was lost.
if (!await session.isDocumentReady(ready.documentId)) {
previous = undefined;
ready = await session.waitForReady();
continue;
}
if (artifact.byteLength > CAPTURE_LIMITS.artifactBytes)
throw new PreviewError('RESULT_TOO_LARGE', 'Screenshot exceeds 4 MiB limit');
const dimensions = readPngDimensions(artifact);
const scale = options.target.deviceScaleFactor ?? 1;
if (dimensions.width !== options.target.width * scale || dimensions.height !== options.target.height * scale)
throw new PreviewError('INTERNAL_ERROR', 'Screenshot dimensions do not match viewport and device scale');
if (options.stableCapture) {
const { decodeVisualPng } = await import('../../visual/compare.js');
const decoded = (await decodeVisualPng(artifact)).data;
const stable = previous && previous.length === decoded.length && previous.every((byte, index) => byte === decoded[index]);
previous = decoded;
if (!stable) {
await ready.frame.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
session.remaining();
continue;
}
}
if (encoding.format === 'webp')
artifact = await encodeScreenshotWebp(ready.page, artifact);
return { artifact, result: { storyId: options.target.storyId, variantId: options.target.variantId, ...dimensions, ...(options.stableCapture ? { browserVersion: ready.page.context().browser().version() } : {}), mimeType: encoding.format === 'webp' ? 'image/webp' : 'image/png', bytes: artifact.byteLength, sha256: createHash('sha256').update(artifact).digest('hex') } };
}
}
catch (error) {
if (session.timedOut)
throw new PreviewError('TIMEOUT', 'Screenshot exceeded its preview deadline', true);
if (signal.aborted)
throw new PreviewError('CANCELLED', 'Screenshot operation cancelled');
if (session.pageFailed)
throw new PreviewError('PREVIEW_NOT_READY', 'Preview page failed', true);
if (error instanceof PreviewError)
throw error;
throw new PreviewError('PREVIEW_NOT_READY', 'Screenshot could not be captured', true);
}
},
cleanup: session.close,
};
}