-
Notifications
You must be signed in to change notification settings - Fork 282
Expand file tree
/
Copy pathappWorker.ts
More file actions
487 lines (444 loc) · 18.2 KB
/
appWorker.ts
File metadata and controls
487 lines (444 loc) · 18.2 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
import * as path from "path";
import { EventEmitter } from "events";
import * as vscode from "vscode";
import WebSocket = require("ws");
import { logger } from "@vscode/debugadapter";
import * as nls from "vscode-nls";
import { ensurePackagerRunning } from "../common/packagerStatus";
import { ErrorHelper } from "../common/error/errorHelper";
import { ExecutionsLimiter } from "../common/executionsLimiter";
import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
import { InternalErrorCode } from "../common/error/internalErrorCode";
import { FileSystem } from "../common/node/fileSystem";
import { PromiseUtil } from "../common/node/promise";
import { ForkedAppWorker } from "./forkedAppWorker";
import { ScriptImporter } from "./scriptImporter";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize = nls.loadMessageBundle();
export interface RNAppMessage {
method: string;
url?: string;
// These objects have also other properties but that we don't currently use
}
export interface IDebuggeeWorker {
start(): Promise<any>;
stop(): void;
postMessage(message: RNAppMessage): void;
}
function printDebuggingError(error: Error, reason: any) {
const nestedError = ErrorHelper.getNestedError(
error,
InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect,
reason,
);
logger.error(nestedError.message);
}
/** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket
* and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles
* is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully.
* When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones.
*/
export class MultipleLifetimesAppWorker extends EventEmitter {
public static WORKER_BOOTSTRAP = `
// Initialize some variables before react-native code would access them
var onmessage=null, self=global;
// Cache Node's original require as __debug__.require
global.__debug__={require: require};
// Prevent leaking process.versions from debugger process to
// worker because pure React Native doesn't do that and some packages as js-md5 rely on this behavior
Object.defineProperty(process, "versions", {
value: undefined
});
// Polyfill for url.fileURLToPath - needed because this code runs in user's RN environment
// where we cannot use import/require. Keep this implementation.
function fileUrlToPath(url) {
if (process.platform === 'win32') {
return url.toString().replace('file:///', '');
} else {
return url.toString().replace('file://', '');
}
}
function getNativeModules() {
var NativeModules;
try {
// This approach is for old RN versions
NativeModules = global.require('NativeModules');
} catch (err) {
// ignore error and try another way for more recent RN versions
try {
var nativeModuleId;
var modules = global.__r.getModules();
var ids = Object.keys(modules);
for (var i = 0; i < ids.length; i++) {
if (modules[ids[i]].verboseName) {
var packagePath = new String(modules[ids[i]].verboseName);
if (packagePath.indexOf('Libraries/BatchedBridge/NativeModules.js') > 0 || packagePath.indexOf('Libraries\\\\BatchedBridge\\\\NativeModules.js') > 0) {
nativeModuleId = parseInt(ids[i], 10);
break;
}
}
}
if (nativeModuleId) {
NativeModules = global.__r(nativeModuleId);
}
}
catch (err) {
// suppress errors
}
}
return NativeModules;
}
// Originally, this was made for iOS only
var vscodeHandlers = {
'vscode_reloadApp': function () {
var NativeModules = getNativeModules();
if (NativeModules && NativeModules.DevSettings) {
NativeModules.DevSettings.reload();
}
},
'vscode_showDevMenu': function () {
var NativeModules = getNativeModules();
if (NativeModules && NativeModules.DevMenu) {
NativeModules.DevMenu.show();
}
}
};
process.on("message", function (message) {
if (message.data && vscodeHandlers[message.data.method]) {
vscodeHandlers[message.data.method]();
} else if(onmessage) {
onmessage(message);
}
});
var postMessage = function(message){
process.send(message);
};
if (!self.postMessage) {
self.postMessage = postMessage;
}
var importScripts = (function(){
var fs=require('fs'), vm=require('vm');
return function(scriptUrl){
scriptUrl = fileUrlToPath(scriptUrl);
var scriptCode = fs.readFileSync(scriptUrl, 'utf8');
// Add a 'debugger;' statement to stop code execution
// to wait for the sourcemaps to be processed by the debug adapter
vm.runInThisContext('debugger;' + scriptCode, {filename: scriptUrl});
};
})();
`;
public static CONSOLE_TRACE_PATCH = `// Worker is ran as nodejs process, so console.trace() writes to stderr and it leads to error in native app
// To avoid this console.trace() is overridden to print stacktrace via console.log()
// Please, see Node JS implementation: https://github.com/nodejs/node/blob/master/lib/internal/console/constructor.js
console.trace = (function() {
return function() {
try {
var err = {
name: 'Trace',
message: require('util').format.apply(null, arguments)
};
// Node uses 10, but usually it's not enough for RN app trace
Error.stackTraceLimit = 30;
Error.captureStackTrace(err, console.trace);
console.log(err.stack);
} catch (e) {
console.error(e);
}
};
})();
`;
public static PROCESS_TO_STRING_PATCH = `// As worker is ran in node, it breaks broadcast-channels package approach of identifying if it’s ran in node:
// https://github.com/pubkey/broadcast-channel/blob/master/src/util.js#L64
// To avoid it if process.toString() is called if will return empty string instead of [object process].
var nativeObjectToString = Object.prototype.toString;
Object.prototype.toString = function() {
if (this === process) {
return '';
} else {
return nativeObjectToString.call(this);
}
};
`;
public static WORKER_DONE = `// Notify debugger that we're done with loading
// and started listening for IPC messages
postMessage({workerLoaded:true});`;
public static FETCH_STUB = `(function(self) {
'use strict';
if (self.fetch) {
return;
}
self.fetch = fetch;
function fetch(url) {
return new Promise((resolve, reject) => {
var data = require('fs').readFileSync(fileUrlToPath(url), 'utf8');
resolve(
{
text: function () {
return data;
}
});
});
}
})(global);
`;
private packagerAddress: string;
private packagerPort: number;
private sourcesStoragePath: string;
private projectRootPath: string;
private packagerRemoteRoot?: string;
private packagerLocalRoot?: string;
private debuggerWorkerUrlPath?: string;
private socketToApp!: WebSocket;
private cancellationToken: vscode.CancellationToken;
private singleLifetimeWorker: IDebuggeeWorker | null = null;
private webSocketConstructor: (url: string) => WebSocket;
private executionLimiter = new ExecutionsLimiter();
private nodeFileSystem = new FileSystem();
private scriptImporter: ScriptImporter;
constructor(
attachRequestArguments: any,
sourcesStoragePath: string,
projectRootPath: string,
cancellationToken: vscode.CancellationToken,
{ webSocketConstructor = (url: string) => new WebSocket(url) } = {},
) {
super();
this.packagerAddress = attachRequestArguments.address || "localhost";
this.packagerPort = attachRequestArguments.port;
this.packagerRemoteRoot = attachRequestArguments.remoteRoot;
this.packagerLocalRoot = attachRequestArguments.localRoot;
this.debuggerWorkerUrlPath = attachRequestArguments.debuggerWorkerUrlPath;
this.sourcesStoragePath = sourcesStoragePath;
this.projectRootPath = projectRootPath;
this.cancellationToken = cancellationToken;
if (!this.sourcesStoragePath)
throw ErrorHelper.getInternalError(InternalErrorCode.SourcesStoragePathIsNullOrEmpty);
this.webSocketConstructor = webSocketConstructor;
this.scriptImporter = new ScriptImporter(
this.packagerAddress,
this.packagerPort,
sourcesStoragePath,
this.packagerRemoteRoot,
this.packagerLocalRoot,
);
}
public async start(retryAttempt: boolean = false): Promise<void> {
const errPackagerNotRunning = ErrorHelper.getInternalError(
InternalErrorCode.CannotAttachToPackagerCheckPackagerRunningOnPort,
this.packagerPort,
);
await ensurePackagerRunning(this.packagerAddress, this.packagerPort, errPackagerNotRunning);
// Don't fetch debugger worker on socket disconnect
if (!retryAttempt) {
await this.downloadAndPatchDebuggerWorker();
}
return this.createSocketToApp(retryAttempt);
}
public stop(): void {
if (this.socketToApp) {
this.socketToApp.removeAllListeners();
this.socketToApp.close();
}
if (this.singleLifetimeWorker) {
this.singleLifetimeWorker.stop();
}
}
public async downloadAndPatchDebuggerWorker(): Promise<void> {
const scriptToRunPath = path.resolve(
this.sourcesStoragePath,
ScriptImporter.DEBUGGER_WORKER_FILENAME,
);
await this.scriptImporter.downloadDebuggerWorker(
this.sourcesStoragePath,
this.projectRootPath,
this.debuggerWorkerUrlPath,
);
const workerContent = await this.nodeFileSystem.readFile(scriptToRunPath, "utf8");
const isHaulProject = ReactNativeProjectHelper.isHaulProject(this.projectRootPath);
// Add our customizations to debugger worker to get it working smoothly
// in Node env and polyfill WebWorkers API over Node's IPC.
const modifiedDebuggeeContent = [
MultipleLifetimesAppWorker.WORKER_BOOTSTRAP,
MultipleLifetimesAppWorker.CONSOLE_TRACE_PATCH,
MultipleLifetimesAppWorker.PROCESS_TO_STRING_PATCH,
isHaulProject ? MultipleLifetimesAppWorker.FETCH_STUB : null,
workerContent,
MultipleLifetimesAppWorker.WORKER_DONE,
].join("\n");
return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent);
}
public showDevMenuCommand(): void {
if (this.singleLifetimeWorker) {
this.singleLifetimeWorker.postMessage({
method: "vscode_showDevMenu",
});
}
}
public reloadAppCommand(): void {
if (this.singleLifetimeWorker) {
this.singleLifetimeWorker.postMessage({
method: "vscode_reloadApp",
});
}
}
private async startNewWorkerLifetime(): Promise<void> {
this.singleLifetimeWorker = new ForkedAppWorker(
this.packagerAddress,
this.packagerPort,
this.sourcesStoragePath,
this.projectRootPath,
message => {
this.sendMessageToApp(message);
},
this.packagerRemoteRoot,
this.packagerLocalRoot,
);
logger.verbose("A new app worker lifetime was created.");
const startedEvent = await this.singleLifetimeWorker.start();
this.emit("connected", startedEvent);
}
private async createSocketToApp(retryAttempt: boolean = false): Promise<void> {
return new Promise((resolve, reject) => {
this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl());
this.socketToApp.on("open", () => {
this.onSocketOpened();
});
this.socketToApp.on("close", () => {
this.executionLimiter.execute("onSocketClose.msg", /* limitInSeconds*/ 10, () => {
/*
* It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when
* it closes the socket because it already has a connection to a debugger.
* https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38
*/
const msgKey = "_closeMessage";
if (
(this.socketToApp as any)[msgKey] ===
"Another debugger is already connected"
) {
reject(
ErrorHelper.getInternalError(
InternalErrorCode.AnotherDebuggerConnectedToPackager,
),
);
}
logger.log(
localize(
"DisconnectedFromThePackagerToReactNative",
"Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon...",
),
);
});
if (!this.cancellationToken.isCancellationRequested) {
setTimeout(() => {
void this.start(true /* retryAttempt */);
}, 100);
}
});
this.socketToApp.on("message", (message: any) => this.onMessage(message));
this.socketToApp.on("error", (error: Error) => {
if (retryAttempt) {
printDebuggingError(
ErrorHelper.getInternalError(
InternalErrorCode.ReconnectionToPackagerFailedCheckForErrorsOrRestartReactNative,
),
error,
);
}
reject(error);
});
// In an attempt to catch failures in starting the packager on first attempt,
// wait for 300 ms before resolving the promise
void PromiseUtil.delay(300).then(() => resolve());
});
}
private debuggerProxyUrl() {
return `ws://${this.packagerAddress}:${this.packagerPort}/debugger-proxy?role=debugger&name=vscode`;
}
private onSocketOpened() {
this.executionLimiter.execute("onSocketOpened.msg", /* limitInSeconds*/ 10, () =>
logger.log(
localize(
"EstablishedConnectionWithPackagerToReactNativeApp",
"Established a connection with the Proxy (Packager) to the React Native application",
),
),
);
}
private killWorker() {
if (!this.singleLifetimeWorker) return;
this.singleLifetimeWorker.stop();
this.singleLifetimeWorker = null;
}
private onMessage(message: string) {
try {
logger.verbose(`From RN APP: ${message}`);
const object = <RNAppMessage>JSON.parse(message);
if (object.method === "prepareJSRuntime") {
// In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event
// when user reloads an app, hence we need to try to kill it here either.
this.killWorker();
// The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime
this.gotPrepareJSRuntime(object);
} else if (object.method === "$disconnected") {
// We need to shutdown the current app worker, and create a new lifetime
this.killWorker();
} else if (object.method) {
// All the other messages are handled by the single lifetime worker
if (this.singleLifetimeWorker) {
this.singleLifetimeWorker.postMessage(object);
}
} else {
// Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected
logger.verbose(
`The react-native app sent a message without specifying a method: ${message}`,
);
}
} catch (exception) {
printDebuggingError(
ErrorHelper.getInternalError(
InternalErrorCode.FailedToProcessMessageFromReactNativeApp,
message,
),
exception,
);
}
}
private gotPrepareJSRuntime(message: any): void {
// Create the sandbox, and replay that we finished processing the message
this.startNewWorkerLifetime().then(
() => {
this.sendMessageToApp({ replyID: parseInt(message.id, 10) });
},
error =>
printDebuggingError(
ErrorHelper.getInternalError(
InternalErrorCode.FailedToPrepareJSRuntimeEnvironment,
message,
),
error,
),
);
}
private sendMessageToApp(message: any): void {
let stringified = "";
try {
stringified = JSON.stringify(message);
logger.verbose(`To RN APP: ${stringified}`);
this.socketToApp.send(stringified);
} catch (exception) {
const messageToShow = stringified || String(message); // Try to show the stringified version, but show the toString if unavailable
printDebuggingError(
ErrorHelper.getInternalError(
InternalErrorCode.FailedToSendMessageToTheReactNativeApp,
messageToShow,
),
exception,
);
}
}
}