microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1.11.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

308lines · 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}
b84470b5Ezio Li2 years ago188const settingsPort = this.appLauncher.getPackagerPort(projectRootPath);
189if (this.appLauncher.getPackager().getPort() != settingsPort) {
190this.appLauncher.getPackager().resetToSettingsPort();
191}
2c19da7fRedMickey6 years ago192}
193}
984ca036RedMickey6 years ago194
34472878RedMickey5 years ago195protected async disconnectRequest(
196response: DebugProtocol.DisconnectResponse,
197args: DebugProtocol.DisconnectArguments,
198// eslint-disable-next-line @typescript-eslint/no-unused-vars
199request?: DebugProtocol.Request,
200): Promise<void> {
a32e1e1fYuri Skorokhodov5 years ago201if (this.appLauncher) {
202await this.appLauncher.getRnCdpProxy().stopServer();
203}
e23d1841RedMickey6 years ago204
205this.cancellationTokenSource.cancel();
206this.cancellationTokenSource.dispose();
207
208// Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
259c018fYuri Skorokhodov5 years ago209if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) {
e23d1841RedMickey6 years ago210try {
8df5011eYuri Skorokhodov5 years ago211this.appLauncher.getMobilePlatform().dispose();
e23d1841RedMickey6 years ago212} catch (err) {
34472878RedMickey5 years ago213logger.warn(
214localize(
215"CouldNotStopMonitoringLogcat",
216"Couldn't stop monitoring logcat: {0}",
217err.message || err,
218),
219);
e23d1841RedMickey6 years ago220}
221}
222
19df32dcRedMickey4 years ago223this.debugSessionStatus = DebugSessionStatus.Stopped;
67ffa5b4RedMickey6 years ago224await logger.dispose();
225
ebbd64f1RedMickey6 years ago226DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
d93677adRedMickey4 years ago227debugSession: this.vsCodeDebugSession,
ebbd64f1RedMickey6 years ago228args: {
a2ddbba5RedMickey5 years ago229forcedStop: !!(<any>args).forcedStop,
ebbd64f1RedMickey6 years ago230},
231});
232
233this.sendResponse(response);
e23d1841RedMickey6 years ago234}
235
19df32dcRedMickey4 years ago236protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void {
e23d1841RedMickey6 years ago237// We can't print error messages after the debugging session is stopped. This could break the extension work.
34472878RedMickey5 years ago238if (
239(error instanceof InternalError || error instanceof NestedError) &&
240error.errorCode === InternalErrorCode.CancellationTokenTriggered
e23d1841RedMickey6 years ago241) {
242return;
243}
244
28ceac00RedMickey4 years ago245logger.error(error.message);
246
984ca036RedMickey6 years ago247this.sendErrorResponse(
248response,
e23d1841RedMickey6 years ago249{ format: error.message, id: 1 },
984ca036RedMickey6 years ago250undefined,
251undefined,
34472878RedMickey5 years ago252ErrorDestination.User,
984ca036RedMickey6 years ago253);
254}
2c19da7fRedMickey6 years ago255
bfcc8a29Samriel4 years ago256protected async preparePackagerBeforeAttach(
257args: IAttachRequestArgs,
258reactNativeVersions: RNPackageVersions,
259): Promise<void> {
260if (!(await this.appLauncher.getPackager().isRunning())) {
261const runOptions: ILaunchArgs = Object.assign(
262{ reactNativeVersions },
263this.appLauncher.prepareBaseRunOptions(args),
264);
265this.appLauncher.getPackager().setRunOptions(runOptions);
266await this.appLauncher.getPackager().start();
267}
268}
19df32dcRedMickey4 years ago269
270protected showError(error: Error): void {
271void vscode.window.showErrorMessage(error.message, {
272modal: true,
273});
274// We can't print error messages via debug session logger after the session is stopped. This could break the extension work.
275if (this.debugSessionStatus === DebugSessionStatus.Stopped) {
276OutputChannelLogger.getMainChannel().error(error.message);
277return;
278}
279logger.error(error.message);
280}
281
282protected async terminate(): Promise<void> {
283await vscode.commands.executeCommand(this.stopCommand, undefined, {
284sessionId: this.vsCodeDebugSession.id,
285});
286}
2c19da7fRedMickey6 years ago287}
dc94981bQuan Jin3 years ago288
289/**
290* Parses settings.json file for workspace root property
291*/
292export function getProjectRoot(args: any): string {
293const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
294const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
295try {
296const settingsContent = fs.readFileSync(settingsPath, "utf8");
297const parsedSettings = stripJsonTrailingComma(settingsContent);
298const projectRootPath =
299parsedSettings["react-native-tools.projectRoot"] ||
300parsedSettings["react-native-tools"].projectRoot;
301return path.resolve(vsCodeRoot, projectRootPath);
302} catch (e) {
303logger.verbose(
304`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`,
305);
306return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
307}
308}