microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
ce5e88eec6f7cd03403994764507be96c6af4624

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/rnDebugSession.ts

241lines · 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 vscode from "vscode";
5import * as path from "path";
6import * as mkdirp from "mkdirp";
7import { logger } from "vscode-debugadapter";
8import { DebugProtocol } from "vscode-debugprotocol";
9import { ProjectVersionHelper } from "../common/projectVersionHelper";
10import { TelemetryHelper } from "../common/telemetryHelper";
11import { MultipleLifetimesAppWorker } from "./appWorker";
12import { RnCDPMessageHandler } from "../cdp-proxy/CDPMessageHandlers/rnCDPMessageHandler";
13import { DebugSessionBase, DebugSessionStatus, IAttachRequestArgs, ILaunchRequestArgs } from "./debugSessionBase";
14import { JsDebugConfigAdapter } from "./jsDebugConfigAdapter";
15import { ErrorHelper } from "../common/error/errorHelper";
16import { InternalErrorCode } from "../common/error/internalErrorCode";
17import * as nls from "vscode-nls";
18nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
19const localize = nls.loadMessageBundle();
20
21export class RNDebugSession extends DebugSessionBase {
22
23 private readonly terminateCommand: string;
24
25 private appWorker: MultipleLifetimesAppWorker | null;
26 private nodeSession: vscode.DebugSession | null;
27 private onDidStartDebugSessionHandler: vscode.Disposable;
28 private onDidTerminateDebugSessionHandler: vscode.Disposable;
29
30 constructor(session: vscode.DebugSession) {
31 super(session);
32
33 // constants definition
34 this.terminateCommand = "terminate"; // the "terminate" command is sent from the client to the debug adapter in order to give the debuggee a chance for terminating itself
35
36 // variables definition
37 this.appWorker = null;
38
39 this.onDidStartDebugSessionHandler = vscode.debug.onDidStartDebugSession(
40 this.handleStartDebugSession.bind(this)
41 );
42
43 this.onDidTerminateDebugSessionHandler = vscode.debug.onDidTerminateDebugSession(
44 this.handleTerminateDebugSession.bind(this)
45 );
46 }
47
48 protected async launchRequest(response: DebugProtocol.LaunchResponse, launchArgs: ILaunchRequestArgs, request?: DebugProtocol.Request): Promise<void> {
49 return new Promise<void>((resolve, reject) => this.initializeSettings(launchArgs)
50 .then(() => {
51 logger.log("Launching the application");
52 logger.verbose(`Launching the application: ${JSON.stringify(launchArgs, null , 2)}`);
53
54 this.appLauncher.launch(launchArgs)
55 .then(() => {
56 if (launchArgs.enableDebug) {
57 launchArgs.port = launchArgs.port || this.appLauncher.getPackagerPort(launchArgs.cwd);
58 this.attachRequest(response, launchArgs).then(() => {
59 resolve();
60 }).catch((e) => reject(e));
61 } else {
62 this.sendResponse(response);
63 resolve();
64 }
65 })
66 .catch((err) => {
67 reject(ErrorHelper.getInternalError(InternalErrorCode.ApplicationLaunchFailed, err.message || err));
68 });
69 })
70 .catch((err) => {
71 reject(ErrorHelper.getInternalError(InternalErrorCode.ApplicationLaunchFailed, err.message || err));
72 })
73 )
74 .catch(err => this.showError(err, response));
75 }
76
77 protected async attachRequest(response: DebugProtocol.AttachResponse, attachArgs: IAttachRequestArgs, request?: DebugProtocol.Request): Promise<void> {
78 let extProps = {
79 platform: {
80 value: attachArgs.platform,
81 isPii: false,
82 },
83 };
84
85 this.previousAttachArgs = attachArgs;
86 return new Promise<void>((resolve, reject) => this.initializeSettings(attachArgs)
87 .then(() => {
88 logger.log("Attaching to the application");
89 logger.verbose(`Attaching to the application: ${JSON.stringify(attachArgs, null , 2)}`);
90 return ProjectVersionHelper.getReactNativeVersions(attachArgs.cwd, true);
91 })
92 .then(versions => {
93 extProps = TelemetryHelper.addPropertyToTelemetryProperties(versions.reactNativeVersion, "reactNativeVersion", extProps);
94 if (!ProjectVersionHelper.isVersionError(versions.reactNativeWindowsVersion)) {
95 extProps = TelemetryHelper.addPropertyToTelemetryProperties(versions.reactNativeWindowsVersion, "reactNativeWindowsVersion", extProps);
96 }
97 return TelemetryHelper.generate("attach", extProps, (generator) => {
98 attachArgs.port = attachArgs.port || this.appLauncher.getPackagerPort(attachArgs.cwd);
99 return this.appLauncher.getRnCdpProxy().stopServer()
100 .then(() => this.appLauncher.getRnCdpProxy().initializeServer(new RnCDPMessageHandler(), this.cdpProxyLogLevel))
101 .then(() => {
102 logger.log(localize("StartingDebuggerAppWorker", "Starting debugger app worker."));
103
104 const sourcesStoragePath = path.join(this.projectRootPath, ".vscode", ".react");
105 // Create folder if not exist to avoid problems if
106 // RN project root is not a ${workspaceFolder}
107 mkdirp.sync(sourcesStoragePath);
108
109 // If launch is invoked first time, appWorker is undefined, so create it here
110 this.appWorker = new MultipleLifetimesAppWorker(
111 attachArgs,
112 sourcesStoragePath,
113 this.projectRootPath,
114 undefined
115 );
116 this.appLauncher.setAppWorker(this.appWorker);
117
118 this.appWorker.on("connected", (port: number) => {
119 if (this.cancellationTokenSource.token.isCancellationRequested) {
120 return this.appWorker?.stop();
121 }
122
123 logger.log(localize("DebuggerWorkerLoadedRuntimeOnPort", "Debugger worker loaded runtime on port {0}", port));
124
125 this.appLauncher.getRnCdpProxy().setApplicationTargetPort(port);
126
127 if (this.debugSessionStatus === DebugSessionStatus.ConnectionPending) {
128 return;
129 }
130
131 if (this.debugSessionStatus === DebugSessionStatus.FirstConnection) {
132 this.debugSessionStatus = DebugSessionStatus.FirstConnectionPending;
133 this.establishDebugSession(attachArgs, resolve);
134 } else if (this.debugSessionStatus === DebugSessionStatus.ConnectionAllowed) {
135 if (this.nodeSession) {
136 this.debugSessionStatus = DebugSessionStatus.ConnectionPending;
137 this.nodeSession.customRequest(this.terminateCommand);
138 }
139 }
140 });
141 if (this.cancellationTokenSource.token.isCancellationRequested) {
142 return this.appWorker.stop();
143 }
144 return this.appWorker.start();
145 });
146 });
147 })
148 .catch((err) => {
149 reject(ErrorHelper.getInternalError(InternalErrorCode.CouldNotAttachToDebugger, err.message || err));
150 })
151 )
152 .catch(err => this.showError(err, response));
153 }
154
155 protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): Promise<void> {
156 // The client is about to disconnect so first we need to stop app worker
157 if (this.appWorker) {
158 this.appWorker.stop();
159 }
160
161 this.onDidStartDebugSessionHandler.dispose();
162 this.onDidTerminateDebugSessionHandler.dispose();
163
164 super.disconnectRequest(response, args, request);
165 }
166
167 protected establishDebugSession(attachArgs: IAttachRequestArgs, resolve?: (value?: void | PromiseLike<void> | undefined) => void): void {
168 const attachConfiguration = JsDebugConfigAdapter.createDebuggingConfigForPureRN(
169 attachArgs,
170 this.appLauncher.getCdpProxyPort(),
171 this.session.id
172 );
173
174 vscode.debug.startDebugging(
175 this.appLauncher.getWorkspaceFolder(),
176 attachConfiguration,
177 {
178 parentSession: this.session,
179 consoleMode: vscode.DebugConsoleMode.MergeWithParent,
180 }
181 )
182 .then((childDebugSessionStarted: boolean) => {
183 if (childDebugSessionStarted) {
184 this.debugSessionStatus = DebugSessionStatus.ConnectionDone;
185 this.setConnectionAllowedIfPossible();
186 if (resolve) {
187 this.debugSessionStatus = DebugSessionStatus.ConnectionAllowed;
188 resolve();
189 }
190 } else {
191 this.debugSessionStatus = DebugSessionStatus.ConnectionFailed;
192 this.setConnectionAllowedIfPossible();
193 this.resetFirstConnectionStatus();
194 throw new Error("Cannot start child debug session");
195 }
196 },
197 err => {
198 this.debugSessionStatus = DebugSessionStatus.ConnectionFailed;
199 this.setConnectionAllowedIfPossible();
200 this.resetFirstConnectionStatus();
201 throw err;
202 });
203 }
204
205 private handleStartDebugSession(debugSession: vscode.DebugSession) {
206 if (
207 debugSession.configuration.rnDebugSessionId === this.session.id
208 && debugSession.type === this.pwaNodeSessionName
209 ) {
210 this.nodeSession = debugSession;
211 }
212 }
213
214 private handleTerminateDebugSession(debugSession: vscode.DebugSession) {
215 if (
216 debugSession.configuration.rnDebugSessionId === this.session.id
217 && debugSession.type === this.pwaNodeSessionName
218 ) {
219 if (this.debugSessionStatus === DebugSessionStatus.ConnectionPending) {
220 this.establishDebugSession(this.previousAttachArgs);
221 } else {
222 this.session.customRequest(this.disconnectCommand, {forcedStop: true});
223 }
224 }
225 }
226
227 private setConnectionAllowedIfPossible(): void {
228 if (
229 this.debugSessionStatus === DebugSessionStatus.ConnectionDone
230 || this.debugSessionStatus === DebugSessionStatus.ConnectionFailed
231 ) {
232 this.debugSessionStatus = DebugSessionStatus.ConnectionAllowed;
233 }
234 }
235
236 private resetFirstConnectionStatus(): void {
237 if (this.debugSessionStatus === DebugSessionStatus.FirstConnectionPending) {
238 this.debugSessionStatus = DebugSessionStatus.FirstConnection;
239 }
240 }
241}
242