react-native-update-cli 2.28.1 → 2.28.2

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.
@@ -10,6 +10,12 @@ export declare class PermanentBaseError extends Error {
10
10
  export declare class BundleHashMismatchError extends PermanentBaseError {
11
11
  constructor(actual: string, expected: string);
12
12
  }
13
+ /** The base bundle is not Hermes bytecode of the version being compiled. */
14
+ export declare class HbcVersionMismatchError extends PermanentBaseError {
15
+ readonly version: number | null;
16
+ readonly expected: number;
17
+ constructor(version: number | null, expected: number);
18
+ }
13
19
  export interface HermesBaseSelection {
14
20
  /** path of the bundle (HBC) handed to hermesc as -base-bytecode */
15
21
  path: string;
@@ -152,8 +158,14 @@ interface FetchedBaseBundle {
152
158
  * recorded location is stale, so the directory transport (2) still runs; a
153
159
  * mismatch of the entry itself (2, 3) is final — the same bytes would come
154
160
  * back however they are fetched — and raises BundleHashMismatchError.
161
+ *
162
+ * With `expectHbcVersion` (the server does not know the base's version), the
163
+ * bundle's first bytes are checked before its body is fetched; a base of
164
+ * another HBC version, or plain JS, raises HbcVersionMismatchError without
165
+ * downloading the rest. A head read at a recorded location (1) may be stale,
166
+ * so only the directory transport (2) decides.
155
167
  */
156
- export declare function fetchBaseBundle(record: HermesBaseServerRecord, artifactType: BaseArtifactType, archive: string, log?: (message: string) => void): Promise<FetchedBaseBundle>;
168
+ export declare function fetchBaseBundle(record: HermesBaseServerRecord, artifactType: BaseArtifactType, archive: string, log?: (message: string) => void, expectHbcVersion?: number): Promise<FetchedBaseBundle>;
157
169
  export interface ResolveHermesBaseParams {
158
170
  option: HermesBaseOption;
159
171
  hermesCommand: string;
@@ -46,7 +46,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
46
46
  return (mod && mod.__esModule) ? mod : { "default": mod };
47
47
  };
48
48
  Object.defineProperty(exports, "__esModule", { value: true });
49
- exports.LITERAL_SEPARATOR = exports.DEFAULT_CACHE_MAX_FILES = exports.DEFAULT_CACHE_MAX_BYTES = exports.BUNDLE_ENTRY_NAMES = exports.MIN_HERMES_COMPILER_COMMITLY_DATE = exports.MIN_HERMES_COMPILER_BUILD = exports.HERMES_BASE_DETAIL_MAX_CHARS = exports.BundleHashMismatchError = exports.PermanentBaseError = void 0;
49
+ exports.LITERAL_SEPARATOR = exports.DEFAULT_CACHE_MAX_FILES = exports.DEFAULT_CACHE_MAX_BYTES = exports.BUNDLE_ENTRY_NAMES = exports.MIN_HERMES_COMPILER_COMMITLY_DATE = exports.MIN_HERMES_COMPILER_BUILD = exports.HERMES_BASE_DETAIL_MAX_CHARS = exports.HbcVersionMismatchError = exports.BundleHashMismatchError = exports.PermanentBaseError = void 0;
50
50
  exports.classifyHermesCommand = classifyHermesCommand;
51
51
  exports.sha256Hex = sha256Hex;
52
52
  exports.sha256File = sha256File;
@@ -105,6 +105,19 @@ class BundleHashMismatchError extends PermanentBaseError {
105
105
  }
106
106
  }
107
107
  exports.BundleHashMismatchError = BundleHashMismatchError;
108
+ /** The base bundle is not Hermes bytecode of the version being compiled. */
109
+ class HbcVersionMismatchError extends PermanentBaseError {
110
+ version;
111
+ expected;
112
+ constructor(version, expected) {
113
+ super(`downloaded base is HBC ${version ?? 'n/a'}, need ${expected}`);
114
+ this.version = version;
115
+ this.expected = expected;
116
+ }
117
+ }
118
+ exports.HbcVersionMismatchError = HbcVersionMismatchError;
119
+ /** bytes `getHbcVersion` needs to read the version */
120
+ const HBC_HEAD_BYTES = 128;
108
121
  /** time allowed for a response to start (headers) */
109
122
  const FETCH_HEADERS_TIMEOUT_MS = 30_000;
110
123
  /** a download that receives nothing for this long is abandoned */
@@ -517,6 +530,9 @@ async function downloadToFile(url, destination) {
517
530
  }
518
531
  await saveResponse(response, destination, controller);
519
532
  }
533
+ /** the head at a recorded bundle location is not the expected bytecode */
534
+ class StaleHeadError extends Error {
535
+ }
520
536
  function hasBundleLocation(record) {
521
537
  return (record.bundleOffset != null &&
522
538
  record.bundleCompressedSize != null &&
@@ -564,8 +580,14 @@ async function saveResponse(response, destination, controller = new AbortControl
564
580
  * recorded location is stale, so the directory transport (2) still runs; a
565
581
  * mismatch of the entry itself (2, 3) is final — the same bytes would come
566
582
  * back however they are fetched — and raises BundleHashMismatchError.
583
+ *
584
+ * With `expectHbcVersion` (the server does not know the base's version), the
585
+ * bundle's first bytes are checked before its body is fetched; a base of
586
+ * another HBC version, or plain JS, raises HbcVersionMismatchError without
587
+ * downloading the rest. A head read at a recorded location (1) may be stale,
588
+ * so only the directory transport (2) decides.
567
589
  */
568
- async function fetchBaseBundle(record, artifactType, archive, log = () => { }) {
590
+ async function fetchBaseBundle(record, artifactType, archive, log = () => { }, expectHbcVersion) {
569
591
  const matches = bundleEntryMatcher(artifactType);
570
592
  const verified = (bundle) => {
571
593
  if (!bundle)
@@ -587,12 +609,17 @@ async function fetchBaseBundle(record, artifactType, archive, log = () => { }) {
587
609
  // harmony .app nests the bundle in a second zip, so a location inside the
588
610
  // outer archive is never reported for it
589
611
  if (artifactType !== 'app' && hasBundleLocation(record)) {
612
+ const location = {
613
+ dataOffset: record.bundleOffset,
614
+ compressedSize: record.bundleCompressedSize,
615
+ compressionMethod: record.bundleCompression,
616
+ };
590
617
  try {
591
- const { data, fetchedBytes, totalBytes } = await (0, zip_range_1.fetchZipEntryData)(record.url, {
592
- dataOffset: record.bundleOffset,
593
- compressedSize: record.bundleCompressedSize,
594
- compressionMethod: record.bundleCompression,
595
- });
618
+ const headMatches = expectHbcVersion === undefined ||
619
+ (0, hbcTransform_1.getHbcVersion)(await (0, zip_range_1.fetchZipEntryHead)(record.url, location, HBC_HEAD_BYTES)) === expectHbcVersion;
620
+ if (!headMatches)
621
+ throw new StaleHeadError();
622
+ const { data, fetchedBytes, totalBytes } = await (0, zip_range_1.fetchZipEntryData)(record.url, location);
596
623
  return {
597
624
  ...verified(data),
598
625
  transport: 'range-entry',
@@ -605,7 +632,10 @@ async function fetchBaseBundle(record, artifactType, archive, log = () => { }) {
605
632
  skip('server ignores Range');
606
633
  return fromFullResponse(error.response);
607
634
  }
608
- skip(`entry range: ${error?.message ?? error}`);
635
+ // not a transport failure: the directory read below settles it
636
+ if (!(error instanceof StaleHeadError)) {
637
+ skip(`entry range: ${error?.message ?? error}`);
638
+ }
609
639
  }
610
640
  }
611
641
  if (artifactType !== 'app') {
@@ -615,7 +645,17 @@ async function fetchBaseBundle(record, artifactType, archive, log = () => { }) {
615
645
  skip('server ignores Range');
616
646
  return fromFullResponse(remote.response);
617
647
  }
618
- const bundle = await (0, zip_range_1.readRemoteZipEntry)(remote.zipFile, matches, remote.reader);
648
+ const bundle = await (0, zip_range_1.readRemoteZipEntry)(remote.zipFile, matches, remote.reader, expectHbcVersion === undefined
649
+ ? undefined
650
+ : {
651
+ bytes: HBC_HEAD_BYTES,
652
+ check: (head) => {
653
+ const version = (0, hbcTransform_1.getHbcVersion)(head);
654
+ if (version !== expectHbcVersion) {
655
+ throw new HbcVersionMismatchError(version, expectHbcVersion);
656
+ }
657
+ },
658
+ });
619
659
  return {
620
660
  ...verified(bundle),
621
661
  transport: 'range-zip',
@@ -752,7 +792,9 @@ async function resolveHermesBase(params) {
752
792
  const archive = path_1.default.join(dir, `base-${process.pid}-${Date.now()}-${attempt}.${artifactType}`);
753
793
  try {
754
794
  log((0, i18n_1.t)('hermesBaseDownloading', { url: record.url }));
755
- const fetched = await fetchBaseBundle(record, artifactType, archive, log);
795
+ const fetched = await fetchBaseBundle(record, artifactType, archive, log,
796
+ // a server that knows the version already matched it above
797
+ record.bytecodeVersion == null ? bytecodeVersion : undefined);
756
798
  const { bundle, bundleHash: actualHash } = fetched;
757
799
  if (fetched.transport !== 'full') {
758
800
  log((0, i18n_1.t)('hermesBaseRangeFetched', {
@@ -762,10 +804,7 @@ async function resolveHermesBase(params) {
762
804
  }
763
805
  const version = (0, hbcTransform_1.getHbcVersion)(bundle);
764
806
  if (version !== bytecodeVersion) {
765
- log((0, i18n_1.t)('hermesBaseNone', {
766
- reason: `downloaded base is HBC ${version ?? 'n/a'}, need ${bytecodeVersion}`,
767
- }));
768
- return null;
807
+ throw new HbcVersionMismatchError(version, bytecodeVersion);
769
808
  }
770
809
  const cached = await cachePut(bundle, params.cacheMaxMb, actualHash);
771
810
  log((0, i18n_1.t)('hermesBaseUsing', {
@@ -784,6 +823,10 @@ async function resolveHermesBase(params) {
784
823
  };
785
824
  }
786
825
  catch (error) {
826
+ if (error instanceof HbcVersionMismatchError) {
827
+ log((0, i18n_1.t)('hermesBaseNone', { reason: error.message }));
828
+ return null;
829
+ }
787
830
  if (attempt === 2 || error instanceof PermanentBaseError) {
788
831
  log((0, i18n_1.t)('hermesBaseNone', {
789
832
  reason: `download/verify failed: ${error?.message ?? error}`,
@@ -63,6 +63,16 @@ export declare function fetchZipEntryData(url: string, location: Pick<ZipEntryLo
63
63
  fetchedBytes: number;
64
64
  totalBytes: number;
65
65
  }>;
66
+ /**
67
+ * Up to `bytes` leading bytes of an entry, decoded from a prefix of its
68
+ * compressed data (a truncated deflate stream is inflated as far as it goes).
69
+ */
70
+ export declare function decodeEntryHead(raw: Buffer, compressionMethod: number, bytes: number): Buffer;
71
+ /**
72
+ * The first `bytes` of an entry whose compressed bytes are already located,
73
+ * from one small Range request (see `fetchZipEntryData`).
74
+ */
75
+ export declare function fetchZipEntryHead(url: string, location: Pick<ZipEntryLocation, 'dataOffset' | 'compressedSize' | 'compressionMethod'>, bytes: number, options?: RangeOptions): Promise<Buffer>;
66
76
  export interface HttpRangeReaderOptions extends RangeOptions {
67
77
  /** validator of the archive (see `rangeValidator`), sent as If-Range */
68
78
  ifRange?: string;
@@ -135,9 +145,17 @@ export type RemoteZip = {
135
145
  * typical archives) and letting yauzl read the rest on demand.
136
146
  */
137
147
  export declare function openRemoteZip(url: string, options?: RangeOptions): Promise<RemoteZip>;
148
+ /** Look at the head of the matched entry before its body is fetched. */
149
+ export interface EntryHeadCheck {
150
+ bytes: number;
151
+ /** throw to abandon the entry; the error is passed on as is */
152
+ check: (head: Buffer) => void;
153
+ }
138
154
  /**
139
155
  * Read the first matching entry of an opened remote zip, then close it. With
140
- * `reader` given, the entry's header and data are fetched in one request.
156
+ * `reader` given, the entry's header and data are fetched in one request —
157
+ * or, with `head` too, its first bytes are checked first (header and head
158
+ * share one small request, the rest of the body follows only if they pass).
141
159
  */
142
- export declare function readRemoteZipEntry(zipFile: ZipFile, matches: (name: string) => boolean, reader?: HttpRangeReader): Promise<Buffer | null>;
160
+ export declare function readRemoteZipEntry(zipFile: ZipFile, matches: (name: string) => boolean, reader?: HttpRangeReader, head?: EntryHeadCheck): Promise<Buffer | null>;
143
161
  export {};
@@ -10,6 +10,8 @@ exports.bundleLocationFields = bundleLocationFields;
10
10
  exports.parseContentRange = parseContentRange;
11
11
  exports.rangeValidator = rangeValidator;
12
12
  exports.fetchZipEntryData = fetchZipEntryData;
13
+ exports.decodeEntryHead = decodeEntryHead;
14
+ exports.fetchZipEntryHead = fetchZipEntryHead;
13
15
  exports.parseEndOfCentralDirectory = parseEndOfCentralDirectory;
14
16
  exports.openRemoteZip = openRemoteZip;
15
17
  exports.readRemoteZipEntry = readRemoteZipEntry;
@@ -40,6 +42,11 @@ const TAIL_BYTES = 22 + 0xffff + 20;
40
42
  const CHUNK_BYTES = 64 * 1024;
41
43
  /** extra bytes past a hinted entry, covering a longer local extra field */
42
44
  const HINT_SLACK_BYTES = 4 * 1024;
45
+ /**
46
+ * compressed bytes fetched to decode the head of a deflated entry: the
47
+ * dynamic Huffman header plus the first literals fit comfortably
48
+ */
49
+ const HEAD_PROBE_BYTES = 4 * 1024;
43
50
  /** Data location of the first entry matching `matches` in a local zip. */
44
51
  async function locateZipEntry(zipPath, matches) {
45
52
  const found = await openFirstEntry(zipPath, matches);
@@ -154,7 +161,8 @@ function timeoutFor(bytes, options) {
154
161
  if (bytes <= CHUNK_BYTES) {
155
162
  return options.headerTimeoutMs ?? DEFAULT_HEADER_TIMEOUT_MS;
156
163
  }
157
- return ((options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS) +
164
+ // AbortSignal.timeout() rejects a fractional delay
165
+ return Math.ceil((options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS) +
158
166
  ((options.dataTimeoutPerMbMs ?? DEFAULT_DATA_TIMEOUT_PER_MB_MS) * bytes) /
159
167
  (1024 * 1024));
160
168
  }
@@ -270,6 +278,42 @@ async function fetchZipEntryData(url, location, options = {}) {
270
278
  totalBytes: total,
271
279
  };
272
280
  }
281
+ /**
282
+ * Up to `bytes` leading bytes of an entry, decoded from a prefix of its
283
+ * compressed data (a truncated deflate stream is inflated as far as it goes).
284
+ */
285
+ function decodeEntryHead(raw, compressionMethod, bytes) {
286
+ if (compressionMethod === exports.ZIP_STORED)
287
+ return raw.subarray(0, bytes);
288
+ if (compressionMethod !== exports.ZIP_DEFLATED) {
289
+ throw new Error(`unsupported compression method ${compressionMethod}`);
290
+ }
291
+ return (0, zlib_1.inflateRawSync)(raw, {
292
+ finishFlush: zlib_1.constants.Z_SYNC_FLUSH,
293
+ }).subarray(0, bytes);
294
+ }
295
+ /** compressed bytes needed to decode the first `bytes` of an entry */
296
+ function headProbeSize(compressedSize, compressionMethod, bytes) {
297
+ return Math.min(compressedSize, compressionMethod === exports.ZIP_STORED ? bytes : HEAD_PROBE_BYTES);
298
+ }
299
+ /**
300
+ * The first `bytes` of an entry whose compressed bytes are already located,
301
+ * from one small Range request (see `fetchZipEntryData`).
302
+ */
303
+ async function fetchZipEntryHead(url, location, bytes, options = {}) {
304
+ const { dataOffset, compressedSize, compressionMethod } = location;
305
+ if (!Number.isInteger(dataOffset) ||
306
+ !Number.isInteger(compressedSize) ||
307
+ dataOffset < 0 ||
308
+ compressedSize <= 0) {
309
+ throw new Error('invalid bundle location');
310
+ }
311
+ const size = headProbeSize(compressedSize, compressionMethod, bytes);
312
+ const { data } = await fetchRangeBuffer(url, dataOffset, dataOffset + size, {
313
+ timeoutMs: timeoutFor(size, options),
314
+ });
315
+ return decodeEntryHead(data, compressionMethod, bytes);
316
+ }
273
317
  /**
274
318
  * yauzl reader over HTTP Range. Header reads (EOCD, central directory, local
275
319
  * file headers) are widened to CHUNK_BYTES and cached. Chunks are kept as
@@ -547,11 +591,34 @@ async function openRemoteZip(url, options = {}) {
547
591
  });
548
592
  return { kind: 'zip', zipFile, reader };
549
593
  }
594
+ /** `reader.read` as a promise */
595
+ function readAt(reader, position, length) {
596
+ const buffer = Buffer.alloc(length);
597
+ return new Promise((resolve, reject) => reader.read(buffer, 0, length, position, (error) => error ? reject(error) : resolve(buffer)));
598
+ }
599
+ /** The first `bytes` of `entry`, read through `reader` without its body. */
600
+ async function remoteEntryHead(reader, entry, bytes) {
601
+ const start = entry.relativeOffsetOfLocalHeader;
602
+ const header = await readAt(reader, start, LOCAL_HEADER_SIZE);
603
+ if (header.readUInt32LE(0) !== LOCAL_HEADER_SIGNATURE) {
604
+ throw new Error('invalid local file header signature');
605
+ }
606
+ const dataOffset = start +
607
+ LOCAL_HEADER_SIZE +
608
+ header.readUInt16LE(26) +
609
+ header.readUInt16LE(28);
610
+ const size = headProbeSize(entry.compressedSize, entry.compressionMethod, bytes);
611
+ if (size <= 0)
612
+ return Buffer.alloc(0);
613
+ return decodeEntryHead(await readAt(reader, dataOffset, size), entry.compressionMethod, bytes);
614
+ }
550
615
  /**
551
616
  * Read the first matching entry of an opened remote zip, then close it. With
552
- * `reader` given, the entry's header and data are fetched in one request.
617
+ * `reader` given, the entry's header and data are fetched in one request —
618
+ * or, with `head` too, its first bytes are checked first (header and head
619
+ * share one small request, the rest of the body follows only if they pass).
553
620
  */
554
- function readRemoteZipEntry(zipFile, matches, reader) {
621
+ function readRemoteZipEntry(zipFile, matches, reader, head) {
555
622
  return new Promise((resolve, reject) => {
556
623
  let settled = false;
557
624
  const finish = (error, result = null) => {
@@ -568,8 +635,13 @@ function readRemoteZipEntry(zipFile, matches, reader) {
568
635
  zipFile.readEntry();
569
636
  return;
570
637
  }
571
- reader?.hintEntry(entry);
572
- (0, zip_entries_1.readEntry)(entry, zipFile).then((data) => finish(null, data), (error) => finish(error));
638
+ const probe = reader && head
639
+ ? remoteEntryHead(reader, entry, head.bytes).then(head.check)
640
+ : // without a probe the header read may take the body along
641
+ Promise.resolve(reader?.hintEntry(entry));
642
+ probe
643
+ .then(() => (0, zip_entries_1.readEntry)(entry, zipFile))
644
+ .then((data) => finish(null, data), (error) => finish(error));
573
645
  });
574
646
  zipFile.readEntry();
575
647
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-update-cli",
3
- "version": "2.28.1",
3
+ "version": "2.28.2",
4
4
  "description": "command line tool for react-native-update (remote updates for react native)",
5
5
  "main": "lib/exports.js",
6
6
  "types": "lib/exports.d.ts",