Repository navigation
Expand file tree
/
Copy pathcdp.ts
More file actions
118 lines (108 loc) · 3.85 KB
/
Copy pathcdp.ts
File metadata and controls
118 lines (108 loc) · 3.85 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
import { AppError } from '@agent-device/kernel/errors';
import { WebSocket } from 'undici';
import { createReplyWaiters } from './replies.ts';
const REQUEST_TIMEOUT_MS = 20_000;
const CDP_HINT =
'Close Chrome DevTools and other inspector clients attached to the app, then open it again.';
export type CdpTarget = Readonly<{
title: string;
url: string;
webSocketDebuggerUrl: string;
}>;
export type CdpSession = Readonly<{
send<T = Record<string, unknown>>(method: string, params?: Record<string, unknown>): Promise<T>;
evaluate<T>(expression: string): Promise<T>;
on(listener: (method: string, params: Record<string, unknown>) => void): void;
close(): void;
}>;
type CdpMessage = {
id?: number;
method?: string;
params?: Record<string, unknown>;
result?: unknown;
error?: { message: string; code: number };
};
export async function listTargets(port: number): Promise<CdpTarget[]> {
const response = await fetch(`http://localhost:${port}/json`, {
signal: AbortSignal.timeout(5000),
});
if (!response.ok) {
throw new AppError(
'COMMAND_FAILED',
`webOS inspector at localhost:${port} answered ${response.status}`,
);
}
return ((await response.json()) as CdpTarget[]).filter((target) => target.webSocketDebuggerUrl);
}
export async function connectCdp(target: CdpTarget): Promise<CdpSession> {
const socket = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
const fail = (message: string) => {
clearTimeout(timer);
reject(new AppError('COMMAND_FAILED', message, { hint: CDP_HINT }));
};
const timer = setTimeout(() => {
socket.close();
fail(`The webOS page at ${target.url} did not open within ${REQUEST_TIMEOUT_MS}ms`);
}, REQUEST_TIMEOUT_MS);
socket.onopen = (event) => {
clearTimeout(timer);
resolve(event);
};
socket.onerror = () => fail(`Could not open the webOS page at ${target.url}`);
});
let nextId = 0;
const replies = createReplyWaiters<CdpMessage>();
const listeners: ((method: string, params: Record<string, unknown>) => void)[] = [];
socket.onmessage = (event) => {
const message = JSON.parse(String(event.data)) as CdpMessage;
if (message.method) {
for (const listener of listeners) listener(message.method, message.params ?? {});
} else if (message.id !== undefined) {
replies.deliver(String(message.id), message);
}
};
socket.onclose = () =>
replies.failAll(
new AppError('COMMAND_FAILED', 'The webOS page connection closed', { hint: CDP_HINT }),
);
const send = <T>(method: string, params: Record<string, unknown> = {}) => {
const id = ++nextId;
const reply = replies.wait<T>(
String(id),
REQUEST_TIMEOUT_MS,
() =>
new AppError('COMMAND_FAILED', `${method} got no answer within ${REQUEST_TIMEOUT_MS}ms`, {
hint: CDP_HINT,
}),
(message) =>
message.error
? {
error: new AppError('COMMAND_FAILED', `${method} failed: ${message.error.message}`, {
cdpErrorCode: message.error.code,
}),
}
: { value: message.result as T },
);
socket.send(JSON.stringify({ id, method, params }));
return reply;
};
return {
send,
async evaluate<T>(expression: string) {
const { result, exceptionDetails } = await send<{
result: { value?: T };
exceptionDetails?: { exception?: { description?: string }; text: string };
}>('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
if (exceptionDetails) {
throw new AppError(
'COMMAND_FAILED',
`Page script failed: ${exceptionDetails.exception?.description ?? exceptionDetails.text}`,
);
}
return result.value as T;
},
on: (listener) => listeners.push(listener),
close: () => socket.close(),
};
}