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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +194 -5
  3. package/android/build.gradle +66 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +206 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  7. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  8. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  9. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  10. package/ios/BundleDropBridge.m +45 -0
  11. package/ios/BundleDropLocator.swift +66 -4
  12. package/ios/BundleDropModule.swift +181 -3
  13. package/ios/BundleDropOtaResolver.swift +137 -29
  14. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  15. package/ios/BundleDropStartupRecovery.swift +1108 -0
  16. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  17. package/lib/CLI/cli.d.ts +1 -0
  18. package/lib/CLI/cli.js +57 -6
  19. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  20. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  21. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  22. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  23. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  24. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  25. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  26. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  27. package/lib/CLI/scripts/aipowered/init-project-config.js +221 -45
  28. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  29. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  30. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  31. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  32. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  33. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  34. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  35. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  36. package/lib/CLI/scripts/doctor.js +162 -22
  37. package/lib/CLI/scripts/expo/configure-expo.js +52 -60
  38. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  39. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  40. package/lib/CLI/scripts/init-config.d.ts +7 -7
  41. package/lib/CLI/scripts/init-config.js +198 -14
  42. package/lib/CLI/scripts/login-cli.js +31 -7
  43. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  44. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  45. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  46. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  47. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  48. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  49. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  50. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  51. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  52. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  53. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  54. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  55. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  56. package/lib/CLI/scripts/upload-cli.js +74 -11
  57. package/lib/CLI/serverUrl.d.ts +3 -0
  58. package/lib/CLI/serverUrl.js +31 -0
  59. package/lib/api/clientApi.d.ts +3 -1
  60. package/lib/api/clientApi.js +14 -0
  61. package/lib/api/types.d.ts +39 -0
  62. package/lib/bundleInfo.d.ts +2 -0
  63. package/lib/bundleInfo.js +16 -1
  64. package/lib/context.d.ts +1 -1
  65. package/lib/context.js +12 -2
  66. package/lib/fs/bundlePointer.d.ts +1 -17
  67. package/lib/fs/bundlePointer.js +5 -93
  68. package/lib/index.d.ts +2 -0
  69. package/lib/index.js +3 -1
  70. package/lib/install/bundleInstallShared.js +4 -4
  71. package/lib/install/installFromZip.d.ts +3 -0
  72. package/lib/install/installFromZip.js +10 -1
  73. package/lib/loadConfig.d.ts +17 -1
  74. package/lib/loadConfig.js +16 -0
  75. package/lib/manager/downloadAndInstall.d.ts +3 -2
  76. package/lib/manager/downloadAndInstall.js +134 -66
  77. package/lib/manager/reporting.d.ts +8 -1
  78. package/lib/manager/reporting.js +17 -22
  79. package/lib/manager/rollbackState.d.ts +18 -52
  80. package/lib/manager/rollbackState.js +115 -216
  81. package/lib/manager/updateCheck.d.ts +1 -0
  82. package/lib/manager/updateCheck.js +224 -78
  83. package/lib/manager/updateState.d.ts +2 -1
  84. package/lib/manager/updateState.js +59 -6
  85. package/lib/metro.d.ts +8 -1
  86. package/lib/metro.js +69 -19
  87. package/lib/native/bundleDropNative.d.ts +62 -0
  88. package/lib/native/bundleDropNative.js +268 -2
  89. package/lib/native/fs.d.ts +6 -0
  90. package/lib/native/fs.js +24 -0
  91. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  92. package/lib/patch-engine/installFromPatchSet.js +16 -5
  93. package/lib/patch-engine/patchTransport.d.ts +2 -0
  94. package/lib/patch-engine/patchTransport.js +9 -0
  95. package/lib/runtime/initState.d.ts +5 -0
  96. package/lib/runtime/initState.js +4 -0
  97. package/lib/runtime/service.js +82 -67
  98. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  99. package/lib/runtime-delivery/artifactCapability.js +32 -0
  100. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  101. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  102. package/lib/runtime-delivery/bootstrapConfig.d.ts +68 -0
  103. package/lib/runtime-delivery/bootstrapConfig.js +278 -0
  104. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  105. package/lib/runtime-delivery/diagnostics.js +58 -0
  106. package/lib/runtime-delivery/encoding.d.ts +5 -0
  107. package/lib/runtime-delivery/encoding.js +132 -0
  108. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  109. package/lib/runtime-delivery/heartbeat.js +88 -0
  110. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  111. package/lib/runtime-delivery/localResolver.js +81 -0
  112. package/lib/runtime-delivery/manifestState.d.ts +11 -0
  113. package/lib/runtime-delivery/manifestState.js +123 -0
  114. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  115. package/lib/runtime-delivery/manifestVerifier.js +335 -0
  116. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  117. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  118. package/lib/runtime-delivery/types.d.ts +87 -0
  119. package/lib/runtime-delivery/types.js +6 -0
  120. package/lib/scripts/bundle.d.ts +9 -2
  121. package/lib/scripts/bundle.js +68 -18
  122. package/lib/scripts/download-bundle.d.ts +1 -0
  123. package/lib/scripts/download-bundle.js +2 -2
  124. package/lib/scripts/resolveModule.d.ts +2 -0
  125. package/lib/scripts/resolveModule.js +5 -0
  126. package/package.json +5 -2
  127. package/plugin/xcodeBuildPhase.js +2 -1
