-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathTextSnapshot.ts
More file actions
325 lines (295 loc) · 9.76 KB
/
TextSnapshot.ts
File metadata and controls
325 lines (295 loc) · 9.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {logger} from './logger.js';
import type {McpPage} from './McpPage.js';
import type {
Protocol,
SerializedAXNode,
ElementHandle,
} from './third_party/index.js';
import type {DevToolsData} from './tools/ToolDefinition.js';
import type {TextSnapshotNode} from './types.js';
export class TextSnapshot {
static nextSnapshotId = 1;
static resetCounter() {
TextSnapshot.nextSnapshotId = 1;
}
root: TextSnapshotNode;
idToNode: Map<string, TextSnapshotNode>;
snapshotId: string;
selectedElementUid?: string;
hasSelectedElement: boolean;
verbose: boolean;
constructor(data: {
root: TextSnapshotNode;
idToNode: Map<string, TextSnapshotNode>;
snapshotId: string;
selectedElementUid?: string;
hasSelectedElement: boolean;
verbose: boolean;
}) {
this.root = data.root;
this.idToNode = data.idToNode;
this.snapshotId = data.snapshotId;
this.selectedElementUid = data.selectedElementUid;
this.hasSelectedElement = data.hasSelectedElement;
this.verbose = data.verbose;
}
static async create(
page: McpPage,
options: {
verbose?: boolean;
devtoolsData?: DevToolsData;
extraHandles?: ElementHandle[];
} = {},
): Promise<TextSnapshot> {
const verbose = options.verbose ?? false;
const rootNode = await page.pptrPage.accessibility.snapshot({
includeIframes: true,
interestingOnly: !verbose,
});
if (!rootNode) {
throw new Error('Failed to create accessibility snapshot');
}
const {uniqueBackendNodeIdToMcpId} = page;
const snapshotId = TextSnapshot.nextSnapshotId++;
// Iterate through the whole accessibility node tree and assign node ids that
// will be used for the tree serialization and mapping ids back to nodes.
let idCounter = 0;
const idToNode = new Map<string, TextSnapshotNode>();
const seenUniqueIds = new Set<string>();
const seenBackendNodeIds = new Set<number>();
const assignIds = (node: SerializedAXNode): TextSnapshotNode => {
let id = '';
// @ts-expect-error untyped backendNodeId.
const backendNodeId: number = node.backendNodeId;
// @ts-expect-error untyped loaderId.
const uniqueBackendId = `${node.loaderId}_${backendNodeId}`;
const existingMcpId = uniqueBackendNodeIdToMcpId.get(uniqueBackendId);
if (existingMcpId !== undefined) {
// Re-use MCP exposed ID if the uniqueId is the same.
id = existingMcpId;
} else {
// Only generate a new ID if we have not seen the node before.
id = `${snapshotId}_${idCounter++}`;
uniqueBackendNodeIdToMcpId.set(uniqueBackendId, id);
}
seenUniqueIds.add(uniqueBackendId);
seenBackendNodeIds.add(backendNodeId);
const nodeWithId: TextSnapshotNode = {
...node,
id,
children: node.children
? node.children.map(child => assignIds(child))
: [],
};
// The AXNode for an option doesn't contain its `value`.
// Therefore, set text content of the option as value.
if (node.role === 'option') {
const optionText = node.name;
if (optionText) {
nodeWithId.value = optionText.toString();
}
}
idToNode.set(nodeWithId.id, nodeWithId);
return nodeWithId;
};
const rootNodeWithId = assignIds(rootNode);
await TextSnapshot.insertExtraNodes(
page,
idToNode,
seenUniqueIds,
snapshotId,
idCounter,
rootNodeWithId,
seenBackendNodeIds,
options.extraHandles ?? [],
);
const snapshot = new TextSnapshot({
root: rootNodeWithId,
snapshotId: String(snapshotId),
idToNode,
hasSelectedElement: false,
verbose,
});
const data = options.devtoolsData ?? (await page.getDevToolsData());
if (data?.cdpBackendNodeId) {
snapshot.hasSelectedElement = true;
snapshot.selectedElementUid = page.resolveCdpElementId(
data.cdpBackendNodeId,
);
}
// Clean up unique IDs that we did not see anymore.
for (const key of uniqueBackendNodeIdToMcpId.keys()) {
if (!seenUniqueIds.has(key)) {
uniqueBackendNodeIdToMcpId.delete(key);
}
}
return snapshot;
}
// ExtraHandles represent DOM nodes which might not be part of the accessibility tree, e.g. DOM nodes
// returned by in-page tools. We insert them into the tree by finding the closest ancestor in the
// tree and inserting the node as a child. The ancestor's child nodes are re-parented if necessary.
private static async insertExtraNodes(
page: McpPage,
idToNode: Map<string, TextSnapshotNode>,
seenUniqueIds: Set<string>,
snapshotId: number,
idCounter: number,
rootNodeWithId: TextSnapshotNode,
seenBackendNodeIds: Set<number>,
extraHandles: ElementHandle[],
): Promise<void> {
const {uniqueBackendNodeIdToMcpId} = page;
const createExtraNode = async (
handle: ElementHandle,
): Promise<TextSnapshotNode | null> => {
const backendNodeId = await handle.backendNodeId();
if (!backendNodeId || seenBackendNodeIds.has(backendNodeId)) {
return null;
}
const uniqueBackendId = `custom_${backendNodeId}`;
if (seenUniqueIds.has(uniqueBackendId)) {
return null;
}
seenBackendNodeIds.add(backendNodeId);
let id = '';
const mcpId = uniqueBackendNodeIdToMcpId.get(uniqueBackendId);
if (mcpId !== undefined) {
id = mcpId;
} else {
id = `${snapshotId}_${idCounter++}`;
uniqueBackendNodeIdToMcpId.set(uniqueBackendId, id);
}
seenUniqueIds.add(uniqueBackendId);
const tagHandle = await handle.getProperty('localName');
const tagValue = await tagHandle.jsonValue();
const extraNode: TextSnapshotNode = {
role: tagValue,
id,
backendNodeId,
children: [],
elementHandle: async () => handle,
};
return extraNode;
};
const findAncestorNode = async (
handle: ElementHandle,
): Promise<TextSnapshotNode | null> => {
let ancestorHandle = await handle.evaluateHandle(el => el.parentElement);
while (ancestorHandle) {
const ancestorElement = ancestorHandle.asElement();
if (!ancestorElement) {
await ancestorHandle.dispose();
return null;
}
const ancestorBackendId = await ancestorElement.backendNodeId();
if (ancestorBackendId) {
const ancestorNode = idToNode
.values()
.find(node => node.backendNodeId === ancestorBackendId);
if (ancestorNode) {
await ancestorHandle.dispose();
return ancestorNode;
}
}
const nextHandle = await ancestorElement.evaluateHandle(
el => el.parentElement,
);
await ancestorHandle.dispose();
ancestorHandle = nextHandle;
}
return null;
};
const findDescendantNodes = async (
backendNodeId?: number,
): Promise<Set<number>> => {
const descendantIds = new Set<number>();
if (!backendNodeId) {
return descendantIds;
}
try {
// @ts-expect-error internal API
const client = page.pptrPage._client();
if (client) {
const {node}: {node: Protocol.DOM.Node} = await client.send(
'DOM.describeNode',
{
backendNodeId,
depth: -1,
pierce: true,
},
);
const collect = (node: Protocol.DOM.Node) => {
if (node.backendNodeId && node.backendNodeId !== backendNodeId) {
descendantIds.add(node.backendNodeId);
}
if (node.children) {
for (const child of node.children) {
collect(child);
}
}
};
collect(node);
}
} catch (e) {
logger(
`Failed to collect descendants for backend node ${backendNodeId}`,
e,
);
}
return descendantIds;
};
const moveChildNodes = (
attachTarget: TextSnapshotNode,
extraNode: TextSnapshotNode,
descendantIds: Set<number>,
): number => {
let firstMovedIndex = -1;
if (descendantIds.size > 0 && attachTarget.children) {
const remainingChildren: TextSnapshotNode[] = [];
for (const child of attachTarget.children) {
if (child.backendNodeId && descendantIds.has(child.backendNodeId)) {
if (firstMovedIndex === -1) {
firstMovedIndex = remainingChildren.length;
}
extraNode.children.push(child);
} else {
remainingChildren.push(child);
}
}
attachTarget.children = remainingChildren;
}
return firstMovedIndex !== -1
? firstMovedIndex
: attachTarget.children
? attachTarget.children.length
: 0;
};
if (extraHandles.length) {
page.extraHandles = extraHandles;
}
const reorgInfo: Array<{
extraNode: TextSnapshotNode;
attachTarget: TextSnapshotNode;
descendantIds: Set<number>;
}> = [];
for (const handle of page.extraHandles) {
const extraNode = await createExtraNode(handle);
if (!extraNode) {
continue;
}
idToNode.set(extraNode.id, extraNode);
const attachTarget = (await findAncestorNode(handle)) || rootNodeWithId;
const descendantIds = await findDescendantNodes(extraNode.backendNodeId);
reorgInfo.push({extraNode, attachTarget, descendantIds});
}
for (const {extraNode, attachTarget, descendantIds} of reorgInfo) {
const index = moveChildNodes(attachTarget, extraNode, descendantIds);
attachTarget.children.splice(index, 0, extraNode);
}
}
}