dsh-chrome-bridge 1.19.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 (89) 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 +37 -16
  14. package/download.js +895 -69
  15. package/drag.js +68 -30
  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 +312 -16
  22. package/i18n/index.js +17 -0
  23. package/i18n/ru.js +312 -16
  24. package/i18n/zh.js +310 -14
  25. package/image-guard.js +13 -6
  26. package/index.js +21 -1073
  27. package/locale/ru.json +7 -0
  28. package/nav.js +56 -10
  29. package/package.json +8 -1
  30. package/panel.js +14 -4
  31. package/refs.js +293 -240
  32. package/setup.js +248 -74
  33. package/tools/click.js +58 -0
  34. package/tools/devtools.js +61 -0
  35. package/tools/dialog.js +22 -0
  36. package/tools/download.js +50 -0
  37. package/tools/drag.js +61 -0
  38. package/tools/eval.js +22 -0
  39. package/tools/fill.js +77 -0
  40. package/tools/handoff.js +40 -0
  41. package/tools/index.js +38 -0
  42. package/tools/input.js +147 -0
  43. package/tools/nav.js +57 -0
  44. package/tools/read.js +87 -0
  45. package/tools/record.js +120 -0
  46. package/tools/screenshot.js +223 -0
  47. package/tools/tabs.js +131 -0
  48. package/tools/wait.js +56 -0
  49. package/vendor/cb +616 -35
  50. package/vendor/extension/_locales/en/messages.json +3 -0
  51. package/vendor/extension/_locales/ru/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  53. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  54. package/vendor/extension/background.js +2 -1969
  55. package/vendor/extension/confirm.css +148 -0
  56. package/vendor/extension/confirm.html +49 -0
  57. package/vendor/extension/confirm.js +188 -0
  58. package/vendor/extension/in-page-cursor.js +599 -0
  59. package/vendor/extension/manifest.json +11 -2
  60. package/vendor/extension/popup.css +99 -5
  61. package/vendor/extension/popup.html +28 -2
  62. package/vendor/extension/popup.js +430 -45
  63. package/vendor/extension/sw/boot.js +111 -0
  64. package/vendor/extension/sw/cdp.js +411 -0
  65. package/vendor/extension/sw/chooser.js +192 -0
  66. package/vendor/extension/sw/confirm.js +608 -0
  67. package/vendor/extension/sw/cursor.js +241 -0
  68. package/vendor/extension/sw/dispatch.js +129 -0
  69. package/vendor/extension/sw/download.js +279 -0
  70. package/vendor/extension/sw/fetch-hub.js +224 -0
  71. package/vendor/extension/sw/frames.js +651 -0
  72. package/vendor/extension/sw/imaging.js +361 -0
  73. package/vendor/extension/sw/native.js +111 -0
  74. package/vendor/extension/sw/net-tools.js +525 -0
  75. package/vendor/extension/sw/ops.js +829 -0
  76. package/vendor/extension/sw/popup-api.js +303 -0
  77. package/vendor/extension/sw/profile.js +166 -0
  78. package/vendor/extension/sw/record.js +494 -0
  79. package/vendor/extension/sw/state.js +161 -0
  80. package/vendor/extension/sw/tabui.js +219 -0
  81. package/vendor/extension/sw/util.js +166 -0
  82. package/vendor/extension/sw/welcome.js +26 -0
  83. package/vendor/extension/sw/windows.js +94 -0
  84. package/vendor/extension/welcome.css +189 -0
  85. package/vendor/extension/welcome.html +70 -0
  86. package/vendor/extension/welcome.js +157 -0
  87. package/vendor/host/host.js +476 -71
  88. package/vendor/in-page-cursor.js +309 -37
  89. package/vendor/skill/SKILL.md +34 -16
package/refs.js CHANGED
@@ -2,222 +2,43 @@
2
2
  * 元素编号:browser_read(what=snapshot) 给页面上能点 / 能填的元素编上号 [N],
3
3
  * 之后 browser_click / browser_input / browser_screenshot 直接传 ref=N,不用猜 CSS 选择器。
4
4
  *
