@gfean/react-native-bundle-drop 0.1.85 → 0.1.94

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.
package/CLIENT_README.md CHANGED
@@ -162,6 +162,44 @@ npx bundle-drop upload android \
162
162
  --author "CI Pipeline"
163
163
  ```
164
164
 
165
+ ### Upload result file
166
+
167
+ After a successful upload, the CLI writes a result file inside the module directory at `node_modules/@gfean/react-native-bundle-drop/dist/bundle-drop-result.json` with all upload details:
168
+
169
+ ```json
170
+ {
171
+ "platform": "android",
172
+ "appVersion": "1.2.3",
173
+ "channel": "General",
174
+ "orgSlug": "my-org",
175
+ "projectSlug": "my-app",
176
+ "runtimeVersion": "1.0.0",
177
+ "bundleId": "abc123",
178
+ "bundleVersion": 42,
179
+ "bundleVersionLabel": "v42",
180
+ "hash": "sha256hex...",
181
+ "releaseNotes": "Bug fixes",
182
+ "author": "CI Pipeline"
183
+ }
184
+ ```
185
+
186
+ Use this in CI to read any field — no output parsing needed:
187
+
188
+ ```bash
189
+ BD_RESULT="node_modules/@gfean/react-native-bundle-drop/dist/bundle-drop-result.json"
190
+
191
+ # Read any field
192
+ jq -r '.bundleVersionLabel' "$BD_RESULT"
193
+ jq -r '.appVersion' "$BD_RESULT"
194
+ jq -r '.channel' "$BD_RESULT"
195
+
196
+ # Azure DevOps
197
+ echo "##vso[task.setvariable variable=BundleVersion]$(jq -r '.bundleVersionLabel' "$BD_RESULT")"
198
+
199
+ # GitHub Actions
200
+ echo "bundle_version=$(jq -r '.bundleVersionLabel' "$BD_RESULT")" >> "$GITHUB_OUTPUT"
201
+ ```
202
+
165
203
  ## 9) Native setup (Android)
166
204
 
167
205
  The only change in your `MainApplication` (Kotlin or Java) is a single override that delegates bundle resolution to BundleDrop. It returns the OTA bundle path when available, otherwise falls back to the default.
package/README.md CHANGED
@@ -8,12 +8,6 @@ yarn add @gfean/react-native-bundle-drop
8
8
  cd ios && pod install && cd ..
9
9
  ```
10
10
 
11
- Add the Android bootstrap side-effect import once (images resolver patch):
12
- ```js
13
- // index.js (or entry file)
14
- import '@gfean/react-native-bundle-drop/bootstrap';
15
- ```
16
-
17
11
  ### Metro config (to resolve bundle.drop.config.js from node_modules)
18
12
  If Metro cannot resolve `bundle.drop.config.js` from within `node_modules`, add an alias in `metro.config.js`:
