@gfean/react-native-bundle-drop 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +194 -5
  3. package/android/build.gradle +66 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +206 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  7. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  8. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  9. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  10. package/ios/BundleDropBridge.m +45 -0
  11. package/ios/BundleDropLocator.swift +66 -4
  12. package/ios/BundleDropModule.swift +181 -3
  13. package/ios/BundleDropOtaResolver.swift +137 -29
  14. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  15. package/ios/BundleDropStartupRecovery.swift +1108 -0
  16. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  17. package/lib/CLI/cli.d.ts +1 -0
  18. package/lib/CLI/cli.js +57 -6
  19. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  20. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  21. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  22. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  23. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  24. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  25. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  26. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  27. package/lib/CLI/scripts/aipowered/init-project-config.js +221 -45
  28. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  29. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  30. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  31. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  32. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  33. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  34. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  35. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  36. package/lib/CLI/scripts/doctor.js +162 -22
  37. package/lib/CLI/scripts/expo/configure-expo.js +52 -60
  38. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  39. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  40. package/lib/CLI/scripts/init-config.d.ts +7 -7
  41. package/lib/CLI/scripts/init-config.js +198 -14
  42. package/lib/CLI/scripts/login-cli.js +31 -7
  43. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  44. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  45. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  46. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  47. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  48. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  49. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  50. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  51. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  52. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  53. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  54. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  55. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  56. package/lib/CLI/scripts/upload-cli.js +74 -11
  57. package/lib/CLI/serverUrl.d.ts +3 -0
  58. package/lib/CLI/serverUrl.js +31 -0
  59. package/lib/api/clientApi.d.ts +3 -1
  60. package/lib/api/clientApi.js +14 -0
  61. package/lib/api/types.d.ts +39 -0
  62. package/lib/bundleInfo.d.ts +2 -0
  63. package/lib/bundleInfo.js +16 -1
  64. package/lib/context.d.ts +1 -1
  65. package/lib/context.js +12 -2
  66. package/lib/fs/bundlePointer.d.ts +1 -17
  67. package/lib/fs/bundlePointer.js +5 -93
  68. package/lib/index.d.ts +2 -0
  69. package/lib/index.js +3 -1
  70. package/lib/install/bundleInstallShared.js +4 -4
  71. package/lib/install/installFromZip.d.ts +3 -0
  72. package/lib/install/installFromZip.js +10 -1
  73. package/lib/loadConfig.d.ts +17 -1
  74. package/lib/loadConfig.js +16 -0
  75. package/lib/manager/downloadAndInstall.d.ts +3 -2
  76. package/lib/manager/downloadAndInstall.js +134 -66
  77. package/lib/manager/reporting.d.ts +8 -1
  78. package/lib/manager/reporting.js +17 -22
  79. package/lib/manager/rollbackState.d.ts +18 -52
  80. package/lib/manager/rollbackState.js +115 -216
  81. package/lib/manager/updateCheck.d.ts +1 -0
  82. package/lib/manager/updateCheck.js +224 -78
  83. package/lib/manager/updateState.d.ts +2 -1
  84. package/lib/manager/updateState.js +59 -6
  85. package/lib/metro.d.ts +8 -1
  86. package/lib/metro.js +69 -19
  87. package/lib/native/bundleDropNative.d.ts +62 -0
  88. package/lib/native/bundleDropNative.js +268 -2
  89. package/lib/native/fs.d.ts +6 -0
  90. package/lib/native/fs.js +24 -0
  91. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  92. package/lib/patch-engine/installFromPatchSet.js +16 -5
  93. package/lib/patch-engine/patchTransport.d.ts +2 -0
  94. package/lib/patch-engine/patchTransport.js +9 -0
  95. package/lib/runtime/initState.d.ts +5 -0
  96. package/lib/runtime/initState.js +4 -0
  97. package/lib/runtime/service.js +82 -67
  98. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  99. package/lib/runtime-delivery/artifactCapability.js +32 -0
  100. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  101. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  102. package/lib/runtime-delivery/bootstrapConfig.d.ts +68 -0
  103. package/lib/runtime-delivery/bootstrapConfig.js +278 -0
  104. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  105. package/lib/runtime-delivery/diagnostics.js +58 -0
  106. package/lib/runtime-delivery/encoding.d.ts +5 -0
  107. package/lib/runtime-delivery/encoding.js +132 -0
  108. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  109. package/lib/runtime-delivery/heartbeat.js +88 -0
  110. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  111. package/lib/runtime-delivery/localResolver.js +81 -0
  112. package/lib/runtime-delivery/manifestState.d.ts +11 -0
  113. package/lib/runtime-delivery/manifestState.js +123 -0
  114. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  115. package/lib/runtime-delivery/manifestVerifier.js +335 -0
  116. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  117. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  118. package/lib/runtime-delivery/types.d.ts +87 -0
  119. package/lib/runtime-delivery/types.js +6 -0
  120. package/lib/scripts/bundle.d.ts +9 -2
  121. package/lib/scripts/bundle.js +68 -18
  122. package/lib/scripts/download-bundle.d.ts +1 -0
  123. package/lib/scripts/download-bundle.js +2 -2
  124. package/lib/scripts/resolveModule.d.ts +2 -0
  125. package/lib/scripts/resolveModule.js +5 -0
  126. package/package.json +5 -2
  127. package/plugin/xcodeBuildPhase.js +2 -1
