microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
88671796c706b57173b085a214f5f00540d7376b

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

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