@gfean/react-native-bundle-drop 0.3.2 → 0.3.5

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 (51) hide show
  1. package/BundleDrop.podspec +4 -1
  2. package/LICENSE +15 -0
  3. package/README.md +120 -253
  4. package/android/build.gradle +91 -1
  5. package/android/gradle.properties +1 -0
  6. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +131 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +65 -89
  8. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +93 -0
  9. package/ios/BundleDropBridge.m +14 -0
  10. package/ios/BundleDropFileOps.swift +220 -0
  11. package/ios/BundleDropLocator.swift +33 -44
  12. package/ios/BundleDropModule.swift +65 -15
  13. package/ios/BundleDropOtaResolver.swift +112 -0
  14. package/ios/BundleDropZipExtractor.h +13 -0
  15. package/ios/BundleDropZipExtractor.m +226 -0
  16. package/lib/CLI/cli.js +15 -3
  17. package/lib/CLI/scripts/init-config.js +12 -5
  18. package/lib/CLI/scripts/init-native-config.js +17 -9
  19. package/lib/CLI/scripts/post-init.js +9 -3
  20. package/lib/CLI/scripts/upload-cli.js +26 -9
  21. package/lib/api/types.d.ts +4 -3
  22. package/lib/bundleInfo.d.ts +12 -0
  23. package/lib/context.d.ts +17 -0
  24. package/lib/context.js +3 -0
  25. package/lib/errors.d.ts +25 -0
  26. package/lib/errors.js +26 -1
  27. package/lib/fs/fsUtils.d.ts +1 -2
  28. package/lib/fs/fsUtils.js +12 -27
  29. package/lib/fs/userProperties.d.ts +25 -4
  30. package/lib/fs/userProperties.js +51 -7
  31. package/lib/index.d.ts +1 -0
  32. package/lib/install/installFromZip.d.ts +1 -1
  33. package/lib/install/installFromZip.js +47 -42
  34. package/lib/loadConfig.d.ts +19 -0
  35. package/lib/loadConfig.js +11 -7
  36. package/lib/manager/downloadAndInstall.js +7 -25
  37. package/lib/manager/reporting.js +2 -2
  38. package/lib/manager/rollbackState.d.ts +3 -3
  39. package/lib/manager/rollbackState.js +6 -19
  40. package/lib/manager/updateCheck.js +2 -2
  41. package/lib/native/fs.d.ts +6 -0
  42. package/lib/native/fs.js +27 -0
  43. package/lib/runtime/initState.d.ts +2 -2
  44. package/lib/runtime/service.js +2 -0
  45. package/lib/scripts/bundle.js +2 -2
  46. package/lib/scripts/resolve-ios-version.d.ts +2 -0
  47. package/lib/scripts/resolve-ios-version.js +74 -0
  48. package/lib/scripts/upload-bundle.js +10 -4
  49. package/lib/types.d.ts +3 -0
  50. package/package.json +53 -16
  51. package/CLIENT_README.md +0 -411
@@ -1,10 +1,11 @@
1
1
  require "json"
2
2
 
3
3
  package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+ native_version = package["nativeVersion"] || package["version"]
4
5
 
5
6
  Pod::Spec.new do |s|
6
7
  s.name = "BundleDrop"
7
- s.version = package["version"]
8
+ s.version = native_version
8
9
  s.summary = package["description"]
9
10
  s.homepage = package["homepage"]
10
11
  s.license = package["license"]
@@ -14,6 +15,8 @@ Pod::Spec.new do |s|
14
15
  s.source = { :git => ".git", :tag => "#{s.version}" }
15
16
 
16
17
  s.source_files = "ios/**/*.{h,m,mm,swift}"
18
+ s.libraries = "z"
19
+ s.swift_version = "5.0"
17
20
 
18
21
  if respond_to?(:install_modules_dependencies, true)
19
22
  install_modules_dependencies(s)
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 GFean
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,278 +1,145 @@
1
- # React Native Bundle Drop (OTA) — Module Guide
1
+ # BundleDrop
2
2
 
