react-native-update-cli 2.22.5 → 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.
@@ -0,0 +1,466 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.HttpRangeReader = exports.RangeUnsupportedError = exports.ZIP_DEFLATED = exports.ZIP_STORED = void 0;
7
+ exports.locateZipEntry = locateZipEntry;
8
+ exports.readZipEntryWithLocation = readZipEntryWithLocation;
9
+ exports.bundleLocationFields = bundleLocationFields;
10
+ exports.parseContentRange = parseContentRange;
11
+ exports.fetchZipEntryData = fetchZipEntryData;
12
+ exports.parseEndOfCentralDirectory = parseEndOfCentralDirectory;
13
+ exports.openRemoteZip = openRemoteZip;
14
+ exports.readRemoteZipEntry = readRemoteZipEntry;
15
+ // Byte-range access to zip archives.
16
+ //
17
+ // Two halves of the same trick: at publish time `locateZipEntry` records where
18
+ // the bundle's compressed bytes sit inside the ppk (so the server can hand
19
+ // that location to the next build), and at build time `fetchZipEntryData` /
20
+ // `openRemoteZip` read just the bundle of a remote archive through HTTP Range
21
+ // requests instead of downloading the whole ppk / apk / ipa. Every helper
22
+ // throws on anything unexpected; callers fall back to a full download.
23
+ const fs_extra_1 = __importDefault(require("fs-extra"));
24
+ const stream_1 = require("stream");
25
+ const yauzl_1 = require("yauzl");
26
+ const zlib_1 = require("zlib");
27
+ const zip_entries_1 = require("./zip-entries");
28
+ exports.ZIP_STORED = 0;
29
+ exports.ZIP_DEFLATED = 8;
30
+ const LOCAL_HEADER_SIGNATURE = 0x04034b50;
31
+ const LOCAL_HEADER_SIZE = 30;
32
+ /**
33
+ * Exactly what yauzl reads to find the EOCD (22 + 65535 comment + 20 zip64
34
+ * locator), so its first read is a cache hit; small archives fit entirely.
35
+ */
36
+ const TAIL_BYTES = 22 + 0xffff + 20;
37
+ /** minimum span fetched for header reads, so header + directory share a request */
38
+ const CHUNK_BYTES = 64 * 1024;
39
+ /** extra bytes past a hinted entry, covering a longer local extra field */
40
+ const HINT_SLACK_BYTES = 4 * 1024;
41
+ /** Data location of the first entry matching `matches` in a local zip. */
42
+ async function locateZipEntry(zipPath, matches) {
43
+ const found = await openFirstEntry(zipPath, matches);
44
+ if (!found)
45
+ return null;
46
+ found.zipFile.close();
47
+ return locationOfEntry(zipPath, found.entry);
48
+ }
49
+ /**
50
+ * Content and data location of the first matching entry in one pass over the
51
+ * archive (publish needs both: the bundle to hash and cache, its location to
52
+ * report to the server).
53
+ */
54
+ async function readZipEntryWithLocation(zipPath, matches) {
55
+ const found = await openFirstEntry(zipPath, matches);
56
+ if (!found)
57
+ return null;
58
+ let data;
59
+ try {
60
+ data = await (0, zip_entries_1.readEntry)(found.entry, found.zipFile);
61
+ }
62
+ finally {
63
+ found.zipFile.close();
64
+ }
65
+ return { data, location: await locationOfEntry(zipPath, found.entry) };
66
+ }
67
+ async function locationOfEntry(zipPath, entry) {
68
+ const header = Buffer.alloc(LOCAL_HEADER_SIZE);
69
+ const fd = await fs_extra_1.default.open(zipPath, 'r');
70
+ try {
71
+ const { bytesRead } = await fs_extra_1.default.read(fd, header, 0, LOCAL_HEADER_SIZE, entry.relativeOffsetOfLocalHeader);
72
+ if (bytesRead !== LOCAL_HEADER_SIZE) {
73
+ throw new Error('truncated local file header');
74
+ }
75
+ }
76
+ finally {
77
+ await fs_extra_1.default.close(fd);
78
+ }
79
+ if (header.readUInt32LE(0) !== LOCAL_HEADER_SIGNATURE) {
80
+ throw new Error('invalid local file header signature');
81
+ }
82
+ const fileNameLength = header.readUInt16LE(26);
83
+ const extraFieldLength = header.readUInt16LE(28);
84
+ return {
85
+ fileName: entry.fileName,
86
+ dataOffset: entry.relativeOffsetOfLocalHeader +
87
+ LOCAL_HEADER_SIZE +
88
+ fileNameLength +
89
+ extraFieldLength,
90
+ compressedSize: entry.compressedSize,
91
+ uncompressedSize: entry.uncompressedSize,
92
+ compressionMethod: entry.compressionMethod,
93
+ };
94
+ }
95
+ /** Open a local zip and stop at the first matching entry (caller closes). */
96
+ function openFirstEntry(zipPath, matches) {
97
+ return new Promise((resolve, reject) => {
98
+ (0, yauzl_1.open)(zipPath, { lazyEntries: true, autoClose: false }, (err, zipFile) => {
99
+ if (err)
100
+ return reject(err);
101
+ let settled = false;
102
+ zipFile.on('error', (error) => {
103
+ if (!settled) {
104
+ settled = true;
105
+ reject(error);
106
+ }
107
+ });
108
+ zipFile.on('end', () => {
109
+ if (!settled) {
110
+ settled = true;
111
+ zipFile.close();
112
+ resolve(null);
113
+ }
114
+ });
115
+ zipFile.on('entry', (entry) => {
116
+ if (settled)
117
+ return;
118
+ if (matches(entry.fileName)) {
119
+ settled = true;
120
+ resolve({ zipFile, entry });
121
+ return;
122
+ }
123
+ zipFile.readEntry();
124
+ });
125
+ zipFile.readEntry();
126
+ });
127
+ });
128
+ }
129
+ /**
130
+ * The `bundleOffset` / `bundleCompressedSize` / `bundleCompression` fields for
131
+ * version/create and package/create, or nothing when the entry cannot be
132
+ * fetched by a single Range request (unknown, empty or exotic compression).
133
+ */
134
+ function bundleLocationFields(location) {
135
+ if (!location ||
136
+ location.compressedSize <= 0 ||
137
+ (location.compressionMethod !== exports.ZIP_STORED &&
138
+ location.compressionMethod !== exports.ZIP_DEFLATED)) {
139
+ return {};
140
+ }
141
+ return {
142
+ bundleOffset: location.dataOffset,
143
+ bundleCompressedSize: location.compressedSize,
144
+ bundleCompression: location.compressionMethod,
145
+ };
146
+ }
147
+ // ---------------------------------------------------------------------------
148
+ // HTTP Range
149
+ // ---------------------------------------------------------------------------
150
+ /** The server answered a Range request with the whole body (HTTP 200). */
151
+ class RangeUnsupportedError extends Error {
152
+ response;
153
+ constructor(response) {
154
+ super(`HTTP ${response.status} without Content-Range`);
155
+ this.response = response;
156
+ this.name = 'RangeUnsupportedError';
157
+ }
158
+ }
159
+ exports.RangeUnsupportedError = RangeUnsupportedError;
160
+ function parseContentRange(header) {
161
+ const match = /^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(header?.trim() ?? '');
162
+ if (!match)
163
+ return null;
164
+ const [start, end, total] = match.slice(1).map(Number);
165
+ if (end < start || end >= total)
166
+ return null;
167
+ return { start, end, total };
168
+ }
169
+ /** One Range request; `end` is exclusive. Resolves with a 206 response. */
170
+ async function fetchRange(url, start, end) {
171
+ const response = await fetch(url, {
172
+ headers: {
173
+ Range: `bytes=${start}-${end - 1}`,
174
+ 'Accept-Encoding': 'identity',
175
+ },
176
+ });
177
+ if (response.status === 200)
178
+ throw new RangeUnsupportedError(response);
179
+ if (response.status !== 206 || !response.body) {
180
+ await response.body?.cancel().catch(() => { });
181
+ throw new Error(`HTTP ${response.status} for bytes=${start}-${end - 1}`);
182
+ }
183
+ const range = parseContentRange(response.headers.get('content-range'));
184
+ if (!range || range.start !== start || range.end !== end - 1) {
185
+ await response.body.cancel().catch(() => { });
186
+ throw new Error(`unexpected Content-Range ${response.headers.get('content-range')}`);
187
+ }
188
+ return Object.assign(response, { range });
189
+ }
190
+ async function fetchRangeBuffer(url, start, end) {
191
+ const response = await fetchRange(url, start, end);
192
+ const data = Buffer.from(await response.arrayBuffer());
193
+ if (data.length !== end - start) {
194
+ throw new Error(`range returned ${data.length} bytes, expected ${end - start}`);
195
+ }
196
+ return { data, total: response.range.total };
197
+ }
198
+ /**
199
+ * Fetch one entry whose compressed bytes are already located (the ppk's own
200
+ * publish-time report) and decompress it. Returns the raw entry content.
201
+ */
202
+ async function fetchZipEntryData(url, location) {
203
+ const { dataOffset, compressedSize, compressionMethod } = location;
204
+ if (compressionMethod !== exports.ZIP_STORED && compressionMethod !== exports.ZIP_DEFLATED) {
205
+ throw new Error(`unsupported compression method ${compressionMethod}`);
206
+ }
207
+ if (!Number.isInteger(dataOffset) ||
208
+ !Number.isInteger(compressedSize) ||
209
+ dataOffset < 0 ||
210
+ compressedSize <= 0) {
211
+ throw new Error('invalid bundle location');
212
+ }
213
+ const { data, total } = await fetchRangeBuffer(url, dataOffset, dataOffset + compressedSize);
214
+ return {
215
+ data: compressionMethod === exports.ZIP_DEFLATED ? (0, zlib_1.inflateRawSync)(data) : data,
216
+ fetchedBytes: compressedSize,
217
+ totalBytes: total,
218
+ };
219
+ }
220
+ /**
221
+ * yauzl reader over HTTP Range. Header reads (EOCD, central directory, local
222
+ * file headers) are widened to CHUNK_BYTES and cached — adjacent or
223
+ * overlapping chunks are merged so a read never re-fetches bytes it already
224
+ * has — and entry data reuses whatever prefix the cache holds (typically the
225
+ * bytes following the local file header) before requesting the rest.
226
+ */
227
+ class HttpRangeReader extends yauzl_1.RandomAccessReader {
228
+ url;
229
+ totalSize;
230
+ chunks = [];
231
+ /** span a header read inside it should widen to (see `hintEntry`) */
232
+ hint = null;
233
+ requests = 0;
234
+ fetchedBytes = 0;
235
+ constructor(url, totalSize, tail) {
236
+ super();
237
+ this.url = url;
238
+ this.totalSize = totalSize;
239
+ if (tail)
240
+ this.addChunk(tail.start, tail.data);
241
+ }
242
+ /**
243
+ * The next entry to be read: yauzl first reads its local file header, and
244
+ * widening that read to the entry's data makes the data stream a cache hit
245
+ * — one request for header + bundle instead of two. The central directory
246
+ * may understate the local header's extra field, hence the slack.
247
+ */
248
+ hintEntry(entry) {
249
+ const start = entry.relativeOffsetOfLocalHeader;
250
+ const end = start +
251
+ LOCAL_HEADER_SIZE +
252
+ entry.fileNameLength +
253
+ entry.extraFieldLength +
254
+ entry.compressedSize +
255
+ HINT_SLACK_BYTES;
256
+ this.hint = { start, end: Math.min(end, this.totalSize) };
257
+ }
258
+ /** Cache `data` at `start`, merging with any chunk it touches. */
259
+ addChunk(start, data) {
260
+ if (data.length === 0)
261
+ return;
262
+ let lo = start;
263
+ let hi = start + data.length;
264
+ const pieces = [{ start, data }];
265
+ const rest = [];
266
+ for (const chunk of this.chunks) {
267
+ const chunkEnd = chunk.start + chunk.data.length;
268
+ if (chunk.start <= hi && chunkEnd >= lo) {
269
+ pieces.push(chunk);
270
+ lo = Math.min(lo, chunk.start);
271
+ hi = Math.max(hi, chunkEnd);
272
+ }
273
+ else {
274
+ rest.push(chunk);
275
+ }
276
+ }
277
+ if (pieces.length === 1) {
278
+ rest.push(pieces[0]);
279
+ }
280
+ else {
281
+ const merged = Buffer.alloc(hi - lo);
282
+ // the new data is written last so it wins over stale overlaps
283
+ for (const piece of pieces.reverse()) {
284
+ piece.data.copy(merged, piece.start - lo);
285
+ }
286
+ rest.push({ start: lo, data: merged });
287
+ }
288
+ rest.sort((a, b) => a.start - b.start);
289
+ this.chunks = rest;
290
+ }
291
+ /** cached bytes starting exactly at `start`, up to `end` (may be shorter) */
292
+ cachedPrefix(start, end) {
293
+ for (const chunk of this.chunks) {
294
+ const chunkEnd = chunk.start + chunk.data.length;
295
+ if (start >= chunk.start && start < chunkEnd) {
296
+ return chunk.data.subarray(start - chunk.start, Math.min(end, chunkEnd) - chunk.start);
297
+ }
298
+ }
299
+ return null;
300
+ }
301
+ cached(start, end) {
302
+ const prefix = this.cachedPrefix(start, end);
303
+ return prefix && prefix.length === end - start ? prefix : null;
304
+ }
305
+ /** start of the cached chunk holding byte `end - 1`, when there is one */
306
+ cachedSuffixStart(end) {
307
+ for (const chunk of this.chunks) {
308
+ if (end - 1 >= chunk.start && end - 1 < chunk.start + chunk.data.length) {
309
+ return chunk.start;
310
+ }
311
+ }
312
+ return null;
313
+ }
314
+ _readStreamForRange(start, end) {
315
+ const prefix = this.cachedPrefix(start, end);
316
+ if (prefix && prefix.length === end - start)
317
+ return stream_1.Readable.from([prefix]);
318
+ const out = new stream_1.PassThrough();
319
+ if (prefix)
320
+ out.write(prefix);
321
+ const from = start + (prefix?.length ?? 0);
322
+ this.requests++;
323
+ fetchRange(this.url, from, end)
324
+ .then((response) => {
325
+ this.fetchedBytes += end - from;
326
+ const body = stream_1.Readable.fromWeb(response.body);
327
+ body.on('error', (error) => out.destroy(error));
328
+ body.pipe(out);
329
+ })
330
+ .catch((error) => out.destroy(error));
331
+ return out;
332
+ }
333
+ read(buffer, offset, length, position, callback) {
334
+ const hit = this.cached(position, position + length);
335
+ if (hit) {
336
+ hit.copy(buffer, offset);
337
+ setImmediate(() => callback(null, length));
338
+ return;
339
+ }
340
+ // fetch only what the cache lacks: skip a cached prefix, stop at a cached
341
+ // suffix (yauzl's EOCD read may just exceed the tail), and otherwise widen
342
+ // so the next header read is free
343
+ const requestEnd = position + length;
344
+ const from = position + (this.cachedPrefix(position, requestEnd)?.length ?? 0);
345
+ const suffixStart = this.cachedSuffixStart(requestEnd);
346
+ let end;
347
+ if (suffixStart !== null && suffixStart > from) {
348
+ end = suffixStart;
349
+ }
350
+ else {
351
+ end = Math.min(this.totalSize, Math.max(requestEnd, from + CHUNK_BYTES));
352
+ if (this.hint &&
353
+ position >= this.hint.start &&
354
+ position < this.hint.end) {
355
+ end = Math.max(end, this.hint.end);
356
+ }
357
+ }
358
+ this.requests++;
359
+ fetchRangeBuffer(this.url, from, end).then(({ data }) => {
360
+ this.fetchedBytes += data.length;
361
+ this.addChunk(from, data);
362
+ const full = this.cached(position, position + length);
363
+ if (!full) {
364
+ callback(new Error('range read did not cover the requested bytes'));
365
+ return;
366
+ }
367
+ full.copy(buffer, offset);
368
+ callback(null, length);
369
+ }, (error) => callback(error));
370
+ }
371
+ }
372
+ exports.HttpRangeReader = HttpRangeReader;
373
+ /** End-of-central-directory record: where the central directory lives. */
374
+ const EOCD_SIGNATURE = 0x06054b50;
375
+ const EOCD_SIZE = 22;
376
+ /** central directories larger than this are left to yauzl's paged reads */
377
+ const MAX_PREFETCH_BYTES = 8 * 1024 * 1024;
378
+ function parseEndOfCentralDirectory(tail) {
379
+ for (let i = tail.length - EOCD_SIZE; i >= 0; i--) {
380
+ if (tail.readUInt32LE(i) !== EOCD_SIGNATURE)
381
+ continue;
382
+ const commentLength = tail.readUInt16LE(i + 20);
383
+ if (i + EOCD_SIZE + commentLength !== tail.length)
384
+ continue;
385
+ const cdSize = tail.readUInt32LE(i + 12);
386
+ const cdOffset = tail.readUInt32LE(i + 16);
387
+ // zip64 markers: let yauzl resolve the real values itself
388
+ if (cdSize === 0xffffffff || cdOffset === 0xffffffff)
389
+ return null;
390
+ return { cdOffset, cdSize };
391
+ }
392
+ return null;
393
+ }
394
+ /**
395
+ * Open a remote zip by fetching its tail (EOCD + central directory for
396
+ * typical archives) and letting yauzl read the rest on demand.
397
+ */
398
+ async function openRemoteZip(url) {
399
+ const response = await fetch(url, {
400
+ headers: { Range: `bytes=-${TAIL_BYTES}`, 'Accept-Encoding': 'identity' },
401
+ });
402
+ if (!response.ok || !response.body) {
403
+ await response.body?.cancel().catch(() => { });
404
+ throw new Error(`HTTP ${response.status}`);
405
+ }
406
+ if (response.status !== 206)
407
+ return { kind: 'full', response };
408
+ const range = parseContentRange(response.headers.get('content-range'));
409
+ if (!range) {
410
+ await response.body.cancel().catch(() => { });
411
+ throw new Error(`unexpected Content-Range ${response.headers.get('content-range')}`);
412
+ }
413
+ const data = Buffer.from(await response.arrayBuffer());
414
+ if (data.length !== range.end - range.start + 1) {
415
+ throw new Error(`tail returned ${data.length} bytes, expected ${range.end - range.start + 1}`);
416
+ }
417
+ const reader = new HttpRangeReader(url, range.total, {
418
+ start: range.start,
419
+ data,
420
+ });
421
+ reader.requests = 1;
422
+ reader.fetchedBytes = data.length;
423
+ // Large archives (apk / ipa with thousands of files) keep their central
424
+ // directory well before the tail; yauzl would otherwise page it in with one
425
+ // sequential request per CHUNK_BYTES. Fetch the missing part at once.
426
+ const eocd = parseEndOfCentralDirectory(data);
427
+ if (eocd &&
428
+ eocd.cdOffset < range.start &&
429
+ range.start - eocd.cdOffset <= MAX_PREFETCH_BYTES) {
430
+ const { data: directory } = await fetchRangeBuffer(url, eocd.cdOffset, range.start);
431
+ reader.requests++;
432
+ reader.fetchedBytes += directory.length;
433
+ reader.addChunk(eocd.cdOffset, directory);
434
+ }
435
+ const zipFile = await new Promise((resolve, reject) => {
436
+ (0, yauzl_1.fromRandomAccessReader)(reader, range.total, { lazyEntries: true, autoClose: false }, (err, file) => (err ? reject(err) : resolve(file)));
437
+ });
438
+ return { kind: 'zip', zipFile, reader };
439
+ }
440
+ /**
441
+ * Read the first matching entry of an opened remote zip, then close it. With
442
+ * `reader` given, the entry's header and data are fetched in one request.
443
+ */
444
+ function readRemoteZipEntry(zipFile, matches, reader) {
445
+ return new Promise((resolve, reject) => {
446
+ let settled = false;
447
+ const finish = (error, result = null) => {
448
+ if (settled)
449
+ return;
450
+ settled = true;
451
+ zipFile.close();
452
+ error ? reject(error) : resolve(result);
453
+ };
454
+ zipFile.on('error', (error) => finish(error));
455
+ zipFile.on('end', () => finish(null, null));
456
+ zipFile.on('entry', (entry) => {
457
+ if (!matches(entry.fileName)) {
458
+ zipFile.readEntry();
459
+ return;
460
+ }
461
+ reader?.hintEntry(entry);
462
+ (0, zip_entries_1.readEntry)(entry, zipFile).then((data) => finish(null, data), (error) => finish(error));
463
+ });
464
+ zipFile.readEntry();
465
+ });
466
+ }
package/lib/versions.js CHANGED
@@ -19,6 +19,7 @@ const hbcTransform_1 = require("./utils/hbcTransform");
19
19
  const hermes_base_1 = require("./utils/hermes-base");
