@gfean/react-native-bundle-drop 0.3.9 → 0.4.2

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 (80) hide show
  1. package/BundleDrop.podspec +9 -2
  2. package/README.md +19 -0
  3. package/android/build.gradle +43 -4
  4. package/android/src/main/cpp/CMakeLists.txt +45 -0
  5. package/android/src/main/cpp/bundle_drop_xdelta_jni.c +55 -0
  6. package/android/src/main/java/com/bundledrop/BundleDropBundleVerifier.kt +73 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +193 -8
  8. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +60 -7
  9. package/android/src/main/java/com/bundledrop/BundleDropOtaPrefs.kt +2 -12
  10. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +208 -3
  11. package/android/src/main/java/com/bundledrop/BundleDropXdeltaNative.kt +57 -0
  12. package/ios/BundleDropBridge.m +27 -0
  13. package/ios/BundleDropBundleVerifier.swift +106 -0
  14. package/ios/BundleDropFileOps.swift +149 -0
  15. package/ios/BundleDropModule.swift +100 -11
  16. package/ios/BundleDropOtaResolver.swift +149 -3
  17. package/ios/BundleDropZipExtractor.m +75 -3
  18. package/lib/CLI/cli.js +1 -8
  19. package/lib/CLI/scripts/upload-cli.d.ts +0 -1
  20. package/lib/CLI/scripts/upload-cli.js +98 -36
  21. package/lib/api/client.d.ts +11 -1
  22. package/lib/api/client.js +84 -17
  23. package/lib/api/clientApi.d.ts +2 -1
  24. package/lib/api/clientApi.js +9 -0
  25. package/lib/api/types.d.ts +65 -13
  26. package/lib/bundleInfo.d.ts +2 -0
  27. package/lib/fs/bundlePointer.d.ts +2 -1
  28. package/lib/fs/bundlePointer.js +34 -6
  29. package/lib/fs/fsUtils.js +4 -1
  30. package/lib/injectImageResolver.js +82 -75
  31. package/lib/install/bundleInstallShared.d.ts +8 -0
  32. package/lib/install/bundleInstallShared.js +97 -0
  33. package/lib/install/bundleVerification.d.ts +5 -0
  34. package/lib/install/bundleVerification.js +34 -0
  35. package/lib/install/installFromZip.d.ts +2 -5
  36. package/lib/install/installFromZip.js +33 -68
  37. package/lib/loadConfig.js +12 -1
  38. package/lib/manager/downloadAndInstall.d.ts +9 -0
  39. package/lib/manager/downloadAndInstall.js +84 -24
  40. package/lib/manager/reporting.js +26 -2
  41. package/lib/manager/rollbackState.js +21 -12
  42. package/lib/manager/updateCheck.js +89 -11
  43. package/lib/manager/updateState.js +3 -9
  44. package/lib/manifest/bundleManifest.d.ts +33 -0
  45. package/lib/manifest/bundleManifest.js +298 -0
  46. package/lib/native/bundleDropNative.js +1 -2
  47. package/lib/native/fs.d.ts +14 -0
  48. package/lib/native/fs.js +35 -0
  49. package/lib/patch-engine/installFromPatchSet.d.ts +16 -0
  50. package/lib/patch-engine/installFromPatchSet.js +143 -0
  51. package/lib/patch-engine/patchOperations.d.ts +33 -0
  52. package/lib/patch-engine/patchOperations.js +77 -0
  53. package/lib/patch-engine/patchTransport.d.ts +18 -0
  54. package/lib/patch-engine/patchTransport.js +81 -0
  55. package/lib/patchAlgorithms.d.ts +4 -0
  56. package/lib/patchAlgorithms.js +9 -0
  57. package/lib/runtime/service.js +43 -9
  58. package/lib/scripts/bundle.d.ts +3 -0
  59. package/lib/scripts/bundle.js +197 -43
  60. package/lib/scripts/download-bundle.js +18 -7
  61. package/package.json +44 -6
  62. package/third_party/xdelta/NOTICE +7 -0
  63. package/third_party/xdelta/PROVENANCE.md +10 -0
  64. package/third_party/xdelta/bundle_drop_xdelta.c +252 -0
  65. package/third_party/xdelta/bundle_drop_xdelta.h +26 -0
  66. package/third_party/xdelta/xdelta3/LICENSE +176 -0
  67. package/third_party/xdelta/xdelta3/config.h +34 -0
  68. package/third_party/xdelta/xdelta3/xdelta3-cfgs.h +171 -0
  69. package/third_party/xdelta/xdelta3/xdelta3-decode.h +1219 -0
  70. package/third_party/xdelta/xdelta3/xdelta3-hash.h +159 -0
  71. package/third_party/xdelta/xdelta3/xdelta3-internal.h +385 -0
  72. package/third_party/xdelta/xdelta3/xdelta3-list.h +127 -0
  73. package/third_party/xdelta/xdelta3/xdelta3.c +4819 -0
  74. package/third_party/xdelta/xdelta3/xdelta3.h +1476 -0
  75. package/lib/CLI/scripts/init-native-config.d.ts +0 -18
  76. package/lib/CLI/scripts/init-native-config.js +0 -539
  77. package/lib/assetExtensions.d.ts +0 -4
  78. package/lib/assetExtensions.js +0 -35
  79. package/lib/scripts/upload-bundle.d.ts +0 -9
  80. package/lib/scripts/upload-bundle.js +0 -320
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tryInstallPatchTransport = void 0;
4
+ const context_1 = require("../context");
5
+ const installId_1 = require("../fs/installId");
6
+ const clientApi_1 = require("../api/clientApi");
7
+ const installFromPatchSet_1 = require("./installFromPatchSet");
8
+ const patchOperations_1 = require("./patchOperations");
9
+ const PATCH_FAILURE_REPORT_TIMEOUT_MS = 1500;
10
+ const reportPatchInstallFailure = async ({ projectSlug, platform, runtimeVersionValue, baseHash, targetHash, algorithm, error, }) => {
11
+ try {
12
+ const installId = await (0, installId_1.getOrCreateInstallId)();
13
+ await (0, clientApi_1.reportPatchApplyFailure)(projectSlug, {
14
+ platform,
15
+ runtimeVersion: runtimeVersionValue,
16
+ installId,
17
+ baseHash,
18
+ targetHash,
19
+ algorithm,
20
+ reason: error instanceof Error ? error.message : 'patch_install_failed',
21
+ });
22
+ }
23
+ catch {
24
+ // Telemetry must never block the full-bundle fallback path.
25
+ }
26
+ };
27
+ const reportPatchInstallFailureBeforeFallback = async (params) => {
28
+ let timeout = null;
29
+ const timeoutPromise = new Promise(resolve => {
30
+ timeout = setTimeout(resolve, PATCH_FAILURE_REPORT_TIMEOUT_MS);
31
+ });
32
+ try {
33
+ await Promise.race([
34
+ reportPatchInstallFailure(params),
35
+ timeoutPromise,
36
+ ]);
37
+ }
38
+ finally {
39
+ if (timeout)
40
+ clearTimeout(timeout);
41
+ }
42
+ };
43
+ const tryInstallPatchTransport = async ({ target, projectSlug, platform, runtimeVersionValue, statusCb, }) => {
44
+ if (target.mode !== 'patch' ||
45
+ !target.baseHash ||
46
+ !(0, patchOperations_1.isSupportedPatchAlgorithm)(target.patchSet?.algorithm) ||
47
+ !target.patchSet?.patchesUrl ||
48
+ !target.patchSet.patchSetHash) {
49
+ return null;
50
+ }
51
+ try {
52
+ statusCb?.('🧩 Downloading patch set...');
53
+ return await (0, installFromPatchSet_1.installFromPatchSet)({
54
+ patchesUrl: target.patchSet.patchesUrl,
55
+ patchSetHash: target.patchSet.patchSetHash,
56
+ manifestUrl: target.manifestUrl,
57
+ missingAssetsUrl: target.patchSet.assets?.missingAssetsUrl,
58
+ missingAssetsHash: target.patchSet.assets?.missingAssetsHash,
59
+ baseHash: target.baseHash,
60
+ targetHash: target.hash,
61
+ algorithm: target.patchSet.algorithm,
62
+ platform,
63
+ statusCb,
64
+ });
65
+ }
66
+ catch (e) {
67
+ await reportPatchInstallFailureBeforeFallback({
68
+ projectSlug,
69
+ platform,
70
+ runtimeVersionValue: runtimeVersionValue ?? context_1.runtimeVersion ?? '',
71
+ baseHash: target.baseHash,
72
+ targetHash: target.hash,
73
+ algorithm: target.patchSet.algorithm,
74
+ error: e,
75
+ });
76
+ statusCb?.('↩️ Patch install failed; falling back to full bundle ZIP');
77
+ console.warn('⚠️ Patch install failed; falling back to full bundle ZIP:', e?.toString?.() || e);
78
+ return null;
79
+ }
80
+ };
81
+ exports.tryInstallPatchTransport = tryInstallPatchTransport;
@@ -0,0 +1,4 @@
1
+ export declare const XDELTA_PATCH_ALGORITHM = "xdelta3-vcdiff";
2
+ export declare const ASSET_ONLY_PATCH_ALGORITHM = "asset-only-v1";
3
+ export declare const SUPPORTED_PATCH_ALGORITHMS: readonly ["xdelta3-vcdiff", "asset-only-v1"];
4
+ export type SupportedPatchAlgorithm = (typeof SUPPORTED_PATCH_ALGORITHMS)[number];
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SUPPORTED_PATCH_ALGORITHMS = exports.ASSET_ONLY_PATCH_ALGORITHM = exports.XDELTA_PATCH_ALGORITHM = void 0;
4
+ exports.XDELTA_PATCH_ALGORITHM = 'xdelta3-vcdiff';
5
+ exports.ASSET_ONLY_PATCH_ALGORITHM = 'asset-only-v1';
6
+ exports.SUPPORTED_PATCH_ALGORITHMS = [
7
+ exports.XDELTA_PATCH_ALGORITHM,
8
+ exports.ASSET_ONLY_PATCH_ALGORITHM,
9
+ ];
@@ -42,6 +42,7 @@ let localStartupPromise = null;
42
42
  let healthTimer = null;
