dsh-chrome-bridge 1.20.0 → 2.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 (88) hide show
  1. package/README.en.md +6 -2
  2. package/README.md +6 -2
  3. package/client.js +110 -29
  4. package/core/ext.js +119 -0
  5. package/core/hosts.js +277 -0
  6. package/core/locale.js +8 -0
  7. package/core/receipt.js +56 -0
  8. package/core/session.js +157 -0
  9. package/core/shots.js +56 -0
  10. package/core/tooldef.js +142 -0
  11. package/core/transport.js +212 -0
  12. package/core/upload.js +59 -0
  13. package/devtools.js +18 -8
  14. package/download.js +879 -60
  15. package/drag.js +38 -20
  16. package/features/frames.js +58 -0
  17. package/features/gif.js +203 -0
  18. package/features/index.js +1 -0
  19. package/features/mock-har.js +85 -0
  20. package/features/record.js +225 -0
  21. package/i18n/en.js +168 -16
  22. package/i18n/ru.js +168 -16
  23. package/i18n/zh.js +168 -16
  24. package/image-guard.js +13 -6
  25. package/index.js +17 -1155
  26. package/locale/ru.json +7 -0
  27. package/nav.js +43 -5
  28. package/package.json +8 -1
  29. package/panel.js +10 -1
  30. package/refs.js +275 -230
  31. package/setup.js +214 -46
  32. package/tools/click.js +58 -0
  33. package/tools/devtools.js +61 -0
  34. package/tools/dialog.js +22 -0
  35. package/tools/download.js +50 -0
  36. package/tools/drag.js +61 -0
  37. package/tools/eval.js +22 -0
  38. package/tools/fill.js +77 -0
  39. package/tools/handoff.js +40 -0
  40. package/tools/index.js +38 -0
  41. package/tools/input.js +147 -0
  42. package/tools/nav.js +57 -0
  43. package/tools/read.js +87 -0
  44. package/tools/record.js +120 -0
  45. package/tools/screenshot.js +223 -0
  46. package/tools/tabs.js +131 -0
  47. package/tools/wait.js +56 -0
  48. package/vendor/cb +616 -35
  49. package/vendor/extension/_locales/en/messages.json +3 -0
  50. package/vendor/extension/_locales/ru/messages.json +3 -0
  51. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  53. package/vendor/extension/background.js +2 -1969
  54. package/vendor/extension/confirm.css +148 -0
  55. package/vendor/extension/confirm.html +49 -0
  56. package/vendor/extension/confirm.js +188 -0
  57. package/vendor/extension/in-page-cursor.js +599 -0
  58. package/vendor/extension/manifest.json +11 -2
  59. package/vendor/extension/popup.css +99 -5
  60. package/vendor/extension/popup.html +28 -2
  61. package/vendor/extension/popup.js +430 -45
  62. package/vendor/extension/sw/boot.js +111 -0
  63. package/vendor/extension/sw/cdp.js +411 -0
  64. package/vendor/extension/sw/chooser.js +192 -0
  65. package/vendor/extension/sw/confirm.js +608 -0
  66. package/vendor/extension/sw/cursor.js +241 -0
  67. package/vendor/extension/sw/dispatch.js +129 -0
  68. package/vendor/extension/sw/download.js +279 -0
  69. package/vendor/extension/sw/fetch-hub.js +224 -0
  70. package/vendor/extension/sw/frames.js +651 -0
  71. package/vendor/extension/sw/imaging.js +361 -0
  72. package/vendor/extension/sw/native.js +111 -0
  73. package/vendor/extension/sw/net-tools.js +525 -0
  74. package/vendor/extension/sw/ops.js +829 -0
  75. package/vendor/extension/sw/popup-api.js +303 -0
  76. package/vendor/extension/sw/profile.js +166 -0
  77. package/vendor/extension/sw/record.js +494 -0
  78. package/vendor/extension/sw/state.js +161 -0
  79. package/vendor/extension/sw/tabui.js +219 -0
  80. package/vendor/extension/sw/util.js +166 -0
  81. package/vendor/extension/sw/welcome.js +26 -0
  82. package/vendor/extension/sw/windows.js +94 -0
  83. package/vendor/extension/welcome.css +189 -0
  84. package/vendor/extension/welcome.html +70 -0
  85. package/vendor/extension/welcome.js +157 -0
  86. package/vendor/host/host.js +476 -71
  87. package/vendor/in-page-cursor.js +309 -37
  88. package/vendor/skill/SKILL.md +34 -16
