microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
aca27f7fdc5c73d80ef5f4556bfd268df7c06a69

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

156lines · modeblame

e45838cbVladimir Kotikov9 years ago1// 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";
6eeec3c0Serge Svekolnikov8 years ago6import * as url from "url";
e45838cbVladimir Kotikov9 years ago7import * as child_process from "child_process";
5c8365a6Artem Egorov8 years ago8import {ScriptImporter, DownloadedScript} from "./scriptImporter";
e45838cbVladimir Kotikov9 years ago9
0a68f8dbArtem Egorov8 years ago10import { logger } from "vscode-chrome-debug-core";
e45838cbVladimir Kotikov9 years ago11import { ErrorHelper } from "../common/error/errorHelper";
12import { IDebuggeeWorker, RNAppMessage } from "./appWorker";
7daed3fcArtem Egorov8 years ago13import { RemoteExtension } from "../common/remoteExtension";
d124bf0eYuri Skorokhodov7 years ago14import * as nls from "vscode-nls";
15const localize = nls.loadMessageBundle();
e45838cbVladimir Kotikov9 years ago16
17function printDebuggingError(message: string, reason: any) {
d124bf0eYuri Skorokhodov7 years ago18const nestedError = ErrorHelper.getNestedWarning(reason, localize("DebuggingWontWorkReloadJSAndReconnect", "{0}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger", message));
0a68f8dbArtem Egorov8 years ago19
20logger.error(nestedError.message);
e45838cbVladimir Kotikov9 years ago21}
22
23/** This class will run the RN App logic inside a forked Node process. The framework to run the logic is provided by the file
24* debuggerWorker.js (designed to run on a WebWorker). We add a couple of tweaks (mostly to polyfill WebWorker API) to that
25* file and load it inside of a process.
26* On this side we listen to IPC messages and either respond to them or redirect them to packager via MultipleLifetimeAppWorker's
27* instance. We also intercept packager's signal to load the bundle's code and mutate the message with path to file we've downloaded
28* to let importScripts function take this file.
29*/
30export class ForkedAppWorker implements IDebuggeeWorker {
31
6eeec3c0Serge Svekolnikov8 years ago32protected scriptImporter: ScriptImporter;
33protected debuggeeProcess: child_process.ChildProcess | null = null;
e45838cbVladimir Kotikov9 years ago34/** A deferred that we use to make sure that worker has been loaded completely defore start sending IPC messages */
6eeec3c0Serge Svekolnikov8 years ago35protected workerLoaded = Q.defer<void>();
5c8365a6Artem Egorov8 years ago36private bundleLoaded: Q.Deferred<void>;
7daed3fcArtem Egorov8 years ago37private remoteExtension: RemoteExtension;
e45838cbVladimir Kotikov9 years ago38
39constructor(
6eeec3c0Serge Svekolnikov8 years ago40private packagerAddress: string,
e45838cbVladimir Kotikov9 years ago41private packagerPort: number,
42private sourcesStoragePath: string,
7daed3fcArtem Egorov8 years ago43private projectRootPath: string,
6eeec3c0Serge Svekolnikov8 years ago44private postReplyToApp: (message: any) => void,
45private packagerRemoteRoot?: string,
46private packagerLocalRoot?: string
e45838cbVladimir Kotikov9 years ago47) {
6eeec3c0Serge Svekolnikov8 years ago48this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
7daed3fcArtem Egorov8 years ago49
50this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath);
51
52this.remoteExtension.api.Debugger.onShowDevMenu(() => {
53this.postMessage({
54method: "vscode_showDevMenu",
55});
56});
57
58this.remoteExtension.api.Debugger.onReloadApp(() => {
59this.postMessage({
60method: "vscode_reloadApp",
61});
62});
e45838cbVladimir Kotikov9 years ago63}
64
65public stop() {
66if (this.debuggeeProcess) {
0a68f8dbArtem Egorov8 years ago67logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`);
e45838cbVladimir Kotikov9 years ago68this.debuggeeProcess.kill();
69this.debuggeeProcess = null;
70}
71}
72
73public start(): Q.Promise<number> {
74let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
cc70057dVladimir Kotikov9 years ago75const port = Math.round(Math.random() * 40000 + 3000);
e45838cbVladimir Kotikov9 years ago76
cc70057dVladimir Kotikov9 years ago77// Note that we set --debug-brk flag to pause the process on the first line - this is
78// required for debug adapter to set the breakpoints BEFORE the debuggee has started.
79// The adapter will continue execution once it's done with breakpoints.
f533409bRuslan Bikkinin7 years ago80const nodeArgs = [`--inspect=${port}`, "--debug-brk", scriptToRunPath];
cc70057dVladimir Kotikov9 years ago81// Start child Node process in debugging mode
f533409bRuslan Bikkinin7 years ago82// Using fork instead of spawn causes breakage of piping between app worker and VS Code debug console, e.g. console.log() in application
83// wouldn't work. Please see https://github.com/Microsoft/vscode-react-native/issues/758
84this.debuggeeProcess = child_process.spawn("node", nodeArgs, {
85stdio: ["pipe", "pipe", "pipe", "ipc"],
86})
cc70057dVladimir Kotikov9 years ago87.on("message", (message: any) => {
88// 'workerLoaded' is a special message that indicates that worker is done with loading.
89// We need to wait for it before doing any IPC because process.send doesn't seems to care
6eeec3c0Serge Svekolnikov8 years ago90// about whether the message has been received or not and the first messages are often get
cc70057dVladimir Kotikov9 years ago91// discarded by spawned process
92if (message && message.workerLoaded) {
93this.workerLoaded.resolve(void 0);
94return;
95}
e45838cbVladimir Kotikov9 years ago96
cc70057dVladimir Kotikov9 years ago97this.postReplyToApp(message);
98})
99.on("error", (error: Error) => {
d124bf0eYuri Skorokhodov7 years ago100printDebuggingError(localize("ReactNativeWorkerProcessThrownAnError", "React Native worker process thrown an error"), error);
e45838cbVladimir Kotikov9 years ago101});
cc70057dVladimir Kotikov9 years ago102
103// Resolve with port debugger server is listening on
104// This will be sent to subscribers of MLAppWorker in "connected" event
0a68f8dbArtem Egorov8 years ago105logger.verbose(`Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`);
cc70057dVladimir Kotikov9 years ago106
107return Q.resolve(port);
e45838cbVladimir Kotikov9 years ago108}
109
6eeec3c0Serge Svekolnikov8 years ago110public postMessage(rnMessage: RNAppMessage): Q.Promise<RNAppMessage> {
e45838cbVladimir Kotikov9 years ago111// Before sending messages, make sure that the worker is loaded
6eeec3c0Serge Svekolnikov8 years ago112const promise = this.workerLoaded.promise
936b1ceaArtem Egorov9 years ago113.then(() => {
114if (rnMessage.method !== "executeApplicationScript") {
115// Before sending messages, make sure that the app script executed
116if (this.bundleLoaded) {
117return this.bundleLoaded.promise.then(() => {
118return rnMessage;
119});
120} else {
121return rnMessage;
122}
123} else {
124this.bundleLoaded = Q.defer<void>();
125// When packager asks worker to load bundle we download that bundle and
126// then set url field to point to that downloaded bundle, so the worker
127// will take our modified bundle
5c8365a6Artem Egorov8 years ago128if (rnMessage.url) {
6eeec3c0Serge Svekolnikov8 years ago129const packagerUrl = url.parse(rnMessage.url);
130packagerUrl.host = `${this.packagerAddress}:${this.packagerPort}`;
131rnMessage = {
132...rnMessage,
133url: url.format(packagerUrl),
134};
d124bf0eYuri Skorokhodov7 years ago135logger.verbose(`Packager requested runtime to load script from ${rnMessage.url}`);
979d7bfemax-mironov8 years ago136return this.scriptImporter.downloadAppScript(<string>rnMessage.url, this.projectRootPath)
5c8365a6Artem Egorov8 years ago137.then((downloadedScript: DownloadedScript) => {
138this.bundleLoaded.resolve(void 0);
139return Object.assign({}, rnMessage, { url: downloadedScript.filepath });
140});
141} else {
d124bf0eYuri Skorokhodov7 years ago142throw Error(localize("RNMessageWithMethodExecuteApplicationScriptDoesntHaveURLProperty", "RNMessage with method 'executeApplicationScript' doesn't have 'url' property"));
5c8365a6Artem Egorov8 years ago143}
936b1ceaArtem Egorov9 years ago144}
6eeec3c0Serge Svekolnikov8 years ago145});
146promise.done(
5c8365a6Artem Egorov8 years ago147(message: RNAppMessage) => {
148if (this.debuggeeProcess) {
149this.debuggeeProcess.send({ data: message });
150}
151},
d124bf0eYuri Skorokhodov7 years ago152(reason) => printDebuggingError(localize("CouldntImportScriptAt", "Couldn't import script at <{0}>", rnMessage.url), reason));
6eeec3c0Serge Svekolnikov8 years ago153
154return promise;
e45838cbVladimir Kotikov9 years ago155}
156}