react-native-update-cli 2.24.2 → 2.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +12 -5
  2. package/README.zh-CN.md +12 -5
  3. package/cli.json +7 -1
  4. package/lib/api.d.ts +2 -0
  5. package/lib/api.js +63 -18
  6. package/lib/app.js +25 -3
  7. package/lib/bin.js +39 -45
  8. package/lib/bundle-runner.d.ts +45 -1
  9. package/lib/bundle-runner.js +303 -34
  10. package/lib/bundle.d.ts +1 -1
  11. package/lib/bundle.js +23 -7
  12. package/lib/commands.d.ts +6 -0
  13. package/lib/commands.js +65 -0
  14. package/lib/locales/en.d.ts +7 -14
  15. package/lib/locales/en.js +10 -17
  16. package/lib/locales/zh.d.ts +7 -13
  17. package/lib/locales/zh.js +10 -16
  18. package/lib/package.js +4 -0
  19. package/lib/provider.d.ts +1 -1
  20. package/lib/provider.js +3 -1
  21. package/lib/symbolicate.js +7 -2
  22. package/lib/types.d.ts +1 -0
  23. package/lib/user.js +6 -0
  24. package/lib/utils/add-gitignore.js +7 -1
  25. package/lib/utils/dep-versions.d.ts +7 -0
  26. package/lib/utils/dep-versions.js +78 -26
  27. package/lib/utils/git.js +9 -6
  28. package/lib/utils/hbcTransform.d.ts +15 -0
  29. package/lib/utils/hbcTransform.js +22 -0
  30. package/lib/utils/hermes-base.d.ts +61 -6
  31. package/lib/utils/hermes-base.js +328 -46
  32. package/lib/utils/hermes-literals.d.ts +51 -0
  33. package/lib/utils/hermes-literals.js +210 -0
  34. package/lib/utils/i18n.d.ts +5 -0
  35. package/lib/utils/i18n.js +14 -1
  36. package/lib/utils/index.d.ts +2 -1
  37. package/lib/utils/index.js +9 -4
  38. package/lib/utils/latest-version/index.js +8 -0
  39. package/lib/utils/runtime.d.ts +21 -0
  40. package/lib/utils/runtime.js +138 -5
  41. package/lib/utils/zip-range.js +3 -2
  42. package/lib/versions.js +14 -4
  43. package/package.json +6 -3
  44. package/lib/index.d.ts +0 -1
  45. package/lib/index.js +0 -17
  46. package/src/api.ts +0 -470
  47. package/src/app.ts +0 -241
  48. package/src/auto-update.ts +0 -647
  49. package/src/bin-cresc.ts +0 -8
  50. package/src/bin.ts +0 -115
  51. package/src/bundle-pack.ts +0 -61
  52. package/src/bundle-runner.ts +0 -1430
  53. package/src/bundle.ts +0 -371
  54. package/src/cache.ts +0 -20
  55. package/src/diff.ts +0 -1010
  56. package/src/exports.ts +0 -17
  57. package/src/index.ts +0 -1
  58. package/src/install.ts +0 -50
  59. package/src/locales/en.ts +0 -257
  60. package/src/locales/zh.ts +0 -234
  61. package/src/native-package.ts +0 -338
  62. package/src/package.ts +0 -482
  63. package/src/provider.ts +0 -294
  64. package/src/symbolicate.ts +0 -164
  65. package/src/types.ts +0 -150
  66. package/src/user.ts +0 -39
  67. package/src/utils/add-gitignore.ts +0 -35
  68. package/src/utils/app-info-parser/aab.ts +0 -241
  69. package/src/utils/app-info-parser/apk.ts +0 -92
  70. package/src/utils/app-info-parser/app.ts +0 -7
  71. package/src/utils/app-info-parser/index.ts +0 -54
  72. package/src/utils/app-info-parser/ipa.ts +0 -109
  73. package/src/utils/app-info-parser/resource-finder.ts +0 -508
  74. package/src/utils/app-info-parser/utils.ts +0 -161
  75. package/src/utils/app-info-parser/xml-parser/binary.ts +0 -693
  76. package/src/utils/app-info-parser/xml-parser/manifest.ts +0 -228
  77. package/src/utils/app-info-parser/zip.ts +0 -108
  78. package/src/utils/check-lockfile.ts +0 -93
  79. package/src/utils/check-plugin.ts +0 -38
  80. package/src/utils/command-result.ts +0 -24
  81. package/src/utils/constants.ts +0 -25
  82. package/src/utils/dep-versions.ts +0 -83
  83. package/src/utils/git.ts +0 -71
  84. package/src/utils/hbcTransform.ts +0 -649
  85. package/src/utils/hermes-base.ts +0 -1137
  86. package/src/utils/http-helper.ts +0 -152
  87. package/src/utils/i18n.ts +0 -39
  88. package/src/utils/index.ts +0 -698
  89. package/src/utils/latest-version/index.ts +0 -573
  90. package/src/utils/options.ts +0 -78
  91. package/src/utils/plugin-config.ts +0 -32
  92. package/src/utils/runtime.ts +0 -187
  93. package/src/utils/slim-sourcemap.ts +0 -105
  94. package/src/utils/zip-entries.ts +0 -209
  95. package/src/utils/zip-options.ts +0 -178
  96. package/src/utils/zip-range.ts +0 -727
  97. package/src/utils/zip-raw-writer.ts +0 -247
  98. package/src/versions.ts +0 -892
