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

headlessChrome.ts

613 lines21.6 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 blocks file access; images arrive inlined. Browser-only .localhost permits secure contexts and HTTP resources.
50// publicProxy blocks local networks; pinning the main frame and forbidding popups keeps captures on the page.
51const PAGE_ORIGIN = "http://t3-page.localhost";
52const PAGE_URL = `${PAGE_ORIGIN}/page.html`;
53const PAGE_NAME = "page.html";
54const MEASURE_CONCURRENCY = 3;
55​
56const textEncoder = new TextEncoder();
57​
58// Pages reach 25 MiB; use Node's encoder.
59const pageBody = (html: string) =>
60 Buffer.from(Buffer.from(html, "utf8").toString("base64"), "latin1");
61​
62const CdpMessage = Schema.fromJsonString(
63 Schema.Struct({
64 id: Schema.optional(Schema.Number),
65 method: Schema.optional(Schema.String),
66 sessionId: Schema.optional(Schema.String),
67 params: Schema.optional(Schema.Unknown),
68 result: Schema.optional(Schema.Unknown),
69 error: Schema.optional(Schema.Struct({ message: Schema.String })),
70 }),
71);
72const decodeCdpMessage = Schema.decodeUnknownOption(CdpMessage);
73const encodeCdpCommand = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
74const RemoteObject = Schema.Struct({
75 type: Schema.String,
76 value: Schema.optional(Schema.Unknown),
77 description: Schema.optional(Schema.String),
78});
79const decodeConsoleApiCalled = Schema.decodeUnknownOption(
80 Schema.Struct({ type: Schema.String, args: Schema.Array(RemoteObject) }),
81);
82const decodeExceptionThrown = Schema.decodeUnknownOption(
83 Schema.Struct({
84 exceptionDetails: Schema.Struct({
85 text: Schema.String,
86 exception: Schema.optional(RemoteObject),
87 }),
88 }),
89);
90const decodeRequestPaused = Schema.decodeUnknownOption(
91 Schema.Struct({
92 requestId: Schema.String,
93 request: Schema.Struct({ url: Schema.String }),
94 frameId: Schema.optional(Schema.String),
95 resourceType: Schema.optional(Schema.String),
96 }),
97);
98const decodeLogEntryAdded = Schema.decodeUnknownOption(
99 Schema.Struct({
100 entry: Schema.Struct({
101 level: Schema.String,
102 text: Schema.String,
103 url: Schema.optional(Schema.String),
104 }),
105 }),
106);
107​
108const remoteObjectText = (value: typeof RemoteObject.Type) =>
109 typeof value.value === "string"
110 ? value.value
111 : (value.description ?? (value.value === undefined ? value.type : String(value.value)));
112​
113const CONSOLE_LEVELS: Readonly<Record<string, ConsoleMessage["level"]>> = {
114 log: "log",
115 debug: "log",
116 dir: "log",
117 dirxml: "log",
118 table: "log",
119 trace: "log",
120 info: "info",
121 warning: "warning",
122 error: "error",
123 assert: "error",
124};
125​
126const consoleMessageFromEvent = (method: string, params: unknown): ConsoleMessage | undefined => {
127 if (method === "Runtime.consoleAPICalled") {
128 const event = Option.getOrUndefined(decodeConsoleApiCalled(params));
129 const level = event === undefined ? undefined : CONSOLE_LEVELS[event.type];
130 return event && level ? { level, text: event.args.map(remoteObjectText).join(" ") } : undefined;
131 }
132 if (method === "Runtime.exceptionThrown") {
133 const details = Option.getOrUndefined(decodeExceptionThrown(params))?.exceptionDetails;
134 return details
135 ? { level: "error", text: details.exception?.description ?? details.text }
136 : undefined;
137 }
138 if (method === "Log.entryAdded") {
139 const entry = Option.getOrUndefined(decodeLogEntryAdded(params))?.entry;
140 return entry && (entry.level === "error" || entry.level === "warning")
141 ? { level: entry.level, text: entry.url ? `${entry.text} ${entry.url}` : entry.text }
142 : undefined;
143 }
144 return undefined;
145};
146​
147// Wait for fonts and two paint frames to capture late layout.
148const SETTLE_EXPRESSION =
149 "document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))";
150// scrollHeight is at least viewport height; use the root box for shorter pages.
151const MEASURE_EXPRESSION =
152 "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";
153​
154const Ignored = Schema.Unknown;
155const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });
156const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });
157​
158// Effect's spawner names the signal that ended a child only in its error message.
159const EXIT_SIGNAL = /signal: '(SIG[A-Z0-9]+)'/;
160​
161interface PageEvents {
162 readonly mainFrameId: string;
163 body: Uint8Array | undefined;
164 loaded: Deferred.Deferred<void, BrowserFailure> | undefined;
165 readonly consoleMessages: Array<ConsoleMessage>;
166 omittedConsoleMessages: number;
168​
169// CDP pipe uses fd 3 in, fd 4 out and NUL-delimited JSON.
170const launchBrowser = Effect.fnUntraced(function* (input: {
171 readonly executable: string;
172 readonly noSandbox: boolean;
173 readonly profileDirectory: string;
174}) {
175 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
176 const proxyPort = yield* publicProxy.pipe(
177 Effect.mapError(
178 (cause) => new HtmlRenderBrowserError({ reason: "the preview proxy could not start", cause }),
179 ),
180 );
181 const outgoing = yield* Queue.unbounded<Uint8Array>();
182 const child = yield* spawner
183 .spawn(
184 ChildProcess.make(
185 input.executable,
186 [
187 "--headless=new",
188 "--remote-debugging-pipe",
189 "--no-first-run",
190 "--no-default-browser-check",
191 "--disable-gpu",
192 "--hide-scrollbars",
193 "--mute-audio",
194 "--block-new-web-contents",
195 `--proxy-server=socks5://127.0.0.1:${proxyPort}`,
196 // Loopback would otherwise skip the proxy.
197 "--proxy-bypass-list=<-loopback>",
198 // WebRTC would otherwise send UDP, which no proxy carries.
199 "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
200 ...(input.noSandbox ? ["--no-sandbox"] : []),
201 `--user-data-dir=${input.profileDirectory}`,
202 "about:blank",
203 ],
204 {
205 stdin: "ignore",
206 stdout: "ignore",
207 stderr: "pipe",
208 forceKillAfter: "2 seconds",
209 additionalFds: {
210 fd3: { type: "input", stream: Stream.fromQueue(outgoing) },
211 fd4: { type: "output" },
212 },
213 },
214 ),
215 )
216 .pipe(
217 Effect.mapError(
218 (cause) =>
219 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
220 ),
221 // Node throws some spawn errors synchronously, such as `spawn UNKNOWN`
222 // when policy blocks the executable; `mapError` cannot catch those.
223 Effect.catchDefect((cause) =>
224 Effect.fail(
225 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
226 ),
227 ),
228 );
229​
230 let stderrTail = "";
231 const stderrReader = yield* child.stderr.pipe(
232 Stream.decodeText(),
233 Stream.runForEach((text) =>
234 Effect.sync(() => {
235 stderrTail = (stderrTail + text).slice(-2_048);
236 }),
237 ),
238 Effect.ignore,
239 Effect.forkScoped,
240 );
241​
242 const pending = new Map<
243 number,
244 { readonly method: string; readonly reply: Deferred.Deferred<unknown, BrowserFailure> }
245 >();
246 const pages = new Map<string, PageEvents>();
247 let disconnected: BrowserFailure | undefined;
248 let nextId = 0;
249​
250 const post = (method: string, params: Record<string, unknown>, sessionId?: string) =>
251 Queue.offer(
252 outgoing,
253 new TextEncoder().encode(
254 `${encodeCdpCommand({ id: ++nextId, method, params, sessionId })}\0`,
255 ),
256 ).pipe(Effect.asVoid);
257​
258 // Queue shared body bytes between JSON halves to avoid copies across capture widths.
259 const fulfillPage = (sessionId: string, requestId: string, body: Uint8Array) =>
260 Queue.offerAll(outgoing, [
261 textEncoder.encode(
262 `{"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":"`,
263 ),
264 body,
265 textEncoder.encode('"}}\0'),
266 ]).pipe(Effect.asVoid);
267​
268 // Incoming messages share the session span; frame acknowledgements are frequent.
269 const receive = Effect.fnUntraced(function* (raw: string) {
270 const message = Option.getOrUndefined(decodeCdpMessage(raw));
271 if (message?.id !== undefined) {
272 const waiter = pending.get(message.id);
273 pending.delete(message.id);
274 if (!waiter) return yield* Effect.void;
275 return yield* message.error
276 ? Deferred.fail(
277 waiter.reply,
278 new HtmlRenderBrowserError({
279 reason: `${waiter.method} failed`,
280 cause: message.error.message,
281 }),
282 )
283 : Deferred.succeed(waiter.reply, message.result);
284 }
285 const sessionId = message?.sessionId;
286 const page = sessionId === undefined ? undefined : pages.get(sessionId);
287 if (sessionId === undefined || !page || !message?.method) return yield* Effect.void;
288 if (message.method === "Page.loadEventFired") {
289 return yield* page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
290 }
291 if (message.method === "Fetch.requestPaused") {
292 const paused = Option.getOrUndefined(decodeRequestPaused(message.params));
293 if (!paused) return yield* Effect.void;
294 const body = page.body;
295 const url = paused.request.url.split("#", 1)[0]!;
296 if (url === PAGE_URL && body !== undefined) {
297 return yield* fulfillPage(sessionId, paused.requestId, body);
298 }
299 // Subframes may show other sites covered by Local Network Access; the main frame stays on T3's page.
300 const otherSiteFrame =
301 paused.resourceType === "Document" &&
302 paused.frameId !== page.mainFrameId &&
303 !url.startsWith(`${PAGE_ORIGIN}/`);
304 return yield* otherSiteFrame
305 ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId)
306 : post(
307 "Fetch.failRequest",
308 { requestId: paused.requestId, errorReason: "AccessDenied" },
309 sessionId,
310 );
311 }
312 const consoleMessage = consoleMessageFromEvent(message.method, message.params);
313 if (!consoleMessage) return yield* Effect.void;
314 if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {
315 page.omittedConsoleMessages += 1;
316 return yield* Effect.void;
317 }
318 const text = consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME);
319 // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject.
320 const last = text.charCodeAt(MAX_CONSOLE_TEXT_CHARS - 1);
321 const end =
322 last >= 0xd800 && last <= 0xdbff ? MAX_CONSOLE_TEXT_CHARS - 1 : MAX_CONSOLE_TEXT_CHARS;
323 page.consoleMessages.push({
324 level: consoleMessage.level,
325 text: text.length > MAX_CONSOLE_TEXT_CHARS ? `${text.slice(0, end)}…` : text,
326 });
327 return yield* Effect.void;
328 });
329​
330 // Startup aborts close the pipe; let stderr drain to recover the reason.
331 const disconnect = Effect.gen(function* () {
332 yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore);
333 const exit = yield* child.exitCode.pipe(
334 Effect.map((code): { exitCode?: number; signal?: string; cause?: unknown } => ({
335 exitCode: code,
336 })),
337 Effect.catch((error) => {
338 const signal = EXIT_SIGNAL.exec(String(error.cause))?.[1];
339 return Effect.succeed(signal === undefined ? { cause: error } : { signal, cause: error });
340 }),
341 Effect.timeoutOption("1 second"),
342 );
343 const error = new HtmlRenderBrowserError({
344 reason: "the browser exited unexpectedly",
345 output: stderrTail,
346 ...Option.getOrElse(exit, () => ({})),
347 });
348 disconnected = error;
349 const waiters = [...pending.values()];
350 pending.clear();
351 yield* Effect.forEach(waiters, ({ reply }) => Deferred.fail(reply, error), { discard: true });
352 yield* Effect.forEach(
353 pages.values(),
354 (page) => (page.loaded ? Deferred.fail(page.loaded, error) : Effect.void),
355 { discard: true },
356 );
357 });
358​
359 // Chunks may split messages; screenshot replies span many chunks.
360 let partial: Array<string> = [];
361 yield* child.getOutputFd(4).pipe(
362 Stream.decodeText(),
363 Stream.runForEach((text) => {
364 const complete: Array<string> = [];
365 let start = 0;
366 for (let end = text.indexOf("\0"); end !== -1; end = text.indexOf("\0", start)) {
367 partial.push(text.slice(start, end));
368 complete.push(partial.join(""));
369 partial = [];
370 start = end + 1;
371 }
372 if (start < text.length) partial.push(text.slice(start));
373 return Effect.forEach(complete, receive, { discard: true });
374 }),
375 Effect.ignore,
376 Effect.andThen(disconnect),
377 Effect.forkScoped,
378 );
379​
380 // Signals can miss a confined browser (AppArmor in LXC), so ask it to quit first.
381 // Runs before the spawn's release, which still signals a browser that stays up.
382 yield* Effect.addFinalizer(() =>
383 disconnected
384 ? Effect.void
385 : post("Browser.close", {}).pipe(
386 Effect.andThen(child.exitCode),
387 Effect.timeout("2 seconds"),
388 Effect.ignore,
389 ),
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 // Intercept T3's page and all document navigations to keep the main frame on it.
458 yield* send(
459 "Fetch.enable",
460 {
461 patterns: [
462 { urlPattern: `${PAGE_ORIGIN}/*` },
463 { urlPattern: "*", resourceType: "Document" },
464 ],
465 },
466 Ignored,
467 sessionId,
468 );
469 yield* send(
470 "Emulation.setDeviceMetricsOverride",
471 { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false },
472 Ignored,
473 sessionId,
474 );
475​
476 const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) {
477 const loaded = yield* Deferred.make<void, BrowserFailure>();
478 events.body = body;
479 events.loaded = loaded;
480 const navigation = yield* send(
481 "Page.navigate",
482 { url: `${PAGE_URL}${urlFragment}` },
483 Navigation,
484 sessionId,
485 );
486 if (navigation.errorText) {
487 return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" });
488 }
489 yield* Deferred.await(loaded);
490 yield* send(
491 "Runtime.evaluate",
492 { expression: SETTLE_EXPRESSION, awaitPromise: true },
493 Ignored,
494 sessionId,
495 );
496 const measured = yield* send(
497 "Runtime.evaluate",
498 { expression: MEASURE_EXPRESSION, returnByValue: true },
499 Measured,
500 sessionId,
501 );
502 return Math.max(0, Math.ceil(measured.result.value));
503 });
504​
505 const screenshot = (height: number) =>
506 send(
507 "Page.captureScreenshot",
508 {
509 format: "png",
510 captureBeyondViewport: true,
511 clip: { x: 0, y: 0, width, height, scale: 1 },
512 },
513 Schema.Struct({ data: Schema.String }),
514 sessionId,
515 ).pipe(Effect.map(({ data }) => data));
516​
517 const consoleMessages = (): ReadonlyArray<ConsoleMessage> =>
518 events.omittedConsoleMessages === 0
519 ? [...events.consoleMessages]
520 : [
521 ...events.consoleMessages,
522 {
523 level: "warning",
524 text: `${events.omittedConsoleMessages} more console messages were omitted.`,
525 },
526 ];
527​
528 const close = send("Target.closeTarget", { targetId }, Ignored).pipe(
529 Effect.ensuring(Effect.sync(() => pages.delete(sessionId))),
530 Effect.ignore,
531 );
532​
533 return { load, screenshot, consoleMessages, close };
534 });
535​
536 return { openPage };
537});
538​
539const scratchDirectory = Effect.gen(function* () {
540 const fileSystem = yield* FileSystem.FileSystem;
541 return yield* Effect.acquireRelease(
542 fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }),
543 (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore),
544 ).pipe(
545 Effect.mapError(
546 (cause) =>
547 new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }),
548 ),
549 );
550});
551​
552export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")(
553 function* (input: {
554 readonly executable: string;
555 readonly noSandbox: boolean;
556 readonly html: string;
557 readonly width: number;
558 readonly urlFragment: string;
559 readonly appearance: ThemeAppearance;
560 }) {
561 const path = yield* Path.Path;
562 const directory = yield* scratchDirectory;
563 const browser = yield* launchBrowser({
564 executable: input.executable,
565 noSandbox: input.noSandbox,
566 profileDirectory: path.join(directory, "profile"),
567 });
568 const page = yield* browser.openPage(input.width, input.appearance);
569 const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment);
570 const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT));
571 const png = yield* page.screenshot(capturedHeight);
572 return { png, contentHeight, capturedHeight, consoleMessages: page.consoleMessages() };
573 },
574 Effect.scoped,
575 Effect.timeoutOrElse({
576 duration: CAPTURE_TIMEOUT,
577 orElse: () =>
578 Effect.fail(
579 new HtmlRenderBrowserError({
580 reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`,
581 }),
582 ),
583 }),
584);
585​
586/** Fresh load per width, since pages may lay out only at load. */
587export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
588 readonly executable: string;
589 readonly noSandbox: boolean;
590 readonly html: string;
591 readonly widths: ReadonlyArray<number>;
592 readonly urlFragment: string;
593}) {
594 const path = yield* Path.Path;
595 const directory = yield* scratchDirectory;
596 const browser = yield* launchBrowser({
597 executable: input.executable,
598 noSandbox: input.noSandbox,
599 profileDirectory: path.join(directory, "profile"),
600 });
601 const body = pageBody(input.html);
602 return yield* Effect.forEach(
603 input.widths,
604 (width) =>
605 browser.openPage(width, "dark").pipe(
606 Effect.flatMap((page) =>
607 page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
608 ),
609 Effect.map((height) => [width, height] as const),
610 ),
611 { concurrency: MEASURE_CONCURRENCY },
612 );
613}, Effect.scoped);