microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
280c07463f45573fc0cd19fc2d2eb91eb3e828fd

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/nodeDebugWrapper.ts

247lines · 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 http from "http";
7
8import {Telemetry} from "../common/telemetry";
9import {TelemetryHelper} from "../common/telemetryHelper";
10import {RemoteExtension} from "../common/remoteExtension";
11import {IOSPlatform} from "./ios/iOSPlatform";
12import {PlatformResolver} from "./platformResolver";
13import {IRunOptions} from "../common/launchArgs";
14import {TargetPlatformHelper} from "../common/targetPlatformHelper";
15import {ExtensionTelemetryReporter, ReassignableTelemetryReporter} from "../common/telemetryReporters";
16import {NodeDebugAdapterLogger} from "../common/log/loggers";
17import {Log} from "../common/log/log";
18import {GeneralMobilePlatform} from "../common/generalMobilePlatform";
19
20export class NodeDebugWrapper {
21 private projectRootPath: string;
22 private remoteExtension: RemoteExtension;
23 private telemetryReporter: ReassignableTelemetryReporter;
24 private appName: string;
25 private version: string;
26 private mobilePlatformOptions: IRunOptions;
27
28 private vscodeDebugAdapterPackage: typeof VSCodeDebugAdapter;
29 private nodeDebugSession: typeof NodeDebugSession;
30 private originalLaunchRequest: (response: any, args: any) => void;
31
32 public constructor(appName: string, version: string, telemetryReporter: ReassignableTelemetryReporter, debugAdapter: typeof VSCodeDebugAdapter, debugSession: typeof NodeDebugSession) {
33 this.appName = appName;
34 this.version = version;
35 this.telemetryReporter = telemetryReporter;
36 this.vscodeDebugAdapterPackage = debugAdapter;
37 this.nodeDebugSession = debugSession;
38 this.originalLaunchRequest = this.nodeDebugSession.prototype.launchRequest;
39 }
40
41 /**
42 * Calls customize methods for all requests needed
43 */
44 public customizeNodeAdapterRequests(): void {
45 this.customizeLaunchRequest();
46 this.customizeAttachRequest();
47 this.customizeDisconnectRequest();
48 }
49
50 /**
51 * Intecept the "launchRequest" instance method of NodeDebugSession to interpret arguments.
52 * Launch should:
53 * - Run the packager if needed
54 * - Compile and run application
55 * - Prewarm bundle
56 */
57 private customizeLaunchRequest(): void {
58 const nodeDebugWrapper = this;
59 this.nodeDebugSession.prototype.launchRequest = function (request: any, args: ILaunchRequestArgs) {
60 nodeDebugWrapper.requestSetup(this, args);
61 nodeDebugWrapper.mobilePlatformOptions.target = args.target || "simulator";
62 nodeDebugWrapper.mobilePlatformOptions.iosRelativeProjectPath = !nodeDebugWrapper.isNullOrUndefined(args.iosRelativeProjectPath) ?
63 args.iosRelativeProjectPath :
64 IOSPlatform.DEFAULT_IOS_PROJECT_RELATIVE_PATH;
65
66 // We add the parameter if it's defined (adapter crashes otherwise)
67 if (!nodeDebugWrapper.isNullOrUndefined(args.logCatArguments)) {
68 nodeDebugWrapper.mobilePlatformOptions.logCatArguments = [nodeDebugWrapper.parseLogCatArguments(args.logCatArguments)];
69 }
70
71 return TelemetryHelper.generate("launch", (generator) => {
72 const resolver = new PlatformResolver();
73 return nodeDebugWrapper.remoteExtension.getPackagerPort()
74 .then(packagerPort => {
75 nodeDebugWrapper.mobilePlatformOptions.packagerPort = packagerPort;
76 const mobilePlatform = resolver.resolveMobilePlatform(args.platform, nodeDebugWrapper.mobilePlatformOptions);
77 return Q({})
78 .then(() => {
79 generator.step("checkPlatformCompatibility");
80 TargetPlatformHelper.checkTargetPlatformSupport(nodeDebugWrapper.mobilePlatformOptions.platform);
81 generator.step("startPackager");
82 return mobilePlatform.startPackager();
83 })
84 .then(() => {
85 // We've seen that if we don't prewarm the bundle cache, the app fails on the first attempt to connect to the debugger logic
86 // and the user needs to Reload JS manually. We prewarm it to prevent that issue
87 generator.step("prewarmBundleCache");
88 Log.logMessage("Prewarming bundle cache. This may take a while ...");
89 return mobilePlatform.prewarmBundleCache();
90 })
91 .then(() => {
92 generator.step("mobilePlatform.runApp");
93 Log.logMessage("Building and running application.");
94 return mobilePlatform.runApp();
95 })
96 .then(() =>
97 nodeDebugWrapper.attachRequest(this, request, args, mobilePlatform));
98 }).catch(error =>
99 nodeDebugWrapper.bailOut(this, error.message));
100 });
101 };
102 }
103
104 /**
105 * Intecept the "attachRequest" instance method of NodeDebugSession to interpret arguments
106 */
107 private customizeAttachRequest(): void {
108 const nodeDebugWrapper = this;
109 this.nodeDebugSession.prototype.attachRequest = function (request: any, args: IAttachRequestArgs) {
110 nodeDebugWrapper.requestSetup(this, args);
111 nodeDebugWrapper.attachRequest(this, request, args, new GeneralMobilePlatform(nodeDebugWrapper.mobilePlatformOptions));
112 };
113 }
114
115 /**
116 * Intecept the "disconnectRequest" instance method of NodeDebugSession to interpret arguments
117 */
118 private customizeDisconnectRequest(): void {
119 const originalRequest = this.nodeDebugSession.prototype.disconnectRequest;
120 const nodeDebugWrapper = this;
121
122 this.nodeDebugSession.prototype.disconnectRequest = function (response: any, args: any): void {
123 // First we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
124
125 if (nodeDebugWrapper.mobilePlatformOptions.platform === "android") {
126 nodeDebugWrapper.remoteExtension.stopMonitoringLogcat()
127 .catch(reason =>
128 Log.logError(`WARNING: Couldn't stop monitoring logcat: ${reason.message || reason}\n`))
129 .finally(() =>
130 originalRequest.call(this, response, args));
131 } else {
132 originalRequest.call(this, response, args);
133 }
134 };
135 }
136
137 /**
138 * Makes the required setup for request customization
139 * - Enables telemetry
140 * - Sets up mobilePlatformOptions, remote extension and projectRootPath
141 * - Starts debug server
142 * - Create global logger
143 */
144 private requestSetup(debugSession: NodeDebugSession, args: any) {
145 this.projectRootPath = path.resolve(args.program, "../..");
146 this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath);
147 this.mobilePlatformOptions = {
148 projectRoot: this.projectRootPath,
149 platform: args.platform,
150 };
151
152 // Start to send telemetry
153 this.telemetryReporter.reassignTo(new ExtensionTelemetryReporter(
154 this.appName, this.version, Telemetry.APPINSIGHTS_INSTRUMENTATIONKEY, this.projectRootPath));
155
156 // Create a server waiting for messages to re-initialize the debug session;
157 const debugServerListeningPort = this.createReinitializeServer(debugSession, args.internalDebuggerPort);
158 args.args = [debugServerListeningPort.toString()];
159
160 Log.SetGlobalLogger(new NodeDebugAdapterLogger(this.vscodeDebugAdapterPackage, debugSession));
161 }
162
163 /**
164 * Runs logic needed to attach.
165 * Attach should:
166 * - Enable js debugging
167 */
168 private attachRequest(debugSession: NodeDebugSession, request: any, args: any, mobilePlatform: any): Q.Promise<void> {
169 return TelemetryHelper.generate("attach", (generator) => {
170 return Q({})
171 .then(() => {
172 generator.step("mobilePlatform.enableJSDebuggingMode");
173 if (mobilePlatform) {
174 return mobilePlatform.enableJSDebuggingMode();
175 } else {
176 Log.logMessage("Debugger ready. Enable remote debugging in app.");
177 }
178 }).then(() =>
179 this.originalLaunchRequest.call(debugSession, request, args))
180 .catch(error =>
181 this.bailOut(debugSession, error.message));
182 });
183 }
184
185 /**
186 * Creates internal debug server and returns the port that the server is hook up into.
187 */
188 private createReinitializeServer(debugSession: NodeDebugSession, internalDebuggerPort: string): number {
189 // Create the server
190 const server = http.createServer((req, res) => {
191 res.statusCode = 404;
192 if (req.url === "/refreshBreakpoints") {
193 res.statusCode = 200;
194 if (debugSession) {
195 const sourceMaps = debugSession._sourceMaps;
196 if (sourceMaps) {
197 // Flush any cached source maps
198 sourceMaps._allSourceMaps = {};
199 sourceMaps._generatedToSourceMaps = {};
200 sourceMaps._sourceToGeneratedMaps = {};
201 }
202 // Send an "initialized" event to trigger breakpoints to be re-sent
203 debugSession.sendEvent(new this.vscodeDebugAdapterPackage.InitializedEvent());
204 }
205 }
206 res.end();
207 });
208
209 // Setup listen port and on error response
210 const port = parseInt(internalDebuggerPort, 10) || 9090;
211
212 server.listen(port);
213 server.on("error", (err: Error) => {
214 TelemetryHelper.sendSimpleEvent("reinitializeServerError");
215 Log.logError("Error in debug adapter server: " + err.toString());
216 Log.logMessage("Breakpoints may not update. Consider restarting and specifying a different 'internalDebuggerPort' in launch.json");
217 });
218
219 // Return listen port
220 return port;
221 }
222
223 /**
224 * Logs error to user and finishes the debugging process.
225 */
226 private bailOut(debugSession: NodeDebugSession, message: string): void {
227 Log.logError(`Could not debug. ${message}`);
228 debugSession.sendEvent(new this.vscodeDebugAdapterPackage.TerminatedEvent());
229 process.exit(1);
230 }
231
232 /**
233 * Parses log cat arguments to a string
234 */
235 private parseLogCatArguments(userProvidedLogCatArguments: any): string {
236 return Array.isArray(userProvidedLogCatArguments)
237 ? userProvidedLogCatArguments.join(" ") // If it's an array, we join the arguments
238 : userProvidedLogCatArguments; // If not, we leave it as-is
239 }
240
241 /**
242 * Helper method to know if a value is either null or undefined
243 */
244 private isNullOrUndefined(value: any): boolean {
245 return typeof value === "undefined" || value === null;
246 }
247}