@gfean/react-native-bundle-drop 0.3.6 → 0.3.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.
@@ -99,6 +99,8 @@ dependencies {
99
99
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
100
100
  testImplementation "junit:junit:4.13.2"
101
101
  testImplementation "org.json:json:20231013"
102
+ testImplementation "androidx.test:core:1.6.1"
103
+ testImplementation "org.robolectric:robolectric:4.14.1"
102
104
  }
103
105
 
104
106
  // ---------------------------------------------------------------------------
@@ -15,54 +15,8 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
15
15
  var latestBundlePath: String? = null
16
16
  private set
17
17
 
18
- private const val PREFS_NAME = "BundleDropPrefs"
19
- private const val KEY_BINARY_VERSION = "binary_version"
20
-
21
- private fun getBinaryVersionKey(context: Context): String {
22
- val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
23
- val versionName = pInfo.versionName ?: "unknown"
24
- @Suppress("DEPRECATION")
25
- val versionCode = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
26
- pInfo.longVersionCode
27
- } else {
28
- pInfo.versionCode.toLong()
29
- }
30
- return "$versionName-$versionCode"
31
- }
32
-
33
- private fun getStoredBinaryVersion(context: Context): String? {
34
- return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
35
- .getString(KEY_BINARY_VERSION, null)
36
- }
37
-
38
- private fun setStoredBinaryVersion(context: Context, version: String) {
39
- context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
40
- .edit().putString(KEY_BINARY_VERSION, version).apply()
41
- }
42
-
43
- fun getDownloadedBundlePath(context: Context): String? {
44
- val bundleDropRoot = File(context.filesDir, "bundle-drop")
45
- val result = BundleDropOtaResolver.resolve(
46
- bundleDropRoot = bundleDropRoot,
47
- filesDir = context.filesDir,
48
- currentBinaryVersion = getBinaryVersionKey(context),
49
- storedBinaryVersion = getStoredBinaryVersion(context),
50
- )
51
-
52
- result.storedVersion?.let { setStoredBinaryVersion(context, it) }
53
-
54
- if (result.bundlePath == null) {
55
- if (result.clearedOta) {
56
- Log.d("BundleDrop", "Binary updated, clearing OTA bundle")
57
- } else {
58
- Log.d("BundleDrop", "📦 No OTA bundle found.")
59
- }
60
- } else {
61
- Log.d("BundleDrop", "🔁 Using OTA bundle at: ${result.bundlePath}")
62
- }
63
-
64
- return result.bundlePath
65
- }
18
+ fun getDownloadedBundlePath(context: Context): String? =
19
+ BundleDropNativePaths.getDownloadedBundlePath(context)
66
20
 
67
21
  @JvmStatic
68
22
  fun resolveJSBundleFile(context: Context, fallback: String?): String? {
@@ -104,6 +58,16 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
104
58
  }
105
59
  }
106
60
 
61
+ @ReactMethod
62
+ fun setOtaEnabled(enabled: Boolean, promise: Promise) {
63
+ try {
64
+ BundleDropOtaPrefs.writeOtaEnabled(reactApplicationContext, enabled)
65
+ promise.resolve(null)
66
+ } catch (e: Exception) {
67
+ promise.reject("ERR_SET_OTA_ENABLED", e.message, e)
68
+ }
69
+ }
70
+
107
71
  // Backward compat
108
72
  @ReactMethod
