browserpaw 0.0.0-stage → 5.0.0

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