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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CLIENT_README.md +254 -84
  2. package/README.md +145 -14
  3. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +9 -22
  4. package/ios/BundleDropLocator.swift +0 -6
  5. package/lib/CLI/cli.js +48 -39
  6. package/lib/CLI/scripts/init-config.d.ts +1 -0
  7. package/lib/CLI/scripts/init-config.js +42 -2
  8. package/lib/CLI/scripts/init-native-config.js +428 -45
  9. package/lib/CLI/scripts/login-cli.js +6 -2
  10. package/lib/CLI/scripts/post-init.d.ts +1 -0
  11. package/lib/CLI/scripts/post-init.js +42 -0
  12. package/lib/CLI/scripts/upload-cli.d.ts +2 -0
  13. package/lib/CLI/scripts/upload-cli.js +11 -5
  14. package/lib/api/client.d.ts +1 -1
  15. package/lib/api/client.js +2 -2
  16. package/lib/api/clientApi.d.ts +3 -6
  17. package/lib/api/clientApi.js +7 -18
  18. package/lib/api/types.d.ts +33 -18
  19. package/lib/context.js +1 -1
  20. package/lib/errors.d.ts +2 -2
  21. package/lib/fs/bundlePointer.d.ts +14 -0
  22. package/lib/fs/bundlePointer.js +77 -0
  23. package/lib/fs/installId.d.ts +1 -0
  24. package/lib/fs/installId.js +29 -0
  25. package/lib/fs/userProperties.d.ts +6 -0
  26. package/lib/fs/userProperties.js +100 -0
  27. package/lib/index.d.ts +1 -1
  28. package/lib/index.js +8 -3
  29. package/lib/install/installFromZip.js +7 -18
  30. package/lib/loadConfig.d.ts +5 -0
  31. package/lib/manager/downloadAndInstall.d.ts +10 -0
  32. package/lib/manager/downloadAndInstall.js +50 -42
  33. package/lib/manager/initUpdateManager.js +46 -10
  34. package/lib/manager/reporting.js +5 -3
  35. package/lib/manager/rollbackState.d.ts +30 -0
  36. package/lib/manager/rollbackState.js +186 -0
  37. package/lib/manager/updateCheck.js +57 -18
  38. package/lib/scripts/download-bundle.js +19 -8
  39. package/lib/useBundleDrop.js +14 -2
  40. package/package.json +3 -3
  41. package/lib/api/utils.d.ts +0 -1
  42. package/lib/api/utils.js +0 -8
  43. package/lib/fs/iosPointer.d.ts +0 -1
  44. package/lib/fs/iosPointer.js +0 -20
@@ -38,58 +38,443 @@ function findFileByName(root, fileName) {
38
38
  }
39
39
  return null;
40
40
  }
