react-native-update-cli 2.22.6 → 2.22.7

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.
@@ -23,10 +23,15 @@ export const ZIP_DEFLATED = 8;
23
23
 
24
24
  const LOCAL_HEADER_SIGNATURE = 0x04034b50;
25
25
  const LOCAL_HEADER_SIZE = 30;
26
- /** covers the EOCD (≤ 22 + 65535 bytes) and, for small archives, everything */
27
- const TAIL_BYTES = 64 * 1024;
26
+ /**
27
+ * Exactly what yauzl reads to find the EOCD (22 + 65535 comment + 20 zip64
28
+ * locator), so its first read is a cache hit; small archives fit entirely.
29
+ */
30
+ const TAIL_BYTES = 22 + 0xffff + 20;
28
31
  /** minimum span fetched for header reads, so header + directory share a request */
29
32
  const CHUNK_BYTES = 64 * 1024;
33
+ /** extra bytes past a hinted entry, covering a longer local extra field */
34
+ const HINT_SLACK_BYTES = 4 * 1024;
30
35
 
31
36
  export interface ZipEntryLocation {
32
37
  fileName: string;
@@ -43,8 +48,36 @@ export async function locateZipEntry(
43
48
  zipPath: string,
44
49
  matches: (name: string) => boolean,
45
50
  ): Promise<ZipEntryLocation | null> {
46
- const entry = await findEntry(zipPath, matches);
47
- if (!entry) return null;
51
+ const found = await openFirstEntry(zipPath, matches);
52
+ if (!found) return null;
53
+ found.zipFile.close();
54
+ return locationOfEntry(zipPath, found.entry);
55
+ }
56
+
57
+ /**
58
+ * Content and data location of the first matching entry in one pass over the
59
+ * archive (publish needs both: the bundle to hash and cache, its location to
60
+ * report to the server).
61
+ */
62
+ export async function readZipEntryWithLocation(
63
+ zipPath: string,
64
+ matches: (name: string) => boolean,
65
+ ): Promise<{ data: Buffer; location: ZipEntryLocation } | null> {
66
+ const found = await openFirstEntry(zipPath, matches);
67
+ if (!found) return null;
68
+ let data: Buffer;
69
+ try {
70
+ data = await readEntry(found.entry, found.zipFile);
71
+ } finally {
72
+ found.zipFile.close();
73
+ }
74
+ return { data, location: await locationOfEntry(zipPath, found.entry) };
75
+ }
76
+
77
+ async function locationOfEntry(
78
+ zipPath: string,
79
+ entry: Entry,
80
+ ): Promise<ZipEntryLocation> {
48
81
  const header = Buffer.alloc(LOCAL_HEADER_SIZE);
49
82
  const fd = await fs.open(zipPath, 'r');
50
83
  try {
@@ -79,30 +112,69 @@ export async function locateZipEntry(
79
112
  };
80
113
  }
81
114
 
82
- function findEntry(
115
+ /** Open a local zip and stop at the first matching entry (caller closes). */
116
+ function openFirstEntry(
83
117
  zipPath: string,
84
118
  matches: (name: string) => boolean,
85
- ): Promise<Entry | null> {
119
+ ): Promise<{ zipFile: ZipFile; entry: Entry } | null> {
86
120
  return new Promise((resolve, reject) => {
87
- openZipFile(zipPath, { lazyEntries: true }, (err, zipFile) => {
88
- if (err) return reject(err);
89
- let found: Entry | null = null;
90
- zipFile.on('error', reject);
91
- zipFile.on('end', () => resolve(found));
92
- zipFile.on('entry', (entry: Entry) => {
93
- if (!found && matches(entry.fileName)) {
94
- found = entry;
95
- zipFile.close();
96
- resolve(found);
97
- return;
98
- }
121
+ openZipFile(
122
+ zipPath,
123
+ { lazyEntries: true, autoClose: false },
124
+ (err, zipFile) => {
125
+ if (err) return reject(err);
126
+ let settled = false;
127
+ zipFile.on('error', (error) => {
128
+ if (!settled) {
129
+ settled = true;
130
+ reject(error);
131
+ }
132
+ });
133
+ zipFile.on('end', () => {
134
+ if (!settled) {
135
+ settled = true;
136
+ zipFile.close();
137
+ resolve(null);
138
+ }
139
+ });
140
+ zipFile.on('entry', (entry: Entry) => {
141
+ if (settled) return;
142
+ if (matches(entry.fileName)) {
143
+ settled = true;
144
+ resolve({ zipFile, entry });
145
+ return;
146
+ }
147
+ zipFile.readEntry();
148
+ });
99
149
  zipFile.readEntry();
100
- });
101
- zipFile.readEntry();
102
- });
150
+ },
151
+ );
103
152
  });
104
153
  }
105
154
 
155
+ /**
156
+ * The `bundleOffset` / `bundleCompressedSize` / `bundleCompression` fields for
157
+ * version/create and package/create, or nothing when the entry cannot be
158
+ * fetched by a single Range request (unknown, empty or exotic compression).
159
+ */
160
+ export function bundleLocationFields(
161
+ location: ZipEntryLocation | null | undefined,
162
+ ): Record<string, number> {
163
+ if (
164
+ !location ||
165
+ location.compressedSize <= 0 ||
166
+ (location.compressionMethod !== ZIP_STORED &&
167
+ location.compressionMethod !== ZIP_DEFLATED)
168
+ ) {
169
+ return {};
170
+ }
171
+ return {
172
+ bundleOffset: location.dataOffset,
173
+ bundleCompressedSize: location.compressedSize,
174
+ bundleCompression: location.compressionMethod,
175
+ };
176
+ }
177
+
106
178
  // ---------------------------------------------------------------------------
107
179
  // HTTP Range
108
180
  // ---------------------------------------------------------------------------
@@ -208,11 +280,15 @@ export async function fetchZipEntryData(
208
280
 
209
281
  /**
210
282
  * yauzl reader over HTTP Range. Header reads (EOCD, central directory, local
211
- * file headers) are widened to CHUNK_BYTES and cached so a small archive costs
212
- * one request; entry data streams straight from its own request.
283
+ * file headers) are widened to CHUNK_BYTES and cached — adjacent or
284
+ * overlapping chunks are merged so a read never re-fetches bytes it already
285
+ * has — and entry data reuses whatever prefix the cache holds (typically the
286
+ * bytes following the local file header) before requesting the rest.
213
287
  */
214
288
  export class HttpRangeReader extends RandomAccessReader {
215
- private readonly chunks: { start: number; data: Buffer }[] = [];
289
+ private chunks: { start: number; data: Buffer }[] = [];
290
+ /** span a header read inside it should widen to (see `hintEntry`) */
291
+ private hint: { start: number; end: number } | null = null;
216
292
  requests = 0;
217
293
  fetchedBytes = 0;
218
294
 
@@ -222,26 +298,97 @@ export class HttpRangeReader extends RandomAccessReader {
222
298
  tail?: { start: number; data: Buffer },
223
299
  ) {
224
300
  super();
225
- if (tail) this.chunks.push(tail);
301
+ if (tail) this.addChunk(tail.start, tail.data);
302
+ }
303
+
304
+ /**
305
+ * The next entry to be read: yauzl first reads its local file header, and
306
+ * widening that read to the entry's data makes the data stream a cache hit
307
+ * — one request for header + bundle instead of two. The central directory
308
+ * may understate the local header's extra field, hence the slack.
309
+ */
310
+ hintEntry(entry: Entry): void {
311
+ const start = entry.relativeOffsetOfLocalHeader;
312
+ const end =
313
+ start +
314
+ LOCAL_HEADER_SIZE +
315
+ entry.fileNameLength +
316
+ entry.extraFieldLength +
317
+ entry.compressedSize +
318
+ HINT_SLACK_BYTES;
319
+ this.hint = { start, end: Math.min(end, this.totalSize) };
320
+ }
321
+
322
+ /** Cache `data` at `start`, merging with any chunk it touches. */
323
+ addChunk(start: number, data: Buffer): void {
324
+ if (data.length === 0) return;
325
+ let lo = start;
326
+ let hi = start + data.length;
327
+ const pieces: { start: number; data: Buffer }[] = [{ start, data }];
328
+ const rest: { start: number; data: Buffer }[] = [];
329
+ for (const chunk of this.chunks) {
330
+ const chunkEnd = chunk.start + chunk.data.length;
331
+ if (chunk.start <= hi && chunkEnd >= lo) {
332
+ pieces.push(chunk);
333
+ lo = Math.min(lo, chunk.start);
334
+ hi = Math.max(hi, chunkEnd);
335
+ } else {
336
+ rest.push(chunk);
337
+ }
338
+ }
339
+ if (pieces.length === 1) {
340
+ rest.push(pieces[0]);
341
+ } else {
342
+ const merged = Buffer.alloc(hi - lo);
343
+ // the new data is written last so it wins over stale overlaps
344
+ for (const piece of pieces.reverse()) {
345
+ piece.data.copy(merged, piece.start - lo);
346
+ }
347
+ rest.push({ start: lo, data: merged });
348
+ }
349
+ rest.sort((a, b) => a.start - b.start);
350
+ this.chunks = rest;
351
+ }
352
+
353
+ /** cached bytes starting exactly at `start`, up to `end` (may be shorter) */
354
+ private cachedPrefix(start: number, end: number): Buffer | null {
355
+ for (const chunk of this.chunks) {
356
+ const chunkEnd = chunk.start + chunk.data.length;
357
+ if (start >= chunk.start && start < chunkEnd) {
358
+ return chunk.data.subarray(
359
+ start - chunk.start,
360
+ Math.min(end, chunkEnd) - chunk.start,
361
+ );
362
+ }
363
+ }
364
+ return null;
226
365
  }
227
366
 
228
367
  private cached(start: number, end: number): Buffer | null {
368
+ const prefix = this.cachedPrefix(start, end);
369
+ return prefix && prefix.length === end - start ? prefix : null;
370
+ }
371
+
372
+ /** start of the cached chunk holding byte `end - 1`, when there is one */
373
+ private cachedSuffixStart(end: number): number | null {
229
374
  for (const chunk of this.chunks) {
230
- if (start >= chunk.start && end <= chunk.start + chunk.data.length) {
231
- return chunk.data.subarray(start - chunk.start, end - chunk.start);
375
+ if (end - 1 >= chunk.start && end - 1 < chunk.start + chunk.data.length) {
376
+ return chunk.start;
232
377
  }
233
378
  }
234
379
  return null;
235
380
  }
236
381
 
237
382
  _readStreamForRange(start: number, end: number): Readable {
238
- const hit = this.cached(start, end);
239
- if (hit) return Readable.from([hit]);
383
+ const prefix = this.cachedPrefix(start, end);
384
+ if (prefix && prefix.length === end - start) return Readable.from([prefix]);
240
385
  const out = new PassThrough();
386
+ if (prefix) out.write(prefix);
387
+ const from = start + (prefix?.length ?? 0);
241
388
  this.requests++;
242
- fetchRange(this.url, start, end)
389
+ fetchRange(this.url, from, end)
243
390
  .then((response) => {
244
- this.fetchedBytes += end - start;
391
+ this.fetchedBytes += end - from;
245
392
  const body = Readable.fromWeb(response.body as any);
246
393
  body.on('error', (error) => out.destroy(error));
247
394
  body.pipe(out);
@@ -263,16 +410,37 @@ export class HttpRangeReader extends RandomAccessReader {
263
410
  setImmediate(() => callback(null, length));
264
411
  return;
265
412
  }
266
- const end = Math.min(
267
- this.totalSize,
268
- Math.max(position + length, position + CHUNK_BYTES),
269
- );
413
+ // fetch only what the cache lacks: skip a cached prefix, stop at a cached
414
+ // suffix (yauzl's EOCD read may just exceed the tail), and otherwise widen
415
+ // so the next header read is free
416
+ const requestEnd = position + length;
417
+ const from =
418
+ position + (this.cachedPrefix(position, requestEnd)?.length ?? 0);
419
+ const suffixStart = this.cachedSuffixStart(requestEnd);
420
+ let end: number;
421
+ if (suffixStart !== null && suffixStart > from) {
422
+ end = suffixStart;
423
+ } else {
424
+ end = Math.min(this.totalSize, Math.max(requestEnd, from + CHUNK_BYTES));
425
+ if (
426
+ this.hint &&
427
+ position >= this.hint.start &&
428
+ position < this.hint.end
429
+ ) {
430
+ end = Math.max(end, this.hint.end);
431
+ }
432
+ }
270
433
  this.requests++;
271
- fetchRangeBuffer(this.url, position, end).then(
434
+ fetchRangeBuffer(this.url, from, end).then(
272
435
  ({ data }) => {
273
436
  this.fetchedBytes += data.length;
274
- this.chunks.push({ start: position, data });
275
- data.copy(buffer, offset, 0, length);
437
+ this.addChunk(from, data);
438
+ const full = this.cached(position, position + length);
439
+ if (!full) {
440
+ callback(new Error('range read did not cover the requested bytes'));
441
+ return;
442
+ }
443
+ full.copy(buffer, offset);
276
444
  callback(null, length);
277
445
  },
278
446
  (error) => callback(error),
@@ -280,6 +448,28 @@ export class HttpRangeReader extends RandomAccessReader {
280
448
  }
281
449
  }
282
450
 
451
+ /** End-of-central-directory record: where the central directory lives. */
452
+ const EOCD_SIGNATURE = 0x06054b50;
453
+ const EOCD_SIZE = 22;
454
+ /** central directories larger than this are left to yauzl's paged reads */
455
+ const MAX_PREFETCH_BYTES = 8 * 1024 * 1024;
456
+
457
+ export function parseEndOfCentralDirectory(
458
+ tail: Buffer,
459
+ ): { cdOffset: number; cdSize: number } | null {
460
+ for (let i = tail.length - EOCD_SIZE; i >= 0; i--) {
461
+ if (tail.readUInt32LE(i) !== EOCD_SIGNATURE) continue;
462
+ const commentLength = tail.readUInt16LE(i + 20);
463
+ if (i + EOCD_SIZE + commentLength !== tail.length) continue;
464
+ const cdSize = tail.readUInt32LE(i + 12);
465
+ const cdOffset = tail.readUInt32LE(i + 16);
466
+ // zip64 markers: let yauzl resolve the real values itself
467
+ if (cdSize === 0xffffffff || cdOffset === 0xffffffff) return null;
468
+ return { cdOffset, cdSize };
469
+ }
470
+ return null;
471
+ }
472
+
283
473
  export type RemoteZip =
284
474
  | { kind: 'zip'; zipFile: ZipFile; reader: HttpRangeReader }
285
475
  /** the server ignored Range: the whole archive is streaming in `response` */
@@ -317,6 +507,24 @@ export async function openRemoteZip(url: string): Promise<RemoteZip> {
317
507
  });
318
508
  reader.requests = 1;
319
509
  reader.fetchedBytes = data.length;
510
+ // Large archives (apk / ipa with thousands of files) keep their central
511
+ // directory well before the tail; yauzl would otherwise page it in with one
512
+ // sequential request per CHUNK_BYTES. Fetch the missing part at once.
513
+ const eocd = parseEndOfCentralDirectory(data);
514
+ if (
515
+ eocd &&
516
+ eocd.cdOffset < range.start &&
517
+ range.start - eocd.cdOffset <= MAX_PREFETCH_BYTES
518
+ ) {
519
+ const { data: directory } = await fetchRangeBuffer(
520
+ url,
521
+ eocd.cdOffset,
522
+ range.start,
523
+ );
524
+ reader.requests++;
525
+ reader.fetchedBytes += directory.length;
526
+ reader.addChunk(eocd.cdOffset, directory);
527
+ }
320
528
  const zipFile = await new Promise<ZipFile>((resolve, reject) => {
321
529
  fromRandomAccessReader(
322
530
  reader,
@@ -328,10 +536,14 @@ export async function openRemoteZip(url: string): Promise<RemoteZip> {
328
536
  return { kind: 'zip', zipFile, reader };
329
537
  }
330
538
 
331
- /** Read the first matching entry of an opened remote zip, then close it. */
539
+ /**
540
+ * Read the first matching entry of an opened remote zip, then close it. With
541
+ * `reader` given, the entry's header and data are fetched in one request.
542
+ */
332
543
  export function readRemoteZipEntry(
333
544
  zipFile: ZipFile,
334
545
  matches: (name: string) => boolean,
546
+ reader?: HttpRangeReader,
335
547
  ): Promise<Buffer | null> {
336
548
  return new Promise((resolve, reject) => {
337
549
  let settled = false;
@@ -348,6 +560,7 @@ export function readRemoteZipEntry(
348
560
  zipFile.readEntry();
349
561
  return;
350
562
  }
563
+ reader?.hintEntry(entry);
351
564
  readEntry(entry, zipFile).then(
352
565
  (data) => finish(null, data),
353
566
  (error) => finish(error),
package/src/versions.ts CHANGED
@@ -18,7 +18,10 @@ import {
18
18
  } from './utils/hermes-base';
19
19
  import { t } from './utils/i18n';
20
20
  import { getBooleanOption, getStringListOption } from './utils/options';
21
- import { locateZipEntry, ZIP_DEFLATED, ZIP_STORED } from './utils/zip-range';
21
+ import {
22
+ bundleLocationFields,
23
+ readZipEntryWithLocation,
24
+ } from './utils/zip-range';
22
25
 
23
26
  interface VersionCommandOptions {
24
27
  [key: string]: unknown;
@@ -476,27 +479,22 @@ async function describePpkBundle(
476
479
  // server version — strict, tolerant or too old to know the field — accepts.
477
480
  const meta: Record<string, unknown> = {};
478
481
  try {
479
- const bundle = await extractBundleFromArchive(ppkPath);
482
+ // one pass over the ppk: the bundle itself plus where its compressed
483
+ // bytes live, so the next build can fetch just them with one HTTP Range
484
+ // request
485
+ const found = ppkPath.toLowerCase().endsWith('.ppk')
486
+ ? await readZipEntryWithLocation(ppkPath, (name) =>
487
+ BUNDLE_ENTRY_NAMES.includes(name),
488
+ ).catch(() => null)
489
+ : null;
490
+ const bundle = found?.data ?? (await extractBundleFromArchive(ppkPath));
480
491
  if (bundle) {
481
- meta.bundleHash = sha256Hex(bundle);
492
+ const bundleHash = sha256Hex(bundle);
493
+ meta.bundleHash = bundleHash;
482
494
  const hbcVersion = getHbcVersion(bundle) ?? base?.bytecodeVersion;
483
495
  if (hbcVersion != null) meta.bytecodeVersion = hbcVersion;
484
- await cachePut(bundle).catch(() => {});
485
- // where the bundle's compressed bytes live inside the ppk, so the next
486
- // build can fetch just them with one HTTP Range request
487
- const location = await locateZipEntry(ppkPath, (name) =>
488
- BUNDLE_ENTRY_NAMES.includes(name),
489
- ).catch(() => null);
490
- if (
491
- location &&
492
- location.compressedSize > 0 &&
493
- (location.compressionMethod === ZIP_STORED ||
494
- location.compressionMethod === ZIP_DEFLATED)
495
- ) {
496
- meta.bundleOffset = location.dataOffset;
497
- meta.bundleCompressedSize = location.compressedSize;
498
- meta.bundleCompression = location.compressionMethod;
499
- }
496
+ await cachePut(bundle, undefined, bundleHash).catch(() => {});
497
+ Object.assign(meta, bundleLocationFields(found?.location));
500
498
  }
501
499
  } catch {
502
500
  // best effort: metadata never blocks a publish