microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/nodeDebugWrapper.ts
256lines · modeblame
e45838cbVladimir Kotikov9 years ago | 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 {IOSPlatform} from "./ios/iOSPlatform"; | |
| 13 | import {PlatformResolver} from "./platformResolver"; | |
| 14 | import {IRunOptions} from "../common/launchArgs"; | |
| 15 | import {TargetPlatformHelper} from "../common/targetPlatformHelper"; | |
| 16 | import {ExtensionTelemetryReporter, ReassignableTelemetryReporter} from "../common/telemetryReporters"; | |
| 17 | import {NodeDebugAdapterLogger} from "../common/log/loggers"; | |
| 18 | import {Log} from "../common/log/log"; | |
| 19 | import {GeneralMobilePlatform} from "../common/generalMobilePlatform"; | |
| 20 | | |
| 21 | import { MultipleLifetimesAppWorker } from "./appWorker"; | |
| 22 | import { ForkedAppWorker } from "./forkedAppWorker"; | |
| 23 | | |
| 24 | export function makeSession(debugSessionClass: typeof ChromeDebuggerCorePackage.ChromeDebugSession, | |
| 25 | debugSessionOpts: ChromeDebuggerCorePackage.IChromeDebugSessionOpts, | |
| 26 | debugAdapterPackage: typeof VSCodeDebugAdapterPackage, | |
| 27 | telemetryReporter: ReassignableTelemetryReporter, | |
| 28 | appName: string, version: string): typeof ChromeDebuggerCorePackage.ChromeDebugSession { | |
| 29 | | |
| 30 | return class extends debugSessionClass { | |
| 31 | | |
| 32 | private projectRootPath: string; | |
| 33 | private remoteExtension: RemoteExtension; | |
| 34 | private mobilePlatformOptions: IRunOptions; | |
| 35 | private appWorker: MultipleLifetimesAppWorker = null; | |
| 36 | | |
| 37 | constructor(debuggerLinesAndColumnsStartAt1?: boolean, isServer?: boolean) { | |
| 38 | super(debuggerLinesAndColumnsStartAt1, isServer, debugSessionOpts); | |
| 39 | } | |
| 40 | | |
| 41 | // Override ChromeDebugSession's sendEvent to control what we will send to client | |
| 42 | public sendEvent(event: VSCodeDebugAdapterPackage.Event): void { | |
| 43 | // 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 | |
| 45 | // to packager. Also in this case we need to reinstantiate the debug adapter, as the current | |
| 46 | // implementation of ChromeDebugAdapter doesn't allow us to reattach to another debug target easily. | |
| 47 | // As of now it's easier to throw previous instance out and create a new one. | |
| 48 | if (event.event === "terminated" && event.body && event.body.restart === true) { | |
| 49 | // Casting debugAdapter to any to make this compile, as TS doesn't allow instantiating abstract classes | |
| 50 | this._debugAdapter = new (<any>debugSessionOpts.adapter)(debugSessionOpts, this); | |
| 51 | return; | |
| 52 | } | |
| 53 | | |
| 54 | super.sendEvent(event); | |
| 55 | } | |
| 56 | | |
| 57 | protected dispatchRequest(request: VSCodeDebugAdapterPackage.Request): void { | |
| 58 | if (request.command === "disconnect") | |
| 59 | return this.disconnect(request); | |
| 60 | | |
| 61 | if (request.command === "attach") | |
| 62 | return this.attach(request); | |
| 63 | | |
| 64 | if (request.command === "launch") | |
| 65 | return this.launch(request); | |
| 66 | | |
| 67 | return super.dispatchRequest(request); | |
| 68 | } | |
| 69 | | |
| 70 | private launch(request: VSCodeDebugAdapterPackage.Request): void { | |
| 71 | this.requestSetup(request.arguments); | |
| 72 | this.mobilePlatformOptions.target = request.arguments.target || "simulator"; | |
| 73 | this.mobilePlatformOptions.iosRelativeProjectPath = !isNullOrUndefined(request.arguments.iosRelativeProjectPath) ? | |
| 74 | request.arguments.iosRelativeProjectPath : | |
| 75 | IOSPlatform.DEFAULT_IOS_PROJECT_RELATIVE_PATH; | |
| 76 | | |
| 77 | // We add the parameter if it's defined (adapter crashes otherwise) | |
| 78 | if (!isNullOrUndefined(request.arguments.logCatArguments)) { | |
| 79 | this.mobilePlatformOptions.logCatArguments = [parseLogCatArguments(request.arguments.logCatArguments)]; | |
| 80 | } | |
| 81 | | |
| 82 | if (!isNullOrUndefined(request.arguments.variant)) { | |
| 83 | this.mobilePlatformOptions.variant = request.arguments.variant; | |
| 84 | } | |
| 85 | | |
| 86 | TelemetryHelper.generate("launch", (generator) => { | |
| 87 | return this.remoteExtension.getPackagerPort() | |
| 88 | .then((packagerPort: number) => { | |
| 89 | this.mobilePlatformOptions.packagerPort = packagerPort; | |
| 90 | const mobilePlatform = new PlatformResolver() | |
| 91 | .resolveMobilePlatform(request.arguments.platform, this.mobilePlatformOptions); | |
| 92 | | |
| 93 | generator.step("checkPlatformCompatibility"); | |
| 94 | TargetPlatformHelper.checkTargetPlatformSupport(this.mobilePlatformOptions.platform); | |
| 95 | generator.step("startPackager"); | |
| 96 | return mobilePlatform.startPackager() | |
| 97 | .then(() => { | |
| 98 | // We've seen that if we don't prewarm the bundle cache, the app fails on the first attempt to connect to the debugger logic | |
| 99 | // and the user needs to Reload JS manually. We prewarm it to prevent that issue | |
| 100 | generator.step("prewarmBundleCache"); | |
| 101 | Log.logMessage("Prewarming bundle cache. This may take a while ..."); | |
| 102 | return mobilePlatform.prewarmBundleCache(); | |
| 103 | }) | |
| 104 | .then(() => { | |
| 105 | generator.step("mobilePlatform.runApp"); | |
| 106 | Log.logMessage("Building and running application."); | |
| 107 | return mobilePlatform.runApp(); | |
| 108 | }) | |
| 109 | .then(() => { | |
f920e582Vladimir Kotikov9 years ago | 110 | return this.attachRequest(request, packagerPort, mobilePlatform); |
e45838cbVladimir Kotikov9 years ago | 111 | }); |
f920e582Vladimir Kotikov9 years ago | 112 | }) |
| 113 | .catch(error => this.bailOut(error.message)); | |
e45838cbVladimir Kotikov9 years ago | 114 | }); |
| 115 | | |
| 116 | } | |
| 117 | | |
| 118 | private attach(request: VSCodeDebugAdapterPackage.Request): void { | |
| 119 | this.requestSetup(request.arguments); | |
f920e582Vladimir Kotikov9 years ago | 120 | this.remoteExtension.getPackagerPort() |
| 121 | .then((packagerPort: number) => this.attachRequest(request, packagerPort)); | |
e45838cbVladimir Kotikov9 years ago | 122 | } |
| 123 | | |
| 124 | private disconnect(request: VSCodeDebugAdapterPackage.Request): void { | |
| 125 | // The client is about to disconnect so first we need to stop app worker | |
f920e582Vladimir Kotikov9 years ago | 126 | if (this.appWorker) { |
| 127 | this.appWorker.stop(); | |
| 128 | } | |
e45838cbVladimir Kotikov9 years ago | 129 | |
| 130 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session | |
| 131 | if (this.mobilePlatformOptions.platform === "android") { | |
| 132 | this.remoteExtension.stopMonitoringLogcat() | |
| 133 | .catch(reason => Log.logError(`WARNING: Couldn't stop monitoring logcat: ${reason.message || reason}\n`)) | |
| 134 | .finally(() => super.dispatchRequest(request)); | |
| 135 | } else { | |
| 136 | super.dispatchRequest(request); | |
| 137 | } | |
| 138 | } | |
| 139 | | |
f920e582Vladimir Kotikov9 years ago | 140 | private requestSetup(args: any): void { |
e45838cbVladimir Kotikov9 years ago | 141 | this.projectRootPath = getProjectRoot(args); |
| 142 | this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath); | |
| 143 | this.mobilePlatformOptions = { | |
| 144 | projectRoot: this.projectRootPath, | |
| 145 | platform: args.platform, | |
| 146 | }; | |
| 147 | | |
| 148 | // Start to send telemetry | |
| 149 | telemetryReporter.reassignTo(new ExtensionTelemetryReporter( | |
| 150 | appName, version, Telemetry.APPINSIGHTS_INSTRUMENTATIONKEY, this.projectRootPath)); | |
| 151 | | |
| 152 | Log.SetGlobalLogger(new NodeDebugAdapterLogger(debugAdapterPackage, this)); | |
| 153 | } | |
| 154 | | |
| 155 | /** | |
| 156 | * Runs logic needed to attach. | |
| 157 | * Attach should: | |
| 158 | * - Enable js debugging | |
| 159 | */ | |
f920e582Vladimir Kotikov9 years ago | 160 | private attachRequest(request: VSCodeDebugAdapterPackage.Request, |
| 161 | packagerPort: number, | |
| 162 | mobilePlatform?: GeneralMobilePlatform): Q.Promise<void> { | |
e45838cbVladimir Kotikov9 years ago | 163 | return TelemetryHelper.generate("attach", (generator) => { |
| 164 | return Q({}) | |
| 165 | .then(() => { | |
| 166 | generator.step("mobilePlatform.enableJSDebuggingMode"); | |
| 167 | if (mobilePlatform) { | |
| 168 | return mobilePlatform.enableJSDebuggingMode(); | |
| 169 | } else { | |
| 170 | Log.logMessage("Debugger ready. Enable remote debugging in app."); | |
| 171 | } | |
| 172 | }) | |
| 173 | .then(() => { | |
| 174 | | |
| 175 | Log.logMessage("Starting debugger app worker."); | |
| 176 | // TODO: remove dependency on args.program - "program" property is technically | |
| 177 | // no more required in launch configuration and could be removed | |
| 178 | const workspaceRootPath = path.resolve(path.dirname(request.arguments.program), ".."); | |
| 179 | const sourcesStoragePath = path.join(workspaceRootPath, ".vscode", ".react"); | |
| 180 | | |
| 181 | // If launch is invoked first time, appWorker is undefined, so create it here | |
f920e582Vladimir Kotikov9 years ago | 182 | this.appWorker = new MultipleLifetimesAppWorker(packagerPort, sourcesStoragePath, { |
e45838cbVladimir Kotikov9 years ago | 183 | // Inject our custom debuggee worker |
| 184 | sandboxedAppConstructor: (path: string, messageFunc: (message: any) => void) => | |
f920e582Vladimir Kotikov9 years ago | 185 | new ForkedAppWorker(packagerPort, path, messageFunc), |
e45838cbVladimir Kotikov9 years ago | 186 | } |
| 187 | ); | |
| 188 | | |
| 189 | this.appWorker.on("connected", (port: number) => { | |
f920e582Vladimir Kotikov9 years ago | 190 | Log.logMessage("Debugger worker loaded runtime on port " + port); |
e45838cbVladimir Kotikov9 years ago | 191 | // Don't mutate original request to avoid side effects |
| 192 | let attachArguments = Object.assign({}, request.arguments, { port, restart: true, request: "attach" }); | |
| 193 | let attachRequest = Object.assign({}, request, { command: "attach", arguments: attachArguments }); | |
| 194 | | |
| 195 | super.dispatchRequest(attachRequest); | |
| 196 | }); | |
| 197 | | |
| 198 | return this.appWorker.start(); | |
| 199 | }) | |
| 200 | .catch(error => this.bailOut(error.message)); | |
| 201 | }); | |
| 202 | } | |
| 203 | | |
| 204 | /** | |
| 205 | * Logs error to user and finishes the debugging process. | |
| 206 | */ | |
| 207 | private bailOut(message: string): void { | |
| 208 | Log.logError(`Could not debug. ${message}`); | |
8049d420Vladimir Kotikov9 years ago | 209 | this.sendEvent(new debugAdapterPackage.TerminatedEvent()); |
e45838cbVladimir Kotikov9 years ago | 210 | }; |
| 211 | }; | |
| 212 | } | |
| 213 | | |
| 214 | export function makeAdapter(debugAdapterClass: typeof Node2DebugAdapterPackage.Node2DebugAdapter): typeof Node2DebugAdapterPackage.Node2DebugAdapter { | |
| 215 | return class extends debugAdapterClass { | |
| 216 | public doAttach(port: number, targetUrl?: string, address?: string, timeout?: number): Promise<void> { | |
4b86d595Vladimir Kotikov9 years ago | 217 | // We need to overwrite ChromeDebug's _attachMode to let Node2 adapter |
e45838cbVladimir Kotikov9 years ago | 218 | // to set up breakpoints on initial pause event |
| 219 | this._attachMode = false; | |
| 220 | return super.doAttach(port, targetUrl, address, timeout); | |
| 221 | } | |
| 222 | }; | |
| 223 | } | |
| 224 | | |
| 225 | /** | |
| 226 | * Parses log cat arguments to a string | |
| 227 | */ | |
| 228 | function parseLogCatArguments(userProvidedLogCatArguments: any): string { | |
| 229 | return Array.isArray(userProvidedLogCatArguments) | |
| 230 | ? userProvidedLogCatArguments.join(" ") // If it's an array, we join the arguments | |
| 231 | : userProvidedLogCatArguments; // If not, we leave it as-is | |
| 232 | } | |
| 233 | | |
| 234 | /** | |
| 235 | * Helper method to know if a value is either null or undefined | |
| 236 | */ | |
| 237 | function isNullOrUndefined(value: any): boolean { | |
| 238 | return typeof value === "undefined" || value === null; | |
| 239 | } | |
| 240 | | |
| 241 | /** | |
| 242 | * Parses settings.json file for workspace root property | |
| 243 | */ | |
| 244 | function getProjectRoot(args: any): string { | |
| 245 | try { | |
| 246 | let vsCodeRoot = path.resolve(args.program, "../.."); | |
| 247 | let settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); | |
| 248 | let settingsContent = fs.readFileSync(settingsPath, "utf8"); | |
| 249 | settingsContent = stripJsonComments(settingsContent); | |
| 250 | let parsedSettings = JSON.parse(settingsContent); | |
| 251 | let projectRootPath = parsedSettings["react-native-tools"].projectRoot; | |
| 252 | return path.resolve(vsCodeRoot, projectRootPath); | |
| 253 | } catch (e) { | |
| 254 | return path.resolve(args.program, "../.."); | |
| 255 | } | |
| 256 | } |