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

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/CLIENT_README.md +254 -84
  2. package/README.md +145 -14
  3. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +94 -21
  4. package/ios/BundleDropBridge.m +29 -1
  5. package/ios/BundleDropLocator.swift +0 -6
  6. package/ios/BundleDropModule.swift +132 -4
  7. package/lib/CLI/cli.js +48 -39
  8. package/lib/CLI/scripts/init-config.d.ts +1 -0
  9. package/lib/CLI/scripts/init-config.js +42 -2
  10. package/lib/CLI/scripts/init-native-config.js +428 -45
  11. package/lib/CLI/scripts/login-cli.js +6 -2
  12. package/lib/CLI/scripts/post-init.d.ts +1 -0
  13. package/lib/CLI/scripts/post-init.js +42 -0
  14. package/lib/CLI/scripts/upload-cli.d.ts +2 -0
  15. package/lib/CLI/scripts/upload-cli.js +11 -5
  16. package/lib/api/client.d.ts +1 -1
  17. package/lib/api/client.js +2 -2
  18. package/lib/api/clientApi.d.ts +3 -6
  19. package/lib/api/clientApi.js +7 -18
  20. package/lib/api/types.d.ts +33 -18
  21. package/lib/bundleInfo.js +5 -5
  22. package/lib/context.js +3 -3
  23. package/lib/errors.d.ts +2 -2
  24. package/lib/fs/bundlePointer.d.ts +14 -0
  25. package/lib/fs/bundlePointer.js +77 -0
  26. package/lib/fs/fsUtils.js +13 -13
  27. package/lib/fs/installId.d.ts +1 -0
  28. package/lib/fs/installId.js +29 -0
  29. package/lib/fs/userProperties.d.ts +6 -0
  30. package/lib/fs/userProperties.js +100 -0
  31. package/lib/index.d.ts +1 -1
  32. package/lib/index.js +8 -3
  33. package/lib/injectImageResolver.js +2 -2
  34. package/lib/install/installFromZip.js +9 -20
  35. package/lib/loadConfig.d.ts +5 -0
  36. package/lib/manager/downloadAndInstall.d.ts +10 -0
  37. package/lib/manager/downloadAndInstall.js +50 -42
  38. package/lib/manager/initUpdateManager.js +46 -10
  39. package/lib/manager/reporting.js +5 -3
  40. package/lib/manager/rollbackState.d.ts +30 -0
  41. package/lib/manager/rollbackState.js +186 -0
  42. package/lib/manager/updateCheck.js +57 -18
  43. package/lib/native/fs.d.ts +17 -0
  44. package/lib/native/fs.js +33 -0
  45. package/lib/scripts/download-bundle.js +19 -8
  46. package/lib/useBundleDrop.js +14 -2
  47. package/package.json +3 -4
  48. package/lib/api/utils.d.ts +0 -1
  49. package/lib/api/utils.js +0 -8
  50. package/lib/fs/iosPointer.d.ts +0 -1
  51. package/lib/fs/iosPointer.js +0 -20
@@ -62,6 +62,12 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
62
62
  null
63
63
  }
64
64
  }
65
+
66
+ @JvmStatic
67
+ fun resolveJSBundleFile(context: Context, fallback: String?): String? {
68
+ val path = getDownloadedBundlePath(context)
69
+ return if (!path.isNullOrEmpty()) path else fallback
70
+ }
65
71
  }
66
72
 
67
73
  override fun getName(): String = "BundleDrop"
@@ -76,7 +82,8 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
76
82
 
77
83
  @ReactMethod
78
84
  fun restartReactNative() {
79
- val activity = currentActivity ?: return
85
+ // ✅ Only change: don't access `currentActivity` directly; use reactApplicationContext.currentActivity
86
+ val activity = reactApplicationContext.currentActivity ?: return
80
87
  val context = reactApplicationContext
81
88
 
82
89
  val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
@@ -118,31 +125,97 @@ class BundleDropModule(reactContext: ReactApplicationContext) :
118
125
  }
