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