microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1.10.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

303lines · 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 };
2c19da7fRedMickey6 years ago71}
72
34472878RedMickey5 years ago73export interface ILaunchRequestArgs
74extends DebugProtocol.LaunchRequestArguments,
75IAttachRequestArgs {}
2c19da7fRedMickey6 years ago76
77export abstract class DebugSessionBase extends LoggingDebugSession {
09f6024fHeniker4 years ago78protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> =
79new vscode.EventEmitter<TerminateEventArgs>();
34472878RedMickey5 years ago80public static readonly onDidTerminateRootDebugSession =
81DebugSessionBase.rootSessionTerminatedEventEmitter.event;
ebbd64f1RedMickey6 years ago82
a2ddbba5RedMickey5 years ago83protected readonly stopCommand: string;
19df32dcRedMickey4 years ago84protected readonly terminateCommand: string;
ebbd64f1RedMickey6 years ago85protected readonly pwaNodeSessionName: string;
86
2c19da7fRedMickey6 years ago87protected appLauncher: AppLauncher;
88protected projectRootPath: string;
89protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
90protected previousAttachArgs: IAttachRequestArgs;
91protected cdpProxyLogLevel: LogLevel;
92protected debugSessionStatus: DebugSessionStatus;
19df32dcRedMickey4 years ago93protected nodeSession: vscode.DebugSession | null;
d93677adRedMickey4 years ago94protected rnSession: RNSession;
95protected vsCodeDebugSession: vscode.DebugSession;
e23d1841RedMickey6 years ago96protected cancellationTokenSource: vscode.CancellationTokenSource;
2c19da7fRedMickey6 years ago97
d93677adRedMickey4 years ago98constructor(rnSession: RNSession) {
2c19da7fRedMickey6 years ago99super();
100
ebbd64f1RedMickey6 years ago101// constants definition
102this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
a2ddbba5RedMickey5 years ago103this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button
19df32dcRedMickey4 years ago104this.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 ago105
106// variables definition
d93677adRedMickey4 years ago107this.rnSession = rnSession;
108this.vsCodeDebugSession = rnSession.vsCodeDebugSession;
2c19da7fRedMickey6 years ago109this.isSettingsInitialized = false;
110this.debugSessionStatus = DebugSessionStatus.FirstConnection;
e23d1841RedMickey6 years ago111this.cancellationTokenSource = new vscode.CancellationTokenSource();
19df32dcRedMickey4 years ago112this.nodeSession = null;
e23d1841RedMickey6 years ago113}
114
34472878RedMickey5 years ago115protected initializeRequest(
116response: DebugProtocol.InitializeResponse,
117// eslint-disable-next-line @typescript-eslint/no-unused-vars
118args: DebugProtocol.InitializeRequestArguments,
119): void {
e23d1841RedMickey6 years ago120response.body = response.body || {};
121
122response.body.supportsConfigurationDoneRequest = true;
123response.body.supportsEvaluateForHovers = true;
124response.body.supportTerminateDebuggee = true;
125response.body.supportsCancelRequest = true;
126
127this.sendResponse(response);
2c19da7fRedMickey6 years ago128}
129
34472878RedMickey5 years ago130protected abstract establishDebugSession(
131attachArgs: IAttachRequestArgs,
132resolve?: (value?: void | PromiseLike<void> | undefined) => void,
133): void;
b7451aefRedMickey6 years ago134
0d77292aJiglioNero4 years ago135protected async initializeSettings(args: any): Promise<void> {
2c19da7fRedMickey6 years ago136if (!this.isSettingsInitialized) {
137let chromeDebugCoreLogs = getLoggingDirectory();
138if (chromeDebugCoreLogs) {
139chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt");
140}
141let logLevel: string = args.trace;
142if (logLevel) {
143logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
144logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false);
34472878RedMickey5 years ago145this.cdpProxyLogLevel =
146LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
2c19da7fRedMickey6 years ago147} else {
148logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
34472878RedMickey5 years ago149this.cdpProxyLogLevel =
150LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
2c19da7fRedMickey6 years ago151}
152
2db9ac85Yuri Skorokhodov5 years ago153if (typeof args.sourceMaps !== "boolean") {
2c19da7fRedMickey6 years ago154args.sourceMaps = true;
155}
156
5514e287RedMickey6 years ago157if (typeof args.enableDebug !== "boolean") {
158args.enableDebug = true;
159}
160
81fc1822JiglioNero4 years ago161// Now there is a problem with processing time of 'createFromSourceMap' function of js-debug
162// So we disable this functionality by default https://github.com/microsoft/vscode-js-debug/issues/1033
163if (typeof args.sourceMapRenames !== "boolean") {
164args.sourceMapRenames = false;
165}
166
43e6ccc3JiglioNero4 years ago167const projectRootPath = SettingsHelper.getReactNativeProjectRoot(args.cwd);
0d77292aJiglioNero4 years ago168const isReactProject = await ReactNativeProjectHelper.isReactNativeProject(
169projectRootPath,
170);
171if (!isReactProject) {
172throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError);
173}
4dfb1c4cetatanova5 years ago174
0d77292aJiglioNero4 years ago175const appLauncher = await AppLauncher.getOrCreateAppLauncherByProjectRootPath(
176projectRootPath,
4dfb1c4cetatanova5 years ago177);
0d77292aJiglioNero4 years ago178this.appLauncher = appLauncher;
179this.projectRootPath = projectRootPath;
180this.isSettingsInitialized = true;
181this.appLauncher.getOrUpdateNodeModulesRoot(true);
d93677adRedMickey4 years ago182if (this.vsCodeDebugSession.workspaceFolder) {
0d77292aJiglioNero4 years ago183this.appLauncher.updateDebugConfigurationRoot(
d93677adRedMickey4 years ago184this.vsCodeDebugSession.workspaceFolder.uri.fsPath,
0d77292aJiglioNero4 years ago185);
186}
2c19da7fRedMickey6 years ago187}
188}
984ca036RedMickey6 years ago189
34472878RedMickey5 years ago190protected async disconnectRequest(
191response: DebugProtocol.DisconnectResponse,
192args: DebugProtocol.DisconnectArguments,
193// eslint-disable-next-line @typescript-eslint/no-unused-vars
194request?: DebugProtocol.Request,
195): Promise<void> {
a32e1e1fYuri Skorokhodov5 years ago196if (this.appLauncher) {
197await this.appLauncher.getRnCdpProxy().stopServer();
198}
e23d1841RedMickey6 years ago199
200this.cancellationTokenSource.cancel();
201this.cancellationTokenSource.dispose();
202
203// Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
259c018fYuri Skorokhodov5 years ago204if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) {
e23d1841RedMickey6 years ago205try {
8df5011eYuri Skorokhodov5 years ago206this.appLauncher.getMobilePlatform().dispose();
e23d1841RedMickey6 years ago207} catch (err) {
34472878RedMickey5 years ago208logger.warn(
209localize(
210"CouldNotStopMonitoringLogcat",
211"Couldn't stop monitoring logcat: {0}",
212err.message || err,
213),
214);
e23d1841RedMickey6 years ago215}
216}
217
19df32dcRedMickey4 years ago218this.debugSessionStatus = DebugSessionStatus.Stopped;
67ffa5b4RedMickey6 years ago219await logger.dispose();
220
ebbd64f1RedMickey6 years ago221DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
d93677adRedMickey4 years ago222debugSession: this.vsCodeDebugSession,
ebbd64f1RedMickey6 years ago223args: {
a2ddbba5RedMickey5 years ago224forcedStop: !!(<any>args).forcedStop,
ebbd64f1RedMickey6 years ago225},
226});
227
228this.sendResponse(response);
e23d1841RedMickey6 years ago229}
230
19df32dcRedMickey4 years ago231protected terminateWithErrorResponse(error: Error, response: DebugProtocol.Response): void {
e23d1841RedMickey6 years ago232// We can't print error messages after the debugging session is stopped. This could break the extension work.
34472878RedMickey5 years ago233if (
234(error instanceof InternalError || error instanceof NestedError) &&
235error.errorCode === InternalErrorCode.CancellationTokenTriggered
e23d1841RedMickey6 years ago236) {
237return;
238}
239
28ceac00RedMickey4 years ago240logger.error(error.message);
241
984ca036RedMickey6 years ago242this.sendErrorResponse(
243response,
e23d1841RedMickey6 years ago244{ format: error.message, id: 1 },
984ca036RedMickey6 years ago245undefined,
246undefined,
34472878RedMickey5 years ago247ErrorDestination.User,
984ca036RedMickey6 years ago248);
249}
2c19da7fRedMickey6 years ago250
bfcc8a29Samriel4 years ago251protected async preparePackagerBeforeAttach(
252args: IAttachRequestArgs,
253reactNativeVersions: RNPackageVersions,
254): Promise<void> {
255if (!(await this.appLauncher.getPackager().isRunning())) {
256const runOptions: ILaunchArgs = Object.assign(
257{ reactNativeVersions },
258this.appLauncher.prepareBaseRunOptions(args),
259);
260this.appLauncher.getPackager().setRunOptions(runOptions);
261await this.appLauncher.getPackager().start();
262}
263}
19df32dcRedMickey4 years ago264
265protected showError(error: Error): void {
266void vscode.window.showErrorMessage(error.message, {
267modal: true,
268});
269// We can't print error messages via debug session logger after the session is stopped. This could break the extension work.
270if (this.debugSessionStatus === DebugSessionStatus.Stopped) {
271OutputChannelLogger.getMainChannel().error(error.message);
272return;
273}
274logger.error(error.message);
275}
276
277protected async terminate(): Promise<void> {
278await vscode.commands.executeCommand(this.stopCommand, undefined, {
279sessionId: this.vsCodeDebugSession.id,
280});
281}
2c19da7fRedMickey6 years ago282}
dc94981bQuan Jin3 years ago283
284/**
285* Parses settings.json file for workspace root property
286*/
287export function getProjectRoot(args: any): string {
288const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
289const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
290try {
291const settingsContent = fs.readFileSync(settingsPath, "utf8");
292const parsedSettings = stripJsonTrailingComma(settingsContent);
293const projectRootPath =
294parsedSettings["react-native-tools.projectRoot"] ||
295parsedSettings["react-native-tools"].projectRoot;
296return path.resolve(vsCodeRoot, projectRootPath);
297} catch (e) {
298logger.verbose(
299`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`,
300);
301return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
302}
303}