20
20
  const i18n_1 = require("./utils/i18n");
21
21
  const options_1 = require("./utils/options");
22
+ const zip_range_1 = require("./utils/zip-range");
22
23
  function normalizeDeps(input) {
23
24
  if (!input) {
24
25
  return undefined;
@@ -328,13 +329,21 @@ async function describePpkBundle(ppkPath, base) {
328
329
  // server version — strict, tolerant or too old to know the field — accepts.
329
330
  const meta = {};
330
331
  try {
331
- const bundle = await (0, hermes_base_1.extractBundleFromArchive)(ppkPath);
332
+ // one pass over the ppk: the bundle itself plus where its compressed
333
+ // bytes live, so the next build can fetch just them with one HTTP Range
334
+ // request
335
+ const found = ppkPath.toLowerCase().endsWith('.ppk')
336
+ ? await (0, zip_range_1.readZipEntryWithLocation)(ppkPath, (name) => hermes_base_1.BUNDLE_ENTRY_NAMES.includes(name)).catch(() => null)
337
+ : null;
338
+ const bundle = found?.data ?? (await (0, hermes_base_1.extractBundleFromArchive)(ppkPath));
332
339
  if (bundle) {
333
- meta.bundleHash = (0, hermes_base_1.sha256Hex)(bundle);
340
+ const bundleHash = (0, hermes_base_1.sha256Hex)(bundle);
341
+ meta.bundleHash = bundleHash;
334
342
  const hbcVersion = (0, hbcTransform_1.getHbcVersion)(bundle) ?? base?.bytecodeVersion;
335
343
  if (hbcVersion != null)
336
344
  meta.bytecodeVersion = hbcVersion;
337
- await (0, hermes_base_1.cachePut)(bundle).catch(() => { });
345
+ await (0, hermes_base_1.cachePut)(bundle, undefined, bundleHash).catch(() => { });
346
+ Object.assign(meta, (0, zip_range_1.bundleLocationFields)(found?.location));
338
347
  }
339
348
  }
340
349
  catch {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-update-cli",
3
- "version": "2.22.5",
3
+ "version": "2.22.7",
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",