react-native-update-cli 2.22.6 → 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 +35 -2
  9. package/lib/bundle-runner.js +313 -128
  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 +31 -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 +31 -7
  26. package/lib/utils/hermes-base.js +284 -76
  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 +84 -13
  37. package/lib/utils/zip-range.js +363 -63
  38. package/lib/versions.js +30 -23
  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 +419 -171
  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 +42 -14
  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 +311 -81
  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 +436 -67
  59. package/src/versions.ts +34 -26
@@ -13,6 +13,7 @@ import { createHash } from 'crypto';
13
13
  import fs from 'fs-extra';
14
14
  import os from 'os';
15
15
  import path from 'path';
16
+ import { PassThrough, Readable } from 'stream';
16
17
  import { pipeline } from 'stream/promises';
17
18
  import { tempDir } from './constants';
18
19
  import { getHbcVersion } from './hbcTransform';
@@ -29,6 +30,27 @@ import {
29
30
 
30
31
  export type HermesBaseOption = 'auto' | 'none' | string;
31
32
 
33
+ /**
34
+ * The base cannot be obtained whatever the transport or how often it is
35
+ * retried (wrong content on the server, no bundle in the package, ...).
36
+ */
37
+ export class PermanentBaseError extends Error {}
38
+ /** The fetched bundle's sha256 differs from what the server recorded. */
39
+ export class BundleHashMismatchError extends PermanentBaseError {
40
+ constructor(actual: string, expected: string) {
41
+ super(
42
+ `bundleHash mismatch (${actual.slice(0, 12)} != ${expected.slice(0, 12)})`,
43
+ );
44
+ }
45
+ }
46
+
47
+ /** time allowed for a response to start (headers) */
48
+ const FETCH_HEADERS_TIMEOUT_MS = 30_000;
49
+ /** a download that receives nothing for this long is abandoned */
50
+ const STREAM_IDLE_TIMEOUT_MS = 60_000;
51
+ /** cachePut leftovers (`<hash>.<pid>.tmp`) older than this are evicted */
52
+ const STALE_CACHE_TMP_MS = 60 * 60 * 1000;
53
+
32
54
  export interface HermesBaseSelection {
33
55
  /** path of the bundle (HBC) handed to hermesc as -base-bytecode */
34
56
  path: string;
@@ -151,8 +173,89 @@ export function sha256Hex(data: Buffer): string {
151
173
  return createHash('sha256').update(data).digest('hex');
152
174
  }
153
175
 
154
- /** Compile an empty file to learn which HBC version this hermesc emits. */
176
+ /** sha256 of a file, streamed (a cached base can be tens of MB) */
177
+ export async function sha256File(file: string): Promise<string> {
178
+ const hash = createHash('sha256');
179
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
180
+ return hash.digest('hex');
181
+ }
182
+
183
+ /** HBC version from the first bytes of a file, without reading the rest */
184
+ export async function readFileHbcVersion(file: string): Promise<number | null> {
185
+ const header = Buffer.alloc(128);
186
+ const fd = await fs.open(file, 'r');
187
+ try {
188
+ const { bytesRead } = await fs.read(fd, header, 0, 128, 0);
189
+ return getHbcVersion(header.subarray(0, bytesRead));
190
+ } catch {
191
+ return null;
192
+ } finally {
193
+ await fs.close(fd);
194
+ }
195
+ }
196
+
197
+ const PROBE_CACHE_FILE = 'hbc-versions.json';
198
+ const PROBE_CACHE_ENTRIES = 16;
199
+
200
+ /** identity of a hermesc binary for the probe cache: path + size + mtime */
201
+ function probeCacheKey(hermesCommand: string): string | null {
202
+ try {
203
+ const stat = fs.statSync(hermesCommand);
204
+ return `${path.resolve(hermesCommand)}|${stat.size}|${Math.floor(stat.mtimeMs)}`;
205
+ } catch {
206
+ return null;
207
+ }
208
+ }
209
+
210
+ function readProbeCache(): Record<string, number> {
211
+ try {
212
+ const parsed = JSON.parse(
213
+ fs.readFileSync(path.join(cacheDir(), PROBE_CACHE_FILE), 'utf8'),
214
+ );
215
+ return parsed && typeof parsed === 'object' ? parsed : {};
216
+ } catch {
217
+ return {};
218
+ }
219
+ }
220
+
221
+ function writeProbeCache(entries: Record<string, number>): void {
222
+ try {
223
+ const keys = Object.keys(entries);
224
+ // keep the most recently inserted entries only
225
+ const trimmed = Object.fromEntries(
226
+ keys.slice(-PROBE_CACHE_ENTRIES).map((key) => [key, entries[key]]),
227
+ );
228
+ fs.ensureDirSync(cacheDir());
229
+ fs.writeFileSync(
230
+ path.join(cacheDir(), PROBE_CACHE_FILE),
231
+ JSON.stringify(trimmed),
232
+ );
233
+ } catch {
234
+ // the cache is a convenience; probing again next time is fine
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Which HBC version this hermesc emits. The answer is remembered per binary
240
+ * (path, size, mtime) in the cache dir so only the first run of a given
241
+ * hermesc pays for the empty-file compile.
242
+ */
155
243
  export function probeHbcVersion(hermesCommand: string): number | null {
244
+ const key = probeCacheKey(hermesCommand);
245
+ if (key) {
246
+ const cached = readProbeCache()[key];
247
+ if (Number.isInteger(cached) && cached > 0) return cached;
248
+ }
249
+ const version = compileProbe(hermesCommand);
250
+ if (key && version !== null) {
251
+ const { [key]: _stale, ...others } = readProbeCache();
252
+ writeProbeCache({ ...others, [key]: version });
253
+ }
254
+ return version;
255
+ }
256
+
257
+ /** Compile an empty file to learn which HBC version this hermesc emits. */
258
+ function compileProbe(hermesCommand: string): number | null {
156
259
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rnu-hermes-probe-'));
157
260
  try {
158
261
  const input = path.join(dir, 'probe.js');
@@ -288,8 +391,7 @@ export async function cacheLookup(bundleHash: string): Promise<string | null> {
288
391
  if (!/^[0-9a-f]{64}$/.test(bundleHash)) return null;
289
392
  const file = path.join(cacheDir(), bundleHash);
290
393
  if (!(await fs.pathExists(file))) return null;
291
- const data = await fs.readFile(file);
292
- if (sha256Hex(data) !== bundleHash) {
394
+ if ((await sha256File(file).catch(() => '')) !== bundleHash) {
293
395
  // corrupt entry: never trust cache content
294
396
  await fs.remove(file).catch(() => {});
295
397
  return null;
@@ -303,8 +405,9 @@ export async function cacheLookup(bundleHash: string): Promise<string | null> {
303
405
  export async function cachePut(
304
406
  bundle: Buffer,
305
407
  maxMb?: number,
408
+ knownHash?: string,
306
409
  ): Promise<{ path: string; bundleHash: string }> {
307
- const bundleHash = sha256Hex(bundle);
410
+ const bundleHash = knownHash ?? sha256Hex(bundle);
308
411
  const dir = cacheDir();
309
412
  await fs.ensureDir(dir);
310
413
  const file = path.join(dir, bundleHash);
@@ -328,11 +431,19 @@ export async function enforceCacheLimits(
328
431
  if (!(await fs.pathExists(dir))) return;
329
432
  const { maxBytes, maxFiles } = cacheLimits(maxMb);
330
433
  const entries: { name: string; size: number; mtime: number }[] = [];
434
+ const staleTmpCutoff = Date.now() - STALE_CACHE_TMP_MS;
331
435
  for (const name of await fs.readdir(dir)) {
332
- if (!/^[0-9a-f]{64}$/.test(name)) continue;
436
+ const isTmp = isCacheTmpName(name);
437
+ if (!isTmp && !/^[0-9a-f]{64}$/.test(name)) continue;
333
438
  const stat = await fs.stat(path.join(dir, name)).catch(() => null);
334
- if (stat?.isFile())
335
- entries.push({ name, size: stat.size, mtime: stat.mtimeMs });
439
+ if (!stat?.isFile()) continue;
440
+ if (isTmp) {
441
+ // an interrupted cachePut; nothing will ever rename it into place
442
+ if (stat.mtimeMs < staleTmpCutoff)
443
+ await fs.remove(path.join(dir, name)).catch(() => {});
444
+ continue;
445
+ }
446
+ entries.push({ name, size: stat.size, mtime: stat.mtimeMs });
336
447
  }
337
448
  entries.sort((a, b) => b.mtime - a.mtime); // newest first
338
449
  let total = 0;
@@ -346,12 +457,23 @@ export async function enforceCacheLimits(
346
457
  }
347
458
  }
348
459
 
460
+ /** `<sha256>.<pid>.tmp`, the staging name cachePut writes before renaming */
461
+ function isCacheTmpName(name: string): boolean {
462
+ return /^[0-9a-f]{64}\.\d+\.tmp$/.test(name);
463
+ }
464
+
465
+ /** Remove every cached bundle (and staging leftovers); returns the bundle count. */
349
466
  export async function cleanCache(): Promise<number> {
350
467
  const dir = cacheDir();
351
468
  if (!(await fs.pathExists(dir))) return 0;
352
- const names = (await fs.readdir(dir)).filter((n) => /^[0-9a-f]{64}$/.test(n));
353
- for (const name of names) await fs.remove(path.join(dir, name));
354
- return names.length;
469
+ let bundles = 0;
470
+ for (const name of await fs.readdir(dir)) {
471
+ const isBundle = /^[0-9a-f]{64}$/.test(name);
472
+ if (!isBundle && !isCacheTmpName(name)) continue;
473
+ await fs.remove(path.join(dir, name));
474
+ if (isBundle) bundles += 1;
475
+ }
476
+ return bundles;
355
477
  }
356
478
 
357
479
  export async function cacheStats(): Promise<{
@@ -397,16 +519,21 @@ export async function downloadToFile(
397
519
  url: string,
398
520
  destination: string,
399
521
  ): Promise<void> {
400
- const response = await fetch(url);
522
+ const controller = new AbortController();
523
+ const headersTimer = setTimeout(
524
+ () => controller.abort(new Error('timeout waiting for response')),
525
+ FETCH_HEADERS_TIMEOUT_MS,
526
+ );
527
+ let response: Response;
528
+ try {
529
+ response = await fetch(url, { signal: controller.signal });
530
+ } finally {
531
+ clearTimeout(headersTimer);
532
+ }
401
533
  if (!response.ok || !response.body) {
402
534
  throw new Error(`download failed: HTTP ${response.status} ${url}`);
403
535
  }
404
- await fs.ensureDir(path.dirname(destination));
405
- const { Readable } = await import('stream');
406
- await pipeline(
407
- Readable.fromWeb(response.body as any),
408
- fs.createWriteStream(destination),
409
- );
536
+ await saveResponse(response, destination, controller);
410
537
  }
411
538
 
412
539
  // ---------------------------------------------------------------------------
@@ -432,6 +559,8 @@ export interface HermesBaseServerRecord {
432
559
 
433
560
  interface FetchedBaseBundle {
434
561
  bundle: Buffer;
562
+ /** sha256 of `bundle`, computed once here */
563
+ bundleHash: string;
435
564
  /** how the bytes were obtained, for the log line */
436
565
  transport: 'range-entry' | 'range-zip' | 'full';
437
566
  fetchedBytes?: number;
@@ -448,57 +577,90 @@ function hasBundleLocation(record: HermesBaseServerRecord): boolean {
448
577
  );
449
578
  }
450
579
 
580
+ /**
581
+ * Stream a response body to disk, giving up when no bytes arrive for
582
+ * STREAM_IDLE_TIMEOUT_MS. `controller` is the one the request was made with
583
+ * (aborting it also tears down the socket); a foreign response gets its own.
584
+ */
451
585
  async function saveResponse(
452
586
  response: Response,
453
587
  destination: string,
588
+ controller = new AbortController(),
454
589
  ): Promise<void> {
455
590
  if (!response.body) throw new Error('empty response body');
456
591
  await fs.ensureDir(path.dirname(destination));
457
- const { Readable } = await import('stream');
458
- await pipeline(
459
- Readable.fromWeb(response.body as any),
460
- fs.createWriteStream(destination),
461
- );
592
+ const abort = () =>
593
+ controller.abort(
594
+ new Error(`download stalled for ${STREAM_IDLE_TIMEOUT_MS / 1000}s`),
595
+ );
596
+ let idle = setTimeout(abort, STREAM_IDLE_TIMEOUT_MS);
597
+ const watchdog = new PassThrough({
598
+ transform(chunk, _encoding, callback) {
599
+ clearTimeout(idle);
600
+ idle = setTimeout(abort, STREAM_IDLE_TIMEOUT_MS);
601
+ callback(null, chunk);
602
+ },
603
+ });
604
+ try {
605
+ await pipeline(
606
+ Readable.fromWeb(response.body as any),
607
+ watchdog,
608
+ fs.createWriteStream(destination),
609
+ { signal: controller.signal },
610
+ );
611
+ } finally {
612
+ clearTimeout(idle);
613
+ }
462
614
  }
463
615
 
464
616
  /**
465
617
  * Obtain the base bundle with as little traffic as possible, in order:
466
618
  * 1. one Range request for the bundle's compressed bytes when the server
467
- * knows their location (ppk published by a CLI that reported it);
619
+ * knows their location (ppk / apk / ipa published by a CLI that
620
+ * reported it);
468
621
  * 2. the archive's central directory over Range, then just the bundle
469
622
  * entry (any zip: ppk, apk, ipa — harmony .app nests a second zip and
470
623
  * is skipped);
471
624
  * 3. the whole archive, as before.
472
625
  * A server that ignores Range (HTTP 200) streams the full archive into
473
- * `archive` without a second request. Range results are verified against
474
- * `record.bundleHash` here; a mismatch (e.g. re-packaged object) falls
475
- * through to the next transport instead of failing the resolution.
626
+ * `archive` without a second request. Every result is verified against
627
+ * `record.bundleHash`. A mismatch of the located bytes (1) may only mean the
628
+ * recorded location is stale, so the directory transport (2) still runs; a
629
+ * mismatch of the entry itself (2, 3) is final — the same bytes would come
630
+ * back however they are fetched — and raises BundleHashMismatchError.
476
631
  */
477
632
  export async function fetchBaseBundle(
478
633
  record: HermesBaseServerRecord,
479
634
  artifactType: BaseArtifactType,
480
635
  archive: string,
481
636
  log: (message: string) => void = () => {},
482
- ): Promise<FetchedBaseBundle | null> {
637
+ ): Promise<FetchedBaseBundle> {
483
638
  const matches = bundleEntryMatcher(artifactType);
484
- const verified = (bundle: Buffer | null): Buffer | null => {
485
- if (!bundle) throw new Error('bundle entry not found');
486
- if (record.bundleHash && sha256Hex(bundle) !== record.bundleHash) {
487
- throw new Error('bundleHash mismatch');
639
+ const verified = (
640
+ bundle: Buffer | null,
641
+ ): { bundle: Buffer; bundleHash: string } => {
642
+ if (!bundle) throw new PermanentBaseError('bundle entry not found');
643
+ const bundleHash = sha256Hex(bundle);
644
+ if (record.bundleHash && bundleHash !== record.bundleHash) {
645
+ throw new BundleHashMismatchError(bundleHash, record.bundleHash);
488
646
  }
489
- return bundle;
647
+ return { bundle, bundleHash };
490
648
  };
491
649
  const fromFullResponse = async (
492
650
  response: Response,
493
- ): Promise<FetchedBaseBundle | null> => {
651
+ ): Promise<FetchedBaseBundle> => {
494
652
  await saveResponse(response, archive);
495
- const bundle = await extractBundleFromArchive(archive);
496
- return bundle ? { bundle, transport: 'full' } : null;
653
+ return {
654
+ ...verified(await extractBundleFromArchive(archive)),
655
+ transport: 'full',
656
+ };
497
657
  };
498
658
  const skip = (reason: string) =>
499
659
  log(t('hermesBaseRangeFallback', { reason }));
500
660
 
501
- if (artifactType === 'ppk' && hasBundleLocation(record)) {
661
+ // harmony .app nests the bundle in a second zip, so a location inside the
662
+ // outer archive is never reported for it
663
+ if (artifactType !== 'app' && hasBundleLocation(record)) {
502
664
  try {
503
665
  const { data, fetchedBytes, totalBytes } = await fetchZipEntryData(
504
666
  record.url,
@@ -509,7 +671,7 @@ export async function fetchBaseBundle(
509
671
  },
510
672
  );
511
673
  return {
512
- bundle: verified(data) as Buffer,
674
+ ...verified(data),
513
675
  transport: 'range-entry',
514
676
  fetchedBytes,
515
677
  totalBytes,
@@ -530,9 +692,13 @@ export async function fetchBaseBundle(
530
692
  skip('server ignores Range');
531
693
  return fromFullResponse(remote.response);
532
694
  }
533
- const bundle = await readRemoteZipEntry(remote.zipFile, matches);
695
+ const bundle = await readRemoteZipEntry(
696
+ remote.zipFile,
697
+ matches,
698
+ remote.reader,
699
+ );
534
700
  return {
535
- bundle: verified(bundle) as Buffer,
701
+ ...verified(bundle),
536
702
  transport: 'range-zip',
537
703
  fetchedBytes: remote.reader.fetchedBytes,
538
704
  totalBytes: remote.reader.totalSize,
@@ -542,13 +708,17 @@ export async function fetchBaseBundle(
542
708
  skip('server ignores Range');
543
709
  return fromFullResponse(error.response);
544
710
  }
711
+ // the real entry was read and is not the recorded one: final
712
+ if (error instanceof PermanentBaseError) throw error;
545
713
  skip(`zip range: ${error?.message ?? error}`);
546
714
  }
547
715
  }
548
716
 
549
717
  await downloadToFile(record.url, archive);
550
- const bundle = await extractBundleFromArchive(archive);
551
- return bundle ? { bundle, transport: 'full' } : null;
718
+ return {
719
+ ...verified(await extractBundleFromArchive(archive)),
720
+ transport: 'full',
721
+ };
552
722
  }
553
723
 
554
724
  export interface ResolveHermesBaseParams {
@@ -617,7 +787,9 @@ export async function resolveHermesBase(
617
787
  }
618
788
  let record: HermesBaseServerRecord | null = null;
619
789
  try {
620
- record = await params.fetchBase(params.appId, bytecodeVersion);
790
+ record = await retryOnce(() =>
791
+ params.fetchBase(params.appId as string, bytecodeVersion),
792
+ );
621
793
  } catch (error: any) {
622
794
  log(
623
795
  t('hermesBaseNone', {
@@ -650,6 +822,19 @@ export async function resolveHermesBase(
650
822
  // 1. cache by bundleHash
651
823
  if (record.bundleHash) {
652
824
  const hit = await cacheLookup(record.bundleHash);
825
+ if (hit && record.bytecodeVersion == null) {
826
+ // the server does not know the HBC version (legacy version, native
827
+ // package): the download path checks it, the cache path must too
828
+ const version = await readFileHbcVersion(hit);
829
+ if (version !== bytecodeVersion) {
830
+ log(
831
+ t('hermesBaseNone', {
832
+ reason: `cached base is HBC ${version ?? 'n/a'}, need ${bytecodeVersion}`,
833
+ }),
834
+ );
835
+ return null;
836
+ }
837
+ }
653
838
  if (hit) {
654
839
  log(
655
840
  t('hermesBaseUsing', {
@@ -667,7 +852,7 @@ export async function resolveHermesBase(
667
852
  };
668
853
  }
669
854
  }
670
- // 2. download, extract, verify, cache — up to two attempts
855
+ // 2. download, extract, verify, cache — transport errors get a second try
671
856
  for (let attempt = 1; attempt <= 2; attempt++) {
672
857
  const dir = tmpDir();
673
858
  await fs.ensureDir(dir);
@@ -686,9 +871,7 @@ export async function resolveHermesBase(
686
871
  try {
687
872
  log(t('hermesBaseDownloading', { url: record.url }));
688
873
  const fetched = await fetchBaseBundle(record, artifactType, archive, log);
689
- if (!fetched)
690
- throw new Error('bundle entry not found in downloaded package');
691
- const { bundle } = fetched;
874
+ const { bundle, bundleHash: actualHash } = fetched;
692
875
  if (fetched.transport !== 'full') {
693
876
  log(
694
877
  t('hermesBaseRangeFetched', {
@@ -697,12 +880,6 @@ export async function resolveHermesBase(
697
880
  }),
698
881
  );
699
882
  }
700
- const actualHash = sha256Hex(bundle);
701
- if (record.bundleHash && actualHash !== record.bundleHash) {
702
- throw new Error(
703
- `bundleHash mismatch (${actualHash.slice(0, 12)} != ${record.bundleHash.slice(0, 12)})`,
704
- );
705
- }
706
883
  const version = getHbcVersion(bundle);
707
884
  if (version !== bytecodeVersion) {
708
885
  log(
@@ -712,7 +889,7 @@ export async function resolveHermesBase(
712
889
  );
713
890
  return null;
714
891
  }
715
- const cached = await cachePut(bundle, params.cacheMaxMb);
892
+ const cached = await cachePut(bundle, params.cacheMaxMb, actualHash);
716
893
  log(
717
894
  t('hermesBaseUsing', {
718
895
  source:
@@ -731,7 +908,7 @@ export async function resolveHermesBase(
731
908
  source,
732
909
  };
733
910
  } catch (error: any) {
734
- if (attempt === 2) {
911
+ if (attempt === 2 || error instanceof PermanentBaseError) {
735
912
  log(
736
913
  t('hermesBaseNone', {
737
914
  reason: `download/verify failed: ${error?.message ?? error}`,
@@ -746,6 +923,16 @@ export async function resolveHermesBase(
746
923
  return null;
747
924
  }
748
925
 
926
+ /** one retry after a short pause, for transient network failures */
927
+ async function retryOnce<T>(action: () => Promise<T>): Promise<T> {
928
+ try {
929
+ return await action();
930
+ } catch {
931
+ await new Promise((resolve) => setTimeout(resolve, 500));
932
+ return action();
933
+ }
934
+ }
935
+
749
936
  export function hermescArgsWithBase(
750
937
  baseArgs: string[],
751
938
  basePath: string | null,
@@ -780,41 +967,84 @@ export function normalizeDisassemblyLine(
780
967
  line: string,
781
968
  strings: Map<number, string>,
782
969
  ): string | null {
783
- if (/^Offset in debug table/.test(line)) return null;
784
- let m =
785
- /^(\s*New(?:Array|Object)WithBuffer)(?:Long)?(?:AndParent)?\s+(r\d+)(.*)$/.exec(
786
- line,
787
- );
788
- if (m) {
789
- const nums = m[3].match(/\d+/g) ?? [];
790
- return `${m[1]} ${m[2]} sizes=${nums.slice(0, 1).join(',')}`;
791
- }
792
- m = /^(\s*J[A-Za-z]+?)(Long)?\s+(L\d+|\d+)(.*)$/.exec(line);
793
- if (m) return `${m[1]} <tgt>${m[4]}`;
794
- m = /^(\s*DefineOwnById\w*\s+r\d+, r\d+, \d+, )(\d+)$/.exec(line);
795
- if (m) line = `${m[1]}"${strings.get(Number(m[2])) ?? `?${m[2]}`}"`;
970
+ // Cheap dispatch on the opcode before touching any regex: dumps run to
971
+ // millions of lines and only a handful of instructions need rewriting.
972
+ let indent = 0;
973
+ while (indent < line.length && isSpace(line.charCodeAt(indent))) indent++;
974
+ let opEnd = indent;
975
+ while (opEnd < line.length && isLetter(line.charCodeAt(opEnd))) opEnd++;
976
+ const opcode = line.slice(indent, opEnd);
977
+ if (opcode === 'Offset' && line.startsWith('Offset in debug table', indent)) {
978
+ return null;
979
+ }
980
+ let m: RegExpExecArray | null;
981
+ if (opcode.startsWith('New') && opcode.includes('WithBuffer')) {
982
+ m =
983
+ /^(\s*New(?:Array|Object)WithBuffer)(?:Long)?(?:AndParent)?\s+(r\d+)(.*)$/.exec(
984
+ line,
985
+ );
986
+ if (m) {
987
+ const nums = m[3].match(/\d+/g) ?? [];
988
+ return `${m[1]} ${m[2]} sizes=${nums.slice(0, 1).join(',')}`;
989
+ }
990
+ }
991
+ if (opcode.charCodeAt(0) === 0x4a /* J */) {
992
+ m = /^(\s*J[A-Za-z]+?)(Long)?\s+(L\d+|\d+)(.*)$/.exec(line);
993
+ if (m) return `${m[1]} <tgt>${m[4]}`;
994
+ }
995
+ if (opcode.startsWith('DefineOwnById')) {
996
+ m = /^(\s*DefineOwnById\w*\s+r\d+, r\d+, \d+, )(\d+)$/.exec(line);
997
+ if (m) line = `${m[1]}"${strings.get(Number(m[2])) ?? `?${m[2]}`}"`;
998
+ }
796
999
  // Operand-width variants of one instruction (GetByIdShort/GetById/GetByIdLong,
797
1000
  // LoadConstString/LoadConstStringLongIndex, ...) only differ by how wide a
798
1001
  // string/function id or offset is encoded — a foreign base hands the new
799
1002
  // code's hot strings large ids, so the delta build legitimately picks the
800
1003
  // wider form. Fold the suffix and the column padding that follows it.
801
- m = /^(\s*)([A-Za-z]+?)(?:LongIndex|Long|Short)?(\s+.*|)$/.exec(line);
802
- if (m) line = `${m[1]}${m[2]}${m[3].replace(/\s+/g, ' ')}`;
803
- // Switch jump tables sit after the instructions; their relative offset (and
804
- // the table header hermesc prints for them) moves with instruction widths.
805
- // The two switch instructions carry that offset in different operands:
806
- // StringSwitchImm rX, <id>, <jtOffset>, <defaultLabel>, <count>
807
- // UIntSwitchImm rX, <jtOffset>, <defaultLabel>, <min>, <max>
808
- // Folding only the first shape let a shifted UIntSwitchImm offset read as a
809
- // real difference and drop an otherwise good delta build.
810
- m = /^(\s*StringSwitchImm r\d+, \d+, )\d+(, L\d+, \d+)$/.exec(line);
811
- if (m) line = `${m[1]}<jt>${m[2]}`;
812
- m = /^(\s*UIntSwitchImm r\d+, )\d+(, L\d+, \d+, \d+)$/.exec(line);
813
- if (m) line = `${m[1]}<jt>${m[2]}`;
814
- if (/^\s*offset \d+$/.test(line)) line = line.replace(/\d+$/, '<jt>');
1004
+ if (
1005
+ opEnd > indent &&
1006
+ (opEnd === line.length || isSpace(line.charCodeAt(opEnd)))
1007
+ ) {
1008
+ const folded = foldWidthSuffix(opcode);
1009
+ line = `${line.slice(0, indent)}${folded}${line.slice(opEnd).replace(/\s+/g, ' ')}`;
1010
+ // Switch jump tables sit after the instructions; their relative offset (and
1011
+ // the table header hermesc prints for them) moves with instruction widths.
1012
+ // The two switch instructions carry that offset in different operands:
1013
+ // StringSwitchImm rX, <id>, <jtOffset>, <defaultLabel>, <count>
1014
+ // UIntSwitchImm rX, <jtOffset>, <defaultLabel>, <min>, <max>
1015
+ // Folding only the first shape let a shifted UIntSwitchImm offset read as a
1016
+ // real difference and drop an otherwise good delta build.
1017
+ if (folded === 'StringSwitchImm') {
1018
+ m = /^(\s*StringSwitchImm r\d+, \d+, )\d+(, L\d+, \d+)$/.exec(line);
1019
+ if (m) line = `${m[1]}<jt>${m[2]}`;
1020
+ } else if (folded === 'UIntSwitchImm') {
1021
+ m = /^(\s*UIntSwitchImm r\d+, )\d+(, L\d+, \d+, \d+)$/.exec(line);
1022
+ if (m) line = `${m[1]}<jt>${m[2]}`;
1023
+ } else if (folded === 'offset' && /^\s*offset \d+$/.test(line)) {
1024
+ line = line.replace(/\d+$/, '<jt>');
1025
+ }
1026
+ }
815
1027
  return line;
816
1028
  }
817
1029
 
1030
+ function isSpace(code: number): boolean {
1031
+ return code === 0x20 || code === 0x09 || code === 0x0d;
1032
+ }
1033
+
1034
+ function isLetter(code: number): boolean {
1035
+ return (code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a);
1036
+ }
1037
+
1038
+ /** strip one operand-width suffix (LongIndex, Long, Short) off an opcode */
1039
+ function foldWidthSuffix(opcode: string): string {
1040
+ for (const suffix of ['LongIndex', 'Long', 'Short']) {
1041
+ if (opcode.length > suffix.length && opcode.endsWith(suffix)) {
1042
+ return opcode.slice(0, -suffix.length);
1043
+ }
1044
+ }
1045
+ return opcode;
1046
+ }
1047
+
818
1048
  /** Split a readable stream into lines without readline (Bun's readline async iterator misbehaves when pulled manually). */
819
1049
  async function* streamLines(
820
1050
  stream: NodeJS.ReadableStream,
@@ -122,20 +122,31 @@ export const testUrls = async (
122
122
  });
123
123
  };
124
124
 
125
- export const getBaseUrl = (async () => {
125
+ let baseUrlPromise: Promise<string> | undefined;
126
+
127
+ async function resolveBaseUrl(): Promise<string> {
126
128
  const testEndpoint = process.env.PUSHY_REGISTRY || process.env.RNU_API;
127
129
  if (testEndpoint) {
128
130
  return testEndpoint;
129
131
  }
130
- return testUrls(defaultEndpoints.map((url) => `${url}/status`)).then(
131
- (ret) => {
132
- let baseUrl = defaultEndpoints[0];
133
- if (ret) {
134
- // remove /status
135
- baseUrl = ret.replace('/status', '');
136
- }
137
- // console.log('baseUrl', baseUrl);
138
- return baseUrl;
139
- },
140
- );
141
- })();
132
+ const ret = await testUrls(defaultEndpoints.map((url) => `${url}/status`));
133
+ let baseUrl = defaultEndpoints[0];
134
+ if (ret) {
135
+ // remove /status
136
+ baseUrl = ret.replace('/status', '');
137
+ }
138
+ // console.log('baseUrl', baseUrl);
139
+ return baseUrl;
140
+ }
141
+
142
+ /**
143
+ * The API base url: the env override, or the first default endpoint that
144
+ * answers a HEAD ping. Resolved lazily on the first API call (offline commands
145
+ * such as `hdiff`/`help` never ping) and memoized for the process lifetime.
146
+ */
147
+ export const getBaseUrl = (): Promise<string> => {
148
+ if (!baseUrlPromise) {
149
+ baseUrlPromise = resolveBaseUrl();
150
+ }
151
+ return baseUrlPromise;
152
+ };