forked from revopush/code-push-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact-native-utils.ts
More file actions
502 lines (434 loc) · 17 KB
/
Copy pathreact-native-utils.ts
File metadata and controls
502 lines (434 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import * as fs from "fs";
import * as chalk from "chalk";
import * as path from "path";
import * as childProcess from "child_process";
import { coerce, compare, gte, valid } from "semver";
import { downloadBlob, extractIPA, fileDoesNotExistOrIsDirectory } from "./utils/file-utils";
import * as dotenv from "dotenv";
import { DotenvParseOutput } from "dotenv";
import * as cli from "../script/types/cli";
import { log, sdk } from "./command-executor";
const g2js = require("gradle-to-js/lib/parser");
export function isValidVersion(version: string): boolean {
return !!valid(version) || /^\d+\.\d+$/.test(version);
}
export async function getBundleSourceMapOutput(command: cli.IReleaseReactCommand, bundleName: string, sourcemapOutputFolder: string) {
let bundleSourceMapOutput: string | undefined;
switch (command.platform) {
case "android": {
// see BundleHermesCTask -> resolvePackagerSourceMapFile
// for Hermes targeted bundles there are 2 source maps: "packager" (metro) and "compiler" (Hermes)
// Metro bundles use <bundleAssetName>.packager.map notation
const isHermes = await isHermesEnabled(command, command.platform);
if (isHermes) {
bundleSourceMapOutput = path.join(sourcemapOutputFolder, bundleName + ".packager.map");
} else {
bundleSourceMapOutput = path.join(sourcemapOutputFolder, bundleName + ".map");
}
break;
}
case "ios": {
// see react-native-xcode.sh
// to match js bundle generated by Xcode and by Revopush cli we must respect SOURCEMAP_FILE value
// because it appears as //# sourceMappingURL value in a js bundle
const xcodeDotEnvValue = getXcodeDotEnvValue("SOURCEMAP_FILE");
const sourceMapFilename = xcodeDotEnvValue ? path.basename(xcodeDotEnvValue) : bundleName + ".map";
bundleSourceMapOutput = path.join(sourcemapOutputFolder, sourceMapFilename);
break;
}
default:
throw new Error('Platform must be either "android", "ios" or "windows".');
}
return bundleSourceMapOutput;
}
export async function takeHermesBaseBytecode(
command: cli.IReleaseReactCommand,
baseReleaseTmpFolder: string,
outputFolder: string,
bundleName: string
): Promise<string | null> {
const { bundleBlobUrl } = await sdk.getBaseRelease(command.appName, command.deploymentName, command.appStoreVersion, command.buildNumber);
if (!bundleBlobUrl) {
return null;
}
const baseReleaseArchive = await downloadBlob(bundleBlobUrl, baseReleaseTmpFolder);
await extractIPA(baseReleaseArchive, baseReleaseTmpFolder);
const baseReleaseBundle = path.join(baseReleaseTmpFolder, path.basename(outputFolder), bundleName);
if (!fs.existsSync(baseReleaseBundle)) {
log(chalk.cyan("\nNo base release available...\n"));
return null;
}
return baseReleaseBundle;
}
export async function runHermesEmitBinaryCommand(
command: cli.IReleaseReactCommand,
bundleName: string,
outputFolder: string,
sourcemapOutputFolder: string,
extraHermesFlags: string[],
gradleFile: string,
baseBytecode?: string
): Promise<void> {
const hermesArgs: string[] = [];
const envNodeArgs: string = process.env.CODE_PUSH_NODE_ARGS;
if (typeof envNodeArgs !== "undefined") {
Array.prototype.push.apply(hermesArgs, envNodeArgs.trim().split(/\s+/));
}
Array.prototype.push.apply(hermesArgs, [
"-emit-binary",
"-O",
"-out",
path.join(outputFolder, bundleName + ".hbc"),
path.join(outputFolder, bundleName),
"-w",
"-max-diagnostic-width=80",
...extraHermesFlags,
]);
if (sourcemapOutputFolder) {
hermesArgs.push("-output-source-map");
}
if (baseBytecode) {
hermesArgs.push("-base-bytecode", baseBytecode);
}
console.log(chalk.cyan("Converting JS bundle to byte code via Hermes, running command:\n"));
const hermesCommand = await getHermesCommand(gradleFile);
const hermesProcess = childProcess.spawn(hermesCommand, hermesArgs);
console.log(`${hermesCommand} ${hermesArgs.join(" ")}`);
return new Promise<void>((resolve, reject) => {
hermesProcess.stdout.on("data", (data: Buffer) => {
console.log(data.toString().trim());
});
hermesProcess.stderr.on("data", (data: Buffer) => {
console.error(data.toString().trim());
});
hermesProcess.on("close", (exitCode: number, signal: string) => {
if (exitCode !== 0) {
reject(new Error(`"hermes" command failed (exitCode=${exitCode}, signal=${signal}).`));
}
// Copy HBC bundle to overwrite JS bundle
const source = path.join(outputFolder, bundleName + ".hbc");
const destination = path.join(outputFolder, bundleName);
fs.copyFile(source, destination, (err) => {
if (err) {
console.error(err);
reject(new Error(`Copying file ${source} to ${destination} failed. "hermes" previously exited with code ${exitCode}.`));
}
fs.unlink(source, (err) => {
if (err) {
console.error(err);
reject(err);
}
resolve(null as void);
});
});
});
}).then(async () => {
if (!sourcemapOutputFolder) {
// skip source map compose if source map is not enabled
return;
}
const composeSourceMapsPath = getComposeSourceMapsPath();
if (!composeSourceMapsPath) {
throw new Error("react-native compose-source-maps.js scripts is not found");
}
const jsCompilerSourceMapFile = path.join(outputFolder, bundleName + ".hbc" + ".map");
if (!fs.existsSync(jsCompilerSourceMapFile)) {
throw new Error(`sourcemap file ${jsCompilerSourceMapFile} is not found`);
}
const platformSourceMapOutput = await getBundleSourceMapOutput(command, bundleName, sourcemapOutputFolder);
return new Promise((resolve, reject) => {
let bundleSourceMapOutput = sourcemapOutputFolder;
let combinedSourceMapOutput = sourcemapOutputFolder;
if (!sourcemapOutputFolder.endsWith(".map")) {
bundleSourceMapOutput = platformSourceMapOutput;
switch (command.platform) {
case "android": {
combinedSourceMapOutput = path.join(sourcemapOutputFolder, bundleName + ".map");
break;
}
case "ios": {
combinedSourceMapOutput = bundleSourceMapOutput;
break;
}
default:
throw new Error('Platform must be either "android", "ios" or "windows".');
}
}
const composeSourceMapsArgs = [
composeSourceMapsPath,
bundleSourceMapOutput,
jsCompilerSourceMapFile,
"-o",
combinedSourceMapOutput,
];
// https://github.com/facebook/react-native/blob/master/react.gradle#L211
// https://github.com/facebook/react-native/blob/master/scripts/react-native-xcode.sh#L178
// packager.sourcemap.map + hbc.sourcemap.map = sourcemap.map
const composeSourceMapsProcess = childProcess.spawn("node", composeSourceMapsArgs);
console.log(`${composeSourceMapsPath} ${composeSourceMapsArgs.join(" ")}`);
composeSourceMapsProcess.stdout.on("data", (data: Buffer) => {
console.log(data.toString().trim());
});
composeSourceMapsProcess.stderr.on("data", (data: Buffer) => {
console.error(data.toString().trim());
});
composeSourceMapsProcess.on("close", (exitCode: number, signal: string) => {
if (exitCode !== 0) {
reject(new Error(`"compose-source-maps" command failed (exitCode=${exitCode}, signal=${signal}).`));
}
// Delete the HBC sourceMap, otherwise it will be included in 'code-push' bundle as well
fs.unlink(jsCompilerSourceMapFile, (err) => {
if (err) {
console.error(err);
reject(err);
}
resolve(null);
});
});
});
});
}
export function getXcodeDotEnvValue(key: string): string | undefined {
const xcodeEnvs = loadEnvAsMap([path.join("ios", ".xcode.env.local"), path.join("ios", ".xcode.env.local")]);
return xcodeEnvs.get(key);
}
export async function getMinifyParams(command: cli.IReleaseReactCommand) {
const isHermes = await isHermesEnabled(command);
switch (command.platform) {
case "android": {
// android always explicitly pass --minify true/false
// TaskConfiguration it.minifyEnabled.set(!isHermesEnabledInThisVariant)
return ["--minify", !isHermes];
}
case "ios": {
//if [[ $USE_HERMES != false && $DEV == false ]]; then
// EXTRA_ARGS+=("--minify" "false")
// fi
// ios does pass --minify false only if Hermes enables and does pass anything otherwise
return isHermes ? ["--minify", false] : [];
}
default:
throw new Error('Platform must be either "android", "ios" or "windows".');
}
}
export async function isHermesEnabled(command: cli.IReleaseReactCommand, platform: string = command.platform.toLowerCase()) {
if (command.useHermes) return true;
if (platform === "android") return getAndroidHermesEnabled(command.gradleFile);
if (platform === "ios") return getiOSHermesEnabled(command.podFile);
return false;
}
function parseBuildGradleFile(gradleFile: string) {
let buildGradlePath: string = path.join("android", "app");
if (gradleFile) {
buildGradlePath = gradleFile;
}
try {
if (fs.lstatSync(buildGradlePath).isDirectory()) {
buildGradlePath = path.join(buildGradlePath, "build.gradle");
fs.accessSync(buildGradlePath);
}
} catch {
throw new Error(`Unable to find gradle file "${buildGradlePath}".`);
}
return g2js.parseFile(buildGradlePath).catch(() => {
throw new Error(`Unable to parse the "${buildGradlePath}" file. Please ensure it is a well-formed Gradle file.`);
});
}
function parseGradlePropertiesFile(gradleFile: string): Record<string, string> {
let gradlePropsPath: string = path.join("android", "gradle.properties");
try {
if (gradleFile) {
const base = gradleFile;
const stat = fs.lstatSync(base);
if (stat.isDirectory()) {
if (path.basename(base) === "app") {
gradlePropsPath = path.join(base, "..", "gradle.properties");
} else {
gradlePropsPath = path.join(base, "gradle.properties");
}
} else {
gradlePropsPath = path.join(path.dirname(base), "..", "gradle.properties");
}
}
} catch {}
gradlePropsPath = path.normalize(gradlePropsPath);
if (fileDoesNotExistOrIsDirectory(gradlePropsPath)) {
throw new Error(`Unable to find gradle.properties file "${gradlePropsPath}".`);
}
const text = fs.readFileSync(gradlePropsPath, "utf8");
const props: Record<string, string> = {};
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith("#")) continue;
const m = line.match(/^([^=\s]+)\s*=\s*(.*)$/);
if (m) {
const key = m[1].trim();
const val = m[2].trim();
props[key] = val;
}
}
return props;
}
async function getHermesCommandFromGradle(gradleFile: string): Promise<string> {
const buildGradle: any = await parseBuildGradleFile(gradleFile);
const hermesCommandProperty: any = Array.from(buildGradle["project.ext.react"] || []).find((prop: string) =>
prop.trim().startsWith("hermesCommand:")
);
if (hermesCommandProperty) {
return hermesCommandProperty.replace("hermesCommand:", "").trim().slice(1, -1);
} else {
return "";
}
}
async function getAndroidHermesEnabled(gradleFile: string): Promise<boolean> {
try {
const props = parseGradlePropertiesFile(gradleFile);
if (typeof props.hermesEnabled !== "undefined") {
const v = String(props.hermesEnabled).trim().toLowerCase();
if (v === "true") return true;
if (v === "false") return false;
}
} catch {}
try {
const buildGradle: any = await parseBuildGradleFile(gradleFile);
const lines: string[] = Array.from(buildGradle["project.ext.react"] || []);
if (lines.some((l) => /\benableHermes\s*:\s*true\b/.test(l))) return true;
if (lines.some((l) => /\benableHermes\s*:\s*false\b/.test(l))) return false;
} catch {}
const rnVersion = coerce(getReactNativeVersion())?.version;
return rnVersion && compare(rnVersion, "0.70.0") >= 0;
}
function getiOSHermesEnabled(podFile: string): boolean {
const podPath = podFile || path.join("ios", "Podfile");
if (podFile && fileDoesNotExistOrIsDirectory(podPath)) {
throw new Error(`Unable to find Podfile file "${podPath}".`);
} else if (!podFile && fileDoesNotExistOrIsDirectory(podPath)) {
// No Podfile at default path (e.g. Android-only project); fall back to RN version heuristic
const rnVersion = coerce(getReactNativeVersion())?.version;
return !!(rnVersion && compare(rnVersion, "0.70.0") >= 0);
}
try {
const podFileContents = fs.readFileSync(podPath).toString();
const hasTrue = /([^#\n]*:?hermes_enabled(\s+|\n+)?(=>|:)(\s+|\n+)?true)/.test(podFileContents);
if (hasTrue) return true;
const hasFalse = /([^#\n]*:?hermes_enabled(\s+|\n+)?(=>|:)(\s+|\n+)?false)/.test(podFileContents);
if (hasFalse) return false;
const rnVersion = coerce(getReactNativeVersion())?.version;
return rnVersion && compare(rnVersion, "0.70.0") >= 0;
} catch (error) {
throw error;
}
}
function loadEnvAsMap(envPaths = []): Map<string, string | undefined> {
const merged: DotenvParseOutput = {};
for (const envPath of envPaths) {
if (fs.existsSync(envPath)) {
Object.assign(merged, dotenv.parse(fs.readFileSync(envPath))); // later files override earlier ones
}
}
// fallback to process.env for anything missing
return new Map([...Object.entries(process.env), ...Object.entries(merged)]);
}
function getHermesOSBin(): string {
switch (process.platform) {
case "win32":
return "win64-bin";
case "darwin":
return "osx-bin";
case "freebsd":
case "linux":
case "sunos":
default:
return "linux64-bin";
}
}
function getHermesOSExe(): string {
const react63orAbove = compare(coerce(getReactNativeVersion())?.version, "0.63.0") !== -1;
const hermesExecutableName = react63orAbove ? "hermesc" : "hermes";
switch (process.platform) {
case "win32":
return hermesExecutableName + ".exe";
default:
return hermesExecutableName;
}
}
async function getHermesCommand(gradleFile: string): Promise<string> {
const fileExists = (file: string): boolean => {
try {
return fs.statSync(file).isFile();
} catch (e) {
return false;
}
};
// Hermes is bundled with react-native since 0.69
const reactNativePath = getReactNativePackagePath();
const bundledHermesEngine = path.join(reactNativePath, "sdks", "hermesc", getHermesOSBin(), getHermesOSExe());
if (fileExists(bundledHermesEngine)) {
return bundledHermesEngine;
}
let gradleHermesCommand = "";
try {
gradleHermesCommand = await getHermesCommandFromGradle(gradleFile);
} catch {
// Gradle files not present (e.g. iOS-only project); skip to node_modules fallback
}
if (gradleHermesCommand) {
return path.join("android", "app", gradleHermesCommand.replace("%OS-BIN%", getHermesOSBin()));
} else {
const nodeModulesPath = getNodeModulesPath(reactNativePath);
// assume if hermes-engine exists it should be used instead of hermesvm
const hermesEngine = path.join(nodeModulesPath, "hermes-engine", getHermesOSBin(), getHermesOSExe());
if (fileExists(hermesEngine)) {
return hermesEngine;
}
// RN 0.83 hermes-compiler
const hermesCompiler = path.join(nodeModulesPath, "hermes-compiler", "hermesc", getHermesOSBin(), getHermesOSExe());
if (fileExists(hermesCompiler)) {
return hermesCompiler;
}
return path.join(nodeModulesPath, "hermesvm", getHermesOSBin(), "hermes");
}
}
function getComposeSourceMapsPath(): string {
// detect if compose-source-maps.js script exists
const composeSourceMaps = path.join(getReactNativePackagePath(), "scripts", "compose-source-maps.js");
if (fs.existsSync(composeSourceMaps)) {
return composeSourceMaps;
}
return null;
}
function getNodeModulesPath(reactNativePath: string): string {
const nodeModulesPath = path.dirname(reactNativePath);
if (directoryExistsSync(nodeModulesPath)) {
return nodeModulesPath;
}
return path.join("node_modules");
}
export function getReactNativePackagePath(): string {
const result = childProcess.spawnSync("node", ["--print", "require.resolve('react-native/package.json')"]);
const packagePath = path.dirname(result.stdout.toString());
if (result.status === 0 && directoryExistsSync(packagePath)) {
return packagePath;
}
return path.join("node_modules", "react-native");
}
export function directoryExistsSync(dirname: string): boolean {
try {
return fs.statSync(dirname).isDirectory();
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
return false;
}
export function getReactNativeVersion(): string {
try {
const result = childProcess.spawnSync("node", ["--print", "require('react-native/package.json').version"]);
return result.stdout.toString().trim();
} catch (error) {
throw new Error(
'Unable to resolve "react-native". Please make sure it is installed in your project (e.g. "npm install react-native").'
);
}
}