119
126
  }
120
127
 
121
- // @ReactMethod
122
- // fun forceReloadJS() {
123
- // val manager = (reactApplicationContext.currentActivity?.application as? ReactApplication)
124
- // ?.reactNativeHost?.reactInstanceManager
125
- //
126
- // if (manager != null) {
127
- // Log.d("BundleDrop", "🔁 Forcing React context recreation from native...")
128
- //
129
- // reactApplicationContext
130
- // .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
131
- // .emit("bundleReloadStart", null)
132
- //
133
- // reactApplicationContext.runOnUiQueueThread {
134
- // manager.recreateReactContextInBackground()
135
- // }
136
- // } else {
137
- // Log.e("BundleDrop", "❌ ReactInstanceManager is null.")
138
- // }
139
- // }
128
+ // ---------------------------------------------------------------------------
129
+ // FS primitives (replaces react-native-fs dependency)
130
+ // ---------------------------------------------------------------------------
131
+
132
+ @ReactMethod
133
+ fun fsExists(path: String, promise: Promise) {
134
+ promise.resolve(File(path).exists())
135
+ }
136
+
137
+ @ReactMethod
138
+ fun fsReadFile(path: String, encoding: String, promise: Promise) {
139
+ try {
140
+ val file = File(path)
141
+ if (!file.exists()) {
142
+ promise.reject("ENOENT", "File not found: $path")
143
+ return
144
+ }
145
+ if (encoding == "base64") {
146
+ val bytes = file.readBytes()
147
+ promise.resolve(android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP))
148
+ } else {
149
+ promise.resolve(file.readText(Charsets.UTF_8))
150
+ }
151
+ } catch (e: Exception) {
152
+ promise.reject("ERR_READ", e.message, e)
153
+ }
154
+ }
155
+
156
+ @ReactMethod
157
+ fun fsWriteFile(path: String, content: String, encoding: String, promise: Promise) {
158
+ try {
159
+ val file = File(path)
160
+ file.parentFile?.mkdirs()
161
+ if (encoding == "base64") {
162
+ val bytes = android.util.Base64.decode(content, android.util.Base64.DEFAULT)
163
+ file.writeBytes(bytes)
164
+ } else {
165
+ file.writeText(content, Charsets.UTF_8)
166
+ }
167
+ promise.resolve(null)
168
+ } catch (e: Exception) {
169
+ promise.reject("ERR_WRITE", e.message, e)
170
+ }
171
+ }
172
+
173
+ @ReactMethod
174
+ fun fsMkdir(path: String, promise: Promise) {
175
+ try {
176
+ val dir = File(path)
177
+ if (!dir.exists()) dir.mkdirs()
178
+ promise.resolve(null)
179
+ } catch (e: Exception) {
180
+ promise.reject("ERR_MKDIR", e.message, e)
181
+ }
182
+ }
183
+
184
+ @ReactMethod
185
+ fun fsUnlink(path: String, promise: Promise) {
186
+ try {
187
+ val file = File(path)
188
+ if (file.exists()) file.delete()
189
+ promise.resolve(null)
190
+ } catch (e: Exception) {
191
+ promise.reject("ERR_UNLINK", e.message, e)
192
+ }
193
+ }
194
+
195
+ @ReactMethod
196
+ fun fsMoveFile(src: String, dest: String, promise: Promise) {
197
+ try {
198
+ val srcFile = File(src)
199
+ val destFile = File(dest)
200
+ destFile.parentFile?.mkdirs()
201
+ if (!srcFile.renameTo(destFile)) {
202
+ srcFile.copyTo(destFile, overwrite = true)
203
+ srcFile.delete()
204
+ }
205
+ promise.resolve(null)
206
+ } catch (e: Exception) {
207
+ promise.reject("ERR_MOVE", e.message, e)
208
+ }
209
+ }
140
210
 
