@gfean/react-native-bundle-drop 0.1.47 → 0.1.82

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 (44) hide show
  1. package/CLIENT_README.md +254 -84
  2. package/README.md +145 -14
  3. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +9 -22
  4. package/ios/BundleDropLocator.swift +0 -6
  5. package/lib/CLI/cli.js +48 -39
  6. package/lib/CLI/scripts/init-config.d.ts +1 -0
  7. package/lib/CLI/scripts/init-config.js +42 -2
  8. package/lib/CLI/scripts/init-native-config.js +428 -45
  9. package/lib/CLI/scripts/login-cli.js +7 -3
  10. package/lib/CLI/scripts/post-init.d.ts +1 -0
  11. package/lib/CLI/scripts/post-init.js +42 -0
  12. package/lib/CLI/scripts/upload-cli.d.ts +2 -0
  13. package/lib/CLI/scripts/upload-cli.js +11 -5
  14. package/lib/api/client.d.ts +1 -1
  15. package/lib/api/client.js +2 -2
  16. package/lib/api/clientApi.d.ts +3 -6
  17. package/lib/api/clientApi.js +7 -18
  18. package/lib/api/types.d.ts +33 -18
  19. package/lib/context.js +1 -1
  20. package/lib/errors.d.ts +2 -2
  21. package/lib/fs/bundlePointer.d.ts +14 -0
  22. package/lib/fs/bundlePointer.js +77 -0
  23. package/lib/fs/installId.d.ts +1 -0
  24. package/lib/fs/installId.js +29 -0
  25. package/lib/fs/userProperties.d.ts +6 -0
  26. package/lib/fs/userProperties.js +100 -0
  27. package/lib/index.d.ts +1 -1
  28. package/lib/index.js +8 -3
  29. package/lib/install/installFromZip.js +7 -18
  30. package/lib/loadConfig.d.ts +5 -0
  31. package/lib/manager/downloadAndInstall.d.ts +10 -0
  32. package/lib/manager/downloadAndInstall.js +50 -42
  33. package/lib/manager/initUpdateManager.js +46 -10
  34. package/lib/manager/reporting.js +5 -3
  35. package/lib/manager/rollbackState.d.ts +30 -0
  36. package/lib/manager/rollbackState.js +186 -0
  37. package/lib/manager/updateCheck.js +57 -18
  38. package/lib/scripts/download-bundle.js +19 -8
  39. package/lib/useBundleDrop.js +14 -2
  40. package/package.json +3 -3
  41. package/lib/api/utils.d.ts +0 -1
  42. package/lib/api/utils.js +0 -8
  43. package/lib/fs/iosPointer.d.ts +0 -1
  44. package/lib/fs/iosPointer.js +0 -20
package/CLIENT_README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Bundle Drop Client Quickstart (React Native)
2
2
 
3
- This guide is for app teams integrating the `react-native-bundle-drop` module to fetch and apply OTA bundles from your Bundle Drop backend.
3
+ This guide is for app teams integrating `@gfean/react-native-bundle-drop` to fetch and apply OTA bundles.
4
4
 
5
5
  ## 1) Install and link
6
6
  ```bash
@@ -8,14 +8,14 @@ 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 (resolver patches):
11
+ Add the Android bootstrap side-effect import:
12
12
  ```js
13
13
  // index.js (entry)
14
14
  import '@gfean/react-native-bundle-drop/bootstrap';
15
15
  ```
16
16
 
17
17
  ### Metro config (resolve bundle.drop.config.js from node_modules)
18
- If Metro can’t find `bundle.drop.config.js` when a package requires it, add an alias:
18
+ If Metro cannot find `bundle.drop.config.js` from packages, add an alias:
19
19
  ```js
20
20
  // metro.config.js
21
21
  const path = require('path');
