opencode-apex 0.1.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/README.md +155 -0
- package/advisor.ts +290 -0
- package/browser/actions.ts +811 -0
- package/browser/cdp.ts +603 -0
- package/browser/endpoint.ts +243 -0
- package/browser.ts +556 -0
- package/core/advisor-agent.ts +93 -0
- package/core/advisor-session.ts +292 -0
- package/core/advisor-tool.ts +76 -0
- package/core/bus.ts +192 -0
- package/core/conditions.ts +66 -0
- package/core/config.ts +533 -0
- package/core/crypto.ts +193 -0
- package/core/guard.ts +248 -0
- package/core/ingest-listener.ts +193 -0
- package/core/patterns.ts +385 -0
- package/core/redact.ts +256 -0
- package/core/rpc.ts +117 -0
- package/core/templates.ts +100 -0
- package/docs/ADVISOR.md +91 -0
- package/docs/BROWSER.md +226 -0
- package/docs/CONFIG.md +97 -0
- package/docs/EVENTS.md +102 -0
- package/docs/GUARD.md +165 -0
- package/docs/REDACT.md +121 -0
- package/docs/TROUBLESHOOTING.md +203 -0
- package/events.ts +934 -0
- package/guard.ts +250 -0
- package/index.ts +147 -0
- package/opencode-apex.jsonc +249 -0
- package/package.json +34 -0
- package/redact.ts +156 -0
package/browser/cdp.ts
ADDED
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cliente CDP sobre WebSocket contra un Chromium externo.
|
|
3
|
+
*
|
|
4
|
+
* El plugin-browser del servidor solo conoce el contrato Browser.Action/Result;
|
|
5
|
+
* este módulo traduce esas acciones al protocolo real. La equivalencia con la
|
|
6
|
+
* app Electron es directa: allí es `contents.debugger.sendCommand`, aquí es un
|
|
7
|
+
* mensaje por el socket.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { randomUUID } from "node:crypto"
|
|
11
|
+
import { WebSocket as NodeWebSocket } from "ws"
|
|
12
|
+
import { resolveEndpoint, type EndpointCandidate } from "./endpoint.js"
|
|
13
|
+
|
|
14
|
+
export const PROTOCOL_VERSION = "1.3"
|
|
15
|
+
|
|
16
|
+
export interface TlsOptions {
|
|
17
|
+
readonly ca?: Buffer
|
|
18
|
+
readonly rejectUnauthorized?: boolean
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export class CdpError extends Error {
|
|
22
|
+
readonly code: string
|
|
23
|
+
constructor(message: string, { code = "cdp_error" }: { code?: string } = {}) {
|
|
24
|
+
super(message)
|
|
25
|
+
this.name = "CdpError"
|
|
26
|
+
this.code = code
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ConnectInput {
|
|
31
|
+
readonly cdpUrl?: string
|
|
32
|
+
readonly profileDir?: string
|
|
33
|
+
readonly signal?: AbortSignal
|
|
34
|
+
readonly onCandidate?: (candidate: EndpointCandidate) => void
|
|
35
|
+
readonly timeoutMs?: number
|
|
36
|
+
readonly headers?: Record<string, string>
|
|
37
|
+
readonly tls?: TlsOptions
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export class CdpClient {
|
|
41
|
+
#socket: NodeWebSocket
|
|
42
|
+
#nextId = 1
|
|
43
|
+
#pending = new Map<number, { resolve: (value: any) => void; reject: (error: Error) => void }>()
|
|
44
|
+
#listeners = new Map<string, Set<(params: any, sessionId?: string) => void>>()
|
|
45
|
+
#closed = false
|
|
46
|
+
/** Cómo se resolvió el endpoint; útil para logs de diagnóstico. */
|
|
47
|
+
endpoint: EndpointCandidate | undefined
|
|
48
|
+
/** Grabaciones en curso, guardadas en el cliente para sobrevivir comandos. */
|
|
49
|
+
readonly traces: TraceState
|
|
50
|
+
|
|
51
|
+
private constructor(socket: NodeWebSocket, traces: TraceState) {
|
|
52
|
+
this.#socket = socket
|
|
53
|
+
this.traces = traces
|
|
54
|
+
socket.on("message", (data) => this.#onMessage(data.toString()))
|
|
55
|
+
socket.on("close", () => {
|
|
56
|
+
this.#closed = true
|
|
57
|
+
for (const { reject } of this.#pending.values()) {
|
|
58
|
+
reject(new CdpError("CDP socket closed", { code: "cdp_closed" }))
|
|
59
|
+
}
|
|
60
|
+
this.#pending.clear()
|
|
61
|
+
})
|
|
62
|
+
// Sin listener, un error de transporte tumba el proceso. Lo dejamos pasar:
|
|
63
|
+
// quien reintenta decide qué hacer.
|
|
64
|
+
socket.on("error", () => {})
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Conecta al Chromium externo.
|
|
69
|
+
*
|
|
70
|
+
* Cada conexión abre un popup "Allow remote debugging?" en el navegador: por
|
|
71
|
+
* eso quien llama debe mantener ESTE objeto vivo y no reconectar por comando.
|
|
72
|
+
*/
|
|
73
|
+
static async connect(input: ConnectInput): Promise<CdpClient> {
|
|
74
|
+
const { signal, onCandidate, timeoutMs = 60_000, headers, tls } = input
|
|
75
|
+
const endpoint = await resolveEndpoint({ cdpUrl: input.cdpUrl, profileDir: input.profileDir })
|
|
76
|
+
const failures: string[] = []
|
|
77
|
+
|
|
78
|
+
// Varios perfiles pueden declarar el mismo puerto (ficheros stale). Probamos
|
|
79
|
+
// en orden y nos quedamos con el primero que de verdad responde.
|
|
80
|
+
for (const candidate of endpoint.candidates) {
|
|
81
|
+
if (signal?.aborted) throw new CdpError("aborted before connect", { code: "aborted" })
|
|
82
|
+
onCandidate?.(candidate)
|
|
83
|
+
|
|
84
|
+
const socket = createSocket(candidate.webSocketDebuggerUrl, { headers, tls })
|
|
85
|
+
const opened = await new Promise<boolean>((resolve) => {
|
|
86
|
+
// El modo toggle deja el handshake a medias hasta que alguien acepta el
|
|
87
|
+
// popup "Allow remote debugging?". Sin este timeout el proceso se queda
|
|
88
|
+
// colgado para siempre en silencio.
|
|
89
|
+
const timer = setTimeout(() => finish(false), timeoutMs)
|
|
90
|
+
const onAbort = () => {
|
|
91
|
+
try {
|
|
92
|
+
socket.close()
|
|
93
|
+
} catch {
|
|
94
|
+
// el socket puede estar ya cerrado
|
|
95
|
+
}
|
|
96
|
+
finish(false)
|
|
97
|
+
}
|
|
98
|
+
const finish = (value: boolean) => {
|
|
99
|
+
clearTimeout(timer)
|
|
100
|
+
signal?.removeEventListener("abort", onAbort)
|
|
101
|
+
resolve(value)
|
|
102
|
+
}
|
|
103
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
104
|
+
socket.once("open", () => finish(true))
|
|
105
|
+
socket.once("error", () => finish(false))
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
if (!opened) {
|
|
109
|
+
failures.push(`${candidate.profileDir ?? candidate.webSocketDebuggerUrl} (sin respuesta o popup sin aprobar)`)
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const client = new CdpClient(socket, { trace: undefined, cpu: new Map() })
|
|
114
|
+
client.endpoint = candidate
|
|
115
|
+
return client
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
throw new CdpError(
|
|
119
|
+
`No se pudo abrir CDP. Probados: ${failures.join(", ")}. ` +
|
|
120
|
+
`Si el navegador usa el toggle de chrome://inspect/#remote-debugging, ` +
|
|
121
|
+
`acepta el popup "Allow remote debugging?" de cada intento y reintenta.`,
|
|
122
|
+
{ code: "cdp_no_ws" },
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Envía un comando CDP y espera su respuesta. */
|
|
127
|
+
send(method: string, params: Record<string, unknown> = {}, sessionId?: string): Promise<any> {
|
|
128
|
+
if (this.#closed) return Promise.reject(new CdpError("CDP socket closed", { code: "cdp_closed" }))
|
|
129
|
+
|
|
130
|
+
const id = this.#nextId++
|
|
131
|
+
const message: Record<string, unknown> = { id, method, params }
|
|
132
|
+
if (sessionId) message.sessionId = sessionId
|
|
133
|
+
|
|
134
|
+
return new Promise((resolve, reject) => {
|
|
135
|
+
this.#pending.set(id, { resolve, reject })
|
|
136
|
+
try {
|
|
137
|
+
this.#socket.send(JSON.stringify(message))
|
|
138
|
+
} catch (error) {
|
|
139
|
+
this.#pending.delete(id)
|
|
140
|
+
reject(new CdpError(`failed to send ${method}: ${(error as Error).message}`, { code: "cdp_send_failed" }))
|
|
141
|
+
}
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
on(method: string, handler: (params: any, sessionId?: string) => void): () => void {
|
|
146
|
+
let set = this.#listeners.get(method)
|
|
147
|
+
if (!set) {
|
|
148
|
+
set = new Set()
|
|
149
|
+
this.#listeners.set(method, set)
|
|
150
|
+
}
|
|
151
|
+
set.add(handler)
|
|
152
|
+
return () => {
|
|
153
|
+
set.delete(handler)
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
close() {
|
|
158
|
+
this.#closed = true
|
|
159
|
+
try {
|
|
160
|
+
this.#socket.close()
|
|
161
|
+
} catch {
|
|
162
|
+
// el socket puede estar ya cerrado
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
#onMessage(raw: string) {
|
|
167
|
+
let message: any
|
|
168
|
+
try {
|
|
169
|
+
message = JSON.parse(raw)
|
|
170
|
+
} catch {
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (message.id !== undefined) {
|
|
175
|
+
const entry = this.#pending.get(message.id)
|
|
176
|
+
if (!entry) return
|
|
177
|
+
this.#pending.delete(message.id)
|
|
178
|
+
if (message.error) {
|
|
179
|
+
entry.reject(
|
|
180
|
+
new CdpError(`${message.error.message ?? "CDP error"} (${message.error.code ?? "?"})`, {
|
|
181
|
+
code: "cdp_command_failed",
|
|
182
|
+
}),
|
|
183
|
+
)
|
|
184
|
+
} else {
|
|
185
|
+
entry.resolve(message.result ?? {})
|
|
186
|
+
}
|
|
187
|
+
return
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (message.method) {
|
|
191
|
+
// Un evento de sesión se entrega a los dos quenchados: el que incluye el
|
|
192
|
+
// sessionId y el que no. Así los colectores pueden afinar por sesión sin
|
|
193
|
+
// perder al resto de oyentes.
|
|
194
|
+
const key = message.sessionId ? `${message.sessionId}:${message.method}` : message.method
|
|
195
|
+
for (const handler of this.#listeners.get(key) ?? []) this.#fire(handler, message)
|
|
196
|
+
for (const handler of this.#listeners.get(message.method) ?? []) this.#fire(handler, message)
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
#fire(handler: (params: any, sessionId?: string) => void, message: any) {
|
|
201
|
+
try {
|
|
202
|
+
handler(message.params ?? {}, message.sessionId)
|
|
203
|
+
} catch {
|
|
204
|
+
// un handler roto no debe tumbar el stream de eventos
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
interface TraceState {
|
|
210
|
+
trace: { tabID: string; startedAt: number; durationMs: number } | undefined
|
|
211
|
+
cpu: Map<string, string>
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export interface LiveTab {
|
|
215
|
+
readonly id: string
|
|
216
|
+
readonly targetId: string
|
|
217
|
+
readonly url: string
|
|
218
|
+
readonly title: string
|
|
219
|
+
readonly loading: boolean
|
|
220
|
+
readonly canGoBack: boolean
|
|
221
|
+
readonly canGoForward: boolean
|
|
222
|
+
readonly generation: number
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Traduce una tab opencode (`tab_<uuid>`) al targetId de Chromium que realmente
|
|
227
|
+
* existe en el navegador externo. Los IDs de opencode no coinciden con los de
|
|
228
|
+
* CDP, así que mantenemos el mapeo ourselves.
|
|
229
|
+
*/
|
|
230
|
+
export class TabRegistry {
|
|
231
|
+
readonly cdp: CdpClient
|
|
232
|
+
#byTabID = new Map<string, { id: string; targetId: string }>()
|
|
233
|
+
#generation = 0
|
|
234
|
+
#sessions = new Map<string, string>() // tabID → sessionId (cacheado)
|
|
235
|
+
#live = new Set<string>() // sessionIds que siguen vivos
|
|
236
|
+
|
|
237
|
+
constructor(cdp: CdpClient) {
|
|
238
|
+
this.cdp = cdp
|
|
239
|
+
// Una sesión CDP muere con la navegación: hay que reengancharse y, sobre
|
|
240
|
+
// todo, abrir de nuevo los dominios que tuviera activados.
|
|
241
|
+
cdp.on("Target.detachedFromTarget", (params: any) => {
|
|
242
|
+
if (params.sessionId) this.#live.delete(params.sessionId)
|
|
243
|
+
})
|
|
244
|
+
cdp.on("Target.detachedFromTarget", (params: any) => {
|
|
245
|
+
if (!params.targetId) return
|
|
246
|
+
for (const [id, entry] of this.#byTabID) {
|
|
247
|
+
if (entry.targetId !== params.targetId) continue
|
|
248
|
+
this.#sessions.delete(id)
|
|
249
|
+
this.#byTabID.delete(id)
|
|
250
|
+
}
|
|
251
|
+
})
|
|
252
|
+
cdp.on("Target.sessionDetached", (params: any) => {
|
|
253
|
+
if (params.sessionId) this.#live.delete(params.sessionId)
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Marca una sesión como viva; lo llama attach al resolverla. */
|
|
258
|
+
markLive(sessionId: string) {
|
|
259
|
+
this.#live.add(sessionId)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
get generation() {
|
|
263
|
+
return this.#generation
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
bumpGeneration() {
|
|
267
|
+
this.#generation += 1
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async list(): Promise<LiveTab[]> {
|
|
271
|
+
const { targetInfos } = await this.cdp.send("Target.getTargets")
|
|
272
|
+
const tabs: LiveTab[] = []
|
|
273
|
+
|
|
274
|
+
for (const target of targetInfos as Array<{ targetId: string; type: string; url: string; title?: string }>) {
|
|
275
|
+
if (target.type !== "page") continue
|
|
276
|
+
if (target.url.startsWith("devtools://")) continue
|
|
277
|
+
|
|
278
|
+
const existing = this.#findByTarget(target.targetId)
|
|
279
|
+
const id = existing ?? `tab_${randomUUID()}`
|
|
280
|
+
const previous = existing ? this.#byTabID.get(existing) : undefined
|
|
281
|
+
|
|
282
|
+
tabs.push({
|
|
283
|
+
id,
|
|
284
|
+
targetId: target.targetId,
|
|
285
|
+
url: target.url,
|
|
286
|
+
title: target.title ?? "",
|
|
287
|
+
loading: false,
|
|
288
|
+
canGoBack: false,
|
|
289
|
+
canGoForward: false,
|
|
290
|
+
generation: this.#generation,
|
|
291
|
+
})
|
|
292
|
+
this.#byTabID.set(id, { ...(previous ?? {}), id, targetId: target.targetId })
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Limpia entradas cuyo target ya no existe (el usuario cerró la pestaña).
|
|
296
|
+
const live = new Set(tabs.map((tab) => tab.targetId))
|
|
297
|
+
for (const [id, entry] of this.#byTabID) {
|
|
298
|
+
if (!live.has(entry.targetId)) this.#byTabID.delete(id)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return tabs
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
resolve(tabID: string): string {
|
|
305
|
+
const entry = this.#byTabID.get(tabID)
|
|
306
|
+
if (!entry)
|
|
307
|
+
throw new CdpError(`Unknown tabID ${tabID}. Call browser.tabs.list({}) for valid IDs.`, {
|
|
308
|
+
code: "tab_unavailable",
|
|
309
|
+
})
|
|
310
|
+
return entry.targetId
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
attach(tabID: string): Promise<string> {
|
|
314
|
+
const targetId = this.resolve(tabID)
|
|
315
|
+
// Cacheamos el sessionId por tab: `Target.attachToTarget` devuelve uno NUEVO
|
|
316
|
+
// en cada llamada, y los colectores de console/red se indexan por sessionId.
|
|
317
|
+
// Sin cache, cada comando abría una sesión distinta y su buffer salía
|
|
318
|
+
// siempre vacío (medido: 0 mensajes, 0 peticiones).
|
|
319
|
+
const cached = this.#sessions.get(tabID)
|
|
320
|
+
if (cached && this.#live.has(cached)) return Promise.resolve(cached)
|
|
321
|
+
|
|
322
|
+
return this.cdp
|
|
323
|
+
.send("Target.attachToTarget", { targetId, flatten: true })
|
|
324
|
+
.then(({ sessionId }: { sessionId: string }) => {
|
|
325
|
+
this.#sessions.set(tabID, sessionId)
|
|
326
|
+
this.#live.add(sessionId)
|
|
327
|
+
return sessionId
|
|
328
|
+
})
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async createTarget(url?: string): Promise<{ id: string; targetId: string }> {
|
|
332
|
+
const { targetId } = await this.cdp.send("Target.createTarget", { url: url ?? "about:blank" })
|
|
333
|
+
const id = `tab_${randomUUID()}`
|
|
334
|
+
this.#byTabID.set(id, { id, targetId })
|
|
335
|
+
return { id, targetId }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
async closeTarget(tabID: string) {
|
|
339
|
+
const targetId = this.resolve(tabID)
|
|
340
|
+
await this.cdp.send("Target.closeTarget", { targetId })
|
|
341
|
+
this.#byTabID.delete(tabID)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
#findByTarget(targetId: string) {
|
|
345
|
+
for (const [id, entry] of this.#byTabID) if (entry.targetId === targetId) return id
|
|
346
|
+
return undefined
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export interface ConsoleMessage {
|
|
351
|
+
id: string
|
|
352
|
+
timestampMs: number
|
|
353
|
+
level: string
|
|
354
|
+
text: string
|
|
355
|
+
textTruncated: boolean
|
|
356
|
+
source?: { url: string; line: number; column: number }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export interface CapturedRequest {
|
|
360
|
+
id: string
|
|
361
|
+
url: string
|
|
362
|
+
method: string
|
|
363
|
+
resourceType: string
|
|
364
|
+
timestampMs: number
|
|
365
|
+
statusCode?: number
|
|
366
|
+
state: string
|
|
367
|
+
durationMs?: number
|
|
368
|
+
failure?: string
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export interface DownloadRecord {
|
|
372
|
+
id: string
|
|
373
|
+
name: string
|
|
374
|
+
mime: string
|
|
375
|
+
bytes: number
|
|
376
|
+
state: string
|
|
377
|
+
__url?: string
|
|
378
|
+
__guid?: string
|
|
379
|
+
__data?: string
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Colectores de eventos por sesión CDP.
|
|
384
|
+
*
|
|
385
|
+
* CDP no es consulta-por-consulta: console y red son flujos. Hay que suscribirse
|
|
386
|
+
* ANTES de que ocurra y acumular en memoria, igual que hace la app Electron con
|
|
387
|
+
* `Runtime.consoleAPICalled` / `Network.requestWillBeSent`.
|
|
388
|
+
*/
|
|
389
|
+
export class EventCollector {
|
|
390
|
+
#cdp: CdpClient
|
|
391
|
+
#unsub: Array<() => void> = []
|
|
392
|
+
#console = new Map<string, ConsoleMessage[]>()
|
|
393
|
+
#requests = new Map<string, CapturedRequest[]>()
|
|
394
|
+
#bodies = new Map<string, { request: any; response: any; postData?: string }>()
|
|
395
|
+
#dialogs = new Map<string, { type: string; message: string; defaultValue: string }>()
|
|
396
|
+
#downloads = new Map<string, DownloadRecord[]>()
|
|
397
|
+
#attached = new Set<string>()
|
|
398
|
+
|
|
399
|
+
constructor(cdp: CdpClient) {
|
|
400
|
+
this.#cdp = cdp
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** Activa los dominios de CDP para una sesión y empieza a acumular. */
|
|
404
|
+
async attach(sessionId: string | undefined, { network = true, log = true } = {}): Promise<void> {
|
|
405
|
+
const sid = sessionId ?? ""
|
|
406
|
+
|
|
407
|
+
// Idempotente: executeAction llama a attach en CADA comando. Si reiniciáramos
|
|
408
|
+
// los buffers aquí, cada lectura (console/network.list) borraría justo lo que
|
|
409
|
+
// venía a leer — medido: 0 mensajes y 0 peticiones siempre.
|
|
410
|
+
if (this.#attached.has(sid)) return
|
|
411
|
+
this.#attached.add(sid)
|
|
412
|
+
|
|
413
|
+
this.#console.set(sid, [])
|
|
414
|
+
this.#requests.set(sid, [])
|
|
415
|
+
this.#downloads.set(sid, [])
|
|
416
|
+
|
|
417
|
+
if (log) {
|
|
418
|
+
await this.#cdp.send("Log.enable", {}, sessionId).catch(() => undefined)
|
|
419
|
+
this.#unsub.push(
|
|
420
|
+
this.#cdp.on(`${sid}:Log.entryAdded`, (params: any) => {
|
|
421
|
+
const entry = params.entry ?? {}
|
|
422
|
+
this.#push(this.#console, sid, {
|
|
423
|
+
id: String(
|
|
424
|
+
entry.source === "network" && entry.networkRequestId
|
|
425
|
+
? entry.networkRequestId
|
|
426
|
+
: (entry.timestamp ?? this.#console.get(sid)?.length ?? 0),
|
|
427
|
+
),
|
|
428
|
+
timestampMs: Math.round(entry.timestamp ?? 0),
|
|
429
|
+
level: entry.level ?? "info",
|
|
430
|
+
text: entry.text ?? "",
|
|
431
|
+
textTruncated: false,
|
|
432
|
+
source: entry.url
|
|
433
|
+
? { url: entry.url, line: entry.lineNumber ?? 0, column: entry.columnNumber ?? 0 }
|
|
434
|
+
: undefined,
|
|
435
|
+
})
|
|
436
|
+
}),
|
|
437
|
+
)
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
this.#unsub.push(
|
|
441
|
+
this.#cdp.on(`${sid}:Runtime.consoleAPICalled`, (params: any) => {
|
|
442
|
+
const text = (params.args ?? [])
|
|
443
|
+
.map((a: any) => a.value ?? a.description ?? a.unserializableValue ?? "")
|
|
444
|
+
.join(" ")
|
|
445
|
+
this.#push(this.#console, sid, {
|
|
446
|
+
id: `${params.timestamp ?? 0}-${this.#console.get(sid)?.length ?? 0}`,
|
|
447
|
+
timestampMs: Math.round((params.timestamp ?? 0) * 1000),
|
|
448
|
+
level: levelFromType(params.type),
|
|
449
|
+
text: text.slice(0, 100_000),
|
|
450
|
+
textTruncated: text.length > 100_000,
|
|
451
|
+
})
|
|
452
|
+
}),
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
this.#unsub.push(
|
|
456
|
+
this.#cdp.on(`${sid}:Runtime.exceptionThrown`, (params: any) => {
|
|
457
|
+
const d = params.exceptionDetails ?? {}
|
|
458
|
+
this.#push(this.#console, sid, {
|
|
459
|
+
id: `exc-${this.#console.get(sid)?.length ?? 0}`,
|
|
460
|
+
timestampMs: Math.round((params.timestamp ?? 0) * 1000),
|
|
461
|
+
level: "error",
|
|
462
|
+
text: d.exception?.description ?? d.text ?? "Uncaught exception",
|
|
463
|
+
textTruncated: false,
|
|
464
|
+
})
|
|
465
|
+
}),
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
this.#unsub.push(
|
|
469
|
+
this.#cdp.on(`${sid}:Page.javascriptDialogOpening`, (params: any) => {
|
|
470
|
+
this.#dialogs.set(sid, {
|
|
471
|
+
type: params.type ?? "alert",
|
|
472
|
+
message: params.message ?? "",
|
|
473
|
+
defaultValue: params.defaultPrompt ?? "",
|
|
474
|
+
})
|
|
475
|
+
}),
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
this.#unsub.push(
|
|
479
|
+
this.#cdp.on(`${sid}:Page.javascriptDialogClosed`, () => {
|
|
480
|
+
this.#dialogs.delete(sid)
|
|
481
|
+
}),
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
this.#unsub.push(
|
|
485
|
+
this.#cdp.on(`${sid}:Page.downloadWillBegin`, (params: any) => {
|
|
486
|
+
this.#push(this.#downloads, sid, {
|
|
487
|
+
id: `file_${String(params.guid ?? this.#downloads.get(sid)?.length ?? 0).replace(/-/g, "")}`,
|
|
488
|
+
name: params.suggestedFilename ?? "download",
|
|
489
|
+
mime: params.mimeType ?? "application/octet-stream",
|
|
490
|
+
bytes: 0,
|
|
491
|
+
state: "pending",
|
|
492
|
+
__url: params.url,
|
|
493
|
+
__guid: params.guid,
|
|
494
|
+
})
|
|
495
|
+
}),
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
if (!network) return
|
|
499
|
+
await this.#cdp.send("Network.enable", {}, sessionId).catch(() => undefined)
|
|
500
|
+
this.#unsub.push(
|
|
501
|
+
this.#cdp.on(`${sid}:Network.requestWillBeSent`, (params: any) => {
|
|
502
|
+
const req = params.request ?? {}
|
|
503
|
+
const entry: CapturedRequest = {
|
|
504
|
+
id: String(params.requestId),
|
|
505
|
+
url: req.url ?? "",
|
|
506
|
+
method: req.method ?? "GET",
|
|
507
|
+
resourceType: resourceFromType(params.type),
|
|
508
|
+
timestampMs: Math.round((params.timestamp ?? 0) * 1000),
|
|
509
|
+
state: "pending",
|
|
510
|
+
}
|
|
511
|
+
this.#push(this.#requests, sid, entry)
|
|
512
|
+
this.#bodies.set(params.requestId, { request: req, response: undefined, postData: req.postData })
|
|
513
|
+
}),
|
|
514
|
+
)
|
|
515
|
+
this.#unsub.push(
|
|
516
|
+
this.#cdp.on(`${sid}:Network.responseReceived`, (params: any) => {
|
|
517
|
+
const entry = (this.#requests.get(sid) ?? []).find((r) => r.id === String(params.requestId))
|
|
518
|
+
if (!entry) return
|
|
519
|
+
entry.statusCode = params.response?.status ?? 0
|
|
520
|
+
entry.state = "completed"
|
|
521
|
+
entry.durationMs = Math.round(((params.timestamp ?? 0) - entry.timestampMs / 1000) * 1000)
|
|
522
|
+
const slot = this.#bodies.get(params.requestId)
|
|
523
|
+
if (slot) slot.response = params.response
|
|
524
|
+
}),
|
|
525
|
+
)
|
|
526
|
+
this.#unsub.push(
|
|
527
|
+
this.#cdp.on(`${sid}:Network.loadingFailed`, (params: any) => {
|
|
528
|
+
const entry = (this.#requests.get(sid) ?? []).find((r) => r.id === String(params.requestId))
|
|
529
|
+
if (!entry) return
|
|
530
|
+
entry.state = "failed"
|
|
531
|
+
entry.failure = params.errorText ?? "failed"
|
|
532
|
+
}),
|
|
533
|
+
)
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
consoleMessages(sessionId: string | undefined): ConsoleMessage[] {
|
|
537
|
+
return this.#console.get(sessionId ?? "") ?? []
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
requests(sessionId: string | undefined): CapturedRequest[] {
|
|
541
|
+
return this.#requests.get(sessionId ?? "") ?? []
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** bodies se indexa por requestId (único), no por sesión — de ahí el _sessionId. */
|
|
545
|
+
requestBody(_sessionId: string | undefined, requestID: string) {
|
|
546
|
+
return this.#bodies.get(requestID)
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
dialog(sessionId: string | undefined) {
|
|
550
|
+
return this.#dialogs.get(sessionId ?? "") ?? null
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
downloads(sessionId: string | undefined): DownloadRecord[] {
|
|
554
|
+
return this.#downloads.get(sessionId ?? "") ?? []
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
dispose() {
|
|
558
|
+
for (const off of this.#unsub) off()
|
|
559
|
+
this.#unsub = []
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
#push<K, V>(map: Map<K, V[]>, key: K, value: V) {
|
|
563
|
+
const list = map.get(key) ?? []
|
|
564
|
+
list.push(value)
|
|
565
|
+
map.set(key, list)
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const levelFromType = (type: string) =>
|
|
570
|
+
type === "error" || type === "assert" ? "error" : type === "warning" ? "warning" : type === "debug" ? "debug" : "info"
|
|
571
|
+
|
|
572
|
+
const RESOURCE_BY_TYPE: Record<string, string> = {
|
|
573
|
+
Document: "document",
|
|
574
|
+
Stylesheet: "stylesheet",
|
|
575
|
+
Image: "image",
|
|
576
|
+
Media: "media",
|
|
577
|
+
Font: "font",
|
|
578
|
+
Script: "script",
|
|
579
|
+
XHR: "xhr",
|
|
580
|
+
Fetch: "fetch",
|
|
581
|
+
EventSource: "eventsource",
|
|
582
|
+
WebSocket: "websocket",
|
|
583
|
+
Manifest: "manifest",
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const resourceFromType = (type: string) => RESOURCE_BY_TYPE[type] ?? "other"
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Opciones del WebSocket para conexiones remotas.
|
|
590
|
+
*
|
|
591
|
+
* El cliente CDP nativo de Chrome NO habla TLS ni pide cabeceras: expone un
|
|
592
|
+
* websocket en claro y sin auth. Por eso, para un navegador en otra máquina lo
|
|
593
|
+
* normal es interponer un túnel/proxy inverso (ssh -L, tailscale, cloudflared,
|
|
594
|
+
* stunnel, nginx) y apuntar aquí al `wss://` que publica ese proxy. De ahí que
|
|
595
|
+
* soportemos cabeceras y un CA propio.
|
|
596
|
+
*/
|
|
597
|
+
function createSocket(url: string, { headers, tls }: { headers?: Record<string, string>; tls?: TlsOptions } = {}) {
|
|
598
|
+
const options: Record<string, unknown> = {}
|
|
599
|
+
if (headers && Object.keys(headers).length > 0) options.headers = headers
|
|
600
|
+
if (tls?.ca) options.ca = tls.ca
|
|
601
|
+
if (tls?.rejectUnauthorized !== undefined) options.rejectUnauthorized = tls.rejectUnauthorized
|
|
602
|
+
return new NodeWebSocket(url, options)
|
|
603
|
+
}
|