@howaboua/pi-browser 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +22 -0
  3. package/README.md +47 -0
  4. package/biome.json +31 -0
  5. package/changelog.ts +337 -0
  6. package/dist/index.d.ts +3 -0
  7. package/dist/index.js +82 -0
  8. package/dist/remote-worker.d.ts +2 -0
  9. package/dist/remote-worker.js +3005 -0
  10. package/dist/src/browser/artifacts.d.ts +13 -0
  11. package/dist/src/browser/artifacts.js +133 -0
  12. package/dist/src/browser/bounds.d.ts +4 -0
  13. package/dist/src/browser/bounds.js +129 -0
  14. package/dist/src/browser/config.d.ts +11 -0
  15. package/dist/src/browser/config.js +106 -0
  16. package/dist/src/browser/help.d.ts +1 -0
  17. package/dist/src/browser/help.js +27 -0
  18. package/dist/src/browser/launcher.d.ts +8 -0
  19. package/dist/src/browser/launcher.js +169 -0
  20. package/dist/src/browser/operation-executor.d.ts +9 -0
  21. package/dist/src/browser/operation-executor.js +112 -0
  22. package/dist/src/browser/operation.d.ts +92 -0
  23. package/dist/src/browser/operation.js +20 -0
  24. package/dist/src/browser/parse-operation.d.ts +6 -0
  25. package/dist/src/browser/parse-operation.js +248 -0
  26. package/dist/src/browser/remote-helper.d.ts +3 -0
  27. package/dist/src/browser/remote-helper.js +114 -0
  28. package/dist/src/browser/remote-process.d.ts +7 -0
  29. package/dist/src/browser/remote-process.js +78 -0
  30. package/dist/src/browser/remote.d.ts +4 -0
  31. package/dist/src/browser/remote.js +73 -0
  32. package/dist/src/browser/request.d.ts +8 -0
  33. package/dist/src/browser/request.js +80 -0
  34. package/dist/src/browser/routes.d.ts +16 -0
  35. package/dist/src/browser/routes.js +40 -0
  36. package/dist/src/browser/runtime.d.ts +17 -0
  37. package/dist/src/browser/runtime.js +61 -0
  38. package/dist/src/browser/settings.d.ts +2 -0
  39. package/dist/src/browser/settings.js +164 -0
  40. package/dist/src/browser/worker-server.d.ts +2 -0
  41. package/dist/src/browser/worker-server.js +241 -0
  42. package/dist/src/browser-parameters.d.ts +42 -0
  43. package/dist/src/browser-parameters.js +113 -0
  44. package/dist/src/browser-tool.d.ts +48 -0
  45. package/dist/src/browser-tool.js +71 -0
  46. package/dist/src/cdp/actions/click.d.ts +4 -0
  47. package/dist/src/cdp/actions/click.js +56 -0
  48. package/dist/src/cdp/actions/element.d.ts +22 -0
  49. package/dist/src/cdp/actions/element.js +126 -0
  50. package/dist/src/cdp/actions/page.d.ts +7 -0
  51. package/dist/src/cdp/actions/page.js +127 -0
  52. package/dist/src/cdp/actions/screenshot.d.ts +10 -0
  53. package/dist/src/cdp/actions/screenshot.js +96 -0
  54. package/dist/src/cdp/actions/selector.d.ts +2 -0
  55. package/dist/src/cdp/actions/selector.js +41 -0
  56. package/dist/src/cdp/actions/type.d.ts +3 -0
  57. package/dist/src/cdp/actions/type.js +138 -0
  58. package/dist/src/cdp/client.d.ts +20 -0
  59. package/dist/src/cdp/client.js +248 -0
  60. package/dist/src/cdp/discovery.d.ts +7 -0
  61. package/dist/src/cdp/discovery.js +153 -0
  62. package/dist/src/cdp/evaluate.d.ts +3 -0
  63. package/dist/src/cdp/evaluate.js +31 -0
  64. package/dist/src/cdp/pages.d.ts +3 -0
  65. package/dist/src/cdp/pages.js +40 -0
  66. package/dist/src/cdp/serial.d.ts +1 -0
  67. package/dist/src/cdp/serial.js +18 -0
  68. package/dist/src/cdp/session.d.ts +25 -0
  69. package/dist/src/cdp/session.js +246 -0
  70. package/dist/src/cdp/snapshot-contract.d.ts +32 -0
  71. package/dist/src/cdp/snapshot-contract.js +23 -0
  72. package/dist/src/cdp/snapshot.d.ts +3 -0
  73. package/dist/src/cdp/snapshot.js +205 -0
  74. package/dist/src/cdp/types.d.ts +20 -0
  75. package/dist/src/cdp/types.js +14 -0
  76. package/dist/src/cdp/url.d.ts +1 -0
  77. package/dist/src/cdp/url.js +12 -0
  78. package/index.ts +115 -0
  79. package/package.json +93 -0
  80. package/remote-worker.ts +58 -0
  81. package/src/browser/artifacts.ts +178 -0
  82. package/src/browser/bounds.ts +159 -0
  83. package/src/browser/config.ts +162 -0
  84. package/src/browser/help.ts +30 -0
  85. package/src/browser/launcher.ts +208 -0
  86. package/src/browser/operation-executor.ts +251 -0
  87. package/src/browser/operation.ts +105 -0
  88. package/src/browser/parse-operation.ts +272 -0
  89. package/src/browser/remote-helper.ts +137 -0
  90. package/src/browser/remote-process.ts +85 -0
  91. package/src/browser/remote.ts +120 -0
  92. package/src/browser/request.ts +95 -0
  93. package/src/browser/routes.ts +69 -0
  94. package/src/browser/runtime.ts +84 -0
  95. package/src/browser/settings.ts +219 -0
  96. package/src/browser/worker-server.ts +274 -0
  97. package/src/browser-parameters.ts +118 -0
  98. package/src/browser-tool.ts +88 -0
  99. package/src/cdp/actions/click.ts +126 -0
  100. package/src/cdp/actions/element.ts +234 -0
  101. package/src/cdp/actions/page.ts +219 -0
  102. package/src/cdp/actions/screenshot.ts +176 -0
  103. package/src/cdp/actions/selector.ts +63 -0
  104. package/src/cdp/actions/type.ts +224 -0
  105. package/src/cdp/client.ts +286 -0
  106. package/src/cdp/discovery.ts +198 -0
  107. package/src/cdp/evaluate.ts +55 -0
  108. package/src/cdp/pages.ts +60 -0
  109. package/src/cdp/serial.ts +23 -0
  110. package/src/cdp/session.ts +345 -0
  111. package/src/cdp/snapshot-contract.ts +63 -0
  112. package/src/cdp/snapshot.ts +273 -0
  113. package/src/cdp/types.ts +49 -0
  114. package/src/cdp/url.ts +11 -0
  115. package/tsconfig.json +7 -0
