microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
280c07463f45573fc0cd19fc2d2eb91eb3e828fd

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/rn-extension.ts

174lines · 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
4import * as fs from "fs";
5
6// @ifdef DEBUG
7try {
8 fs.statSync(`${__filename}.map`); // We check if source maps are available
9 /* tslint:disable:no-var-requires */
10 require("source-map-support").install(); // If they are, we enable stack traces translation to typescript
11 /* tslint:enable:no-var-requires */
12} catch (exceptions) {
13 // If something goes wrong, we just ignore the errors
14}
15// @endif
16
17import * as Q from "q";
18import * as path from "path";
19import * as vscode from "vscode";
20
21import {FileSystem} from "../common/node/fileSystem";
22import {CommandPaletteHandler} from "./commandPaletteHandler";
23import {Packager} from "../common/packager";
24import {EntryPointHandler, ProcessType} from "../common/entryPointHandler";
25import {ErrorHelper} from "../common/error/errorHelper";
26import {InternalError} from "../common/error/internalError";
27import {InternalErrorCode} from "../common/error/internalErrorCode";
28import {Log} from "../common/log/log";
29import {PackagerStatusIndicator} from "./packagerStatusIndicator";
30import {ReactNativeProjectHelper} from "../common/reactNativeProjectHelper";
31import {ReactDirManager} from "./reactDirManager";
32import {IntellisenseHelper} from "./intellisenseHelper";
33import {Telemetry} from "../common/telemetry";
34import {TelemetryHelper} from "../common/telemetryHelper";
35import {ExtensionServer} from "./extensionServer";
36import {DelayedOutputChannelLogger} from "./outputChannelLogger";
37import {ExponentHelper} from "../common/exponent/exponentHelper";
38
39/* all components use the same packager instance */
40const projectRootPath = vscode.workspace.rootPath;
41const globalPackager = new Packager(projectRootPath);
42const packagerStatusIndicator = new PackagerStatusIndicator();
43const globalExponentHelper = new ExponentHelper(projectRootPath);
44const commandPaletteHandler = new CommandPaletteHandler(projectRootPath, globalPackager, packagerStatusIndicator, globalExponentHelper);
45
46const outputChannelLogger = new DelayedOutputChannelLogger("React-Native");
47const entryPointHandler = new EntryPointHandler(ProcessType.Extension, outputChannelLogger);
48const reactNativeProjectHelper = new ReactNativeProjectHelper(projectRootPath);
49const fsUtil = new FileSystem();
50
51interface ISetupableDisposable extends vscode.Disposable {
52 setup(): Q.Promise<any>;
53}
54
55export function activate(context: vscode.ExtensionContext): void {
56
57 entryPointHandler.runApp("react-native", () => <string>require("../../package.json").version,
58 ErrorHelper.getInternalError(InternalErrorCode.ExtensionActivationFailed), projectRootPath, () => {
59 return reactNativeProjectHelper.isReactNativeProject()
60 .then(isRNProject => {
61 if (isRNProject) {
62 let activateExtensionEvent = TelemetryHelper.createTelemetryEvent("activate");
63 Telemetry.send(activateExtensionEvent);
64
65 warnWhenReactNativeVersionIsNotSupported();
66 entryPointHandler.runFunction("debugger.setupLauncherStub",
67 ErrorHelper.getInternalError(InternalErrorCode.DebuggerStubLauncherFailed), () =>
68 setupReactNativeDebugger()
69 .then(() =>
70 setupAndDispose(new ReactDirManager(), context))
71 .then(() =>
72 setupAndDispose(new ExtensionServer(projectRootPath, globalPackager, packagerStatusIndicator, globalExponentHelper), context))
73 .then(() => {}));
74 entryPointHandler.runFunction("intelliSense.setup",
75 ErrorHelper.getInternalError(InternalErrorCode.IntellisenseSetupFailed), () =>
76 IntellisenseHelper.setupReactNativeIntellisense());
77 }
78 entryPointHandler.runFunction("debugger.setupNodeDebuggerLocation",
79 ErrorHelper.getInternalError(InternalErrorCode.NodeDebuggerConfigurationFailed), () =>
80 configureNodeDebuggerLocation());
81 registerReactNativeCommands(context);
82 });
83 });
84}
85
86export function deactivate(): void {
87 // Kill any packager processes that we spawned
88 entryPointHandler.runFunction("extension.deactivate",
89 ErrorHelper.getInternalError(InternalErrorCode.FailedToStopPackagerOnExit),
90 () => {
91 commandPaletteHandler.stopPackager();
92 }, /*errorsAreFatal*/ true);
93}
94
95function configureNodeDebuggerLocation(): Q.Promise<void> {
96 const nodeDebugExtension = vscode.extensions.getExtension("ms-vscode.node-debug") // We try to get the new version
97 || vscode.extensions.getExtension("andreweinand.node-debug"); // If it's not available, we try to get the old version
98 if (!nodeDebugExtension) {
99 return Q.reject<void>(ErrorHelper.getInternalError(InternalErrorCode.CouldNotFindLocationOfNodeDebugger));
100 }
101 const nodeDebugPath = nodeDebugExtension.extensionPath;
102 return fsUtil.writeFile(path.resolve(__dirname, "../", "debugger", "nodeDebugLocation.json"), JSON.stringify({ nodeDebugPath }));
103}
104
105function setupAndDispose<T extends ISetupableDisposable>(setuptableDisposable: T, context: vscode.ExtensionContext): Q.Promise<T> {
106 return setuptableDisposable.setup()
107 .then(() => {
108 context.subscriptions.push(setuptableDisposable);
109 return setuptableDisposable;
110 });
111}
112
113function warnWhenReactNativeVersionIsNotSupported(): void {
114 return reactNativeProjectHelper.validateReactNativeVersion().done(() => { }, reason => {
115 TelemetryHelper.sendSimpleEvent("unsupportedRNVersion", { rnVersion: reason });
116 const shortMessage = `React Native Tools need React Native version 0.19.0 or later to be installed in <PROJECT_ROOT>/node_modules/`;
117 const longMessage = `${shortMessage}: ${reason}`;
118 vscode.window.showWarningMessage(shortMessage);
119 Log.logMessage(longMessage);
120 });
121}
122
123function registerReactNativeCommands(context: vscode.ExtensionContext): void {
124 // Register React Native commands
125 registerVSCodeCommand(context, "runAndroid", ErrorHelper.getInternalError(InternalErrorCode.FailedToRunOnAndroid), () => commandPaletteHandler.runAndroid());
126 registerVSCodeCommand(context, "runIos", ErrorHelper.getInternalError(InternalErrorCode.FailedToRunOnIos), () => commandPaletteHandler.runIos());
127 registerVSCodeCommand(context, "startPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStartPackager), () => commandPaletteHandler.startPackager());
128 registerVSCodeCommand(context, "startExponentPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStartExponentPackager), () => commandPaletteHandler.startExponentPackager());
129 registerVSCodeCommand(context, "stopPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStopPackager), () => commandPaletteHandler.stopPackager());
130 registerVSCodeCommand(context, "restartPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToRestartPackager), () => commandPaletteHandler.restartPackager());
131 registerVSCodeCommand(context, "publishToExpHost", ErrorHelper.getInternalError(InternalErrorCode.FailedToPublishToExpHost), () => commandPaletteHandler.publishToExpHost());
132}
133
134function registerVSCodeCommand(
135 context: vscode.ExtensionContext, commandName: string,
136 error: InternalError, commandHandler: () => Q.Promise<void>): void {
137 context.subscriptions.push(vscode.commands.registerCommand(
138 `reactNative.${commandName}`,
139 () =>
140 entryPointHandler.runFunction(
141 `commandPalette.${commandName}`, error,
142 commandHandler)));
143}
144
145/**
146 * Sets up the debugger for the React Native project by dropping
147 * the debugger stub into the workspace
148 */
149function setupReactNativeDebugger(): Q.Promise<void> {
150 const launcherPath = require.resolve("../debugger/launcher");
151 const pkg = require("../../package.json");
152 const extensionVersionNumber = pkg.version;
153 const extensionName = pkg.name;
154
155 let debuggerEntryCode =
156 `// This file is automatically generated by ${extensionName}@${extensionVersionNumber}
157// Please do not modify it manually. All changes will be lost.
158try {
159 var path = require("path");
160 var Launcher = require(${JSON.stringify(launcherPath)}).Launcher;
161 new Launcher(path.resolve(__dirname, "..")).launch();
162} catch (e) {
163 throw new Error("Unable to launch application. Try deleting .vscode/launchReactNative.js and restarting vscode.");
164}`;
165
166 const vscodeFolder = path.join(projectRootPath, ".vscode");
167 const debugStub = path.join(vscodeFolder, "launchReactNative.js");
168
169 return fsUtil.ensureDirectory(vscodeFolder)
170 .then(() => fsUtil.ensureFileWithContents(debugStub, debuggerEntryCode))
171 .catch((err: Error) => {
172 vscode.window.showErrorMessage(err.message);
173 });
174}