microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/debugSessionBase.ts
303lines · 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 | } |
| 72 | |
| 73 | export interface ILaunchRequestArgs |
| 74 | extends DebugProtocol.LaunchRequestArguments, |
| 75 | IAttachRequestArgs {} |
| 76 | |
| 77 | export abstract class DebugSessionBase extends LoggingDebugSession { |
| 78 | protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = |
| 79 | new vscode.EventEmitter<TerminateEventArgs>(); |
| 80 | public static readonly onDidTerminateRootDebugSession = |
| 81 | DebugSessionBase.rootSessionTerminatedEventEmitter.event; |
| 82 | |
| 83 | protected readonly stopCommand: string; |
| 84 | protected readonly terminateCommand: string; |
| 85 | protected readonly pwaNodeSessionName: string; |
| 86 | |
| 87 | protected appLauncher: AppLauncher; |
| 88 | protected projectRootPath: string; |
| 89 | protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function |
| 90 | protected previousAttachArgs: IAttachRequestArgs; |
| 91 | protected cdpProxyLogLevel: LogLevel; |
| 92 | protected debugSessionStatus: DebugSessionStatus; |
| 93 | protected nodeSession: vscode.DebugSession | null; |
| 94 | protected rnSession: RNSession; |
| 95 | protected vsCodeDebugSession: vscode.DebugSession; |
| 96 | protected cancellationTokenSource: vscode.CancellationTokenSource; |
| 97 | |
| 98 | constructor(rnSession: RNSession) { |
| 99 | super(); |
| 100 | |
| 101 | // constants definition |
| 102 | this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension |
| 103 | this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button |
| 104 | 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 |
| 105 | |
| 106 | // variables definition |
| 107 | this.rnSession = rnSession; |
| 108 | this.vsCodeDebugSession = rnSession.vsCodeDebugSession; |
| 109 | this.isSettingsInitialized = false; |
| 110 | this.debugSessionStatus = DebugSessionStatus.FirstConnection; |
| 111 | this.cancellationTokenSource = new vscode.CancellationTokenSource(); |
| 112 | this.nodeSession = null; |
| 113 | } |
| 114 | |
| 115 | protected initializeRequest( |
| 116 | response: DebugProtocol.InitializeResponse, |
| 117 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 118 | args: DebugProtocol.InitializeRequestArguments, |
| 119 | ): void { |
| 120 | response.body = response.body || {}; |
| 121 | |
| 122 | response.body.supportsConfigurationDoneRequest = true; |
| 123 | response.body.supportsEvaluateForHovers = true; |
| 124 | response.body.supportTerminateDebuggee = true; |
| 125 | response.body.supportsCancelRequest = true; |
| 126 | |
| 127 | this.sendResponse(response); |
| 128 | } |
| 129 | |
| 130 | protected abstract establishDebugSession( |
| 131 | attachArgs: IAttachRequestArgs, |
| 132 | resolve?: (value?: void | PromiseLike<void> | undefined) => void, |
| 133 | ): void; |
| 134 | |
| 135 | protected async initializeSettings(args: any): Promise<void> { |
| 136 | if (!this.isSettingsInitialized) { |
| 137 | let chromeDebugCoreLogs = getLoggingDirectory(); |
| 138 | if (chromeDebugCoreLogs) { |
| 139 | chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt"); |
| 140 | } |
| 141 | let logLevel: string = args.trace; |
| 142 | if (logLevel) { |
| 143 | logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase()); |
| 144 | logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false); |
| 145 | this.cdpProxyLogLevel = |
| 146 | LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None; |
| 147 | } else { |
| 148 | logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false); |
| 149 | this.cdpProxyLogLevel = |
| 150 | LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None; |
| 151 | } |
| 152 | |
| 153 | if (typeof args.sourceMaps !== "boolean") { |
| 154 | args.sourceMaps = true; |
| 155 | } |
| 156 | |
| 157 | if (typeof args.enableDebug !== "boolean") { |
| 158 | args.enableDebug = true; |
| 159 | } |
| 160 | |
| 161 | // Now there is a problem with processing time of 'createFromSourceMap' function of js-debug |
| 162 | // So we disable this functionality by default https://github.com/microsoft/vscode-js-debug/issues/1033 |
| 163 | if (typeof args.sourceMapRenames !== "boolean") { |
| 164 | args.sourceMapRenames = false; |
| 165 | } |
| 166 | |
| 167 | const projectRootPath = SettingsHelper.getReactNativeProjectRoot(args.cwd); |
| 168 | const isReactProject = await ReactNativeProjectHelper.isReactNativeProject( |
| 169 | projectRootPath, |
| 170 | ); |
| 171 | if (!isReactProject) { |
| 172 | throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError); |
| 173 | } |
| 174 | |
| 175 | const appLauncher = await AppLauncher.getOrCreateAppLauncherByProjectRootPath( |
| 176 | projectRootPath, |
| 177 | ); |
| 178 | this.appLauncher = appLauncher; |
| 179 | this.projectRootPath = projectRootPath; |
| 180 | this.isSettingsInitialized = true; |
| 181 | this.appLauncher.getOrUpdateNodeModulesRoot(true); |
| 182 | if (this.vsCodeDebugSession.workspaceFolder) { |
| 183 | this.appLauncher.updateDebugConfigurationRoot( |
| 184 | this.vsCodeDebugSession.workspaceFolder.uri.fsPath, |
| 185 | ); |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | protected async disconnectRequest( |
| 191 | response: DebugProtocol.DisconnectResponse, |
| 192 | args: DebugProtocol.DisconnectArguments, |
| 193 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 194 | request?: DebugProtocol.Request, |
| 195 | ): Promise<void> { |
| 196 | if (this.appLauncher) { |
| 197 | await this.appLauncher.getRnCdpProxy().stopServer(); |
| 198 | } |
| 199 | |
| 200 | this.cancellationTokenSource.cancel(); |
| 201 | this.cancellationTokenSource.dispose(); |
| 202 | |
| 203 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session |
| 204 | if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) { |
| 205 | try { |
| 206 | this.appLauncher.getMobilePlatform().dispose(); |
| 207 | } catch (err) { |
| 208 | logger.warn( |
| 209 | localize( |
| 210 | "CouldNotStopMonitoringLogcat", |
| 211 | "Couldn't stop monitoring logcat: {0}", |
| 212 | err.message || err, |
| 213 | ), |
| 214 | ); |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | this.debugSessionStatus = DebugSessionStatus.Stopped; |
| 219 | await logger.dispose(); |
| 220 | |
| 221 | DebugSessionBase.rootSessionTerminatedEventEmitter.fire({ |
| 222 | debugSession: this.vsCodeDebugSession, |
| 223 | args: { |
| 224 | forcedStop: !!(<any>args).forcedStop, |
| 225 | }, |
| 226 | }); |
| 227 | |
| 228 | this.sendResponse(response); |
| 229 | } |
| 230 | |
| 231 | protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void { |
| 232 | // We can't print error messages after the debugging session is stopped. This could break the extension work. |
| 233 | if ( |
| 234 | (error instanceof InternalError || error instanceof NestedError) && |
| 235 | error.errorCode === InternalErrorCode.CancellationTokenTriggered |
| 236 | ) { |
| 237 | return; |
| 238 | } |
| 239 | |
| 240 | logger.error(error.message); |
| 241 | |
| 242 | this.sendErrorResponse( |
| 243 | response, |
| 244 | { format: error.message, id: 1 }, |
| 245 | undefined, |
| 246 | undefined, |
| 247 | ErrorDestination.User, |
| 248 | ); |
| 249 | } |
| 250 | |
| 251 | protected async preparePackagerBeforeAttach( |
| 252 | args: IAttachRequestArgs, |
| 253 | reactNativeVersions: RNPackageVersions, |
| 254 | ): Promise<void> { |
| 255 | if (!(await this.appLauncher.getPackager().isRunning())) { |
| 256 | const runOptions: ILaunchArgs = Object.assign( |
| 257 | { reactNativeVersions }, |
| 258 | this.appLauncher.prepareBaseRunOptions(args), |
| 259 | ); |
| 260 | this.appLauncher.getPackager().setRunOptions(runOptions); |
| 261 | await this.appLauncher.getPackager().start(); |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | protected showError(error: Error): void { |
| 266 | void vscode.window.showErrorMessage(error.message, { |
| 267 | modal: true, |
| 268 | }); |
| 269 | // We can't print error messages via debug session logger after the session is stopped. This could break the extension work. |
| 270 | if (this.debugSessionStatus === DebugSessionStatus.Stopped) { |
| 271 | OutputChannelLogger.getMainChannel().error(error.message); |
| 272 | return; |
| 273 | } |
| 274 | logger.error(error.message); |
| 275 | } |
| 276 | |
| 277 | protected async terminate(): Promise<void> { |
| 278 | await vscode.commands.executeCommand(this.stopCommand, undefined, { |
| 279 | sessionId: this.vsCodeDebugSession.id, |
| 280 | }); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | /** |
| 285 | * Parses settings.json file for workspace root property |
| 286 | */ |
| 287 | export function getProjectRoot(args: any): string { |
| 288 | const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); |
| 289 | const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); |
| 290 | try { |
| 291 | const settingsContent = fs.readFileSync(settingsPath, "utf8"); |
| 292 | const parsedSettings = stripJsonTrailingComma(settingsContent); |
| 293 | const projectRootPath = |
| 294 | parsedSettings["react-native-tools.projectRoot"] || |
| 295 | parsedSettings["react-native-tools"].projectRoot; |
| 296 | return path.resolve(vsCodeRoot, projectRootPath); |
| 297 | } catch (e) { |
| 298 | logger.verbose( |
| 299 | `${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`, |
| 300 | ); |
| 301 | return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); |
| 302 | } |
| 303 | } |
| 304 | |