Open History to see the last commit
1import * as Deferred from "effect/Deferred";
2import * as Effect from "effect/Effect";
3import * as Fiber from "effect/Fiber";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Queue from "effect/Queue";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
13import { publicProxy } from "./publicProxy.ts";
14
15export class HtmlRenderBrowserError extends Schema.TaggedError<HtmlRenderBrowserError>()(
16 "HtmlRenderBrowserError",
17 {
18 reason: Schema.String,
19 cause: Schema.optional(Schema.Defect()),
20 output: Schema.optional(Schema.String),
21 exitCode: Schema.optional(Schema.Number),
22 signal: Schema.optional(Schema.String),
23 },
24) {
25 override get message(): string {
26 const exit =
27 this.exitCode !== undefined
28 ? ` (exit code ${this.exitCode})`
29 : this.signal !== undefined
30 ? ` (signal ${this.signal})`
31 : "";
32 return `Headless Chrome could not render the page: ${this.reason}${exit}.`;
33 }
34}
35
36type BrowserFailure = HtmlRenderBrowserError;
37
38export interface ConsoleMessage {
39 readonly level: "log" | "info" | "warning" | "error";
40 readonly text: string;
41}
42
43const MAX_CONSOLE_MESSAGES = 20;
44const MAX_CONSOLE_TEXT_CHARS = 500;
45const VIEWPORT_HEIGHT = 800;
46const MAX_CAPTURE_HEIGHT = 4_000;
47const CAPTURE_TIMEOUT = "20 seconds";
48// Chrome refuses local files to every web page, frame, worker, and popup, so a
49// page cannot read files the agent's provider withholds; local images reach it
50// already inlined as data URIs. `.localhost` keeps it a secure context that may
51// still load plain-http resources, and the request never leaves the browser.
52// All of the browser's traffic goes through `publicProxy`, which only reaches
53// public addresses, so a page cannot reach this machine's local network. The
54// main frame also stays on the page and the browser opens no popups, so a
55// capture always shows the page itself.
56const PAGE_ORIGIN = "http://t3-page.localhost";
57const PAGE_URL = `${PAGE_ORIGIN}/page.html`;
58const PAGE_NAME = "page.html";
59const MEASURE_CONCURRENCY = 3;
60
61const textEncoder = new TextEncoder();
62
63/**
64 * Node's encoder, since pages run to 25 MiB.
65 */
66const pageBody = (html: string) =>
67 Buffer.from(Buffer.from(html, "utf8").toString("base64"), "latin1");
68
69const CdpMessage = Schema.fromJsonString(
70 Schema.Struct({
71 id: Schema.optional(Schema.Number),
72 method: Schema.optional(Schema.String),
73 sessionId: Schema.optional(Schema.String),
74 params: Schema.optional(Schema.Unknown),
75 result: Schema.optional(Schema.Unknown),
76 error: Schema.optional(Schema.Struct({ message: Schema.String })),
77 }),
78);
79const decodeCdpMessage = Schema.decodeUnknownOption(CdpMessage);
80const encodeCdpCommand = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
81const RemoteObject = Schema.Struct({
82 type: Schema.String,
83 value: Schema.optional(Schema.Unknown),
84 description: Schema.optional(Schema.String),
85});
86const decodeConsoleApiCalled = Schema.decodeUnknownOption(
87 Schema.Struct({ type: Schema.String, args: Schema.Array(RemoteObject) }),
88);
89const decodeExceptionThrown = Schema.decodeUnknownOption(
90 Schema.Struct({
91 exceptionDetails: Schema.Struct({
92 text: Schema.String,
93 exception: Schema.optional(RemoteObject),
94 }),
95 }),
96);
97const decodeRequestPaused = Schema.decodeUnknownOption(
98 Schema.Struct({
99 requestId: Schema.String,
100 request: Schema.Struct({ url: Schema.String }),
101 frameId: Schema.optional(Schema.String),
102 resourceType: Schema.optional(Schema.String),
103 }),
104);
105const decodeLogEntryAdded = Schema.decodeUnknownOption(
106 Schema.Struct({
107 entry: Schema.Struct({
108 level: Schema.String,
109 text: Schema.String,
110 url: Schema.optional(Schema.String),
111 }),
112 }),
113);
114
115const remoteObjectText = (value: typeof RemoteObject.Type) =>
116 typeof value.value === "string"
117 ? value.value
118 : (value.description ?? (value.value === undefined ? value.type : String(value.value)));
119
120const CONSOLE_LEVELS: Readonly<Record<string, ConsoleMessage["level"]>> = {
121 log: "log",
122 debug: "log",
123 dir: "log",
124 dirxml: "log",
125 table: "log",
126 trace: "log",
127 info: "info",
128 warning: "warning",
129 error: "error",
130 assert: "error",
131};
132
133const consoleMessageFromEvent = (method: string, params: unknown): ConsoleMessage | undefined => {
134 if (method === "Runtime.consoleAPICalled") {
135 const event = Option.getOrUndefined(decodeConsoleApiCalled(params));
136 const level = event === undefined ? undefined : CONSOLE_LEVELS[event.type];
137 return event && level ? { level, text: event.args.map(remoteObjectText).join(" ") } : undefined;
138 }
139 if (method === "Runtime.exceptionThrown") {
140 const details = Option.getOrUndefined(decodeExceptionThrown(params))?.exceptionDetails;
141 return details
142 ? { level: "error", text: details.exception?.description ?? details.text }
143 : undefined;
144 }
145 if (method === "Log.entryAdded") {
146 const entry = Option.getOrUndefined(decodeLogEntryAdded(params))?.entry;
147 return entry && (entry.level === "error" || entry.level === "warning")
148 ? { level: entry.level, text: entry.url ? `${entry.text} ${entry.url}` : entry.text }
149 : undefined;
150 }
151 return undefined;
152};
153
154// Resolves after web fonts load and two frames paint, so late layout lands in the capture.
155const SETTLE_EXPRESSION =
156 "document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))";
157// The root's scroll height never drops below the viewport, so a short page
158// reports its own box height instead.
159const MEASURE_EXPRESSION =
160 "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";
161
162const Ignored = Schema.Unknown;
163const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });
164const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });
165
166// Effect's spawner names the signal that ended a child only in its error message.
167const EXIT_SIGNAL = /signal: '(SIG[A-Z0-9]+)'/;
168
169interface PageEvents {
170 readonly mainFrameId: string;
171 body: Uint8Array | undefined;
172 loaded: Deferred.Deferred<void, BrowserFailure> | undefined;
173 readonly consoleMessages: Array<ConsoleMessage>;
174 omittedConsoleMessages: number;
175}
176
177/**
178 * Starts the headless shell for the life of the scope, speaking CDP over
179 * `--remote-debugging-pipe` (fd 3 in, fd 4 out, NUL-delimited JSON).
180 */
181const launchBrowser = Effect.fnUntraced(function* (input: {
182 readonly executable: string;
183 readonly noSandbox: boolean;
184 readonly profileDirectory: string;
185}) {
186 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
187 const proxyPort = yield* publicProxy.pipe(
188 Effect.mapError(
189 (cause) => new HtmlRenderBrowserError({ reason: "the preview proxy could not start", cause }),
190 ),
191 );
192 const outgoing = yield* Queue.unbounded<Uint8Array>();
193 const child = yield* spawner
194 .spawn(
195 ChildProcess.make(
196 input.executable,
197 [
198 "--headless=new",
199 "--remote-debugging-pipe",
200 "--no-first-run",
201 "--no-default-browser-check",
202 "--disable-gpu",
203 "--hide-scrollbars",
204 "--mute-audio",
205 "--block-new-web-contents",
206 `--proxy-server=socks5://127.0.0.1:${proxyPort}`,
207 // Loopback would otherwise skip the proxy.
208 "--proxy-bypass-list=<-loopback>",
209 // WebRTC would otherwise send UDP, which no proxy carries.
210 "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
211 ...(input.noSandbox ? ["--no-sandbox"] : []),
212 `--user-data-dir=${input.profileDirectory}`,
213 "about:blank",
214 ],
215 {
216 stdin: "ignore",
217 stdout: "ignore",
218 stderr: "pipe",
219 forceKillAfter: "2 seconds",
220 additionalFds: {
221 fd3: { type: "input", stream: Stream.fromQueue(outgoing) },
222 fd4: { type: "output" },
223 },
224 },
225 ),
226 )
227 .pipe(
228 Effect.mapError(
229 (cause) =>
230 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
231 ),
232 // Node throws some spawn errors synchronously, such as `spawn UNKNOWN`
233 // when policy blocks the executable; `mapError` cannot catch those.
234 Effect.catchDefect((cause) =>
235 Effect.fail(
236 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
237 ),
238 ),
239 );
240
241 let stderrTail = "";
242 const stderrReader = yield* child.stderr.pipe(
243 Stream.decodeText(),
244 Stream.runForEach((text) =>
245 Effect.sync(() => {
246 stderrTail = (stderrTail + text).slice(-2_048);
247 }),
248 ),
249 Effect.ignore,
250 Effect.forkScoped,
251 );
252
253 const pending = new Map<
254 number,
255 { readonly method: string; readonly reply: Deferred.Deferred<unknown, BrowserFailure> }
256 >();
257 const pages = new Map<string, PageEvents>();
258 let disconnected: BrowserFailure | undefined;
259 let nextId = 0;
260
261 const post = (method: string, params: Record<string, unknown>, sessionId: string) =>
262 Queue.offer(
263 outgoing,
264 new TextEncoder().encode(
265 `${encodeCdpCommand({ id: ++nextId, method, params, sessionId })}\0`,
266 ),
267 ).pipe(Effect.asVoid);
268
269 // Serves the page. Its body is shared bytes between two small JSON halves,
270 // queued together, so loading a page of up to 25 MiB at several widths never
271 // copies it on this side.
272 const fulfillPage = (sessionId: string, requestId: string, body: Uint8Array) =>
273 Queue.offerAll(outgoing, [
274 textEncoder.encode(
275 `{"id":${++nextId},"sessionId":${JSON.stringify(sessionId)},"method":"Fetch.fulfillRequest","params":{"requestId":${JSON.stringify(requestId)},"responseCode":200,"responseHeaders":[{"name":"Content-Type","value":"text/html; charset=utf-8"}],"body":"`,
276 ),
277 body,
278 textEncoder.encode('"}}\0'),
279 ]).pipe(Effect.asVoid);
280
281 const receive = (raw: string) => {
282 const message = Option.getOrUndefined(decodeCdpMessage(raw));
283 if (message?.id !== undefined) {
284 const waiter = pending.get(message.id);
285 pending.delete(message.id);
286 if (!waiter) return Effect.void;
287 return message.error
288 ? Deferred.fail(
289 waiter.reply,
290 new HtmlRenderBrowserError({
291 reason: `${waiter.method} failed`,
292 cause: message.error.message,
293 }),
294 )
295 : Deferred.succeed(waiter.reply, message.result);
296 }
297 const sessionId = message?.sessionId;
298 const page = sessionId === undefined ? undefined : pages.get(sessionId);
299 if (sessionId === undefined || !page || !message?.method) return Effect.void;
300 if (message.method === "Page.loadEventFired") {
301 return page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
302 }
303 if (message.method === "Fetch.requestPaused") {
304 const paused = Option.getOrUndefined(decodeRequestPaused(message.params));
305 if (!paused) return Effect.void;
306 const body = page.body;
307 const url = paused.request.url.split("#", 1)[0]!;
308 if (url === PAGE_URL && body !== undefined) {
309 return fulfillPage(sessionId, paused.requestId, body);
310 }
311 // A frame inside the page may show another site; Local Network Access
312 // still covers it. The main frame and T3's own origin serve nothing else.
313 const otherSiteFrame =
314 paused.resourceType === "Document" &&
315 paused.frameId !== page.mainFrameId &&
316 !url.startsWith(`${PAGE_ORIGIN}/`);
317 return otherSiteFrame
318 ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId)
319 : post(
320 "Fetch.failRequest",
321 { requestId: paused.requestId, errorReason: "AccessDenied" },
322 sessionId,
323 );
324 }
325 const consoleMessage = consoleMessageFromEvent(message.method, message.params);
326 if (!consoleMessage) return Effect.void;
327 if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {
328 page.omittedConsoleMessages += 1;
329 return Effect.void;
330 }
331 const text = consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME);
332 page.consoleMessages.push({
333 level: consoleMessage.level,
334 text:
335 text.length > MAX_CONSOLE_TEXT_CHARS ? `${text.slice(0, MAX_CONSOLE_TEXT_CHARS)}…` : text,
336 });
337 return Effect.void;
338 };
339
340 // The pipe closes when the browser exits. A startup abort, such as a missing
341 // sandbox, says why on stderr, which may still be draining, so give it a moment.
342 const disconnect = Effect.gen(function* () {
343 yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore);
344 const exit = yield* child.exitCode.pipe(
345 Effect.map((code): { exitCode?: number; signal?: string; cause?: unknown } => ({
346 exitCode: code,
347 })),
348 Effect.catch((error) => {
349 const signal = EXIT_SIGNAL.exec(String(error.cause))?.[1];
350 return Effect.succeed(signal === undefined ? { cause: error } : { signal, cause: error });
351 }),
352 Effect.timeoutOption("1 second"),
353 );
354 const error = new HtmlRenderBrowserError({
355 reason: "the browser exited unexpectedly",
356 output: stderrTail,
357 ...Option.getOrElse(exit, () => ({})),
358 });
359 disconnected = error;
360 const waiters = [...pending.values()];
361 pending.clear();
362 yield* Effect.forEach(waiters, ({ reply }) => Deferred.fail(reply, error), { discard: true });
363 yield* Effect.forEach(
364 pages.values(),
365 (page) => (page.loaded ? Deferred.fail(page.loaded, error) : Effect.void),
366 { discard: true },
367 );
368 });
369
370 // Decoded text chunks may split a message anywhere, and a screenshot reply spans many.
371 let partial: Array<string> = [];
372 yield* child.getOutputFd(4).pipe(
373 Stream.decodeText(),
374 Stream.runForEach((text) => {
375 const complete: Array<string> = [];
376 let start = 0;
377 for (let end = text.indexOf("\0"); end !== -1; end = text.indexOf("\0", start)) {
378 partial.push(text.slice(start, end));
379 complete.push(partial.join(""));
380 partial = [];
381 start = end + 1;
382 }
383 if (start < text.length) partial.push(text.slice(start));
384 return Effect.forEach(complete, receive, { discard: true });
385 }),
386 Effect.ignore,
387 Effect.andThen(disconnect),
388 Effect.forkScoped,
389 );
390
391 const send = Effect.fn("headlessChrome.send")(function* <A>(
392 method: string,
393 params: Record<string, unknown>,
394 result: Schema.Decoder<A>,
395 sessionId?: string,
396 ) {
397 if (disconnected) return yield* disconnected;
398 const id = ++nextId;
399 const reply = yield* Deferred.make<unknown, BrowserFailure>();
400 pending.set(id, { method, reply });
401 const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
402 yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
403 return yield* Deferred.await(reply).pipe(
404 Effect.flatMap(Schema.decodeUnknownEffect(result)),
405 Effect.mapError((error) =>
406 error._tag === "HtmlRenderBrowserError"
407 ? error
408 : new HtmlRenderBrowserError({
409 reason: `${method} returned an unexpected result`,
410 cause: error,
411 }),
412 ),
413 );
414 });
415
416 const openPage = Effect.fnUntraced(function* (width: number) {
417 const { targetId } = yield* send(
418 "Target.createTarget",
419 { url: "about:blank" },
420 Schema.Struct({ targetId: Schema.String }),
421 );
422 const { sessionId } = yield* send(
423 "Target.attachToTarget",
424 { targetId, flatten: true },
425 Schema.Struct({ sessionId: Schema.String }),
426 );
427 const events: PageEvents = {
428 // A page target's id is its main frame's id.
429 mainFrameId: targetId,
430 body: undefined,
431 loaded: undefined,
432 consoleMessages: [],
433 omittedConsoleMessages: 0,
434 };
435 pages.set(sessionId, events);
436 yield* send("Page.enable", {}, Ignored, sessionId);
437 yield* send("Runtime.enable", {}, Ignored, sessionId);
438 yield* send("Log.enable", {}, Ignored, sessionId);
439 // Previews have no use for WebRTC, whose ICE servers can make the browser
440 // resolve names outside the proxy. Runs before page scripts in every frame.
441 yield* send(
442 "Page.addScriptToEvaluateOnNewDocument",
443 {
444 source: "delete window.RTCPeerConnection; delete window.webkitRTCPeerConnection;",
445 runImmediately: true,
446 },
447 Ignored,
448 sessionId,
449 );
450 // Pauses T3's own origin, to serve the page, and every document, to keep
451 // the main frame on it.
452 yield* send(
453 "Fetch.enable",
454 {
455 patterns: [
456 { urlPattern: `${PAGE_ORIGIN}/*` },
457 { urlPattern: "*", resourceType: "Document" },
458 ],
459 },
460 Ignored,
461 sessionId,
462 );
463 yield* send(
464 "Emulation.setDeviceMetricsOverride",
465 { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false },
466 Ignored,
467 sessionId,
468 );
469
470 const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) {
471 const loaded = yield* Deferred.make<void, BrowserFailure>();
472 events.body = body;
473 events.loaded = loaded;
474 const navigation = yield* send(
475 "Page.navigate",
476 { url: `${PAGE_URL}${urlFragment}` },
477 Navigation,
478 sessionId,
479 );
480 if (navigation.errorText) {
481 return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" });
482 }
483 yield* Deferred.await(loaded);
484 yield* send(
485 "Runtime.evaluate",
486 { expression: SETTLE_EXPRESSION, awaitPromise: true },
487 Ignored,
488 sessionId,
489 );
490 const measured = yield* send(
491 "Runtime.evaluate",
492 { expression: MEASURE_EXPRESSION, returnByValue: true },
493 Measured,
494 sessionId,
495 );
496 return Math.max(0, Math.ceil(measured.result.value));
497 });
498
499 const screenshot = (height: number) =>
500 send(
501 "Page.captureScreenshot",
502 {
503 format: "png",
504 captureBeyondViewport: true,
505 clip: { x: 0, y: 0, width, height, scale: 1 },
506 },
507 Schema.Struct({ data: Schema.String }),
508 sessionId,
509 ).pipe(Effect.map(({ data }) => data));
510
511 const consoleMessages = (): ReadonlyArray<ConsoleMessage> =>
512 events.omittedConsoleMessages === 0
513 ? [...events.consoleMessages]
514 : [
515 ...events.consoleMessages,
516 {
517 level: "warning",
518 text: `${events.omittedConsoleMessages} more console messages were omitted.`,
519 },
520 ];
521
522 const close = send("Target.closeTarget", { targetId }, Ignored).pipe(
523 Effect.ensuring(Effect.sync(() => pages.delete(sessionId))),
524 Effect.ignore,
525 );
526
527 return { load, screenshot, consoleMessages, close };
528 });
529
530 return { openPage };
531});
532
533const scratchDirectory = Effect.gen(function* () {
534 const fileSystem = yield* FileSystem.FileSystem;
535 return yield* Effect.acquireRelease(
536 fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }),
537 (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore),
538 ).pipe(
539 Effect.mapError(
540 (cause) =>
541 new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }),
542 ),
543 );
544});
545
546export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")(
547 function* (input: {
548 readonly executable: string;
549 readonly noSandbox: boolean;
550 readonly html: string;
551 readonly width: number;
552 readonly urlFragment: string;
553 }) {
554 const path = yield* Path.Path;
555 const directory = yield* scratchDirectory;
556 const browser = yield* launchBrowser({
557 executable: input.executable,
558 noSandbox: input.noSandbox,
559 profileDirectory: path.join(directory, "profile"),
560 });
561 const page = yield* browser.openPage(input.width);
562 const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment);
563 const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT));
564 const png = yield* page.screenshot(capturedHeight);
565 return { png, contentHeight, capturedHeight, consoleMessages: page.consoleMessages() };
566 },
567 Effect.scoped,
568 Effect.timeoutOrElse({
569 duration: CAPTURE_TIMEOUT,
570 orElse: () =>
571 Effect.fail(
572 new HtmlRenderBrowserError({
573 reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`,
574 }),
575 ),
576 }),
577);
578
579/**
580 * Content heights of the page at each width, each from a fresh load, since
581 * pages often lay themselves out from the width once at load.
582 */
583export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
584 readonly executable: string;
585 readonly noSandbox: boolean;
586 readonly html: string;
587 readonly widths: ReadonlyArray<number>;
588 readonly urlFragment: string;
589}) {
590 const path = yield* Path.Path;
591 const directory = yield* scratchDirectory;
592 const browser = yield* launchBrowser({
593 executable: input.executable,
594 noSandbox: input.noSandbox,
595 profileDirectory: path.join(directory, "profile"),
596 });
597 const body = pageBody(input.html);
598 return yield* Effect.forEach(
599 input.widths,
600 (width) =>
601 browser.openPage(width).pipe(
602 Effect.flatMap((page) =>
603 page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
604 ),
605 Effect.map((height) => [width, height] as const),
606 ),
607 { concurrency: MEASURE_CONCURRENCY },
608 );
609}, Effect.scoped);