react-native-update-cli 2.22.7 → 2.22.8

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 (59) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/cli.json +5 -0
  4. package/lib/api.d.ts +7 -0
  5. package/lib/api.js +106 -38
  6. package/lib/app.js +3 -2
  7. package/lib/bin.js +16 -2
  8. package/lib/bundle-runner.d.ts +11 -4
  9. package/lib/bundle-runner.js +176 -90
  10. package/lib/bundle.d.ts +1 -0
  11. package/lib/bundle.js +2 -0
  12. package/lib/diff.d.ts +9 -0
  13. package/lib/diff.js +162 -120
  14. package/lib/locales/en.d.ts +1 -0
  15. package/lib/locales/en.js +1 -0
  16. package/lib/locales/zh.d.ts +1 -0
  17. package/lib/locales/zh.js +1 -0
  18. package/lib/package.d.ts +7 -3
  19. package/lib/package.js +22 -12
  20. package/lib/types.d.ts +2 -0
  21. package/lib/utils/dep-versions.d.ts +7 -0
  22. package/lib/utils/dep-versions.js +66 -31
  23. package/lib/utils/hbcTransform.d.ts +21 -0
  24. package/lib/utils/hbcTransform.js +146 -5
  25. package/lib/utils/hermes-base.d.ts +21 -4
  26. package/lib/utils/hermes-base.js +146 -37
  27. package/lib/utils/http-helper.d.ts +6 -1
  28. package/lib/utils/http-helper.js +23 -11
  29. package/lib/utils/index.d.ts +30 -1
  30. package/lib/utils/index.js +98 -24
  31. package/lib/utils/latest-version/index.d.ts +11 -8
  32. package/lib/utils/latest-version/index.js +63 -18
  33. package/lib/utils/zip-entries.js +20 -15
  34. package/lib/utils/zip-options.d.ts +2 -0
  35. package/lib/utils/zip-options.js +9 -4
  36. package/lib/utils/zip-range.d.ts +47 -15
  37. package/lib/utils/zip-range.js +192 -83
  38. package/lib/versions.js +19 -9
  39. package/package.json +11 -11
  40. package/src/api.ts +126 -46
  41. package/src/app.ts +3 -2
  42. package/src/bin.ts +17 -2
  43. package/src/bundle-runner.ts +225 -113
  44. package/src/bundle.ts +3 -0
  45. package/src/diff.ts +210 -153
  46. package/src/locales/en.ts +2 -0
  47. package/src/locales/zh.ts +2 -0
  48. package/src/package.ts +26 -13
  49. package/src/types.ts +2 -0
  50. package/src/utils/dep-versions.ts +76 -33
  51. package/src/utils/hbcTransform.ts +194 -5
  52. package/src/utils/hermes-base.ts +156 -45
  53. package/src/utils/http-helper.ts +24 -13
  54. package/src/utils/index.ts +136 -26
  55. package/src/utils/latest-version/index.ts +82 -29
  56. package/src/utils/zip-entries.ts +18 -16
  57. package/src/utils/zip-options.ts +8 -3
  58. package/src/utils/zip-range.ts +244 -88
  59. package/src/versions.ts +17 -7
@@ -82,10 +82,10 @@ interface LatestVersionOptions {
82
82
  * Awaiting the api to return might take time, depending on the network, and might impact your package loading performance.
83
83
  * You can use the cache mechanism to improve load performance and reduce unnecessary network requests.
84
84
  * If `useCache` is not supplied, the api will always check for updates and wait for every requests to return before returning itself.
85
- * If `useCache` is used, the api will always returned immediately, with either (for each provided packages):
86
- * 1) a latest/next version available if a cache was found
87
- * 2) no latest/next version available if no cache was found - in such case updates will be fetched in the background and a cache will
88
- * be created for each provided packages and made available for the next call to the api.
85
+ * If `useCache` is used (for each provided package):
86
+ * 1) a fresh cache (younger than `cacheMaxAge`, from the same registry) answers without any network request
87
+ * 2) otherwise the registry is queried and the cache refreshed; when that query fails, a stale cache (if any) is used instead.
88
+ * Combine with `unref` so a slow refresh never keeps the process alive.
89
89
  * @default false
90
90
  */
91
91
  readonly useCache?: boolean;
