/
Device.js
557 lines (495 loc) Β· 17.5 KB
/
Device.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
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
* @oncall react_native
*/
import type {
DebuggerRequest,
GetScriptSourceRequest,
GetScriptSourceResponse,
MessageFromDevice,
MessageToDevice,
Page,
SetBreakpointByUrlRequest,
} from './types';
import * as fs from 'fs';
import * as http from 'http';
import * as path from 'path';
import WS from 'ws';
const debug = require('debug')('Metro:InspectorProxy');
const PAGES_POLLING_INTERVAL = 1000;
// Android's stock emulator and other emulators such as genymotion use a standard localhost alias.
const EMULATOR_LOCALHOST_ADDRESSES: Array<string> = ['10.0.2.2', '10.0.3.2'];
// Prefix for script URLs that are alphanumeric IDs. See comment in _processMessageFromDevice method for
// more details.
const FILE_PREFIX = 'file://';
type DebuggerInfo = {
// Debugger web socket connection
socket: typeof WS,
// If we replaced address (like '10.0.2.2') to localhost we need to store original
// address because Chrome uses URL or urlRegex params (instead of scriptId) to set breakpoints.
originalSourceURLAddress?: string,
prependedFilePrefix: boolean,
pageId: string,
...
};
const REACT_NATIVE_RELOADABLE_PAGE_ID = '-1';
/**
* Device class represents single device connection to Inspector Proxy. Each device
* can have multiple inspectable pages.
*/
class Device {
// ID of the device.
_id: number;
// Name of the device.
_name: string;
// Package name of the app.
_app: string;
// Stores socket connection between Inspector Proxy and device.
_deviceSocket: typeof WS;
// Stores last list of device's pages.
_pages: Array<Page>;
// Stores information about currently connected debugger (if any).
_debuggerConnection: ?DebuggerInfo = null;
// Last known Page ID of the React Native page.
// This is used by debugger connections that don't have PageID specified
// (and will interact with the latest React Native page).
_lastConnectedReactNativePage: ?Page = null;
// Whether we are in the middle of a reload in the REACT_NATIVE_RELOADABLE_PAGE.
_isReloading: boolean = false;
// The previous "GetPages" message, for deduplication in debug logs.
_lastGetPagesMessage: string = '';
// Mapping built from scriptParsed events and used to fetch file content in `Debugger.getScriptSource`.
_scriptIdToSourcePathMapping: Map<string, string> = new Map();
// Root of the project used for relative to absolute source path conversion.
_projectRoot: string;
constructor(
id: number,
name: string,
app: string,
socket: typeof WS,
projectRoot: string,
) {
this._id = id;
this._name = name;
this._app = app;
this._pages = [];
this._deviceSocket = socket;
this._projectRoot = projectRoot;
this._deviceSocket.on('message', (message: string) => {
const parsedMessage = JSON.parse(message);
if (parsedMessage.event === 'getPages') {
// There's a 'getPages' message every second, so only show them if they change
if (message !== this._lastGetPagesMessage) {
debug(
'(Debugger) (Proxy) <- (Device), getPages ping has changed: ' +
message,
);
this._lastGetPagesMessage = message;
}
} else {
debug('(Debugger) (Proxy) <- (Device): ' + message);
}
this._handleMessageFromDevice(parsedMessage);
});
this._deviceSocket.on('close', () => {
// Device disconnected - close debugger connection.
if (this._debuggerConnection) {
this._debuggerConnection.socket.close();
this._debuggerConnection = null;
}
});
this._setPagesPolling();
}
getName(): string {
return this._name;
}
getPagesList(): Array<Page> {
if (this._lastConnectedReactNativePage) {
const reactNativeReloadablePage = {
id: REACT_NATIVE_RELOADABLE_PAGE_ID,
title: 'React Native Experimental (Improved Chrome Reloads)',
vm: "don't use",
app: this._app,
};
return this._pages.concat(reactNativeReloadablePage);
} else {
return this._pages;
}
}
// Handles new debugger connection to this device:
// 1. Sends connect event to device
// 2. Forwards all messages from the debugger to device as wrappedEvent
// 3. Sends disconnect event to device when debugger connection socket closes.
handleDebuggerConnection(socket: typeof WS, pageId: string) {
// Disconnect current debugger if we already have debugger connected.
if (this._debuggerConnection) {
this._debuggerConnection.socket.close();
this._debuggerConnection = null;
}
const debuggerInfo = {
socket,
prependedFilePrefix: false,
pageId,
};
this._debuggerConnection = debuggerInfo;
debug(`Got new debugger connection for page ${pageId} of ${this._name}`);
this._sendMessageToDevice({
event: 'connect',
payload: {
pageId: this._mapToDevicePageId(pageId),
},
});
socket.on('message', (message: string) => {
debug('(Debugger) -> (Proxy) (Device): ' + message);
const debuggerRequest = JSON.parse(message);
const handled = this._interceptMessageFromDebugger(
debuggerRequest,
debuggerInfo,
socket,
);
if (!handled) {
this._sendMessageToDevice({
event: 'wrappedEvent',
payload: {
pageId: this._mapToDevicePageId(pageId),
wrappedEvent: JSON.stringify(debuggerRequest),
},
});
}
});
socket.on('close', () => {
debug(`Debugger for page ${pageId} and ${this._name} disconnected.`);
this._sendMessageToDevice({
event: 'disconnect',
payload: {
pageId: this._mapToDevicePageId(pageId),
},
});
this._debuggerConnection = null;
});
const sendFunc = socket.send;
socket.send = function (message: string) {
debug('(Debugger) <- (Proxy) (Device): ' + message);
return sendFunc.call(socket, message);
};
}
// Handles messages received from device:
// 1. For getPages responses updates local _pages list.
// 2. All other messages are forwarded to debugger as wrappedEvent.
//
// In the future more logic will be added to this method for modifying
// some of the messages (like updating messages with source maps and file
// locations).
_handleMessageFromDevice(message: MessageFromDevice) {
if (message.event === 'getPages') {
this._pages = message.payload;
// Check if device have new React Native page.
// There is usually no more than 2-3 pages per device so this operation
// is not expensive.
// TODO(hypuk): It is better for VM to send update event when new page is
// created instead of manually checking this on every getPages result.
for (let i = 0; i < this._pages.length; ++i) {
if (this._pages[i].title.indexOf('React') >= 0) {
if (this._pages[i].id != this._lastConnectedReactNativePage?.id) {
this._newReactNativePage(this._pages[i]);
break;
}
}
}
} else if (message.event === 'disconnect') {
// Device sends disconnect events only when page is reloaded or
// if debugger socket was disconnected.
const pageId = message.payload.pageId;
const debuggerSocket = this._debuggerConnection
? this._debuggerConnection.socket
: null;
if (debuggerSocket && debuggerSocket.readyState === WS.OPEN) {
if (
this._debuggerConnection != null &&
this._debuggerConnection.pageId !== REACT_NATIVE_RELOADABLE_PAGE_ID
) {
debug(`Page ${pageId} is reloading.`);
debuggerSocket.send(JSON.stringify({method: 'reload'}));
}
}
} else if (message.event === 'wrappedEvent') {
if (this._debuggerConnection == null) {
return;
}
// FIXME: Is it possible that we received message for pageID that does not
// correspond to current debugger connection?
const debuggerSocket = this._debuggerConnection.socket;
if (debuggerSocket == null || debuggerSocket.readyState !== WS.OPEN) {
// TODO(hypuk): Send error back to device?
return;
}
const parsedPayload = JSON.parse(message.payload.wrappedEvent);
if (this._debuggerConnection) {
// Wrapping just to make flow happy :)
this._processMessageFromDevice(parsedPayload, this._debuggerConnection);
}
const messageToSend = JSON.stringify(parsedPayload);
debuggerSocket.send(messageToSend);
}
}
// Sends single message to device.
_sendMessageToDevice(message: MessageToDevice) {
try {
if (message.event !== 'getPages') {
debug('(Debugger) (Proxy) -> (Device): ' + JSON.stringify(message));
}
this._deviceSocket.send(JSON.stringify(message));
} catch (error) {}
}
// Sends 'getPages' request to device every PAGES_POLLING_INTERVAL milliseconds.
_setPagesPolling() {
setInterval(
() => this._sendMessageToDevice({event: 'getPages'}),
PAGES_POLLING_INTERVAL,
);
}
// We received new React Native Page ID.
_newReactNativePage(page: Page) {
debug(`React Native page updated to ${page.id}`);
if (
this._debuggerConnection == null ||
this._debuggerConnection.pageId !== REACT_NATIVE_RELOADABLE_PAGE_ID
) {
// We can just remember new page ID without any further actions if no
// debugger is currently attached or attached debugger is not
// "Reloadable React Native" connection.
this._lastConnectedReactNativePage = page;
return;
}
const oldPageId = this._lastConnectedReactNativePage?.id;
this._lastConnectedReactNativePage = page;
this._isReloading = true;
// We already had a debugger connected to React Native page and a
// new one appeared - in this case we need to emulate execution context
// detroy and resend Debugger.enable and Runtime.enable commands to new
// page.
if (oldPageId != null) {
this._sendMessageToDevice({
event: 'disconnect',
payload: {
pageId: oldPageId,
},
});
}
this._sendMessageToDevice({
event: 'connect',
payload: {
pageId: page.id,
},
});
const toSend = [
{method: 'Runtime.enable', id: 1e9},
{method: 'Debugger.enable', id: 1e9},
];
for (const message of toSend) {
this._sendMessageToDevice({
event: 'wrappedEvent',
payload: {
pageId: this._mapToDevicePageId(page.id),
wrappedEvent: JSON.stringify(message),
},
});
}
}
// Allows to make changes in incoming message from device.
_processMessageFromDevice(
payload: {method: string, params: {sourceMapURL: string, url: string}},
debuggerInfo: DebuggerInfo,
) {
// Replace Android addresses for scriptParsed event.
if (payload.method === 'Debugger.scriptParsed') {
const params = payload.params || {};
if ('sourceMapURL' in params) {
for (let i = 0; i < EMULATOR_LOCALHOST_ADDRESSES.length; ++i) {
const address = EMULATOR_LOCALHOST_ADDRESSES[i];
if (params.sourceMapURL.indexOf(address) >= 0) {
payload.params.sourceMapURL = params.sourceMapURL.replace(
address,
'localhost',
);
debuggerInfo.originalSourceURLAddress = address;
}
}
}
if ('url' in params) {
for (let i = 0; i < EMULATOR_LOCALHOST_ADDRESSES.length; ++i) {
const address = EMULATOR_LOCALHOST_ADDRESSES[i];
if (params.url.indexOf(address) >= 0) {
payload.params.url = params.url.replace(address, 'localhost');
debuggerInfo.originalSourceURLAddress = address;
}
}
// Chrome doesn't download source maps if URL param is not a valid
// URL. Some frameworks pass alphanumeric script ID instead of URL which causes
// Chrome to not download source maps. In this case we want to prepend script ID
// with 'file://' prefix.
if (payload.params.url.match(/^[0-9a-z]+$/)) {
payload.params.url = FILE_PREFIX + payload.params.url;
debuggerInfo.prependedFilePrefix = true;
}
// $FlowFixMe[prop-missing]
if (params.scriptId != null) {
this._scriptIdToSourcePathMapping.set(params.scriptId, params.url);
}
}
if (debuggerInfo.pageId == REACT_NATIVE_RELOADABLE_PAGE_ID) {
// Chrome won't use the source map unless it appears to be new.
if (payload.params.sourceMapURL) {
payload.params.sourceMapURL +=
'&cachePrevention=' + this._mapToDevicePageId(debuggerInfo.pageId);
}
if (payload.params.url) {
payload.params.url +=
'&cachePrevention=' + this._mapToDevicePageId(debuggerInfo.pageId);
}
}
}
if (
payload.method === 'Runtime.executionContextCreated' &&
this._isReloading
) {
// The new context is ready. First notify Chrome that we've reloaded so
// it'll resend its breakpoints. If we do this earlier, we may not be
// ready to receive them.
debuggerInfo.socket.send(
JSON.stringify({method: 'Runtime.executionContextsCleared'}),
);
// The VM starts in a paused mode. Ask it to resume.
// Note that if setting breakpoints in early initialization functions,
// there's a currently race condition between these functions executing
// and Chrome re-applying the breakpoints due to the message above.
//
// This is not an issue in VSCode/Nuclide where the IDE knows to resume
// at its convenience.
this._sendMessageToDevice({
event: 'wrappedEvent',
payload: {
pageId: this._mapToDevicePageId(debuggerInfo.pageId),
wrappedEvent: JSON.stringify({method: 'Debugger.resume', id: 0}),
},
});
this._isReloading = false;
}
}
// Allows to make changes in incoming messages from debugger. Returns a boolean
// indicating whether the message has been handled locally (i.e. does not need
// to be forwarded to the target).
_interceptMessageFromDebugger(
req: DebuggerRequest,
debuggerInfo: DebuggerInfo,
socket: typeof WS,
): boolean {
if (req.method === 'Debugger.setBreakpointByUrl') {
this._processDebuggerSetBreakpointByUrl(req, debuggerInfo);
} else if (req.method === 'Debugger.getScriptSource') {
this._processDebuggerGetScriptSource(req, socket);
return true;
}
return false;
}
_processDebuggerSetBreakpointByUrl(
req: SetBreakpointByUrlRequest,
debuggerInfo: DebuggerInfo,
) {
// If we replaced Android emulator's address to localhost we need to change it back.
if (debuggerInfo.originalSourceURLAddress) {
if (req.params.url) {
req.params.url = req.params.url.replace(
'localhost',
debuggerInfo.originalSourceURLAddress,
);
if (
req.params.url &&
req.params.url.startsWith(FILE_PREFIX) &&
debuggerInfo.prependedFilePrefix
) {
// Remove fake URL prefix if we modified URL in _processMessageFromDevice.
// $FlowFixMe[incompatible-use]
req.params.url = req.params.url.slice(FILE_PREFIX.length);
}
}
if (req.params.urlRegex) {
req.params.urlRegex = req.params.urlRegex.replace(
/localhost/g,
// $FlowFixMe[incompatible-call]
debuggerInfo.originalSourceURLAddress,
);
}
}
}
_processDebuggerGetScriptSource(
req: GetScriptSourceRequest,
socket: typeof WS,
) {
let scriptSource = `Source for script with id '${req.params.scriptId}' was not found.`;
const sendResponse = () => {
const result: GetScriptSourceResponse = {scriptSource};
socket.send(JSON.stringify({id: req.id, result}));
};
const pathToSource = this._scriptIdToSourcePathMapping.get(
req.params.scriptId,
);
if (pathToSource) {
let pathIsURL = false;
try {
pathIsURL = new URL(pathToSource).hostname == 'localhost';
} catch {}
if (pathIsURL) {
http
.get(pathToSource, httpResponse => {
const {statusCode} = httpResponse;
if (statusCode == 200) {
httpResponse.setEncoding('utf8');
scriptSource = '';
httpResponse.on('data', body => {
scriptSource += body;
});
httpResponse.on('end', () => {
sendResponse();
});
} else {
scriptSource = `Fetching ${pathToSource} returned status ${statusCode}`;
sendResponse();
httpResponse.resume();
}
})
.on('error', e => {
scriptSource = `Fetching ${pathToSource} failed with error ${e.message}`;
sendResponse();
});
} else {
try {
scriptSource = fs.readFileSync(
path.resolve(this._projectRoot, pathToSource),
'utf8',
);
} catch (err) {
scriptSource = err.message;
}
sendResponse();
}
}
}
_mapToDevicePageId(pageId: string): string {
if (
pageId === REACT_NATIVE_RELOADABLE_PAGE_ID &&
this._lastConnectedReactNativePage != null
) {
return this._lastConnectedReactNativePage.id;
} else {
return pageId;
}
}
}
module.exports = Device;