-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.js
248 lines (236 loc) · 9.82 KB
/
mod.js
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
/// <reference types="./mod.d.ts" />
const UNDEFINED_VALUE = undefined;
const MESSAGE_EVENT = "message";
const OPEN_EVENT = "open";
const CLOSE_EVENT = "close";
const ERROR_EVENT = "error";
const CONNECTION_REFUSED_ERROR_CODE = "ConnectionRefused";
const CONNECTION_ERROR_CODE = "ConnectionError";
const MIN_INVALID_HTTP_STATUS_CODE = 400;
const GET_METHOD = "GET";
const PUT_METHOD = "PUT";
const DEFAULT_URL = "http://localhost:9222";
const DEFAULT_PATH = "json/version";
const DEFAULT_PATH_TARGETS = "json";
const DEFAULT_PATH_NEW_TARGET = "json/new";
const DEFAULT_PATH_ACTIVATE_TARGET = "json/activate";
const DEFAULT_PATH_CLOSE_TARGET = "json/close";
const DEFAULT_CONNECTION_MAX_RETRY = 20;
const DEFAULT_CONNECTION_RETRY_DELAY = 500;
const DEFAULT_OPTIONS = {
apiUrl: DEFAULT_URL,
apiPath: DEFAULT_PATH,
apiPathTargets: DEFAULT_PATH_TARGETS,
apiPathNewTarget: DEFAULT_PATH_NEW_TARGET,
apiPathActivateTarget: DEFAULT_PATH_ACTIVATE_TARGET,
apiPathCloseTarget: DEFAULT_PATH_CLOSE_TARGET,
connectionMaxRetry: DEFAULT_CONNECTION_MAX_RETRY,
connectionRetryDelay: DEFAULT_CONNECTION_RETRY_DELAY
};
class CDP {
#connection;
#options = Object.assign({}, options);
#pendingEventListenerCalls = new Map();
constructor(options) {
// deno-lint-ignore no-this-alias
const cdp = this;
const proxy = new Proxy(Object.create(null), {
get(target, propertyName) {
if (propertyName in cdp) {
return cdp[propertyName];
} else if (propertyName in target) {
return target[propertyName];
} else {
return getDomain(target, propertyName);
}
}
});
Object.assign(cdp.#options, options);
return proxy;
function getDomain(target, domainName) {
target[domainName] = new Proxy(Object.create(null), {
get(target, methodName) {
if (methodName in this) {
return this[methodName];
} else if (methodName in target) {
return target[methodName];
} else {
return getDomainMethodFunction(target, methodName, domainName);
}
},
addEventListener: getDomainListenerFunction("addEventListener", domainName),
removeEventListener: getDomainListenerFunction("removeEventListener", domainName)
});
return target[domainName];
}
function getDomainMethodFunction(target, methodName, domainName) {
target[methodName] = async (params = {}, sessionId) => {
await ready();
const pendingEventListenerCalls = cdp.#pendingEventListenerCalls.get(domainName);
if (pendingEventListenerCalls !== UNDEFINED_VALUE) {
while (pendingEventListenerCalls.length > 0) {
const { methodName, domainName, type, listener } = pendingEventListenerCalls.shift();
cdp.#connection[methodName](`${domainName}.${type}`, listener);
}
cdp.#pendingEventListenerCalls.delete(domainName);
}
return cdp.#connection.sendMessage(`${domainName}.${methodName}`, params, sessionId);
};
return target[methodName];
}
function getDomainListenerFunction(methodName, domainName) {
return (type, listener) => {
if (cdp.#connection === UNDEFINED_VALUE) {
let pendingEventListenerCalls = cdp.#pendingEventListenerCalls.get(domainName);
if (pendingEventListenerCalls === UNDEFINED_VALUE) {
pendingEventListenerCalls = [];
cdp.#pendingEventListenerCalls.set(domainName, pendingEventListenerCalls);
}
pendingEventListenerCalls.push({ methodName, domainName, type, listener });
} else {
cdp.#connection[methodName](`${domainName}.${type}`, listener);
}
};
}
async function ready() {
if (cdp.#connection === UNDEFINED_VALUE) {
let webSocketDebuggerUrl = cdp.#options.webSocketDebuggerUrl;
if (webSocketDebuggerUrl === UNDEFINED_VALUE) {
const url = new URL(cdp.#options.apiPath, cdp.#options.apiUrl);
({ webSocketDebuggerUrl } = await fetchData(url, cdp.#options));
}
const connection = new Connection(webSocketDebuggerUrl);
await connection.open();
cdp.#connection = connection;
}
}
}
get options() {
return this.#options;
}
set options(value) {
Object.assign(this.#options, value);
}
get connection() {
return this.#connection;
}
reset() {
if (this.#connection !== UNDEFINED_VALUE) {
this.#connection.close();
this.#connection = UNDEFINED_VALUE;
this.#pendingEventListenerCalls.clear();
}
}
static getTargets() {
const { apiPathTargets, apiUrl } = options;
return fetchData(new URL(apiPathTargets, apiUrl), options);
}
static createTarget(url) {
const { apiPathNewTarget, apiUrl } = options;
const path = url ? `${apiPathNewTarget}?${url}` : apiPathNewTarget;
return fetchData(new URL(path, apiUrl), options, PUT_METHOD);
}
static async activateTarget(targetId) {
const { apiPathActivateTarget, apiUrl } = options;
await fetchData(new URL(`${apiPathActivateTarget}/${targetId}`, apiUrl), options, GET_METHOD, false);
}
static async closeTarget(targetId) {
const { apiPathCloseTarget, apiUrl } = options;
await fetchData(new URL(`${apiPathCloseTarget}/${targetId}`, apiUrl), options, GET_METHOD, false);
}
}
const options = Object.assign({}, DEFAULT_OPTIONS);
const cdp = new CDP(options);
const getTargets = CDP.getTargets;
const createTarget = CDP.createTarget;
const activateTarget = CDP.activateTarget;
const closeTarget = CDP.closeTarget;
export { cdp, CDP, options, getTargets, createTarget, activateTarget, closeTarget, CONNECTION_REFUSED_ERROR_CODE, CONNECTION_ERROR_CODE };
class Connection extends EventTarget {
#webSocketDebuggerUrl;
#webSocket;
#pendingRequests = new Map();
#nextRequestId = 0;
constructor(webSocketDebuggerUrl) {
super();
this.#webSocketDebuggerUrl = webSocketDebuggerUrl;
}
open() {
this.#webSocket = new WebSocket(this.#webSocketDebuggerUrl);
this.#webSocket.addEventListener(MESSAGE_EVENT, (event) => this.#onMessage(JSON.parse(event.data)));
return new Promise((resolve, reject) => {
this.#webSocket.addEventListener(OPEN_EVENT, () => resolve());
this.#webSocket.addEventListener(CLOSE_EVENT, (event) => reject(new Error(event.reason)));
this.#webSocket.addEventListener(ERROR_EVENT, () => reject(new Error()));
});
}
sendMessage(method, params = {}, sessionId) {
const id = this.#nextRequestId;
const message = JSON.stringify({ id, method, params, sessionId });
this.#nextRequestId = (this.#nextRequestId + 1) % Number.MAX_SAFE_INTEGER;
this.#webSocket.send(message);
let pendingRequest;
const promise = new Promise((resolve, reject) => (pendingRequest = { resolve, reject, method, params, sessionId }));
this.#pendingRequests.set(id, pendingRequest);
return promise;
}
close() {
this.#webSocket.close();
}
#onMessage({ id, method, result, error, params, sessionId }) {
if (id !== UNDEFINED_VALUE) {
const { resolve, reject, method, params, sessionId } = this.#pendingRequests.get(id);
if (error === UNDEFINED_VALUE) {
resolve(result);
} else {
const message = error.message + " when calling " + `${method}(${JSON.stringify(params)})` + `
${sessionId === UNDEFINED_VALUE ? "" : ` (sessionId ${JSON.stringify(sessionId)})`}`;
const errorEvent = new Error(message);
errorEvent.code = error.code;
reject(errorEvent);
}
this.#pendingRequests.delete(id);
}
if (method !== UNDEFINED_VALUE) {
const event = new Event(method);
Object.assign(event, { params, sessionId });
this.dispatchEvent(event);
}
}
}
function fetchData(url, options, method = GET_METHOD, parseJSON = true) {
return retryConnection(async () => {
let response;
try {
response = await fetch(url, { method });
} catch (error) {
error.code = CONNECTION_REFUSED_ERROR_CODE;
throw error;
}
if (response.status >= MIN_INVALID_HTTP_STATUS_CODE) {
const error = new Error(response.statusText || `HTTP Error ${response.status}`);
error.status = response.status;
error.code = CONNECTION_ERROR_CODE;
throw new Error(error);
} else {
if (parseJSON) {
return response.json();
} else {
return response.text();
}
}
}, options);
}
async function retryConnection(fn, options, retryCount = 0) {
const { connectionMaxRetry, connectionRetryDelay } = options;
try {
return await fn();
} catch (error) {
if (error.code == CONNECTION_REFUSED_ERROR_CODE && retryCount < connectionMaxRetry) {
await new Promise((resolve) => setTimeout(resolve, connectionRetryDelay));
return retryConnection(fn, options, retryCount + 1);
} else {
throw error;
}
}
}