Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HtmlRender.ts

500 lines18.5 KB

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