dsh-plugin-doubao 0.0.0-stage → 0.2.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/bridge.js ADDED
@@ -0,0 +1,608 @@
1
+ /**
2
+ * The signed-request bridge.
3
+ *
4
+ * Doubao's risk engine wants an `a_bogus` + `msToken` pair on every chat
5
+ * request, and both are minted by native code inside the official client: the
6
+ * page's own `fetch` is wrapped by a preload hook that appends them, and no
7
+ * bundle on disk carries the algorithm (a scan of all 26 loaded scripts finds
8
+ * only the string "acrawler", never "a_bogus"). A plain Node request is
9
+ * therefore rejected with 710022004 no matter how closely it imitates the
10
+ * client's payload — that was measured across URL shape, body shape, cookies,
11
+ * conversation state and model choice.
12
+ *
13
+ * What does work is letting the client sign for us. This module drives the
14
+ * already-running client over the DevTools protocol: the page performs the
15
+ * fetch itself, so its own hook adds the signature, and each body chunk is
16
+ * pushed back through a Runtime binding as soon as it arrives. The measured
17
+ * first byte this way is 160-220ms, faster than the unsigned path ever was.
18
+ *
19
+ * The bridge is optional infrastructure, not a hard dependency: when no client
20
+ * is reachable the caller falls back to a direct request and reports whatever
21
+ * the service says. That keeps the plugin working on machines with no client
22
+ * installed, where a direct request is the only option anyway.
23
+ */
24
+ import { join, posix } from 'node:path'
25
+
26
+ const DEFAULT_PORT = 9222
27
+ const PUSH_BINDING = '__dshDoubaoPush'
28
+ const SESSION_VAR = '__dshDoubaoSession'
29
+
30
+ /**
31
+ * The client is an Electron app on every platform, but where it lives and what
32
+ * its process is called differ. Keep the OS-specific facts in one place so the
33
+ * launcher, the stopper and the discovery probe all agree. `platform` is a
34
+ * parameter on the injectable functions so tests can exercise any OS on any
35
+ * host.
36
+ */
37
+ const CLIENT_EXE = {
38
+ win32: 'D:\\Doubao\\app\\Doubao.exe',
39
+ darwin: '/Applications/Doubao.app/Contents/MacOS/Doubao',
40
+ linux: '/opt/Doubao/doubao',
41
+ }
42
+ const CLIENT_PROCESS = { win32: 'Doubao.exe', darwin: 'Doubao', linux: 'doubao' }
43
+
44
+ /**
45
+ * Where a Doubao client may live. The launcher must not assume the machine
46
+ * matches this one: the exe sits wherever the user chose to install it, and
47
+ * `D:\Doubao` is a known-good install here, not a universal rule. Discovery
48
+ * asks the OS first (running process, uninstall registry, mdfind, `which`) and
49
+ * probes these locations only as a last resort.
50
+ */
51
+ function knownLocations(platform) {
52
+ if (platform === 'darwin') {
53
+ return [
54
+ CLIENT_EXE.darwin,
55
+ process.env.HOME && posix.join(process.env.HOME, 'Applications', 'Doubao.app', 'Contents', 'MacOS', 'Doubao'),
56
+ ]
57
+ }
58
+ if (platform === 'linux') {
59
+ return [CLIENT_EXE.linux, '/usr/bin/doubao', process.env.HOME && posix.join(process.env.HOME, '.local', 'bin', 'doubao')]
60
+ }
61
+ return [
62
+ CLIENT_EXE.win32,
63
+ ...['LOCALAPPDATA', 'ProgramFiles', 'ProgramFiles(x86)'].flatMap((key) =>
64
+ process.env[key]
65
+ ? [
66
+ join(process.env[key], 'Doubao', 'app', 'Doubao.exe'),
67
+ join(process.env[key], 'Doubao', 'Doubao.exe'),
68
+ ]
69
+ : [],
70
+ ),
71
+ ]
72
+ }
73
+ const CLIENT_CANDIDATES = {
74
+ win32: knownLocations('win32').filter(Boolean),
75
+ darwin: knownLocations('darwin').filter(Boolean),
76
+ linux: knownLocations('linux').filter(Boolean),
77
+ }
78
+
79
+ /**
80
+ * CDP pages we are willing to run inside.
81
+ *
82
+ * The client opens several targets; only the chat surface is a real window with
83
+ * a cookie jar. The background target in particular loads the same origin with
84
+ * a zero viewport and answers nothing useful, so matching on type alone would
85
+ * silently pick a dud.
86
+ */
87
+ export function pickTarget(list) {
88
+ if (!Array.isArray(list)) return undefined
89
+ return list.find(
90
+ (t) =>
91
+ t.type === 'page' &&
92
+ /^(doubao:\/\/doubao-chat|https:\/\/www\.doubao\.com)/.test(String(t.url ?? '')),
93
+ )
94
+ }
95
+
96
+ async function listTargets(port) {
97
+ const res = await fetch('http://127.0.0.1:' + port + '/json/list', {
98
+ signal: AbortSignal.timeout(1200),
99
+ })
100
+ if (!res.ok) return undefined
101
+ return res.json()
102
+ }
103
+
104
+ /**
105
+ * Stop every running instance of the client so the next launch can own the
106
+ * single-instance lock *with* the debugger flag. On Windows the client is one
107
+ * process tree (`Doubao.exe`), so a plain taskkill is enough; a live client
108
+ * without the flag cannot be given a port any other way — a second spawn just
109
+ * joins it and drops the flag.
110
+ *
111
+ * Injectable so tests never touch a real process.
112
+ */
113
+ export async function stopExistingClient(
114
+ { execFile = defaultExecFile, platform = process.platform, name } = {},
115
+ ) {
116
+ const proc = name ?? CLIENT_PROCESS[platform] ?? 'Doubao.exe'
117
+ // `-x` matches the exact process NAME. Never use `-f` here: that matches the
118
+ // whole command line, so a harness started from a path containing
119
+ // "dsh-plugin-doubao" would kill itself.
120
+ const [file, args] =
121
+ platform === 'win32'
122
+ ? ['taskkill', ['/F', '/IM', proc, '/T']]
123
+ : ['pkill', ['-x', proc]]
124
+ try {
125
+ await execFile(file, args, { timeout: 5000 })
126
+ } catch {
127
+ // "no process found" is exactly the case we want — treat it as success.
128
+ }
129
+ // Release the single-instance lock and the old debug socket before relaunch.
130
+ await new Promise((r) => setTimeout(r, 800))
131
+ }
132
+
133
+ function defaultExecFile(file, args, opts) {
134
+ return new Promise((resolve, reject) => {
135
+ import('node:child_process').then(({ execFile }) => {
136
+ execFile(file, args, opts, (err, stdout, stderr) => (err ? reject(err) : resolve({ stdout, stderr })))
137
+ }, reject)
138
+ })
139
+ }
140
+
141
+ function defaultSpawn(command, args, opts) {
142
+ return import('node:child_process').then(({ spawn }) => {
143
+ const child = spawn(command, args, opts)
144
+ child.unref()
145
+ return child
146
+ })
147
+ }
148
+
149
+ async function waitForClient(port, tries, available, pollMs = 400) {
150
+ for (let i = 0; i < tries; i += 1) {
151
+ await new Promise((r) => setTimeout(r, pollMs))
152
+ if (await available(port).catch(() => false)) return true
153
+ }
154
+ return false
155
+ }
156
+
157
+ /**
158
+ * Launch the client with a debugging port open, restarting an existing instance
159
+ * if one is in the way.
160
+ *
161
+ * The client is a normal Electron app; the port only exists when it was started
162
+ * with the flag, and a second launch joins an already-running instance and
163
+ * silently drops the flag. So: spawn once and give it a short chance; if the
164
+ * bridge still is not up, stop whatever client is running and spawn again —
165
+ * that second launch now owns the instance and keeps the flag. Best-effort by
166
+ * design: the caller treats a miss as "no bridge".
167
+ *
168
+ * Every external effect is injectable so tests can exercise both the clean
169
+ * start and the restart path without spawning or killing anything real.
170
+ */
171
+ export async function launchClient(
172
+ port = DEFAULT_PORT,
173
+ {
174
+ spawn: spawnFn = defaultSpawn,
175
+ execFile = defaultExecFile,
176
+ stop = stopExistingClient,
177
+ available = bridgeAvailable,
178
+ discover = discoverClientExe,
179
+ pollMs = 400,
180
+ } = {},
181
+ ) {
182
+ const clientExe = await discover({ execFile }).catch(() => undefined)
183
+ if (!clientExe) return false
184
+ const args = ['--remote-debugging-port=' + port, '--remote-allow-origins=*']
185
+ const opts = { detached: true, stdio: 'ignore' }
186
+ // A cold Electron start can take well over ten seconds on a slow machine.
187
+ // Killing at 3.2s would murder the instance we just launched. First launch
188
+ // gets a generous window; only a *confirmed* live-but-unflagged instance is
189
+ // worth the disruptive restart.
190
+ const start = async (tries) => {
191
+ try {
192
+ await spawnFn(clientExe, args, opts)
193
+ } catch {
194
+ return false
195
+ }
196
+ return waitForClient(port, tries, available, pollMs)
197
+ }
198
+ if (await start(30)) return true // ~12s cold start
199
+ // A live instance ate our flag. Stop it and launch once more for real. If
200
+ // nothing actually came up, this stop is a harmless no-op (taskkill/pkill on
201
+ // a missing process is swallowed), and the second start is our last chance.
202
+ await stop({ execFile })
203
+ return start(15)
204
+ }
205
+
206
+ function defaultExistsSync(path) {
207
+ return import('node:fs').then(({ existsSync }) => existsSync(path))
208
+ }
209
+
210
+ /**
211
+ * Find the client executable on this machine.
212
+ *
213
+ * A running client is the best source: its own process carries the exact path,
214
+ * and it is also the instance that has to be stopped before a flagged relaunch.
215
+ * When nothing is running, fall back to probing the usual install locations and
216
+ * the uninstall registry. Every external call is injectable so tests never need
217
+ * a real client or PowerShell.
218
+ */
219
+ export async function discoverClientExe(
220
+ { execFile = defaultExecFile, exists = defaultExistsSync, platform = process.platform } = {},
221
+ ) {
222
+ const candidates = CLIENT_CANDIDATES[platform] ?? CLIENT_CANDIDATES.win32
223
+
224
+ if (platform === 'win32') {
225
+ // A live process is the strongest hint; the uninstall registry is next, and
226
+ // works even when the client is closed (exactly when we need to launch it).
227
+ const probe =
228
+ "$p=@();" +
229
+ "Get-Process Doubao -ErrorAction SilentlyContinue | ForEach-Object { if ($_.Path) { $p += $_.Path } };" +
230
+ "Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'," +
231
+ "'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'," +
232
+ "'HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*' -ErrorAction SilentlyContinue |" +
233
+ "Where-Object { $_.DisplayName -like '*Doubao*' -or $_.DisplayName -like '*豆包*' } |" +
234
+ "ForEach-Object { " +
235
+ "if ($_.DisplayIcon) { $ic = ($_.DisplayIcon -replace '^\"|\"$','' -replace ',\\d+$',''); $dir = Split-Path $ic -Parent; " +
236
+ "if ($dir) { $p += (Join-Path $dir 'app\\Doubao.exe'); $p += (Join-Path $dir 'Doubao.exe') } }; " +
237
+ "if ($_.InstallLocation) { $p += (Join-Path $_.InstallLocation 'app\\Doubao.exe'); $p += (Join-Path $_.InstallLocation 'Doubao.exe') } };" +
238
+ "$p | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1"
239
+ try {
240
+ const { stdout } = await execFile('powershell', ['-NoProfile', '-NonInteractive', '-Command', probe], {
241
+ timeout: 6000,
242
+ })
243
+ const found = String(stdout ?? '')
244
+ .split(/\r?\n/)
245
+ .map((s) => s.trim())
246
+ .find((s) => /Doubao\.exe$/i.test(s))
247
+ if (found && await exists(found)) return found
248
+ } catch {
249
+ // No process, no PowerShell, or no registry hit — probe known locations.
250
+ }
251
+ } else if (platform === 'darwin') {
252
+ // Spotlight knows where the .app was dropped, even outside /Applications.
253
+ try {
254
+ const { stdout } = await execFile('mdfind', ['kMDItemFSName == "Doubao.app"'], { timeout: 6000 })
255
+ for (const app of String(stdout ?? '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean)) {
256
+ const exe = posix.join(app, 'Contents', 'MacOS', 'Doubao')
257
+ if (await exists(exe)) return exe
258
+ }
259
+ } catch {
260
+ // mdfind missing or Spotlight disabled — fall through to a running process.
261
+ }
262
+ try {
263
+ const { stdout } = await execFile('ps', ['-axo', 'command='], { timeout: 6000 })
264
+ const match = String(stdout ?? '').match(/(\/[^ \n]*Doubao\.app\/Contents\/MacOS\/Doubao)(?=\s|$)/)
265
+ if (match && await exists(match[1])) return match[1]
266
+ } catch {
267
+ // Not running; probe known locations below.
268
+ }
269
+ } else {
270
+ // Linux: PATH first (AppImage / deb / snap wrappers all land on PATH), then
271
+ // a running process reported by /proc through `pgrep -a`.
272
+ try {
273
+ const { stdout } = await execFile('which', ['doubao'], { timeout: 6000 })
274
+ for (const line of String(stdout ?? '').split(/\r?\n/).map((s) => s.trim())) {
275
+ if (line && await exists(line)) return line
276
+ }
277
+ } catch {
278
+ // `which` absent or not on PATH — probe known locations below.
279
+ }
280
+ try {
281
+ const { stdout } = await execFile('pgrep', ['-a', 'doubao'], { timeout: 6000 })
282
+ const line = String(stdout ?? '')
283
+ .split(/\r?\n/)
284
+ .map((s) => s.trim())
285
+ .find(Boolean)
286
+ if (line) {
287
+ const exe = line.split(/\s+/)[0]
288
+ if (exe && await exists(exe)) return exe
289
+ }
290
+ } catch {
291
+ // Not running; probe known locations below.
292
+ }
293
+ }
294
+
295
+ for (const candidate of candidates) {
296
+ if (await exists(candidate)) return candidate
297
+ }
298
+ return undefined
299
+ }
300
+
301
+ /** A minimal CDP client: one socket, request/response ids, event fan-out. */
302
+ class Cdp {
303
+ constructor(socket) {
304
+ this.socket = socket
305
+ this.nextId = 0
306
+ this.pending = new Map()
307
+ this.listeners = new Set()
308
+ this.closed = false
309
+ socket.addEventListener('message', (ev) => {
310
+ let msg
311
+ try {
312
+ msg = JSON.parse(ev.data)
313
+ } catch {
314
+ return
315
+ }
316
+ if (msg.id !== undefined && this.pending.has(msg.id)) {
317
+ const { resolve, reject } = this.pending.get(msg.id)
318
+ this.pending.delete(msg.id)
319
+ if (msg.error) reject(new Error(msg.error.message ?? 'cdp error'))
320
+ else resolve(msg.result)
321
+ return
322
+ }
323
+ for (const fn of this.listeners) fn(msg)
324
+ })
325
+ socket.addEventListener('close', () => {
326
+ this.closed = true
327
+ const draining = [...this.pending.values()]
328
+ this.pending.clear()
329
+ for (const { reject } of draining) reject(new Error('cdp socket closed'))
330
+ for (const fn of this.listeners) fn({ method: '__closed' })
331
+ })
332
+ }
333
+
334
+ send(method, params = {}) {
335
+ if (this.closed) return Promise.reject(new Error('cdp socket closed'))
336
+ const id = ++this.nextId
337
+ return new Promise((resolve, reject) => {
338
+ this.pending.set(id, { resolve, reject })
339
+ this.socket.send(JSON.stringify({ id, method, params }))
340
+ // Every call here is either trivial setup or a page program that returns
341
+ // immediately; anything slower than this means the client is wedged.
342
+ const timer = setTimeout(() => {
343
+ if (!this.pending.has(id)) return
344
+ this.pending.delete(id)
345
+ reject(new Error('cdp timeout: ' + method))
346
+ }, 15_000)
347
+ timer.unref?.()
348
+ })
349
+ }
350
+
351
+ on(fn) {
352
+ this.listeners.add(fn)
353
+ return () => this.listeners.delete(fn)
354
+ }
355
+
356
+ close() {
357
+ try {
358
+ this.socket.close()
359
+ } catch {
360
+ /* already gone */
361
+ }
362
+ }
363
+ }
364
+
365
+ async function connect(port) {
366
+ const list = await listTargets(port)
367
+ const target = pickTarget(list)
368
+ if (!target?.webSocketDebuggerUrl) return undefined
369
+ const socket = new WebSocket(target.webSocketDebuggerUrl)
370
+ await new Promise((resolve, reject) => {
371
+ const timer = setTimeout(() => reject(new Error('cdp connect timeout')), 5_000)
372
+ socket.addEventListener(
373
+ 'open',
374
+ () => {
375
+ clearTimeout(timer)
376
+ resolve()
377
+ },
378
+ { once: true },
379
+ )
380
+ socket.addEventListener(
381
+ 'error',
382
+ () => {
383
+ clearTimeout(timer)
384
+ reject(new Error('cdp connect failed'))
385
+ },
386
+ { once: true },
387
+ )
388
+ })
389
+ return new Cdp(socket)
390
+ }
391
+
392
+ /** Is a client reachable right now? Cheap enough to call on every request. */
393
+ export async function bridgeAvailable(port = DEFAULT_PORT) {
394
+ const list = await listTargets(port).catch(() => undefined)
395
+ return pickTarget(list) !== undefined
396
+ }
397
+
398
+ /**
399
+ * One launch attempt per port per process.
400
+ *
401
+ * Otherwise every turn would spawn the client again while it is starting up,
402
+ * and a failed attempt would be retried on every single message. The result is
403
+ * cached — including a failure, because a machine without the client will not
404
+ * grow one between two questions.
405
+ */
406
+ const launchAttempts = new Map() // port -> { promise, at }
407
+ // A failed launch is cached only briefly: a machine that had no client a minute
408
+ // ago may have one now, and a permanent cache would strand those users on the
409
+ // unsigned path forever. Concurrent callers still share one in-flight attempt.
410
+ const LAUNCH_RETRY_MS = 30_000
411
+
412
+ export function forgetLaunchAttempts() {
413
+ launchAttempts.clear()
414
+ }
415
+
416
+ /**
417
+ * Make a bridge exist, starting the client if it is not up at all.
418
+ *
419
+ * This is the difference between "the plugin works when the client happens to
420
+ * be running" and "the plugin works": without the debugger port there is nobody
421
+ * to sign the request, and the unsigned one is refused with 710022004 the
422
+ * moment the account is under scrutiny. A client that is already running
423
+ * ignores the flag, so this cannot retro-fit a port onto a live instance — that
424
+ * needs a restart, which is the user's call, not ours.
425
+ */
426
+ export async function ensureBridge(
427
+ port = DEFAULT_PORT,
428
+ { launch = launchClient, available = bridgeAvailable, retryMs = LAUNCH_RETRY_MS } = {},
429
+ ) {
430
+ if (await available(port).catch(() => false)) return true
431
+ const now = Date.now()
432
+ const cached = launchAttempts.get(port)
433
+ if (cached && now - cached.at < retryMs) {
434
+ return cached.promise.catch(() => false)
435
+ }
436
+ const promise = (async () => {
437
+ const started = await launch(port).catch(() => false)
438
+ if (!started) return false
439
+ return available(port).catch(() => false)
440
+ })()
441
+ launchAttempts.set(port, { promise, at: now })
442
+ return promise.catch(() => false)
443
+ }
444
+
445
+ /**
446
+ * The program that runs inside the page.
447
+ *
448
+ * It is deliberately self-contained and defensive: a throw is reported back
449
+ * through the binding rather than surfacing as a silent hang, because a CDP
450
+ * evaluation that returns `'ok'` has no way to carry a later rejection.
451
+ */
452
+ function pageProgram(url, body) {
453
+ return `(() => {
454
+ const push = window.${PUSH_BINDING}
455
+ const send = (o) => { try { push(JSON.stringify(o)) } catch (e) {} }
456
+ const ctl = new AbortController()
457
+ window.${SESSION_VAR} = { cancel: () => ctl.abort() }
458
+ const timer = setTimeout(() => ctl.abort(), 180000)
459
+ ;(async () => {
460
+ try {
461
+ const res = await fetch(${JSON.stringify(url)}, {
462
+ method: 'POST',
463
+ headers: { 'Content-Type': 'application/json' },
464
+ body: ${JSON.stringify(body)},
465
+ signal: ctl.signal,
466
+ })
467
+ if (!res.ok || !res.body) {
468
+ send({ t: 'x', m: 'http ' + res.status })
469
+ return
470
+ }
471
+ const reader = res.body.getReader()
472
+ const dec = new TextDecoder()
473
+ for (;;) {
474
+ const { value, done } = await reader.read()
475
+ if (done) break
476
+ send({ t: 'c', d: dec.decode(value, { stream: true }) })
477
+ }
478
+ // Flush any trailing bytes that did not complete a code point.
479
+ const tail = dec.decode()
480
+ if (tail) send({ t: 'c', d: tail })
481
+ reader.cancel().catch(() => {})
482
+ send({ t: 'e' })
483
+ } catch (e) {
484
+ send({ t: 'x', m: String(e) })
485
+ } finally {
486
+ clearTimeout(timer)
487
+ window.${SESSION_VAR} = null
488
+ }
489
+ })()
490
+ return 'ok'
491
+ })()`
492
+ }
493
+
494
+ /**
495
+ * Ask a reachable client to perform the request and stream the body back.
496
+ *
497
+ * Yields the raw response text in whatever slices the client hands over, so the
498
+ * caller can reuse its frame parser untouched. Throws on transport failure,
499
+ * which the caller turns into a fallback rather than an error.
500
+ */
501
+ export async function* bridgeStream({ url, body, port = DEFAULT_PORT, signal }) {
502
+ // An already-cancelled caller must not emit a real chat request: the abort
503
+ // listener below only fires for *future* aborts. Bail before touching the
504
+ // client (mirrors Pacer.runIterable in doubao.js).
505
+ if (signal?.aborted) throw signal.reason ?? new Error('aborted')
506
+ const cdp = await connect(port)
507
+ if (!cdp) throw new Error('no doubao client listening')
508
+
509
+ const queue = []
510
+ let notify = null
511
+ let finished = false
512
+ let failure = null
513
+ let cancelSent = Promise.resolve()
514
+
515
+ const wake = () => {
516
+ if (!notify) return
517
+ const fn = notify
518
+ notify = null
519
+ fn()
520
+ }
521
+
522
+ const off = cdp.on((msg) => {
523
+ if (msg.method === '__closed') {
524
+ finished = true
525
+ failure = failure ?? new Error('client page closed')
526
+ wake()
527
+ return
528
+ }
529
+ if (msg.method !== 'Runtime.bindingCalled' || msg.params?.name !== PUSH_BINDING) return
530
+ let payload
531
+ try {
532
+ payload = JSON.parse(msg.params.payload ?? 'null')
533
+ } catch {
534
+ return
535
+ }
536
+ if (payload?.t === 'c' && typeof payload.d === 'string') {
537
+ queue.push(payload.d)
538
+ } else if (payload?.t === 'e') {
539
+ finished = true
540
+ wake()
541
+ } else if (payload?.t === 'x') {
542
+ finished = true
543
+ failure = new Error(String(payload.m ?? 'client request failed'))
544
+ wake()
545
+ }
546
+ })
547
+
548
+ const onAbort = () => {
549
+ finished = true
550
+ failure = new Error('aborted')
551
+ // Remember the cancel send so the finally block can await it before closing
552
+ // the socket — otherwise the cancel CDP message races with socket close and
553
+ // the page keeps streaming for up to its 180s budget.
554
+ cancelSent = cdp
555
+ .send('Runtime.evaluate', {
556
+ expression: `try { window.${SESSION_VAR}?.cancel?.() } catch (e) {}`,
557
+ returnByValue: true,
558
+ })
559
+ .catch(() => {})
560
+ wake()
561
+ }
562
+ signal?.addEventListener?.('abort', onAbort, { once: true })
563
+
564
+ // Watchdog: a lost end-frame ('e'/'x') or a dropped binding would otherwise
565
+ // leave the loop below spinning forever, leaking the socket and listeners.
566
+ // The page caps its own fetch at 180s; give the Node side a little more room.
567
+ let watchdog = null
568
+
569
+ try {
570
+ await cdp.send('Runtime.enable')
571
+ await cdp.send('Runtime.addBinding', { name: PUSH_BINDING })
572
+
573
+ const started = await cdp.send('Runtime.evaluate', {
574
+ expression: pageProgram(url, body),
575
+ returnByValue: true,
576
+ })
577
+ if (started?.exceptionDetails) throw new Error('client rejected the request program')
578
+
579
+ watchdog = setTimeout(() => {
580
+ if (finished) return
581
+ finished = true
582
+ failure = new Error('client bridge timed out waiting for the response to finish')
583
+ wake()
584
+ }, 200_000)
585
+ watchdog.unref?.()
586
+
587
+ for (;;) {
588
+ while (queue.length) yield queue.shift()
589
+ if (finished) break
590
+ await new Promise((resolve) => {
591
+ notify = resolve
592
+ const timer = setTimeout(resolve, 250)
593
+ timer.unref?.()
594
+ })
595
+ }
596
+ while (queue.length) yield queue.shift()
597
+ if (failure) throw failure
598
+ } finally {
599
+ if (watchdog) clearTimeout(watchdog)
600
+ signal?.removeEventListener?.('abort', onAbort)
601
+ off()
602
+ // Let the cancel message reach the page before tearing down the socket.
603
+ await cancelSent
604
+ cdp.close()
605
+ }
606
+ }
607
+
608
+ export { DEFAULT_PORT }