41
- function patchAndroidMainApplication(filePath) {
41
+ // ---------------------------------------------------------------------------
42
+ // Android MainApplication.kt patcher
43
+ //
44
+ // Decision tree:
45
+ // 1. Already patched (resolveJSBundleFile or getDownloadedBundlePath) → skip.
46
+ // 2. Has `override fun getJSBundleFile()` → inject one-liner (older template).
47
+ // 3. Has ReactHost-style template (reactHost / getDefaultReactHost):
48
+ // a. reactNativeHost property exists → add getJSBundleFile() override inside it.
49
+ // b. reactNativeHost missing → insert full reactNativeHost block + rewire reactHost.
50
+ // 4. None matched → print manual instructions.
51
+ // ---------------------------------------------------------------------------
52
+ const BUNDLE_DROP_IMPORT = 'import com.bundledrop.BundleDropModule';
53
+ const ONE_LINER = `override fun getJSBundleFile(): String? =\n` +
54
+ ` BundleDropModule.resolveJSBundleFile(applicationContext, super.getJSBundleFile())`;
55
+ const REACT_HOST_IMPORTS = [
56
+ 'import com.facebook.react.ReactHost',
57
+ 'import com.facebook.react.ReactNativeHost',
58
+ 'import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative',
59
+ 'import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost',
60
+ 'import com.facebook.react.defaults.DefaultReactNativeHost',
61
+ ];
62
+ const REACT_NATIVE_HOST_BLOCK = `\
63
+ override val reactNativeHost: ReactNativeHost =
64
+ object : DefaultReactNativeHost(this) {
65
+
66
+ override fun getPackages() = PackageList(this).packages
67
+ override fun getJSMainModuleName(): String = "index"
68
+ override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
69
+
70
+ override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
71
+ override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
72
+
73
+ override fun getJSBundleFile(): String? =
74
+ BundleDropModule.resolveJSBundleFile(applicationContext, super.getJSBundleFile())
75
+ }`;
76
+ const REACT_HOST_OVERRIDE = `\
77
+ override val reactHost: ReactHost by lazy {
78
+ getDefaultReactHost(
79
+ context = applicationContext,
80
+ reactNativeHost = reactNativeHost
81
+ )
82
+ }`;
83
+ /**
84
+ * Starting from an opening brace at `openIndex`, count balanced braces
85
+ * and return the index *after* the matching closing brace.
86
+ * Returns -1 if unbalanced.
87
+ */
88
+ function findMatchingBrace(content, openIndex) {
89
+ let depth = 1;
90
+ let i = openIndex + 1;
91
+ while (i < content.length && depth > 0) {
92
+ if (content[i] === '{')
93
+ depth++;
94
+ else if (content[i] === '}')
95
+ depth--;
96
+ i++;
97
+ }
98
+ return depth === 0 ? i : -1;
99
+ }
100
+ function ensureImport(content, importLine) {
101
+ if (content.includes(importLine))
102
+ return content;
103
+ const lastImport = content.lastIndexOf('\nimport ');
104
+ if (lastImport !== -1) {
105
+ const eol = content.indexOf('\n', lastImport + 1);
106
+ return content.slice(0, eol + 1) + importLine + '\n' + content.slice(eol + 1);
107
+ }
108
+ return importLine + '\n' + content;
109
+ }
110
+ function patchAndroidMainApplicationKotlin(filePath) {
42
111
  let content = fs_extra_1.default.readFileSync(filePath, 'utf8');
43
- if (content.includes('BundleDropModule.getDownloadedBundlePath')) {
44
- console.log(chalk_1.default.gray(`ℹ️ Android already references BundleDrop in ${filePath}`));
112
+ // 1. Already patched?
113
+ if (content.includes('BundleDropModule.resolveJSBundleFile') ||
114
+ content.includes('BundleDropModule.getDownloadedBundlePath')) {
115
+ console.log(chalk_1.default.gray(` Already patched: ${filePath}`));
45
116
  return;
46
117
  }
47
- // Ensure import
48
- if (!content.includes('import com.bundledrop.BundleDropModule')) {
49
- content = content.replace(/(import\s+com\.facebook\.react\.ReactNativeHost[^\n]*\n)/, `$1import com.bundledrop.BundleDropModule\n`);
118
+ // 2. Older template — has getJSBundleFile() already
119
+ const methodRegex = /override fun getJSBundleFile\(\)\s*:\s*String\?/;
120
+ if (methodRegex.test(content)) {
121
+ console.log(chalk_1.default.cyan(' Detected existing getJSBundleFile() override (older RN template)'));
122
+ content = ensureImport(content, BUNDLE_DROP_IMPORT);
123
+ // Expression-body form: override fun getJSBundleFile(): String? = ...
124
+ const exprMethodRegex = /override fun getJSBundleFile\(\)\s*:\s*String\?\s*=[^\n]+/;
125
+ if (exprMethodRegex.test(content)) {
126
+ content = content.replace(exprMethodRegex, ONE_LINER);
127
+ }
128
+ else {
129
+ // Block-body form: use brace-counting to safely capture the full method
130
+ const methodStart = content.search(methodRegex);
131
+ const openBrace = content.indexOf('{', methodStart);
132
+ if (methodStart !== -1 && openBrace !== -1) {
133
+ const afterClose = findMatchingBrace(content, openBrace);
134
+ if (afterClose !== -1) {
135
+ content = content.slice(0, methodStart) + ONE_LINER + content.slice(afterClose);
136
+ }
137
+ }
138
+ }
139
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
140
+ console.log(chalk_1.default.green(` ✅ Patched getJSBundleFile() with BundleDrop one-liner: ${filePath}`));
141
+ return;
50
142
  }
51
- const methodRegex = /override fun getJSBundleFile\(\): String\?\s*\{\s*/;
52
- if (!methodRegex.test(content)) {
53
- console.log(chalk_1.default.yellow(`⚠️ Could not find getJSBundleFile() in ${filePath}. Please add manually:\n` +
54
- `val bundlePath = BundleDropModule.getDownloadedBundlePath(this)\nif (bundlePath != null) return bundlePath`));
143
+ // 3. RN 0.84+ ReactHost template
144
+ const hasReactHost = content.includes('override val reactHost') || content.includes('getDefaultReactHost(');
145
+ if (hasReactHost) {
146
+ const hasReactNativeHost = content.includes('override val reactNativeHost');
147
+ if (hasReactNativeHost) {
148
+ // 3a. reactNativeHost exists — inject getJSBundleFile() inside the object block
149
+ console.log(chalk_1.default.cyan(' Detected ReactHost template with existing reactNativeHost override'));
150
+ content = ensureImport(content, BUNDLE_DROP_IMPORT);
151
+ // Find the object block's opening brace using brace-counting
152
+ const rnhIdx = content.indexOf('override val reactNativeHost');
153
+ const objectIdx = rnhIdx !== -1 ? content.indexOf('{', content.indexOf('object', rnhIdx)) : -1;
154
+ if (objectIdx !== -1) {
155
+ const blockEnd = findMatchingBrace(content, objectIdx);
156
+ if (blockEnd !== -1) {
157
+ // Insert the one-liner just before the closing brace
158
+ const closingBrace = blockEnd - 1;
159
+ const indented = ONE_LINER.split('\n').join('\n ');
160
+ content =
161
+ content.slice(0, closingBrace) +
162
+ '\n\n ' + indented + '\n ' +
163
+ content.slice(closingBrace);
164
+ }
165
+ else {
166
+ console.log(chalk_1.default.yellow(` ⚠️ Found reactNativeHost but could not parse its object block.\n` +
167
+ ` Please add inside the DefaultReactNativeHost object:\n\n` +
168
+ ` ${ONE_LINER.split('\n').join('\n ')}`));
169
+ return;
170
+ }
171
+ }
172
+ else {
173
+ console.log(chalk_1.default.yellow(` ⚠️ Found reactNativeHost but could not locate the object block.\n` +
174
+ ` Please add inside the DefaultReactNativeHost object:\n\n` +
175
+ ` ${ONE_LINER.split('\n').join('\n ')}`));
176
+ return;
177
+ }
178
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
179
+ console.log(chalk_1.default.green(` ✅ Injected getJSBundleFile() into existing reactNativeHost: ${filePath}`));
180
+ return;
181
+ }
182
+ // 3b. No reactNativeHost — insert full block + rewire reactHost
183
+ console.log(chalk_1.default.cyan(' Detected RN 0.84+ ReactHost template without reactNativeHost — inserting full block'));
184
+ content = ensureImport(content, BUNDLE_DROP_IMPORT);
185
+ for (const imp of REACT_HOST_IMPORTS) {
186
+ content = ensureImport(content, imp);
187
+ }
188
+ // Replace entire reactHost property using brace-counting (safe with nested blocks)
189
+ const reactHostIdx = content.indexOf('override val reactHost');
190
+ if (reactHostIdx !== -1) {
191
+ const openBrace = content.indexOf('{', reactHostIdx);
192
+ if (openBrace !== -1) {
193
+ const afterClose = findMatchingBrace(content, openBrace);
194
+ if (afterClose !== -1) {
195
+ content =
196
+ content.slice(0, reactHostIdx) +
197
+ REACT_NATIVE_HOST_BLOCK +
198
+ '\n\n' +
199
+ REACT_HOST_OVERRIDE +
200
+ content.slice(afterClose);
201
+ }
202
+ }
203
+ }
204
+ // Fallback: if replacement didn't happen (no brace match), insert before onCreate
205
+ if (!content.includes('override val reactNativeHost')) {
206
+ const onCreateIdx = content.indexOf('override fun onCreate');
207
+ if (onCreateIdx !== -1) {
208
+ content =
209
+ content.slice(0, onCreateIdx) +
210
+ REACT_NATIVE_HOST_BLOCK +
211
+ '\n\n' +
212
+ REACT_HOST_OVERRIDE +
213
+ '\n\n ' +
214
+ content.slice(onCreateIdx);
215
+ }
216
+ else {
217
+ console.log(chalk_1.default.yellow(` ⚠️ Could not find a suitable insertion point in ${filePath}.\n` +
218
+ ` Please add the reactNativeHost + reactHost blocks manually (see CLIENT_README.md).`));
219
+ return;
220
+ }
221
+ }
222
+ // Ensure onCreate calls loadReactNative
223
+ if (!content.includes('loadReactNative(')) {
224
+ const onCreateBody = /override fun onCreate\(\)\s*\{/;
225
+ if (onCreateBody.test(content)) {
226
+ content = content.replace(onCreateBody, match => {
227
+ return match + '\n loadReactNative(this)';
228
+ });
229
+ }
230
+ }
231
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
232
+ console.log(chalk_1.default.green(` ✅ Inserted reactNativeHost block and rewired reactHost for BundleDrop: ${filePath}`));
55
233
  return;
56
234
  }
57
- content = content.replace(methodRegex, match => {
58
- return (match +
59
- ` val bundlePath = BundleDropModule.getDownloadedBundlePath(application)\n` +
60
- ` if (bundlePath != null) {\n` +
61
- ` return bundlePath\n` +
62
- ` }\n`);
63
- });
64
- fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
65
- console.log(chalk_1.default.green(`✅ Patched Android MainApplication: ${filePath}`));
235
+ // 4. No recognizable template
236
+ console.log(chalk_1.default.yellow(` ⚠️ Could not detect a supported MainApplication template in ${filePath}.\n` +
237
+ ` Please add the BundleDrop override manually. See CLIENT_README.md section "Native setup (Android)".`));
66
238
  }
67
- function patchIosAppDelegate(filePath) {
239
+ // ---------------------------------------------------------------------------
240
+ // Android MainApplication.java patcher (older RN versions)
241
+ //
242
+ // Decision tree:
243
+ // 1. Already patched (BundleDropModule reference) → skip.
244
+ // 2. Has getJSBundleFile() method → replace body with BundleDrop call.
245
+ // 3. Has ReactNativeHost anonymous class → inject getJSBundleFile() inside it.
246
+ // 4. None matched → print manual instructions.
247
+ // ---------------------------------------------------------------------------
248
+ const JAVA_BUNDLE_DROP_IMPORT = 'import com.bundledrop.BundleDropModule;';
249
+ const JAVA_GET_JS_BUNDLE_METHOD = `@Override\n` +
250
+ ` protected String getJSBundleFile() {\n` +
251
+ ` return BundleDropModule.resolveJSBundleFile(getApplicationContext(), super.getJSBundleFile());\n` +
252
+ ` }`;
253
+ function ensureJavaImport(content, importLine) {
254
+ if (content.includes(importLine))
255
+ return content;
256
+ const lastImport = content.lastIndexOf('\nimport ');
257
+ if (lastImport !== -1) {
258
+ const eol = content.indexOf('\n', lastImport + 1);
259
+ return content.slice(0, eol + 1) + importLine + '\n' + content.slice(eol + 1);
260
+ }
261
+ return importLine + '\n' + content;
262
+ }
263
+ function patchAndroidMainApplicationJava(filePath) {
68
264
  let content = fs_extra_1.default.readFileSync(filePath, 'utf8');
69
- if (!content.includes('import BundleDrop')) {
70
- content = content.replace(/^(import .*React.*\n)/m, `$1import BundleDrop\n`);
265
+ // 1. Already patched?
266
+ if (content.includes('BundleDropModule.resolveJSBundleFile') ||
267
+ content.includes('BundleDropModule.getDownloadedBundlePath')) {
268
+ console.log(chalk_1.default.gray(` Already patched: ${filePath}`));
269
+ return;
71
270
  }
72
- const bundleRegex = /override func bundleURL\(\) -> URL\?\s*\{[\s\S]*?#endif\s*\}/m;
73
- if (bundleRegex.test(content)) {
74
- content = content.replace(bundleRegex, () => {
75
- return `override func bundleURL() -> URL? {
271
+ // 2. Has getJSBundleFile() method — replace its body
272
+ const methodSignature = /protected\s+String\s+getJSBundleFile\s*\(\s*\)/;
273
+ if (methodSignature.test(content)) {
274
+ console.log(chalk_1.default.cyan(' Detected existing getJSBundleFile() override (Java)'));
275
+ content = ensureJavaImport(content, JAVA_BUNDLE_DROP_IMPORT);
276
+ const methodStart = content.search(methodSignature);
277
+ const openBrace = content.indexOf('{', methodStart);
278
+ if (methodStart !== -1 && openBrace !== -1) {
279
+ const afterClose = findMatchingBrace(content, openBrace);
280
+ if (afterClose !== -1) {
281
+ content = content.slice(0, methodStart) + JAVA_GET_JS_BUNDLE_METHOD + content.slice(afterClose);
282
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
283
+ console.log(chalk_1.default.green(` ✅ Patched getJSBundleFile() with BundleDrop call (Java): ${filePath}`));
284
+ return;
285
+ }
286
+ }
287
+ console.log(chalk_1.default.yellow(` ⚠️ Found getJSBundleFile() but could not safely parse its body.\n` +
288
+ ` Please replace the method body manually. See CLIENT_README.md section "Native setup (Android)".`));
289
+ return;
290
+ }
291
+ // 3. Has ReactNativeHost anonymous class — inject getJSBundleFile() inside it
292
+ const rnhPattern = /new\s+(DefaultReactNativeHost|ReactNativeHost)\s*\(/;
293
+ const rnhMatch = content.match(rnhPattern);
294
+ if (rnhMatch) {
295
+ console.log(chalk_1.default.cyan(` Detected ${rnhMatch[1]} anonymous class — injecting getJSBundleFile()`));
296
+ content = ensureJavaImport(content, JAVA_BUNDLE_DROP_IMPORT);
297
+ const rnhIdx = content.search(rnhPattern);
298
+ // Find the opening brace of the anonymous class (after the constructor args)
299
+ const ctorOpen = content.indexOf('(', rnhIdx);
300
+ if (ctorOpen !== -1) {
301
+ // Skip past constructor parens to find the class body brace
302
+ let parenDepth = 1;
303
+ let ci = ctorOpen + 1;
304
+ while (ci < content.length && parenDepth > 0) {
305
+ if (content[ci] === '(')
306
+ parenDepth++;
307
+ else if (content[ci] === ')')
308
+ parenDepth--;
309
+ ci++;
310
+ }
311
+ // ci is now right after the closing ')' of the constructor — find the '{'
312
+ const classBodyOpen = content.indexOf('{', ci);
313
+ if (classBodyOpen !== -1) {
314
+ const classBodyEnd = findMatchingBrace(content, classBodyOpen);
315
+ if (classBodyEnd !== -1) {
316
+ const closingBrace = classBodyEnd - 1;
317
+ content =
318
+ content.slice(0, closingBrace) +
319
+ '\n\n ' + JAVA_GET_JS_BUNDLE_METHOD.split('\n').join('\n ').trimStart() + '\n ' +
320
+ content.slice(closingBrace);
321
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
322
+ console.log(chalk_1.default.green(` ✅ Injected getJSBundleFile() into ReactNativeHost (Java): ${filePath}`));
323
+ return;
324
+ }
325
+ }
326
+ }
327
+ console.log(chalk_1.default.yellow(` ⚠️ Found ReactNativeHost but could not safely parse its anonymous class.\n` +
328
+ ` Please add getJSBundleFile() override manually. See CLIENT_README.md section "Native setup (Android)".`));
329
+ return;
330
+ }
331
+ // 4. No recognizable template
332
+ console.log(chalk_1.default.yellow(` ⚠️ Could not detect a supported MainApplication template in ${filePath}.\n` +
333
+ ` Please add the BundleDrop override manually. See CLIENT_README.md section "Native setup (Android)".`));
334
+ }
335
+ function patchAndroidMainApplication(filePath) {
336
+ const ext = path_1.default.extname(filePath);
337
+ console.log(chalk_1.default.cyan(` ✅ Found MainApplication: ${filePath}`));
338
+ if (ext === '.kt') {
339
+ patchAndroidMainApplicationKotlin(filePath);
340
+ }
341
+ else if (ext === '.java') {
342
+ patchAndroidMainApplicationJava(filePath);
343
+ }
344
+ else {
345
+ console.log(chalk_1.default.yellow(` ⚠️ Unsupported MainApplication file type (${ext}). Please patch manually.\n` +
346
+ ` See CLIENT_README.md section "Native setup (Android)".`));
347
+ }
348
+ }
349
+ // ---------------------------------------------------------------------------
350
+ // iOS AppDelegate patcher
351
+ //
352
+ // Supports:
353
+ // - AppDelegate.swift (bundleURL() override)
354
+ // - AppDelegate.m / .mm (sourceURLForBridge: method)
355
+ //
356
+ // Search order under ios/:
357
+ // 1. AppDelegate.swift
358
+ // 2. AppDelegate.mm
359
+ // 3. AppDelegate.m
360
+ // ---------------------------------------------------------------------------
361
+ const SWIFT_BUNDLE_URL_BODY = `override func bundleURL() -> URL? {
76
362
  #if DEBUG
77
363
  return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
78
364
  #else
79
- // Release: OTA if present, else embedded bundle
80
365
  if let url = BundleDropLocator.bundleURL() {
81
366
  return url
82
367
  }
83
368
  return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
84
369
  #endif
85
370
  }`;
86
- });
371
+ const OBJC_SOURCE_URL_BODY = `- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
372
+ {
373
+ #if DEBUG
374
+ return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
375
+ #else
376
+ NSURL *otaURL = [BundleDropLocator bundleURL];
377
+ if (otaURL != nil) {
378
+ return otaURL;
379
+ }
380
+ return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
381
+ #endif
382
+ }`;
383
+ function patchIosAppDelegateSwift(filePath) {
384
+ let content = fs_extra_1.default.readFileSync(filePath, 'utf8');
385
+ if (content.includes('BundleDropLocator.bundleURL()') || content.includes('import BundleDrop')) {
386
+ console.log(chalk_1.default.gray(` Already patched: ${filePath}`));
387
+ return;
388
+ }
389
+ // Ensure import
390
+ const reactImport = content.match(/^import .*React.*$/m);
391
+ if (reactImport) {
392
+ content = content.replace(reactImport[0], reactImport[0] + '\nimport BundleDrop');
87
393
  }
88
394
  else {
89
- console.log(chalk_1.default.yellow(`⚠️ Could not find bundleURL() override in ${filePath}. Please add the OTA preference manually (Debug -> Metro, Release -> locator fallback).`));
395
+ const firstImport = content.match(/^import .+$/m);
396
+ if (firstImport) {
397
+ content = content.replace(firstImport[0], firstImport[0] + '\nimport BundleDrop');
398
+ }
399
+ else {
400
+ content = 'import BundleDrop\n' + content;
401
+ }
402
+ }
403
+ // Patch bundleURL()
404
+ const bundleRegex = /override func bundleURL\(\)\s*->\s*URL\?\s*\{[\s\S]*?#endif\s*\}/m;
405
+ if (bundleRegex.test(content)) {
406
+ content = content.replace(bundleRegex, SWIFT_BUNDLE_URL_BODY);
407
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
408
+ console.log(chalk_1.default.green(` ✅ Patched iOS AppDelegate (Swift): ${filePath}`));
409
+ return;
410
+ }
411
+ // bundleURL without #if/#endif (simple body)
412
+ const simpleBundleRegex = /override func bundleURL\(\)\s*->\s*URL\?\s*\{[^}]*\}/m;
413
+ if (simpleBundleRegex.test(content)) {
414
+ content = content.replace(simpleBundleRegex, SWIFT_BUNDLE_URL_BODY);
415
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
416
+ console.log(chalk_1.default.green(` ✅ Patched iOS AppDelegate (Swift): ${filePath}`));
417
+ return;
418
+ }
419
+ // Write the import we added but warn about the method
420
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
421
+ console.log(chalk_1.default.yellow(` ⚠️ Could not find bundleURL() override in ${filePath}.\n` +
422
+ ` Please add manually: Debug → Metro, Release → BundleDropLocator.bundleURL() fallback to main.jsbundle.\n` +
423
+ ` See CLIENT_README.md section "Native setup (iOS)".`));
424
+ }
425
+ function patchIosAppDelegateObjc(filePath) {
426
+ let content = fs_extra_1.default.readFileSync(filePath, 'utf8');
427
+ const ext = path_1.default.extname(filePath);
428
+ if (content.includes('[BundleDropLocator bundleURL]') ||
429
+ content.includes('#import <BundleDrop/')) {
430
+ console.log(chalk_1.default.gray(` Already patched: ${filePath}`));
431
+ return;
432
+ }
433
+ // Ensure import
434
+ const importLine = '#import <BundleDrop/BundleDrop-Swift.h>';
435
+ if (!content.includes(importLine)) {
436
+ const reactImport = content.match(/^#import\s+<React\/[^>]+>.*$/m);
437
+ if (reactImport) {
438
+ content = content.replace(reactImport[0], reactImport[0] + '\n' + importLine);
439
+ }
440
+ else {
441
+ const firstImport = content.match(/^#import\s+.+$/m);
442
+ if (firstImport) {
443
+ content = content.replace(firstImport[0], firstImport[0] + '\n' + importLine);
444
+ }
445
+ else {
446
+ content = importLine + '\n' + content;
447
+ }
448
+ }
90
449
  }
450
+ // Patch sourceURLForBridge:
451
+ const sourceUrlRegex = /-\s*\(NSURL\s*\*\)\s*sourceURLForBridge\s*:\s*\(RCTBridge\s*\*\)\s*bridge\s*\{[\s\S]*?\n\}/m;
452
+ if (sourceUrlRegex.test(content)) {
453
+ content = content.replace(sourceUrlRegex, OBJC_SOURCE_URL_BODY);
454
+ fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
455
+ const label = ext === '.mm' ? 'ObjC++' : 'ObjC';
456
+ console.log(chalk_1.default.green(` ✅ Patched iOS AppDelegate (${label}): ${filePath}`));
457
+ return;
458
+ }
459
+ // Write the import we added but warn about the method
91
460
  fs_extra_1.default.writeFileSync(filePath, content, 'utf8');
92
- console.log(chalk_1.default.green(`✅ Patched iOS AppDelegate: ${filePath}`));
461
+ console.log(chalk_1.default.yellow(` ⚠️ Could not find sourceURLForBridge: in ${filePath}.\n` +
462
+ ` Please locate the method that returns the JS bundle URL and apply the Release OTA fallback.\n` +
463
+ ` See CLIENT_README.md section "Native setup (iOS)".`));
464
+ }
465
+ function patchIosAppDelegate(filePath) {
466
+ const ext = path_1.default.extname(filePath);
467
+ console.log(chalk_1.default.cyan(` ✅ Found AppDelegate: ${filePath}`));
468
+ if (ext === '.swift') {
469
+ patchIosAppDelegateSwift(filePath);
470
+ }
471
+ else if (ext === '.m' || ext === '.mm') {
472
+ patchIosAppDelegateObjc(filePath);
473
+ }
474
+ else {
475
+ console.log(chalk_1.default.yellow(` ⚠️ Unsupported AppDelegate file type (${ext}). Please patch manually.\n` +
476
+ ` See CLIENT_README.md section "Native setup (iOS)".`));
477
+ }
93
478
  }
94
479
  async function initNativeConfig() {
95
480
  const projectRoot = findProjectRoot(process.cwd());
@@ -112,26 +497,24 @@ async function initNativeConfig() {
112
497
  const androidPath = path_1.default.join(projectRoot, 'android', 'app', 'src', 'main', 'java');
113
498
  const mainAppKotlin = findFileByName(androidPath, 'MainApplication.kt');
114
499
  const mainAppJava = findFileByName(androidPath, 'MainApplication.java');
115
- if (mainAppKotlin) {
116
- patchAndroidMainApplication(mainAppKotlin);
117
- }
118
- else if (mainAppJava) {
119
- console.log(chalk_1.default.yellow(`⚠️ Found Java MainApplication at ${mainAppJava}. Automated patching for Java is not implemented; please apply the snippet manually.`));
500
+ const androidTarget = mainAppKotlin ?? mainAppJava;
501
+ if (androidTarget) {
502
+ patchAndroidMainApplication(androidTarget);
120
503
  }
121
504
  else {
122
- console.log(chalk_1.default.yellow('⚠️ Could not locate MainApplication in android/app/src/main/java.'));
123
- }
124
- // iOS
125
- const appDelegateSwift = path_1.default.join(projectRoot, 'ios', 'AppDelegate.swift');
126
- const appDelegateObjc = path_1.default.join(projectRoot, 'ios', 'AppDelegate.m');
127
- if (fs_extra_1.default.existsSync(appDelegateSwift)) {
128
- patchIosAppDelegate(appDelegateSwift);
505
+ console.log(chalk_1.default.yellow(' ⚠️ Could not locate MainApplication in android/app/src/main/java.'));
129
506
  }
130
- else if (fs_extra_1.default.existsSync(appDelegateObjc)) {
131
- console.log(chalk_1.default.yellow(`⚠️ Found Objective-C AppDelegate at ${appDelegateObjc}. Automated patching for ObjC is not implemented; please apply the snippet manually.`));
507
+ // iOS — search recursively under ios/ (handles ios/AppDelegate.swift, ios/<ProjectName>/AppDelegate.swift, etc.)
508
+ const iosRoot = path_1.default.join(projectRoot, 'ios');
509
+ const appDelegateSwift = findFileByName(iosRoot, 'AppDelegate.swift');
510
+ const appDelegateObjcpp = findFileByName(iosRoot, 'AppDelegate.mm');
511
+ const appDelegateObjc = findFileByName(iosRoot, 'AppDelegate.m');
512
+ const iosTarget = appDelegateSwift ?? appDelegateObjcpp ?? appDelegateObjc;
513
+ if (iosTarget) {
514
+ patchIosAppDelegate(iosTarget);
132
515
  }
133
516
  else {
134
- console.log(chalk_1.default.yellow('⚠️ Could not locate AppDelegate in ios/.'));
517
+ console.log(chalk_1.default.yellow(' ⚠️ Could not locate AppDelegate under ios/.'));
135
518
  }
136
519
  }
137
520
  exports.default = initNativeConfig;
@@ -11,6 +11,7 @@ const os_1 = __importDefault(require("os"));
11
11
  const path_1 = __importDefault(require("path"));
12
12
  const prompts_1 = __importDefault(require("prompts"));
13
13
  const init_config_1 = require("./init-config");
14
+ const post_init_1 = require("./post-init");
14
15
  const login = async () => {
15
16
  const { email, password } = await (0, prompts_1.default)([
16
17
  {
@@ -33,7 +34,8 @@ const login = async () => {
33
34
  email,
34
35
  password,
35
36
  });
36
- const { token, email: userEmail, firstName, lastName, projects = [], organizations = [], memberships = [], downloadApiKey, } = res.data;
37
+ const { token, email: userEmail, firstName, lastName, projects = [], organizations = [], memberships = [], } = res.data;
38
+ const downloadApiKey = res.data?.downloadApiKey;
37
39
  const tokenPath = path_1.default.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
38
40
  await fs_extra_1.default.ensureDir(path_1.default.dirname(tokenPath));
39
41
  await fs_extra_1.default.writeJson(tokenPath, {
@@ -43,11 +45,13 @@ const login = async () => {
43
45
  organizations,
44
46
  memberships,
45
47
  downloadApiKey,
48
+ serverUrl: baseUrl,
46
49
  });
47
50
  console.log(chalk_1.default.green('✅ Logged in successfully as:'), chalk_1.default.cyan(`${firstName} ${lastName}`));
48
51
  // Attempt to scaffold bundle.drop.config.js if missing
49
52
  const serverUrl = new URL(loginUrl).origin;
50
- await (0, init_config_1.initConfig)({ serverUrl, projects, organizations, downloadApiKey });
53
+ await (0, init_config_1.initConfig)({ serverUrl, projects, organizations, downloadApiKey, authToken: token });
54
+ await (0, post_init_1.runPostInitPrompts)();
51
55
  }
52
56
  catch (err) {
53
57
  console.error(chalk_1.default.red('❌ Login failed:'), err.response?.data?.error || err.message);
@@ -0,0 +1 @@
1
+ export declare function runPostInitPrompts(): Promise<void>;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.runPostInitPrompts = runPostInitPrompts;
7
+ const prompts_1 = __importDefault(require("prompts"));
8
+ async function runPostInitPrompts() {
9
+ // Offer to set up Metro alias for bundle.drop.config.js resolution
10
+ const metroAnswer = await (0, prompts_1.default)({
11
+ type: 'confirm',
12
+ name: 'runMetro',
13
+ message: 'Also add the Metro alias for bundle.drop.config.js (recommended)?',
14
+ initial: true,
15
+ });
16
+ if (metroAnswer.runMetro) {
17
+ try {
18
+ //eslint-disable-next-line
19
+ await require('./init-metro-config').initMetroConfig();
20
+ }
21
+ catch (err) {
22
+ console.log(`⚠️ Failed to initialize Metro config; please refer to manual setup instructions. (${err?.message || err})`);
23
+ }
24
+ }
25
+ // Offer to patch native entrypoints (after Metro prompt finishes)
26
+ const nativeAnswer = await (0, prompts_1.default)({
27
+ type: 'confirm',
28
+ name: 'runNative',
29
+ message: 'Patch native entrypoints (MainApplication/AppDelegate) to prefer OTA? (Standard RN setups only)',
30
+ initial: false,
31
+ });
32
+ if (nativeAnswer.runNative) {
33
+ try {
34
+ //eslint-disable-next-line
35
+ await require('./init-native-config').initNativeConfig();
36
+ console.log('⚠️ Please double-check the native changes in MainApplication/AppDelegate.');
37
+ }
38
+ catch (err) {
39
+ console.log(`⚠️ Failed to initialize native config; please refer to manual setup instructions. (${err?.message || err})`);
40
+ }
41
+ }
42
+ }
@@ -5,4 +5,6 @@ export default function upload(platform: string, options: {
5
5
  buildGradlePath?: string;
6
6
  runtimeVersion?: string;
7
7
  releaseNotes?: string;
8
+ token?: string;
9
+ author?: string;
8
10
  }): Promise<void>;
@@ -66,12 +66,15 @@ async function upload(platform, options) {
66
66
  ui_1.log.error('❌ Missing "serverUrl", "org.slug" or "project.slug" in config');
67
67
  process.exit(1);
68
68
  }
69
- // Validate auth token
70
- if (!fs.existsSync(authPath)) {
71
- ui_1.log.error('❌ Not authenticated. Please run `bundle-drop login` first.');
72
- process.exit(1);
69
+ // Resolve auth token: --token flag takes priority over auth.json
70
+ let token = options.token;
71
+ if (!token) {
72
+ if (!fs.existsSync(authPath)) {
73
+ ui_1.log.error('❌ Not authenticated. Please run `bundle-drop login` or pass --token.');
74
+ process.exit(1);
75
+ }
76
+ token = JSON.parse(fs.readFileSync(authPath, 'utf-8')).token;
73
77
  }
74
- const { token } = JSON.parse(fs.readFileSync(authPath, 'utf-8'));
75
78
  // Validate channel
76
79
  const channel = options.channel;
77
80
  if (!channel) {
@@ -200,6 +203,9 @@ async function upload(platform, options) {
200
203
  if (releaseNotes) {
201
204
  form.append('releaseNotes', releaseNotes);
202
205
  }
206
+ if (options.author) {
207
+ form.append('author', options.author);
208
+ }
203
209
  form.append('file', fs.createReadStream(zipPath));
204
210
  ui_1.log.arrow('Uploading bundle to server...');
205
211
  try {
@@ -1 +1 @@
1
- export declare const apiClient: import("axios").AxiosInstance;
1
+ export declare const apiClient: any;
package/lib/api/client.js CHANGED
@@ -4,9 +4,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.apiClient = void 0;
7
- const axios_1 = __importDefault(require("axios"));
7
+ const axios_cjs_1 = __importDefault(require("axios/dist/browser/axios.cjs"));
8
8
  const context_1 = require("../context");
9
- exports.apiClient = axios_1.default.create({
9
+ exports.apiClient = axios_cjs_1.default.create({
10
10
  baseURL: context_1.config.serverUrl,
11
11
  });
12
12
  // Attach x-api-key automatically (if configured) and ensure Accept header defaults to JSON for API calls.