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