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
@@ -5,8 +5,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.HttpRangeReader = exports.RangeUnsupportedError = exports.ZIP_DEFLATED = exports.ZIP_STORED = void 0;
7
7
  exports.locateZipEntry = locateZipEntry;
8
+ exports.readZipEntryWithLocation = readZipEntryWithLocation;
9
+ exports.bundleLocationFields = bundleLocationFields;
8
10
  exports.parseContentRange = parseContentRange;
11
+ exports.rangeValidator = rangeValidator;
9
12
  exports.fetchZipEntryData = fetchZipEntryData;
13
+ exports.parseEndOfCentralDirectory = parseEndOfCentralDirectory;
10
14
  exports.openRemoteZip = openRemoteZip;
11
15
  exports.readRemoteZipEntry = readRemoteZipEntry;
12
16
  // Byte-range access to zip archives.
@@ -26,15 +30,42 @@ exports.ZIP_STORED = 0;
26
30
  exports.ZIP_DEFLATED = 8;
27
31
  const LOCAL_HEADER_SIGNATURE = 0x04034b50;
28
32
  const LOCAL_HEADER_SIZE = 30;
29
- /** covers the EOCD (≤ 22 + 65535 bytes) and, for small archives, everything */
30
- const TAIL_BYTES = 64 * 1024;
33
+ /**
34
+ * Exactly what yauzl reads to find the EOCD (22 + 65535 comment + 20 zip64
35
+ * locator), so its first read is a cache hit; small archives fit entirely.
36
+ */
37
+ const TAIL_BYTES = 22 + 0xffff + 20;
31
38
  /** minimum span fetched for header reads, so header + directory share a request */
32
39
  const CHUNK_BYTES = 64 * 1024;
40
+ /** extra bytes past a hinted entry, covering a longer local extra field */
41
+ const HINT_SLACK_BYTES = 4 * 1024;
33
42
  /** Data location of the first entry matching `matches` in a local zip. */