5
- * 全在插件这一层做,只用宿主已有的 eval op —— 不改扩展。
6
- * (改扩展得让用户去 chrome://extensions 重新加载;插件改了重启 DSH 就行。)
7
- *
8
5
  * 编号怎么记:
9
- * · 元素上打 data-dsh-ref="N" → 编号本身就是选择器 [data-dsh-ref="N"],
10
- * 现成的 clickEl / type / select / upload / hover / shot 全都直接能用
11
- * · 开放 shadow root 里的元素、同源 iframe 里的元素 document.querySelector 够不着,另记一份 WeakRef
12
- * 在 window.__dshSnap.shadow,动作时退回按坐标操作(框架里的坐标加上框架在页面上的位置)
13
- * · 跨站的 iframe 读不到里面(浏览器不让),只列一行提示
6
+ * · 用 window.__dshSnap.refs 的 WeakRef 和 ids 的反向记录核对元素身份
7
+ * · 仅当 [data-dsh-ref="N"] 命中同一元素时,才把它当作动作的选择器
8
+ * · shadow root、同源 iframe 或属性被替换时,按元素的整页视口坐标定位
9
+ * · 跨站 iframe 由扩展在隔离世界维护编号;旧扩展保留框架提示
14
10
  * · 同一个元素再快照沿用旧编号(模型手里的旧编号继续有效);页面跳转后全部失效
15
11
  */
16
12
 
17
- const ATTR = 'data-dsh-ref'
18
-
19
- /** 在页面里跑:扫一遍可操作元素,打编号,返回一行一个的清单。 */
20
- const SNAPSHOT_JS = (scope, maxItems) => `(() => {
21
- const S = window.__dshSnap || (window.__dshSnap = { next: 1, shadow: new Map() });
22
- const ATTR = ${JSON.stringify(ATTR)};
23
- const norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
24
- const cut = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
25
- const q = (s) => JSON.stringify(s);
26
-
27
- const root = ${scope ? `document.querySelector(${JSON.stringify(scope)})` : 'document.body'};
28
- if (!root) return { error: 'scope' };
29
-
30
- const TAGS = new Set(['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'SUMMARY']);
31
- const ROLES = new Set(['button', 'link', 'checkbox', 'radio', 'switch', 'tab', 'menuitem', 'menuitemcheckbox',
32
- 'menuitemradio', 'option', 'combobox', 'textbox', 'searchbox', 'slider', 'spinbutton', 'treeitem', 'listbox']);
33
- const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'META', 'LINK']);
34
- const FORM = new Set(['INPUT', 'SELECT', 'TEXTAREA']);
13
+ import { scanPage } from './vendor/extension/sw/frames.js'
14
+ import { frameField, isFrameRef, locateFrame, mergeFrameSnapshot, mergeFrameTexts } from './features/frames.js'
15
+ import { tt } from './i18n/index.js'
35
16
 
36
- // 框架里的元素按它自己那一页算样式
37
- const css = (el) => (el.ownerDocument.defaultView || window).getComputedStyle(el);
38
- const cursorOf = (el) => { try { return css(el).cursor } catch { return '' } };
39
- const shown = (el, st) => {
40
- const r = el.getBoundingClientRect();
41
- if (r.width < 1 || r.height < 1) return false;
42
- if (st.visibility === 'hidden') return false;
43
- // 自定义样式的复选框常常把 <input> 设成透明叠在上面 —— 它照样接得住点击
44
- if (!FORM.has(el.tagName) && Number(st.opacity) === 0) return false;
45
- return true;
46
- };
47
- const interactive = (el, st) => {
48
- const tag = el.tagName;
49
- if (TAGS.has(tag)) {
50
- if (tag === 'A') return el.hasAttribute('href') || el.hasAttribute('onclick');
51
- if (tag === 'INPUT') return el.type !== 'hidden';
52
- return true;
53
- }
54
- const role = (el.getAttribute('role') || '').split(' ')[0];
55
- if (ROLES.has(role)) return true;
56
- if (el.isContentEditable && !(el.parentElement && el.parentElement.isContentEditable)) return true;
57
- if (el.hasAttribute('onclick')) return true;
58
- if (el.getAttribute('tabindex') !== null && el.tabIndex >= 0 && role !== 'dialog') return true;
59
- // 手搓的 <div> 按钮:认 cursor:pointer,但只认「从这里开始变成手型」的那一层,子元素继承的不算
60
- if (st.cursor === 'pointer') {
61
- const p = el.parentElement;
62
- return !p || cursorOf(p) !== 'pointer';
63
- }
64
- return false;
65
- };
66
- const roleOf = (el) => {
67
- const r = (el.getAttribute('role') || '').split(' ')[0];
68
- if (r) return r;
69
- const tag = el.tagName;
70
- if (tag === 'A') return 'link';
71
- if (tag === 'BUTTON' || tag === 'SUMMARY') return 'button';
72
- if (tag === 'SELECT') return el.multiple ? 'listbox' : 'combobox';
73
- if (tag === 'TEXTAREA') return 'textbox';
74
- if (tag === 'INPUT') {
75
- const t = (el.type || 'text').toLowerCase();
76
- return ({ checkbox: 'checkbox', radio: 'radio', range: 'slider', file: 'file', button: 'button',
77
- submit: 'button', reset: 'button', image: 'button', search: 'searchbox', number: 'spinbutton',
78
- color: 'color', date: 'date', 'datetime-local': 'date', month: 'date', week: 'date', time: 'time' })[t] || 'textbox';
79
- }
80
- if (el.isContentEditable) return 'textbox';
81
- return 'clickable';
82
- };
83
- const byId = (el, id) => {
84
- const r = el.getRootNode();
85
- return (r.getElementById && r.getElementById(id)) || document.getElementById(id);
86
- };
87
- const nameOf = (el) => {
88
- const aria = norm(el.getAttribute('aria-label'));
89
- if (aria) return aria;
90
- const lb = el.getAttribute('aria-labelledby');
91
- if (lb) {
92
- const t = norm(lb.split(/\\s+/).map((id) => { const n = byId(el, id); return n ? n.innerText || n.textContent : ''; }).join(' '));
93
- if (t) return t;
94
- }
95
- if (el.labels && el.labels.length) {
96
- const t = norm([...el.labels].map((l) => l.innerText).join(' '));
97
- if (t) return t;
98
- }
99
- if (el.tagName === 'INPUT' && ['button', 'submit', 'reset'].includes(el.type)) return norm(el.value || el.type);
100
- if (el.tagName === 'INPUT' && el.type === 'image') return norm(el.alt || el.title || 'image');
101
- if (!FORM.has(el.tagName)) {
102
- const t = norm(el.innerText);
103
- if (t) return t;
104
- const img = el.querySelector('img[alt]');
105
- if (img && norm(img.alt)) return norm(img.alt);
106
- const svgTitle = el.querySelector('svg title');
107
- if (svgTitle && norm(svgTitle.textContent)) return norm(svgTitle.textContent);
108
- }
109
- return norm(el.getAttribute('title'));
110
- };
111
- const hrefOf = (el) => {
112
- const h = el.getAttribute('href');
113
- if (!h || h.startsWith('javascript:')) return '';
114
- try {
115
- const u = new URL(h, el.baseURI);
116
- return u.origin === location.origin ? (u.pathname + u.search + u.hash) : (u.host + u.pathname);
117
- } catch { return h; }
118
- };
119
- const stateOf = (el, role) => {
120
- const out = [];
121
- const tag = el.tagName;
122
- if (tag === 'INPUT' && ['checkbox', 'radio'].includes(el.type)) { if (el.checked) out.push('已勾选'); }
123
- else if (el.getAttribute('aria-checked') === 'true') out.push('已勾选');
124
- if (el.getAttribute('aria-selected') === 'true') out.push('已选中');
125
- const ex = el.getAttribute('aria-expanded');
126
- if (ex === 'true') out.push('已展开'); else if (ex === 'false') out.push('已收起');
127
- if (el.disabled || el.getAttribute('aria-disabled') === 'true') out.push('不可用');
128
- if (el.readOnly) out.push('只读');
129
- let extra = '';
130
- if (tag === 'SELECT') {
131
- const o = el.selectedOptions && el.selectedOptions[0];
132
- extra = ' = ' + q(cut(norm(o ? o.textContent : ''), 40)) + '(' + el.options.length + ' 个选项)';
133
- } else if (tag === 'INPUT' && el.type === 'password') {
134
- if (el.value) extra = ' = ••••';
135
- } else if ((tag === 'INPUT' && !['checkbox', 'radio', 'button', 'submit', 'reset', 'image', 'file'].includes(el.type)) || tag === 'TEXTAREA') {
136
- if (el.value) extra = ' = ' + q(cut(norm(el.value), 60));
137
- } else if (role === 'textbox' && el.isContentEditable) {
138
- const t = norm(el.innerText);
139
- if (t) extra = ' = ' + q(cut(t, 60));
140
- }
141
- const ph = el.getAttribute('placeholder');
142
- if (ph && !el.value) extra += ' 提示' + q(cut(norm(ph), 40));
143
- if (tag === 'A') { const h = hrefOf(el); if (h) extra += ' → ' + cut(h, 70); }
144
- return extra + (out.length ? ' (' + out.join(',') + ')' : '');
145
- };
146
-
147
- const seen = new Set();
148
- const assign = (el) => {
149
- let n = Number(el.getAttribute(ATTR)) || 0;
150
- if (n && seen.has(n)) n = 0; // cloneNode 会把属性一起抄过去 —— 撞号就重新发
151
- if (!n) { n = S.next++; el.setAttribute(ATTR, String(n)); }
152
- seen.add(n);
153
- if (el.getRootNode() !== document) S.shadow.set(n, new WeakRef(el));
154
- return n;
155
- };
17
+ const ATTR = 'data-dsh-ref'
156
18
 
157
- const lines = [];
158
- let count = 0, more = 0, scanned = 0;
159
- const MAX = ${Number(maxItems) || 300};
160
- const walk = (parent, depth = 0) => {
161
- for (const el of parent.children) {
162
- if (++scanned > 30000) return;
163
- if (SKIP.has(el.tagName) || el.id === '__dsh_cursor__') continue;
164
- let st;
165
- try { st = css(el); } catch { continue; }
166
- if (st.display === 'none') continue;
167
- if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
168
- if (!shown(el, st)) continue;
169
- const label = '[iframe] ' + cut(el.getAttribute('src') || el.getAttribute('title') || el.getAttribute('name') || '', 80);
170
- let doc = null;
171
- try { doc = el.contentDocument; } catch {}
172
- if (doc && doc.body && depth < 5) {
173
- lines.push(label + ' ↓');
174
- walk(doc.body, depth + 1);
175
- lines.push('[/iframe]');
176
- } else {
177
- lines.push(label + '(跨站框架,读不到里面:browser_screenshot 看,按坐标 x/y 点)');
178
- }
179
- continue;
180
- }
181
- const hm = /^H([1-3])$/.exec(el.tagName);
182
- if (hm && shown(el, st)) {
183
- const t = norm(el.innerText);
184
- if (t) lines.push('#'.repeat(Number(hm[1])) + ' ' + cut(t, 80));
185
- } else if (interactive(el, st) && shown(el, st)) {
186
- if (count >= MAX) { more++; }
187
- else {
188
- const role = roleOf(el);
189
- const name = nameOf(el);
190
- lines.push('[' + assign(el) + '] ' + role + (name ? ' ' + q(cut(name, 80)) : '') + stateOf(el, role));
191
- count++;
192
- }
193
- }
194
- if (el.tagName === 'SELECT' || el.tagName === 'svg') continue;
195
- walk(el, depth);
196
- if (el.shadowRoot) walk(el.shadowRoot, depth);
197
- }
198
- };
199
- walk(root);
200
- if (root.shadowRoot) walk(root.shadowRoot);
201
- return { lines, count, more, scanned, title: document.title, url: location.href };
202
- })()`
19
+ const SNAPSHOT_JS = (selector, scope, query) =>
20
+ `(${scanPage})(${JSON.stringify(selector)}, ${JSON.stringify(scope)}, ${JSON.stringify(query)}, null)`
203
21
 
204
22
  /** 在页面里跑:编号 → 元素。普通元素给选择器;shadow 里的给坐标(顺带滚进视口)。 */
205
- const LOCATE_JS = (ref, wantPoint) => `(async () => {
23
+ const LOCATE_JS = (ref, wantPoint, expectedDocId) => `(async () => {
206
24
  const sel = ${JSON.stringify(`[${ATTR}="${ref}"]`)};
207
- let el = document.querySelector(sel);
208
- let shadow = false;
209
- if (!el) {
210
- const w = window.__dshSnap && window.__dshSnap.shadow.get(${Number(ref)});
211
- el = w && w.deref();
212
- shadow = true;
213
- }
25
+ const getRef = () => ${refElementJs(ref, expectedDocId)};
26
+ const el = getRef();
214
27
  // 框架跳转过的话,旧元素还「连着」它那份已经作废的文档:defaultView 没了就算失效
215
28
  if (!el || !el.isConnected || !el.ownerDocument.defaultView) return { gone: true };
216
- // 密码框的 value 绝不拿出来(会进工具结果、上光标名牌)
29
+ const shadow = el.getRootNode() !== document || document.querySelector(sel) !== el;
30
+ // 敏感输入不进入工具结果或光标名牌。
31
+ const masked = (${scanPage})(el, 'mask', el.ownerDocument.defaultView.getComputedStyle(el));
217
32
  const out = { shadow, selector: shadow ? null : sel, tag: el.tagName.toLowerCase(),
218
- text: (el.innerText || (el.type === 'password' ? '' : el.value) || el.getAttribute('aria-label') || '').replace(/\\s+/g, ' ').trim().slice(0, 60) };
33
+ text: (masked ? '••••' : el.innerText || el.value || el.getAttribute('aria-label') || '').replace(/\\s+/g, ' ').trim().slice(0, 60) };
219
34
  if (!${wantPoint ? 'true' : 'false'} && !shadow) return out;
220
- return { ...out, ...(await ${BOX_FN}(el)) };
35
+ const point = await ${BOX_FN}(el);
36
+ if (getRef() !== el) return { gone: true };
37
+ if (!out.shadow && document.querySelector(sel) !== el) {
38
+ out.shadow = true;
39
+ out.selector = null;
40
+ }
41
+ return { ...out, ...point };
221
42
  })()`
222
43
 
223
44
  /**
@@ -242,34 +63,90 @@ const BOX_FN = `(async (el) => {
242
63
  box: { x: left, y: top, width: r.width, height: r.height } };
243
64
  })`
244
65
 
245
- /** 页内表达式:编号 → 元素(找不到是 null)。普通元素按属性找,shadow / 框架里的查 WeakRef 表。 */
246
- export const refElementJs = (ref) => `(document.querySelector(${JSON.stringify(`[${ATTR}="${Number(ref)}"]`)}) || (() => {
247
- const w = window.__dshSnap && window.__dshSnap.shadow.get(${Number(ref)});
248
- const el = w && w.deref();
249
- return el && el.isConnected && el.ownerDocument.defaultView ? el : null;
250
- })())`
66
+ /** 页内表达式:只信快照登记的元素,不从 DOM 属性反查编号。 */
67
+ export const refElementJs = (ref, expectedDocId) => `(() => {
68
+ const number = ${Number(ref)};
69
+ const state = window.__dshSnap;
70
+ if (${expectedDocId !== undefined} && state?.documentId !== ${JSON.stringify(expectedDocId)}) return null;
71
+ const el = state?.refs?.get(number)?.deref();
72
+ if (!el || !el.isConnected || !el.ownerDocument.defaultView || state.ids?.get(el) !== number) return null;
73
+ return el;
74
+ })()`
75
+
76
+ const tabDocs = new Map()
77
+ export const tabRefElementJs = (tabId, ref) => refElementJs(ref, tabDocs.get(tabId))
251
78
 
252
- const goneError = (ref) =>
253
- new Error(`编号 ${ref} 已失效(页面变了或跳转过)——重新 browser_read what=snapshot 拿新编号`)
79
+ const goneError = (ref) => new Error(tt('err.refGone', { ref }))
254
80
 
255
81
  /**
256
82
  * 拍快照:返回给模型看的文本。
257
83
  * @param call 与宿主通话的函数(index.js 的 call)
258
84
  */
259
- export async function snapshot(call, tabId, { selector, limit = 8000, maxItems = 300 } = {}) {
260
- const r = await call('eval', { tabId, expression: SNAPSHOT_JS(selector, maxItems), userGesture: false })
85
+ const snapshotHistory = new Map()
86
+ const SNAPSHOT_CHARS = 8000
87
+
88
+ export async function snapshot(call, tabId, { selector, scope = 'all', diff = false, query = '', cursor = 0, limit = 300, maxItems } = {}) {
89
+ const key = JSON.stringify([tabId, selector || '', scope, query.trim().toLowerCase()])
90
+ const previous = snapshotHistory.get(key)
91
+ const r = await call('eval', { tabId, expression: SNAPSHOT_JS(selector, scope, query.trim().toLowerCase()), userGesture: false })
261
92
  const v = r.value
262
- if (!v) throw new Error('页面没返回快照(可能刚跳转,重试一次)')
263
- if (v.error === 'scope') throw new Error(`没找到元素: ${selector}`)
93
+ if (!v) throw new Error(tt('err.snapshotFailed'))
94
+ if (v.error === 'scope') throw new Error(tt('err.noElement', { sel: selector }))
95
+
96
+ await mergeFrameSnapshot(call, tabId, v, scope, query)
264
97
 
265
- const head = `${v.title || ''}\n${v.url}\n可操作元素 ${v.count} 个([N] 是编号:browser_click / browser_input 传 ref=N)`
266
- const body = v.lines.join('\n') || '(没找到可操作的元素)'
267
- let text = `${head}\n\n${body}`
268
- if (v.more) text += `\n…还有 ${v.more} 个元素没列出——传 selector 只看页面的一部分`
269
- if (text.length > limit) {
270
- const cutAt = text.lastIndexOf('\n', limit)
271
- text = text.slice(0, cutAt > 0 ? cutAt : limit) + `\n…(截断,全文 ${text.length} 字——传 selector 缩小范围,或调大 limit)`
98
+ tabDocs.delete(tabId)
99
+ tabDocs.set(tabId, v.documentId)
100
+ if (tabDocs.size > 256) tabDocs.delete(tabDocs.keys().next().value)
101
+
102
+ const old = previous?.url === v.url && previous.documentId === v.documentId ? previous : null
103
+ const lines = new Map(v.rows.filter(({ ref }) => ref !== undefined).map(({ ref, line }) => [ref, line]))
104
+ let rows = v.rows.map(({ line }) => line)
105
+ let mode = ''
106
+ if (diff) {
107
+ if (old && cursor > 0 && old.diffPage) {
108
+ ({ rows, mode } = old.diffPage)
109
+ } else if (old) {
110
+ rows = []
111
+ for (const [ref, line] of lines) {
112
+ if (!old.lines.has(ref)) rows.push(`[+] ${line}`)
113
+ else if (old.lines.get(ref) !== line) rows.push(`[~] ${line}`)
114
+ }
115
+ for (const [ref, line] of old.lines) if (!lines.has(ref)) rows.push(`[-] ${line}`)
116
+ mode = tt('res.snap.diff', { count: rows.length })
117
+ } else {
118
+ mode = tt('res.snap.full')
119
+ }
120
+ }
121
+
122
+ const head = [v.title, v.url, tt('res.snap.head', { count: v.count }), mode].filter(Boolean).join('\n')
123
+ const page = []
124
+ let chars = head.length
125
+ const end = Math.min(rows.length, cursor + (maxItems ?? limit))
126
+ for (let i = cursor; i < end; i++) {
127
+ if (page.length && chars + rows[i].length + 1 > SNAPSHOT_CHARS) break
128
+ page.push(rows[i])
129
+ chars += rows[i].length + 1
130
+ }
131
+ const next = cursor + page.length
132
+ snapshotHistory.delete(key)
133
+ snapshotHistory.set(key, {
134
+ url: v.url,
135
+ documentId: v.documentId,
136
+ lines: cursor > 0 && old ? old.lines : lines,
137
+ diffPage: diff && next < rows.length ? { rows, mode } : null,
138
+ })
139
+ let cachedRows = [...snapshotHistory.values()].reduce((sum, entry) => sum + entry.lines.size + (entry.diffPage?.rows.length || 0), 0)
140
+ for (const [view, entry] of snapshotHistory) {
141
+ if (snapshotHistory.size === 1 || snapshotHistory.size <= 16 && cachedRows <= 60_000) break
142
+ cachedRows -= entry.lines.size + (entry.diffPage?.rows.length || 0)
143
+ snapshotHistory.delete(view)
272
144
  }
145
+ const empty = diff && old ? tt('res.snap.noChanges') : tt('res.snap.nothing')
146
+ let text = `${head}\n\n${page.join('\n') || empty}`
147
+ if (next < rows.length) text += tt('res.snap.more', { more: rows.length - next, cursor: next })
148
+ if (v.outside) text += tt('res.snap.outside', { count: v.outside })
149
+ if (v.capped) text += tt('res.snap.scanCap')
273
150
  return text
274
151
  }
275
152
 
@@ -280,8 +157,9 @@ export async function snapshot(call, tabId, { selector, limit = 8000, maxItems =
280
157
  */
281
158
  export async function locate(call, tabId, ref, { wantPoint = false } = {}) {
282
159
  const n = Number(ref)
283
- if (!Number.isInteger(n) || n < 1) throw new Error(`编号要是正整数,收到的是 ${ref}`)
284
- const r = await call('eval', { tabId, expression: LOCATE_JS(n, wantPoint), userGesture: false })
160
+ if (!Number.isInteger(n) || n < 1) throw new Error(tt('err.refNotInt', { ref }))
161
+ if (isFrameRef(n)) return locateFrame(call, tabId, n)
162
+ const r = await call('eval', { tabId, expression: LOCATE_JS(n, wantPoint, tabDocs.get(tabId)), userGesture: false })
285
163
  const v = r.value
286
164
  if (!v || v.gone) throw goneError(n)
287
165
  return v
@@ -304,40 +182,45 @@ export async function elementBox(call, tabId, { ref, selector }) {
304
182
  })()`,
