microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
cf911877212a8e04adfa526f170bcaeb217a1c6b

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/nodeDebugWrapper.ts

267lines · modeblame

e45838cbVladimir Kotikov9 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 Q from "q";
5import * as path from "path";
6import * as fs from "fs";
7import stripJsonComments = require("strip-json-comments");
8
b8999098Dmitry Zinovyev9 years ago9import { Telemetry } from "../common/telemetry";
10import { TelemetryHelper } from "../common/telemetryHelper";
11import { RemoteExtension } from "../common/remoteExtension";
3a155214Artem Egorov8 years ago12import { RemoteTelemetryReporter, ReassignableTelemetryReporter } from "../common/telemetryReporters";
2d876061Ruslan Bikkinin8 years ago13import { ChromeDebugSession, IChromeDebugSessionOpts, ChromeDebugAdapter, logger } from "vscode-chrome-debug-core";
e3b0fb3bChance An8 years ago14import { ContinuedEvent, TerminatedEvent, Logger, Response } from "vscode-debugadapter";
0a68f8dbArtem Egorov8 years ago15import { DebugProtocol } from "vscode-debugprotocol";
e45838cbVladimir Kotikov9 years ago16
17import { MultipleLifetimesAppWorker } from "./appWorker";
18
2d876061Ruslan Bikkinin8 years ago19import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
d124bf0eYuri Skorokhodov7 years ago20import * as nls from "vscode-nls";
21import { ErrorHelper } from "../common/error/errorHelper";
22import { InternalErrorCode } from "../common/error/internalErrorCode";
23const localize = nls.loadMessageBundle();
0a68f8dbArtem Egorov8 years ago24
b8999098Dmitry Zinovyev9 years ago25export function makeSession(
0a68f8dbArtem Egorov8 years ago26debugSessionClass: typeof ChromeDebugSession,
27debugSessionOpts: IChromeDebugSessionOpts,
b8999098Dmitry Zinovyev9 years ago28telemetryReporter: ReassignableTelemetryReporter,
0a68f8dbArtem Egorov8 years ago29appName: string, version: string): typeof ChromeDebugSession {
e45838cbVladimir Kotikov9 years ago30
31return class extends debugSessionClass {
32
33private projectRootPath: string;
34private remoteExtension: RemoteExtension;
5c8365a6Artem Egorov8 years ago35private appWorker: MultipleLifetimesAppWorker | null = null;
e45838cbVladimir Kotikov9 years ago36
37constructor(debuggerLinesAndColumnsStartAt1?: boolean, isServer?: boolean) {
38super(debuggerLinesAndColumnsStartAt1, isServer, debugSessionOpts);
39}
40
41// Override ChromeDebugSession's sendEvent to control what we will send to client
0a68f8dbArtem Egorov8 years ago42public sendEvent(event: DebugProtocol.Event): void {
e45838cbVladimir Kotikov9 years ago43// Do not send "terminated" events signaling about session's restart to client as it would cause it
44// to restart adapter's process, while we want to stay alive and don't want to interrupt connection
6c75098eVladimir9 years ago45// to packager.
b8999098Dmitry Zinovyev9 years ago46
720e992dArtem Egorov8 years ago47if (event.event === "terminated" && event.body && event.body.restart) {
b8999098Dmitry Zinovyev9 years ago48
49// Worker has been reloaded and switched to "continue" state
50// So we have to send "continued" event to client instead of "terminated"
51// Otherwise client might mistakenly show "stopped" state
0a68f8dbArtem Egorov8 years ago52let continuedEvent: ContinuedEvent = {
b8999098Dmitry Zinovyev9 years ago53event: "continued",
54type: "event",
55seq: event["seq"], // tslint:disable-line
56body: { threadId: event.body.threadId },
57};
58
59super.sendEvent(continuedEvent);
e45838cbVladimir Kotikov9 years ago60return;
61}
62
63super.sendEvent(event);
64}
65
0a68f8dbArtem Egorov8 years ago66protected dispatchRequest(request: DebugProtocol.Request): void {
e45838cbVladimir Kotikov9 years ago67if (request.command === "disconnect")
68return this.disconnect(request);
69
70if (request.command === "attach")
71return this.attach(request);
72
73if (request.command === "launch")
74return this.launch(request);
75
76return super.dispatchRequest(request);
77}
78
0a68f8dbArtem Egorov8 years ago79private launch(request: DebugProtocol.Request): void {
2d876061Ruslan Bikkinin8 years ago80this.requestSetup(request.arguments)
81.then(() => {
db6fd42aRuslan Bikkinin7 years ago82logger.verbose(`Handle launch request: ${JSON.stringify(request.arguments, null , 2)}`);
2d876061Ruslan Bikkinin8 years ago83return this.remoteExtension.launch(request);
84})
cbb0e869Artem Egorov8 years ago85.then(() => {
2e432a9eArtem Egorov8 years ago86return this.remoteExtension.getPackagerPort(request.arguments.program);
0a68f8dbArtem Egorov8 years ago87})
88.then((packagerPort: number) => {
6eeec3c0Serge Svekolnikov8 years ago89this.attachRequest({
90...request,
91arguments: {
92...request.arguments,
93port: packagerPort,
94},
95});
0a68f8dbArtem Egorov8 years ago96})
97.catch(error => {
748105d9Artem Egorov8 years ago98this.bailOut(error.data || error.message);
cbb0e869Artem Egorov8 years ago99});
e45838cbVladimir Kotikov9 years ago100}
101
0a68f8dbArtem Egorov8 years ago102private attach(request: DebugProtocol.Request): void {
2d876061Ruslan Bikkinin8 years ago103this.requestSetup(request.arguments)
104.then(() => {
db6fd42aRuslan Bikkinin7 years ago105logger.verbose(`Handle attach request: ${request.arguments}`);
2d876061Ruslan Bikkinin8 years ago106return this.remoteExtension.getPackagerPort(request.arguments.program);
107})
0a68f8dbArtem Egorov8 years ago108.then((packagerPort: number) => {
6eeec3c0Serge Svekolnikov8 years ago109this.attachRequest({
110...request,
111arguments: {
112...request.arguments,
e92278b5Serge Svekolnikov8 years ago113port: request.arguments.port || packagerPort,
6eeec3c0Serge Svekolnikov8 years ago114},
115});
2d876061Ruslan Bikkinin8 years ago116})
117.catch(error => {
118this.bailOut(error.data || error.message);
cbb0e869Artem Egorov8 years ago119});
e45838cbVladimir Kotikov9 years ago120}
121
0a68f8dbArtem Egorov8 years ago122private disconnect(request: DebugProtocol.Request): void {
e45838cbVladimir Kotikov9 years ago123// The client is about to disconnect so first we need to stop app worker
f920e582Vladimir Kotikov9 years ago124if (this.appWorker) {
125this.appWorker.stop();
126}
e45838cbVladimir Kotikov9 years ago127
128// Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
0a68f8dbArtem Egorov8 years ago129if (request.arguments.platform === "android") {
e45838cbVladimir Kotikov9 years ago130this.remoteExtension.stopMonitoringLogcat()
d124bf0eYuri Skorokhodov7 years ago131.catch(reason => logger.warn(localize("CouldNotStopMonitoringLogcat", "Couldn't stop monitoring logcat: {0}", reason.message || reason)))
b8999098Dmitry Zinovyev9 years ago132.finally(() => super.dispatchRequest(request));
e45838cbVladimir Kotikov9 years ago133} else {
134super.dispatchRequest(request);
135}
136}
137
2d876061Ruslan Bikkinin8 years ago138private requestSetup(args: any): Q.Promise<void> {
0a68f8dbArtem Egorov8 years ago139let logLevel: string = args.trace;
140if (logLevel) {
141logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
142logger.setup(Logger.LogLevel[logLevel], false);
143} else {
144logger.setup(Logger.LogLevel.Log, false);
145}
146
2d876061Ruslan Bikkinin8 years ago147const projectRootPath = getProjectRoot(args);
148return ReactNativeProjectHelper.isReactNativeProject(projectRootPath)
149.then((result) => {
150if (!result) {
d124bf0eYuri Skorokhodov7 years ago151throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError);
2d876061Ruslan Bikkinin8 years ago152}
153this.projectRootPath = projectRootPath;
154this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath);
155
156// Start to send telemetry
157telemetryReporter.reassignTo(new RemoteTelemetryReporter(
158appName, version, Telemetry.APPINSIGHTS_INSTRUMENTATIONKEY, this.projectRootPath));
159return void 0;
160});
e45838cbVladimir Kotikov9 years ago161}
162
163/**
164* Runs logic needed to attach.
165* Attach should:
166* - Enable js debugging
167*/
0a68f8dbArtem Egorov8 years ago168// tslint:disable-next-line:member-ordering
031832ffArtem Egorov8 years ago169protected attachRequest(request: DebugProtocol.Request): Q.Promise<void> {
170const extProps = {
171platform: {
172value: request.arguments.platform,
173isPii: false,
174},
175};
176
177return TelemetryHelper.generate("attach", extProps, (generator) => {
e45838cbVladimir Kotikov9 years ago178return Q({})
179.then(() => {
d124bf0eYuri Skorokhodov7 years ago180logger.log(localize("StartingDebuggerAppWorker", "Starting debugger app worker."));
e45838cbVladimir Kotikov9 years ago181// TODO: remove dependency on args.program - "program" property is technically
182// no more required in launch configuration and could be removed
183const workspaceRootPath = path.resolve(path.dirname(request.arguments.program), "..");
184const sourcesStoragePath = path.join(workspaceRootPath, ".vscode", ".react");
185
186// If launch is invoked first time, appWorker is undefined, so create it here
6eeec3c0Serge Svekolnikov8 years ago187this.appWorker = new MultipleLifetimesAppWorker(
188request.arguments,
189sourcesStoragePath,
190this.projectRootPath,
191undefined);
e45838cbVladimir Kotikov9 years ago192this.appWorker.on("connected", (port: number) => {
d124bf0eYuri Skorokhodov7 years ago193logger.log(localize("DebuggerWorkerLoadedRuntimeOnPort", "Debugger worker loaded runtime on port {0}", port));
e45838cbVladimir Kotikov9 years ago194// Don't mutate original request to avoid side effects
6eeec3c0Serge Svekolnikov8 years ago195let attachArguments = Object.assign({}, request.arguments, {
196address: "localhost",
197port,
198restart: true,
199request: "attach",
200remoteRoot: undefined,
201localRoot: undefined,
202});
6c75098eVladimir9 years ago203// Reinstantiate debug adapter, as the current implementation of ChromeDebugAdapter
204// doesn't allow us to reattach to another debug target easily. As of now it's easier
205// to throw previous instance out and create a new one.
0a68f8dbArtem Egorov8 years ago206(this as any)._debugAdapter = new (<any>debugSessionOpts.adapter)(debugSessionOpts, this);
e3b0fb3bChance An8 years ago207
208// Explicity call _debugAdapter.attach() to prevent directly calling dispatchRequest()
209// yield a response as "attach" even for "launch" request. Because dispatchRequest() will
210// decide to do a sendResponse() aligning with the request parameter passed in.
211Q((this as any)._debugAdapter.attach(attachArguments, request.seq))
2d876061Ruslan Bikkinin8 years ago212.then((responseBody) => {
213const response: DebugProtocol.Response = new Response(request);
214response.body = responseBody;
215this.sendResponse(response);
216});
e45838cbVladimir Kotikov9 years ago217});
218
219return this.appWorker.start();
220})
221.catch(error => this.bailOut(error.message));
222});
223}
224
225/**
226* Logs error to user and finishes the debugging process.
227*/
228private bailOut(message: string): void {
d124bf0eYuri Skorokhodov7 years ago229logger.error(localize("CouldNotDebug", "Could not debug. {0}" , message));
0a68f8dbArtem Egorov8 years ago230this.sendEvent(new TerminatedEvent());
27710197Vladimir Kotikov8 years ago231}
e45838cbVladimir Kotikov9 years ago232};
233}
234
0a68f8dbArtem Egorov8 years ago235export function makeAdapter(debugAdapterClass: typeof ChromeDebugAdapter): typeof ChromeDebugAdapter {
e45838cbVladimir Kotikov9 years ago236return class extends debugAdapterClass {
4f7b3bc0Anna Kocheshkova8 years ago237public doAttach(port: number, targetUrl?: string, address?: string, timeout?: number): Promise<void> {
4b86d595Vladimir Kotikov9 years ago238// We need to overwrite ChromeDebug's _attachMode to let Node2 adapter
e45838cbVladimir Kotikov9 years ago239// to set up breakpoints on initial pause event
0a68f8dbArtem Egorov8 years ago240(this as any)._attachMode = false;
e45838cbVladimir Kotikov9 years ago241return super.doAttach(port, targetUrl, address, timeout);
242}
639a73d7Artem Egorov7 years ago243
244public async terminate(args: DebugProtocol.TerminatedEvent) {
245return this.disconnect({
246terminateDebuggee: true,
247});
248}
e45838cbVladimir Kotikov9 years ago249};
250}
251
252/**
253* Parses settings.json file for workspace root property
254*/
255function getProjectRoot(args: any): string {
256try {
257let vsCodeRoot = path.resolve(args.program, "../..");
258let settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
259let settingsContent = fs.readFileSync(settingsPath, "utf8");
260settingsContent = stripJsonComments(settingsContent);
261let parsedSettings = JSON.parse(settingsContent);
9a364375Serge Svekolnikov8 years ago262let projectRootPath = parsedSettings["react-native-tools.projectRoot"] || parsedSettings["react-native-tools"].projectRoot;
e45838cbVladimir Kotikov9 years ago263return path.resolve(vsCodeRoot, projectRootPath);
264} catch (e) {
265return path.resolve(args.program, "../..");
266}
267}