@@ -93,14 +93,18 @@ interface LatestVersionOptions {
93
93
  /**
94
94
  * How long the cache for the provided packages should be used before being refreshed (in milliseconds).
95
95
  * If `useCache` is not supplied, this option has no effect.
96
- * If `0` is used, this will force the cache to refresh immediately:
97
- * 1) The api will returned immediately (without any latest nor next version available for the provided packages)
98
- * 2) New updates will be fetched in the background
99
- * 3) The cache for each provided packages will be refreshed and made available for the next call to the api
96
+ * If `0` is used, the cache is always refreshed (a stale cache still serves as a fallback when the refresh fails).
100
97
  * @default ONE_DAY
101
98
  */
102
99
  readonly cacheMaxAge?: number;
103
100
 
101
+ /**
102
+ * Do not let the registry request keep the process alive: its socket is `unref`'d, so the process may exit before the
103
+ * request completes (the returned promise then simply never settles). Use for opportunistic background checks.
104
+ * @default false
105
+ */
106
+ readonly unref?: boolean;
107
+
104
108
  /**
105
109
  * A JavaScript package registry url that implements the CommonJS Package Registry specification.
106
110
  * @default "Looks at any registry urls in the .npmrc file or fallback to the default npm registry instead"
@@ -190,6 +194,8 @@ interface PackageMetadata {
190
194
  lastUpdateDate: number;
191
195
  versions: string[];
192
196
  distTags: Record<string, string>;
197
+ /** registry the metadata came from; a cache from another registry is not reused */
198
+ registryUrl?: string;
193
199
  }
194
200
 
195
201
  export const ONE_DAY = 1000 * 60 * 60 * 24; // eslint-disable-line @typescript-eslint/naming-convention
@@ -202,14 +208,21 @@ const isPackageJson = (obj: any): obj is PackageJson => {
202
208
  );
203
209
  };
204
210
 