@@ -1,698 +0,0 @@
1
- import chalk from 'chalk';
2
- import { compare, satisfies } from 'compare-versions';
3
- import { createHash } from 'crypto';
4
- import path from 'path';
5
- import type { Root as ProtobufRoot } from 'protobufjs';
6
- import { read } from 'read';
7
- import { open as openZipFile, type Entry as YauzlEntry } from 'yauzl';
8
- import pkg from '../../package.json';
9
- import type AppInfoParserType from './app-info-parser';
10
- import { checkPlugins } from './check-plugin';
11
- import { IS_CRESC } from './constants';
12
- import { getDepVersions } from './dep-versions';
13
- import { t } from './i18n';
14
-
15
- // app-info-parser (and its zip/plist/protobuf stack) is only needed by the
16
- // package commands; load it on first use instead of on every CLI start.
17
- function createAppInfoParser(fn: string): AppInfoParserType {
18
- const { default: AppInfoParser } =
19
- require('./app-info-parser') as typeof import('./app-info-parser');
20
- return new AppInfoParser(fn);
21
- }
22
-
23
- /**
24
- * tty-table (~25 ms to load) only when a table is rendered. Bun's require of
25
- * a CJS module can hand back a namespace object, so unwrap `default`.
26
- */
27
- export function loadTtyTable(): typeof import('tty-table') {
28
- const mod = require('tty-table');
29
- return (mod.default ?? mod) as typeof import('tty-table');
30
- }
31
-
32
- type ApkMetaEntry = {
33
- name?: string;
34
- value?: string | number | Array<string | number>;
35
- };
36
-
37
- type ParsedApkInfo = {
38
- versionName: string;
39
- application: {
40
- metaData?: ApkMetaEntry[];
41
- };
42
- };
43
-
44
- type ParsedIpaInfo = {
45
- CFBundleShortVersionString: string;
46
- };
47
-
48
- type ParsedAppMetaInfo = {
49
- versionName?: string;
50
- pushy_build_time?: number | string;
51
- };
52
-
53
- type AabXmlAttr = {
54
- name: string;
55
- value: string;
56
- compiledItem?: {
57
- ref?: {
58
- id?: number;
59
- };
60
- prim?: {
61
- intDecimalValue?: number;
62
- };
63
- };
64
- };
65
-
66
- type AabXmlElement = {
67
- name: string;
68
- attribute: AabXmlAttr[];
69
- child: Array<{ element?: AabXmlElement }>;
70
- };
71
-
72
- type AabXmlNodeObject = {
73
- element: AabXmlElement;
74
- };
75
-
76
- type AabResourceEntry = {
77
- entryId: number;
78
- configValue?: Array<{
79
- value?: {
80
- item?: {
81
- str?: {
82
- value?: string;
83
- };
84
- };
85
- };
86
- }>;
87
- };
88
-
89
- type AabResourceType = {
90
- typeId: number;
91
- entry: AabResourceEntry[];
92
- };
93
-
94
- type AabResourcePackage = {
95
- packageId: number;
96
- type: AabResourceType[];
97
- };
98
-
99
- type AabResourceTableObject = {
100
- package: AabResourcePackage[];
101
- };
102
-
103
- export function isNonInteractive() {
104
- const envValue = process.env.NO_INTERACTIVE?.toLowerCase();
105
- return (
106
- global.NO_INTERACTIVE === true || envValue === 'true' || envValue === '1'
107
- );
108
- }
109
-
110
- export async function question(query: string, password?: boolean) {
111
- if (isNonInteractive()) {
112
- return '';
113
- }
114
- return read({
115
- prompt: query,
116
- silent: password,
117
- replace: password ? '*' : undefined,
118
- });
119
- }
120
-
121
- export function translateOptions<T extends Record<string, unknown>>(
122
- options: T,
123
- map?: Record<string, string>,
124
- ): T & Record<string, unknown> {
125
- if (!map) {
126
- // Existing logic for template replacement if no map is provided
127
- const ret: Record<string, unknown> = {};
128
- for (const key in options) {
129
- const value = options[key];
130
- if (typeof value === 'string') {
131
- ret[key] = value.replace(/\$\{(\w+)\}/g, (placeholder, name) => {
132
- const replacement = options[name] ?? process.env[name];
133
- if (
134
- typeof replacement === 'string' ||
135
- typeof replacement === 'number' ||
136
- typeof replacement === 'boolean'
137
- ) {
138
- return String(replacement);
139
- }
140
- return placeholder;
141
- });
142
- } else {
143
- ret[key] = value;
144
- }
145
- }
146
- return ret as T & Record<string, unknown>;
147
- }
148
-
149
- const result: Record<string, unknown> = { ...options };
150
- for (const [key, value] of Object.entries(map)) {
151
- if (result[key] !== undefined) {
152
- result[value] = result[key];
153
- delete result[key];
154
- }
155
- }
156
- return result as T;
157
- }
158
-
159
- // bundleHash: sha256 of the raw bundle bytes extracted from the package. Must
160
- // stay byte-identical with what the client hashes at runtime (its embedded
161
- // bundle, which is also the pdiff source) — the server compares the two to
162
- // decide pdiff applicability. Raw bytes, no normalization of any kind.
163
- // getEntries is typed Buffer | Blob (app-info-parser's browser/node duality);
164
- // under Node it is always a Buffer, but handle both.
165
- async function sha256(data: Buffer | Blob): Promise<string> {
166
- const buffer = Buffer.isBuffer(data)
167
- ? data
168
- : Buffer.from(await data.arrayBuffer());
169
- return createHash('sha256').update(buffer).digest('hex');
170
- }
171
-
172
- // Anchored exact paths: unanchored/unescaped patterns also matched entries
173
- // like index.android.bundle.map or .backup, and a later match would silently
174
- // overwrite the real bundle, registering a wrong bundleHash.
175
- export const ApkBundleFileName = /^assets\/index\.android\.bundle$/;
176
- const ApkUpdateJsonName = /^res\/raw\/update\.json$/;
177
-
178
- export async function getApkInfo(fn: string) {
179
- const appInfoParser = createAppInfoParser(fn);
180
- // read both entries in a single scan over the archive
181
- const entries = await appInfoParser.parser.getEntries([
182
- ApkBundleFileName,
183
- ApkUpdateJsonName,
184
- ]);
185
- const bundleFile = entries[String(ApkBundleFileName)];
186
- if (!bundleFile) {
187
- throw new Error(
188
- t('bundleNotFound', {
189
- packageType: 'apk',
190
- entryFile: 'index.android.bundle',
191
- }),
192
- );
193
- }
194
- const updateJsonFile = entries[String(ApkUpdateJsonName)];
195
- let appCredential = {};
196
- if (updateJsonFile) {
197
- appCredential = JSON.parse(updateJsonFile.toString()).android;
198
- }
199
- const { versionName, application } =
200
- await appInfoParser.parse<ParsedApkInfo>();
201
- let buildTime = 0;
202
- if (Array.isArray(application.metaData)) {
203
- for (const meta of application.metaData) {
204
- if (meta.name === 'pushy_build_time') {
205
- if (Array.isArray(meta.value)) {
206
- const firstValue = meta.value[0];
207
- buildTime = Number(firstValue);
208
- } else if (meta.value !== undefined) {
209
- buildTime = Number(meta.value);
210
- }
211
- }
212
- }
213
- }
214
- if (!Number.isFinite(buildTime) || buildTime === 0) {
215
- throw new Error(t('buildTimeNotFound'));
216
- }
217
- return {
218
- versionName,
219
- buildTime,
220
- bundleHash: await sha256(bundleFile),
221
- bundleFile,
222
- ...appCredential,
223
- };
224
- }
225
-
226
- export async function getAppInfo(fn: string) {
227
- const appInfoParser = createAppInfoParser(fn);
228
- // single scan (and single nested .hap extraction) for all three entries
229
- const [bundleFile, updateJsonFile, metaJsonFile] =
230
- await appInfoParser.parser.getEntriesFromHarmonyApp([
231
- /^resources\/rawfile\/bundle\.harmony\.js$/,
232
- /^resources\/rawfile\/update\.json$/,
233
- /^resources\/rawfile\/meta\.json$/,
234
- ]);
235
- if (!bundleFile) {
236
- throw new Error(
237
- t('bundleNotFound', {
238
- packageType: 'app',
239
- entryFile: 'bundle.harmony.js',
240
- }),
241
- );
242
- }
243
- let appCredential = {};
244
- if (updateJsonFile) {
245
- appCredential = JSON.parse(updateJsonFile.toString()).harmony;
246
- }
247
- let metaData: ParsedAppMetaInfo = {};
248
- if (metaJsonFile) {
249
- metaData = JSON.parse(metaJsonFile.toString()) as ParsedAppMetaInfo;
250
- }
251
- const { versionName, pushy_build_time } = metaData;
252
- let buildTime = 0;
253
- if (pushy_build_time) {
254
- buildTime = Number(pushy_build_time);
255
- }
256
- if (!Number.isFinite(buildTime) || buildTime === 0) {
257
- throw new Error(t('buildTimeNotFound'));
258
- }
259
- return {
260
- versionName,
261
- buildTime,
262
- bundleHash: await sha256(bundleFile),
263
- bundleFile,
264
- ...appCredential,
265
- };
266
- }
267
-
268
- // lowercase because the zip reader also matches against the lowercased entry
269
- // name (real IPAs use "Payload/")
270
- export const IpaBundleFileName = /^payload\/[^/]+\.app\/main\.jsbundle$/;
271
- const IpaUpdateJsonName = /^payload\/[^/]+\.app\/assets\/update\.json$/;
272
- const IpaBuildTimeName = /^payload\/[^/]+\.app\/pushy_build_time\.txt$/;
273
- // Not in root bundle when use `use_frameworks`
274
- const IpaBuildTimeFrameworkName =
275
- /^payload\/[^/]+\.app\/frameworks\/react_native_update\.framework\/pushy_build_time\.txt$/;
276
-
277
- export async function getIpaInfo(fn: string) {
278
- const appInfoParser = createAppInfoParser(fn);
279
- // read all four entries in a single scan over the archive
280
- const entries = await appInfoParser.parser.getEntries([
281
- IpaBundleFileName,
282
- IpaUpdateJsonName,
283
- IpaBuildTimeName,
284
- IpaBuildTimeFrameworkName,
285
- ]);
286
- const bundleFile = entries[String(IpaBundleFileName)];
287
- if (!bundleFile) {
288
- throw new Error(
289
- t('bundleNotFound', {
290
- packageType: 'ipa',
291
- entryFile: 'main.jsbundle',
292
- }),
293
- );
294
- }
295
- const updateJsonFile = entries[String(IpaUpdateJsonName)];
296
- let appCredential = {};
297
- if (updateJsonFile) {
298
- appCredential = JSON.parse(updateJsonFile.toString()).ios;
299
- }
300
- const { CFBundleShortVersionString: versionName } =
301
- await appInfoParser.parse<ParsedIpaInfo>();
302
- const buildTimeTxtBuffer =
303
- entries[String(IpaBuildTimeName)] ??
304
- entries[String(IpaBuildTimeFrameworkName)];
305
- if (!buildTimeTxtBuffer) {
306
- throw new Error(t('buildTimeNotFound'));
307
- }
308
- const buildTime = buildTimeTxtBuffer.toString().trim();
309
- return {
310
- versionName,
311
- buildTime,
312
- bundleHash: await sha256(bundleFile),
313
- bundleFile,
314
- ...appCredential,
315
- };
316
- }
317
-
318
- export async function getAabInfo(fn: string) {
319
- const protobuf = require('protobufjs') as typeof import('protobufjs');
320
- const root = await protobuf.load(
321
- path.join(__dirname, '../../proto/Resources.proto'),
322
- );
323
- const XmlNode = root.lookupType('aapt.pb.XmlNode');
324
-
325
- const buffer = await readZipEntry(fn, 'base/manifest/AndroidManifest.xml');
326
-
327
- const message = XmlNode.decode(buffer);
328
- const object = XmlNode.toObject(message, {
329
- enums: String,
330
- longs: String,
331
- bytes: String,
332
- defaults: true,
333
- arrays: true,
334
- }) as AabXmlNodeObject;
335
-
336
- const manifestElement = object.element;
337
- if (manifestElement.name !== 'manifest') {
338
- throw new Error(t('invalidManifest'));
339
- }
340
-
341
- let versionName = '';
342
- for (const attr of manifestElement.attribute) {
343
- if (attr.name === 'versionName') {
344
- versionName = attr.value;
345
- }
346
- }
347
-
348
- let buildTime = 0;
349
- const appCredential = {};
350
-
351
- // Find application node
352
- const applicationNode = manifestElement.child.find(
353
- (child) => child.element?.name === 'application',
354
- );
355
- const applicationElement = applicationNode?.element;
356
- if (applicationElement) {
357
- const metaDataNodes = applicationElement.child.filter(
358
- (child) => child.element?.name === 'meta-data',
359
- );
360
- for (const meta of metaDataNodes) {
361
- let name = '';
362
- let value = '';
363
- let resourceId = 0;
364
-
365
- const metaElement = meta.element;
366
- if (!metaElement) {
367
- continue;
368
- }
369
- for (const attr of metaElement.attribute) {
370
- if (attr.name === 'name') {
371
- name = attr.value;
372
- }
373
- if (attr.name === 'value') {
374
- value = attr.value;
375
- if (attr.compiledItem?.ref?.id) {
376
- resourceId = attr.compiledItem.ref.id;
377
- } else if (attr.compiledItem?.prim?.intDecimalValue) {
378
- value = attr.compiledItem.prim.intDecimalValue.toString();
379
- }
380
- }
381
- }
382
-
383
- if (name === 'pushy_build_time') {
384
- if (resourceId > 0) {
385
- const resolvedValue = await resolveResource(fn, resourceId, root);
386
- if (resolvedValue) {
387
- value = resolvedValue;
388
- }
389
- }
390
- buildTime = Number(value);
391
- }
392
- }
393
- }
394
-
395
- if (!Number.isFinite(buildTime) || buildTime === 0) {
396
- throw new Error(t('buildTimeNotFound'));
397
- }
398
-
399
- // The JS bundle lives in the base module; these are the same bytes the
400
- // extracted APK carries (extractApk copies entries verbatim), so the hash
401
- // matches what uploadAab ends up registering via getApkInfo. Lenient on
402
- // absence — getAabInfo is display-only (parseAab); the upload path goes
403
- // through extractApk → getApkInfo which enforces the bundle's presence.
404
- let bundleHash: string | undefined;
405
- try {
406
- bundleHash = await sha256(
407
- await readZipEntry(fn, 'base/assets/index.android.bundle'),
408
- );
409
- } catch {
410
- // no embedded bundle (e.g. debug AAB); omit the field
411
- }
412
-
413
- return {
414
- versionName,
415
- buildTime,
416
- ...(bundleHash ? { bundleHash } : {}),
417
- ...appCredential,
418
- };
419
- }
420
-
421
- async function readZipEntry(fn: string, entryName: string): Promise<Buffer> {
422
- return new Promise((resolve, reject) => {
423
- openZipFile(fn, { lazyEntries: true }, (err, zipfile) => {
424
- if (err || !zipfile) {
425
- reject(err ?? new Error('Failed to open zip file'));
426
- return;
427
- }
428
- let found = false;
429
- zipfile.readEntry();
430
- zipfile.on('entry', (entry: YauzlEntry) => {
431
- if (entry.fileName === entryName) {
432
- found = true;
433
- zipfile.openReadStream(entry, (streamError, readStream) => {
434
- if (streamError || !readStream) {
435
- zipfile.close();
436
- reject(streamError ?? new Error('Failed to read zip entry'));
437
- return;
438
- }
439
- const chunks: Buffer[] = [];
440
- readStream.on('data', (chunk: Buffer) => chunks.push(chunk));
441
- readStream.on('end', () => {
442
- zipfile.close();
443
- resolve(Buffer.concat(chunks));
444
- });
445
- readStream.on('error', (error) => {
446
- zipfile.close();
447
- reject(error);
448
- });
449
- });
450
- } else {
451
- zipfile.readEntry();
452
- }
453
- });
454
- zipfile.on('end', () => {
455
- if (!found) reject(new Error(`${entryName} not found in AAB`));
456
- });
457
- zipfile.on('error', reject);
458
- });
459
- });
460
- }
461
-
462
- async function resolveResource(
463
- fn: string,
464
- resourceId: number,
465
- root: ProtobufRoot,
466
- ): Promise<string | null> {
467
- const pkgId = (resourceId >> 24) & 0xff;
468
- const typeId = (resourceId >> 16) & 0xff;
469
- const entryId = resourceId & 0xffff;
470
-
471
- try {
472
- const buffer = await readZipEntry(fn, 'base/resources.pb');
473
- const ResourceTable = root.lookupType('aapt.pb.ResourceTable');
474
- const message = ResourceTable.decode(buffer);
475
- const object = ResourceTable.toObject(message, {
476
- enums: String,
477
- longs: String,
478
- bytes: String,
479
- defaults: true,
480
- arrays: true,
481
- }) as AabResourceTableObject;
482
-
483
- // Find package
484
- const pkg = object.package.find((pkgItem) => pkgItem.packageId === pkgId);
485
- if (!pkg) return null;
486
-
487
- // Find type
488
- const type = pkg.type.find((typeItem) => typeItem.typeId === typeId);
489
- if (!type) return null;
490
-
491
- // Find entry
492
- const entry = type.entry.find((entryItem) => entryItem.entryId === entryId);
493
- if (!entry) return null;
494
-
495
- // Get value from configValue
496
- if (entry.configValue && entry.configValue.length > 0) {
497
- const val = entry.configValue[0]?.value;
498
- const stringValue = val?.item?.str?.value;
499
- if (typeof stringValue === 'string') {
500
- return stringValue;
501
- }
502
- }
503
- } catch (e) {
504
- console.warn(t('failedToResolveResource', { error: e }));
505
- }
506
- return null;
507
- }
508
-
509
- const VERSION_CHECK_PACKAGES = [
510
- 'react-native-update-cli',
511
- 'react-native-update',
512
- ];
513
-
514
- /**
515
- * Latest registry versions of the CLI and the client library, in that order
516
- * (`undefined` where unknown). Never rejects.
517
- *
518
- * `background: true` answers from a 1-day cache when possible and otherwise
519
- * refreshes it with an unref'd request, so the process is free to exit before
520
- * the registry answers; `background: false` always asks the registry and
521
- * waits (refreshing the cache on the way).
522
- */
523
- async function getLatestVersions(
524
- background: boolean,
525
- ): Promise<Array<string | undefined>> {
526
- // the registry client pulls in global-dirs/registry-auth-token/semver: only
527
- // pay for them when actually checking
528
- const { default: latestVersion } =
529
- require('./latest-version') as typeof import('./latest-version');
530
- return latestVersion(VERSION_CHECK_PACKAGES, {
531
- useCache: true,
532
- ...(background ? { unref: true } : { cacheMaxAge: 0 }),
533
- requestOptions: {
534
- timeout: 2000,
535
- },
536
- })
537
- .then((pkgs) => pkgs.map((pkg) => pkg.latest))
538
- .catch(() => VERSION_CHECK_PACKAGES.map(() => undefined));
539
- }
540
-
541
- function isNewer(latest: string | undefined, current: string | undefined) {
542
- if (!latest || !current) {
543
- return false;
544
- }
545
- try {
546
- return compare(latest, current, '>');
547
- } catch {
548
- return false;
549
- }
550
- }
551
-
552
- function latestTag(version: string | undefined) {
553
- return version
554
- ? ` ${t('latestVersionTag', { version: chalk.green(version) })}`
555
- : '';
556
- }
557
-
558
- export interface VersionCheck {
559
- /** settles once the registry check has finished (or failed); never rejects */
560
- done: Promise<void>;
561
- /** wait for the check, but never longer than `graceMs` */
562
- settle: (graceMs: number) => Promise<void>;
563
- /** launch a detached self-update after the foreground command is done */
564
- startAutoUpdate: () => void;
565
- /**
566
- * Print the "newer version available" hints if the check has completed by
567
- * now; a no-op while it is still pending, when nothing is newer, and after
568
- * the first call. Safe to call from a process 'exit' handler.
569
- */
570
- printHints: () => void;
571
- }
572
-
573
- /**
574
- * Print the installed CLI / react-native-update versions (and refuse or warn
575
- * about unsupported client versions) immediately, without touching the
576
- * network.
577
- *
578
- * With `wait: true` (the `-v`/`version` command) the registry is queried
579
- * first and the latest versions are printed inline. Otherwise the registry
580
- * check runs in the background and the returned `printHints` shows what is
581
- * newer once the command is done — the command itself is never delayed by it.
582
- */
583
- export async function printVersionCommand({
584
- wait = true,
585
- }: {
586
- wait?: boolean;
587
- } = {}): Promise<VersionCheck> {
588
- const rnuVersion = getDepVersions()['react-native-update'];
589
-
590
- let latest: Array<string | undefined> | undefined;
591
- const check = getLatestVersions(!wait).then((versions) => {
592
- latest = versions;
593
- });
594
- if (wait) {
595
- await check;
596
- }
597
- const [latestCliVersion, latestRnuVersion] = latest ?? [];
598
-
599
- console.log(
600
- `react-native-update-cli: ${pkg.version}${latestTag(latestCliVersion)}`,
601
- );
602
- try {
603
- const { consumeAutoUpdateNotice } =
604
- require('../auto-update') as typeof import('../auto-update');
605
- const notice = consumeAutoUpdateNotice(pkg.version);
606
- if (notice?.kind === 'updated') {
607
- console.log(
608
- t('autoUpdateSuccess', {
609
- from: notice.currentVersion,
610
- to: notice.targetVersion,
611
- }),
612
- );
613
- } else if (notice?.kind === 'permission') {
614
- console.warn(
615
- t('autoUpdatePermission', {
616
- command: notice.command,
617
- }),
618
- );
619
- }
620
- } catch {
621
- // A corrupt/unwritable updater cache cannot affect normal commands.
622
- }
623
- if (rnuVersion) {
624
- console.log(
625
- `react-native-update: ${rnuVersion}${latestTag(latestRnuVersion)}`,
626
- );
627
- if (IS_CRESC) {
628
- if (satisfies(rnuVersion, '<10.27.0')) {
629
- console.error(
630
- 'Unsupported version, please update to the latest version: npm i react-native-update@latest',
631
- );
632
- process.exit(1);
633
- }
634
- } else {
635
- if (satisfies(rnuVersion, '<8.5.2')) {
636
- console.warn(
637
- `当前版本已不再支持,请至少升级到 v8 的最新小版本后重新打包(代码无需改动): npm i react-native-update@8 .
638
- 如有使用安装 apk 的功能,请注意添加所需权限 https://pushy.reactnative.cn/docs/api#async-function-downloadandinstallapkurl`,
639
- );
640
- } else if (satisfies(rnuVersion, '9.0.0 - 9.2.1')) {
641
- console.warn(
642
- `当前版本已不再支持,请至少升级到 v9 的最新小版本后重新打包(代码无需改动,可直接热更): npm i react-native-update@9 .
643
- 如有使用安装 apk 的功能,请注意添加所需权限 https://pushy.reactnative.cn/docs/api#async-function-downloadandinstallapkurl`,
644
- );
645
- } else if (satisfies(rnuVersion, '10.0.0 - 10.17.0')) {
646
- console.warn(
647
- '当前版本已不再支持,请升级到 v10 的最新小版本(代码无需改动,可直接热更): npm i react-native-update@10',
648
- );
649
- }
650
- }
651
- } else {
652
- console.log(t('rnuVersionNotFound'));
653
- }
654
-
655
- let hinted = wait; // inline tags already shown
656
- const printHints = () => {
657
- if (hinted || !latest) {
658
- return;
659
- }
660
- hinted = true;
661
- const [cliLatest, rnuLatest] = latest;
662
- if (isNewer(cliLatest, pkg.version)) {
663
- console.log(
664
- `react-native-update-cli: ${pkg.version}${latestTag(cliLatest)}`,
665
- );
666
- }
667
- if (rnuVersion && isNewer(rnuLatest, rnuVersion)) {
668
- console.log(`react-native-update: ${rnuVersion}${latestTag(rnuLatest)}`);
669
- }
670
- };
671
-
672
- const settle = (graceMs: number) => {
673
- let timer: NodeJS.Timeout | undefined;
674
- const grace = new Promise<void>((resolve) => {
675
- timer = setTimeout(resolve, graceMs);
676
- });
677
- return Promise.race([check, grace]).then(() => clearTimeout(timer));
678
- };
679
-
680
- let autoUpdateStarted = false;
681
- const startAutoUpdate = () => {
682
- if (autoUpdateStarted || !isNewer(latest?.[0], pkg.version)) {
683
- return;
684
- }
685
- autoUpdateStarted = true;
686
- try {
687
- const { launchAutoUpdate } =
688
- require('../auto-update') as typeof import('../auto-update');
689
- launchAutoUpdate(pkg.version, latest?.[0]);
690
- } catch {
691
- // Self-update is strictly opportunistic and never affects the command.
692
- }
693
- };
694
-
695
- return { done: check, settle, startAutoUpdate, printHints };
696
- }
697
-
698
- export { checkPlugins };