19
13
  ```js
@@ -23,6 +23,9 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
23
23
  var latestBundlePath: String? = null
24
24
  private set
25
25
 
26
+ private const val PREFS_NAME = "BundleDropPrefs"
27
+ private const val KEY_BINARY_VERSION = "binary_version"
28
+
26
29
  private fun currentJsonPath(context: Context): File {
27
30
  return File(context.filesDir, "bundle-drop/current.json")
28
31
  }
@@ -51,16 +54,65 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
51
54
  return if (file.exists()) file.absolutePath else null
52
55
  }
53
56
 
54
- // Call this from MainApplication.kt to fetch the custom bundle path
57
+ private fun getBinaryVersionKey(context: Context): String {
58
+ val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)
59
+ val versionName = pInfo.versionName ?: "unknown"
60
+ @Suppress("DEPRECATION")
61
+ val versionCode = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
62
+ pInfo.longVersionCode
63
+ } else {
64
+ pInfo.versionCode.toLong()
65
+ }
66
+ return "$versionName-$versionCode"
67
+ }
68
+
69
+ private fun getStoredBinaryVersion(context: Context): String? {
70
+ return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
71
+ .getString(KEY_BINARY_VERSION, null)
72
+ }
73
+
74
+ private fun setStoredBinaryVersion(context: Context, version: String) {
75
+ context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
76
+ .edit().putString(KEY_BINARY_VERSION, version).apply()
77
+ }
78
+
79
+ private fun clearOtaState(context: Context) {
80
+ try {
81
+ val root = File(context.filesDir, "bundle-drop")
82
+ val filesToClear = listOf(
83
+ File(root, "current.json"),
84
+ File(root, "previous.json"),
85
+ File(root, "state.json"),
86
+ File(context.filesDir, "bundle-info.json"),
87
+ )
88
+ filesToClear.forEach { if (it.exists()) it.delete() }
89
+ } catch (e: Exception) {
90
+ Log.w("BundleDrop", "Failed to clear OTA state: ${e.message}", e)
91
+ }
92
+ }
93
+
55
94
  fun getDownloadedBundlePath(context: Context): String? {
56
95
  val path = readCurrentPointer(context) ?: legacyBundlePath(context)
57
- return if (path != null) {
58
- Log.d("BundleDrop", "🔁 Using OTA bundle at: $path")
59
- path
60
- } else {
96
+
97
+ if (path == null) {
98
+ setStoredBinaryVersion(context, getBinaryVersionKey(context))
61
99
  Log.d("BundleDrop", "📦 No OTA bundle found.")
62
- null
100
+ return null
63
101
  }
102
+
103
+ val currentVersion = getBinaryVersionKey(context)
104
+ val lastVersion = getStoredBinaryVersion(context)
105
+
106
+ if (lastVersion != null && lastVersion != currentVersion) {
107
+ Log.d("BundleDrop", "Binary updated ($lastVersion → $currentVersion), clearing OTA bundle")
108
+ clearOtaState(context)
109
+ setStoredBinaryVersion(context, currentVersion)
110
+ return null
111
+ }
112
+
113
+ setStoredBinaryVersion(context, currentVersion)
114
+ Log.d("BundleDrop", "🔁 Using OTA bundle at: $path")
115
+ return path
64
116
  }
65
117
 
66
118
  @JvmStatic
@@ -112,12 +164,20 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
112
164
 
113
165
  @ReactMethod(isBlockingSynchronousMethod = true)
114
166
  fun getImageManifestSync(): String? {
167
+ return readImageManifestRaw()
168
+ }
169
+
170
+ @ReactMethod
171
+ fun getImageManifest(promise: Promise) {
172
+ promise.resolve(readImageManifestRaw())
173
+ }
174
+
175
+ private fun readImageManifestRaw(): String? {
115
176
  val context = reactApplicationContext
116
177
  val current = readCurrentPointer(context) ?: return null
117
178
  val bundleDir = File(current).parentFile ?: return null
118
- val path = File(bundleDir, "image-manifest.json").absolutePath
119
179
  return try {
120
- val file = File(path)
180
+ val file = File(bundleDir, "image-manifest.json")
121
181
  if (file.exists()) file.readText() else null
122
182
  } catch (e: Exception) {
123
183
  Log.e("BundleDrop", "Failed to read manifest: ${e.message}", e)
@@ -1,22 +1,61 @@
1
1
  import Foundation
2
2
 
3
3
  @objc public final class BundleDropLocator: NSObject {
4
+
5
+ private static let binaryVersionKey = "BundleDropBinaryVersion"
6
+
7
+ private static func getBinaryVersionKey() -> String {
8
+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
9
+ let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"
10
+ return "\(version)-\(build)"
11
+ }
12
+
13
+ private static func clearOtaState(root: URL) {
14
+ let fm = FileManager.default
15
+ let filesToClear = [
16
+ root.appendingPathComponent("current.json"),
17
+ root.appendingPathComponent("previous.json"),
18
+ root.appendingPathComponent("state.json"),
19
+ ]
20
+ filesToClear.forEach { try? fm.removeItem(at: $0) }
21
+
22
+ if let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first {
23
+ try? fm.removeItem(at: docs.appendingPathComponent("bundle-info.json"))
24
+ }
25
+ }
26
+
4
27
  @objc public static func bundleURL() -> URL? {
5
28
  let fm = FileManager.default
6
29
  guard let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first else { return nil }
7
30
  let root = lib.appendingPathComponent("bundle-drop", isDirectory: true)
8
31
  let current = root.appendingPathComponent("current.json")
9
32
 
10
- if fm.fileExists(atPath: current.path) {
11
- do {
12
- let data = try Data(contentsOf: current)
13
- let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
14
- guard let bundlePath = obj?["bundlePath"] as? String else { return nil }
15
- let url = URL(fileURLWithPath: bundlePath)
16
- return fm.fileExists(atPath: url.path) ? url : nil
17
- } catch {
18
- print("⚠️ BundleDrop: failed reading current.json: \(error)")
19
- }
33
+ let currentVersion = getBinaryVersionKey()
34
+
35
+ guard fm.fileExists(atPath: current.path) else {
36
+ UserDefaults.standard.set(currentVersion, forKey: binaryVersionKey)
37
+ return nil
38
+ }
39
+
40
+ let lastVersion = UserDefaults.standard.string(forKey: binaryVersionKey)
41
+ if let lastVersion = lastVersion, lastVersion != currentVersion {
42
+ print("BundleDrop: Binary updated (\(lastVersion) → \(currentVersion)), clearing OTA bundle")
43
+ clearOtaState(root: root)
44
+ UserDefaults.standard.set(currentVersion, forKey: binaryVersionKey)
45
+ return nil
46
+ }
47
+
48
+ do {
49
+ let data = try Data(contentsOf: current)
50
+ let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any]
51
+ guard let bundlePath = obj?["bundlePath"] as? String else { return nil }
52
+ let url = URL(fileURLWithPath: bundlePath)
53
+ guard fm.fileExists(atPath: url.path) else { return nil }
54
+
55
+ UserDefaults.standard.set(currentVersion, forKey: binaryVersionKey)
56
+ return url
57
+ } catch {
58
+ print("⚠️ BundleDrop: failed reading current.json: \(error)")
20
59
  }
21
60
 
22
61
  return nil
@@ -125,6 +125,7 @@ async function initConfig(params) {
125
125
  }
126
126
  const content = `module.exports = {
127
127
  serverUrl: '${resolvedServerUrl}',
128
+ defaultChannel: 'General',
128
129
  runtimeVersion: {
129
130
  ios: '1.0.0',
130
131
  android: '1.0.0',
@@ -217,7 +217,33 @@ async function upload(platform, options) {
217
217
  maxContentLength: Infinity,
218
218
  maxBodyLength: Infinity,
219
219
  });
220
- ui_1.log.success(`✅ Upload complete (bundleId: ${res.data?.bundleId || 'N/A'})`);
220
+ const result = {
221
+ platform,
222
+ appVersion: version ?? null,
223
+ channel: channel ?? null,
224
+ orgSlug: orgSlug ?? null,
225
+ projectSlug: projectSlug ?? null,
226
+ runtimeVersion: res.data?.runtimeVersion ?? runtimeVersion ?? null,
227
+ bundleId: res.data?.bundleId ?? null,
228
+ bundleVersion: res.data?.bundleVersion ?? null,
229
+ bundleVersionLabel: res.data?.bundleVersionLabel ?? null,
230
+ hash: res.data?.hash ?? null,
231
+ releaseNotes: releaseNotes ?? null,
232
+ author: options.author ?? null,
233
+ };
234
+ ui_1.log.success(`✅ Upload complete`);
235
+ if (result.bundleVersion != null)
236
+ ui_1.log.label('Bundle Version', `${result.bundleVersion}`);
237
+ if (result.bundleVersionLabel)
238
+ ui_1.log.label('Bundle Label', result.bundleVersionLabel);
239
+ if (result.hash)
240
+ ui_1.log.label('Hash', result.hash);
241
+ const resultDir = path.join(packageRoot, 'dist');
242
+ if (!fs.existsSync(resultDir))
243
+ fs.mkdirSync(resultDir, { recursive: true });
244
+ const resultPath = path.join(resultDir, 'bundle-drop-result.json');
245
+ fs.writeFileSync(resultPath, JSON.stringify(result, null, 2));
246
+ ui_1.log.label('Result file', resultPath);
221
247
  }
