/
index.ts
410 lines (348 loc) · 12 KB
/
index.ts
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/**
* This file is part of the vscode-helpers distribution.
* Copyright (c) Marcel Joachim Kloubert.
*
* vscode-helpers is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* vscode-helpers is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import * as _ from 'lodash';
import * as vscode from 'vscode';
import * as vscode_helpers from '../index';
import * as vscode_helpers_disposable from '../disposable/index';
import * as vscode_helpers_events from '../events/index';
import * as vscode_helpers_http from '../http/index';
import * as WebSocket from 'ws';
/**
* A browser item.
*/
export interface BrowserItem extends NodeJS.EventEmitter, vscode.Disposable {
/**
* The description.
*/
readonly description?: string;
/**
* Closes the connection to the item.
*
* @return {PromiseLike<boolean>} The promise that indicates if operation was successful or not.
*/
readonly close: () => PromiseLike<boolean>;
/**
* Options a connection to the item.
*
* @return {PromiseLike<boolean>} The promise that indicates if operation was successful or not.
*/
readonly connect: () => PromiseLike<boolean>;
/**
* The ID of the item.
*/
readonly id: string;
/**
* Indicates if a connection to the item has been established or not.
*/
readonly isConnected: boolean;
/**
* Invokes a method for the item.
*
* @param {string} method The method to invoke.
* @param {any} [params] Parameters for the method.
* @param {SendToBrowserItemCallback} [callback] The optional callback.
*/
readonly send: (method: string, params?: any, callback?: SendToBrowserItemCallback) => PromiseLike<void>;
/**
* Gets the underyling (web) socket URI.
*/
readonly socketUri: string;
}
/**
* A browser IFrame.
*/
export interface BrowserFrame extends BrowserPage {
/**
* Gets the ID of the parent.
*/
readonly parentId: string;
}
/**
* A browser page.
*/
export interface BrowserPage extends BrowserItem {
/**
* Gets the URI of the FavIcon.
*/
readonly favIcon: string;
/**
* The title of the page.
*/
readonly title: string;
}
/**
* Options for a DevTools client.
*/
export interface DevToolsClientOptions {
/**
* The host address.
*/
readonly host?: string;
/**
* The TCP host.
*/
readonly port?: number;
}
export type SendToBrowserItemCallback = (message: any) => any;
/**
* A DevTools client.
*/
export class DevToolsClient extends vscode_helpers_disposable.DisposableBase {
/**
* Initializes a new instance of that class.
*
* @param {DevToolsClientOptions} [opts] Custom options.
*/
public constructor(opts?: DevToolsClientOptions) {
super();
this.options = opts || <any>{};
}
private async getBrowserItems(): Promise<any[]> {
const RESP = await vscode_helpers_http.GET(`http://${ this.host }:${ this.port }/json`);
if (200 !== RESP.code) {
throw new Error(`Unexpected response ${ RESP.code }: '${ RESP.status }'`);
}
return vscode_helpers.asArray(
JSON.parse(
(await RESP.readBody()).toString('utf8')
)
).filter(i => {
return !vscode_helpers.isEmptyString( i['webSocketDebuggerUrl'] );
});
}
/**
* Returns a list of all IFrames.
*
* @return {Promise<BrowserFrame[]>} The promise with the frames.
*/
public async getFrames() {
const IFRAMES: BrowserFrame[] = [];
const IFRAME_ITEMS = (
await this.getBrowserItems()
).filter(i => {
return 'iframe' === vscode_helpers.normalizeString(i['type']);
});
for (const FI of IFRAME_ITEMS) {
const NEW_FRAME = new BrowserFrameImpl(this);
NEW_FRAME.id = vscode_helpers.toStringSafe( FI['id'] );
NEW_FRAME.parentId = vscode_helpers.toStringSafe( FI['parentId'] );
NEW_FRAME.favIcon = vscode_helpers.toStringSafe( FI['faviconUrl'] );
NEW_FRAME.title = vscode_helpers.toStringSafe( FI['title'] );
NEW_FRAME.description = vscode_helpers.toStringSafe( FI['description'] );
NEW_FRAME.socketUri = vscode_helpers.toStringSafe( FI['webSocketDebuggerUrl'] );
IFRAMES.push( NEW_FRAME );
}
return IFRAMES;
}
/**
* Returns a list of all pages.
*
* @return {Promise<BrowserPage[]>} The promise with the pages.
*/
public async getPages() {
const PAGES: BrowserPage[] = [];
const PAGE_ITEMS = (
await this.getBrowserItems()
).filter(i => {
return 'page' === vscode_helpers.normalizeString(i['type']);
});
for (const PI of PAGE_ITEMS) {
const NEW_PAGE = new BrowserPageImpl(this);
NEW_PAGE.id = vscode_helpers.toStringSafe( PI['id'] );
NEW_PAGE.favIcon = vscode_helpers.toStringSafe( PI['faviconUrl'] );
NEW_PAGE.title = vscode_helpers.toStringSafe( PI['title'] );
NEW_PAGE.description = vscode_helpers.toStringSafe( PI['description'] );
NEW_PAGE.socketUri = vscode_helpers.toStringSafe( PI['webSocketDebuggerUrl'] );
PAGES.push( NEW_PAGE );
}
return PAGES;
}
/**
* Gets the host address.
*/
public get host() {
let hostAddr = vscode_helpers.toStringSafe(this.options.host);
if ('' === hostAddr) {
hostAddr = '127.0.0.1';
}
return hostAddr;
}
/**
* Gets the options for the client.
*/
public readonly options: DevToolsClientOptions;
/**
* Gets the TCP port.
*/
public get port() {
let tcpPort = parseInt(
vscode_helpers.toStringSafe(this.options.port).trim()
);
if (isNaN(tcpPort)) {
tcpPort = 9222;
}
return tcpPort;
}
}
abstract class BrowserItemBase extends vscode_helpers_disposable.DisposableBase implements BrowserItem {
private _nextId = 0;
private _sendCallbacks: { [id: number]: SendToBrowserItemCallback };
private _socket: WebSocket;
public constructor(public readonly client: DevToolsClient) {
super();
}
public close() {
return new Promise<boolean>((resolve, reject) => {
const COMPLETED = vscode_helpers.createCompletedAction(resolve, reject);
const CUR_SOCKET = this._socket;
if (_.isNil(CUR_SOCKET)) {
COMPLETED(null, false);
return;
}
try {
CUR_SOCKET.close();
vscode_helpers_events.tryRemoveAllListeners(CUR_SOCKET);
this._socket = null;
COMPLETED(null);
} catch (e) {
COMPLETED(e);
}
});
}
public connect() {
return new Promise<boolean>((resolve, reject) => {
const COMPLETED = vscode_helpers.createCompletedAction(resolve, reject);
if (this.isInFinalizeState) {
COMPLETED(
new Error('Object is or is going to be disposed')
);
return;
}
if (!_.isNil(this._socket)) {
COMPLETED(null, false);
return;
}
try {
const NEW_SOCKET = new WebSocket( this.socketUri );
NEW_SOCKET.once('error', (err) => {
if (err) {
COMPLETED(err);
}
});
NEW_SOCKET.once('close', () => {
this._socket = null;
this.emit('close',
NEW_SOCKET);
});
NEW_SOCKET.once('open', () => {
this._sendCallbacks = {};
this._socket = NEW_SOCKET;
COMPLETED(null, true);
});
NEW_SOCKET.on('message', (data) => {
const ALL_CALLBACKS = this._sendCallbacks;
if (!_.isNil(ALL_CALLBACKS)) {
try {
let msg: any;
if (!_.isNil(data)) {
msg = JSON.parse(
vscode_helpers.toStringSafe(data)
);
}
if (_.isObject(msg)) {
const MSG_ID = parseInt(
vscode_helpers.toStringSafe(msg.id).trim()
);
if (!isNaN(MSG_ID)) {
const DELETE_CALLBACK = (err?: any) => {
delete ALL_CALLBACKS[MSG_ID];
};
try {
const CALLBACK = ALL_CALLBACKS[MSG_ID];
if (!_.isNil(CALLBACK)) {
Promise.resolve(
CALLBACK(msg)
).then(() => {
DELETE_CALLBACK();
}, (err) => {
DELETE_CALLBACK(err);
});
}
} finally {
DELETE_CALLBACK();
}
}
}
} catch { }
}
this.emit('message',
NEW_SOCKET, data);
});
} catch (e) {
COMPLETED(e);
}
});
}
public description: string;
public id: string;
public get isConnected() {
return !_.isNil(this._socket);
}
public onDispose() {
const CUR_SOCKET = this._socket;
if (!_.isNil(CUR_SOCKET)) {
CUR_SOCKET.close();
vscode_helpers_events.tryRemoveAllListeners(CUR_SOCKET);
this._socket = null;
}
this._sendCallbacks = null;
}
public send(method: string, params?: any, callback?: SendToBrowserItemCallback) {
method = vscode_helpers.toStringSafe(method).trim();
return new Promise<void>((resolve, reject) => {
const COMPLETED = vscode_helpers.createCompletedAction(resolve, reject);
let id = 0;
try {
id = ++this._nextId;
if (!_.isNil(callback)) {
this._sendCallbacks[id] = callback;
}
this._socket.send(
JSON.stringify({
id: id,
method: method,
params: params,
}),
(err) => {
COMPLETED(err);
}
);
} catch (e) {
delete this._sendCallbacks[id];
COMPLETED(e);
}
});
}
public socketUri: string;
}
class BrowserPageImpl extends BrowserItemBase implements BrowserPage {
public favIcon: string;
public title: string;
}
class BrowserFrameImpl extends BrowserPageImpl implements BrowserFrame {
public parentId: string;
}