@@ -1,7 +1,85 @@
1
+ require "digest"
2
+ require "fileutils"
1
3
  require "json"
4
+ require "open3"
5
+ require "shellwords"
6
+
7
+ bundle_drop_native_runtime_identity_resource = lambda do
8
+ return nil unless defined?(Pod::Config)
9
+
10
+ project_root = File.expand_path("..", Pod::Config.instance.installation_root.to_s)
11
+ config_path = File.join(project_root, "bundle.drop.config.js")
12
+ writer_path = File.join(
13
+ __dir__,
14
+ "lib",
15
+ "CLI",
16
+ "scripts",
17
+ "native",
18
+ "write-runtime-identity.js"
19
+ )
20
+ unless File.file?(writer_path)
21
+ raise Pod::Informative,
22
+ "Bundle Drop native runtime identity writer is missing: #{writer_path}"
23
+ end
24
+
25
+ resource_path = File.join(
26
+ "ios",
27
+ "build",
28
+ "generated",
29
+ "runtime-identity",
30
+ Digest::SHA256.hexdigest(project_root)[0, 16],
31
+ "bundle-drop-build-identity.json"
32
+ )
33
+ output_path = File.join(__dir__, resource_path)
34
+
35
+ if File.file?(config_path)
36
+ stdout, stderr, status = Open3.capture3(
37
+ ENV.fetch("NODE_BINARY", "node"),
38
+ writer_path,
39
+ "--project-root", project_root,
40
+ "--platform", "ios",
41
+ "--output", output_path
42
+ )
43
+ unless status.success?
44
+ detail = stderr.strip.empty? ? stdout.strip : stderr.strip
45
+ raise Pod::Informative,
46
+ "Bundle Drop could not generate the iOS runtime identity: #{detail}"
47
+ end
48
+
49
+ identity = JSON.parse(File.read(output_path))
50
+ return nil if identity["source"] == "expo"
51
+ unless identity["runtimeVersion"].is_a?(String) && !identity["runtimeVersion"].empty?
52
+ raise Pod::Informative, "Bundle Drop generated an invalid iOS runtime identity."
53
+ end
54
+ else
55
+ # CocoaPods evaluates the podspec before `bundle-drop login` in the documented
56
+ # fresh-install flow. Keep the resource and build phase in the Pods project so
57
+ # the first native build can replace this inert placeholder after setup.
58
+ FileUtils.mkdir_p(File.dirname(output_path))
59
+ File.write(
60
+ output_path,
61
+ JSON.generate({
62
+ "schemaVersion" => 1,
63
+ "platform" => "ios",
64
+ "source" => "unconfigured"
65
+ }) + "\n"
66
+ )
67
+ end
68
+ resource_path
69
+ end
2
70
 
3
71
  package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
72
  native_version = package["nativeVersion"] || package["version"]