@@ -0,0 +1,301 @@
1
+ import Foundation
2
+ import ObjectiveC.runtime
3
+
4
+ /// Process-level integration between the startup ledger and React Native's
5
+ /// lifecycle. The controller itself remains Foundation-only and directly testable.
6
+ enum BundleDropStartupRecoveryAdapter {
7
+ static let protocolVersion = BundleDropStartupRecoveryController.protocolVersion
8
+
9
+ private static let lock = NSRecursiveLock()
10
+ private static let processToken = UUID().uuidString.lowercased()
11
+ private static var recoveryController: BundleDropStartupRecoveryController?
12
+ private static var activeAttemptHash: String?
13
+ private static var activeAttemptId: String?
14
+ private static var selectedHash: String?
15
+ private static var observersInstalled = false
16
+ private static let contentBindings = BundleDropStartupContentBindings()
17
+
18
+ static func selectStartupBundle(bundleDropRoot: URL) -> URL? {
19
+ installReactLifecycleObservers()
20
+ let selection = controller(bundleDropRoot: bundleDropRoot).selectStartupBundle()
21
+ captureStartupSelection(selection)
22
+ return selection.bundleURL
23
+ }
24
+
25
+ static func downloadedBundleURL() -> URL? {
26
+ guard BundleDropLocatorCore.hasRuntimeIdentityForOta(),
27
+ BundleDropLocatorCore.isOtaEnabled(),
28
+ let root = defaultRoot() else {
29
+ return nil
30
+ }
31
+ return controller(bundleDropRoot: root).passiveCurrentBundle()
32
+ }
33
+
34
+ static func activateCandidate(
35
+ hash: String,
36
+ maxCrashCount: Int,
37
+ healthCheckMode: String,
38
+ healthyAfterSec: Double
39
+ ) throws -> BundleDropStartupActivationResult {
40
+ try requireDefaultController().activateCandidate(
41
+ hash: hash,
42
+ maxCrashCount: maxCrashCount,
43
+ healthCheckMode: healthCheckMode,
44
+ healthyAfterSec: healthyAfterSec
45
+ )
46
+ }
47
+
48
+ static func beginReload() -> URL? {
49
+ guard let controller = defaultController() else { return nil }
50
+ installReactLifecycleObservers()
51
+ let selection = controller.selectStartupBundle(beginReload: true)
52
+ captureStartupSelection(selection)
53
+ return selection.bundleURL
54
+ }
55
+
56
+ static func markHealthy(hash: String, attemptId: String) -> Bool {
57
+ guard let controller = defaultController() else { return false }
58
+ let marked = controller.markHealthy(hash: hash, attemptId: attemptId)
59
+ if marked { clearCapturedAttempt() }
60
+ return marked
61
+ }
62
+
63
+ static func snapshot() throws -> [String: Any] {
64
+ try requireDefaultController().snapshot()
65
+ }
66
+
67
+ static func setRevokedHashes(_ hashes: [String]) throws -> Bool {
68
+ try requireDefaultController().setRevokedHashes(hashes)
69
+ return true
70
+ }
71
+
72
+ static func acknowledgeRecovery(eventId: String) throws -> Bool {
73
+ try requireDefaultController().acknowledgeRecovery(eventId: eventId)
74
+ }
75
+
76
+ static func rollback(forceEmbedded: Bool) throws -> BundleDropStartupRollbackResult {
77
+ let result = try requireDefaultController().rollback(forceEmbedded: forceEmbedded)
78
+ clearCapturedAttempt()
79
+ return result
80
+ }
81
+
82
+ static func capturedAttempt() -> (hash: String?, attemptId: String?) {
83
+ lock.lock()
84
+ defer { lock.unlock() }
85
+ return (activeAttemptHash, activeAttemptId)
86
+ }
87
+
88
+ static func clearCapturedAttempt() {
89
+ captureAttempt(hash: nil, attemptId: nil)
90
+ }
91
+
92
+ static func capturedSelectedHash() -> String? {
93
+ lock.lock()
94
+ defer { lock.unlock() }
95
+ return selectedHash
96
+ }
97
+
98
+ static func clearCapturedSelection() {
99
+ lock.lock()
100
+ activeAttemptHash = nil
101
+ activeAttemptId = nil
102
+ selectedHash = nil
103
+ contentBindings.capture(hash: nil, attemptId: nil, bundleURL: nil)
104
+ lock.unlock()
105
+ }
106
+
107
+ static func captureStartupSelection(_ selection: BundleDropStartupSelection) {
108
+ lock.lock()
109
+ activeAttemptHash = selection.attemptHash
110
+ activeAttemptId = selection.attemptId
111
+ let bundleHash = selection.bundleURL?
112
+ .deletingLastPathComponent()
113
+ .lastPathComponent
114
+ selectedHash = bundleHash?.range(
115
+ of: "^[a-f0-9]{64}$",
116
+ options: .regularExpression
117
+ ) == nil ? nil : bundleHash
118
+ contentBindings.capture(
119
+ hash: selection.attemptHash,
120
+ attemptId: selection.attemptId,
121
+ bundleURL: selection.bundleURL
122
+ )
123
+ lock.unlock()
124
+ }
125
+
126
+ private static func defaultRoot() -> URL? {
127
+ FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first?
128
+ .appendingPathComponent("bundle-drop", isDirectory: true)
129
+ }
130
+
131
+ private static func defaultController() -> BundleDropStartupRecoveryController? {
132
+ defaultRoot().map(controller)
133
+ }
134
+
135
+ private static func requireDefaultController() throws -> BundleDropStartupRecoveryController {
136
+ guard let controller = defaultController() else {
137
+ throw BundleDropStartupRecoveryError.storageUnavailable
138
+ }
139
+ return controller
140
+ }
141
+
142
+ private static func controller(bundleDropRoot: URL) -> BundleDropStartupRecoveryController {
143
+ lock.lock()
144
+ defer { lock.unlock() }
145
+ if let recoveryController { return recoveryController }
146
+ let created = BundleDropStartupRecoveryController(
147
+ bundleDropRoot: bundleDropRoot,
148
+ expectedRuntimeVersion: BundleDropLocatorCore.getRuntimeVersion(),
149
+ expectedBinaryIdentity: BundleDropLocatorCore.getBinaryVersionKey(),
150
+ processToken: processToken
151
+ )
152
+ recoveryController = created
153
+ return created
154
+ }
155
+
156
+ private static func captureAttempt(hash: String?, attemptId: String?) {
157
+ lock.lock()
158
+ activeAttemptHash = hash
159
+ activeAttemptId = attemptId
160
+ lock.unlock()
161
+ }
162
+
163
+ private static func installReactLifecycleObservers() {
164
+ lock.lock()
165
+ guard !observersInstalled else {
166
+ lock.unlock()
167
+ return
168
+ }
169
+ observersInstalled = true
170
+ lock.unlock()
171
+
172
+ NotificationCenter.default.addObserver(
173
+ forName: Notification.Name("RCTJavaScriptDidLoadNotification"),
174
+ object: nil,
175
+ queue: nil
176
+ ) { notification in
177
+ contentBindings.runtimeDidLoad(bundleURL: bundleURL(from: notification))
178
+ }
179
+
180
+ NotificationCenter.default.addObserver(
181
+ forName: Notification.Name("RCTContentDidAppearNotification"),
182
+ object: nil,
183
+ queue: nil
184
+ ) { notification in
185
+ guard let attempt = contentBindings.binding(for: notification.object) else { return }
186
+ let hash = attempt.hash
187
+ let attemptId = attempt.attemptId
188
+ guard let delay = defaultController()?.markContentAppeared(
189
+ hash: hash,
190
+ attemptId: attemptId
191
+ ) else { return }
192
+ let markHealthy = {
193
+ _ = BundleDropStartupRecoveryAdapter.markHealthy(hash: hash, attemptId: attemptId)
194
+ }
195
+ if delay <= 0 {
196
+ markHealthy()
197
+ } else {
198
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: markHealthy)
199
+ }
200
+ }
201
+ }
202
+
203
+ static func bundleURL(from notification: Notification) -> URL? {
204
+ let selector = NSSelectorFromString("bundleURL")
205
+ let providers = [notification.userInfo?["bridge"], notification.object].compactMap { $0 }
206
+ for provider in providers {
207
+ let object = provider as AnyObject
208
+ // RCTBridgeProxy forwards -bundleURL but reports responds(to:) as false.
209
+ // Checking the concrete Objective-C implementation keeps URL identity
210
+ // available in bridgeless RN without accepting an anonymous global event.
211
+ guard object.responds(to: selector) ||
212
+ class_getInstanceMethod(type(of: object), selector) != nil else {
213
+ continue
214
+ }
215
+ if let url = object.perform(selector)?.takeUnretainedValue() as? URL {
216
+ return url
217
+ }
218
+ }
219
+ return nil
220
+ }
221
+ }
222
+
223
+ /// Associates each React root with the startup attempt that selected its runtime.
224
+ /// Legacy and Fabric both post `RCTContentDidAppearNotification` with their root
225
+ /// object, so a notification arriving late from an older root remains bound to
226
+ /// the older attempt instead of blessing the newest reload.
227
+ final class BundleDropStartupContentBindings {
228
+ struct Binding: Equatable {
229
+ let generation: UInt64
230
+ let hash: String
231
+ let attemptId: String
232
+ let bundlePath: String
233
+ }
234
+
235
+ private final class RootEntry {
236
+ weak var root: AnyObject?
237
+ let binding: Binding
238
+
239
+ init(root: AnyObject, binding: Binding) {
240
+ self.root = root
241
+ self.binding = binding
242
+ }
243
+ }
244
+
245
+ private let lock = NSLock()
246
+ private var generation: UInt64 = 0
247
+ private var activeBinding: Binding?
248
+ private var activeRuntimeLoaded = false
249
+ private var roots: [ObjectIdentifier: RootEntry] = [:]
250
+
251
+ func capture(hash: String?, attemptId: String?, bundleURL: URL?) {
252
+ lock.lock()
253
+ defer { lock.unlock() }
254
+ generation &+= 1
255
+ if let hash, let attemptId, let bundleURL {
256
+ activeBinding = Binding(
257
+ generation: generation,
258
+ hash: hash,
259
+ attemptId: attemptId,
260
+ bundlePath: Self.normalizedPath(bundleURL)
261
+ )
262
+ } else {
263
+ activeBinding = nil
264
+ }
265
+ activeRuntimeLoaded = false
266
+ roots = roots.filter { $0.value.root != nil }
267
+ }
268
+
269
+ func runtimeDidLoad(bundleURL: URL?) {
270
+ lock.lock()
271
+ defer { lock.unlock() }
272
+ guard let activeBinding,
273
+ let bundleURL,
274
+ Self.normalizedPath(bundleURL) == activeBinding.bundlePath else {
275
+ return
276
+ }
277
+ activeRuntimeLoaded = true
278
+ // React may reuse an RCTRootView across legacy reloads. Once the selected
279
+ // runtime has loaded, roots belong to the new generation when they next
280
+ // report content appearance.
281
+ roots.removeAll()
282
+ }
283
+
284
+ func binding(for root: Any?) -> Binding? {
285
+ guard let root else { return nil }
286
+ let rootObject = root as AnyObject
287
+ lock.lock()
288
+ defer { lock.unlock() }
289
+ let identifier = ObjectIdentifier(rootObject)
290
+ if let existing = roots[identifier], existing.root === rootObject {
291
+ return existing.binding
292
+ }
293
+ guard activeRuntimeLoaded, let activeBinding else { return nil }
294
+ roots[identifier] = RootEntry(root: rootObject, binding: activeBinding)
295
+ return activeBinding
296
+ }
297
+
298
+ private static func normalizedPath(_ url: URL) -> String {
299
+ url.standardizedFileURL.resolvingSymlinksInPath().path
300
+ }
301
+ }
package/lib/CLI/cli.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  export declare const buildProgram: () => import("commander").Command;
3
+ export declare const runCli: (argv?: string[]) => Promise<void>;
package/lib/CLI/cli.js CHANGED
@@ -4,7 +4,7 @@ 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
+ exports.runCli = exports.buildProgram = void 0;
8
8
  const axios_1 = __importDefault(require("axios"));
