microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
3b6023b2c4497b5b8cf54373639977efc9e6e612

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/debugger/appWorker.ts

266lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as vm from "vm";
5import * as Q from "q";
6import * as path from "path";
7import * as WebSocket from "ws";
8import {ScriptImporter} from "./scriptImporter";
9import {Packager} from "../common/packager";
10import {ErrorHelper} from "../common/error/errorHelper";
11import {Log} from "../common/log/log";
12import {LogLevel} from "../common/log/logHelper";
13import {FileSystem} from "../common/node/fileSystem";
14import {ExecutionsLimiter} from "../common/executionsLimiter";
15
16import Module = require("module");
17
18// This file is a replacement of: https://github.com/facebook/react-native/blob/8d397b4cbc05ad801cfafb421cee39bcfe89711d/local-cli/server/util/debugger.html for Node.JS
19interface DebuggerWorkerSandbox {
20 __filename: string;
21 __dirname: string;
22 self: DebuggerWorkerSandbox;
23 console: typeof console;
24 require: (id: string) => any;
25 importScripts: (url: string) => void;
26 postMessage: (object: any) => void;
27 onmessage: (object: RNAppMessage) => void;
28 postMessageArgument: RNAppMessage; // We use this argument to pass messages to the worker
29}
30
31interface RNAppMessage {
32 method: string;
33 // These objects have also other properties but that we don't currently use
34}
35
36function printDebuggingError(message: string, reason: any) {
37 Log.logWarning(ErrorHelper.getNestedWarning(reason, `${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`));
38}
39
40export class SandboxedAppWorker {
41 /** This class will run the RN App logic inside a sandbox. The framework to run the logic is provided by the file
42 * debuggerWorker.js (designed to run on a WebWorker). We load that file inside a sandbox, and then we use the
43 * PROCESS_MESSAGE_INSIDE_SANDBOX script to execute the logic to respond to a message inside the sandbox.
44 * The code inside the debuggerWorker.js will call the global function postMessage to send a reply back to the app,
45 * so we define our custom function there, so we can handle the message. We also provide our own importScript function
46 * to download any script used by debuggerWorker.js
47 */
48 private sourcesStoragePath: string;
49 private debugAdapterPort: number;
50 private postReplyToApp: (message: any) => void;
51
52 private sandbox: DebuggerWorkerSandbox;
53 private sandboxContext: vm.Context;
54 private scriptToReceiveMessageInSandbox: vm.Script;
55
56 private pendingScriptImport = Q(void 0);
57
58 private nodeFileSystem: FileSystem;
59 private scriptImporter: ScriptImporter;
60
61 private static PROCESS_MESSAGE_INSIDE_SANDBOX = "onmessage({ data: postMessageArgument });";
62
63 constructor(sourcesStoragePath: string, debugAdapterPort: number, postReplyToApp: (message: any) => void, {
64 nodeFileSystem = new FileSystem(),
65 scriptImporter = new ScriptImporter(sourcesStoragePath)
66 } = {}) {
67 this.sourcesStoragePath = sourcesStoragePath;
68 this.debugAdapterPort = debugAdapterPort;
69 this.postReplyToApp = postReplyToApp;
70 this.scriptToReceiveMessageInSandbox = new vm.Script(SandboxedAppWorker.PROCESS_MESSAGE_INSIDE_SANDBOX);
71
72 this.nodeFileSystem = nodeFileSystem;
73 this.scriptImporter = scriptImporter;
74 }
75
76 public start(): Q.Promise<void> {
77 let scriptToRunPath = require.resolve(path.join(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILE_BASENAME));
78 this.initializeSandboxAndContext(scriptToRunPath);
79 return this.readFileContents(scriptToRunPath).then(fileContents =>
80 // On a debugger worker the onmessage variable already exist. We need to declare it before the
81 // javascript file can assign it. We do it in the first line without a new line to not break
82 // the debugging experience of debugging debuggerWorker.js itself (as part of the extension)
83 this.runInSandbox(scriptToRunPath, "var onmessage = null; " + fileContents));
84 }
85
86 public postMessage(object: RNAppMessage): void {
87 this.sandbox.postMessageArgument = object;
88 this.scriptToReceiveMessageInSandbox.runInContext(this.sandboxContext);
89 }
90
91 private initializeSandboxAndContext(scriptToRunPath: string): void {
92 let scriptToRunModule = new Module(scriptToRunPath);
93
94 this.sandbox = {
95 __filename: scriptToRunPath,
96 __dirname: path.dirname(scriptToRunPath),
97 self: null,
98 console: console,
99 require: (filePath: string) => scriptToRunModule.require(filePath), // Give the sandbox access to require("<filePath>");
100 importScripts: (url: string) => this.importScripts(url), // Import script like using <script/>
101 postMessage: (object: any) => this.gotResponseFromDebuggerWorker(object), // Post message back to the UI thread
102 onmessage: null,
103 postMessageArgument: null
104 };
105 this.sandbox.self = this.sandbox;
106
107 this.sandboxContext = vm.createContext(this.sandbox);
108 }
109
110 private runInSandbox(filename: string, fileContents?: string): Q.Promise<void> {
111 let fileContentsPromise = fileContents
112 ? Q(fileContents)
113 : this.readFileContents(filename);
114
115 return fileContentsPromise.then(contents => {
116 vm.runInContext(contents, this.sandboxContext, filename);
117 });
118 }
119
120 private readFileContents(filename: string) {
121 return this.nodeFileSystem.readFile(filename).then(contents => contents.toString());
122 }
123
124 private importScripts(url: string): void {
125 /* The debuggerWorker.js executes this code:
126 importScripts(message.url);
127 sendReply();
128
129 In the original code importScripts is a sync call. In our code it's async, so we need to mess with sendReply() so we won't
130 actually send the reply back to the application until after importScripts has finished executing. We use
131 this.pendingScriptImport to make the gotResponseFromDebuggerWorker() method hold the reply back, until've finished importing
132 and running the script */
133 let defer = Q.defer<{}>();
134 this.pendingScriptImport = defer.promise;
135
136 // The next line converts to any due to the incorrect typing on node.d.ts of vm.runInThisContext
137 this.scriptImporter.downloadAppScript(url, this.debugAdapterPort)
138 .then(downloadedScript =>
139 this.runInSandbox(downloadedScript.filepath, downloadedScript.contents))
140 .done(() => {
141 // Now we let the reply to the app proceed
142 defer.resolve({});
143 }, reason => {
144 printDebuggingError(`Couldn't import script at <${url}>`, reason);
145 });
146 }
147
148 private gotResponseFromDebuggerWorker(object: any): void {
149 // We might need to hold the response until a script is imported. See comments on this.importScripts()
150 this.pendingScriptImport.done(() =>
151 this.postReplyToApp(object), reason => {
152 printDebuggingError("Unexpected internal error while processing a message from the RN App.", reason);
153 });
154 }
155}
156
157export class MultipleLifetimesAppWorker {
158 /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket
159 * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles
160 * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created succesfully.
161 * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones.
162 */
163 private sourcesStoragePath: string;
164 private debugAdapterPort: number;
165 private socketToApp: WebSocket;
166 private singleLifetimeWorker: SandboxedAppWorker;
167
168 private sandboxedAppConstructor: (storagePath: string, adapterPort: number, messageFunction: (message: any) => void) => SandboxedAppWorker;
169 private webSocketConstructor: (url: string) => WebSocket;
170
171 private executionLimiter = new ExecutionsLimiter();
172
173 constructor(sourcesStoragePath: string, debugAdapterPort: number, {
174 sandboxedAppConstructor = (path: string, port: number, messageFunc: (message: any) => void) => new SandboxedAppWorker(path, port, messageFunc),
175 webSocketConstructor = (url: string) => new WebSocket(url)
176 } = {}) {
177 this.sourcesStoragePath = sourcesStoragePath;
178 this.debugAdapterPort = debugAdapterPort;
179 console.assert(!!this.sourcesStoragePath, "The sourcesStoragePath argument was null or empty");
180
181 this.sandboxedAppConstructor = sandboxedAppConstructor;
182 this.webSocketConstructor = webSocketConstructor;
183 }
184
185 public start(): Q.Promise<void> {
186 this.socketToApp = this.createSocketToApp();
187 return Q.resolve<void>(void 0); // Currently this method is sync
188 }
189
190 private startNewWorkerLifetime(): Q.Promise<void> {
191 this.singleLifetimeWorker = this.sandboxedAppConstructor(this.sourcesStoragePath, this.debugAdapterPort, (message) => {
192 this.sendMessageToApp(message);
193 });
194 Log.logInternalMessage(LogLevel.Info, "A new app worker lifetime was created.");
195 return this.singleLifetimeWorker.start();
196 }
197
198 private createSocketToApp() {
199 let socketToApp = this.webSocketConstructor(this.debuggerProxyUrl());
200 socketToApp.on("open", () =>
201 this.onSocketOpened());
202 socketToApp.on("close", () =>
203 this.onSocketClose());
204 socketToApp.on("message",
205 (message: any) => this.onMessage(message));
206 socketToApp.on("error",
207 (error: Error) => printDebuggingError("An error ocurred while using the socket to communicate with the React Native app", error));
208 return socketToApp;
209 }
210
211 private debuggerProxyUrl() {
212 return `ws://${Packager.HOST}/debugger-proxy?role=debugger&name=vscode`;
213 }
214
215 private onSocketOpened() {
216 this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () =>
217 Log.logMessage("Established a connection with the Proxy (Packager) to the React Native application"));
218 }
219
220 private onSocketClose() {
221 this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () =>
222 Log.logMessage("Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon..."));
223 setTimeout(() => this.start(), 100);
224 }
225
226 private onMessage(message: string) {
227 try {
228 Log.logInternalMessage(LogLevel.Trace, "From RN APP: " + message);
229 let object = <RNAppMessage>JSON.parse(message);
230 if (object.method === "prepareJSRuntime") {
231 // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime
232 this.gotPrepareJSRuntime(object);
233 } else if (object.method === "$disconnected") {
234 // We need to shutdown the current app worker, and create a new lifetime
235 this.singleLifetimeWorker = null;
236 } else if (object.method) {
237 // All the other messages are handled by the single lifetime worker
238 this.singleLifetimeWorker.postMessage(object);
239 } else {
240 // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected
241 Log.logInternalMessage(LogLevel.Info, "The react-native app sent a message without specifying a method: " + message);
242 }
243 } catch (exception) {
244 printDebuggingError(`Failed to process message from the React Native app. Message:\n${message}`, exception);
245 }
246 }
247
248 private gotPrepareJSRuntime(message: any): void {
249 // Create the sandbox, and replay that we finished processing the message
250 this.startNewWorkerLifetime().done(() => {
251 this.sendMessageToApp({ replyID: parseInt(message.id, 10) });
252 }, error => printDebuggingError(`Failed to prepare the JavaScript runtime environment. Message:\n${message}`, error));
253 }
254
255 private sendMessageToApp(message: any): void {
256 let stringified: string = null;
257 try {
258 stringified = JSON.stringify(message);
259 Log.logInternalMessage(LogLevel.Trace, "To RN APP: " + stringified);
260 this.socketToApp.send(stringified);
261 } catch (exception) {
262 let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable
263 printDebuggingError(`Failed to send message to the React Native app. Message:\n${messageToShow}`, exception);
264 }
265 }
266}
267