microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
18d8ad2abfdce9bcdb96cc3fe6fb491da873c8f6

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/nodeDebugWrapper.ts

191lines · 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 fs from "fs";
5import * as path from "path";
6import * as http from "http";
7
8import {Telemetry} from "../common/telemetry";
9import {TelemetryHelper} from "../common/telemetryHelper";
10import {RemoteExtension} from "../common/remoteExtension";
11import {EntryPointHandler, ProcessType} from "../common/entryPointHandler";
12import {ErrorHelper} from "../common/error/errorHelper";
13import {InternalErrorCode} from "../common/error/internalErrorCode";
14import {ExtensionTelemetryReporter, NullTelemetryReporter, ReassignableTelemetryReporter} from "../common/telemetryReporters";
15
16// These typings do not reflect the typings as intended to be used
17// but rather as they exist in truth, so we can reach into the internals
18// and access what we need.
19declare module VSCodeDebugAdapter {
20 class DebugSession {
21 public static run: Function;
22 public sendEvent(event: VSCodeDebugAdapter.InitializedEvent): void;
23 public start(input: any, output: any): void;
24 public launchRequest(response: any, args: any): void;
25 public disconnectRequest(response: any, args: any): void;
26 }
27 class InitializedEvent {
28 constructor();
29 }
30 class OutputEvent {
31 constructor(message: string, destination?: string);
32 }
33 class TerminatedEvent {
34 constructor();
35 }
36}
37
38declare class SourceMaps {
39 public _sourceToGeneratedMaps: {};
40 public _generatedToSourceMaps: {};
41 public _allSourceMaps: {};
42}
43
44declare class NodeDebugSession extends VSCodeDebugAdapter.DebugSession {
45 public _sourceMaps: SourceMaps;
46}
47
48interface ILaunchArgs {
49 platform: string;
50 target?: string;
51 internalDebuggerPort?: any;
52 args: string[];
53 logCatArguments: any;
54 program: string;
55}
56
57let version = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "package.json"), "utf-8")).version;
58
59function bailOut(reason: string): void {
60 // Things have gone wrong in initialization: Report the error to telemetry and exit
61 TelemetryHelper.sendSimpleEvent(reason);
62 process.exit(1);
63}
64
65function parseLogCatArguments(userProvidedLogCatArguments: any) {
66 return Array.isArray(userProvidedLogCatArguments)
67 ? userProvidedLogCatArguments.join(" ") // If it's an array, we join the arguments
68 : userProvidedLogCatArguments; // If not, we leave it as-is
69}
70
71function isNullOrUndefined(value: any): boolean {
72 return typeof value === "undefined" || value === null;
73}
74
75let projectRootPath: string = null;
76
77// Enable telemetry
78const telemetryReporter = new ReassignableTelemetryReporter(new NullTelemetryReporter());
79const appName = "react-native-debug-adapter";
80new EntryPointHandler(ProcessType.Debugger).runApp(appName, () => version,
81 ErrorHelper.getInternalError(InternalErrorCode.DebuggingFailed), telemetryReporter, () => {
82 let nodeDebugFolder: string;
83 let vscodeDebugAdapterPackage: typeof VSCodeDebugAdapter;
84
85 // nodeDebugLocation.json is dynamically generated on extension activation.
86 // If it fails, we must not have been in a react native project
87 try {
88 /* tslint:disable:no-var-requires */
89 nodeDebugFolder = require("./nodeDebugLocation.json").nodeDebugPath;
90 vscodeDebugAdapterPackage = require(path.join(nodeDebugFolder, "node_modules", "vscode-debugadapter"));
91 /* tslint:enable:no-var-requires */
92 } catch (e) {
93 // Nothing we can do here: can't even communicate back because we don't know how to speak debug adapter
94 bailOut("cannotFindDebugAdapter");
95 }
96
97 // Temporarily dummy out the DebugSession.run function so we do not start the debug adapter until we are ready
98 const originalDebugSessionRun = vscodeDebugAdapterPackage.DebugSession.run;
99 vscodeDebugAdapterPackage.DebugSession.run = function() { };
100
101 let nodeDebug: { NodeDebugSession: typeof NodeDebugSession };
102
103 try {
104 /* tslint:disable:no-var-requires */
105 nodeDebug = require(path.join(nodeDebugFolder, "out", "node", "nodeDebug"));
106 /* tslint:enable:no-var-requires */
107 } catch (e) {
108 // Unable to find nodeDebug, but we can make our own communication channel now
109 const debugSession = new vscodeDebugAdapterPackage.DebugSession();
110 // Note: this will not work in the context of debugging the debug adapter and communicating over a socket,
111 // but in that case we have much better ways to investigate errors.
112 debugSession.start(process.stdin, process.stdout);
113 debugSession.sendEvent(new vscodeDebugAdapterPackage.OutputEvent("Unable to start debug adapter: " + e.toString(), "stderr"));
114 debugSession.sendEvent(new vscodeDebugAdapterPackage.TerminatedEvent());
115
116 bailOut("cannotFindNodeDebugAdapter");
117 }
118
119 vscodeDebugAdapterPackage.DebugSession.run = originalDebugSessionRun;
120
121 // Intecept the "launchRequest" instance method of NodeDebugSession to interpret arguments
122 const originalNodeDebugSessionLaunchRequest = nodeDebug.NodeDebugSession.prototype.launchRequest;
123 nodeDebug.NodeDebugSession.prototype.launchRequest = function(request: any, args: ILaunchArgs) {
124 projectRootPath = path.resolve(args.program, "../..");
125 telemetryReporter.reassignTo(new ExtensionTelemetryReporter( // We start to send telemetry
126 appName, version, Telemetry.APPINSIGHTS_INSTRUMENTATIONKEY, projectRootPath));
127
128 // Create a server waiting for messages to re-initialize the debug session;
129 const reinitializeServer = http.createServer((req, res) => {
130 res.statusCode = 404;
131 if (req.url === "/refreshBreakpoints") {
132 res.statusCode = 200;
133 if (this) {
134 const sourceMaps = this._sourceMaps;
135 if (sourceMaps) {
136 // Flush any cached source maps
137 sourceMaps._allSourceMaps = {};
138 sourceMaps._generatedToSourceMaps = {};
139 sourceMaps._sourceToGeneratedMaps = {};
140 }
141 // Send an "initialized" event to trigger breakpoints to be re-sent
142 this.sendEvent(new vscodeDebugAdapterPackage.InitializedEvent());
143 }
144 }
145 res.end();
146 });
147 const debugServerListeningPort = parseInt(args.internalDebuggerPort, 10) || 9090;
148
149
150 reinitializeServer.listen(debugServerListeningPort);
151 reinitializeServer.on("error", (err: Error) => {
152 TelemetryHelper.sendSimpleEvent("reinitializeServerError");
153 this.sendEvent(new vscodeDebugAdapterPackage.OutputEvent("Error in debug adapter server: " + err.toString(), "stderr"));
154 this.sendEvent(new vscodeDebugAdapterPackage.OutputEvent("Breakpoints may not update. Consider restarting and specifying a different 'internalDebuggerPort' in launch.json"));
155 });
156
157 // We do not permit arbitrary args to be passed to our process
158 args.args = [
159 args.platform,
160 debugServerListeningPort.toString(),
161 args.target || "simulator",
162 ];
163
164 if (!isNullOrUndefined(args.logCatArguments)) { // We add the parameter if it's defined (adapter crashes otherwise)
165 args.args = args.args.concat([parseLogCatArguments(args.logCatArguments)]);
166 }
167
168 originalNodeDebugSessionLaunchRequest.call(this, request, args);
169 };
170
171 // Intecept the "launchRequest" instance method of NodeDebugSession to interpret arguments
172 const originalNodeDebugSessionDisconnectRequest = nodeDebug.NodeDebugSession.prototype.disconnectRequest;
173 function customDisconnectRequest(response: any, args: any): void {
174 try {
175 // First we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
176 const remoteExtension = new RemoteExtension(projectRootPath);
177 remoteExtension.stopMonitoringLocat()
178 .finally(() => originalNodeDebugSessionDisconnectRequest.call(this, response, args))
179 .done(() => { }, reason => // We just print a warning if something fails
180 process.stderr.write(`WARNING: Couldn't stop monitoring logcat: ${reason.message || reason}\n`));
181 } catch (exception) {
182 // This is a "nice to have" feature, so we just fire the message and forget. We don't event handle
183 // errors in the response promise
184 process.stderr.write(`WARNING: Couldn't stop monitoring logcat. Sync exception: ${exception.message || exception}\n`);
185 originalNodeDebugSessionDisconnectRequest.call(this, response, args);
186 }
187 }
188 nodeDebug.NodeDebugSession.prototype.disconnectRequest = customDisconnectRequest;
189
190 vscodeDebugAdapterPackage.DebugSession.run(nodeDebug.NodeDebugSession);
191 });
192