141
211
  override fun getConstants(): MutableMap<String, Any> {
142
212
  val map = mutableMapOf<String, Any>()
143
213
  downloadedBundlePath?.let {
144
214
  map["downloadedBundlePath"] = it
145
215
  }
216
+ val context = reactApplicationContext
217
+ map["DocumentDirectoryPath"] = context.filesDir.absolutePath
218
+ map["LibraryDirectoryPath"] = context.filesDir.absolutePath
146
219
  return map
147
220
  }
148
- }
221
+ }
@@ -1,6 +1,5 @@
1
1
  #import <React/RCTBridgeModule.h>
2
2
 
3
- // JS name "BundleDrop" -> Swift class "BundleDropModule"
4
3
  @interface RCT_EXTERN_REMAP_MODULE(BundleDrop, BundleDropModule, NSObject)
5
4
 
6
5
  RCT_EXTERN_METHOD(getDownloadedBundlePath:(RCTPromiseResolveBlock)resolve
@@ -8,6 +7,35 @@ RCT_EXTERN_METHOD(getDownloadedBundlePath:(RCTPromiseResolveBlock)resolve
8
7
 
9
8
  RCT_EXTERN_METHOD(restartReactNative)
10
9
 
10
+ // FS primitives
11
+ RCT_EXTERN_METHOD(fsExists:(NSString *)path
12
+ resolve:(RCTPromiseResolveBlock)resolve
13
+ reject:(RCTPromiseRejectBlock)reject)
14
+
15
+ RCT_EXTERN_METHOD(fsReadFile:(NSString *)path
16
+ encoding:(NSString *)encoding
17
+ resolve:(RCTPromiseResolveBlock)resolve
18
+ reject:(RCTPromiseRejectBlock)reject)
19
+
20
+ RCT_EXTERN_METHOD(fsWriteFile:(NSString *)path
21
+ content:(NSString *)content
22
+ encoding:(NSString *)encoding
23
+ resolve:(RCTPromiseResolveBlock)resolve
24
+ reject:(RCTPromiseRejectBlock)reject)
25
+
26
+ RCT_EXTERN_METHOD(fsMkdir:(NSString *)path
27
+ resolve:(RCTPromiseResolveBlock)resolve
28
+ reject:(RCTPromiseRejectBlock)reject)
29
+
30
+ RCT_EXTERN_METHOD(fsUnlink:(NSString *)path
31
+ resolve:(RCTPromiseResolveBlock)resolve
32
+ reject:(RCTPromiseRejectBlock)reject)
33
+
34
+ RCT_EXTERN_METHOD(fsMoveFile:(NSString *)src
35
+ dest:(NSString *)dest
36
+ resolve:(RCTPromiseResolveBlock)resolve
37
+ reject:(RCTPromiseRejectBlock)reject)
38
+
11
39
  + (BOOL)requiresMainQueueSetup
12
40
  {
13
41
  return NO;
@@ -19,12 +19,6 @@ import Foundation
19
19
  }
20
20
  }
21
21
 
22
- // legacy fallback: Documents/main.jsbundle
23
- if let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first {
24
- let legacy = docs.appendingPathComponent("main.jsbundle")
25
- if fm.fileExists(atPath: legacy.path) { return legacy }
26
- }
27
-
28
22
  return nil
29
23
  }
30
24
 
@@ -1,10 +1,11 @@
1
1
  import Foundation
2
2
  import React
3
3
 
