react-native-update-cli 2.24.2 → 2.26.0

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 (98) hide show
  1. package/README.md +12 -5
  2. package/README.zh-CN.md +12 -5
  3. package/cli.json +7 -1
  4. package/lib/api.d.ts +2 -0
  5. package/lib/api.js +63 -18
  6. package/lib/app.js +25 -3
  7. package/lib/bin.js +39 -45
  8. package/lib/bundle-runner.d.ts +45 -1
  9. package/lib/bundle-runner.js +303 -34
  10. package/lib/bundle.d.ts +1 -1
  11. package/lib/bundle.js +23 -7
  12. package/lib/commands.d.ts +6 -0
  13. package/lib/commands.js +65 -0
  14. package/lib/locales/en.d.ts +7 -14
  15. package/lib/locales/en.js +10 -17
  16. package/lib/locales/zh.d.ts +7 -13
  17. package/lib/locales/zh.js +10 -16
  18. package/lib/package.js +4 -0
  19. package/lib/provider.d.ts +1 -1
  20. package/lib/provider.js +3 -1
  21. package/lib/symbolicate.js +7 -2
  22. package/lib/types.d.ts +1 -0
  23. package/lib/user.js +6 -0
  24. package/lib/utils/add-gitignore.js +7 -1
  25. package/lib/utils/dep-versions.d.ts +7 -0
  26. package/lib/utils/dep-versions.js +78 -26
  27. package/lib/utils/git.js +9 -6
  28. package/lib/utils/hbcTransform.d.ts +15 -0
  29. package/lib/utils/hbcTransform.js +22 -0
  30. package/lib/utils/hermes-base.d.ts +61 -6
  31. package/lib/utils/hermes-base.js +328 -46
  32. package/lib/utils/hermes-literals.d.ts +51 -0
  33. package/lib/utils/hermes-literals.js +210 -0
  34. package/lib/utils/i18n.d.ts +5 -0
  35. package/lib/utils/i18n.js +14 -1
  36. package/lib/utils/index.d.ts +2 -1
  37. package/lib/utils/index.js +9 -4
  38. package/lib/utils/latest-version/index.js +8 -0
  39. package/lib/utils/runtime.d.ts +21 -0
  40. package/lib/utils/runtime.js +138 -5
  41. package/lib/utils/zip-range.js +3 -2
  42. package/lib/versions.js +14 -4
  43. package/package.json +6 -3
  44. package/lib/index.d.ts +0 -1
  45. package/lib/index.js +0 -17
  46. package/src/api.ts +0 -470
  47. package/src/app.ts +0 -241
  48. package/src/auto-update.ts +0 -647
  49. package/src/bin-cresc.ts +0 -8
  50. package/src/bin.ts +0 -115
  51. package/src/bundle-pack.ts +0 -61
  52. package/src/bundle-runner.ts +0 -1430
  53. package/src/bundle.ts +0 -371
  54. package/src/cache.ts +0 -20
  55. package/src/diff.ts +0 -1010
  56. package/src/exports.ts +0 -17
  57. package/src/index.ts +0 -1
  58. package/src/install.ts +0 -50
  59. package/src/locales/en.ts +0 -257
  60. package/src/locales/zh.ts +0 -234
  61. package/src/native-package.ts +0 -338
  62. package/src/package.ts +0 -482
  63. package/src/provider.ts +0 -294
  64. package/src/symbolicate.ts +0 -164
  65. package/src/types.ts +0 -150
  66. package/src/user.ts +0 -39
  67. package/src/utils/add-gitignore.ts +0 -35
  68. package/src/utils/app-info-parser/aab.ts +0 -241
  69. package/src/utils/app-info-parser/apk.ts +0 -92
  70. package/src/utils/app-info-parser/app.ts +0 -7
  71. package/src/utils/app-info-parser/index.ts +0 -54
  72. package/src/utils/app-info-parser/ipa.ts +0 -109
  73. package/src/utils/app-info-parser/resource-finder.ts +0 -508
  74. package/src/utils/app-info-parser/utils.ts +0 -161
  75. package/src/utils/app-info-parser/xml-parser/binary.ts +0 -693
  76. package/src/utils/app-info-parser/xml-parser/manifest.ts +0 -228
  77. package/src/utils/app-info-parser/zip.ts +0 -108
  78. package/src/utils/check-lockfile.ts +0 -93
  79. package/src/utils/check-plugin.ts +0 -38
  80. package/src/utils/command-result.ts +0 -24
  81. package/src/utils/constants.ts +0 -25
  82. package/src/utils/dep-versions.ts +0 -83
  83. package/src/utils/git.ts +0 -71
  84. package/src/utils/hbcTransform.ts +0 -649
  85. package/src/utils/hermes-base.ts +0 -1137
  86. package/src/utils/http-helper.ts +0 -152
  87. package/src/utils/i18n.ts +0 -39
  88. package/src/utils/index.ts +0 -698
  89. package/src/utils/latest-version/index.ts +0 -573
  90. package/src/utils/options.ts +0 -78
  91. package/src/utils/plugin-config.ts +0 -32
  92. package/src/utils/runtime.ts +0 -187
  93. package/src/utils/slim-sourcemap.ts +0 -105
  94. package/src/utils/zip-entries.ts +0 -209
  95. package/src/utils/zip-options.ts +0 -178
  96. package/src/utils/zip-range.ts +0 -727
  97. package/src/utils/zip-raw-writer.ts +0 -247
  98. package/src/versions.ts +0 -892
