The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { ThemeAppearance } from "@t3tools/shared/themePalettes"; |
| 2 | import * as Deferred from "effect/Deferred"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Fiber from "effect/Fiber"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Path from "effect/Path"; |
| 8 | import * as Queue from "effect/Queue"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 12 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 13 | |
| 14 | import { publicProxy } from "./publicProxy.ts"; |
| 15 | |
| 16 | export 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 | } |
| 35 | } |
| 36 | |
| 37 | type BrowserFailure = HtmlRenderBrowserError; |
| 38 | |
| 39 | export interface ConsoleMessage { |
| 40 | readonly level: "log" | "info" | "warning" | "error"; |
| 41 | readonly text: string; |
| 42 | } |
| 43 | |
| 44 | const MAX_CONSOLE_MESSAGES = 20; |
| 45 | const MAX_CONSOLE_TEXT_CHARS = 500; |
| 46 | const VIEWPORT_HEIGHT = 800; |
| 47 | const MAX_CAPTURE_HEIGHT = 4_000; |
| 48 | const 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. |
| 51 | const PAGE_ORIGIN = "http://t3-page.localhost"; |
| 52 | const PAGE_URL = `${PAGE_ORIGIN}/page.html`; |
| 53 | const PAGE_NAME = "page.html"; |
| 54 | const MEASURE_CONCURRENCY = 3; |
| 55 | |
| 56 | const textEncoder = new TextEncoder(); |
| 57 | |
| 58 | // Pages reach 25 MiB; use Node's encoder. |
| 59 | const pageBody = (html: string) => |
| 60 | Buffer.from(Buffer.from(html, "utf8").toString("base64"), "latin1"); |
| 61 | |
| 62 | const 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 | ); |
| 72 | const decodeCdpMessage = Schema.decodeUnknownOption(CdpMessage); |
| 73 | const encodeCdpCommand = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); |
| 74 | const RemoteObject = Schema.Struct({ |
| 75 | type: Schema.String, |
| 76 | value: Schema.optional(Schema.Unknown), |
| 77 | description: Schema.optional(Schema.String), |
| 78 | }); |
| 79 | const decodeConsoleApiCalled = Schema.decodeUnknownOption( |
| 80 | Schema.Struct({ type: Schema.String, args: Schema.Array(RemoteObject) }), |
| 81 | ); |
| 82 | const decodeExceptionThrown = Schema.decodeUnknownOption( |
| 83 | Schema.Struct({ |
| 84 | exceptionDetails: Schema.Struct({ |
| 85 | text: Schema.String, |
| 86 | exception: Schema.optional(RemoteObject), |
| 87 | }), |
| 88 | }), |
| 89 | ); |
| 90 | const 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 | ); |
| 98 | const 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 | |
| 108 | const clipConsoleText = (text: string) => { |
| 109 | if (text.length <= MAX_CONSOLE_TEXT_CHARS) return text; |
| 110 | // Half an emoji serializes to a lone surrogate escape, which provider JSON parsers reject. |
| 111 | const last = text.charCodeAt(MAX_CONSOLE_TEXT_CHARS - 1); |
| 112 | const end = |
| 113 | last >= 0xd800 && last <= 0xdbff ? MAX_CONSOLE_TEXT_CHARS - 1 : MAX_CONSOLE_TEXT_CHARS; |
| 114 | return `${text.slice(0, end)}…`; |
| 115 | }; |
| 116 | |
| 117 | const 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 | |
| 122 | const 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 | const consoleMessageFromEvent = (method: string, params: unknown): ConsoleMessage | undefined => { |
| 136 | if (method === "Runtime.consoleAPICalled") { |
| 137 | const event = Option.getOrUndefined(decodeConsoleApiCalled(params)); |
| 138 | const level = event === undefined ? undefined : CONSOLE_LEVELS[event.type]; |
| 139 | return event && level ? { level, text: event.args.map(remoteObjectText).join(" ") } : undefined; |
| 140 | } |
| 141 | if (method === "Runtime.exceptionThrown") { |
| 142 | const details = Option.getOrUndefined(decodeExceptionThrown(params))?.exceptionDetails; |
| 143 | return details |
| 144 | ? { level: "error", text: details.exception?.description ?? details.text } |
| 145 | : undefined; |
| 146 | } |
| 147 | if (method === "Log.entryAdded") { |
| 148 | const entry = Option.getOrUndefined(decodeLogEntryAdded(params))?.entry; |
| 149 | return entry && (entry.level === "error" || entry.level === "warning") |
| 150 | ? { level: entry.level, text: entry.url ? `${entry.text} ${entry.url}` : entry.text } |
| 151 | : undefined; |
| 152 | } |
| 153 | return undefined; |
| 154 | }; |
| 155 | |
| 156 | // Wait for fonts and two paint frames to capture late layout. |
| 157 | const SETTLE_EXPRESSION = |
| 158 | "document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))"; |
| 159 | // scrollHeight is at least viewport height; use the root box for shorter pages. |
| 160 | const MEASURE_EXPRESSION = |
| 161 | "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()"; |
| 162 | |
| 163 | const Ignored = Schema.Unknown; |
| 164 | const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) }); |
| 165 | const 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. |
| 168 | const EXIT_SIGNAL = /signal: '(SIG[A-Z0-9]+)'/; |
| 169 | |
| 170 | interface PageEvents { |
| 171 | readonly mainFrameId: string; |
| 172 | body: Uint8Array | undefined; |
| 173 | loaded: Deferred.Deferred<void, BrowserFailure> | undefined; |
| 174 | readonly consoleMessages: Array<ConsoleMessage>; |
| 175 | omittedConsoleMessages: number; |
| 176 | } |
| 177 | |
| 178 | // CDP pipe uses fd 3 in, fd 4 out and NUL-delimited JSON. |
| 179 | const launchBrowser = Effect.fnUntraced(function* (input: { |
| 180 | readonly executable: string; |
| 181 | readonly noSandbox: boolean; |
| 182 | readonly profileDirectory: string; |
| 183 | }) { |
| 184 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 185 | const proxy = yield* publicProxy.pipe( |
| 186 | Effect.mapError( |
| 187 | (cause) => new HtmlRenderBrowserError({ reason: "the preview proxy could not start", cause }), |
| 188 | ), |
| 189 | ); |
| 190 | const outgoing = yield* Queue.unbounded<Uint8Array>(); |
| 191 | const child = yield* spawner |
| 192 | .spawn( |
| 193 | ChildProcess.make( |
| 194 | input.executable, |
| 195 | [ |
| 196 | "--headless=new", |
| 197 | "--remote-debugging-pipe", |
| 198 | "--no-first-run", |
| 199 | "--no-default-browser-check", |
| 200 | "--disable-gpu", |
| 201 | "--hide-scrollbars", |
| 202 | "--mute-audio", |
| 203 | "--block-new-web-contents", |
| 204 | `--proxy-server=socks5://127.0.0.1:${proxy.port}`, |
| 205 | // Loopback would otherwise skip the proxy. |
| 206 | "--proxy-bypass-list=<-loopback>", |
| 207 | // WebRTC would otherwise send UDP, which no proxy carries. |
| 208 | "--force-webrtc-ip-handling-policy=disable_non_proxied_udp", |
| 209 | ...(input.noSandbox ? ["--no-sandbox"] : []), |
| 210 | `--user-data-dir=${input.profileDirectory}`, |
| 211 | "about:blank", |
| 212 | ], |
| 213 | { |
| 214 | stdin: "ignore", |
| 215 | stdout: "ignore", |
| 216 | stderr: "pipe", |
| 217 | forceKillAfter: "2 seconds", |
| 218 | additionalFds: { |
| 219 | fd3: { type: "input", stream: Stream.fromQueue(outgoing) }, |
| 220 | fd4: { type: "output" }, |
| 221 | }, |
| 222 | }, |
| 223 | ), |
| 224 | ) |
| 225 | .pipe( |
| 226 | Effect.mapError( |
| 227 | (cause) => |
| 228 | new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }), |
| 229 | ), |
| 230 | // Node throws some spawn errors synchronously, such as `spawn UNKNOWN` |
| 231 | // when policy blocks the executable; `mapError` cannot catch those. |
| 232 | Effect.catchDefect((cause) => |
| 233 | Effect.fail( |
| 234 | new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }), |
| 235 | ), |
| 236 | ), |
| 237 | ); |
| 238 | |
| 239 | let stderrTail = ""; |
| 240 | const stderrReader = yield* child.stderr.pipe( |
| 241 | Stream.decodeText(), |
| 242 | Stream.runForEach((text) => |
| 243 | Effect.sync(() => { |
| 244 | stderrTail = (stderrTail + text).slice(-2_048); |
| 245 | }), |
| 246 | ), |
| 247 | Effect.ignore, |
| 248 | Effect.forkScoped, |
| 249 | ); |
| 250 | |
| 251 | const pending = new Map< |
| 252 | number, |
| 253 | { readonly method: string; readonly reply: Deferred.Deferred<unknown, BrowserFailure> } |
| 254 | >(); |
| 255 | const pages = new Map<string, PageEvents>(); |
| 256 | let disconnected: BrowserFailure | undefined; |
| 257 | let nextId = 0; |
| 258 | |
| 259 | const post = (method: string, params: Record<string, unknown>, sessionId?: string) => |
| 260 | Queue.offer( |
| 261 | outgoing, |
| 262 | new TextEncoder().encode( |
| 263 | `${encodeCdpCommand({ id: ++nextId, method, params, sessionId })}\0`, |
| 264 | ), |
| 265 | ).pipe(Effect.asVoid); |
| 266 | |
| 267 | // Queue shared body bytes between JSON halves to avoid copies across capture widths. |
| 268 | const fulfillPage = (sessionId: string, requestId: string, body: Uint8Array) => |
| 269 | Queue.offerAll(outgoing, [ |
| 270 | textEncoder.encode( |
| 271 | `{"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":"`, |
| 272 | ), |
| 273 | body, |
| 274 | textEncoder.encode('"}}\0'), |
| 275 | ]).pipe(Effect.asVoid); |
| 276 | |
| 277 | // Incoming messages share the session span; frame acknowledgements are frequent. |
| 278 | const receive = Effect.fnUntraced(function* (raw: string) { |
| 279 | const message = Option.getOrUndefined(decodeCdpMessage(raw)); |
| 280 | if (message?.id !== undefined) { |
| 281 | const waiter = pending.get(message.id); |
| 282 | pending.delete(message.id); |
| 283 | if (!waiter) return yield* Effect.void; |
| 284 | return yield* message.error |
| 285 | ? Deferred.fail( |
| 286 | waiter.reply, |
| 287 | new HtmlRenderBrowserError({ |
| 288 | reason: `${waiter.method} failed`, |
| 289 | cause: message.error.message, |
| 290 | }), |
| 291 | ) |
| 292 | : Deferred.succeed(waiter.reply, message.result); |
| 293 | } |
| 294 | const sessionId = message?.sessionId; |
| 295 | const page = sessionId === undefined ? undefined : pages.get(sessionId); |
| 296 | if (sessionId === undefined || !page || !message?.method) return yield* Effect.void; |
| 297 | if (message.method === "Page.loadEventFired") { |
| 298 | return yield* page.loaded ? Deferred.succeed(page.loaded, undefined) : Effect.void; |
| 299 | } |
| 300 | if (message.method === "Fetch.requestPaused") { |
| 301 | const paused = Option.getOrUndefined(decodeRequestPaused(message.params)); |
| 302 | if (!paused) return yield* Effect.void; |
| 303 | const body = page.body; |
| 304 | const url = paused.request.url.split("#", 1)[0]!; |
| 305 | if (url === PAGE_URL && body !== undefined) { |
| 306 | return yield* fulfillPage(sessionId, paused.requestId, body); |
| 307 | } |
| 308 | // Subframes may show other sites covered by Local Network Access; the main frame stays on T3's page. |
| 309 | const otherSiteFrame = |
| 310 | paused.resourceType === "Document" && |
| 311 | paused.frameId !== page.mainFrameId && |
| 312 | !url.startsWith(`${PAGE_ORIGIN}/`); |
| 313 | return yield* otherSiteFrame |
| 314 | ? post("Fetch.continueRequest", { requestId: paused.requestId }, sessionId) |
| 315 | : post( |
| 316 | "Fetch.failRequest", |
| 317 | { requestId: paused.requestId, errorReason: "AccessDenied" }, |
| 318 | sessionId, |
| 319 | ); |
| 320 | } |
| 321 | const consoleMessage = consoleMessageFromEvent(message.method, message.params); |
| 322 | if (!consoleMessage) return yield* Effect.void; |
| 323 | if (page.consoleMessages.length >= MAX_CONSOLE_MESSAGES) { |
| 324 | page.omittedConsoleMessages += 1; |
| 325 | return yield* Effect.void; |
| 326 | } |
| 327 | page.consoleMessages.push({ |
| 328 | level: consoleMessage.level, |
| 329 | text: clipConsoleText(consoleMessage.text.replaceAll(PAGE_URL, PAGE_NAME)), |
| 330 | }); |
| 331 | return yield* Effect.void; |
| 332 | }); |
| 333 | |
| 334 | // Startup aborts close the pipe; let stderr drain to recover the reason. |
| 335 | const disconnect = Effect.gen(function* () { |
| 336 | yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore); |
| 337 | const exit = yield* child.exitCode.pipe( |
| 338 | Effect.map((code): { exitCode?: number; signal?: string; cause?: unknown } => ({ |
| 339 | exitCode: code, |
| 340 | })), |
| 341 | Effect.catch((error) => { |
| 342 | const signal = EXIT_SIGNAL.exec(String(error.cause))?.[1]; |
| 343 | return Effect.succeed(signal === undefined ? { cause: error } : { signal, cause: error }); |
| 344 | }), |
| 345 | Effect.timeoutOption("1 second"), |
| 346 | ); |
| 347 | const error = new HtmlRenderBrowserError({ |
| 348 | reason: "the browser exited unexpectedly", |
| 349 | output: stderrTail, |
| 350 | ...Option.getOrElse(exit, () => ({})), |
| 351 | }); |
| 352 | disconnected = error; |
| 353 | const waiters = [...pending.values()]; |
| 354 | pending.clear(); |
| 355 | yield* Effect.forEach(waiters, ({ reply }) => Deferred.fail(reply, error), { discard: true }); |
| 356 | yield* Effect.forEach( |
| 357 | pages.values(), |
| 358 | (page) => (page.loaded ? Deferred.fail(page.loaded, error) : Effect.void), |
| 359 | { discard: true }, |
| 360 | ); |
| 361 | }); |
| 362 | |
| 363 | // Chunks may split messages; screenshot replies span many chunks. |
| 364 | let partial: Array<string> = []; |
| 365 | yield* child.getOutputFd(4).pipe( |
| 366 | Stream.decodeText(), |
| 367 | Stream.runForEach((text) => { |
| 368 | const complete: Array<string> = []; |
| 369 | let start = 0; |
| 370 | for (let end = text.indexOf("\0"); end !== -1; end = text.indexOf("\0", start)) { |
| 371 | partial.push(text.slice(start, end)); |
| 372 | complete.push(partial.join("")); |
| 373 | partial = []; |
| 374 | start = end + 1; |
| 375 | } |
| 376 | if (start < text.length) partial.push(text.slice(start)); |
| 377 | return Effect.forEach(complete, receive, { discard: true }); |
| 378 | }), |
| 379 | Effect.ignore, |
| 380 | Effect.andThen(disconnect), |
| 381 | Effect.forkScoped, |
| 382 | ); |
| 383 | |
| 384 | // Signals can miss a confined browser (AppArmor in LXC), so ask it to quit first. |
| 385 | // Runs before the spawn's release, which still signals a browser that stays up. |
| 386 | yield* Effect.addFinalizer(() => |
| 387 | disconnected |
| 388 | ? Effect.void |
| 389 | : post("Browser.close", {}).pipe( |
| 390 | Effect.andThen(child.exitCode), |
| 391 | Effect.timeout("2 seconds"), |
| 392 | Effect.ignore, |
| 393 | ), |
| 394 | ); |
| 395 | |
| 396 | const send = Effect.fn("headlessChrome.send")(function* <A>( |
| 397 | method: string, |
| 398 | params: Record<string, unknown>, |
| 399 | result: Schema.Decoder<A>, |
| 400 | sessionId?: string, |
| 401 | ) { |
| 402 | if (disconnected) return yield* disconnected; |
| 403 | const id = ++nextId; |
| 404 | const reply = yield* Deferred.make<unknown, BrowserFailure>(); |
| 405 | pending.set(id, { method, reply }); |
| 406 | const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) }); |
| 407 | yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`)); |
| 408 | return yield* Deferred.await(reply).pipe( |
| 409 | Effect.flatMap(Schema.decodeUnknownEffect(result)), |
| 410 | Effect.mapError((error) => |
| 411 | error._tag === "HtmlRenderBrowserError" |
| 412 | ? error |
| 413 | : new HtmlRenderBrowserError({ |
| 414 | reason: `${method} returned an unexpected result`, |
| 415 | cause: error, |
| 416 | }), |
| 417 | ), |
| 418 | ); |
| 419 | }); |
| 420 | |
| 421 | // Chrome's default context can stall Fetch interception during navigation. |
| 422 | const { browserContextId } = yield* send( |
| 423 | "Target.createBrowserContext", |
| 424 | {}, |
| 425 | Schema.Struct({ browserContextId: Schema.String }), |
| 426 | ); |
| 427 | |
| 428 | const openPage = Effect.fnUntraced(function* (width: number, appearance: ThemeAppearance) { |
| 429 | const { targetId } = yield* send( |
| 430 | "Target.createTarget", |
| 431 | { url: "about:blank", browserContextId }, |
| 432 | Schema.Struct({ targetId: Schema.String }), |
| 433 | ); |
| 434 | const { sessionId } = yield* send( |
| 435 | "Target.attachToTarget", |
| 436 | { targetId, flatten: true }, |
| 437 | Schema.Struct({ sessionId: Schema.String }), |
| 438 | ); |
| 439 | const events: PageEvents = { |
| 440 | // A page target's id is its main frame's id. |
| 441 | mainFrameId: targetId, |
| 442 | body: undefined, |
| 443 | loaded: undefined, |
| 444 | consoleMessages: [], |
| 445 | omittedConsoleMessages: 0, |
| 446 | }; |
| 447 | pages.set(sessionId, events); |
| 448 | yield* send("Page.enable", {}, Ignored, sessionId); |
| 449 | yield* send("Runtime.enable", {}, Ignored, sessionId); |
| 450 | yield* send("Log.enable", {}, Ignored, sessionId); |
| 451 | yield* send( |
| 452 | "Emulation.setEmulatedMedia", |
| 453 | { features: [{ name: "prefers-color-scheme", value: appearance }] }, |
| 454 | Ignored, |
| 455 | sessionId, |
| 456 | ); |
| 457 | // Previews have no use for WebRTC, whose ICE servers can make the browser |
| 458 | // resolve names outside the proxy. Runs before page scripts in every frame. |
| 459 | yield* send( |
| 460 | "Page.addScriptToEvaluateOnNewDocument", |
| 461 | { |
| 462 | source: "delete window.RTCPeerConnection; delete window.webkitRTCPeerConnection;", |
| 463 | runImmediately: true, |
| 464 | }, |
| 465 | Ignored, |
| 466 | sessionId, |
| 467 | ); |
| 468 | // Intercept T3's page and all document navigations to keep the main frame on it. |
| 469 | yield* send( |
| 470 | "Fetch.enable", |
| 471 | { |
| 472 | patterns: [ |
| 473 | { urlPattern: `${PAGE_ORIGIN}/*` }, |
| 474 | { urlPattern: "*", resourceType: "Document" }, |
| 475 | ], |
| 476 | }, |
| 477 | Ignored, |
| 478 | sessionId, |
| 479 | ); |
| 480 | yield* send( |
| 481 | "Emulation.setDeviceMetricsOverride", |
| 482 | { width, height: VIEWPORT_HEIGHT, deviceScaleFactor: 1, mobile: false }, |
| 483 | Ignored, |
| 484 | sessionId, |
| 485 | ); |
| 486 | |
| 487 | const load = Effect.fnUntraced(function* (body: Uint8Array, urlFragment: string) { |
| 488 | const loaded = yield* Deferred.make<void, BrowserFailure>(); |
| 489 | events.body = body; |
| 490 | events.loaded = loaded; |
| 491 | const navigation = yield* send( |
| 492 | "Page.navigate", |
| 493 | { url: `${PAGE_URL}${urlFragment}` }, |
| 494 | Navigation, |
| 495 | sessionId, |
| 496 | ); |
| 497 | if (navigation.errorText) { |
| 498 | return yield* new HtmlRenderBrowserError({ reason: "the page could not be opened" }); |
| 499 | } |
| 500 | yield* Deferred.await(loaded); |
| 501 | yield* send( |
| 502 | "Runtime.evaluate", |
| 503 | { expression: SETTLE_EXPRESSION, awaitPromise: true }, |
| 504 | Ignored, |
| 505 | sessionId, |
| 506 | ); |
| 507 | const measured = yield* send( |
| 508 | "Runtime.evaluate", |
| 509 | { expression: MEASURE_EXPRESSION, returnByValue: true }, |
| 510 | Measured, |
| 511 | sessionId, |
| 512 | ); |
| 513 | return Math.max(0, Math.ceil(measured.result.value)); |
| 514 | }); |
| 515 | |
| 516 | const screenshot = (height: number) => |
| 517 | send( |
| 518 | "Page.captureScreenshot", |
| 519 | { |
| 520 | format: "png", |
| 521 | captureBeyondViewport: true, |
| 522 | clip: { x: 0, y: 0, width, height, scale: 1 }, |
| 523 | }, |
| 524 | Schema.Struct({ data: Schema.String }), |
| 525 | sessionId, |
| 526 | ).pipe(Effect.map(({ data }) => data)); |
| 527 | |
| 528 | const consoleMessages = (): ReadonlyArray<ConsoleMessage> => |
| 529 | events.omittedConsoleMessages === 0 |
| 530 | ? [...events.consoleMessages] |
| 531 | : [ |
| 532 | ...events.consoleMessages, |
| 533 | { |
| 534 | level: "warning", |
| 535 | text: `${events.omittedConsoleMessages} more console messages were omitted.`, |
| 536 | }, |
| 537 | ]; |
| 538 | |
| 539 | const close = send("Target.closeTarget", { targetId }, Ignored).pipe( |
| 540 | Effect.ensuring(Effect.sync(() => pages.delete(sessionId))), |
| 541 | Effect.ignore, |
| 542 | ); |
| 543 | |
| 544 | return { load, screenshot, consoleMessages, close }; |
| 545 | }); |
| 546 | |
| 547 | // Each capture opens one page per browser, so this note belongs to that page alone. |
| 548 | const fakeIpNote = (): ReadonlyArray<ConsoleMessage> => |
| 549 | [...proxy.fakeIpHosts].map(([host, address]) => ({ |
| 550 | level: "warning", |
| 551 | text: clipConsoleText( |
| 552 | `DNS returned blocked 198.18.0.0/15 addresses, which may come from Clash or Mihomo fake-IP DNS. Inline the resource, add its host to fake-ip-filter, or switch DNS to redir-host. Affected host: ${host} (${address})`, |
| 553 | ), |
| 554 | })); |
| 555 | |
| 556 | return { openPage, fakeIpNote }; |
| 557 | }); |
| 558 | |
| 559 | const scratchDirectory = Effect.gen(function* () { |
| 560 | const fileSystem = yield* FileSystem.FileSystem; |
| 561 | return yield* Effect.acquireRelease( |
| 562 | fileSystem.makeTempDirectory({ prefix: "t3-html-preview-" }), |
| 563 | (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore), |
| 564 | ).pipe( |
| 565 | Effect.mapError( |
| 566 | (cause) => |
| 567 | new HtmlRenderBrowserError({ reason: "a temporary directory could not be created", cause }), |
| 568 | ), |
| 569 | ); |
| 570 | }); |
| 571 | |
| 572 | export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreenshot")( |
| 573 | function* (input: { |
| 574 | readonly executable: string; |
| 575 | readonly noSandbox: boolean; |
| 576 | readonly html: string; |
| 577 | readonly width: number; |
| 578 | readonly urlFragment: string; |
| 579 | readonly appearance: ThemeAppearance; |
| 580 | }) { |
| 581 | const path = yield* Path.Path; |
| 582 | const directory = yield* scratchDirectory; |
| 583 | const browser = yield* launchBrowser({ |
| 584 | executable: input.executable, |
| 585 | noSandbox: input.noSandbox, |
| 586 | profileDirectory: path.join(directory, "profile"), |
| 587 | }); |
| 588 | const page = yield* browser.openPage(input.width, input.appearance); |
| 589 | const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment); |
| 590 | const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT)); |
| 591 | const png = yield* page.screenshot(capturedHeight); |
| 592 | return { |
| 593 | png, |
| 594 | contentHeight, |
| 595 | capturedHeight, |
| 596 | consoleMessages: [...page.consoleMessages(), ...browser.fakeIpNote()], |
| 597 | }; |
| 598 | }, |
| 599 | Effect.scoped, |
| 600 | Effect.timeoutOrElse({ |
| 601 | duration: CAPTURE_TIMEOUT, |
| 602 | orElse: () => |
| 603 | Effect.fail( |
| 604 | new HtmlRenderBrowserError({ |
| 605 | reason: `the page did not finish loading within ${CAPTURE_TIMEOUT}`, |
| 606 | }), |
| 607 | ), |
| 608 | }), |
| 609 | ); |
| 610 | |
| 611 | /** Fresh load per width, since pages may lay out only at load. */ |
| 612 | export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: { |
| 613 | readonly executable: string; |
| 614 | readonly noSandbox: boolean; |
| 615 | readonly html: string; |
| 616 | readonly widths: ReadonlyArray<number>; |
| 617 | readonly urlFragment: string; |
| 618 | }) { |
| 619 | const path = yield* Path.Path; |
| 620 | const directory = yield* scratchDirectory; |
| 621 | const browser = yield* launchBrowser({ |
| 622 | executable: input.executable, |
| 623 | noSandbox: input.noSandbox, |
| 624 | profileDirectory: path.join(directory, "profile"), |
| 625 | }); |
| 626 | const body = pageBody(input.html); |
| 627 | return yield* Effect.forEach( |
| 628 | input.widths, |
| 629 | (width) => |
| 630 | browser.openPage(width, "dark").pipe( |
| 631 | Effect.flatMap((page) => |
| 632 | page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)), |
| 633 | ), |
| 634 | Effect.map((height) => [width, height] as const), |
| 635 | ), |
| 636 | { concurrency: MEASURE_CONCURRENCY }, |
| 637 | ); |
| 638 | }, Effect.scoped); |