-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathcdp-client.ts
More file actions
272 lines (236 loc) · 7.34 KB
/
cdp-client.ts
File metadata and controls
272 lines (236 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import { WebSocket } from 'ws';
/**
* Configuration options for the CDP client.
*/
export interface CDPClientOptions {
/**
* WebSocket URL to connect to (e.g., 'ws://127.0.0.1:9229/ws').
* Can also use the format 'ws://host:port' without path for standard V8 inspector.
*/
url: string;
/**
* Number of connection retry attempts before giving up.
* @default 5
*/
retries?: number;
/**
* Delay in milliseconds between retry attempts.
* @default 1000
*/
retryDelayMs?: number;
/**
* Connection timeout in milliseconds.
* @default 10000
*/
connectionTimeoutMs?: number;
/**
* Default timeout for CDP method calls in milliseconds.
* @default 30000
*/
defaultTimeoutMs?: number;
/**
* Whether to log debug messages.
* @default false
*/
debug?: boolean;
}
/**
* Response type for CDP heap usage queries.
*/
export interface HeapUsage {
usedSize: number;
totalSize: number;
}
interface CDPResponse {
id?: number;
method?: string;
error?: { message: string };
result?: unknown;
}
interface PendingRequest {
resolve: (value: unknown) => void;
reject: (error: Error) => void;
}
/**
* Low-level CDP client for connecting to V8 inspector endpoints.
*
* For memory profiling, prefer using `MemoryProfiler` which provides a higher-level API.
*
* @example
* ```typescript
* const cdp = new CDPClient({ url: 'ws://127.0.0.1:9229/ws' });
* await cdp.connect();
* await cdp.send('Runtime.enable');
* await cdp.close();
* ```
*/
export class CDPClient {
private _ws: WebSocket | null;
private _messageId: number;
private _pendingRequests: Map<number, PendingRequest>;
private _connected: boolean;
private readonly _options: Required<CDPClientOptions>;
public constructor(options: CDPClientOptions) {
this._ws = null;
this._messageId = 0;
this._pendingRequests = new Map();
this._connected = false;
this._options = {
retries: 5,
retryDelayMs: 1000,
connectionTimeoutMs: 10000,
defaultTimeoutMs: 30000,
debug: false,
...options,
};
}
/**
* Connect to the V8 inspector WebSocket endpoint.
* Will retry according to the configured retry settings.
*/
public async connect(): Promise<void> {
const { retries, retryDelayMs } = this._options;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
await this._tryConnect();
return;
} catch (err) {
this._log(`Connection attempt ${attempt}/${retries} failed:`, (err as Error).message);
if (attempt < retries) {
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
} else {
throw err;
}
}
}
}
/**
* Send a CDP method call and wait for the response.
*
* @param method - The CDP method name (e.g., 'HeapProfiler.enable')
* @param params - Optional parameters for the method
* @param timeoutMs - Timeout in milliseconds (defaults to configured defaultTimeoutMs)
* @returns The result from the CDP method
*/
public async send<T = unknown>(method: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<T> {
if (!this._ws || this._ws.readyState !== WebSocket.OPEN) {
throw new Error('WebSocket not connected');
}
const timeout = timeoutMs ?? this._options.defaultTimeoutMs;
const id = ++this._messageId;
const message = JSON.stringify({ id, method, params });
this._log('Sending:', method, params || '');
return new Promise((resolve, reject) => {
this._pendingRequests.set(id, {
resolve: value => resolve(value as T),
reject,
});
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this._ws!.send(message);
setTimeout(() => {
if (this._pendingRequests.has(id)) {
this._pendingRequests.delete(id);
reject(new Error(`CDP request ${method} timed out after ${timeout}ms`));
}
}, timeout);
});
}
/**
* Send a CDP method call without waiting for a response.
* Useful for commands that may not return responses in certain V8 environments.
*
* @param method - The CDP method name
* @param params - Optional parameters for the method
* @param settleDelayMs - Time to wait after sending (default: 100ms)
*/
public async sendFireAndForget(method: string, params?: Record<string, unknown>, settleDelayMs = 100): Promise<void> {
if (!this._ws || this._ws.readyState !== WebSocket.OPEN) {
throw new Error('WebSocket not connected');
}
const id = ++this._messageId;
const message = JSON.stringify({ id, method, params });
this._log('Sending (fire-and-forget):', method, params || '');
this._ws.send(message);
// Give the command time to execute
await new Promise(resolve => setTimeout(resolve, settleDelayMs));
}
/**
* Check if the client is currently connected.
*/
public isConnected(): boolean {
return this._connected && this._ws?.readyState === WebSocket.OPEN;
}
/**
* Close the WebSocket connection.
*/
public async close(): Promise<void> {
if (this._ws) {
this._ws.close();
this._ws = null;
this._connected = false;
}
}
private _log(...args: unknown[]): void {
if (this._options.debug) {
// eslint-disable-next-line no-console
console.log('[CDPClient]', ...args);
}
}
private async _tryConnect(): Promise<void> {
const { url, connectionTimeoutMs } = this._options;
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error(`Connection to ${url} timed out after ${connectionTimeoutMs}ms`));
}, connectionTimeoutMs);
this._ws = new WebSocket(url);
this._ws.on('open', () => {
clearTimeout(timeoutId);
this._connected = true;
this._log('WebSocket connected to', url);
resolve();
});
this._ws.on('error', (err: Error) => {
clearTimeout(timeoutId);
reject(new Error(`Failed to connect to inspector at ${url}: ${err.message}`));
});
this._ws.on('close', () => {
this._connected = false;
});
this._ws.on('message', (data: Buffer) => {
try {
const rawMessage = data.toString();
this._log('Received raw message:', rawMessage.slice(0, 500));
const message = JSON.parse(rawMessage) as CDPResponse;
// CDP event (not a response to our request)
if (message.method) {
this._log('CDP event:', message.method);
return;
}
if (message.id !== undefined) {
this._log(
'CDP response for id:',
message.id,
'error:',
message.error,
'has result:',
message.result !== undefined,
);
const pending = this._pendingRequests.get(message.id);
if (pending) {
this._pendingRequests.delete(message.id);
if (message.error) {
pending.reject(new Error(`CDP error: ${message.error.message}`));
} else {
pending.resolve(message.result);
}
} else {
this._log('No pending request found for id:', message.id);
}
}
} catch (e) {
this._log('Failed to parse CDP message:', e);
}
});
});
}
}