9
9
  const chalk_1 = __importDefault(require("chalk"));
10
10
  const commander_1 = require("commander");
@@ -15,9 +15,9 @@ const upload_cli_1 = __importDefault(require("./scripts/upload-cli"));
15
15
  const sight_cli_1 = require("./scripts/sight-cli");
16
16
  const post_init_1 = require("./scripts/post-init");
17
17
  const logo_1 = require("./logo");
18
+ const serverUrl_1 = require("./serverUrl");
18
19
  const package_json_1 = __importDefault(require("../../package.json"));
19
20
  const logo = (0, logo_1.buildBundleDropLogo)();
20
- const DEFAULT_SERVER_URL = 'https://api.bundledrop.app';
21
21
  const DOCS_CLI_URL = 'https://bundledrop.app/docs/cli';
22
22
  const DOCS_UPLOADING_URL = 'https://bundledrop.app/docs/uploading';
23
23
  const DOCS_CI_CD_URL = 'https://bundledrop.app/docs/ci-cd';
@@ -40,7 +40,6 @@ const runSetupWithManualFallback = async (params) => {
40
40
  }
41
41
  };
42
42
  const getTokenPath = () => path_1.default.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
43
- const normalizeServerUrl = (url) => url?.replace(/\/$/, '') || DEFAULT_SERVER_URL;
44
43
  const readStoredAuthData = () => {
45
44
  const tokenPath = getTokenPath();
46
45
  if (!fs_1.default.existsSync(tokenPath)) {
@@ -183,6 +182,7 @@ ${chalk_1.default.gray('CI/CD docs →')} ${chalk_1.default.underline.gray(DOCS_
183
182
  .option('--token <token>', 'Personal Access Token (alternative to `bundle-drop login`)')
184
183
  .option('--project-type <type>', 'Force project type: expo or bare')
185
184
  .option('--dry-run', 'Preview setup and AI context without changing files')
185
+ .option('--migrate-code-push', 'Explicitly remove react-native-code-push after reviewing its native migration')
186
186
  .option('--migrate-expo-updates', 'Explicitly remove active expo-updates configuration and dependency')
187
187
  .option('--prebuild', 'Run a layered Expo prebuild for committed native directories')
188
188
  .option('--yes', 'Approve ordinary setup changes noninteractively')
@@ -197,7 +197,7 @@ ${chalk_1.default.gray('CI/CD docs →')} ${chalk_1.default.underline.gray(DOCS_
197
197
  projectRoot: process.cwd(),
198
198
  explicitType: options.projectType,
199
199
  });
200
- const serverUrl = normalizeServerUrl(process.env.BUNDLE_DROP_SERVER_URL);
200
+ const serverUrl = (0, serverUrl_1.normalizeServerUrl)(process.env.BUNDLE_DROP_SERVER_URL);
201
201
  const tokenContext = await fetchFreshAuthContext({
202
202
  serverUrl,
203
203
  token: options.token,
@@ -217,6 +217,9 @@ ${chalk_1.default.gray('CI/CD docs →')} ${chalk_1.default.underline.gray(DOCS_
217
217
  options: {
218
218
  ...options,
219
219
  projectType,
220
+ ...(configResult?.bootstrapContent
221
+ ? { runtimeDeliveryBootstrap: { content: configResult.bootstrapContent } }
222
+ : {}),
220
223
  ...(!hadConfig && configResult
221
224
  ? {
222
225
  virtualConfig: {
@@ -255,7 +258,7 @@ ${chalk_1.default.gray('CI/CD docs →')} ${chalk_1.default.underline.gray(DOCS_
255
258
  projectRoot: process.cwd(),
256
259
  explicitType: options.projectType,
257
260
  });
258
- const serverUrl = normalizeServerUrl(data.serverUrl || data.baseUrl || process.env.BUNDLE_DROP_SERVER_URL);
261
+ const serverUrl = (0, serverUrl_1.normalizeServerUrl)(data.serverUrl || data.baseUrl || process.env.BUNDLE_DROP_SERVER_URL);
259
262
  const freshContext = await fetchFreshAuthContext({
260
263
  serverUrl,
261
264
  token: data.token,
@@ -279,6 +282,9 @@ ${chalk_1.default.gray('CI/CD docs →')} ${chalk_1.default.underline.gray(DOCS_
279
282
  options: {
280
283
  ...options,
281
284
  projectType,
285
+ ...(configResult?.bootstrapContent
286
+ ? { runtimeDeliveryBootstrap: { content: configResult.bootstrapContent } }
287
+ : {}),
282
288
  ...(!hadConfig && configResult
283
289
  ? {
284
290
  virtualConfig: {
@@ -295,6 +301,40 @@ ${chalk_1.default.gray('CI/CD docs →')} ${chalk_1.default.underline.gray(DOCS_
295
301
  preservePendingConfig: !hadConfig && !options.dryRun,
296
302
  });
297
303
  });
304
+ program
305
+ .command('sync')
306
+ .option('--token <token>', 'Personal Access Token (alternative to `bundle-drop login`)')
307
+ .option('--dry-run', 'Validate and preview bootstrap synchronization without writing')
308
+ .description('Refresh the package-managed runtime delivery bootstrap')
309
+ .action(async (options) => {
310
+ const initConfigModule = require('../CLI/scripts/init-config');
311
+ if (!initConfigModule.hasExistingBundleDropConfig()) {
312
+ throw new Error('bundle-drop sync requires bundle.drop.config.js. Run `bundle-drop init` first.');
313
+ }
314
+ const authState = options.token ? null : readStoredAuthData();
315
+ const token = options.token || authState?.data?.token;
316
+ if (!token) {
317
+ throw new Error('Not authenticated. Run `bundle-drop login` or pass --token.');
318
+ }
319
+ const serverUrl = (0, serverUrl_1.normalizeServerUrl)(authState?.data?.serverUrl || authState?.data?.baseUrl || process.env.BUNDLE_DROP_SERVER_URL);
320
+ const result = await initConfigModule.initConfig({
321
+ serverUrl,
322
+ projects: [],
323
+ organizations: [],
324
+ authToken: token,
325
+ dryRun: Boolean(options.dryRun),
326
+ });
327
+ const deliveryDisabled = result?.bootstrapRetired === true;
328
+ if (!result?.bootstrapContent && !deliveryDisabled) {
329
+ throw new Error('The backend did not return a valid runtime delivery bootstrap for this project. ' +
330
+ 'The existing bootstrap was preserved.');
331
+ }
332
+ if (options.dryRun) {
333
+ console.log(chalk_1.default.gray(deliveryDisabled
334
+ ? 'Runtime delivery is disabled; the stale bootstrap would be removed. No files changed.'
335
+ : 'Runtime delivery bootstrap is valid. No files changed.'));
336
+ }
337
+ });
298
338
  program
299
339
  .command('doctor')
300
340
  .option('--platform <platform>', 'Limit checks to ios or android')
@@ -356,6 +396,17 @@ ${chalk_1.default.bold('Examples:')}
356
396
  return program;
357
397
  };
358
398
  exports.buildProgram = buildProgram;
399
+ const runCli = async (argv = process.argv) => {
400
+ try {
401
+ await (0, exports.buildProgram)().parseAsync(argv);
402
+ }
403
+ catch (error) {
404
+ const message = error instanceof Error ? error.message : String(error);
405
+ console.error(chalk_1.default.red(`❌ ${message}`));
406
+ process.exitCode = 1;
407
+ }
408
+ };
409
+ exports.runCli = runCli;
359
410
  if (require.main === module) {
360
- (0, exports.buildProgram)().parse();
411
+ void (0, exports.runCli)();
361
412
  }
@@ -6,26 +6,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.restoreSetupBackups = restoreSetupBackups;
7
7
  exports.applySetupPatchPlans = applySetupPatchPlans;
8
8
  const crypto_1 = __importDefault(require("crypto"));
9
- const fs_extra_1 = __importDefault(require("fs-extra"));
10
- const path_1 = __importDefault(require("path"));
11
9
  const validate_plan_1 = require("./validate-plan");
10
+ const safe_file_transaction_1 = require("../safe-file-transaction");
12
11
  const sha256 = (content) => crypto_1.default.createHash('sha256').update(content).digest('hex');
13
- const timestamp = () => new Date().toISOString().replace(/[:.]/g, '-');
14
12
  const isAllowedSetupFile = (projectType, filePath) => projectType === 'expo'
15
13
  ? (0, validate_plan_1.isPatchableExpoConfig)(filePath)
16
14
  : (0, validate_plan_1.isPatchableNativeEntrypoint)(filePath);
17
15
  function restoreSetupBackups(result) {
18
16
  for (const relativePath of result.changedFiles) {
19
- const backupPath = path_1.default.join(result.backupDir, relativePath);
20
- if (fs_extra_1.default.existsSync(backupPath)) {
21
- fs_extra_1.default.copyFileSync(backupPath, path_1.default.join(result.projectRoot, relativePath));
22
- }
17
+ (0, safe_file_transaction_1.restoreProjectFile)(result.projectRoot, result.backupDir, relativePath);
23
18
  }
24
19
  }
25
20
  function applySetupPatchPlans(params) {
26
21
  const result = {
27
22
  projectRoot: params.projectRoot,
28
- backupDir: path_1.default.join(params.projectRoot, '.bundledrop-backup', timestamp()),
23
+ backupDir: (0, safe_file_transaction_1.createSafeBackupDirectory)(params.projectRoot, 'ai-setup'),
29
24
  changedFiles: [],
30
25
  };
31
26
  try {
@@ -33,18 +28,13 @@ function applySetupPatchPlans(params) {
33
28
  if (!(0, validate_plan_1.isSafeRelativePath)(change.file) || !isAllowedSetupFile(params.projectType, change.file)) {
34
29
  throw new Error(`Refusing to write AI setup plan outside its allowlist: ${change.file}`);
35
30
  }
36
- const targetPath = path_1.default.join(params.projectRoot, change.file);
37
- const original = fs_extra_1.default.readFileSync(targetPath, 'utf8');
38
- if (sha256(original) !== change.originalSha256) {
31
+ const target = (0, safe_file_transaction_1.inspectProjectFile)(params.projectRoot, change.file);
32
+ if (!target.exists || sha256(target.content) !== change.originalSha256) {
39
33
  throw new Error(`File changed since AI setup scan: ${change.file}`);
40
34
  }
41
- const backupPath = path_1.default.join(result.backupDir, change.file);
42
- fs_extra_1.default.ensureDirSync(path_1.default.dirname(backupPath));
43
- fs_extra_1.default.copyFileSync(targetPath, backupPath);
35
+ (0, safe_file_transaction_1.writeBackupFile)(result.backupDir, change.file, target.content, target.mode);
44
36
  result.changedFiles.push(change.file);
45
- const temporaryPath = `${targetPath}.bundledrop-tmp`;
46
- fs_extra_1.default.writeFileSync(temporaryPath, change.updated, 'utf8');
47
- fs_extra_1.default.renameSync(temporaryPath, targetPath);
37
+ (0, safe_file_transaction_1.writeProjectFileAtomically)(params.projectRoot, change.file, change.updated, target.mode);
48
38
  }
49
39
  return result;
50
40
  }
@@ -5,7 +5,29 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.requestAiSetupPlan = requestAiSetupPlan;
7
7
  const axios_1 = __importDefault(require("axios"));
8
+ const credential_safety_1 = require("./credential-safety");
9
+ const terminal_safety_1 = require("./terminal-safety");
8
10
  const DEFAULT_AI_INIT_TIMEOUT_MS = 180000;
11
+ const MAX_BACKEND_DIAGNOSTIC_LENGTH = 1000;
12
+ const safeBackendDiagnostic = (value) => {
13
+ if (typeof value !== 'string')
14
+ return null;
15
+ const diagnostic = value.trim();
16
+ if (!diagnostic ||
17
+ diagnostic.length > MAX_BACKEND_DIAGNOSTIC_LENGTH ||
18
+ (0, credential_safety_1.findKnownBundleDropCredential)(diagnostic)) {
19
+ return null;
20
+ }
21
+ return (0, terminal_safety_1.escapeTerminalControls)(diagnostic);
22
+ };
23
+ const safeBackendDetailReason = (details) => {
24
+ if (!details || typeof details !== 'object' || Array.isArray(details))
25
+ return null;
26
+ const descriptor = Object.getOwnPropertyDescriptor(details, 'reason');
27
+ if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, 'value'))
28
+ return null;
29
+ return safeBackendDiagnostic(descriptor.value);
30
+ };
9
31
  const resolveTimeoutMs = () => {
10
32
  const value = Number(process.env.BUNDLE_DROP_AI_INIT_TIMEOUT_MS || '');
11
33
  return Number.isFinite(value) && value > 0 ? value : DEFAULT_AI_INIT_TIMEOUT_MS;
@@ -26,9 +48,12 @@ async function requestAiSetupPlan(params) {
26
48
  if (error?.code === 'ECONNABORTED' || /timeout/i.test(String(error?.message || ''))) {
27
49
  throw new Error('AI setup planning timed out. Try again, or increase BUNDLE_DROP_AI_INIT_TIMEOUT_MS.');
28
50
  }
29
- const message = raw && typeof raw === 'object'
30
- ? raw.error || JSON.stringify(raw)
31
- : raw || error?.message || 'AI setup planning failed';
32
- throw new Error(`AI setup planning failed: ${message}`);
51
+ const diagnostic = raw && typeof raw === 'object'
52
+ ? safeBackendDetailReason(raw.details) || safeBackendDiagnostic(raw.error)
53
+ : safeBackendDiagnostic(raw);
54
+ const fallback = diagnostic || safeBackendDiagnostic(error?.message);
55
+ throw new Error(fallback
56
+ ? `AI setup planning failed: ${fallback}`
57
+ : 'AI setup planning failed');
33
58
  }
34
59
  }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Finds CodePush ownership outside package files and provider-patched native entrypoints.
3
+ * Only relative paths are returned; file contents never leave this local validation boundary.
4
+ */
5
+ export declare function findCodePushResiduePaths(projectRoot: string): string[];
@@ -0,0 +1,126 @@
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.findCodePushResiduePaths = findCodePushResiduePaths;
7
+ const fs_extra_1 = __importDefault(require("fs-extra"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const MAX_VISITED_ENTRIES = 20000;
10
+ const MAX_CANDIDATE_FILES = 500;
11
+ const MAX_FILE_BYTES = 1024 * 1024;
12
+ const MAX_TOTAL_BYTES = 5 * 1024 * 1024;
13
+ const SKIPPED_DIRECTORIES = new Set([
14
+ '.bundle-drop',
15
+ '.bundledrop-backup',
16
+ '.expo',
17
+ '.git',
18
+ '.gradle',
19
+ 'build',
20
+ 'coverage',
21
+ 'deriveddata',
22
+ 'dist',
23
+ 'generated',
24
+ 'lib',
25
+ 'node_modules',
26
+ 'pods',
27
+ 'vendor',
28
+ ]);
29
+ const JS_SOURCE_EXTENSION = /\.(?:cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
30
+ const CODE_PUSH_REFERENCE = /\b(?:react-native-code-push|code[\s_.-]*push|com\.microsoft\.codepush\.react)/i;
31
+ const toPosix = (filePath) => filePath.split(path_1.default.sep).join('/');
32
+ const isCodePushResidueCandidate = (relativePath) => {
33
+ const parts = relativePath.split('/');
34
+ const basename = parts[parts.length - 1];
35
+ if (JS_SOURCE_EXTENSION.test(basename))
36
+ return true;
37
+ if (parts[0] === 'android') {
38
+ if (/^MainApplication\.(?:java|kt)$/i.test(basename))
39
+ return false;
40
+ return /\.(?:gradle|gradle\.kts|java|kt|properties|xml)$/i.test(basename);
41
+ }
42
+ if (parts[0] === 'ios') {
43
+ if (/^AppDelegate\.(?:m|mm|swift)$/i.test(basename))
44
+ return false;
45
+ return basename === 'Podfile' ||
46
+ /\.(?:h|m|mm|pbxproj|plist|podspec|swift|xcconfig)$/i.test(basename);
47
+ }
48
+ return false;
49
+ };
50
+ const scanLimitError = (detail) => new Error(`CodePush residue validation could not safely complete (${detail}). ` +
51
+ 'Clean up CodePush manually or reduce the project scan surface, then retry. No files changed.');
52
+ /**
53
+ * Finds CodePush ownership outside package files and provider-patched native entrypoints.
54
+ * Only relative paths are returned; file contents never leave this local validation boundary.
55
+ */
56
+ function findCodePushResiduePaths(projectRoot) {
57
+ const pendingDirectories = [''];
58
+ const residuePaths = [];
59
+ let visitedEntries = 0;
60
+ let candidateFiles = 0;
61
+ let totalBytes = 0;
62
+ while (pendingDirectories.length) {
63
+ const relativeDirectory = pendingDirectories.pop();
64
+ const absoluteDirectory = path_1.default.join(projectRoot, relativeDirectory);
65
+ let entries;
66
+ try {
67
+ entries = fs_extra_1.default.readdirSync(absoluteDirectory, { withFileTypes: true });
68
+ }
69
+ catch {
70
+ throw scanLimitError(`cannot inspect ${toPosix(relativeDirectory) || '.'}`);
71
+ }
72
+ entries.sort((left, right) => left.name.localeCompare(right.name));
73
+ for (const entry of entries) {
74
+ visitedEntries += 1;
75
+ if (visitedEntries > MAX_VISITED_ENTRIES) {
76
+ throw scanLimitError(`more than ${MAX_VISITED_ENTRIES} filesystem entries`);
77
+ }
78
+ const relativePath = relativeDirectory
79
+ ? path_1.default.join(relativeDirectory, entry.name)
80
+ : entry.name;
81
+ const absolutePath = path_1.default.join(projectRoot, relativePath);
82
+ let stat;
83
+ try {
84
+ stat = fs_extra_1.default.lstatSync(absolutePath);
85
+ }
86
+ catch {
87
+ throw scanLimitError(`cannot inspect ${toPosix(relativePath)}`);
88
+ }
89
+ if (SKIPPED_DIRECTORIES.has(entry.name.toLowerCase()))
90
+ continue;
91
+ if (stat.isSymbolicLink()) {
92
+ throw scanLimitError(`relevant project path ${toPosix(relativePath)} is a symbolic link`);
93
+ }
94
+ if (stat.isDirectory()) {
95
+ pendingDirectories.push(relativePath);
96
+ continue;
97
+ }
98
+ if (!stat.isFile())
99
+ continue;
100
+ const posixPath = toPosix(relativePath);
101
+ if (!isCodePushResidueCandidate(posixPath))
102
+ continue;
103
+ candidateFiles += 1;
104
+ if (candidateFiles > MAX_CANDIDATE_FILES) {
105
+ throw scanLimitError(`more than ${MAX_CANDIDATE_FILES} relevant files`);
106
+ }
107
+ if (stat.size > MAX_FILE_BYTES) {
108
+ throw scanLimitError(`${posixPath} exceeds the per-file limit`);
109
+ }
110
+ totalBytes += stat.size;
111
+ if (totalBytes > MAX_TOTAL_BYTES) {
112
+ throw scanLimitError(`relevant files exceed ${MAX_TOTAL_BYTES} bytes`);
113
+ }
114
+ let content;
115
+ try {
116
+ content = fs_extra_1.default.readFileSync(absolutePath, 'utf8');
117
+ }
118
+ catch {
119
+ throw scanLimitError(`cannot read ${posixPath}`);
120
+ }
121
+ if (CODE_PUSH_REFERENCE.test(content))
122
+ residuePaths.push(posixPath);
123
+ }
124
+ }
125
+ return residuePaths.sort();
126
+ }
@@ -0,0 +1 @@
1
+ export declare const findKnownBundleDropCredential: (value: string) => string | null;