@@ -23,7 +23,6 @@ const path = require('path');
23
23
  module.exports = {
24
24
  resolver: {
25
25
  extraNodeModules: {
26
- // Lets packages do: require('bundle-drop-config')
27
26
  'bundle-drop-config': path.resolve(__dirname, 'bundle.drop.config.js'),
28
27
  },
29
28
  },
@@ -35,18 +34,25 @@ Add `bundle.drop.config.js` to your project root:
35
34
  ```js
36
35
  module.exports = {
37
36
  serverUrl: '<YOUR_BACKEND_URL>',
37
+ runtimeVersion: {
38
+ ios: '1.0.0',
39
+ android: '1.0.0',
40
+ },
38
41
  org: { slug: '<org-slug>' },
39
- project: { name: '<Project Name>', slug: '<project-slug>', apiKey: '<optional-api-key>' },
40
- debugLocal: false, // set true to force localhost (10.0.2.2 on Android)
42
+ project: {
43
+ name: '<Project Name>',
44
+ slug: '<project-slug>',
45
+ apiKey: '<project-api-key>',
46
+ },
47
+ debugLocal: false,
41
48
  };
42
49
  ```
43
50
 
44
51
  ## 3) Minimal usage
45
52
  Startup (optional auto mode):
46
53
  ```ts
47
- // App.tsx
48
54
  import { useEffect } from 'react';
49
- import { initUpdateManager } from 'react-native-bundle-drop';
55
+ import { initUpdateManager } from '@gfean/react-native-bundle-drop';
50
56
 
51
57
  useEffect(() => {
52
58
  initUpdateManager({
@@ -59,7 +65,7 @@ useEffect(() => {
59
65
 
60
66
  Manual UI example:
61
67
  ```ts
62
- import { useBundleDrop } from 'react-native-bundle-drop/useBundleDrop';
68
+ import { useBundleDrop } from '@gfean/react-native-bundle-drop';
63
69
 
64
70
  const {
65
71
  status,
@@ -69,12 +75,12 @@ const {
69
75
  checkLatest,
70
76
  downloadUpdate,
71
77
  applyUpdate,
72
- } = useBundleDrop({ channelName: 'General', policy: 'manual' });
78
+ fetchAvailableChannels,
79
+ availableChannels,
80
+ } = useBundleDrop({ channelName: 'General' });
73
81
  ```
74
- - `downloadUpdate`: download and stage; it will apply on next launch or when you call `applyUpdate` (returns `{ result, status }`).
75
- - `applyUpdate`: apply a staged update now (reload) (returns `{ result, status }`).
76
82
 
77
- Quick check-only pattern (no download):
83
+ Quick check-only pattern:
78
84
  ```ts
79
85
  const { checkLatest, status } = useBundleDrop({ channelName: 'General' });
80
86
  await checkLatest();
@@ -82,92 +88,256 @@ console.log(status);
82
88
  ```
83
89
 
84
90
  ## 4) Policies
85
- - `manual`: nothing automatic; call the actions yourself.
86
- - `immediate`: download and stage, then apply now; if a staged update exists, it applies immediately.
87
- - `on-next-launch`: download and stage; apply on next cold start (pending flag stays true until applied).
88
-
89
- ## 5) Channels (naming tips)
90
- - Keep names simple and stable: `General`, `Beta`, `QA`.
91
- - Use `channelName` consistently in both the client (init/useBundleDrop) and upload CLI flag.
92
- - Prefer a default channel like `General` so your app can fall back gracefully.
93
-
94
- ## 6) Compatibility (runtimeVersion)
95
- - Define a `runtimeVersion` per platform in `bundle.drop.config.js` (e.g. `{ ios: "1.0.0", android: "1.0.0" }`).
96
- - The bundler injects `runtimeVersion` into the metadata JSON inside the ZIP; upload includes it automatically.
97
- - The client sends `runtimeVersion` on `checkForUpdate`; server should only return bundles that match the requesting runtime.
98
-
99
- ### Channel listing (API key)
100
- Use `fetchAvailableChannels` from the `useBundleDrop` hook to retrieve available channel names (requires `project.apiKey`):
91
+ - `manual`: no auto download/apply.
92
+ - `immediate`: download, stage, then apply immediately.
93
+ - `on-next-launch`: download and stage now; apply on next launch.
94
+
95
+ ## 5) Channels
96
+ - Keep channel names stable: `General`, `Beta`, `QA`.
97
+ - Use the same `channelName` in app runtime and in upload CLI.
98
+ - `fetchAvailableChannels()` retrieves available public channels for the configured project.
99
+
100
+ ## 6) Compatibility (`runtimeVersion`)
101
+ - Define `runtimeVersion` per platform in `bundle.drop.config.js`.
102
+ - Upload embeds `runtimeVersion` in metadata.
103
+ - Client sends `runtimeVersion` during OTA resolve.
104
+
105
+ ## 7) Targeted rollout (`currentUserProperties`)
106
+ Use user properties to target cohorts from backend rollout rules.
107
+
101
108
  ```ts
102
- const { fetchAvailableChannels, availableChannels, status } = useBundleDrop();
103
- useEffect(() => {
104
- fetchAvailableChannels();
105
- }, []);
109
+ import {
110
+ setUserProperty,
111
+ setUserPropery,
112
+ getUserProperties,
113
+ getCurrentUserProperties,
114
+ removeUserProperty,
115
+ resetUserProperties,
116
+ } from '@gfean/react-native-bundle-drop';
117
+
118
+ await setUserProperty('QA Analyst');
119
+ await setUserProperty('Beta Tester');
120
+ await setUserPropery('QA Analyst'); // alias + duplicate ignored
121
+
122
+ const propsA = await getUserProperties();
123
+ const propsB = await getCurrentUserProperties();
124
+
125
+ await removeUserProperty('Beta Tester');
126
+ await resetUserProperties();
106
127
  ```
107
- The hook calls `GET /channels/public/byProjectSlug?projectSlug=<slug>&orgSlug=<orgSlug>` with your API key and stores the result in `availableChannels`.
108
128
 
109
- ## 7) Server expectations
110
- - Endpoint `/bundle/checkForUpdate` should accept `project`, `platform`, `channelName`, `currentBundleVersion?`, `currentHash?`, `runtimeVersion?` and return `{ upToDate, bundleVersion, version, hash, downloadUrl?, reason?, incompatible? }`.
111
- - Endpoints `/bundle/latest`, `/bundle/:hash`, and `/bundle/:hash/download` should respond with JSON containing a `downloadUrl` to the signed ZIP built by your upload script. Clients should follow that URL to fetch the ZIP (no auth headers needed on the signed URL).
112
- - Endpoint `/channels/public/byProjectSlug` should accept `projectSlug` and `orgSlug` (API-key protected via `x-api-key` or `apiKey` header) and return an array of channel names (e.g., `["General", "QA"]`).
129
+ Behavior:
130
+ - Values are trimmed.
131
+ - Duplicates are ignored.
132
+ - Stored locally in `bundle-drop/user-properties.json`.
133
+ - Sent automatically as `currentUserProperties` during OTA resolve checks.
113
134
 
114
- ## 8) Bundling/Upload (CI/local)
115
- - Login once:
135
+ ## 8) Bundling/upload (CI/local)
136
+ - Login (interactive, for local development):
116
137
  ```bash
117
138
  npx bundle-drop login
118
139
  ```
119
- - Bundle and upload (Android):
140
+ - Upload Android:
120
141
  ```bash
121
142
  npx bundle-drop upload android --version 1.2.3 --channel General
122
- # or: --buildgradle-path android/app/build.gradle
143
+ # or --buildgradle-path android/app/build.gradle
123
144
  ```
124
- - Bundle and upload (iOS):
145
+ - Upload iOS:
125
146
  ```bash
126
147
  npx bundle-drop upload ios --plist-file ios/Info.plist --channel General
127
- # or: --version 1.2.3
148
+ # or --version 1.2.3
128
149
  ```
129
- - Optional: `--release-notes "text"`; `--runtimeVersion x.y.z`.
130
- - Requires `~/.bundle-drop/auth.json` from `bundle-drop login` and `bundle.drop.config.js` in project root (with `org.slug`, `project.slug`, `serverUrl`).
131
-
132
- ## 9) App entry hooks (JS bundle resolution)
133
- - **Android (MainApplication)**: ensure OTA bundles are used when present.
134
- ```kt
135
- import com.bundledrop.BundleDropModule
136
- // ...
137
- override fun getJSBundleFile(): String? {
138
- val bundlePath = BundleDropModule.getDownloadedBundlePath(application)
139
- return bundlePath ?: super.getJSBundleFile()
150
+ - Optional upload flags:
151
+ - `--runtimeVersion x.y.z` — override runtime version
152
+ - `--release-notes "text"` — attach release notes (max 2000 chars)
153
+ - `--token <pat>` — authenticate with a Personal Access Token (skips `bundle-drop login`; ideal for CI/CD)
154
+ - `--author <name>` — override the author name stored with the bundle
155
+
156
+ ### CI/CD example
157
+ ```bash
158
+ npx bundle-drop upload android \
159
+ --version 1.2.3 \
160
+ --channel General \
161
+ --token $BUNDLE_DROP_PAT \
162
+ --author "CI Pipeline"
163
+ ```
164
+
165
+ ## 9) Native setup (Android)
166
+
167
+ 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.
168
+
169
+ Kotlin:
170
+ ```kt
171
+ override fun getJSBundleFile(): String? =
172
+ BundleDropModule.resolveJSBundleFile(applicationContext, super.getJSBundleFile())
173
+ ```
174
+
175
+ Java:
176
+ ```java
177
+ @Override
178
+ protected String getJSBundleFile() {
179
+ return BundleDropModule.resolveJSBundleFile(getApplicationContext(), super.getJSBundleFile());
180
+ }
181
+ ```
182
+
183
+ ### A) Kotlin — older RN template (has `reactNativeHost`)
184
+
185
+ If your `MainApplication.kt` already has a `reactNativeHost` block, add the import and the one-liner inside it:
186
+
187
+ ```kt
188
+ import com.bundledrop.BundleDropModule
189
+
190
+ // inside your existing reactNativeHost object:
191
+ override fun getJSBundleFile(): String? =
192
+ BundleDropModule.resolveJSBundleFile(applicationContext, super.getJSBundleFile())
193
+ ```
194
+
195
+ ### B) Kotlin — RN 0.84+ template (ReactHost, no `reactNativeHost`)
196
+
197
+ RN 0.84+ templates use `ReactHost` but don't expose `reactNativeHost`. BundleDrop needs `ReactNativeHost.getJSBundleFile()`, so you reintroduce `reactNativeHost` and wire `reactHost` from it.
198
+
199
+ 1. Add imports (only if missing):
200
+ ```kt
201
+ import com.bundledrop.BundleDropModule
202
+ import com.facebook.react.ReactHost
203
+ import com.facebook.react.ReactNativeHost
204
+ import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative
205
+ import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
206
+ import com.facebook.react.defaults.DefaultReactNativeHost
207
+ ```
208
+
209
+ 2. Add `reactNativeHost` property (before `reactHost`):
210
+ ```kt
211
+ override val reactNativeHost: ReactNativeHost =
212
+ object : DefaultReactNativeHost(this) {
213
+
214
+ override fun getPackages() = PackageList(this).packages
215
+ override fun getJSMainModuleName(): String = "index"
216
+ override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
217
+
218
+ override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
219
+ override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
220
+
221
+ override fun getJSBundleFile(): String? =
222
+ BundleDropModule.resolveJSBundleFile(applicationContext, super.getJSBundleFile())
140
223
  }
141
- - **iOS (AppDelegate.swift)**: prefer the OTA bundle via the module’s locator (works in debug and release).
142
- ```swift
143
- // Add this near the top of AppDelegate.swift
144
- import BundleDrop
145
-
146
- // Override to prefer OTA in release
147
- override func bundleURL() -> URL? {
148
- if let url = BundleDropModule.getJSBundleURL() {
224
+ ```
225
+
226
+ 3. Ensure `reactHost` is created from `reactNativeHost`:
227
+ ```kt
228
+ override val reactHost: ReactHost by lazy {
229
+ getDefaultReactHost(
230
+ context = applicationContext,
231
+ reactNativeHost = reactNativeHost
232
+ )
233
+ }
234
+ ```
235
+
236
+ 4. Ensure `onCreate()` calls:
237
+ ```kt
238
+ loadReactNative(this)
239
+ ```
240
+
241
+ ### C) Java — older RN template (`MainApplication.java`)
242
+
243
+ Older React Native versions used Java instead of Kotlin. Add the import and the override inside your `ReactNativeHost` anonymous class:
244
+
245
+ ```java
246
+ import com.bundledrop.BundleDropModule;
247
+
248
+ // inside your ReactNativeHost (or DefaultReactNativeHost) anonymous class:
249
+ @Override
250
+ protected String getJSBundleFile() {
251
+ return BundleDropModule.resolveJSBundleFile(getApplicationContext(), super.getJSBundleFile());
252
+ }
253
+ ```
254
+
255
+ Full example context:
256
+
257
+ ```java
258
+ private final ReactNativeHost mReactNativeHost =
259
+ new DefaultReactNativeHost(this) {
260
+ @Override
261
+ protected List<ReactPackage> getPackages() {
262
+ return new PackageList(this).getPackages();
263
+ }
264
+
265
+ @Override
266
+ protected String getJSMainModuleName() {
267
+ return "index";
268
+ }
269
+
270
+ @Override
271
+ protected boolean getUseDeveloperSupport() {
272
+ return BuildConfig.DEBUG;
273
+ }
274
+
275
+ @Override
276
+ protected String getJSBundleFile() {
277
+ return BundleDropModule.resolveJSBundleFile(getApplicationContext(), super.getJSBundleFile());
278
+ }
279
+ };
280
+ ```
281
+
282
+ > **Note:** The CLI command `npx bundle-drop init` detects your template (Kotlin/Java, older/new) automatically and applies the correct patch.
283
+
284
+ ## 10) Native setup (iOS)
285
+
286
+ The goal is to load the OTA bundle in **Release** (if present) and fall back to the embedded `main.jsbundle`, while keeping **Debug** on Metro.
287
+
288
+ ### A) Swift (`AppDelegate.swift`)
289
+
290
+ Add the import and replace the `bundleURL()` override:
291
+
292
+ ```swift
293
+ import BundleDrop
294
+
295
+ override func bundleURL() -> URL? {
296
+ #if DEBUG
297
+ return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
298
+ #else
299
+ if let url = BundleDropLocator.bundleURL() {
149
300
  return url
150
301
  }
151
- #if !DEBUG
152
- return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
153
- #else
154
- return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
155
- #endif
302
+ return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
303
+ #endif
304
+ }
305
+ ```
306
+
307
+ ### B) Objective-C / ObjC++ (`AppDelegate.m` / `AppDelegate.mm`)
308
+
309
+ Add the import and replace the `sourceURLForBridge:` method:
310
+
311
+ ```objc
312
+ #import <BundleDrop/BundleDrop-Swift.h>
313
+
314
+ - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
315
+ {
316
+ #if DEBUG
317
+ return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
318
+ #else
319
+ NSURL *otaURL = [BundleDropLocator bundleURL];
320
+ if (otaURL != nil) {
321
+ return otaURL;
156
322
  }
157
- ```
323
+ return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
324
+ #endif
325
+ }
326
+ ```
327
+
328
+ > **Note:** The CLI command `npx bundle-drop init` searches `ios/` recursively for `AppDelegate.swift`, `.mm`, or `.m` and patches whichever it finds first.
329
+
330
+ ## 11) Public API snapshot
331
+ Top-level exports:
332
+ - `getAvailableChannels`, `checkForUpdate`, `getInstalledBundleInfo`
333
+ - `downloadUpdate`
334
+ - `getUpdateState`, `applyUpdate`
335
+ - `initUpdateManager`
336
+ - `useBundleDrop`
337
+ - `BundleDropError`, `isBundleDropError`
338
+ - `setUserProperty`, `setUserPropery`, `getUserProperties`, `getCurrentUserProperties`, `removeUserProperty`, `resetUserProperties`
158
339
 
159
- ## 10) Notes
160
- - Android asset resolver is patched automatically; OTA assets should resolve like bundled ones.
161
- - Local metadata is stored at `bundle-info.json` in the app document directory.
162
- - `getUpdateState()` returns `{ hasBundle, info, pendingApply }` if you need raw state.
163
- - Types are re-exported from the package entry: `BundleInfo`, `UpdatePolicy`.
164
- - API calls are centralized under `src/api/` with an axios interceptor that applies your `x-api-key`; `src/index.tsx` remains the public barrel re-export.
165
- - Env tips:
166
- - Set `debugLocal: true` in config to force localhost/10.0.2.2.
167
- - If you want a kill switch, guard your `initUpdateManager` call (e.g., `if (!Config.BUNDLE_DROP_DISABLE) { ... }`).
168
-
169
- ## 11) QA checklist
170
- - Verify `checkLatest` on the target channel reports up-to-date when expected.
171
- - Download and stage with `downloadUpdate`, then apply with `applyUpdate`; verify both immediate apply and next-launch behavior.
172
- - Confirm pending flag/UI reflects staged state after download and clears after apply.
173
- - Spot-check a couple of images/assets after OTA (Android manifest remap) to ensure they resolve.
340
+ ## 12) Notes
341
+ - Android asset resolver patching runs automatically.
342
+ - `getUpdateState()` returns `{ hasBundle, info, pendingApply }`.
343
+ - Set `debugLocal: true` to force localhost (`10.0.2.2` on Android).
package/README.md CHANGED
@@ -37,26 +37,34 @@ module.exports = {
37
37
  serverUrl: 'http://localhost:4000', // or prod URL
38
38
  org: { slug: 'your-org-slug' },
39
39
  project: {
40
- name: 'ProCredit Mobile App',
41
- slug: 'procredit-mobile',
42
- apiKey: 'optional-api-key', // used if provided
40
+ name: 'Your App Name',
41
+ slug: 'your-app-slug',
42
+ apiKey: 'optional-api-key', // project-scoped; auto-filled by CLI init/login
43
43
  },
44
44
  debugLocal: true, // optional: force localhost (10.0.2.2 on Android, localhost on iOS)
45
45
  };
46
46
  ```
47
47
  - Login token stored at `~/.bundle-drop/auth.json` (use CLI `bundle-drop login`).
48
+ - The CLI will fetch a project-scoped `apiKey` from `GET /projects/:projectSlug/credentials` using your JWT and write it into `bundle.drop.config.js`. If you have multiple projects, the CLI prompts you to select the project before fetching credentials.
48
49
 
49
50
  ## Runtime APIs (app code)
50
- - `checkForUpdate(channelName?, onStatusUpdate?)`: metadata-only check; no download.
51
- - `downloadUpdate(options?, onStatusUpdate?)`: downloads and stages the update (sets `pendingApply: true`); it will apply on next launch or when you call `applyUpdate`.
51
+ - `checkForUpdate(channelName?, onStatusUpdate?)`: resolve-only metadata check (no download). Uses `POST /projects/:projectSlug/ota/resolve` and can return `NOOP`, `INSTALL`, or `ROLLBACK` (plus `NO_COMPATIBLE_BUNDLE` details).
52
+ - `downloadUpdate(options?, onStatusUpdate?)`: resolves (unless `resolvedTarget` is provided), downloads, and stages the update (sets `pendingApply: true`). Returns `{ status: 'staged' | 'upToDate' | 'rollback' | 'incompatible' }`.
52
53
  - `applyUpdate(onStatusUpdate?)`: apply a staged update now (restarts the RN bridge).
53
54
  - `getUpdateState()`: returns `{ hasBundle, info, pendingApply }` from local metadata.
54
55
  - `initUpdateManager({ channelName, policy, onStatusUpdate, checkOnly })`: startup helper
55
56
  - `policy: 'manual' | 'immediate' | 'on-next-launch'`
56
57
  - `immediate`: download and stage, then apply now (reload). If a staged update is pending, applies it immediately.
57
58
  - `on-next-launch`: download and stage; app will pick it up on the next launch (pending flag remains until applied).
58
- - `manual`: no auto download/apply; optional `checkOnly` will just run a check.
59
+ - `manual`: no auto download/apply (resolve still runs for status and rollback decisions).
60
+ - On launch it reconciles pending state, runs rollback guardrails, auto-commits the active bundle, then resolves once. If `ROLLBACK` is returned it switches to `previous.json` (or native fallback) and restarts.
59
61
  - `useBundleDrop` hook (optional helper): returns status, busy flag, installed info, pending state, and actions (`checkLatest`, `downloadUpdate`, `applyUpdate`, `fetchAvailableChannels`). Action calls return structured results plus the status string they set.
62
+ - User property APIs (for targeted rollout):
63
+ - `setUserProperty(value: string)`: add a user property (trimmed, de-duplicated).
64
+ - `setUserPropery(value: string)`: backward-compatible alias of `setUserProperty`.
65
+ - `getUserProperties()` and `getCurrentUserProperties()`: read all saved properties.
66
+ - `removeUserProperty(value: string)`: remove one property.
67
+ - `resetUserProperties()`: clear all properties.
60
68
 
61
69
  Android extras:
62
70
  - Asset resolver patches (`injectBundleDropImageResolver`, `patchImageRenderToForceResolve`) are applied on module load so images referenced directly still resolve after OTA.
@@ -65,11 +73,100 @@ Android extras:
65
73
  ## Config loading
66
74
  - `src/loadConfig.ts` loads `bundle.drop.config.js` (fixed relative path) and honors `debugLocal` to force localhost.
67
75
 
76
+ ## Server API (Public)
77
+ All endpoints are project-scoped and require `x-api-key` (project download API key).
78
+
79
+ ### `POST /projects/:projectSlug/ota/resolve`
80
+ Request body:
81
+ ```json
82
+ {
83
+ "channelName": "General",
84
+ "platform": "ios|android",
85
+ "runtimeVersion": "3.0.0",
86
+ "currentHash": "abc123",
87
+ "currentUserProperties": ["QA Analyst", "Beta Tester"],
88
+ "previousHash": "prev456",
89
+ "currentBundleVersion": 12,
90
+ "installId": "install-id-string"
91
+ }
92
+ ```
93
+ Notes:
94
+ - `installId` is generated once per install and stored at `bundle-drop/install-id.txt` (under the platform-specific `bundle-drop` root).
95
+ - `previousHash` is read from `previous.json` when available.
96
+ - `currentUserProperties` is read from local `bundle-drop/user-properties.json` and sent automatically on each resolve.
97
+
98
+ Response shapes:
99
+ ```json
100
+ { "action": "NOOP", "reason": "UP_TO_DATE" }
101
+ ```
102
+ ```json
103
+ {
104
+ "action": "NOOP",
105
+ "reason": "NO_COMPATIBLE_BUNDLE",
106
+ "requestedRuntimeVersion": "3.0.0",
107
+ "latestRuntimeVersionOnChannel": "3.1.0"
108
+ }
109
+ ```
110
+ ```json
111
+ {
112
+ "action": "INSTALL",
113
+ "target": {
114
+ "hash": "def789",
115
+ "downloadUrl": "https://signed-url",
116
+ "bundleVersion": 13,
117
+ "version": "optional",
118
+ "runtimeVersion": "optional"
119
+ }
120
+ }
121
+ ```
122
+ ```json
123
+ { "action": "ROLLBACK", "reason": "CURRENT_REVOKED_NO_SAFE_TARGET" }
124
+ ```
125
+ Notes:
126
+ - `NOOP` reasons: `UP_TO_DATE`, `ROLLOUT_PAUSED`, `ROLLOUT_NOT_ELIGIBLE`, `NO_PUBLISHED_BUNDLE`, `NO_COMPATIBLE_BUNDLE`.
127
+ - `ROLLBACK` reasons are server-defined (for example: `CURRENT_REVOKED_NO_SAFE_TARGET`, `CURRENT_REVOKED_NO_COMPATIBLE_TARGET`).
128
+ Client behavior:
129
+ - `NOOP`: do nothing.
130
+ - `INSTALL`: download `target.downloadUrl`, stage it, then apply per policy.
131
+ - `ROLLBACK`: switch to `previous.json` if present; otherwise clear `current.json` and fall back to the native bundle (no re-download).
132
+
133
+ ### `POST /projects/:projectSlug/bundle/:hash/installed`
134
+ Called once the staged bundle is active (after apply on launch). Used for telemetry.
135
+ Payload fields:
136
+ - `channelName`
137
+ - `platform`
138
+ - `installId` (persistent per-install id stored at `bundle-drop/install-id.txt`)
139
+ - `runtimeVersion`
140
+
141
+ ### `GET /projects/:projectSlug/channels/public`
142
+ Returns the list of public channel names.
143
+
144
+ ## Rollback behavior (default)
145
+ - Bundles are stored by hash under the platform `bundle-drop` root and activated via `current.json`.
146
+ - The previous active bundle is retained in `previous.json` for rollback.
147
+ - A small `state.json` tracks candidate activation, crash window, and commit status.
148
+ - The module auto-commits the active bundle once JS has started (via `initUpdateManager`/`useBundleDrop`).
149
+ - Server-triggered rollback switches the pointer; if no previous OTA bundle exists, it falls back to the native bundle by clearing `current.json`.
150
+
151
+ Optional rollback policy (tuning only):
152
+ ```js
153
+ rollback: {
154
+ maxCrashCount: 2,
155
+ crashWindowSec: 300,
156
+ commitTimeoutSec: 300,
157
+ }
158
+ ```
159
+
68
160
  ## Bundling & Uploading (CLI)
69
- - Login once:
161
+ - Login once (interactive, stores JWT locally):
70
162
  ```bash
71
163
  npx bundle-drop login
72
164
  ```
165
+ - If you need to (re)generate config and fetch the project-scoped API key:
166
+ ```bash
167
+ npx bundle-drop init
168
+ npx bundle-drop init --token bdp_pat_xxx # alternative: use a PAT instead of login
169
+ ```
73
170
  - Upload (builds, zips, uploads, cleans up):
74
171
  ```bash
75
172
  npx bundle-drop upload android --version 1.2.3 --channel General
@@ -77,10 +174,24 @@ Android extras:
77
174
  ```
78
175
  Flags:
79
176
  - `--version` (ios/android) or `--plist-file` (iOS) or `--buildgradle-path` (Android) to derive version.
80
- - `--release-notes "<text>"` optional.
177
+ - `--release-notes "<text>"` optional release notes (max 2000 chars).
178
+ - `--token <pat>` use a Personal Access Token instead of `bundle-drop login`. Ideal for CI/CD.
179
+ - `--author <name>` override the author name stored with the bundle (defaults to uploading user's name).
180
+ - `--runtimeVersion <v>` override runtimeVersion from metadata/config.
181
+
81
182
  Requirements:
82
183
  - `bundle.drop.config.js` with `serverUrl`, `org.slug`, `project.slug`.
83
- - Auth token at `~/.bundle-drop/auth.json` from `bundle-drop login`.
184
+ - `project.apiKey` is used by the client for public endpoints (channel listing + OTA resolve).
185
+ - Authentication via one of: `--token` flag (PAT), or `~/.bundle-drop/auth.json` from `bundle-drop login`.
186
+
187
+ ### CI/CD example
188
+ ```bash
189
+ npx bundle-drop upload android \
190
+ --version 1.2.3 \
191
+ --channel General \
192
+ --token $BUNDLE_DROP_PAT \
193
+ --author "CI Pipeline"
194
+ ```
84
195
 
85
196
  ## Typical usage
86
197
  ```ts
@@ -102,16 +213,35 @@ const {
102
213
  checkLatest,
103
214
  downloadUpdate,
104
215
  applyUpdate,
105
- } = useBundleDrop({ channelName: 'General', policy: 'manual' });
216
+ } = useBundleDrop({ channelName: 'General' });
106
217
 
107
218
  // downloadUpdate() will stage the bundle (applies on next launch or when you call applyUpdate()).
108
219
  ```
109
220
 
221
+ ## Targeted rollout properties
222
+ ```ts
223
+ import {
224
+ setUserProperty,
225
+ getUserProperties,
226
+ removeUserProperty,
227
+ resetUserProperties,
228
+ } from '@gfean/react-native-bundle-drop';
229
+
230
+ await setUserProperty('QA Analyst');
231
+ await setUserProperty('Beta Tester');
232
+ await setUserProperty('QA Analyst'); // duplicate ignored
233
+
234
+ const props = await getUserProperties(); // ['QA Analyst', 'Beta Tester']
235
+ await removeUserProperty('Beta Tester');
236
+ await resetUserProperties();
237
+ ```
238
+
110
239
  ## CLI (bin)
111
240
  - `modules/react-native-bundle-drop/src/CLI/cli.ts` provides:
112
241
  - `bundle-drop login|logout|whoami`
113
- - `bundle-drop upload <platform> --version <ver> --channel <name> [--plist-file <path>] [--runtimeVersion <v>] [--release-notes "<text>"]`
114
- - Same auth/config requirements as scripts.
242
+ - `bundle-drop init [--token <pat>]`
243
+ - `bundle-drop upload <platform> --version <ver> --channel <name> [--plist-file <path>] [--runtimeVersion <v>] [--release-notes "<text>"] [--token <pat>] [--author <name>]`
244
+ - Auth via `--token` (PAT) or `~/.bundle-drop/auth.json` (from `bundle-drop login`).
115
245
 
116
246
  ## Android localhost note
117
247
  - When `debugLocal` is true (or env is set), Android uses `http://10.0.2.2:4000`; iOS uses `http://localhost:4000`.
@@ -121,9 +251,10 @@ const {
121
251
  - Ensure `bundle.drop.config.js` has `serverUrl`, `org.slug`, and `project.slug`; otherwise the module falls back to localhost defaults.
122
252
 
123
253
  ## Maintainer notes (internal structure)
124
- - `src/index.tsx` is a thin barrel; public API remains unchanged.
254
+ - `src/index.tsx` is a thin barrel for public exports.
125
255
  - Early side-effects/config live in `src/bootstrap.ts` (loads config, detects platform, patches Android images).
126
- - File system helpers: `src/fs/*` (atomic writes, iOS pointer).
256
+ - File system helpers: `src/fs/*` (atomic writes, bundle pointers).
257
+ - Rollback/state helpers: `src/manager/rollbackState.ts`.
127
258
  - Native accessors: `src/native/bundleDropNative.ts`.
128
259
  - Install flow: `src/install/installFromZip.ts`.
129
260
  - API client layer: `src/api/*` (axios client + typed endpoints).