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.
- package/README.en.md +6 -2
- package/README.md +6 -2
- package/client.js +110 -29
- package/core/ext.js +119 -0
- package/core/hosts.js +277 -0
- package/core/locale.js +8 -0
- package/core/receipt.js +56 -0
- package/core/session.js +157 -0
- package/core/shots.js +56 -0
- package/core/tooldef.js +142 -0
- package/core/transport.js +212 -0
- package/core/upload.js +59 -0
- package/devtools.js +18 -8
- package/download.js +879 -60
- package/drag.js +38 -20
- package/features/frames.js +58 -0
- package/features/gif.js +203 -0
- package/features/index.js +1 -0
- package/features/mock-har.js +85 -0
- package/features/record.js +225 -0
- package/i18n/en.js +168 -16
- package/i18n/ru.js +168 -16
- package/i18n/zh.js +168 -16
- package/image-guard.js +13 -6
- package/index.js +17 -1155
- package/locale/ru.json +7 -0
- package/nav.js +43 -5
- package/package.json +8 -1
- package/panel.js +10 -1
- package/refs.js +275 -230
- package/setup.js +214 -46
- package/tools/click.js +58 -0
- package/tools/devtools.js +61 -0
- package/tools/dialog.js +22 -0
- package/tools/download.js +50 -0
- package/tools/drag.js +61 -0
- package/tools/eval.js +22 -0
- package/tools/fill.js +77 -0
- package/tools/handoff.js +40 -0
- package/tools/index.js +38 -0
- package/tools/input.js +147 -0
- package/tools/nav.js +57 -0
- package/tools/read.js +87 -0
- package/tools/record.js +120 -0
- package/tools/screenshot.js +223 -0
- package/tools/tabs.js +131 -0
- package/tools/wait.js +56 -0
- package/vendor/cb +616 -35
- package/vendor/extension/_locales/en/messages.json +3 -0
- package/vendor/extension/_locales/ru/messages.json +3 -0
- package/vendor/extension/_locales/zh_CN/messages.json +3 -0
- package/vendor/extension/_locales/zh_TW/messages.json +3 -0
- package/vendor/extension/background.js +2 -1969
- package/vendor/extension/confirm.css +148 -0
- package/vendor/extension/confirm.html +49 -0
- package/vendor/extension/confirm.js +188 -0
- package/vendor/extension/in-page-cursor.js +599 -0
- package/vendor/extension/manifest.json +11 -2
- package/vendor/extension/popup.css +99 -5
- package/vendor/extension/popup.html +28 -2
- package/vendor/extension/popup.js +430 -45
- package/vendor/extension/sw/boot.js +111 -0
- package/vendor/extension/sw/cdp.js +411 -0
- package/vendor/extension/sw/chooser.js +192 -0
- package/vendor/extension/sw/confirm.js +608 -0
- package/vendor/extension/sw/cursor.js +241 -0
- package/vendor/extension/sw/dispatch.js +129 -0
- package/vendor/extension/sw/download.js +279 -0
- package/vendor/extension/sw/fetch-hub.js +224 -0
- package/vendor/extension/sw/frames.js +651 -0
- package/vendor/extension/sw/imaging.js +361 -0
- package/vendor/extension/sw/native.js +111 -0
- package/vendor/extension/sw/net-tools.js +525 -0
- package/vendor/extension/sw/ops.js +829 -0
- package/vendor/extension/sw/popup-api.js +303 -0
- package/vendor/extension/sw/profile.js +166 -0
- package/vendor/extension/sw/record.js +494 -0
- package/vendor/extension/sw/state.js +161 -0
- package/vendor/extension/sw/tabui.js +219 -0
- package/vendor/extension/sw/util.js +166 -0
- package/vendor/extension/sw/welcome.js +26 -0
- package/vendor/extension/sw/windows.js +94 -0
- package/vendor/extension/welcome.css +189 -0
- package/vendor/extension/welcome.html +70 -0
- package/vendor/extension/welcome.js +157 -0
- package/vendor/host/host.js +476 -71
- package/vendor/in-page-cursor.js +309 -37
- package/vendor/skill/SKILL.md +34 -16
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { clearPending, detachIdle, failLoadWaiter, forgetAttached, handleCdpEvent, handleDetach } from './cdp.js'
|
|
2
|
+
import { initConfirm } from './confirm.js'
|
|
3
|
+
import { refreshControls } from './cursor.js'
|
|
4
|
+
import { initFetchHub } from './fetch-hub.js'
|
|
5
|
+
import { initFrames } from './frames.js'
|
|
6
|
+
import { connect, post } from './native.js'
|
|
7
|
+
import { initNetTools } from './net-tools.js'
|
|
8
|
+
import { handleRuntimeMessage, releaseAllTabs, restorePrefs, setPaused } from './popup-api.js'
|
|
9
|
+
import { initProfile } from './profile.js'
|
|
10
|
+
import { initRecord } from './record.js'
|
|
11
|
+
import { S } from './state.js'
|
|
12
|
+
import { reconcileGroups, restoreGroups } from './tabui.js'
|
|
13
|
+
import { log, notify, updateBadge } from './util.js'
|
|
14
|
+
import { maybeOpenWelcome } from './welcome.js'
|
|
15
|
+
import { forgetAgentWindow, restoreWindows, saveAgentWindows } from './windows.js'
|
|
16
|
+
|
|
17
|
+
function rememberTab(t, created) {
|
|
18
|
+
const now = Date.now()
|
|
19
|
+
for (const [id, entry] of S.recentTabs) if (entry.at < now - 30000) S.recentTabs.delete(id)
|
|
20
|
+
const prev = S.recentTabs.get(t.id)
|
|
21
|
+
if (!created && !prev) return
|
|
22
|
+
S.recentTabs.delete(t.id)
|
|
23
|
+
S.recentTabs.set(t.id, { id: t.id, openerTabId: t.openerTabId ?? prev?.openerTabId,
|
|
24
|
+
url: t.pendingUrl || t.url || prev?.url || '', title: t.title ?? prev?.title ?? '', at: created ? now : prev.at })
|
|
25
|
+
if (S.recentTabs.size > 40) S.recentTabs.delete(S.recentTabs.keys().next().value)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function boot() {
|
|
29
|
+
if (S.startupReady) return
|
|
30
|
+
restorePrefs()
|
|
31
|
+
restoreGroups()
|
|
32
|
+
restoreWindows()
|
|
33
|
+
initProfile()
|
|
34
|
+
initConfirm()
|
|
35
|
+
initFetchHub()
|
|
36
|
+
initNetTools()
|
|
37
|
+
initFrames()
|
|
38
|
+
initRecord()
|
|
39
|
+
|
|
40
|
+
chrome.runtime.onMessage.addListener(handleRuntimeMessage)
|
|
41
|
+
chrome.debugger.onDetach.addListener(handleDetach)
|
|
42
|
+
chrome.debugger.onEvent.addListener((src, method, params) => {
|
|
43
|
+
try { handleCdpEvent(src, method, params) }
|
|
44
|
+
finally { notify(S.cdpEvents, src, method, params) }
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
chrome.commands?.onCommand?.addListener(command => {
|
|
48
|
+
if (command === 'emergency-stop') S.prefsReady.then(() => setPaused(true, 'shortcut')).catch(e => log(String(e)))
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
chrome.alarms.create('dsh-keepalive', { periodInMinutes: 1 })
|
|
52
|
+
chrome.alarms.onAlarm.addListener((a) => {
|
|
53
|
+
if (a.name !== 'dsh-keepalive') return
|
|
54
|
+
detachIdle().catch((e) => log('detachIdle 失败:', String(e && e.message || e))) // 空闲超过 60 秒的标签页断开调试
|
|
55
|
+
if (!S.port) connect()
|
|
56
|
+
else post({ id: 'ka-' + Date.now(), ok: true, keepalive: true })
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
chrome.runtime.onStartup.addListener(connect)
|
|
60
|
+
chrome.runtime.onInstalled.addListener((details) => {
|
|
61
|
+
connect()
|
|
62
|
+
maybeOpenWelcome(details)
|
|
63
|
+
})
|
|
64
|
+
// 每次 worker 起来都对一次账:认领还活着的分组、拆掉孤儿组和残留角标
|
|
65
|
+
S.startupReady = S.prefsReady.then(reconcileGroups).then(() => S.paused && releaseAllTabs())
|
|
66
|
+
|
|
67
|
+
chrome.tabs.onCreated.addListener(t => {
|
|
68
|
+
if (t?.url || t?.pendingUrl) S.tabUrl.set(t.id, t.url || t.pendingUrl)
|
|
69
|
+
rememberTab(t, true)
|
|
70
|
+
notify(S.tabCreated, t)
|
|
71
|
+
})
|
|
72
|
+
chrome.tabs.onUpdated.addListener((id, change, tab) => {
|
|
73
|
+
const url = tab?.url || tab?.pendingUrl || change?.url
|
|
74
|
+
if (url) S.tabUrl.set(id, url)
|
|
75
|
+
if (change.status === 'complete') refreshControls(id)
|
|
76
|
+
rememberTab(tab, false)
|
|
77
|
+
notify(S.tabUpdated, id, change, tab)
|
|
78
|
+
})
|
|
79
|
+
chrome.tabs.onRemoved.addListener((tabId) => {
|
|
80
|
+
S.recentTabs.delete(tabId)
|
|
81
|
+
S.tabUrl.delete(tabId)
|
|
82
|
+
for (const sess of S.SESSIONS.values()) sess.tabs.delete(tabId)
|
|
83
|
+
if (S.activeDownload?.tabId === tabId) S.activeDownload.interrupt()
|
|
84
|
+
clearPending(tabId)
|
|
85
|
+
S.tabSessions.delete(tabId)
|
|
86
|
+
S.ensureInflight.delete(tabId)
|
|
87
|
+
if (S.activeHandoff?.tabId === tabId) S.activeHandoff.resolve({ done: false, aborted: true })
|
|
88
|
+
forgetAttached(tabId, 'target_closed')
|
|
89
|
+
updateBadge()
|
|
90
|
+
S.lastUsed.delete(tabId)
|
|
91
|
+
S.groupedTabs.delete(tabId) // 标签页都没了,组也轮不到我们拆
|
|
92
|
+
S.cursorReady.delete(tabId)
|
|
93
|
+
S.cursorPos.delete(tabId)
|
|
94
|
+
S.tabEpoch.delete(tabId)
|
|
95
|
+
S.dialogs.delete(tabId)
|
|
96
|
+
S.choosers.delete(tabId)
|
|
97
|
+
S.chooserSkip.delete(tabId)
|
|
98
|
+
failLoadWaiter(tabId, '标签页在加载中被关掉了')
|
|
99
|
+
if (S.agentTabs.delete(tabId)) saveAgentWindows()
|
|
100
|
+
})
|
|
101
|
+
chrome.tabGroups.onRemoved?.addListener(({ id }) => {
|
|
102
|
+
if (S.ownedGroupIds.delete(id)) chrome.storage?.session?.set({ ownedGroupIds: [...S.ownedGroupIds] }).catch(e => log(String(e)))
|
|
103
|
+
for (const [key, gid] of S.ourGroup) if (gid === id) S.ourGroup.delete(key)
|
|
104
|
+
})
|
|
105
|
+
chrome.windows.onRemoved.addListener((windowId) => {
|
|
106
|
+
forgetAgentWindow(windowId) // 干活窗口被关了:下次新开页再开一个
|
|
107
|
+
})
|
|
108
|
+
connect()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export { getOps } from './ops.js'
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { dropChooser, inspectChooser, releaseHold } from './chooser.js'
|
|
2
|
+
import { beginAgentInput, installInputListener, markCursor, refreshControls } from './cursor.js'
|
|
3
|
+
import { getOps } from './ops.js'
|
|
4
|
+
import { setPaused } from './popup-api.js'
|
|
5
|
+
import { CDP_VERSION, CHOOSER_TTL_MS, DETACH_IDLE_MS, NET_MAX, PAUSED_MSG, S } from './state.js'
|
|
6
|
+
import { markTab, unmarkTab } from './tabui.js'
|
|
7
|
+
import { log, notify, subscribe, timeLeft, within } from './util.js'
|
|
8
|
+
|
|
9
|
+
// Each subscription returns an unsubscribe function. Keep-alive predicates are synchronous.
|
|
10
|
+
function onCdpEvent(fn) { return subscribe(S.cdpEvents, fn) }
|
|
11
|
+
function onTabAttached(fn) { return subscribe(S.tabAttached, fn) }
|
|
12
|
+
function onTabDetached(fn) { return subscribe(S.tabDetached, fn) }
|
|
13
|
+
function shouldKeepAlive(fn) { return subscribe(S.keepAlive, fn) }
|
|
14
|
+
|
|
15
|
+
function rememberAttached(id) {
|
|
16
|
+
if (S.attached.has(id)) return
|
|
17
|
+
S.attached.add(id)
|
|
18
|
+
notify(S.tabAttached, id)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function forgetAttached(id, reason) {
|
|
22
|
+
if (S.attached.delete(id)) notify(S.tabDetached, id, reason)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function detachIdle() {
|
|
26
|
+
const now = Date.now()
|
|
27
|
+
for (const tabId of [...S.attached]) {
|
|
28
|
+
if (now - (S.lastUsed.get(tabId) || 0) < DETACH_IDLE_MS) continue
|
|
29
|
+
if (S.activeHandoff?.tabId === tabId || now - S.choosers.get(tabId)?.at < CHOOSER_TTL_MS || S.tabQueues.has(tabId)) continue
|
|
30
|
+
if ([...S.keepAlive].some(fn => fn(tabId))) continue
|
|
31
|
+
if (S.inflight.has(tabId)) continue // 有 CDP 调用在飞(长 evaluate、截图…)
|
|
32
|
+
if (S.loadWaiters.has(tabId)) continue // 正在等页面加载完成
|
|
33
|
+
|
|
34
|
+
// reason 'idle':空闲断开不算解绑(照样通知 onTabDetached 的订阅者,受保护网站的放行据此留着)
|
|
35
|
+
await getOps().detach({ tabId }, { reason: 'idle' })
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function ensure(tabId) {
|
|
40
|
+
const id = Number(tabId)
|
|
41
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
42
|
+
S.lastUsed.set(id, Date.now())
|
|
43
|
+
if (S.ensureInflight.has(id)) return S.ensureInflight.get(id)
|
|
44
|
+
if (S.attached.has(id)) return id
|
|
45
|
+
const check = () => {
|
|
46
|
+
if (S.paused || S.ensureInflight.get(id) !== job) throw new Error(S.paused ? PAUSED_MSG : '调试器已断开')
|
|
47
|
+
}
|
|
48
|
+
const job = Promise.resolve().then(async () => {
|
|
49
|
+
check()
|
|
50
|
+
try { await chrome.debugger.attach({ tabId: id }, CDP_VERSION) }
|
|
51
|
+
catch (e) { if (!String(e.message || e).includes('Already attached')) throw e }
|
|
52
|
+
try {
|
|
53
|
+
for (const d of ['Page', 'DOM', 'Runtime', 'Network', 'Log']) {
|
|
54
|
+
check()
|
|
55
|
+
await chrome.debugger.sendCommand({ tabId: id }, d + '.enable', {})
|
|
56
|
+
}
|
|
57
|
+
check()
|
|
58
|
+
await chrome.debugger.sendCommand({ tabId: id }, 'Emulation.setFocusEmulationEnabled', { enabled: true })
|
|
59
|
+
check()
|
|
60
|
+
rememberAttached(id)
|
|
61
|
+
await installInputListener(id)
|
|
62
|
+
check()
|
|
63
|
+
await markTab(id)
|
|
64
|
+
check()
|
|
65
|
+
return id
|
|
66
|
+
} catch (e) {
|
|
67
|
+
if (S.ensureInflight.get(id) === job || (!S.ensureInflight.has(id) && !S.attached.has(id))) {
|
|
68
|
+
forgetAttached(id, 'attach_failed')
|
|
69
|
+
await chrome.debugger.detach({ tabId: id }).catch(() => {})
|
|
70
|
+
if (!S.attached.has(id)) await unmarkTab(id)
|
|
71
|
+
}
|
|
72
|
+
throw e
|
|
73
|
+
}
|
|
74
|
+
}).finally(() => { if (S.ensureInflight.get(id) === job) S.ensureInflight.delete(id) })
|
|
75
|
+
S.ensureInflight.set(id, job)
|
|
76
|
+
return job
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 慢的 CDP 命令单独放宽:整页 / 大页面截图 15 秒常常不够 */
|
|
80
|
+
const CDP_TIMEOUT_MS = { 'Page.captureScreenshot': 60_000 }
|
|
81
|
+
|
|
82
|
+
async function send(tabId, method, params, timeoutMs = CDP_TIMEOUT_MS[method] || 15000) {
|
|
83
|
+
const id = Number(tabId)
|
|
84
|
+
// 每条命令前都重查暂停:用户中途按了暂停,进行中的点击 / 输入不再往下发
|
|
85
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
86
|
+
// 必修:以前只有 evaluate 之前才 ensure,key/hover/scroll/dialog 这些直接 send 的 op
|
|
87
|
+
// 在空闲松手后永远失败。统一在这里 ensure:既能自动重连,也顺带刷新 lastUsed。
|
|
88
|
+
const deadline = Date.now() + timeoutMs
|
|
89
|
+
await within(ensure(id), timeoutMs, '等待调试器超时')
|
|
90
|
+
timeoutMs = timeLeft(deadline)
|
|
91
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
92
|
+
S.inflight.set(id, (S.inflight.get(id) || 0) + 1)
|
|
93
|
+
let timer
|
|
94
|
+
try {
|
|
95
|
+
if (method.startsWith('Input.')) beginAgentInput(id)
|
|
96
|
+
const p = chrome.debugger.sendCommand({ tabId: id }, method, params || {})
|
|
97
|
+
// 兜底:任何 CDP 命令都不该把 op 挂死(历史上 mouseWheel 就不回包)
|
|
98
|
+
return await Promise.race([
|
|
99
|
+
p,
|
|
100
|
+
new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`CDP ${method} ${Math.round(timeoutMs / 1000)} 秒没回应`)), timeoutMs) }),
|
|
101
|
+
])
|
|
102
|
+
} finally {
|
|
103
|
+
clearTimeout(timer)
|
|
104
|
+
const n = (S.inflight.get(id) || 1) - 1
|
|
105
|
+
if (n <= 0) S.inflight.delete(id); else S.inflight.set(id, n)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 发出去、不要求回包的 CDP 命令。
|
|
111
|
+
* 实测:Input.dispatchMouseEvent 的 mouseWheel 在 Chrome 155 上**事件生效但不回包**,
|
|
112
|
+
* 用 send() 等回复会把 scroll 挂死(客户端 45 秒超时)。这里等一小会儿就走。
|
|
113
|
+
*/
|
|
114
|
+
async function sendNoReply(tabId, method, params, graceMs = 1500) {
|
|
115
|
+
const id = Number(tabId)
|
|
116
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
117
|
+
await ensure(id)
|
|
118
|
+
if (S.paused) throw new Error(PAUSED_MSG)
|
|
119
|
+
S.inflight.set(id, (S.inflight.get(id) || 0) + 1)
|
|
120
|
+
let timer
|
|
121
|
+
try {
|
|
122
|
+
await Promise.race([
|
|
123
|
+
chrome.debugger.sendCommand({ tabId: id }, method, params || {}).catch(() => {}),
|
|
124
|
+
new Promise((res) => { timer = setTimeout(res, graceMs) }),
|
|
125
|
+
])
|
|
126
|
+
} finally {
|
|
127
|
+
clearTimeout(timer)
|
|
128
|
+
const n = (S.inflight.get(id) || 1) - 1
|
|
129
|
+
if (n <= 0) S.inflight.delete(id); else S.inflight.set(id, n)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 等页面加载的标签页关掉了 / 调试器断开了:立刻让 nav 失败,别白等到超时、还报「已到」 */
|
|
134
|
+
function failLoadWaiter(tabId, why) {
|
|
135
|
+
for (const entry of S.loadWaiters.get(tabId) || []) entry.finish(new Error(why))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function handleDetach(src, reason) {
|
|
139
|
+
if (src && src.tabId != null) {
|
|
140
|
+
failLoadWaiter(src.tabId, reason === 'target_closed' ? '标签页在加载中被关掉了' : '等页面加载时调试器被断开了(多半是点掉了 Chrome 的调试提示条)')
|
|
141
|
+
S.ensureInflight.delete(src.tabId)
|
|
142
|
+
if (S.activeDownload?.tabId === src.tabId) S.activeDownload.interrupt()
|
|
143
|
+
clearPending(src.tabId)
|
|
144
|
+
S.dialogs.delete(src.tabId)
|
|
145
|
+
if (reason === 'canceled_by_user') S.prefsReady.then(() => setPaused(true, 'canceled_by_user')).catch(e => log(String(e)))
|
|
146
|
+
forgetAttached(src.tabId, reason)
|
|
147
|
+
S.lastUsed.delete(src.tabId)
|
|
148
|
+
S.chooserArmed.delete(src.tabId) // 拦截跟着调试会话没了;拦下的那个框(choosers)不用删,节点 id 换会话照样认
|
|
149
|
+
unmarkTab(src.tabId).catch((e) => log('unmark 失败:', String(e && e.message || e))) // 用户点掉调试提示也算松手
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function handleCdpEvent(src, method, params) {
|
|
154
|
+
if (method === 'Page.loadEventFired') {
|
|
155
|
+
refreshControls(src.tabId)
|
|
156
|
+
S.cursorReady.delete(src.tabId)
|
|
157
|
+
markCursor(src.tabId, false).catch(() => {}) // 导航后页内光标没了,标签上的小鼠标跟着灭
|
|
158
|
+
for (const entry of S.loadWaiters.get(src.tabId) || []) entry.finish(true)
|
|
159
|
+
}
|
|
160
|
+
if (method === 'Page.javascriptDialogOpening') {
|
|
161
|
+
S.dialogs.set(src.tabId, { type: params.type, message: params.message, at: Date.now() })
|
|
162
|
+
}
|
|
163
|
+
if (method === 'Page.javascriptDialogClosed') {
|
|
164
|
+
S.dialogs.delete(src.tabId)
|
|
165
|
+
}
|
|
166
|
+
if (method === 'Page.fileChooserOpened') {
|
|
167
|
+
// 没有 backendNodeId:不是 <input type=file>(showOpenFilePicker 这类),拦下来等于给网页取消了,也塞不进去。
|
|
168
|
+
// 记下来回话里说清楚,这个标签页之后一阵不再拦,模型再点一次就会照常弹出系统窗口
|
|
169
|
+
if (!params.backendNodeId) S.chooserSkip.set(src.tabId, Date.now())
|
|
170
|
+
const c = {
|
|
171
|
+
id: crypto.randomUUID(), key: `__dshPick_${Date.now()}_${Math.random().toString(36).slice(2)}`, owner: S.chooserOwner.get(src.tabId), mode: params.mode,
|
|
172
|
+
backendNodeId: params.backendNodeId || null, frameId: params.frameId || null, at: Date.now(),
|
|
173
|
+
}
|
|
174
|
+
releaseHold(src.tabId, S.choosers.get(src.tabId)) // 同一标签页新框顶掉旧框
|
|
175
|
+
c.ready = inspectChooser(src.tabId, c)
|
|
176
|
+
S.choosers.set(src.tabId, c)
|
|
177
|
+
const w = S.chooserWaiters.get(src.tabId)
|
|
178
|
+
if (w) w()
|
|
179
|
+
}
|
|
180
|
+
if (method === 'Page.frameNavigated' && params.frame?.parentId && S.attached.has(src.tabId))
|
|
181
|
+
void installInputListener(src.tabId)
|
|
182
|
+
if (method === 'Page.frameNavigated' && params.frame && !params.frame.parentId) {
|
|
183
|
+
if (typeof params.frame.url === 'string' && params.frame.url) S.tabUrl.set(src.tabId, params.frame.url)
|
|
184
|
+
dropChooser(src.tabId) // 换页了,原来那个文件框也没了
|
|
185
|
+
S.chooserSkip.delete(src.tabId)
|
|
186
|
+
}
|
|
187
|
+
if (method === 'Network.requestWillBeSent') {
|
|
188
|
+
// WebSocket/SSE 这类连接永不 finished,netPending 得有个上限(NET 有 400,它原来没有)
|
|
189
|
+
if (S.netPending.size > NET_MAX) {
|
|
190
|
+
const oldest = S.netPending.keys().next().value
|
|
191
|
+
S.netPending.delete(oldest)
|
|
192
|
+
}
|
|
193
|
+
if (!['WebSocket', 'EventSource'].includes(params.type)) S.netChanged.set(src.tabId, Date.now())
|
|
194
|
+
const key = src.tabId + '/' + params.requestId
|
|
195
|
+
const prev = S.netPending.get(key)
|
|
196
|
+
const chain = new Set(prev?.urls || [])
|
|
197
|
+
if (prev?.url) chain.add(prev.url)
|
|
198
|
+
if (params.redirectResponse?.url) chain.add(params.redirectResponse.url)
|
|
199
|
+
if (params.request?.url) chain.add(params.request.url)
|
|
200
|
+
if (params.documentURL) chain.add(params.documentURL)
|
|
201
|
+
const topUrl = S.tabUrl.get(src.tabId) || ''
|
|
202
|
+
if (topUrl) chain.add(topUrl)
|
|
203
|
+
const pageUrl = params.documentURL || prev?.pageUrl || topUrl
|
|
204
|
+
S.netPending.set(key, {
|
|
205
|
+
id: params.requestId, tabId: src.tabId, method: params.request.method, url: params.request.url,
|
|
206
|
+
urls: [...chain], pageUrl,
|
|
207
|
+
type: params.type, at: Date.now(), remoteIP: params.redirectResponse?.remoteIPAddress || prev?.remoteIP || '',
|
|
208
|
+
})
|
|
209
|
+
}
|
|
210
|
+
if (method === 'Network.responseReceived') {
|
|
211
|
+
const p = S.netPending.get(src.tabId + '/' + params.requestId)
|
|
212
|
+
if (p) {
|
|
213
|
+
p.status = params.response.status
|
|
214
|
+
p.mime = params.response.mimeType
|
|
215
|
+
p.type = params.type || p.type
|
|
216
|
+
if (params.response?.url && p.urls && !p.urls.includes(params.response.url)) p.urls.push(params.response.url)
|
|
217
|
+
if (params.response?.remoteIPAddress) p.remoteIP = params.response.remoteIPAddress
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (method === 'Network.loadingFinished' || method === 'Network.loadingFailed') {
|
|
221
|
+
const p = S.netPending.get(src.tabId + '/' + params.requestId)
|
|
222
|
+
if (p) {
|
|
223
|
+
p.ms = Date.now() - p.at
|
|
224
|
+
if (method === 'Network.loadingFailed') p.failed = params.errorText
|
|
225
|
+
S.NET.push(p)
|
|
226
|
+
if (S.NET.length > NET_MAX) S.NET.shift()
|
|
227
|
+
S.netPending.delete(src.tabId + '/' + params.requestId)
|
|
228
|
+
if (!['WebSocket', 'EventSource'].includes(p.type)) S.netChanged.set(src.tabId, Date.now())
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (method === 'Runtime.consoleAPICalled') {
|
|
232
|
+
const args = params.args || []
|
|
233
|
+
const f = params.stackTrace && params.stackTrace.callFrames && params.stackTrace.callFrames[0]
|
|
234
|
+
const item = { tabId: src.tabId, level: params.type, kind: 'console', text: args.map(fmtArg).join(' '),
|
|
235
|
+
at: params.timestamp, where: f && f.url ? `${f.url}:${f.lineNumber + 1}` : '', pageUrl: S.tabUrl.get(src.tabId) || '' }
|
|
236
|
+
// 调试器接上前打的旧消息是 V8 补发的,补发不带对象预览(只剩 "Object")——回页面里展开一下
|
|
237
|
+
if (pushConsole(item) && args.some(needsExpand)) {
|
|
238
|
+
expandArgs(src.tabId, args).then((t) => { item.text = t.slice(0, 2000) }).catch(() => {})
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (method === 'Runtime.exceptionThrown') {
|
|
242
|
+
// 没被 catch 的 JS 报错 —— 调试网页时最要紧的一类,console API 那条路收不到
|
|
243
|
+
const d = params.exceptionDetails || {}
|
|
244
|
+
pushConsole({ tabId: src.tabId, level: 'error', kind: 'exception',
|
|
245
|
+
text: (d.exception && (d.exception.description || d.exception.value)) || d.text || 'Uncaught',
|
|
246
|
+
at: params.timestamp, where: d.url ? `${d.url}:${(d.lineNumber || 0) + 1}` : '', pageUrl: S.tabUrl.get(src.tabId) || '' })
|
|
247
|
+
}
|
|
248
|
+
if (method === 'Log.entryAdded') {
|
|
249
|
+
// 浏览器自己报的:请求失败、CSP 拦截、废弃 API 警告……
|
|
250
|
+
const e = params.entry || {}
|
|
251
|
+
if (e.level !== 'verbose') {
|
|
252
|
+
pushConsole({ tabId: src.tabId, level: e.level, kind: e.source || 'browser', text: e.text || '',
|
|
253
|
+
at: e.timestamp, where: e.url || '', pageUrl: S.tabUrl.get(src.tabId) || '' })
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** console 参数 → 一段字。对象/数组用 V8 带的预览拼成 {a: 1, b: "x"},不然只看得到 "Object"。 */
|
|
259
|
+
function clearPending(tabId) {
|
|
260
|
+
S.userTakeover.delete(tabId)
|
|
261
|
+
S.agentInputUntil.delete(tabId)
|
|
262
|
+
for (const [key, req] of S.netPending) if (req.tabId === tabId) S.netPending.delete(key)
|
|
263
|
+
S.netChanged.delete(tabId)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function fmtArg(a) {
|
|
267
|
+
if (a.value !== undefined) return typeof a.value === 'string' ? a.value : JSON.stringify(a.value)
|
|
268
|
+
if (a.unserializableValue) return a.unserializableValue
|
|
269
|
+
const p = a.preview
|
|
270
|
+
if (p && p.properties && (p.subtype === 'array' || (p.type === 'object' && !p.subtype))) {
|
|
271
|
+
const val = (x) => (x.type === 'string' ? JSON.stringify(x.value) : x.value ?? x.type)
|
|
272
|
+
const more = p.overflow ? ', …' : ''
|
|
273
|
+
return p.subtype === 'array'
|
|
274
|
+
? `[${p.properties.map(val).join(', ')}${more}]`
|
|
275
|
+
: `{${p.properties.map((x) => `${x.name}: ${val(x)}`).join(', ')}${more}}`
|
|
276
|
+
}
|
|
277
|
+
return a.description || a.type
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const needsExpand = (a) => a.objectId && !a.preview && a.type === 'object' && (!a.subtype || a.subtype === 'array')
|
|
281
|
+
|
|
282
|
+
/** 页内把对象拼成和预览一样的样子:{a: 1, b: "x"} / [1, 2] */
|
|
283
|
+
const EXPAND_FN = `function () {
|
|
284
|
+
const v = (x) => typeof x === 'string' ? JSON.stringify(x) : x === null ? 'null'
|
|
285
|
+
: Array.isArray(x) ? 'Array(' + x.length + ')'
|
|
286
|
+
: typeof x === 'object' ? ((x.constructor && x.constructor.name) || 'Object')
|
|
287
|
+
: typeof x === 'function' ? 'ƒ' : String(x);
|
|
288
|
+
if (Array.isArray(this)) return '[' + this.slice(0, 20).map(v).join(', ') + (this.length > 20 ? ', …' : '') + ']';
|
|
289
|
+
const ks = Object.keys(this);
|
|
290
|
+
return '{' + ks.slice(0, 20).map((k) => k + ': ' + v(this[k])).join(', ') + (ks.length > 20 ? ', …' : '') + '}';
|
|
291
|
+
}`
|
|
292
|
+
|
|
293
|
+
async function expandArgs(tabId, args) {
|
|
294
|
+
const parts = []
|
|
295
|
+
for (const a of args) {
|
|
296
|
+
if (!needsExpand(a)) { parts.push(fmtArg(a)); continue }
|
|
297
|
+
try {
|
|
298
|
+
const r = await chrome.debugger.sendCommand({ tabId }, 'Runtime.callFunctionOn',
|
|
299
|
+
{ objectId: a.objectId, functionDeclaration: EXPAND_FN, returnByValue: true, silent: true })
|
|
300
|
+
parts.push(r && r.result && typeof r.result.value === 'string' ? r.result.value : fmtArg(a))
|
|
301
|
+
} catch {
|
|
302
|
+
parts.push(fmtArg(a))
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return parts.join(' ')
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** 重新 attach 时 V8 会把旧消息补发一遍 —— 按「标签页 + 时间 + 内容」去重。 */
|
|
309
|
+
function pushConsole(item) {
|
|
310
|
+
item.text = String(item.text || '').slice(0, 2000)
|
|
311
|
+
item.at = Math.round(Number(item.at) || Date.now())
|
|
312
|
+
item.key = item.text // 去重按原始文字比:text 之后可能被 expandArgs 改写
|
|
313
|
+
const dup = S.CONSOLE.some(c => c.tabId === item.tabId && c.at === item.at && c.key === item.key)
|
|
314
|
+
if (dup) return false
|
|
315
|
+
S.CONSOLE.push(item)
|
|
316
|
+
if (S.CONSOLE.length > 300) S.CONSOLE.shift()
|
|
317
|
+
return true
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* 注入表达式并取值(有异常就抛,别把 undefined 当成功)。
|
|
322
|
+
* userGesture 仅在调用方显式要求时启用:读页面、找元素、画光标都不带,不白送页面一次「用户激活」。
|
|
323
|
+
*/
|
|
324
|
+
async function evaluate(tabId, expression, userGesture = false, timeoutMs) {
|
|
325
|
+
const r = await send(tabId, 'Runtime.evaluate', {
|
|
326
|
+
expression,
|
|
327
|
+
returnByValue: true,
|
|
328
|
+
awaitPromise: true,
|
|
329
|
+
userGesture: !!userGesture,
|
|
330
|
+
}, timeoutMs)
|
|
331
|
+
if (r.exceptionDetails) {
|
|
332
|
+
const d = r.exceptionDetails
|
|
333
|
+
throw new Error((d.exception && (d.exception.description || d.exception.value)) || d.text || '页面 JS 抛异常')
|
|
334
|
+
}
|
|
335
|
+
return r.result ? r.result.value : undefined
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** 页内找一个元素的中点(顺带滚动到可视区),返回视口坐标 */
|
|
339
|
+
const POINT_HELPER = `
|
|
340
|
+
const __dsh_norm = (s) => (s || '').replace(/\\s+/g, ' ').trim();
|
|
341
|
+
const __dsh_visible = (el) => {
|
|
342
|
+
const r = el.getBoundingClientRect();
|
|
343
|
+
if (r.width < 1 || r.height < 1) return false;
|
|
344
|
+
const st = getComputedStyle(el);
|
|
345
|
+
if (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0) return false;
|
|
346
|
+
return true;
|
|
347
|
+
};
|
|
348
|
+
const __dsh_cover = (el, x, y) => {
|
|
349
|
+
const hit = document.elementFromPoint(x, y);
|
|
350
|
+
const inside = (node, ancestor) => {
|
|
351
|
+
while (node) {
|
|
352
|
+
if (ancestor.contains(node)) return true;
|
|
353
|
+
node = node.getRootNode().host;
|
|
354
|
+
}
|
|
355
|
+
return false;
|
|
356
|
+
};
|
|
357
|
+
if (!hit || inside(hit, el) || inside(el, hit)) return {};
|
|
358
|
+
return { occluded: { tag: hit.tagName.toLowerCase(), text: __dsh_norm(hit.innerText).slice(0, 80),
|
|
359
|
+
id: hit.id, className: hit.getAttribute('class') || '' } };
|
|
360
|
+
};
|
|
361
|
+
const __dsh_point = (el) => {
|
|
362
|
+
el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
|
|
363
|
+
return new Promise((res) => {
|
|
364
|
+
let done = false;
|
|
365
|
+
const finish = () => {
|
|
366
|
+
if (done) return;
|
|
367
|
+
done = true;
|
|
368
|
+
const r = el.getBoundingClientRect();
|
|
369
|
+
res({ ...__dsh_cover(el, r.left + r.width / 2, r.top + r.height / 2), x: r.left + r.width / 2, y: r.top + r.height / 2,
|
|
370
|
+
tag: el.tagName.toLowerCase(),
|
|
371
|
+
// 输入框没 innerText,退到 aria-label / placeholder;密码框的 value 绝不拿出来(会上名牌、进工具结果)
|
|
372
|
+
text: __dsh_norm(el.innerText || (['button', 'submit', 'reset'].includes(el.type) ? el.value : '') || el.getAttribute('aria-label') ||
|
|
373
|
+
el.getAttribute('placeholder') || el.getAttribute('title') || el.getAttribute('alt') || '').slice(0, 80) });
|
|
374
|
+
};
|
|
375
|
+
// 后台标签页里 Chrome 会暂停 requestAnimationFrame —— 只等 rAF 的话这个 Promise
|
|
376
|
+
// 永远不 resolve,整个 click-el / click-text 就卡死(45 秒超时、还不回话)。
|
|
377
|
+
// 所以 rAF 之外再挂一个定时器兜底。
|
|
378
|
+
requestAnimationFrame(() => requestAnimationFrame(finish));
|
|
379
|
+
setTimeout(finish, 120);
|
|
380
|
+
});
|
|
381
|
+
};
|
|
382
|
+
`
|
|
383
|
+
|
|
384
|
+
async function pointOf(tabId, finderJs, deadline) {
|
|
385
|
+
const pt = await evaluate(tabId, `(async () => { ${POINT_HELPER} ${finderJs} })()`, false, deadline && timeLeft(deadline))
|
|
386
|
+
if (!pt) throw new Error('没找到目标元素(可能不可见或文字不匹配)')
|
|
387
|
+
return pt
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const CDP_ALLOWLIST = new Set([
|
|
391
|
+
'Page.captureScreenshot', 'Page.getLayoutMetrics', 'Page.getNavigationHistory', 'Page.navigateToHistoryEntry',
|
|
392
|
+
'Page.reload', 'Page.navigate', 'Page.getFrameTree', 'Page.handleJavaScriptDialog', 'Page.setInterceptFileChooserDialog',
|
|
393
|
+
'Page.startScreencast', 'Page.stopScreencast', 'Page.screencastFrameAck', 'Page.bringToFront', 'Page.printToPDF',
|
|
394
|
+
'Runtime.evaluate', 'Runtime.callFunctionOn', 'Runtime.releaseObjectGroup', 'Runtime.getProperties',
|
|
395
|
+
'Network.getResponseBody', 'Network.getCookies',
|
|
396
|
+
])
|
|
397
|
+
function checkCdp(method, params) {
|
|
398
|
+
const domain = /^(Input|Emulation|DOM|Accessibility|CSS|Overlay|Log)\.[A-Za-z]+$/
|
|
399
|
+
if (typeof method !== 'string' || method === 'DOM.setFileInputFiles' || (!domain.test(method) && !CDP_ALLOWLIST.has(method)))
|
|
400
|
+
throw new Error(`CDP 方法不在允许列表内: ${method}`)
|
|
401
|
+
if (method === 'Network.getCookies' && (!Array.isArray(params?.urls) || !params.urls.length ||
|
|
402
|
+
!params.urls.every(url => { try { return ['http:', 'https:'].includes(new URL(url).protocol) && typeof url === 'string' } catch { return false } })))
|
|
403
|
+
throw new Error('Network.getCookies 需要明确指定 http/https urls')
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export {
|
|
407
|
+
onCdpEvent, onTabAttached, onTabDetached, shouldKeepAlive, rememberAttached, forgetAttached,
|
|
408
|
+
detachIdle, ensure, CDP_TIMEOUT_MS, send, sendNoReply, failLoadWaiter, handleDetach,
|
|
409
|
+
handleCdpEvent, clearPending, fmtArg, needsExpand, EXPAND_FN, expandArgs, pushConsole,
|
|
410
|
+
evaluate, POINT_HELPER, pointOf, CDP_ALLOWLIST, checkCdp,
|
|
411
|
+
}
|