/** * 最小 CDP 客户端 * =============== * 只依赖 Node 22 自带的全局 WebSocket(undici 实现),不引 ws / puppeteer。 * * 为什么不用 Playwright:桌面端的外壳本来就是直接连 Chrome DevTools 协议 * (见 resources/plugin/cocorobo/browser.mjs),页面工具要复现的语义(挑页签、 * 执行脚本、投文件、硬刷新)在 CDP 里都是一等公民;引一个浏览器框架反而会把 * "哪条命令对应桌面端哪个行为"这层对应关系藏起来。 * * 一个连接 = 一个 target(页签)。多页签就是多条连接,省掉 sessionId 复用的复杂度。 */ const DEFAULT_TIMEOUT = 30_000 export class CDPError extends Error { constructor (message, info) { super(message) this.name = 'CDPError' this.code = (info && info.code) || '' this.method = (info && info.method) || '' } } export class CDP { #ws = null #nextId = 1 #pending = new Map() #listeners = new Map() #closed = false #opening = null constructor (url, options = {}) { this.url = url this.timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT this.label = options.label || 'cdp' } static async connect (url, options) { const client = new CDP(url, options) await client.opened() return client } opened () { if (this.#opening) return this.#opening this.#opening = new Promise((resolve, reject) => { let ws try { ws = new WebSocket(this.url) } catch (err) { reject(new CDPError(`WebSocket 建连失败:${err.message}`)) return } this.#ws = ws const timer = setTimeout(() => { try { ws.close() } catch { /* 已经关了 */ } reject(new CDPError('连接 CDP 超时')) }, this.timeoutMs) timer.unref?.() const settle = (fn, arg) => { clearTimeout(timer) fn(arg) } ws.addEventListener('message', (event) => { if (typeof event.data !== 'string') return let msg try { msg = JSON.parse(event.data) } catch { return } this.#dispatch(msg) }) ws.addEventListener('open', () => settle(resolve)) ws.addEventListener('error', () => settle(reject, new CDPError(`连接 ${this.label} 失败`))) ws.addEventListener('close', () => { this.#closed = true for (const [, entry] of this.#pending) { clearTimeout(entry.timer) entry.reject(new CDPError(`连接已关闭(${this.label})`)) } this.#pending.clear() for (const fn of this.#listeners.get('close') || []) { try { fn() } catch { /* 订阅方自己处理 */ } } }) }) return this.#opening } #dispatch (msg) { if (msg.id != null) { const entry = this.#pending.get(msg.id) if (!entry) return this.#pending.delete(msg.id) clearTimeout(entry.timer) if (msg.error) entry.reject(new CDPError(msg.error.message, { code: msg.error.code, method: entry.method })) else entry.resolve(msg.result) return } if (!msg.method) return for (const fn of this.#listeners.get(msg.method) || []) { try { fn(msg.params || {}) } catch { /* 单个订阅者异常不影响其它 */ } } } send (method, params = {}, options = {}) { if (this.#closed || !this.#ws) return Promise.reject(new CDPError('连接未就绪')) const id = this.#nextId++ const timeoutMs = options.timeoutMs || this.timeoutMs return new Promise((resolve, reject) => { const timer = setTimeout(() => { this.#pending.delete(id) reject(new CDPError(`CDP ${method} 超时(${timeoutMs}ms)`, { method })) }, timeoutMs) timer.unref?.() this.#pending.set(id, { resolve, reject, timer, method }) try { this.#ws.send(JSON.stringify({ id, method, params })) } catch (err) { clearTimeout(timer) this.#pending.delete(id) reject(new CDPError(`发送 ${method} 失败:${err.message}`, { method })) } }) } on (method, fn) { if (!this.#listeners.has(method)) this.#listeners.set(method, new Set()) this.#listeners.get(method).add(fn) return () => this.off(method, fn) } off (method, fn) { const set = this.#listeners.get(method) if (set) set.delete(fn) } close () { this.#closed = true try { this.#ws?.close() } catch { /* 已经关了 */ } } }