microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/debugSessionBase.ts
330lines · 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 | |
| 4 | import * as path from "path"; |
| 5 | import * as fs from "fs"; |
| 6 | import * as vscode from "vscode"; |
| 7 | import { LoggingDebugSession, Logger, logger, ErrorDestination } from "@vscode/debugadapter"; |
| 8 | import { DebugProtocol } from "vscode-debugprotocol"; |
| 9 | import * as nls from "vscode-nls"; |
| 10 | import { stripJsonTrailingComma } from "../common/utils"; |
| 11 | import { getLoggingDirectory, LogHelper, LogLevel } from "../extension/log/LogHelper"; |
| 12 | import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper"; |
| 13 | import { ErrorHelper } from "../common/error/errorHelper"; |
| 14 | import { InternalErrorCode } from "../common/error/internalErrorCode"; |
| 15 | import { InternalError, NestedError } from "../common/error/internalError"; |
| 16 | import { ILaunchArgs, IRunOptions, PlatformType } from "../extension/launchArgs"; |
| 17 | import { AppLauncher } from "../extension/appLauncher"; |
| 18 | import { RNPackageVersions } from "../common/projectVersionHelper"; |
| 19 | import { SettingsHelper } from "../extension/settingsHelper"; |
| 20 | import { OutputChannelLogger } from "../extension/log/OutputChannelLogger"; |
| 21 | import { RNSession } from "./debugSessionWrapper"; |
| 22 | |
| 23 | nls.config({ |
| 24 | messageFormat: nls.MessageFormat.bundle, |
| 25 | bundleFormat: nls.BundleFormat.standalone, |
| 26 | })(); |
| 27 | const localize = nls.loadMessageBundle(); |
| 28 | |
| 29 | /** |
| 30 | * Enum of possible statuses of debug session |
| 31 | */ |
| 32 | export 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 | |
| 51 | export interface TerminateEventArgs { |
| 52 | debugSession: vscode.DebugSession; |
| 53 | args: any; |
| 54 | } |
| 55 | |
| 56 | export 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 | |
| 75 | export interface ILaunchRequestArgs |
| 76 | extends DebugProtocol.LaunchRequestArguments, |
| 77 | IAttachRequestArgs {} |
| 78 | |
| 79 | export 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 | response.body.exceptionBreakpointFilters = [ |
| 130 | { |
| 131 | filter: "all", |
| 132 | label: "Caught Exceptions", |
| 133 | default: false, |
| 134 | supportsCondition: true, |
| 135 | description: "Breaks on all throw errors, even if they're caught later.", |
| 136 | // eslint-disable-next-line @typescript-eslint/quotes |
| 137 | conditionDescription: 'error.name == "MyError"', |
| 138 | }, |
| 139 | { |
| 140 | filter: "uncaught", |
| 141 | label: "Uncaught Exceptions", |
| 142 | default: false, |
| 143 | supportsCondition: true, |
| 144 | description: "Breaks only on errors or promise rejections that are not handled.", |
| 145 | // eslint-disable-next-line @typescript-eslint/quotes |
| 146 | conditionDescription: 'error.name == "MyError"', |
| 147 | }, |
| 148 | ]; |
| 149 | |
| 150 | this.sendResponse(response); |
| 151 | } |
| 152 | |
| 153 | protected abstract establishDebugSession( |
| 154 | attachArgs: IAttachRequestArgs, |
| 155 | resolve?: (value?: void | PromiseLike<void> | undefined) => void, |
| 156 | ): void; |
| 157 | |
| 158 | protected async initializeSettings(args: any): Promise<void> { |
| 159 | if (!this.isSettingsInitialized) { |
| 160 | let chromeDebugCoreLogs = getLoggingDirectory(); |
| 161 | if (chromeDebugCoreLogs) { |
| 162 | chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt"); |
| 163 | } |
| 164 | let logLevel: string = args.trace; |
| 165 | if (logLevel) { |
| 166 | logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase()); |
| 167 | logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false); |
| 168 | this.cdpProxyLogLevel = |
| 169 | LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None; |
| 170 | } else { |
| 171 | logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false); |
| 172 | this.cdpProxyLogLevel = |
| 173 | LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None; |
| 174 | } |
| 175 | |
| 176 | if (typeof args.sourceMaps !== "boolean") { |
| 177 | args.sourceMaps = true; |
| 178 | } |
| 179 | |
| 180 | if (typeof args.enableDebug !== "boolean") { |
| 181 | args.enableDebug = true; |
| 182 | } |
| 183 | |
| 184 | // Now there is a problem with processing time of 'createFromSourceMap' function of js-debug |
| 185 | // So we disable this functionality by default https://github.com/microsoft/vscode-js-debug/issues/1033 |
| 186 | if (typeof args.sourceMapRenames !== "boolean") { |
| 187 | args.sourceMapRenames = false; |
| 188 | } |
| 189 | |
| 190 | const projectRootPath = SettingsHelper.getReactNativeProjectRoot(args.cwd); |
| 191 | const isReactProject = await ReactNativeProjectHelper.isReactNativeProject( |
| 192 | projectRootPath, |
| 193 | ); |
| 194 | if (!isReactProject) { |
| 195 | throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError); |
| 196 | } |
| 197 | |
| 198 | const appLauncher = await AppLauncher.getOrCreateAppLauncherByProjectRootPath( |
| 199 | projectRootPath, |
| 200 | ); |
| 201 | this.appLauncher = appLauncher; |
| 202 | this.projectRootPath = projectRootPath; |
| 203 | this.isSettingsInitialized = true; |
| 204 | this.appLauncher.getOrUpdateNodeModulesRoot(true); |
| 205 | if (this.vsCodeDebugSession.workspaceFolder) { |
| 206 | this.appLauncher.updateDebugConfigurationRoot( |
| 207 | this.vsCodeDebugSession.workspaceFolder.uri.fsPath, |
| 208 | ); |
| 209 | } |
| 210 | const settingsPort = this.appLauncher.getPackagerPort(projectRootPath); |
| 211 | if (this.appLauncher.getPackager().getPort() != settingsPort) { |
| 212 | this.appLauncher.getPackager().resetToSettingsPort(); |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | protected async disconnectRequest( |
| 218 | response: DebugProtocol.DisconnectResponse, |
| 219 | args: DebugProtocol.DisconnectArguments, |
| 220 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 221 | request?: DebugProtocol.Request, |
| 222 | ): Promise<void> { |
| 223 | if (this.appLauncher) { |
| 224 | await this.appLauncher.getRnCdpProxy().stopServer(); |
| 225 | } |
| 226 | |
| 227 | this.cancellationTokenSource.cancel(); |
| 228 | this.cancellationTokenSource.dispose(); |
| 229 | |
| 230 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session |
| 231 | if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) { |
| 232 | try { |
| 233 | this.appLauncher.getMobilePlatform().dispose(); |
| 234 | } catch (err) { |
| 235 | logger.warn( |
| 236 | localize( |
| 237 | "CouldNotStopMonitoringLogcat", |
| 238 | "Couldn't stop monitoring logcat: {0}", |
| 239 | err.message || err, |
| 240 | ), |
| 241 | ); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | this.debugSessionStatus = DebugSessionStatus.Stopped; |
| 246 | await logger.dispose(); |
| 247 | |
| 248 | DebugSessionBase.rootSessionTerminatedEventEmitter.fire({ |
| 249 | debugSession: this.vsCodeDebugSession, |
| 250 | args: { |
| 251 | forcedStop: !!(<any>args).forcedStop, |
| 252 | }, |
| 253 | }); |
| 254 | |
| 255 | this.sendResponse(response); |
| 256 | } |
| 257 | |
| 258 | protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void { |
| 259 | // We can't print error messages after the debugging session is stopped. This could break the extension work. |
| 260 | if ( |
| 261 | (error instanceof InternalError || error instanceof NestedError) && |
| 262 | error.errorCode === InternalErrorCode.CancellationTokenTriggered |
| 263 | ) { |
| 264 | return; |
| 265 | } |
| 266 | |
| 267 | logger.error(error.message); |
| 268 | |
| 269 | this.sendErrorResponse( |
| 270 | response, |
| 271 | { format: error.message, id: 1 }, |
| 272 | undefined, |
| 273 | undefined, |
| 274 | ErrorDestination.User, |
| 275 | ); |
| 276 | } |
| 277 | |
| 278 | protected async preparePackagerBeforeAttach( |
| 279 | args: IAttachRequestArgs, |
| 280 | reactNativeVersions: RNPackageVersions, |
| 281 | ): Promise<void> { |
| 282 | if (!(await this.appLauncher.getPackager().isRunning())) { |
| 283 | const runOptions: ILaunchArgs = Object.assign( |
| 284 | { reactNativeVersions }, |
| 285 | this.appLauncher.prepareBaseRunOptions(args), |
| 286 | ); |
| 287 | this.appLauncher.getPackager().setRunOptions(runOptions); |
| 288 | await this.appLauncher.getPackager().start(); |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | protected showError(error: Error): void { |
| 293 | void vscode.window.showErrorMessage(error.message, { |
| 294 | modal: true, |
| 295 | }); |
| 296 | // We can't print error messages via debug session logger after the session is stopped. This could break the extension work. |
| 297 | if (this.debugSessionStatus === DebugSessionStatus.Stopped) { |
| 298 | OutputChannelLogger.getMainChannel().error(error.message); |
| 299 | return; |
| 300 | } |
| 301 | logger.error(error.message); |
| 302 | } |
| 303 | |
| 304 | protected async terminate(): Promise<void> { |
| 305 | await vscode.commands.executeCommand(this.stopCommand, undefined, { |
| 306 | sessionId: this.vsCodeDebugSession.id, |
| 307 | }); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | /** |
| 312 | * Parses settings.json file for workspace root property |
| 313 | */ |
| 314 | export function getProjectRoot(args: any): string { |
| 315 | const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); |
| 316 | const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); |
| 317 | try { |
| 318 | const settingsContent = fs.readFileSync(settingsPath, "utf8"); |
| 319 | const parsedSettings = stripJsonTrailingComma(settingsContent); |
| 320 | const projectRootPath = |
| 321 | parsedSettings["react-native-tools.projectRoot"] || |
| 322 | parsedSettings["react-native-tools"].projectRoot; |
| 323 | return path.resolve(vsCodeRoot, projectRootPath); |
| 324 | } catch (e) { |
| 325 | logger.verbose( |
| 326 | `${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`, |
| 327 | ); |
| 328 | return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); |
| 329 | } |
| 330 | } |
| 331 | |