73
+ native_runtime_identity_resource = bundle_drop_native_runtime_identity_resource.call
74
+ native_runtime_identity_project_root = if native_runtime_identity_resource
75
+ File.expand_path("..", Pod::Config.instance.installation_root.to_s)
76
+ end
77
+ native_runtime_identity_writer = if native_runtime_identity_resource
78
+ File.join(__dir__, "lib", "CLI", "scripts", "native", "write-runtime-identity.js")
79
+ end
80
+ native_runtime_identity_output = if native_runtime_identity_resource
81
+ File.join(__dir__, native_runtime_identity_resource)
82
+ end
5
83
 
6
84
  Pod::Spec.new do |s|
7
85
  s.name = "BundleDrop"
@@ -15,6 +93,24 @@ Pod::Spec.new do |s|
15
93
  s.source = { :git => ".git", :tag => "#{s.version}" }
16
94
 
17
95
  s.source_files = "ios/**/*.{h,m,mm,swift}", "third_party/xdelta/**/*.{c,h}"
96
+ s.resources = native_runtime_identity_resource if native_runtime_identity_resource
97
+ if native_runtime_identity_resource
98
+ # Intentionally omit output files so Xcode reruns this when a bare app builds,
99
+ # even when CocoaPods has not been reinstalled since its config changed.
100
+ s.script_phase = {
101
+ :name => "Regenerate Bundle Drop runtime identity",
102
+ :execution_position => :before_compile,
103
+ :show_env_vars_in_log => "0",
104
+ :script => <<-SCRIPT
105
+ set -e
106
+ "${NODE_BINARY:-node}" \
107
+ #{Shellwords.escape(native_runtime_identity_writer)} \
108
+ --project-root #{Shellwords.escape(native_runtime_identity_project_root)} \
109
+ --platform ios \
110
+ --output #{Shellwords.escape(native_runtime_identity_output)}
111
+ SCRIPT
112
+ }
113
+ end
18
114
  s.public_header_files = "ios/BundleDropLocator.h", "ios/BundleDropZipExtractor.h"
19
115
  s.private_header_files = "third_party/xdelta/**/*.h"
