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
@@ -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,34 +112,99 @@ 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
  // ---------------------------------------------------------------------------
109
181
 
182
+ /** Deadlines for the Range requests; every field has a default. */
183
+ export interface RangeOptions {
184
+ /** reads of at most CHUNK_BYTES (tail, headers, directory pages), default 20 s */
185
+ headerTimeoutMs?: number;
186
+ /** base deadline for larger reads (entry data, a prefetched directory), default 30 s */
187
+ dataTimeoutMs?: number;
188
+ /** added to `dataTimeoutMs` per MB requested, default 1 s */
189
+ dataTimeoutPerMbMs?: number;
190
+ }
191
+
192
+ const DEFAULT_HEADER_TIMEOUT_MS = 20_000;
193
+ const DEFAULT_DATA_TIMEOUT_MS = 30_000;
194
+ const DEFAULT_DATA_TIMEOUT_PER_MB_MS = 1_000;
195
+
196
+ /** deadline for a request of `bytes`: flat for header-sized reads, scaled otherwise */
197
+ function timeoutFor(bytes: number, options: RangeOptions): number {
198
+ if (bytes <= CHUNK_BYTES) {
199
+ return options.headerTimeoutMs ?? DEFAULT_HEADER_TIMEOUT_MS;
200
+ }
201
+ return (
202
+ (options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS) +
203
+ ((options.dataTimeoutPerMbMs ?? DEFAULT_DATA_TIMEOUT_PER_MB_MS) * bytes) /
204
+ (1024 * 1024)
205
+ );
206
+ }
207
+
110
208
  /** The server answered a Range request with the whole body (HTTP 200). */
