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