package/src/diff.ts DELETED
@@ -1,1010 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import * as fs from 'fs-extra';
3
- import { npm, yarn } from 'global-dirs';
4
- import os from 'os';
5
- import path from 'path';
6
- import type { Entry, ZipFile as YauzlZipFile } from 'yauzl';
7
- import { ZipFile as YazlZipFile } from 'yazl';
8
- import { resolveNativePackageEntry } from './native-package';
9
- import type { CommandContext, Platform } from './types';
10
- import { translateOptions } from './utils';
11
- import { isPPKBundleFileName, scriptName, tempDir } from './utils/constants';
12
- import {
13
- type HbcTransformMeta,
14
- transformHbcFile,
15
- transformHbcWithLayoutInPlace,
16
- tryTransformPair,
17
- tryTransformPairFiles,
18
- } from './utils/hbcTransform';
19
- import { t } from './utils/i18n';
20
- import {
21
- enumZipEntries,
22
- readEntry,
23
- readEntryPrefix,
24
- writeEntry,
25
- } from './utils/zip-entries';
26
- import {
27
- ZIP_ENTRY_SNIFF_BYTES,
28
- zipOptionsForManifestEntry,
29
- zipOptionsForPatchEntry,
30
- zipOptionsForPayloadEntry,
31
- } from './utils/zip-options';
32
-
33
- type Diff = (
34
- oldSource?: Buffer,
35
- newSource?: Buffer,
36
- ) => Buffer | Promise<Buffer>;
37
- type Patch = (oldSource: Buffer, diffData: Buffer) => Buffer;
38
- type DiffStream = (
39
- oldPath: string,
40
- newPath: string,
41
- outDiffPath: string,
42
- ) => unknown | Promise<unknown>;
43
- type PatchStream = (
44
- oldPath: string,
45
- diffPath: string,
46
- outNewPath: string,
47
- ) => unknown | Promise<unknown>;
48
- type HdiffModule = {
49
- diff?: Diff;
50
- patch?: Patch;
51
- diffStream?: DiffStream;
52
- patchStream?: PatchStream;
53
- diffSingleStream?: DiffStream;
54
- patchSingleStream?: PatchStream;
55
- capabilities?: {
56
- diffStreamVerifiesOutput?: boolean;
57
- diffSingleStreamVerifiesOutput?: boolean;
58
- diffWindowVerifiesOutput?: boolean;
59
- };
60
- };
61
- type BundleSource =
62
- | { kind: 'buffer'; data: Buffer }
63
- | {
64
- kind: 'file';
65
- path: string;
66
- size: number;
67
- materializeDurationMs: number;
68
- };
69
- type BundlePatch =
70
- | { kind: 'buffer'; data: Buffer }
71
- | { kind: 'file'; path: string };
72
- type BundlePatchResult = {
73
- patch: BundlePatch;
74
- hbcTransform?: HbcTransformMeta;
75
- };
76
- type EntryMap = Record<string, ZipEntryContent & { fileName: string }>;
77
- /** 内容键(见 zipEntryContentKey)→ 原包路径 */
78
- type ContentMap = Record<string, string>;
79
- type ZipEntryContent = Pick<Entry, 'crc32' | 'uncompressedSize'>;
80
- type CopyMap = Record<string, string>;
81
- type DiffTarget =
82
- | { kind: 'ppk' }
83
- | {
84
- kind: 'package';
85
- platform: Platform;
86
- };
87
- type DiffCommandConfig = {
88
- diffFnName: string;
89
- target: DiffTarget;
90
- };
91
-
92
- export { enumZipEntries, readEntry };
93
-
94
- /**
95
- * 判定两个 zip entry 内容相同的键:crc32 单独并不足以证明内容一致(32 位
96
- * 校验和碰撞并不罕见,尤其是长度不同的文件),必须同时要求解压后长度相等。
97
- * 仅用于生成端匹配,manifest 里的 copies / copiesCrc 格式不变。
98
- */
99
- export function zipEntryContentKey(entry: ZipEntryContent): string {
100
- return `${entry.crc32}:${entry.uncompressedSize}`;
101
- }
102
-
103
- export function zipEntriesHaveSameContent(
104
- left: ZipEntryContent,
105
- right: ZipEntryContent,
106
- ): boolean {
107
- return (
108
- left.crc32 === right.crc32 &&
109
- left.uncompressedSize === right.uncompressedSize
110
- );
111
- }
112
-
113
- const loadModule = <T>(pkgName: string): T | undefined => {
114
- const nodePathDirs = (process.env.NODE_PATH || '')
115
- .split(path.delimiter)
116
- .filter(Boolean);
117
- const resolvePaths = ['.', ...nodePathDirs, npm.packages, yarn.packages];
118
-
119
- try {
120
- const resolved = require.resolve(pkgName, { paths: resolvePaths });
121
- return require(resolved) as T;
122
- } catch {}
123
-
124
- return undefined;
125
- };
126
-
127
- const hdiff = loadModule<HdiffModule>('node-hdiffpatch');
128
-
129
- function basename(fn: string): string | undefined {
130
- const m = /^(.+\/)[^/]+\/?$/.exec(fn);
131
- return m?.[1];
132
- }
133
-
134
- function createOutputZip(output: string) {
135
- fs.ensureDirSync(path.dirname(output));
136
- const zipfile = new YazlZipFile();
137
- const writeStream = fs.createWriteStream(output);
138
- const writePromise = new Promise<void>((resolve, reject) => {
139
- zipfile.outputStream.on('error', reject);
140
- // without this, a full disk / read-only target left the promise pending
141
- writeStream.on('error', reject);
142
- zipfile.outputStream.pipe(writeStream).on('close', () => {
143
- resolve(void 0);
144
- });
145
- });
146
- // 失败时释放输出 fd 并删掉半成品,避免残留一个截断的 patch 包
147
- const abort = async () => {
148
- writePromise.catch(() => {});
149
- zipfile.outputStream.unpipe(writeStream);
150
- // yazl 的 outputStream 类型声明缺 destroy,运行时是 PassThrough
151
- (zipfile.outputStream as unknown as { destroy(): void }).destroy();
152
- if (!writeStream.closed) {
153
- // 等 fd 真正关闭再删文件,避免 Windows 上删除被占用文件失败
154
- await new Promise<void>((resolve) => {
155
- writeStream.once('close', () => resolve());
156
- if (!writeStream.destroyed) {
157
- writeStream.destroy();
158
- }
159
- });
160
- }
161
- await fs.rm(output, { force: true });
162
- };
163
- return { zipfile, writePromise, abort };
164
- }
165
-
166
- /**
167
- * 打开输出包,执行 build 填充条目并返回 manifest,最后写入 __diff.json
168
- * 收尾。build 或收尾任何一步失败都会关闭输出流、删除半成品并重新抛出。
169
- */
170
- async function writeDiffZip(
171
- output: string,
172
- build: (zipfile: YazlZipFile) => Promise<Record<string, unknown>>,
173
- ) {
174
- const { zipfile, writePromise, abort } = createOutputZip(output);
175
- try {
176
- const manifest = await build(zipfile);
177
- await finishDiffZip(zipfile, writePromise, manifest);
178
- } catch (error) {
179
- await abort();
180
- throw error;
181
- }
182
- }
183
-
184
- // baseline patch 小于该值时跳过变换尝试:节省一次 diff 的 CPU,
185
- // 且此时变换收益上限(~25%)也抵不过元数据开销
186
- const HBC_TRANSFORM_MIN_BASELINE_BYTES = 64 * 1024;
187
-
188
- type BundleDiffOptions = {
189
- hbcTransform?: boolean;
190
- patchFn?: Patch;
191
- /** 测试用:覆写跳过变换尝试的 baseline 大小下限 */
192
- minBaselineBytes?: number;
193
- /**
194
- * bundle 尺寸达到该字节数时改走流式 diff:生成端内存 O(块匹配),
195
- * 彻底绕开内存 diff 的后缀数组峰值(~6× bundle)。0/未设 = 关闭。
196
- * 优先使用 single 格式流式生成(diffSingleStream,产物与 diff() 同格式,
197
- * 老客户端可直接应用,任何轨道均可开启);仅当 single 流式不可用时回退
198
- * HDIFF13(diffStream)——该格式老客户端不识别,只应在 v2 轨道下开启。
199
- */
200
- streamThresholdBytes?: number;
201
- diffStreamFn?: DiffStream;
202
- patchStreamFn?: PatchStream;
203
- /** 流式产物是否为 single 格式(决定 baseline 轨道是否可用) */
204
- streamEmitsSingleFormat?: boolean;
205
- /** diffStreamFn 内部已经完整 apply-and-compare,可跳过重复还原 */
206
- streamOutputVerified?: boolean;
207
- onDiffPhase?: (metric: {
208
- phase: 'materialize' | 'diff' | 'verify';
209
- durationMs: number;
210
- inputBytes: number;
211
- outputBytes?: number;
212
- skipped?: boolean;
213
- }) => void;
214
- };
215
-
216
- function reportDiffPhase(
217
- options: BundleDiffOptions,
218
- metric: Parameters<NonNullable<BundleDiffOptions['onDiffPhase']>>[0],
219
- ) {
220
- try {
221
- options.onDiffPhase?.(metric);
222
- } catch {
223
- // Observability must never break patch generation.
224
- }
225
- }
226
-
227
- const bundleSourceSize = (source: BundleSource) =>
228
- source.kind === 'buffer' ? source.data.length : source.size;
229
-
230
- const bundleSourceBuffer = async (source: BundleSource) =>
231
- source.kind === 'buffer' ? source.data : fs.readFile(source.path);
232
-
233
- async function bundleSourceFile(
234
- source: BundleSource,
235
- outputPath: string,
236
- ): Promise<string> {
237
- if (source.kind === 'file') {
238
- return source.path;
239
- }
240
- await fs.writeFile(outputPath, source.data);
241
- return outputPath;
242
- }
243
-
244
- async function hashFile(filePath: string): Promise<string> {
245
- const hash = createHash('sha256');
246
- for await (const chunk of fs.createReadStream(filePath)) {
247
- hash.update(chunk as Buffer);
248
- }
249
- return hash.digest('hex');
250
- }
251
-
252
- async function filesEqual(leftPath: string, rightPath: string) {
253
- const [leftStat, rightStat] = await Promise.all([
254
- fs.stat(leftPath),
255
- fs.stat(rightPath),
256
- ]);
257
- if (leftStat.size !== rightStat.size) {
258
- return false;
259
- }
260
- const [leftHash, rightHash] = await Promise.all([
261
- hashFile(leftPath),
262
- hashFile(rightPath),
263
- ]);
264
- return leftHash === rightHash;
265
- }
266
-
267
- /**
268
- * 大 bundle 流式路径:bundle 直接从 ZIP entry 落盘后传入 native,
269
- * 避免 old/new/restored 的整块 Buffer 副本。HBC 变换 T/T⁻¹ 也在文件上
270
- * 按段定位改写(transformHbcFile),全程不持有整个 bundle。native 已
271
- * 自校验的普通产物不再重复 patch;自定义/变换路径仍保留 round-trip 校验。
272
- */
273
- async function buildStreamBundlePatch(
274
- originSource: BundleSource,
275
- newSource: BundleSource,
276
- options: BundleDiffOptions,
277
- workRoot: string,
278
- ): Promise<BundlePatchResult> {
279
- const diffStreamFn = options.diffStreamFn;
280
- const patchStreamFn = options.patchStreamFn;
281
- if (!diffStreamFn || !patchStreamFn) {
282
- throw new Error(
283
- 'stream diff requires diffStream/patchStream from node-hdiffpatch',
284
- );
285
- }
286
-
287
- const tempRoot = fs.mkdtempSync(path.join(workRoot, 'stream-'));
288
- const inputBytes =
289
- bundleSourceSize(originSource) + bundleSourceSize(newSource);
290
- const extractionDurationMs =
291
- (originSource.kind === 'file' ? originSource.materializeDurationMs : 0) +
292
- (newSource.kind === 'file' ? newSource.materializeDurationMs : 0);
293
- let phaseStartedAt = performance.now();
294
- const rawOldFile = await bundleSourceFile(
295
- originSource,
296
- path.join(tempRoot, 'old.bin'),
297
- );
298
- const rawNewFile = await bundleSourceFile(
299
- newSource,
300
- path.join(tempRoot, 'new.bin'),
301
- );
302
- // 变换走文件版 T:只读头部选布局、按段定位改写,不把 bundle 读进内存
303
- const transformedOldFile = path.join(tempRoot, 'old-transformed.bin');
304
- const transformedNewFile = path.join(tempRoot, 'new-transformed.bin');
305
- const pair = options.hbcTransform
306
- ? await tryTransformPairFiles(
307
- rawOldFile,
308
- rawNewFile,
309
- transformedOldFile,
310
- transformedNewFile,
311
- )
312
- : null;
313
- reportDiffPhase(options, {
314
- phase: 'materialize',
315
- durationMs: extractionDurationMs + performance.now() - phaseStartedAt,
316
- inputBytes,
317
- });
318
-
319
- // 与内存路径同一约束:变换候选连同元数据开销必须比 baseline 更小才采用,
320
- // 因此变换命中时两个候选都要生成再比较。
321
- phaseStartedAt = performance.now();
322
- const rawPatchFile = path.join(tempRoot, 'patch-raw.bin');
323
- await diffStreamFn(rawOldFile, rawNewFile, rawPatchFile);
324
- let patchFile = rawPatchFile;
325
- let patchBytes = (await fs.stat(rawPatchFile)).size;
326
- let chosenPair: typeof pair = null;
327
- if (pair) {
328
- const transformedPatchFile = path.join(tempRoot, 'patch-transformed.bin');
329
- await diffStreamFn(
330
- transformedOldFile,
331
- transformedNewFile,
332
- transformedPatchFile,
333
- );
334
- const transformedPatchBytes = (await fs.stat(transformedPatchFile)).size;
335
- const metaOverhead = Buffer.byteLength(JSON.stringify(pair.meta));
336
- if (transformedPatchBytes + metaOverhead < patchBytes) {
337
- patchFile = transformedPatchFile;
338
- patchBytes = transformedPatchBytes;
339
- chosenPair = pair;
340
- }
341
- }
342
- reportDiffPhase(options, {
343
- phase: 'diff',
344
- durationMs: performance.now() - phaseStartedAt,
345
- inputBytes,
346
- outputBytes: patchBytes,
347
- });
348
-
349
- // 变换路径必须验证 T⁻¹ 和元数据;未声明自校验的自定义 diff 也保留
350
- // round-trip。node-hdiffpatch native 普通路径已经在返回前完整验证。
351
- if (chosenPair || !options.streamOutputVerified) {
352
- phaseStartedAt = performance.now();
353
- const restoredFile = path.join(tempRoot, 'restored.bin');
354
- await patchStreamFn(
355
- chosenPair ? transformedOldFile : rawOldFile,
356
- patchFile,
357
- restoredFile,
358
- );
359
- if (chosenPair) {
360
- // T⁻¹ 同样在文件上按段改写,再以流式哈希比对,内存与 bundle 大小无关
361
- const restoredRawFile = path.join(tempRoot, 'restored-raw.bin');
362
- const inverted = await transformHbcFile(
363
- restoredFile,
364
- restoredRawFile,
365
- chosenPair.layout,
366
- true,
367
- );
368
- if (!inverted || !(await filesEqual(restoredRawFile, rawNewFile))) {
369
- throw new Error('stream diff round-trip verification failed');
370
- }
371
- } else if (!(await filesEqual(restoredFile, rawNewFile))) {
372
- throw new Error('stream diff round-trip verification failed');
373
- }
374
- reportDiffPhase(options, {
375
- phase: 'verify',
376
- durationMs: performance.now() - phaseStartedAt,
377
- inputBytes,
378
- outputBytes: patchBytes,
379
- });
380
- } else {
381
- reportDiffPhase(options, {
382
- phase: 'verify',
383
- durationMs: 0,
384
- inputBytes,
385
- outputBytes: patchBytes,
386
- skipped: true,
387
- });
388
- }
389
-
390
- return {
391
- patch: { kind: 'file', path: patchFile },
392
- ...(chosenPair ? { hbcTransform: chosenPair.meta } : {}),
393
- };
394
- }
395
-
396
- /**
397
- * 生成 bundle patch:默认现状路径;开启 hbcTransform 时对 Hermes bundle
398
- * 做双候选择优(baseline vs 变换域 + 元数据开销),且变换候选必须通过
399
- * 本地 round-trip 还原自检才会被采用——收益永不为负,未知格式天然安全。
400
- */
401
- async function buildBundlePatch(
402
- diffFn: Diff,
403
- originSource: BundleSource | undefined,
404
- newSource: BundleSource,
405
- options: BundleDiffOptions,
406
- workRoot: string,
407
- ): Promise<BundlePatchResult> {
408
- if (
409
- options.streamThresholdBytes &&
410
- originSource &&
411
- Math.max(bundleSourceSize(originSource), bundleSourceSize(newSource)) >=
412
- options.streamThresholdBytes
413
- ) {
414
- return buildStreamBundlePatch(originSource, newSource, options, workRoot);
415
- }
416
-
417
- const [originBuffer, newBuffer] = await Promise.all([
418
- originSource
419
- ? bundleSourceBuffer(originSource)
420
- : Promise.resolve(undefined),
421
- bundleSourceBuffer(newSource),
422
- ]);
423
- const baseline = await diffFn(originBuffer, newBuffer);
424
- if (
425
- !options.hbcTransform ||
426
- !options.patchFn ||
427
- !originBuffer ||
428
- baseline.length <
429
- (options.minBaselineBytes ?? HBC_TRANSFORM_MIN_BASELINE_BYTES)
430
- ) {
431
- return { patch: { kind: 'buffer', data: baseline } };
432
- }
433
-
434
- const pair = tryTransformPair(originBuffer, newBuffer);
435
- if (!pair) {
436
- return { patch: { kind: 'buffer', data: baseline } };
437
- }
438
-
439
- try {
440
- const candidate = await diffFn(pair.tOld, pair.tNew);
441
- const metaOverhead = Buffer.byteLength(JSON.stringify(pair.meta));
442
- if (candidate.length + metaOverhead >= baseline.length) {
443
- return { patch: { kind: 'buffer', data: baseline } };
444
- }
445
-
446
- // patched 是 patchFn 新返回的 Buffer,原地做 T⁻¹ 省去一次整块拷贝
447
- const patched = options.patchFn(pair.tOld, candidate);
448
- if (
449
- !transformHbcWithLayoutInPlace(patched, pair.layout, true) ||
450
- Buffer.compare(patched, newBuffer) !== 0
451
- ) {
452
- console.warn(t('hbcTransformRoundTripFailed'));
453
- return { patch: { kind: 'buffer', data: baseline } };
454
- }
455
- return {
456
- patch: { kind: 'buffer', data: candidate },
457
- hbcTransform: pair.meta,
458
- };
459
- } catch {
460
- return { patch: { kind: 'buffer', data: baseline } };
461
- }
462
- }
463
-
464
- async function addBundlePatch(
465
- zipfile: YazlZipFile,
466
- entry: Entry,
467
- nextZipfile: YauzlZipFile,
468
- diffFn: Diff,
469
- originSource: BundleSource | undefined,
470
- bundleOptions: BundleDiffOptions,
471
- hbcTransformMetas: Record<string, HbcTransformMeta>,
472
- workRoot: string,
473
- ) {
474
- const shouldStream =
475
- !!bundleOptions.streamThresholdBytes &&
476
- !!originSource &&
477
- Math.max(bundleSourceSize(originSource), entry.uncompressedSize) >=
478
- bundleOptions.streamThresholdBytes;
479
- let newSource: BundleSource;
480
- if (shouldStream) {
481
- const nextRoot = fs.mkdtempSync(path.join(workRoot, 'next-'));
482
- const nextPath = path.join(nextRoot, 'bundle.bin');
483
- const startedAt = performance.now();
484
- await writeEntry(entry, nextZipfile, nextPath);
485
- newSource = {
486
- kind: 'file',
487
- path: nextPath,
488
- size: entry.uncompressedSize,
489
- materializeDurationMs: performance.now() - startedAt,
490
- };
491
- } else {
492
- newSource = { kind: 'buffer', data: await readEntry(entry, nextZipfile) };
493
- }
494
-
495
- const { patch, hbcTransform } = await buildBundlePatch(
496
- diffFn,
497
- originSource,
498
- newSource,
499
- bundleOptions,
500
- workRoot,
501
- );
502
- const patchEntryName = `${entry.fileName}.patch`;
503
- if (hbcTransform) {
504
- hbcTransformMetas[patchEntryName] = hbcTransform;
505
- }
506
- if (patch.kind === 'file') {
507
- zipfile.addFile(patch.path, patchEntryName, zipOptionsForPatchEntry());
508
- } else {
509
- zipfile.addBuffer(patch.data, patchEntryName, zipOptionsForPatchEntry());
510
- }
511
- }
512
-
513
- async function readOriginBundleSource(
514
- entry: Entry,
515
- zipFile: YauzlZipFile,
516
- bundleOptions: BundleDiffOptions,
517
- workRoot: string,
518
- ): Promise<BundleSource> {
519
- if (!bundleOptions.streamThresholdBytes) {
520
- return { kind: 'buffer', data: await readEntry(entry, zipFile) };
521
- }
522
- const originRoot = fs.mkdtempSync(path.join(workRoot, 'origin-'));
523
- const originPath = path.join(originRoot, 'bundle.bin');
524
- const startedAt = performance.now();
525
- await writeEntry(entry, zipFile, originPath);
526
- return {
527
- kind: 'file',
528
- path: originPath,
529
- size: entry.uncompressedSize,
530
- materializeDurationMs: performance.now() - startedAt,
531
- };
532
- }
533
-
534
- async function addFileFromZipEntry(
535
- zipfile: YazlZipFile,
536
- entry: Entry,
537
- nextZipfile: YauzlZipFile,
538
- ) {
539
- const entryPrefix = await readEntryPrefix(
540
- entry,
541
- nextZipfile,
542
- ZIP_ENTRY_SNIFF_BYTES,
543
- );
544
- await new Promise<void>((resolve, reject) => {
545
- nextZipfile.openReadStream(entry, (err, readStream) => {
546
- if (err) {
547
- return reject(err);
548
- }
549
- if (!readStream) {
550
- return reject(new Error(`Unable to read zip entry: ${entry.fileName}`));
551
- }
552
- zipfile.addReadStream(
553
- readStream,
554
- entry.fileName,
555
- zipOptionsForPayloadEntry(entry.fileName, entryPrefix),
556
- );
557
- readStream.on('error', reject);
558
- readStream.on('end', () => {
559
- resolve(void 0);
560
- });
561
- });
562
- });
563
- }
564
-
565
- function finishDiffZip(
566
- zipfile: YazlZipFile,
567
- writePromise: Promise<void>,
568
- manifest: Record<string, unknown>,
569
- ) {
570
- const diffManifest = Buffer.from(JSON.stringify(manifest));
571
- zipfile.addBuffer(
572
- diffManifest,
573
- '__diff.json',
574
- zipOptionsForManifestEntry(diffManifest.length),
575
- );
576
- zipfile.end();
577
- return writePromise;
578
- }
579
-
580
- async function diffFromPPK(
581
- origin: string,
582
- next: string,
583
- output: string,
584
- diffFn: Diff,
585
- bundleOptions: BundleDiffOptions,
586
- workRoot: string,
587
- ) {
588
- const originEntries: EntryMap = {};
589
- const originMap: ContentMap = {};
590
-
591
- let originSource: BundleSource | undefined;
592
-
593
- await enumZipEntries(origin, async (entry, zipFile) => {
594
- originEntries[entry.fileName] = entry;
595
- if (!/\/$/.test(entry.fileName)) {
596
- // isFile
597
- originMap[zipEntryContentKey(entry)] = entry.fileName;
598
-
599
- if (isPPKBundleFileName(entry.fileName)) {
600
- // This is source.
601
- originSource = await readOriginBundleSource(
602
- entry,
603
- zipFile,
604
- bundleOptions,
605
- workRoot,
606
- );
607
- }
608
- }
609
- });
610
-
611
- if (!originSource) {
612
- throw new Error(t('bundleFileNotFound'));
613
- }
614
-
615
- const copies: CopyMap = {};
616
- const bundleSource = originSource;
617
-
618
- await writeDiffZip(output, async (zipfile) => {
619
- const addedEntry: Record<string, true> = {};
620
-
621
- function addEntry(fn: string) {
622
- //console.log(fn);
623
- if (!fn || addedEntry[fn]) {
624
- return;
625
- }
626
- addedEntry[fn] = true;
627
- const base = basename(fn);
628
- if (base) {
629
- addEntry(base);
630
- }
631
- zipfile.addEmptyDirectory(fn);
632
- }
633
-
634
- const newEntries: EntryMap = {};
635
- const hbcTransformMetas: Record<string, HbcTransformMeta> = {};
636
-
637
- await enumZipEntries(next, async (entry, nextZipfile) => {
638
- newEntries[entry.fileName] = entry;
639
-
640
- if (/\/$/.test(entry.fileName)) {
641
- // Directory
642
- if (!originEntries[entry.fileName]) {
643
- addEntry(entry.fileName);
644
- }
645
- } else if (isPPKBundleFileName(entry.fileName)) {
646
- await addBundlePatch(
647
- zipfile,
648
- entry,
649
- nextZipfile,
650
- diffFn,
651
- bundleSource,
652
- bundleOptions,
653
- hbcTransformMetas,
654
- workRoot,
655
- );
656
- } else {
657
- // If same file.
658
- const originEntry = originEntries[entry.fileName];
659
- if (originEntry && zipEntriesHaveSameContent(originEntry, entry)) {
660
- // ignore
661
- return;
662
- }
663
-
664
- // If moved from other place
665
- const movedFrom = originMap[zipEntryContentKey(entry)];
666
- if (movedFrom) {
667
- const base = basename(entry.fileName);
668
- if (base && !originEntries[base]) {
669
- addEntry(base);
670
- }
671
- copies[entry.fileName] = movedFrom;
672
- return;
673
- }
674
-
675
- // New file.
676
- const basePath = basename(entry.fileName);
677
- if (basePath) {
678
- addEntry(basePath);
679
- }
680
-
681
- await addFileFromZipEntry(zipfile, entry, nextZipfile);
682
- }
683
- });
684
-
685
- const deletes: Record<string, 1> = {};
686
-
687
- for (const k in originEntries) {
688
- if (!newEntries[k]) {
689
- console.log(t('deleteFile', { file: k }));
690
- deletes[k] = 1;
691
- }
692
- }
693
-
694
- return {
695
- copies,
696
- deletes,
697
- ...(Object.keys(hbcTransformMetas).length
698
- ? { hbcTransform: hbcTransformMetas }
699
- : {}),
700
- };
701
- });
702
- }
703
-
704
- async function diffFromPackage(
705
- origin: string,
706
- next: string,
707
- output: string,
708
- diffFn: Diff,
709
- platform: Platform,
710
- bundleOptions: BundleDiffOptions,
711
- workRoot: string,
712
- ) {
713
- // 路径 → 内容键(crc32 + 解压后长度)
714
- const originEntries: Record<string, string> = {};
715
- const originMap: ContentMap = {};
716
-
717
- let originSource: BundleSource | undefined;
718
-
719
- // Content checksum (CRC32) for every copied entry, keyed by target path.
720
- // Two consumers on the client: locating a file by content when its origin
721
- // path is not present verbatim on device (APK baseline diff applied on an
722
- // AAB/split-apk install whose res/ paths were shortened), and verifying
723
- // that a path-matched file still has the expected bytes before copying
724
- // (BUNDLEHASH_MIGRATION.md §4.2.1 — a rebuilt binary may keep the path but
725
- // drift the content; mismatch must fall back to full instead of silently
726
- // installing a wrong resource).
727
- const copiesCrc: Record<string, number> = {};
728
-
729
- await enumZipEntries(origin, async (entry, zipFile) => {
730
- if (!/\/$/.test(entry.fileName)) {
731
- const resolvedEntry = resolveNativePackageEntry(platform, entry.fileName);
732
- if (!resolvedEntry) {
733
- return;
734
- }
735
- const fn = resolvedEntry.diffPath;
736
-
737
- //console.log(fn);
738
- // isFile
739
- const contentKey = zipEntryContentKey(entry);
740
- originEntries[fn] = contentKey;
741
- originMap[contentKey] = fn;
742
-
743
- if (resolvedEntry.kind === 'bundle') {
744
- // This is source.
745
- originSource = await readOriginBundleSource(
746
- entry,
747
- zipFile,
748
- bundleOptions,
749
- workRoot,
750
- );
751
- }
752
- }
753
- });
754
-
755
- if (!originSource) {
756
- throw new Error(t('bundleFileNotFound'));
757
- }
758
-
759
- const copies: CopyMap = {};
760
- const bundleSource = originSource;
761
-
762
- await writeDiffZip(output, async (zipfile) => {
763
- const hbcTransformMetas: Record<string, HbcTransformMeta> = {};
764
-
765
- await enumZipEntries(next, async (entry, nextZipfile) => {
766
- if (/\/$/.test(entry.fileName)) {
767
- // Directory
768
- zipfile.addEmptyDirectory(entry.fileName);
769
- } else if (isPPKBundleFileName(entry.fileName)) {
770
- await addBundlePatch(
771
- zipfile,
772
- entry,
773
- nextZipfile,
774
- diffFn,
775
- bundleSource,
776
- bundleOptions,
777
- hbcTransformMetas,
778
- workRoot,
779
- );
780
- } else {
781
- // If same file.
782
- const contentKey = zipEntryContentKey(entry);
783
- if (originEntries[entry.fileName] === contentKey) {
784
- copies[entry.fileName] = '';
785
- copiesCrc[entry.fileName] = entry.crc32;
786
- return;
787
- }
788
- // If moved from other place
789
- const movedFrom = originMap[contentKey];
790
- if (movedFrom) {
791
- copies[entry.fileName] = movedFrom;
792
- copiesCrc[entry.fileName] = entry.crc32;
793
- return;
794
- }
795
-
796
- await addFileFromZipEntry(zipfile, entry, nextZipfile);
797
- }
798
- });
799
-
800
- return {
801
- copies,
802
- copiesCrc,
803
- ...(Object.keys(hbcTransformMetas).length
804
- ? { hbcTransform: hbcTransformMetas }
805
- : {}),
806
- };
807
- });
808
- }
809
-
810
- type DiffCommandOptions = {
811
- customDiff?: Diff;
812
- customPatch?: Patch;
813
- customDiffStream?: DiffStream;
814
- customPatchStream?: PatchStream;
815
- customDiffStreamVerified?: boolean;
816
- customDiffSingleStream?: DiffStream;
817
- customPatchSingleStream?: PatchStream;
818
- customDiffSingleStreamVerified?: boolean;
819
- customHdiffModule?: HdiffModule;
820
- onDiffPhase?: BundleDiffOptions['onDiffPhase'];
821
- hbcTransform?: boolean;
822
- bundleStreamThreshold?: number;
823
- [key: string]: any;
824
- };
825
-
826
- function resolveDiffImplementation(options: DiffCommandOptions): Diff {
827
- if (options.customDiff) {
828
- return options.customDiff;
829
- }
830
-
831
- const hdiffModule = options.customHdiffModule ?? hdiff;
832
- if (!hdiffModule?.diff) {
833
- throw new Error(t('nodeHdiffpatchRequired', { scriptName }));
834
- }
835
- return hdiffModule.diff;
836
- }
837
-
838
- // round-trip 自检需要 patch 能力;拿不到时禁用变换(安全优先),不报错
839
- function resolvePatchImplementation(
840
- options: DiffCommandOptions,
841
- ): Patch | undefined {
842
- if (options.customPatch) {
843
- return options.customPatch;
844
- }
845
- const hdiffModule = options.customHdiffModule ?? hdiff;
846
- return hdiffModule?.patch;
847
- }
848
-
849
- function resolveBundleDiffOptions(
850
- options: DiffCommandOptions,
851
- ): BundleDiffOptions {
852
- const hdiffModule = options.customHdiffModule ?? hdiff;
853
- const streamOptions: Pick<
854
- BundleDiffOptions,
855
- | 'streamThresholdBytes'
856
- | 'diffStreamFn'
857
- | 'patchStreamFn'
858
- | 'streamEmitsSingleFormat'
859
- | 'streamOutputVerified'
860
- > = {};
861
- const observerOptions =
862
- typeof options.onDiffPhase === 'function'
863
- ? { onDiffPhase: options.onDiffPhase }
864
- : {};
865
- if (
866
- typeof options.bundleStreamThreshold === 'number' &&
867
- options.bundleStreamThreshold > 0
868
- ) {
869
- const singleDiffStreamFn =
870
- options.customDiffSingleStream ?? hdiffModule?.diffSingleStream;
871
- const singlePatchStreamFn =
872
- options.customPatchSingleStream ?? hdiffModule?.patchSingleStream;
873
- const diffStreamFn = options.customDiffStream ?? hdiffModule?.diffStream;
874
- const patchStreamFn = options.customPatchStream ?? hdiffModule?.patchStream;
875
- if (singleDiffStreamFn && singlePatchStreamFn) {
876
- streamOptions.streamThresholdBytes = options.bundleStreamThreshold;
877
- streamOptions.diffStreamFn = singleDiffStreamFn;
878
- streamOptions.patchStreamFn = singlePatchStreamFn;
879
- streamOptions.streamEmitsSingleFormat = true;
880
- streamOptions.streamOutputVerified = options.customDiffSingleStream
881
- ? options.customDiffSingleStreamVerified === true
882
- : hdiffModule?.capabilities?.diffSingleStreamVerifiesOutput === true;
883
- } else if (diffStreamFn && patchStreamFn) {
884
- streamOptions.streamThresholdBytes = options.bundleStreamThreshold;
885
- streamOptions.diffStreamFn = diffStreamFn;
886
- streamOptions.patchStreamFn = patchStreamFn;
887
- streamOptions.streamEmitsSingleFormat = false;
888
- streamOptions.streamOutputVerified = options.customDiffStream
889
- ? options.customDiffStreamVerified === true
890
- : hdiffModule?.capabilities?.diffStreamVerifiesOutput === true;
891
- } else {
892
- console.warn(t('bundleStreamNeedsHdiffpatch'));
893
- }
894
- }
895
-
896
- if (!options.hbcTransform) {
897
- return { ...observerOptions, ...streamOptions };
898
- }
899
- const patchFn = resolvePatchImplementation(options);
900
- if (!patchFn) {
901
- console.warn(t('hbcTransformNeedsPatch'));
902
- return { ...observerOptions, ...streamOptions };
903
- }
904
- return {
905
- hbcTransform: true,
906
- patchFn,
907
- ...observerOptions,
908
- ...streamOptions,
909
- ...(typeof options.hbcTransformMinBaseline === 'number'
910
- ? { minBaselineBytes: options.hbcTransformMinBaseline }
911
- : {}),
912
- };
913
- }
914
-
915
- function diffArgsCheck(
916
- args: string[],
917
- options: DiffCommandOptions,
918
- diffFnName: string,
919
- ) {
920
- const [origin, next] = args;
921
-
922
- if (!origin || !next) {
923
- throw new Error(t('usageDiff', { command: diffFnName }));
924
- }
925
-
926
- const diffFn = resolveDiffImplementation(options);
927
- const { output } = translateOptions({
928
- ...options,
929
- tempDir,
930
- } as DiffCommandOptions & { tempDir: string });
931
- if (typeof output !== 'string') {
932
- throw new Error(t('outputPathRequired'));
933
- }
934
-
935
- return {
936
- origin,
937
- next,
938
- diffFn,
939
- realOutput: output.replace(/\$\{time\}/g, `${Date.now()}`),
940
- };
941
- }
942
-
943
- const createDiffCommand =
944
- ({ diffFnName, target }: DiffCommandConfig) =>
945
- async ({ args, options }: CommandContext) => {
946
- const { origin, next, realOutput, diffFn } = diffArgsCheck(
947
- args,
948
- options as DiffCommandOptions,
949
- diffFnName,
950
- );
951
- const bundleOptions = resolveBundleDiffOptions(
952
- options as DiffCommandOptions,
953
- );
954
-
955
- const workRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'rnu-bundle-diff-'));
956
- try {
957
- if (target.kind === 'ppk') {
958
- await diffFromPPK(
959
- origin,
960
- next,
961
- realOutput,
962
- diffFn,
963
- bundleOptions,
964
- workRoot,
965
- );
966
- } else {
967
- await diffFromPackage(
968
- origin,
969
- next,
970
- realOutput,
971
- diffFn,
972
- target.platform,
973
- bundleOptions,
974
- workRoot,
975
- );
976
- }
977
- } finally {
978
- fs.rmSync(workRoot, { recursive: true, force: true });
979
- }
980
-
981
- console.log(t('diffPackageGenerated', { output: realOutput }));
982
- };
983
-
984
- export const diffCommands = {
985
- hdiff: createDiffCommand({
986
- diffFnName: 'hdiff',
987
- target: { kind: 'ppk' },
988
- }),
989
- hdiffFromApk: createDiffCommand({
990
- diffFnName: 'hdiffFromApk',
991
- target: {
992
- kind: 'package',
993
- platform: 'android',
994
- },
995
- }),
996
- hdiffFromApp: createDiffCommand({
997
- diffFnName: 'hdiffFromApp',
998
- target: {
999
- kind: 'package',
1000
- platform: 'harmony',
1001
- },
1002
- }),
1003
- hdiffFromIpa: createDiffCommand({
1004
- diffFnName: 'hdiffFromIpa',
1005
- target: {
1006
- kind: 'package',
1007
- platform: 'ios',
1008
- },
1009
- }),
1010
- };