forked from dosyago/dn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprotocol.js
285 lines (249 loc) · 8.14 KB
/
protocol.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import {context} from './common.js';
const ROOT_SESSION = "browser";
// actually we use 'tot' but in chrome.debugger.attach 'tot' is
// not a supported version string
const VERSION = "1.3";
function promisify(context, name, err) {
return async function(...args) {
let resolver, rejector;
const pr = new Promise((res,rej) => ([resolver, rejector] = [res,rej]));
args.push(promisifiedCallback);
context[name](...args);
return pr;
function promisifiedCallback(...result) {
let error = err(name);
if ( !! error ) {
return rejector(error);
}
return resolver(...result);
}
}
}
let Ws, Fetch;
async function loadDependencies() {
if ( context == 'extension' ) {
// no need to do anything here
} else if ( context == 'node' ) {
const {default:ws} = await import('ws');
const {default:nodeFetch} = await import('node-fetch');
Ws = ws;
Fetch = nodeFetch;
}
}
export async function connect({port:port = 9222} = {}) {
if ( context == 'extension' ) {
const Handlers = {};
const getTargets = promisify(chrome.debugger, 'getTargets', guardError);
const attach = promisify(chrome.debugger, 'attach', guardError);
const sendCommand = promisify(chrome.debugger, 'sendCommand', guardError);
let resp, firstTarget, targets;
chrome.debugger.onEvent.addListener(handle);
// attach to all existing targets
targets = await getTargets();
targets = targets.filter(T => T.type == 'page' && T.url.startsWith('http'));
for ( const T of targets ) {
if ( ! T.attached ) {
resp = await attach({targetId:T.id}, VERSION);
console.log("attached", {resp});
}
}
if ( targets.length ) {
firstTarget = targets[0].id;
}
await confirmAllAttached();
// discover targets is blocked in extensions
// instead we manually discover via tabs onCreated
let nextAttachConfirmation;
chrome.tabs.onCreated.addListener(async Tab => {
console.log(Tab);
const url = Tab.url || Tab.pendingUrl;
const attachable = url.startsWith('about') || url.startsWith('http');
if ( attachable ) {
const target = {tabId:Tab.id};
const r = await attach(target, VERSION);
if ( ! firstTarget ) {
firstTarget = Tab.id;
}
console.log("attach", {resp:r});
}
if ( nextAttachConfirmation ) {
clearTimeout(nextAttachConfirmation);
}
nextAttachConfirmation = setTimeout(confirmAllAttached, 200);
});
chrome.tabs.onUpdated.addListener(async (id, changed, Tab) => {
const {url} = changed;
const attachable = url && (url.startsWith('about') || url.startsWith('http'));
if ( attachable && ! Tab.attached ) {
const target = {tabId:id};
const r = await attach(target, VERSION);
if ( ! firstTarget ) {
firstTarget = id;
}
console.log("attach", {resp:r});
}
if ( nextAttachConfirmation ) {
clearTimeout(nextAttachConfirmation);
}
nextAttachConfirmation = setTimeout(confirmAllAttached, 200);
});
return {send, on};
async function on(method, handler) {
let listeners = Handlers[method];
if ( ! listeners ) {
Handlers[method] = listeners = [];
}
listeners.push(handler);
}
async function send(method, params = {}, id = firstTarget) {
let tabId, targetId;
if ( Number.isInteger(id) ) {
tabId = id;
} else if ( typeof id == "string" ) {
targetId = id;
} else {
throw new Error(`Must specify an id to send command to. ${method}`);
}
try {
return await sendCommand(
{targetId, tabId},
method,
params,
);
} catch(e) {
console.warn(`${method}`, e);
return {error:e};
}
}
async function handle(source, method, params) {
const listeners = Handlers[method];
if ( Array.isArray(listeners) ) {
for( const func of listeners ) {
try {
func(method, params, source);
} catch(e) {
console.warn(`Listener failed`, method, JSON.stringify(params), e, func.toString().slice(0,140));
}
}
}
}
function guardError(prefix = '') {
if ( chrome.runtime.lastError ) {
if ( typeof prefix == 'object' ) {
try {
prefix = JSON.stringify(prefix, null, 2);
} catch(e) {
console.warn(e);
prefix = prefix + '';
}
}
const error = `${prefix}: ${chrome.runtime.lastError.message}`;
return error;
}
return false;
}
async function confirmAllAttached() {
resp = await getTargets();
targets = resp.filter(T => T.type == 'page' && T.url.startsWith('http') && !T.attached);
console.assert(targets.length == 0, "We are not attached to some attachable targets", targets);
}
} else if ( context == 'node' ) {
if ( ! Ws || ! Fetch ) {
await loadDependencies();
}
try {
const {webSocketDebuggerUrl} = await Fetch(`http://localhost:${port}/json/version`).then(r => r.json());
const socket = new Ws(webSocketDebuggerUrl);
const Resolvers = {};
const Handlers = {};
socket.on('message', handle);
let id = 0;
let resolve;
const promise = new Promise(res => resolve = res);
socket.on('open', () => resolve());
await promise;
return {
send,
on, ons,
close
}
async function send(method, params = {}, sessionId) {
const message = {
method, params, sessionId,
id: ++id
};
if ( ! sessionId ) {
delete message[sessionId];
}
const key = `${sessionId||ROOT_SESSION}:${message.id}`;
let resolve;
const promise = new Promise(res => resolve = res);
Resolvers[key] = resolve;
socket.send(JSON.stringify(message));
return promise;
}
async function handle(message) {
const stringMessage = message;
message = JSON.parse(message);
if ( message.error ) {
//console.warn(message);
}
const {sessionId} = message;
const {method, params} = message;
const {id, result} = message;
if ( id ) {
const key = `${sessionId||ROOT_SESSION}:${id}`;
const resolve = Resolvers[key];
if ( ! resolve ) {
console.warn(`No resolver for key`, key, stringMessage.slice(0,140));
} else {
Resolvers[key] = undefined;
try {
await resolve(result);
} catch(e) {
console.warn(`Resolver failed`, e, key, stringMessage.slice(0,140), resolve);
}
}
} else if ( method ) {
const listeners = Handlers[method];
if ( Array.isArray(listeners) ) {
for( const func of listeners ) {
try {
func({message, sessionId});
} catch(e) {
console.warn(`Listener failed`, method, e, func.toString().slice(0,140), stringMessage.slice(0,140));
}
}
}
} else {
console.warn(`Unknown message on socket`, message);
}
}
function on(method, handler) {
let listeners = Handlers[method];
if ( ! listeners ) {
Handlers[method] = listeners = [];
}
listeners.push(wrap(handler));
}
function ons(method, handler) {
let listeners = Handlers[method];
if ( ! listeners ) {
Handlers[method] = listeners = [];
}
listeners.push(handler);
}
function close() {
socket.close();
}
function wrap(fn) {
return ({message, sessionId}) => fn(message.params)
}
} catch(e) {
console.log("Error communicating with browser", e);
process.exit(1);
}
} else {
throw new TypeError('Currently only supports running in Node.JS or as a Chrome Extension with Debugger permissions');
}
}