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

headlessChrome.ts

617 lines21.7 KB

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