3
- This package powers OTA bundle download/upload and asset resolution for React Native.
3
+ [![npm version](https://img.shields.io/npm/v/%40gfean%2Freact-native-bundle-drop?color=2b7fff&label=npm)](https://www.npmjs.com/package/@gfean/react-native-bundle-drop)
4
+ [![license](https://img.shields.io/badge/license-ISC-84cc16)](#license)
5
+ [![website](https://img.shields.io/badge/website-bundledrop.app-2563eb)](https://bundledrop.app)
6
+ [![docs](https://img.shields.io/badge/docs-bundledrop.app%2Fdocs-0f766e)](https://bundledrop.app/docs)
7
+ [![dashboard](https://img.shields.io/badge/dashboard-developer.bundledrop.app-111827)](https://developer.bundledrop.app)
8
+
9
+ Deploy React Native updates instantly — skip App Store and Play Store delays entirely.
10
+
11
+ Drop-in OTA solution for bare React Native apps.
12
+
13
+ [Website](https://bundledrop.app) • [Docs](https://bundledrop.app/docs) • [Dashboard](https://developer.bundledrop.app)
14
+
15
+ ---
16
+
17
+ ## Why BundleDrop?
18
+
19
+ Shipping a small fix should not require a full mobile release.
20
+
21
+ BundleDrop lets you ship updates instantly, directly to your users:
22
+ - push JavaScript updates instantly
23
+ - roll out changes gradually
24
+ - target specific channels or cohorts
25
+ - rollback safely when needed
26
+ - manage releases from a dedicated dashboard
27
+
28
+ Built for production React Native apps.
29
+
30
+ ---
31
+
32
+ ## What You Can Do
33
+
34
+ - ship production hotfixes in seconds
35
+ - release to `General`, `Beta`, or custom channels
36
+ - target users with dynamic properties
37
+ - control when updates are applied
38
+ - integrate with CI/CD pipelines
39
+
40
+ ---
41
+
42
+ ## Installation
4
43
 
5
- ## Install
6
44
  ```bash
7
- yarn add @gfean/react-native-bundle-drop
8
- cd ios && pod install && cd ..
45
+ npm install @gfean/react-native-bundle-drop
9
46
  ```
10
47
 
11
- ### Metro config (to resolve bundle.drop.config.js from node_modules)
12
- If Metro cannot resolve `bundle.drop.config.js` from within `node_modules`, add an alias in `metro.config.js`:
13
- ```js
14
- // metro.config.js
15
- const path = require('path');
16
-
17
- module.exports = {
18
- resolver: {
19
- extraNodeModules: {
20
- // Allows packages to do: require('bundle-drop-config')
21
- 'bundle-drop-config': path.resolve(__dirname, 'bundle.drop.config.js'),
22
- },
23
- },
24
- };
48
+ ```bash
49
+ cd ios && pod install
25
50
  ```
26
51
 
27
- ## Prerequisites
28
- - `bundle.drop.config.js` in your app root:
29
- ```js
30
- module.exports = {
31
- serverUrl: 'http://localhost:4000', // or prod URL
32
- org: { slug: 'your-org-slug' },
33
- project: {
34
- name: 'Your App Name',
35
- slug: 'your-app-slug',
36
- apiKey: 'optional-api-key', // project-scoped; auto-filled by CLI init/login
37
- },
38
- debugLocal: true, // optional: force localhost (10.0.2.2 on Android, localhost on iOS)
39
- };
40
- ```
41
- - Login token stored at `~/.bundle-drop/auth.json` (use CLI `bundle-drop login`).
42
- - 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.
43
-
44
- ## Runtime APIs (app code)
45
- - `BundleDrop.init({ environment, enabled?, channelName?, policy?, onStatusUpdate?, checkOnly? })`: required startup entrypoint.
46
- - `environment` is required and should come from your app runtime config (`.env`, schema, build flavor, etc.), not from `bundle.drop.config.js`.
47
- - `enabled` defaults to `true`. Set `enabled: false` to keep BundleDrop configured but fully no-op for the current runtime.
48
- - When `enabled: false`, BundleDrop does not run startup OTA work and public OTA actions return disabled/no-op results while warning once.
49
- - `policy: 'manual' | 'immediate' | 'on-next-launch'`
50
- - `manual`: initialize BundleDrop, hydrate local state, run rollback guardrails, and commit the active bundle, but do not auto-resolve/download/apply.
51
- - `immediate`: after startup checks, download and apply immediately.
52
- - `on-next-launch`: after startup checks, download and stage for the next launch.
53
- - `checkOnly: true` limits startup to a resolve/check and skips download/apply even if policy is not `manual`.
54
- - Same-config double init is a no-op. Different-config re-init throws.
55
- - `BundleDrop.setChannel(channelName)`: change the active runtime channel for subsequent singleton OTA actions.
56
- - `BundleDrop.getChannelName()`: read the current active runtime channel.
57
- - `checkForUpdate(onStatusUpdate?)`: resolve-only metadata check (no download). Uses the channel/environment from `BundleDrop.init(...)` and can return `NOOP`, `INSTALL`, or `ROLLBACK` (plus `NO_COMPATIBLE_BUNDLE` details).
58
- - `downloadUpdate(onStatusUpdate?)`: resolves, downloads, and stages the update (sets `pendingApply: true`). Returns `{ status: 'staged' | 'upToDate' | 'rollback' | 'incompatible' | 'disabled' }`.
59
- - `applyUpdate(onStatusUpdate?)`: apply a staged update now (restarts the RN bridge). Returns `{ status: 'applied' | 'noBundle' | 'alreadyApplied' | 'disabled' }`.
60
- - `getUpdateState()`: returns `{ hasBundle, info, pendingApply }` from local metadata.
61
- - `getAvailableBundles(options?)`: fetch a paginated list of downloadable bundles for a channel.
62
- - `installBundle(hash, downloadUrl, bundleVersion?, version?, runtimeVersion?, onStatusUpdate?)`: manually stage a specific bundle by hash and URL.
63
- - `useBundleDrop()` hook (optional helper): subscriber over the singleton runtime started by `BundleDrop.init(...)`. Returns `channelName`, `setChannel`, `isEnabled`, status, busy flag, installed info, pending state, and actions (`checkLatest`, `downloadUpdate`, `applyUpdate`, `fetchAvailableChannels`, `fetchBundles`, `installBundle`). If init is missing, it warns once and exposes a disabled no-op snapshot instead of throwing.
64
- - User property APIs (for targeted rollout):
65
- - `setUserProperty(value: string)`: add a user property (trimmed, de-duplicated).
66
- - `setUserPropery(value: string)`: backward-compatible alias of `setUserProperty`.
67
- - `getUserProperties()` and `getCurrentUserProperties()`: read all saved properties.
68
- - `removeUserProperty(value: string)`: remove one property.
69
- - `resetUserProperties()`: clear all properties.
70
-
71
- Android extras:
72
- - Asset resolver patches (`injectBundleDropImageResolver`, `patchImageRenderToForceResolve`) are applied on module load so images referenced directly still resolve after OTA.
73
- - Manifest is built at bundle time and merged with a runtime manifest built during unzip to cover filename-only lookups.
74
-
75
- ## Config loading
76
- - `src/loadConfig.ts` loads `bundle.drop.config.js` (fixed relative path) and honors `debugLocal` to force localhost.
77
-
78
- ## Server API (Public)
79
- All endpoints are project-scoped and require `x-api-key` (project download API key).
80
-
81
- ### `POST /projects/:projectSlug/ota/resolve`
82
- Request body:
83
- ```json
84
- {
85
- "channelName": "General",
86
- "platform": "ios|android",
87
- "runtimeVersion": "3.0.0",
88
- "environment": "production",
89
- "currentHash": "abc123",
90
- "currentUserProperties": { "cohort": "beta" },
91
- "previousHash": "prev456",
92
- "currentBundleVersion": 12,
93
- "installId": "install-id-string"
94
- }
95
- ```
96
- Notes:
97
- - `installId` is generated once per install and stored at `bundle-drop/install-id.txt` (under the platform-specific `bundle-drop` root).
98
- - `previousHash` is read from `previous.json` when available.
99
- - `currentUserProperties` is read from local `bundle-drop/user-properties.json` and sent automatically on each resolve.
100
- - `environment` is read from `BundleDrop.init(...)` and sent automatically on resolve/install telemetry.
101
-
102
- Response shapes:
103
- ```json
104
- { "action": "NOOP", "reason": "UP_TO_DATE" }
105
- ```
106
- ```json
107
- {
108
- "action": "NOOP",
109
- "reason": "NO_COMPATIBLE_BUNDLE",
110
- "requestedRuntimeVersion": "3.0.0",
111
- "latestRuntimeVersionOnChannel": "3.1.0"
112
- }
113
- ```
114
- ```json
115
- {
116
- "action": "INSTALL",
117
- "target": {
118
- "hash": "def789",
119
- "downloadUrl": "https://signed-url",
120
- "bundleVersion": 13,
121
- "version": "optional",
122
- "runtimeVersion": "optional"
123
- }
124
- }
125
- ```
126
- ```json
127
- { "action": "ROLLBACK", "reason": "CURRENT_REVOKED_NO_SAFE_TARGET" }
128
- ```
129
- Notes:
130
- - `NOOP` reasons: `UP_TO_DATE`, `ROLLOUT_PAUSED`, `ROLLOUT_NOT_ELIGIBLE`, `NO_PUBLISHED_BUNDLE`, `NO_COMPATIBLE_BUNDLE`.
131
- - `ROLLBACK` reasons are server-defined (for example: `CURRENT_REVOKED_NO_SAFE_TARGET`, `CURRENT_REVOKED_NO_COMPATIBLE_TARGET`).
132
- Client behavior:
133
- - `NOOP`: do nothing.
134
- - `INSTALL`: download `target.downloadUrl`, stage it, then apply per policy.
135
- - `ROLLBACK`: switch to `previous.json` if present; otherwise clear `current.json` and fall back to the native bundle (no re-download).
136
-
137
- ### `POST /projects/:projectSlug/bundle/:hash/installed`
138
- Called once the staged bundle is active (after apply on launch). Used for telemetry.
139
- Payload fields:
140
- - `channelName`
141
- - `platform`
142
- - `installId` (persistent per-install id stored at `bundle-drop/install-id.txt`)
143
- - `runtimeVersion`
144
- - `environment`
145
-
146
- ### `GET /projects/:projectSlug/channels/public`
147
- Returns the list of public channel names.
148
-
149
- ## Rollback behavior (default)
150
- - Bundles are stored by hash under the platform `bundle-drop` root and activated via `current.json`.
151
- - The previous active bundle is retained in `previous.json` for rollback.
152
- - A small `state.json` tracks candidate activation, crash window, and commit status.
153
- - The module auto-commits the active bundle once JS has started (via `BundleDrop.init(...)`).
154
- - Server-triggered rollback switches the pointer; if no previous OTA bundle exists, it falls back to the native bundle by clearing `current.json`.
155
-
156
- Optional rollback policy (tuning only):
157
- ```js
158
- rollback: {
159
- maxCrashCount: 2,
160
- crashWindowSec: 300,
161
- commitTimeoutSec: 300,
162
- }
163
- ```
52
+ ---
53
+
54
+ ## Quick Start
55
+
56
+ ### 1. Connect your project
164
57
 
165
- ## Bundling & Uploading (CLI)
166
- - Login once (interactive, stores JWT locally):
167
- ```bash
168
- npx bundle-drop login
169
- ```
170
- - If you need to (re)generate config and fetch the project-scoped API key:
171
- ```bash
172
- npx bundle-drop init
173
- npx bundle-drop init --token bdp_pat_xxx # alternative: use a PAT instead of login
174
- ```
175
- - Upload (builds, zips, uploads, cleans up):
176
- ```bash
177
- npx bundle-drop upload android --version 1.2.3 --channel General
178
- npx bundle-drop upload ios --plist-file ios/Info.plist --channel General
179
- ```
180
- Flags:
181
- - `--version` (ios/android) or `--plist-file` (iOS) or `--buildgradle-path` (Android) to derive version.
182
- - `--release-notes "<text>"` optional release notes (max 2000 chars).
183
- - `--token <pat>` use a Personal Access Token instead of `bundle-drop login`. Ideal for CI/CD.
184
- - `--author <name>` override the author name stored with the bundle (defaults to uploading user's name).
185
- - `--runtimeVersion <v>` override runtimeVersion from metadata/config.
186
-
187
- Requirements:
188
- - `bundle.drop.config.js` with `serverUrl`, `org.slug`, `project.slug`.
189
- - `project.apiKey` is used by the client for public endpoints (channel listing + OTA resolve).
190
- - Authentication via one of: `--token` flag (PAT), or `~/.bundle-drop/auth.json` from `bundle-drop login`.
191
-
192
- ### CI/CD example
193
58
  ```bash
194
- npx bundle-drop upload android \
195
- --version 1.2.3 \
196
- --channel General \
197
- --token $BUNDLE_DROP_PAT \
198
- --author "CI Pipeline"
59
+ npx bundle-drop login
60
+ npx bundle-drop init
199
61
  ```
200
62
 
201
- ## Typical usage
63
+ ### 2. Bootstrap BundleDrop in your app
64
+
202
65
  ```ts
203
- // index.js / entry
204
- import '@gfean/react-native-bundle-drop/bootstrap';
205
66
  import { BundleDrop } from '@gfean/react-native-bundle-drop';
206
67
 
207
68
  BundleDrop.init({
208
69
  enabled: !__DEV__,
209
70
  environment: __DEV__ ? 'development' : 'production',
210
- policy: __DEV__ ? 'manual' : 'on-next-launch',
71
+ policy: 'on-next-launch',
211
72
  channelName: 'General',
212
- onStatusUpdate: msg => console.log('[OTA]', msg),
213
73
  });
74
+ ```
75
+
76
+ ### 3. Ship an update
214
77
 
215
- // Manual UI (hook)
216
- const {
217
- channelName,
218
- setChannel,
219
- isEnabled,
220
- status,
221
- isBusy,
222
- installedInfo,
223
- pendingApply,
224
- checkLatest,
225
- downloadUpdate,
226
- applyUpdate,
227
- fetchBundles,
228
- installBundle,
229
- } = useBundleDrop();
230
-
231
- setChannel('Beta');
232
-
233
- // downloadUpdate() will stage the bundle (applies on next launch or when you call applyUpdate()).
78
+ ```bash
79
+ npx bundle-drop upload android --version 1.2.3 --channel General
80
+ npx bundle-drop upload ios --plist-file ios/Info.plist --channel General
234
81
  ```
235
82
 
236
- ## Targeted rollout properties
83
+ Use `--token` in CI/CD pipelines.
84
+
85
+ ---
86
+
87
+ ## Update Policies
88
+
89
+ Choose how updates are applied:
90
+
91
+ - `manual`: check only, no automatic apply
92
+ - `immediate`: download and apply right away
93
+ - `on-next-launch`: stage now, apply on next launch
94
+
95
+ `on-next-launch` is the safest default for most apps.
96
+
97
+ ---
98
+
99
+ ## Why Not App Store Updates?
100
+
101
+ App Store and Play Store releases are slow and heavyweight.
102
+
103
+ BundleDrop gives you instant updates with full control without waiting for review.
104
+
105
+ ---
106
+
107
+ ## Targeted Rollouts
108
+
109
+ Use user properties to target specific cohorts:
110
+
237
111
  ```ts
238
- import {
239
- setUserProperty,
240
- getUserProperties,
241
- removeUserProperty,
242
- resetUserProperties,
243
- } from '@gfean/react-native-bundle-drop';
244
-
245
- await setUserProperty('QA Analyst');
246
- await setUserProperty('Beta Tester');
247
- await setUserProperty('QA Analyst'); // duplicate ignored
248
-
249
- const props = await getUserProperties(); // ['QA Analyst', 'Beta Tester']
250
- await removeUserProperty('Beta Tester');
251
- await resetUserProperties();
112
+ import { setUserProperty } from '@gfean/react-native-bundle-drop';
113
+
114
+ await setUserProperty('plan', 'pro');
115
+ await setUserProperty('age', 33);
116
+ await setUserProperty('beta', true);
252
117
  ```
253
118
 
254
- ## CLI (bin)
255
- - `modules/react-native-bundle-drop/src/CLI/cli.ts` provides:
256
- - `bundle-drop login|logout|whoami`
257
- - `bundle-drop init [--token <pat>]`
258
- - `bundle-drop upload <platform> --version <ver> --channel <name> [--plist-file <path>] [--runtimeVersion <v>] [--release-notes "<text>"] [--token <pat>] [--author <name>]`
259
- - Auth via `--token` (PAT) or `~/.bundle-drop/auth.json` (from `bundle-drop login`).
260
-
261
- ## Android localhost note
262
- - When `debugLocal` is true (or env is set), Android uses `http://10.0.2.2:4000`; iOS uses `http://localhost:4000`.
263
-
264
- ## Troubleshooting
265
- - If bundling fails with `EMFILE`, raise file descriptor limit (`ulimit -n 8192`) and retry.
266
- - Ensure `bundle.drop.config.js` has `serverUrl`, `org.slug`, and `project.slug`; otherwise the module falls back to localhost defaults.
267
- - If you want BundleDrop off in Metro/dev, prefer `BundleDrop.init({ enabled: false, ... })` over skipping init entirely. That keeps hook consumers mounted safely while OTA APIs remain no-op.
268
-
269
- ## Maintainer notes (internal structure)
270
- - `src/index.tsx` is a thin barrel for public exports.
271
- - Early side-effects/config live in `src/bootstrap.ts` (loads config, detects platform, patches Android images).
272
- - File system helpers: `src/fs/*` (atomic writes, bundle pointers).
273
- - Rollback/state helpers: `src/manager/rollbackState.ts`.
274
- - Native accessors: `src/native/bundleDropNative.ts`.
275
- - Install flow: `src/install/installFromZip.ts`.
276
- - API client layer: `src/api/*` (axios client + typed endpoints).
277
- - Runtime service/state: `src/runtime/*` (`initState`, `service`).
278
- - Update managers: `src/manager/*` (`updateCheck`, `downloadAndInstall`, `updateState`, `reporting`).
119
+ User property values must be strings, finite numbers, or booleans. Keys are trimmed and must be
120
+ non-empty, 128 characters or fewer, and cannot start with `$`, contain `.`, contain a null byte, or
121
+ use reserved prototype names.
122
+
123
+ ---
124
+
125
+ ## Docs
126
+
127
+ Full documentation:
128
+
129
+ - Website: [bundledrop.app](https://bundledrop.app)
130
+ - Docs: [bundledrop.app/docs](https://bundledrop.app/docs)
131
+ - Dashboard: [developer.bundledrop.app](https://developer.bundledrop.app)
132
+
133
+ ---
134
+
135
+ ## Notes
136
+
137
+ - Requires a BundleDrop backend and project setup
138
+ - Supports React Native on iOS and Android
139
+ - Best suited for bare React Native apps
140
+
141
+ ---
142
+
143
+ ## License
144
+
145
+ ISC
@@ -19,6 +19,10 @@ buildscript {
19
19
  apply plugin: "com.android.library"
20
20
  apply plugin: "kotlin-android"
21
21
 
22
+ if (project.hasProperty("standalone")) {
23
+ apply plugin: "jacoco"
24
+ }
25
+
22
26
  def getExtOrIntegerDefault(name) {
23
27
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["BundleDrop_" + name]).toInteger()
24
28
  }
@@ -64,6 +68,19 @@ android {
64
68
  sourceCompatibility JavaVersion.VERSION_1_8
65
69
  targetCompatibility JavaVersion.VERSION_1_8
66
70
  }
71
+
72
+ kotlinOptions {
73
+ jvmTarget = "1.8"
74
+ }
75
+ }
76
+
77
+ afterEvaluate {
78
+ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { kotlinTask ->
79
+ def javaTask = tasks.findByName(kotlinTask.name.replace("Kotlin", "JavaWithJavac"))
80
+ if (javaTask != null && javaTask.hasProperty("targetCompatibility")) {
81
+ kotlinTask.kotlinOptions.jvmTarget = javaTask.targetCompatibility.toString()
82
+ }
83
+ }
67
84
  }
68
85
 
69
86
  repositories {
@@ -74,6 +91,79 @@ repositories {
74
91
  def kotlin_version = getExtOrDefault("kotlinVersion")
75
92
 
76
93
  dependencies {
77
- implementation "com.facebook.react:react-android"
94
+ if (project.hasProperty("standalone")) {
95
+ compileOnly "com.facebook.react:react-android:+"
96
+ } else {
97
+ implementation "com.facebook.react:react-android"
98
+ }
78
99
  implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
100
+ testImplementation "junit:junit:4.13.2"
101
+ testImplementation "org.json:json:20231013"
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // JaCoCo coverage for host-side unit tests (standalone only)
106
+ // ---------------------------------------------------------------------------
107
+
108
+ if (project.hasProperty("standalone")) {
109
+ android.testOptions.unitTests.all {
110
+ jacoco {
111
+ includeNoLocationClasses = true
112
+ excludes = ["jdk.internal.*"]
113
+ }
114
+ }
115
+
116
+ def excludedFromCoverage = ["**/BundleDropModule*", "**/BundleDropPackage*"]
117
+
118
+ tasks.register("jacocoTestReport", JacocoReport) {
119
+ dependsOn "testDebugUnitTest"
120
+ group = "verification"
121
+ description = "Generate JaCoCo coverage report for debug unit tests"
122
+
123
+ def mainSrc = "${project.projectDir}/src/main/java"
124
+ def debugTree = fileTree(
125
+ dir: "${buildDir}/tmp/kotlin-classes/debug",
126
+ excludes: excludedFromCoverage
127
+ )
128
+ def execData = file("${buildDir}/jacoco/testDebugUnitTest.exec")
129
+
130
+ sourceDirectories.setFrom(files(mainSrc))
131
+ classDirectories.setFrom(debugTree)
132
+ executionData.setFrom(files(execData))
133
+
134
+ reports {
135
+ html.required = true
136
+ xml.required = true
137
+ }
138
+ }
139
+
140
+ tasks.register("jacocoCoverageGate", JacocoCoverageVerification) {
141
+ dependsOn "jacocoTestReport"
142
+ group = "verification"
143
+ description = "Enforce coverage thresholds on testable native classes"
144
+
145
+ def debugTree = fileTree(
146
+ dir: "${buildDir}/tmp/kotlin-classes/debug",
147
+ excludes: excludedFromCoverage
148
+ )
149
+ def execData = file("${buildDir}/jacoco/testDebugUnitTest.exec")
150
+
151
+ classDirectories.setFrom(debugTree)
152
+ executionData.setFrom(files(execData))
153
+
154
+ violationRules {
155
+ rule {
156
+ element = "CLASS"
157
+ includes = ["com.bundledrop.BundleDropOtaResolver"]
158
+ limit { counter = "LINE"; minimum = 0.90 }
159
+ limit { counter = "BRANCH"; minimum = 0.85 }
160
+ }
161
+ rule {
162
+ element = "CLASS"
163
+ includes = ["com.bundledrop.BundleDropFileOps"]
164
+ limit { counter = "LINE"; minimum = 0.55 }
165
+ limit { counter = "BRANCH"; minimum = 0.55 }
166
+ }
167
+ }
168
+ }
79
169
  }
@@ -3,3 +3,4 @@ BundleDrop_minSdkVersion=24
3
3
  BundleDrop_targetSdkVersion=34
4
4
  BundleDrop_compileSdkVersion=35
5
5
  BundleDrop_ndkVersion=27.1.12297006
6
+ android.useAndroidX=true
@@ -0,0 +1,131 @@
1
+ package com.bundledrop
2
+
3
+ import java.io.File
4
+ import java.io.FileInputStream
5
+ import java.io.FileOutputStream
6
+ import java.net.URL
7
+ import java.util.zip.ZipInputStream
8
+
9
+ object BundleDropFileOps {
10
+
11
+ fun validateHttpUrl(url: String): URL {
12
+ val parsed = URL(url)
13
+ val scheme = parsed.protocol?.lowercase()
14
+ if (scheme != "https" && scheme != "http") {
15
+ throw java.io.IOException("Invalid or non-HTTP URL: $url")
16
+ }
17
+ return parsed
18
+ }
19
+
20
+ fun unlinkPath(path: String) {
21
+ val file = File(path)
22
+ if (file.exists()) {
23
+ if (file.isDirectory) file.deleteRecursively() else file.delete()
24
+ }
25
+ }
26
+
27
+ fun unzipFile(
28
+ zipPath: String,
29
+ destPath: String,
30
+ maxEntryBytes: Long = 128L * 1024 * 1024,
31
+ maxTotalBytes: Long = 512L * 1024 * 1024,
32
+ ): List<String> {
33
+ val destDir = File(destPath)
34
+ java.util.zip.ZipFile(zipPath).use { /* validate central directory before extraction */ }
35
+ if (!destDir.exists()) destDir.mkdirs()
36
+
37
+ val filenames = mutableListOf<String>()
38
+ val buf = ByteArray(8192)
39
+ var totalWritten = 0L
40
+
41
+ ZipInputStream(FileInputStream(zipPath)).use { zis ->
42
+ var entry = zis.nextEntry
43
+ while (entry != null) {
44
+ if (!entry.isDirectory) {
45
+ val outFile = File(destDir, entry.name)
46
+ if (!outFile.canonicalPath.startsWith(destDir.canonicalPath + File.separator)) {
47
+ throw SecurityException("Zip entry outside target dir: ${entry.name}")
48
+ }
49
+ outFile.parentFile?.mkdirs()
50
+ var entryWritten = 0L
51
+ FileOutputStream(outFile).use { fos ->
52
+ var len: Int
53
+ while (zis.read(buf).also { len = it } > 0) {
54
+ entryWritten += len
55
+ totalWritten += len
56
+ if (entryWritten > maxEntryBytes) {
57
+ throw java.io.IOException("ZIP entry exceeds ${maxEntryBytes / (1024 * 1024)} MB limit: ${entry.name}")
58
+ }
59
+ if (totalWritten > maxTotalBytes) {
60
+ throw java.io.IOException("ZIP total uncompressed exceeds ${maxTotalBytes / (1024 * 1024)} MB limit")
61
+ }
62
+ fos.write(buf, 0, len)
63
+ }
64
+ }
65
+ filenames.add(entry.name)
66
+ } else {
67
+ val dirFile = File(destDir, entry.name)
68
+ if (!dirFile.canonicalPath.startsWith(destDir.canonicalPath + File.separator)) {
69
+ throw SecurityException("Zip entry outside target dir: ${entry.name}")
70
+ }
71
+ dirFile.mkdirs()
72
+ }
73
+ zis.closeEntry()
74
+ entry = zis.nextEntry
75
+ }
76
+ }
77
+
78
+ return filenames
79
+ }
80
+
81
+ fun moveFile(src: File, dest: File) {
82
+ dest.parentFile?.mkdirs()
83
+ if (!src.renameTo(dest)) {
84
+ src.copyTo(dest, overwrite = true)
85
+ src.delete()
86
+ }
87
+ }
88
+
89
+ fun downloadToFile(
90
+ parsedUrl: URL,
91
+ destFile: File,
92
+ maxBytes: Long = 256L * 1024 * 1024,
93
+ connectTimeout: Int = 30_000,
94
+ readTimeout: Int = 60_000,
95
+ ) {
96
+ var connection: java.net.HttpURLConnection? = null
97
+ try {
98
+ destFile.parentFile?.mkdirs()
99
+
100
+ connection = parsedUrl.openConnection() as java.net.HttpURLConnection
101
+ connection.connectTimeout = connectTimeout
102
+ connection.readTimeout = readTimeout
103
+ connection.instanceFollowRedirects = true
104
+
105
+ val status = connection.responseCode
106
+ if (status !in 200..299) {
107
+ throw java.io.IOException("HTTP $status: ${connection.responseMessage}")
108
+ }
109
+
110
+ var totalRead = 0L
111
+ connection.inputStream.use { input ->
112
+ FileOutputStream(destFile).use { output ->
113
+ val buf = ByteArray(8192)
114
+ var len: Int
115
+ while (input.read(buf).also { len = it } > 0) {
116
+ totalRead += len
117
+ if (totalRead > maxBytes) {
118
+ throw java.io.IOException("Download exceeds ${maxBytes / (1024 * 1024)} MB limit")
119
+ }
120
+ output.write(buf, 0, len)
121
+ }
122
+ }
123
+ }
124
+ } catch (e: Exception) {
125
+ try { destFile.delete() } catch (_: Exception) {}
126
+ throw e
127
+ } finally {
128
+ try { connection?.disconnect() } catch (_: Exception) {}
129
+ }
130
+ }
131
+ }