@@ -0,0 +1,651 @@
1
+ import { onTabDetached } from './cdp.js'
2
+ import { ensureUrlAllowed, isUrlAllowed } from './confirm.js'
3
+ import { registerOps } from './ops.js'
4
+ import { HANDOFF_LOCKED, PAUSED_MSG, QUEUED, S, TAKEOVER_OPS } from './state.js'
5
+ import { timeLeft } from './util.js'
6
+
7
+ // Serialized by Chrome for isolated frames and by refs.js for the main snapshot.
8
+ export function scanPage(selector, scope, query, frame) {
9
+ const sensitive = (el, style) => {
10
+ if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && !el.isContentEditable) return false;
11
+ const value = String(el.isContentEditable ? el.innerText || '' : el.value || '');
12
+ const fields = ['name', 'id', 'autocomplete', 'aria-label', 'placeholder', 'title'].map(attr => el.getAttribute(attr) || '').join(' ');
13
+ return ['password', 'tel'].includes(el.type) ||
14
+ (style.webkitTextSecurity && style.webkitTextSecurity !== 'none') ||
15
+ (/^numeric$/i.test(el.getAttribute('inputmode') || '') && !!value) ||
16
+ /(?:^|[\s_-])pin(?:$|[\s_-])|otp|passcode|verif|2fa|mfa|sms[_-]?code|auth[_-]?code|cvv|cvc|card|secret|token|api[_-]?key|pwd|pass(?:word|wd)?/i.test(fields) ||
17
+ /(?:^|\s)(?:one-time-code|cc-number|cc-csc)(?:\s|$)/i.test(fields) ||
18
+ (/(?:^|[\s_-])code(?:$|[\s_-])/i.test(fields) && (Boolean(frame) || /^[a-z0-9]{4,10}$/i.test(value.trim()))) ||
19
+ /(?:\d[\s-]?){11}\d/.test(value);
20
+ };
21
+ if (scope === 'mask') return sensitive(selector, query);
22
+ // innerText on an ancestor can include a masked editable child's contents.
23
+ // Redact before query matching or truncation as well as before returning text.
24
+ function redactWithin(root) {
25
+ const hiddenValues = new Set();
26
+ function collectSecrets(root) {
27
+ for (const el of root.querySelectorAll('*')) {
28
+ if (el.shadowRoot) collectSecrets(el.shadowRoot);
29
+ if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA' && !el.isContentEditable) continue;
30
+ if (!sensitive(el, getComputedStyle(el))) continue;
31
+ const values = [el.value, el.innerText, el.tagName === 'TEXTAREA' && el.defaultValue];
32
+ for (const value of values) if (value) hiddenValues.add(String(value));
33
+ }
34
+ }
35
+ collectSecrets(root);
36
+ if (root.shadowRoot) collectSecrets(root.shadowRoot);
37
+ const secrets = [...hiddenValues].sort((a, b) => b.length - a.length);
38
+ return text => {
39
+ for (const secret of secrets) text = text.replaceAll(secret, '••••');
40
+ return text;
41
+ };
42
+ }
43
+ const redact = frame ? redactWithin(document) : text => text;
44
+ if (scope === 'frameText') return redact(document.body?.innerText || '').trim().slice(0, 16000);
45
+ const key = frame ? '__dshFrameSnap' : '__dshSnap';
46
+ const S = window[key] ||= { next: 1, shadow: new Map(), ids: new WeakMap() };
47
+ if (frame) S.label = el => {
48
+ if (sensitive(el, getComputedStyle(el))) return '••••';
49
+ const text = el.innerText || el.value || el.getAttribute('aria-label') || '';
50
+ return redactWithin(el)(text).replace(/\s+/g, ' ').trim().slice(0, 60);
51
+ };
52
+ const ATTR = 'data-dsh-ref';
53
+ const norm = (s) => redact(s || '').replace(/\s+/g, ' ').trim();
54
+ const cut = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
55
+ const q = (s) => JSON.stringify(s);
56
+
57
+ const root = selector ? document.querySelector(selector) : document.body;
58
+ const viewport = scope === 'viewport';
59
+ if (!root) return { error: 'scope' };
60
+
61
+ const TAGS = new Set(['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'SUMMARY']);
62
+ const ROLES = new Set(['button', 'link', 'checkbox', 'radio', 'switch', 'tab', 'menuitem', 'menuitemcheckbox',
63
+ 'menuitemradio', 'option', 'combobox', 'textbox', 'searchbox', 'slider', 'spinbutton', 'treeitem', 'listbox']);
64
+ const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'META', 'LINK']);
65
+ const FORM = new Set(['INPUT', 'SELECT', 'TEXTAREA']);
66
+
67
+ // 框架里的元素按它自己那一页算样式
68
+ const css = (el) => (el.ownerDocument.defaultView || window).getComputedStyle(el);
69
+ const cursorOf = (el) => { try { return css(el).cursor } catch { return '' } };
70
+ const shown = (el, st) => {
71
+ const r = el.getBoundingClientRect();
72
+ if (r.width < 1 || r.height < 1) return false;
73
+ if (st.visibility === 'hidden') return false;
74
+ // 自定义样式的复选框常常把 <input> 设成透明叠在上面 —— 它照样接得住点击
75
+ if (!FORM.has(el.tagName) && Number(st.opacity) === 0) return false;
76
+ return true;
77
+ };
78
+ const interactive = (el, st) => {
79
+ const tag = el.tagName;
80
+ if (TAGS.has(tag)) {
81
+ if (tag === 'A') return el.hasAttribute('href') || el.hasAttribute('onclick');
82
+ if (tag === 'INPUT') return el.type !== 'hidden';
83
+ return true;
84
+ }
85
+ const role = (el.getAttribute('role') || '').split(' ')[0];
86
+ if (ROLES.has(role)) return true;
87
+ if (el.isContentEditable && !(el.parentElement && el.parentElement.isContentEditable)) return true;
88
+ if (el.hasAttribute('onclick')) return true;
89
+ if (el.getAttribute('tabindex') !== null && el.tabIndex >= 0 && role !== 'dialog') return true;
90
+ // 手搓的 <div> 按钮:认 cursor:pointer,但只认「从这里开始变成手型」的那一层,子元素继承的不算
91
+ if (st.cursor === 'pointer') {
92
+ const p = el.parentElement;
93
+ return !p || cursorOf(p) !== 'pointer';
94
+ }
95
+ return false;
96
+ };
97
+ const roleOf = (el) => {
98
+ const r = (el.getAttribute('role') || '').split(' ')[0];
99
+ if (r) return r;
100
+ const tag = el.tagName;
101
+ if (tag === 'A') return 'link';
102
+ if (tag === 'BUTTON' || tag === 'SUMMARY') return 'button';
103
+ if (tag === 'SELECT') return el.multiple ? 'listbox' : 'combobox';
104
+ if (tag === 'TEXTAREA') return 'textbox';
105
+ if (tag === 'INPUT') {
106
+ const t = (el.type || 'text').toLowerCase();
107
+ return ({ checkbox: 'checkbox', radio: 'radio', range: 'slider', file: 'file', button: 'button',
108
+ submit: 'button', reset: 'button', image: 'button', search: 'searchbox', number: 'spinbutton',
109
+ color: 'color', date: 'date', 'datetime-local': 'date', month: 'date', week: 'date', time: 'time' })[t] || 'textbox';
110
+ }
111
+ if (el.isContentEditable) return 'textbox';
112
+ return 'clickable';
113
+ };
114
+ const byId = (el, id) => {
115
+ const r = el.getRootNode();
116
+ return (r.getElementById && r.getElementById(id)) || document.getElementById(id);
117
+ };
118
+ const nameOf = (el, masked) => {
119
+ const aria = norm(el.getAttribute('aria-label'));
120
+ if (aria) return aria;
121
+ const lb = el.getAttribute('aria-labelledby');
122
+ if (lb) {
123
+ const t = norm(lb.split(/\s+/).map((id) => { const n = byId(el, id); return n ? n.innerText || n.textContent : ''; }).join(' '));
124
+ if (t) return t;
125
+ }
126
+ if (el.labels && el.labels.length) {
127
+ const t = norm([...el.labels].map((l) => l.innerText).join(' '));
128
+ if (t) return t;
129
+ }
130
+ if (el.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes(el.type)) return masked ? '••••' : norm(el.value || el.type);
131
+ if (el.tagName === 'INPUT' && el.type === 'image') return norm(el.alt || el.title || 'image');
132
+ if (!FORM.has(el.tagName) && !masked) {
133
+ const t = norm(el.innerText);
134
+ if (t) return t;
135
+ const img = el.querySelector('img[alt]');
136
+ if (img && norm(img.alt)) return norm(img.alt);
137
+ const svgTitle = el.querySelector('svg title');
138
+ if (svgTitle && norm(svgTitle.textContent)) return norm(svgTitle.textContent);
139
+ }
140
+ return norm(el.getAttribute('title'));
141
+ };
142
+ const hrefOf = (el) => {
143
+ const h = el.getAttribute('href');
144
+ if (!h || h.startsWith('javascript:')) return '';
145
+ try {
146
+ const u = new URL(h, el.baseURI);
147
+ return u.origin === location.origin ? (u.pathname + u.search + u.hash) : (u.host + u.pathname);
148
+ } catch { return h; }
149
+ };
150
+ const stateOf = (el, role, masked) => {
151
+ const out = [];
152
+ const tag = el.tagName;
153
+ if (tag === 'INPUT' && ['checkbox', 'radio'].includes(el.type)) { if (el.checked) out.push('已勾选'); }
154
+ else if (el.getAttribute('aria-checked') === 'true') out.push('已勾选');
155
+ if (el.getAttribute('aria-selected') === 'true') out.push('已选中');
156
+ const ex = el.getAttribute('aria-expanded');
157
+ if (ex === 'true') out.push('已展开'); else if (ex === 'false') out.push('已收起');
158
+ if (el.disabled || el.getAttribute('aria-disabled') === 'true') out.push('不可用');
159
+ if (el.readOnly) out.push('只读');
160
+ let extra = '';
161
+ if (tag === 'SELECT') {
162
+ const o = el.selectedOptions && el.selectedOptions[0];
163
+ extra = ' = ' + q(cut(norm(o ? o.textContent : ''), 40)) + '(' + el.options.length + ' 个选项)';
164
+ } else if (masked) {
165
+ if (el.isContentEditable ? norm(el.innerText) : el.value) extra = ' = ••••';
166
+ } else if ((tag === 'INPUT' && !['checkbox', 'radio', 'button', 'submit', 'reset', 'image', 'file'].includes(el.type)) || tag === 'TEXTAREA') {
167
+ if (el.value) extra = ' = ' + q(cut(norm(el.value), 60));
168
+ } else if (role === 'textbox' && el.isContentEditable) {
169
+ const t = norm(el.innerText);
170
+ if (t) extra = ' = ' + q(cut(t, 60));
171
+ }
172
+ const ph = el.getAttribute('placeholder');
173
+ if (ph && !el.value) extra += ' 提示' + q(cut(norm(ph), 40));
174
+ if (tag === 'A') { const h = hrefOf(el); if (h) extra += ' → ' + cut(h, 70); }
175
+ return extra + (out.length ? ' (' + out.join(',') + ')' : '');
176
+ };
177
+
178
+ S.ids ||= new WeakMap();
179
+ S.refs ||= new Map();
180
+ for (const [ref, weak] of S.refs) {
181
+ if (!weak.deref()?.isConnected) { S.refs.delete(ref); S.shadow.delete(ref); }
182
+ }
183
+ const assign = (el) => {
184
+ let n = S.ids.get(el);
185
+ if (!frame && n >= 10000 && n % 10000) {
186
+ S.refs.delete(n);
187
+ S.shadow.delete(n);
188
+ n = null;
189
+ }
190
+ if (frame && !n && S.next >= 10000) return null;
191
+ if (!n) {
192
+ n = S.next++;
193
+ if (!frame && n >= 10000) n = (n - 9999) * 10000;
194
+ S.ids.set(el, n);
195
+ }
196
+ if (!frame && el.getAttribute(ATTR) !== String(n)) el.setAttribute(ATTR, String(n));
197
+ if (!S.refs.has(n)) S.refs.set(n, new WeakRef(el));
198
+ if (el.getRootNode() !== document) S.shadow.set(n, S.refs.get(n));
199
+ return n;
200
+ };
201
+ const inViewport = (el) => {
202
+ const rect = el.getBoundingClientRect();
203
+ let left = rect.left, top = rect.top, right = rect.right, bottom = rect.bottom;
204
+ if (frame?.clip) {
205
+ left = Math.max(left, frame.clip.left); top = Math.max(top, frame.clip.top);
206
+ right = Math.min(right, frame.clip.right); bottom = Math.min(bottom, frame.clip.bottom);
207
+ }
208
+ const parentOf = (node) => node.parentElement || node.getRootNode().host;
209
+ let node = el;
210
+ for (let view = el.ownerDocument.defaultView; view;) {
211
+ for (let parent = parentOf(node); parent; parent = parentOf(parent)) {
212
+ const { overflowX, overflowY } = css(parent);
213
+ const clips = (overflow) => /^(hidden|auto|clip|scroll)$/.test(overflow);
214
+ if (!clips(overflowX) && !clips(overflowY)) continue;
215
+ const bounds = parent.getBoundingClientRect();
216
+ if (clips(overflowX)) {
217
+ left = Math.max(left, bounds.left + parent.clientLeft);
218
+ right = Math.min(right, bounds.left + parent.clientLeft + parent.clientWidth);
219
+ }
220
+ if (clips(overflowY)) {
221
+ top = Math.max(top, bounds.top + parent.clientTop);
222
+ bottom = Math.min(bottom, bounds.top + parent.clientTop + parent.clientHeight);
223
+ }
224
+ }
225
+ left = Math.max(0, left);
226
+ top = Math.max(0, top);
227
+ right = Math.min(view.innerWidth, right);
228
+ bottom = Math.min(view.innerHeight, bottom);
229
+ if (right <= left || bottom <= top) return false;
230
+ if (view === window) return true;
231
+ const frame = view.frameElement;
232
+ if (!frame) return false;
233
+ const bounds = frame.getBoundingClientRect();
234
+ const x = bounds.left + frame.clientLeft, y = bounds.top + frame.clientTop;
235
+ left += x; right += x; top += y; bottom += y;
236
+ view = view.parent;
237
+ node = frame;
238
+ }
239
+ return false;
240
+ };
241
+
242
+ const rows = [];
243
+ let count = 0, outside = 0, scanned = 0, capped = false;
244
+ const scanLimit = 30000;
245
+ const walk = (el, depth = 0, path = []) => {
246
+ if (scanned >= scanLimit || SKIP.has(el.tagName) || el.id === '__dsh_cursor__') return;
247
+ scanned++;
248
+ let st;
249
+ try { st = css(el); } catch { return; }
250
+ if (st.display === 'none') return;
251
+ if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
252
+ if (frame || !shown(el, st)) return;
253
+ const label = '[iframe] ' + cut(el.getAttribute('src') || el.getAttribute('title') || el.getAttribute('name') || '', 80);
254
+ const context = !query && (!viewport || inViewport(el));
255
+ const parent = el.ownerDocument.defaultView;
256
+ const index = Array.prototype.indexOf.call(parent.frames || [], el.contentWindow);
257
+ const childPath = [...path, index];
258
+ let doc = null;
259
+ try { doc = el.contentDocument; } catch {}
260
+ if (doc?.body && doc.defaultView?.origin === parent.origin && depth < 5) {
261
+ if (context) rows.push({ line: label + ' ↓' });
262
+ walk(doc.body, depth + 1, childPath);
263
+ if (context) rows.push({ line: '[/iframe]' });
264
+ } else {
265
+ rows.push({ crossPath: childPath, line: context ? label + '(跨站框架,读不到里面:browser_screenshot 看,按坐标 x/y 点)' : null });
266
+ }
267
+ return;
268
+ }
269
+ const masked = sensitive(el, st);
270
+ if (shown(el, st)) {
271
+ const heading = /^H([1-3])$/.exec(el.tagName);
272
+ if (heading && !masked && !query && (!viewport || inViewport(el))) {
273
+ const title = norm(el.innerText);
274
+ if (title) rows.push({ line: '#'.repeat(Number(heading[1])) + ' ' + cut(title, 80) });
275
+ }
276
+ if (interactive(el, st)) {
277
+ const role = roleOf(el);
278
+ const name = nameOf(el, masked);
279
+ const state = stateOf(el, role, masked);
280
+ const value = masked ? '' : norm(String(el.value || ''));
281
+ if (!query || (role + ' ' + name + ' ' + value + ' ' + state).toLowerCase().includes(query)) {
282
+ if (viewport && !inViewport(el)) outside++;
283
+ else {
284
+ const ref = assign(el);
285
+ if (ref === null) capped = true;
286
+ else {
287
+ rows.push({ ref, line: '[' + ref + '] ' + role + (name ? ' ' + q(cut(name, 80)) : '') + state });
288
+ count++;
289
+ }
290
+ }
291
+ }
292
+ }
293
+ }
294
+ if (el.tagName === 'SELECT' || el.tagName === 'svg' || (masked && el.isContentEditable)) return;
295
+ for (const child of el.children) walk(child, depth, path);
296
+ if (el.shadowRoot) for (const child of el.shadowRoot.children) walk(child, depth, path);
297
+ };
298
+ walk(root);
299
+ return { rows, count, outside, capped: capped || scanned >= scanLimit, title: document.title, url: location.href, documentId: S.documentId ||= Math.random().toString(36).slice(2) };
300
+ }
301
+
302
+ // Cross-origin WindowProxy exposes indexed child windows. This associates an
303
+ // owner with its browsing context even for duplicate URLs, srcdoc and redirects.
304
+ function frameInfo(scrollChild = null, metadataOnly = false, point = null) {
305
+ const path = []
306
+ for (let w = window; w !== w.top; w = w.parent) {
307
+ const index = Array.prototype.indexOf.call(w.parent.frames, w)
308
+ if (index < 0) return null
309
+ path.unshift(index)
310
+ }
311
+ const info = { path, width: innerWidth, height: innerHeight, href: location.href, origin: self.origin }
312
+ if (metadataOnly) return info
313
+ function hitAt(x, y) {
314
+ let hit = document.elementFromPoint(x, y)
315
+ while (hit?.shadowRoot) {
316
+ const inner = hit.shadowRoot.elementFromPoint(x, y)
317
+ if (!inner || inner === hit) break
318
+ hit = inner
319
+ }
320
+ return hit
321
+ }
322
+ if (point) {
323
+ const frame = window.frames[point.child]
324
+ return Boolean(frame && hitAt(point.x, point.y)?.contentWindow === frame)
325
+ }
326
+ const children = {}
327
+ function scale(el, rect, style) {
328
+ // offsetWidth rounds to integral CSS pixels. Preserve fractional sizes
329
+ // before applying zoom or an axis-aligned transform.
330
+ function size(axis, sides, fallback) {
331
+ const base = parseFloat(style[axis])
332
+ if (!Number.isFinite(base)) return fallback
333
+ const extra = sides.reduce((sum, side) => sum + (parseFloat(style['padding' + side]) || 0)
334
+ + (parseFloat(style['border' + side + 'Width']) || 0), 0)
335
+ return style.boxSizing === 'border-box' ? base : base + extra
336
+ }
337
+ return [rect.width / size('width', ['Left', 'Right'], el.offsetWidth),
338
+ rect.height / size('height', ['Top', 'Bottom'], el.offsetHeight)]
339
+ }
340
+ function owners(root) {
341
+ for (const el of root.querySelectorAll('*')) {
342
+ if (el.shadowRoot) owners(el.shadowRoot)
343
+ if (!['IFRAME', 'FRAME'].includes(el.tagName)) continue
344
+ const i = Array.prototype.indexOf.call(window.frames, el.contentWindow)
345
+ if (i < 0) continue
346
+ if (i === scrollChild) el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
347
+ const r = el.getBoundingClientRect(), st = getComputedStyle(el)
348
+ if (!r.width || !r.height || st.visibility === 'hidden' || Number(st.opacity) === 0) continue
349
+ // A non-axis-aligned box cannot be mapped by adding offsets. Never
350
+ // turn its bounding rectangle into a plausible but incorrect click.
351
+ let left = 0, top = 0, right = innerWidth, bottom = innerHeight, aligned = true
352
+ for (let p = el; p; p = p.parentElement || p.getRootNode().host) {
353
+ const style = getComputedStyle(p)
354
+ if (style.transform !== 'none' && style.transform) {
355
+ const m = new DOMMatrixReadOnly(style.transform)
356
+ if (!m.is2D || m.b || m.c || m.a <= 0 || m.d <= 0) aligned = false
357
+ }
358
+ if (style.perspective && style.perspective !== 'none' || style.rotate && style.rotate !== 'none') aligned = false
359
+ if (style.scale && style.scale !== 'none' && style.scale.split(/\s+/).some(v => parseFloat(v) <= 0)) aligned = false
360
+ if (p === el) continue
361
+ const b = p.getBoundingClientRect()
362
+ if (!/^(hidden|auto|scroll|clip)$/.test(style.overflowX) && !/^(hidden|auto|scroll|clip)$/.test(style.overflowY)) continue
363
+ const [cx, cy] = scale(p, b, style)
364
+ if (/^(hidden|auto|scroll|clip)$/.test(style.overflowX)) {
365
+ left = Math.max(left, b.left + cx * p.clientLeft); right = Math.min(right, b.left + cx * (p.clientLeft + p.clientWidth))
366
+ }
367
+ if (/^(hidden|auto|scroll|clip)$/.test(style.overflowY)) {
368
+ top = Math.max(top, b.top + cy * p.clientTop); bottom = Math.min(bottom, b.top + cy * (p.clientTop + p.clientHeight))
369
+ }
370
+ }
371
+ const [sx, sy] = scale(el, r, st)
372
+ const visibleLeft = Math.max(left, r.left), visibleRight = Math.min(right, r.right)
373
+ const visibleTop = Math.max(top, r.top), visibleBottom = Math.min(bottom, r.bottom)
374
+ if (aligned && visibleRight > visibleLeft && visibleBottom > visibleTop) {
375
+ const x = (visibleLeft + visibleRight) / 2, y = (visibleTop + visibleBottom) / 2
376
+ const hit = hitAt(x, y)
377
+ aligned = hit === el || el.contains(hit)
378
+ } else aligned = false
379
+ children[i] = { x: r.left + sx * (el.clientLeft + (parseFloat(st.paddingLeft) || 0)),
380
+ y: r.top + sy * (el.clientTop + (parseFloat(st.paddingTop) || 0)), sx, sy,
381
+ left, top, right, bottom, aligned }
382
+ }
383
+ }
384
+ if (window.length) owners(document)
385
+ return { ...info, children }
386
+ }
387
+
388
+ async function frameAction(local, action, args) {
389
+ const store = window.__dshFrameSnap
390
+ const el = store?.refs.get(local)?.deref()
391
+ if (!el?.isConnected || el.ownerDocument !== document || store.ids.get(el) !== local) return null
392
+ if (action === 'locate') {
393
+ el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
394
+ const r = el.getBoundingClientRect()
395
+ return { tag: el.tagName.toLowerCase(), text: store.label(el),
396
+ box: { x: r.left, y: r.top, width: r.width, height: r.height } }
397
+ }
398
+ if (el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true') return 'disabled'
399
+ if (action === 'focus') {
400
+ el.focus()
401
+ return el.getRootNode().activeElement === el ? 'ok' : 'rejected'
402
+ }
403
+ if (action === 'check') {
404
+ const native = el.tagName === 'INPUT' && ['checkbox', 'radio'].includes(el.type)
405
+ if (!native && !['checkbox', 'switch', 'radio'].includes(el.getAttribute('role'))) return 'wrong'
406
+ const checked = () => native ? (el.indeterminate ? 'mixed' : String(el.checked)) : el.getAttribute('aria-checked')
407
+ if (checked() === String(args.checked)) return 'ok'
408
+ if (native && el.type === 'radio' && !args.checked) return 'wrong'
409
+ el.click()
410
+ await Promise.resolve()
411
+ return el.isConnected && checked() === String(args.checked) ? 'ok' : 'rejected'
412
+ }
413
+ let proto, value, option
414
+ if (action === 'select') {
415
+ if (el.tagName !== 'SELECT') return 'wrong'
416
+ option = [...el.options].find(o => o.value === args.value) ||
417
+ [...el.options].find(o => o.textContent.trim() === args.value)
418
+ if (!option) return 'noOption'
419
+ if (option.disabled || option.parentElement?.disabled) return 'disabled'
420
+ proto = HTMLSelectElement.prototype
421
+ value = option.value
422
+ } else {
423
+ if (action !== 'fill' || el.readOnly || el.getAttribute('aria-readonly') === 'true') return 'wrong'
424
+ if (el.tagName === 'TEXTAREA') proto = HTMLTextAreaElement.prototype
425
+ else if (el.tagName === 'INPUT' && /^(text|search|email|tel|password|url|number)$/.test(el.type)) proto = HTMLInputElement.prototype
426
+ else return 'wrong'
427
+ el.focus()
428
+ if (!el.isConnected || el.getRootNode().activeElement !== el) return 'wrong'
429
+ value = String(args.value ?? '')
430
+ }
431
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, value)
432
+ el.dispatchEvent(new Event('input', { bubbles: true, composed: true }))
433
+ el.dispatchEvent(new Event('change', { bubbles: true }))
434
+ await Promise.resolve()
435
+ if (!el.isConnected || el.value !== value) return 'rejected'
436
+ return option ? { value, label: option.textContent.trim() } : 'ok'
437
+ }
438
+
439
+ const tabSlots = new Map()
440
+ let nextSlot = 0
441
+ let endSlot = 0
442
+ let allocation = Promise.resolve()
443
+ function reserveSlot() {
444
+ // Reserve blocks before use so a restarted MV3 worker never recycles a ref.
445
+ const pending = allocation.then(async () => {
446
+ if (nextSlot === endSlot) {
447
+ nextSlot = (await chrome.storage.session.get('dshFrameSlot')).dshFrameSlot || 1
448
+ endSlot = nextSlot + 256
449
+ await chrome.storage.session.set({ dshFrameSlot: endSlot }).catch(error => { endSlot = nextSlot; throw error })
450
+ }
451
+ return nextSlot++
452
+ })
453
+ allocation = pending.catch(() => {})
454
+ return pending
455
+ }
456
+
457
+ function inject(tabId, target, func, args = []) {
458
+ return chrome.scripting.executeScript({ target: { tabId: Number(tabId), ...target }, world: 'ISOLATED', func, args })
459
+ }
460
+
461
+ async function inDocument(tabId, frame, func, args) {
462
+ // Target the actual document: a frameId check after a write would be too late.
463
+ try {
464
+ const [row] = await inject(tabId, { documentIds: [frame.documentId] }, func, args)
465
+ return row?.documentId === frame.documentId && row.frameId === frame.frameId ? row.result : null
466
+ } catch (error) {
467
+ if (/no document|no frame|frame .*removed|no matching/i.test(error.message)) return null
468
+ throw error
469
+ }
470
+ }
471
+
472
+ async function tree(tabId) {
473
+ const result = await inject(tabId, { allFrames: true }, frameInfo, [null, true])
474
+ const byPath = new Map()
475
+ for (const { frameId, documentId, result: info } of result) {
476
+ if (info && documentId) byPath.set(info.path.join('.'), { frameId, documentId, ...info })
477
+ }
478
+ return byPath
479
+ }
480
+
481
+ async function loadGeometry(tabId, byPath, path) {
482
+ for (let i = 0; i < path.length; i++) {
483
+ const parent = byPath.get(path.slice(0, i).join('.'))
484
+ if (!parent) return null
485
+ if (!parent.children) {
486
+ const info = await inDocument(tabId, parent, frameInfo)
487
+ if (!info) return null
488
+ parent.children = info.children
489
+ }
490
+ }
491
+ return geometry(byPath, path)
492
+ }
493
+
494
+ function geometry(byPath, path) {
495
+ let parent = byPath.get('')
496
+ if (!parent) return null
497
+ let x = 0, y = 0, sx = 1, sy = 1, aligned = true
498
+ let left = 0, top = 0, right = parent.width, bottom = parent.height
499
+ for (let i = 0; i < path.length; i++) {
500
+ const b = parent.children[path[i]]
501
+ parent = byPath.get(path.slice(0, i + 1).join('.'))
502
+ if (!b || !parent) return null
503
+ left = Math.max(left, x + sx * b.left); right = Math.min(right, x + sx * b.right)
504
+ top = Math.max(top, y + sy * b.top); bottom = Math.min(bottom, y + sy * b.bottom)
505
+ x += sx * b.x; y += sy * b.y; sx *= b.sx; sy *= b.sy
506
+ aligned &&= b.aligned
507
+ left = Math.max(left, x); top = Math.max(top, y)
508
+ right = Math.min(right, x + sx * parent.width); bottom = Math.min(bottom, y + sy * parent.height)
509
+ }
510
+ return { x, y, sx, sy, aligned, clip: { left: (left-x)/sx, top: (top-y)/sy, right: (right-x)/sx, bottom: (bottom-y)/sy } }
511
+ }
512
+
513
+ function frameGate(tabId, op, timeoutMs) {
514
+ const deadline = Number.isFinite(timeoutMs) ? Date.now() + timeoutMs : Infinity
515
+ return async (frames, path, previous) => {
516
+ const urls = new Set()
517
+ const add = frame => {
518
+ if (frame?.href) urls.add(frame.href)
519
+ if (frame?.origin && frame.origin !== 'null') urls.add(frame.origin)
520
+ }
521
+ add(previous)
522
+ for (let depth = 0; depth <= path.length; depth++) add(frames.get(path.slice(0, depth).join('.')))
523
+ for (const href of urls) {
524
+ if (!isUrlAllowed(tabId, href)) await ensureUrlAllowed(tabId, href, { op })
525
+ if (S.paused) throw new Error(PAUSED_MSG)
526
+ if (deadline !== Infinity) timeLeft(deadline)
527
+ }
528
+ if ([...urls].some(href => !isUrlAllowed(tabId, href))) throw new Error('USER_DENIED_SENSITIVE')
529
+ }
530
+ }
531
+
532
+ async function collect({ tabId, paths, scope, query = '', timeoutMs }, textOnly) {
533
+ tabId = Number(tabId)
534
+ const allow = frameGate(tabId, textOnly ? 'frameTexts' : 'frameSnapshot', timeoutMs)
535
+ let slots = tabSlots.get(tabId)
536
+ if (!slots) tabSlots.set(tabId, slots = new Map())
537
+ const frames = await tree(tabId)
538
+ const liveDocs = new Set([...frames.values()].map(f => f.documentId))
539
+ for (const [slot, f] of slots) if (!liveDocs.has(f.documentId)) slots.delete(slot)
540
+ const groups = []
541
+ // Chrome only guarantees the main frame's position in allFrames results.
542
+ const ordered = [...frames.values()].sort((a, b) => {
543
+ for (let i = 0; i < Math.min(a.path.length, b.path.length); i++) {
544
+ if (a.path[i] !== b.path[i]) return a.path[i] - b.path[i]
545
+ }
546
+ return a.path.length - b.path.length
547
+ })
548
+ for (const f of ordered) {
549
+ if (!f.frameId || f.href.startsWith('chrome-extension:')) continue
550
+ const root = paths?.find(p => p.length <= f.path.length && p.every((n, i) => n === f.path[i]))
551
+ if (paths ? !root : f.origin === frames.get('')?.origin) continue
552
+ await allow(frames, f.path)
553
+ const g = await loadGeometry(tabId, frames, f.path)
554
+ if (!g) continue
555
+ const path = root || f.path
556
+ if (textOnly) {
557
+ const text = await inDocument(tabId, f, scanPage, [null, 'frameText', '', {}])
558
+ if (text != null) groups.push({ path, src: f.href.slice(0, 120), text })
559
+ if (groups.length === 30) break
560
+ continue
561
+ }
562
+ const data = await inDocument(tabId, f, scanPage, [null, scope || 'all', query, { clip: g.clip }])
563
+ if (!data?.rows) continue
564
+ let slot = [...slots].find(([, entry]) => entry.documentId === f.documentId)?.[0]
565
+ if (!slot) slot = await reserveSlot()
566
+ slots.set(slot, { frameId: f.frameId, documentId: f.documentId, href: f.href, origin: f.origin })
567
+ const rows = data.rows.map(row => {
568
+ if (row.ref == null) return row
569
+ const ref = slot * 10000 + row.ref
570
+ return { ref, line: '[' + ref + ']' + row.line.slice(row.line.indexOf(']') + 1) }
571
+ })
572
+ groups.push({ path, rows, count: data.count, outside: data.outside, capped: data.capped })
573
+ }
574
+ return { groups }
575
+ }
576
+
577
+ async function act({ tabId, ref, timeoutMs, ...args }, action) {
578
+ tabId = Number(tabId)
579
+ const slot = Math.floor(ref / 10000)
580
+ const entry = tabSlots.get(tabId)?.get(slot)
581
+ if (!entry || !Number.isSafeInteger(ref) || !(ref % 10000)) return { gone: true }
582
+
583
+ const op = action === 'locate' ? 'frameLocate' : action === 'select' ? 'frameSelect' : 'frameSetField'
584
+ const allow = frameGate(tabId, op, timeoutMs)
585
+ let frames = await tree(tabId)
586
+ const frame = [...frames.values()].find(f => f.documentId === entry.documentId && f.frameId === entry.frameId)
587
+ if (!frame) return { gone: true }
588
+ await allow(frames, frame.path, entry)
589
+ const apply = () => tabSlots.get(tabId)?.get(slot) === entry
590
+ ? inDocument(tabId, entry, frameAction, [ref % 10000, action, args]) : null
591
+ if (action !== 'locate') {
592
+ // Confirm the frame still has the active document after the prompt.
593
+ // Pin the write to its document ID to also cover the injection race.
594
+ try {
595
+ const [active] = await inject(tabId, { frameIds: [entry.frameId] }, frameInfo, [null, true])
596
+ if (active?.documentId !== entry.documentId) return { gone: true }
597
+ } catch (error) {
598
+ if (/no frame|frame .*removed/i.test(error.message)) return { gone: true }
599
+ throw error
600
+ }
601
+ const result = await apply()
602
+ return result == null ? { gone: true } : { result }
603
+ }
604
+ for (let depth = 0; depth < frame.path.length; depth++) {
605
+ const parent = frames.get(frame.path.slice(0, depth).join('.'))
606
+ if (!parent || !await inDocument(tabId, parent, frameInfo, [frame.path[depth]])) return { gone: true }
607
+ }
608
+ const target = await apply()
609
+ if (!target) return { gone: true }
610
+ frames = await tree(tabId)
611
+ if (frames.get(frame.path.join('.'))?.documentId !== frame.documentId) return { gone: true }
612
+ await allow(frames, frame.path, entry)
613
+ const g = await loadGeometry(tabId, frames, frame.path)
614
+ if (!g?.aligned) return { gone: true }
615
+ const r = target.box
616
+ const box = { x: g.x + r.x * g.sx, y: g.y + r.y * g.sy, width: r.width * g.sx, height: r.height * g.sy }
617
+ const left = Math.max(r.x, g.clip.left), right = Math.min(r.x + r.width, g.clip.right)
618
+ const top = Math.max(r.y, g.clip.top), bottom = Math.min(r.y + r.height, g.clip.bottom)
619
+ if (right <= left || bottom <= top) return { gone: true }
620
+ let x = (left + right) / 2, y = (top + bottom) / 2
621
+ // The iframe's center can be visible while an overlay covers the control.
622
+ for (let i = frame.path.length - 1; i >= 0; i--) {
623
+ const parent = frames.get(frame.path.slice(0, i).join('.'))
624
+ const child = frame.path[i]
625
+ const bounds = parent.children[child]
626
+ x = bounds.x + x * bounds.sx
627
+ y = bounds.y + y * bounds.sy
628
+ if (!await inDocument(tabId, parent, frameInfo, [null, false, { child, x, y }])) return { gone: true }
629
+ }
630
+ return { ...target, box, x, y, shadow: true, crossFrame: true, frameId: frame.frameId }
631
+ }
632
+
633
+ export function initFrames() {
634
+ const ops = {
635
+ frameSnapshot: args => collect(args, false),
636
+ frameTexts: args => collect(args, true),
637
+ frameLocate: args => act(args, 'locate'),
638
+ frameSetField: args => act(args, ['focus', 'fill', 'check'].includes(args.action) ? args.action : 'invalid'),
639
+ frameSelect: args => act(args, 'select'),
640
+ }
641
+ for (const name of Object.keys(ops)) {
642
+ QUEUED.add(name)
643
+ HANDOFF_LOCKED.add(name)
644
+ if (['frameLocate', 'frameSetField', 'frameSelect'].includes(name)) TAKEOVER_OPS.add(name)
645
+ }
646
+ registerOps(ops)
647
+ onTabDetached((id, reason) => {
648
+ if (reason === 'target_closed') tabSlots.delete(id)
649
+ })
650
+ chrome.tabs.onRemoved.addListener(id => tabSlots.delete(id))
651
+ }