microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
60ad4ec06bdc0f0e5e8c8114e1cc685f1dbc2568

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

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