microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
65e55367b12bd1ee2098c976b1b5ec29074e1226

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

262lines · modeblame

2c19da7fRedMickey6 years ago1// 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 path from "path";
6import * as fs from "fs";
7import stripJsonComments = require("strip-json-comments");
984ca036RedMickey6 years ago8import { LoggingDebugSession, Logger, logger, ErrorDestination } from "vscode-debugadapter";
2c19da7fRedMickey6 years ago9import { DebugProtocol } from "vscode-debugprotocol";
10import { getLoggingDirectory, LogHelper } from "../extension/log/LogHelper";
11import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
12import { ErrorHelper } from "../common/error/errorHelper";
13import { InternalErrorCode } from "../common/error/internalErrorCode";
e23d1841RedMickey6 years ago14import { InternalError, NestedError } from "../common/error/internalError";
5471436aRedMickey5 years ago15import { IRunOptions, PlatformType } from "../extension/launchArgs";
2c19da7fRedMickey6 years ago16import { AppLauncher } from "../extension/appLauncher";
17import { LogLevel } from "../extension/log/LogHelper";
e23d1841RedMickey6 years ago18import * as nls from "vscode-nls";
34472878RedMickey5 years ago19nls.config({
20messageFormat: nls.MessageFormat.bundle,
21bundleFormat: nls.BundleFormat.standalone,
22})();
e23d1841RedMickey6 years ago23const localize = nls.loadMessageBundle();
2c19da7fRedMickey6 years ago24
25/**
26* Enum of possible statuses of debug session
27*/
28export enum DebugSessionStatus {
29/** A session has been just created */
30FirstConnection,
31/** This status is required in order to exclude the possible creation of several debug sessions at the first start */
32FirstConnectionPending,
33/** This status means that an application can be reloaded */
34ConnectionAllowed,
35/** This status means that an application is reloading now, and we shouldn't terminate the current debug session */
36ConnectionPending,
37/** A debuggee connected successfully */
38ConnectionDone,
39/** A debuggee failed to connect */
40ConnectionFailed,
41}
42
ebbd64f1RedMickey6 years ago43export interface TerminateEventArgs {
44debugSession: vscode.DebugSession;
45args: any;
46}
47
5471436aRedMickey5 years ago48export interface IAttachRequestArgs
49extends DebugProtocol.AttachRequestArguments,
50IRunOptions,
51vscode.DebugConfiguration {
259c018fYuri Skorokhodov5 years ago52webkitRangeMax: number;
53webkitRangeMin: number;
34472878RedMickey5 years ago54cwd: string /* Automatically set by VS Code to the currently opened folder */;
2c19da7fRedMickey6 years ago55port: number;
56url?: string;
6f9a0779JiglioNero5 years ago57useHermesEngine: boolean;
2c19da7fRedMickey6 years ago58address?: string;
59trace?: string;
5d47053fRedMickey6 years ago60skipFiles?: [];
1bdccb66RedMickey6 years ago61sourceMaps?: boolean;
62sourceMapPathOverrides?: { [key: string]: string };
2c19da7fRedMickey6 years ago63}
64
34472878RedMickey5 years ago65export interface ILaunchRequestArgs
66extends DebugProtocol.LaunchRequestArguments,
67IAttachRequestArgs {}
2c19da7fRedMickey6 years ago68
69export abstract class DebugSessionBase extends LoggingDebugSession {
ebbd64f1RedMickey6 years ago70protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = new vscode.EventEmitter<TerminateEventArgs>();
34472878RedMickey5 years ago71public static readonly onDidTerminateRootDebugSession =
72DebugSessionBase.rootSessionTerminatedEventEmitter.event;
ebbd64f1RedMickey6 years ago73
a2ddbba5RedMickey5 years ago74protected readonly stopCommand: string;
ebbd64f1RedMickey6 years ago75protected readonly pwaNodeSessionName: string;
76
2c19da7fRedMickey6 years ago77protected appLauncher: AppLauncher;
78protected projectRootPath: string;
79protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
80protected previousAttachArgs: IAttachRequestArgs;
81protected cdpProxyLogLevel: LogLevel;
82protected debugSessionStatus: DebugSessionStatus;
83protected session: vscode.DebugSession;
e23d1841RedMickey6 years ago84protected cancellationTokenSource: vscode.CancellationTokenSource;
2c19da7fRedMickey6 years ago85
86constructor(session: vscode.DebugSession) {
87super();
88
ebbd64f1RedMickey6 years ago89// constants definition
90this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
a2ddbba5RedMickey5 years ago91this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button
ebbd64f1RedMickey6 years ago92
93// variables definition
2c19da7fRedMickey6 years ago94this.session = session;
95this.isSettingsInitialized = false;
96this.debugSessionStatus = DebugSessionStatus.FirstConnection;
e23d1841RedMickey6 years ago97this.cancellationTokenSource = new vscode.CancellationTokenSource();
98}
99
34472878RedMickey5 years ago100protected initializeRequest(
101response: DebugProtocol.InitializeResponse,
102// eslint-disable-next-line @typescript-eslint/no-unused-vars
103args: DebugProtocol.InitializeRequestArguments,
104): void {
e23d1841RedMickey6 years ago105response.body = response.body || {};
106
107response.body.supportsConfigurationDoneRequest = true;
108response.body.supportsEvaluateForHovers = true;
109response.body.supportTerminateDebuggee = true;
110response.body.supportsCancelRequest = true;
111
112this.sendResponse(response);
2c19da7fRedMickey6 years ago113}
114
34472878RedMickey5 years ago115protected abstract establishDebugSession(
116attachArgs: IAttachRequestArgs,
117resolve?: (value?: void | PromiseLike<void> | undefined) => void,
118): void;
b7451aefRedMickey6 years ago119
4dfb1c4cetatanova5 years ago120protected initializeSettings(args: any): Promise<void> {
2c19da7fRedMickey6 years ago121if (!this.isSettingsInitialized) {
122let chromeDebugCoreLogs = getLoggingDirectory();
123if (chromeDebugCoreLogs) {
124chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt");
125}
126let logLevel: string = args.trace;
127if (logLevel) {
128logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
129logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false);
34472878RedMickey5 years ago130this.cdpProxyLogLevel =
131LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
2c19da7fRedMickey6 years ago132} else {
133logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
34472878RedMickey5 years ago134this.cdpProxyLogLevel =
135LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
2c19da7fRedMickey6 years ago136}
137
2db9ac85Yuri Skorokhodov5 years ago138if (typeof args.sourceMaps !== "boolean") {
2c19da7fRedMickey6 years ago139args.sourceMaps = true;
140}
141
5514e287RedMickey6 years ago142if (typeof args.enableDebug !== "boolean") {
143args.enableDebug = true;
144}
145
81fc1822JiglioNero5 years ago146// Now there is a problem with processing time of 'createFromSourceMap' function of js-debug
147// So we disable this functionality by default https://github.com/microsoft/vscode-js-debug/issues/1033
148if (typeof args.sourceMapRenames !== "boolean") {
149args.sourceMapRenames = false;
150}
151
2c19da7fRedMickey6 years ago152const projectRootPath = getProjectRoot(args);
4dfb1c4cetatanova5 years ago153
154return ReactNativeProjectHelper.isReactNativeProject(projectRootPath).then(
155(result: boolean) => {
156if (!result) {
157throw ErrorHelper.getInternalError(
158InternalErrorCode.NotInReactNativeFolderError,
159);
160}
161return AppLauncher.getOrCreateAppLauncherByProjectRootPath(
162projectRootPath,
163).then((appLauncher: AppLauncher) => {
164this.appLauncher = appLauncher;
165this.projectRootPath = projectRootPath;
166this.isSettingsInitialized = true;
167this.appLauncher.getOrUpdateNodeModulesRoot(true);
168if (this.session.workspaceFolder) {
169this.appLauncher.updateDebugConfigurationRoot(
170this.session.workspaceFolder.uri.fsPath,
171);
172}
173});
174},
175);
2c19da7fRedMickey6 years ago176} else {
ce5e88eeYuri Skorokhodov5 years ago177return Promise.resolve();
2c19da7fRedMickey6 years ago178}
179}
984ca036RedMickey6 years ago180
34472878RedMickey5 years ago181protected async disconnectRequest(
182response: DebugProtocol.DisconnectResponse,
183args: DebugProtocol.DisconnectArguments,
184// eslint-disable-next-line @typescript-eslint/no-unused-vars
185request?: DebugProtocol.Request,
186): Promise<void> {
a32e1e1fYuri Skorokhodov5 years ago187if (this.appLauncher) {
188await this.appLauncher.getRnCdpProxy().stopServer();
189}
e23d1841RedMickey6 years ago190
191this.cancellationTokenSource.cancel();
192this.cancellationTokenSource.dispose();
193
194// Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
259c018fYuri Skorokhodov5 years ago195if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) {
e23d1841RedMickey6 years ago196try {
8df5011eYuri Skorokhodov5 years ago197this.appLauncher.getMobilePlatform().dispose();
e23d1841RedMickey6 years ago198} catch (err) {
34472878RedMickey5 years ago199logger.warn(
200localize(
201"CouldNotStopMonitoringLogcat",
202"Couldn't stop monitoring logcat: {0}",
203err.message || err,
204),
205);
e23d1841RedMickey6 years ago206}
207}
208
67ffa5b4RedMickey6 years ago209await logger.dispose();
210
ebbd64f1RedMickey6 years ago211DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
212debugSession: this.session,
213args: {
a2ddbba5RedMickey5 years ago214forcedStop: !!(<any>args).forcedStop,
ebbd64f1RedMickey6 years ago215},
216});
217
218this.sendResponse(response);
e23d1841RedMickey6 years ago219}
220
221protected showError(error: Error, response: DebugProtocol.Response): void {
222// We can't print error messages after the debugging session is stopped. This could break the extension work.
34472878RedMickey5 years ago223if (
224(error instanceof InternalError || error instanceof NestedError) &&
225error.errorCode === InternalErrorCode.CancellationTokenTriggered
e23d1841RedMickey6 years ago226) {
227return;
228}
229
28ceac00RedMickey4 years ago230logger.error(error.message);
231
984ca036RedMickey6 years ago232this.sendErrorResponse(
233response,
e23d1841RedMickey6 years ago234{ format: error.message, id: 1 },
984ca036RedMickey6 years ago235undefined,
236undefined,
34472878RedMickey5 years ago237ErrorDestination.User,
984ca036RedMickey6 years ago238);
239}
2c19da7fRedMickey6 years ago240}
241
242/**
243* Parses settings.json file for workspace root property
244*/
245export function getProjectRoot(args: any): string {
246const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
247const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
248try {
249let settingsContent = fs.readFileSync(settingsPath, "utf8");
250settingsContent = stripJsonComments(settingsContent);
251let parsedSettings = JSON.parse(settingsContent);
34472878RedMickey5 years ago252let projectRootPath =
253parsedSettings["react-native-tools.projectRoot"] ||
254parsedSettings["react-native-tools"].projectRoot;
2c19da7fRedMickey6 years ago255return path.resolve(vsCodeRoot, projectRootPath);
256} catch (e) {
34472878RedMickey5 years ago257logger.verbose(
258`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`,
259);
2c19da7fRedMickey6 years ago260return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
261}
262}