111
209
  export class RangeUnsupportedError extends Error {
112
210
  constructor(readonly response: Response) {
@@ -129,22 +227,59 @@ export function parseContentRange(header: string | null): ContentRange | null {
129
227
  return { start, end, total };
130
228
  }
131
229
 
230
+ /**
231
+ * The validator to send as `If-Range` on later requests for the same object,
232
+ * so a replaced archive answers 200 (handled like a server without Range)
233
+ * instead of mixing bytes of two versions. Weak ETags are not allowed there.
234
+ */
235
+ export function rangeValidator(headers: Headers): string | undefined {
236
+ const etag = headers.get('etag')?.trim();
237
+ if (etag && !/^W\//i.test(etag)) return etag;
238
+ return headers.get('last-modified')?.trim() || undefined;
239
+ }
240
+
241
+ /** An aborted fetch as a plain Error (never mistaken for a 200 answer). */
242
+ function describeAbort(error: unknown, what: string, timeoutMs: number): Error {
243
+ const name = (error as { name?: string } | null)?.name;
244
+ if (name === 'TimeoutError' || name === 'AbortError') {
245
+ return new Error(`timed out after ${timeoutMs} ms fetching ${what}`);
246
+ }
247
+ return error instanceof Error ? error : new Error(String(error));
248
+ }
249
+
250
+ interface RequestOptions {
251
+ timeoutMs: number;
252
+ ifRange?: string;
253
+ /** archive size seen by the first request; a different one is an error */
254
+ expectTotal?: number;
255
+ }
256
+
132
257
  /** One Range request; `end` is exclusive. Resolves with a 206 response. */
133
258
  async function fetchRange(
134
259
  url: string,
135
260
  start: number,
136
261
  end: number,
262
+ options: RequestOptions,
137
263
  ): Promise<Response & { range: ContentRange }> {
138
- const response = await fetch(url, {
139
- headers: {
140
- Range: `bytes=${start}-${end - 1}`,
141
- 'Accept-Encoding': 'identity',
142
- },
143
- });
264
+ const what = `bytes=${start}-${end - 1}`;
265
+ const headers: Record<string, string> = {
266
+ Range: what,
267
+ 'Accept-Encoding': 'identity',
268
+ };
269
+ if (options.ifRange) headers['If-Range'] = options.ifRange;
270
+ let response: Response;
271
+ try {
272
+ response = await fetch(url, {
273
+ headers,
274
+ signal: AbortSignal.timeout(options.timeoutMs),
275
+ });
276
+ } catch (error) {
277
+ throw describeAbort(error, what, options.timeoutMs);
278
+ }
144
279
  if (response.status === 200) throw new RangeUnsupportedError(response);
145
280
  if (response.status !== 206 || !response.body) {
146
281
  await response.body?.cancel().catch(() => {});
147
- throw new Error(`HTTP ${response.status} for bytes=${start}-${end - 1}`);
282
+ throw new Error(`HTTP ${response.status} for ${what}`);
148
283
  }
149
284
  const range = parseContentRange(response.headers.get('content-range'));
150
285
  if (!range || range.start !== start || range.end !== end - 1) {
@@ -153,6 +288,15 @@ async function fetchRange(
153
288
  `unexpected Content-Range ${response.headers.get('content-range')}`,
154
289
  );
155
290
  }
291
+ if (
292
+ options.expectTotal !== undefined &&
293
+ range.total !== options.expectTotal
294
+ ) {
295
+ await response.body.cancel().catch(() => {});
296
+ throw new Error(
297
+ `archive size changed: ${range.total} bytes, expected ${options.expectTotal}`,
298
+ );
299
+ }
156
300
  return Object.assign(response, { range });
157
301
  }
158
302
 
@@ -160,9 +304,16 @@ async function fetchRangeBuffer(
160
304
  url: string,
161
305
  start: number,
162
306
  end: number,
307
+ options: RequestOptions,
163
308
  ): Promise<{ data: Buffer; total: number }> {
164
- const response = await fetchRange(url, start, end);
165
- const data = Buffer.from(await response.arrayBuffer());
309
+ const response = await fetchRange(url, start, end, options);
310
+ let data: Buffer;
311
+ try {
312
+ // Buffer.from(ArrayBuffer) is a view: the body is held exactly once
313
+ data = Buffer.from(await response.arrayBuffer());
314
+ } catch (error) {
315
+ throw describeAbort(error, `bytes=${start}-${end - 1}`, options.timeoutMs);
316
+ }
166
317
  if (data.length !== end - start) {
167
318
  throw new Error(
168
319
  `range returned ${data.length} bytes, expected ${end - start}`,
@@ -181,6 +332,7 @@ export async function fetchZipEntryData(
181
332
  ZipEntryLocation,
182
333
  'dataOffset' | 'compressedSize' | 'compressionMethod'
183
334
  >,
335
+ options: RangeOptions = {},
184
336
  ): Promise<{ data: Buffer; fetchedBytes: number; totalBytes: number }> {
185
337
  const { dataOffset, compressedSize, compressionMethod } = location;
186
338
  if (compressionMethod !== ZIP_STORED && compressionMethod !== ZIP_DEFLATED) {
@@ -198,6 +350,7 @@ export async function fetchZipEntryData(
198
350
  url,
199
351
  dataOffset,
200
352
  dataOffset + compressedSize,
353
+ { timeoutMs: timeoutFor(compressedSize, options) },
201
354
  );
202
355
  return {
203
356
  data: compressionMethod === ZIP_DEFLATED ? inflateRawSync(data) : data,
@@ -206,44 +359,176 @@ export async function fetchZipEntryData(
206
359
  };
207
360
  }
208
361
 
362
+ export interface HttpRangeReaderOptions extends RangeOptions {
363
+ /** validator of the archive (see `rangeValidator`), sent as If-Range */
364
+ ifRange?: string;
365
+ }
366
+
367
+ interface Chunk {
368
+ start: number;
369
+ data: Buffer;
370
+ }
371
+
209
372
  /**
210
373
  * 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.
374
+ * file headers) are widened to CHUNK_BYTES and cached. Chunks are kept as
375
+ * fetched — only overlapping ones are merged, touching ones are read across —
376
+ * so an entry's bytes are held once, and a read reuses whatever prefix the
377
+ * cache holds (typically the bytes following the local file header) before
378
+ * requesting the rest. Every request after the first carries If-Range and
379
+ * must report the same archive size.
213
380
  */
214
381
  export class HttpRangeReader extends RandomAccessReader {
215
- private readonly chunks: { start: number; data: Buffer }[] = [];
382
+ /** sorted by `start`, never overlapping */
383
+ private chunks: Chunk[] = [];
384
+ /** span a header read inside it should widen to (see `hintEntry`) */
385
+ private hint: { start: number; end: number } | null = null;
216
386
  requests = 0;
217
387
  fetchedBytes = 0;
218
388
 
219
389
  constructor(
220
390
  private readonly url: string,
221
391
  readonly totalSize: number,
222
- tail?: { start: number; data: Buffer },
392
+ tail?: Chunk,
393
+ private readonly options: HttpRangeReaderOptions = {},
223
394
  ) {
224
395
  super();
225
- if (tail) this.chunks.push(tail);
396
+ if (tail) this.addChunk(tail.start, tail.data);
397
+ }
398
+
399
+ /**
400
+ * The next entry to be read: yauzl first reads its local file header, and
401
+ * widening that read to the entry's data makes the data stream a cache hit
402
+ * — one request for header + bundle instead of two. The central directory
403
+ * may understate the local header's extra field, hence the slack.
404
+ */
405
+ hintEntry(entry: Entry): void {
406
+ const start = entry.relativeOffsetOfLocalHeader;
407
+ const end =
408
+ start +
409
+ LOCAL_HEADER_SIZE +
410
+ entry.fileNameLength +
411
+ entry.extraFieldLength +
412
+ entry.compressedSize +
413
+ HINT_SLACK_BYTES;
414
+ this.hint = { start, end: Math.min(end, this.totalSize) };
226
415
  }
227
416
 
228
- private cached(start: number, end: number): Buffer | null {
417
+ /** Cache `data` at `start`, merging with any chunk it overlaps. */
418
+ addChunk(start: number, data: Buffer): void {
419
+ if (data.length === 0) return;
420
+ let lo = start;
421
+ let hi = start + data.length;
422
+ const pieces: Chunk[] = [{ start, data }];
423
+ const rest: Chunk[] = [];
229
424
  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);
425
+ const chunkEnd = chunk.start + chunk.data.length;
426
+ if (chunk.start < hi && chunkEnd > lo) {
427
+ pieces.push(chunk);
428
+ lo = Math.min(lo, chunk.start);
429
+ hi = Math.max(hi, chunkEnd);
430
+ } else {
431
+ rest.push(chunk);
432
+ }
433
+ }
434
+ if (pieces.length === 1) {
435
+ rest.push(pieces[0]);
436
+ } else {
437
+ const merged = Buffer.alloc(hi - lo);
438
+ // the new data is written last so it wins over stale overlaps
439
+ for (const piece of pieces.reverse()) {
440
+ piece.data.copy(merged, piece.start - lo);
232
441
  }
442
+ rest.push({ start: lo, data: merged });
443
+ }
444
+ rest.sort((a, b) => a.start - b.start);
445
+ this.chunks = rest;
446
+ }
447
+
448
+ /** Fetch `[start, end)` into the cache in one request. */
449
+ async prefetch(start: number, end: number): Promise<void> {
450
+ this.addChunk(start, await this.fetchBuffer(start, end));
451
+ }
452
+
453
+ private requestOptions(bytes: number): RequestOptions {
454
+ return {
455
+ timeoutMs: timeoutFor(bytes, this.options),
456
+ ifRange: this.options.ifRange,
457
+ expectTotal: this.totalSize,
458
+ };
459
+ }
460
+
461
+ private async fetchBuffer(start: number, end: number): Promise<Buffer> {
462
+ this.requests++;
463
+ const { data } = await fetchRangeBuffer(
464
+ this.url,
465
+ start,
466
+ end,
467
+ this.requestOptions(end - start),
468
+ );
469
+ this.fetchedBytes += data.length;
470
+ return data;
471
+ }
472
+
473
+ /**
474
+ * Contiguous cached pieces starting exactly at `start`, up to `end`: views
475
+ * into one chunk or into a run of touching chunks, possibly ending short.
476
+ */
477
+ private cachedPieces(start: number, end: number): Buffer[] {
478
+ const pieces: Buffer[] = [];
479
+ let at = start;
480
+ for (const chunk of this.chunks) {
481
+ const chunkEnd = chunk.start + chunk.data.length;
482
+ if (chunkEnd <= at) continue;
483
+ if (chunk.start > at) break;
484
+ const stop = Math.min(end, chunkEnd);
485
+ pieces.push(chunk.data.subarray(at - chunk.start, stop - chunk.start));
486
+ at = stop;
487
+ if (at >= end) break;
488
+ }
489
+ return pieces;
490
+ }
491
+
492
+ /** start of the cached run (touching chunks) holding byte `end - 1` */
493
+ private cachedSuffixStart(end: number): number | null {
494
+ let i = this.chunks.findIndex(
495
+ (c) => end - 1 >= c.start && end - 1 < c.start + c.data.length,
496
+ );
497
+ if (i < 0) return null;
498
+ while (
499
+ i > 0 &&
500
+ this.chunks[i - 1].start + this.chunks[i - 1].data.length ===
501
+ this.chunks[i].start
502
+ ) {
503
+ i--;
233
504
  }
234
- return null;
505
+ return this.chunks[i].start;
506
+ }
507
+
508
+ /** start of the first cached chunk at or after `position` */
509
+ private nextCachedStart(position: number): number | null {
510
+ const chunk = this.chunks.find((c) => c.start >= position);
511
+ return chunk ? chunk.start : null;
235
512
  }
236
513
 
237
514
  _readStreamForRange(start: number, end: number): Readable {
238
- const hit = this.cached(start, end);
239
- if (hit) return Readable.from([hit]);
515
+ const pieces = this.cachedPieces(start, end);
516
+ const have = pieces.reduce((sum, piece) => sum + piece.length, 0);
517
+ if (have === end - start) return Readable.from(pieces);
240
518
  const out = new PassThrough();
519
+ for (const piece of pieces) out.write(piece);
520
+ const from = start + have;
521
+ const options = this.requestOptions(end - from);
241
522
  this.requests++;
242
- fetchRange(this.url, start, end)
523
+ fetchRange(this.url, from, end, options)
243
524
  .then((response) => {
244
- this.fetchedBytes += end - start;
525
+ this.fetchedBytes += end - from;
245
526
  const body = Readable.fromWeb(response.body as any);
246
- body.on('error', (error) => out.destroy(error));
527
+ body.on('error', (error) =>
528
+ out.destroy(
529
+ describeAbort(error, `bytes=${from}-${end - 1}`, options.timeoutMs),
530
+ ),
531
+ );
247
532
  body.pipe(out);
248
533
  })
249
534
  .catch((error) => out.destroy(error));
@@ -257,22 +542,50 @@ export class HttpRangeReader extends RandomAccessReader {
257
542
  position: number,
258
543
  callback: (err: Error | null, bytesRead?: number) => void,
259
544
  ): void {
260
- const hit = this.cached(position, position + length);
261
- if (hit) {
262
- hit.copy(buffer, offset);
545
+ const requestEnd = position + length;
546
+ const copyOut = (pieces: Buffer[]): boolean => {
547
+ let at = offset;
548
+ for (const piece of pieces) {
549
+ piece.copy(buffer, at);
550
+ at += piece.length;
551
+ }
552
+ return at - offset === length;
553
+ };
554
+ const cached = this.cachedPieces(position, requestEnd);
555
+ if (copyOut(cached)) {
263
556
  setImmediate(() => callback(null, length));
264
557
  return;
265
558
  }
266
- const end = Math.min(
267
- this.totalSize,
268
- Math.max(position + length, position + CHUNK_BYTES),
269
- );
270
- this.requests++;
271
- fetchRangeBuffer(this.url, position, end).then(
272
- ({ data }) => {
273
- this.fetchedBytes += data.length;
274
- this.chunks.push({ start: position, data });
275
- data.copy(buffer, offset, 0, length);
559
+ // fetch only what the cache lacks: skip the cached prefix, stop at a
560
+ // cached suffix (yauzl's EOCD read may just exceed the tail), and
561
+ // otherwise widen so the next header read is free — to exactly the hinted
562
+ // entry when the hint covers this read, else by CHUNK_BYTES — but never
563
+ // into bytes already cached beyond the request
564
+ const from =
565
+ position + cached.reduce((sum, piece) => sum + piece.length, 0);
566
+ const suffixStart = this.cachedSuffixStart(requestEnd);
567
+ let end: number;
568
+ if (suffixStart !== null && suffixStart > from) {
569
+ end = suffixStart;
570
+ } else {
571
+ const hinted =
572
+ this.hint !== null &&
573
+ position >= this.hint.start &&
574
+ requestEnd <= this.hint.end;
575
+ end = hinted
576
+ ? (this.hint as { end: number }).end
577
+ : Math.max(requestEnd, from + CHUNK_BYTES);
578
+ end = Math.min(end, this.totalSize);
579
+ const next = this.nextCachedStart(requestEnd);
580
+ if (next !== null && next < end) end = next;
581
+ }
582
+ this.fetchBuffer(from, end).then(
583
+ (data) => {
584
+ this.addChunk(from, data);
585
+ if (!copyOut(this.cachedPieces(position, requestEnd))) {
586
+ callback(new Error('range read did not cover the requested bytes'));
587
+ return;
588
+ }
276
589
  callback(null, length);
277
590
  },
278
591
  (error) => callback(error),
@@ -280,6 +593,26 @@ export class HttpRangeReader extends RandomAccessReader {
280
593
  }
281
594
  }
282
595
 
596
+ /** End-of-central-directory record: where the central directory lives. */
597
+ const EOCD_SIGNATURE = 0x06054b50;
598
+ const EOCD_SIZE = 22;
599
+
600
+ export function parseEndOfCentralDirectory(
601
+ tail: Buffer,
602
+ ): { cdOffset: number; cdSize: number } | null {
603
+ for (let i = tail.length - EOCD_SIZE; i >= 0; i--) {
604
+ if (tail.readUInt32LE(i) !== EOCD_SIGNATURE) continue;
605
+ const commentLength = tail.readUInt16LE(i + 20);
606
+ if (i + EOCD_SIZE + commentLength !== tail.length) continue;
607
+ const cdSize = tail.readUInt32LE(i + 12);
608
+ const cdOffset = tail.readUInt32LE(i + 16);
609
+ // zip64 markers: let yauzl resolve the real values itself
610
+ if (cdSize === 0xffffffff || cdOffset === 0xffffffff) return null;
611
+ return { cdOffset, cdSize };
612
+ }
613
+ return null;
614
+ }
615
+
283
616
  export type RemoteZip =
284
617
  | { kind: 'zip'; zipFile: ZipFile; reader: HttpRangeReader }
285
618
  /** the server ignored Range: the whole archive is streaming in `response` */
@@ -289,10 +622,20 @@ export type RemoteZip =
289
622
  * Open a remote zip by fetching its tail (EOCD + central directory for
290
623
  * typical archives) and letting yauzl read the rest on demand.
291
624
  */
292
- export async function openRemoteZip(url: string): Promise<RemoteZip> {
293
- const response = await fetch(url, {
294
- headers: { Range: `bytes=-${TAIL_BYTES}`, 'Accept-Encoding': 'identity' },
295
- });
625
+ export async function openRemoteZip(
626
+ url: string,
627
+ options: RangeOptions = {},
628
+ ): Promise<RemoteZip> {
629
+ const timeoutMs = timeoutFor(TAIL_BYTES, options);
630
+ let response: Response;
631
+ try {
632
+ response = await fetch(url, {
633
+ headers: { Range: `bytes=-${TAIL_BYTES}`, 'Accept-Encoding': 'identity' },
634
+ signal: AbortSignal.timeout(timeoutMs),
635
+ });
636
+ } catch (error) {
637
+ throw describeAbort(error, `bytes=-${TAIL_BYTES}`, timeoutMs);
638
+ }
296
639
  if (!response.ok || !response.body) {
297
640
  await response.body?.cancel().catch(() => {});
298
641
  throw new Error(`HTTP ${response.status}`);
@@ -305,18 +648,39 @@ export async function openRemoteZip(url: string): Promise<RemoteZip> {
305
648
  `unexpected Content-Range ${response.headers.get('content-range')}`,
306
649
  );
307
650
  }
308
- const data = Buffer.from(await response.arrayBuffer());
651
+ let data: Buffer;
652
+ try {
653
+ data = Buffer.from(await response.arrayBuffer());
654
+ } catch (error) {
655
+ throw describeAbort(error, `bytes=-${TAIL_BYTES}`, timeoutMs);
656
+ }
309
657
  if (data.length !== range.end - range.start + 1) {
310
658
  throw new Error(
311
659
  `tail returned ${data.length} bytes, expected ${range.end - range.start + 1}`,
312
660
  );
313
661
  }
314
- const reader = new HttpRangeReader(url, range.total, {
315
- start: range.start,
316
- data,
317
- });
662
+ const reader = new HttpRangeReader(
663
+ url,
664
+ range.total,
665
+ { start: range.start, data },
666
+ { ...options, ifRange: rangeValidator(response.headers) },
667
+ );
318
668
  reader.requests = 1;
319
669
  reader.fetchedBytes = data.length;
670
+ // Large archives (apk / ipa with thousands of files) keep their central
671
+ // directory well before the tail; yauzl would otherwise page it in with one
672
+ // sequential request per CHUNK_BYTES. Fetch the missing part at once — one
673
+ // buffer of exactly its size — as long as the EOCD describes a directory
674
+ // that ends inside the tail (a corrupt record could claim the whole file).
675
+ const eocd = parseEndOfCentralDirectory(data);
676
+ if (
677
+ eocd &&
678
+ eocd.cdOffset < range.start &&
679
+ eocd.cdOffset + eocd.cdSize >= range.start &&
680
+ eocd.cdOffset + eocd.cdSize <= range.total - EOCD_SIZE
681
+ ) {
682
+ await reader.prefetch(eocd.cdOffset, range.start);
683
+ }
320
684
  const zipFile = await new Promise<ZipFile>((resolve, reject) => {
321
685
  fromRandomAccessReader(
322
686
  reader,
@@ -328,10 +692,14 @@ export async function openRemoteZip(url: string): Promise<RemoteZip> {
328
692
  return { kind: 'zip', zipFile, reader };
329
693
  }
330
694
 
331
- /** Read the first matching entry of an opened remote zip, then close it. */
695
+ /**
696
+ * Read the first matching entry of an opened remote zip, then close it. With
697
+ * `reader` given, the entry's header and data are fetched in one request.
698
+ */
332
699
  export function readRemoteZipEntry(
333
700
  zipFile: ZipFile,
334
701
  matches: (name: string) => boolean,
702
+ reader?: HttpRangeReader,
335
703
  ): Promise<Buffer | null> {
336
704
  return new Promise((resolve, reject) => {
337
705
  let settled = false;
@@ -348,6 +716,7 @@ export function readRemoteZipEntry(
348
716
  zipFile.readEntry();
349
717
  return;
350
718
  }
719
+ reader?.hintEntry(entry);
351
720
  readEntry(entry, zipFile).then(
352
721
  (data) => finish(null, data),
353
722
  (error) => finish(error),