dsh-embedded-browser-next 0.0.0-stage → 1.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/LICENSE +21 -0
- package/README.en.md +275 -0
- package/README.md +274 -2
- package/cordis.patch.yml +16 -0
- package/lib/browser.js +2634 -0
- package/lib/cdp.js +320 -0
- package/lib/client.js +3991 -0
- package/lib/diagnostics.js +48 -0
- package/lib/downloads.js +73 -0
- package/lib/external.js +96 -0
- package/lib/human.js +145 -0
- package/lib/index.js +609 -0
- package/lib/lazy.js +193 -0
- package/lib/mjpeg.js +154 -0
- package/lib/paths.js +107 -0
- package/lib/residency.js +234 -0
- package/lib/router.js +687 -0
- package/lib/routes.js +446 -0
- package/lib/screencast.js +1629 -0
- package/lib/snapshot-window.js +73 -0
- package/lib/tools.js +740 -0
- package/lib/ws.js +253 -0
- package/package.json +60 -4
package/lib/cdp.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal zero-dependency Chrome DevTools Protocol client.
|
|
3
|
+
*
|
|
4
|
+
* Two layers:
|
|
5
|
+
* - `Cdp` owns the browser-level WebSocket (`/json/version` -> webSocketDebuggerUrl)
|
|
6
|
+
* and can attach to page targets.
|
|
7
|
+
* - `Session` owns one attached target (flatten mode) and carries the page-level
|
|
8
|
+
* commands and events used by the browser manager and the screencast bridge.
|
|
9
|
+
*
|
|
10
|
+
* No third-party module is required: Node >= 22 ships global `fetch` and `WebSocket`.
|
|
11
|
+
*
|
|
12
|
+
* @module dsh-embedded-browser/cdp
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Default per-command budget; screencast capture and navigation pass their own. */
|
|
16
|
+
const DEFAULT_TIMEOUT_MS = 30_000
|
|
17
|
+
|
|
18
|
+
/** Error carrying the CDP error payload so callers can branch on it. */
|
|
19
|
+
export class CdpError extends Error {
|
|
20
|
+
constructor(method, detail) {
|
|
21
|
+
super(`cdp ${method} failed: ${detail}`)
|
|
22
|
+
this.name = 'CdpError'
|
|
23
|
+
this.method = method
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** One WebSocket carrying JSON-RPC frames, with pending-call bookkeeping. */
|
|
28
|
+
class Wire {
|
|
29
|
+
constructor(url) {
|
|
30
|
+
this.url = url
|
|
31
|
+
this.nextId = 1
|
|
32
|
+
this.pending = new Map()
|
|
33
|
+
this.listeners = new Map()
|
|
34
|
+
this.closed = false
|
|
35
|
+
this.closeListeners = new Set()
|
|
36
|
+
this.socket = new WebSocket(url)
|
|
37
|
+
this.ready = new Promise((resolve, reject) => {
|
|
38
|
+
this.socket.onopen = () => resolve()
|
|
39
|
+
this.socket.onerror = () => reject(new Error(`cdp: cannot open ${url}`))
|
|
40
|
+
})
|
|
41
|
+
this.socket.onmessage = (event) => this.dispatch(String(event.data))
|
|
42
|
+
this.socket.onclose = () => {
|
|
43
|
+
this.closed = true
|
|
44
|
+
for (const [, entry] of this.pending) entry.reject(new Error('cdp: connection closed'))
|
|
45
|
+
this.pending.clear()
|
|
46
|
+
for (const listener of this.closeListeners) listener()
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
dispatch(raw) {
|
|
51
|
+
let message
|
|
52
|
+
try {
|
|
53
|
+
message = JSON.parse(raw)
|
|
54
|
+
} catch {
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
if (message.id !== undefined) {
|
|
58
|
+
const entry = this.pending.get(message.id)
|
|
59
|
+
if (entry === undefined) return
|
|
60
|
+
this.pending.delete(message.id)
|
|
61
|
+
if (message.error !== undefined) entry.reject(new CdpError(entry.method, JSON.stringify(message.error)))
|
|
62
|
+
else entry.resolve(message.result ?? {})
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
if (typeof message.method !== 'string') return
|
|
66
|
+
const key = message.sessionId === undefined ? message.method : `${message.sessionId}:${message.method}`
|
|
67
|
+
const handlers = this.listeners.get(key)
|
|
68
|
+
if (handlers === undefined) return
|
|
69
|
+
for (const handler of [...handlers]) {
|
|
70
|
+
try {
|
|
71
|
+
handler(message.params ?? {})
|
|
72
|
+
} catch {
|
|
73
|
+
/* listener errors never break the wire */
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
send(method, params, sessionId, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
79
|
+
if (this.closed) return Promise.reject(new Error('cdp: connection is closed'))
|
|
80
|
+
const id = this.nextId++
|
|
81
|
+
const frame = { id, method }
|
|
82
|
+
if (params !== undefined) frame.params = params
|
|
83
|
+
if (sessionId !== undefined) frame.sessionId = sessionId
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
const timer = setTimeout(() => {
|
|
86
|
+
this.pending.delete(id)
|
|
87
|
+
reject(new CdpError(method, 'timeout'))
|
|
88
|
+
}, timeoutMs)
|
|
89
|
+
this.pending.set(id, {
|
|
90
|
+
method,
|
|
91
|
+
resolve: (value) => {
|
|
92
|
+
clearTimeout(timer)
|
|
93
|
+
resolve(value)
|
|
94
|
+
},
|
|
95
|
+
reject: (error) => {
|
|
96
|
+
clearTimeout(timer)
|
|
97
|
+
reject(error)
|
|
98
|
+
},
|
|
99
|
+
})
|
|
100
|
+
this.socket.send(JSON.stringify(frame))
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
on(method, handler, sessionId) {
|
|
105
|
+
const key = sessionId === undefined ? method : `${sessionId}:${method}`
|
|
106
|
+
let set = this.listeners.get(key)
|
|
107
|
+
if (set === undefined) {
|
|
108
|
+
set = new Set()
|
|
109
|
+
this.listeners.set(key, set)
|
|
110
|
+
}
|
|
111
|
+
set.add(handler)
|
|
112
|
+
return () => {
|
|
113
|
+
set.delete(handler)
|
|
114
|
+
if (set.size === 0) this.listeners.delete(key)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
onClose(handler) {
|
|
119
|
+
this.closeListeners.add(handler)
|
|
120
|
+
return () => this.closeListeners.delete(handler)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
close() {
|
|
124
|
+
this.closed = true
|
|
125
|
+
try {
|
|
126
|
+
this.socket.close()
|
|
127
|
+
} catch {
|
|
128
|
+
/* already gone */
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Browser-level CDP connection plus target attachment helpers. */
|
|
134
|
+
export class Cdp {
|
|
135
|
+
constructor(wire) {
|
|
136
|
+
this.wire = wire
|
|
137
|
+
this.port = undefined
|
|
138
|
+
this.version = undefined
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Connect to an already running browser's DevTools endpoint.
|
|
143
|
+
* @param port - DevTools HTTP port.
|
|
144
|
+
* @param options - timeout budget and version payload reuse.
|
|
145
|
+
* @returns connected client.
|
|
146
|
+
*/
|
|
147
|
+
static async connect(port, { timeoutMs = 10_000, version } = {}) {
|
|
148
|
+
const info = version ?? (await fetchVersion(port, timeoutMs))
|
|
149
|
+
const wire = new Wire(info.webSocketDebuggerUrl)
|
|
150
|
+
await wire.ready
|
|
151
|
+
const cdp = new Cdp(wire)
|
|
152
|
+
cdp.port = port
|
|
153
|
+
cdp.version = info
|
|
154
|
+
return cdp
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
send(method, params, timeoutMs) {
|
|
158
|
+
return this.wire.send(method, params, undefined, timeoutMs)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
on(method, handler) {
|
|
162
|
+
return this.wire.on(method, handler)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
onClose(handler) {
|
|
166
|
+
return this.wire.onClose(handler)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Whether the wire has closed.
|
|
171
|
+
*
|
|
172
|
+
* A closed wire is not a dead browser: Edge can drop the DevTools socket while
|
|
173
|
+
* the process keeps running perfectly well. Callers use this to tell "no
|
|
174
|
+
* connection yet" apart from "connection that will never work again".
|
|
175
|
+
*/
|
|
176
|
+
get closed() {
|
|
177
|
+
return this.wire.closed
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Every page target, in Chrome's own order (an "active" flag is not exposed). */
|
|
181
|
+
async pages() {
|
|
182
|
+
const response = await fetch(`http://127.0.0.1:${this.port}/json/list`)
|
|
183
|
+
const list = await response.json()
|
|
184
|
+
return list.filter((entry) => entry.type === 'page')
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Create a tab and return its attached session. */
|
|
188
|
+
async newPage(url = 'about:blank') {
|
|
189
|
+
const { targetId } = await this.send('Target.createTarget', { url })
|
|
190
|
+
return this.attach(targetId)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Attach to one target in flatten mode and return a page session. */
|
|
194
|
+
async attach(targetId) {
|
|
195
|
+
const { sessionId } = await this.send('Target.attachToTarget', { targetId, flatten: true })
|
|
196
|
+
return new Session(this, targetId, sessionId)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Attach to the newest page target, creating one when the browser has none. */
|
|
200
|
+
async attachAnyPage() {
|
|
201
|
+
const pages = await this.pages()
|
|
202
|
+
if (pages.length === 0) return this.newPage()
|
|
203
|
+
return this.attach(pages[pages.length - 1].id)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Bring a target to the foreground so the human's panel shows that tab. */
|
|
207
|
+
async activate(targetId) {
|
|
208
|
+
await this.send('Target.activateTarget', { targetId })
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async closeTarget(targetId) {
|
|
212
|
+
await this.send('Target.closeTarget', { targetId })
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
close() {
|
|
216
|
+
this.wire.close()
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** One attached target: page commands, events, and the helpers built on them. */
|
|
221
|
+
export class Session {
|
|
222
|
+
constructor(cdp, targetId, sessionId) {
|
|
223
|
+
this.cdp = cdp
|
|
224
|
+
this.targetId = targetId
|
|
225
|
+
this.sessionId = sessionId
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
send(method, params, timeoutMs) {
|
|
229
|
+
return this.cdp.wire.send(method, params, this.sessionId, timeoutMs)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
on(method, handler) {
|
|
233
|
+
return this.cdp.wire.on(method, handler, this.sessionId)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Resolve on the next matching event, or on timeout (`undefined`). */
|
|
237
|
+
next(method, timeoutMs = 30_000) {
|
|
238
|
+
return new Promise((resolve) => {
|
|
239
|
+
const timer = setTimeout(() => {
|
|
240
|
+
off()
|
|
241
|
+
resolve(undefined)
|
|
242
|
+
}, timeoutMs)
|
|
243
|
+
const off = this.on(method, (params) => {
|
|
244
|
+
clearTimeout(timer)
|
|
245
|
+
off()
|
|
246
|
+
resolve(params)
|
|
247
|
+
})
|
|
248
|
+
})
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async enable() {
|
|
252
|
+
await this.send('Page.enable')
|
|
253
|
+
await this.send('Runtime.enable')
|
|
254
|
+
await this.send('DOM.enable').catch(() => {})
|
|
255
|
+
await this.send('Network.enable').catch(() => {})
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Navigate and wait for the load event (best effort; SPAs settle later). */
|
|
259
|
+
async navigate(url, { waitMs = 30_000 } = {}) {
|
|
260
|
+
const loaded = this.next('Page.loadEventFired', waitMs)
|
|
261
|
+
const result = await this.send('Page.navigate', { url }, waitMs)
|
|
262
|
+
// A navigation that never leaves the machine still resolves the command, so
|
|
263
|
+
// the failure only shows up as `errorText`. Surfacing it here replaces a
|
|
264
|
+
// 30-second "load event never fired" timeout with the actual reason.
|
|
265
|
+
if (typeof result?.errorText === 'string' && result.errorText !== '') {
|
|
266
|
+
throw new Error(`navigation failed: ${result.errorText} — ${url}`)
|
|
267
|
+
}
|
|
268
|
+
await loaded
|
|
269
|
+
return result
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async evaluate(expression, { awaitPromise = true, timeoutMs } = {}) {
|
|
273
|
+
const result = await this.send(
|
|
274
|
+
'Runtime.evaluate',
|
|
275
|
+
{ expression, returnByValue: true, awaitPromise },
|
|
276
|
+
timeoutMs,
|
|
277
|
+
)
|
|
278
|
+
if (result.exceptionDetails !== undefined) {
|
|
279
|
+
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text ?? 'evaluate failed'
|
|
280
|
+
throw new Error(detail)
|
|
281
|
+
}
|
|
282
|
+
return result.result?.value
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async viewport() {
|
|
286
|
+
const metrics = await this.send('Page.getLayoutMetrics').catch(() => undefined)
|
|
287
|
+
const visual = metrics?.cssVisualViewport ?? metrics?.visualViewport
|
|
288
|
+
if (visual !== undefined) {
|
|
289
|
+
return { width: Math.round(visual.clientWidth), height: Math.round(visual.clientHeight) }
|
|
290
|
+
}
|
|
291
|
+
const size = await this.evaluate('JSON.stringify({w:innerWidth,h:innerHeight})')
|
|
292
|
+
const parsed = JSON.parse(size)
|
|
293
|
+
return { width: parsed.w, height: parsed.h }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async title() {
|
|
297
|
+
return this.evaluate('document.title')
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
close() {
|
|
301
|
+
return this.send('Target.detachFromTarget', { sessionId: this.sessionId }).catch(() => {})
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Read the DevTools version payload, retrying until the endpoint answers. */
|
|
306
|
+
export async function fetchVersion(port, timeoutMs = 10_000) {
|
|
307
|
+
const deadline = Date.now() + timeoutMs
|
|
308
|
+
let lastError
|
|
309
|
+
for (;;) {
|
|
310
|
+
try {
|
|
311
|
+
const response = await fetch(`http://127.0.0.1:${port}/json/version`)
|
|
312
|
+
if (response.ok) return await response.json()
|
|
313
|
+
lastError = new Error(`devtools endpoint answered ${response.status}`)
|
|
314
|
+
} catch (error) {
|
|
315
|
+
lastError = error
|
|
316
|
+
}
|
|
317
|
+
if (Date.now() > deadline) throw new Error(`devtools endpoint on port ${port} is not ready: ${lastError?.message}`)
|
|
318
|
+
await new Promise((resolve) => setTimeout(resolve, 200))
|
|
319
|
+
}
|
|
320
|
+
}
|