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

ServerBrowserPage.ts

661 lines24.1 KB

1// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off - Playwright callbacks run outside the Effect runtime.
2​
3import {
4 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
5 type PreviewAutomationClickInput,
6 type PreviewAutomationConsoleEntry,
7 type PreviewAutomationDragInput,
8 type PreviewAutomationEvaluateInput,
9 type PreviewAutomationHoverInput,
10 type PreviewAutomationNetworkEntry,
11 type PreviewAutomationPressInput,
12 type PreviewAutomationScrollInput,
13 type PreviewAutomationSelectInput,
14 type PreviewAutomationSelectResult,
15 type PreviewAutomationSnapshot,
16 type PreviewAutomationTypeInput,
17 type PreviewAutomationUploadInput,
18 type PreviewAutomationWaitForInput,
19} from "@t3tools/contracts";
20import { constVoid } from "effect/Function";
21import type { CDPSession, Locator, Page } from "playwright-core";
22import * as NodeCrypto from "node:crypto";
23import { BrowserControlInterrupted } from "./SessionControl.ts";
24​
25const MAX_EVALUATION_BYTES = 64_000;
26const MAX_VISIBLE_TEXT_LENGTH = 20_000;
27const MAX_SCREENSHOT_WIDTH = 1280;
28const WAIT_POLL_MS = 100;
29export const DIAGNOSTIC_BUFFER_LIMIT = 200;
30​
31export class ServerBrowserOperationError extends Error {
32 readonly tag: string;
33 readonly detail: unknown;
34​
35 constructor(tag: string, message: string, detail?: unknown) {
36 super(message);
37 this.tag = tag;
38 this.detail = detail;
39 }
41​
42export const toOperationError = (cause: unknown): ServerBrowserOperationError => {
43 if (cause instanceof BrowserControlInterrupted)
44 return new ServerBrowserOperationError(
45 "PreviewAutomationControlInterruptedError",
46 cause.message,
47 cause.reason,
48 );
49 if (cause instanceof ServerBrowserOperationError) return cause;
50 const message = cause instanceof Error ? cause.message : String(cause);
51 const firstLine = message.split("\n")[0] ?? message;
52 if (cause instanceof Error && cause.name === "TimeoutError") {
53 return new ServerBrowserOperationError("PreviewAutomationTimeoutError", firstLine);
54 }
55 if (
56 /while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message)
57 ) {
58 return new ServerBrowserOperationError("PreviewAutomationInvalidSelectorError", firstLine);
59 }
60 if (/not an <input>|not editable|not an editable/i.test(message)) {
61 return new ServerBrowserOperationError("PreviewAutomationTargetNotEditableError", firstLine);
62 }
63 return new ServerBrowserOperationError("PreviewAutomationExecutionError", firstLine);
64};
65​
66const DEFAULT_TIMEOUT_MS = 15_000;
67​
68const pageRefs = new WeakMap<Page, { generation: string; refs: Map<string, string> }>();
69// A compact runtime namespace prevents old refs from aliasing after a server restart.
70const refNamespace = NodeCrypto.randomUUID().slice(0, 8);
71let snapshotSequence = 0;
72const nextRefGeneration = () => `${refNamespace}-${(++snapshotSequence).toString(36)}`;
73​
74/** A takeover revokes previously issued refs even when the document stays unchanged. */
75export const invalidateRefs = (page: Page) => {
76 const state = pageRefs.get(page);
77 if (state) {
78 state.generation = nextRefGeneration();
79 state.refs.clear();
80 }
81};
82​
83const refsFor = (page: Page) => {
84 let state = pageRefs.get(page);
85 if (!state) {
86 state = { generation: nextRefGeneration(), refs: new Map<string, string>() };
87 pageRefs.set(page, state);
88 page.on("framenavigated", () => invalidateRefs(page));
89 page.on("framedetached", () => invalidateRefs(page));
90 }
91 return state;
92};
93​
94const targetLocator = (
95 page: Page,
96 input: { readonly locator?: string | undefined; readonly selector?: string | undefined },
97): Locator | null => {
98 const selector = input.locator ?? input.selector;
99 if (selector === undefined) return null;
100 // Ignore quoted/escaped CSS values when looking for a selector-engine boundary.
101 const engines = selector.replace(
102 /\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g,
103 " ",
104 );
105 if (/(?:^|>>)\s*\*?aria-ref\s*=/.test(engines)) {
106 const ref = /^\s*aria-ref\s*=\s*(\S+)\s*$/.exec(selector)?.[1];
107 const nativeRef = ref === undefined ? undefined : pageRefs.get(page)?.refs.get(ref);
108 if (nativeRef === undefined) {
109 throw new ServerBrowserOperationError(
110 "PreviewAutomationInvalidSelectorError",
111 "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.",
112 { staleRef: true },
113 );
114 }
115 return page.locator(`aria-ref=${nativeRef}`);
116 }
117 // Playwright's strict locators reject ambiguous controls rather than acting on row one.
118 return page.locator(selector);
119};
120​
121export type PointerReporter = (
122 point: { readonly x: number; readonly y: number },
123 phase: "move" | "click",
124) => Promise<void>;
125const noPointer: PointerReporter = async () => {};
126​
127const targetPoint = async (
128 page: Page,
129 locator: Locator | null,
130 input: { readonly x?: number | undefined; readonly y?: number | undefined },
131 timeout: number,
132) => {
133 if (locator === null) return { x: input.x ?? 0, y: input.y ?? 0 };
134 await locator.scrollIntoViewIfNeeded({ timeout });
135 const box = await locator.boundingBox({ timeout });
136 if (box) return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
137 const viewport = page.viewportSize();
138 return { x: (viewport?.width ?? 0) / 2, y: (viewport?.height ?? 0) / 2 };
139};
140​
141const SNAPSHOT_SCRIPT = `(() => {
142 return {
143 url: location.href,
144 title: document.title,
145 loading: document.readyState !== "complete",
146 visibleText: (document.body?.innerText || "").slice(0, ${MAX_VISIBLE_TEXT_LENGTH}),
147 interactiveElements: [],
148 };
149})()`;
150​
151// Scaled captures repaint live screencasts, so callers pause them. Clips use document offsets.
152export const captureViewport = async (
153 page: Page,
154 cdp: CDPSession,
155 options: { readonly format: "png" | "jpeg"; readonly quality?: number; readonly scale: number },
156) => {
157 let clip;
158 if (options.scale < 1) {
159 const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
160 const { cssVisualViewport } = await cdp.send("Page.getLayoutMetrics");
161 clip = {
162 x: cssVisualViewport.pageX,
163 y: cssVisualViewport.pageY,
164 ...viewport,
165 scale: options.scale,
166 };
167 }
168 const { data } = await cdp.send("Page.captureScreenshot", {
169 format: options.format,
170 ...(options.quality === undefined ? {} : { quality: options.quality }),
171 ...(clip ? { clip } : {}),
172 });
173 return data;
174};
175​
176export const snapshot = async (input: {
177 readonly page: Page;
178 readonly cdp: CDPSession;
179 readonly renderScale: number;
180 readonly consoleEntries: ReadonlyArray<PreviewAutomationConsoleEntry>;
181 readonly networkEntries: ReadonlyArray<PreviewAutomationNetworkEntry>;
182 readonly actionTimeline: PreviewAutomationSnapshot["actionTimeline"];
183}): Promise<PreviewAutomationSnapshot> => {
184 const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 };
185 const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * input.renderScale));
186 const state = refsFor(input.page);
187 invalidateRefs(input.page);
188 const generation = state.generation;
189 const [page, tree, data] = await Promise.all([
190 input.page.evaluate(SNAPSHOT_SCRIPT) as Promise<
191 Pick<
192 PreviewAutomationSnapshot,
193 "url" | "title" | "loading" | "visibleText" | "interactiveElements"
194 >
195 >,
196 input.page.ariaSnapshot({ mode: "ai", boxes: true, timeout: DEFAULT_TIMEOUT_MS }),
197 captureViewport(input.page, input.cdp, { format: "png", scale }),
198 ]);
199 if (state.generation !== generation) {
200 throw new ServerBrowserOperationError(
201 "PreviewAutomationExecutionError",
202 "The page changed while capturing its snapshot. Take another snapshot.",
203 );
204 }
205 const accessibilityTree = tree
206 .slice(0, MAX_VISIBLE_TEXT_LENGTH)
207 .replace(/\[ref=((?:f\d+)?e\d+)\]/g, (_match, nativeRef: string) => {
208 const ref = `t3-${generation}-${nativeRef}`;
209 state.refs.set(ref, nativeRef);
210 return `[ref=${ref}]`;
211 });
212 return {
213 ...page,
214 accessibilityTree,
215 consoleEntries: [...input.consoleEntries],
216 networkEntries: [...input.networkEntries],
217 actionTimeline: [...input.actionTimeline],
218 screenshot: {
219 mimeType: "image/png",
220 data,
221 width: Math.round(viewport.width * input.renderScale * scale),
222 height: Math.round(viewport.height * input.renderScale * scale),
223 },
224 };
225};
226​
227/**
228 * A click whose handler opens a dialog does not finish until the dialog is
229 * resolved, so it returns as soon as the dialog opens; status then reports it.
230 */
231export const click = async (
232 page: Page,
233 input: PreviewAutomationClickInput,
234 pointer: PointerReporter = noPointer,
235): Promise<{ readonly x: number; readonly y: number }> => {
236 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
237 const locator = targetLocator(page, input);
238 const point = await targetPoint(page, locator, input, timeout);
239 await pointer(point, "click");
240 const options = { button: input.button ?? "left", clickCount: input.clickCount ?? 1 } as const;
241 const clicked =
242 locator === null
243 ? page.mouse.click(point.x, point.y, options)
244 : locator.click({ ...options, timeout });
245 let onDialog = constVoid;
246 const dialogOpened = new Promise<"dialog">((resolve) => {
247 onDialog = () => resolve("dialog");
248 page.once("dialog", onDialog);
249 });
250 try {
251 if ((await Promise.race([clicked, dialogOpened])) === "dialog") void clicked.catch(constVoid);
252 } finally {
253 page.off("dialog", onDialog);
254 }
255 return point;
256};
257​
258export const type = async (page: Page, input: PreviewAutomationTypeInput) => {
259 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
260 const locator = targetLocator(page, input);
261 if (locator !== null && input.clear) {
262 await locator.fill(input.text, { timeout });
263 return;
264 }
265 // A shadow host also matches :focus; use its innermost focused descendant.
266 const target = locator ?? page.locator("*:focus").last();
267 const focused =
268 (locator !== null || (await target.count()) > 0) &&
269 (await target.evaluate(
270 (element) => {
271 // Like the desktop host: an enabled text control or contenteditable
272 // that actually takes focus. Anything else would swallow the text or
273 // send it to whichever field had focus before.
274 const control = element as unknown as {
275 readonly type?: string;
276 readonly disabled?: boolean;
277 readonly readOnly?: boolean;
278 readonly isContentEditable?: boolean;
279 readonly focus?: () => void;
280 };
281 const nonText = [
282 "button",
283 "checkbox",
284 "color",
285 "file",
286 "hidden",
287 "image",
288 "radio",
289 "range",
290 "reset",
291 "submit",
292 ];
293 const textControl =
294 element.tagName === "TEXTAREA" ||
295 (element.tagName === "INPUT" && !nonText.includes(control.type ?? "text"));
296 if (!(textControl || control.isContentEditable) || control.disabled || control.readOnly) {
297 return false;
298 }
299 control.focus?.();
300 const root = element.getRootNode() as { readonly activeElement?: typeof element | null };
301 const active = root.activeElement;
302 return active != null && (active === element || element.contains(active));
303 },
304 undefined,
305 { timeout },
306 ));
307 if (focused !== true) {
308 throw new ServerBrowserOperationError(
309 "PreviewAutomationTargetNotEditableError",
310 "The target is not an enabled text field, so no text was typed.",
311 );
312 }
313 if (input.clear) {
314 await page.keyboard.press("ControlOrMeta+A");
315 await page.keyboard.press("Delete");
316 }
317 await page.keyboard.insertText(input.text);
318};
319​
320export const hover = async (
321 page: Page,
322 input: PreviewAutomationHoverInput,
323 pointer: PointerReporter = noPointer,
324) => {
325 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
326 const locator = targetLocator(page, input);
327 await pointer(await targetPoint(page, locator, input, timeout), "move");
328 if (locator === null) {
329 await page.mouse.move(input.x ?? 0, input.y ?? 0);
330 return;
331 }
332 await locator.hover({ timeout });
333};
334​
335export const select = async (
336 page: Page,
337 input: PreviewAutomationSelectInput,
338): Promise<PreviewAutomationSelectResult> => {
339 const locator = targetLocator(page, input)!;
340 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
341 const options = await locator.evaluate(
342 (element) =>
343 element.tagName === "SELECT"
344 ? Array.from(
345 (element as unknown as { options: ArrayLike<{ value: string; label: string }> })
346 .options,
347 ({ value, label }) => ({ value, label: label.trim() }),
348 )
349 : null,
350 undefined,
351 { timeout },
352 );
353 const values =
354 options &&
355 input.values.map(
356 (entry) =>
357 (
358 options.find((option) => option.value === entry) ??
359 options.find((option) => option.label === entry.trim())
360 )?.value ?? entry,
361 );
362 if (values === null)
363 throw new ServerBrowserOperationError(
364 "PreviewAutomationTargetNotEditableError",
365 "This element is not a <select>. Click a custom dropdown, then click its option.",
366 );
367 return { selected: await locator.selectOption(values, { timeout }) };
368};
369​
370export const drag = async (
371 page: Page,
372 input: PreviewAutomationDragInput,
373 pointer: PointerReporter = noPointer,
374) => {
375 const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
376 const source = targetLocator(page, { locator: input.source })!;
377 const target = targetLocator(page, { locator: input.target })!;
378 await pointer(await targetPoint(page, source, {}, timeout), "move");
379 // Observe the drag's outcome as it starts: a rejection nobody handles while the cursor
380 // moves exits the server.
381 const dragFailure = source.dragTo(target, { timeout }).then(
382 () => null,
383 (error: unknown) => ({ error }),
384 );
385 const end = await target.boundingBox({ timeout }).catch(() => null);
386 if (end) await pointer({ x: end.x + end.width / 2, y: end.y + end.height / 2 }, "move");
387 const failure = await dragFailure;
388 if (failure) throw failure.error;
389};
390​
391export const setInputFiles = async (page: Page, input: PreviewAutomationUploadInput) => {
392 const locator = targetLocator(page, input);
393 if (locator === null) return false;
394 await locator.setInputFiles([...input.paths], { timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS });
395 return true;
396};
397​
398export const press = async (page: Page, input: PreviewAutomationPressInput) => {
399 await page.keyboard.press([...(input.modifiers ?? []), input.key].join("+"));
400};
401​
402export const scroll = async (page: Page, input: PreviewAutomationScrollInput) => {
403 const delta = [input.deltaX ?? 0, input.deltaY ?? 0] as const;
404 const locator = targetLocator(page, input);
405 if (locator === null) {
406 // Page-side code is passed as source: the server compiles without DOM types.
407 await page.evaluate(`scrollBy(${delta[0]}, ${delta[1]})`);
408 return;
409 }
410 await locator.evaluate((element, [x, y]) => element.scrollBy(x, y), delta);
411};
412​
413/**
414 * Runs an agent's expression, bounded by its request's deadline. Past it, the
415 * page's script is terminated and the call fails, so the tab's control queue
416 * frees for the next request instead of waiting on the script.
417 */
418export const evaluate = async (
419 cdp: CDPSession,
420 input: PreviewAutomationEvaluateInput,
421 timeoutMs: number,
422) => {
423 let timer: ReturnType<typeof setTimeout> | undefined;
424 const expired = new Promise<never>((_, reject) => {
425 timer = setTimeout(() => {
426 // Stops a busy script; an awaited promise is abandoned and settles unread.
427 void cdp.send("Runtime.terminateExecution").catch(constVoid);
428 reject(
429 new ServerBrowserOperationError(
430 "PreviewAutomationTimeoutError",
431 `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,
432 ),
433 );
434 }, timeoutMs);
435 });
436 const evaluation = cdp.send("Runtime.evaluate", {
437 expression: input.expression,
438 awaitPromise: input.awaitPromise ?? true,
439 returnByValue: input.returnByValue ?? true,
440 });
441 void evaluation.catch(constVoid);
442 const result = await Promise.race([evaluation, expired]).finally(() => clearTimeout(timer));
443 if (result.exceptionDetails) {
444 throw new ServerBrowserOperationError(
445 "PreviewAutomationExecutionError",
446 result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,
447 );
448 }
449 const value =
450 "value" in result.result ? result.result.value : (result.result.description ?? null);
451 const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");
452 if (actualBytes > MAX_EVALUATION_BYTES) {
453 throw new ServerBrowserOperationError(
454 "PreviewAutomationResultTooLargeError",
455 `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,
456 { maximumBytes: MAX_EVALUATION_BYTES },
457 );
458 }
459 return value;
460};
461​
462export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) => {
463 const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
464 const deadline = Date.now() + timeoutMs;
465 const locator = targetLocator(page, input);
466 const { text, urlIncludes } = input;
467 const checks: Array<() => Promise<boolean>> = [];
468 if (locator !== null) checks.push(async () => (await locator.count()) > 0);
469 if (text !== undefined) {
470 // A navigation can destroy the context mid-check; that counts as not yet.
471 checks.push(() =>
472 page
473 .evaluate(`(document.body?.innerText ?? "").includes(${JSON.stringify(text)})`)
474 .then((found) => found === true)
475 .catch(() => false),
476 );
477 }
478 if (urlIncludes !== undefined) checks.push(async () => page.url().includes(urlIncludes));
479 for (;;) {
480 const results = await Promise.all(checks.map((check) => check()));
481 if (results.every(Boolean)) return;
482 if (Date.now() >= deadline) {
483 throw new ServerBrowserOperationError(
484 "PreviewAutomationTimeoutError",
485 `Waited ${timeoutMs}ms without every condition holding.`,
486 );
487 }
488 await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS));
489 }
490};
491​
492const NET_ERROR_CODES: Readonly<Record<string, number>> = {
493 ERR_FAILED: -2,
494 ERR_TIMED_OUT: -7,
495 ERR_CONNECTION_CLOSED: -100,
496 ERR_CONNECTION_RESET: -101,
497 ERR_CONNECTION_REFUSED: -102,
498 ERR_NAME_NOT_RESOLVED: -105,
499 ERR_INTERNET_DISCONNECTED: -106,
500 ERR_ADDRESS_UNREACHABLE: -109,
501 ERR_CERT_AUTHORITY_INVALID: -202,
502 ERR_EMPTY_RESPONSE: -324,
503};
504​
505export const parseNetError = (errorText: string) => {
506 const description = /ERR_[A-Z_]+/.exec(errorText)?.[0] ?? errorText;
507 return { description, code: NET_ERROR_CODES[description] ?? -2 };
508};
509​
510export const RECORDING_ENCODER_SCRIPT = `(() => {
511 const canvas = document.createElement("canvas");
512 const context = canvas.getContext("2d");
513 const chunks = [];
514 let recorder = null;
515 let started = null;
516 let stopped = null;
517 let sizeBytes = 0;
518 let tooLarge = false;
519 let frame = null;
520 let cursor = null;
521 let ring = null;
522 const AGENT_CURSOR_PATH = new Path2D("M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z");
523 let ringTimer = null;
524 let scale = 1;
525 let offsetX = 0;
526 let offsetY = 0;
527 const paint = () => {
528 if (!frame) return;
529 const fit = Math.min(canvas.width / frame.width, canvas.height / frame.height);
530 const width = frame.width * fit;
531 const height = frame.height * fit;
532 offsetX = (canvas.width - width) / 2;
533 offsetY = (canvas.height - height) / 2;
534 if (width < canvas.width || height < canvas.height) {
535 context.fillStyle = "#000";
536 context.fillRect(0, 0, canvas.width, canvas.height);
537 }
538 context.drawImage(frame, offsetX, offsetY, width, height);
539 scale = (width / frame.width) * frame.cssScale;
540 if (ring) {
541 const age = (performance.now() - ring.at) / 400;
542 if (age < 1) {
543 context.beginPath();
544 context.arc(offsetX + ring.x * scale, offsetY + ring.y * scale, (8 + 18 * age) * scale, 0, Math.PI * 2);
545 context.strokeStyle = "rgba(59,130,246," + (0.9 * (1 - age)) + ")";
546 context.lineWidth = 3 * scale;
547 context.stroke();
548 }
549 }
550 if (cursor) {
551 // The agent cursor (lucide MousePointer2, as in the live panel), never the human arrow.
552 const s = 20 / 24 * scale;
553 context.save();
554 context.translate(offsetX + cursor.x * scale - 2 * scale, offsetY + cursor.y * scale - 2 * scale);
555 context.scale(s, s);
556 context.lineWidth = 2;
557 context.lineJoin = "round";
558 context.lineCap = "round";
559 context.fillStyle = "#fff";
560 context.strokeStyle = "#2563eb";
561 context.shadowColor = "rgba(0,0,0,0.25)";
562 context.shadowBlur = 2;
563 context.fill(AGENT_CURSOR_PATH);
564 context.shadowColor = "transparent";
565 context.stroke(AGENT_CURSOR_PATH);
566 context.restore();
567 }
568 };
569 window.__t3Recorder = {
570 async frame(base64, cssWidth) {
571 if (tooLarge) return false;
572 const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
573 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
574 if (tooLarge) { bitmap.close(); return false; }
575 if (!recorder) {
576 canvas.width = bitmap.width;
577 canvas.height = bitmap.height;
578 const mimeType = ["video/mp4;codecs=avc1.640033", "video/webm;codecs=vp9", "video/webm"].find((type) => MediaRecorder.isTypeSupported(type));
579 const bitsPerSecond = Math.min(50e6, Math.max(2.5e6, bitmap.width * bitmap.height * 30 * 0.05));
580 recorder = new MediaRecorder(canvas.captureStream(30), { mimeType, videoBitsPerSecond: bitsPerSecond });
581 started = new Promise((resolve, reject) => {
582 recorder.onstart = resolve;
583 recorder.onerror = (event) => reject(event.error);
584 });
585 stopped = new Promise((resolve) => { recorder.onstop = resolve; });
586 recorder.ondataavailable = (event) => {
587 if (tooLarge || event.data.size === 0) return;
588 sizeBytes += event.data.size;
589 if (sizeBytes > ${PROVIDER_SEND_TURN_MAX_FILE_BYTES}) {
590 tooLarge = true;
591 chunks.length = 0;
592 clearInterval(ringTimer);
593 frame?.close();
594 frame = null;
595 if (recorder.state !== "inactive") recorder.stop();
596 for (const track of recorder.stream.getTracks()) track.stop();
597 return;
598 }
599 chunks.push(event.data);
600 };
601 recorder.start(1000);
602 }
603 // Frame px per page CSS px, before fitting into the canvas.
604 bitmap.cssScale = bitmap.width / cssWidth;
605 frame?.close();
606 frame = bitmap;
607 paint();
608 await started;
609 return true;
610 },
611 cursor(x, y, click) {
612 if (tooLarge) return;
613 cursor = { x, y };
614 if (click) {
615 ring = { x, y, at: performance.now() };
616 clearInterval(ringTimer);
617 ringTimer = setInterval(() => {
618 paint();
619 if (performance.now() - ring.at > 400) { ring = null; clearInterval(ringTimer); paint(); }
620 }, 33);
621 }
622 paint();
623 },
624 async stop() {
625 if (!recorder) return { mimeType: null, count: 0, bytes: 0 };
626 if (recorder.state !== "inactive") {
627 // Consume the cached frame, then wait for the final paint to reach the
628 // capture stream. Animation ticks alone can stop before it is delivered.
629 const video = document.createElement("video");
630 video.muted = true;
631 video.srcObject = recorder.stream;
632 const nextFrame = () => Promise.race([
633 new Promise(resolve => video.requestVideoFrameCallback(resolve)),
634 stopped,
635 ]);
636 const initial = nextFrame();
637 void video.play().catch(() => {});
638 await initial;
639 if (recorder.state !== "inactive") {
640 const delivered = nextFrame();
641 recorder.stream.getVideoTracks()[0].requestFrame();
642 paint();
643 await delivered;
644 }
645 video.pause();
646 video.srcObject = null;
647 if (recorder.state !== "inactive") recorder.stop();
648 }
649 await stopped;
650 return { mimeType: recorder.mimeType, count: chunks.length, bytes: sizeBytes };
651 },
652 async chunk(index) {
653 const bytes = new Uint8Array(await chunks[index].arrayBuffer());
654 let binary = "";
655 for (let offset = 0; offset < bytes.length; offset += 0x8000) {
656 binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
657 }
658 return btoa(binary);
659 },
660 };
661})()`;