microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1.11.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

304lines · 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 path from "path";
5import * as fs from "fs";
09f6024fHeniker4 years ago6import * as vscode from "vscode";
984ca036RedMickey6 years ago7import { LoggingDebugSession, Logger, logger, ErrorDestination } from "vscode-debugadapter";
2c19da7fRedMickey6 years ago8import { DebugProtocol } from "vscode-debugprotocol";
09f6024fHeniker4 years ago9import * as nls from "vscode-nls";
dc94981bQuan Jin3 years ago10import { stripJsonTrailingComma } from "../common/utils";
09f6024fHeniker4 years ago11import { getLoggingDirectory, LogHelper, LogLevel } from "../extension/log/LogHelper";
2c19da7fRedMickey6 years ago12import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
13import { ErrorHelper } from "../common/error/errorHelper";
14import { InternalErrorCode } from "../common/error/internalErrorCode";
e23d1841RedMickey6 years ago15import { InternalError, NestedError } from "../common/error/internalError";
bfcc8a29Samriel4 years ago16import { ILaunchArgs, IRunOptions, PlatformType } from "../extension/launchArgs";
2c19da7fRedMickey6 years ago17import { AppLauncher } from "../extension/appLauncher";
bfcc8a29Samriel4 years ago18import { RNPackageVersions } from "../common/projectVersionHelper";
43e6ccc3JiglioNero4 years ago19import { SettingsHelper } from "../extension/settingsHelper";
19df32dcRedMickey4 years ago20import { OutputChannelLogger } from "../extension/log/OutputChannelLogger";
d93677adRedMickey4 years ago21import { RNSession } from "./debugSessionWrapper";
bfcc8a29Samriel4 years ago22
34472878RedMickey5 years ago23nls.config({
24messageFormat: nls.MessageFormat.bundle,
25bundleFormat: nls.BundleFormat.standalone,
26})();
e23d1841RedMickey6 years ago27const localize = nls.loadMessageBundle();
2c19da7fRedMickey6 years ago28
29/**
30* Enum of possible statuses of debug session
31*/
32export enum DebugSessionStatus {
33/** A session has been just created */
34FirstConnection,
35/** This status is required in order to exclude the possible creation of several debug sessions at the first start */
36FirstConnectionPending,
37/** This status means that an application can be reloaded */
38ConnectionAllowed,
39/** This status means that an application is reloading now, and we shouldn't terminate the current debug session */
40ConnectionPending,
41/** A debuggee connected successfully */
42ConnectionDone,
43/** A debuggee failed to connect */
44ConnectionFailed,
19df32dcRedMickey4 years ago45/** The session is handling disconnect request now */
46Stopping,
47/** The session is stopped */
48Stopped,
2c19da7fRedMickey6 years ago49}
50
ebbd64f1RedMickey6 years ago51export interface TerminateEventArgs {
52debugSession: vscode.DebugSession;
53args: any;
54}
55
5471436aRedMickey5 years ago56export interface IAttachRequestArgs
57extends DebugProtocol.AttachRequestArguments,
58IRunOptions,
59vscode.DebugConfiguration {
259c018fYuri Skorokhodov5 years ago60webkitRangeMax: number;
61webkitRangeMin: number;
34472878RedMickey5 years ago62cwd: string /* Automatically set by VS Code to the currently opened folder */;
2c19da7fRedMickey6 years ago63port: number;
64url?: string;
6f9a0779JiglioNero5 years ago65useHermesEngine: boolean;
2c19da7fRedMickey6 years ago66address?: string;
67trace?: string;
5d47053fRedMickey6 years ago68skipFiles?: [];
1bdccb66RedMickey6 years ago69sourceMaps?: boolean;
70sourceMapPathOverrides?: { [key: string]: string };
2d89fb47Ezio Li3 years ago71jsDebugTrace?: boolean;
2c19da7fRedMickey6 years ago72}
73
34472878RedMickey5 years ago74export interface ILaunchRequestArgs
75extends DebugProtocol.LaunchRequestArguments,
76IAttachRequestArgs {}
2c19da7fRedMickey6 years ago77
78export abstract class DebugSessionBase extends LoggingDebugSession {
09f6024fHeniker4 years ago79protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> =
80new vscode.EventEmitter<TerminateEventArgs>();
34472878RedMickey5 years ago81public static readonly onDidTerminateRootDebugSession =
82DebugSessionBase.rootSessionTerminatedEventEmitter.event;
ebbd64f1RedMickey6 years ago83
a2ddbba5RedMickey5 years ago84protected readonly stopCommand: string;
19df32dcRedMickey4 years ago85protected readonly terminateCommand: string;
ebbd64f1RedMickey6 years ago86protected readonly pwaNodeSessionName: string;
87
2c19da7fRedMickey6 years ago88protected appLauncher: AppLauncher;
89protected projectRootPath: string;
90protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
91protected previousAttachArgs: IAttachRequestArgs;
92protected cdpProxyLogLevel: LogLevel;
93protected debugSessionStatus: DebugSessionStatus;
19df32dcRedMickey4 years ago94protected nodeSession: vscode.DebugSession | null;
d93677adRedMickey4 years ago95protected rnSession: RNSession;
96protected vsCodeDebugSession: vscode.DebugSession;
e23d1841RedMickey6 years ago97protected cancellationTokenSource: vscode.CancellationTokenSource;
2c19da7fRedMickey6 years ago98
d93677adRedMickey4 years ago99constructor(rnSession: RNSession) {
2c19da7fRedMickey6 years ago100super();
101
ebbd64f1RedMickey6 years ago102// constants definition
103this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
a2ddbba5RedMickey5 years ago104this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button
19df32dcRedMickey4 years ago105this.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 ago106
107// variables definition
d93677adRedMickey4 years ago108this.rnSession = rnSession;
109this.vsCodeDebugSession = rnSession.vsCodeDebugSession;
2c19da7fRedMickey6 years ago110this.isSettingsInitialized = false;
111this.debugSessionStatus = DebugSessionStatus.FirstConnection;
e23d1841RedMickey6 years ago112this.cancellationTokenSource = new vscode.CancellationTokenSource();
19df32dcRedMickey4 years ago113this.nodeSession = null;
e23d1841RedMickey6 years ago114}
115
34472878RedMickey5 years ago116protected initializeRequest(
117response: DebugProtocol.InitializeResponse,
118// eslint-disable-next-line @typescript-eslint/no-unused-vars
119args: DebugProtocol.InitializeRequestArguments,
120): void {
e23d1841RedMickey6 years ago121response.body = response.body || {};
122
123response.body.supportsConfigurationDoneRequest = true;
124response.body.supportsEvaluateForHovers = true;
125response.body.supportTerminateDebuggee = true;
126response.body.supportsCancelRequest = true;
127
128this.sendResponse(response);
2c19da7fRedMickey6 years ago129}
130
34472878RedMickey5 years ago131protected abstract establishDebugSession(
132attachArgs: IAttachRequestArgs,
133resolve?: (value?: void | PromiseLike<void> | undefined) => void,
134): void;
b7451aefRedMickey6 years ago135
0d77292aJiglioNero4 years ago136protected async initializeSettings(args: any): Promise<void> {
2c19da7fRedMickey6 years ago137if (!this.isSettingsInitialized) {
138let chromeDebugCoreLogs = getLoggingDirectory();
139if (chromeDebugCoreLogs) {
140chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt");
141}
142let logLevel: string = args.trace;
143if (logLevel) {
144logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
145logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false);
34472878RedMickey5 years ago146this.cdpProxyLogLevel =
147LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
2c19da7fRedMickey6 years ago148} else {
149logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
34472878RedMickey5 years ago150this.cdpProxyLogLevel =
151LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
2c19da7fRedMickey6 years ago152}
153
2db9ac85Yuri Skorokhodov5 years ago154if (typeof args.sourceMaps !== "boolean") {
2c19da7fRedMickey6 years ago155args.sourceMaps = true;
156}
157
5514e287RedMickey6 years ago158if (typeof args.enableDebug !== "boolean") {
159args.enableDebug = true;
160}
161
81fc1822JiglioNero4 years ago162// Now there is a problem with processing time of 'createFromSourceMap' function of js-debug
163// So we disable this functionality by default https://github.com/microsoft/vscode-js-debug/issues/1033
164if (typeof args.sourceMapRenames !== "boolean") {
165args.sourceMapRenames = false;
166}
167
43e6ccc3JiglioNero4 years ago168const projectRootPath = SettingsHelper.getReactNativeProjectRoot(args.cwd);
0d77292aJiglioNero4 years ago169const isReactProject = await ReactNativeProjectHelper.isReactNativeProject(
170projectRootPath,
171);
172if (!isReactProject) {
173throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError);
174}
4dfb1c4cetatanova5 years ago175
0d77292aJiglioNero4 years ago176const appLauncher = await AppLauncher.getOrCreateAppLauncherByProjectRootPath(
177projectRootPath,
4dfb1c4cetatanova5 years ago178);
0d77292aJiglioNero4 years ago179this.appLauncher = appLauncher;
180this.projectRootPath = projectRootPath;
181this.isSettingsInitialized = true;
182this.appLauncher.getOrUpdateNodeModulesRoot(true);
d93677adRedMickey4 years ago183if (this.vsCodeDebugSession.workspaceFolder) {
0d77292aJiglioNero4 years ago184this.appLauncher.updateDebugConfigurationRoot(
d93677adRedMickey4 years ago185this.vsCodeDebugSession.workspaceFolder.uri.fsPath,
0d77292aJiglioNero4 years ago186);
187}
2c19da7fRedMickey6 years ago188}
189}
984ca036RedMickey6 years ago190
34472878RedMickey5 years ago191protected async disconnectRequest(
192response: DebugProtocol.DisconnectResponse,
193args: DebugProtocol.DisconnectArguments,
194// eslint-disable-next-line @typescript-eslint/no-unused-vars
195request?: DebugProtocol.Request,
196): Promise<void> {
a32e1e1fYuri Skorokhodov5 years ago197if (this.appLauncher) {
198await this.appLauncher.getRnCdpProxy().stopServer();
199}
e23d1841RedMickey6 years ago200
201this.cancellationTokenSource.cancel();
202this.cancellationTokenSource.dispose();
203
204// Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
259c018fYuri Skorokhodov5 years ago205if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) {
e23d1841RedMickey6 years ago206try {
8df5011eYuri Skorokhodov5 years ago207this.appLauncher.getMobilePlatform().dispose();
e23d1841RedMickey6 years ago208} catch (err) {
34472878RedMickey5 years ago209logger.warn(
210localize(
211"CouldNotStopMonitoringLogcat",
212"Couldn't stop monitoring logcat: {0}",
213err.message || err,
214),
215);
e23d1841RedMickey6 years ago216}
217}
218
19df32dcRedMickey4 years ago219this.debugSessionStatus = DebugSessionStatus.Stopped;
67ffa5b4RedMickey6 years ago220await logger.dispose();
221
ebbd64f1RedMickey6 years ago222DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
d93677adRedMickey4 years ago223debugSession: this.vsCodeDebugSession,
ebbd64f1RedMickey6 years ago224args: {
a2ddbba5RedMickey5 years ago225forcedStop: !!(<any>args).forcedStop,
ebbd64f1RedMickey6 years ago226},
227});
228
229this.sendResponse(response);
e23d1841RedMickey6 years ago230}
231
19df32dcRedMickey4 years ago232protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void {
e23d1841RedMickey6 years ago233// We can't print error messages after the debugging session is stopped. This could break the extension work.
34472878RedMickey5 years ago234if (
235(error instanceof InternalError || error instanceof NestedError) &&
236error.errorCode === InternalErrorCode.CancellationTokenTriggered
e23d1841RedMickey6 years ago237) {
238return;
239}
240
28ceac00RedMickey4 years ago241logger.error(error.message);
242
984ca036RedMickey6 years ago243this.sendErrorResponse(
244response,
e23d1841RedMickey6 years ago245{ format: error.message, id: 1 },
984ca036RedMickey6 years ago246undefined,
247undefined,
34472878RedMickey5 years ago248ErrorDestination.User,
984ca036RedMickey6 years ago249);
250}
2c19da7fRedMickey6 years ago251
bfcc8a29Samriel4 years ago252protected async preparePackagerBeforeAttach(
253args: IAttachRequestArgs,
254reactNativeVersions: RNPackageVersions,
255): Promise<void> {
256if (!(await this.appLauncher.getPackager().isRunning())) {
257const runOptions: ILaunchArgs = Object.assign(
258{ reactNativeVersions },
259this.appLauncher.prepareBaseRunOptions(args),
260);
261this.appLauncher.getPackager().setRunOptions(runOptions);
262await this.appLauncher.getPackager().start();
263}
264}
19df32dcRedMickey4 years ago265
266protected showError(error: Error): void {
267void vscode.window.showErrorMessage(error.message, {
268modal: true,
269});
270// We can't print error messages via debug session logger after the session is stopped. This could break the extension work.
271if (this.debugSessionStatus === DebugSessionStatus.Stopped) {
272OutputChannelLogger.getMainChannel().error(error.message);
273return;
274}
275logger.error(error.message);
276}
277
278protected async terminate(): Promise<void> {
279await vscode.commands.executeCommand(this.stopCommand, undefined, {
280sessionId: this.vsCodeDebugSession.id,
281});
282}
2c19da7fRedMickey6 years ago283}
dc94981bQuan Jin3 years ago284
285/**
286* Parses settings.json file for workspace root property
287*/
288export function getProjectRoot(args: any): string {
289const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
290const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
291try {
292const settingsContent = fs.readFileSync(settingsPath, "utf8");
293const parsedSettings = stripJsonTrailingComma(settingsContent);
294const projectRootPath =
295parsedSettings["react-native-tools.projectRoot"] ||
296parsedSettings["react-native-tools"].projectRoot;
297return path.resolve(vsCodeRoot, projectRootPath);
298} catch (e) {
299logger.verbose(
300`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`,
301);
302return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
303}
304}