43
43
  let runtimeRestartRequested = false;
44
44
  let activeBundleInfoForObservability = null;
45
+ let nativeOtaEnabledPromise = Promise.resolve();
45
46
  let snapshot = {
46
47
  status: DISABLED_STATUS,
47
48
  isBusy: false,
@@ -252,7 +253,10 @@ async function runStartupFlow() {
252
253
  const runtime = (0, initState_1.assertBundleDropInitialized)();
253
254
  const statusCb = status => emitStatus(status);
254
255
  void (0, fsUtils_1.cleanOrphanedTempZips)(`${context_1.BUNDLE_DROP_ROOT}/bundles`);
255
- localStartupPromise = runLocalStartupFlow();
256
+ localStartupPromise = (async () => {
257
+ await nativeOtaEnabledPromise;
258
+ return runLocalStartupFlow();
259
+ })();
256
260
  const { bundlePath, currentPointer, rollbackState } = await localStartupPromise;
257
261
  const rollbackPolicy = (0, rollbackState_1.getRollbackPolicy)();
258
262
  const rollbackResult = await (0, rollbackState_1.rollbackToPreviousIfNeeded)(rollbackPolicy, {
@@ -301,16 +305,24 @@ async function runStartupFlow() {
301
305
  if (decision.action === 'NOOP' || runtime.policy === 'manual' || runtime.checkOnly) {
302
306
  return;
303
307
  }
304
- if (!decision.downloadUrl || !decision.hash) {
308
+ const downloadUrl = decision.mode === 'patch'
309
+ ? decision.fallback?.downloadUrl
310
+ : decision.downloadUrl;
311
+ if (!downloadUrl || !decision.hash) {
305
312
  emitStatus('⚠️ Update available but missing download URL');
306
313
  return;
307
314
  }
308
315
  const resolvedTarget = {
309
316
  hash: decision.hash,
310
- downloadUrl: decision.downloadUrl,
317
+ downloadUrl,
311
318
  bundleVersion: decision.bundleVersion,
312
319
  version: decision.version,
313
320
  runtimeVersion: decision.runtimeVersion,
321
+ manifestUrl: decision.manifestUrl,
322
+ mode: decision.mode,
323
+ baseHash: decision.baseHash,
324
+ patchSet: decision.patchSet,
325
+ fallback: decision.fallback,
314
326
  };
315
327
  const downloadResult = await (0, downloadAndInstall_1.downloadUpdate)({
316
328
  channelName: runtime.channelName,
@@ -361,8 +373,8 @@ function initBundleDrop(options) {
361
373
  runtimeRestartRequested = false;
362
374
  activeBundleInfoForObservability = null;
363
375
  }
364
- // Persist for the next cold start; do not block init on this I/O (errors are swallowed in native helper).
365
- void (0, bundleDropNative_1.setOtaEnabledNative)(config.enabled);
376
+ // Persist for the next cold start and for native path reads in this process.
377
+ nativeOtaEnabledPromise = (0, bundleDropNative_1.setOtaEnabledNative)(config.enabled);
366
378
  patchSnapshot({
367
379
  channelName: config.channelName,
368
380
  isEnabled: config.enabled,
@@ -457,6 +469,7 @@ async function applyDownloadedUpdate(extraStatusHandler) {
457
469
  return { result: { status: 'disabled' }, status: DISABLED_STATUS };
458
470
  }
459
471
  await waitForStartupIfNeeded();
472
+ await nativeOtaEnabledPromise;
460
473
  return withBusy(async () => {
461
474
  const result = await (0, updateState_1.applyUpdate)(status => emitStatus(status, extraStatusHandler), () => {
462
475
  runtimeRestartRequested = true;
@@ -535,10 +548,31 @@ async function installBundleFromListItem(bundle) {
535
548
  return { result: { status: 'incompatible' }, status };
536
549
  }
537
550
  return withBusy(async () => {
538
- const result = await (0, downloadAndInstall_1.installBundle)(bundle.hash, downloadUrl, bundle.bundleVersion, bundle.version, bundle.runtimeVersion, {
539
- channelName: runtime.channelName,
540
- onStatusUpdate: emitStatus,
541
- });
551
+ const resolvedDecision = await (0, updateCheck_1.checkForUpdate)(runtime.channelName, emitStatus).catch(() => null);
552
+ const canUseResolvedTransport = resolvedDecision?.action === 'INSTALL' &&
553
+ (resolvedDecision.bundleHash ?? resolvedDecision.hash) === bundle.hash;
554
+ const result = canUseResolvedTransport
555
+ ? await (0, downloadAndInstall_1.downloadUpdate)({
556
+ channelName: runtime.channelName,
557
+ resolvedTarget: {
558
+ hash: bundle.hash,
559
+ downloadUrl: resolvedDecision.mode === 'patch'
560
+ ? resolvedDecision.fallback?.downloadUrl ?? downloadUrl
561
+ : resolvedDecision.downloadUrl ?? downloadUrl,
562
+ bundleVersion: resolvedDecision.bundleVersion ?? bundle.bundleVersion,
563
+ version: resolvedDecision.version ?? bundle.version,
564
+ runtimeVersion: resolvedDecision.runtimeVersion ?? bundle.runtimeVersion,
565
+ manifestUrl: resolvedDecision.manifestUrl,
566
+ mode: resolvedDecision.mode,
567
+ baseHash: resolvedDecision.baseHash,
568
+ patchSet: resolvedDecision.patchSet,
569
+ fallback: resolvedDecision.fallback,
570
+ },
571
+ }, emitStatus)
572
+ : await (0, downloadAndInstall_1.installBundle)(bundle.hash, downloadUrl, bundle.bundleVersion, bundle.version, bundle.runtimeVersion, {
573
+ channelName: runtime.channelName,
574
+ onStatusUpdate: emitStatus,
575
+ });
542
576
  if (result.status === 'staged') {
543
577
  const status = `✅ v${bundle.bundleVersion} downloaded. Will apply on next launch or when you call applyUpdate.`;
544
578
  emitStatus(status);
@@ -14,4 +14,7 @@ export declare function runBundleScript(options?: {
14
14
  zipPath: string;
15
15
  runtimeVersion: string;
16
16
  hash: string;
17
+ bundleHash: string;
18
+ jsBundleHash: string;
19
+ manifestPath: string;
17
20
  };
@@ -44,10 +44,138 @@ const child_process_1 = require("child_process");
44
44
  const crypto_1 = require("crypto");
45
45
  const fs = __importStar(require("fs"));
46
46
  const path = __importStar(require("path"));
47
- const assetExtensions_1 = require("../assetExtensions");
47
+ const bundleManifest_1 = require("../manifest/bundleManifest");
48
48
  const projectRoot_1 = require("./projectRoot");
49
49
  Object.defineProperty(exports, "findProjectRoot", { enumerable: true, get: function () { return projectRoot_1.findProjectRoot; } });
50
50
  const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..');
51
+ const sha256Buffer = (buffer) => (0, crypto_1.createHash)('sha256').update(buffer).digest('hex');
52
+ const manifestRoleForPath = (filePath) => {
53
+ if (filePath === 'main.jsbundle')
54
+ return 'jsbundle';
55
+ if (filePath.startsWith('metadata-'))
56
+ return 'metadata';
57
+ if (filePath === 'image-manifest.json')
58
+ return 'androidImageManifest';
59
+ return 'asset';
60
+ };
61
+ const createFileEntry = (filePath, buffer) => ({
62
+ path: (0, bundleManifest_1.normalizeManifestPath)(filePath),
63
+ size: buffer.length,
64
+ sha256: sha256Buffer(buffer),
65
+ role: manifestRoleForPath((0, bundleManifest_1.normalizeManifestPath)(filePath)),
66
+ });
67
+ const readTextIfExists = (filePath) => {
68
+ if (!fs.existsSync(filePath))
69
+ return null;
70
+ return fs.readFileSync(filePath, 'utf8');
71
+ };
72
+ const readPlatformSetting = (value, platform) => {
73
+ if (typeof value === 'boolean' || value === 'auto')
74
+ return value;
75
+ if (!value || typeof value !== 'object')
76
+ return undefined;
77
+ const platformValue = value[platform];
78
+ return typeof platformValue === 'boolean' || platformValue === 'auto'
79
+ ? platformValue
80
+ : undefined;
81
+ };
82
+ const detectBoolean = (contents, truePatterns, falsePatterns) => {
83
+ const joined = contents.filter((content) => !!content).join('\n');
84
+ if (!joined)
85
+ return undefined;
86
+ if (falsePatterns.some(pattern => pattern.test(joined)))
87
+ return false;
88
+ if (truePatterns.some(pattern => pattern.test(joined)))
89
+ return true;
90
+ return undefined;
91
+ };
92
+ const readIosProjectSettings = (projectRoot) => {
93
+ const iosDir = path.join(projectRoot, 'ios');
94
+ if (!fs.existsSync(iosDir))
95
+ return null;
96
+ const projectFiles = fs
97
+ .readdirSync(iosDir)
98
+ .filter(fileName => fileName.endsWith('.xcodeproj'))
99
+ .map(fileName => path.join(iosDir, fileName, 'project.pbxproj'));
100
+ const contents = projectFiles
101
+ .map(readTextIfExists)
102
+ .filter((content) => Boolean(content));
103
+ return contents.length ? contents.join('\n') : null;
104
+ };
105
+ const readHermesHelp = (hermescPath) => {
106
+ try {
107
+ return String((0, child_process_1.execSync)(`"${hermescPath}" -help`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }));
108
+ }
109
+ catch {
110
+ return '';
111
+ }
112
+ };
113
+ const hermesHelpIncludesFlag = (help, flag) => new RegExp(`(?:^|\\n)\\s*${flag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\s|=)`).test(help);
114
+ const buildHermesFlags = (hermescPath, generateSourceMap) => {
115
+ const help = readHermesHelp(hermescPath);
116
+ const flags = ['-emit-binary'];
117
+ if (hermesHelpIncludesFlag(help, '-O')) {
118
+ flags.push('-O');
119
+ }
120
+ if (hermesHelpIncludesFlag(help, '-g0')) {
121
+ flags.push('-g0');
122
+ }
123
+ if (generateSourceMap && hermesHelpIncludesFlag(help, '-output-source-map')) {
124
+ flags.push('-output-source-map');
125
+ }
126
+ return flags;
127
+ };
128
+ const promoteHermesBytecode = (hbcPath, bundlePath) => {
129
+ if (!fs.existsSync(hbcPath)) {
130
+ throw new Error(`Hermes compiler did not write bytecode output at ${hbcPath}`);
131
+ }
132
+ fs.copyFileSync(hbcPath, bundlePath);
133
+ fs.unlinkSync(hbcPath);
134
+ };
135
+ const detectHermesFromNativeProject = (projectRoot, platform) => {
136
+ if (platform === 'android') {
137
+ return detectBoolean([
138
+ readTextIfExists(path.join(projectRoot, 'android', 'gradle.properties')),
139
+ readTextIfExists(path.join(projectRoot, 'android', 'app', 'build.gradle')),
140
+ readTextIfExists(path.join(projectRoot, 'android', 'app', 'build.gradle.kts')),
141
+ ], [
142
+ /(?:^|\n)\s*hermesEnabled\s*=\s*true\b/,
143
+ /\bhermesEnabled\s+(?:=|\()\s*true\b/,
144
+ /\benableHermes\s*[:=]\s*true\b/,
145
+ ], [
146
+ /(?:^|\n)\s*hermesEnabled\s*=\s*false\b/,
147
+ /\bhermesEnabled\s+(?:=|\()\s*false\b/,
148
+ /\benableHermes\s*[:=]\s*false\b/,
149
+ ]);
150
+ }
151
+ return detectBoolean([
152
+ readTextIfExists(path.join(projectRoot, 'ios', 'Podfile')),
153
+ readIosProjectSettings(projectRoot),
154
+ ], [
155
+ /:hermes_enabled\s*=>\s*true\b/,
156
+ /\bhermes_enabled\s*:\s*true\b/,
157
+ /\bhermesEnabled\s*[:=]\s*true\b/,
158
+ /\bUSE_HERMES\s*=\s*true\s*;/,
159
+ ], [
160
+ /:hermes_enabled\s*=>\s*false\b/,
161
+ /\bhermes_enabled\s*:\s*false\b/,
162
+ /\bhermesEnabled\s*[:=]\s*false\b/,
163
+ /\bUSE_HERMES\s*=\s*false\s*;/,
164
+ ]);
165
+ };
166
+ const shouldCompileHermesBytecode = (cfg, platform, projectRoot) => {
167
+ const explicit = readPlatformSetting(cfg.hermesBytecode, platform) ??
168
+ readPlatformSetting(cfg.hermes, platform);
169
+ if (typeof explicit === 'boolean')
170
+ return explicit;
171
+ const detected = detectHermesFromNativeProject(projectRoot, platform);
172
+ if (detected !== undefined)
173
+ return detected;
174
+ if (explicit === 'auto') {
175
+ console.warn(`⚠️ Could not detect Hermes for ${platform}; set hermesBytecode.${platform} in bundle.drop.config.js to opt in explicitly.`);
176
+ }
177
+ return false;
178
+ };
51
179
  function runBundleScript(options) {
52
180
  const packageRoot = getPackageRoot();
53
181
  const platform = options?.platform || process.argv[2] || 'ios';
@@ -61,25 +189,31 @@ function runBundleScript(options) {
61
189
  const assetsDir = path.join(outputDir, 'assets');
62
190
  const bundlePath = path.join(outputDir, 'main.jsbundle');
63
191
  const metadataPath = path.join(outputDir, `metadata-${fileSuffix}.json`);
192
+ const manifestPath = path.join(outputDir, bundleManifest_1.BUNDLE_MANIFEST);
64
193
  const sourceMapPath = path.join(outputDir, 'main.jsbundle.map');
65
194
  const zipPath = path.join(outputDir, `bundle-${platform}.zip`);
66
195
  const imageManifest = {};
67
196
  const projectRoot = (0, projectRoot_1.findProjectRoot)(options?.cwd || process.cwd());
68
197
  const generateSourceMap = options?.sourcemap ?? process.argv.includes('--sourcemap');
198
+ const appVersion = process.env.BUNDLE_DROP_APP_VERSION;
69
199
  let runtimeVersion;
70
200
  const configPath = path.resolve(projectRoot, 'bundle.drop.config.js');
71
- if (fs.existsSync(configPath)) {
72
- //eslint-disable-next-line
73
- const cfg = require(configPath);
74
- runtimeVersion = cfg?.runtimeVersion?.[platform];
75
- if (!runtimeVersion) {
76
- console.warn(`⚠️ No runtimeVersion found for ${platform} in bundle.drop.config.js. Example: runtimeVersion: { ios: "1.0.0", android: "1.0.0" }`);
77
- }
201
+ if (!fs.existsSync(configPath)) {
202
+ console.error('❌ bundle.drop.config.js not found in project root');
203
+ process.exit(1);
78
204
  }
79
- else {
80
- console.warn('⚠️ bundle.drop.config.js not found in project root; runtimeVersion will be omitted.');
205
+ //eslint-disable-next-line
206
+ const cfg = require(configPath);
207
+ runtimeVersion = cfg?.runtimeVersion?.[platform];
208
+ if (!runtimeVersion) {
209
+ console.error(`❌ Missing runtimeVersion.${platform} in bundle.drop.config.js. Example: runtimeVersion: { ios: "1.0.0", android: "1.0.0" }`);
210
+ process.exit(1);
211
+ }
212
+ if (!appVersion) {
213
+ console.error('❌ BUNDLE_DROP_APP_VERSION is required so bundle-manifest.json can include the app version');
214
+ process.exit(1);
81
215
  }
82
- [bundlePath, zipPath, metadataPath, sourceMapPath].forEach(file => {
216
+ [bundlePath, zipPath, metadataPath, manifestPath, sourceMapPath].forEach(file => {
83
217
  if (fs.existsSync(file))
84
218
  fs.unlinkSync(file);
85
219
  });
@@ -94,7 +228,8 @@ function runBundleScript(options) {
94
228
  --dev false \
95
229
  --entry-file index.js \
96
230
  --bundle-output "${bundlePath}" \
97
- --assets-dest "${assetsDir}"${sourcemapFlag}`, { stdio: 'inherit' });
231
+ --assets-dest "${assetsDir}" \
232
+ --reset-cache${sourcemapFlag}`, { stdio: 'inherit' });
98
233
  console.log('✅ Bundle created');
99
234
  const osBin = process.platform === 'darwin'
100
235
  ? 'osx-bin'
@@ -103,16 +238,18 @@ function runBundleScript(options) {
103
238
  : 'linux64-bin';
104
239
  const hermesLocations = [
105
240
  path.join(projectRoot, 'node_modules', 'react-native', 'sdks', 'hermesc', osBin, 'hermesc'),
241
+ path.join(projectRoot, 'node_modules', 'hermes-compiler', 'hermesc', osBin, 'hermesc'),
106
242
  path.join(projectRoot, 'node_modules', 'hermes-engine', osBin, 'hermesc'),
107
243
  ];
108
244
  const hermescPath = hermesLocations.find(p => fs.existsSync(p));
109
- if (hermescPath) {
245
+ const hermesEnabled = shouldCompileHermesBytecode(cfg, platform, projectRoot);
246
+ if (hermesEnabled && hermescPath) {
110
247
  const hbcPath = bundlePath + '.hbc';
111
- const hermesMapFlag = generateSourceMap ? ` -output-source-map` : '';
112
248
  try {
113
249
  console.log(`🔥 Compiling to Hermes bytecode (${platform})...`);
114
- (0, child_process_1.execSync)(`"${hermescPath}" -emit-binary -out "${hbcPath}" "${bundlePath}"${hermesMapFlag}`, { stdio: ['ignore', 'ignore', 'ignore'] });
115
- fs.renameSync(hbcPath, bundlePath);
250
+ const hermesFlags = buildHermesFlags(hermescPath, generateSourceMap).join(' ');
251
+ (0, child_process_1.execSync)(`"${hermescPath}" ${hermesFlags} -out "${hbcPath}" "${bundlePath}"`, { stdio: ['ignore', 'ignore', 'ignore'] });
252
+ promoteHermesBytecode(hbcPath, bundlePath);
116
253
  console.log('✅ Hermes bytecode compiled');
117
254
  }
118
255
  catch (e) {
@@ -141,27 +278,32 @@ function runBundleScript(options) {
141
278
  fs.unlinkSync(hermesMapPath);
142
279
  }
143
280
  }
281
+ else if (hermesEnabled) {
282
+ console.log('ℹ️ Hermes compiler not found — bundling plain JS');
283
+ }
144
284
  else {
145
- console.log('ℹ️ Hermes not found — bundling plain JS');
285
+ console.log(`ℹ️ Hermes bytecode disabled for ${platform} — bundling plain JS`);
286
+ }
287
+ if (!fs.existsSync(bundlePath)) {
288
+ throw new Error(`Bundle output missing after bundling: ${bundlePath}`);
146
289
  }
147
290
  const bundleBuffer = fs.readFileSync(bundlePath);
148
- const hash = (0, crypto_1.createHash)('sha256').update(bundleBuffer).digest('hex');
291
+ const jsBundleHash = sha256Buffer(bundleBuffer);
149
292
  const metadata = {
150
293
  platform,
151
- hash,
152
- timestamp: new Date().toISOString(),
294
+ jsBundleHash,
153
295
  bundlePath: 'main.jsbundle',
154
296
  sizeInBytes: bundleBuffer.length,
155
297
  };
156
298
  if (runtimeVersion) {
157
299
  metadata.runtimeVersion = runtimeVersion;
158
300
  }
159
- fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));
160
- console.log('🧠 Metadata saved');
161
- console.log('📌 Hash:', hash);
301
+ const stagedFiles = new Map();
302
+ stagedFiles.set('main.jsbundle', bundleBuffer);
303
+ const metadataFilePath = `metadata-${fileSuffix}.json`;
304
+ const metadataBuffer = Buffer.from(JSON.stringify(metadata, null, 2));
305
+ stagedFiles.set(metadataFilePath, metadataBuffer);
162
306
  const zip = new adm_zip_1.default();
163
- zip.addFile('main.jsbundle', bundleBuffer);
164
- zip.addFile(`metadata-${fileSuffix}.json`, Buffer.from(JSON.stringify(metadata, null, 2)));
165
307
  const addAssetsToZip = (dir) => {
166
308
  const items = fs.readdirSync(dir);
167
309
  for (const item of items) {
@@ -173,32 +315,40 @@ function runBundleScript(options) {
173
315
  }
174
316
  else {
175
317
  const buffer = fs.readFileSync(fullPath);
176
- zip.addFile(normalizedPath, buffer);
318
+ stagedFiles.set((0, bundleManifest_1.normalizeManifestPath)(normalizedPath), buffer);
177
319
  if (isAndroid) {
178
- const withAssetsPrefix = `assets/${normalizedPath}`;
179
- const manifestKey = normalizedPath.replace(/\.[^.]+$/, '');
180
- const manifestKeyNoPrefix = manifestKey.replace(/^assets\//, '');
181
- const baseNameKey = manifestKey.split('/').pop() || manifestKey;
182
- const baseWithExt = normalizedPath.split('/').pop() || normalizedPath;
183
- imageManifest[normalizedPath] = normalizedPath;
184
- imageManifest[manifestKey] = normalizedPath;
185
- imageManifest[manifestKeyNoPrefix] = normalizedPath;
186
- imageManifest[withAssetsPrefix] = normalizedPath;
187
- imageManifest[withAssetsPrefix.replace(/\.[^.]+$/, '')] = normalizedPath;
188
- if ((0, assetExtensions_1.isImageAssetPath)(normalizedPath)) {
189
- imageManifest[baseNameKey] = normalizedPath;
190
- imageManifest[baseWithExt] = normalizedPath;
191
- }
320
+ const manifestKey = (0, bundleManifest_1.normalizeManifestPath)(normalizedPath).replace(/^assets\//, '');
321
+ imageManifest[manifestKey] = (0, bundleManifest_1.normalizeManifestPath)(normalizedPath);
192
322
  }
193
323
  }
194
324
  }
195
325
  };
196
326
  addAssetsToZip(assetsDir);
197
- if (isAndroid && Object.keys(imageManifest).length > 0) {
198
- zip.addFile('image-manifest.json', Buffer.from(JSON.stringify(imageManifest, null, 2)));
327
+ if (isAndroid) {
328
+ stagedFiles.set('image-manifest.json', Buffer.from(JSON.stringify(imageManifest, null, 2)));
199
329
  console.log(`🧩 Injected image-manifest.json with ${Object.keys(imageManifest).length} entries`);
200
330
  }
331
+ const files = [...stagedFiles.entries()].map(([filePath, buffer]) => createFileEntry(filePath, buffer));
332
+ fs.writeFileSync(metadataPath, metadataBuffer);
333
+ const bundleHash = (0, bundleManifest_1.calculateBundleHash)(files);
334
+ const manifest = (0, bundleManifest_1.createBundleManifest)({
335
+ bundleHash,
336
+ jsBundleHash,
337
+ platform,
338
+ runtimeVersion,
339
+ version: appVersion,
340
+ files,
341
+ });
342
+ const manifestBuffer = Buffer.from(JSON.stringify(manifest, null, 2));
343
+ stagedFiles.set(bundleManifest_1.BUNDLE_MANIFEST, manifestBuffer);
344
+ fs.writeFileSync(manifestPath, manifestBuffer);
345
+ console.log('🧠 Metadata saved');
346
+ console.log('📌 Bundle Hash:', bundleHash);
347
+ console.log('📌 JS Bundle Hash:', jsBundleHash);
201
348
  console.log('📦 Zipping bundle...');
349
+ for (const [filePath, buffer] of stagedFiles.entries()) {
350
+ zip.addFile(filePath, buffer);
351
+ }
202
352
  zip.writeZip(zipPath);
203
353
  console.log('✅ OTA bundle zipped');
204
354
  return {
@@ -209,9 +359,13 @@ function runBundleScript(options) {
209
359
  metadataPath,
210
360
  zipPath,
211
361
  runtimeVersion,
212
- hash,
362
+ hash: bundleHash,
363
+ bundleHash,
364
+ jsBundleHash,
365
+ manifestPath,
213
366
  };
214
367
  }
368
+ /* istanbul ignore next */
215
369
  if (require.main === module) {
216
370
  runBundleScript();
217
371
  }
@@ -70,7 +70,7 @@ async function runDownloadBundle(options) {
70
70
  const runtimeVersion = config?.runtimeVersion?.[platform] || config?.runtimeVersion?.[platform];
71
71
  const channelName = argv[3] || config?.defaultChannel || 'General';
72
72
  const resolveEndpoint = `${serverUrl}/projects/${encodeURIComponent(project.slug)}/ota/resolve`;
73
- const outputPath = path.join(outputDir, `main.${platform}.jsbundle`);
73
+ const outputPath = path.join(outputDir, `bundle-${platform}.zip`);
74
74
  if (!fs.existsSync(outputDir)) {
75
75
  fs.mkdirSync(outputDir, { recursive: true });
76
76
  }
@@ -83,9 +83,16 @@ async function runDownloadBundle(options) {
83
83
  channelName,
84
84
  platform,
85
85
  runtimeVersion: runtimeVersion ?? null,
86
+ environment: null,
86
87
  currentHash: null,
87
- previousHash: null,
88
- currentBundleVersion: null,
88
+ rejectedHashes: [],
89
+ installId: 'cli-download',
90
+ currentUserProperties: {},
91
+ transport: {
92
+ manifestVersion: 1,
93
+ patchAlgorithms: [],
94
+ supportsContentAddressedAssets: true,
95
+ },
89
96
  }, {
90
97
  headers: {
91
98
  Accept: 'application/json',
@@ -94,15 +101,19 @@ async function runDownloadBundle(options) {
94
101
  timeout: 15000,
95
102
  });
96
103
  const decision = resolveResponse.data;
97
- const bundleDownloadUrl = decision?.action === 'INSTALL' ? decision?.target?.downloadUrl : null;
104
+ const bundleDownloadUrl = decision?.action === 'INSTALL' && decision?.mode === 'patch'
105
+ ? decision?.fallback?.downloadUrl
106
+ : decision?.action === 'INSTALL'
107
+ ? decision?.target?.downloadUrl
108
+ : null;
98
109
  if (!bundleDownloadUrl) {
99
- console.error('❌ Resolve did not return an INSTALL decision with a downloadUrl');
110
+ console.error('❌ Resolve did not return an INSTALL decision with a full bundle downloadUrl');
100
111
  process.exit(1);
101
112
  }
102
- console.log(`⬇️ Downloading latest ${platform} bundle from signed URL...`);
113
+ console.log(`⬇️ Downloading latest ${platform} full bundle ZIP from signed URL...`);
103
114
  const bundleResponse = await axios_1.default.get(bundleDownloadUrl, { responseType: 'arraybuffer' });
104
115
  await fs.promises.writeFile(outputPath, Buffer.from(bundleResponse.data));
105
- console.log(`✅ Bundle downloaded and saved to: ${outputPath}`);
116
+ console.log(`✅ Bundle ZIP downloaded and saved to: ${outputPath}`);
106
117
  return outputPath;
107
118
  }
108
119
  catch (err) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gfean/react-native-bundle-drop",
3
- "version": "0.3.9",
4
- "nativeVersion": "0.3.8",
3
+ "version": "0.4.2",
4
+ "nativeVersion": "0.4.2",
5
5
  "description": "Over-the-air (OTA) updates for React Native — ship fixes instantly, no App Store or Play Store delays",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",
@@ -35,16 +35,39 @@
35
35
  ],
36
36
  "scripts": {
37
37
  "clean": "rimraf lib dist",
38
- "build": "tsc -p tsconfig.build.json && node scripts/make-cli-executable.js",
38
+ "build": "yarn clean && tsc -p tsconfig.build.json && node scripts/make-cli-executable.js",
39
39
  "prepare": "husky",
40
40
  "test": "jest --runInBand",
41
41
  "test:coverage": "jest --runInBand --coverage",
42
42
  "coverage:check": "node scripts/check-coverage-thresholds.cjs",
43
- "test:android": "node scripts/run-android-tests.cjs",
43
+ "test:android:unit": "node scripts/run-android-tests.cjs",
44
+ "test:android": "yarn test:android:unit",
45
+ "test:android:device": "node scripts/run-android-instrumented-tests.cjs",
44
46
  "test:ios": "node scripts/run-ios-tests.cjs",
45
- "test:native": "yarn test:android && yarn test:ios",
47
+ "test:native": "yarn verify:native",
48
+ "test:harness": "jest --runInBand src/tests/harness",
49
+ "harness:app:install": "node scripts/harness/install-app-deps.cjs",
50
+ "harness:app:install:rn85:new": "node scripts/harness/install-app-deps.cjs rn-0.85-new-arch",
51
+ "harness:app:install:rn71:old": "node scripts/harness/install-app-deps.cjs rn-0.71-old-arch",
52
+ "harness:app:install:rn74:old": "node scripts/harness/install-app-deps.cjs rn-0.74-old-arch",
53
+ "harness:app:install:rn78:old": "node scripts/harness/install-app-deps.cjs rn-0.78-old-arch",
54
+ "harness:ios": "node scripts/harness/run-app-harness.cjs ios",
55
+ "harness:android": "node scripts/harness/run-app-harness.cjs android",
56
+ "harness:ios:rn85:new": "node scripts/harness/run-app-harness.cjs ios rn-0.85-new-arch",
57
+ "harness:android:rn85:new": "node scripts/harness/run-app-harness.cjs android rn-0.85-new-arch",
58
+ "harness:ios:rn71:old": "node scripts/harness/run-app-harness.cjs ios rn-0.71-old-arch",
59
+ "harness:android:rn71:old": "node scripts/harness/run-app-harness.cjs android rn-0.71-old-arch",
60
+ "harness:ios:rn74:old": "node scripts/harness/run-app-harness.cjs ios rn-0.74-old-arch",
61
+ "harness:android:rn74:old": "node scripts/harness/run-app-harness.cjs android rn-0.74-old-arch",
62
+ "harness:ios:rn78:old": "node scripts/harness/run-app-harness.cjs ios rn-0.78-old-arch",
63
+ "harness:android:rn78:old": "node scripts/harness/run-app-harness.cjs android rn-0.78-old-arch",
64
+ "harness:backend:live": "node scripts/harness/live-backend-smoke.cjs",
65
+ "harness:pack": "node scripts/harness/pack-dry-run.cjs",
46
66
  "coverage:gate": "yarn test:coverage && yarn coverage:check",
47
- "prepublishOnly": "yarn clean && yarn build",
67
+ "verify:quick": "yarn coverage:gate && yarn harness:pack",
68
+ "verify:native": "yarn test:android && yarn test:ios",
69
+ "verify:release": "yarn verify:quick && yarn verify:native",
70
+ "prepublishOnly": "yarn clean && yarn build && yarn harness:pack",
48
71
  "build-and-publish": "yarn clean && yarn build && npm publish --access=restricted",
49
72
  "publish:local": "yalc publish --private"
50
73
  },
@@ -78,6 +101,21 @@
78
101
  "android/build.gradle",
79
102
  "android/gradle.properties",
80
103
  "ios/*.{m,h,mm,swift}",
104
+ "third_party/xdelta/NOTICE",
105
+ "third_party/xdelta/PROVENANCE.md",
106
+ "third_party/xdelta/bundle_drop_xdelta.c",
107
+ "third_party/xdelta/bundle_drop_xdelta.h",
108
+ "third_party/xdelta/xdelta3/LICENSE",
109
+ "third_party/xdelta/xdelta3/config.h",
110
+ "third_party/xdelta/xdelta3/xdelta3-cfgs.h",
111
+ "third_party/xdelta/xdelta3/xdelta3-decode.h",
112
+ "third_party/xdelta/xdelta3/xdelta3-hash.h",
113
+ "third_party/xdelta/xdelta3/xdelta3-internal.h",
114
+ "third_party/xdelta/xdelta3/xdelta3-list.h",
115
+ "third_party/xdelta/xdelta3/xdelta3.c",
116
+ "third_party/xdelta/xdelta3/xdelta3.h",
117
+ "!third_party/xdelta/README.md",
118
+ "!third_party/xdelta/xdelta3/README.md",
81
119
  "BundleDrop.podspec",
82
120
  "react-native.config.js",
83
121
  "README.md"