109
73
  fun forceReloadJS() {
@@ -0,0 +1,64 @@
1
+ package com.bundledrop
2
+
3
+ import android.content.Context
4
+ import android.util.Log
5
+ import java.io.File
6
+
7
+ /**
8
+ * Resolves the on-disk OTA JS bundle path (no React / bridge types).
9
+ *
10
+ * Shared by [BundleDropModule] so cold-start `resolveJSBundleFile`, the JS bridge
11
+ * `getDownloadedBundlePath`, and tests use the same logic — including the OTA-disabled gate.
12
+ */
13
+ object BundleDropNativePaths {
14
+ private const val KEY_BINARY_VERSION = "binary_version"
15
+
16
+ private fun getBinaryVersionKey(context: Context): String {
17
+ val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
18
+ val versionName = pInfo.versionName ?: "unknown"
19
+ @Suppress("DEPRECATION")
20
+ val versionCode = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
21
+ pInfo.longVersionCode
22
+ } else {
23
+ pInfo.versionCode.toLong()
24
+ }
25
+ return "$versionName-$versionCode"
26
+ }
27
+
28
+ private fun getStoredBinaryVersion(context: Context): String? {
29
+ return context.getSharedPreferences(BundleDropOtaPrefs.PREFS_NAME, Context.MODE_PRIVATE)
30
+ .getString(KEY_BINARY_VERSION, null)
31
+ }
32
+
33
+ private fun setStoredBinaryVersion(context: Context, version: String) {
34
+ context.getSharedPreferences(BundleDropOtaPrefs.PREFS_NAME, Context.MODE_PRIVATE)
35
+ .edit().putString(KEY_BINARY_VERSION, version).apply()
36
+ }
37
+
38
+ @JvmStatic
39
+ fun getDownloadedBundlePath(context: Context): String? {
40
+ if (!BundleDropOtaPrefs.isOtaEnabled(context)) return null
41
+
42
+ val bundleDropRoot = File(context.filesDir, "bundle-drop")
43
+ val result = BundleDropOtaResolver.resolve(
44
+ bundleDropRoot = bundleDropRoot,
45
+ filesDir = context.filesDir,
46
+ currentBinaryVersion = getBinaryVersionKey(context),
47
+ storedBinaryVersion = getStoredBinaryVersion(context),
48
+ )
49
+
50
+ result.storedVersion?.let { setStoredBinaryVersion(context, it) }
51
+
52
+ if (result.bundlePath == null) {
53
+ if (result.clearedOta) {
54
+ Log.d("BundleDrop", "Binary updated, clearing OTA bundle")
55
+ } else {
56
+ Log.d("BundleDrop", "📦 No OTA bundle found.")
57
+ }
58
+ } else {
59
+ Log.d("BundleDrop", "🔁 Using OTA bundle at: ${result.bundlePath}")
60
+ }
61
+
62
+ return result.bundlePath
63
+ }
64
+ }
@@ -0,0 +1,41 @@
1
+ package com.bundledrop
2
+
3
+ import android.content.Context
4
+ import android.content.SharedPreferences
5
+
6
+ /**
7
+ * Persist whether the native bundle resolver may load an OTA JS bundle on cold start.
8
+ *
9
+ * **Storage:** [PREFS_NAME] SharedPreferences file. [KEY_OTA_ENABLED] matches iOS
10
+ * `BundleDropLocator.otaEnabledKey` (`bundledrop_ota_enabled`) for cross-platform debugging.
11
+ * Older releases used [LEGACY_KEY_OTA_ENABLED]; it is still read when the new key is absent,
12
+ * and is removed when JS persists a value via [writeOtaEnabled].
13
+ */
14
+ object BundleDropOtaPrefs {
15
+ const val PREFS_NAME = "BundleDropPrefs"
16
+ const val KEY_OTA_ENABLED = "bundledrop_ota_enabled"
17
+ private const val LEGACY_KEY_OTA_ENABLED = "ota_enabled"
18
+
19
+ fun preferences(context: Context): SharedPreferences =
20
+ context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
21
+
22
+ fun isOtaEnabled(context: Context): Boolean = readIsOtaEnabled(preferences(context))
23
+
24
+ fun readIsOtaEnabled(prefs: SharedPreferences): Boolean {
25
+ val hasNew = prefs.contains(KEY_OTA_ENABLED)
26
+ val hasLegacy = prefs.contains(LEGACY_KEY_OTA_ENABLED)
27
+ if (!hasNew && !hasLegacy) return true
28
+ return if (hasNew) {
29
+ prefs.getBoolean(KEY_OTA_ENABLED, true)
30
+ } else {
31
+ prefs.getBoolean(LEGACY_KEY_OTA_ENABLED, true)
32
+ }
33
+ }
34
+
35
+ fun writeOtaEnabled(context: Context, enabled: Boolean) {
36
+ preferences(context).edit()
37
+ .putBoolean(KEY_OTA_ENABLED, enabled)
38
+ .remove(LEGACY_KEY_OTA_ENABLED)
39
+ .apply()
40
+ }
41
+ }
@@ -7,6 +7,10 @@ RCT_EXTERN_METHOD(getDownloadedBundlePath:(RCTPromiseResolveBlock)resolve
7
7
 
8
8
  RCT_EXTERN_METHOD(restartReactNative)
9
9
 
10
+ RCT_EXTERN_METHOD(setOtaEnabled:(BOOL)enabled
11
+ resolve:(RCTPromiseResolveBlock)resolve
12
+ reject:(RCTPromiseRejectBlock)reject)
13
+
10
14
  // FS primitives
11
15
  RCT_EXTERN_METHOD(fsExists:(NSString *)path
12
16
  resolve:(RCTPromiseResolveBlock)resolve
@@ -4,6 +4,14 @@ import Foundation
4
4
 
5
5
  static let binaryVersionKey = "BundleDropBinaryVersion"
6
6
 
7
+ /// Matches Android `BundleDropOtaPrefs.KEY_OTA_ENABLED` for cross-platform debugging.
8
+ static let otaEnabledKey = "bundledrop_ota_enabled"
9
+
10
+ static func isOtaEnabled(userDefaults: UserDefaults = .standard) -> Bool {
11
+ if userDefaults.object(forKey: otaEnabledKey) == nil { return true }
12
+ return userDefaults.bool(forKey: otaEnabledKey)
13
+ }
14
+
7
15
  static func getBinaryVersionKey(bundle: Bundle = .main) -> String {
8
16
  let version = bundle.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
9
17
  let build = bundle.infoDictionary?["CFBundleVersion"] as? String ?? "0"
@@ -33,6 +41,8 @@ import Foundation
33
41
  shouldLogBinaryUpdate: Bool = true,
34
42
  log: (String) -> Void = { print($0) }
35
43
  ) -> URL? {
44
+ // Single gate for public and internal entrypoints (tests inject `userDefaults`).
45
+ if !isOtaEnabled(userDefaults: userDefaults) { return nil }
36
46
  let lastVersion = userDefaults.string(forKey: binaryVersionKey)
37
47
  let result = BundleDropOtaResolver.resolve(
38
48
  bundleDropRoot: bundleDropRoot,
@@ -23,6 +23,16 @@ final class BundleDropModule: NSObject {
23
23
  resolve(nil)
24
24
  }
25
25
 
26
+ @objc
27
+ func setOtaEnabled(
28
+ _ enabled: Bool,
29
+ resolve: @escaping RCTPromiseResolveBlock,
30
+ reject: @escaping RCTPromiseRejectBlock
31
+ ) {
32
+ UserDefaults.standard.set(enabled, forKey: BundleDropLocator.otaEnabledKey)
33
+ resolve(nil)
34
+ }
35
+
26
36
  @objc
27
37
  func restartReactNative() {
28
38
  DispatchQueue.main.async {
@@ -1,2 +1,3 @@
1
1
  export declare function getDownloadedBundlePathNative(): Promise<string | null>;
2
2
  export declare function restartReactNativeNative(): void;
3
+ export declare function setOtaEnabledNative(enabled: boolean): Promise<void>;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getDownloadedBundlePathNative = getDownloadedBundlePathNative;
4
4
  exports.restartReactNativeNative = restartReactNativeNative;
5
+ exports.setOtaEnabledNative = setOtaEnabledNative;
5
6
  const react_native_1 = require("react-native");
6
7
  const { BundleDrop } = react_native_1.NativeModules;
7
8
  async function getDownloadedBundlePathNative() {
@@ -20,3 +21,16 @@ async function getDownloadedBundlePathNative() {
20
21
  function restartReactNativeNative() {
21
22
  BundleDrop?.restartReactNative?.();
22
23
  }
24
+ async function setOtaEnabledNative(enabled) {
25
+ if (!BundleDrop?.setOtaEnabled)
26
+ return;
27
+ try {
28
+ await BundleDrop.setOtaEnabled(enabled);
29
+ }
30
+ catch (e) {
31
+ // Best-effort; native may not support this method on older versions.
32
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
33
+ console.debug('BundleDrop.setOtaEnabled failed (best-effort):', e);
34
+ }
35
+ }
36
+ }
@@ -38,8 +38,10 @@ const DEFAULT_STATUS = 'Click the button to check for updates';
38
38
  const DISABLED_STATUS = 'BundleDrop is disabled';
39
39
  let updateFlowActive = false;
40
40
  let startupPromise = null;
41
+ let localStartupPromise = null;
41
42
  let healthTimer = null;
42
43
  let runtimeRestartRequested = false;
44
+ let activeBundleInfoForObservability = null;
43
45
  let snapshot = {
44
46
  status: DISABLED_STATUS,
45
47
  isBusy: false,
@@ -221,10 +223,15 @@ async function withBusy(fn) {
221
223
  async function waitForStartupIfNeeded() {
222
224
  await startupPromise;
223
225
  }
224
- async function runStartupFlow() {
225
- const runtime = (0, initState_1.assertBundleDropInitialized)();
226
- const statusCb = status => emitStatus(status);
227
- void (0, fsUtils_1.cleanOrphanedTempZips)(`${context_1.BUNDLE_DROP_ROOT}/bundles`);
226
+ async function waitForLocalStartupIfNeeded() {
227
+ try {
228
+ await localStartupPromise;
229
+ }
230
+ catch {
231
+ activeBundleInfoForObservability = null;
232
+ }
233
+ }
234
+ async function runLocalStartupFlow() {
228
235
  const [bundleInfo, bundlePath, currentPointer, rollbackState] = await Promise.all([
229
236
  (0, bundleInfo_1.readBundleInfo)(),
230
237
  (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
@@ -233,6 +240,20 @@ async function runStartupFlow() {
233
240
  ]);
234
241
  await (0, updateState_1.reconcileAppliedBundleOnLaunch)({ bundleInfo, bundlePath });
235
242
  await refreshState({ bundleInfo, bundlePath });
243
+ const state = await (0, updateState_1.getUpdateState)({ bundlePath });
244
+ activeBundleInfoForObservability = state.hasBundle ? state.info || null : null;
245
+ return {
246
+ bundlePath,
247
+ currentPointer,
248
+ rollbackState,
249
+ };
250
+ }
251
+ async function runStartupFlow() {
252
+ const runtime = (0, initState_1.assertBundleDropInitialized)();
253
+ const statusCb = status => emitStatus(status);
254
+ void (0, fsUtils_1.cleanOrphanedTempZips)(`${context_1.BUNDLE_DROP_ROOT}/bundles`);
255
+ localStartupPromise = runLocalStartupFlow();
256
+ const { bundlePath, currentPointer, rollbackState } = await localStartupPromise;
236
257
  const rollbackPolicy = (0, rollbackState_1.getRollbackPolicy)();
237
258
  const rollbackResult = await (0, rollbackState_1.rollbackToPreviousIfNeeded)(rollbackPolicy, {
238
259
  currentPointer,
@@ -338,7 +359,10 @@ function initBundleDrop(options) {
338
359
  const { alreadyInitialized, config } = (0, initState_1.initializeBundleDropRuntime)(options);
339
360
  if (!alreadyInitialized) {
340
361
  runtimeRestartRequested = false;
362
+ activeBundleInfoForObservability = null;
341
363
  }
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);
342
366
  patchSnapshot({
343
367
  channelName: config.channelName,
344
368
  isEnabled: config.enabled,
@@ -504,13 +528,14 @@ async function installBundleFromListItem(bundle) {
504
528
  return { result: { status: 'disabled' }, status: DISABLED_STATUS };
505
529
  }
506
530
  await waitForStartupIfNeeded();
507
- if (!bundle.downloadUrl) {
531
+ const downloadUrl = bundle.downloadUrl;
532
+ if (!downloadUrl) {
508
533
  const status = '⚠️ Bundle is not downloadable (expired or unavailable)';
509
534
  emitStatus(status);
510
535
  return { result: { status: 'incompatible' }, status };
511
536
  }
512
537
  return withBusy(async () => {
513
- const result = await (0, downloadAndInstall_1.installBundle)(bundle.hash, bundle.downloadUrl, bundle.bundleVersion, bundle.version, bundle.runtimeVersion, {
538
+ const result = await (0, downloadAndInstall_1.installBundle)(bundle.hash, downloadUrl, bundle.bundleVersion, bundle.version, bundle.runtimeVersion, {
514
539
  channelName: runtime.channelName,
515
540
  onStatusUpdate: emitStatus,
516
541
  });
@@ -535,6 +560,20 @@ async function getInstalledBundleInfo() {
535
560
  const state = await refreshState();
536
561
  return state.info || null;
537
562
  }
563
+ function getEmbeddedObservabilityContext() {
564
+ return {
565
+ source: 'embedded',
566
+ dist: 'embedded',
567
+ tags: {
568
+ bundle_drop_hash: null,
569
+ bundle_drop_channel: null,
570
+ bundle_drop_version: null,
571
+ bundle_drop_runtime_version: null,
572
+ bundle_drop_platform: null,
573
+ },
574
+ context: null,
575
+ };
576
+ }
538
577
  /**
539
578
  * Pre-formatted context for error tracking integrations.
540
579
  *
@@ -547,20 +586,14 @@ async function getInstalledBundleInfo() {
547
586
  * executing, so the context falls back to `'embedded'`.
548
587
  */
549
588
  async function getObservabilityContext() {
550
- const info = await getInstalledBundleInfo();
589
+ const runtime = getEnabledRuntime();
590
+ if (!runtime) {
591
+ return getEmbeddedObservabilityContext();
592
+ }
593
+ await waitForLocalStartupIfNeeded();
594
+ const info = activeBundleInfoForObservability;
551
595
  if (!info || info.pendingApply || !info.hash) {
552
- return {
553
- source: 'embedded',
554
- dist: 'embedded',
555
- tags: {
556
- bundle_drop_hash: null,
557
- bundle_drop_channel: null,
558
- bundle_drop_version: null,
559
- bundle_drop_runtime_version: null,
560
- bundle_drop_platform: null,
561
- },
562
- context: null,
563
- };
596
+ return getEmbeddedObservabilityContext();
564
597
  }
565
598
  return {
566
599
  source: 'ota',
@@ -646,6 +679,8 @@ function resetBundleDropRuntimeServiceForTests() {
646
679
  clearHealthTimer();
647
680
  updateFlowActive = false;
648
681
  startupPromise = null;
682
+ localStartupPromise = null;
683
+ activeBundleInfoForObservability = null;
649
684
  snapshot = {
650
685
  status: DISABLED_STATUS,
651
686
  isBusy: false,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@gfean/react-native-bundle-drop",
3
- "version": "0.3.6",
4
- "nativeVersion": "0.3.6",
3
+ "version": "0.3.7",
4
+ "nativeVersion": "0.3.7",
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",