microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
678db279088f7b3fd6c7888d37be778e758ff688

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

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