@liyuera/dsh-chrome-browser 0.3.0 → 0.5.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 (100) hide show
  1. package/README.md +238 -12
  2. package/extension/icons/icon-128.png +0 -0
  3. package/extension/icons/icon-16.png +0 -0
  4. package/extension/icons/icon-32.png +0 -0
  5. package/extension/icons/icon-48.png +0 -0
  6. package/extension/manifest.json +12 -5
  7. package/extension/service-worker.js +772 -70
  8. package/lib/activity.d.ts +65 -0
  9. package/lib/activity.d.ts.map +1 -0
  10. package/lib/activity.js +111 -0
  11. package/lib/activity.js.map +1 -0
  12. package/lib/backend.d.ts +235 -11
  13. package/lib/backend.d.ts.map +1 -1
  14. package/lib/backend.js +429 -40
  15. package/lib/backend.js.map +1 -1
  16. package/lib/cdp.d.ts +7 -1
  17. package/lib/cdp.d.ts.map +1 -1
  18. package/lib/cdp.js +17 -1
  19. package/lib/cdp.js.map +1 -1
  20. package/lib/chrome.d.ts +8 -0
  21. package/lib/chrome.d.ts.map +1 -1
  22. package/lib/chrome.js +20 -0
  23. package/lib/chrome.js.map +1 -1
  24. package/lib/client/BrowserActivity.d.ts +22 -0
  25. package/lib/client/BrowserActivity.d.ts.map +1 -0
  26. package/lib/client/BrowserActivity.js +100 -0
  27. package/lib/client/BrowserActivity.js.map +1 -0
  28. package/lib/client/activity.d.ts +27 -0
  29. package/lib/client/activity.d.ts.map +1 -0
  30. package/lib/client/activity.js +57 -0
  31. package/lib/client/activity.js.map +1 -0
  32. package/lib/client/index.d.ts +4 -6
  33. package/lib/client/index.d.ts.map +1 -1
  34. package/lib/client/index.js +13 -19
  35. package/lib/client/index.js.map +1 -1
  36. package/lib/client/tab-catalog.d.ts +11 -1
  37. package/lib/client/tab-catalog.d.ts.map +1 -1
  38. package/lib/client/tab-catalog.js.map +1 -1
  39. package/lib/client/tab-source.d.ts +8 -2
  40. package/lib/client/tab-source.d.ts.map +1 -1
  41. package/lib/client/tab-source.js.map +1 -1
  42. package/lib/client.js +177 -13
  43. package/lib/client.js.map +1 -1
  44. package/lib/console-events.d.ts +32 -0
  45. package/lib/console-events.d.ts.map +1 -0
  46. package/lib/console-events.js +106 -0
  47. package/lib/console-events.js.map +1 -0
  48. package/lib/console-log.d.ts +107 -0
  49. package/lib/console-log.d.ts.map +1 -0
  50. package/lib/console-log.js +158 -0
  51. package/lib/console-log.js.map +1 -0
  52. package/lib/expressions.d.ts +71 -2
  53. package/lib/expressions.d.ts.map +1 -1
  54. package/lib/expressions.js +277 -14
  55. package/lib/expressions.js.map +1 -1
  56. package/lib/extension-package.d.ts +49 -0
  57. package/lib/extension-package.d.ts.map +1 -1
  58. package/lib/extension-package.js +115 -0
  59. package/lib/extension-package.js.map +1 -1
  60. package/lib/help.d.ts +89 -0
  61. package/lib/help.d.ts.map +1 -0
  62. package/lib/help.js +94 -0
  63. package/lib/help.js.map +1 -0
  64. package/lib/index.d.ts +4 -2
  65. package/lib/index.d.ts.map +1 -1
  66. package/lib/index.js +30 -9
  67. package/lib/index.js.map +1 -1
  68. package/lib/presentation.d.ts +130 -0
  69. package/lib/presentation.d.ts.map +1 -0
  70. package/lib/presentation.js +361 -0
  71. package/lib/presentation.js.map +1 -0
  72. package/lib/routes.d.ts +3 -8
  73. package/lib/routes.d.ts.map +1 -1
  74. package/lib/routes.js +24 -109
  75. package/lib/routes.js.map +1 -1
  76. package/lib/skill.d.ts +50 -0
  77. package/lib/skill.d.ts.map +1 -0
  78. package/lib/skill.js +164 -0
  79. package/lib/skill.js.map +1 -0
  80. package/lib/text.d.ts +21 -0
  81. package/lib/text.d.ts.map +1 -1
  82. package/lib/text.js +18 -0
  83. package/lib/text.js.map +1 -1
  84. package/lib/tools.d.ts +22 -4
  85. package/lib/tools.d.ts.map +1 -1
  86. package/lib/tools.js +493 -75
  87. package/lib/tools.js.map +1 -1
  88. package/lib/ws.d.ts +9 -2
  89. package/lib/ws.d.ts.map +1 -1
  90. package/lib/ws.js +49 -19
  91. package/lib/ws.js.map +1 -1
  92. package/package.json +5 -3
  93. package/lib/bindings.d.ts +0 -23
  94. package/lib/bindings.d.ts.map +0 -1
  95. package/lib/bindings.js +0 -49
  96. package/lib/bindings.js.map +0 -1
  97. package/lib/client/TabPicker.d.ts +0 -54
  98. package/lib/client/TabPicker.d.ts.map +0 -1
  99. package/lib/client/TabPicker.js +0 -329
  100. package/lib/client/TabPicker.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * dsh Chrome Bridge service worker: a long-lived WebSocket to the local dsh
2
+ * dsh Chrome Control service worker: a long-lived WebSocket to the local dsh
3
3
  * host. The host pushes commands (list tabs / read / eval / click / type /
4
4
  * navigate / open / screenshot); this worker executes them against the real
5
5
  * browser and pushes results back. The open socket keeps the worker alive,
@@ -44,6 +44,10 @@ function connect() {
44
44
  retryMs = 1000
45
45
  hostOrigin = url.replace(/^ws/u, 'http').replace(/\/chrome-browser\/ext\/ws$/u, '')
46
46
  trace('open ' + url)
47
+ hello()
48
+ // Chrome suspends this worker when idle, which detaches the debugger and
49
+ // silently ends console capture. Re-arm whatever was capturing.
50
+ void rearmConsole()
47
51
  }
48
52
  socket.onmessage = (event) => { void handle(event.data) }
