microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
c0b32993595df760282a903082cf37d59de18ea8

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

152lines · 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 Q from "q";
5import * as path from "path";
6import * as url from "url";
7import * as child_process from "child_process";
8import {ScriptImporter, DownloadedScript} from "./scriptImporter";
9
10import { logger } from "vscode-chrome-debug-core";
11import { ErrorHelper } from "../common/error/errorHelper";
12import { IDebuggeeWorker, RNAppMessage } from "./appWorker";
13import { RemoteExtension } from "../common/remoteExtension";
14
15function printDebuggingError(message: string, reason: any) {
16 const nestedError = ErrorHelper.getNestedWarning(reason, `${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`);
17
18 logger.error(nestedError.message);
19}
20
21/** This class will run the RN App logic inside a forked Node process. The framework to run the logic is provided by the file
22 * debuggerWorker.js (designed to run on a WebWorker). We add a couple of tweaks (mostly to polyfill WebWorker API) to that
23 * file and load it inside of a process.
24 * On this side we listen to IPC messages and either respond to them or redirect them to packager via MultipleLifetimeAppWorker's
25 * instance. We also intercept packager's signal to load the bundle's code and mutate the message with path to file we've downloaded
26 * to let importScripts function take this file.
27 */
28export class ForkedAppWorker implements IDebuggeeWorker {
29
30 protected scriptImporter: ScriptImporter;
31 protected debuggeeProcess: child_process.ChildProcess | null = null;
32 /** A deferred that we use to make sure that worker has been loaded completely defore start sending IPC messages */
33 protected workerLoaded = Q.defer<void>();
34 private bundleLoaded: Q.Deferred<void>;
35 private remoteExtension: RemoteExtension;
36
37 constructor(
38 private packagerAddress: string,
39 private packagerPort: number,
40 private sourcesStoragePath: string,
41 private projectRootPath: string,
42 private postReplyToApp: (message: any) => void,
43 private packagerRemoteRoot?: string,
44 private packagerLocalRoot?: string
45 ) {
46 this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
47
48 this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath);
49
50 this.remoteExtension.api.Debugger.onShowDevMenu(() => {
51 this.postMessage({
52 method: "vscode_showDevMenu",
53 });
54 });
55
56 this.remoteExtension.api.Debugger.onReloadApp(() => {
57 this.postMessage({
58 method: "vscode_reloadApp",
59 });
60 });
61 }
62
63 public stop() {
64 if (this.debuggeeProcess) {
65 logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`);
66 this.debuggeeProcess.kill();
67 this.debuggeeProcess = null;
68 }
69 }
70
71 public start(): Q.Promise<number> {
72 let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
73 const port = Math.round(Math.random() * 40000 + 3000);
74
75 // Note that we set --debug-brk flag to pause the process on the first line - this is
76 // required for debug adapter to set the breakpoints BEFORE the debuggee has started.
77 // The adapter will continue execution once it's done with breakpoints.
78 const nodeArgs = [`--inspect=${port}`, "--debug-brk", scriptToRunPath];
79 // Start child Node process in debugging mode
80 this.debuggeeProcess = child_process.spawn("node", nodeArgs, {
81 stdio: ["pipe", "pipe", "pipe", "ipc"],
82 })
83 .on("message", (message: any) => {
84 // 'workerLoaded' is a special message that indicates that worker is done with loading.
85 // We need to wait for it before doing any IPC because process.send doesn't seems to care
86 // about whether the message has been received or not and the first messages are often get
87 // discarded by spawned process
88 if (message && message.workerLoaded) {
89 this.workerLoaded.resolve(void 0);
90 return;
91 }
92
93 this.postReplyToApp(message);
94 })
95 .on("error", (error: Error) => {
96 printDebuggingError("React Native worker process thrown an error", error);
97 });
98
99 // Resolve with port debugger server is listening on
100 // This will be sent to subscribers of MLAppWorker in "connected" event
101 logger.verbose(`Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`);
102
103 return Q.resolve(port);
104 }
105
106 public postMessage(rnMessage: RNAppMessage): Q.Promise<RNAppMessage> {
107 // Before sending messages, make sure that the worker is loaded
108 const promise = this.workerLoaded.promise
109 .then(() => {
110 if (rnMessage.method !== "executeApplicationScript") {
111 // Before sending messages, make sure that the app script executed
112 if (this.bundleLoaded) {
113 return this.bundleLoaded.promise.then(() => {
114 return rnMessage;
115 });
116 } else {
117 return rnMessage;
118 }
119 } else {
120 this.bundleLoaded = Q.defer<void>();
121 // When packager asks worker to load bundle we download that bundle and
122 // then set url field to point to that downloaded bundle, so the worker
123 // will take our modified bundle
124 if (rnMessage.url) {
125 const packagerUrl = url.parse(rnMessage.url);
126 packagerUrl.host = `${this.packagerAddress}:${this.packagerPort}`;
127 rnMessage = {
128 ...rnMessage,
129 url: url.format(packagerUrl),
130 };
131 logger.verbose("Packager requested runtime to load script from " + rnMessage.url);
132 return this.scriptImporter.downloadAppScript(<string>rnMessage.url)
133 .then((downloadedScript: DownloadedScript) => {
134 this.bundleLoaded.resolve(void 0);
135 return Object.assign({}, rnMessage, { url: downloadedScript.filepath });
136 });
137 } else {
138 throw Error("RNMessage with method 'executeApplicationScript' doesn't have 'url' property");
139 }
140 }
141 });
142 promise.done(
143 (message: RNAppMessage) => {
144 if (this.debuggeeProcess) {
145 this.debuggeeProcess.send({ data: message });
146 }
147 },
148 (reason) => printDebuggingError(`Couldn't import script at <${rnMessage.url}>`, reason));
149
150 return promise;
151 }
152}
153