20
116
  s.pod_target_xcconfig = {
package/README.md CHANGED
@@ -96,7 +96,8 @@ npx bundle-drop login
96
96
  npx bundle-drop doctor
97
97
  ```
98
98
 
99
- `login` signs you in, creates `bundle.drop.config.js` when needed, detects Expo or
99
+ `login` signs you in, creates `bundle.drop.config.js` when needed, pins the
100
+ authenticated runtime-delivery bootstrap under `.bundle-drop/`, detects Expo or
100
101
  bare React Native, previews the integration changes, and completes setup. `doctor`
101
102
  then validates configuration, runtime identity, native integration, and startup
102
103
  ownership.
@@ -113,6 +114,87 @@ npx bundle-drop init --project-type bare
113
114
  Run `npx bundle-drop doctor` again after changing native integration, Metro, Expo
114
115
  configuration, or runtime versions.
115
116
 
117
+ When Bundle Drop rotates manifest verification keys or changes the public manifest
118
+ route, refresh the pinned client-visible bootstrap explicitly:
119
+
120
+ ```bash
121
+ npx bundle-drop sync
122
+ npx bundle-drop doctor
123
+ ```
124
+
125
+ Apps upgrading from an inline `runtimeDelivery` block or a direct Metro alias should
126
+ remove that stale block and run `npx bundle-drop init` once to install the
127
+ package-managed Metro wrapper. Inline delivery data is ignored: the validated
128
+ runtime-delivery lockfile is the sole trust source. After that one-time migration, `sync`
129
+ is the narrow command for refreshing trust data.
130
+
131
+ The runtime-delivery lockfile is not a secret and should be committed. Setup keeps the
132
+ generated Metro wrapper, build receipts, and other transient `.bundle-drop` files
133
+ ignored while allowing `.bundle-drop/runtime-delivery.lock.json` into source
134
+ control. Projects with the former `runtime-delivery.generated.json` filename remain
135
+ readable; run `bundle-drop sync` to migrate and remove that legacy file.
136
+
137
+ ### Manual setup without AI planning
138
+
139
+ You can configure Bundle Drop without sending project files to the AI setup planner.
140
+ Create `bundle.drop.config.js` with the project identity and public project API key
141
+ shown in the developer dashboard:
142
+
143
+ ```js
144
+ module.exports = {
145
+ serverUrl: 'https://api.bundledrop.app',
146
+ defaultChannel: 'develop',
147
+ runtimeVersion: { ios: '1.0.0', android: '1.0.0' },
148
+ org: { slug: 'your-org' },
149
+ project: {
150
+ name: 'Your App',
151
+ slug: 'your-app',
152
+ apiKey: 'your-public-project-key',
153
+ },
154
+ };
155
+ ```
156
+
157
+ Wrap the final exported Metro config. For bare React Native:
158
+
159
+ ```js
160
+ const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
161
+ const { withBundleDrop } = require('@gfean/react-native-bundle-drop/metro');
162
+
163
+ const config = mergeConfig(getDefaultConfig(__dirname), {});
164
+ module.exports = withBundleDrop(config, { projectRoot: __dirname });
165
+ ```
166
+
167
+ For Expo:
168
+
169
+ ```js
170
+ const { getDefaultConfig } = require('expo/metro-config');
171
+ const { withBundleDropExpo } = require('@gfean/react-native-bundle-drop/metro');
172
+
173
+ module.exports = withBundleDropExpo(getDefaultConfig(__dirname), {
174
+ projectRoot: __dirname,
175
+ });
176
+ ```
177
+
178
+ Expo projects must also add `@gfean/react-native-bundle-drop` to the app config's
179
+ `plugins` array. Bare projects must connect Bundle Drop to the Release bundle URL in
180
+ their Android and iOS entrypoints. Follow the
181
+ [manual native setup guide](https://bundledrop.app/docs/manual-setup) because the
182
+ entrypoint shape varies across React Native versions.
183
+
184
+ Finish every manual setup by authenticating, generating the public trust bootstrap,
185
+ and validating the complete integration:
186
+
187
+ ```bash
188
+ npx bundle-drop login
189
+ npx bundle-drop sync
190
+ npx bundle-drop doctor
191
+ ```
192
+
193
+ `sync` creates `.bundle-drop/runtime-delivery.lock.json`, recreates it if it or
194
+ the entire `.bundle-drop` directory was deleted, and repairs the corresponding
195
+ `.gitignore` rules. The lockfile contains public identity and verification material,
196
+ not secrets, so commit it with the application.
197
+
116
198
  ## Initialize the Runtime
117
199
 
118
200
  Call `BundleDrop.init` once, as early as possible in the app process.
@@ -239,6 +321,109 @@ example, an iOS-only native change should bump `runtimeVersion.ios`; Android can
239
321
  its existing value. This makes the compatibility boundary explicit and prevents an
240
322
  update from reaching a binary that cannot run it.
241
323
 
324
+ ## Native Startup Recovery
325
+
326
+ Bundle Drop records every OTA startup attempt in native storage before React Native
327
+ receives the bundle path. If an attempt does not reach its configured health boundary,
328
+ the next distinct app launch counts it as incomplete. The candidate is retried until
329
+ `rollback.maxCrashCount` is reached, then quarantined locally and replaced with the
330
+ previous native-proven healthy OTA bundle. If that bundle is missing, corrupt,
331
+ incompatible, or locally revoked, startup falls back to the bundle embedded in the app.
332
+
333
+ Automatic health waits for React content to appear and then applies
334
+ `rollback.healthyAfterSec`. Apps with a stronger readiness boundary can opt into
335
+ `healthCheckMode: 'manual'` and call `BundleDrop.reportHealthy()` after hydration,
336
+ migrations, authentication bootstrap, or navigation setup completes. Health is committed
337
+ against the exact native launch attempt, so a delayed callback from an older React runtime
338
+ cannot approve a newer launch.
339
+
340
+ Recovery is local and offline; it never waits for a network request during startup. With
341
+ `maxCrashCount: 0`, launch-health counting and automatic crash-loop rollback are disabled,
342
+ while integrity, runtime compatibility, quarantine, and locally persisted revocation checks
343
+ still apply. Native startup recovery requires a binary built with the corresponding SDK
344
+ `nativeVersion`; it cannot be added to an older installed binary through OTA JavaScript.
345
+ Crashes after an attempt is healthy do not trigger this rollback path and should use normal
346
+ crash reporting plus fix-forward or explicit rollback controls.
347
+
348
+ ## Managed Runtime Delivery
349
+
350
+ Runtime delivery is package-managed. `bundle.drop.config.js` stays focused on
351
+ application-owned values such as project identity, channel, runtime versions, and
352
+ rollback policy; it does not contain manifest hosts, access routes, public keys, or
353
+ a delivery-mode switch.
354
+
355
+ `bundle-drop login` and `bundle-drop init` synchronize the trust bootstrap during
356
+ setup. `bundle-drop sync` performs the same narrow operation later for repair or key
357
+ rotation. Each command validates authenticated project credentials and writes the
358
+ identity-bound `.bundle-drop/runtime-delivery.lock.json`. Metro confirms that
359
+ the bootstrap belongs to the same server, organization, and project before merging
360
+ it into the runtime module. Malformed, copied, unsupported, or private-key-bearing
361
+ data is rejected.
362
+
363
+ Older apps with an inline `runtimeDelivery` block keep their ordinary project
364
+ configuration, but the inline block is ignored and should be removed during
365
+ migration. Only the identity-bound runtime-delivery lockfile can enable managed delivery.
366
+ If the server explicitly disables delivery for a project, synchronization removes a
367
+ stale bootstrap and the SDK continues through the compatible `/ota/resolve` path.
368
+
369
+ The SDK resolves a complete public lane locally. Invalid, expired, incomplete,
370
+ dynamic, unavailable, or network-failed manifests safely fall back to `/ota/resolve`.
371
+ Artifact download authorization remains API-key authenticated and uses opaque
372
+ release and artifact references rather than URLs embedded in the manifest.
373
+
374
+ Lane manifests are signed state and are not themselves the revocation clock. Every
375
+ local check also fetches a small environment-wide signed publisher lease. The SDK
376
+ verifies its key, exact manifest origin, issue time, and short absolute expiry before
377
+ it verifies or persists lane generation state. A missing, invalid, expired, or
378
+ operator-disabled lease therefore falls back to `/ota/resolve`, even when cached
379
+ manifest bytes remain cryptographically valid.
380
+
381
+ Artifact download capabilities are intentionally short-lived. If an artifact URL is
382
+ rejected with HTTP 401 or 403 during download, the SDK reauthorizes the original
383
+ signed selection once and retries only when its generation, target, transport,
384
+ artifact references, and signed hashes are unchanged. Verification, reconstruction,
385
+ and installation failures are never retried this way.
386
+
387
+ With managed delivery, install through `downloadUpdate`, or use the React hook's
388
+ `fetchBundles` and `installBundle(bundle)` list-item flow. Direct named
389
+ `installBundle(hash, url, ...)` calls are rejected because they bypass the fresh
390
+ resolve and artifact-authorization decision.
391
+
392
+ Unchanged install state is reported at most once every seven days. A current bundle
393
+ hash, app environment, or user-property change is reported immediately; successful
394
+ installs continue to use the separate idempotent installed receipt.
395
+
396
+ The manifest URL is derived from `manifestBaseUrl`, `manifestAccessId`, channel,
397
+ platform, and runtime version. `manifestAccessId` is an opaque URL-routing value,
398
+ not a signing secret. `publicKeys` contains public P-256 JWK coordinates keyed by
399
+ the manifest JWS `kid`, which permits signing-key rotation.
400
+
401
+ Pass `onRuntimeDeliveryDiagnostic` to `BundleDrop.init` to export the fast-path
402
+ signals to your metrics system. Events contain a bounded counter name, cumulative
403
+ process count, timestamp, and optional channel/reason/status metadata; they never
404
+ contain access IDs, install IDs, JWS bodies, user properties, or artifact URLs.
405
+ `getRuntimeDeliveryDiagnosticCounters()` returns a process-local snapshot. The
406
+ counter names are `manifest_hit`, `dynamic_manifest`, `origin_fallback`,
407
+ `invalid_signature`, `unknown_key`, `lane_mismatch`,
408
+ `generation_regression`, `generation_equivocation`,
409
+ `manifest_http_error`, `manifest_network_error`, `manifest_timeout`,
410
+ `manifest_too_large`, `manifest_invalid`, `manifest_stream_unavailable`,
411
+ `authority_lease_http_error`, `authority_lease_network_error`,
412
+ `authority_lease_timeout`, `authority_lease_too_large`,
413
+ `authority_lease_invalid`, `authority_lease_invalid_signature`,
414
+ `authority_lease_unknown_key`, `authority_lease_expired`,
415
+ `authority_lease_origin_mismatch`, and `authority_lease_disabled`.
416
+
417
+ Manifest responses are read incrementally and cancelled as soon as they exceed
418
+ 1 MiB. A runtime without a readable response stream fails closed to `/ota/resolve`
419
+ instead of buffering an unbounded body.
420
+
421
+ Managed runtime delivery uses native SHA-256 and ES256 verification. After upgrading to
422
+ an SDK release whose `nativeVersion` includes this support (`0.5.0` or newer), run
423
+ Pods/prebuild as appropriate and ship a new native binary before enabling runtime
424
+ delivery for the project. Bundle Drop's native-version validation will reject a JavaScript/native
425
+ adapter mismatch.
426
+
242
427
  ## Upload an Update
243
428
 
244
429
  With the default literal runtime configuration, Expo uploads resolve the app version
@@ -369,7 +554,7 @@ Import the runtime API from `@gfean/react-native-bundle-drop`.
369
554
  | `BundleDrop.init(options)` | Initialize the runtime for the app process. |
370
555
  | `BundleDrop.setChannel(name)` / `setChannel` | Change the active channel for singleton actions. |
371
556
  | `BundleDrop.getChannelName()` / `getChannelName` | Read the active channel. |
372
- | `BundleDrop.reportHealthy()` / `reportHealthy` | Mark the running OTA candidate healthy for this device. |
557
+ | `BundleDrop.reportHealthy()` / `reportHealthy` | In manual health mode, ask native recovery to mark the exact running OTA attempt healthy. |
373
558
 
374
559
  **`BundleDrop.init(options)`**
375
560
 
@@ -381,6 +566,7 @@ Import the runtime API from `@gfean/react-native-bundle-drop`.
381
566
  | `policy` | `'manual' \| 'immediate' \| 'on-next-launch'` | `'manual'` | Startup behavior after hydration. |
382
567
  | `checkOnly` | `boolean` | `false` | Startup resolves updates without downloading or applying them. |
383
568
  | `onStatusUpdate` | `(status: string) => void` | — | Listener for human-readable status messages. |
569
+ | `onRuntimeDeliveryDiagnostic` | `(event: RuntimeDeliveryDiagnosticEvent) => void` | — | Listener for bounded runtime-delivery counter events suitable for metrics export. |
384
570
 
385
571
  **Update actions** — `checkForUpdate`, `downloadUpdate`, `installBundle`,
386
572
  `applyUpdate`, `getUpdateState`, `getInstalledBundleInfo`, `getAvailableBundles`,
@@ -395,10 +581,13 @@ plus update actions.
395
581
 
396
582
  **Errors** — `BundleDropError`, `isBundleDropError`.
397
583
 
398
- **Metro** — import `withBundleDropExpo` from
399
- `@gfean/react-native-bundle-drop/metro` when configuring Expo Metro manually.
584
+ **Runtime delivery diagnostics** — `getRuntimeDeliveryDiagnosticCounters` returns
585
+ the current process-local counter snapshot.
586
+
587
+ **Metro** — import `withBundleDropExpo` for Expo or `withBundleDrop` for bare React
588
+ Native from `@gfean/react-native-bundle-drop/metro` when configuring Metro manually.
400
589
 
401
- **CLI** (`npx bundle-drop <command>`) — `login`, `logout`, `whoami`, `init`,
590
+ **CLI** (`npx bundle-drop <command>`) — `login`, `logout`, `whoami`, `init`, `sync`,
402
591
  `doctor`, `eas-receipt <ios|android>`, and `upload <ios|android>`.
403
592
 
404
593
  ## Good to Know
@@ -1,3 +1,19 @@
1
+ import javax.inject.Inject
2
+ import org.gradle.process.ExecOperations
3
+
4
+ abstract class BundleDropNativeIdentityCommandExecutor {
5
+ @Inject
6
+ abstract ExecOperations getExecOperations()
7
+
8
+ void execute(File workingDirectory, String executable, List<?> arguments) {
9
+ execOperations.exec { spec ->
10
+ spec.workingDir workingDirectory
11
+ spec.executable executable
12
+ spec.args arguments
13
+ }.assertNormalExitValue()
14
+ }
15
+ }
16
+
1
17
  buildscript {
2
18
  ext.getExtOrDefault = {name ->
3
19
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['BundleDrop_' + name]
@@ -88,6 +104,49 @@ android {
88
104
  }
89
105
  }
90
106
 
107
+ if (!project.hasProperty("standalone") && rootProject.findProject(":bundledrop-expo") == null) {
108
+ def bundleDropProjectRoot = rootProject.projectDir.parentFile.canonicalFile
109
+ def bundleDropConfigFile = new File(bundleDropProjectRoot, "bundle.drop.config.js")
110
+ if (bundleDropConfigFile.isFile()) {
111
+ def bundleDropIdentityWriter = file(
112
+ "../lib/CLI/scripts/native/write-runtime-identity.js"
113
+ ).canonicalFile
114
+ if (!bundleDropIdentityWriter.isFile()) {
115
+ throw new GradleException(
116
+ "Bundle Drop native runtime identity writer is missing: ${bundleDropIdentityWriter}"
117
+ )
118
+ }
119
+ def bundleDropGeneratedAssets = file("${buildDir}/generated/bundleDropIdentity/assets")
120
+ def bundleDropIdentityOutput = new File(
121
+ bundleDropGeneratedAssets,
122
+ "bundle-drop/build-identity.json"
123
+ )
124
+ android.sourceSets.main.assets.srcDir(bundleDropGeneratedAssets)
125
+ def bundleDropCommandExecutor = objects.newInstance(
126
+ BundleDropNativeIdentityCommandExecutor
127
+ )
128
+ def generateBundleDropNativeRuntimeIdentity = tasks.register(
129
+ "generateBundleDropNativeRuntimeIdentity"
130
+ ) { task ->
131
+ task.inputs.file(bundleDropConfigFile)
132
+ task.inputs.file(bundleDropIdentityWriter)
133
+ task.outputs.file(bundleDropIdentityOutput)
134
+ task.doLast {
135
+ def nodeBinary = System.getenv("NODE_BINARY") ?: "node"
136
+ bundleDropCommandExecutor.execute(bundleDropProjectRoot, nodeBinary, [
137
+ bundleDropIdentityWriter.path,
138
+ "--project-root", bundleDropProjectRoot.path,
139
+ "--platform", "android",
140
+ "--output", bundleDropIdentityOutput.path
141
+ ])
142
+ }
143
+ }
144
+ tasks.named("preBuild").configure { task ->
145
+ task.dependsOn(generateBundleDropNativeRuntimeIdentity)
146
+ }
147
+ }
148
+ }
149
+
91
150
  afterEvaluate {
92
151
  tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { kotlinTask ->
93
152
  def javaTask = tasks.findByName(kotlinTask.name.replace("Kotlin", "JavaWithJavac"))
@@ -132,6 +191,7 @@ dependencies {
132
191
 
133
192
  if (project.hasProperty("standalone")) {
134
193
  testImplementation "junit:junit:4.13.2"
194
+ testImplementation "com.squareup.okhttp3:okhttp:4.12.0"
135
195
  testImplementation "org.json:json:20231013"
136
196
  testImplementation "androidx.test:core:1.6.1"
137
197
  testImplementation "org.robolectric:robolectric:4.14.1"
@@ -199,6 +259,12 @@ if (project.hasProperty("standalone")) {
199
259
  limit { counter = "LINE"; minimum = 0.90 }
200
260
  limit { counter = "BRANCH"; minimum = 0.85 }
201
261
  }
262
+ rule {
263
+ element = "CLASS"
264
+ includes = ["com.bundledrop.BundleDropStartupRecoveryController"]
265
+ limit { counter = "LINE"; minimum = 0.90 }
266
+ limit { counter = "BRANCH"; minimum = 0.70 }
267
+ }
202
268
  rule {
203
269
  element = "CLASS"
204
270
  includes = ["com.bundledrop.BundleDropFileOps"]
@@ -0,0 +1,86 @@
1
+ package com.bundledrop
2
+
3
+ import java.io.File
4
+ import java.io.FileOutputStream
5
+ import java.io.InterruptedIOException
6
+ import java.net.URL
7
+ import java.util.concurrent.TimeUnit
8
+ import okhttp3.OkHttpClient
9
+ import okhttp3.Request
10
+
11
+ internal class BundleDropBoundedDownloadHttpException(
12
+ val status: Int,
13
+ message: String,
14
+ ) : java.io.IOException(message)
15
+
16
+ internal class BundleDropBoundedDownloadTooLargeException(message: String) :
17
+ java.io.IOException(message)
18
+
19
+ internal class BundleDropBoundedDownloadTimeoutException(cause: Throwable) :
20
+ java.io.IOException("Download timed out", cause)
21
+
22
+ internal object BundleDropBoundedDownloader {
23
+ fun downloadToFile(
24
+ baseClient: OkHttpClient,
25
+ parsedUrl: URL,
26
+ destFile: File,
27
+ maxBytes: Long,
28
+ timeoutMs: Long,
29
+ ) {
30
+ require(maxBytes > 0) { "maxBytes must be positive" }
31
+ require(timeoutMs > 0) { "timeoutMs must be positive" }
32
+
33
+ val client = baseClient.newBuilder()
34
+ .callTimeout(timeoutMs, TimeUnit.MILLISECONDS)
35
+ .build()
36
+ val request = Request.Builder()
37
+ .url(parsedUrl)
38
+ .get()
39
+ .header("Accept", "application/jose+json, application/json")
40
+ .build()
41
+
42
+ try {
43
+ client.newCall(request).execute().use { response ->
44
+ if (!response.isSuccessful) {
45
+ throw BundleDropBoundedDownloadHttpException(
46
+ response.code,
47
+ "HTTP ${response.code}: ${response.message}",
48
+ )
49
+ }
50
+
51
+ val body = response.body
52
+ ?: throw java.io.IOException("Manifest response body is missing")
53
+ if (body.contentLength() > maxBytes) {
54
+ throw tooLarge(maxBytes)
55
+ }
56
+
57
+ destFile.parentFile?.mkdirs()
58
+ body.byteStream().use { input ->
59
+ FileOutputStream(destFile).use { output ->
60
+ val buffer = ByteArray(8192)
61
+ var totalRead = 0L
62
+ while (true) {
63
+ val bytesRead = input.read(buffer)
64
+ if (bytesRead < 0) break
65
+ if (bytesRead.toLong() > maxBytes - totalRead) {
66
+ throw tooLarge(maxBytes)
67
+ }
68
+ output.write(buffer, 0, bytesRead)
69
+ totalRead += bytesRead
70
+ }
71
+ }
72
+ }
73
+ }
74
+ } catch (error: InterruptedIOException) {
75
+ try { destFile.delete() } catch (_: Exception) {}
76
+ throw BundleDropBoundedDownloadTimeoutException(error)
77
+ } catch (error: Exception) {
78
+ try { destFile.delete() } catch (_: Exception) {}
79
+ throw error
80
+ }
81
+ }
82
+
83
+ private fun tooLarge(maxBytes: Long) = BundleDropBoundedDownloadTooLargeException(
84
+ "Download exceeds $maxBytes byte limit",
85
+ )
86
+ }