222
248
  catch (err) {
223
249
  const raw = err?.response?.data || err.message;
package/lib/bootstrap.js CHANGED
@@ -4,7 +4,9 @@ const context_1 = require("./context");
4
4
  const injectImageResolver_1 = require("./injectImageResolver");
5
5
  const patchImageAutoResolve_1 = require("./patchImageAutoResolve");
6
6
  // Patch early so assets bundled with the app (before OTA) still resolve on Android.
7
+ // Image.render is patched synchronously (cheap), but the manifest-based resolver
8
+ // loads asynchronously to avoid blocking the JS thread with a sync native bridge call.
7
9
  if (!context_1.isIOS) {
8
- (0, injectImageResolver_1.injectBundleDropImageResolver)();
9
10
  (0, patchImageAutoResolve_1.patchImageRenderToForceResolve)();
11
+ (0, injectImageResolver_1.injectBundleDropImageResolverAsync)().catch(() => { });
10
12
  }
package/lib/context.d.ts CHANGED
@@ -2,4 +2,5 @@ export declare const config: import("./loadConfig").BundleDropProjectConfig;
2
2
  export declare const platform: string;
3
3
  export declare const isIOS: boolean;
4
4
  export declare const runtimeVersion: string;
5
+ export declare const defaultChannel: string;
5
6
  export declare const BUNDLE_DROP_ROOT: string;
package/lib/context.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.BUNDLE_DROP_ROOT = exports.runtimeVersion = exports.isIOS = exports.platform = exports.config = void 0;
6
+ exports.BUNDLE_DROP_ROOT = exports.defaultChannel = exports.runtimeVersion = exports.isIOS = exports.platform = exports.config = void 0;
7
7
  const react_native_1 = require("react-native");
8
8
  const fs_1 = __importDefault(require("./native/fs"));
9
9
  const loadConfig_1 = require("./loadConfig");
@@ -11,6 +11,7 @@ exports.config = (0, loadConfig_1.loadConfig)();
11
11
  exports.platform = react_native_1.Platform.OS === 'ios' ? 'ios' : 'android';
12
12
  exports.isIOS = exports.platform === 'ios';
13
13
  exports.runtimeVersion = exports.config.runtimeVersion?.[exports.platform];
14
+ exports.defaultChannel = exports.config.defaultChannel || 'General';
14
15
  exports.BUNDLE_DROP_ROOT = exports.isIOS
15
16
  ? `${fs_1.default.LibraryDirectoryPath}/bundle-drop`
16
17
  : `${fs_1.default.DocumentDirectoryPath}/bundle-drop`;
package/lib/fs/fsUtils.js CHANGED
@@ -14,12 +14,23 @@ async function ensureDir(dir) {
14
14
  }
15
15
  }
