-
Notifications
You must be signed in to change notification settings - Fork 24.5k
/
Copy pathInspectorProxy.js
269 lines (237 loc) · 8.41 KB
/
InspectorProxy.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
/**
* 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 strict-local
* @format
* @oncall react_native
*/
import type {
JsonPagesListResponse,
JsonVersionResponse,
Page,
PageDescription,
} from './types';
import type {EventReporter} from '../types/EventReporter';
import type {Experiments} from '../types/Experiments';
import type {IncomingMessage, ServerResponse} from 'http';
import url from 'url';
import WS from 'ws';
import Device from './Device';
const debug = require('debug')('Metro:InspectorProxy');
const WS_DEVICE_URL = '/inspector/device';
const WS_DEBUGGER_URL = '/inspector/debug';
const PAGES_LIST_JSON_URL = '/json';
const PAGES_LIST_JSON_URL_2 = '/json/list';
const PAGES_LIST_JSON_VERSION_URL = '/json/version';
const INTERNAL_ERROR_CODE = 1011;
export interface InspectorProxyQueries {
getPageDescriptions(): Array<PageDescription>;
}
/**
* Main Inspector Proxy class that connects JavaScript VM inside Android/iOS apps and JS debugger.
*/
export default class InspectorProxy implements InspectorProxyQueries {
// Root of the project used for relative to absolute source path conversion.
_projectRoot: string;
/** The base URL to the dev server from the developer machine. */
_serverBaseUrl: string;
// Maps device ID to Device instance.
_devices: Map<string, Device>;
// Internal counter for device IDs -- just gets incremented for each new device.
_deviceCounter: number = 0;
_eventReporter: ?EventReporter;
_experiments: Experiments;
constructor(
projectRoot: string,
serverBaseUrl: string,
eventReporter: ?EventReporter,
experiments: Experiments,
) {
this._projectRoot = projectRoot;
this._serverBaseUrl = serverBaseUrl;
this._devices = new Map();
this._eventReporter = eventReporter;
this._experiments = experiments;
}
getPageDescriptions(): Array<PageDescription> {
// Build list of pages from all devices.
let result: Array<PageDescription> = [];
Array.from(this._devices.entries()).forEach(([deviceId, device]) => {
result = result.concat(
device
.getPagesList()
.map((page: Page) =>
this._buildPageDescription(deviceId, device, page),
),
);
});
return result;
}
// Process HTTP request sent to server. We only respond to 2 HTTP requests:
// 1. /json/version returns Chrome debugger protocol version that we use
// 2. /json and /json/list returns list of page descriptions (list of inspectable apps).
// This list is combined from all the connected devices.
processRequest(
request: IncomingMessage,
response: ServerResponse,
next: (?Error) => mixed,
) {
if (
request.url === PAGES_LIST_JSON_URL ||
request.url === PAGES_LIST_JSON_URL_2
) {
this._sendJsonResponse(response, this.getPageDescriptions());
} else if (request.url === PAGES_LIST_JSON_VERSION_URL) {
this._sendJsonResponse(response, {
Browser: 'Mobile JavaScript',
'Protocol-Version': '1.1',
});
} else {
next();
}
}
createWebSocketListeners(): {
[path: string]: WS.Server,
} {
return {
[WS_DEVICE_URL]: this._createDeviceConnectionWSServer(),
[WS_DEBUGGER_URL]: this._createDebuggerConnectionWSServer(),
};
}
// Converts page information received from device into PageDescription object
// that is sent to debugger.
_buildPageDescription(
deviceId: string,
device: Device,
page: Page,
): PageDescription {
const {host, protocol} = new URL(this._serverBaseUrl);
const webSocketScheme = protocol === 'https:' ? 'wss' : 'ws';
const webSocketUrlWithoutProtocol = `${host}${WS_DEBUGGER_URL}?device=${deviceId}&page=${page.id}`;
const webSocketDebuggerUrl = `${webSocketScheme}://${webSocketUrlWithoutProtocol}`;
// For now, `/json/list` returns the legacy built-in `devtools://` URL, to
// preserve existing handling by Flipper. This may return a placeholder in
// future -- please use the `/open-debugger` endpoint.
const devtoolsFrontendUrl =
`devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&${webSocketScheme}=` +
encodeURIComponent(webSocketUrlWithoutProtocol);
return {
id: `${deviceId}-${page.id}`,
description: page.app,
title: page.title,
faviconUrl: 'https://reactjs.org/favicon.ico',
devtoolsFrontendUrl,
type: 'node',
webSocketDebuggerUrl,
vm: page.vm,
deviceName: device.getName(),
};
}
// Sends object as response to HTTP request.
// Just serializes object using JSON and sets required headers.
_sendJsonResponse(
response: ServerResponse,
object: JsonPagesListResponse | JsonVersionResponse,
) {
const data = JSON.stringify(object, null, 2);
response.writeHead(200, {
'Content-Type': 'application/json; charset=UTF-8',
'Cache-Control': 'no-cache',
'Content-Length': data.length.toString(),
Connection: 'close',
});
response.end(data);
}
// Adds websocket handler for device connections.
// Device connects to /inspector/device and passes device and app names as
// HTTP GET params.
// For each new websocket connection we parse device and app names and create
// new instance of Device class.
_createDeviceConnectionWSServer(): ws$WebSocketServer {
const wss = new WS.Server({
noServer: true,
perMessageDeflate: true,
// Don't crash on exceptionally large messages - assume the device is
// well-behaved and the debugger is prepared to handle large messages.
maxPayload: 0,
});
// $FlowFixMe[value-as-type]
wss.on('connection', async (socket: WS, req) => {
try {
const fallbackDeviceId = String(this._deviceCounter++);
const query = url.parse(req.url || '', true).query || {};
const deviceId = query.device || fallbackDeviceId;
const deviceName = query.name || 'Unknown';
const appName = query.app || 'Unknown';
const oldDevice = this._devices.get(deviceId);
const newDevice = new Device(
deviceId,
deviceName,
appName,
socket,
this._projectRoot,
this._eventReporter,
);
if (oldDevice) {
oldDevice.handleDuplicateDeviceConnection(newDevice);
}
this._devices.set(deviceId, newDevice);
debug(
`Got new connection: name=${deviceName}, app=${appName}, device=${deviceId}`,
);
socket.on('close', () => {
this._devices.delete(deviceId);
debug(`Device ${deviceName} disconnected.`);
});
} catch (e) {
console.error('error', e);
socket.close(INTERNAL_ERROR_CODE, e?.toString() ?? 'Unknown error');
}
});
return wss;
}
// Returns websocket handler for debugger connections.
// Debugger connects to webSocketDebuggerUrl that we return as part of page description
// in /json response.
// When debugger connects we try to parse device and page IDs from the query and pass
// websocket object to corresponding Device instance.
_createDebuggerConnectionWSServer(): ws$WebSocketServer {
const wss = new WS.Server({
noServer: true,
perMessageDeflate: false,
// Don't crash on exceptionally large messages - assume the debugger is
// well-behaved and the device is prepared to handle large messages.
maxPayload: 0,
});
// $FlowFixMe[value-as-type]
wss.on('connection', async (socket: WS, req) => {
try {
const query = url.parse(req.url || '', true).query || {};
const deviceId = query.device;
const pageId = query.page;
if (deviceId == null || pageId == null) {
throw new Error('Incorrect URL - must provide device and page IDs');
}
const device = this._devices.get(deviceId);
if (device == null) {
throw new Error('Unknown device with ID ' + deviceId);
}
device.handleDebuggerConnection(socket, pageId, {
userAgent: req.headers['user-agent'] ?? null,
});
} catch (e) {
console.error(e);
socket.close(INTERNAL_ERROR_CODE, e?.toString() ?? 'Unknown error');
this._eventReporter?.logEvent({
type: 'connect_debugger_frontend',
status: 'error',
error: e,
});
}
});
return wss;
}
}