@@ -0,0 +1,118 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import { type TSchema, Type } from "typebox";
3
+
4
+ export function browserParameters(hosts: readonly string[]) {
5
+ const route: Record<string, TSchema> =
6
+ hosts.length > 0
7
+ ? {
8
+ host: Type.Optional(
9
+ StringEnum(hosts, { description: "Configured browser host" }),
10
+ ),
11
+ }
12
+ : {};
13
+ const request = (properties: Record<string, TSchema>) =>
14
+ Type.Object({ ...route, ...properties }, { additionalProperties: false });
15
+ const refId = Type.String({
16
+ minLength: 1,
17
+ description: "Tab ref_id returned by tabs",
18
+ });
19
+ const elementId = Type.Integer({
20
+ minimum: 1,
21
+ description: "Element id returned by open or find",
22
+ });
23
+ const responseLength = StringEnum(["short", "medium", "long"] as const);
24
+ const handle = Type.String({
25
+ minLength: 1,
26
+ description: "Continuation handle returned by browser",
27
+ });
28
+ return Type.Union([
29
+ request({ action: StringEnum(["help", "start"] as const) }),
30
+ request({
31
+ action: Type.Literal("tabs"),
32
+ query: Type.Optional(Type.String({ minLength: 1 })),
33
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
34
+ }),
35
+ request({
36
+ action: Type.Literal("open"),
37
+ ref_id: refId,
38
+ lineno: Type.Optional(Type.Integer({ minimum: 1 })),
39
+ response_length: Type.Optional(responseLength),
40
+ }),
41
+ request({
42
+ action: Type.Literal("open"),
43
+ url: Type.String({ minLength: 1 }),
44
+ }),
45
+ request({
46
+ action: Type.Literal("find"),
47
+ ref_id: refId,
48
+ pattern: Type.String({ minLength: 1 }),
49
+ lineno: Type.Optional(Type.Integer({ minimum: 1 })),
50
+ response_length: Type.Optional(responseLength),
51
+ }),
52
+ request({ action: Type.Literal("click"), ref_id: refId, id: elementId }),
53
+ request({
54
+ action: Type.Literal("click"),
55
+ ref_id: refId,
56
+ selector: Type.String({ minLength: 1 }),
57
+ }),
58
+ request({
59
+ action: Type.Literal("click"),
60
+ ref_id: refId,
61
+ x: Type.Number(),
62
+ y: Type.Number(),
63
+ }),
64
+ request({
65
+ action: Type.Literal("type"),
66
+ ref_id: refId,
67
+ id: Type.Optional(elementId),
68
+ text: Type.String({ minLength: 1 }),
69
+ }),
70
+ request({
71
+ action: StringEnum(["screenshot", "html"] as const),
72
+ ref_id: refId,
73
+ }),
74
+ request({
75
+ action: StringEnum(["screenshot", "html"] as const),
76
+ ref_id: refId,
77
+ id: elementId,
78
+ }),
79
+ request({
80
+ action: StringEnum(["screenshot", "html"] as const),
81
+ ref_id: refId,
82
+ selector: Type.String({ minLength: 1 }),
83
+ }),
84
+ request({
85
+ action: Type.Literal("navigate"),
86
+ ref_id: refId,
87
+ url: Type.String({ minLength: 1 }),
88
+ }),
89
+ request({
90
+ action: Type.Literal("evaluate"),
91
+ ref_id: refId,
92
+ expression: Type.String({ minLength: 1 }),
93
+ }),
94
+ request({ action: Type.Literal("network"), ref_id: refId }),
95
+ request({
96
+ action: Type.Literal("load_all"),
97
+ ref_id: refId,
98
+ selector: Type.String({ minLength: 1 }),
99
+ interval_ms: Type.Optional(Type.Integer({ minimum: 0, maximum: 60_000 })),
100
+ }),
101
+ request({
102
+ action: Type.Literal("raw"),
103
+ ref_id: refId,
104
+ method: Type.String({ minLength: 1 }),
105
+ params: Type.Optional(Type.Object({}, { additionalProperties: true })),
106
+ }),
107
+ request({
108
+ action: Type.Literal("read_result"),
109
+ handle,
110
+ offset: Type.Optional(Type.Integer({ minimum: 0 })),
111
+ }),
112
+ request({ action: Type.Literal("discard_result"), handle }),
113
+ request({
114
+ action: Type.Literal("stop"),
115
+ ref_id: Type.Optional(refId),
116
+ }),
117
+ ]);
118
+ }
@@ -0,0 +1,88 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import { BROWSER_ACTIONS } from "./browser/operation.js";
3
+ import { type BrowserRequest, parseBrowserRequest } from "./browser/request.js";
4
+ import { BrowserRuntime } from "./browser/runtime.js";
5
+ import { browserParameters } from "./browser-parameters.js";
6
+
7
+ interface BrowserToolParams {
8
+ action: (typeof BROWSER_ACTIONS)[number];
9
+ }
10
+
11
+ const preparedBrowserRequest = Symbol("preparedBrowserRequest");
12
+
13
+ interface PreparedBrowserInput {
14
+ [preparedBrowserRequest]: BrowserRequest;
15
+ }
16
+
17
+ export function prepareBrowserCodeModeInput(input: unknown): BrowserToolParams {
18
+ // Freeform requests can batch operations that the normal Pi schema does not
19
+ // expose. Carry the parsed request beside a schema-valid adapter input.
20
+ const prepared: BrowserToolParams = { action: "help" };
21
+ Object.defineProperty(prepared, preparedBrowserRequest, {
22
+ value: parseBrowserRequest(input),
23
+ });
24
+ return prepared;
25
+ }
26
+
27
+ function isPreparedBrowserInput(input: unknown): input is PreparedBrowserInput {
28
+ return (
29
+ typeof input === "object" &&
30
+ input !== null &&
31
+ preparedBrowserRequest in input
32
+ );
33
+ }
34
+
35
+ function browserRequest(input: unknown): BrowserRequest {
36
+ return isPreparedBrowserInput(input)
37
+ ? input[preparedBrowserRequest]
38
+ : parseBrowserRequest(input);
39
+ }
40
+
41
+ export function createBrowserTool(runtime: BrowserRuntime) {
42
+ const parameters = browserParameters(runtime.hosts);
43
+ return defineTool({
44
+ name: "browser",
45
+ label: "Browser",
46
+ description:
47
+ "Inspect and control logged-in browser tabs with bounded accessibility content, interactive references, continuations and expert CDP actions.",
48
+ parameters,
49
+ promptSnippet: "Help first.",
50
+ promptGuidelines: [
51
+ "browser: tabs -> open; keep ref_id/id/cursors with their result.",
52
+ ...(runtime.hosts.length > 0
53
+ ? [
54
+ "browser: Keep a user-named host on every call and its refs/handles.",
55
+ ]
56
+ : []),
57
+ "browser: Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser.",
58
+ ],
59
+ async execute(_toolCallId, input, signal, onUpdate) {
60
+ const result = await runtime.execute(browserRequest(input), {
61
+ signal: signal ?? new AbortController().signal,
62
+ onOperation(operation, index, total) {
63
+ onUpdate?.({
64
+ content: [
65
+ {
66
+ type: "text",
67
+ text:
68
+ total === 1
69
+ ? `Browser ${operation.action}`
70
+ : `Browser ${operation.action} ${index + 1}/${total}`,
71
+ },
72
+ ],
73
+ details: {
74
+ action: operation.action,
75
+ index: index + 1,
76
+ total,
77
+ status: "running",
78
+ },
79
+ });
80
+ },
81
+ });
82
+ return {
83
+ content: [{ type: "text", text: JSON.stringify(result) }],
84
+ details: result,
85
+ };
86
+ },
87
+ });
88
+ }
@@ -0,0 +1,126 @@
1
+ import { sleep } from "../discovery.js";
2
+ import type { CdpConnection, ElementRefs } from "../types.js";
3
+ import {
4
+ backendCenter,
5
+ type ElementPoint,
6
+ requireElementRef,
7
+ } from "./element.js";
8
+ import { selectorBackendNode } from "./selector.js";
9
+
10
+ function dispatchMouse(
11
+ cdp: CdpConnection,
12
+ sessionId: string,
13
+ type: "mouseMoved" | "mousePressed" | "mouseReleased",
14
+ point: Pick<ElementPoint, "x" | "y">,
15
+ signal?: AbortSignal,
16
+ ): Promise<unknown> {
17
+ return cdp.send(
18
+ "Input.dispatchMouseEvent",
19
+ {
20
+ x: point.x,
21
+ y: point.y,
22
+ button: "left",
23
+ clickCount: 1,
24
+ modifiers: 0,
25
+ type,
26
+ },
27
+ sessionId,
28
+ signal,
29
+ );
30
+ }
31
+
32
+ async function pressAndRelease(
33
+ cdp: CdpConnection,
34
+ sessionId: string,
35
+ point: Pick<ElementPoint, "x" | "y">,
36
+ signal?: AbortSignal,
37
+ ): Promise<void> {
38
+ let pressed = false;
39
+ try {
40
+ await dispatchMouse(cdp, sessionId, "mousePressed", point, signal);
41
+ pressed = true;
42
+ await sleep(50, signal);
43
+ await dispatchMouse(cdp, sessionId, "mouseReleased", point, signal);
44
+ pressed = false;
45
+ } finally {
46
+ if (pressed) {
47
+ await dispatchMouse(
48
+ cdp,
49
+ sessionId,
50
+ "mouseReleased",
51
+ point,
52
+ undefined,
53
+ ).catch(() => undefined);
54
+ }
55
+ }
56
+ }
57
+
58
+ async function clickBackendNode(
59
+ cdp: CdpConnection,
60
+ sessionId: string,
61
+ backendNodeId: number,
62
+ signal?: AbortSignal,
63
+ ): Promise<ElementPoint> {
64
+ const initial = await backendCenter(
65
+ cdp,
66
+ sessionId,
67
+ backendNodeId,
68
+ true,
69
+ signal,
70
+ );
71
+ await dispatchMouse(cdp, sessionId, "mouseMoved", initial, signal);
72
+ const point = await backendCenter(
73
+ cdp,
74
+ sessionId,
75
+ backendNodeId,
76
+ false,
77
+ signal,
78
+ );
79
+ await pressAndRelease(cdp, sessionId, point, signal);
80
+ return point;
81
+ }
82
+
83
+ export async function clickSelector(
84
+ cdp: CdpConnection,
85
+ sessionId: string,
86
+ selector: string,
87
+ signal?: AbortSignal,
88
+ ): Promise<string> {
89
+ if (!selector) throw new Error("CSS selector required");
90
+ const backendNodeId = await selectorBackendNode(
91
+ cdp,
92
+ sessionId,
93
+ selector,
94
+ signal,
95
+ );
96
+ const point = await clickBackendNode(cdp, sessionId, backendNodeId, signal);
97
+ return `Clicked <${point.tag}> "${point.text}"`;
98
+ }
99
+
100
+ export async function clickRef(
101
+ cdp: CdpConnection,
102
+ sessionId: string,
103
+ elementRefs: ElementRefs,
104
+ id: number | string,
105
+ signal?: AbortSignal,
106
+ ): Promise<string> {
107
+ const ref = requireElementRef(elementRefs, id);
108
+ await clickBackendNode(cdp, sessionId, ref.backendNodeId, signal);
109
+ return `Clicked element ${ref.id}`;
110
+ }
111
+
112
+ export async function clickCoordinates(
113
+ cdp: CdpConnection,
114
+ sessionId: string,
115
+ x: number,
116
+ y: number,
117
+ signal?: AbortSignal,
118
+ ): Promise<string> {
119
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
120
+ throw new Error("x and y must be finite CSS-pixel numbers");
121
+ }
122
+ const point = { x, y };
123
+ await dispatchMouse(cdp, sessionId, "mouseMoved", point, signal);
124
+ await pressAndRelease(cdp, sessionId, point, signal);
125
+ return `Clicked at CSS (${x}, ${y})`;
126
+ }
@@ -0,0 +1,234 @@
1
+ import { sleep } from "../discovery.js";
2
+ import { positiveInteger } from "../snapshot-contract.js";
3
+ import type { CdpConnection, ElementRefs } from "../types.js";
4
+ import { asRecord } from "../types.js";
5
+
6
+ export interface ElementPoint {
7
+ x: number;
8
+ y: number;
9
+ tag: string;
10
+ text: string;
11
+ }
12
+
13
+ export interface ScreenshotClip {
14
+ x: number;
15
+ y: number;
16
+ width: number;
17
+ height: number;
18
+ scale: number;
19
+ }
20
+
21
+ export function requireElementRef(
22
+ elementRefs: ElementRefs,
23
+ id: number | string,
24
+ ): { id: number; backendNodeId: number } {
25
+ const parsed = positiveInteger(id, "element id");
26
+ const backendNodeId = elementRefs.get(parsed);
27
+ if (!backendNodeId) {
28
+ throw new Error(
29
+ `Unknown element id ${id}; run open again and use a current element id`,
30
+ );
31
+ }
32
+ return { id: parsed, backendNodeId };
33
+ }
34
+
35
+ async function resolveBackendObject(
36
+ cdp: CdpConnection,
37
+ sessionId: string,
38
+ backendNodeId: number,
39
+ signal?: AbortSignal,
40
+ ): Promise<string> {
41
+ const response = asRecord(
42
+ await cdp.send("DOM.resolveNode", { backendNodeId }, sessionId, signal),
43
+ "DOM.resolveNode response",
44
+ );
45
+ const object = asRecord(response["object"], "resolved DOM object");
46
+ if (typeof object["objectId"] !== "string") {
47
+ throw new Error("Element is no longer available; run open again");
48
+ }
49
+ return object["objectId"];
50
+ }
51
+
52
+ export async function withBackendObject<T>(
53
+ cdp: CdpConnection,
54
+ sessionId: string,
55
+ backendNodeId: number,
56
+ action: (objectId: string) => Promise<T>,
57
+ signal?: AbortSignal,
58
+ ): Promise<T> {
59
+ const objectId = await resolveBackendObject(
60
+ cdp,
61
+ sessionId,
62
+ backendNodeId,
63
+ signal,
64
+ );
65
+ try {
66
+ return await action(objectId);
67
+ } finally {
68
+ await cdp
69
+ .send("Runtime.releaseObject", { objectId }, sessionId, undefined)
70
+ .catch(() => undefined);
71
+ }
72
+ }
73
+
74
+ export async function scrollBackendIntoView(
75
+ cdp: CdpConnection,
76
+ sessionId: string,
77
+ backendNodeId: number,
78
+ signal?: AbortSignal,
79
+ ): Promise<void> {
80
+ await withBackendObject(
81
+ cdp,
82
+ sessionId,
83
+ backendNodeId,
84
+ (objectId) =>
85
+ cdp.send(
86
+ "Runtime.callFunctionOn",
87
+ {
88
+ objectId,
89
+ functionDeclaration:
90
+ 'function() { this.scrollIntoView({block: "center", inline: "center"}); }',
91
+ },
92
+ sessionId,
93
+ signal,
94
+ ),
95
+ signal,
96
+ );
97
+ await sleep(50, signal);
98
+ }
99
+
100
+ export async function backendCenter(
101
+ cdp: CdpConnection,
102
+ sessionId: string,
103
+ backendNodeId: number,
104
+ scroll = true,
105
+ signal?: AbortSignal,
106
+ ): Promise<ElementPoint> {
107
+ if (scroll) {
108
+ await scrollBackendIntoView(cdp, sessionId, backendNodeId, signal);
109
+ }
110
+ const response = await withBackendObject(
111
+ cdp,
112
+ sessionId,
113
+ backendNodeId,
114
+ (objectId) =>
115
+ cdp.send(
116
+ "Runtime.callFunctionOn",
117
+ {
118
+ objectId,
119
+ functionDeclaration: `function() {
120
+ const rect = this.getBoundingClientRect();
121
+ const style = getComputedStyle(this);
122
+ const disabled = this.matches(':disabled') ||
123
+ this.getAttribute('aria-disabled') === 'true';
124
+ const hidden = rect.width <= 0 || rect.height <= 0 ||
125
+ style.display === 'none' || style.visibility === 'hidden' ||
126
+ style.visibility === 'collapse' || style.pointerEvents === 'none' ||
127
+ Number(style.opacity) === 0 || this.closest('[inert]') !== null;
128
+ if (hidden) return { ok: false, error: 'Element is not visible or interactable' };
129
+ if (disabled) return { ok: false, error: 'Element is disabled' };
130
+ const x = rect.left + rect.width / 2;
131
+ const y = rect.top + rect.height / 2;
132
+ const root = this.getRootNode();
133
+ const hit = root && typeof root.elementFromPoint === 'function'
134
+ ? root.elementFromPoint(x, y)
135
+ : this.ownerDocument.elementFromPoint(x, y);
136
+ if (!hit || (hit !== this && !this.contains(hit))) {
137
+ const blocker = hit ? '<' + hit.tagName.toLowerCase() + '>' : 'no element';
138
+ return { ok: false, error: 'Element center is covered by ' + blocker };
139
+ }
140
+ return {
141
+ ok: true,
142
+ x,
143
+ y,
144
+ tag: this.tagName,
145
+ text: (this.textContent || '').trim().substring(0, 80)
146
+ };
147
+ }`,
148
+ returnByValue: true,
149
+ },
150
+ sessionId,
151
+ signal,
152
+ ),
153
+ signal,
154
+ );
155
+ const result = asRecord(response, "element center response");
156
+ const point = asRecord(
157
+ asRecord(result["result"], "element center result")["value"],
158
+ "element center",
159
+ );
160
+ if (point["ok"] !== true) {
161
+ throw new Error(
162
+ typeof point["error"] === "string"
163
+ ? point["error"]
164
+ : "Element has no clickable box",
165
+ );
166
+ }
167
+ if (typeof point["x"] !== "number" || typeof point["y"] !== "number") {
168
+ throw new Error("Element center has invalid coordinates");
169
+ }
170
+ return {
171
+ x: point["x"],
172
+ y: point["y"],
173
+ tag: typeof point["tag"] === "string" ? point["tag"] : "ELEMENT",
174
+ text: typeof point["text"] === "string" ? point["text"] : "",
175
+ };
176
+ }
177
+
178
+ export async function visibleElementClip(
179
+ cdp: CdpConnection,
180
+ sessionId: string,
181
+ quad: number[],
182
+ padding = 10,
183
+ signal?: AbortSignal,
184
+ ): Promise<ScreenshotClip> {
185
+ const response = asRecord(
186
+ await cdp.send("Page.getLayoutMetrics", {}, sessionId, signal),
187
+ "layout metrics",
188
+ );
189
+ const viewportValue =
190
+ response["cssVisualViewport"] ??
191
+ response["visualViewport"] ??
192
+ response["cssLayoutViewport"] ??
193
+ response["layoutViewport"];
194
+ const viewport = asRecord(viewportValue, "layout viewport");
195
+ if (
196
+ typeof viewport["clientWidth"] !== "number" ||
197
+ typeof viewport["clientHeight"] !== "number" ||
198
+ viewport["clientWidth"] <= 0 ||
199
+ viewport["clientHeight"] <= 0
200
+ ) {
201
+ throw new Error("Could not determine a bounded screenshot viewport");
202
+ }
203
+ const pageX = typeof viewport["pageX"] === "number" ? viewport["pageX"] : 0;
204
+ const pageY = typeof viewport["pageY"] === "number" ? viewport["pageY"] : 0;
205
+ const xs = [quad[0], quad[2], quad[4], quad[6]].filter(
206
+ (value): value is number => typeof value === "number",
207
+ );
208
+ const ys = [quad[1], quad[3], quad[5], quad[7]].filter(
209
+ (value): value is number => typeof value === "number",
210
+ );
211
+ if (xs.length !== 4 || ys.length !== 4) {
212
+ throw new Error("Element has an invalid screenshot box");
213
+ }
214
+ const x = Math.max(pageX, Math.min(...xs) - padding);
215
+ const y = Math.max(pageY, Math.min(...ys) - padding);
216
+ const right = Math.min(
217
+ pageX + viewport["clientWidth"],
218
+ Math.max(...xs) + padding,
219
+ );
220
+ const bottom = Math.min(
221
+ pageY + viewport["clientHeight"],
222
+ Math.max(...ys) + padding,
223
+ );
224
+ if (right <= x || bottom <= y) {
225
+ throw new Error("Element has no visible screenshot box");
226
+ }
227
+ return {
228
+ x,
229
+ y,
230
+ width: right - x,
231
+ height: bottom - y,
232
+ scale: 1,
233
+ };
234
+ }