49
53
  socket.onerror = () => { /* onclose follows */ }
@@ -68,7 +72,11 @@ function scheduleRetry() {
68
72
  // does not keep this worker alive: a JS heartbeat interval keeps it warm,
69
73
  // and the alarm below wakes a suspended worker so the bridge reconnects.
70
74
  setInterval(() => {
71
- if (socket !== null && socket.readyState === 1) send({ kind: 'heartbeat' })
75
+ if (socket === null || socket.readyState !== 1) return
76
+ send({ kind: 'heartbeat' })
77
+ // Re-introducing here is what lets the host notice that its own files were
78
+ // updated underneath a running extension, without waiting for a reconnect.
79
+ hello()
72
80
  }, 20_000)
73
81
 
74
82
  chrome.alarms.create('dsh-bridge', { periodInMinutes: 0.5 })
@@ -78,6 +86,44 @@ chrome.alarms.onAlarm.addListener(alarm => {
78
86
  chrome.runtime.onStartup.addListener(() => connect())
79
87
  chrome.runtime.onInstalled.addListener(() => connect())
80
88
 
89
+ /**
90
+ * Ops this worker answers, sent to the host on connect and on every heartbeat.
91
+ *
92
+ * Chrome never re-reads an unpacked extension's files, so a host that shipped a
93
+ * new op would otherwise only find out when the extension answered `unknown op`
94
+ * — an internal error with no hint that a reload is what is missing. Comparing
95
+ * this roster, and the version beside it, is what lets the host say so.
96
+ * tests/extension-scope.spec.ts keeps the list equal to the cases in run().
97
+ */
98
+ const SUPPORTED_OPS = [
99
+ 'list-tabs', 'read', 'inventory', 'wait', 'hover', 'press', 'select', 'eval',
100
+ 'click', 'type', 'console-start', 'console-stop', 'close', 'navigate', 'open',
101
+ 'screenshot', 'trace', 'reload',
102
+ ]
103
+
104
+ /**
105
+ * Fingerprint of this extension's own files, written by `npm run extension:stamp`
106
+ * and checked by tests/extension-package.spec.ts.
107
+ *
108
+ * It is a constant rather than a hash computed here on purpose. Measured in a
109
+ * real browser: `fetch(chrome.runtime.getURL('service-worker.js'))` returns the
110
+ * file on DISK, not the copy Chrome loaded, so a runtime self-hash reported the
111
+ * new bytes while the old code was still running — the host saw a match and the
112
+ * user stayed on a stale extension with nothing to show for it. Only a value
113
+ * carried by the loaded code can tell the host which code is loaded.
114
+ */
115
+ const BUILD_HASH = 'd985d7da53d76c69be7b9a72879970e33a1e440a01a2741081820c8045ec55e0'
116
+
117
+ /** Introduce this worker: what it runs, what it can answer, and which code it is. */
118
+ async function hello() {
119
+ send({
120
+ kind: 'hello',
121
+ version: chrome.runtime.getManifest().version,
122
+ ops: SUPPORTED_OPS,
123
+ build: BUILD_HASH,
124
+ })
125
+ }
126
+
81
127
  function send(payload) {
82
128
  if (socket !== null && socket.readyState === 1) socket.send(JSON.stringify(payload))
83
129
  }
@@ -119,10 +165,14 @@ async function handle(data) {
119
165
  trace('op ' + command.op + ' ' + command.seq)
120
166
  try {
121
167
  // One stuck op (page hang, capture on a hidden window) must never block
122
- // the sequential loop; each op gets its own absolute deadline.
168
+ // the sequential loop; each op gets its own absolute deadline. The op was
169
+ // already dispatched, so its outcome is unknown rather than failed — the
170
+ // host must not have the model retry a click or a type blindly.
123
171
  const outcome = await Promise.race([
124
172
  run(command),
125
- new Promise((resolve, reject) => setTimeout(() => reject(new Error(`${command.op} 超时(12s)`)), 12000)),
173
+ new Promise((resolve, reject) => setTimeout(() => reject(new Error(
174
+ `${command.op} 超时(12s):结果未知,不要直接重试,先确认页面当前状态`,
175
+ )), 12000)),
126
176
  ])
127
177
  results.push({ seq: command.seq, ok: true, data: safe(outcome) })
128
178
  trace('op-ok ' + command.seq)
@@ -134,6 +184,212 @@ async function handle(data) {
134
184
  if (results.length > 0) send({ kind: 'results', results })
135
185
  }
136
186
 
187
+ // ---------------------------------------------------------------- console
188
+ //
189
+ // Console capture attaches Chrome's debugger to one tab and forwards what the
190
+ // page (and the browser) logs. It cannot be a wrapper around `console`: the
191
+ // most useful messages — failed requests, CSP refusals, deprecations — are
192
+ // raised by the browser, never by a page call. Attaching shows Chrome's
193
+ // "started debugging this browser" bar on that tab until capture stops.
194
+ //
195
+ // The host holds the entries in a bounded per-tab buffer; this worker only
196
+ // forwards. It keeps the capture set in storage.session so that a suspended
197
+ // worker can re-attach instead of losing capture silently.
198
+
199
+ /** storage.session key holding the tab ids currently captured. */
200
+ const CONSOLE_TABS_KEY = 'consoleTabs'
201
+
202
+ /** Entries buffered before a flush is forced, so a logging loop cannot grow it. */
203
+ const CONSOLE_QUEUE_MAX = 50
204
+
205
+ /** Delay that batches a burst into one frame. */
206
+ const CONSOLE_FLUSH_MS = 100
207
+
208
+ let consoleQueue = []
209
+ let consoleTimer = null
210
+
211
+ /** Tab ids this worker is capturing, from session storage (survives suspension). */
212
+ async function consoleTabs() {
213
+ try {
214
+ const data = await chrome.storage.session.get(CONSOLE_TABS_KEY)
215
+ const tabs = data[CONSOLE_TABS_KEY]
216
+ return Array.isArray(tabs) ? tabs.filter(id => typeof id === 'number') : []
217
+ } catch {
218
+ return []
219
+ }
220
+ }
221
+
222
+ async function setConsoleTabs(tabs) {
223
+ await chrome.storage.session.set({ [CONSOLE_TABS_KEY]: tabs })
224
+ }
225
+
226
+ /**
227
+ * Mirrors `consoleMessageFrom` in the host's src/console-events.ts, which maps
228
+ * the same events for the CDP backend. The bridge cannot import host modules,
229
+ * so the two copies must stay in step; tests/console-capture.spec.ts requires
230
+ * them to agree on the same recorded events.
231
+ */
232
+ function renderRemote(value) {
233
+ if (typeof value !== 'object' || value === null) return String(value)
234
+ const type = typeof value.type === 'string' ? value.type : 'object'
235
+ if (type === 'undefined') return 'undefined'
236
+ if (value.value !== undefined && value.value !== null) return String(value.value)
237
+ if (value.value === null) return 'null'
238
+ const preview = typeof value.preview === 'object' && value.preview !== null ? value.preview : undefined
239
+ if (preview !== undefined) {
240
+ const properties = Array.isArray(preview.properties) ? preview.properties : []
241
+ const rendered = properties.map((property) => {
242
+ if (typeof property !== 'object' || property === null) return '?'
243
+ const name = typeof property.name === 'string' ? property.name : '?'
244
+ const shown = property.value !== undefined ? String(property.value) : String(property.type ?? '?')
245
+ return `${name}: ${shown}`
246
+ })
247
+ const head = typeof preview.description === 'string' && preview.description !== '' ? preview.description : ''
248
+ const more = preview.overflow === true ? ', …' : ''
249
+ return `${head}{${rendered.join(', ')}${more}}`
250
+ }
251
+ if (typeof value.description === 'string' && value.description !== '') return value.description
252
+ return type
253
+ }
254
+
255
+ function sourceFromStack(stackTrace) {
256
+ if (typeof stackTrace !== 'object' || stackTrace === null) return undefined
257
+ const frames = stackTrace.callFrames
258
+ if (!Array.isArray(frames)) return undefined
259
+ const first = frames[0]
260
+ if (typeof first !== 'object' || first === null) return undefined
261
+ const url = typeof first.url === 'string' ? first.url : ''
262
+ const line = typeof first.lineNumber === 'number' ? first.lineNumber + 1 : undefined
263
+ if (url === '') return undefined
264
+ return line === undefined ? url : `${url}:${line}`
265
+ }
266
+
267
+ function sourceFromEntry(entry) {
268
+ const url = typeof entry.url === 'string' ? entry.url : ''
269
+ if (url === '') return undefined
270
+ const line = typeof entry.lineNumber === 'number' ? entry.lineNumber : undefined
271
+ return line === undefined ? url : `${url}:${line}`
272
+ }
273
+
274
+ const MAX_ARG_CHARS = 2048
275
+
276
+ function consoleMessageFrom(method, params) {
277
+ if (method === 'Runtime.consoleAPICalled') {
278
+ const args = Array.isArray(params.args) ? params.args : []
279
+ const text = args.map(renderRemote).join(' ').slice(0, MAX_ARG_CHARS)
280
+ const level = typeof params.type === 'string' ? params.type : 'log'
281
+ const source = sourceFromStack(params.stackTrace)
282
+ return source === undefined ? { level, text } : { level, text, source }
283
+ }
284
+ if (method === 'Log.entryAdded') {
285
+ const entry = params.entry
286
+ if (typeof entry !== 'object' || entry === null) return undefined
287
+ const text = typeof entry.text === 'string' ? entry.text : ''
288
+ if (text === '') return undefined
289
+ const level = typeof entry.level === 'string' ? entry.level : 'info'
290
+ const source = sourceFromEntry(entry)
291
+ return source === undefined ? { level, text } : { level, text, source }
292
+ }
293
+ return undefined
294
+ }
295
+
296
+ /** Group a batch by tab and push one frame per tab. */
297
+ function flushConsole() {
298
+ if (consoleTimer !== null) {
299
+ clearTimeout(consoleTimer)
300
+ consoleTimer = null
301
+ }
302
+ if (consoleQueue.length === 0) return
303
+ const batch = consoleQueue
304
+ consoleQueue = []
305
+ const byTab = new Map()
306
+ for (const item of batch) {
307
+ const list = byTab.get(item.tabId)
308
+ const entry = item.source === undefined
309
+ ? { level: item.level, text: item.text }
310
+ : { level: item.level, text: item.text, source: item.source }
311
+ if (list === undefined) byTab.set(item.tabId, [entry])
312
+ else list.push(entry)
313
+ }
314
+ for (const [tabId, entries] of byTab) send({ kind: 'event', event: 'console', tabId, entries })
315
+ }
316
+
317
+ /**
318
+ * Buffer one message. The queue drains on a short timer or at
319
+ * CONSOLE_QUEUE_MAX, so it stays bounded even while the socket is down; a
320
+ * closed socket drops the batch rather than growing without limit.
321
+ */
322
+ function queueConsole(tabId, entry) {
323
+ consoleQueue.push({ tabId, ...entry })
324
+ if (consoleQueue.length >= CONSOLE_QUEUE_MAX) {
325
+ flushConsole()
326
+ return
327
+ }
328
+ if (consoleTimer === null) consoleTimer = setTimeout(flushConsole, CONSOLE_FLUSH_MS)
329
+ }
330
+
331
+ /** Attach the debugger to one tab, or report why it cannot be captured. */
332
+ async function startConsole(tabId) {
333
+ const id = Number(tabId)
334
+ if (!Number.isInteger(id)) throw new Error(`无效的标签页 id:${String(tabId)}`)
335
+ const targets = await chrome.debugger.getTargets()
336
+ const existing = targets.find(target => target.tabId === id && target.attached === true)
337
+ if (existing !== undefined && existing.extensionId !== chrome.runtime.id) {
338
+ throw new Error('该标签页已被另一个调试器占用(例如已打开 DevTools);请关闭后重试')
339
+ }
340
+ if (existing === undefined) await chrome.debugger.attach({ tabId: id }, '1.3')
341
+ // Log.enable also replays entries the browser buffered before enabling it.
342
+ await chrome.debugger.sendCommand({ tabId: id }, 'Runtime.enable')
343
+ await chrome.debugger.sendCommand({ tabId: id }, 'Log.enable')
344
+ const tabs = await consoleTabs()
345
+ if (!tabs.includes(id)) await setConsoleTabs([...tabs, id])
346
+ trace('console-start ' + id)
347
+ return { tabId: String(id) }
348
+ }
349
+
350
+ async function stopConsole(tabId) {
351
+ const id = Number(tabId)
352
+ const tabs = await consoleTabs()
353
+ await setConsoleTabs(tabs.filter(candidate => candidate !== id))
354
+ try {
355
+ await chrome.debugger.detach({ tabId: id })
356
+ } catch {
357
+ // Already detached, or the tab is gone: that is the state we wanted.
358
+ }
359
+ trace('console-stop ' + id)
360
+ return { tabId: String(id) }
361
+ }
362
+
363
+ /** Re-attach every captured tab, dropping the ones that can no longer be captured. */
364
+ async function rearmConsole() {
365
+ for (const id of await consoleTabs()) {
366
+ try {
367
+ await startConsole(id)
368
+ } catch (error) {
369
+ trace('console-rearm-failed ' + id + ' ' + String((error && error.message) || error).slice(0, 60))
370
+ await stopConsole(id)
371
+ }
372
+ }
373
+ }
374
+
375
+ chrome.debugger.onEvent.addListener((source, method, params) => {
376
+ if (typeof source.tabId !== 'number') return
377
+ const entry = consoleMessageFrom(method, params || {})
378
+ if (entry === undefined) return
379
+ queueConsole(String(source.tabId), entry)
380
+ })
381
+
382
+ // A user opening DevTools force-detaches us; stop claiming to capture that tab
383
+ // rather than re-attaching behind them.
384
+ chrome.debugger.onDetach.addListener((source) => {
385
+ if (typeof source.tabId !== 'number') return
386
+ void consoleTabs().then(async (tabs) => {
387
+ if (!tabs.includes(source.tabId)) return
388
+ await setConsoleTabs(tabs.filter(id => id !== source.tabId))
389
+ trace('console-detached ' + source.tabId)
390
+ })
391
+ })
392
+
137
393
  async function run(command) {
138
394
  switch (command.op) {
139
395
  case 'list-tabs': {
@@ -148,12 +404,46 @@ async function run(command) {
148
404
  }
149
405
  case 'read':
150
406
  return pageExec(command.args.tabId, readPage, [command.args.includeHtml === true])
407
+ case 'inventory':
408
+ return pageExec(command.args.tabId, pageAgent, [{ op: 'inventory' }])
409
+ case 'wait':
410
+ return pageExec(command.args.tabId, waitCondition, [command.args.selector, command.args.state])
411
+ case 'hover':
412
+ return pageExec(command.args.tabId, hoverSelector, [command.args.selector])
413
+ case 'press':
414
+ // `undefined` is not a serializable injection argument, so an omitted
415
+ // selector travels as null and pressKey treats null as "current focus".
416
+ return pageExec(command.args.tabId, pageAgent, [{
417
+ op: 'press',
418
+ key: command.args.key,
419
+ selector: command.args.selector === undefined ? null : command.args.selector,
420
+ }])
421
+ case 'select':
422
+ return pageExec(command.args.tabId, selectOption, [command.args.selector, command.args.value])
151
423
  case 'eval':
152
- return pageExec(command.args.tabId, evalExpression, [command.args.expression])
424
+ return evalInPage(command.args.tabId, command.args.expression)
153
425
  case 'click':
154
- return pageExec(command.args.tabId, clickSelector, [command.args.selector, command.args.all === true])
426
+ return pageExec(command.args.tabId, pageAgent, [
427
+ { op: 'click', selector: command.args.selector, all: command.args.all === true },
428
+ ])
155
429
  case 'type':
156
430
  return pageExec(command.args.tabId, typeInto, [command.args.selector, command.args.text || '', command.args.clear !== false])
431
+ case 'console-start':
432
+ return startConsole(command.args.tabId)
433
+ case 'console-stop':
434
+ return stopConsole(command.args.tabId)
435
+ case 'reload': {
436
+ // Answer first: `chrome.runtime.reload()` tears this worker down, so a
437
+ // result sent after it would never leave. The delay lets the frame flush.
438
+ setTimeout(() => chrome.runtime.reload(), 50)
439
+ return { reloaded: true }
440
+ }
441
+ case 'close': {
442
+ const id = Number(command.args.tabId)
443
+ if (!Number.isInteger(id)) throw new Error(`无效的标签页 id:${String(command.args.tabId)}`)
444
+ await chrome.tabs.remove(id)
445
+ return { tabId: String(id) }
446
+ }
157
447
  case 'navigate': {
158
448
  const tab = await chrome.tabs.update(Number(command.args.tabId), { url: command.args.url })
159
449
  return { id: tab.id, title: tab.title || '', url: tab.url || '', active: tab.active === true }
@@ -163,16 +453,15 @@ async function run(command) {
163
453
  return { id: tab.id, title: tab.title || '', url: tab.url || '', active: true }
164
454
  }
165
455
  case 'screenshot': {
166
- const tab = await chrome.tabs.get(Number(command.args.tabId))
167
- await chrome.tabs.update(tab.id, { active: true })
168
- // The capture below snapshots the window's visible tab; give the
169
- // activation a beat to paint.
170
- await new Promise(resolve => setTimeout(resolve, 150))
171
- const dataUrl = await captureVisibleWithCooldown(tab.windowId)
172
- // Image bytes travel back as a plain HTTP POST, never as a WS JSON
173
- // frame: an oversized base64 frame closed the bridge right after a
174
- // successful capture. The host persists the upload and returns a path.
175
- const blob = await (await fetch(dataUrl)).blob()
456
+ // Through the debugger, not `chrome.tabs.captureVisibleTab`: that one
457
+ // needs the window visible and painting, so it fails with "image readback
458
+ // failed" while the user is looking at something else — and when the
459
+ // window merely stops repainting it returns the PREVIOUS frame with no
460
+ // sign that it did. Page.captureScreenshot has neither problem.
461
+ const base64 = await captureViaDebugger(Number(command.args.tabId))
462
+ // Image bytes travel back as a plain HTTP POST, never as a WS JSON frame:
463
+ // an oversized frame closed the bridge right after a successful capture.
464
+ const blob = await (await fetch('data:image/jpeg;base64,' + base64)).blob()
176
465
  const upload = await fetch(`${hostOrigin}/chrome-browser/ext/upload`, {
177
466
  method: 'POST',
178
467
  headers: { 'content-type': 'application/octet-stream' },
@@ -192,59 +481,250 @@ async function run(command) {
192
481
  }
193
482
  }
194
483
 
195
- // Chrome rate-limits captureVisibleTab per window (invocations close in
196
- // time hit a quota error and screenshots fail). Serialize captures, keep a
197
- // 800ms minimum gap, and back off once before retrying a quota refusal.
198
- let captureChain = Promise.resolve()
199
- let lastCaptureAt = 0
200
-
201
- // A minimized or hidden window can make captureVisibleTab never settle,
202
- // which would block the whole (sequential) command loop; bound it.
203
- // JPEG at 75 keeps the payload far smaller than PNG: an oversized data URL
204
- // (tens of MB) building a JSON message can OOM-kill the MV3 worker right
205
- // after the capture, mid-send.
206
- function captureWithTimeout(windowId) {
207
- return new Promise((resolve, reject) => {
208
- const timer = setTimeout(() => {
209
- const error = new Error('截图超时(10s),请确认该窗口可见')
210
- error.isCaptureTimeout = true
211
- reject(error)
212
- }, 10000)
213
- chrome.tabs.captureVisibleTab(windowId, { format: 'jpeg', quality: 75 }).then(
214
- data => { clearTimeout(timer); resolve(data) },
215
- error => { clearTimeout(timer); reject(error) },
216
- )
217
- })
484
+ /** JPEG quality the screenshot is encoded at before upload. */
485
+ const SCREENSHOT_QUALITY = 75
486
+
487
+ /**
488
+ * Capture one tab as base64 JPEG through the debugger protocol.
489
+ *
490
+ * `Page.captureScreenshot` renders the tab rather than reading back the window's
491
+ * painted surface, so it works while the tab is in the background and cannot
492
+ * answer with a stale frame. It costs the debugger infobar on that tab, which is
493
+ * why a tab `chrome_console` already attached needs no second attach.
494
+ */
495
+ async function captureViaDebugger(tabId) {
496
+ const id = Number(tabId)
497
+ if (!Number.isInteger(id)) throw new Error(`无效的标签页 id:${String(tabId)}`)
498
+ const targets = await chrome.debugger.getTargets()
499
+ const existing = targets.find(target => target.tabId === id && target.attached === true)
500
+ if (existing !== undefined && existing.extensionId !== chrome.runtime.id) {
501
+ throw new Error('该标签页已被另一个调试器占用(例如已打开 DevTools),无法截图;请关闭 DevTools 后重试')
502
+ }
503
+ const ours = existing !== undefined
504
+ if (!ours) await chrome.debugger.attach({ tabId: id }, '1.3')
505
+ try {
506
+ const response = await chrome.debugger.sendCommand({ tabId: id }, 'Page.captureScreenshot', {
507
+ format: 'jpeg',
508
+ quality: SCREENSHOT_QUALITY,
509
+ captureBeyondViewport: false,
510
+ })
511
+ if (response === undefined || typeof response.data !== 'string' || response.data === '') {
512
+ throw new Error('截图失败:调试通道没有返回图像数据')
513
+ }
514
+ return response.data
515
+ } finally {
516
+ if (!ours) {
517
+ try {
518
+ await chrome.debugger.detach({ tabId: id })
519
+ } catch (error) {
520
+ // Already detached or the tab is gone: that is the state we wanted.
521
+ if (!/not attached|No tab/i.test(String(error && error.message))) throw error
522
+ }
523
+ }
524
+ }
218
525
  }
219
526
 
220
- async function captureVisibleWithCooldown(windowId) {
221
- const run = async () => {
222
- const waitMs = Math.max(0, lastCaptureAt + 800 - Date.now())
223
- if (waitMs > 0) await new Promise(resolve => setTimeout(resolve, waitMs))
224
- lastCaptureAt = Date.now()
225
- try {
226
- return await captureWithTimeout(windowId)
227
- } catch (error) {
228
- // A hidden window times out and a retry cannot help it; only quota
229
- // refusals deserve the back-off retry.
230
- if (error && error.isCaptureTimeout === true) throw error
231
- await new Promise(resolve => setTimeout(resolve, 1500))
232
- lastCaptureAt = Date.now()
233
- return await captureWithTimeout(windowId)
527
+ /**
528
+ * Every page-side helper, nested inside the one function Chrome injects.
529
+ *
530
+ * `chrome.scripting.executeScript` serializes a function's SOURCE and runs it in
531
+ * the page: the closure does not come along. A helper that calls another
532
+ * top-level helper, or reads a top-level const, therefore fails in the page with
533
+ * a ReferenceError while working perfectly in a test that concatenates the
534
+ * declarations into one scope. Nesting them here gives them one real scope.
535
+ * tests/extension-scope.spec.ts fails if a declaration referenced from here is
536
+ * left outside.
537
+ */
538
+ function pageAgent(request) {
539
+ const KEY_CODES = {
540
+ Enter: 13,
541
+ Escape: 27,
542
+ Tab: 9,
543
+ Backspace: 8,
544
+ Delete: 46,
545
+ ArrowUp: 38,
546
+ ArrowDown: 40,
547
+ ArrowLeft: 37,
548
+ ArrowRight: 39,
549
+ Home: 36,
550
+ End: 35,
551
+ PageUp: 33,
552
+ PageDown: 34,
553
+ ' ': 32,
554
+ }
555
+
556
+ // Must stay identical to INTERACTIVE_SELECTOR in the host's src/expressions.ts;
557
+ // a truncated value silently narrows what the inventory can see.
558
+ const INVENTORY_SELECTOR = 'a[href],button,input,select,textarea,[role=button],[role=link],'
559
+ + '[role=checkbox],[role=radio],[role=tab],[role=menuitem],[role=switch],[contenteditable=""],[contenteditable=true]'
560
+
561
+ const INVENTORY_LIMIT = 150
562
+
563
+ const MAX_NAME_CHARS = 80
564
+
565
+ function describeTarget(el) {
566
+ if (el.disabled === true) return 'disabled'
567
+ const rect = el.getBoundingClientRect()
568
+ if (rect.width === 0 || rect.height === 0) return 'invisible'
569
+ const style = getComputedStyle(el)
570
+ if (style.visibility === 'hidden' || style.display === 'none') return 'invisible'
571
+ const x = rect.left + rect.width / 2
572
+ const y = rect.top + rect.height / 2
573
+ if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) return 'offscreen'
574
+ const root = el.getRootNode()
575
+ const from = root && typeof root.elementFromPoint === 'function' ? root : document
576
+ const hit = from.elementFromPoint(x, y)
577
+ if (hit === null) return 'offscreen'
578
+ return hit === el || el.contains(hit) ? 'ok' : 'covered'
579
+ }
580
+
581
+ function cssEscape(value) {
582
+ return (typeof CSS !== 'undefined' && CSS.escape)
583
+ ? CSS.escape(value)
584
+ : String(value).replace(/[^a-zA-Z0-9_-]/g, (ch) => '\\' + ch)
585
+ }
586
+
587
+ function stableSelector(el) {
588
+ if (el.id) {
589
+ const byId = '#' + cssEscape(el.id)
590
+ try {
591
+ if (document.querySelectorAll(byId).length === 1) return byId
592
+ } catch (error) {
593
+ // An id that is not a usable selector: fall through to the path.
594
+ }
595
+ }
596
+ const parts = []
597
+ let node = el
598
+ for (let depth = 0; node && node.nodeType === 1 && depth < 4; depth++) {
599
+ const tag = node.tagName.toLowerCase()
600
+ const parent = node.parentElement
601
+ if (parent === null) {
602
+ parts.unshift(tag)
603
+ break
604
+ }
605
+ const siblings = Array.from(parent.children).filter((child) => child.tagName === node.tagName)
606
+ parts.unshift(siblings.length > 1 ? tag + ':nth-of-type(' + (siblings.indexOf(node) + 1) + ')' : tag)
607
+ node = parent
234
608
  }
609
+ return parts.join(' > ')
610
+ }
611
+
612
+ function nameOf(el) {
613
+ const raw = el.getAttribute('aria-label')
614
+ || (el.innerText && el.innerText.trim())
615
+ || el.value
616
+ || el.getAttribute('placeholder')
617
+ || el.getAttribute('title')
618
+ || el.getAttribute('name')
619
+ || ''
620
+ return String(raw).replace(/\s+/g, ' ').trim().slice(0, MAX_NAME_CHARS)
621
+ }
622
+
623
+ function clickSelector(selector, all) {
624
+ const matched = document.querySelectorAll(selector)
625
+ const targets = all ? Array.from(matched) : matched.length > 0 ? [matched[0]] : []
626
+ const outcome = {
627
+ matched: matched.length, clicked: 0, disabled: 0, invisible: 0, offscreen: 0, covered: 0, ariaDisabled: 0,
628
+ }
629
+ for (const el of targets) {
630
+ const state = describeTarget(el)
631
+ if (state === 'disabled') { outcome.disabled++; continue }
632
+ if (state !== 'ok') outcome[state]++
633
+ if (el.getAttribute('aria-disabled') === 'true') outcome.ariaDisabled++
634
+ el.click()
635
+ outcome.clicked++
636
+ }
637
+ return outcome
638
+ }
639
+
640
+ function interactiveInventory() {
641
+ const matched = document.querySelectorAll(INVENTORY_SELECTOR)
642
+ const items = []
643
+ for (const el of matched) {
644
+ if (items.length >= INVENTORY_LIMIT) break
645
+ const rect = el.getBoundingClientRect()
646
+ if (rect.width === 0 || rect.height === 0) continue
647
+ const style = getComputedStyle(el)
648
+ if (style.visibility === 'hidden' || style.display === 'none') continue
649
+ const state = describeTarget(el)
650
+ items.push({
651
+ selector: stableSelector(el),
652
+ role: el.getAttribute('role') || el.tagName.toLowerCase(),
653
+ name: nameOf(el),
654
+ inView: state !== 'offscreen',
655
+ disabled: el.disabled === true || el.getAttribute('aria-disabled') === 'true',
656
+ covered: state === 'covered',
657
+ })
658
+ }
659
+ return { title: document.title, url: location.href, matched: matched.length, items }
660
+ }
661
+
662
+ function pressKey(key, selector) {
663
+ const el = selector === undefined || selector === null || selector === ''
664
+ ? document.activeElement
665
+ : document.querySelector(selector)
666
+ if (el === null) return { found: false, pressed: false, submitted: false }
667
+ const node = el === null ? document.body : el
668
+ if (typeof node.focus === 'function') node.focus()
669
+ const init = { key, bubbles: true, cancelable: true, keyCode: KEY_CODES[key] || 0 }
670
+ node.dispatchEvent(new KeyboardEvent('keydown', init))
671
+ node.dispatchEvent(new KeyboardEvent('keypress', init))
672
+ node.dispatchEvent(new KeyboardEvent('keyup', init))
673
+ let submitted = false
674
+ if (key === 'Enter') {
675
+ const form = node.form || (typeof node.closest === 'function' ? node.closest('form') : null)
676
+ if (form && typeof form.requestSubmit === 'function') {
677
+ form.requestSubmit()
678
+ submitted = true
679
+ }
680
+ }
681
+ return { found: true, pressed: true, submitted }
682
+ }
683
+
684
+ // A throw must not escape: `chrome.scripting.executeScript` answers it with
685
+ // `result: undefined` and no `error`, so a malformed selector would reach the
686
+ // model as "no element matched" — the page never saw the query at all.
687
+ try {
688
+ switch (request.op) {
689
+ case 'click': return clickSelector(request.selector, request.all === true)
690
+ case 'inventory': return interactiveInventory()
691
+ case 'press': return pressKey(request.key, request.selector)
692
+ default: return { __dshPageError: '未知的页面操作:' + request.op }
693
+ }
694
+ } catch (error) {
695
+ return { __dshPageError: String((error && error.message) || error) }
235
696
  }
236
- captureChain = captureChain.then(run, run)
237
- return captureChain
238
697
  }
239
698
 
240
- async function pageExec(tabId, func, args) {
699
+ /**
700
+ * Run one injected helper and report a throw as a failure.
701
+ *
702
+ * `chrome.scripting.executeScript` answers an exception inside the injected
703
+ * function with `result: undefined`, so a broken helper would reach the host as
704
+ * `null` — where it reads as "nothing matched". That is how a malformed CSS
705
+ * selector turned into "no element matched selector", and how an undefined
706
+ * helper turned into an empty inventory.
707
+ */
708
+ async function pageExec(tabId, func, args, world) {
241
709
  const [injection] = await chrome.scripting.executeScript({
242
710
  target: { tabId: Number(tabId) },
243
- world: 'MAIN',
711
+ world: world || 'MAIN',
244
712
  func,
245
713
  args,
246
714
  })
247
- return injection !== undefined && injection.result !== undefined ? injection.result : null
715
+ if (injection === undefined) throw new Error('无法注入该标签页(可能已关闭或不允许脚本注入)')
716
+ if (injection.error !== undefined && injection.error !== null) {
717
+ const thrown = injection.error
718
+ const message = thrown.description || thrown.value || '注入的脚本抛出了异常'
719
+ throw new Error(String(message))
720
+ }
721
+ const result = injection.result === undefined ? null : injection.result
722
+ // The MAIN world reports a throw as `result: undefined` alone, so a helper
723
+ // that fails says so in its own envelope instead.
724
+ if (typeof result === 'object' && result !== null && typeof result.__dshPageError === 'string') {
725
+ throw new Error(result.__dshPageError)
726
+ }
727
+ return result
248
728
  }
249
729
 
250
730
  /** MAIN-world helpers (functions are serialized; no outer scope). */
@@ -258,23 +738,231 @@ function readPage(includeHtml) {
258
738
  }
259
739
  }
260
740
 
741
+ /**
742
+ * Evaluate one expression and report the outcome as data.
743
+ *
744
+ * The throw must not escape this function: `chrome.scripting.executeScript`
745
+ * turns an escaping exception into `result: undefined`, which reaches the model
746
+ * as a silent `null` — a syntax error, a runtime throw and a blocked `eval`
747
+ * would all read as "the value is null". The `__dshEval` tag is what tells the
748
+ * host this envelope apart from an expression that legitimately returns an
749
+ * object with `ok`/`value` keys.
750
+ */
261
751
  function evalExpression(expression) {
262
- const value = (0, eval)(expression)
263
- return value === undefined ? 'undefined' : value
752
+ try {
753
+ const value = (0, eval)(expression)
754
+ return { __dshEval: 1, ok: true, value: value === undefined ? null : value }
755
+ } catch (error) {
756
+ return { __dshEval: 1, ok: false, error: String((error && error.message) || error) }
757
+ }
758
+ }
759
+
760
+ /** Whether a failed main-world evaluation failed because the page forbids `eval`. */
761
+ function isEvalBlocked(message) {
762
+ return /unsafe-eval|Content Security Policy|EvalError|call to eval\(\)/i.test(message)
264
763
  }
265
764
 
266
- function clickSelector(selector, all) {
267
- const matched = document.querySelectorAll(selector)
268
- let count = 0
269
- if (all) {
270
- for (const el of matched) { el.click(); count++ }
271
- } else if (matched.length > 0) {
272
- matched[0].click()
273
- count = 1
765
+ /**
766
+ * Run one expression through the debugger protocol.
767
+ *
768
+ * `Runtime.evaluate` is not subject to the page's Content-Security-Policy, which
769
+ * is the whole reason this path exists: on a page whose `script-src` omits
770
+ * `unsafe-eval` — GitHub is one — neither the page's own world nor the
771
+ * extension's isolated world may call `eval`. This is also the path the CDP
772
+ * backend has always used, so an expression means the same thing on both.
773
+ *
774
+ * A per-call attach shows the debugger infobar on that tab and is refused while
775
+ * DevTools is open, so it is a fallback rather than the default.
776
+ */
777
+ async function evalViaDebugger(tabId, expression) {
778
+ const id = Number(tabId)
779
+ if (!Number.isInteger(id)) throw new Error(`无效的标签页 id:${String(tabId)}`)
780
+ const targets = await chrome.debugger.getTargets()
781
+ const existing = targets.find(target => target.tabId === id && target.attached === true)
782
+ if (existing !== undefined && existing.extensionId !== chrome.runtime.id) {
783
+ throw new Error('该标签页已被另一个调试器占用(例如已打开 DevTools),无法执行表达式;请关闭 DevTools 后重试')
784
+ }
785
+ // Console capture may already hold this tab: reuse its session and leave it attached.
786
+ const ours = existing !== undefined
787
+ if (!ours) await chrome.debugger.attach({ tabId: id }, '1.3')
788
+ try {
789
+ const response = await chrome.debugger.sendCommand({ tabId: id }, 'Runtime.evaluate', {
790
+ expression,
791
+ returnByValue: true,
792
+ awaitPromise: true,
793
+ })
794
+ if (response !== undefined && response.exceptionDetails !== undefined) {
795
+ const details = response.exceptionDetails
796
+ const thrown = details.exception
797
+ const message = (thrown !== undefined && (thrown.description || thrown.value)) || details.text || '表达式执行出错'
798
+ throw new Error(String(message))
799
+ }
800
+ const result = response === undefined ? undefined : response.result
801
+ if (result === undefined) return null
802
+ // A result the protocol could not serialize by value arrives as a description.
803
+ return Object.prototype.hasOwnProperty.call(result, 'value') ? result.value : null
804
+ } finally {
805
+ if (!ours) {
806
+ try {
807
+ await chrome.debugger.detach({ tabId: id })
808
+ } catch (error) {
809
+ // Already detached or the tab is gone: that is the state we wanted.
810
+ if (!/not attached|No tab/i.test(String(error && error.message))) throw error
811
+ }
812
+ }
274
813
  }
275
- return count
276
814
  }
277
815
 
816
+ /**
817
+ * Run one expression and report the outcome as data.
818
+ *
819
+ * Prefers the page's own world, because that is where the page's JavaScript
820
+ * globals live. When the page's Content-Security-Policy forbids `eval` there,
821
+ * the debugger protocol runs the same expression under no such policy and the
822
+ * answer says which route it took.
823
+ */
824
+ async function evalInPage(tabId, expression) {
825
+ const main = await pageExec(tabId, evalExpression, [expression], 'MAIN')
826
+ if (main !== null && main.ok === true) {
827
+ return { __dshEval: 1, ok: true, value: main.value, world: 'main' }
828
+ }
829
+ const mainError = main !== null && typeof main.error === 'string' ? main.error : 'evaluation failed'
830
+ if (!isEvalBlocked(mainError)) return { __dshEval: 1, ok: false, error: mainError }
831
+
832
+ try {
833
+ const value = await evalViaDebugger(tabId, expression)
834
+ return { __dshEval: 1, ok: true, value, world: 'debugger' }
835
+ } catch (error) {
836
+ const debuggerError = String((error && error.message) || error)
837
+ return {
838
+ __dshEval: 1,
839
+ ok: false,
840
+ error: '页面的 CSP 禁止主世界 eval,调试通道也无法执行。主世界: '
841
+ + mainError + ';调试通道: ' + debuggerError,
842
+ }
843
+ }
844
+ }
845
+
846
+ /**
847
+ * Why one element may not receive a working click, as a single verdict. Mirrors
848
+ * the `probe` inside CLICK_PROBE in the host's src/expressions.ts; tests/click-outcome.spec.ts
849
+ * runs both against the same stub DOM and requires identical output.
850
+ */
851
+
852
+
853
+
854
+
855
+ /**
856
+ * Wait condition. Mirrors `waitExpression` in the host's src/expressions.ts,
857
+ * which the CDP backend evaluates for the same polls; tests/primitives.spec.ts
858
+ * requires the two to agree on every state.
859
+ */
860
+ function waitCondition(selector, state) {
861
+ const el = document.querySelector(selector)
862
+ const attached = el !== null
863
+ let shown = false
864
+ if (attached) {
865
+ const rect = el.getBoundingClientRect()
866
+ if (rect.width > 0 && rect.height > 0) {
867
+ const style = getComputedStyle(el)
868
+ shown = style.visibility !== 'hidden' && style.display !== 'none'
869
+ }
870
+ }
871
+ if (state === 'attached') return attached
872
+ if (state === 'detached') return !attached
873
+ if (state === 'visible') return attached && shown
874
+ if (state === 'hidden') return !attached || !shown
875
+ return false
876
+ }
877
+
878
+ /**
879
+ * Key press. Mirrors `pressExpression` in the host's src/expressions.ts, which
880
+ * the CDP backend evaluates for the same call; tests/primitives.spec.ts requires
881
+ * the two to agree. Synthetic key events trigger no default action, so Enter
882
+ * submits the owning form explicitly.
883
+ */
884
+
885
+
886
+
887
+ /**
888
+ * Select an option. Mirrors `selectExpression` in the host's src/expressions.ts.
889
+ * A value with no matching option leaves the select unchanged and the result
890
+ * says so, rather than reporting a success the page never saw.
891
+ */
892
+ function selectOption(selector, value) {
893
+ const el = document.querySelector(selector)
894
+ if (el === null) return { matched: 0, changed: false, value: '', options: [] }
895
+ if (!(el instanceof HTMLSelectElement)) {
896
+ return { matched: 1, changed: false, value: '', options: [], reason: 'not a <select>' }
897
+ }
898
+ const all = Array.from(el.options).map((option) => option.value)
899
+ const options = all.slice(0, 30)
900
+ // Checked BEFORE assigning: assigning a value no option carries sets
901
+ // selectedIndex to -1 and clears the control, so a call that is about to be
902
+ // rejected would still wipe the selection the user had.
903
+ if (all.indexOf(value) === -1) return { matched: 1, changed: false, value: el.value, options }
904
+ const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value').set
905
+ setter.call(el, value)
906
+ const changed = el.value === value
907
+ if (changed) {
908
+ el.dispatchEvent(new Event('input', { bubbles: true }))
909
+ el.dispatchEvent(new Event('change', { bubbles: true }))
910
+ }
911
+ return { matched: 1, changed, value: el.value, options }
912
+ }
913
+
914
+ /**
915
+ * Hover. Mirrors `hoverExpression` in the host's src/expressions.ts. The events
916
+ * are synthetic: they reach the page's listeners but do not set the browser's
917
+ * own hover state, so a control revealed purely by a CSS `:hover` rule stays
918
+ * hidden. Real pointer input is not available on the bridge, so both backends
919
+ * behave the same.
920
+ */
921
+ function hoverSelector(selector) {
922
+ const el = document.querySelector(selector)
923
+ if (el === null) return { matched: 0, hovered: false }
924
+ const rect = el.getBoundingClientRect()
925
+ const init = {
926
+ bubbles: true,
927
+ cancelable: true,
928
+ view: window,
929
+ clientX: rect.left + rect.width / 2,
930
+ clientY: rect.top + rect.height / 2,
931
+ }
932
+ const Pointer = typeof PointerEvent === 'function' ? PointerEvent : MouseEvent
933
+ for (const type of ['pointerover', 'mouseover', 'pointermove', 'mousemove']) {
934
+ el.dispatchEvent(new Pointer(type, init))
935
+ }
936
+ // Enter does not bubble; it is delivered on the target only.
937
+ for (const type of ['pointerenter', 'mouseenter']) {
938
+ el.dispatchEvent(new Pointer(type, { ...init, bubbles: false }))
939
+ }
940
+ return { matched: 1, hovered: true }
941
+ }
942
+
943
+ /**
944
+ * Interactive-element inventory. Mirrors `inventoryExpression` in the host's
945
+ * src/expressions.ts, which the CDP backend evaluates against the same page;
946
+ * tests/inventory.spec.ts requires the two to agree. Shares `describeTarget`
947
+ * with the click probe, so `covered` means the same thing in both results.
948
+ */
949
+ + '[role=checkbox],[role=radio],[role=tab],[role=menuitem],[role=switch],[contenteditable=""],[contenteditable=true]'
950
+
951
+
952
+
953
+
954
+
955
+
956
+
957
+
958
+
959
+
960
+
961
+ /**
962
+ * Set one control's value. `clear` false inserts at the caret the way the CDP
963
+ * backend's `Input.insertText` does, rather than replacing the whole value —
964
+ * the two backends must mean the same thing by the same argument.
965
+ */
278
966
  function typeInto(selector, text, clear) {
279
967
  const el = document.querySelector(selector)
280
968
  if (!el) return false
@@ -293,7 +981,21 @@ function typeInto(selector, text, clear) {
293
981
  el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype,
294
982
  'value',
295
983
  ).set
296
- setter.call(el, text)
984
+ let next = text
985
+ let caret = text.length
986
+ if (clear === false) {
987
+ const start = typeof el.selectionStart === 'number' ? el.selectionStart : el.value.length
988
+ const end = typeof el.selectionEnd === 'number' ? el.selectionEnd : start
989
+ next = el.value.slice(0, start) + text + el.value.slice(end)
990
+ caret = start + text.length
991
+ }
992
+ setter.call(el, next)
993
+ try {
994
+ el.setSelectionRange(caret, caret)
995
+ } catch (error) {
996
+ // Number and email inputs refuse setSelectionRange; the value still stands.
997
+ if (!/setSelectionRange|selection/i.test(String(error && error.message))) throw error
998
+ }
297
999
  el.dispatchEvent(new Event('input', { bubbles: true }))
298
1000
  el.dispatchEvent(new Event('change', { bubbles: true }))
299
1001
  } else {