305
183
  userGesture: false,
306
184
  })
307
- if (!r.value) throw new Error(`没找到元素: ${selector}`)
185
+ if (!r.value) throw new Error(tt('err.noElement', { sel: selector }))
308
186
  return r.value
309
187
  }
310
188
 
311
- /** shadow DOM 里的元素:直接在页面里聚焦(document.querySelector 够不着它)。 */
189
+ /** 选择器无法定位时,直接聚焦快照记录的元素。 */
312
190
  export async function focusShadow(call, tabId, ref) {
191
+ if (isFrameRef(ref)) return frameField(call, tabId, 'frameSetField', { ref, action: 'focus' })
313
192
  const n = Number(ref)
314
193
  const r = await call('eval', {
315
194
  tabId,
316
195
  expression: `(() => {
317
- const w = window.__dshSnap && window.__dshSnap.shadow.get(${n});
318
- const el = w && w.deref();
319
- if (!el || !el.isConnected || !el.ownerDocument.defaultView) return null;
196
+ const el = ${tabRefElementJs(tabId, n)};
197
+ if (!el) return null;
320
198
  el.focus();
321
199
  return el.getRootNode().activeElement === el;
322
200
  })()`,
323
201
  })
324
202
  if (r.value === null) throw goneError(n)
325
- if (!r.value) throw new Error(`编号 ${n} 聚焦失败(元素可能不可聚焦)`)
203
+ if (!r.value) throw new Error(tt('err.refFocus', { n }))
326
204
  }
