histoire
Version:
A fast story book powered by Vite
145 lines (144 loc) • 8.55 kB
JavaScript
import { Buffer } from 'node:buffer';
import { randomUUID } from 'node:crypto';
import { getContextScreenshotSetup } from '../../runtime/registry.js';
import { getDevPreviewHost } from '../../vite/mcp-preview-html.js';
import { observeUiClientConnection } from './client-connection.js';
import { listScreenshotFiles, readScreenshotFile, screenshotFilePathForBudget } from './files.js';
import { registerUiHttpRoute, uiHttpPath } from './http.js';
import { createUiScreenshotService } from './screenshot-service.js';
import { isUiChannelEventWithinBudget, uiRequestIdSchema, uiScreenshotSchema } from './validation.js';
const screenshotResultEvent = 'histoire:ui:screenshot-result';
const screenshotSetupReserveBytes = 8 * 1024;
const screenshotResultLimitError = { code: 'invalid', message: 'Capture result exceeds the 64 KB channel limit' };
const largestScreenshotError = { code: 'unavailable', message: 'Install Playwright in this project: pnpm add -D playwright && pnpm exec playwright install chromium --only-shell' };
/** Projects schema paths to fixed messages without echoing invalid request values. */
function screenshotOptionsError(issues) {
const width = issues.some(issue => issue.path[0] === 'viewport' && issue.path[1] === 'width');
const height = issues.some(issue => issue.path[0] === 'viewport' && issue.path[1] === 'height');
if (width && height)
return { code: 'invalid', message: 'Screenshot viewport width and height must be integers within allowed limits' };
if (width)
return { code: 'invalid', message: 'Screenshot viewport width must be an integer between 1 and 3840' };
if (height)
return { code: 'invalid', message: 'Screenshot viewport height must be an integer between 1 and 2160' };
return { code: 'invalid', message: 'Invalid screenshot options' };
}
/** Admit only captures whose full exact receipts or target errors fit one event. */
function canSendScreenshotResult(request) {
const files = [];
const errors = [];
for (const target of request.targets) {
const file = { path: screenshotFilePathForBudget(target, request.format), storyId: target.storyId, variantId: target.variantId, ...(target.frameKey ? { frameKey: target.frameKey } : {}) };
const error = { storyId: target.storyId, variantId: target.variantId, ...(target.frameKey ? { frameKey: target.frameKey } : {}), error: largestScreenshotError };
// Files win for long paths; public failure messages win for short IDs.
// Keeping the larger exact row bounds every valid mixed completion.
if (Buffer.byteLength(JSON.stringify(file)) >= Buffer.byteLength(JSON.stringify(error)))
files.push(file);
else
errors.push(error);
}
return isUiChannelEventWithinBudget(screenshotResultEvent, { requestId: request.requestId, files, ...(errors.length ? { errors } : {}) }, screenshotSetupReserveBytes);
}
/** Publish a compact correlated error if an unexpected result exceeds its frame. */
function sendScreenshotResult(channel, result, client) {
if (client.socket.readyState !== 1)
return;
if (!isUiChannelEventWithinBudget(screenshotResultEvent, result))
result = { requestId: result.requestId, error: screenshotResultLimitError };
channel.send(screenshotResultEvent, result, client);
}
/** Resolve the same preview host, globals, and theme policy as MCP screenshots. */
export function resolveUiScreenshotTarget(ctx, server, isActive, epoch, request, target) {
const story = ctx.storyFiles.find(file => file.story?.id === target.storyId)?.story;
if (!isActive() || !story || story.docsOnly || !story.variants.some(variant => variant.id === target.variantId))
throw new Error('Screenshot target unavailable');
const checkerboard = ['$checkerboard', '$checkerboard-dark'].includes(request.background);
const configuredBackground = checkerboard || ['transparent', ...ctx.config.backgroundPresets.map(preset => preset.color)].includes(request.background);
if (!configuredBackground && !/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i.test(request.background))
throw new Error('Screenshot background unavailable');
const address = server.resolvedUrls?.local[0];
if (!address)
throw new Error('Preview server unavailable');
return {
root: ctx.root,
host: getDevPreviewHost(server),
setupOwner: getContextScreenshotSetup(ctx, isActive),
target: {
origin: new URL(address).origin,
...target,
epoch,
width: request.viewport.width,
height: request.viewport.height,
deviceScaleFactor: request.scale,
globals: ctx.config.preview?.globals ?? {},
colorScheme: ctx.config.theme.defaultColorScheme === 'auto' ? undefined : ctx.config.theme.defaultColorScheme,
textDirection: 'ltr',
backgroundColor: checkerboard ? 'transparent' : request.background,
isActive,
},
};
}
/** Register correlated capture/list/cancel requests on this dev generation only. */
export function registerScreenshotChannel(ctx, server, channel, execution, isActive, options = {}) {
const epoch = randomUUID();
const service = createUiScreenshotService({ root: ctx.root, execution, resolve: (request, target) => ({ ...resolveUiScreenshotTarget(ctx, server, isActive, epoch, request, target), ...(options.launch ? { launch: options.launch } : {}) }) });
const connections = new Set();
channel.addCleanup(service.close);
channel.addCleanup(() => {
for (const connection of connections)
connection.dispose();
connections.clear();
});
const imagePrefix = uiHttpPath(server, '/__histoire/screenshots/');
channel.addCleanup(registerUiHttpRoute(server, imagePrefix, (request, response) => {
const name = request.url.slice(imagePrefix.length);
void (async () => {
const image = isActive() && request.method === 'GET' ? await readScreenshotFile(ctx.root, name) : undefined;
response.statusCode = image ? 200 : 404;
response.setHeader('content-type', image?.mimeType ?? 'text/plain');
response.setHeader('x-content-type-options', 'nosniff');
response.setHeader('cache-control', 'no-store');
response.end(image?.bytes ?? 'Screenshot unavailable');
})().catch(() => {
response.statusCode = 404;
response.end('Screenshot unavailable');
});
}, isActive));
channel.on('histoire:ui:screenshot', value => value, async (value, client) => {
const parsed = uiScreenshotSchema.safeParse(value);
if (!parsed.success) {
const identity = uiRequestIdSchema.safeParse(value && typeof value === 'object' ? { requestId: value.requestId } : undefined);
if (identity.success)
sendScreenshotResult(channel, { requestId: identity.data.requestId, error: screenshotOptionsError(parsed.error.issues) }, client);
return;
}
const request = parsed.data;
if (!canSendScreenshotResult(request)) {
sendScreenshotResult(channel, { requestId: request.requestId, error: screenshotResultLimitError }, client);
return;
}
const connection = observeUiClientConnection(client, () => service.cancel(request.requestId, client));
if (!connection.isOpen()) {
connection.dispose();
return;
}
connections.add(connection);
try {
const result = await service.capture(request, client);
if (connection.isOpen())
sendScreenshotResult(channel, result, client);
}
catch {
if (connection.isOpen())
sendScreenshotResult(channel, { requestId: request.requestId, error: { code: 'failed', message: 'Screenshot could not be captured' } }, client);
}
finally {
connections.delete(connection);
connection.dispose();
}
});
channel.on('histoire:ui:screenshot-cancel', value => uiRequestIdSchema.parse(value), (value, client) => service.cancel(value.requestId, client));
channel.on('histoire:ui:screenshot-list', value => uiRequestIdSchema.parse(value), async (value, client) => {
channel.send('histoire:ui:screenshot-list-result', { requestId: value.requestId, files: await listScreenshotFiles(ctx.root, value.requestId) }, client);
});
}