Open History to see the last commit
1import type { ThreadId } from "@t3tools/contracts";
2import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import {
5 clampHtmlRenderHeight,
6 HTML_RENDER_COLUMN_WIDTH,
7 HTML_RENDER_MAX_TITLE_LENGTH,
8 HTML_RENDER_MEASURE_FONTS,
9 HTML_RENDER_MEASURE_WIDTHS,
10 htmlRenderTheme,
11 htmlRenderThemeFragment,
12 injectHtmlRenderBootstrap,
13 type HtmlRenderReference,
14} from "@t3tools/shared/htmlRender";
15import {
16 T3_CODE_DARK_THEME_COLORS,
17 T3_CODE_LIGHT_THEME_COLORS,
18 type ThemeAppearance,
19} from "@t3tools/shared/themePalettes";
20import * as Context from "effect/Context";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import type * as Path from "effect/Path";
26import * as Schema from "effect/Schema";
27import * as Semaphore from "effect/Semaphore";
28import * as Stream from "effect/Stream";
29import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
30
31import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
32import { createAttachmentId } from "../attachmentStore.ts";
33import { resolveRootCliCommand } from "../cli/invocation.ts";
34import * as ServerConfig from "../config.ts";
35import * as HeadlessChrome from "./headlessChrome.ts";
36import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
37import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
38
39const MIB = 1024 * 1024;
40const MAX_IMAGE_BYTES = 10 * MIB;
41const MAX_PAGE_BYTES = 25 * MIB;
42const formatMib = (bytes: number) => `${(bytes / MIB).toFixed(1)} MiB`;
43
44export class HtmlRenderImagesNotFoundError extends Schema.TaggedError<HtmlRenderImagesNotFoundError>()(
45 "HtmlRenderImagesNotFoundError",
46 { paths: Schema.Array(Schema.String) },
47) {
48 override get message(): string {
49 return `These local images could not be read: ${this.paths.join(", ")}. Use absolute paths to existing image files, or remove them.`;
50 }
51}
52
53export class HtmlRenderImageTooLargeError extends Schema.TaggedError<HtmlRenderImageTooLargeError>()(
54 "HtmlRenderImageTooLargeError",
55 { path: Schema.String, sizeBytes: Schema.Number },
56) {
57 override get message(): string {
58 return `${this.path} is ${formatMib(this.sizeBytes)}; each local image must be at most ${formatMib(MAX_IMAGE_BYTES)}.`;
59 }
60}
61
62export class HtmlRenderPageTooLargeError extends Schema.TaggedError<HtmlRenderPageTooLargeError>()(
63 "HtmlRenderPageTooLargeError",
64 { sizeBytes: Schema.Number },
65) {
66 override get message(): string {
67 return `With its images inlined the page is ${formatMib(this.sizeBytes)}; the limit is ${formatMib(MAX_PAGE_BYTES)}. Use smaller images.`;
68 }
69}
70
71export class HtmlRenderViewportHeightError extends Schema.TaggedError<HtmlRenderViewportHeightError>()(
72 "HtmlRenderViewportHeightError",
73 { found: Schema.String },
74) {
75 override get message(): string {
76 return `The page uses a viewport height unit (${this.found}). The frame grows to fit the page, so a size that follows the viewport makes it grow again and again. Let content set the height, or use fixed pixel heights.`;
77 }
78}
79
80// Only stylesheets and style attributes are checked, so page text that mentions
81// a unit passes; comments match first so their contents are skipped. Scripts
82// are still checked, since markup they insert applies. An unclosed comment,
83// tag, or quote runs to the end of the page, which keeps both patterns linear
84// on hostile input.
85const CSS_SOURCE =
86 /<!--[\s\S]*?(?:-->|$)|<style\b[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))/gi;
87// The lookbehind skips base64 runs, such as an inlined image that happens to contain "1vh".
88const VIEWPORT_HEIGHT_UNIT = /(?<![\w.+/])(?:\d+(?:\.\d+)?|\.\d+)[sld]?vh(?![\w-])/i;
89
90const rejectViewportHeight = (html: string) => {
91 for (const [, sheet, doubleQuoted, singleQuoted, unquoted] of html.matchAll(CSS_SOURCE)) {
92 const css = sheet ?? doubleQuoted ?? singleQuoted ?? unquoted ?? "";
93 const found = VIEWPORT_HEIGHT_UNIT.exec(css)?.[0];
94 if (found !== undefined) return Effect.fail(new HtmlRenderViewportHeightError({ found }));
95 }
96 return Effect.void;
97};
98
99export class HtmlRenderStoreError extends Schema.TaggedError<HtmlRenderStoreError>()(
100 "HtmlRenderStoreError",
101 { cause: Schema.Defect() },
102) {
103 override get message(): string {
104 return "The HTML render could not be saved.";
105 }
106}
107
108export type HtmlRenderPrepareError =
109 | HtmlRenderImagesNotFoundError
110 | HtmlRenderImageTooLargeError
111 | HtmlRenderPageTooLargeError
112 | HtmlRenderViewportHeightError;
113
114export interface HtmlPreview {
115 readonly png: string;
116 readonly width: number;
117 readonly contentHeight: number;
118 readonly capturedHeight: number;
119 readonly consoleMessages: ReadonlyArray<HeadlessChrome.ConsoleMessage>;
120 readonly missingImages?: ReadonlyArray<string>;
121}
122
123export class HtmlRender extends Context.Service<
124 HtmlRender,
125 {
126 readonly prepare: (html: string) => Effect.Effect<string, HtmlRenderPrepareError>;
127 readonly publish: (input: {
128 readonly threadId: ThreadId;
129 readonly html: string;
130 readonly title: string;
131 readonly height: number;
132 }) => Effect.Effect<HtmlRenderReference, HtmlRenderPrepareError | HtmlRenderStoreError>;
133 readonly preview: (input: {
134 readonly html: string;
135 readonly width?: number | undefined;
136 readonly appearance?: ThemeAppearance | undefined;
137 }) => Effect.Effect<
138 HtmlPreview,
139 | Exclude<HtmlRenderPrepareError, HtmlRenderImagesNotFoundError>
140 | PreviewBrowser.PreviewBrowserInstallError
141 | PreviewBrowser.PreviewBrowserInstallingError
142 | PreviewBrowser.PreviewBrowserUnsupportedError
143 | PreviewBrowserHost.PreviewBrowserHostError
144 | HeadlessChrome.HtmlRenderBrowserError
145 >;
146 }
147>()("t3/htmlRender/HtmlRender") {}
148
149const IMAGE_MIME_TYPES: Record<string, string> = {
150 png: "image/png",
151 jpg: "image/jpeg",
152 jpeg: "image/jpeg",
153 gif: "image/gif",
154 webp: "image/webp",
155 avif: "image/avif",
156 svg: "image/svg+xml",
157 bmp: "image/bmp",
158 ico: "image/x-icon",
159};
160const IMAGE_EXTENSIONS = Object.keys(IMAGE_MIME_TYPES).join("|");
161const ABSOLUTE_PATH = String.raw`(?:/(?!/)|[a-z]:[\\/])`;
162const LOCAL_IMAGE_PATTERN = new RegExp(
163 String.raw`(["'\x60])(${ABSOLUTE_PATH}(?:(?!\1)[^\r\n]){0,2048}?\.(?:${IMAGE_EXTENSIONS}))\1` +
164 String.raw`|url\(\s*(${ABSOLUTE_PATH}[^\s"'\x60()]{0,2048}?\.(?:${IMAGE_EXTENSIONS}))\s*\)`,
165 "gid",
166);
167
168const findLocalImages = (html: string) =>
169 Array.from(html.matchAll(LOCAL_IMAGE_PATTERN)).flatMap((match) => {
170 const span = match.indices?.[2] ?? match.indices?.[3];
171 return span ? [{ start: span[0], end: span[1], path: html.slice(span[0], span[1]) }] : [];
172 });
173
174// Inside a JS string literal a Windows path's backslashes are escaped.
175const filePathFor = (reference: string) =>
176 /^[a-z]:/i.test(reference) ? reference.replaceAll("\\\\", "\\") : reference;
177
178const dataUriPrefix = (path: string) =>
179 `data:${IMAGE_MIME_TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream"};base64,`;
180
181const latin1 = (bytes: Uint8Array, start: number, end: number) =>
182 String.fromCharCode(...bytes.subarray(start, end));
183
184/**
185 * Whether file bytes are an image, whatever the file is named, so a symlink or
186 * renamed file cannot carry other data, such as a secret, into a page.
187 */
188const isImageBytes = (bytes: Uint8Array) => {
189 const head = latin1(bytes, 0, 12);
190 if (
191 head.startsWith("\x89PNG") ||
192 head.startsWith("\xff\xd8\xff") ||
193 head.startsWith("GIF8") ||
194 head.startsWith("\0\0\x01\0") ||
195 (head.startsWith("BM") && head.slice(6, 10) === "\0\0\0\0") ||
196 (head.startsWith("RIFF") && head.slice(8, 12) === "WEBP") ||
197 /^ftyp(?:avif|avis|mif1)$/.test(head.slice(4, 12))
198 ) {
199 return true;
200 }
201 return hasSvgRoot(new TextDecoder().decode(bytes.subarray(0, 4096)));
202};
203
204const after = (text: string, token: string, from: number) => {
205 const at = text.indexOf(token, from);
206 return at === -1 ? -1 : at + token.length;
207};
208
209const hasSvgRoot = (text: string) => {
210 let at = 0;
211 while (at !== -1) {
212 while (/\s/.test(text.charAt(at))) at += 1;
213 if (text.startsWith("<?", at)) at = after(text, "?>", at + 2);
214 else if (text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
215 else if (text.slice(at, at + 9).toLowerCase() === "<!doctype") at = afterDoctype(text, at + 9);
216 // XML names are case-sensitive, and only these characters can end one here.
217 else return /^<svg[ \t\r\n/>]/.test(text.slice(at, at + 5));
218 }
219 return false;
220};
221
222const afterDoctype = (text: string, from: number) => {
223 let inSubset = false;
224 let at = from;
225 while (at !== -1 && at < text.length) {
226 const char = text[at];
227 if (char === '"' || char === "'") at = after(text, char, at + 1);
228 else if (inSubset && text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
229 else if (inSubset && text.startsWith("<?", at)) at = after(text, "?>", at + 2);
230 else if (char === ">" && !inSubset) return at + 1;
231 else {
232 if (char === "[") inSubset = true;
233 else if (char === "]") inSubset = false;
234 at += 1;
235 }
236 }
237 return -1;
238};
239
240const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (html: string) {
241 const fileSystem = yield* FileSystem.FileSystem;
242 const references = findLocalImages(html);
243 const files = yield* Effect.forEach(
244 [...new Set(references.map((reference) => reference.path))],
245 (path) =>
246 fileSystem.stat(filePathFor(path)).pipe(
247 Effect.map((info) => ({
248 path,
249 size: info.type === "File" ? Number(info.size) : undefined,
250 })),
251 Effect.orElseSucceed(() => ({ path, size: undefined })),
252 ),
253 { concurrency: 8 },
254 );
255 const oversized = files.find((file) => file.size !== undefined && file.size > MAX_IMAGE_BYTES);
256 if (oversized?.size !== undefined) {
257 return yield* new HtmlRenderImageTooLargeError({
258 path: oversized.path,
259 sizeBytes: oversized.size,
260 });
261 }
262 const sizes = new Map(files.map((file) => [file.path, file.size]));
263 const pageBytes = references.reduce((total, reference) => {
264 const size = sizes.get(reference.path);
265 return size === undefined
266 ? total
267 : total +
268 dataUriPrefix(reference.path).length +
269 Math.ceil(size / 3) * 4 -
270 Buffer.byteLength(reference.path);
271 }, Buffer.byteLength(html));
272 if (pageBytes > MAX_PAGE_BYTES) {
273 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: pageBytes });
274 }
275 // Files can grow after `stat`. Each read stops one byte past the image
276 // limit, and reading stops once the images read so far cannot fit the page.
277 let readBytes = 0;
278 const images = yield* Effect.forEach(
279 files.filter((file) => file.size !== undefined),
280 (file) =>
281 Effect.gen(function* () {
282 const read = yield* fileSystem
283 .stream(filePathFor(file.path), { bytesToRead: MAX_IMAGE_BYTES + 1 })
284 .pipe(Stream.mkUint8Array, Effect.option);
285 if (Option.isNone(read) || !isImageBytes(read.value)) return [];
286 const bytes = read.value;
287 if (bytes.byteLength > MAX_IMAGE_BYTES) {
288 return yield* new HtmlRenderImageTooLargeError({
289 path: file.path,
290 sizeBytes: bytes.byteLength,
291 });
292 }
293 readBytes += Math.ceil(bytes.byteLength / 3) * 4;
294 if (readBytes > MAX_PAGE_BYTES) {
295 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: readBytes });
296 }
297 return [{ path: file.path, bytes }];
298 }),
299 { concurrency: 4 },
300 ).pipe(Effect.map((entries) => entries.flat()));
301 const dataUris = new Map(
302 images.map(
303 (image) =>
304 [
305 image.path,
306 dataUriPrefix(image.path) + Buffer.from(image.bytes).toString("base64"),
307 ] as const,
308 ),
309 );
310 const parts: Array<string> = [];
311 let cursor = 0;
312 for (const reference of references) {
313 const dataUri = dataUris.get(reference.path);
314 if (dataUri === undefined) continue;
315 parts.push(html.slice(cursor, reference.start), dataUri);
316 cursor = reference.end;
317 }
318 parts.push(html.slice(cursor));
319 const inlined = parts.join("");
320 const inlinedBytes = Buffer.byteLength(inlined);
321 if (inlinedBytes > MAX_PAGE_BYTES) {
322 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: inlinedBytes });
323 }
324 return {
325 html: inlined,
326 missing: files.filter((file) => !dataUris.has(file.path)).map((file) => file.path),
327 };
328});
329
330const MIN_PREVIEW_WIDTH = 240;
331const MAX_PREVIEW_WIDTH = 1_600;
332const MAX_CONCURRENT_BROWSERS = 2;
333const MEASURE_TIMEOUT = "6 seconds";
334
335const MEASURE_FRAGMENT = htmlRenderThemeFragment(
336 htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_MEASURE_FONTS),
337);
338
339const make = Effect.gen(function* () {
340 const fileSystem = yield* FileSystem.FileSystem;
341 const config = yield* ServerConfig.ServerConfig;
342 const previewBrowser = yield* PreviewBrowser.PreviewBrowser;
343 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
344 const services = yield* Effect.context<
345 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
346 >();
347 const browsers = yield* Semaphore.make(MAX_CONCURRENT_BROWSERS);
348 // Chrome's sandbox stays on unless the operator explicitly turns it off.
349 // Chrome also refuses it as root, where that opt-out is the only way to run.
350 const noSandbox = PreviewBrowserHost.sandboxDisabled(yield* HostProcess.Environment);
351 const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND);
352
353 const launching = <A>(
354 executable: string,
355 run: (noSandbox: boolean) => Effect.Effect<A, HeadlessChrome.HtmlRenderBrowserError>,
356 ) =>
357 browsers.withPermits(1)(
358 run(noSandbox).pipe(
359 Effect.catchTags({
360 HtmlRenderBrowserError: (error) =>
361 error.output === undefined
362 ? Effect.fail(error)
363 : PreviewBrowserHost.diagnoseLaunchFailure({
364 executable,
365 setupCommand,
366 output: error.output,
367 }).pipe(
368 Effect.provideContext(services),
369 Effect.flatMap((hostError) => Effect.fail(hostError ?? error)),
370 ),
371 }),
372 ),
373 );
374
375 const measure = Effect.fn("HtmlRender.measure")(
376 function* (html: string) {
377 const executable = yield* previewBrowser.installed;
378 if (Option.isNone(executable)) return undefined;
379 const heights = yield* launching(executable.value, (noSandbox) =>
380 HeadlessChrome.measureHtmlHeights({
381 executable: executable.value,
382 noSandbox,
383 html,
384 widths: HTML_RENDER_MEASURE_WIDTHS,
385 urlFragment: MEASURE_FRAGMENT,
386 }).pipe(Effect.provideContext(services)),
387 ).pipe(
388 Effect.timeoutOrElse({
389 duration: MEASURE_TIMEOUT,
390 orElse: () =>
391 Effect.fail(
392 new HeadlessChrome.HtmlRenderBrowserError({
393 reason: `measuring took longer than ${MEASURE_TIMEOUT}`,
394 }),
395 ),
396 }),
397 );
398 return heights.toSorted(([left], [right]) => left - right);
399 },
400 Effect.catch((cause) =>
401 Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
402 cause,
403 }).pipe(Effect.as(undefined)),
404 ),
405 );
406
407 // The bootstrap goes in first so its head scan never runs over inlined image data.
408 const inline = (html: string) =>
409 inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services));
410
411 const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) {
412 yield* rejectViewportHeight(html);
413 const inlined = yield* inline(html);
414 if (inlined.missing.length > 0) {
415 return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing });
416 }
417 return inlined.html;
418 });
419
420 const publish = Effect.fn("HtmlRender.publish")(function* (input: {
421 readonly threadId: ThreadId;
422 readonly html: string;
423 readonly title: string;
424 readonly height: number;
425 }) {
426 const html = yield* prepare(input.html);
427 // The `-html` id suffix makes the asset route serve it as a sandboxed text/html document.
428 const attachmentId = createAttachmentId(input.threadId, "html");
429 const filePath =
430 attachmentId === null
431 ? null
432 : resolveAttachmentRelativePath({
433 attachmentsDir: config.attachmentsDir,
434 relativePath: `${attachmentId}.html`,
435 });
436 if (attachmentId === null || filePath === null) {
437 return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
438 }
439 const baseReference: HtmlRenderReference = {
440 attachmentId,
441 title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
442 height: clampHtmlRenderHeight(input.height),
443 };
444 return yield* fileSystem.writeFileString(filePath, html).pipe(
445 Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
446 Effect.uninterruptible,
447 Effect.andThen(measure(html)),
448 Effect.andThen((heights) => {
449 const reference: HtmlRenderReference = {
450 ...baseReference,
451 ...(heights === undefined ? {} : { heights }),
452 };
453 return mcpSessions
454 .recordHtmlRender(input.threadId, input, reference)
455 .pipe(Effect.as(reference));
456 }),
457 // An interrupted publish must leave neither an attachment nor a recoverable reference.
458 Effect.onError(() =>
459 Effect.all(
460 [
461 fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore),
462 mcpSessions.takeHtmlRender(input.threadId, input, baseReference).pipe(Effect.ignore),
463 ],
464 { discard: true },
465 ),
466 ),
467 );
468 });
469
470 const preview = Effect.fn("HtmlRender.preview")(function* (input: {
471 readonly html: string;
472 readonly width?: number | undefined;
473 readonly appearance?: ThemeAppearance | undefined;
474 }) {
475 const width = Math.min(
476 MAX_PREVIEW_WIDTH,
477 Math.max(MIN_PREVIEW_WIDTH, Math.round(input.width ?? HTML_RENDER_COLUMN_WIDTH)),
478 );
479 const appearance = input.appearance ?? "dark";
480 yield* rejectViewportHeight(input.html);
481 const inlined = yield* inline(input.html);
482 const executable = yield* previewBrowser.executable;
483 const theme = htmlRenderTheme(
484 appearance === "light" ? T3_CODE_LIGHT_THEME_COLORS : T3_CODE_DARK_THEME_COLORS,
485 appearance,
486 HTML_RENDER_MEASURE_FONTS,
487 );
488 const screenshot = yield* launching(executable, (noSandbox) =>
489 HeadlessChrome.captureHtmlScreenshot({
490 executable,
491 noSandbox,
492 html: inlined.html,
493 width,
494 urlFragment: htmlRenderThemeFragment(theme),
495 }).pipe(Effect.provideContext(services)),
496 );
497 return {
498 ...screenshot,
499 width,
500 ...(inlined.missing.length === 0 ? {} : { missingImages: inlined.missing }),
501 } satisfies HtmlPreview;
502 });
503
504 return HtmlRender.of({ prepare, publish, preview });
505});
506
507export const layer = Layer.effect(HtmlRender, make);