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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLIENT_README.md CHANGED
@@ -49,25 +49,35 @@ module.exports = {
49
49
  ```
50
50
 
51
51
  ## 3) Minimal usage
52
- Startup (optional auto mode):
52
+ Startup (required):
53
53
  ```ts
54
- import { useEffect } from 'react';
55
- import { initUpdateManager } from '@gfean/react-native-bundle-drop';
56
-
57
- useEffect(() => {
58
- initUpdateManager({
59
- policy: __DEV__ ? 'manual' : 'on-next-launch', // or 'immediate'
60
- channelName: 'General',
61
- onStatusUpdate: msg => console.log('[OTA]', msg),
62
- });
63
- }, []);
54
+ import '@gfean/react-native-bundle-drop/bootstrap';
55
+ import { BundleDrop } from '@gfean/react-native-bundle-drop';
56
+
57
+ BundleDrop.init({
58
+ enabled: !__DEV__,
59
+ environment: __DEV__ ? 'development' : 'production',
60
+ policy: __DEV__ ? 'manual' : 'on-next-launch',
61
+ channelName: 'General',
62
+ onStatusUpdate: msg => console.log('[OTA]', msg),
63
+ });
64
64
  ```
65
65
 
66
+ `environment` is required and should come from your app runtime config (`.env`, schema loader, build flavor, etc.), not from `bundle.drop.config.js`. `enabled` defaults to `true`; set `enabled: false` when you want BundleDrop initialized in no-op mode for a given runtime.
67
+
68
+ Recommended pattern:
69
+ - Always call `BundleDrop.init(...)` during startup.
70
+ - Use `enabled: false` when OTA should be off for a given runtime, such as Metro/dev or certain app flavors.
71
+ - This keeps `useBundleDrop()` safe to mount while all OTA actions remain no-op.
72
+
66
73
  Manual UI example:
67
74
  ```ts
68
75
  import { useBundleDrop } from '@gfean/react-native-bundle-drop';
69
76
 
70
77
  const {
78
+ channelName,
79
+ setChannel,
80
+ isEnabled,
71
81
  status,
72
82
  isBusy,
73
83
  installedInfo,
@@ -77,25 +87,32 @@ const {
77
87
  applyUpdate,
78
88
  fetchAvailableChannels,
79
89
  availableChannels,
80
- } = useBundleDrop({ channelName: 'General' });
90
+ } = useBundleDrop();
81
91
  ```
82
92
 
93
+ If `BundleDrop.init(...)` is skipped, BundleDrop warns once and behaves like `enabled: false` until init happens.
94
+
83
95
  Quick check-only pattern:
84
96
  ```ts
85
- const { checkLatest, status } = useBundleDrop({ channelName: 'General' });
97
+ const { checkLatest, status } = useBundleDrop();
86
98
  await checkLatest();
87
99
  console.log(status);
88
100
  ```
89
101
 
90
102
  ## 4) Policies
91
- - `manual`: no auto download/apply.
103
+ - `manual`: initialize local BundleDrop state but do not auto resolve/download/apply on startup.
92
104
  - `immediate`: download, stage, then apply immediately.
93
105
  - `on-next-launch`: download and stage now; apply on next launch.
94
106
 
107
+ `checkOnly: true` can be combined with init when you want startup to perform only a resolve/check.
108
+
95
109
  ## 5) Channels
96
110
  - Keep channel names stable: `General`, `Beta`, `QA`.
97
- - Use the same `channelName` in app runtime and in upload CLI.
111
+ - `BundleDrop.init(...)` sets the initial runtime `channelName`.
112
+ - `BundleDrop.setChannel(channelName)` or `useBundleDrop().setChannel(channelName)` can switch the active channel later.
113
+ - `BundleDrop.getChannelName()` reads the active runtime channel outside React.
98
114
  - `fetchAvailableChannels()` retrieves available public channels for the configured project.
115
+ - `fetchBundles({ channelName? })` lists downloadable bundles, defaulting to the active runtime channel.
99
116
 
100
117
  ## 6) Compatibility (`runtimeVersion`)
101
118
  - Define `runtimeVersion` per platform in `bundle.drop.config.js`.
@@ -132,6 +149,16 @@ Behavior:
132
149
  - Stored locally in `bundle-drop/user-properties.json`.
133
150
  - Sent automatically as `currentUserProperties` during OTA resolve checks.
134
151
 
152
+ Environment behavior:
153
+ - `environment` is sent automatically from `BundleDrop.init(...)`.
154
+ - It is intended for analytics and future runtime targeting context.
155
+ - Do not store environment in `bundle.drop.config.js`.
156
+
157
+ Disabled behavior:
158
+ - With `enabled: false`, BundleDrop does not perform startup OTA work.
159
+ - `useBundleDrop()` exposes `isEnabled: false`.
160
+ - OTA actions such as `checkLatest()`, `downloadUpdate()`, and `applyUpdate()` return disabled/no-op results instead of throwing.
161
+
135
162
  ## 8) Bundling/upload (CI/local)
136
163
  - Login (interactive, for local development):
137
164
  ```bash
@@ -367,10 +394,13 @@ Add the import and replace the `sourceURLForBridge:` method:
367
394
 
368
395
  ## 11) Public API snapshot
369
396
  Top-level exports:
397
+ - `BundleDrop.init`
398
+ - `BundleDrop.setChannel`
399
+ - `BundleDrop.getChannelName`
370
400
  - `getAvailableChannels`, `checkForUpdate`, `getInstalledBundleInfo`
371
- - `downloadUpdate`
401
+ - `getAvailableBundles`
402
+ - `downloadUpdate`, `installBundle`
372
403
  - `getUpdateState`, `applyUpdate`
373
- - `initUpdateManager`
374
404
  - `useBundleDrop`
375
405
  - `BundleDropError`, `isBundleDropError`
376
406
  - `setUserProperty`, `setUserPropery`, `getUserProperties`, `getCurrentUserProperties`, `removeUserProperty`, `resetUserProperties`
package/README.md CHANGED
@@ -42,17 +42,25 @@ module.exports = {
42
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
43
 
44
44
  ## Runtime APIs (app code)
45
- - `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).
46
- - `downloadUpdate(options?, onStatusUpdate?)`: resolves (unless `resolvedTarget` is provided), downloads, and stages the update (sets `pendingApply: true`). Returns `{ status: 'staged' | 'upToDate' | 'rollback' | 'incompatible' }`.
47
- - `applyUpdate(onStatusUpdate?)`: apply a staged update now (restarts the RN bridge).
48
- - `getUpdateState()`: returns `{ hasBundle, info, pendingApply }` from local metadata.
49
- - `initUpdateManager({ channelName, policy, onStatusUpdate, checkOnly })`: startup helper
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.
50
49
  - `policy: 'manual' | 'immediate' | 'on-next-launch'`
51
- - `immediate`: download and stage, then apply now (reload). If a staged update is pending, applies it immediately.
52
- - `on-next-launch`: download and stage; app will pick it up on the next launch (pending flag remains until applied).
53
- - `manual`: no auto download/apply (resolve still runs for status and rollback decisions).
54
- - 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.
55
- - `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.
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.
56
64
  - User property APIs (for targeted rollout):
57
65
  - `setUserProperty(value: string)`: add a user property (trimmed, de-duplicated).
58
66
  - `setUserPropery(value: string)`: backward-compatible alias of `setUserProperty`.
@@ -77,8 +85,9 @@ Request body:
77
85
  "channelName": "General",
78
86
  "platform": "ios|android",
79
87
  "runtimeVersion": "3.0.0",
88
+ "environment": "production",
80
89
  "currentHash": "abc123",
81
- "currentUserProperties": ["QA Analyst", "Beta Tester"],
90
+ "currentUserProperties": { "cohort": "beta" },
82
91
  "previousHash": "prev456",
83
92
  "currentBundleVersion": 12,
84
93
  "installId": "install-id-string"
@@ -88,6 +97,7 @@ Notes:
88
97
  - `installId` is generated once per install and stored at `bundle-drop/install-id.txt` (under the platform-specific `bundle-drop` root).
89
98
  - `previousHash` is read from `previous.json` when available.
90
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.
91
101
 
92
102
  Response shapes:
93
103
  ```json
@@ -131,6 +141,7 @@ Payload fields:
131
141
  - `platform`
132
142
  - `installId` (persistent per-install id stored at `bundle-drop/install-id.txt`)
133
143
  - `runtimeVersion`
144
+ - `environment`
134
145
 
135
146
  ### `GET /projects/:projectSlug/channels/public`
136
147
  Returns the list of public channel names.
@@ -139,7 +150,7 @@ Returns the list of public channel names.
139
150
  - Bundles are stored by hash under the platform `bundle-drop` root and activated via `current.json`.
140
151
  - The previous active bundle is retained in `previous.json` for rollback.
141
152
  - A small `state.json` tracks candidate activation, crash window, and commit status.
142
- - The module auto-commits the active bundle once JS has started (via `initUpdateManager`/`useBundleDrop`).
153
+ - The module auto-commits the active bundle once JS has started (via `BundleDrop.init(...)`).
143
154
  - Server-triggered rollback switches the pointer; if no previous OTA bundle exists, it falls back to the native bundle by clearing `current.json`.
144
155
 
145
156
  Optional rollback policy (tuning only):
@@ -189,17 +200,23 @@ npx bundle-drop upload android \
189
200
 
190
201
  ## Typical usage
191
202
  ```ts
192
- // App.tsx startup (optional auto behavior)
193
- useEffect(() => {
194
- initUpdateManager({
195
- policy: __DEV__ ? 'manual' : 'on-next-launch', // or 'immediate'
196
- channelName: 'General',
197
- onStatusUpdate: msg => console.log('[OTA]', msg),
198
- });
199
- }, []);
203
+ // index.js / entry
204
+ import '@gfean/react-native-bundle-drop/bootstrap';
205
+ import { BundleDrop } from '@gfean/react-native-bundle-drop';
206
+
207
+ BundleDrop.init({
208
+ enabled: !__DEV__,
209
+ environment: __DEV__ ? 'development' : 'production',
210
+ policy: __DEV__ ? 'manual' : 'on-next-launch',
211
+ channelName: 'General',
212
+ onStatusUpdate: msg => console.log('[OTA]', msg),
213
+ });
200
214
 
201
215
  // Manual UI (hook)
202
216
  const {
217
+ channelName,
218
+ setChannel,
219
+ isEnabled,
203
220
  status,
204
221
  isBusy,
205
222
  installedInfo,
@@ -207,7 +224,11 @@ const {
207
224
  checkLatest,
208
225
  downloadUpdate,
209
226
  applyUpdate,
210
- } = useBundleDrop({ channelName: 'General' });
227
+ fetchBundles,
228
+ installBundle,
229
+ } = useBundleDrop();
230
+
231
+ setChannel('Beta');
211
232
 
212
233
  // downloadUpdate() will stage the bundle (applies on next launch or when you call applyUpdate()).
213
234
  ```
@@ -243,6 +264,7 @@ await resetUserProperties();
243
264
  ## Troubleshooting
244
265
  - If bundling fails with `EMFILE`, raise file descriptor limit (`ulimit -n 8192`) and retry.
245
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.
246
268
 
247
269
  ## Maintainer notes (internal structure)
248
270
  - `src/index.tsx` is a thin barrel for public exports.
@@ -252,4 +274,5 @@ await resetUserProperties();
252
274
  - Native accessors: `src/native/bundleDropNative.ts`.
253
275
  - Install flow: `src/install/installFromZip.ts`.
254
276
  - API client layer: `src/api/*` (axios client + typed endpoints).
255
- - Update managers: `src/manager/*` (`updateCheck`, `downloadAndInstall`, `updateState`, `reporting`, `initUpdateManager`).
277
+ - Runtime service/state: `src/runtime/*` (`initState`, `service`).
278
+ - Update managers: `src/manager/*` (`updateCheck`, `downloadAndInstall`, `updateState`, `reporting`).
package/lib/CLI/cli.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  #!/usr/bin/env node
2
- export {};
2
+ import { Command } from 'commander';
3
+ export declare const buildProgram: () => Command;
package/lib/CLI/cli.js CHANGED
@@ -4,16 +4,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.buildProgram = void 0;
7
8
  const chalk_1 = __importDefault(require("chalk"));
8
9
  const commander_1 = require("commander");
9
10
  const figures_1 = __importDefault(require("figures"));
11
+ const fs_1 = __importDefault(require("fs"));
12
+ const os_1 = __importDefault(require("os"));
13
+ const path_1 = __importDefault(require("path"));
10
14
  const upload_cli_1 = __importDefault(require("./scripts/upload-cli"));
11
15
  const post_init_1 = require("./scripts/post-init");
12
16
  const package_json_1 = __importDefault(require("../../package.json"));
13
- const program = new commander_1.Command();
14
- program
15
- .name('bundle-drop')
16
- .version(package_json_1.default.version || '0.0.0', '-v, --cli-version', 'Show CLI version');
17
17
  const logo = chalk_1.default.cyanBright(`
18
18
  ______ ______
19
19
  |_ _ \\ |_ _ \`.
@@ -22,12 +22,40 @@ const logo = chalk_1.default.cyanBright(`
22
22
  _| |__) |_| |_.' /
23
23
  |_______/|______.'
24
24
  `) + chalk_1.default.bold.cyanBright(`\n${figures_1.default.star} React Native Bundle Drop CLI ${figures_1.default.star}`);
25
- program.addHelpText('beforeAll', logo);
26
- program.addHelpText('before', `
25
+ const DEFAULT_SERVER_URL = 'https://api.bundledrop.app';
26
+ const getTokenPath = () => path_1.default.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
27
+ const normalizeServerUrl = (url) => url?.replace(/\/$/, '') || DEFAULT_SERVER_URL;
28
+ const readStoredAuthData = () => {
29
+ const tokenPath = getTokenPath();
30
+ if (!fs_1.default.existsSync(tokenPath)) {
31
+ return { tokenPath, exists: false, data: null, isInvalid: false };
32
+ }
33
+ try {
34
+ const raw = fs_1.default.readFileSync(tokenPath, 'utf-8');
35
+ const parsed = JSON.parse(raw);
36
+ if (!parsed || typeof parsed !== 'object') {
37
+ throw new Error('Invalid auth payload');
38
+ }
39
+ return { tokenPath, exists: true, data: parsed, isInvalid: false };
40
+ }
41
+ catch {
42
+ return { tokenPath, exists: true, data: null, isInvalid: true };
43
+ }
44
+ };
45
+ const logInvalidAuthFile = () => {
46
+ console.log('❌ Failed to read CLI auth session. Please run `bundle-drop login` again or use --token.');
47
+ };
48
+ const buildProgram = () => {
49
+ const program = new commander_1.Command();
50
+ program
51
+ .name('bundle-drop')
52
+ .version(package_json_1.default.version || '0.0.0', '-v, --cli-version', 'Show CLI version');
53
+ program.addHelpText('beforeAll', logo);
54
+ program.addHelpText('before', `
27
55
  ${chalk_1.default.magentaBright('A blazing-fast OTA delivery system for React Native by GFean.\n')}
28
56
  ${chalk_1.default.bold.cyan('Available Commands:')}
29
57
  `);
30
- program.addHelpText('afterAll', `
58
+ program.addHelpText('afterAll', `
31
59
  ${chalk_1.default.bold.cyan('Common Usage:')}
32
60
  ${chalk_1.default.gray('bundle-drop login')}
33
61
  ${chalk_1.default.gray('bundle-drop init')}
@@ -36,22 +64,19 @@ ${chalk_1.default.bold.cyan('Common Usage:')}
36
64
  ${chalk_1.default.gray('bundle-drop upload android --buildgradle-path android/app/build.gradle --channel General --release-notes "Fixes"')}
37
65
 
38
66
  ${chalk_1.default.gray('Need help? →')} ${chalk_1.default.underline.gray('https://github.com/GFean/react-native-bundle-drop')}\n`);
39
- // ------------------------
40
- // Commands
41
- // ------------------------
42
- program
43
- .command('upload')
44
- .argument('<platform>', chalk_1.default.gray('ios or android'))
45
- .option('--plist-file <path>', 'Path to Info.plist for iOS')
46
- .option('--version <version>', 'App version. iOS will fallback to --plist-file; Android can fallback to build.gradle when provided.')
47
- .option('--buildgradle-path <path>', 'Optional Android build.gradle path to read versionName')
48
- .option('--channel <name>', 'Target channel name to associate the bundle') // ← ADD THIS LINE
49
- .option('--runtimeVersion <runtimeVersion>', 'Override runtimeVersion from metadata/config')
50
- .option('--release-notes <text>', 'Release notes (max 2000 chars)')
51
- .option('--token <token>', 'Personal Access Token (alternative to `bundle-drop login`)')
52
- .option('--author <name>', 'Override the author name stored with the bundle')
53
- .description(chalk_1.default.whiteBright('Bundle and upload an OTA zip to the server'))
54
- .addHelpText('after', `
67
+ program
68
+ .command('upload')
69
+ .argument('<platform>', chalk_1.default.gray('ios or android'))
70
+ .option('--plist-file <path>', 'Path to Info.plist for iOS')
71
+ .option('--version <version>', 'App version. iOS will fallback to --plist-file; Android can fallback to build.gradle when provided.')
72
+ .option('--buildgradle-path <path>', 'Optional Android build.gradle path to read versionName')
73
+ .option('--channel <name>', 'Target channel name to associate the bundle')
74
+ .option('--runtimeVersion <runtimeVersion>', 'Override runtimeVersion from metadata/config')
75
+ .option('--release-notes <text>', 'Release notes (max 2000 chars)')
76
+ .option('--token <token>', 'Personal Access Token (alternative to `bundle-drop login`)')
77
+ .option('--author <name>', 'Override the author name stored with the bundle')
78
+ .description(chalk_1.default.whiteBright('Bundle and upload an OTA zip to the server'))
79
+ .addHelpText('after', `
55
80
  ${chalk_1.default.bold('Examples:')}
56
81
  ${chalk_1.default.gray('bundle-drop upload android --version 1.2.3 --channel General')}
57
82
  ${chalk_1.default.gray('bundle-drop upload ios --plist-file ios/Info.plist --channel General')}
@@ -59,114 +84,100 @@ ${chalk_1.default.bold('Examples:')}
59
84
  ${chalk_1.default.gray('bundle-drop upload android --version 1.2.3 --channel General --runtimeVersion 3.0.0')}
60
85
  ${chalk_1.default.gray('bundle-drop upload android --version 1.2.3 --channel General --token bdp_pat_xxx')}
61
86
  `)
62
- .action(upload_cli_1.default);
63
- program
64
- .command('logout')
65
- .description('Log out of the CLI')
66
- .action(() => {
67
- //eslint-disable-next-line
68
- const fs = require('fs');
69
- //eslint-disable-next-line
70
- const path = require('path');
71
- //eslint-disable-next-line
72
- const os = require('os');
73
- const tokenPath = path.join(os.homedir(), '.bundle-drop', 'auth.json');
74
- if (fs.existsSync(tokenPath)) {
75
- fs.unlinkSync(tokenPath);
76
- console.log('🚪 Logged out.');
77
- }
78
- else {
79
- console.log('ℹ️ Not logged in.');
80
- }
81
- });
82
- program
83
- .command('login')
84
- .description('Log in to the CLI')
85
- .action(() => {
86
- //eslint-disable-next-line
87
- require('../CLI/scripts/login-cli').default();
88
- });
89
- program
90
- .command('init')
91
- .option('--token <token>', 'Personal Access Token (alternative to `bundle-drop login`)')
92
- .description('Generate bundle.drop.config.js from your logged-in account context')
93
- .action(async (options) => {
94
- //eslint-disable-next-line
95
- const fs = require('fs');
96
- //eslint-disable-next-line
97
- const path = require('path');
98
- //eslint-disable-next-line
99
- const os = require('os');
100
- if (options.token) {
101
- const serverUrl = process.env.BUNDLE_DROP_SERVER_URL?.replace(/\/$/, '') ||
102
- 'https://api.bundledrop.app';
103
- //eslint-disable-next-line
87
+ .action(upload_cli_1.default);
88
+ program
89
+ .command('logout')
90
+ .description('Log out of the CLI')
91
+ .action(() => {
92
+ const tokenPath = getTokenPath();
93
+ if (fs_1.default.existsSync(tokenPath)) {
94
+ fs_1.default.unlinkSync(tokenPath);
95
+ console.log('🚪 Logged out.');
96
+ }
97
+ else {
98
+ console.log('ℹ️ Not logged in.');
99
+ }
100
+ });
101
+ program
102
+ .command('login')
103
+ .description('Log in to the CLI')
104
+ .action(() => {
105
+ require('../CLI/scripts/login-cli').default();
106
+ });
107
+ program
108
+ .command('init')
109
+ .option('--token <token>', 'Personal Access Token (alternative to `bundle-drop login`)')
110
+ .description('Generate bundle.drop.config.js from your logged-in account context')
111
+ .action(async (options) => {
112
+ if (options.token) {
113
+ await require('../CLI/scripts/init-config').initConfig({
114
+ serverUrl: normalizeServerUrl(process.env.BUNDLE_DROP_SERVER_URL),
115
+ projects: [],
116
+ organizations: [],
117
+ downloadApiKey: '',
118
+ authToken: options.token,
119
+ });
120
+ await (0, post_init_1.runPostInitPrompts)();
121
+ return;
122
+ }
123
+ const authState = readStoredAuthData();
124
+ if (!authState.exists) {
125
+ console.log('ℹ️ Not logged in. Please run `bundle-drop login` or use --token.');
126
+ return;
127
+ }
128
+ if (authState.isInvalid || !authState.data) {
129
+ logInvalidAuthFile();
130
+ return;
131
+ }
132
+ const data = authState.data;
133
+ if (!data.token) {
134
+ logInvalidAuthFile();
135
+ return;
136
+ }
104
137
  await require('../CLI/scripts/init-config').initConfig({
105
- serverUrl,
106
- projects: [],
107
- organizations: [],
108
- downloadApiKey: '',
109
- authToken: options.token,
138
+ serverUrl: normalizeServerUrl(data.serverUrl || data.baseUrl || process.env.BUNDLE_DROP_SERVER_URL),
139
+ projects: data.projects || [],
140
+ organizations: data.organizations || [],
141
+ downloadApiKey: data.downloadApiKey || '',
142
+ authToken: data.token,
110
143
  });
111
144
  await (0, post_init_1.runPostInitPrompts)();
112
- return;
113
- }
114
- const tokenPath = path.join(os.homedir(), '.bundle-drop', 'auth.json');
115
- if (!fs.existsSync(tokenPath)) {
116
- console.log('ℹ️ Not logged in. Please run `bundle-drop login` or use --token.');
117
- return;
118
- }
119
- const data = JSON.parse(fs.readFileSync(tokenPath, 'utf-8'));
120
- const projects = data.projects || [];
121
- const organizations = data.organizations || [];
122
- const downloadApiKey = data.downloadApiKey || '';
123
- const token = data.token;
124
- const serverUrl = data.serverUrl ||
125
- data.baseUrl ||
126
- process.env.BUNDLE_DROP_SERVER_URL?.replace(/\/$/, '') ||
127
- 'https://api.bundledrop.app';
128
- //eslint-disable-next-line
129
- await require('../CLI/scripts/init-config').initConfig({
130
- serverUrl,
131
- projects,
132
- organizations,
133
- downloadApiKey,
134
- authToken: token,
135
145
  });
136
- await (0, post_init_1.runPostInitPrompts)();
137
- });
138
- program
139
- .command('init-native')
140
- .description('Attempt to apply native changes (AppDelegate / MainApplication) automatically')
141
- .action(() => {
142
- //eslint-disable-next-line
143
- require('../CLI/scripts/init-native-config').initNativeConfig();
144
- });
145
- program
146
- .command('init-metro')
147
- .description('Ensure Metro can resolve bundle.drop.config.js via extraNodeModules alias')
148
- .action(() => {
149
- //eslint-disable-next-line
150
- require('../CLI/scripts/init-metro-config').initMetroConfig();
151
- });
152
- program
153
- .command('whoami')
154
- .description('Show currently logged in user')
155
- .action(() => {
156
- //eslint-disable-next-line
157
- const fs = require('fs');
158
- //eslint-disable-next-line
159
- const path = require('path');
160
- //eslint-disable-next-line
161
- const os = require('os');
162
- const tokenPath = path.join(os.homedir(), '.bundle-drop', 'auth.json');
163
- if (fs.existsSync(tokenPath)) {
164
- const data = fs.readFileSync(tokenPath, 'utf-8');
165
- const { user } = JSON.parse(data);
166
- console.log(`👤 Logged in as: ${chalk_1.default.cyan(user.firstName + ' ' + user.lastName)} <${user.email}>`);
167
- }
168
- else {
169
- console.log('ℹ️ Not logged in.');
170
- }
171
- });
172
- program.parse();
146
+ program
147
+ .command('init-native')
148
+ .description('Attempt to apply native changes (AppDelegate / MainApplication) automatically')
149
+ .action(() => {
150
+ require('../CLI/scripts/init-native-config').initNativeConfig();
151
+ });
152
+ program
153
+ .command('init-metro')
154
+ .description('Ensure Metro can resolve bundle.drop.config.js via extraNodeModules alias')
155
+ .action(() => {
156
+ require('../CLI/scripts/init-metro-config').initMetroConfig();
157
+ });
158
+ program
159
+ .command('whoami')
160
+ .description('Show currently logged in user')
161
+ .action(() => {
162
+ const authState = readStoredAuthData();
163
+ if (!authState.exists) {
164
+ console.log('ℹ️ Not logged in.');
165
+ return;
166
+ }
167
+ const user = authState.data?.user;
168
+ if (authState.isInvalid ||
169
+ !user ||
170
+ !user.firstName ||
171
+ !user.lastName ||
172
+ !user.email) {
173
+ logInvalidAuthFile();
174
+ return;
175
+ }
176
+ console.log(`👤 Logged in as: ${chalk_1.default.cyan(`${user.firstName} ${user.lastName}`)} <${user.email}>`);
177
+ });
178
+ return program;
179
+ };
180
+ exports.buildProgram = buildProgram;
181
+ if (require.main === module) {
182
+ (0, exports.buildProgram)().parse();
183
+ }
@@ -1,2 +1,18 @@
1
+ export declare function findProjectRoot(startDir: string): string;
2
+ export declare function findFileByName(root: string, fileName: string): string | null;
3
+ /**
4
+ * Starting from an opening brace at `openIndex`, count balanced braces
5
+ * and return the index *after* the matching closing brace.
6
+ * Returns -1 if unbalanced.
7
+ */
8
+ export declare function findMatchingBrace(content: string, openIndex: number): number;
9
+ export declare function ensureImport(content: string, importLine: string): string;
10
+ export declare function patchAndroidMainApplicationKotlin(filePath: string): void;
11
+ export declare function ensureJavaImport(content: string, importLine: string): string;
12
+ export declare function patchAndroidMainApplicationJava(filePath: string): void;
13
+ export declare function patchAndroidMainApplication(filePath: string): void;
14
+ export declare function patchIosAppDelegateSwift(filePath: string): void;
15
+ export declare function patchIosAppDelegateObjc(filePath: string): void;
16
+ export declare function patchIosAppDelegate(filePath: string): void;
1
17
  export declare function initNativeConfig(): Promise<void>;
2
18
  export default initNativeConfig;
@@ -3,6 +3,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.findProjectRoot = findProjectRoot;
7
+ exports.findFileByName = findFileByName;
8
+ exports.findMatchingBrace = findMatchingBrace;
9
+ exports.ensureImport = ensureImport;
10
+ exports.patchAndroidMainApplicationKotlin = patchAndroidMainApplicationKotlin;
11
+ exports.ensureJavaImport = ensureJavaImport;
12
+ exports.patchAndroidMainApplicationJava = patchAndroidMainApplicationJava;
13
+ exports.patchAndroidMainApplication = patchAndroidMainApplication;
14
+ exports.patchIosAppDelegateSwift = patchIosAppDelegateSwift;
15
+ exports.patchIosAppDelegateObjc = patchIosAppDelegateObjc;
16
+ exports.patchIosAppDelegate = patchIosAppDelegate;
6
17
  exports.initNativeConfig = initNativeConfig;
7
18
  const chalk_1 = __importDefault(require("chalk"));
8
19
  const fs_extra_1 = __importDefault(require("fs-extra"));