browserpaw 0.0.0-stage → 5.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.
- package/LICENSE +681 -0
- package/README.md +4 -2
- package/dist/v5/cli-files.cjs +147 -0
- package/dist/v5/cli.cjs +4900 -0
- package/dist/v5/extension/assets/popup-Djl4pI1R.css +359 -0
- package/dist/v5/extension/background.js +39389 -0
- package/dist/v5/extension/browserpaw-build.json +191 -0
- package/dist/v5/extension/chunks/popup-BSqTH70w.js +6575 -0
- package/dist/v5/extension/content-scripts/agent-cursor.js +1475 -0
- package/dist/v5/extension/icon/128.png +0 -0
- package/dist/v5/extension/icon/16.png +0 -0
- package/dist/v5/extension/icon/32.png +0 -0
- package/dist/v5/extension/icon/48.png +0 -0
- package/dist/v5/extension/icon/96.png +0 -0
- package/dist/v5/extension/images/cursor-chat.png +0 -0
- package/dist/v5/extension/inject-scripts/accessibility-tree-helper.js +2031 -0
- package/dist/v5/extension/inject-scripts/keyboard-helper.js +412 -0
- package/dist/v5/extension/inject-scripts/network-helper.js +378 -0
- package/dist/v5/extension/inject-scripts/screenshot-helper.js +449 -0
- package/dist/v5/extension/inpage-engine.js +9437 -0
- package/dist/v5/extension/manifest.json +1 -0
- package/dist/v5/extension/popup.html +14 -0
- package/dist/v5/host.cjs +19813 -0
- package/dist/v5/recipes/bilibili-popular-videos.json +364 -0
- package/dist/v5/recipes/bilibili-video-detail.json +395 -0
- package/dist/v5/recipes/developer.mozilla.org.md +15 -0
- package/dist/v5/recipes/github-issue-thread.json +313 -0
- package/dist/v5/recipes/github-releases.json +218 -0
- package/dist/v5/recipes/github-repo-readme.json +306 -0
- package/dist/v5/recipes/github-repo-search.json +313 -0
- package/dist/v5/recipes/mdn-search.json +219 -0
- package/dist/v5/recipes/npm-compare.json +458 -0
- package/dist/v5/recipes/reddit-post-read.json +289 -0
- package/dist/v5/recipes/reddit-subreddit-posts.json +331 -0
- package/dist/v5/recipes/v2ex-node-topics.json +334 -0
- package/dist/v5/recipes/v2ex-topic-read.json +325 -0
- package/dist/v5/recipes/x-profile-posts.json +332 -0
- package/dist/v5/recipes/x-search-thread.json +293 -0
- package/dist/v5/recipes/x-visible-thread.json +260 -0
- package/dist/v5/recipes/youtube-search-videos.json +279 -0
- package/dist/v5/recipes/youtube-video-read.json +349 -0
- package/dist/v5/run_host.bat +7 -0
- package/dist/v5/run_host.sh +6 -0
- package/dist/v5/skill/browserpaw/SKILL.md +48 -0
- package/dist/v5/skill/browserpaw/assets/recipes/bilibili-popular-videos.json +364 -0
- package/dist/v5/skill/browserpaw/assets/recipes/bilibili-video-detail.json +395 -0
- package/dist/v5/skill/browserpaw/assets/recipes/developer.mozilla.org.md +15 -0
- package/dist/v5/skill/browserpaw/assets/recipes/github-issue-thread.json +313 -0
- package/dist/v5/skill/browserpaw/assets/recipes/github-releases.json +218 -0
- package/dist/v5/skill/browserpaw/assets/recipes/github-repo-readme.json +306 -0
- package/dist/v5/skill/browserpaw/assets/recipes/github-repo-search.json +313 -0
- package/dist/v5/skill/browserpaw/assets/recipes/mdn-search.json +219 -0
- package/dist/v5/skill/browserpaw/assets/recipes/npm-compare.json +458 -0
- package/dist/v5/skill/browserpaw/assets/recipes/reddit-post-read.json +289 -0
- package/dist/v5/skill/browserpaw/assets/recipes/reddit-subreddit-posts.json +331 -0
- package/dist/v5/skill/browserpaw/assets/recipes/v2ex-node-topics.json +334 -0
- package/dist/v5/skill/browserpaw/assets/recipes/v2ex-topic-read.json +325 -0
- package/dist/v5/skill/browserpaw/assets/recipes/x-profile-posts.json +332 -0
- package/dist/v5/skill/browserpaw/assets/recipes/x-search-thread.json +293 -0
- package/dist/v5/skill/browserpaw/assets/recipes/x-visible-thread.json +260 -0
- package/dist/v5/skill/browserpaw/assets/recipes/youtube-search-videos.json +279 -0
- package/dist/v5/skill/browserpaw/assets/recipes/youtube-video-read.json +349 -0
- package/dist/v5/skill/browserpaw/references/TROUBLESHOOTING.md +7 -0
- package/dist/v5/skill/browserpaw/references/TROUBLESHOOTING.zh-CN.md +5 -0
- package/dist/v5/skill/browserpaw/references/browser-data.md +33 -0
- package/dist/v5/skill/browserpaw/references/commands.md +103 -0
- package/dist/v5/skill/browserpaw/references/debugging.md +32 -0
- package/dist/v5/skill/browserpaw/references/recipe-contract.md +47 -0
- package/package.json +67 -4
|
@@ -0,0 +1,2031 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
// accessibility-tree-helper.js
|
|
3
|
+
// Injected script to generate an accessibility-like tree of the visible page
|
|
4
|
+
// Elements receive stable refs (ref_*) via WeakRef mapping for later reference.
|
|
5
|
+
|
|
6
|
+
(function () {
|
|
7
|
+
if (window.__ACCESSIBILITY_TREE_HELPER_INITIALIZED__) return;
|
|
8
|
+
window.__ACCESSIBILITY_TREE_HELPER_INITIALIZED__ = true;
|
|
9
|
+
|
|
10
|
+
// Traversal and output limits to ensure stability on very large/complex pages
|
|
11
|
+
const MAX_DEPTH = 30; // maximum DOM depth to traverse
|
|
12
|
+
const MAX_NODES = 4000; // hard limit to avoid long blocking on huge DOMs
|
|
13
|
+
const MAX_LINE_LABEL = 100; // max characters for a single label in output
|
|
14
|
+
const REF_MAP_LIMIT = 1000; // limit size of the ref map to keep payload small
|
|
15
|
+
|
|
16
|
+
const TAG_ROLE_MAP = new Map([
|
|
17
|
+
['a', 'link'],
|
|
18
|
+
['button', 'button'],
|
|
19
|
+
['select', 'combobox'],
|
|
20
|
+
['textarea', 'textbox'],
|
|
21
|
+
['h1', 'heading'],
|
|
22
|
+
['h2', 'heading'],
|
|
23
|
+
['h3', 'heading'],
|
|
24
|
+
['h4', 'heading'],
|
|
25
|
+
['h5', 'heading'],
|
|
26
|
+
['h6', 'heading'],
|
|
27
|
+
['img', 'image'],
|
|
28
|
+
['nav', 'navigation'],
|
|
29
|
+
['main', 'main'],
|
|
30
|
+
['header', 'banner'],
|
|
31
|
+
['footer', 'contentinfo'],
|
|
32
|
+
['section', 'region'],
|
|
33
|
+
['article', 'article'],
|
|
34
|
+
['aside', 'complementary'],
|
|
35
|
+
['form', 'form'],
|
|
36
|
+
['table', 'table'],
|
|
37
|
+
['ul', 'list'],
|
|
38
|
+
['ol', 'list'],
|
|
39
|
+
['li', 'listitem'],
|
|
40
|
+
['label', 'label'],
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
const INPUT_TYPE_ROLE_MAP = new Map([
|
|
44
|
+
['submit', 'button'],
|
|
45
|
+
['button', 'button'],
|
|
46
|
+
['checkbox', 'checkbox'],
|
|
47
|
+
['radio', 'radio'],
|
|
48
|
+
['file', 'button'],
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
const TEXT_LABEL_TAGS = new Set(['button', 'a', 'summary']);
|
|
52
|
+
const HEADING_TAG_RE = /^h[1-6]$/;
|
|
53
|
+
const INTERACTIVE_TAGS = new Set([
|
|
54
|
+
'a',
|
|
55
|
+
'button',
|
|
56
|
+
'input',
|
|
57
|
+
'select',
|
|
58
|
+
'textarea',
|
|
59
|
+
'details',
|
|
60
|
+
'summary',
|
|
61
|
+
]);
|
|
62
|
+
const INTERACTIVE_ROLES = new Set([
|
|
63
|
+
'button',
|
|
64
|
+
'link',
|
|
65
|
+
'checkbox',
|
|
66
|
+
'radio',
|
|
67
|
+
'switch',
|
|
68
|
+
'slider',
|
|
69
|
+
'option',
|
|
70
|
+
'menuitem',
|
|
71
|
+
'textbox',
|
|
72
|
+
'searchbox',
|
|
73
|
+
'combobox',
|
|
74
|
+
'spinbutton',
|
|
75
|
+
'tab',
|
|
76
|
+
'treeitem',
|
|
77
|
+
]);
|
|
78
|
+
const SHADOW_INTERACTIVE_SELECTOR =
|
|
79
|
+
'input, textarea, select, button, a[href], [contenteditable="true"], [role="button"], [role="link"], [role="textbox"], [role="combobox"], [role="searchbox"], [role="menuitem"], [role="option"], [role="switch"], [role="radio"], [role="checkbox"], [role="tab"], [role="slider"]';
|
|
80
|
+
const STRUCTURAL_TAGS = new Set([
|
|
81
|
+
'h1',
|
|
82
|
+
'h2',
|
|
83
|
+
'h3',
|
|
84
|
+
'h4',
|
|
85
|
+
'h5',
|
|
86
|
+
'h6',
|
|
87
|
+
'nav',
|
|
88
|
+
'main',
|
|
89
|
+
'header',
|
|
90
|
+
'footer',
|
|
91
|
+
'section',
|
|
92
|
+
'article',
|
|
93
|
+
'aside',
|
|
94
|
+
]);
|
|
95
|
+
const FORMISH_ROLES = new Set(['search', 'form', 'group', 'toolbar', 'navigation']);
|
|
96
|
+
const FORMISH_TAGS = new Set(['form', 'fieldset', 'nav', 'legend']);
|
|
97
|
+
const EXCLUDED_TAGS = new Set(['script', 'style', 'meta', 'link', 'title', 'noscript']);
|
|
98
|
+
const SELECTOR_IDENTITY_ATTRS = ['data-testid', 'data-cy', 'name'];
|
|
99
|
+
const EMPTY_GENERIC_LINE_RE = /^\s*- generic \[ref=ref_\d+\]$/;
|
|
100
|
+
|
|
101
|
+
function syncReverseMapAndPrune(map, reverseMap) {
|
|
102
|
+
for (const key in map) {
|
|
103
|
+
if (!Object.prototype.hasOwnProperty.call(map, key)) continue;
|
|
104
|
+
const weak = map[key];
|
|
105
|
+
const derefed = weak && typeof weak.deref === 'function' ? weak.deref() : null;
|
|
106
|
+
if (!derefed) {
|
|
107
|
+
delete map[key];
|
|
108
|
+
} else if (typeof derefed === 'object' || typeof derefed === 'function') {
|
|
109
|
+
reverseMap.set(derefed, key);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function ensureElementRefRegistry() {
|
|
115
|
+
if (!window.__mcpElementMap) window.__mcpElementMap = window.__claudeElementMap || {};
|
|
116
|
+
if (!window.__mcpRefCounter) window.__mcpRefCounter = window.__claudeRefCounter || 0;
|
|
117
|
+
window.__claudeElementMap = window.__mcpElementMap;
|
|
118
|
+
window.__claudeRefCounter = window.__mcpRefCounter;
|
|
119
|
+
|
|
120
|
+
const map = window.__mcpElementMap;
|
|
121
|
+
let reverseMap = window.__mcpElementReverseMap;
|
|
122
|
+
let rebuilt = false;
|
|
123
|
+
if (!(reverseMap instanceof WeakMap) || window.__mcpElementReverseMapSource !== map) {
|
|
124
|
+
reverseMap = new WeakMap();
|
|
125
|
+
window.__mcpElementReverseMap = reverseMap;
|
|
126
|
+
window.__mcpElementReverseMapSource = map;
|
|
127
|
+
syncReverseMapAndPrune(map, reverseMap);
|
|
128
|
+
rebuilt = true;
|
|
129
|
+
}
|
|
130
|
+
return { map, reverseMap, rebuilt };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function syncAndPruneElementRefs() {
|
|
134
|
+
const { map, reverseMap, rebuilt } = ensureElementRefRegistry();
|
|
135
|
+
if (!rebuilt) {
|
|
136
|
+
syncReverseMapAndPrune(map, reverseMap);
|
|
137
|
+
}
|
|
138
|
+
return { map, reverseMap };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function getOrAssignElementRef(el) {
|
|
142
|
+
const { map, reverseMap } = ensureElementRefRegistry();
|
|
143
|
+
const existing = reverseMap.get(el);
|
|
144
|
+
if (existing) {
|
|
145
|
+
const existingWeak = Object.prototype.hasOwnProperty.call(map, existing)
|
|
146
|
+
? map[existing]
|
|
147
|
+
: null;
|
|
148
|
+
if (existingWeak && typeof existingWeak.deref === 'function' && existingWeak.deref() === el) {
|
|
149
|
+
return existing;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const refId = `ref_${++window.__mcpRefCounter}`;
|
|
153
|
+
window.__claudeRefCounter = window.__mcpRefCounter;
|
|
154
|
+
map[refId] = new WeakRef(el);
|
|
155
|
+
reverseMap.set(el, refId);
|
|
156
|
+
return refId;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Keep a weak map from ref id to elements and an O(1) reverse WeakMap
|
|
160
|
+
ensureElementRefRegistry();
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Infer ARIA-like role from element
|
|
164
|
+
* @param {Element} el
|
|
165
|
+
* @returns {string}
|
|
166
|
+
*/
|
|
167
|
+
function inferRole(el) {
|
|
168
|
+
const role = el.getAttribute('role');
|
|
169
|
+
if (role) return role;
|
|
170
|
+
const tag = el.tagName.toLowerCase();
|
|
171
|
+
if (tag === 'input') {
|
|
172
|
+
const type = el.getAttribute('type') || '';
|
|
173
|
+
return INPUT_TYPE_ROLE_MAP.get(type) || 'textbox';
|
|
174
|
+
}
|
|
175
|
+
return TAG_ROLE_MAP.get(tag) || 'generic';
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Derive readable label for element
|
|
180
|
+
* @param {Element} el
|
|
181
|
+
* @returns {string}
|
|
182
|
+
*/
|
|
183
|
+
function inferLabel(el) {
|
|
184
|
+
const tag = el.tagName.toLowerCase();
|
|
185
|
+
if (tag === 'select') {
|
|
186
|
+
const sel = /** @type {HTMLSelectElement} */ (el);
|
|
187
|
+
const opt = sel.querySelector('option[selected]') || sel.options[sel.selectedIndex];
|
|
188
|
+
if (opt && opt.textContent) return opt.textContent.trim();
|
|
189
|
+
}
|
|
190
|
+
const aria = el.getAttribute('aria-label');
|
|
191
|
+
if (aria && aria.trim()) return aria.trim();
|
|
192
|
+
const placeholder = el.getAttribute('placeholder');
|
|
193
|
+
if (placeholder && placeholder.trim()) return placeholder.trim();
|
|
194
|
+
const title = el.getAttribute('title');
|
|
195
|
+
if (title && title.trim()) return title.trim();
|
|
196
|
+
const alt = el.getAttribute('alt');
|
|
197
|
+
if (alt && alt.trim()) return alt.trim();
|
|
198
|
+
if (/** @type {HTMLElement} */ (el).id) {
|
|
199
|
+
const lab = document.querySelector(`label[for="${/** @type {HTMLElement} */ (el).id}"]`);
|
|
200
|
+
if (lab && lab.textContent && lab.textContent.trim()) return lab.textContent.trim();
|
|
201
|
+
}
|
|
202
|
+
if (tag === 'input') {
|
|
203
|
+
const input = /** @type {HTMLInputElement} */ (el);
|
|
204
|
+
const type = input.getAttribute('type') || '';
|
|
205
|
+
const val = input.getAttribute('value');
|
|
206
|
+
if (type === 'submit' && val && val.trim()) return val.trim();
|
|
207
|
+
if (input.value && input.value.length < 50 && input.value.trim()) return input.value.trim();
|
|
208
|
+
}
|
|
209
|
+
if (TEXT_LABEL_TAGS.has(tag)) {
|
|
210
|
+
let text = '';
|
|
211
|
+
for (let i = 0; i < el.childNodes.length; i++) {
|
|
212
|
+
const n = el.childNodes[i];
|
|
213
|
+
if (n.nodeType === Node.TEXT_NODE) text += n.textContent || '';
|
|
214
|
+
}
|
|
215
|
+
if (text.trim()) return text.trim();
|
|
216
|
+
}
|
|
217
|
+
if (HEADING_TAG_RE.test(tag)) {
|
|
218
|
+
const t = el.textContent;
|
|
219
|
+
if (t && t.trim()) return t.trim().substring(0, MAX_LINE_LABEL);
|
|
220
|
+
}
|
|
221
|
+
if (tag === 'img') {
|
|
222
|
+
const src = el.getAttribute('src');
|
|
223
|
+
if (src) {
|
|
224
|
+
const file = src.split('/').pop()?.split('?')[0];
|
|
225
|
+
return `Image: ${file}`;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
let agg = '';
|
|
229
|
+
for (let i = 0; i < el.childNodes.length; i++) {
|
|
230
|
+
const n = el.childNodes[i];
|
|
231
|
+
if (n.nodeType === Node.TEXT_NODE) agg += n.textContent || '';
|
|
232
|
+
}
|
|
233
|
+
if (agg && agg.trim() && agg.trim().length >= 3) {
|
|
234
|
+
const v = agg.trim();
|
|
235
|
+
return v.length > 50 ? v.substring(0, 50) + '...' : v;
|
|
236
|
+
}
|
|
237
|
+
return '';
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function getCachedComputedStyle(el, state) {
|
|
241
|
+
const cache = state && state.styleCache;
|
|
242
|
+
if (cache && cache.has(el)) return cache.get(el);
|
|
243
|
+
const cs = window.getComputedStyle(/** @type {HTMLElement} */ (el));
|
|
244
|
+
if (cache) cache.set(el, cs);
|
|
245
|
+
return cs;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function getCachedBoundingRect(el, state) {
|
|
249
|
+
const cache = state && state.rectCache;
|
|
250
|
+
if (cache && cache.has(el)) return cache.get(el);
|
|
251
|
+
const rect = /** @type {HTMLElement} */ (el).getBoundingClientRect();
|
|
252
|
+
if (cache) cache.set(el, rect);
|
|
253
|
+
return rect;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function getCachedLabel(el, state) {
|
|
257
|
+
const cache = state && state.labelCache;
|
|
258
|
+
if (cache && cache.has(el)) return cache.get(el);
|
|
259
|
+
const label = inferLabel(el);
|
|
260
|
+
if (cache) cache.set(el, label);
|
|
261
|
+
return label;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function getCachedInteractive(el, state) {
|
|
265
|
+
const cache = state && state.interactiveCache;
|
|
266
|
+
if (cache && cache.has(el)) return cache.get(el);
|
|
267
|
+
const interactive = isInteractive(el);
|
|
268
|
+
if (cache) cache.set(el, interactive);
|
|
269
|
+
return interactive;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Check if element is visible in DOM
|
|
274
|
+
* @param {Element} el
|
|
275
|
+
* @param {{styleCache?: WeakMap<Element, CSSStyleDeclaration>}=} state
|
|
276
|
+
*/
|
|
277
|
+
function isVisible(el, state) {
|
|
278
|
+
const cs = getCachedComputedStyle(el, state);
|
|
279
|
+
if (cs.display === 'none' || cs.visibility === 'hidden' || cs.opacity === '0') return false;
|
|
280
|
+
const he = /** @type {HTMLElement} */ (el);
|
|
281
|
+
return he.offsetWidth > 0 && he.offsetHeight > 0;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Whether the element is interactive
|
|
286
|
+
* @param {Element} el
|
|
287
|
+
*/
|
|
288
|
+
function isInteractive(el) {
|
|
289
|
+
// Native interactive tags
|
|
290
|
+
const tag = el.tagName.toLowerCase();
|
|
291
|
+
if (INTERACTIVE_TAGS.has(tag)) return true;
|
|
292
|
+
|
|
293
|
+
// Generic interactive hints
|
|
294
|
+
if (el.getAttribute('onclick') != null) return true;
|
|
295
|
+
if (
|
|
296
|
+
el.getAttribute('tabindex') != null &&
|
|
297
|
+
String(el.getAttribute('tabindex')).trim() !== '' &&
|
|
298
|
+
!String(el.getAttribute('tabindex')).trim().startsWith('-')
|
|
299
|
+
)
|
|
300
|
+
return true;
|
|
301
|
+
if (el.getAttribute('contenteditable') === 'true') return true;
|
|
302
|
+
|
|
303
|
+
// ARIA roles commonly used by custom elements
|
|
304
|
+
const role = (el.getAttribute && el.getAttribute('role')) || '';
|
|
305
|
+
if (role && INTERACTIVE_ROLES.has(role.toLowerCase())) return true;
|
|
306
|
+
|
|
307
|
+
// Shadow host case: treat host as interactive if its open shadow root contains
|
|
308
|
+
// an interactive control (textarea/input/select/button/a or contenteditable).
|
|
309
|
+
try {
|
|
310
|
+
const anyEl = /** @type {any} */ (el);
|
|
311
|
+
const sr = anyEl && anyEl.shadowRoot ? anyEl.shadowRoot : null;
|
|
312
|
+
if (sr) {
|
|
313
|
+
const inner = sr.querySelector(SHADOW_INTERACTIVE_SELECTOR);
|
|
314
|
+
if (inner) return true;
|
|
315
|
+
}
|
|
316
|
+
} catch (_) {
|
|
317
|
+
/* ignore */
|
|
318
|
+
}
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Structural containers useful to include
|
|
324
|
+
* @param {Element} el
|
|
325
|
+
*/
|
|
326
|
+
function isStructural(el) {
|
|
327
|
+
const tag = el.tagName.toLowerCase();
|
|
328
|
+
if (STRUCTURAL_TAGS.has(tag)) return true;
|
|
329
|
+
return el.getAttribute('role') != null;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Form-ish containers to keep
|
|
334
|
+
* @param {Element} el
|
|
335
|
+
*/
|
|
336
|
+
function isFormishContainer(el) {
|
|
337
|
+
const tag = el.tagName.toLowerCase();
|
|
338
|
+
const role = (el.getAttribute && el.getAttribute('role')) || '';
|
|
339
|
+
if (FORMISH_TAGS.has(tag) || FORMISH_ROLES.has(role)) return true;
|
|
340
|
+
const id = /** @type {HTMLElement} */ (el).id || '';
|
|
341
|
+
// Normalize className for HTML/SVG elements
|
|
342
|
+
let cls = '';
|
|
343
|
+
try {
|
|
344
|
+
const attr = el.getAttribute && el.getAttribute('class');
|
|
345
|
+
if (typeof attr === 'string') cls = attr;
|
|
346
|
+
else {
|
|
347
|
+
const cn = /** @type {any} */ (el).className;
|
|
348
|
+
if (typeof cn === 'string') cls = cn;
|
|
349
|
+
else if (cn && typeof cn.baseVal === 'string') cls = cn.baseVal;
|
|
350
|
+
}
|
|
351
|
+
} catch (e) {
|
|
352
|
+
/* ignore */
|
|
353
|
+
}
|
|
354
|
+
return (
|
|
355
|
+
id.includes('search') ||
|
|
356
|
+
cls.includes('search') ||
|
|
357
|
+
id.includes('form') ||
|
|
358
|
+
cls.includes('form') ||
|
|
359
|
+
id.includes('menu') ||
|
|
360
|
+
cls.includes('menu') ||
|
|
361
|
+
id.includes('nav') ||
|
|
362
|
+
cls.includes('nav')
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// Utility: query CSS across open shadow roots (best-effort)
|
|
367
|
+
function querySelectorDeepFirst(selector) {
|
|
368
|
+
try {
|
|
369
|
+
// Fast path
|
|
370
|
+
const direct = document.querySelector(selector);
|
|
371
|
+
if (direct) return direct;
|
|
372
|
+
} catch (_) {}
|
|
373
|
+
const visited = new Set();
|
|
374
|
+
const stack = [document.documentElement];
|
|
375
|
+
while (stack.length) {
|
|
376
|
+
const node = stack.pop();
|
|
377
|
+
if (!node || visited.has(node)) continue;
|
|
378
|
+
visited.add(node);
|
|
379
|
+
try {
|
|
380
|
+
const root = /** @type {any} */ (node).shadowRoot || (node.nodeType === 9 ? node : null);
|
|
381
|
+
if (root) {
|
|
382
|
+
try {
|
|
383
|
+
const hit = root.querySelector(selector);
|
|
384
|
+
if (hit) return hit;
|
|
385
|
+
} catch (_) {}
|
|
386
|
+
}
|
|
387
|
+
} catch (_) {}
|
|
388
|
+
// Traverse DOM and shadow roots
|
|
389
|
+
try {
|
|
390
|
+
const children = /** @type {Element} */ (node).children || [];
|
|
391
|
+
for (let i = 0; i < children.length; i++) stack.push(children[i]);
|
|
392
|
+
const sr = /** @type {any} */ (node).shadowRoot;
|
|
393
|
+
if (sr && sr.children) {
|
|
394
|
+
for (let i = 0; i < sr.children.length; i++) stack.push(sr.children[i]);
|
|
395
|
+
}
|
|
396
|
+
} catch (_) {}
|
|
397
|
+
}
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Query CSS selector and return match info including uniqueness check.
|
|
403
|
+
* @param {string} selector - CSS selector to query
|
|
404
|
+
* @param {boolean} allowMultiple - If true, skip uniqueness check and return first match
|
|
405
|
+
* @returns {{element: Element | null, matchCount: number, error?: string}}
|
|
406
|
+
* Note: matchCount is capped at 2 (where 2 means "2 or more") for performance
|
|
407
|
+
*/
|
|
408
|
+
function querySelectorWithUniquenessCheck(selector, allowMultiple = false) {
|
|
409
|
+
const seen = new Set();
|
|
410
|
+
let firstMatch = null;
|
|
411
|
+
let matchCount = 0;
|
|
412
|
+
|
|
413
|
+
const recordMatch = (el) => {
|
|
414
|
+
if (!(el instanceof Element) || seen.has(el)) return false;
|
|
415
|
+
seen.add(el);
|
|
416
|
+
matchCount++;
|
|
417
|
+
if (!firstMatch) firstMatch = el;
|
|
418
|
+
// Short-circuit if:
|
|
419
|
+
// - allowMultiple is true and we found first match (no need to continue)
|
|
420
|
+
// - allowMultiple is false and we found multiple matches
|
|
421
|
+
if (allowMultiple && firstMatch) return true;
|
|
422
|
+
if (!allowMultiple && matchCount >= 2) return true;
|
|
423
|
+
return false;
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
// Query in main document
|
|
427
|
+
let selectorError = null;
|
|
428
|
+
try {
|
|
429
|
+
const directMatches = document.querySelectorAll(selector);
|
|
430
|
+
for (let i = 0; i < directMatches.length; i++) {
|
|
431
|
+
if (recordMatch(directMatches[i])) {
|
|
432
|
+
// Early exit: either found first match (allowMultiple) or found multiple (not allowed)
|
|
433
|
+
return { element: firstMatch, matchCount: allowMultiple ? 1 : 2 };
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
} catch (e) {
|
|
437
|
+
selectorError = e;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
if (selectorError) {
|
|
441
|
+
return {
|
|
442
|
+
element: null,
|
|
443
|
+
matchCount: 0,
|
|
444
|
+
error: `Invalid CSS selector "${selector}": ${selectorError.message || selectorError}`,
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// If allowMultiple and we already have a match, return immediately
|
|
449
|
+
if (allowMultiple && firstMatch) {
|
|
450
|
+
return { element: firstMatch, matchCount: 1 };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Query in shadow DOMs
|
|
454
|
+
const visited = new Set();
|
|
455
|
+
const stack = [document.documentElement];
|
|
456
|
+
while (stack.length) {
|
|
457
|
+
const node = stack.pop();
|
|
458
|
+
if (!node || visited.has(node)) continue;
|
|
459
|
+
visited.add(node);
|
|
460
|
+
|
|
461
|
+
try {
|
|
462
|
+
const shadowRoot = /** @type {any} */ (node).shadowRoot;
|
|
463
|
+
if (shadowRoot) {
|
|
464
|
+
try {
|
|
465
|
+
const shadowMatches = shadowRoot.querySelectorAll(selector);
|
|
466
|
+
for (let i = 0; i < shadowMatches.length; i++) {
|
|
467
|
+
if (recordMatch(shadowMatches[i])) {
|
|
468
|
+
// Early exit: either found first match (allowMultiple) or found multiple (not allowed)
|
|
469
|
+
return { element: firstMatch, matchCount: allowMultiple ? 1 : 2 };
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
} catch (e) {
|
|
473
|
+
return {
|
|
474
|
+
element: null,
|
|
475
|
+
matchCount: 0,
|
|
476
|
+
error: `Invalid CSS selector "${selector}": ${e.message || e}`,
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// Add shadow root children to stack
|
|
481
|
+
try {
|
|
482
|
+
const shadowChildren = shadowRoot.children || [];
|
|
483
|
+
for (let i = 0; i < shadowChildren.length; i++) {
|
|
484
|
+
stack.push(shadowChildren[i]);
|
|
485
|
+
}
|
|
486
|
+
} catch (_) {}
|
|
487
|
+
}
|
|
488
|
+
} catch (_) {}
|
|
489
|
+
|
|
490
|
+
// Add regular children to stack
|
|
491
|
+
try {
|
|
492
|
+
const children = /** @type {Element} */ (node).children || [];
|
|
493
|
+
for (let i = 0; i < children.length; i++) {
|
|
494
|
+
stack.push(children[i]);
|
|
495
|
+
}
|
|
496
|
+
} catch (_) {}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return { element: firstMatch, matchCount: Math.min(matchCount, 2) };
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Query XPath selector and return match info including uniqueness check.
|
|
504
|
+
* @param {string} selector - XPath selector to query
|
|
505
|
+
* @param {boolean} allowMultiple - If true, skip uniqueness check and return first match
|
|
506
|
+
* @returns {{element: Element | null, matchCount: number, error?: string}}
|
|
507
|
+
* Note: matchCount is capped at 2 (where 2 means "2 or more") for performance
|
|
508
|
+
*/
|
|
509
|
+
function queryXPathWithUniquenessCheck(selector, allowMultiple = false) {
|
|
510
|
+
if (!selector) {
|
|
511
|
+
return { element: null, matchCount: 0 };
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
try {
|
|
515
|
+
if (allowMultiple) {
|
|
516
|
+
// When multiple matches are allowed, use ANY_UNORDERED_NODE_TYPE for performance
|
|
517
|
+
// This returns just the first match without evaluating the entire result set
|
|
518
|
+
const result = document.evaluate(
|
|
519
|
+
selector,
|
|
520
|
+
document,
|
|
521
|
+
null,
|
|
522
|
+
XPathResult.ANY_UNORDERED_NODE_TYPE,
|
|
523
|
+
null,
|
|
524
|
+
);
|
|
525
|
+
const firstMatch =
|
|
526
|
+
result.singleNodeValue instanceof Element
|
|
527
|
+
? /** @type {Element} */ (result.singleNodeValue)
|
|
528
|
+
: null;
|
|
529
|
+
return { element: firstMatch, matchCount: firstMatch ? 1 : 0 };
|
|
530
|
+
} else {
|
|
531
|
+
// When uniqueness is required, use ORDERED_NODE_SNAPSHOT_TYPE to count matches
|
|
532
|
+
const snapshot = document.evaluate(
|
|
533
|
+
selector,
|
|
534
|
+
document,
|
|
535
|
+
null,
|
|
536
|
+
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
|
|
537
|
+
null,
|
|
538
|
+
);
|
|
539
|
+
const totalMatches = snapshot.snapshotLength;
|
|
540
|
+
// Cap at 2 for performance (2 means "2 or more")
|
|
541
|
+
const matchCount = Math.min(totalMatches, 2);
|
|
542
|
+
const firstMatch =
|
|
543
|
+
totalMatches > 0 && snapshot.snapshotItem(0) instanceof Element
|
|
544
|
+
? /** @type {Element} */ (snapshot.snapshotItem(0))
|
|
545
|
+
: null;
|
|
546
|
+
return { element: firstMatch, matchCount };
|
|
547
|
+
}
|
|
548
|
+
} catch (e) {
|
|
549
|
+
return {
|
|
550
|
+
element: null,
|
|
551
|
+
matchCount: 0,
|
|
552
|
+
error: `Invalid XPath "${selector}": ${e.message || e}`,
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Whether to include element in tree under config
|
|
559
|
+
* @param {Element} el
|
|
560
|
+
* @param {{filter?: 'all'|'interactive'}} cfg
|
|
561
|
+
* @param {object=} state
|
|
562
|
+
*/
|
|
563
|
+
function shouldInclude(el, cfg, state) {
|
|
564
|
+
const tag = el.tagName.toLowerCase();
|
|
565
|
+
if (EXCLUDED_TAGS.has(tag)) return false;
|
|
566
|
+
if (el.getAttribute('aria-hidden') === 'true') return false;
|
|
567
|
+
if (!isVisible(el, state)) return false;
|
|
568
|
+
if (cfg.filter !== 'all') {
|
|
569
|
+
const r = getCachedBoundingRect(el, state);
|
|
570
|
+
if (!(
|
|
571
|
+
r.top < window.innerHeight &&
|
|
572
|
+
r.bottom > 0 &&
|
|
573
|
+
r.left < window.innerWidth &&
|
|
574
|
+
r.right > 0
|
|
575
|
+
))
|
|
576
|
+
return false;
|
|
577
|
+
}
|
|
578
|
+
if (cfg.filter === 'interactive') return getCachedInteractive(el, state);
|
|
579
|
+
if (getCachedInteractive(el, state)) return true;
|
|
580
|
+
if (isStructural(el)) return true;
|
|
581
|
+
if (getCachedLabel(el, state).length > 0) return true;
|
|
582
|
+
return isFormishContainer(el);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Generate a fairly stable CSS selector
|
|
587
|
+
* @param {Element} el
|
|
588
|
+
* @returns {string}
|
|
589
|
+
*/
|
|
590
|
+
function generateSelector(el) {
|
|
591
|
+
if (!(el instanceof Element)) return '';
|
|
592
|
+
if (/** @type {HTMLElement} */ (el).id) {
|
|
593
|
+
const idSel = `#${CSS.escape(/** @type {HTMLElement} */ (el).id)}`;
|
|
594
|
+
if (document.querySelectorAll(idSel).length === 1) return idSel;
|
|
595
|
+
}
|
|
596
|
+
for (const attr of SELECTOR_IDENTITY_ATTRS) {
|
|
597
|
+
const attrValue = el.getAttribute(attr);
|
|
598
|
+
if (attrValue) {
|
|
599
|
+
const s = `[${attr}="${CSS.escape(attrValue)}"]`;
|
|
600
|
+
if (document.querySelectorAll(s).length === 1) return s;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
let path = '';
|
|
604
|
+
let current = el;
|
|
605
|
+
while (current && current.nodeType === Node.ELEMENT_NODE && current.tagName !== 'BODY') {
|
|
606
|
+
let selector = current.tagName.toLowerCase();
|
|
607
|
+
const parent = current.parentElement;
|
|
608
|
+
if (parent) {
|
|
609
|
+
const siblings = Array.from(parent.children).filter(
|
|
610
|
+
(child) => child.tagName === current.tagName,
|
|
611
|
+
);
|
|
612
|
+
if (siblings.length > 1) {
|
|
613
|
+
const index = siblings.indexOf(current) + 1;
|
|
614
|
+
selector += `:nth-of-type(${index})`;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
path = path ? `${selector} > ${path}` : selector;
|
|
618
|
+
current = parent;
|
|
619
|
+
}
|
|
620
|
+
return path ? `body > ${path}` : 'body';
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Traverse DOM and build pageContent lines; collect ref map for interactive nodes.
|
|
625
|
+
* @param {Element} el
|
|
626
|
+
* @param {number} depth
|
|
627
|
+
* @param {{filter?: 'all'|'interactive', maxDepth?: number}} cfg
|
|
628
|
+
* @param {string[]} out
|
|
629
|
+
* @param {Array<{ref:string, selector:string, rect:{x:number,y:number,width:number,height:number}}>} refMap
|
|
630
|
+
*/
|
|
631
|
+
function traverse(el, depth, cfg, out, refMap, state) {
|
|
632
|
+
const maxDepth = cfg && typeof cfg.maxDepth === 'number' ? cfg.maxDepth : MAX_DEPTH;
|
|
633
|
+
if (depth > maxDepth || !el || !el.tagName) return;
|
|
634
|
+
if (state.processed >= MAX_NODES) return;
|
|
635
|
+
if (state.visited.has(el)) return;
|
|
636
|
+
state.visited.add(el);
|
|
637
|
+
const include = shouldInclude(el, cfg, state) || depth === 0;
|
|
638
|
+
if (include) {
|
|
639
|
+
const role = inferRole(el);
|
|
640
|
+
let label = getCachedLabel(el, state);
|
|
641
|
+
const refId = getOrAssignElementRef(el);
|
|
642
|
+
const rect = getCachedBoundingRect(el, state);
|
|
643
|
+
const cx = Math.round(rect.left + rect.width / 2);
|
|
644
|
+
const cy = Math.round(rect.top + rect.height / 2);
|
|
645
|
+
let line = `${' '.repeat(depth)}- ${role}`;
|
|
646
|
+
if (label) {
|
|
647
|
+
label = label.replace(/\s+/g, ' ').substring(0, MAX_LINE_LABEL);
|
|
648
|
+
line += ` "${label.replace(/"/g, '\\"')}"`;
|
|
649
|
+
}
|
|
650
|
+
line += ` [ref=${refId}] (x=${cx},y=${cy})`;
|
|
651
|
+
if (/** @type {HTMLElement} */ (el).id) line += ` id="${/** @type {HTMLElement} */ (el).id}"`;
|
|
652
|
+
const href = el.getAttribute('href');
|
|
653
|
+
if (href) line += ` href="${href}"`;
|
|
654
|
+
const type = el.getAttribute('type');
|
|
655
|
+
if (type) line += ` type="${type}"`;
|
|
656
|
+
const placeholder = el.getAttribute('placeholder');
|
|
657
|
+
if (placeholder) line += ` placeholder="${placeholder}"`;
|
|
658
|
+
// Surface disabled/pointer-events for better agent judgement
|
|
659
|
+
try {
|
|
660
|
+
const disabled = el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true';
|
|
661
|
+
if (disabled) line += ` disabled`;
|
|
662
|
+
const cs = getCachedComputedStyle(el, state);
|
|
663
|
+
if (cs && cs.pointerEvents === 'none') line += ` pe=none`;
|
|
664
|
+
} catch (_) {
|
|
665
|
+
/* ignore style issues */
|
|
666
|
+
}
|
|
667
|
+
out.push(line);
|
|
668
|
+
state.included++;
|
|
669
|
+
state.processed++;
|
|
670
|
+
|
|
671
|
+
// Only collect ref mapping for interactive elements to limit cost
|
|
672
|
+
if (getCachedInteractive(el, state) && refMap.length < REF_MAP_LIMIT) {
|
|
673
|
+
refMap.push({
|
|
674
|
+
ref: /** @type {string} */ (refId),
|
|
675
|
+
selector: generateSelector(el),
|
|
676
|
+
rect: {
|
|
677
|
+
x: rect.x,
|
|
678
|
+
y: rect.y,
|
|
679
|
+
width: rect.width,
|
|
680
|
+
height: rect.height,
|
|
681
|
+
},
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
if (state.processed >= MAX_NODES) return;
|
|
686
|
+
// Traverse light DOM children
|
|
687
|
+
if (/** @type {HTMLElement} */ (el).children && depth < maxDepth) {
|
|
688
|
+
const children = /** @type {HTMLElement} */ (el).children;
|
|
689
|
+
for (let i = 0; i < children.length; i++) {
|
|
690
|
+
if (state.processed >= MAX_NODES) break;
|
|
691
|
+
traverse(children[i], include ? depth + 1 : depth, cfg, out, refMap, state);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
// Traverse shadow DOM roots (limited by maxDepth and MAX_NODES)
|
|
695
|
+
try {
|
|
696
|
+
const anyEl = /** @type {any} */ (el);
|
|
697
|
+
if (anyEl && anyEl.shadowRoot && depth < maxDepth) {
|
|
698
|
+
const srChildren = anyEl.shadowRoot.children || [];
|
|
699
|
+
for (let i = 0; i < srChildren.length; i++) {
|
|
700
|
+
if (state.processed >= MAX_NODES) break;
|
|
701
|
+
traverse(srChildren[i], include ? depth + 1 : depth, cfg, out, refMap, state);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
} catch (_) {
|
|
705
|
+
/* ignore shadow errors */
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* Generate tree and return
|
|
711
|
+
* @param {'all'|'interactive'|null} filter
|
|
712
|
+
* @param {{maxDepth?: number, refId?: string}|undefined} options
|
|
713
|
+
*/
|
|
714
|
+
function __generateAccessibilityTree(filter, options) {
|
|
715
|
+
try {
|
|
716
|
+
const start = performance && performance.now ? performance.now() : Date.now();
|
|
717
|
+
const out = [];
|
|
718
|
+
const cfg = { filter: filter || undefined };
|
|
719
|
+
|
|
720
|
+
// Clamp maxDepth to MAX_DEPTH to keep costs bounded
|
|
721
|
+
if (options && Number.isFinite(options.maxDepth)) {
|
|
722
|
+
const d = Math.max(0, Math.floor(Number(options.maxDepth)));
|
|
723
|
+
cfg.maxDepth = Math.min(d, MAX_DEPTH);
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const refMap = [];
|
|
727
|
+
const state = {
|
|
728
|
+
processed: 0,
|
|
729
|
+
included: 0,
|
|
730
|
+
visited: new WeakSet(),
|
|
731
|
+
styleCache: new WeakMap(),
|
|
732
|
+
rectCache: new WeakMap(),
|
|
733
|
+
labelCache: new WeakMap(),
|
|
734
|
+
interactiveCache: new WeakMap(),
|
|
735
|
+
};
|
|
736
|
+
|
|
737
|
+
syncAndPruneElementRefs();
|
|
738
|
+
|
|
739
|
+
// Determine root element (body or refId-specified element)
|
|
740
|
+
let focus = null;
|
|
741
|
+
let root = document.body;
|
|
742
|
+
if (options && options.refId) {
|
|
743
|
+
const refIdStr = String(options.refId || '').trim();
|
|
744
|
+
if (refIdStr) {
|
|
745
|
+
const el = resolveRef(refIdStr);
|
|
746
|
+
if (!el || !(el instanceof Element)) {
|
|
747
|
+
return { error: `ref "${refIdStr}" not found or expired` };
|
|
748
|
+
}
|
|
749
|
+
root = el;
|
|
750
|
+
focus = { refId: refIdStr };
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
if (root) traverse(root, 0, cfg, out, refMap, state);
|
|
755
|
+
const pageContent = out.filter((line) => !EMPTY_GENERIC_LINE_RE.test(line)).join('\n');
|
|
756
|
+
const end = performance && performance.now ? performance.now() : Date.now();
|
|
757
|
+
return {
|
|
758
|
+
pageContent,
|
|
759
|
+
focus,
|
|
760
|
+
viewport: {
|
|
761
|
+
width: window.innerWidth,
|
|
762
|
+
height: window.innerHeight,
|
|
763
|
+
dpr: window.devicePixelRatio || 1,
|
|
764
|
+
},
|
|
765
|
+
stats: {
|
|
766
|
+
processed: state.processed,
|
|
767
|
+
included: state.included,
|
|
768
|
+
durationMs: Math.round(end - start),
|
|
769
|
+
},
|
|
770
|
+
refMap,
|
|
771
|
+
};
|
|
772
|
+
} catch (err) {
|
|
773
|
+
throw new Error(
|
|
774
|
+
'Error generating accessibility tree: ' +
|
|
775
|
+
(err && err.message ? err.message : 'Unknown error'),
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// Expose API on window
|
|
781
|
+
window.__generateAccessibilityTree = __generateAccessibilityTree;
|
|
782
|
+
|
|
783
|
+
// ============================================================================
|
|
784
|
+
// Hover for Ref (DOM Fallback Support)
|
|
785
|
+
// ============================================================================
|
|
786
|
+
|
|
787
|
+
async function handleHoverForRef(ref) {
|
|
788
|
+
if (!ref) return { success: false, error: 'ref is required' };
|
|
789
|
+
const el = resolveRef(ref);
|
|
790
|
+
if (el) {
|
|
791
|
+
dispatchHoverEvents(el);
|
|
792
|
+
return { success: true, target: summarizeElement(el) };
|
|
793
|
+
}
|
|
794
|
+
return await forwardHoverRefToChildren(ref);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function resolveRef(ref) {
|
|
798
|
+
const map = window.__mcpElementMap || window.__claudeElementMap || {};
|
|
799
|
+
const weak = Object.prototype.hasOwnProperty.call(map, ref) ? map[ref] : null;
|
|
800
|
+
return weak && typeof weak.deref === 'function' ? weak.deref() : null;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function dispatchHoverEvents(el) {
|
|
804
|
+
const rect = el.getBoundingClientRect();
|
|
805
|
+
const center = {
|
|
806
|
+
x: Math.round(rect.left + rect.width / 2),
|
|
807
|
+
y: Math.round(rect.top + rect.height / 2),
|
|
808
|
+
};
|
|
809
|
+
['mousemove', 'mouseover', 'mouseenter'].forEach((type) => {
|
|
810
|
+
el.dispatchEvent(
|
|
811
|
+
new MouseEvent(type, {
|
|
812
|
+
bubbles: true,
|
|
813
|
+
cancelable: true,
|
|
814
|
+
clientX: center.x,
|
|
815
|
+
clientY: center.y,
|
|
816
|
+
view: window,
|
|
817
|
+
}),
|
|
818
|
+
);
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
function summarizeElement(el) {
|
|
823
|
+
return {
|
|
824
|
+
tagName: el.tagName,
|
|
825
|
+
id: el.id || '',
|
|
826
|
+
className: el.className || '',
|
|
827
|
+
text: (el.textContent || '').trim().slice(0, 100),
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
let activePickerCancel = null;
|
|
832
|
+
|
|
833
|
+
function resolveFrameTargetOrigin(frame, contentWindow) {
|
|
834
|
+
try {
|
|
835
|
+
const origin = contentWindow?.location?.origin;
|
|
836
|
+
if (origin && origin !== 'null' && /^https?:\/\//i.test(origin)) {
|
|
837
|
+
return origin;
|
|
838
|
+
}
|
|
839
|
+
} catch {}
|
|
840
|
+
try {
|
|
841
|
+
const src =
|
|
842
|
+
(typeof frame?.getAttribute === 'function' && frame.getAttribute('src')) || frame?.src;
|
|
843
|
+
if (src) {
|
|
844
|
+
const parsed = new URL(src, location.href);
|
|
845
|
+
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
|
|
846
|
+
return parsed.origin;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
} catch {}
|
|
850
|
+
return '*';
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
function forwardHoverRefToChildren(ref) {
|
|
854
|
+
return new Promise((resolve) => {
|
|
855
|
+
const frames = Array.from(document.querySelectorAll('iframe, frame'));
|
|
856
|
+
const targetEntries = [];
|
|
857
|
+
const targetWindows = new Set();
|
|
858
|
+
for (const frame of frames) {
|
|
859
|
+
try {
|
|
860
|
+
const contentWindow = frame && frame.contentWindow;
|
|
861
|
+
if (contentWindow && !targetWindows.has(contentWindow)) {
|
|
862
|
+
targetWindows.add(contentWindow);
|
|
863
|
+
targetEntries.push({ frame, contentWindow });
|
|
864
|
+
}
|
|
865
|
+
} catch {}
|
|
866
|
+
}
|
|
867
|
+
if (targetWindows.size === 0) {
|
|
868
|
+
resolve({ success: false, error: `ref "${ref}" not found` });
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
const reqId = `hover_ref_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
872
|
+
const respondedWindows = new Set();
|
|
873
|
+
let lastErrorResult = null;
|
|
874
|
+
let settled = false;
|
|
875
|
+
let timeoutHandle = null;
|
|
876
|
+
|
|
877
|
+
const settle = (result) => {
|
|
878
|
+
if (settled) return;
|
|
879
|
+
settled = true;
|
|
880
|
+
window.removeEventListener('message', listener, true);
|
|
881
|
+
if (timeoutHandle !== null) {
|
|
882
|
+
clearTimeout(timeoutHandle);
|
|
883
|
+
timeoutHandle = null;
|
|
884
|
+
}
|
|
885
|
+
resolve(result);
|
|
886
|
+
};
|
|
887
|
+
|
|
888
|
+
const listener = (ev) => {
|
|
889
|
+
if (settled) return;
|
|
890
|
+
const data = ev?.data;
|
|
891
|
+
if (!data || data.type !== 'rr-bridge-hover-ref-result' || data.reqId !== reqId) return;
|
|
892
|
+
// Verify response comes from one of the targeted child frames
|
|
893
|
+
if (!targetWindows.has(ev.source)) return;
|
|
894
|
+
if (data.result?.success) {
|
|
895
|
+
settle(data.result);
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
respondedWindows.add(ev.source);
|
|
899
|
+
lastErrorResult = data.result || {
|
|
900
|
+
success: false,
|
|
901
|
+
error: `ref "${ref}" not found in child frame`,
|
|
902
|
+
};
|
|
903
|
+
if (respondedWindows.size >= targetWindows.size) {
|
|
904
|
+
settle(lastErrorResult);
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
window.addEventListener('message', listener, true);
|
|
908
|
+
timeoutHandle = setTimeout(() => {
|
|
909
|
+
settle(
|
|
910
|
+
lastErrorResult || { success: false, error: `ref "${ref}" not found in child frames` },
|
|
911
|
+
);
|
|
912
|
+
}, 1500);
|
|
913
|
+
for (const { frame, contentWindow } of targetEntries) {
|
|
914
|
+
try {
|
|
915
|
+
const targetOrigin = resolveFrameTargetOrigin(frame, contentWindow);
|
|
916
|
+
contentWindow.postMessage({ type: 'rr-bridge-hover-ref', reqId, ref }, targetOrigin);
|
|
917
|
+
} catch {
|
|
918
|
+
respondedWindows.add(contentWindow);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
if (respondedWindows.size >= targetWindows.size) {
|
|
922
|
+
settle(
|
|
923
|
+
lastErrorResult || { success: false, error: `ref "${ref}" not found in child frames` },
|
|
924
|
+
);
|
|
925
|
+
}
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// Chrome message bridge for ping and tree generation
|
|
930
|
+
chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
|
|
931
|
+
if (!request || typeof request !== 'object') return false;
|
|
932
|
+
try {
|
|
933
|
+
if (
|
|
934
|
+
request &&
|
|
935
|
+
(request.action === 'chrome_read_page_ping' ||
|
|
936
|
+
String(request.action || '').startsWith('mcp_ping_'))
|
|
937
|
+
) {
|
|
938
|
+
sendResponse({ status: 'pong' });
|
|
939
|
+
return false;
|
|
940
|
+
}
|
|
941
|
+
if (request && request.action === 'rr_overlay') {
|
|
942
|
+
try {
|
|
943
|
+
const cmd = request.cmd || 'init';
|
|
944
|
+
let root = document.getElementById('__rr_overlay_root');
|
|
945
|
+
if (!root) {
|
|
946
|
+
root = document.createElement('div');
|
|
947
|
+
root.id = '__rr_overlay_root';
|
|
948
|
+
Object.assign(root.style, {
|
|
949
|
+
position: 'fixed',
|
|
950
|
+
right: '8px',
|
|
951
|
+
bottom: '8px',
|
|
952
|
+
zIndex: 2_147_483_647,
|
|
953
|
+
maxWidth: '40vw',
|
|
954
|
+
maxHeight: '40vh',
|
|
955
|
+
overflow: 'auto',
|
|
956
|
+
background: 'rgba(0,0,0,0.6)',
|
|
957
|
+
color: '#fff',
|
|
958
|
+
fontFamily:
|
|
959
|
+
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
|
960
|
+
fontSize: '12px',
|
|
961
|
+
padding: '8px',
|
|
962
|
+
borderRadius: '6px',
|
|
963
|
+
boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
|
|
964
|
+
});
|
|
965
|
+
const title = document.createElement('div');
|
|
966
|
+
title.textContent = 'Record-Replay Execution Log';
|
|
967
|
+
Object.assign(title.style, { fontWeight: 'bold', marginBottom: '6px' });
|
|
968
|
+
const body = document.createElement('div');
|
|
969
|
+
body.id = '__rr_overlay_body';
|
|
970
|
+
root.appendChild(title);
|
|
971
|
+
root.appendChild(body);
|
|
972
|
+
document.documentElement.appendChild(root);
|
|
973
|
+
}
|
|
974
|
+
const body = document.getElementById('__rr_overlay_body');
|
|
975
|
+
if (cmd === 'append' && body) {
|
|
976
|
+
const line = document.createElement('div');
|
|
977
|
+
line.textContent = String(request.text || '');
|
|
978
|
+
body.appendChild(line);
|
|
979
|
+
body.scrollTop = body.scrollHeight;
|
|
980
|
+
}
|
|
981
|
+
if (cmd === 'done' && root) {
|
|
982
|
+
root.style.opacity = '0.5';
|
|
983
|
+
}
|
|
984
|
+
sendResponse({ success: true });
|
|
985
|
+
return false;
|
|
986
|
+
} catch (e) {
|
|
987
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
988
|
+
return false;
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
// Element picker: start a temporary overlay to let user pick an element
|
|
992
|
+
if (request && request.action === 'rr_picker_start') {
|
|
993
|
+
let responded = false;
|
|
994
|
+
const respondOnce = (payload) => {
|
|
995
|
+
if (responded) return;
|
|
996
|
+
responded = true;
|
|
997
|
+
try {
|
|
998
|
+
sendResponse(payload);
|
|
999
|
+
} catch {}
|
|
1000
|
+
};
|
|
1001
|
+
try {
|
|
1002
|
+
if (typeof activePickerCancel === 'function') {
|
|
1003
|
+
try {
|
|
1004
|
+
activePickerCancel('preempted');
|
|
1005
|
+
} catch {}
|
|
1006
|
+
activePickerCancel = null;
|
|
1007
|
+
}
|
|
1008
|
+
// state
|
|
1009
|
+
const state = { active: true };
|
|
1010
|
+
const hostId = '__rr_picker_host__';
|
|
1011
|
+
let host = document.getElementById(hostId);
|
|
1012
|
+
if (host) host.remove();
|
|
1013
|
+
host = document.createElement('div');
|
|
1014
|
+
host.id = hostId;
|
|
1015
|
+
Object.assign(host.style, {
|
|
1016
|
+
position: 'fixed',
|
|
1017
|
+
inset: '0',
|
|
1018
|
+
zIndex: 2147483646,
|
|
1019
|
+
cursor: 'crosshair',
|
|
1020
|
+
background: 'rgba(0,0,0,0.0)',
|
|
1021
|
+
});
|
|
1022
|
+
const box = document.createElement('div');
|
|
1023
|
+
Object.assign(box.style, {
|
|
1024
|
+
position: 'fixed',
|
|
1025
|
+
border: '2px solid #3b82f6',
|
|
1026
|
+
background: 'rgba(59,130,246,0.15)',
|
|
1027
|
+
pointerEvents: 'none',
|
|
1028
|
+
});
|
|
1029
|
+
const tip = document.createElement('div');
|
|
1030
|
+
tip.textContent = 'Click to select element (Esc to cancel)';
|
|
1031
|
+
Object.assign(tip.style, {
|
|
1032
|
+
position: 'fixed',
|
|
1033
|
+
top: '10px',
|
|
1034
|
+
left: '10px',
|
|
1035
|
+
background: 'rgba(0,0,0,0.7)',
|
|
1036
|
+
color: '#fff',
|
|
1037
|
+
padding: '6px 10px',
|
|
1038
|
+
borderRadius: '6px',
|
|
1039
|
+
fontSize: '12px',
|
|
1040
|
+
fontFamily: 'system-ui,-apple-system,Segoe UI,Roboto,Arial',
|
|
1041
|
+
});
|
|
1042
|
+
host.appendChild(box);
|
|
1043
|
+
host.appendChild(tip);
|
|
1044
|
+
document.documentElement.appendChild(host);
|
|
1045
|
+
|
|
1046
|
+
const cleanup = () => {
|
|
1047
|
+
try {
|
|
1048
|
+
host.remove();
|
|
1049
|
+
} catch {}
|
|
1050
|
+
try {
|
|
1051
|
+
document.removeEventListener('mousemove', onMove, true);
|
|
1052
|
+
} catch {}
|
|
1053
|
+
try {
|
|
1054
|
+
document.removeEventListener('click', onClick, true);
|
|
1055
|
+
} catch {}
|
|
1056
|
+
try {
|
|
1057
|
+
document.removeEventListener('keydown', onKey, true);
|
|
1058
|
+
} catch {}
|
|
1059
|
+
state.active = false;
|
|
1060
|
+
if (activePickerCancel === cancelPicker) {
|
|
1061
|
+
activePickerCancel = null;
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
const cancelPicker = (reason) => {
|
|
1066
|
+
cleanup();
|
|
1067
|
+
respondOnce({ success: false, cancelled: true, reason });
|
|
1068
|
+
};
|
|
1069
|
+
|
|
1070
|
+
const onMove = (e) => {
|
|
1071
|
+
if (!state.active) return;
|
|
1072
|
+
const el = e.target instanceof Element ? e.target : null;
|
|
1073
|
+
if (!el) return;
|
|
1074
|
+
try {
|
|
1075
|
+
const r = el.getBoundingClientRect();
|
|
1076
|
+
Object.assign(box.style, {
|
|
1077
|
+
left: `${Math.round(r.left)}px`,
|
|
1078
|
+
top: `${Math.round(r.top)}px`,
|
|
1079
|
+
width: `${Math.round(Math.max(0, r.width))}px`,
|
|
1080
|
+
height: `${Math.round(Math.max(0, r.height))}px`,
|
|
1081
|
+
display: r.width > 0 && r.height > 0 ? 'block' : 'none',
|
|
1082
|
+
});
|
|
1083
|
+
} catch {}
|
|
1084
|
+
};
|
|
1085
|
+
const uniqueClassSelector = (node) => {
|
|
1086
|
+
try {
|
|
1087
|
+
const classes = Array.from(node.classList || []).filter(
|
|
1088
|
+
(c) => c && /^[a-zA-Z0-9_-]+$/.test(c),
|
|
1089
|
+
);
|
|
1090
|
+
for (const cls of classes) {
|
|
1091
|
+
const sel = `.${CSS.escape(cls)}`;
|
|
1092
|
+
if (document.querySelectorAll(sel).length === 1) return sel;
|
|
1093
|
+
}
|
|
1094
|
+
const tag = node.tagName ? node.tagName.toLowerCase() : '';
|
|
1095
|
+
for (const cls of classes) {
|
|
1096
|
+
const sel = `${tag}.${CSS.escape(cls)}`;
|
|
1097
|
+
if (document.querySelectorAll(sel).length === 1) return sel;
|
|
1098
|
+
}
|
|
1099
|
+
for (let i = 0; i < Math.min(classes.length, 3); i++) {
|
|
1100
|
+
for (let j = i + 1; j < Math.min(classes.length, 3); j++) {
|
|
1101
|
+
const sel = `.${CSS.escape(classes[i])}.${CSS.escape(classes[j])}`;
|
|
1102
|
+
if (document.querySelectorAll(sel).length === 1) return sel;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
} catch {}
|
|
1106
|
+
return '';
|
|
1107
|
+
};
|
|
1108
|
+
const computeCandidates = (el) => {
|
|
1109
|
+
const cands = [];
|
|
1110
|
+
// css by id / class / short path
|
|
1111
|
+
if (el.id) {
|
|
1112
|
+
const idSel = `#${CSS.escape(el.id)}`;
|
|
1113
|
+
if (document.querySelectorAll(idSel).length === 1)
|
|
1114
|
+
cands.push({ type: 'css', value: idSel });
|
|
1115
|
+
}
|
|
1116
|
+
const classSel = uniqueClassSelector(el);
|
|
1117
|
+
if (classSel) cands.push({ type: 'css', value: classSel });
|
|
1118
|
+
// data-* and name
|
|
1119
|
+
for (const attr of ['data-testid', 'data-cy', 'name']) {
|
|
1120
|
+
const val = el.getAttribute(attr);
|
|
1121
|
+
if (val) {
|
|
1122
|
+
const s = `[${attr}="${CSS.escape(val)}"]`;
|
|
1123
|
+
if (document.querySelectorAll(s).length === 1)
|
|
1124
|
+
cands.push({ type: 'attr', value: s });
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
// aria
|
|
1128
|
+
const aria = el.getAttribute && el.getAttribute('aria-label');
|
|
1129
|
+
if (aria) cands.push({ type: 'aria', value: `textbox[name=${aria}]` });
|
|
1130
|
+
// text for clickable
|
|
1131
|
+
const tag = (el.tagName || '').toLowerCase();
|
|
1132
|
+
if (['button', 'a', 'summary'].includes(tag)) {
|
|
1133
|
+
const text = (el.textContent || '').trim();
|
|
1134
|
+
if (text) cands.push({ type: 'text', value: text.substring(0, 64) });
|
|
1135
|
+
}
|
|
1136
|
+
// fallback path selector
|
|
1137
|
+
const gen = (node) => {
|
|
1138
|
+
if (!(node instanceof Element)) return '';
|
|
1139
|
+
let path = '';
|
|
1140
|
+
let current = node;
|
|
1141
|
+
while (
|
|
1142
|
+
current &&
|
|
1143
|
+
current.nodeType === Node.ELEMENT_NODE &&
|
|
1144
|
+
current.tagName !== 'BODY'
|
|
1145
|
+
) {
|
|
1146
|
+
let sel = current.tagName.toLowerCase();
|
|
1147
|
+
const parent = current.parentElement;
|
|
1148
|
+
if (parent) {
|
|
1149
|
+
const siblings = Array.from(parent.children).filter(
|
|
1150
|
+
(child) => child.tagName === current.tagName,
|
|
1151
|
+
);
|
|
1152
|
+
if (siblings.length > 1) {
|
|
1153
|
+
const index = siblings.indexOf(current) + 1;
|
|
1154
|
+
sel += `:nth-of-type(${index})`;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
path = path ? `${sel} > ${path}` : sel;
|
|
1158
|
+
current = parent;
|
|
1159
|
+
}
|
|
1160
|
+
return path ? `body > ${path}` : 'body';
|
|
1161
|
+
};
|
|
1162
|
+
const pathSel = gen(el);
|
|
1163
|
+
if (pathSel) cands.push({ type: 'css', value: pathSel });
|
|
1164
|
+
return cands;
|
|
1165
|
+
};
|
|
1166
|
+
const onClick = (e) => {
|
|
1167
|
+
if (!state.active) return;
|
|
1168
|
+
e.preventDefault();
|
|
1169
|
+
e.stopPropagation();
|
|
1170
|
+
const el = e.target instanceof Element ? e.target : null;
|
|
1171
|
+
if (!el) {
|
|
1172
|
+
cleanup();
|
|
1173
|
+
respondOnce({ success: false, error: 'no element' });
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
// create ref
|
|
1177
|
+
let refId = null;
|
|
1178
|
+
try {
|
|
1179
|
+
refId = getOrAssignElementRef(el);
|
|
1180
|
+
} catch {}
|
|
1181
|
+
const cands = computeCandidates(el);
|
|
1182
|
+
cleanup();
|
|
1183
|
+
respondOnce({ success: true, ref: refId, candidates: cands });
|
|
1184
|
+
};
|
|
1185
|
+
const onKey = (e) => {
|
|
1186
|
+
if (e.key === 'Escape') {
|
|
1187
|
+
cleanup();
|
|
1188
|
+
respondOnce({ success: false, cancelled: true });
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
activePickerCancel = cancelPicker;
|
|
1192
|
+
document.addEventListener('mousemove', onMove, true);
|
|
1193
|
+
document.addEventListener('click', onClick, true);
|
|
1194
|
+
document.addEventListener('keydown', onKey, true);
|
|
1195
|
+
return true; // async
|
|
1196
|
+
} catch (e) {
|
|
1197
|
+
respondOnce({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1198
|
+
return false;
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
if (request && request.action === 'rr_picker_stop') {
|
|
1202
|
+
try {
|
|
1203
|
+
if (typeof activePickerCancel === 'function') {
|
|
1204
|
+
try {
|
|
1205
|
+
activePickerCancel('stopped');
|
|
1206
|
+
} catch {}
|
|
1207
|
+
activePickerCancel = null;
|
|
1208
|
+
}
|
|
1209
|
+
const host = document.getElementById('__rr_picker_host__');
|
|
1210
|
+
if (host) host.remove();
|
|
1211
|
+
sendResponse({ success: true });
|
|
1212
|
+
return false;
|
|
1213
|
+
} catch (e) {
|
|
1214
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1215
|
+
return false;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
if (request && request.action === 'generateAccessibilityTree') {
|
|
1219
|
+
const result = __generateAccessibilityTree(request.filter || null, {
|
|
1220
|
+
maxDepth: request.depth,
|
|
1221
|
+
refId: request.refId,
|
|
1222
|
+
});
|
|
1223
|
+
if (result && result.error) {
|
|
1224
|
+
sendResponse({ success: false, error: result.error });
|
|
1225
|
+
return false;
|
|
1226
|
+
}
|
|
1227
|
+
sendResponse({ success: true, ...result });
|
|
1228
|
+
return false;
|
|
1229
|
+
}
|
|
1230
|
+
if (request && request.action === 'ensureRefForSelector') {
|
|
1231
|
+
try {
|
|
1232
|
+
// Composite selector support: "frameSelector |> innerSelector"
|
|
1233
|
+
const maybeSel = String(request.selector || '').trim();
|
|
1234
|
+
const allowMultiple = !!request.allowMultiple;
|
|
1235
|
+
if (maybeSel.includes('|>')) {
|
|
1236
|
+
try {
|
|
1237
|
+
const parts = maybeSel
|
|
1238
|
+
.split('|>')
|
|
1239
|
+
.map((s) => s.trim())
|
|
1240
|
+
.filter(Boolean);
|
|
1241
|
+
if (parts.length >= 2) {
|
|
1242
|
+
const frameSel = parts[0];
|
|
1243
|
+
const innerSel = parts.slice(1).join(' |> ');
|
|
1244
|
+
// Find target frame element in current document
|
|
1245
|
+
let frameEl = null;
|
|
1246
|
+
try {
|
|
1247
|
+
frameEl = querySelectorDeepFirst(frameSel) || document.querySelector(frameSel);
|
|
1248
|
+
} catch {}
|
|
1249
|
+
if (
|
|
1250
|
+
!frameEl ||
|
|
1251
|
+
!(frameEl instanceof HTMLIFrameElement || frameEl instanceof HTMLFrameElement)
|
|
1252
|
+
) {
|
|
1253
|
+
sendResponse({
|
|
1254
|
+
success: false,
|
|
1255
|
+
error: `Composite frame selector not found: ${frameSel}`,
|
|
1256
|
+
});
|
|
1257
|
+
return false;
|
|
1258
|
+
}
|
|
1259
|
+
const cw = frameEl.contentWindow;
|
|
1260
|
+
if (!cw) {
|
|
1261
|
+
sendResponse({
|
|
1262
|
+
success: false,
|
|
1263
|
+
error: 'Unable to obtain contentWindow of target frame',
|
|
1264
|
+
});
|
|
1265
|
+
return false;
|
|
1266
|
+
}
|
|
1267
|
+
// Bridge to child frame via postMessage with timeout
|
|
1268
|
+
const reqId = `rrc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1269
|
+
const BRIDGE_TIMEOUT_MS = 5000; // 5 second timeout for iframe bridge
|
|
1270
|
+
let responded = false;
|
|
1271
|
+
let timeoutHandle = null;
|
|
1272
|
+
|
|
1273
|
+
const cleanup = () => {
|
|
1274
|
+
window.removeEventListener('message', listener, true);
|
|
1275
|
+
if (timeoutHandle) {
|
|
1276
|
+
clearTimeout(timeoutHandle);
|
|
1277
|
+
timeoutHandle = null;
|
|
1278
|
+
}
|
|
1279
|
+
};
|
|
1280
|
+
|
|
1281
|
+
const listener = (ev) => {
|
|
1282
|
+
try {
|
|
1283
|
+
const data = ev && ev.data;
|
|
1284
|
+
if (
|
|
1285
|
+
!data ||
|
|
1286
|
+
data.type !== 'rr-bridge-ensure-ref-result' ||
|
|
1287
|
+
data.reqId !== reqId
|
|
1288
|
+
)
|
|
1289
|
+
return;
|
|
1290
|
+
// Validate source is the expected frame (security check)
|
|
1291
|
+
if (ev.source !== cw) return;
|
|
1292
|
+
|
|
1293
|
+
if (responded) return; // Already timed out
|
|
1294
|
+
responded = true;
|
|
1295
|
+
cleanup();
|
|
1296
|
+
|
|
1297
|
+
if (data.success) {
|
|
1298
|
+
sendResponse({
|
|
1299
|
+
success: true,
|
|
1300
|
+
ref: data.ref,
|
|
1301
|
+
center: data.center,
|
|
1302
|
+
href: data.href,
|
|
1303
|
+
});
|
|
1304
|
+
} else {
|
|
1305
|
+
sendResponse({ success: false, error: data.error || 'child failed' });
|
|
1306
|
+
}
|
|
1307
|
+
} catch (e) {
|
|
1308
|
+
if (!responded) {
|
|
1309
|
+
responded = true;
|
|
1310
|
+
cleanup();
|
|
1311
|
+
sendResponse({
|
|
1312
|
+
success: false,
|
|
1313
|
+
error: String(e && e.message ? e.message : e),
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
};
|
|
1318
|
+
|
|
1319
|
+
// Set up timeout to prevent infinite wait
|
|
1320
|
+
timeoutHandle = setTimeout(() => {
|
|
1321
|
+
if (!responded) {
|
|
1322
|
+
responded = true;
|
|
1323
|
+
cleanup();
|
|
1324
|
+
sendResponse({
|
|
1325
|
+
success: false,
|
|
1326
|
+
error: `iframe bridge timeout after ${BRIDGE_TIMEOUT_MS}ms`,
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
}, BRIDGE_TIMEOUT_MS);
|
|
1330
|
+
|
|
1331
|
+
window.addEventListener('message', listener, true);
|
|
1332
|
+
cw.postMessage(
|
|
1333
|
+
{
|
|
1334
|
+
type: 'rr-bridge-ensure-ref',
|
|
1335
|
+
reqId,
|
|
1336
|
+
selector: innerSel,
|
|
1337
|
+
useText: !!request.useText,
|
|
1338
|
+
isXPath: !!request.isXPath,
|
|
1339
|
+
tagName: String(request.tagName || ''),
|
|
1340
|
+
allowMultiple: !!request.allowMultiple,
|
|
1341
|
+
},
|
|
1342
|
+
'*',
|
|
1343
|
+
);
|
|
1344
|
+
return true; // async response via message bridge
|
|
1345
|
+
}
|
|
1346
|
+
} catch (e) {
|
|
1347
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
// Support CSS selector, XPath, or visible text search
|
|
1352
|
+
const useText = !!request.useText;
|
|
1353
|
+
const textQuery = String(request.text || '').trim();
|
|
1354
|
+
const sel = String(request.selector || '').trim();
|
|
1355
|
+
const isXPath = !!request.isXPath;
|
|
1356
|
+
const limitTag = String(request.tagName || '')
|
|
1357
|
+
.trim()
|
|
1358
|
+
.toUpperCase();
|
|
1359
|
+
let el = null;
|
|
1360
|
+
if (useText && textQuery) {
|
|
1361
|
+
const normalize = (s) =>
|
|
1362
|
+
String(s || '')
|
|
1363
|
+
.replace(/\s+/g, ' ')
|
|
1364
|
+
.trim()
|
|
1365
|
+
.toLowerCase();
|
|
1366
|
+
const query = normalize(textQuery);
|
|
1367
|
+
const bigrams = (s) => {
|
|
1368
|
+
const arr = [];
|
|
1369
|
+
for (let i = 0; i < s.length - 1; i++) arr.push(s.slice(i, i + 2));
|
|
1370
|
+
return arr;
|
|
1371
|
+
};
|
|
1372
|
+
const dice = (a, b) => {
|
|
1373
|
+
if (!a || !b) return 0;
|
|
1374
|
+
const A = bigrams(a);
|
|
1375
|
+
const B = bigrams(b);
|
|
1376
|
+
if (A.length === 0 || B.length === 0) return 0;
|
|
1377
|
+
let inter = 0;
|
|
1378
|
+
const map = new Map();
|
|
1379
|
+
for (const t of A) map.set(t, (map.get(t) || 0) + 1);
|
|
1380
|
+
for (const t of B) {
|
|
1381
|
+
const c = map.get(t) || 0;
|
|
1382
|
+
if (c > 0) {
|
|
1383
|
+
inter++;
|
|
1384
|
+
map.set(t, c - 1);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
return (2 * inter) / (A.length + B.length);
|
|
1388
|
+
};
|
|
1389
|
+
let best = { el: null, score: 0 };
|
|
1390
|
+
// Deep traversal including shadow roots
|
|
1391
|
+
const stack = [document.documentElement];
|
|
1392
|
+
let visited = 0;
|
|
1393
|
+
while (stack.length) {
|
|
1394
|
+
const node = /** @type {any} */ (stack.pop());
|
|
1395
|
+
if (!node || !(node instanceof Element)) continue;
|
|
1396
|
+
try {
|
|
1397
|
+
if (limitTag && String(node.tagName || '').toUpperCase() !== limitTag) {
|
|
1398
|
+
// still traverse into children/shadow for performance? yes
|
|
1399
|
+
} else {
|
|
1400
|
+
const cs = window.getComputedStyle(node);
|
|
1401
|
+
if (cs.display === 'none' || cs.visibility === 'hidden' || cs.opacity === '0') {
|
|
1402
|
+
/* skip hidden */
|
|
1403
|
+
} else {
|
|
1404
|
+
const rect = /** @type {HTMLElement} */ (node).getBoundingClientRect();
|
|
1405
|
+
if (rect.width > 0 && rect.height > 0) {
|
|
1406
|
+
const txt = normalize(node.textContent || '');
|
|
1407
|
+
if (txt) {
|
|
1408
|
+
if (txt.includes(query)) {
|
|
1409
|
+
el = /** @type {Element} */ (node);
|
|
1410
|
+
break;
|
|
1411
|
+
}
|
|
1412
|
+
const sc = dice(txt, query);
|
|
1413
|
+
if (sc > best.score)
|
|
1414
|
+
best = { el: /** @type {Element} */ (node), score: sc };
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
} catch {}
|
|
1420
|
+
// push children and shadow children
|
|
1421
|
+
try {
|
|
1422
|
+
const children = node.children || [];
|
|
1423
|
+
for (let i = 0; i < children.length; i++) stack.push(children[i]);
|
|
1424
|
+
} catch {}
|
|
1425
|
+
try {
|
|
1426
|
+
const sr = node.shadowRoot;
|
|
1427
|
+
if (sr && sr.children) {
|
|
1428
|
+
for (let i = 0; i < sr.children.length; i++) stack.push(sr.children[i]);
|
|
1429
|
+
}
|
|
1430
|
+
} catch {}
|
|
1431
|
+
if (++visited > 8000) break;
|
|
1432
|
+
}
|
|
1433
|
+
if (!el && best.el && best.score >= 0.6) el = best.el;
|
|
1434
|
+
} else if (isXPath) {
|
|
1435
|
+
if (!sel) {
|
|
1436
|
+
sendResponse({ success: false, error: 'selector is required' });
|
|
1437
|
+
return false;
|
|
1438
|
+
}
|
|
1439
|
+
const result = queryXPathWithUniquenessCheck(sel, allowMultiple);
|
|
1440
|
+
if (result.error) {
|
|
1441
|
+
sendResponse({ success: false, error: result.error });
|
|
1442
|
+
return false;
|
|
1443
|
+
}
|
|
1444
|
+
if (result.matchCount === 0) {
|
|
1445
|
+
sendResponse({ success: false, error: `selector not found: ${sel}` });
|
|
1446
|
+
return false;
|
|
1447
|
+
}
|
|
1448
|
+
if (!allowMultiple && result.matchCount > 1) {
|
|
1449
|
+
sendResponse({
|
|
1450
|
+
success: false,
|
|
1451
|
+
error: `Selector "${sel}" matched multiple elements. Please refine the selector to match only one element.`,
|
|
1452
|
+
});
|
|
1453
|
+
return false;
|
|
1454
|
+
}
|
|
1455
|
+
el = result.element;
|
|
1456
|
+
} else {
|
|
1457
|
+
if (!sel) {
|
|
1458
|
+
sendResponse({ success: false, error: 'selector is required' });
|
|
1459
|
+
return false;
|
|
1460
|
+
}
|
|
1461
|
+
const result = querySelectorWithUniquenessCheck(sel, allowMultiple);
|
|
1462
|
+
if (result.error) {
|
|
1463
|
+
sendResponse({ success: false, error: result.error });
|
|
1464
|
+
return false;
|
|
1465
|
+
}
|
|
1466
|
+
if (result.matchCount === 0) {
|
|
1467
|
+
sendResponse({ success: false, error: `selector not found: ${sel}` });
|
|
1468
|
+
return false;
|
|
1469
|
+
}
|
|
1470
|
+
if (!allowMultiple && result.matchCount > 1) {
|
|
1471
|
+
sendResponse({
|
|
1472
|
+
success: false,
|
|
1473
|
+
error: `Selector "${sel}" matched multiple elements. Please refine the selector to match only one element.`,
|
|
1474
|
+
});
|
|
1475
|
+
return false;
|
|
1476
|
+
}
|
|
1477
|
+
el = result.element;
|
|
1478
|
+
}
|
|
1479
|
+
if (!el) {
|
|
1480
|
+
sendResponse({ success: false, error: `selector not found: ${sel}` });
|
|
1481
|
+
return false;
|
|
1482
|
+
}
|
|
1483
|
+
const refId = getOrAssignElementRef(el);
|
|
1484
|
+
const rect = /** @type {HTMLElement} */ (el).getBoundingClientRect();
|
|
1485
|
+
sendResponse({
|
|
1486
|
+
success: true,
|
|
1487
|
+
ref: refId,
|
|
1488
|
+
center: {
|
|
1489
|
+
x: Math.round(rect.left + rect.width / 2),
|
|
1490
|
+
y: Math.round(rect.top + rect.height / 2),
|
|
1491
|
+
},
|
|
1492
|
+
});
|
|
1493
|
+
return false;
|
|
1494
|
+
} catch (e) {
|
|
1495
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1496
|
+
return false;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
if (request && request.action === 'dispatchHoverForRef') {
|
|
1500
|
+
handleHoverForRef(String(request.ref || '').trim())
|
|
1501
|
+
.then((result) => sendResponse(result))
|
|
1502
|
+
.catch((error) =>
|
|
1503
|
+
sendResponse({ success: false, error: error?.message || String(error) }),
|
|
1504
|
+
);
|
|
1505
|
+
return true;
|
|
1506
|
+
}
|
|
1507
|
+
if (request && request.action === 'getAttributeForSelector') {
|
|
1508
|
+
try {
|
|
1509
|
+
const sel = String(request.selector || '').trim();
|
|
1510
|
+
const name = String(request.name || '').trim();
|
|
1511
|
+
if (!sel || !name) {
|
|
1512
|
+
sendResponse({ success: false, error: 'selector and name are required' });
|
|
1513
|
+
return false;
|
|
1514
|
+
}
|
|
1515
|
+
const el = document.querySelector(sel) || querySelectorDeepFirst(sel);
|
|
1516
|
+
if (!el) {
|
|
1517
|
+
sendResponse({ success: false, error: `selector not found: ${sel}` });
|
|
1518
|
+
return false;
|
|
1519
|
+
}
|
|
1520
|
+
let value = null;
|
|
1521
|
+
if (name === 'text' || name === 'textContent') {
|
|
1522
|
+
value = (el.textContent || '').trim();
|
|
1523
|
+
} else if (name === 'value') {
|
|
1524
|
+
try {
|
|
1525
|
+
value = /** @type {HTMLInputElement} */ (el).value ?? null;
|
|
1526
|
+
} catch (_) {
|
|
1527
|
+
value = el.getAttribute('value');
|
|
1528
|
+
}
|
|
1529
|
+
} else {
|
|
1530
|
+
value = el.getAttribute(name);
|
|
1531
|
+
}
|
|
1532
|
+
sendResponse({ success: true, value });
|
|
1533
|
+
return false;
|
|
1534
|
+
} catch (e) {
|
|
1535
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1536
|
+
return false;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
if (request && request.action === 'collectVariables') {
|
|
1540
|
+
try {
|
|
1541
|
+
let vars = Array.isArray(request.variables) ? request.variables : [];
|
|
1542
|
+
if ((!vars || vars.length === 0) && request.payload) {
|
|
1543
|
+
try {
|
|
1544
|
+
const p = JSON.parse(String(request.payload || '{}'));
|
|
1545
|
+
if (Array.isArray(p.variables)) vars = p.variables;
|
|
1546
|
+
} catch {}
|
|
1547
|
+
}
|
|
1548
|
+
const useOverlay = request.useOverlay !== false; // default true
|
|
1549
|
+
const values = {};
|
|
1550
|
+
if (!useOverlay) {
|
|
1551
|
+
for (const v of vars) {
|
|
1552
|
+
const key = String(v && v.key ? v.key : '');
|
|
1553
|
+
if (!key) continue;
|
|
1554
|
+
const label = v.label || key;
|
|
1555
|
+
const def = v.default || '';
|
|
1556
|
+
const promptText = `Please enter parameter ${label} (${key})`;
|
|
1557
|
+
let val = window.prompt(promptText, def);
|
|
1558
|
+
if (typeof val !== 'string') val = def;
|
|
1559
|
+
values[key] = val;
|
|
1560
|
+
}
|
|
1561
|
+
sendResponse({ success: true, values });
|
|
1562
|
+
return false;
|
|
1563
|
+
}
|
|
1564
|
+
// Build overlay form
|
|
1565
|
+
const hostId = '__rr_var_overlay__';
|
|
1566
|
+
let host = document.getElementById(hostId);
|
|
1567
|
+
if (host) host.remove();
|
|
1568
|
+
host = document.createElement('div');
|
|
1569
|
+
host.id = hostId;
|
|
1570
|
+
Object.assign(host.style, {
|
|
1571
|
+
position: 'fixed',
|
|
1572
|
+
inset: '0',
|
|
1573
|
+
background: 'rgba(0,0,0,0.35)',
|
|
1574
|
+
zIndex: 2147483646,
|
|
1575
|
+
display: 'flex',
|
|
1576
|
+
alignItems: 'center',
|
|
1577
|
+
justifyContent: 'center',
|
|
1578
|
+
});
|
|
1579
|
+
const panel = document.createElement('div');
|
|
1580
|
+
Object.assign(panel.style, {
|
|
1581
|
+
background: '#fff',
|
|
1582
|
+
borderRadius: '8px',
|
|
1583
|
+
width: 'min(520px, 96vw)',
|
|
1584
|
+
maxHeight: '80vh',
|
|
1585
|
+
overflow: 'auto',
|
|
1586
|
+
boxShadow: '0 8px 24px rgba(0,0,0,0.2)',
|
|
1587
|
+
padding: '16px',
|
|
1588
|
+
fontFamily: 'system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif',
|
|
1589
|
+
});
|
|
1590
|
+
const title = document.createElement('div');
|
|
1591
|
+
title.textContent = 'Please enter replay parameters';
|
|
1592
|
+
Object.assign(title.style, { fontSize: '16px', fontWeight: '600', marginBottom: '12px' });
|
|
1593
|
+
const form = document.createElement('form');
|
|
1594
|
+
for (const v of vars) {
|
|
1595
|
+
const row = document.createElement('div');
|
|
1596
|
+
Object.assign(row.style, { marginBottom: '10px' });
|
|
1597
|
+
const label = document.createElement('label');
|
|
1598
|
+
label.textContent = `${v.label || v.key}${v.sensitive ? ' (sensitive)' : ''}`;
|
|
1599
|
+
Object.assign(label.style, {
|
|
1600
|
+
display: 'block',
|
|
1601
|
+
marginBottom: '6px',
|
|
1602
|
+
fontWeight: '500',
|
|
1603
|
+
});
|
|
1604
|
+
const input = document.createElement('input');
|
|
1605
|
+
input.type = v.sensitive ? 'password' : 'text';
|
|
1606
|
+
input.name = String(v.key);
|
|
1607
|
+
input.value = String(v.default || '');
|
|
1608
|
+
Object.assign(input.style, {
|
|
1609
|
+
width: '100%',
|
|
1610
|
+
boxSizing: 'border-box',
|
|
1611
|
+
padding: '8px 10px',
|
|
1612
|
+
border: '1px solid #d0d7de',
|
|
1613
|
+
borderRadius: '6px',
|
|
1614
|
+
outline: 'none',
|
|
1615
|
+
});
|
|
1616
|
+
row.appendChild(label);
|
|
1617
|
+
row.appendChild(input);
|
|
1618
|
+
form.appendChild(row);
|
|
1619
|
+
}
|
|
1620
|
+
const actions = document.createElement('div');
|
|
1621
|
+
Object.assign(actions.style, { display: 'flex', gap: '8px', marginTop: '12px' });
|
|
1622
|
+
const ok = document.createElement('button');
|
|
1623
|
+
ok.type = 'submit';
|
|
1624
|
+
ok.textContent = 'OK';
|
|
1625
|
+
Object.assign(ok.style, {
|
|
1626
|
+
background: '#0969da',
|
|
1627
|
+
color: '#fff',
|
|
1628
|
+
border: 'none',
|
|
1629
|
+
padding: '8px 16px',
|
|
1630
|
+
borderRadius: '6px',
|
|
1631
|
+
cursor: 'pointer',
|
|
1632
|
+
});
|
|
1633
|
+
const cancel = document.createElement('button');
|
|
1634
|
+
cancel.type = 'button';
|
|
1635
|
+
cancel.textContent = 'Cancel';
|
|
1636
|
+
Object.assign(cancel.style, {
|
|
1637
|
+
background: '#f3f4f6',
|
|
1638
|
+
color: '#111',
|
|
1639
|
+
border: '1px solid #d0d7de',
|
|
1640
|
+
padding: '8px 16px',
|
|
1641
|
+
borderRadius: '6px',
|
|
1642
|
+
cursor: 'pointer',
|
|
1643
|
+
});
|
|
1644
|
+
actions.appendChild(ok);
|
|
1645
|
+
actions.appendChild(cancel);
|
|
1646
|
+
panel.appendChild(title);
|
|
1647
|
+
panel.appendChild(form);
|
|
1648
|
+
panel.appendChild(actions);
|
|
1649
|
+
host.appendChild(panel);
|
|
1650
|
+
document.documentElement.appendChild(host);
|
|
1651
|
+
|
|
1652
|
+
const cleanup = () => {
|
|
1653
|
+
try {
|
|
1654
|
+
host.remove();
|
|
1655
|
+
} catch {}
|
|
1656
|
+
};
|
|
1657
|
+
cancel.onclick = () => {
|
|
1658
|
+
cleanup();
|
|
1659
|
+
sendResponse({ success: false, cancelled: true });
|
|
1660
|
+
};
|
|
1661
|
+
form.onsubmit = (e) => {
|
|
1662
|
+
e.preventDefault();
|
|
1663
|
+
for (const v of vars) {
|
|
1664
|
+
const el = form.querySelector(`input[name="${CSS.escape(String(v.key))}"]`);
|
|
1665
|
+
if (el) values[v.key] = /** @type {HTMLInputElement} */ (el).value;
|
|
1666
|
+
}
|
|
1667
|
+
cleanup();
|
|
1668
|
+
sendResponse({ success: true, values });
|
|
1669
|
+
};
|
|
1670
|
+
return true; // async
|
|
1671
|
+
} catch (e) {
|
|
1672
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1673
|
+
return false;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
if (request && request.action === 'resolveRef') {
|
|
1677
|
+
const ref = request.ref;
|
|
1678
|
+
try {
|
|
1679
|
+
const map = window.__mcpElementMap || window.__claudeElementMap;
|
|
1680
|
+
const weak = map && map[ref];
|
|
1681
|
+
const el = weak && typeof weak.deref === 'function' ? weak.deref() : null;
|
|
1682
|
+
if (!el || !(el instanceof Element)) {
|
|
1683
|
+
sendResponse({ success: false, error: `ref "${ref}" not found or expired` });
|
|
1684
|
+
return false;
|
|
1685
|
+
}
|
|
1686
|
+
const rect = /** @type {HTMLElement} */ (el).getBoundingClientRect();
|
|
1687
|
+
sendResponse({
|
|
1688
|
+
success: true,
|
|
1689
|
+
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
1690
|
+
center: {
|
|
1691
|
+
x: Math.round(rect.left + rect.width / 2),
|
|
1692
|
+
y: Math.round(rect.top + rect.height / 2),
|
|
1693
|
+
},
|
|
1694
|
+
selector: (function () {
|
|
1695
|
+
// Simple selector generation inline to avoid duplication
|
|
1696
|
+
const generateSelector = function (node) {
|
|
1697
|
+
if (!(node instanceof Element)) return '';
|
|
1698
|
+
if (node.id) {
|
|
1699
|
+
const idSel = `#${CSS.escape(node.id)}`;
|
|
1700
|
+
if (document.querySelectorAll(idSel).length === 1) return idSel;
|
|
1701
|
+
}
|
|
1702
|
+
// prefer unique class selectors if available
|
|
1703
|
+
try {
|
|
1704
|
+
const classes = Array.from(node.classList || []).filter(
|
|
1705
|
+
(c) => c && /^[a-zA-Z0-9_-]+$/.test(c),
|
|
1706
|
+
);
|
|
1707
|
+
for (const cls of classes) {
|
|
1708
|
+
const sel = `.${CSS.escape(cls)}`;
|
|
1709
|
+
if (document.querySelectorAll(sel).length === 1) return sel;
|
|
1710
|
+
}
|
|
1711
|
+
const tag = node.tagName ? node.tagName.toLowerCase() : '';
|
|
1712
|
+
for (const cls of classes) {
|
|
1713
|
+
const sel = `${tag}.${CSS.escape(cls)}`;
|
|
1714
|
+
if (document.querySelectorAll(sel).length === 1) return sel;
|
|
1715
|
+
}
|
|
1716
|
+
for (let i = 0; i < Math.min(classes.length, 3); i++) {
|
|
1717
|
+
for (let j = i + 1; j < Math.min(classes.length, 3); j++) {
|
|
1718
|
+
const sel = `.${CSS.escape(classes[i])}.${CSS.escape(classes[j])}`;
|
|
1719
|
+
if (document.querySelectorAll(sel).length === 1) return sel;
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
} catch {}
|
|
1723
|
+
for (const attr of ['data-testid', 'data-cy', 'name']) {
|
|
1724
|
+
const val = node.getAttribute(attr);
|
|
1725
|
+
if (val) {
|
|
1726
|
+
const s = `[${attr}="${CSS.escape(val)}"]`;
|
|
1727
|
+
if (document.querySelectorAll(s).length === 1) return s;
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
let path = '';
|
|
1731
|
+
let current = node;
|
|
1732
|
+
while (
|
|
1733
|
+
current &&
|
|
1734
|
+
current.nodeType === Node.ELEMENT_NODE &&
|
|
1735
|
+
current.tagName !== 'BODY'
|
|
1736
|
+
) {
|
|
1737
|
+
let sel = current.tagName.toLowerCase();
|
|
1738
|
+
const parent = current.parentElement;
|
|
1739
|
+
if (parent) {
|
|
1740
|
+
const siblings = Array.from(parent.children).filter(
|
|
1741
|
+
(c) => c.tagName === current.tagName,
|
|
1742
|
+
);
|
|
1743
|
+
if (siblings.length > 1) {
|
|
1744
|
+
const idx = siblings.indexOf(current) + 1;
|
|
1745
|
+
sel += `:nth-of-type(${idx})`;
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
path = path ? `${sel} > ${path}` : sel;
|
|
1749
|
+
current = parent;
|
|
1750
|
+
}
|
|
1751
|
+
return path ? `body > ${path}` : 'body';
|
|
1752
|
+
};
|
|
1753
|
+
return generateSelector(el);
|
|
1754
|
+
})(),
|
|
1755
|
+
});
|
|
1756
|
+
return false;
|
|
1757
|
+
} catch (e) {
|
|
1758
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1759
|
+
return false;
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
if (request && request.action === 'verifyFingerprint') {
|
|
1763
|
+
try {
|
|
1764
|
+
const ref = String(request.ref || '').trim();
|
|
1765
|
+
const fingerprint = String(request.fingerprint || '').trim();
|
|
1766
|
+
if (!ref || !fingerprint) {
|
|
1767
|
+
sendResponse({ success: false, error: 'ref and fingerprint are required' });
|
|
1768
|
+
return false;
|
|
1769
|
+
}
|
|
1770
|
+
const map = window.__mcpElementMap || window.__claudeElementMap;
|
|
1771
|
+
const weak = map && map[ref];
|
|
1772
|
+
const el = weak && typeof weak.deref === 'function' ? weak.deref() : null;
|
|
1773
|
+
if (!el || !(el instanceof Element)) {
|
|
1774
|
+
sendResponse({ success: false, error: `ref "${ref}" not found or expired` });
|
|
1775
|
+
return false;
|
|
1776
|
+
}
|
|
1777
|
+
// Verify fingerprint: parse stored fingerprint and compare against current element
|
|
1778
|
+
const parts = fingerprint.split('|');
|
|
1779
|
+
const storedTag = parts[0] || 'unknown';
|
|
1780
|
+
const currentTag = el.tagName ? String(el.tagName).toLowerCase() : 'unknown';
|
|
1781
|
+
// Tag names must match
|
|
1782
|
+
if (storedTag !== currentTag) {
|
|
1783
|
+
sendResponse({ success: true, match: false });
|
|
1784
|
+
return false;
|
|
1785
|
+
}
|
|
1786
|
+
// If stored fingerprint includes an id, current element must have the same id
|
|
1787
|
+
const storedIdPart = parts.find((p) => p.startsWith('id='));
|
|
1788
|
+
if (storedIdPart) {
|
|
1789
|
+
const storedId = storedIdPart.slice(3);
|
|
1790
|
+
const currentId = el.id ? String(el.id).trim() : '';
|
|
1791
|
+
if (storedId !== currentId) {
|
|
1792
|
+
sendResponse({ success: true, match: false });
|
|
1793
|
+
return false;
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
sendResponse({ success: true, match: true });
|
|
1797
|
+
return false;
|
|
1798
|
+
} catch (e) {
|
|
1799
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1800
|
+
return false;
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
if (request && request.action === 'focusByRef') {
|
|
1804
|
+
try {
|
|
1805
|
+
const ref = String(request.ref || '');
|
|
1806
|
+
const map = window.__mcpElementMap || window.__claudeElementMap || {};
|
|
1807
|
+
const weak = map[ref];
|
|
1808
|
+
const el = weak && typeof weak.deref === 'function' ? weak.deref() : null;
|
|
1809
|
+
if (!el || !(el instanceof Element)) {
|
|
1810
|
+
sendResponse({ success: false, error: `ref "${ref}" not found or expired` });
|
|
1811
|
+
return false;
|
|
1812
|
+
}
|
|
1813
|
+
try {
|
|
1814
|
+
/** @type {HTMLElement} */ (el).scrollIntoView({
|
|
1815
|
+
behavior: 'instant',
|
|
1816
|
+
block: 'center',
|
|
1817
|
+
inline: 'nearest',
|
|
1818
|
+
});
|
|
1819
|
+
} catch {}
|
|
1820
|
+
try {
|
|
1821
|
+
/** @type {HTMLElement} */ (el).focus && /** @type {HTMLElement} */ (el).focus();
|
|
1822
|
+
} catch {}
|
|
1823
|
+
sendResponse({ success: true });
|
|
1824
|
+
return false;
|
|
1825
|
+
} catch (e) {
|
|
1826
|
+
sendResponse({ success: false, error: String(e && e.message ? e.message : e) });
|
|
1827
|
+
return false;
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
} catch (e) {
|
|
1831
|
+
sendResponse({ success: false, error: e && e.message ? e.message : String(e) });
|
|
1832
|
+
return false;
|
|
1833
|
+
}
|
|
1834
|
+
return false;
|
|
1835
|
+
});
|
|
1836
|
+
|
|
1837
|
+
console.log('Accessibility tree helper script loaded');
|
|
1838
|
+
// Cross-frame bridge: child listens for ensure-ref requests from parent (composite selector)
|
|
1839
|
+
try {
|
|
1840
|
+
window.addEventListener(
|
|
1841
|
+
'message',
|
|
1842
|
+
(ev) => {
|
|
1843
|
+
try {
|
|
1844
|
+
const data = ev && ev.data;
|
|
1845
|
+
if (
|
|
1846
|
+
!data ||
|
|
1847
|
+
(data.type !== 'rr-bridge-hover-ref' && data.type !== 'rr-bridge-ensure-ref')
|
|
1848
|
+
) {
|
|
1849
|
+
return;
|
|
1850
|
+
}
|
|
1851
|
+
// Security guard: child-frame bridge must only process requests from parent frame
|
|
1852
|
+
// Top-level windows have no parent and must never process child-bridge requests
|
|
1853
|
+
if (window === window.top || !window.parent || window.parent === window) {
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
if (ev.source !== window.parent) {
|
|
1857
|
+
return;
|
|
1858
|
+
}
|
|
1859
|
+
const targetOrigin = ev.origin && ev.origin !== 'null' ? ev.origin : '*';
|
|
1860
|
+
// Handle hover-ref bridge requests from parent frame
|
|
1861
|
+
if (data && data.type === 'rr-bridge-hover-ref') {
|
|
1862
|
+
handleHoverForRef(data.ref)
|
|
1863
|
+
.then((result) => {
|
|
1864
|
+
ev.source?.postMessage(
|
|
1865
|
+
{ type: 'rr-bridge-hover-ref-result', reqId: data.reqId, result },
|
|
1866
|
+
targetOrigin,
|
|
1867
|
+
);
|
|
1868
|
+
})
|
|
1869
|
+
.catch((error) => {
|
|
1870
|
+
ev.source?.postMessage(
|
|
1871
|
+
{
|
|
1872
|
+
type: 'rr-bridge-hover-ref-result',
|
|
1873
|
+
reqId: data.reqId,
|
|
1874
|
+
result: { success: false, error: error?.message || String(error) },
|
|
1875
|
+
},
|
|
1876
|
+
targetOrigin,
|
|
1877
|
+
);
|
|
1878
|
+
});
|
|
1879
|
+
return;
|
|
1880
|
+
}
|
|
1881
|
+
if (!data || data.type !== 'rr-bridge-ensure-ref') return;
|
|
1882
|
+
const { reqId, selector, useText, isXPath, tagName } = data || {};
|
|
1883
|
+
const respond = (payload) => {
|
|
1884
|
+
try {
|
|
1885
|
+
ev.source &&
|
|
1886
|
+
ev.source.postMessage(
|
|
1887
|
+
{ type: 'rr-bridge-ensure-ref-result', reqId, ...payload },
|
|
1888
|
+
targetOrigin,
|
|
1889
|
+
);
|
|
1890
|
+
} catch {}
|
|
1891
|
+
};
|
|
1892
|
+
try {
|
|
1893
|
+
const sel = String(selector || '').trim();
|
|
1894
|
+
const limitTag = String(tagName || '')
|
|
1895
|
+
.trim()
|
|
1896
|
+
.toUpperCase();
|
|
1897
|
+
let el = null;
|
|
1898
|
+
if (useText && sel) {
|
|
1899
|
+
const normalize = (s) =>
|
|
1900
|
+
String(s || '')
|
|
1901
|
+
.replace(/\s+/g, ' ')
|
|
1902
|
+
.trim()
|
|
1903
|
+
.toLowerCase();
|
|
1904
|
+
const query = normalize(sel);
|
|
1905
|
+
const bigrams = (s) => {
|
|
1906
|
+
const arr = [];
|
|
1907
|
+
for (let i = 0; i < s.length - 1; i++) arr.push(s.slice(i, i + 2));
|
|
1908
|
+
return arr;
|
|
1909
|
+
};
|
|
1910
|
+
const dice = (a, b) => {
|
|
1911
|
+
if (!a || !b) return 0;
|
|
1912
|
+
const A = bigrams(a),
|
|
1913
|
+
B = bigrams(b);
|
|
1914
|
+
if (!A.length || !B.length) return 0;
|
|
1915
|
+
let inter = 0;
|
|
1916
|
+
const m = new Map();
|
|
1917
|
+
for (const t of A) m.set(t, (m.get(t) || 0) + 1);
|
|
1918
|
+
for (const t of B) {
|
|
1919
|
+
const c = m.get(t) || 0;
|
|
1920
|
+
if (c > 0) {
|
|
1921
|
+
inter++;
|
|
1922
|
+
m.set(t, c - 1);
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
return (2 * inter) / (A.length + B.length);
|
|
1926
|
+
};
|
|
1927
|
+
let best = { el: null, score: 0 };
|
|
1928
|
+
const stack = [document.documentElement];
|
|
1929
|
+
while (stack.length) {
|
|
1930
|
+
const node = stack.pop();
|
|
1931
|
+
if (!node || !(node instanceof Element)) continue;
|
|
1932
|
+
try {
|
|
1933
|
+
if (limitTag && String(node.tagName || '').toUpperCase() !== limitTag) {
|
|
1934
|
+
} else {
|
|
1935
|
+
const cs = window.getComputedStyle(node);
|
|
1936
|
+
if (cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0') {
|
|
1937
|
+
const rect = node.getBoundingClientRect();
|
|
1938
|
+
if (rect.width > 0 && rect.height > 0) {
|
|
1939
|
+
const txt = normalize(node.textContent || '');
|
|
1940
|
+
if (txt) {
|
|
1941
|
+
if (txt.includes(query)) {
|
|
1942
|
+
el = node;
|
|
1943
|
+
break;
|
|
1944
|
+
}
|
|
1945
|
+
const sc = dice(txt, query);
|
|
1946
|
+
if (sc > best.score) best = { el: node, score: sc };
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
} catch {}
|
|
1952
|
+
try {
|
|
1953
|
+
const children = node.children || [];
|
|
1954
|
+
for (let i = 0; i < children.length; i++) stack.push(children[i]);
|
|
1955
|
+
const sr = node.shadowRoot;
|
|
1956
|
+
if (sr && sr.children)
|
|
1957
|
+
for (let i = 0; i < sr.children.length; i++) stack.push(sr.children[i]);
|
|
1958
|
+
} catch {}
|
|
1959
|
+
}
|
|
1960
|
+
if (!el && best.el) el = best.el;
|
|
1961
|
+
} else if (isXPath) {
|
|
1962
|
+
if (!sel) {
|
|
1963
|
+
respond({ success: false, error: 'selector is required' });
|
|
1964
|
+
return;
|
|
1965
|
+
}
|
|
1966
|
+
const allowMultiple = !!data.allowMultiple;
|
|
1967
|
+
const result = queryXPathWithUniquenessCheck(sel, allowMultiple);
|
|
1968
|
+
if (result.error) {
|
|
1969
|
+
respond({ success: false, error: result.error });
|
|
1970
|
+
return;
|
|
1971
|
+
}
|
|
1972
|
+
if (result.matchCount === 0) {
|
|
1973
|
+
respond({ success: false, error: `Selector "${sel}" not found in child frame` });
|
|
1974
|
+
return;
|
|
1975
|
+
}
|
|
1976
|
+
if (!allowMultiple && result.matchCount > 1) {
|
|
1977
|
+
respond({
|
|
1978
|
+
success: false,
|
|
1979
|
+
error: `Selector "${sel}" matched multiple elements inside frame. Please refine the selector to match only one element.`,
|
|
1980
|
+
});
|
|
1981
|
+
return;
|
|
1982
|
+
}
|
|
1983
|
+
el = result.element;
|
|
1984
|
+
} else {
|
|
1985
|
+
if (!sel) {
|
|
1986
|
+
respond({ success: false, error: 'selector is required' });
|
|
1987
|
+
return;
|
|
1988
|
+
}
|
|
1989
|
+
const allowMultiple = !!data.allowMultiple;
|
|
1990
|
+
const result = querySelectorWithUniquenessCheck(sel, allowMultiple);
|
|
1991
|
+
if (result.error) {
|
|
1992
|
+
respond({ success: false, error: result.error });
|
|
1993
|
+
return;
|
|
1994
|
+
}
|
|
1995
|
+
if (result.matchCount === 0) {
|
|
1996
|
+
respond({ success: false, error: `Selector "${sel}" not found in child frame` });
|
|
1997
|
+
return;
|
|
1998
|
+
}
|
|
1999
|
+
if (!allowMultiple && result.matchCount > 1) {
|
|
2000
|
+
respond({
|
|
2001
|
+
success: false,
|
|
2002
|
+
error: `Selector "${sel}" matched multiple elements inside frame. Please refine the selector to match only one element.`,
|
|
2003
|
+
});
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
el = result.element;
|
|
2007
|
+
}
|
|
2008
|
+
if (!el || !(el instanceof Element)) {
|
|
2009
|
+
respond({ success: false, error: 'Element not found in child frame' });
|
|
2010
|
+
return;
|
|
2011
|
+
}
|
|
2012
|
+
const refId = getOrAssignElementRef(el);
|
|
2013
|
+
const rect = el.getBoundingClientRect();
|
|
2014
|
+
respond({
|
|
2015
|
+
success: true,
|
|
2016
|
+
ref: refId,
|
|
2017
|
+
center: {
|
|
2018
|
+
x: Math.round(rect.left + rect.width / 2),
|
|
2019
|
+
y: Math.round(rect.top + rect.height / 2),
|
|
2020
|
+
},
|
|
2021
|
+
href: String(location && location.href ? location.href : ''),
|
|
2022
|
+
});
|
|
2023
|
+
} catch (e) {
|
|
2024
|
+
respond({ success: false, error: String(e && e.message ? e.message : e) });
|
|
2025
|
+
}
|
|
2026
|
+
} catch {}
|
|
2027
|
+
},
|
|
2028
|
+
true,
|
|
2029
|
+
);
|
|
2030
|
+
} catch {}
|
|
2031
|
+
})();
|