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

HtmlRender.ts

458 lines16.6 KB

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