| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854 |
- /**
- * 服务端 Chromium
- * ===============
- * 桌面端的右侧页面是 Electron 的 <webview>,它的能力来自"同一台机器上的浏览器"。
- * Web 版没有这台机器,所以这里给每个老师起一个独立的 Chromium:
- *
- * · 页签(target)—— 对应桌面端按站点分的那几页;
- * · 页面脚本 —— Page.eval 走 Runtime.evaluate,语义和 executeJavaScript 一致;
- * · 投递文件 —— 上传控件走 DOM.setFileInputFiles,页面函数走"取字节 → new File";
- * · 硬刷新 —— 清 HTTP 缓存 + 该站 Service Worker,再 ignoreCache 重载;
- * · 画面回传 —— Page.startScreencast,前端拿 canvas 画;
- * · 输入转发 —— Input.dispatchMouseEvent / dispatchKeyEvent / insertText。
- *
- * 安全边界和桌面端保持一致:脚本只允许在 **平台域名** 的页面里执行;浏览器只监听
- * 127.0.0.1 的调试端口;每个老师一份 user-data-dir,登录态互不可见。
- */
- import { spawn } from 'node:child_process'
- import fs from 'node:fs'
- import path from 'node:path'
- import { CDP, CDPError } from './cdp.js'
- const PLATFORM_RE = /^https?:\/\/([a-z0-9-]+\.)*cocorobo\.(cn|hk|com)(\/|$)/i
- const MAX_RESULT = 200 * 1024
- const MAX_TABS = 8
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
- export function isPlatformUrl (url) {
- return PLATFORM_RE.test(String(url || ''))
- }
- function hostOf (url) {
- try { return new URL(url).host } catch { return '' }
- }
- /** 交给页面的 File 要带对 MIME:上传控件会按 type 过滤,application/octet-stream 常被拒 */
- function guessType (file) {
- const ext = path.extname(String(file || '')).toLowerCase()
- const map = {
- '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
- '.webp': 'image/webp', '.svg': 'image/svg+xml', '.pdf': 'application/pdf',
- '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
- '.json': 'application/json', '.txt': 'text/plain', '.html': 'text/html',
- '.zip': 'application/zip', '.mp4': 'video/mp4', '.mp3': 'audio/mpeg'
- }
- return map[ext] || 'application/octet-stream'
- }
- /** 页面里可能抛任何东西:统一压成可 JSON 化的字符串,别把工具调用打挂 */
- function describeValue (value) {
- if (value == null) return null
- try {
- const json = JSON.stringify(value)
- return json.length > MAX_RESULT ? json.slice(0, MAX_RESULT) : json
- } catch {
- return String(value)
- }
- }
- export class RemoteBrowser {
- constructor (options = {}) {
- this.exe = options.exe || ''
- this.userDataDir = options.userDataDir || ''
- this.downloadDir = options.downloadDir || ''
- this.headless = options.headless !== false
- this.width = options.width || 1440
- this.height = options.height || 900
- this.noSandbox = options.noSandbox !== false
- this.log = options.log || (() => {})
- this.extraArgs = options.extraArgs || []
- this.proc = null
- this.httpPort = 0
- this.browserCdp = null
- this.tabs = new Map() // targetId → tab
- this.hostKey = new Map() // host → targetId(桌面端"一个站点一页"的对应关系)
- this.logs = new Map() // targetId → 最近日志
- this.screencast = new Map() // targetId → {subs:Set, active:boolean, meta}
- this.stopped = false
- }
- // ---------------------------------------------------------------- 生命周期
- async start () {
- if (!this.exe) throw new Error('没有配置浏览器可执行文件(CC_CHROME)')
- if (!fs.existsSync(this.exe)) throw new Error(`浏览器不存在:${this.exe}`)
- fs.mkdirSync(this.userDataDir, { recursive: true })
- const args = [
- '--remote-debugging-port=0',
- `--user-data-dir=${this.userDataDir}`,
- `--window-size=${this.width},${this.height}`,
- '--no-first-run',
- '--no-default-browser-check',
- '--disable-background-networking',
- '--disable-component-update',
- '--disable-sync',
- '--disable-extensions',
- '--disable-features=Translate,MediaRouter,OptimizationHints',
- '--force-color-profile=srgb',
- '--hide-scrollbars',
- '--mute-audio',
- '--lang=zh-CN',
- ...this.extraArgs
- ]
- if (this.headless) args.push('--headless=new')
- // 容器里以 root 跑必须关沙箱;生产环境请用非 root 并去掉这条
- if (this.noSandbox) args.push('--no-sandbox', '--disable-dev-shm-usage')
- args.push('about:blank')
- this.proc = spawn(this.exe, args, { stdio: ['ignore', 'ignore', 'pipe'] })
- this.proc.on('exit', (code) => {
- this.log(`[browser] 退出 code=${code}`)
- if (!this.stopped) this.#failAllTabs('浏览器进程已退出')
- })
- const wsUrl = await this.#waitDevtools()
- this.httpPort = Number(new URL(wsUrl).port)
- this.browserCdp = await CDP.connect(wsUrl, { label: 'browser', timeoutMs: 20_000 })
- this.#watchTargets()
- this.log(`[browser] 就绪 :${this.httpPort}(${this.headless ? 'headless' : 'headed'})`)
- return this
- }
- #waitDevtools () {
- return new Promise((resolve, reject) => {
- let buf = ''
- const timer = setTimeout(() => {
- reject(new Error(`浏览器 20 秒内没有给出调试地址:${buf.slice(-400)}`))
- }, 20_000)
- timer.unref?.()
- const onData = (chunk) => {
- buf += chunk.toString('utf8')
- const m = /DevTools listening on (ws:\/\/[^\s]+)/.exec(buf)
- if (m) {
- clearTimeout(timer)
- this.proc.stderr.off('data', onData)
- resolve(m[1])
- }
- if (buf.length > 8000) buf = buf.slice(-4000)
- }
- this.proc.stderr.on('data', onData)
- this.proc.on('exit', (code) => {
- clearTimeout(timer)
- reject(new Error(`浏览器启动失败(code=${code}):${buf.slice(-400)}`))
- })
- })
- }
- #watchTargets () {
- const cdp = this.browserCdp
- cdp.send('Target.setDiscoverTargets', { discover: true }).catch((err) => {
- this.log(`[browser] 订阅 target 失败:${err.message}`)
- })
- cdp.on('Target.targetCreated', ({ targetInfo }) => this.#trackTarget(targetInfo))
- cdp.on('Target.targetInfoChanged', ({ targetInfo }) => this.#updateTarget(targetInfo))
- cdp.on('Target.targetDestroyed', ({ targetId }) => this.#dropTarget(targetId))
- }
- #trackTarget (info) {
- if (!info || info.type !== 'page') return
- if (String(info.url || '').startsWith('devtools://')) return
- const targetId = info.targetId
- if (this.tabs.has(targetId)) return this.#updateTarget(info)
- const tab = {
- targetId,
- url: String(info.url || ''),
- title: String(info.title || ''),
- loading: false,
- error: '',
- key: '',
- cdp: null,
- opening: null,
- lastUsed: Date.now()
- }
- tab.key = this.#keyFor(tab)
- this.tabs.set(targetId, tab)
- this.log(`[browser] 新页签 ${tab.key} ${tab.url}`)
- // 页签上限:关最久没用的那个,防止老师开一堆把内存吃满
- if (this.tabs.size > MAX_TABS) {
- const victim = [...this.tabs.values()]
- .filter((t) => t.targetId !== targetId)
- .sort((a, b) => a.lastUsed - b.lastUsed)[0]
- if (victim) this.closeTab(victim.targetId).catch(() => {})
- }
- }
- #keyFor (tab) {
- const host = hostOf(tab.url)
- if (!host) return 'blank'
- const taken = this.hostKey.get(host)
- if (!taken || taken === tab.targetId || !this.tabs.has(taken)) {
- this.hostKey.set(host, tab.targetId)
- return host
- }
- return `${host}#${tab.targetId.slice(0, 4)}`
- }
- #updateTarget (info) {
- if (!info || info.type !== 'page') return
- const tab = this.tabs.get(info.targetId)
- if (!tab) return this.#trackTarget(info)
- if (info.url && info.url !== tab.url) {
- tab.url = info.url
- tab.key = this.#keyFor(tab)
- }
- if (typeof info.title === 'string' && info.title !== tab.title) {
- tab.title = info.title
- this.#emit(tab, { type: 'state', field: 'title', value: tab.title })
- }
- }
- #dropTarget (targetId) {
- const tab = this.tabs.get(targetId)
- if (!tab) return
- this.tabs.delete(targetId)
- const host = hostOf(tab.url)
- if (host && this.hostKey.get(host) === targetId) this.hostKey.delete(host)
- try { tab.cdp?.close() } catch { /* 已经断了 */ }
- this.screencast.delete(targetId)
- this.logs.delete(targetId)
- }
- #failAllTabs (message) {
- for (const tab of this.tabs.values()) {
- tab.error = message
- this.#emit(tab, { type: 'state', field: 'error', value: message })
- }
- this.tabs.clear()
- this.hostKey.clear()
- }
- async closeTab (targetId) {
- try {
- await this.browserCdp?.send('Target.closeTarget', { targetId })
- } catch { /* 目标可能已经没了 */ }
- this.#dropTarget(targetId)
- }
- async stop () {
- this.stopped = true
- try { this.browserCdp?.close() } catch { /* 已经断了 */ }
- for (const tab of this.tabs.values()) {
- try { tab.cdp?.close() } catch { /* 已经断了 */ }
- }
- this.tabs.clear()
- this.hostKey.clear()
- if (this.proc && !this.proc.killed) {
- try { this.proc.kill('SIGTERM') } catch { /* 已经退了 */ }
- await sleep(300)
- if (this.proc.exitCode == null) {
- try { this.proc.kill('SIGKILL') } catch { /* 已经退了 */ }
- }
- }
- }
- // ---------------------------------------------------------------- 页签
- list () {
- return [...this.tabs.values()]
- .filter((t) => t.url && !t.url.startsWith('about:'))
- .sort((a, b) => b.lastUsed - a.lastUsed)
- .map((t) => ({ key: t.key, url: t.url, title: t.title, loading: t.loading, error: t.error }))
- }
- /** 桌面端 pickPlatformGuest 的等价物:只认平台域名,urlMatch 按地址挑。 */
- pickGuest (urlMatch) {
- const want = String(urlMatch || '').trim().toLowerCase()
- const candidates = [...this.tabs.values()]
- .filter((t) => isPlatformUrl(t.url))
- .sort((a, b) => b.lastUsed - a.lastUsed)
- if (!candidates.length) return null
- if (!want) return candidates[0]
- return candidates.find((t) => t.url.toLowerCase().includes(want)) || null
- }
- async openTab (url) {
- const target = String(url || '').trim()
- if (!/^https?:\/\//i.test(target)) throw new Error('只支持 http(s) 地址')
- const host = hostOf(target)
- const existingId = host ? this.hostKey.get(host) : ''
- const existing = existingId ? this.tabs.get(existingId) : null
- if (existing) {
- existing.lastUsed = Date.now()
- if (existing.url !== target) await this.navigate(existing, target)
- return existing
- }
- const { targetId } = await this.browserCdp.send('Target.createTarget', { url: 'about:blank' })
- // targetCreated 事件是异步的,等它把 tab 建出来再导航,避免拿不到对象
- const tab = await this.#waitTab(targetId)
- tab.lastUsed = Date.now()
- await this.navigate(tab, target)
- return tab
- }
- async #waitTab (targetId) {
- for (let i = 0; i < 100; i += 1) {
- const tab = this.tabs.get(targetId)
- if (tab) return tab
- await sleep(50)
- }
- throw new Error('页签创建后没有出现')
- }
- async navigate (tab, url) {
- const cdp = await this.#cdpOf(tab)
- tab.loading = true
- tab.error = ''
- this.#emit(tab, { type: 'state', field: 'loading', value: true })
- try {
- await cdp.send('Page.navigate', { url })
- } catch (err) {
- tab.loading = false
- tab.error = err.message
- this.#emit(tab, { type: 'state', field: 'error', value: err.message })
- throw err
- }
- return tab
- }
- async reload (tab, hard = false) {
- const cdp = await this.#cdpOf(tab)
- tab.error = ''
- this.#emit(tab, { type: 'state', field: 'error', value: '' })
- if (hard) {
- const origin = (() => { try { return new URL(tab.url).origin } catch { return '' } })()
- await cdp.send('Network.enable').catch(() => {})
- await cdp.send('Network.setCacheDisabled', { cacheDisabled: true }).catch(() => {})
- if (origin) {
- await cdp.send('Storage.clearDataForOrigin', {
- origin,
- storageTypes: 'service_workers,cache_storage'
- }).catch(() => {})
- }
- // 页面自己注册的 SW 也要一并清掉,否则下次导航又被接回去
- await cdp.send('Runtime.evaluate', {
- expression: `(async () => {
- try {
- const rs = await navigator.serviceWorker.getRegistrations()
- await Promise.all(rs.map((r) => r.unregister()))
- if (globalThis.caches) {
- const keys = await caches.keys()
- await Promise.all(keys.map((k) => caches.delete(k)))
- }
- return true
- } catch { return false }
- })()`,
- awaitPromise: true,
- returnByValue: true
- }).catch(() => {})
- }
- await cdp.send('Page.reload', { ignoreCache: !!hard })
- if (hard) setTimeout(() => { cdp.send('Network.setCacheDisabled', { cacheDisabled: false }).catch(() => {}) }, 1500)
- return { ok: true, url: tab.url }
- }
- // ---------------------------------------------------------------- 页面 CDP
- async #cdpOf (tab) {
- if (tab.cdp) return tab.cdp
- if (tab.opening) return tab.opening
- tab.opening = (async () => {
- const ws = await this.#pageWs(tab.targetId)
- const cdp = await CDP.connect(ws, { label: `page:${tab.key}`, timeoutMs: 20_000 })
- tab.cdp = cdp
- tab.opening = null
- await this.#wire(cdp, tab)
- return cdp
- })().catch((err) => {
- tab.opening = null
- throw err
- })
- return tab.opening
- }
- async #pageWs (targetId) {
- for (let i = 0; i < 60; i += 1) {
- try {
- const res = await fetch(`http://127.0.0.1:${this.httpPort}/json/list`)
- const list = await res.json()
- const hit = list.find((t) => t.id === targetId)
- if (hit && hit.webSocketDebuggerUrl) return hit.webSocketDebuggerUrl
- } catch { /* 浏览器还没起稳 */ }
- await sleep(100)
- }
- throw new Error('拿不到页签的调试地址')
- }
- async #wire (cdp, tab) {
- cdp.send('Page.enable').catch(() => {})
- cdp.send('Runtime.enable').catch(() => {})
- if (this.downloadDir) {
- cdp.send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath: this.downloadDir }).catch(() => {})
- }
- cdp.on('Page.frameNavigated', ({ frame }) => {
- if (!frame || frame.parentId) return
- if (frame.url && frame.url !== tab.url) {
- tab.url = frame.url
- tab.key = this.#keyFor(tab)
- this.#emit(tab, { type: 'state', field: 'url', value: tab.url })
- }
- })
- cdp.on('Page.loadEventFired', async () => {
- tab.loading = false
- this.#emit(tab, { type: 'state', field: 'loading', value: false })
- const title = await this.#title(tab)
- if (title && title !== tab.title) {
- tab.title = title
- this.#emit(tab, { type: 'state', field: 'title', value: title })
- }
- })
- cdp.on('Page.loadingFailed', ({ errorText, isMainFrame }) => {
- if (isMainFrame === false) return
- tab.loading = false
- tab.error = String(errorText || '页面加载失败')
- this.#emit(tab, { type: 'state', field: 'error', value: tab.error })
- this.#emit(tab, { type: 'state', field: 'loading', value: false })
- })
- cdp.on('Inspector.targetCrashed', () => {
- tab.error = '页面崩溃了'
- this.#emit(tab, { type: 'state', field: 'error', value: tab.error })
- })
- // 页面弹 alert/confirm 会把整个页签卡住(CDP 不会自己点掉),统一按「确定」处理
- cdp.on('Page.javascriptDialogOpening', () => {
- cdp.send('Page.handleJavaScriptDialog', { accept: true }).catch(() => {})
- })
- cdp.on('Runtime.consoleAPICalled', ({ type, args }) => {
- this.#pushLog(tab, type, args)
- })
- }
- async #title (tab) {
- try {
- const cdp = tab.cdp
- if (!cdp) return ''
- const { result } = await cdp.send('Runtime.evaluate', {
- expression: 'document.title', returnByValue: true
- }, { timeoutMs: 3000 })
- return String((result && result.value) || '')
- } catch { return '' }
- }
- // ---------------------------------------------------------------- 执行脚本
- async evaluate (tab, code, options = {}) {
- const cdp = await this.#cdpOf(tab)
- tab.lastUsed = Date.now()
- const timeoutMs = Math.min(Math.max(Number(options.timeoutMs) || 8000, 1), 20_000)
- const run = (expression) => cdp.send('Runtime.evaluate', {
- expression,
- awaitPromise: true,
- returnByValue: true,
- userGesture: true,
- allowUnsafeEvalBlockedByCSP: true
- }, { timeoutMs })
- // 桌面端用的是 executeJavaScript(code):按脚本执行,取"最后一条表达式的值"。
- // 这里先原样执行;只有语法错(典型是模型写了顶层 return)才包一层 async IIFE,
- // 而不是靠字符串里有没有 "return" 来判断 —— 那会误伤 querySelector('[type=return]')。
- let evaluated
- try {
- evaluated = await run(code)
- } catch (err) {
- if (!/超时/.test(err.message)) throw err
- throw err
- }
- if (evaluated.exceptionDetails && /SyntaxError/i.test(String(evaluated.exceptionDetails.text || ''))) {
- evaluated = await run(`(async () => { ${code} })()`)
- }
- const { result, exceptionDetails } = evaluated
- if (exceptionDetails) {
- const text = (exceptionDetails.exception && (exceptionDetails.exception.description || exceptionDetails.exception.value)) ||
- exceptionDetails.text || '脚本报错'
- throw new Error(String(text).split('\n')[0])
- }
- const raw = describeValue(result && result.value)
- const truncated = raw != null && raw.length >= MAX_RESULT
- return { value: raw, truncated }
- }
- // ---------------------------------------------------------------- 投递文件
- /**
- * 和外壳 dropFileIntoBrowser 对齐:有 pageFn 就交给页面函数,否则找 input[type=file]。
- * 差别只有一处:桌面端手里直接有 File 对象,这里必须让页面自己去取一次字节 ——
- * 所以文件通过一条带 token 的短时 URL 暴露给页面(见 files.js),
- * 页面里 fetch 完再 new File(),仍然是一个**真 File**,页面业务逻辑一行不用改。
- */
- async dropFile (tab, input) {
- const filePath = String(input.path || '')
- const stat = await fs.promises.stat(filePath).catch(() => null)
- if (!stat || !stat.isFile()) return { ok: false, error: 'file-missing' }
- if (stat.size > 512 * 1024 * 1024) return { ok: false, error: 'too-large', size: stat.size }
- const name = String(input.name || '').trim() || path.basename(filePath)
- const cdp = await this.#cdpOf(tab)
- if (input.pageFn) {
- const fnPath = input.pageFn.split('.').filter(Boolean)
- const argsMode = input.pageFnArgs === 'array' ? 'array' : 'single'
- const literal = JSON.stringify(fnPath)
- const type = guessType(filePath)
- /**
- * 页面拿到真 File 的两种方式,按体积选:
- *
- * ≤ 8MB —— 直接把字节内联进脚本。页面是 https、服务端是 http 时 fetch 会被
- * 浏览器按混合内容拦掉(本机联调就是这样),内联没有任何网络依赖。
- * 更大 —— 走带 token 的短时地址。要求部署在 https 上(同协议、公网域名),
- * 否则浏览器同样会拦;这条限制写进 docs/troubleshooting.md。
- */
- const INLINE_LIMIT = 8 * 1024 * 1024
- let loader
- if (stat.size <= INLINE_LIMIT) {
- const b64 = (await fs.promises.readFile(filePath)).toString('base64')
- loader = `const bin = atob(${JSON.stringify(b64)});
- const bytes = new Uint8Array(bin.length);
- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
- const blob = new Blob([bytes], { type: ${JSON.stringify(type)} });`
- } else {
- const fileUrl = String(input.fileUrl || '')
- if (!fileUrl) {
- return { ok: false, error: 'no-file-url', hint: '文件超过 8MB,需要 https 部署才能交给页面函数' }
- }
- loader = `const res = await fetch(${JSON.stringify(fileUrl)}, { cache: 'no-store', credentials: 'omit' });
- if (!res.ok) return { ok: false, error: 'file-fetch-failed', status: res.status };
- const blob = await res.blob();`
- }
- const expression = `(async () => {
- const path = ${literal};
- let fn = window;
- for (const k of path) {
- fn = fn && fn[k];
- if (fn == null) break;
- }
- if (typeof fn !== 'function') return { ok: false, error: 'no-fn', fn: path.join('.') };
- ${loader}
- const file = new File([blob], ${JSON.stringify(name)}, { type: ${JSON.stringify(type)}, lastModified: Date.now() });
- const meta = { name: file.name, size: file.size, type: file.type, lastModified: file.lastModified };
- try {
- const out = ${argsMode === 'array' ? 'await fn([file], meta)' : 'await fn(file, meta)'};
- return { ok: true, value: out === undefined ? null : out };
- } catch (err) {
- return { ok: false, error: 'fn-threw', hint: String((err && err.message) || err) };
- }
- })()`
- const timeoutMs = Math.min(Number(input.pageFnTimeoutMs) || 120_000, 300_000)
- let evaluated
- try {
- evaluated = await cdp.send('Runtime.evaluate', {
- expression, awaitPromise: true, returnByValue: true, userGesture: true
- }, { timeoutMs })
- } catch (err) {
- if (err instanceof CDPError && /超时/.test(err.message)) {
- return { ok: false, error: 'fn-timeout', hint: '页面函数没有按时返回;文件已经交到页面手里,不要重复投递' }
- }
- throw err
- }
- const { result, exceptionDetails } = evaluated
- if (!result) return { ok: false, error: 'fn-timeout', hint: '页面函数没有按时返回;文件已经交到页面手里,不要重复投递' }
- if (exceptionDetails) {
- return { ok: false, error: 'fn-threw', hint: String(exceptionDetails.text || '页面函数抛错') }
- }
- const out = result.value || {}
- if (out.ok !== true) return { ...out, ok: false }
- return { ok: true, via: 'fn', fn: input.pageFn, name, size: stat.size, value: describeValue(out.value), url: tab.url }
- }
- const nodeId = await this.#findFileInput(tab, input.clickText)
- if (!nodeId) return { ok: false, error: 'no-target', hint: '页面上没有找到 input[type=file]' }
- await cdp.send('DOM.setFileInputFiles', { files: [filePath], nodeId }, { timeoutMs: 60_000 })
- return { ok: true, via: 'change', name, size: stat.size, url: tab.url }
- }
- /** 找上传控件;页面要"先点一下才露出控件"时按 clickText 点一次再找。 */
- async #findFileInput (tab, clickText) {
- const cdp = await this.#cdpOf(tab)
- const find = async () => {
- for (const expression of [
- `document.querySelector('input[type=file]')`,
- // 弹窗/组件里常见:控件在 shadow DOM 或同源 iframe 里
- `(() => {
- const walk = (root) => {
- const hit = root.querySelector && root.querySelector('input[type=file]')
- if (hit) return hit
- for (const el of root.querySelectorAll ? root.querySelectorAll('*') : []) {
- if (el.shadowRoot) { const h = walk(el.shadowRoot); if (h) return h }
- }
- for (const f of document.querySelectorAll('iframe')) {
- try { const d = f.contentDocument; if (d) { const h = walk(d); if (h) return h } } catch { /* 跨域 */ }
- }
- return null
- }
- return walk(document)
- })()`
- ]) {
- const { result } = await cdp.send('Runtime.evaluate', {
- expression: `(() => { const el = ${expression}; return el ? true : false })()`,
- returnByValue: true
- }, { timeoutMs: 4000 }).catch(() => ({ result: { value: false } }))
- if (result && result.value) {
- const { root } = await cdp.send('DOM.getDocument', { depth: -1, pierce: true })
- const { nodeId } = await cdp.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'input[type=file]' })
- if (nodeId) return nodeId
- }
- }
- return 0
- }
- let nodeId = await find()
- if (nodeId) return nodeId
- const texts = (Array.isArray(clickText) ? clickText : []).filter(Boolean)
- for (const text of texts) {
- await cdp.send('Runtime.evaluate', {
- expression: `(() => {
- const want = ${JSON.stringify(String(text))}
- const nodes = [...document.querySelectorAll('button,a,div,span,li')]
- const hit = nodes.find((el) => (el.textContent || '').trim() === want) ||
- nodes.find((el) => (el.textContent || '').includes(want))
- if (!hit) return false
- hit.click()
- return true
- })()`,
- returnByValue: true,
- userGesture: true
- }).catch(() => {})
- for (let i = 0; i < 10; i += 1) {
- await sleep(150)
- nodeId = await find()
- if (nodeId) return nodeId
- }
- }
- return 0
- }
- // ---------------------------------------------------------------- 画面 / 输入
- /** 订阅某个页签的画面与状态。返回退订函数。 */
- subscribe (tab, fn) {
- const state = this.#screencastOf(tab)
- state.subs.add(fn)
- // 先把当前状态补一份:新接上的前端不该干等"下一次状态变化"(页面早就加载完了)
- const snapshot = [
- { type: 'state', field: 'url', value: tab.url },
- { type: 'state', field: 'title', value: tab.title },
- { type: 'state', field: 'loading', value: tab.loading }
- ]
- if (tab.error) snapshot.push({ type: 'state', field: 'error', value: tab.error })
- for (const item of snapshot) {
- try { fn(item) } catch { /* 订阅方自己处理 */ }
- }
- this.#startScreencast(tab).catch((err) => {
- this.log(`[browser] 起画面回传失败:${err.message}`)
- fn({ type: 'state', field: 'error', value: `画面回传失败:${err.message}` })
- })
- return () => {
- state.subs.delete(fn)
- if (state.subs.size === 0) this.#stopScreencast(tab).catch(() => {})
- }
- }
- #emit (tab, payload) {
- const state = this.screencast.get(tab.targetId)
- if (!state) return
- for (const fn of state.subs) {
- try { fn(payload) } catch { /* 订阅方自己处理 */ }
- }
- }
- #screencastOf (tab) {
- let state = this.screencast.get(tab.targetId)
- if (!state) {
- state = { subs: new Set(), active: false, meta: null, width: this.width, height: this.height }
- this.screencast.set(tab.targetId, state)
- }
- return state
- }
- async #startScreencast (tab) {
- const state = this.#screencastOf(tab)
- if (state.active) return
- const cdp = await this.#cdpOf(tab)
- state.active = true
- // 视口按前端画布尺寸设,超出会被缩;这样页面拿到的是"平板/桌面浏览器"尺寸,
- // 不是 headless 默认的 800×600(否则平台页面会走移动断点)
- await cdp.send('Emulation.setDeviceMetricsOverride', {
- width: state.width, height: state.height, deviceScaleFactor: 1, mobile: false
- }).catch(() => {})
- cdp.on('Page.screencastFrame', ({ data, metadata, sessionId }) => {
- state.meta = metadata || null
- cdp.send('Page.screencastFrameAck', { sessionId }).catch(() => {})
- this.#emit(tab, {
- type: 'frame',
- jpeg: Buffer.from(String(data || ''), 'base64'),
- meta: metadata || {}
- })
- })
- await cdp.send('Page.startScreencast', {
- format: 'jpeg',
- quality: 72,
- maxWidth: state.width,
- maxHeight: state.height,
- everyNthFrame: 1
- })
- }
- async #stopScreencast (tab) {
- const state = this.#screencastOf(tab)
- state.active = false
- try { await tab.cdp?.send('Page.stopScreencast') } catch { /* 连接可能已断 */ }
- }
- /** 前端画布尺寸变了:重设视口并重开回传,避免画面被拉伸。 */
- async resize (tab, width, height) {
- const state = this.#screencastOf(tab)
- const w = Math.max(320, Math.min(Number(width) || 0, 2560))
- const h = Math.max(240, Math.min(Number(height) || 0, 1600))
- if (w === state.width && h === state.height) return
- state.width = w
- state.height = h
- const cdp = await this.#cdpOf(tab)
- await cdp.send('Emulation.setDeviceMetricsOverride', {
- width: w, height: h, deviceScaleFactor: 1, mobile: false
- }).catch(() => {})
- if (state.active) {
- await cdp.send('Page.stopScreencast').catch(() => {})
- await cdp.send('Page.startScreencast', {
- format: 'jpeg', quality: 72, maxWidth: w, maxHeight: h, everyNthFrame: 1
- }).catch(() => {})
- }
- }
- // ------------------------------------------------------------------ 输入
- async input (tab, msg) {
- const cdp = await this.#cdpOf(tab)
- tab.lastUsed = Date.now()
- // 前端已经把画布坐标换算成页面 CSS 像素(它知道帧尺寸与 deviceWidth),
- // 这里不再做二次换算,避免两边各缩一次。
- if (msg.t === 'mouse') {
- const x = Number(msg.x) || 0
- const y = Number(msg.y) || 0
- const button = msg.button === 'right' ? 'right' : msg.button === 'middle' ? 'middle' : 'left'
- const buttons = msg.buttons != null ? Number(msg.buttons) : (msg.action === 'down' ? 1 : 0)
- if (msg.action === 'wheel') {
- await cdp.send('Input.dispatchMouseEvent', {
- type: 'mouseWheel', x, y, deltaX: Number(msg.deltaX) || 0, deltaY: Number(msg.deltaY) || 0,
- modifiers: Number(msg.modifiers) || 0
- })
- return
- }
- const type = msg.action === 'down' ? 'mousePressed' : msg.action === 'up' ? 'mouseReleased' : 'mouseMoved'
- await cdp.send('Input.dispatchMouseEvent', {
- type, x, y, button: type === 'mouseMoved' ? 'none' : button,
- buttons, clickCount: msg.action === 'move' ? 0 : (msg.clickCount || 1),
- pointerType: msg.pointerType === 'touch' ? 'mouse' : 'mouse',
- modifiers: Number(msg.modifiers) || 0
- })
- return
- }
- if (msg.t === 'key') {
- const key = String(msg.key || '')
- const code = String(msg.code || '')
- const vk = Number(msg.keyCode) || keyCodeOf(key, code)
- const modifiers = Number(msg.modifiers) || 0
- const printable = key.length === 1 && !msg.ctrlOnly
- if (msg.action === 'down') {
- await cdp.send('Input.dispatchKeyEvent', {
- type: printable ? 'keyDown' : 'rawKeyDown',
- key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk,
- text: printable ? key : (key === 'Enter' ? '\r' : undefined),
- unmodifiedText: printable ? key : undefined,
- modifiers, autoRepeat: !!msg.repeat
- })
- if (!printable && key === 'Enter') {
- await cdp.send('Input.dispatchKeyEvent', {
- type: 'char', key: '\r', text: '\r', unmodifiedText: '\r', modifiers
- }).catch(() => {})
- }
- } else {
- await cdp.send('Input.dispatchKeyEvent', {
- type: 'keyUp', key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, modifiers
- })
- }
- return
- }
- if (msg.t === 'text') {
- await cdp.send('Input.insertText', { text: String(msg.text || '') })
- return
- }
- if (msg.t === 'nav') {
- const url = String(msg.url || '')
- if (!/^https?:\/\//i.test(url)) throw new Error('只支持 http(s) 地址')
- await this.navigate(tab, url)
- return
- }
- if (msg.t === 'close') {
- await this.closeTab(tab.targetId)
- return
- }
- }
- // ------------------------------------------------------------------ 日志
- #pushLog (tab, level, args) {
- const text = (args || []).map((a) => {
- if (a == null) return ''
- if ('value' in a) return typeof a.value === 'string' ? a.value : JSON.stringify(a.value)
- if (a.description) return String(a.description)
- return String(a.type || '')
- }).join(' ').slice(0, 4000)
- const list = this.logs.get(tab.targetId) || []
- list.push({ level, text, at: Date.now() })
- if (list.length > 200) list.shift()
- this.logs.set(tab.targetId, list)
- this.#emit(tab, { type: 'log', level, text })
- }
- logsOf (tab) {
- return this.logs.get(tab.targetId) || []
- }
- }
- /** 键盘事件缺 keyCode 时按 key/code 兜底,否则平台页面的快捷键分支识别不到 */
- function keyCodeOf (key, code) {
- const special = {
- Enter: 13, Tab: 9, Backspace: 8, Escape: 27, Delete: 46, ' ': 32,
- ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40,
- Home: 36, End: 35, PageUp: 33, PageDown: 34,
- Shift: 16, Control: 17, Alt: 18, Meta: 91, CapsLock: 20
- }
- if (special[key]) return special[key]
- if (/^F\d{1,2}$/.test(key)) return 111 + Number(key.slice(1))
- if (key.length === 1) {
- const up = key.toUpperCase()
- if (/[A-Z]/.test(up)) return up.charCodeAt(0)
- if (/[0-9]/.test(key)) return key.charCodeAt(0)
- return up.charCodeAt(0)
- }
- const m = /^Key([A-Z])$/.exec(code || '')
- if (m) return m[1].charCodeAt(0)
- const d = /^Digit([0-9])$/.exec(code || '')
- if (d) return d[1].charCodeAt(0)
- return 0
- }
|