4
- @objc(BundleDropModule) // native class name
4
+ @objc(BundleDropModule)
5
5
  final class BundleDropModule: NSObject {
6
6
 
7
7
  private static var isReloading = false
8
+ private static let fm = FileManager.default
8
9
 
9
10
  // MARK: - OTA bundle path
10
11
 
@@ -22,7 +23,6 @@ final class BundleDropModule: NSObject {
22
23
  resolve(nil)
23
24
  }
24
25
 
25
- // 🚨 Restart RN safely (debounced)
26
26
  @objc
27
27
  func restartReactNative() {
28
28
  DispatchQueue.main.async {
@@ -45,14 +45,142 @@ final class BundleDropModule: NSObject {
45
45
  Self.isReloading = true
46
46
  print("🔄 Restarting RN from \(url.path) size=\(size)")
47
47
 
48
- // Trigger a standard RN reload; AppDelegate.bundleURL() decides OTA vs embedded
49
48
  RCTReloadCommandSetBundleURL(url)
50
49
  RCTTriggerReloadCommandListeners("bundle-drop-restart")
51
50
 
52
- // release lock after a short moment to prevent double-trigger
53
51
  DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
54
52
  Self.isReloading = false
55
53
  }
56
54
  }
57
55
  }
56
+
57
+ // MARK: - Constants
58
+
59
+ @objc
60
+ func constantsToExport() -> [String: Any] {
61
+ let fm = FileManager.default
62
+ let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first?.path ?? ""
63
+ let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first?.path ?? ""
64
+ return [
65
+ "DocumentDirectoryPath": docs,
66
+ "LibraryDirectoryPath": lib,
67
+ ]
68
+ }
69
+
70
+ // MARK: - FS primitives (replaces react-native-fs dependency)
71
+
72
+ @objc
73
+ func fsExists(
74
+ _ path: String,
75
+ resolve: @escaping RCTPromiseResolveBlock,
76
+ reject: @escaping RCTPromiseRejectBlock
77
+ ) {
78
+ resolve(Self.fm.fileExists(atPath: path))
79
+ }
80
+
81
+ @objc
82
+ func fsReadFile(
83
+ _ path: String,
84
+ encoding: String,
85
+ resolve: @escaping RCTPromiseResolveBlock,
86
+ reject: @escaping RCTPromiseRejectBlock
87
+ ) {
88
+ guard Self.fm.fileExists(atPath: path) else {
89
+ reject("ENOENT", "File not found: \(path)", nil)
90
+ return
91
+ }
92
+ do {
93
+ if encoding == "base64" {
94
+ let data = try Data(contentsOf: URL(fileURLWithPath: path))
95
+ resolve(data.base64EncodedString())
96
+ } else {
97
+ let text = try String(contentsOfFile: path, encoding: .utf8)
98
+ resolve(text)
99
+ }
100
+ } catch {
101
+ reject("ERR_READ", error.localizedDescription, error)
102
+ }
103
+ }
104
+
105
+ @objc
106
+ func fsWriteFile(
107
+ _ path: String,
108
+ content: String,
109
+ encoding: String,
110
+ resolve: @escaping RCTPromiseResolveBlock,
111
+ reject: @escaping RCTPromiseRejectBlock
112
+ ) {
113
+ do {
114
+ let dir = (path as NSString).deletingLastPathComponent
115
+ if !Self.fm.fileExists(atPath: dir) {
116
+ try Self.fm.createDirectory(atPath: dir, withIntermediateDirectories: true)
117
+ }
118
+ if encoding == "base64" {
119
+ guard let data = Data(base64Encoded: content) else {
120
+ reject("ERR_WRITE", "Invalid base64 data", nil)
121
+ return
122
+ }
123
+ try data.write(to: URL(fileURLWithPath: path))
124
+ } else {
125
+ try content.write(toFile: path, atomically: true, encoding: .utf8)
126
+ }
127
+ resolve(nil)
128
+ } catch {
129
+ reject("ERR_WRITE", error.localizedDescription, error)
130
+ }
131
+ }
132
+
133
+ @objc
134
+ func fsMkdir(
135
+ _ path: String,
136
+ resolve: @escaping RCTPromiseResolveBlock,
137
+ reject: @escaping RCTPromiseRejectBlock
138
+ ) {
139
+ do {
140
+ if !Self.fm.fileExists(atPath: path) {
141
+ try Self.fm.createDirectory(atPath: path, withIntermediateDirectories: true)
142
+ }
143
+ resolve(nil)
144
+ } catch {
145
+ reject("ERR_MKDIR", error.localizedDescription, error)
146
+ }
147
+ }
148
+
149
+ @objc
150
+ func fsUnlink(
151
+ _ path: String,
152
+ resolve: @escaping RCTPromiseResolveBlock,
153
+ reject: @escaping RCTPromiseRejectBlock
154
+ ) {
155
+ do {
156
+ if Self.fm.fileExists(atPath: path) {
157
+ try Self.fm.removeItem(atPath: path)
158
+ }
159
+ resolve(nil)
160
+ } catch {
161
+ reject("ERR_UNLINK", error.localizedDescription, error)
162
+ }
163
+ }
164
+
165
+ @objc
166
+ func fsMoveFile(
167
+ _ src: String,
168
+ dest: String,
169
+ resolve: @escaping RCTPromiseResolveBlock,
170
+ reject: @escaping RCTPromiseRejectBlock
171
+ ) {
172
+ do {
173
+ let destDir = (dest as NSString).deletingLastPathComponent
174
+ if !Self.fm.fileExists(atPath: destDir) {
175
+ try Self.fm.createDirectory(atPath: destDir, withIntermediateDirectories: true)
176
+ }
177
+ if Self.fm.fileExists(atPath: dest) {
178
+ try Self.fm.removeItem(atPath: dest)
179
+ }
180
+ try Self.fm.moveItem(atPath: src, toPath: dest)
181
+ resolve(nil)
182
+ } catch {
183
+ reject("ERR_MOVE", error.localizedDescription, error)
184
+ }
185
+ }
58
186
  }
