microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/nodeDebugWrapper.ts
204lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. |
| 3 | |
| 4 | import * as Q from "q"; |
| 5 | import * as path from "path"; |
| 6 | import * as fs from "fs"; |
| 7 | import stripJsonComments = require("strip-json-comments"); |
| 8 | |
| 9 | import { Telemetry } from "../common/telemetry"; |
| 10 | import { TelemetryHelper } from "../common/telemetryHelper"; |
| 11 | import { RemoteExtension } from "../common/remoteExtension"; |
| 12 | import { ExtensionTelemetryReporter, ReassignableTelemetryReporter } from "../common/telemetryReporters"; |
| 13 | import { ChromeDebugSession, IChromeDebugSessionOpts, ChromeDebugAdapter, logger } from "vscode-chrome-debug-core"; |
| 14 | import { ContinuedEvent, TerminatedEvent, Logger } from "vscode-debugadapter"; |
| 15 | import { DebugProtocol } from "vscode-debugprotocol"; |
| 16 | |
| 17 | import { MultipleLifetimesAppWorker } from "./appWorker"; |
| 18 | |
| 19 | |
| 20 | export function makeSession( |
| 21 | debugSessionClass: typeof ChromeDebugSession, |
| 22 | debugSessionOpts: IChromeDebugSessionOpts, |
| 23 | telemetryReporter: ReassignableTelemetryReporter, |
| 24 | appName: string, version: string): typeof ChromeDebugSession { |
| 25 | |
| 26 | return class extends debugSessionClass { |
| 27 | |
| 28 | private projectRootPath: string; |
| 29 | private remoteExtension: RemoteExtension; |
| 30 | private appWorker: MultipleLifetimesAppWorker | null = null; |
| 31 | |
| 32 | constructor(debuggerLinesAndColumnsStartAt1?: boolean, isServer?: boolean) { |
| 33 | super(debuggerLinesAndColumnsStartAt1, isServer, debugSessionOpts); |
| 34 | } |
| 35 | |
| 36 | // Override ChromeDebugSession's sendEvent to control what we will send to client |
| 37 | public sendEvent(event: DebugProtocol.Event): void { |
| 38 | // Do not send "terminated" events signaling about session's restart to client as it would cause it |
| 39 | // to restart adapter's process, while we want to stay alive and don't want to interrupt connection |
| 40 | // to packager. |
| 41 | |
| 42 | if (event.event === "terminated" && event.body && event.body.restart) { |
| 43 | |
| 44 | // Worker has been reloaded and switched to "continue" state |
| 45 | // So we have to send "continued" event to client instead of "terminated" |
| 46 | // Otherwise client might mistakenly show "stopped" state |
| 47 | let continuedEvent: ContinuedEvent = { |
| 48 | event: "continued", |
| 49 | type: "event", |
| 50 | seq: event["seq"], // tslint:disable-line |
| 51 | body: { threadId: event.body.threadId }, |
| 52 | }; |
| 53 | |
| 54 | super.sendEvent(continuedEvent); |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | super.sendEvent(event); |
| 59 | } |
| 60 | |
| 61 | protected dispatchRequest(request: DebugProtocol.Request): void { |
| 62 | if (request.command === "disconnect") |
| 63 | return this.disconnect(request); |
| 64 | |
| 65 | if (request.command === "attach") |
| 66 | return this.attach(request); |
| 67 | |
| 68 | if (request.command === "launch") |
| 69 | return this.launch(request); |
| 70 | |
| 71 | return super.dispatchRequest(request); |
| 72 | } |
| 73 | |
| 74 | private launch(request: DebugProtocol.Request): void { |
| 75 | this.requestSetup(request.arguments); |
| 76 | this.remoteExtension.launch(request) |
| 77 | .then(() => { |
| 78 | return this.remoteExtension.getPackagerPort(); |
| 79 | }) |
| 80 | .then((packagerPort: number) => { |
| 81 | this.attachRequest(request, packagerPort); |
| 82 | }) |
| 83 | .catch(error => { |
| 84 | this.bailOut(error.message); |
| 85 | }); |
| 86 | } |
| 87 | |
| 88 | private attach(request: DebugProtocol.Request): void { |
| 89 | this.requestSetup(request.arguments); |
| 90 | this.remoteExtension.getPackagerPort() |
| 91 | .then((packagerPort: number) => { |
| 92 | this.attachRequest(request, packagerPort); |
| 93 | }); |
| 94 | } |
| 95 | |
| 96 | private disconnect(request: DebugProtocol.Request): void { |
| 97 | // The client is about to disconnect so first we need to stop app worker |
| 98 | if (this.appWorker) { |
| 99 | this.appWorker.stop(); |
| 100 | } |
| 101 | |
| 102 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session |
| 103 | if (request.arguments.platform === "android") { |
| 104 | this.remoteExtension.stopMonitoringLogcat() |
| 105 | .catch(reason => logger.warn(`Couldn't stop monitoring logcat: ${reason.message || reason}`)) |
| 106 | .finally(() => super.dispatchRequest(request)); |
| 107 | } else { |
| 108 | super.dispatchRequest(request); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | private requestSetup(args: any): void { |
| 113 | let logLevel: string = args.trace; |
| 114 | if (logLevel) { |
| 115 | logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase()); |
| 116 | logger.setup(Logger.LogLevel[logLevel], false); |
| 117 | } else { |
| 118 | logger.setup(Logger.LogLevel.Log, false); |
| 119 | } |
| 120 | |
| 121 | this.projectRootPath = getProjectRoot(args); |
| 122 | this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath); |
| 123 | |
| 124 | // Start to send telemetry |
| 125 | telemetryReporter.reassignTo(new ExtensionTelemetryReporter( |
| 126 | appName, version, Telemetry.APPINSIGHTS_INSTRUMENTATIONKEY, this.projectRootPath)); |
| 127 | } |
| 128 | |
| 129 | /** |
| 130 | * Runs logic needed to attach. |
| 131 | * Attach should: |
| 132 | * - Enable js debugging |
| 133 | */ |
| 134 | // tslint:disable-next-line:member-ordering |
| 135 | protected attachRequest( |
| 136 | request: DebugProtocol.Request, |
| 137 | packagerPort: number): Q.Promise<void> { |
| 138 | return TelemetryHelper.generate("attach", (generator) => { |
| 139 | return Q({}) |
| 140 | .then(() => { |
| 141 | logger.log("Starting debugger app worker."); |
| 142 | // TODO: remove dependency on args.program - "program" property is technically |
| 143 | // no more required in launch configuration and could be removed |
| 144 | const workspaceRootPath = path.resolve(path.dirname(request.arguments.program), ".."); |
| 145 | const sourcesStoragePath = path.join(workspaceRootPath, ".vscode", ".react"); |
| 146 | |
| 147 | // If launch is invoked first time, appWorker is undefined, so create it here |
| 148 | this.appWorker = new MultipleLifetimesAppWorker(packagerPort, sourcesStoragePath); |
| 149 | this.appWorker.on("connected", (port: number) => { |
| 150 | logger.log("Debugger worker loaded runtime on port " + port); |
| 151 | // Don't mutate original request to avoid side effects |
| 152 | let attachArguments = Object.assign({}, request.arguments, { port, restart: true, request: "attach" }); |
| 153 | let attachRequest = Object.assign({}, request, { command: "attach", arguments: attachArguments }); |
| 154 | |
| 155 | // Reinstantiate debug adapter, as the current implementation of ChromeDebugAdapter |
| 156 | // doesn't allow us to reattach to another debug target easily. As of now it's easier |
| 157 | // to throw previous instance out and create a new one. |
| 158 | (this as any)._debugAdapter = new (<any>debugSessionOpts.adapter)(debugSessionOpts, this); |
| 159 | super.dispatchRequest(attachRequest); |
| 160 | }); |
| 161 | |
| 162 | return this.appWorker.start(); |
| 163 | }) |
| 164 | .catch(error => this.bailOut(error.message)); |
| 165 | }); |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * Logs error to user and finishes the debugging process. |
| 170 | */ |
| 171 | private bailOut(message: string): void { |
| 172 | logger.error(`Could not debug. ${message}`); |
| 173 | this.sendEvent(new TerminatedEvent()); |
| 174 | } |
| 175 | }; |
| 176 | } |
| 177 | |
| 178 | export function makeAdapter(debugAdapterClass: typeof ChromeDebugAdapter): typeof ChromeDebugAdapter { |
| 179 | return class extends debugAdapterClass { |
| 180 | public doAttach(port: number, targetUrl?: string, address?: string, timeout?: number): Promise<void> { |
| 181 | // We need to overwrite ChromeDebug's _attachMode to let Node2 adapter |
| 182 | // to set up breakpoints on initial pause event |
| 183 | (this as any)._attachMode = false; |
| 184 | return super.doAttach(port, targetUrl, address, timeout); |
| 185 | } |
| 186 | }; |
| 187 | } |
| 188 | |
| 189 | /** |
| 190 | * Parses settings.json file for workspace root property |
| 191 | */ |
| 192 | function getProjectRoot(args: any): string { |
| 193 | try { |
| 194 | let vsCodeRoot = path.resolve(args.program, "../.."); |
| 195 | let settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); |
| 196 | let settingsContent = fs.readFileSync(settingsPath, "utf8"); |
| 197 | settingsContent = stripJsonComments(settingsContent); |
| 198 | let parsedSettings = JSON.parse(settingsContent); |
| 199 | let projectRootPath = parsedSettings["react-native-tools"].projectRoot; |
| 200 | return path.resolve(vsCodeRoot, projectRootPath); |
| 201 | } catch (e) { |
| 202 | return path.resolve(args.program, "../.."); |
| 203 | } |
| 204 | } |
| 205 | |