34
43
  async function locateZipEntry(zipPath, matches) {
35
- const entry = await findEntry(zipPath, matches);
36
- if (!entry)
44
+ const found = await openFirstEntry(zipPath, matches);
45
+ if (!found)
46
+ return null;
47
+ found.zipFile.close();
48
+ return locationOfEntry(zipPath, found.entry);
49
+ }
50
+ /**
51
+ * Content and data location of the first matching entry in one pass over the
52
+ * archive (publish needs both: the bundle to hash and cache, its location to
53
+ * report to the server).
54
+ */
55
+ async function readZipEntryWithLocation(zipPath, matches) {
56
+ const found = await openFirstEntry(zipPath, matches);
57
+ if (!found)
37
58
  return null;
59
+ let data;
60
+ try {
61
+ data = await (0, zip_entries_1.readEntry)(found.entry, found.zipFile);
62
+ }
63
+ finally {
64
+ found.zipFile.close();
65
+ }
66
+ return { data, location: await locationOfEntry(zipPath, found.entry) };
67
+ }
68
+ async function locationOfEntry(zipPath, entry) {
38
69
  const header = Buffer.alloc(LOCAL_HEADER_SIZE);
39
70
  const fd = await fs_extra_1.default.open(zipPath, 'r');
40
71
  try {
@@ -62,19 +93,32 @@ async function locateZipEntry(zipPath, matches) {
62
93
  compressionMethod: entry.compressionMethod,
63
94
  };
64
95
  }
65
- function findEntry(zipPath, matches) {
96
+ /** Open a local zip and stop at the first matching entry (caller closes). */
97
+ function openFirstEntry(zipPath, matches) {
66
98
  return new Promise((resolve, reject) => {
67
- (0, yauzl_1.open)(zipPath, { lazyEntries: true }, (err, zipFile) => {
99
+ (0, yauzl_1.open)(zipPath, { lazyEntries: true, autoClose: false }, (err, zipFile) => {
68
100
  if (err)
69
101
  return reject(err);
70
- let found = null;
71
- zipFile.on('error', reject);
72
- zipFile.on('end', () => resolve(found));
73
- zipFile.on('entry', (entry) => {
74
- if (!found && matches(entry.fileName)) {
75
- found = entry;
102
+ let settled = false;
103
+ zipFile.on('error', (error) => {
104
+ if (!settled) {
105
+ settled = true;
106
+ reject(error);
107
+ }
108
+ });
109
+ zipFile.on('end', () => {
110
+ if (!settled) {
111
+ settled = true;
76
112
  zipFile.close();
77
- resolve(found);
113
+ resolve(null);
114
+ }
115
+ });
116
+ zipFile.on('entry', (entry) => {
117
+ if (settled)
118
+ return;
119
+ if (matches(entry.fileName)) {
120
+ settled = true;
121
+ resolve({ zipFile, entry });
78
122
  return;
79
123
  }
80
124
  zipFile.readEntry();
@@ -83,9 +127,36 @@ function findEntry(zipPath, matches) {
83
127
  });
84
128
  });
85
129
  }
86
- // ---------------------------------------------------------------------------
87
- // HTTP Range
88
- // ---------------------------------------------------------------------------
130
+ /**
131
+ * The `bundleOffset` / `bundleCompressedSize` / `bundleCompression` fields for
132
+ * version/create and package/create, or nothing when the entry cannot be
133
+ * fetched by a single Range request (unknown, empty or exotic compression).
134
+ */
135
+ function bundleLocationFields(location) {
136
+ if (!location ||
137
+ location.compressedSize <= 0 ||
138
+ (location.compressionMethod !== exports.ZIP_STORED &&
139
+ location.compressionMethod !== exports.ZIP_DEFLATED)) {
140
+ return {};
141
+ }
142
+ return {
143
+ bundleOffset: location.dataOffset,
144
+ bundleCompressedSize: location.compressedSize,
145
+ bundleCompression: location.compressionMethod,
146
+ };
147
+ }
148
+ const DEFAULT_HEADER_TIMEOUT_MS = 20_000;
149
+ const DEFAULT_DATA_TIMEOUT_MS = 30_000;
150
+ const DEFAULT_DATA_TIMEOUT_PER_MB_MS = 1_000;
151
+ /** deadline for a request of `bytes`: flat for header-sized reads, scaled otherwise */
152
+ function timeoutFor(bytes, options) {
153
+ if (bytes <= CHUNK_BYTES) {
154
+ return options.headerTimeoutMs ?? DEFAULT_HEADER_TIMEOUT_MS;
155
+ }
156
+ return ((options.dataTimeoutMs ?? DEFAULT_DATA_TIMEOUT_MS) +
157
+ ((options.dataTimeoutPerMbMs ?? DEFAULT_DATA_TIMEOUT_PER_MB_MS) * bytes) /
158
+ (1024 * 1024));
159
+ }
89
160
  /** The server answered a Range request with the whole body (HTTP 200). */
90
161
  class RangeUnsupportedError extends Error {
91
162
  response;
@@ -105,30 +176,72 @@ function parseContentRange(header) {
105
176
  return null;
106
177
  return { start, end, total };
107
178
  }
179
+ /**
180
+ * The validator to send as `If-Range` on later requests for the same object,
181
+ * so a replaced archive answers 200 (handled like a server without Range)
182
+ * instead of mixing bytes of two versions. Weak ETags are not allowed there.
183
+ */
184
+ function rangeValidator(headers) {
185
+ const etag = headers.get('etag')?.trim();
186
+ if (etag && !/^W\//i.test(etag))
187
+ return etag;
188
+ return headers.get('last-modified')?.trim() || undefined;
189
+ }
190
+ /** An aborted fetch as a plain Error (never mistaken for a 200 answer). */
191
+ function describeAbort(error, what, timeoutMs) {
192
+ const name = error?.name;
193
+ if (name === 'TimeoutError' || name === 'AbortError') {
194
+ return new Error(`timed out after ${timeoutMs} ms fetching ${what}`);
195
+ }
196
+ return error instanceof Error ? error : new Error(String(error));
197
+ }
108
198
  /** One Range request; `end` is exclusive. Resolves with a 206 response. */
109
- async function fetchRange(url, start, end) {
110
- const response = await fetch(url, {
111
- headers: {
112
- Range: `bytes=${start}-${end - 1}`,
113
- 'Accept-Encoding': 'identity',
114
- },
115
- });
199
+ async function fetchRange(url, start, end, options) {
200
+ const what = `bytes=${start}-${end - 1}`;
201
+ const headers = {
202
+ Range: what,
203
+ 'Accept-Encoding': 'identity',
204
+ };
205
+ if (options.ifRange)
206
+ headers['If-Range'] = options.ifRange;
207
+ let response;
208
+ try {
209
+ response = await fetch(url, {
210
+ headers,
211
+ signal: AbortSignal.timeout(options.timeoutMs),
212
+ });
213
+ }
214
+ catch (error) {
215
+ throw describeAbort(error, what, options.timeoutMs);
216
+ }
116
217
  if (response.status === 200)
117
218
  throw new RangeUnsupportedError(response);
118
219
  if (response.status !== 206 || !response.body) {
119
220
  await response.body?.cancel().catch(() => { });
120
- throw new Error(`HTTP ${response.status} for bytes=${start}-${end - 1}`);
221
+ throw new Error(`HTTP ${response.status} for ${what}`);
121
222
  }
122
223
  const range = parseContentRange(response.headers.get('content-range'));
123
224
  if (!range || range.start !== start || range.end !== end - 1) {
124
225
  await response.body.cancel().catch(() => { });
125
226
  throw new Error(`unexpected Content-Range ${response.headers.get('content-range')}`);
126
227
  }
228
+ if (options.expectTotal !== undefined &&
229
+ range.total !== options.expectTotal) {
230
+ await response.body.cancel().catch(() => { });
231
+ throw new Error(`archive size changed: ${range.total} bytes, expected ${options.expectTotal}`);
232
+ }
127
233
  return Object.assign(response, { range });
128
234
  }
129
- async function fetchRangeBuffer(url, start, end) {
130
- const response = await fetchRange(url, start, end);
131
- const data = Buffer.from(await response.arrayBuffer());
235
+ async function fetchRangeBuffer(url, start, end, options) {
236
+ const response = await fetchRange(url, start, end, options);
237
+ let data;
238
+ try {
239
+ // Buffer.from(ArrayBuffer) is a view: the body is held exactly once
240
+ data = Buffer.from(await response.arrayBuffer());
241
+ }
242
+ catch (error) {
243
+ throw describeAbort(error, `bytes=${start}-${end - 1}`, options.timeoutMs);
244
+ }
132
245
  if (data.length !== end - start) {
133
246
  throw new Error(`range returned ${data.length} bytes, expected ${end - start}`);
134
247
  }
@@ -138,7 +251,7 @@ async function fetchRangeBuffer(url, start, end) {
138
251
  * Fetch one entry whose compressed bytes are already located (the ppk's own
139
252
  * publish-time report) and decompress it. Returns the raw entry content.
140
253
  */
141
- async function fetchZipEntryData(url, location) {
254
+ async function fetchZipEntryData(url, location, options = {}) {
142
255
  const { dataOffset, compressedSize, compressionMethod } = location;
143
256
  if (compressionMethod !== exports.ZIP_STORED && compressionMethod !== exports.ZIP_DEFLATED) {
144
257
  throw new Error(`unsupported compression method ${compressionMethod}`);
@@ -149,7 +262,7 @@ async function fetchZipEntryData(url, location) {
149
262
  compressedSize <= 0) {
150
263
  throw new Error('invalid bundle location');
151
264
  }
152
- const { data, total } = await fetchRangeBuffer(url, dataOffset, dataOffset + compressedSize);
265
+ const { data, total } = await fetchRangeBuffer(url, dataOffset, dataOffset + compressedSize, { timeoutMs: timeoutFor(compressedSize, options) });
153
266
  return {
154
267
  data: compressionMethod === exports.ZIP_DEFLATED ? (0, zlib_1.inflateRawSync)(data) : data,
155
268
  fetchedBytes: compressedSize,
@@ -158,72 +271,240 @@ async function fetchZipEntryData(url, location) {
158
271
  }
159
272
  /**
160
273
  * yauzl reader over HTTP Range. Header reads (EOCD, central directory, local
161
- * file headers) are widened to CHUNK_BYTES and cached so a small archive costs
162
- * one request; entry data streams straight from its own request.
274
+ * file headers) are widened to CHUNK_BYTES and cached. Chunks are kept as
275
+ * fetched — only overlapping ones are merged, touching ones are read across —
276
+ * so an entry's bytes are held once, and a read reuses whatever prefix the
277
+ * cache holds (typically the bytes following the local file header) before
278
+ * requesting the rest. Every request after the first carries If-Range and
279
+ * must report the same archive size.
163
280
  */
164
281
  class HttpRangeReader extends yauzl_1.RandomAccessReader {
165
282
  url;
166
283
  totalSize;
284
+ options;
285
+ /** sorted by `start`, never overlapping */
167
286
  chunks = [];
287
+ /** span a header read inside it should widen to (see `hintEntry`) */
288
+ hint = null;
168
289
  requests = 0;
169
290
  fetchedBytes = 0;
170
- constructor(url, totalSize, tail) {
291
+ constructor(url, totalSize, tail, options = {}) {
171
292
  super();
172
293
  this.url = url;
173
294
  this.totalSize = totalSize;
295
+ this.options = options;
174
296
  if (tail)
175
- this.chunks.push(tail);
297
+ this.addChunk(tail.start, tail.data);
298
+ }
299
+ /**
300
+ * The next entry to be read: yauzl first reads its local file header, and
301
+ * widening that read to the entry's data makes the data stream a cache hit
302
+ * — one request for header + bundle instead of two. The central directory
303
+ * may understate the local header's extra field, hence the slack.
304
+ */
305
+ hintEntry(entry) {
306
+ const start = entry.relativeOffsetOfLocalHeader;
307
+ const end = start +
308
+ LOCAL_HEADER_SIZE +
309
+ entry.fileNameLength +
310
+ entry.extraFieldLength +
311
+ entry.compressedSize +
312
+ HINT_SLACK_BYTES;
313
+ this.hint = { start, end: Math.min(end, this.totalSize) };
176
314
  }
177
- cached(start, end) {
315
+ /** Cache `data` at `start`, merging with any chunk it overlaps. */
316
+ addChunk(start, data) {
317
+ if (data.length === 0)
318
+ return;
319
+ let lo = start;
320
+ let hi = start + data.length;
321
+ const pieces = [{ start, data }];
322
+ const rest = [];
178
323
  for (const chunk of this.chunks) {
179
- if (start >= chunk.start && end <= chunk.start + chunk.data.length) {
180
- return chunk.data.subarray(start - chunk.start, end - chunk.start);
324
+ const chunkEnd = chunk.start + chunk.data.length;
325
+ if (chunk.start < hi && chunkEnd > lo) {
326
+ pieces.push(chunk);
327
+ lo = Math.min(lo, chunk.start);
328
+ hi = Math.max(hi, chunkEnd);
329
+ }
330
+ else {
331
+ rest.push(chunk);
181
332
  }
182
333
  }
183
- return null;
334
+ if (pieces.length === 1) {
335
+ rest.push(pieces[0]);
336
+ }
337
+ else {
338
+ const merged = Buffer.alloc(hi - lo);
339
+ // the new data is written last so it wins over stale overlaps
340
+ for (const piece of pieces.reverse()) {
341
+ piece.data.copy(merged, piece.start - lo);
342
+ }
343
+ rest.push({ start: lo, data: merged });
344
+ }
345
+ rest.sort((a, b) => a.start - b.start);
346
+ this.chunks = rest;
347
+ }
348
+ /** Fetch `[start, end)` into the cache in one request. */
349
+ async prefetch(start, end) {
350
+ this.addChunk(start, await this.fetchBuffer(start, end));
351
+ }
352
+ requestOptions(bytes) {
353
+ return {
354
+ timeoutMs: timeoutFor(bytes, this.options),
355
+ ifRange: this.options.ifRange,
356
+ expectTotal: this.totalSize,
357
+ };
358
+ }
359
+ async fetchBuffer(start, end) {
360
+ this.requests++;
361
+ const { data } = await fetchRangeBuffer(this.url, start, end, this.requestOptions(end - start));
362
+ this.fetchedBytes += data.length;
363
+ return data;
364
+ }
365
+ /**
366
+ * Contiguous cached pieces starting exactly at `start`, up to `end`: views
367
+ * into one chunk or into a run of touching chunks, possibly ending short.
368
+ */
369
+ cachedPieces(start, end) {
370
+ const pieces = [];
371
+ let at = start;
372
+ for (const chunk of this.chunks) {
373
+ const chunkEnd = chunk.start + chunk.data.length;
374
+ if (chunkEnd <= at)
375
+ continue;
376
+ if (chunk.start > at)
377
+ break;
378
+ const stop = Math.min(end, chunkEnd);
379
+ pieces.push(chunk.data.subarray(at - chunk.start, stop - chunk.start));
380
+ at = stop;
381
+ if (at >= end)
382
+ break;
383
+ }
384
+ return pieces;
385
+ }
386
+ /** start of the cached run (touching chunks) holding byte `end - 1` */
387
+ cachedSuffixStart(end) {
388
+ let i = this.chunks.findIndex((c) => end - 1 >= c.start && end - 1 < c.start + c.data.length);
389
+ if (i < 0)
390
+ return null;
391
+ while (i > 0 &&
392
+ this.chunks[i - 1].start + this.chunks[i - 1].data.length ===
393
+ this.chunks[i].start) {
394
+ i--;
395
+ }
396
+ return this.chunks[i].start;
397
+ }
398
+ /** start of the first cached chunk at or after `position` */
399
+ nextCachedStart(position) {
400
+ const chunk = this.chunks.find((c) => c.start >= position);
401
+ return chunk ? chunk.start : null;
184
402
  }
185
403
  _readStreamForRange(start, end) {
186
- const hit = this.cached(start, end);
187
- if (hit)
188
- return stream_1.Readable.from([hit]);
404
+ const pieces = this.cachedPieces(start, end);
405
+ const have = pieces.reduce((sum, piece) => sum + piece.length, 0);
406
+ if (have === end - start)
407
+ return stream_1.Readable.from(pieces);
189
408
  const out = new stream_1.PassThrough();
409
+ for (const piece of pieces)
410
+ out.write(piece);
411
+ const from = start + have;
412
+ const options = this.requestOptions(end - from);
190
413
  this.requests++;
191
- fetchRange(this.url, start, end)
414
+ fetchRange(this.url, from, end, options)
192
415
  .then((response) => {
193
- this.fetchedBytes += end - start;
416
+ this.fetchedBytes += end - from;
194
417
  const body = stream_1.Readable.fromWeb(response.body);
195
- body.on('error', (error) => out.destroy(error));
418
+ body.on('error', (error) => out.destroy(describeAbort(error, `bytes=${from}-${end - 1}`, options.timeoutMs)));
196
419
  body.pipe(out);
197
420
  })
198
421
  .catch((error) => out.destroy(error));
199
422
  return out;
200
423
  }
201
424
  read(buffer, offset, length, position, callback) {
202
- const hit = this.cached(position, position + length);
203
- if (hit) {
204
- hit.copy(buffer, offset);
425
+ const requestEnd = position + length;
426
+ const copyOut = (pieces) => {
427
+ let at = offset;
428
+ for (const piece of pieces) {
429
+ piece.copy(buffer, at);
430
+ at += piece.length;
431
+ }
432
+ return at - offset === length;
433
+ };
434
+ const cached = this.cachedPieces(position, requestEnd);
435
+ if (copyOut(cached)) {
205
436
  setImmediate(() => callback(null, length));
206
437
  return;
207
438
  }
208
- const end = Math.min(this.totalSize, Math.max(position + length, position + CHUNK_BYTES));
209
- this.requests++;
210
- fetchRangeBuffer(this.url, position, end).then(({ data }) => {
211
- this.fetchedBytes += data.length;
212
- this.chunks.push({ start: position, data });
213
- data.copy(buffer, offset, 0, length);
439
+ // fetch only what the cache lacks: skip the cached prefix, stop at a
440
+ // cached suffix (yauzl's EOCD read may just exceed the tail), and
441
+ // otherwise widen so the next header read is free — to exactly the hinted
442
+ // entry when the hint covers this read, else by CHUNK_BYTES — but never
443
+ // into bytes already cached beyond the request
444
+ const from = position + cached.reduce((sum, piece) => sum + piece.length, 0);
445
+ const suffixStart = this.cachedSuffixStart(requestEnd);
446
+ let end;
447
+ if (suffixStart !== null && suffixStart > from) {
448
+ end = suffixStart;
449
+ }
450
+ else {
451
+ const hinted = this.hint !== null &&
452
+ position >= this.hint.start &&
453
+ requestEnd <= this.hint.end;
454
+ end = hinted
455
+ ? this.hint.end
456
+ : Math.max(requestEnd, from + CHUNK_BYTES);
457
+ end = Math.min(end, this.totalSize);
458
+ const next = this.nextCachedStart(requestEnd);
459
+ if (next !== null && next < end)
460
+ end = next;
461
+ }
462
+ this.fetchBuffer(from, end).then((data) => {
463
+ this.addChunk(from, data);
464
+ if (!copyOut(this.cachedPieces(position, requestEnd))) {
465
+ callback(new Error('range read did not cover the requested bytes'));
466
+ return;
467
+ }
214
468
  callback(null, length);
215
469
  }, (error) => callback(error));
216
470
  }
217
471
  }
218
472
  exports.HttpRangeReader = HttpRangeReader;
473
+ /** End-of-central-directory record: where the central directory lives. */
474
+ const EOCD_SIGNATURE = 0x06054b50;
475
+ const EOCD_SIZE = 22;
476
+ function parseEndOfCentralDirectory(tail) {
477
+ for (let i = tail.length - EOCD_SIZE; i >= 0; i--) {
478
+ if (tail.readUInt32LE(i) !== EOCD_SIGNATURE)
479
+ continue;
480
+ const commentLength = tail.readUInt16LE(i + 20);
481
+ if (i + EOCD_SIZE + commentLength !== tail.length)
482
+ continue;
483
+ const cdSize = tail.readUInt32LE(i + 12);
484
+ const cdOffset = tail.readUInt32LE(i + 16);
485
+ // zip64 markers: let yauzl resolve the real values itself
486
+ if (cdSize === 0xffffffff || cdOffset === 0xffffffff)
487
+ return null;
488
+ return { cdOffset, cdSize };
489
+ }
490
+ return null;
491
+ }
219
492
  /**
220
493
  * Open a remote zip by fetching its tail (EOCD + central directory for
221
494
  * typical archives) and letting yauzl read the rest on demand.
222
495
  */
223
- async function openRemoteZip(url) {
224
- const response = await fetch(url, {
225
- headers: { Range: `bytes=-${TAIL_BYTES}`, 'Accept-Encoding': 'identity' },
226
- });
496
+ async function openRemoteZip(url, options = {}) {
497
+ const timeoutMs = timeoutFor(TAIL_BYTES, options);
498
+ let response;
499
+ try {
500
+ response = await fetch(url, {
501
+ headers: { Range: `bytes=-${TAIL_BYTES}`, 'Accept-Encoding': 'identity' },
502
+ signal: AbortSignal.timeout(timeoutMs),
503
+ });
504
+ }
505
+ catch (error) {
506
+ throw describeAbort(error, `bytes=-${TAIL_BYTES}`, timeoutMs);
507
+ }
227
508
  if (!response.ok || !response.body) {
228
509
  await response.body?.cancel().catch(() => { });
229
510
  throw new Error(`HTTP ${response.status}`);
@@ -235,23 +516,41 @@ async function openRemoteZip(url) {
235
516
  await response.body.cancel().catch(() => { });
236
517
  throw new Error(`unexpected Content-Range ${response.headers.get('content-range')}`);
237
518
  }
238
- const data = Buffer.from(await response.arrayBuffer());
519
+ let data;
520
+ try {
521
+ data = Buffer.from(await response.arrayBuffer());
522
+ }
523
+ catch (error) {
524
+ throw describeAbort(error, `bytes=-${TAIL_BYTES}`, timeoutMs);
525
+ }
239
526
  if (data.length !== range.end - range.start + 1) {
240
527
  throw new Error(`tail returned ${data.length} bytes, expected ${range.end - range.start + 1}`);
241
528
  }
242
- const reader = new HttpRangeReader(url, range.total, {
243
- start: range.start,
244
- data,
245
- });
529
+ const reader = new HttpRangeReader(url, range.total, { start: range.start, data }, { ...options, ifRange: rangeValidator(response.headers) });
246
530
  reader.requests = 1;
247
531
  reader.fetchedBytes = data.length;
532
+ // Large archives (apk / ipa with thousands of files) keep their central
533
+ // directory well before the tail; yauzl would otherwise page it in with one
534
+ // sequential request per CHUNK_BYTES. Fetch the missing part at once — one
535
+ // buffer of exactly its size — as long as the EOCD describes a directory
536
+ // that ends inside the tail (a corrupt record could claim the whole file).
537
+ const eocd = parseEndOfCentralDirectory(data);
538
+ if (eocd &&
539
+ eocd.cdOffset < range.start &&
540
+ eocd.cdOffset + eocd.cdSize >= range.start &&
541
+ eocd.cdOffset + eocd.cdSize <= range.total - EOCD_SIZE) {
542
+ await reader.prefetch(eocd.cdOffset, range.start);
543
+ }
248
544
  const zipFile = await new Promise((resolve, reject) => {
249
545
  (0, yauzl_1.fromRandomAccessReader)(reader, range.total, { lazyEntries: true, autoClose: false }, (err, file) => (err ? reject(err) : resolve(file)));
250
546
  });
251
547
  return { kind: 'zip', zipFile, reader };
252
548
  }
253
- /** Read the first matching entry of an opened remote zip, then close it. */
254
- function readRemoteZipEntry(zipFile, matches) {
549
+ /**
550
+ * Read the first matching entry of an opened remote zip, then close it. With
551
+ * `reader` given, the entry's header and data are fetched in one request.
552
+ */
553
+ function readRemoteZipEntry(zipFile, matches, reader) {
255
554
  return new Promise((resolve, reject) => {
256
555
  let settled = false;
257
556
  const finish = (error, result = null) => {
@@ -268,6 +567,7 @@ function readRemoteZipEntry(zipFile, matches) {
268
567
  zipFile.readEntry();
269
568
  return;
270
569
  }
570
+ reader?.hintEntry(entry);
271
571
  (0, zip_entries_1.readEntry)(entry, zipFile).then((data) => finish(null, data), (error) => finish(error));
272
572
  });
273
573
  zipFile.readEntry();
package/lib/versions.js CHANGED
@@ -8,7 +8,6 @@ exports.normalizeDeps = normalizeDeps;
8
8
  exports.fetchVersions = fetchVersions;
9
9
  const chalk_1 = __importDefault(require("chalk"));
10
10
  const compare_versions_1 = require("compare-versions");
11
- const tty_table_1 = __importDefault(require("tty-table"));
12
11
  const api_1 = require("./api");
13
12
  const app_1 = require("./app");
14
13
  const package_1 = require("./package");
@@ -147,7 +146,9 @@ function printDepsChangesForPackage({ pkg, versionDeps, }) {
147
146
  packageId: pkg.id,
148
147
  })));
149
148
  console.log(summaryText);
150
- console.log((0, tty_table_1.default)(header, rows).render());
149
+ // tty-table is ~25 ms to load; only pay for it when a table is rendered
150
+ const Table = (0, utils_1.loadTtyTable)();
151
+ console.log(Table(header, rows).render());
151
152
  console.log(chalk_1.default.yellow((0, i18n_1.t)('depsChangeRiskWarning')));
152
153
  return true;
153
154
  }
@@ -329,24 +330,21 @@ async function describePpkBundle(ppkPath, base) {
329
330
  // server version — strict, tolerant or too old to know the field — accepts.
330
331
  const meta = {};
331
332
  try {
332
- const bundle = await (0, hermes_base_1.extractBundleFromArchive)(ppkPath);
333
+ // one pass over the ppk: the bundle itself plus where its compressed
334
+ // bytes live, so the next build can fetch just them with one HTTP Range
335
+ // request
336
+ const found = ppkPath.toLowerCase().endsWith('.ppk')
337
+ ? await (0, zip_range_1.readZipEntryWithLocation)(ppkPath, (name) => hermes_base_1.BUNDLE_ENTRY_NAMES.includes(name)).catch(() => null)
338
+ : null;
339
+ const bundle = found?.data ?? (await (0, hermes_base_1.extractBundleFromArchive)(ppkPath));
333
340
  if (bundle) {
334
- meta.bundleHash = (0, hermes_base_1.sha256Hex)(bundle);
341
+ const bundleHash = (0, hermes_base_1.sha256Hex)(bundle);
342
+ meta.bundleHash = bundleHash;
335
343
  const hbcVersion = (0, hbcTransform_1.getHbcVersion)(bundle) ?? base?.bytecodeVersion;
336
344
  if (hbcVersion != null)
337
345
  meta.bytecodeVersion = hbcVersion;
338
- await (0, hermes_base_1.cachePut)(bundle).catch(() => { });
339
- // where the bundle's compressed bytes live inside the ppk, so the next
340
- // build can fetch just them with one HTTP Range request
341
- const location = await (0, zip_range_1.locateZipEntry)(ppkPath, (name) => hermes_base_1.BUNDLE_ENTRY_NAMES.includes(name)).catch(() => null);
342
- if (location &&
343
- location.compressedSize > 0 &&
344
- (location.compressionMethod === zip_range_1.ZIP_STORED ||
345
- location.compressionMethod === zip_range_1.ZIP_DEFLATED)) {
346
- meta.bundleOffset = location.dataOffset;
347
- meta.bundleCompressedSize = location.compressedSize;
348
- meta.bundleCompression = location.compressionMethod;
349
- }
346
+ await (0, hermes_base_1.cachePut)(bundle, undefined, bundleHash).catch(() => { });
347
+ Object.assign(meta, (0, zip_range_1.bundleLocationFields)(found?.location));
350
348
  }
351
349
  }
352
350
  catch {
@@ -373,8 +371,16 @@ exports.versionCommands = {
373
371
  appId = (await (0, app_1.getSelectedApp)(platform, options.config)).appId;
374
372
  }
375
373
  const nonInteractive = (0, options_1.getBooleanOption)(options, 'no-interactive', false) || (0, utils_1.isNonInteractive)();
376
- const { hash } = await (0, api_1.uploadFile)(fn, undefined, appId);
377
- const bundleMeta = await describePpkBundle(fn, options.hermesBase);
374
+ // Hashing/caching the bundle and asking git for the commit are independent
375
+ // of the upload, so they overlap with it instead of running afterwards.
376
+ // describePpkBundle never rejects (best effort); a failed upload still
377
+ // fails the publish exactly as before.
378
+ const [{ hash }, bundleMeta, commit] = await Promise.all([
379
+ (0, api_1.uploadFile)(fn, undefined, appId),
380
+ describePpkBundle(fn, options.hermesBase),
381
+ (0, git_1.getCommitInfo)(),
382
+ ]);
383
+ const depVersions = (0, dep_versions_1.getDepVersions)();
378
384
  const versionName = name ||
379
385
  (nonInteractive ? '' : await (0, utils_1.question)((0, i18n_1.t)('versionNameQuestion'))) ||
380
386
  (0, i18n_1.t)('unnamed');
@@ -385,8 +391,8 @@ exports.versionCommands = {
385
391
  (nonInteractive ? '' : await (0, utils_1.question)((0, i18n_1.t)('versionDescriptionQuestion'))),
386
392
  metaInfo: metaInfo ??
387
393
  (nonInteractive ? '' : await (0, utils_1.question)((0, i18n_1.t)('versionMetaInfoQuestion'))),
388
- deps: dep_versions_1.depVersions,
389
- commit: await (0, git_1.getCommitInfo)(),
394
+ deps: depVersions,
395
+ commit,
390
396
  // Hermes delta-mode chain metadata (old servers drop unknown fields)
391
397
  ...bundleMeta,
392
398
  });
@@ -408,7 +414,7 @@ exports.versionCommands = {
408
414
  maxPackageVersion,
409
415
  rollout,
410
416
  dryRun,
411
- versionDeps: dep_versions_1.depVersions,
417
+ versionDeps: depVersions,
412
418
  warnDepsChanges: true,
413
419
  },
414
420
  });
@@ -420,7 +426,7 @@ exports.versionCommands = {
420
426
  options: {
421
427
  versionId: id,
422
428
  platform,
423
- versionDeps: dep_versions_1.depVersions,
429
+ versionDeps: depVersions,
424
430
  warnDepsChanges: true,
425
431
  },
426
432
  });
@@ -528,7 +534,8 @@ exports.versionCommands = {
528
534
  if (nonInteractive) {
529
535
  throw new Error((0, i18n_1.t)('packageIdRequired'));
530
536
  }
531
- pkgId = String((await (0, package_1.choosePackage)(String(appId))).id);
537
+ // the package list was already fetched above: no second round trip
538
+ pkgId = String((await (0, package_1.choosePackage)(String(appId), allPkgs)).id);
532
539
  }
533
540
  if (!pkgId) {
534
541
  throw new Error((0, i18n_1.t)('packageIdRequired'));