211
+ const resolveRegistryUrl = (
212
+ pkgName: string,
213
+ options?: LatestVersionOptions,
214
+ ): string => {
215
+ const i = pkgName.indexOf('/');
216
+ const pkgScope = i !== -1 ? pkgName.slice(0, i) : '';
217
+ return options?.registryUrl ?? getRegistryUrl(pkgScope);
218
+ };
219
+
205
220
  const downloadMetadata = (
206
221
  pkgName: string,
207
222
  options?: LatestVersionOptions,
208
223
  ): Promise<PackageMetadata> => {
209
224
  return new Promise((resolve, reject) => {
210
- const i = pkgName.indexOf('/');
211
- const pkgScope = i !== -1 ? pkgName.slice(0, i) : '';
212
- const registryUrl = options?.registryUrl ?? getRegistryUrl(pkgScope);
225
+ const registryUrl = resolveRegistryUrl(pkgName, options);
213
226
  const pkgUrl = new URL(
214
227
  encodeURIComponent(pkgName).replace(/^%40/, '@'),
215
228
  registryUrl,
@@ -252,6 +265,7 @@ const downloadMetadata = (
252
265
  lastUpdateDate: Date.now(),
253
266
  versions: Object.keys(pkgMetadata.versions as string[]),
254
267
  distTags: pkgMetadata['dist-tags'],
268
+ registryUrl,
255
269
  });
256
270
  return;
257
271
  } catch (err) {
@@ -279,11 +293,23 @@ const downloadMetadata = (
279
293
  request.on('close', () => {
280
294
  request.removeAllListeners();
281
295
  });
296
+ if (options?.unref) {
297
+ // A background check must never delay the process exit: drop the
298
+ // socket's ref (also for a pooled keep-alive socket, which the agent
299
+ // ref's again right before handing it out).
300
+ request.once('socket', (socket: { unref?: () => void }) => {
301
+ socket.unref?.();
302
+ });
303
+ }
282
304
  });
283
305
  };
284
306
 
285
307
  const getCacheDir = (name = '@badisi/latest-version'): string => {
286
308
  const homeDir = homedir();
309
+ if (process.env.XDG_CACHE_HOME) {
310
+ // an explicit override wins on every platform (also lets tests isolate)
311
+ return join(process.env.XDG_CACHE_HOME, name);
312
+ }
287
313
  switch (process.platform) {
288
314
  case 'darwin':
289
315
  return join(homeDir, 'Library', 'Caches', name);
@@ -299,30 +325,48 @@ const getCacheDir = (name = '@badisi/latest-version'): string => {
299
325
  };
300
326
 
301
327
  const saveMetadataToCache = (pkg: PackageMetadata): void => {
302
- const filePath = join(getCacheDir(), `${pkg.name}.json`);
303
- if (!existsSync(dirname(filePath))) {
304
- mkdirSync(dirname(filePath), { recursive: true });
328
+ try {
329
+ const filePath = join(getCacheDir(), `${pkg.name}.json`);
330
+ if (!existsSync(dirname(filePath))) {
331
+ mkdirSync(dirname(filePath), { recursive: true });
332
+ }
333
+ writeFileSync(filePath, JSON.stringify(pkg));
334
+ } catch {
335
+ // a read-only or missing cache dir must not turn into an error
305
336
  }
306
- writeFileSync(filePath, JSON.stringify(pkg));
307
337
  };
308
338
 
339
+ /**
340
+ * The cached metadata of a package (from the same registry), and whether it is
341
+ * still younger than `cacheMaxAge`. A stale entry is returned as well so it can
342
+ * serve as a fallback when the registry is unreachable.
343
+ */
309
344
  const getMetadataFromCache = (
310
345
  pkgName: string,
311
346
  options?: LatestVersionOptions,
312
- ): PackageMetadata | undefined => {
347
+ ): { metadata: PackageMetadata; fresh: boolean } | undefined => {
313
348
  const maxAge = options?.cacheMaxAge ?? ONE_DAY;
314
- if (maxAge !== 0) {
349
+ try {
315
350
  const pkgCacheFilePath = join(getCacheDir(), `${pkgName}.json`);
316
- if (existsSync(pkgCacheFilePath)) {
317
- const pkg = JSON.parse(
318
- readFileSync(pkgCacheFilePath).toString(),
319
- ) as PackageMetadata;
320
- if (Date.now() - pkg.lastUpdateDate < maxAge) {
321
- return pkg;
322
- }
351
+ if (!existsSync(pkgCacheFilePath)) {
352
+ return undefined;
353
+ }
354
+ const metadata = JSON.parse(
355
+ readFileSync(pkgCacheFilePath).toString(),
356
+ ) as PackageMetadata;
357
+ if (
358
+ !metadata ||
359
+ typeof metadata.lastUpdateDate !== 'number' ||
360
+ !metadata.distTags ||
361
+ metadata.registryUrl !== resolveRegistryUrl(pkgName, options)
362
+ ) {
363
+ return undefined;
323
364
  }
365
+ const age = Date.now() - metadata.lastUpdateDate;
366
+ return { metadata, fresh: maxAge !== 0 && age >= 0 && age < maxAge };
367
+ } catch {
368
+ return undefined; // unreadable / corrupt cache is the same as no cache
324
369
  }
325
- return undefined; // invalidates cache
326
370
  };
327
371
 
328
372
  const getRegistryVersions = async (
@@ -332,10 +376,19 @@ const getRegistryVersions = async (
332
376
  ): Promise<RegistryVersions> => {
333
377
  let pkgMetadata: PackageMetadata | undefined;
334
378
  if (pkgName.length && options?.useCache) {
335
- pkgMetadata = getMetadataFromCache(pkgName, options);
336
- if (!pkgMetadata) {
337
- pkgMetadata = await downloadMetadata(pkgName, options);
338
- saveMetadataToCache(pkgMetadata);
379
+ const cached = getMetadataFromCache(pkgName, options);
380
+ if (cached?.fresh) {
381
+ pkgMetadata = cached.metadata;
382
+ } else {
383
+ try {
384
+ pkgMetadata = await downloadMetadata(pkgName, options);
385
+ saveMetadataToCache(pkgMetadata);
386
+ } catch (err) {
387
+ if (!cached) {
388
+ throw err;
389
+ }
390
+ pkgMetadata = cached.metadata; // stale beats nothing
391
+ }
339
392
  }
340
393
  } else if (pkgName.length) {
341
394
  pkgMetadata = await downloadMetadata(pkgName, options);
@@ -7,7 +7,6 @@ import {
7
7
  open as openZipFile,
8
8
  type ZipFile as YauzlZipFile,
9
9
  } from 'yauzl';
10
- import { t } from './i18n';
11
10
 
12
11
  export function readEntry(
13
12
  entry: Entry,
@@ -26,7 +25,8 @@ export function readEntry(
26
25
  buffers.push(chunk);
27
26
  });
28
27
  stream.on('end', () => {
29
- resolve(Buffer.concat(buffers));
28
+ // a single chunk (a cached Range read) is handed back as-is, not copied
29
+ resolve(buffers.length === 1 ? buffers[0] : Buffer.concat(buffers));
30
30
  });
31
31
  stream.on('error', (err) => {
32
32
  reject(err);
@@ -169,21 +169,22 @@ export async function enumZipEntries(
169
169
  path.join(os.tmpdir(), 'nested_zip_'),
170
170
  );
171
171
  const tempZipPath = path.join(tempDir, 'temp.zip');
172
-
173
- await new Promise((res, rej) => {
174
- zipfile.openReadStream(entry, async (err, readStream) => {
175
- if (err) return rej(err);
176
- const writeStream = fs.createWriteStream(tempZipPath);
177
- readStream.on('error', rej);
178
- readStream.pipe(writeStream);
179
- writeStream.on('finish', () => res(void 0));
180
- writeStream.on('error', rej);
172
+ try {
173
+ await new Promise((res, rej) => {
174
+ zipfile.openReadStream(entry, async (err, readStream) => {
175
+ if (err) return rej(err);
176
+ const writeStream = fs.createWriteStream(tempZipPath);
177
+ readStream.on('error', rej);
178
+ readStream.pipe(writeStream);
179
+ writeStream.on('finish', () => res(void 0));
180
+ writeStream.on('error', rej);
181
+ });
181
182
  });
182
- });
183
-
184
- await enumZipEntries(tempZipPath, callback, `${fullPath}/`);
185
183
 
186
- await fs.remove(tempDir);
184
+ await enumZipEntries(tempZipPath, callback, `${fullPath}/`);
185
+ } finally {
186
+ await fs.remove(tempDir);
187
+ }
187
188
  }
188
189
 
189
190
  const result = callback(entry, zipfile, fullPath);
@@ -191,7 +192,8 @@ export async function enumZipEntries(
191
192
  await result;
192
193
  }
193
194
  } catch (error) {
194
- console.error(t('processingError', { error }));
195
+ // the rejection carries the error; logging it here too would make
196
+ // callers report it twice
195
197
  zipfile.close();
196
198
  reject(error);
197
199
  return;
@@ -8,6 +8,11 @@ export type ZipEntryOptions = {
8
8
 
9
9
  export const ZIP_ENTRY_SNIFF_BYTES = 64;
10
10
  export const MANIFEST_COMPRESSION_THRESHOLD_BYTES = 256;
11
+ // Deflate level for the bundle/asset payload. Level 9 measured ~4x the CPU
12
+ // of level 6 on Hermes bytecode for ~0.6% smaller output, so 6 is the sweet
13
+ // spot; the manifest is tiny, so it can afford 9.
14
+ export const PAYLOAD_COMPRESSION_LEVEL = 6;
15
+ export const MANIFEST_COMPRESSION_LEVEL = 9;
11
16
 
12
17
  const alreadyCompressedExtensions = new Set([
13
18
  '.7z',
@@ -139,7 +144,7 @@ export function zipOptionsForPatchEntry(): ZipEntryOptions {
139
144
 
140
145
  export function zipOptionsForManifestEntry(byteLength = 0): ZipEntryOptions {
141
146
  if (byteLength >= MANIFEST_COMPRESSION_THRESHOLD_BYTES) {
142
- return { compressionLevel: 9 };
147
+ return { compressionLevel: MANIFEST_COMPRESSION_LEVEL };
143
148
  }
144
149
  return { compress: false };
145
150
  }
@@ -151,7 +156,7 @@ export function zipOptionsForPayloadEntry(
151
156
  if (prefix && prefix.length > 0) {
152
157
  if (hasHermesBytecodeMagic(prefix)) {
153
158
  // Hermes bytecode is binary, but still benefits significantly from zip deflate.
154
- return { compress: true, compressionLevel: 9 };
159
+ return { compress: true, compressionLevel: PAYLOAD_COMPRESSION_LEVEL };
155
160
  }
156
161
  if (hasAlreadyCompressedMagic(prefix)) {
157
162
  return { compress: false };
@@ -162,7 +167,7 @@ export function zipOptionsForPayloadEntry(
162
167
  if (alreadyCompressedExtensions.has(extension)) {
163
168
  return { compress: false };
164
169
  }
165
- return { compress: true, compressionLevel: 9 };
170
+ return { compress: true, compressionLevel: PAYLOAD_COMPRESSION_LEVEL };
166
171
  }
167
172
 
168
173
  export function zipOptionsForPayloadFile(