327
205
 
328
206
  /** shadow DOM / 框架里的下拉框:直接在页面里选(扩展的 select 只认 document.querySelector 找得到的)。 */
329
207
  export async function selectInPage(call, tabId, ref, value) {
208
+ if (isFrameRef(ref)) return frameField(call, tabId, 'frameSelect', { ref, value: String(value) })
330
209
  const n = Number(ref)
331
210
  const r = await call('eval', {
332
211
  tabId,
333
212
  expression: `(() => {
334
- const el = ${refElementJs(n)};
213
+ const el = ${tabRefElementJs(tabId, n)};
335
214
  if (!el) return null;
336
- if (el.tagName !== 'SELECT') return { ok: false, why: '不是 <select> 元素' };
215
+ if (el.tagName !== 'SELECT') return { ok: false, why: ${JSON.stringify(tt('err.selectNotSelect'))} };
337
216
  const v = ${JSON.stringify(String(value))};
338
217
  const opts = [...el.options];
218
+ if (el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true') {
219
+ return { ok: false, why: ${JSON.stringify(tt('err.fieldDisabled'))} };
220
+ }
339
221
  const hit = opts.find((o) => o.value === v) || opts.find((o) => (o.textContent || '').trim() === v);
340
- if (!hit) return { ok: false, why: '没有这个选项', options: opts.map((o) => o.value).slice(0, 20) };
222
+ if (hit?.disabled || hit?.parentElement?.disabled) return { ok: false, why: ${JSON.stringify(tt('err.fieldDisabled'))} };
223
+ if (!hit) return { ok: false, why: ${JSON.stringify(tt('err.selectNoOption'))}, options: opts.map((o) => o.value).slice(0, 20) };
341
224
  el.value = hit.value;
342
225
  el.dispatchEvent(new Event('input', { bubbles: true }));
343
226
  el.dispatchEvent(new Event('change', { bubbles: true }));
@@ -347,32 +230,202 @@ export async function selectInPage(call, tabId, ref, value) {
347
230
  })
348
231
  const v = r.value
349
232
  if (v === null) throw goneError(n)
350
- if (!v.ok) throw new Error(`选择失败:${v.why}${v.options ? '(可选值:' + v.options.join(', ') + ')' : ''}`)
233
+ if (!v.ok) {
234
+ throw new Error(
235
+ tt('err.selectFailed', {
236
+ why: v.why,
237
+ options: v.options ? tt('err.selectOptions', { options: v.options.join(', ') }) : '',
238
+ }),
239
+ )
240
+ }
351
241
  return v
352
242
  }
353
243
 
354
- /** 同源 iframe 里的可见文字(document.body.innerText 不含框架内容);跨站的只给一行提示。 */
244
+ /** 按嵌套位置合并每个 iframe 的可见文字,旧版扩展保留跨站提示。 */
355
245
  export async function frameTexts(call, tabId) {
356
246
  const r = await call('eval', {
357
247
  tabId,
358
248
  expression: `(() => {
359
249
  const out = [];
360
- const walk = (doc, depth) => {
250
+ const walk = (doc, depth, path) => {
361
251
  for (const f of doc.querySelectorAll('iframe, frame')) {
362
252
  const b = f.getBoundingClientRect();
363
253
  if (b.width < 2 || b.height < 2) continue;
364
254
  const src = (f.getAttribute('src') || f.getAttribute('title') || f.getAttribute('name') || '').slice(0, 120);
255
+ const index = Array.prototype.indexOf.call(doc.defaultView.frames || [], f.contentWindow);
256
+ const childPath = [...path, index];
365
257
  let d = null;
366
258
  try { d = f.contentDocument; } catch {}
367
- if (!d || !d.body) { out.push({ src, cross: true }); continue; }
259
+ if (!d?.body || d.defaultView?.origin !== doc.defaultView.origin) { out.push({ src, cross: true, path: childPath }); continue; }
368
260
  out.push({ src, text: (d.body.innerText || '').trim() });
369
- if (depth < 4) walk(d, depth + 1);
261
+ if (depth < 4) walk(d, depth + 1, childPath);
370
262
  }
371
263
  };
372
- walk(document, 0);
264
+ walk(document, 0, []);
373
265
  return out.slice(0, 30);
374
266
  })()`,
375
267
  userGesture: false,
376
268
  })
377
- return Array.isArray(r.value) ? r.value : []
269
+ const rows = Array.isArray(r.value) ? r.value : []
270
+ return mergeFrameTexts(call, tabId, rows)
271
+ }
272
+
273
+ const elementFor = (tabId, { ref, selector }) => ref != null ? tabRefElementJs(tabId, ref)
274
+ : selector ? `document.querySelector(${JSON.stringify(selector)})` : 'document.activeElement'
275
+
276
+ function missingTarget({ ref, selector }) {
277
+ return ref != null ? goneError(ref) : new Error(tt('err.noElement', { sel: selector || tt('res.input.active') }))
278
+ }
279
+
280
+ export async function setField(call, tabId, args) {
281
+ const { action, checked, value } = args
282
+ if (action === 'select') return selectInPage(call, tabId, args.ref, value)
283
+ if (isFrameRef(args.ref)) return frameField(call, tabId, 'frameSetField', args)
284
+ const { value: result } = await call('eval', {
285
+ tabId,
286
+ userGesture: false,
287
+ expression: `(async () => {
288
+ const el = ${elementFor(tabId, args)};
289
+ if (!el || !el.isConnected) return null;
290
+ if (el.matches(':disabled') || el.getAttribute('aria-disabled') === 'true') return 'disabled';
291
+ if (${action === 'check'}) {
292
+ const desired = ${checked === true};
293
+ const native = el.tagName === 'INPUT' && ['checkbox', 'radio'].includes(el.type);
294
+ const custom = ['checkbox', 'switch', 'radio'].includes(el.getAttribute('role'));
295
+ if (!native && !custom) return 'wrong';
296
+ const state = () => native ? el.checked && !el.indeterminate : el.getAttribute('aria-checked') === 'true';
297
+ const mixed = native ? el.indeterminate : el.getAttribute('aria-checked') === 'mixed';
298
+ if (!mixed && state() === desired) return 'ok';
299
+ if (native && el.type === 'radio' && !desired) return 'wrong';
300
+ el.click();
301
+ await Promise.resolve();
302
+ return state() === desired && !(native && el.indeterminate) && el.getAttribute('aria-checked') !== 'mixed' ? 'ok' : 'rejected';
303
+ }
304
+ const view = el.ownerDocument.defaultView;
305
+ if (el.isContentEditable) return 'wrong';
306
+ const proto = el.tagName === 'TEXTAREA' ? view.HTMLTextAreaElement.prototype
307
+ : el.tagName === 'INPUT' && ['text', 'search', 'password', 'email', 'tel', 'url', 'number'].includes(el.type)
308
+ ? view.HTMLInputElement.prototype : null;
309
+ if (!proto || el.readOnly || el.getAttribute('aria-readonly') === 'true') return 'wrong';
310
+ el.focus();
311
+ if (!el.isConnected) return null;
312
+ if (el.getRootNode().activeElement !== el) return 'wrong';
313
+ const value = ${JSON.stringify(String(value ?? ''))};
314
+ el.select();
315
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, value);
316
+ el.dispatchEvent(new view.Event('input', { bubbles: true, composed: true }));
317
+ el.dispatchEvent(new view.Event('change', { bubbles: true }));
318
+ await Promise.resolve();
319
+ if (!el.isConnected) return null;
320
+ if (el.value !== value) return 'rejected';
321
+ return 'ok';
322
+ })()`,
323
+ })
324
+ if (result == null) throw missingTarget(args)
325
+ if (result === 'disabled') throw new Error(tt('err.fieldDisabled'))
326
+ if (result === 'wrong') throw new Error(tt('err.fieldWrong'))
327
+ if (result !== 'ok') throw new Error(tt('err.fieldRejected'))
328
+ }
329
+
330
+ export async function scrollElement(call, tabId, args) {
331
+ const dx = Number.isFinite(Number(args.dx)) ? Number(args.dx) : 0
332
+ const dy = Number.isFinite(Number(args.dy)) ? Number(args.dy) : 600
333
+ const r = await call('eval', {
334
+ tabId,
335
+ userGesture: false,
336
+ expression: `(() => {
337
+ const el = ${elementFor(tabId, args)};
338
+ if (!el) return null;
339
+ const view = el.ownerDocument.defaultView || window;
340
+ const scrollable = (n) => {
341
+ if (!n || n.nodeType !== 1) return false;
342
+ const canY = n.scrollHeight > n.clientHeight + 1;
343
+ const canX = n.scrollWidth > n.clientWidth + 1;
344
+ if (!canY && !canX) return false;
345
+ const st = view.getComputedStyle(n);
346
+ if (!st || (st.overflowY === undefined && st.overflowX === undefined)) return n === el;
347
+ return (canY && /auto|scroll|overlay/.test(st.overflowY)) || (canX && /auto|scroll|overlay/.test(st.overflowX));
348
+ };
349
+ let target = el;
350
+ if (!scrollable(target)) {
351
+ let cur = el.parentElement;
352
+ while (cur && !scrollable(cur)) cur = cur.parentElement;
353
+ target = cur || el.ownerDocument.scrollingElement || el.ownerDocument.documentElement || el;
354
+ }
355
+ target.scrollBy({ left: ${dx}, top: ${dy}, behavior: 'instant' });
356
+ return { scrollTop: Math.round(target.scrollTop), scrollHeight: target.scrollHeight };
357
+ })()`,
358
+ })
359
+ if (!r.value) throw missingTarget(args)
360
+ return r.value
361
+ }
362
+
363
+ export async function readStructured(call, tabId, { what, selector, limit }) {
364
+ const { value } = await call('eval', {
365
+ tabId,
366
+ userGesture: false,
367
+ expression: `(() => {
368
+ const root = ${selector ? `document.querySelector(${JSON.stringify(selector)})`
369
+ : what === 'table' ? 'document.body' : "document.querySelector('main, [role=main]') || document.querySelector('article') || document.body"};
370
+ if (!root) return null;
371
+ const clean = (text) => String(text || '').replace(/\\s+/g, ' ').trim();
372
+ const visible = (el) => {
373
+ if (el.closest('script, style, noscript, template, [hidden], [aria-hidden=true]')) return false;
374
+ const style = el.ownerDocument.defaultView.getComputedStyle(el);
375
+ return style.visibility !== 'hidden' && (el.getClientRects().length > 0 || style.display === 'contents');
376
+ };
377
+ const max = ${Math.max(1, limit) + 1};
378
+ let out = '';
379
+ if (${what === 'table'}) {
380
+ const tables = root.tagName === 'TABLE' ? [root] : root.querySelectorAll('table');
381
+ for (const table of tables) {
382
+ if (!visible(table)) continue;
383
+ if (out) out += '\\n';
384
+ for (const row of table.rows) {
385
+ if (!visible(row)) continue;
386
+ out += Array.from(row.cells, (cell) => clean(cell.innerText || cell.textContent)).join('\\t') + '\\n';
387
+ if (out.length >= max) return out.slice(0, max);
388
+ }
389
+ }
390
+ return out.replace(/\\n+$/, '');
391
+ }
392
+ const escape = (s) => s.replace(/[\\\\*_\`\\[\\]<>]/g, (char) => '\\\\' + char);
393
+ const inline = (node) => {
394
+ if (node.nodeType === 3) return escape(node.nodeValue.replace(/\\s+/g, ' '));
395
+ if (node.nodeType !== 1 || !visible(node)) return '';
396
+ if (node.tagName === 'BR') return ' ';
397
+ const body = Array.from(node.childNodes, inline).join('');
398
+ if (node.tagName !== 'A' || !body.trim() || !node.hasAttribute('href')) return body;
399
+ try {
400
+ const url = new URL(node.getAttribute('href'), node.baseURI);
401
+ if (!['https:', 'http:', 'mailto:'].includes(url.protocol)) return body;
402
+ return '[' + body.trim() + '](<' + url.href.replace(/>/g, '%3E') + '>)';
403
+ } catch { return body; }
404
+ };
405
+ const append = (line) => { if (line && out.length < max) out += (out ? '\\n' : '') + line; };
406
+ const walk = (el, depth = 0) => {
407
+ if (out.length >= max || depth > 30 || !visible(el)) return;
408
+ if (/^H[1-6]$/.test(el.tagName)) append('#'.repeat(Number(el.tagName[1])) + ' ' + clean(inline(el)) + '\\n');
409
+ else if (['P', 'BLOCKQUOTE', 'A', 'PRE'].includes(el.tagName)) append(clean(inline(el)) + '\\n');
410
+ else if (['OL', 'UL'].includes(el.tagName)) {
411
+ let index = el.start || 1;
412
+ for (const item of el.children) {
413
+ if (out.length >= max) break;
414
+ if (item.tagName !== 'LI' || !visible(item)) continue;
415
+ const nodes = Array.from(item.childNodes);
416
+ const text = clean(nodes.filter((node) => !['OL', 'UL'].includes(node.tagName)).map(inline).join(''));
417
+ if (text) append(' '.repeat(depth) + (el.tagName === 'OL' ? index++ + '. ' : '- ') + text);
418
+ for (const node of nodes) if (['OL', 'UL'].includes(node.tagName)) walk(node, depth + 1);
419
+ }
420
+ if (!depth && out) out += '\\n';
421
+ } else {
422
+ for (const child of el.children) walk(child, depth);
423
+ }
424
+ };
425
+ walk(root);
426
+ return (out.trim() || clean(inline(root))).slice(0, max);
427
+ })()`,
428
+ })
429
+ if (value === null && selector) throw new Error(tt('err.noElement', { sel: selector }))
430
+ return value || ''
378
431
  }