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

HtmlRender.ts

670 lines26.1 KB

1import type { ThreadId } from "@t3tools/contracts";
2import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";
5import { isNetworkPath } from "@t3tools/shared/path";
6import {
7 clampHtmlRenderHeight,
8 HTML_RENDER_COLUMN_WIDTH,
9 HTML_RENDER_MAX_TITLE_LENGTH,
10 HTML_RENDER_MEASURE_FONTS,
11 HTML_RENDER_MEASURE_WIDTHS,
12 htmlRenderTheme,
13 htmlRenderThemeFragment,
14 injectHtmlRenderBootstrap,
15 type HtmlRenderReference,
16} from "@t3tools/shared/htmlRender";
17import {
18 T3_CODE_DARK_THEME_COLORS,
19 T3_CODE_LIGHT_THEME_COLORS,
20 type ThemeAppearance,
21} from "@t3tools/shared/themePalettes";
22import * as Context from "effect/Context";
23import * as Effect from "effect/Effect";
24import * as FileSystem from "effect/FileSystem";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Path from "effect/Path";
28import * as Schema from "effect/Schema";
29import * as Semaphore from "effect/Semaphore";
30import * as Stream from "effect/Stream";
31import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
32​
33import { openMediaFile } from "../assets/MediaFile.ts";
34import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
35import { createAttachmentId } from "../attachmentStore.ts";
36import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
37import { resolveRootCliCommand } from "../cli/invocation.ts";
38import * as ServerConfig from "../config.ts";
39import * as HeadlessChrome from "./headlessChrome.ts";
40import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
41import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
42​
43const MIB = 1024 * 1024;
44const MAX_IMAGE_BYTES = 10 * MIB;
45const MAX_PAGE_BYTES = 25 * MIB;
46const HTML_FILE_EXTENSION = /\.html?$/i;
47// Like the image check, judge the bytes: a renamed .env or key does not start like a page.
48const HTML_DOCUMENT_START = /^\s*<(?:!doctype\s+html|html)[\s>]/i;
49const formatMib = (bytes: number) => `${(bytes / MIB).toFixed(1)} MiB`;
50​
51export class HtmlRenderFileError extends Schema.TaggedError<HtmlRenderFileError>()(
52 "HtmlRenderFileError",
53 { path: Schema.String, cause: Schema.optional(Schema.Defect()) },
54) {
55 override get message(): string {
56 return `${this.path} is not a readable HTML document. Pass an absolute path to a regular .html file that starts with <!doctype html> or <html>, or pass html instead.`;
57 }
59​
60export class HtmlRenderFileTooLargeError extends Schema.TaggedError<HtmlRenderFileTooLargeError>()(
61 "HtmlRenderFileTooLargeError",
62 { path: Schema.String, sizeBytes: Schema.Number },
63) {
64 override get message(): string {
65 return `${this.path} is ${formatMib(this.sizeBytes)}; a page must be at most ${formatMib(MAX_PAGE_BYTES)}.`;
66 }
68​
69export class HtmlRenderImagesNotFoundError extends Schema.TaggedError<HtmlRenderImagesNotFoundError>()(
70 "HtmlRenderImagesNotFoundError",
71 { paths: Schema.Array(Schema.String) },
72) {
73 override get message(): string {
74 return `These local images could not be read: ${this.paths.join(", ")}. Use absolute paths to existing image files, or remove them.`;
75 }
77​
78export class HtmlRenderImageTooLargeError extends Schema.TaggedError<HtmlRenderImageTooLargeError>()(
79 "HtmlRenderImageTooLargeError",
80 { path: Schema.String, sizeBytes: Schema.Number },
81) {
82 override get message(): string {
83 return `${this.path} is ${formatMib(this.sizeBytes)}; each local image must be at most ${formatMib(MAX_IMAGE_BYTES)}.`;
84 }
86​
87export class HtmlRenderPageTooLargeError extends Schema.TaggedError<HtmlRenderPageTooLargeError>()(
88 "HtmlRenderPageTooLargeError",
89 { sizeBytes: Schema.Number },
90) {
91 override get message(): string {
92 return `With its images inlined the page is ${formatMib(this.sizeBytes)}; the limit is ${formatMib(MAX_PAGE_BYTES)}. Use smaller images.`;
93 }
95​
96export class HtmlRenderViewportHeightError extends Schema.TaggedError<HtmlRenderViewportHeightError>()(
97 "HtmlRenderViewportHeightError",
98 { found: Schema.String },
99) {
100 override get message(): string {
101 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.`;
102 }
104​
105// Check stylesheets, style attributes, and scripts (which may write either); skip comments whole.
106// Consume unclosed comments, tags, or quotes through EOF to keep every pattern linear.
107const HTML_CSS_SOURCE =
108 /<!--[\s\S]*?(?:-->|$)|<script(?=[\s/>])((?:=\s*(?:"[^"]*(?:"|$)|'[^']*(?:'|$)|[^\s>]*)|[^>])*)(?:>|$)([\s\S]*?)(?:<\/script\s*>|$)|<style(?=[\s/>])[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|<[a-z]((?:=\s*(?:"[^"]*(?:"|$)|'[^']*(?:'|$)|[^\s>]*)|[^>])*)/gi;
109// Inside a tag, skip other attributes' quoted values, such as a title that mentions style=.
110// A quote opens a value only right after `=`; an unquoted value such as `it's` or `a="b` runs to a space.
111const TAG_STYLE =
112 /\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))|=\s*(?:"[^"]*(?:"|$)|'[^']*(?:'|$)|[^\s>]*)/gi;
113// A script is not markup, so take any style block or attribute it spells out.
114const SCRIPT_STYLE =
115 /<!--[\s\S]*?(?:-->|$)|<style(?=[\s/>])[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))/gi;
116// vb and vmax follow the frame height too; vmin stays, as the frame width caps it.
117// The lookbehind skips base64 runs, such as an inlined image that happens to contain "1vh",
118// and identifiers such as `.h-100vmax` or `.h\+100vh`, while signed and scientific-notation lengths still count.
119const VIEWPORT_HEIGHT_UNIT =
120 /(?<![\w.+/\\-])[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?[sld]?v(?:h|b|max)(?![\w-])/i;
121// In CSS, skip comments and strings so generated text like `content:"100vh"` passes.
122// Escapes and unquoted url() bodies go first: there a quote or `/*` is plain text.
123// An unclosed string ends at a newline, as CSS ends it there.
124const CSS_VIEWPORT_HEIGHT_UNIT = new RegExp(
125 String.raw`\\[\s\S]|url\((?!\s*["'])[^)]*\)?|\/\*[\s\S]*?(?:\*\/|$)|"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n\f])*"?|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n\f])*'?|(${VIEWPORT_HEIGHT_UNIT.source})`,
126 "gi",
127);
128​
129const findInCss = (css: string) => {
130 for (const [, found] of css.matchAll(CSS_VIEWPORT_HEIGHT_UNIT)) {
131 if (found !== undefined) return found;
132 }
133 return undefined;
134};
135​
136// Generated text (`content`) only lives in stylesheets. Attribute values hold HTML character
137// references and scripts hold their own quotes, so neither is parsed as CSS strings.
138const findViewportHeight = (source: string, pattern: RegExp) => {
139 for (const [, ...captures] of source.matchAll(pattern)) {
140 for (const css of captures) {
141 const found = css === undefined ? undefined : VIEWPORT_HEIGHT_UNIT.exec(css)?.[0];
142 if (found !== undefined) return found;
143 }
144 }
145 return undefined;
146};
147​
148const rejectViewportHeight = (html: string) => {
149 for (const [, scriptTag, script, sheet, tag] of html.matchAll(HTML_CSS_SOURCE)) {
150 const found =
151 script !== undefined
152 ? (findViewportHeight(scriptTag ?? "", TAG_STYLE) ??
153 findViewportHeight(script, SCRIPT_STYLE))
154 : tag !== undefined
155 ? findViewportHeight(tag, TAG_STYLE)
156 : findInCss(sheet ?? "");
157 if (found !== undefined) return Effect.fail(new HtmlRenderViewportHeightError({ found }));
158 }
159 return Effect.void;
160};
161​
162export class HtmlRenderStoreError extends Schema.TaggedError<HtmlRenderStoreError>()(
163 "HtmlRenderStoreError",
164 { cause: Schema.Defect() },
165) {
166 override get message(): string {
167 return "The HTML render could not be saved.";
168 }
170​
171export type HtmlRenderPrepareError =
172 | HtmlRenderImagesNotFoundError
173 | HtmlRenderImageTooLargeError
174 | HtmlRenderPageTooLargeError
175 | HtmlRenderViewportHeightError;
176​
177export type HtmlRenderSource = { readonly html: string } | { readonly path: string };
178​
179export interface HtmlPreview {
180 readonly png: string;
181 readonly width: number;
182 readonly contentHeight: number;
183 readonly capturedHeight: number;
184 readonly consoleMessages: ReadonlyArray<HeadlessChrome.ConsoleMessage>;
185 readonly missingImages?: ReadonlyArray<string>;
187​
188export class HtmlRender extends Context.Service<
189 HtmlRender,
190 {
191 readonly prepare: (html: string) => Effect.Effect<string, HtmlRenderPrepareError>;
192 readonly publish: (
193 input: HtmlRenderSource & {
194 readonly threadId: ThreadId;
195 readonly title: string;
196 readonly height: number;
197 },
198 ) => Effect.Effect<
199 HtmlRenderReference,
200 | HtmlRenderFileError
201 | HtmlRenderFileTooLargeError
202 | HtmlRenderPrepareError
203 | HtmlRenderStoreError
204 >;
205 readonly preview: (
206 input: HtmlRenderSource & {
207 readonly width?: number | undefined;
208 readonly appearance?: ThemeAppearance | undefined;
209 },
210 ) => Effect.Effect<
211 HtmlPreview,
212 | HtmlRenderFileError
213 | HtmlRenderFileTooLargeError
214 | Exclude<HtmlRenderPrepareError, HtmlRenderImagesNotFoundError>
215 | PreviewBrowser.PreviewBrowserInstallError
216 | PreviewBrowser.PreviewBrowserInstallingError
217 | PreviewBrowser.PreviewBrowserUnsupportedError
218 | PreviewBrowserHost.PreviewBrowserHostError
219 | HeadlessChrome.HtmlRenderBrowserError
220 >;
221 }
222>()("t3/htmlRender/HtmlRender") {}
223​
224const IMAGE_MIME_TYPES: Record<string, string> = {
225 png: "image/png",
226 jpg: "image/jpeg",
227 jpeg: "image/jpeg",
228 gif: "image/gif",
229 webp: "image/webp",
230 avif: "image/avif",
231 svg: "image/svg+xml",
232 bmp: "image/bmp",
233 ico: "image/x-icon",
234};
235const IMAGE_EXTENSIONS = Object.keys(IMAGE_MIME_TYPES).join("|");
236const ABSOLUTE_PATH = String.raw`(?:/(?!/)|[a-z]:[\\/])`;
237const LOCAL_IMAGE_PATTERN = new RegExp(
238 String.raw`(["'\x60])(${ABSOLUTE_PATH}(?:(?!\1)[^\r\n]){0,2048}?\.(?:${IMAGE_EXTENSIONS}))(?:(?<=\.svg)#(?:(?!\1)[^\r\n]){0,2048})?\1` +
239 String.raw`|url\(\s*(${ABSOLUTE_PATH}[^\s"'\x60()]{0,2048}?\.(?:${IMAGE_EXTENSIONS}))(?:(?<=\.svg)#[^\s"'\x60()]{0,2048})?\s*\)`,
240 "gid",
241);
242const HTML_TAG_END = String.raw`(?:[^"'<>]|"[^"]*(?:"|$)|'[^']*(?:'|$))*(?:>|$)`;
243const HTML_COMMENT_CONTEXT = new RegExp(
244 String.raw`<!--(?:-?>|[\s\S]*?(?:--!?>|$))|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)(?=[\s/>])${HTML_TAG_END}[\s\S]*?(?:</\1(?=[\s/>])${HTML_TAG_END}|$)|<plaintext(?=[\s/>])[\s\S]*$|<[a-z!/]${HTML_TAG_END}`,
245 "gi",
246);
247​
248const findLocalImages = (html: string) =>
249 Array.from(
250 // Preserve raw text and quoted attributes; blank only comments without shifting offsets.
251 html
252 .replace(HTML_COMMENT_CONTEXT, (source) =>
253 source.startsWith("<!--")
254 ? source.replace(/[^\r\n]+/g, (run) => " ".repeat(run.length))
255 : source,
256 )
257 .matchAll(LOCAL_IMAGE_PATTERN),
258 ).flatMap((match) => {
259 const span = match.indices?.[2] ?? match.indices?.[3];
260 return span ? [{ start: span[0], end: span[1], path: html.slice(span[0], span[1]) }] : [];
261 });
262​
263// Inside a JS string literal a Windows path's backslashes are escaped.
264const filePathFor = (reference: string) =>
265 /^[a-z]:/i.test(reference) ? reference.replaceAll("\\\\", "\\") : reference;
266​
267// Try the literal path first so raw filesystem strings keep working, then percent-decode URL paths.
268const filePathCandidatesFor = (reference: string) => {
269 const literal = filePathFor(reference);
270 const decoded = safeDecodeURIComponent(literal);
271 return decoded !== literal && !decoded.includes("\0") && !isNetworkPath(decoded)
272 ? [literal, decoded]
273 : [literal];
274};
275​
276const dataUriPrefix = (path: string) =>
277 `data:${IMAGE_MIME_TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream"};base64,`;
278​
279const latin1 = (bytes: Uint8Array, start: number, end: number) =>
280 String.fromCharCode(...bytes.subarray(start, end));
281​
282// Validate bytes, not filenames, so renamed files or symlinks cannot inline secrets.
283const isImageBytes = (bytes: Uint8Array) => {
284 const head = latin1(bytes, 0, 12);
285 if (
286 head.startsWith("\x89PNG") ||
287 head.startsWith("\xff\xd8\xff") ||
288 head.startsWith("GIF8") ||
289 head.startsWith("\0\0\x01\0") ||
290 (head.startsWith("BM") && head.slice(6, 10) === "\0\0\0\0") ||
291 (head.startsWith("RIFF") && head.slice(8, 12) === "WEBP") ||
292 /^ftyp(?:avif|avis|mif1)$/.test(head.slice(4, 12))
293 ) {
294 return true;
295 }
296 return hasSvgRoot(new TextDecoder().decode(bytes.subarray(0, 4096)));
297};
298​
299const after = (text: string, token: string, from: number) => {
300 const at = text.indexOf(token, from);
301 return at === -1 ? -1 : at + token.length;
302};
303​
304const hasSvgRoot = (text: string) => {
305 let at = 0;
306 while (at !== -1) {
307 while (/\s/.test(text.charAt(at))) at += 1;
308 if (text.startsWith("<?", at)) at = after(text, "?>", at + 2);
309 else if (text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
310 else if (text.slice(at, at + 9).toLowerCase() === "<!doctype") at = afterDoctype(text, at + 9);
311 // XML names are case-sensitive, and only these characters can end one here.
312 else return /^<svg[ \t\r\n/>]/.test(text.slice(at, at + 5));
313 }
314 return false;
315};
316​
317const afterDoctype = (text: string, from: number) => {
318 let inSubset = false;
319 let at = from;
320 while (at !== -1 && at < text.length) {
321 const char = text[at];
322 if (char === '"' || char === "'") at = after(text, char, at + 1);
323 else if (inSubset && text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
324 else if (inSubset && text.startsWith("<?", at)) at = after(text, "?>", at + 2);
325 else if (char === ">" && !inSubset) return at + 1;
326 else {
327 if (char === "[") inSubset = true;
328 else if (char === "]") inSubset = false;
329 at += 1;
330 }
331 }
332 return -1;
333};
334​
335const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (html: string) {
336 const fileSystem = yield* FileSystem.FileSystem;
337 const references = findLocalImages(html);
338 const files = yield* Effect.forEach(
339 [...new Set(references.map((reference) => reference.path))],
340 (path) =>
341 Effect.gen(function* () {
342 for (const candidate of filePathCandidatesFor(path)) {
343 const info = yield* fileSystem.stat(candidate).pipe(Effect.option);
344 if (Option.isSome(info) && info.value.type === "File") {
345 return { path, filePath: candidate, size: Number(info.value.size) };
346 }
347 }
348 return { path, filePath: undefined, size: undefined };
349 }),
350 { concurrency: 8 },
351 );
352 const oversized = files.find((file) => file.size !== undefined && file.size > MAX_IMAGE_BYTES);
353 if (oversized?.size !== undefined) {
354 return yield* new HtmlRenderImageTooLargeError({
355 path: oversized.path,
356 sizeBytes: oversized.size,
357 });
358 }
359 const sizes = new Map(files.map((file) => [file.path, file.size]));
360 const pageBytes = references.reduce((total, reference) => {
361 const size = sizes.get(reference.path);
362 return size === undefined
363 ? total
364 : total +
365 dataUriPrefix(reference.path).length +
366 Math.ceil(size / 3) * 4 -
367 Buffer.byteLength(reference.path);
368 }, Buffer.byteLength(html));
369 if (pageBytes > MAX_PAGE_BYTES) {
370 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: pageBytes });
371 }
372 // Files can grow after stat; bound each read and stop when accumulated images cannot fit.
373 let readBytes = 0;
374 const images = yield* Effect.forEach(
375 files.filter((file) => file.size !== undefined),
376 (file) =>
377 Effect.gen(function* () {
378 if (file.filePath === undefined) return [];
379 const read = yield* fileSystem
380 .stream(file.filePath, { bytesToRead: MAX_IMAGE_BYTES + 1 })
381 .pipe(Stream.mkUint8Array, Effect.option);
382 if (Option.isNone(read) || !isImageBytes(read.value)) return [];
383 const bytes = read.value;
384 if (bytes.byteLength > MAX_IMAGE_BYTES) {
385 return yield* new HtmlRenderImageTooLargeError({
386 path: file.path,
387 sizeBytes: bytes.byteLength,
388 });
389 }
390 readBytes += Math.ceil(bytes.byteLength / 3) * 4;
391 if (readBytes > MAX_PAGE_BYTES) {
392 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: readBytes });
393 }
394 return [{ path: file.path, bytes }];
395 }),
396 { concurrency: 4 },
397 ).pipe(Effect.map((entries) => entries.flat()));
398 const dataUris = new Map(
399 images.map(
400 (image) =>
401 [
402 image.path,
403 dataUriPrefix(image.path) + Buffer.from(image.bytes).toString("base64"),
404 ] as const,
405 ),
406 );
407 const parts: Array<string> = [];
408 let cursor = 0;
409 for (const reference of references) {
410 const dataUri = dataUris.get(reference.path);
411 if (dataUri === undefined) continue;
412 parts.push(html.slice(cursor, reference.start), dataUri);
413 cursor = reference.end;
414 }
415 parts.push(html.slice(cursor));
416 const inlined = parts.join("");
417 const inlinedBytes = Buffer.byteLength(inlined);
418 if (inlinedBytes > MAX_PAGE_BYTES) {
419 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: inlinedBytes });
420 }
421 return {
422 html: inlined,
423 missing: files.filter((file) => !dataUris.has(file.path)).map((file) => file.path),
424 };
425});
426​
427const MIN_PREVIEW_WIDTH = 240;
428const MAX_PREVIEW_WIDTH = 1_600;
429const MAX_CONCURRENT_BROWSERS = 2;
430const MEASURE_TIMEOUT = "6 seconds";
431​
432const MEASURE_FRAGMENT = htmlRenderThemeFragment(
433 htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_MEASURE_FONTS),
434);
435​
436const make = Effect.gen(function* () {
437 const fileSystem = yield* FileSystem.FileSystem;
438 const path = yield* Path.Path;
439 const config = yield* ServerConfig.ServerConfig;
440 const isServerInternalPath = yield* makeIsServerInternalPath;
441 const previewBrowser = yield* PreviewBrowser.PreviewBrowser;
442 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
443 const services = yield* Effect.context<
444 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
445 >();
446 const browsers = yield* Semaphore.make(MAX_CONCURRENT_BROWSERS);
447 // Keep Chrome sandboxed unless explicitly disabled; root must opt out to run.
448 const noSandbox = PreviewBrowserHost.sandboxDisabled(yield* HostProcess.Environment);
449 // sudo resets the environment, so the command has to name this server's home.
450 const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND, [
451 "--base-dir",
452 config.baseDir,
453 ]);
454​
455 const launching = <A>(
456 executable: string,
457 run: (noSandbox: boolean) => Effect.Effect<A, HeadlessChrome.HtmlRenderBrowserError>,
458 ) =>
459 browsers.withPermits(1)(
460 run(noSandbox).pipe(
461 Effect.catchTags({
462 HtmlRenderBrowserError: (error) =>
463 error.output === undefined
464 ? Effect.fail(error)
465 : PreviewBrowserHost.diagnoseLaunchFailure({
466 executable,
467 setupCommand,
468 output: error.output,
469 }).pipe(
470 Effect.provideContext(services),
471 Effect.flatMap((hostError) => Effect.fail(hostError ?? error)),
472 ),
473 }),
474 ),
475 );
476​
477 const measure = Effect.fn("HtmlRender.measure")(
478 function* (html: string) {
479 const executable = yield* previewBrowser.installed;
480 if (Option.isNone(executable)) return undefined;
481 const heights = yield* launching(executable.value, (noSandbox) =>
482 HeadlessChrome.measureHtmlHeights({
483 executable: executable.value,
484 noSandbox,
485 html,
486 widths: HTML_RENDER_MEASURE_WIDTHS,
487 urlFragment: MEASURE_FRAGMENT,
488 }).pipe(Effect.provideContext(services)),
489 ).pipe(
490 Effect.timeoutOrElse({
491 duration: MEASURE_TIMEOUT,
492 orElse: () =>
493 Effect.fail(
494 new HeadlessChrome.HtmlRenderBrowserError({
495 reason: `measuring took longer than ${MEASURE_TIMEOUT}`,
496 }),
497 ),
498 }),
499 );
500 return heights.toSorted(([left], [right]) => left - right);
501 },
502 Effect.catch((cause) =>
503 Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
504 cause,
505 }).pipe(Effect.as(undefined)),
506 ),
507 );
508​
509 const readPageFile = Effect.fn("HtmlRender.readPageFile")(function* (filePath: string) {
510 const unreadable = new HtmlRenderFileError({ path: filePath });
511 if (!path.isAbsolute(filePath) || isNetworkPath(filePath)) return yield* unreadable;
512 // Check the resolved file, so a symlink named .html cannot reach another file.
513 const realPath = yield* fileSystem
514 .realPath(filePath)
515 .pipe(Effect.mapError((cause) => new HtmlRenderFileError({ path: filePath, cause })));
516 if (!HTML_FILE_EXTENSION.test(realPath) || (yield* isServerInternalPath(realPath))) {
517 return yield* unreadable;
518 }
519 // Open without following links and recheck the path, so a link or FIFO swapped in is refused.
520 const html = yield* Effect.scoped(
521 Effect.gen(function* () {
522 const file = yield* openMediaFile(realPath).pipe(
523 Effect.mapError((cause) => new HtmlRenderFileError({ path: filePath, cause })),
524 );
525 // Unlike client reads, the caller may be sandboxed: a second hard link could give any
526 // file an .html name.
527 if (file === null || file.info.nlink !== 1n) return yield* unreadable;
528 if (file.info.size > BigInt(MAX_PAGE_BYTES)) {
529 return yield* new HtmlRenderFileTooLargeError({
530 path: filePath,
531 sizeBytes: Number(file.info.size),
532 });
533 }
534 // One read may return fewer bytes, so fill up to the checked size; growth past it is ignored.
535 return yield* Effect.tryPromise({
536 try: async () => {
537 const buffer = Buffer.alloc(Number(file.info.size));
538 let filled = 0;
539 while (filled < buffer.length) {
540 const { bytesRead } = await file.handle.read(buffer, filled, buffer.length - filled);
541 if (bytesRead === 0) break;
542 filled += bytesRead;
543 }
544 return buffer.toString("utf8", 0, filled);
545 },
546 catch: (cause) => new HtmlRenderFileError({ path: filePath, cause }),
547 });
548 }),
549 );
550 return HTML_DOCUMENT_START.test(html) ? html : yield* unreadable;
551 });
552​
553 const readSource = (input: HtmlRenderSource) =>
554 "path" in input ? readPageFile(input.path) : Effect.succeed(input.html);
555​
556 // The bootstrap goes in first so its head scan never runs over inlined image data.
557 const inline = (html: string) =>
558 inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services));
559​
560 const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) {
561 yield* rejectViewportHeight(html);
562 const inlined = yield* inline(html);
563 if (inlined.missing.length > 0) {
564 return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing });
565 }
566 return inlined.html;
567 });
568​
569 const publish = Effect.fn("HtmlRender.publish")(function* (
570 input: HtmlRenderSource & {
571 readonly threadId: ThreadId;
572 readonly title: string;
573 readonly height: number;
574 },
575 ) {
576 const source = yield* readSource(input);
577 const html = yield* prepare(source);
578 // The `-html` id suffix makes the asset route serve it as a sandboxed text/html document.
579 const attachmentId = createAttachmentId(input.threadId, "html");
580 const filePath =
581 attachmentId === null
582 ? null
583 : resolveAttachmentRelativePath({
584 attachmentsDir: config.attachmentsDir,
585 relativePath: `${attachmentId}.html`,
586 });
587 if (attachmentId === null || filePath === null) {
588 return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
589 }
590 const baseReference: HtmlRenderReference = {
591 attachmentId,
592 title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
593 height: clampHtmlRenderHeight(input.height),
594 };
595 return yield* fileSystem.writeFileString(filePath, html).pipe(
596 Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
597 Effect.uninterruptible,
598 Effect.andThen(measure(html)),
599 Effect.andThen((heights) => {
600 const reference: HtmlRenderReference = {
601 ...baseReference,
602 ...(heights === undefined ? {} : { heights }),
603 };
604 return mcpSessions
605 .recordHtmlRender(
606 input.threadId,
607 {
608 html: source,
609 path: "path" in input ? input.path : undefined,
610 title: input.title,
611 height: input.height,
612 },
613 reference,
614 )
615 .pipe(Effect.as(reference));
616 }),
617 // An interrupted publish must leave neither an attachment nor a recoverable reference.
618 Effect.onError(() =>
619 Effect.all(
620 [
621 fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore),
622 mcpSessions.takeHtmlRender(input.threadId, input, baseReference).pipe(Effect.ignore),
623 ],
624 { discard: true },
625 ),
626 ),
627 );
628 });
629​
630 const preview = Effect.fn("HtmlRender.preview")(function* (
631 input: HtmlRenderSource & {
632 readonly width?: number | undefined;
633 readonly appearance?: ThemeAppearance | undefined;
634 },
635 ) {
636 const width = Math.min(
637 MAX_PREVIEW_WIDTH,
638 Math.max(MIN_PREVIEW_WIDTH, Math.round(input.width ?? HTML_RENDER_COLUMN_WIDTH)),
639 );
640 const appearance = input.appearance ?? "dark";
641 const source = yield* readSource(input);
642 yield* rejectViewportHeight(source);
643 const inlined = yield* inline(source);
644 const executable = yield* previewBrowser.executable;
645 const theme = htmlRenderTheme(
646 appearance === "light" ? T3_CODE_LIGHT_THEME_COLORS : T3_CODE_DARK_THEME_COLORS,
647 appearance,
648 HTML_RENDER_MEASURE_FONTS,
649 );
650 const screenshot = yield* launching(executable, (noSandbox) =>
651 HeadlessChrome.captureHtmlScreenshot({
652 executable,
653 noSandbox,
654 html: inlined.html,
655 width,
656 urlFragment: htmlRenderThemeFragment(theme),
657 appearance,
658 }).pipe(Effect.provideContext(services)),
659 );
660 return {
661 ...screenshot,
662 width,
663 ...(inlined.missing.length === 0 ? {} : { missingImages: inlined.missing }),
664 } satisfies HtmlPreview;
665 });
666​
667 return HtmlRender.of({ prepare, publish, preview });
668});
669​
670export const layer = Layer.effect(HtmlRender, make);