16
16
  async function atomicWriteJson(path, data) {
17
- const tmp = `${path}.tmp`;
18
- await fs_1.default.writeFile(tmp, JSON.stringify(data), 'utf8');
19
- if (await fs_1.default.exists(path)) {
20
- await fs_1.default.unlink(path);
17
+ const tmp = `${path}.${Date.now()}_${Math.random().toString(36).slice(2, 8)}.tmp`;
18
+ try {
19
+ await fs_1.default.writeFile(tmp, JSON.stringify(data), 'utf8');
20
+ try {
21
+ await fs_1.default.unlink(path);
22
+ }
23
+ catch { /* already removed by concurrent writer */ }
24
+ await fs_1.default.moveFile(tmp, path);
25
+ }
26
+ catch {
27
+ // Atomic rename failed (concurrent writer moved/removed our tmp); fall back to direct write.
28
+ await fs_1.default.writeFile(path, JSON.stringify(data), 'utf8');
29
+ try {
30
+ await fs_1.default.unlink(tmp);
31
+ }
32
+ catch { /* clean up orphaned tmp if it exists */ }
21
33
  }
22
- await fs_1.default.moveFile(tmp, path);
23
34
  }
24
35
  async function ensureParentDir(filePath) {
25
36
  const dir = filePath.substring(0, filePath.lastIndexOf('/'));
@@ -28,11 +39,21 @@ async function ensureParentDir(filePath) {
28
39
  }
29
40
  }
30
41
  async function writeFileAtomicBase64(path, base64) {
31
- const tmp = `${path}.tmp`;
42
+ const tmp = `${path}.${Date.now()}_${Math.random().toString(36).slice(2, 8)}.tmp`;
32
43
  await ensureParentDir(path);
33
- await fs_1.default.writeFile(tmp, base64, 'base64');
34
- if (await fs_1.default.exists(path)) {
35
- await fs_1.default.unlink(path);
44
+ try {
45
+ await fs_1.default.writeFile(tmp, base64, 'base64');
46
+ try {
47
+ await fs_1.default.unlink(path);
48
+ }
49
+ catch { /* already removed by concurrent writer */ }
50
+ await fs_1.default.moveFile(tmp, path);
51
+ }
52
+ catch {
53
+ await fs_1.default.writeFile(path, base64, 'base64');
54
+ try {
55
+ await fs_1.default.unlink(tmp);
56
+ }
57
+ catch { /* clean up orphaned tmp if it exists */ }
36
58
  }
37
- await fs_1.default.moveFile(tmp, path);
38
59
  }
@@ -1,2 +1,3 @@
1
1
  export declare function patchImageResolverWithManifest(manifest: Record<string, string>): void;
2
2
  export declare function injectBundleDropImageResolver(manifestOverride?: Record<string, string>): void;
3
+ export declare function injectBundleDropImageResolverAsync(): Promise<void>;
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.patchImageResolverWithManifest = patchImageResolverWithManifest;
7
7
  exports.injectBundleDropImageResolver = injectBundleDropImageResolver;
8
+ exports.injectBundleDropImageResolverAsync = injectBundleDropImageResolverAsync;
8
9
  const react_native_1 = require("react-native");
9
10
  const fs_1 = __importDefault(require("./native/fs"));
10
11
  let hasPatched = false;
@@ -90,10 +91,8 @@ function patchImageResolverWithManifest(manifest) {
90
91
  if (finalPath) {
91
92
  const hasExtension = /\.[a-zA-Z0-9]+$/.test(finalPath);
92
93
  const fullPath = `file://${fs_1.default.DocumentDirectoryPath}/${finalPath}${hasExtension ? '' : (uri.match(/\.[^.]+$/)?.[0] ?? '')}`;
93
- console.log(`🧩 Overriding asset path: ${uri} → ${fullPath}`);
94
94
  return { ...resolved, uri: fullPath };
95
95
  }
96
- console.warn('🧩 No matching key found in manifest for URI:', uri);
97
96
  return resolved;
98
97
  };
99
98
  }
@@ -106,16 +105,31 @@ function injectBundleDropImageResolver(manifestOverride) {
106
105
  let manifest = manifestOverride;
107
106
  if (!manifest) {
108
107
  const raw = BundleDrop.getImageManifestSync?.();
109
- if (!raw) {
110
- console.warn('🧩 No manifest returned from native');
108
+ if (!raw)
111
109
  return;
112
- }
113
110
  manifest = JSON.parse(raw);
114
111
  }
115
112
  patchImageResolverWithManifest(manifest);
116
113
  hasPatched = true;
117
114
  }
118
- catch (e) {
119
- console.warn('🧩 Failed to patch image resolver:', e.message);
115
+ catch {
116
+ // Silently ignore – async path will retry
117
+ }
118
+ }
119
+ async function injectBundleDropImageResolverAsync() {
120
+ if (react_native_1.Platform.OS !== 'android')
121
+ return;
122
+ if (hasPatched)
123
+ return;
124
+ try {
125
+ const raw = await BundleDrop.getImageManifest?.();
126
+ if (!raw)
127
+ return;
128
+ const manifest = JSON.parse(raw);
129
+ patchImageResolverWithManifest(manifest);
130
+ hasPatched = true;
131
+ }
132
+ catch {
133
+ // Non-critical: images fall back to default resolution
120
134
  }
121
135
  }
@@ -13,6 +13,7 @@ export type BundleDropProjectConfig = {
13
13
  ios: string;
14
14
  android: string;
15
15
  };
16
+ defaultChannel?: string;
16
17
  rollback?: {
17
18
  maxCrashCount?: number;
18
19
  crashWindowSec?: number;
@@ -14,7 +14,7 @@ const errors_1 = require("../errors");
14
14
  const rollbackState_1 = require("./rollbackState");
15
15
  async function downloadAndStageUpdate(options, onStatusUpdate) {
16
16
  const { project } = context_1.config;
17
- const channelName = options?.channelName || 'General';
17
+ const channelName = options?.channelName || context_1.defaultChannel;
18
18
  const platform = context_1.platform;
19
19
  const statusCb = onStatusUpdate;
20
20
  const resolvedTarget = options?.resolvedTarget;
@@ -126,7 +126,7 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
126
126
  pendingApply: true,
127
127
  runtimeVersion: metadataFromZip.runtimeVersion ?? serverRuntimeVersion ?? context_1.runtimeVersion ?? undefined,
128
128
  };
129
- (0, bundleInfo_1.writeBundleInfo)(installedInfo);
129
+ await (0, bundleInfo_1.writeBundleInfo)(installedInfo);
130
130
  await (0, bundlePointer_1.setCurrentBundlePointer)(bundlePath, installedHash);
131
131
  await (0, rollbackState_1.markCandidateActivated)(installedHash);
132
132
  return { status: 'staged', bundlePath, hash: installedHash };
@@ -5,28 +5,43 @@ const downloadAndInstall_1 = require("./downloadAndInstall");
5
5
  const updateCheck_1 = require("./updateCheck");
6
6
  const updateState_1 = require("./updateState");
7
7
  const rollbackState_1 = require("./rollbackState");
8
+ const bundleInfo_1 = require("../bundleInfo");
9
+ const context_1 = require("../context");
10
+ const bundlePointer_1 = require("../fs/bundlePointer");
8
11
  const bundleDropNative_1 = require("../native/bundleDropNative");
9
12
  async function initUpdateManager(opts) {
10
13
  const policy = opts?.policy || 'manual';
11
- const channelName = opts?.channelName || 'General';
14
+ const channelName = opts?.channelName || context_1.defaultChannel;
12
15
  const statusCb = opts?.onStatusUpdate;
13
- // Reconcile pending state on launch (assume downloaded bundle is active if present).
14
- await (0, updateState_1.reconcileAppliedBundleOnLaunch)();
16
+ // Prefetch all startup data in parallel (single bridge round-trip instead of
17
+ // 8+ sequential reads across reconcile / rollback / commit / getUpdateState).
18
+ const [bundleInfo, bundlePath, currentPointer, rollbackStateData] = await Promise.all([
19
+ (0, bundleInfo_1.readBundleInfo)(),
20
+ (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
21
+ (0, bundlePointer_1.readCurrentBundlePointer)(),
22
+ (0, rollbackState_1.readRollbackState)(),
23
+ ]);
24
+ await (0, updateState_1.reconcileAppliedBundleOnLaunch)({ bundleInfo, bundlePath });
15
25
  const rollbackPolicy = (0, rollbackState_1.getRollbackPolicy)();
16
- const rollbackResult = await (0, rollbackState_1.rollbackToPreviousIfNeeded)(rollbackPolicy);
26
+ const rollbackResult = await (0, rollbackState_1.rollbackToPreviousIfNeeded)(rollbackPolicy, {
27
+ currentPointer,
28
+ rollbackState: rollbackStateData,
29
+ });
17
30
  if (rollbackResult.rolledBack) {
18
31
  statusCb?.('↩️ Rolled back to previous bundle');
19
32
  (0, bundleDropNative_1.restartReactNativeNative)();
20
33
  return;
21
34
  }
22
- // If we got this far, JS booted successfully for the current bundle.
23
- await (0, rollbackState_1.commitActiveBundle)();
24
- const pendingState = await (0, updateState_1.getUpdateState)();
35
+ await (0, rollbackState_1.commitActiveBundle)({ currentPointer });
36
+ // bundlePath hasn't changed; let bundleInfo re-read (reconcile may have updated it).
37
+ const pendingState = await (0, updateState_1.getUpdateState)({ bundlePath });
25
38
  if (pendingState.pendingApply) {
26
39
  if (policy === 'immediate') {
27
40
  statusCb?.('♻️ Applying previously downloaded update...');
28
- await (0, updateState_1.applyUpdate)(statusCb);
29
- return;
41
+ const applyResult = await (0, updateState_1.applyUpdate)(statusCb);
42
+ if (applyResult.status === 'applied')
43
+ return;
44
+ // 'alreadyApplied' or 'noBundle' — fall through to checkForUpdate
30
45
  }
31
46
  if (policy === 'on-next-launch') {
32
47
  statusCb?.('✅ Update downloaded; will apply on next launch.');
@@ -1,3 +1,4 @@
1
+ import { type BundlePointer } from '../fs/bundlePointer';
1
2
  export type RollbackPolicy = {
2
3
  maxCrashCount?: number;
3
4
  crashWindowSec?: number;
@@ -13,13 +14,23 @@ export type RollbackState = {
13
14
  crashWindowStartedAt?: number;
14
15
  lastLaunchAt?: number;
15
16
  };
17
+ declare function readState(): Promise<RollbackState | null>;
18
+ export { readState as readRollbackState };
16
19
  export declare function markCandidateActivated(hash: string): Promise<void>;
17
- export declare function commitActiveBundle(): Promise<void>;
18
- export declare function evaluateRollbackOnLaunch(policy?: RollbackPolicy): Promise<{
20
+ export declare function commitActiveBundle(cached?: {
21
+ currentPointer?: BundlePointer | null;
22
+ }): Promise<void>;
23
+ export declare function evaluateRollbackOnLaunch(policy?: RollbackPolicy, cached?: {
24
+ currentPointer?: BundlePointer | null;
25
+ rollbackState?: RollbackState | null;
26
+ }): Promise<{
19
27
  shouldRollback: boolean;
20
28
  reason?: 'crash_loop' | 'commit_timeout';
21
29
  }>;
22
- export declare function rollbackToPreviousIfNeeded(policy?: RollbackPolicy): Promise<{
30
+ export declare function rollbackToPreviousIfNeeded(policy?: RollbackPolicy, cached?: {
31
+ currentPointer?: BundlePointer | null;
32
+ rollbackState?: RollbackState | null;
33
+ }): Promise<{
23
34
  rolledBack: boolean;
24
35
  reason?: 'crash_loop' | 'commit_timeout';
25
36
  }>;
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readRollbackState = readState;
6
7
  exports.markCandidateActivated = markCandidateActivated;
7
8
  exports.commitActiveBundle = commitActiveBundle;
8
9
  exports.evaluateRollbackOnLaunch = evaluateRollbackOnLaunch;
@@ -66,8 +67,8 @@ async function markCandidateActivated(hash) {
66
67
  lastGoodHash: previousHash ?? undefined,
67
68
  });
68
69
  }
69
- async function commitActiveBundle() {
70
- const current = await (0, bundlePointer_1.readCurrentBundlePointer)();
70
+ async function commitActiveBundle(cached) {
71
+ const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
71
72
  const hash = current?.hash;
72
73
  if (!hash)
73
74
  return;
@@ -80,13 +81,13 @@ async function commitActiveBundle() {
80
81
  lastGoodHash: hash,
81
82
  });
82
83
  }
83
- async function evaluateRollbackOnLaunch(policy) {
84
- const current = await (0, bundlePointer_1.readCurrentBundlePointer)();
84
+ async function evaluateRollbackOnLaunch(policy, cached) {
85
+ const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
85
86
  const activeHash = current?.hash;
86
87
  if (!activeHash)
87
88
  return { shouldRollback: false };
88
89
  const now = nowSec();
89
- const state = (await readState()) || {};
90
+ const state = (cached?.rollbackState !== undefined ? cached.rollbackState : await readState()) || {};
90
91
  const normalized = normalizePolicy(policy);
91
92
  const next = {
92
93
  ...state,
@@ -115,8 +116,8 @@ async function evaluateRollbackOnLaunch(policy) {
115
116
  await writeState(next);
116
117
  return { shouldRollback: false };
117
118
  }
118
- async function rollbackToPreviousIfNeeded(policy) {
119
- const decision = await evaluateRollbackOnLaunch(policy);
119
+ async function rollbackToPreviousIfNeeded(policy, cached) {
120
+ const decision = await evaluateRollbackOnLaunch(policy, cached);
120
121
  if (!decision.shouldRollback)
121
122
  return { rolledBack: false };
122
123
  const res = await rollbackToPreviousOrNative();
@@ -6,6 +6,7 @@ exports.getInstalledBundleInfo = getInstalledBundleInfo;
6
6
  const context_1 = require("../context");
7
7
  const bundleInfo_1 = require("../bundleInfo");
8
8
  const clientApi_1 = require("../api/clientApi");
9
+ const context_2 = require("../context");
9
10
  const bundlePointer_1 = require("../fs/bundlePointer");
10
11
  const installId_1 = require("../fs/installId");
11
12
  const userProperties_1 = require("../fs/userProperties");
@@ -28,19 +29,19 @@ async function getAvailableChannels() {
28
29
  throw e;
29
30
  }
30
31
  }
31
- async function checkForUpdate(channelName = 'General', onStatusUpdate) {
32
+ async function checkForUpdate(channelName = context_2.defaultChannel, onStatusUpdate) {
32
33
  const { project } = context_1.config;
33
- const local = await (0, bundleInfo_1.readBundleInfo)();
34
34
  try {
35
35
  onStatusUpdate?.('🔍 Checking for updates...');
36
- const [currentPtr, previousPtr, currentUserProperties] = await Promise.all([
36
+ const [local, currentPtr, previousPtr, currentUserProperties, installId] = await Promise.all([
37
+ (0, bundleInfo_1.readBundleInfo)(),
37
38
  (0, bundlePointer_1.readCurrentBundlePointer)(),
38
39
  (0, bundlePointer_1.readPreviousBundlePointer)(),
39
40
  (0, userProperties_1.getCurrentUserProperties)(),
41
+ (0, installId_1.getOrCreateInstallId)(),
40
42
  ]);
41
43
  const currentHash = currentPtr?.hash ?? local?.hash ?? null;
42
44
  const previousHash = previousPtr?.hash ?? null;
43
- const installId = await (0, installId_1.getOrCreateInstallId)();
44
45
  const res = await (0, clientApi_1.postOtaResolve)(project.slug, {
45
46
  channelName,
46
47
  platform: context_1.platform,
@@ -1,3 +1,4 @@
1
+ import { BundleInfo } from '../bundleInfo';
1
2
  export type ApplyUpdateResult = {
2
3
  status: 'applied';
3
4
  } | {
@@ -5,10 +6,16 @@ export type ApplyUpdateResult = {
5
6
  } | {
6
7
  status: 'alreadyApplied';
7
8
  };
8
- export declare const getUpdateState: () => Promise<{
9
+ export declare const getUpdateState: (cached?: {
10
+ bundleInfo?: BundleInfo | null;
11
+ bundlePath?: string | null;
12
+ }) => Promise<{
9
13
  hasBundle: boolean;
10
- info: import("../bundleInfo").BundleInfo;
14
+ info: BundleInfo;
11
15
  pendingApply: boolean;
12
16
  }>;
13
- export declare const reconcileAppliedBundleOnLaunch: () => Promise<void>;
17
+ export declare const reconcileAppliedBundleOnLaunch: (cached?: {
18
+ bundleInfo?: BundleInfo | null;
19
+ bundlePath?: string | null;
20
+ }) => Promise<void>;
14
21
  export declare const applyUpdate: (onStatusUpdate?: (status: string) => void) => Promise<ApplyUpdateResult>;
@@ -5,9 +5,9 @@ const bundleDropNative_1 = require("../native/bundleDropNative");
5
5
  const bundleInfo_1 = require("../bundleInfo");
6
6
  const reporting_1 = require("./reporting");
7
7
  const errors_1 = require("../errors");
8
- const getUpdateState = async () => {
9
- const info = await (0, bundleInfo_1.readBundleInfo)();
10
- const path = await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
8
+ const getUpdateState = async (cached) => {
9
+ const info = cached?.bundleInfo !== undefined ? cached.bundleInfo : await (0, bundleInfo_1.readBundleInfo)();
10
+ const path = cached?.bundlePath !== undefined ? cached.bundlePath : await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
11
11
  return {
12
12
  hasBundle: !!path,
13
13
  info,
@@ -15,18 +15,18 @@ const getUpdateState = async () => {
15
15
  };
16
16
  };
17
17
  exports.getUpdateState = getUpdateState;
18
- const reconcileAppliedBundleOnLaunch = async () => {
19
- const state = await (0, exports.getUpdateState)();
18
+ const reconcileAppliedBundleOnLaunch = async (cached) => {
19
+ const state = await (0, exports.getUpdateState)(cached);
20
20
  if (!state.info?.pendingApply)
21
21
  return;
22
22
  if (!state.hasBundle)
23
23
  return;
24
- // Assume that if a downloaded bundle exists on disk during app launch, it is the active bundle.
25
24
  await (0, bundleInfo_1.updateBundleInfo)({ pendingApply: false, installedAt: new Date().toISOString() });
26
- await (0, reporting_1.reportInstalledIfReady)({
25
+ // Fire-and-forget: don't block the startup path for server reporting
26
+ (0, reporting_1.reportInstalledIfReady)({
27
27
  hasBundle: true,
28
28
  info: state.info ? { ...state.info, pendingApply: false } : state.info,
29
- });
29
+ }).catch(() => { });
30
30
  };
31
31
  exports.reconcileAppliedBundleOnLaunch = reconcileAppliedBundleOnLaunch;
32
32
  const applyUpdate = async (onStatusUpdate) => {
@@ -8,7 +8,6 @@ function patchImageRenderToForceResolve() {
8
8
  if (isPatched || !react_native_1.Image.render)
9
9
  return;
10
10
  isPatched = true;
11
- console.log('🧩 Patching Image.render to force resolveAssetSource');
12
11
  const OriginalRender = react_native_1.Image.render;
13
12
  react_native_1.Image.render = function (...args) {
14
13
  const props = args[0];
@@ -21,5 +20,4 @@ function patchImageRenderToForceResolve() {
21
20
  }
22
21
  return OriginalRender.apply(this, args);
23
22
  };
24
- console.log('🧩 Patched Image.render to force resolveAssetSource');
25
23
  }
@@ -62,7 +62,7 @@ if (!project?.slug) {
62
62
  process.exit(1);
63
63
  }
64
64
  const runtimeVersion = config?.runtimeVersion?.[platform] || config?.runtimeVersion?.[platform];
65
- const channelName = process.argv[3] || 'General';
65
+ const channelName = process.argv[3] || config?.defaultChannel || 'General';
66
66
  const resolveEndpoint = `${serverUrl}/projects/${encodeURIComponent(project.slug)}/ota/resolve`;
67
67
  const outputPath = path.join(outputDir, `main.${platform}.jsbundle`);
68
68
  if (!fs.existsSync(outputDir)) {
@@ -3,7 +3,7 @@ import { DownloadUpdateResult } from './manager/downloadAndInstall';
3
3
  import { ApplyUpdateResult } from './manager/updateState';
4
4
  import { UpdateCheckResponse } from './api/types';
5
5
  type UseBundleDropOptions = {
6
- /** Channel to target; defaults to "General". */
6
+ /** Channel to target; defaults to config.defaultChannel or "General". */
7
7
  channelName?: string;
8
8
  };
9
9
  type UseBundleDropReturn = {
@@ -2,12 +2,13 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useBundleDrop = useBundleDrop;
4
4
  const react_1 = require("react");
5
+ const context_1 = require("./context");
5
6
  const updateCheck_1 = require("./manager/updateCheck");
6
7
  const downloadAndInstall_1 = require("./manager/downloadAndInstall");
7
8
  const updateState_1 = require("./manager/updateState");
8
9
  const rollbackState_1 = require("./manager/rollbackState");
9
10
  function useBundleDrop(options) {
10
- const channelName = options?.channelName || 'General';
11
+ const channelName = options?.channelName || context_1.defaultChannel;
11
12
  const [status, setStatus] = (0, react_1.useState)('Click the button to check for updates');
12
13
  const [installedInfo, setInstalledInfo] = (0, react_1.useState)(null);
13
14
  const [pendingApply, setPendingApply] = (0, react_1.useState)(false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gfean/react-native-bundle-drop",
3
- "version": "0.1.85",
3
+ "version": "0.1.94",
4
4
  "description": "react native ota by gFean",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",