microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2d3a052eafbcd8bddff2825d5f0049a168da4b16

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/packager.ts

161lines · 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 {ChildProcess} from "child_process";
5import {CommandExecutor} from "./commandExecutor";
6import {Log, LogLevel} from "./log";
7import {Node} from "./node/node";
8import {OutputChannel} from "vscode";
9import {Package} from "./node/package";
10import {PromiseUtil} from "./node/promise";
11import {Request} from "./node/request";
12
13import * as Q from "q";
14import * as path from "path";
15
16export class Packager {
17 // TODO: Make the port configurable via a launch argument
18 public static PORT = "8081";
19 public static HOST = `localhost:${Packager.PORT}`;
20 public static DEBUGGER_WORKER_FILE_BASENAME = "debuggerWorker";
21 public static DEBUGGER_WORKER_FILENAME = Packager.DEBUGGER_WORKER_FILE_BASENAME + ".js";
22
23 private projectPath: string;
24 private packagerProcess: ChildProcess;
25 private sourcesStoragePath: string;
26
27 private static JS_INJECTOR_FILENAME = "opn-main.js";
28 private static JS_INJECTOR_FILEPATH = path.resolve(path.dirname(path.dirname(__dirname)), "js-patched", Packager.JS_INJECTOR_FILENAME);
29 private static NODE_MODULES_FODLER_NAME = "node_modules";
30 private static OPN_PACKAGE_NAME = "opn";
31 private static REACT_NATIVE_PACKAGE_NAME = "react-native";
32 private static OPN_PACKAGE_MAIN_FILENAME = "index.js";
33
34 constructor(projectPath: string, sourcesStoragePath?: string) {
35 this.projectPath = projectPath;
36 this.sourcesStoragePath = sourcesStoragePath;
37 }
38
39 public start(outputChannel?: OutputChannel): Q.Promise<void> {
40 this.isRunning().done(running => {
41 if (!running) {
42 return this.monkeyPatchOpnForRNPackager()
43 .then(() => {
44 let args = ["--port", Packager.PORT];
45 let childEnvForDebugging = Object.assign({}, process.env, { REACT_DEBUGGER: "echo A debugger is not needed: " });
46
47 Log.logMessage("Starting Packager", outputChannel);
48 // The packager will continue running while we debug the application, so we can"t
49 // wait for this command to finish
50
51 let spawnOptions = { env: childEnvForDebugging };
52
53 new CommandExecutor(this.projectPath).spawnReactCommand("start", args, spawnOptions, outputChannel).then((packagerProcess) => {
54 this.packagerProcess = packagerProcess;
55 });
56 }).done();
57 }
58 });
59
60 return this.awaitStart().then(() => {
61 Log.logMessage("Packager started.", outputChannel);
62 if (this.sourcesStoragePath) {
63 return this.downloadDebuggerWorker().then(() => {
64 Log.logMessage("Downloaded debuggerWorker.js (Logic to run the React Native app) from the Packager.");
65 });
66 }
67 });
68 }
69
70 public stop(outputChannel?: OutputChannel): void {
71 Log.logMessage("Stopping Packager", outputChannel);
72
73 if (this.packagerProcess) {
74 this.packagerProcess.kill();
75 this.packagerProcess = null;
76 Log.logMessage("Packager stopped", outputChannel);
77 } else {
78 Log.logMessage("Packager not found", outputChannel);
79 }
80 }
81
82 public prewarmBundleCache(platform: string) {
83 let bundleURL = `http://${Packager.HOST}/index.${platform}.bundle`;
84 Log.logInternalMessage(LogLevel.Info, "About to get: " + bundleURL);
85 return new Request().request(bundleURL, true).then(() => {
86 Log.logMessage("The Bundle Cache was prewarmed.");
87 });
88 }
89
90 private isRunning(): Q.Promise<boolean> {
91 let statusURL = `http://${Packager.HOST}/status`;
92
93 return new Request().request(statusURL)
94 .then((body: string) => {
95 return body === "packager-status:running";
96 },
97 (error: any) => {
98 return false;
99 });
100 }
101
102 private awaitStart(retryCount = 30, delay = 2000): Q.Promise<boolean> {
103 let pu: PromiseUtil = new PromiseUtil();
104 return pu.retryAsync(() => this.isRunning(), (running) => running, retryCount, delay, "Could not start the packager.");
105 }
106
107 private downloadDebuggerWorker(): Q.Promise<void> {
108 let debuggerWorkerURL = `http://${Packager.HOST}/${Packager.DEBUGGER_WORKER_FILENAME}`;
109 let debuggerWorkerLocalPath = path.join(this.sourcesStoragePath, Packager.DEBUGGER_WORKER_FILENAME);
110 Log.logInternalMessage(LogLevel.Info, "About to download: " + debuggerWorkerURL + " to: " + debuggerWorkerLocalPath);
111 return new Request().request(debuggerWorkerURL, true).then((body: string) => {
112 return new Node.FileSystem().writeFile(debuggerWorkerLocalPath, body);
113 });
114 }
115
116 private findOpnPackage(): Q.Promise<string> {
117 try {
118 let flatDependencyPackagePath = path.resolve(this.projectPath, Packager.NODE_MODULES_FODLER_NAME,
119 Packager.OPN_PACKAGE_NAME, Packager.OPN_PACKAGE_MAIN_FILENAME);
120
121 let nestedDependencyPackagePath = path.resolve(this.projectPath, Packager.NODE_MODULES_FODLER_NAME,
122 Packager.REACT_NATIVE_PACKAGE_NAME, Packager.NODE_MODULES_FODLER_NAME, Packager.OPN_PACKAGE_NAME, Packager.OPN_PACKAGE_MAIN_FILENAME);
123
124 let fsHelper = new Node.FileSystem();
125
126 // Attempt to find the 'opn' package directly under the project's node_modules folder (node4 +)
127 // Else, attempt to find the package within the dependent node_modules of react-native package
128 let possiblePaths = [flatDependencyPackagePath, nestedDependencyPackagePath];
129 return Q.any(possiblePaths.map(path =>
130 fsHelper.exists(path).then(exists =>
131 exists
132 ? Q.resolve(path)
133 : Q.reject<string>("opn package location not found"))));
134 } catch (err) {
135 console.error ("The package \'opn\' was not found." + err);
136 }
137 }
138
139 private monkeyPatchOpnForRNPackager(): Q.Promise<void> {
140 let opnPackage: Package;
141 let destnFilePath: string;
142
143 // Finds the 'opn' package
144 return this.findOpnPackage()
145 .then((opnIndexFilePath) => {
146 destnFilePath = opnIndexFilePath;
147 // Read the package's "package.json"
148 opnPackage = new Package(path.resolve(path.dirname(destnFilePath)));
149 return opnPackage.parsePackageInformation();
150 }).then((packageJson) => {
151 if (packageJson.main !== Packager.JS_INJECTOR_FILENAME) {
152 // Copy over the patched 'opn' main file
153 return new Node.FileSystem().copyFile(Packager.JS_INJECTOR_FILEPATH, path.resolve(path.dirname(destnFilePath), Packager.JS_INJECTOR_FILENAME))
154 .then(() => {
155 // Write/over-write the "main" attribute with the new file
156 return opnPackage.setMainFile(Packager.JS_INJECTOR_FILENAME);
157 });
158 }
159 });
160 }
161}
162