@xiangyixie/dsh-superagent 0.12.0 → 0.14.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/lib/browser.js ADDED
@@ -0,0 +1,795 @@
1
+ /**
2
+ * Zero-dependency Chromium control over the DevTools protocol.
3
+ *
4
+ * Node 22+ ships a global `WebSocket`, so one browser can be driven without a
5
+ * single npm package: launch Chromium with `--remote-debugging-port=0`, read the
6
+ * port it chose from `DevToolsActivePort`, then exchange CDP frames with it.
7
+ *
8
+ * Everything here is deliberately plain: no retries on a dead socket, no
9
+ * implicit browser reuse across processes, and no fallback that would turn a
10
+ * failed action into a silent no-op. A caller gets either a result or an error.
11
+ *
12
+ * @module dsh-superagent/browser
13
+ */
14
+ import { spawn } from 'node:child_process'
15
+ import { existsSync } from 'node:fs'
16
+ import fsp from 'node:fs/promises'
17
+ import os from 'node:os'
18
+ import path from 'node:path'
19
+
20
+ const LAUNCH_TIMEOUT_MS = 20000
21
+ const CALL_TIMEOUT_MS = 30000
22
+ const NAVIGATION_TIMEOUT_MS = 30000
23
+
24
+ /** Chromium-family executables, in the order a Windows desktop usually has them. */
25
+ export const BROWSER_CANDIDATES = [
26
+ 'C:/Program Files/Google/Chrome/Application/chrome.exe',
27
+ 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
28
+ 'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
29
+ 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
30
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
31
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
32
+ '/usr/bin/google-chrome',
33
+ '/usr/bin/chromium',
34
+ '/usr/bin/chromium-browser',
35
+ '/usr/bin/microsoft-edge',
36
+ ]
37
+
38
+ /**
39
+ * Resolve the browser binary to drive.
40
+ * @param {{ explicit?: string|null, env?: NodeJS.ProcessEnv, platform?: string, exists?: (file: string) => boolean }} [options]
41
+ * @returns {string|null} absolute executable path, or null when none is installed.
42
+ */
43
+ export function findBrowserExecutable({ explicit = null, env = process.env, platform = process.platform, exists = existsSync } = {}) {
44
+ const named = explicit ?? env.DSH_BROWSER_PATH ?? null
45
+ if (typeof named === 'string' && named.trim()) {
46
+ const file = path.resolve(named.trim())
47
+ return exists(file) ? file : null
48
+ }
49
+ const candidates = platform === 'win32'
50
+ ? BROWSER_CANDIDATES.filter(entry => /^[A-Za-z]:\//.test(entry))
51
+ : BROWSER_CANDIDATES.filter(entry => entry.startsWith('/'))
52
+ for (const candidate of candidates) {
53
+ if (exists(candidate)) return candidate
54
+ }
55
+ return null
56
+ }
57
+
58
+ /** One CDP message channel. Calls are correlated by numeric id, events by method. */
59
+ class CdpConnection {
60
+ #socket
61
+ #nextId = 1
62
+ #pending = new Map()
63
+ #listeners = new Set()
64
+ #closed
65
+ #closePromise
66
+
67
+ constructor(socket) {
68
+ this.#socket = socket
69
+ this.#closed = new Promise(resolve => {
70
+ this.#closePromise = resolve
71
+ })
72
+ socket.addEventListener('message', event => this.#route(event.data))
73
+ socket.addEventListener('close', () => this.#failAll(new Error('the DevTools connection closed')))
74
+ socket.addEventListener('error', () => this.#failAll(new Error('the DevTools connection failed')))
75
+ }
76
+
77
+ /**
78
+ * @param {string} url - Chrome DevTools websocket URL.
79
+ * @param {{ timeoutMs?: number }} [options]
80
+ * @returns {Promise<CdpConnection>}
81
+ */
82
+ static async connect(url, { timeoutMs = LAUNCH_TIMEOUT_MS } = {}) {
83
+ if (typeof WebSocket !== 'function') {
84
+ throw new Error('this Node version has no global WebSocket; zero-dependency browser control needs Node 22 or newer')
85
+ }
86
+ const socket = new WebSocket(url)
87
+ await new Promise((resolve, reject) => {
88
+ const timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs}ms connecting to ${url}`)), timeoutMs)
89
+ const done = fn => () => {
90
+ clearTimeout(timer)
91
+ fn()
92
+ }
93
+ socket.addEventListener('open', done(resolve), { once: true })
94
+ socket.addEventListener('error', done(() => reject(new Error(`cannot reach the DevTools endpoint ${url}`))), { once: true })
95
+ })
96
+ return new CdpConnection(socket)
97
+ }
98
+
99
+ #route(raw) {
100
+ let message
101
+ try {
102
+ message = JSON.parse(typeof raw === 'string' ? raw : String(raw))
103
+ } catch {
104
+ return
105
+ }
106
+ if (message.id !== undefined) {
107
+ const waiting = this.#pending.get(message.id)
108
+ if (!waiting) return
109
+ this.#pending.delete(message.id)
110
+ if (message.error) waiting.reject(new Error(`${waiting.method}: ${message.error.message ?? 'DevTools error'}`))
111
+ else waiting.resolve(message.result ?? {})
112
+ return
113
+ }
114
+ for (const listener of this.#listeners) listener(message)
115
+ }
116
+
117
+ #failAll(error) {
118
+ for (const [, waiting] of this.#pending) waiting.reject(error)
119
+ this.#pending.clear()
120
+ this.#closePromise()
121
+ }
122
+
123
+ /**
124
+ * Send one command and wait for its reply.
125
+ * @param {string} method - e.g. `Runtime.evaluate`.
126
+ * @param {object} [params]
127
+ * @param {{ sessionId?: string, timeoutMs?: number }} [options]
128
+ */
129
+ send(method, params = {}, { sessionId, timeoutMs = CALL_TIMEOUT_MS } = {}) {
130
+ if (this.#socket.readyState !== 1) {
131
+ return Promise.reject(new Error(`the DevTools connection is not open (${method})`))
132
+ }
133
+ const id = this.#nextId++
134
+ const envelope = { id, method, params }
135
+ if (sessionId) envelope.sessionId = sessionId
136
+ return new Promise((resolve, reject) => {
137
+ const timer = setTimeout(() => {
138
+ this.#pending.delete(id)
139
+ reject(new Error(`${method} timed out after ${timeoutMs}ms`))
140
+ }, timeoutMs)
141
+ this.#pending.set(id, {
142
+ method,
143
+ resolve: value => {
144
+ clearTimeout(timer)
145
+ resolve(value)
146
+ },
147
+ reject: error => {
148
+ clearTimeout(timer)
149
+ reject(error)
150
+ },
151
+ })
152
+ this.#socket.send(JSON.stringify(envelope))
153
+ })
154
+ }
155
+
156
+ /** Listen for every DevTools event; returns an unsubscribe function. */
157
+ onEvent(listener) {
158
+ this.#listeners.add(listener)
159
+ return () => this.#listeners.delete(listener)
160
+ }
161
+
162
+ /** Wait until the socket closes. */
163
+ closed() {
164
+ return this.#closed
165
+ }
166
+
167
+ close() {
168
+ try {
169
+ this.#socket.close()
170
+ } catch {
171
+ // Already closing; nothing to release.
172
+ }
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Wait for `DevToolsActivePort` to appear, which is how a browser launched with
178
+ * port 0 reports the port it actually took.
179
+ */
180
+ async function readActivePort(userDataDir, { timeoutMs = LAUNCH_TIMEOUT_MS, child = null } = {}) {
181
+ const file = path.join(userDataDir, 'DevToolsActivePort')
182
+ const started = Date.now()
183
+ for (;;) {
184
+ if (child && child.exitCode !== null) {
185
+ throw new Error(`the browser exited with code ${child.exitCode} before opening a debugging port`)
186
+ }
187
+ try {
188
+ const text = await fsp.readFile(file, 'utf8')
189
+ const [port, target] = text.split('\n')
190
+ if (port && /^\d+$/.test(port.trim())) {
191
+ return { port: Number(port.trim()), path: (target ?? '').trim() }
192
+ }
193
+ } catch {
194
+ // Not written yet.
195
+ }
196
+ if (Date.now() - started > timeoutMs) {
197
+ throw new Error(`the browser did not open a debugging port within ${timeoutMs}ms (expected ${file})`)
198
+ }
199
+ await new Promise(resolve => setTimeout(resolve, 100))
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Launch a Chromium-family browser with its own profile directory.
205
+ *
206
+ * The profile is isolated on purpose: the user's everyday cookies and logins
207
+ * stay out of reach, which is exactly why an agent cannot inherit them.
208
+ *
209
+ * @param {{
210
+ * executablePath?: string|null,
211
+ * userDataDir?: string|null,
212
+ * headless?: boolean,
213
+ * timeoutMs?: number,
214
+ * env?: NodeJS.ProcessEnv,
215
+ * }} [options]
216
+ * @returns {Promise<{ port: number, wsUrl: string, executablePath: string, userDataDir: string, pid: number|undefined, close: () => Promise<void> }>}
217
+ */
218
+ export async function launchBrowser({
219
+ executablePath = null,
220
+ userDataDir = null,
221
+ headless = true,
222
+ timeoutMs = LAUNCH_TIMEOUT_MS,
223
+ env = process.env,
224
+ } = {}) {
225
+ const executable = findBrowserExecutable({ explicit: executablePath, env })
226
+ if (!executable) {
227
+ throw new Error(
228
+ 'no Chromium-family browser found; set runtime.browser.executablePath (or DSH_BROWSER_PATH) to chrome.exe or msedge.exe',
229
+ )
230
+ }
231
+ const profileDir = userDataDir
232
+ ? path.resolve(userDataDir)
233
+ : await fsp.mkdtemp(path.join(os.tmpdir(), 'dsh-runtime-profile-'))
234
+ await fsp.mkdir(profileDir, { recursive: true })
235
+ const args = [
236
+ '--remote-debugging-port=0',
237
+ `--user-data-dir=${profileDir}`,
238
+ '--no-first-run',
239
+ '--no-default-browser-check',
240
+ '--disable-background-networking',
241
+ '--disable-component-update',
242
+ '--disable-sync',
243
+ '--disable-extensions',
244
+ '--disable-features=Translate,MediaRouter',
245
+ '--window-size=1280,900',
246
+ ]
247
+ if (headless) args.push('--headless=new')
248
+ args.push('about:blank')
249
+
250
+ const child = spawn(executable, args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true })
251
+ let stderr = ''
252
+ child.stderr?.on('data', chunk => {
253
+ if (stderr.length < 4000) stderr += String(chunk)
254
+ })
255
+ const close = async () => {
256
+ if (child.exitCode === null) {
257
+ child.kill()
258
+ await new Promise(resolve => {
259
+ const timer = setTimeout(resolve, 3000)
260
+ child.once('exit', () => {
261
+ clearTimeout(timer)
262
+ resolve()
263
+ })
264
+ })
265
+ }
266
+ }
267
+ let active
268
+ try {
269
+ active = await readActivePort(profileDir, { timeoutMs, child })
270
+ } catch (error) {
271
+ await close()
272
+ throw new Error(`${error.message}${stderr ? `\nbrowser stderr: ${stderr.trim().slice(0, 800)}` : ''}`)
273
+ }
274
+ const wsUrl = `ws://127.0.0.1:${active.port}${active.path || `/devtools/browser/`}`
275
+ return { port: active.port, wsUrl, executablePath: executable, userDataDir: profileDir, pid: child.pid, close }
276
+ }
277
+
278
+ /**
279
+ * Read the browser websocket URL from an already running browser that was
280
+ * started with `--remote-debugging-port=<port>`.
281
+ * @param {number} port
282
+ * @returns {Promise<{ wsUrl: string, browser: string, webSocketDebuggerUrl: string }>}
283
+ */
284
+ export async function discoverEndpoint(port) {
285
+ const response = await fetch(`http://127.0.0.1:${port}/json/version`)
286
+ if (!response.ok) throw new Error(`no DevTools endpoint on 127.0.0.1:${port} (HTTP ${response.status})`)
287
+ const info = await response.json()
288
+ if (!info?.webSocketDebuggerUrl) throw new Error(`127.0.0.1:${port} answered without a webSocketDebuggerUrl`)
289
+ return { wsUrl: info.webSocketDebuggerUrl, browser: info.Browser ?? 'unknown', webSocketDebuggerUrl: info.webSocketDebuggerUrl }
290
+ }
291
+
292
+ /**
293
+ * In-page enumeration of actionable elements.
294
+ *
295
+ * It assigns `data-dsh-el="<index>"` to every element it returns, so a later
296
+ * click can address the exact node instead of re-running an ambiguous selector.
297
+ * The accessible name follows the ARIA fallback order closely enough to match
298
+ * what a screen reader announces for buttons, links, and labelled inputs.
299
+ */
300
+ export const ENUMERATE_ELEMENTS = String.raw`(() => {
301
+ const MAX = 400
302
+ const visible = el => {
303
+ const rect = el.getBoundingClientRect()
304
+ if (rect.width < 1 || rect.height < 1) return false
305
+ const style = getComputedStyle(el)
306
+ if (style.visibility === 'hidden' || style.display === 'none') return false
307
+ if (Number(style.opacity || '1') < 0.05) return false
308
+ return true
309
+ }
310
+ const implicitRole = el => {
311
+ const tag = el.tagName.toLowerCase()
312
+ const type = (el.getAttribute('type') || '').toLowerCase()
313
+ if (tag === 'a') return 'link'
314
+ if (tag === 'button') return 'button'
315
+ if (tag === 'select') return 'combobox'
316
+ if (tag === 'textarea') return 'textbox'
317
+ if (tag === 'summary') return 'button'
318
+ if (tag === 'input') {
319
+ if (['button', 'submit', 'reset', 'image'].includes(type)) return 'button'
320
+ if (type === 'checkbox') return 'checkbox'
321
+ if (type === 'radio') return 'radio'
322
+ if (type === 'file') return 'file-input'
323
+ if (type === 'search') return 'searchbox'
324
+ return 'textbox'
325
+ }
326
+ if (el.isContentEditable) return 'textbox'
327
+ return null
328
+ }
329
+ const nameOf = el => {
330
+ const labelled = el.getAttribute('aria-labelledby')
331
+ if (labelled) {
332
+ const text = labelled.split(/\s+/)
333
+ .map(id => document.getElementById(id)?.textContent || '')
334
+ .join(' ')
335
+ .trim()
336
+ if (text) return text
337
+ }
338
+ const aria = el.getAttribute('aria-label')
339
+ if (aria && aria.trim()) return aria.trim()
340
+ const tag = el.tagName.toLowerCase()
341
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {
342
+ if (el.labels && el.labels.length > 0) {
343
+ const text = [...el.labels].map(label => label.textContent || '').join(' ').trim()
344
+ if (text) return text
345
+ }
346
+ const placeholder = el.getAttribute('placeholder')
347
+ if (placeholder && placeholder.trim()) return placeholder.trim()
348
+ }
349
+ const alt = el.getAttribute('alt')
350
+ if (alt && alt.trim()) return alt.trim()
351
+ const title = el.getAttribute('title')
352
+ if (title && title.trim()) return title.trim()
353
+ const text = (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim()
354
+ if (text) return text
355
+ return (el.getAttribute('value') || '').trim()
356
+ }
357
+ const selector = 'a[href], button, input, select, textarea, summary, [role], [onclick], [contenteditable="true"], [tabindex]'
358
+ const nodes = [...document.querySelectorAll(selector)]
359
+ for (const node of document.querySelectorAll('[data-dsh-el]')) node.removeAttribute('data-dsh-el')
360
+ const out = []
361
+ let index = 0
362
+ for (const el of nodes) {
363
+ if (out.length >= MAX) break
364
+ if (!visible(el)) continue
365
+ const role = (el.getAttribute('role') || implicitRole(el) || '').trim() || null
366
+ const name = nameOf(el)
367
+ if (!role && !name && !el.hasAttribute('onclick') && !el.hasAttribute('tabindex')) continue
368
+ const rect = el.getBoundingClientRect()
369
+ el.setAttribute('data-dsh-el', String(index))
370
+ out.push({
371
+ index,
372
+ tag: el.tagName.toLowerCase(),
373
+ role,
374
+ name,
375
+ type: (el.getAttribute('type') || '').toLowerCase() || null,
376
+ href: el.getAttribute('href'),
377
+ disabled: el.disabled === true || el.getAttribute('aria-disabled') === 'true',
378
+ checked: typeof el.checked === 'boolean' ? el.checked : null,
379
+ value: typeof el.value === 'string' ? el.value.slice(0, 200) : null,
380
+ bbox: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) },
381
+ inViewport: rect.bottom > 0 && rect.right > 0 && rect.top < innerHeight && rect.left < innerWidth,
382
+ })
383
+ index += 1
384
+ }
385
+ return {
386
+ url: location.href,
387
+ title: document.title,
388
+ scroll: { x: Math.round(scrollX), y: Math.round(scrollY) },
389
+ viewport: { width: innerWidth, height: innerHeight },
390
+ elements: out,
391
+ }
392
+ })()`
393
+
394
+ /**
395
+ * Decide whether a page is asking a person to do something automation must not
396
+ * do for them: solve a CAPTCHA, enter an SMS code, confirm "you are human",
397
+ * scan a QR code, or sign in.
398
+ *
399
+ * Only page text is inspected, deliberately. A reCAPTCHA badge or a password
400
+ * field on an ordinary settings page must not stop a run, so a check is only
401
+ * reported when the copy says a person is needed; the password field counts
402
+ * only next to a sign-in word.
403
+ *
404
+ * @param {{ text?: string, passwordField?: boolean }} [signals]
405
+ * @returns {{ kind: string, label: string, matched: string }|null}
406
+ */
407
+ export function classifyHumanGate({ text = '', passwordField = false } = {}) {
408
+ const body = String(text ?? '').slice(0, 20000)
409
+ const rules = [
410
+ {
411
+ kind: 'human-verification',
412
+ label: 'a CAPTCHA or "confirm you are human" check',
413
+ patterns: [
414
+ /confirm (that )?you are (a )?human/i,
415
+ /verify (that )?you are (a )?human/i,
416
+ /i'?m not a robot/i,
417
+ /not a robot/i,
418
+ /captcha/i,
419
+ /人机验证/,
420
+ /安全验证/,
421
+ /完成验证/,
422
+ /滑动.{0,8}验证/,
423
+ /拖动.{0,8}滑块/,
424
+ /滑块验证/,
425
+ ],
426
+ },
427
+ {
428
+ kind: 'sms-code',
429
+ label: 'an SMS or one-time verification code',
430
+ patterns: [
431
+ /短信验证码/,
432
+ /短信验证/,
433
+ /验证码/,
434
+ /verification code/i,
435
+ /one[- ]time (pass)?code/i,
436
+ /动态码/,
437
+ /校验码/,
438
+ ],
439
+ },
440
+ {
441
+ kind: 'two-factor',
442
+ label: 'a two-factor confirmation',
443
+ patterns: [/two[- ]factor/i, /\b2fa\b/i, /authenticator/i, /双重验证/, /两步验证/, /身份验证器/],
444
+ },
445
+ {
446
+ kind: 'qr-login',
447
+ label: 'a QR-code sign-in',
448
+ patterns: [/扫码登录/, /扫一扫登录/, /二维码登录/, /scan (the )?qr/i, /qr code.*(sign|log)\s?in/i],
449
+ },
450
+ {
451
+ kind: 'login-required',
452
+ label: 'a sign-in the page is waiting for',
453
+ patterns: [
454
+ /请先登录/,
455
+ /请登录后/,
456
+ /登录后(查看|继续|访问|才)/,
457
+ /登录已(过期|失效)/,
458
+ /未登录/,
459
+ /please (sign|log) in/i,
460
+ /sign in to continue/i,
461
+ /log in to continue/i,
462
+ /session (has )?expired/i,
463
+ /authentication required/i,
464
+ ],
465
+ },
466
+ ]
467
+ for (const rule of rules) {
468
+ for (const pattern of rule.patterns) {
469
+ const match = pattern.exec(body)
470
+ if (match) return { kind: rule.kind, label: rule.label, matched: match[0] }
471
+ }
472
+ }
473
+ if (passwordField && /(sign in|log in|登录)/i.test(body)) {
474
+ return { kind: 'login-required', label: 'a sign-in form the page is waiting for', matched: 'password field' }
475
+ }
476
+ return null
477
+ }
478
+
479
+ /**
480
+ * One tab, attached as a flat DevTools session.
481
+ *
482
+ * Coordinates are CSS pixels from the top-left of the viewport, which is what
483
+ * `Input.dispatchMouseEvent` and `getBoundingClientRect()` both use, so a
484
+ * reported box can be fed straight back into a click.
485
+ */
486
+ export class PageSession {
487
+ /**
488
+ * @param {CdpConnection} connection
489
+ * @param {string} sessionId
490
+ * @param {string} targetId
491
+ */
492
+ constructor(connection, sessionId, targetId) {
493
+ this.connection = connection
494
+ this.sessionId = sessionId
495
+ this.targetId = targetId
496
+ this.closed = false
497
+ }
498
+
499
+ #send(method, params = {}, timeoutMs) {
500
+ return this.connection.send(method, params, { sessionId: this.sessionId, timeoutMs })
501
+ }
502
+
503
+ /** Enable the domains every later call depends on. */
504
+ async init({ width = 1280, height = 900, emulateViewport = true } = {}) {
505
+ await this.#send('Page.enable')
506
+ await this.#send('Runtime.enable')
507
+ // A fixed viewport makes a screenshot a stable piece of evidence instead of
508
+ // whatever size the last window happened to have. An attached tab is the
509
+ // user's own window, so it keeps the size the user gave it.
510
+ if (emulateViewport) {
511
+ await this.#send('Emulation.setDeviceMetricsOverride', {
512
+ width,
513
+ height,
514
+ deviceScaleFactor: 1,
515
+ mobile: false,
516
+ })
517
+ }
518
+ return this
519
+ }
520
+
521
+ /**
522
+ * Navigate and wait for `document.readyState` to settle.
523
+ * @param {string} url
524
+ * @param {{ timeoutMs?: number }} [options]
525
+ */
526
+ async goto(url, { timeoutMs = NAVIGATION_TIMEOUT_MS } = {}) {
527
+ const result = await this.#send('Page.navigate', { url }, timeoutMs)
528
+ if (result.errorText) throw new Error(`navigation to ${url} failed: ${result.errorText}`)
529
+ await this.waitForIdle({ timeoutMs })
530
+ return { url: await this.evaluate('location.href'), title: await this.evaluate('document.title') }
531
+ }
532
+
533
+ /** Poll until the document finished loading or the timeout expires. */
534
+ async waitForIdle({ timeoutMs = NAVIGATION_TIMEOUT_MS } = {}) {
535
+ const started = Date.now()
536
+ for (;;) {
537
+ const state = await this.evaluate('document.readyState', { timeoutMs: 5000 })
538
+ if (state === 'complete') return
539
+ if (Date.now() - started > timeoutMs) return
540
+ await new Promise(resolve => setTimeout(resolve, 100))
541
+ }
542
+ }
543
+
544
+ /**
545
+ * Evaluate an expression in the page and return its JSON value.
546
+ * @param {string} expression
547
+ * @param {{ awaitPromise?: boolean, timeoutMs?: number }} [options]
548
+ */
549
+ async evaluate(expression, { awaitPromise = true, timeoutMs = CALL_TIMEOUT_MS } = {}) {
550
+ const result = await this.#send('Runtime.evaluate', {
551
+ expression,
552
+ returnByValue: true,
553
+ awaitPromise,
554
+ userGesture: true,
555
+ }, timeoutMs)
556
+ if (result.exceptionDetails) {
557
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text
558
+ throw new Error(`page script threw: ${String(detail).split('\n')[0]}`)
559
+ }
560
+ return result.result?.value
561
+ }
562
+
563
+ /** Enumerate actionable elements, assigning a clickable data-dsh-el index. */
564
+ async elements() {
565
+ return this.evaluate(ENUMERATE_ELEMENTS)
566
+ }
567
+
568
+ /**
569
+ * Report the human check this page is waiting for, or null.
570
+ *
571
+ * The classifier is injected from its own source so the page and the unit
572
+ * tests run exactly the same rules.
573
+ *
574
+ * @returns {Promise<{ kind: string, label: string, matched: string }|null>}
575
+ */
576
+ async humanGate() {
577
+ const expression = `(() => {
578
+ const visible = el => {
579
+ const rect = el.getBoundingClientRect()
580
+ if (rect.width < 1 || rect.height < 1) return false
581
+ const style = getComputedStyle(el)
582
+ return style.visibility !== 'hidden' && style.display !== 'none'
583
+ }
584
+ const passwordField = [...document.querySelectorAll('input[type="password"]')].some(visible)
585
+ const text = (document.body ? document.body.innerText : '').slice(0, 20000)
586
+ return (${classifyHumanGate.toString()})({ text, passwordField })
587
+ })()`
588
+ return this.evaluate(expression)
589
+ }
590
+
591
+ /**
592
+ * Click one element by its `data-dsh-el` index.
593
+ * @param {number} index
594
+ */
595
+ async clickIndex(index) {
596
+ const box = await this.evaluate(`(() => {
597
+ const el = document.querySelector('[data-dsh-el="${Number(index)}"]')
598
+ if (!el) return null
599
+ el.scrollIntoView({ block: 'center', inline: 'center' })
600
+ const rect = el.getBoundingClientRect()
601
+ return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2, width: rect.width, height: rect.height }
602
+ })()`)
603
+ if (!box) throw new Error(`element index ${index} is no longer on the page; list the elements again`)
604
+ return this.clickAt({ x: box.x, y: box.y, box })
605
+ }
606
+
607
+ /**
608
+ * Dispatch a real mouse press/release at a viewport coordinate.
609
+ * @param {{ x: number, y: number, box?: object }} point
610
+ */
611
+ async clickAt({ x, y, box = null }) {
612
+ const base = { x, y, button: 'left', clickCount: 1 }
613
+ await this.#send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y })
614
+ await this.#send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base })
615
+ await this.#send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base })
616
+ return { x: Math.round(x), y: Math.round(y), box }
617
+ }
618
+
619
+ /**
620
+ * Focus an element and insert text.
621
+ * @param {{ index?: number, text: string, submit?: boolean }} options
622
+ */
623
+ async typeInto({ index = null, text, submit = false }) {
624
+ if (index !== null) await this.clickIndex(index)
625
+ // insertText goes through the same input pipeline as a paste: React and
626
+ // plain inputs both see it, and it cannot be swallowed by a slow keymap.
627
+ await this.#send('Input.insertText', { text })
628
+ if (submit) await this.pressEnter()
629
+ return { index, inserted: text.length, submit }
630
+ }
631
+
632
+ /** Press Enter through the input domain, so a form submits the way a user's key would. */
633
+ async pressEnter() {
634
+ const key = { key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 }
635
+ await this.#send('Input.dispatchKeyEvent', { type: 'keyDown', ...key, text: '\r' })
636
+ await this.#send('Input.dispatchKeyEvent', { type: 'keyUp', ...key })
637
+ }
638
+
639
+ /**
640
+ * Capture a PNG screenshot.
641
+ * @param {{ path: string, fullPage?: boolean }} options
642
+ * @returns {Promise<{ path: string, bytes: number, width: number, height: number }>}
643
+ */
644
+ async screenshot({ path: file, fullPage = false }) {
645
+ const { data } = await this.#send('Page.captureScreenshot', {
646
+ format: 'png',
647
+ fromSurface: true,
648
+ captureBeyondViewport: fullPage,
649
+ })
650
+ const buffer = Buffer.from(data, 'base64')
651
+ await fsp.mkdir(path.dirname(file), { recursive: true })
652
+ await fsp.writeFile(file, buffer)
653
+ const size = await this.evaluate('({ width: innerWidth, height: innerHeight })')
654
+ return { path: file, bytes: buffer.length, width: size.width, height: size.height }
655
+ }
656
+
657
+ /**
658
+ * Poll for a condition.
659
+ * @param {{ text?: string|null, css?: string|null, urlContains?: string|null, timeoutMs?: number, intervalMs?: number, sleepMs?: number }} [options]
660
+ */
661
+ async waitFor({ text = null, css = null, urlContains = null, timeoutMs = 10000, intervalMs = 150, sleepMs = null } = {}) {
662
+ if (sleepMs !== null) {
663
+ await new Promise(resolve => setTimeout(resolve, Math.max(0, Number(sleepMs) || 0)))
664
+ return { waited: Number(sleepMs), condition: 'sleep' }
665
+ }
666
+ const started = Date.now()
667
+ const checks = []
668
+ if (text) {
669
+ const needle = JSON.stringify(String(text))
670
+ checks.push(`(document.body ? document.body.innerText : '').includes(${needle})`)
671
+ }
672
+ if (css) checks.push(`Boolean(document.querySelector(${JSON.stringify(String(css))}))`)
673
+ if (urlContains) checks.push(`location.href.includes(${JSON.stringify(String(urlContains))})`)
674
+ if (checks.length === 0) throw new Error('wait needs text, css, url_contains, or milliseconds')
675
+ const expression = `Boolean(${checks.join(' && ')})`
676
+ for (;;) {
677
+ if (await this.evaluate(expression, { timeoutMs: 5000 })) {
678
+ return { waited: Date.now() - started, condition: expression }
679
+ }
680
+ if (Date.now() - started > timeoutMs) {
681
+ throw new Error(`waited ${timeoutMs}ms and the condition never became true: ${expression}`)
682
+ }
683
+ await new Promise(resolve => setTimeout(resolve, intervalMs))
684
+ }
685
+ }
686
+ }
687
+
688
+ /**
689
+ * A browser plus the single tab this plugin keeps for the process.
690
+ *
691
+ * One tab is enough for the supported actions and keeps the audit trail
692
+ * unambiguous: every URL in the log belongs to the same page.
693
+ */
694
+ export async function openBrowser({ executablePath = null, headless = true, timeoutMs = LAUNCH_TIMEOUT_MS, width = 1280, height = 900, userDataDir = null } = {}) {
695
+ const launched = await launchBrowser({ executablePath, headless, timeoutMs, userDataDir })
696
+ let connection
697
+ try {
698
+ connection = await CdpConnection.connect(launched.wsUrl, { timeoutMs })
699
+ const { targetId } = await connection.send('Target.createTarget', { url: 'about:blank' })
700
+ const { sessionId } = await connection.send('Target.attachToTarget', { targetId, flatten: true })
701
+ const page = new PageSession(connection, sessionId, targetId)
702
+ await page.init({ width, height })
703
+ return {
704
+ page,
705
+ connection,
706
+ mode: 'launch',
707
+ port: launched.port,
708
+ executablePath: launched.executablePath,
709
+ userDataDir: launched.userDataDir,
710
+ persistentProfile: Boolean(userDataDir),
711
+ headless: headless === true,
712
+ pid: launched.pid,
713
+ async close() {
714
+ try {
715
+ await connection.send('Target.closeTarget', { targetId })
716
+ } catch {
717
+ // The tab may already be gone; the socket close below still releases it.
718
+ }
719
+ connection.close()
720
+ await launched.close()
721
+ },
722
+ }
723
+ } catch (error) {
724
+ connection?.close()
725
+ await launched.close()
726
+ throw error
727
+ }
728
+ }
729
+
730
+ /**
731
+ * Attach to a browser the user started themselves with `--remote-debugging-port`.
732
+ *
733
+ * The existing tab is reused, not a new one, and the window keeps its size: this
734
+ * is the user's own session, so the plugin borrows it rather than repainting it.
735
+ * The returned `close` detaches; it never terminates the user's browser.
736
+ *
737
+ * @param {{ port: number, timeoutMs?: number, width?: number, height?: number }} options
738
+ */
739
+ export async function attachBrowser({ port, timeoutMs = LAUNCH_TIMEOUT_MS, width = 1280, height = 900 }) {
740
+ const endpoint = await discoverEndpoint(port)
741
+ const connection = await CdpConnection.connect(endpoint.wsUrl, { timeoutMs })
742
+ let targetId = null
743
+ let createdTarget = false
744
+ try {
745
+ const targets = await connection.send('Target.getTargets')
746
+ const pages = (targets.targetInfos ?? [])
747
+ .filter(info => info.type === 'page' && !String(info.url ?? '').startsWith('devtools://'))
748
+ // Prefer a real page over about:blank, so a freshly started browser does not
749
+ // win over the tab the user already has open.
750
+ const existing = pages.find(info => /^https?:/i.test(String(info.url ?? ''))) ?? pages[0]
751
+ if (existing) {
752
+ targetId = existing.targetId
753
+ } else {
754
+ targetId = (await connection.send('Target.createTarget', { url: 'about:blank' })).targetId
755
+ createdTarget = true
756
+ }
757
+ const { sessionId } = await connection.send('Target.attachToTarget', { targetId, flatten: true })
758
+ const page = new PageSession(connection, sessionId, targetId)
759
+ await page.init({ width, height, emulateViewport: false })
760
+ let attachedUrl = null
761
+ try {
762
+ attachedUrl = await page.evaluate('location.href')
763
+ } catch {
764
+ attachedUrl = null
765
+ }
766
+ return {
767
+ page,
768
+ connection,
769
+ mode: 'attach',
770
+ port,
771
+ executablePath: null,
772
+ userDataDir: null,
773
+ persistentProfile: true,
774
+ headless: false,
775
+ pid: null,
776
+ browser: endpoint.browser,
777
+ attachedUrl,
778
+ createdTarget,
779
+ async close() {
780
+ // Only a tab this process created is closed; the user's own tabs stay.
781
+ if (createdTarget) {
782
+ try {
783
+ await connection.send('Target.closeTarget', { targetId })
784
+ } catch {
785
+ // The tab may already be gone.
786
+ }
787
+ }
788
+ connection.close()
789
+ },
790
+ }
791
+ } catch (error) {
792
+ connection.close()
793
+ throw error
794
+ }
795
+ }