package/lib/CLI/cli.js CHANGED
@@ -7,13 +7,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const commander_1 = require("commander");
9
9
  const figures_1 = __importDefault(require("figures"));
10
- const prompts_1 = __importDefault(require("prompts"));
11
10
  const upload_cli_1 = __importDefault(require("./scripts/upload-cli"));
11
+ const post_init_1 = require("./scripts/post-init");
12
12
  const package_json_1 = __importDefault(require("../../package.json"));
13
13
  const program = new commander_1.Command();
14
14
  program
15
15
  .name('bundle-drop')
16
- .version(package_json_1.default.version || '0.0.0', '-v, --version', 'Show CLI version');
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
  |_ _ \\ |_ _ \`.
@@ -27,7 +27,15 @@ program.addHelpText('before', `
27
27
  ${chalk_1.default.magentaBright('A blazing-fast OTA delivery system for React Native by GFean.\n')}
28
28
  ${chalk_1.default.bold.cyan('Available Commands:')}
29
29
  `);
30
- program.addHelpText('afterAll', `\n${chalk_1.default.gray('Need help? →')} ${chalk_1.default.underline.gray('https://github.com/GFean/react-native-bundle-drop')}\n`);
30
+ program.addHelpText('afterAll', `
31
+ ${chalk_1.default.bold.cyan('Common Usage:')}
32
+ ${chalk_1.default.gray('bundle-drop login')}
33
+ ${chalk_1.default.gray('bundle-drop init')}
34
+ ${chalk_1.default.gray('bundle-drop upload android --version 1.2.3 --channel General')}
35
+ ${chalk_1.default.gray('bundle-drop upload ios --plist-file ios/Info.plist --channel General')}
36
+ ${chalk_1.default.gray('bundle-drop upload android --buildgradle-path android/app/build.gradle --channel General --release-notes "Fixes"')}
37
+
38
+ ${chalk_1.default.gray('Need help? →')} ${chalk_1.default.underline.gray('https://github.com/GFean/react-native-bundle-drop')}\n`);
31
39
  // ------------------------
32
40
  // Commands
33
41
  // ------------------------
@@ -38,7 +46,19 @@ program
38
46
  .option('--version <version>', 'App version. iOS will fallback to --plist-file; Android can fallback to build.gradle when provided.')
39
47
  .option('--buildgradle-path <path>', 'Optional Android build.gradle path to read versionName')
40
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')
41
53
  .description(chalk_1.default.whiteBright('Bundle and upload an OTA zip to the server'))
54
+ .addHelpText('after', `
55
+ ${chalk_1.default.bold('Examples:')}
56
+ ${chalk_1.default.gray('bundle-drop upload android --version 1.2.3 --channel General')}
57
+ ${chalk_1.default.gray('bundle-drop upload ios --plist-file ios/Info.plist --channel General')}
58
+ ${chalk_1.default.gray('bundle-drop upload android --buildgradle-path android/app/build.gradle --channel QA --release-notes "Bug fixes"')}
59
+ ${chalk_1.default.gray('bundle-drop upload android --version 1.2.3 --channel General --runtimeVersion 3.0.0')}
60
+ ${chalk_1.default.gray('bundle-drop upload android --version 1.2.3 --channel General --token bdp_pat_xxx')}
61
+ `)
42
62
  .action(upload_cli_1.default);
43
63
  program
44
64
  .command('logout')
@@ -68,63 +88,52 @@ program
68
88
  });
69
89
  program
70
90
  .command('init')
91
+ .option('--token <token>', 'Personal Access Token (alternative to `bundle-drop login`)')
71
92
  .description('Generate bundle.drop.config.js from your logged-in account context')
72
- .action(async () => {
93
+ .action(async (options) => {
73
94
  //eslint-disable-next-line
74
95
  const fs = require('fs');
75
96
  //eslint-disable-next-line
76
97
  const path = require('path');
77
98
  //eslint-disable-next-line
78
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
104
+ await require('../CLI/scripts/init-config').initConfig({
105
+ serverUrl,
106
+ projects: [],
107
+ organizations: [],
108
+ downloadApiKey: '',
109
+ authToken: options.token,
110
+ });
111
+ await (0, post_init_1.runPostInitPrompts)();
112
+ return;
113
+ }
79
114
  const tokenPath = path.join(os.homedir(), '.bundle-drop', 'auth.json');
80
115
  if (!fs.existsSync(tokenPath)) {
81
- console.log('â„šī¸ Not logged in. Please run `bundle-drop login` first.');
116
+ console.log('â„šī¸ Not logged in. Please run `bundle-drop login` or use --token.');
82
117
  return;
83
118
  }
84
119
  const data = JSON.parse(fs.readFileSync(tokenPath, 'utf-8'));
85
120
  const projects = data.projects || [];
86
121
  const organizations = data.organizations || [];
87
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';
88
128
  //eslint-disable-next-line
89
129
  await require('../CLI/scripts/init-config').initConfig({
90
- serverUrl: process.env.BUNDLE_DROP_SERVER_URL?.replace(/\/$/, '') || 'https://api.bundledrop.app',
130
+ serverUrl,
91
131
  projects,
92
132
  organizations,
93
133
  downloadApiKey,
134
+ authToken: token,
94
135
  });
95
- // Offer to set up Metro alias for bundle.drop.config.js resolution
96
- const metroAnswer = await (0, prompts_1.default)({
97
- type: 'confirm',
98
- name: 'runMetro',
99
- message: 'Also add the Metro alias for bundle.drop.config.js (recommended)?',
100
- initial: true,
101
- });
102
- if (metroAnswer.runMetro) {
103
- try {
104
- //eslint-disable-next-line
105
- await require('../CLI/scripts/init-metro-config').initMetroConfig();
106
- }
107
- catch (err) {
108
- console.log(`âš ī¸ Failed to initialize Metro config; please refer to manual setup instructions. (${err?.message || err})`);
109
- }
110
- }
111
- // Offer to patch native entrypoints (after Metro prompt finishes)
112
- const nativeAnswer = await (0, prompts_1.default)({
113
- type: 'confirm',
114
- name: 'runNative',
115
- message: 'Patch native entrypoints (MainApplication/AppDelegate) to prefer OTA? (Standard RN setups only)',
116
- initial: false,
117
- });
118
- if (nativeAnswer.runNative) {
119
- try {
120
- //eslint-disable-next-line
121
- await require('../CLI/scripts/init-native-config').initNativeConfig();
122
- console.log('âš ī¸ Please double-check the native changes in MainApplication/AppDelegate.');
123
- }
124
- catch (err) {
125
- console.log(`âš ī¸ Failed to initialize native config; please refer to manual setup instructions. (${err?.message || err})`);
126
- }
127
- }
136
+ await (0, post_init_1.runPostInitPrompts)();
128
137
  });
129
138
  program
130
139
  .command('init-native')
@@ -13,5 +13,6 @@ export declare function initConfig(params: {
13
13
  projects: Project[];
14
14
  organizations: Org[];
15
15
  downloadApiKey?: string;
16
+ authToken?: string;
16
17
  }): Promise<void>;
17
18
  export default initConfig;
@@ -4,10 +4,32 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.initConfig = initConfig;
7
+ const axios_1 = __importDefault(require("axios"));
7
8
  const chalk_1 = __importDefault(require("chalk"));
8
9
  const fs_extra_1 = __importDefault(require("fs-extra"));
9
10
  const path_1 = __importDefault(require("path"));
10
11
  const prompts_1 = __importDefault(require("prompts"));
12
+ function normalizeServerUrl(url) {
13
+ return url.replace(/\/$/, '');
14
+ }
15
+ async function fetchProjectCredentials(params) {
16
+ const baseUrl = normalizeServerUrl(params.serverUrl);
17
+ const url = `${baseUrl}/projects/${encodeURIComponent(params.projectSlug)}/credentials`;
18
+ try {
19
+ const res = await axios_1.default.get(url, {
20
+ headers: {
21
+ Accept: 'application/json',
22
+ Authorization: `Bearer ${params.authToken}`,
23
+ },
24
+ timeout: 15000,
25
+ });
26
+ return res.data || null;
27
+ }
28
+ catch (err) {
29
+ console.log(chalk_1.default.yellow(`âš ī¸ Failed to fetch project credentials from ${url}. Please verify login and project access.`));
30
+ return null;
31
+ }
32
+ }
11
33
  function findProjectRoot(startDir) {
12
34
  let dir = path_1.default.resolve(startDir);
13
35
  const MAX_UP = 12;
@@ -83,8 +105,26 @@ async function initConfig(params) {
83
105
  if (org)
84
106
  orgSlug = org.slug;
85
107
  }
108
+ let resolvedServerUrl = normalizeServerUrl(params.serverUrl);
109
+ let apiKey = params.downloadApiKey || '';
110
+ if (projectSlug && params.authToken) {
111
+ const credentials = await fetchProjectCredentials({
112
+ serverUrl: resolvedServerUrl,
113
+ projectSlug,
114
+ authToken: params.authToken,
115
+ });
116
+ if (credentials?.downloadApiKey) {
117
+ apiKey = credentials.downloadApiKey;
118
+ }
119
+ else if (!apiKey) {
120
+ console.log(chalk_1.default.yellow('âš ī¸ No project API key returned from /projects/:projectSlug/credentials; config will be created without apiKey.'));
121
+ }
122
+ }
123
+ else if (projectSlug && !params.authToken && !apiKey) {
124
+ console.log(chalk_1.default.yellow('âš ī¸ Missing auth token; cannot fetch project API key.'));
125
+ }
86
126
  const content = `module.exports = {
87
- serverUrl: '${params.serverUrl}',
127
+ serverUrl: '${resolvedServerUrl}',
88
128
  runtimeVersion: {
89
129
  ios: '1.0.0',
90
130
  android: '1.0.0',
@@ -95,7 +135,7 @@ async function initConfig(params) {
95
135
  project: {
96
136
  name: '${projectName.replace(/'/g, "\\'")}',
97
137
  slug: '${projectSlug}',
98
- apiKey: '${params.downloadApiKey || ''}',
138
+ apiKey: '${apiKey.replace(/'/g, "\\'")}',
99
139
  },
100
140
  debugLocal: false,
101
141
  };