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

headlessChrome.ts

722 lines26.9 KB

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";
12import {
13 encodeHtmlRenderOutline,
14 HTML_RENDER_COLUMN_WIDTH,
15 HTML_RENDER_OUTLINE_MAX_BOXES,
16} from "@t3tools/shared/htmlRender";
17​
18import { publicProxy } from "./publicProxy.ts";
19​
20export class HtmlRenderBrowserError extends Schema.TaggedError<HtmlRenderBrowserError>()(
21 "HtmlRenderBrowserError",
22 {
23 reason: Schema.String,
24 cause: Schema.optional(Schema.Defect()),
25 /** The end of the browser's stderr when it exited, for diagnosing host setup. */
26 output: Schema.optional(Schema.String),
27 },
28) {
29 override get message(): string {
30 return `Headless Chrome could not render the page: ${this.reason}.`;
31 }
33​
34type BrowserFailure = HtmlRenderBrowserError;
35​
36export interface ConsoleMessage {
37 readonly level: "log" | "info" | "warning" | "error";
38 readonly text: string;
40​
41const MAX_CONSOLE_MESSAGES = 20;
42const MAX_CONSOLE_TEXT_CHARS = 500;
43const VIEWPORT_HEIGHT = 800;
44const MAX_CAPTURE_HEIGHT = 4_000;
45const CAPTURE_TIMEOUT = "20 seconds";
46// Pages load from this made-up web origin, never from a file. Chrome refuses
47// local files to every web page, frame, worker, and popup, so a page cannot
48// read files the agent's provider withholds; local images reach it already
49// inlined as data URIs. `.localhost` keeps it a secure context that may still
50// load plain-http resources, and the request never leaves the browser.
51// All of the browser's traffic goes through `publicProxy`, which only reaches
52// public addresses, so a page cannot reach this machine's local network. The
53// main frame also stays on the page and the browser opens no popups, so a
54// capture always shows the page itself.
55const PAGE_ORIGIN = "http://t3-page.localhost";
56const PAGE_URL = `${PAGE_ORIGIN}/page.html`;
57// Stack traces and load errors name the page this way instead of its URL.
58const PAGE_NAME = "page.html";
59// Each measuring load reads its own copy of the page off the pipe.
60const MEASURE_CONCURRENCY = 3;
61​
62const textEncoder = new TextEncoder();
63​
64/**
65 * A page as the base64 bytes `PAGE_URL` serves, encoded once however often it
66 * loads. Node's encoder, since pages run to 25 MiB.
67 */
68const pageBody = (html: string) =>
69 Buffer.from(Buffer.from(html, "utf8").toString("base64"), "latin1");
70​
71const CdpMessage = Schema.fromJsonString(
72 Schema.Struct({
73 id: Schema.optional(Schema.Number),
74 method: Schema.optional(Schema.String),
75 sessionId: Schema.optional(Schema.String),
76 params: Schema.optional(Schema.Unknown),
77 result: Schema.optional(Schema.Unknown),
78 error: Schema.optional(Schema.Struct({ message: Schema.String })),
79 }),
80);
81const decodeCdpMessage = Schema.decodeUnknownOption(CdpMessage);
82const encodeCdpCommand = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
83const RemoteObject = Schema.Struct({
84 type: Schema.String,
85 value: Schema.optional(Schema.Unknown),
86 description: Schema.optional(Schema.String),
87});
88const decodeConsoleApiCalled = Schema.decodeUnknownOption(
89 Schema.Struct({ type: Schema.String, args: Schema.Array(RemoteObject) }),
90);
91const decodeExceptionThrown = Schema.decodeUnknownOption(
92 Schema.Struct({
93 exceptionDetails: Schema.Struct({
94 text: Schema.String,
95 exception: Schema.optional(RemoteObject),
96 }),
97 }),
98);
99const decodeRequestPaused = Schema.decodeUnknownOption(
100 Schema.Struct({
101 requestId: Schema.String,
102 request: Schema.Struct({ url: Schema.String }),
103 frameId: Schema.optional(Schema.String),
104 resourceType: Schema.optional(Schema.String),
105 }),
106);
107const decodeLogEntryAdded = Schema.decodeUnknownOption(
108 Schema.Struct({
109 entry: Schema.Struct({
110 level: Schema.String,
111 text: Schema.String,
112 url: Schema.optional(Schema.String),
113 }),
114 }),
115);
116​
117const remoteObjectText = (value: typeof RemoteObject.Type) =>
118 typeof value.value === "string"
119 ? value.value
120 : (value.description ?? (value.value === undefined ? value.type : String(value.value)));
121​
122const CONSOLE_LEVELS: Readonly<Record<string, ConsoleMessage["level"]>> = {
123 log: "log",
124 debug: "log",
125 dir: "log",
126 dirxml: "log",
127 table: "log",
128 trace: "log",
129 info: "info",
130 warning: "warning",
131 error: "error",
132 assert: "error",
133};
134​
135/** Everything the page logs, uncaught exceptions, and the browser's own load errors. */
136const consoleMessageFromEvent = (method: string, params: unknown): ConsoleMessage | undefined => {
137 if (method === "Runtime.consoleAPICalled") {
138 const event = Option.getOrUndefined(decodeConsoleApiCalled(params));
139 const level = event === undefined ? undefined : CONSOLE_LEVELS[event.type];
140 return event && level ? { level, text: event.args.map(remoteObjectText).join(" ") } : undefined;
141 }
142 if (method === "Runtime.exceptionThrown") {
143 const details = Option.getOrUndefined(decodeExceptionThrown(params))?.exceptionDetails;
144 return details
145 ? { level: "error", text: details.exception?.description ?? details.text }
146 : undefined;
147 }
148 if (method === "Log.entryAdded") {
149 const entry = Option.getOrUndefined(decodeLogEntryAdded(params))?.entry;
150 return entry && (entry.level === "error" || entry.level === "warning")
151 ? { level: entry.level, text: entry.url ? `${entry.text} ${entry.url}` : entry.text }
152 : undefined;
153 }
154 return undefined;
155};
156​
157// Resolves after web fonts load and two frames paint, so late layout lands in the capture.
158const SETTLE_EXPRESSION =
159 "document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))";
160// The root's scroll height never drops below the viewport, so a short page
161// reports its own box height instead.
162const MEASURE_EXPRESSION =
163 "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";
164​
165// The page's main blocks in document order, for a client's loading skeleton:
166// media and solid shapes, text with its line count, and tables with their row
167// count. Boxes that only wrap other blocks are walked through, not drawn.
168// Past the detail budget, remaining blocks are kept whole, and once the outline
169// is full, one block of text lines stands in for the rest of the page, so the
170// skeleton still reaches the bottom.
171const OUTLINE_MAX_VISITS = 2_000;
172const OUTLINE_EXPRESSION = `(() => {
173 const boxes = [], detail = ${HTML_RENDER_OUTLINE_MAX_BOXES - 12}, max = ${HTML_RENDER_OUTLINE_MAX_BOXES};
174 const media = "canvas,svg,img,video,picture,iframe,object,embed,input,select,textarea,button";
175 const pageBackground = getComputedStyle(document.documentElement).backgroundColor;
176 const filled = (s) => (s.backgroundColor !== "rgba(0, 0, 0, 0)" && s.backgroundColor !== pageBackground) || s.backgroundImage !== "none" || parseFloat(s.borderTopWidth) + parseFloat(s.borderBottomWidth) + parseFloat(s.borderLeftWidth) > 0;
177 const add = (kind, r, lines) => boxes.push([kind, r.left + scrollX, r.top + scrollY, r.width, r.height, lines]);
178 const lineCount = (s, r) => Math.max(1, Math.round(r.height / (parseFloat(s.lineHeight) || parseFloat(s.fontSize) * 1.5 || 20)));
179 // Text's own extent, so a short heading in a wide block stays short.
180 const addText = (el, s, r) => {
181 const range = document.createRange();
182 range.selectNodeContents(el);
183 const t = range.getBoundingClientRect();
184 const box = t.width >= 2 && t.height >= 2 ? t : r;
185 add("text", box, lineCount(s, box));
186 };
187 // Visits are capped too, so a huge generated DOM costs no more than a page.
188 let full = false, visits = 0;
189 // Whether an element holds text of its own, looking at its first few children only.
190 const hasOwnText = (el) => {
191 let n = el.firstChild;
192 for (let i = 0; n && i < 64; n = n.nextSibling, i++) if (n.nodeType === 3 && n.data.trim() !== "") return true;
193 return false;
194 };
195 const walk = (parent, ps) => {
196 for (const el of parent.childNodes) {
197 // The last slot is kept for whatever the outline has no room left for.
198 if (boxes.length >= max - 1 || ++visits > ${OUTLINE_MAX_VISITS}) { full = true; return; }
199 // Bare text only reaches here under body or a display: contents element.
200 if (el.nodeType === 3) {
201 if (el.data.trim() === "") continue;
202 const range = document.createRange();
203 range.selectNodeContents(el);
204 const t = range.getBoundingClientRect();
205 if (t.width >= 2 && t.height >= 2) add("text", t, lineCount(ps, t));
206 continue;
207 }
208 if (el.nodeType !== 1) continue;
209 const s = getComputedStyle(el);
210 if (s.display === "none" || s.visibility === "hidden" || s.opacity === "0") continue;
211 if (s.display === "contents") { walk(el, s); continue; }
212 const r = el.getBoundingClientRect();
213 // A zero-size box can still show positioned children, unless it clips them.
214 if (r.width < 2 || r.height < 2) { if (s.overflow === "visible") walk(el, s); continue; }
215 const tag = el.localName;
216 if (el.matches(media)) { add("media", r, 1); continue; }
217 if (tag === "table") { add("table", r, el.rows.length); continue; }
218 const text = hasOwnText(el);
219 if (boxes.length >= detail) { if (el.querySelector(media) || (!text && !el.firstElementChild)) add("media", r, 1); else addText(el, s, r); continue; }
220 if (text) { addText(el, s, r); continue; }
221 if (el.children.length === 0) { if (filled(s)) add("media", r, 1); continue; }
222 walk(el, s);
223 }
224 };
225 walk(document.body, getComputedStyle(document.body));
226 if (full) {
227 const top = Math.max(0, ...boxes.map((b) => b[2] + b[4]));
228 const root = document.documentElement;
229 const rest = (root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height) - top;
230 if (rest >= 8) boxes.push(["text", 0, top, document.documentElement.clientWidth, rest, Math.max(1, Math.round(rest / 28))]);
231 }
232 return boxes;
233})()`;
234const Outlined = Schema.Struct({
235 result: Schema.Struct({
236 value: Schema.Array(
237 Schema.Tuple([
238 Schema.Literals(["text", "media", "table"]),
239 Schema.Finite,
240 Schema.Finite,
241 Schema.Finite,
242 Schema.Finite,
243 Schema.Finite,
244 ]),
245 ),
246 }),
247});
248​
249const Ignored = Schema.Unknown;
250const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });
251const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });
252​
253interface PageEvents {
254 /** The page's main frame, which only ever shows `PAGE_URL`. */
255 readonly mainFrameId: string;
256 /** The page served for `PAGE_URL`, from `pageBody`. */
257 body: Uint8Array | undefined;
258 loaded: Deferred.Deferred<void, BrowserFailure> | undefined;
259 readonly consoleMessages: Array<ConsoleMessage>;
260 omittedConsoleMessages: number;
262​
263/**
264 * Starts the headless shell for the life of the scope, speaking CDP over
265 * `--remote-debugging-pipe` (fd 3 in, fd 4 out, NUL-delimited JSON). Scope
266 * close kills the process group. Each page is its own target, so pages load
267 * in parallel.
268 */
269const launchBrowser = Effect.fnUntraced(function* (input: {
270 readonly executable: string;
271 readonly noSandbox: boolean;
272 readonly profileDirectory: string;
273}) {
274 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
275 const proxyPort = yield* publicProxy.pipe(
276 Effect.mapError(
277 (cause) => new HtmlRenderBrowserError({ reason: "the preview proxy could not start", cause }),
278 ),
279 );
280 const outgoing = yield* Queue.unbounded<Uint8Array>();
281 const child = yield* spawner
282 .spawn(
283 ChildProcess.make(
284 input.executable,
285 [
286 "--headless=new",
287 "--remote-debugging-pipe",
288 "--no-first-run",
289 "--no-default-browser-check",
290 "--disable-gpu",
291 "--hide-scrollbars",
292 "--mute-audio",
293 "--block-new-web-contents",
294 `--proxy-server=socks5://127.0.0.1:${proxyPort}`,
295 // Loopback would otherwise skip the proxy.
296 "--proxy-bypass-list=<-loopback>",
297 // WebRTC would otherwise send UDP, which no proxy carries.
298 "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
299 ...(input.noSandbox ? ["--no-sandbox"] : []),
300 `--user-data-dir=${input.profileDirectory}`,
301 "about:blank",
302 ],
303 {
304 stdin: "ignore",
305 stdout: "ignore",
306 stderr: "pipe",
307 forceKillAfter: "2 seconds",
308 additionalFds: {
309 fd3: { type: "input", stream: Stream.fromQueue(outgoing) },
310 fd4: { type: "output" },
311 },
312 },
313 ),
314 )
315 .pipe(
316 Effect.mapError(
317 (cause) =>
318 new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }),
319 ),
320 );
321​
322 let stderrTail = "";
323 const stderrReader = yield* child.stderr.pipe(
324 Stream.decodeText(),
325 Stream.runForEach((text) =>
326 Effect.sync(() => {
327 stderrTail = (stderrTail + text).slice(-2_048);
328 }),
329 ),
330 Effect.ignore,
331 Effect.forkScoped,
332 );
333​
334 const pending = new Map<
335 number,
336 { readonly method: string; readonly reply: Deferred.Deferred<unknown, BrowserFailure> }
337 >();
338 const pages = new Map<string, PageEvents>();
339 let disconnected: BrowserFailure | undefined;
340 let nextId = 0;
341​
342 // A command whose reply nobody awaits; `receive` drops replies without a waiter.
343 const post = (method: string, params: Record<string, unknown>, sessionId: string) =>
344 Queue.offer(
345 outgoing,
346 new TextEncoder().encode(
347 `${encodeCdpCommand({ id: ++nextId, method, params, sessionId })}\0`,
348 ),
349 ).pipe(Effect.asVoid);
350​
351 // Serves the page. Its body is shared bytes between two small JSON halves,
352 // queued together, so loading a page of up to 25 MiB at several widths never
353 // copies it on this side.
354 const fulfillPage = (sessionId: string, requestId: string, body: Uint8Array) =>
355 Queue.offerAll(outgoing, [
356 textEncoder.encode(
357 `{"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":"`,
358 ),
359 body,
360 textEncoder.encode('"}}\0'),
361 ]).pipe(Effect.asVoid);
362​
363 const receive = (raw: string) => {
364 const message = Option.getOrUndefined(decodeCdpMessage(raw));
365 if (message?.id !== undefined) {
366 const waiter = pending.get(message.id);
367 pending.delete(message.id);
368 if (!waiter) return Effect.void;
369 return message.error
370 ? Deferred.fail(
371 waiter.reply,
372 new HtmlRenderBrowserError({
373 reason: `${waiter.method} failed`,
374 cause: message.error.message,
375 }),
376 )
377 : Deferred.succeed(waiter.reply, message.result);
378 }
379 const sessionId = message?.sessionId;
380 const page = sessionId === undefined ? undefined : pages.get(sessionId);
381 if (sessionId === undefined || !page || !message?.method) return Effect.void;
382 if (message.method === "Page.loadEventFired") {
383 return page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void;
384 }
385 if (message.method === "Fetch.requestPaused") {
386 const paused = Option.getOrUndefined(decodeRequestPaused(message.params));
387 if (!paused) return Effect.void;
388 const body = page.body;
389 const url = paused.request.url.split("#", 1)[0]!;
390 if (url === PAGE_URL && body !== undefined) {
391 return fulfillPage(sessionId, paused.requestId, body);
392 }
393 // A frame inside the page may show another site; Local Network Access
394 // still covers it. The main frame and T3's own origin serve nothing else.
395 const otherSiteFrame =
396 paused.resourceType === "Document" &&
397 paused.frameId !== page.mainFrameId &&
398 !url.startsWith(`${PAGE_ORIGIN}/`);
399 return otherSiteFrame
400 ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId)
401 : post(
402 "Fetch.failRequest",
403 { requestId: paused.requestId, errorReason: "AccessDenied" },
404 sessionId,
405 );
406 }
407 const consoleMessage = consoleMessageFromEvent(message.method, message.params);
408 if (!consoleMessage) return Effect.void;
409 if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) {
410 page.omittedConsoleMessages += 1;
411 return Effect.void;
412 }
413 const text = consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME);
414 page.consoleMessages.push({
415 level: consoleMessage.level,
416 text:
417 text.length > MAX_CONSOLE_TEXT_CHARS ? `${text.slice(0, MAX_CONSOLE_TEXT_CHARS)}…` : text,
418 });
419 return Effect.void;
420 };
421​
422 // The pipe closes when the browser exits. A startup abort, such as a missing
423 // sandbox, says why on stderr, which may still be draining, so give it a moment.
424 const disconnect = Effect.gen(function* () {
425 yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore);
426 const error = new HtmlRenderBrowserError({
427 reason: "the browser exited unexpectedly",
428 output: stderrTail,
429 });
430 disconnected = error;
431 const waiters = [...pending.values()];
432 pending.clear();
433 yield* Effect.forEach(waiters, ({ reply }) => Deferred.fail(reply, error), { discard: true });
434 yield* Effect.forEach(
435 pages.values(),
436 (page) => (page.loaded ? Deferred.fail(page.loaded, error) : Effect.void),
437 { discard: true },
438 );
439 });
440​
441 // Decoded text chunks may split a message anywhere, and a screenshot reply spans many.
442 let partial: Array<string> = [];
443 yield* child.getOutputFd(4).pipe(
444 Stream.decodeText(),
445 Stream.runForEach((text) => {
446 const complete: Array<string> = [];
447 let start = 0;
448 for (let end = text.indexOf("\0"); end !== -1; end = text.indexOf("\0", start)) {
449 partial.push(text.slice(start, end));
450 complete.push(partial.join(""));
451 partial = [];
452 start = end + 1;
453 }
454 if (start < text.length) partial.push(text.slice(start));
455 return Effect.forEach(complete, receive, { discard: true });
456 }),
457 Effect.ignore,
458 // Interruption means the scope is closing on purpose; only an exit disconnects.
459 Effect.andThen(disconnect),
460 Effect.forkScoped,
461 );
462​
463 const send = <A>(
464 method: string,
465 params: Record<string, unknown>,
466 result: Schema.Decoder<A>,
467 sessionId?: string,
468 ) =>
469 Effect.gen(function* () {
470 if (disconnected) return yield* disconnected;
471 const id = ++nextId;
472 const reply = yield* Deferred.make<unknown, BrowserFailure>();
473 pending.set(id, { method, reply });
474 const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) });
475 yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`));
476 return yield* Deferred.await(reply).pipe(
477 Effect.flatMap(Schema.decodeUnknownEffect(result)),
478 Effect.mapError((error) =>
479 error._tag === "HtmlRenderBrowserError"
480 ? error
481 : new HtmlRenderBrowserError({
482 reason: `${method} returned an unexpected result`,
483 cause: error,
484 }),
485 ),
486 );
487 });
488​
489 /** A fresh page at `width`; each `load` navigates it and measures the settled layout. */
490 const openPage = Effect.fnUntraced(function* (width: number) {
491 const { targetId } = yield* send(
492 "Target.createTarget",
493 { url: "about:blank" },
494 Schema.Struct({ targetId: Schema.String }),
495 );
496 const { sessionId } = yield* send(
497 "Target.attachToTarget",
498 { targetId, flatten: true },
499 Schema.Struct({ sessionId: Schema.String }),
500 );
501 const events: PageEvents = {
502 // A page target's id is its main frame's id.
503 mainFrameId: targetId,
504 body: undefined,
505 loaded: undefined,
506 consoleMessages: [],
507 omittedConsoleMessages: 0,
508 };
509 pages.set(sessionId, events);
510 yield* send("Page.enable", {}, Ignored, sessionId);
511 yield* send("Runtime.enable", {}, Ignored, sessionId);
512 yield* send("Log.enable", {}, Ignored, sessionId);
513 // Previews have no use for WebRTC, whose ICE servers can make the browser
514 // resolve names outside the proxy. Runs before page scripts in every frame.
515 yield* send(
516 "Page.addScriptToEvaluateOnNewDocument",
517 {
518 source: "delete window.RTCPeerConnection; delete window.webkitRTCPeerConnection;",
519 runImmediately: true,
520 },
521 Ignored,
522 sessionId,
523 );
524 // Pauses T3's own origin, to serve the page, and every document, to keep
525 // the main frame on it.
526 yield* send(
527 "Fetch.enable",
528 {
529 patterns: [
530 { urlPattern: `${PAGE_ORIGIN}/*` },
531 { urlPattern: "*", resourceType: "Document" },
532 ],
533 },
534 Ignored,
535 sessionId,
536 );
537 yield* send(
538 "Emulation.setDeviceMetricsOverride",
539 { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false },
540 Ignored,
541 sessionId,
542 );
543​
544 /** Loads a page from `pageBody`, so callers loading it often encode it once. */
545 const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) {
546 const loaded = yield* Deferred.make<void, BrowserFailure>();
547 events.body = body;
548 events.loaded = loaded;
549 const navigation = yield* send(
550 "Page.navigate",
551 { url: `${PAGE_URL}${urlFragment}` },
552 Navigation,
553 sessionId,
554 );
555 if (navigation.errorText) {
556 return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" });
557 }
558 yield* Deferred.await(loaded);
559 yield* send(
560 "Runtime.evaluate",
561 { expression: SETTLE_EXPRESSION, awaitPromise: true },
562 Ignored,
563 sessionId,
564 );
565 const measured = yield* send(
566 "Runtime.evaluate",
567 { expression: MEASURE_EXPRESSION, returnByValue: true },
568 Measured,
569 sessionId,
570 );
571 return Math.max(0, Math.ceil(measured.result.value));
572 });
573​
574 const screenshot = (height: number) =>
575 send(
576 "Page.captureScreenshot",
577 {
578 format: "png",
579 captureBeyondViewport: true,
580 clip: { x: 0, y: 0, width, height, scale: 1 },
581 },
582 Schema.Struct({ data: Schema.String }),
583 sessionId,
584 ).pipe(Effect.map(({ data }) => data));
585​
586 const consoleMessages = (): ReadonlyArray<ConsoleMessage> =>
587 events.omittedConsoleMessages === 0
588 ? [...events.consoleMessages]
589 : [
590 ...events.consoleMessages,
591 {
592 level: "warning",
593 text: `${events.omittedConsoleMessages} more console messages were omitted.`,
594 },
595 ];
596​
597 // Frees the page in the browser once it is no longer needed.
598 const close = send("Target.closeTarget", { targetId }, Ignored).pipe(
599 Effect.ensuring(Effect.sync(() => pages.delete(sessionId))),
600 Effect.ignore,
601 );
602​
603 /** The loaded page's outline, encoded for an `HtmlRenderReference`. */
604 const outline = send(
605 "Runtime.evaluate",
606 { expression: OUTLINE_EXPRESSION, returnByValue: true },
607 Outlined,
608 sessionId,
609 ).pipe(
610 Effect.map(({ result }) =>
611 encodeHtmlRenderOutline(
612 result.value.map(([kind, x, y, boxWidth, height, lines]) => ({
613 kind,
614 x,
615 y,
616 width: boxWidth,
617 height,
618 lines,
619 })),
620 ),
621 ),
622 );
623​
624 return { load, outline, screenshot, consoleMessages, close };
625 });
626​
627 return { openPage };
628});
629​
630/** A temporary directory for the browser profile, removed with the scope. */
631const scratchDirectory = Effect.gen(function* () {
632 const fileSystem = yield* FileSystem.FileSystem;
633 return yield* Effect.acquireRelease(
634 fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }),
635 (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore),
636 ).pipe(
637 Effect.mapError(
638 (cause) =>
639 new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }),
640 ),
641 );
642});
643​
644/** Loads `html` at `width` and returns a PNG of the top of the page. */
645export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")(
646 function* (input: {
647 readonly executable: string;
648 readonly noSandbox: boolean;
649 readonly html: string;
650 readonly width: number;
651 readonly urlFragment: string;
652 }) {
653 const path = yield* Path.Path;
654 const directory = yield* scratchDirectory;
655 const browser = yield* launchBrowser({
656 executable: input.executable,
657 noSandbox: input.noSandbox,
658 profileDirectory: path.join(directory, "profile"),
659 });
660 const page = yield* browser.openPage(input.width);
661 const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment);
662 const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT));
663 const png = yield* page.screenshot(capturedHeight);
664 return { png, contentHeight, capturedHeight, consoleMessages: page.consoleMessages() };
665 },
666 Effect.scoped,
667 Effect.timeoutOrElse({
668 duration: CAPTURE_TIMEOUT,
669 orElse: () =>
670 Effect.fail(
671 new HtmlRenderBrowserError({
672 reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`,
673 }),
674 ),
675 }),
676);
677​
678/**
679 * Content heights of the page at each width, each from a fresh load, since
680 * pages often lay themselves out from the width once at load. One browser,
681 * a few widths at a time. The load at the column width also reads the page's
682 * outline; an outline that cannot be read is left out.
683 */
684export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
685 readonly executable: string;
686 readonly noSandbox: boolean;
687 readonly html: string;
688 readonly widths: ReadonlyArray<number>;
689 readonly urlFragment: string;
690}) {
691 const path = yield* Path.Path;
692 const directory = yield* scratchDirectory;
693 const browser = yield* launchBrowser({
694 executable: input.executable,
695 noSandbox: input.noSandbox,
696 profileDirectory: path.join(directory, "profile"),
697 });
698 const body = pageBody(input.html);
699 let outline: string | undefined;
700 const heights = yield* Effect.forEach(
701 input.widths,
702 (width) =>
703 browser.openPage(width).pipe(
704 Effect.flatMap((page) =>
705 page.load(body, input.urlFragment).pipe(
706 Effect.tap(() =>
707 width === HTML_RENDER_COLUMN_WIDTH
708 ? page.outline.pipe(
709 Effect.tap((value) => Effect.sync(() => (outline = value))),
710 Effect.ignore,
711 )
712 : Effect.void,
713 ),
714 Effect.ensuring(page.close),
715 ),
716 ),
717 Effect.map((height) => [width, height] as const),
718 ),
719 { concurrency: MEASURE_CONCURRENCY },
720 );
721 return { heights, outline };
722}, Effect.scoped);