microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/debugSessionBase.ts
303lines · 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"; |
984ca036RedMickey6 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"; |
d93677adRedMickey4 years ago | 21 | import { RNSession } from "./debugSessionWrapper"; |
bfcc8a29Samriel4 years ago | 22 | |
34472878RedMickey5 years ago | 23 | nls.config({ |
| 24 | messageFormat: nls.MessageFormat.bundle, | |
| 25 | bundleFormat: nls.BundleFormat.standalone, | |
| 26 | })(); | |
e23d1841RedMickey6 years ago | 27 | const localize = nls.loadMessageBundle(); |
2c19da7fRedMickey6 years ago | 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, | |
19df32dcRedMickey4 years ago | 45 | /** The session is handling disconnect request now */ |
| 46 | Stopping, | |
| 47 | /** The session is stopped */ | |
| 48 | Stopped, | |
2c19da7fRedMickey6 years ago | 49 | } |
| 50 | | |
ebbd64f1RedMickey6 years ago | 51 | export interface TerminateEventArgs { |
| 52 | debugSession: vscode.DebugSession; | |
| 53 | args: any; | |
| 54 | } | |
| 55 | | |
5471436aRedMickey5 years ago | 56 | export interface IAttachRequestArgs |
| 57 | extends DebugProtocol.AttachRequestArguments, | |
| 58 | IRunOptions, | |
| 59 | vscode.DebugConfiguration { | |
259c018fYuri Skorokhodov5 years ago | 60 | webkitRangeMax: number; |
| 61 | webkitRangeMin: number; | |
34472878RedMickey5 years ago | 62 | cwd: string /* Automatically set by VS Code to the currently opened folder */; |
2c19da7fRedMickey6 years ago | 63 | port: number; |
| 64 | url?: string; | |
6f9a0779JiglioNero5 years ago | 65 | useHermesEngine: boolean; |
2c19da7fRedMickey6 years ago | 66 | address?: string; |
| 67 | trace?: string; | |
5d47053fRedMickey6 years ago | 68 | skipFiles?: []; |
1bdccb66RedMickey6 years ago | 69 | sourceMaps?: boolean; |
| 70 | sourceMapPathOverrides?: { [key: string]: string }; | |
2c19da7fRedMickey6 years ago | 71 | } |
| 72 | | |
34472878RedMickey5 years ago | 73 | export interface ILaunchRequestArgs |
| 74 | extends DebugProtocol.LaunchRequestArguments, | |
| 75 | IAttachRequestArgs {} | |
2c19da7fRedMickey6 years ago | 76 | |
| 77 | export abstract class DebugSessionBase extends LoggingDebugSession { | |
09f6024fHeniker4 years ago | 78 | protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = |
| 79 | new vscode.EventEmitter<TerminateEventArgs>(); | |
34472878RedMickey5 years ago | 80 | public static readonly onDidTerminateRootDebugSession = |
| 81 | DebugSessionBase.rootSessionTerminatedEventEmitter.event; | |
ebbd64f1RedMickey6 years ago | 82 | |
a2ddbba5RedMickey5 years ago | 83 | protected readonly stopCommand: string; |
19df32dcRedMickey4 years ago | 84 | protected readonly terminateCommand: string; |
ebbd64f1RedMickey6 years ago | 85 | protected readonly pwaNodeSessionName: string; |
| 86 | | |
2c19da7fRedMickey6 years ago | 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; | |
19df32dcRedMickey4 years ago | 93 | protected nodeSession: vscode.DebugSession | null; |
d93677adRedMickey4 years ago | 94 | protected rnSession: RNSession; |
| 95 | protected vsCodeDebugSession: vscode.DebugSession; | |
e23d1841RedMickey6 years ago | 96 | protected cancellationTokenSource: vscode.CancellationTokenSource; |
2c19da7fRedMickey6 years ago | 97 | |
d93677adRedMickey4 years ago | 98 | constructor(rnSession: RNSession) { |
2c19da7fRedMickey6 years ago | 99 | super(); |
| 100 | | |
ebbd64f1RedMickey6 years ago | 101 | // constants definition |
| 102 | this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension | |
a2ddbba5RedMickey5 years ago | 103 | this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button |
19df32dcRedMickey4 years ago | 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 |
ebbd64f1RedMickey6 years ago | 105 | |
| 106 | // variables definition | |
d93677adRedMickey4 years ago | 107 | this.rnSession = rnSession; |
| 108 | this.vsCodeDebugSession = rnSession.vsCodeDebugSession; | |
2c19da7fRedMickey6 years ago | 109 | this.isSettingsInitialized = false; |
| 110 | this.debugSessionStatus = DebugSessionStatus.FirstConnection; | |
e23d1841RedMickey6 years ago | 111 | this.cancellationTokenSource = new vscode.CancellationTokenSource(); |
19df32dcRedMickey4 years ago | 112 | this.nodeSession = null; |
e23d1841RedMickey6 years ago | 113 | } |
| 114 | | |
34472878RedMickey5 years ago | 115 | protected initializeRequest( |
| 116 | response: DebugProtocol.InitializeResponse, | |
| 117 | // eslint-disable-next-line @typescript-eslint/no-unused-vars | |
| 118 | args: DebugProtocol.InitializeRequestArguments, | |
| 119 | ): void { | |
e23d1841RedMickey6 years ago | 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); | |
2c19da7fRedMickey6 years ago | 128 | } |
| 129 | | |
34472878RedMickey5 years ago | 130 | protected abstract establishDebugSession( |
| 131 | attachArgs: IAttachRequestArgs, | |
| 132 | resolve?: (value?: void | PromiseLike<void> | undefined) => void, | |
| 133 | ): void; | |
b7451aefRedMickey6 years ago | 134 | |
0d77292aJiglioNero4 years ago | 135 | protected async initializeSettings(args: any): Promise<void> { |
2c19da7fRedMickey6 years ago | 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); | |
34472878RedMickey5 years ago | 145 | this.cdpProxyLogLevel = |
| 146 | LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None; | |
2c19da7fRedMickey6 years ago | 147 | } else { |
| 148 | logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false); | |
34472878RedMickey5 years ago | 149 | this.cdpProxyLogLevel = |
| 150 | LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None; | |
2c19da7fRedMickey6 years ago | 151 | } |
| 152 | | |
2db9ac85Yuri Skorokhodov5 years ago | 153 | if (typeof args.sourceMaps !== "boolean") { |
2c19da7fRedMickey6 years ago | 154 | args.sourceMaps = true; |
| 155 | } | |
| 156 | | |
5514e287RedMickey6 years ago | 157 | if (typeof args.enableDebug !== "boolean") { |
| 158 | args.enableDebug = true; | |
| 159 | } | |
| 160 | | |
81fc1822JiglioNero4 years ago | 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 | | |
43e6ccc3JiglioNero4 years ago | 167 | const projectRootPath = SettingsHelper.getReactNativeProjectRoot(args.cwd); |
0d77292aJiglioNero4 years ago | 168 | const isReactProject = await ReactNativeProjectHelper.isReactNativeProject( |
| 169 | projectRootPath, | |
| 170 | ); | |
| 171 | if (!isReactProject) { | |
| 172 | throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError); | |
| 173 | } | |
4dfb1c4cetatanova5 years ago | 174 | |
0d77292aJiglioNero4 years ago | 175 | const appLauncher = await AppLauncher.getOrCreateAppLauncherByProjectRootPath( |
| 176 | projectRootPath, | |
4dfb1c4cetatanova5 years ago | 177 | ); |
0d77292aJiglioNero4 years ago | 178 | this.appLauncher = appLauncher; |
| 179 | this.projectRootPath = projectRootPath; | |
| 180 | this.isSettingsInitialized = true; | |
| 181 | this.appLauncher.getOrUpdateNodeModulesRoot(true); | |
d93677adRedMickey4 years ago | 182 | if (this.vsCodeDebugSession.workspaceFolder) { |
0d77292aJiglioNero4 years ago | 183 | this.appLauncher.updateDebugConfigurationRoot( |
d93677adRedMickey4 years ago | 184 | this.vsCodeDebugSession.workspaceFolder.uri.fsPath, |
0d77292aJiglioNero4 years ago | 185 | ); |
| 186 | } | |
2c19da7fRedMickey6 years ago | 187 | } |
| 188 | } | |
984ca036RedMickey6 years ago | 189 | |
34472878RedMickey5 years ago | 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> { | |
a32e1e1fYuri Skorokhodov5 years ago | 196 | if (this.appLauncher) { |
| 197 | await this.appLauncher.getRnCdpProxy().stopServer(); | |
| 198 | } | |
e23d1841RedMickey6 years ago | 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 | |
259c018fYuri Skorokhodov5 years ago | 204 | if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) { |
e23d1841RedMickey6 years ago | 205 | try { |
8df5011eYuri Skorokhodov5 years ago | 206 | this.appLauncher.getMobilePlatform().dispose(); |
e23d1841RedMickey6 years ago | 207 | } catch (err) { |
34472878RedMickey5 years ago | 208 | logger.warn( |
| 209 | localize( | |
| 210 | "CouldNotStopMonitoringLogcat", | |
| 211 | "Couldn't stop monitoring logcat: {0}", | |
| 212 | err.message || err, | |
| 213 | ), | |
| 214 | ); | |
e23d1841RedMickey6 years ago | 215 | } |
| 216 | } | |
| 217 | | |
19df32dcRedMickey4 years ago | 218 | this.debugSessionStatus = DebugSessionStatus.Stopped; |
67ffa5b4RedMickey6 years ago | 219 | await logger.dispose(); |
| 220 | | |
ebbd64f1RedMickey6 years ago | 221 | DebugSessionBase.rootSessionTerminatedEventEmitter.fire({ |
d93677adRedMickey4 years ago | 222 | debugSession: this.vsCodeDebugSession, |
ebbd64f1RedMickey6 years ago | 223 | args: { |
a2ddbba5RedMickey5 years ago | 224 | forcedStop: !!(<any>args).forcedStop, |
ebbd64f1RedMickey6 years ago | 225 | }, |
| 226 | }); | |
| 227 | | |
| 228 | this.sendResponse(response); | |
e23d1841RedMickey6 years ago | 229 | } |
| 230 | | |
19df32dcRedMickey4 years ago | 231 | protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void { |
e23d1841RedMickey6 years ago | 232 | // We can't print error messages after the debugging session is stopped. This could break the extension work. |
34472878RedMickey5 years ago | 233 | if ( |
| 234 | (error instanceof InternalError || error instanceof NestedError) && | |
| 235 | error.errorCode === InternalErrorCode.CancellationTokenTriggered | |
e23d1841RedMickey6 years ago | 236 | ) { |
| 237 | return; | |
| 238 | } | |
| 239 | | |
28ceac00RedMickey4 years ago | 240 | logger.error(error.message); |
| 241 | | |
984ca036RedMickey6 years ago | 242 | this.sendErrorResponse( |
| 243 | response, | |
e23d1841RedMickey6 years ago | 244 | { format: error.message, id: 1 }, |
984ca036RedMickey6 years ago | 245 | undefined, |
| 246 | undefined, | |
34472878RedMickey5 years ago | 247 | ErrorDestination.User, |
984ca036RedMickey6 years ago | 248 | ); |
| 249 | } | |
2c19da7fRedMickey6 years ago | 250 | |
bfcc8a29Samriel4 years ago | 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 | } | |
19df32dcRedMickey4 years ago | 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 | } | |
2c19da7fRedMickey6 years ago | 282 | } |
dc94981bQuan Jin3 years ago | 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 | } |