microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1.12.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

309lines · 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 path from "path";
5import * as fs from "fs";
6import * as vscode from "vscode";
7import { LoggingDebugSession, Logger, logger, ErrorDestination } from "@vscode/debugadapter";
8import { DebugProtocol } from "vscode-debugprotocol";
9import * as nls from "vscode-nls";
10import { stripJsonTrailingComma } from "../common/utils";
11import { getLoggingDirectory, LogHelper, LogLevel } from "../extension/log/LogHelper";
12import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
13import { ErrorHelper } from "../common/error/errorHelper";
14import { InternalErrorCode } from "../common/error/internalErrorCode";
15import { InternalError, NestedError } from "../common/error/internalError";
16import { ILaunchArgs, IRunOptions, PlatformType } from "../extension/launchArgs";
17import { AppLauncher } from "../extension/appLauncher";
18import { RNPackageVersions } from "../common/projectVersionHelper";
19import { SettingsHelper } from "../extension/settingsHelper";
20import { OutputChannelLogger } from "../extension/log/OutputChannelLogger";
21import { RNSession } from "./debugSessionWrapper";
22
23nls.config({
24 messageFormat: nls.MessageFormat.bundle,
25 bundleFormat: nls.BundleFormat.standalone,
26})();
27const localize = nls.loadMessageBundle();
28
29/**
30 * Enum of possible statuses of debug session
31 */
32export enum DebugSessionStatus {
33 /** A session has been just created */
34 FirstConnection,
35 /** This status is required in order to exclude the possible creation of several debug sessions at the first start */
36 FirstConnectionPending,
37 /** This status means that an application can be reloaded */
38 ConnectionAllowed,
39 /** This status means that an application is reloading now, and we shouldn't terminate the current debug session */
40 ConnectionPending,
41 /** A debuggee connected successfully */
42 ConnectionDone,
43 /** A debuggee failed to connect */
44 ConnectionFailed,
45 /** The session is handling disconnect request now */
46 Stopping,
47 /** The session is stopped */
48 Stopped,
49}
50
51export interface TerminateEventArgs {
52 debugSession: vscode.DebugSession;
53 args: any;
54}
55
56export interface IAttachRequestArgs
57 extends DebugProtocol.AttachRequestArguments,
58 IRunOptions,
59 vscode.DebugConfiguration {
60 webkitRangeMax: number;
61 webkitRangeMin: number;
62 cwd: string /* Automatically set by VS Code to the currently opened folder */;
63 port: number;
64 url?: string;
65 useHermesEngine: boolean;
66 address?: string;
67 trace?: string;
68 skipFiles?: [];
69 sourceMaps?: boolean;
70 sourceMapPathOverrides?: { [key: string]: string };
71 jsDebugTrace?: boolean;
72 browserTarget?: string;
73}
74
75export interface ILaunchRequestArgs
76 extends DebugProtocol.LaunchRequestArguments,
77 IAttachRequestArgs {}
78
79export abstract class DebugSessionBase extends LoggingDebugSession {
80 protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> =
81 new vscode.EventEmitter<TerminateEventArgs>();
82 public static readonly onDidTerminateRootDebugSession =
83 DebugSessionBase.rootSessionTerminatedEventEmitter.event;
84
85 protected readonly stopCommand: string;
86 protected readonly terminateCommand: string;
87 protected readonly pwaNodeSessionName: string;
88
89 protected appLauncher: AppLauncher;
90 protected projectRootPath: string;
91 protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
92 protected previousAttachArgs: IAttachRequestArgs;
93 protected cdpProxyLogLevel: LogLevel;
94 protected debugSessionStatus: DebugSessionStatus;
95 protected nodeSession: vscode.DebugSession | null;
96 protected rnSession: RNSession;
97 protected vsCodeDebugSession: vscode.DebugSession;
98 protected cancellationTokenSource: vscode.CancellationTokenSource;
99
100 constructor(rnSession: RNSession) {
101 super();
102
103 // constants definition
104 this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
105 this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button
106 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
107
108 // variables definition
109 this.rnSession = rnSession;
110 this.vsCodeDebugSession = rnSession.vsCodeDebugSession;
111 this.isSettingsInitialized = false;
112 this.debugSessionStatus = DebugSessionStatus.FirstConnection;
113 this.cancellationTokenSource = new vscode.CancellationTokenSource();
114 this.nodeSession = null;
115 }
116
117 protected initializeRequest(
118 response: DebugProtocol.InitializeResponse,
119 // eslint-disable-next-line @typescript-eslint/no-unused-vars
120 args: DebugProtocol.InitializeRequestArguments,
121 ): void {
122 response.body = response.body || {};
123
124 response.body.supportsConfigurationDoneRequest = true;
125 response.body.supportsEvaluateForHovers = true;
126 response.body.supportTerminateDebuggee = true;
127 response.body.supportsCancelRequest = true;
128
129 this.sendResponse(response);
130 }
131
132 protected abstract establishDebugSession(
133 attachArgs: IAttachRequestArgs,
134 resolve?: (value?: void | PromiseLike<void> | undefined) => void,
135 ): void;
136
137 protected async initializeSettings(args: any): Promise<void> {
138 if (!this.isSettingsInitialized) {
139 let chromeDebugCoreLogs = getLoggingDirectory();
140 if (chromeDebugCoreLogs) {
141 chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt");
142 }
143 let logLevel: string = args.trace;
144 if (logLevel) {
145 logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
146 logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false);
147 this.cdpProxyLogLevel =
148 LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
149 } else {
150 logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
151 this.cdpProxyLogLevel =
152 LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
153 }
154
155 if (typeof args.sourceMaps !== "boolean") {
156 args.sourceMaps = true;
157 }
158
159 if (typeof args.enableDebug !== "boolean") {
160 args.enableDebug = true;
161 }
162
163 // Now there is a problem with processing time of 'createFromSourceMap' function of js-debug
164 // So we disable this functionality by default https://github.com/microsoft/vscode-js-debug/issues/1033
165 if (typeof args.sourceMapRenames !== "boolean") {
166 args.sourceMapRenames = false;
167 }
168
169 const projectRootPath = SettingsHelper.getReactNativeProjectRoot(args.cwd);
170 const isReactProject = await ReactNativeProjectHelper.isReactNativeProject(
171 projectRootPath,
172 );
173 if (!isReactProject) {
174 throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError);
175 }
176
177 const appLauncher = await AppLauncher.getOrCreateAppLauncherByProjectRootPath(
178 projectRootPath,
179 );
180 this.appLauncher = appLauncher;
181 this.projectRootPath = projectRootPath;
182 this.isSettingsInitialized = true;
183 this.appLauncher.getOrUpdateNodeModulesRoot(true);
184 if (this.vsCodeDebugSession.workspaceFolder) {
185 this.appLauncher.updateDebugConfigurationRoot(
186 this.vsCodeDebugSession.workspaceFolder.uri.fsPath,
187 );
188 }
189 const settingsPort = this.appLauncher.getPackagerPort(projectRootPath);
190 if (this.appLauncher.getPackager().getPort() != settingsPort) {
191 this.appLauncher.getPackager().resetToSettingsPort();
192 }
193 }
194 }
195
196 protected async disconnectRequest(
197 response: DebugProtocol.DisconnectResponse,
198 args: DebugProtocol.DisconnectArguments,
199 // eslint-disable-next-line @typescript-eslint/no-unused-vars
200 request?: DebugProtocol.Request,
201 ): Promise<void> {
202 if (this.appLauncher) {
203 await this.appLauncher.getRnCdpProxy().stopServer();
204 }
205
206 this.cancellationTokenSource.cancel();
207 this.cancellationTokenSource.dispose();
208
209 // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
210 if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) {
211 try {
212 this.appLauncher.getMobilePlatform().dispose();
213 } catch (err) {
214 logger.warn(
215 localize(
216 "CouldNotStopMonitoringLogcat",
217 "Couldn't stop monitoring logcat: {0}",
218 err.message || err,
219 ),
220 );
221 }
222 }
223
224 this.debugSessionStatus = DebugSessionStatus.Stopped;
225 await logger.dispose();
226
227 DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
228 debugSession: this.vsCodeDebugSession,
229 args: {
230 forcedStop: !!(<any>args).forcedStop,
231 },
232 });
233
234 this.sendResponse(response);
235 }
236
237 protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void {
238 // We can't print error messages after the debugging session is stopped. This could break the extension work.
239 if (
240 (error instanceof InternalError || error instanceof NestedError) &&
241 error.errorCode === InternalErrorCode.CancellationTokenTriggered
242 ) {
243 return;
244 }
245
246 logger.error(error.message);
247
248 this.sendErrorResponse(
249 response,
250 { format: error.message, id: 1 },
251 undefined,
252 undefined,
253 ErrorDestination.User,
254 );
255 }
256
257 protected async preparePackagerBeforeAttach(
258 args: IAttachRequestArgs,
259 reactNativeVersions: RNPackageVersions,
260 ): Promise<void> {
261 if (!(await this.appLauncher.getPackager().isRunning())) {
262 const runOptions: ILaunchArgs = Object.assign(
263 { reactNativeVersions },
264 this.appLauncher.prepareBaseRunOptions(args),
265 );
266 this.appLauncher.getPackager().setRunOptions(runOptions);
267 await this.appLauncher.getPackager().start();
268 }
269 }
270
271 protected showError(error: Error): void {
272 void vscode.window.showErrorMessage(error.message, {
273 modal: true,
274 });
275 // We can't print error messages via debug session logger after the session is stopped. This could break the extension work.
276 if (this.debugSessionStatus === DebugSessionStatus.Stopped) {
277 OutputChannelLogger.getMainChannel().error(error.message);
278 return;
279 }
280 logger.error(error.message);
281 }
282
283 protected async terminate(): Promise<void> {
284 await vscode.commands.executeCommand(this.stopCommand, undefined, {
285 sessionId: this.vsCodeDebugSession.id,
286 });
287 }
288}
289
290/**
291 * Parses settings.json file for workspace root property
292 */
293export function getProjectRoot(args: any): string {
294 const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
295 const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
296 try {
297 const settingsContent = fs.readFileSync(settingsPath, "utf8");
298 const parsedSettings = stripJsonTrailingComma(settingsContent);
299 const projectRootPath =
300 parsedSettings["react-native-tools.projectRoot"] ||
301 parsedSettings["react-native-tools"].projectRoot;
302 return path.resolve(vsCodeRoot, projectRootPath);
303 } catch (e) {
304 logger.verbose(
305 `${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`,
306 );
307 return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
308 }
309}
310