@capgo/capacitor-updater 9.0.1 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/README.md +106 -81
  2. package/android/build.gradle +1 -3
  3. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +513 -21
  4. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +675 -34
  5. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +82 -10
  6. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +23 -0
  7. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +188 -4
  8. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +81 -1
  9. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +72 -21
  10. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +5 -1
  11. package/dist/docs.json +13 -13
  12. package/dist/esm/definitions.d.ts +57 -23
  13. package/dist/esm/definitions.js.map +1 -1
  14. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1278 -107
  15. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +38 -0
  16. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +583 -56
  17. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +8 -1
  18. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +6 -1
  19. package/ios/Tests/CapacitorUpdaterPluginTests/CapacitorUpdaterPluginTests.swift +2705 -77
  20. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +9 -4
  21. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +67 -2
  22. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +130 -5
  23. package/ios/Tests/CapacitorUpdaterPluginTests/NetworkTransportTests.swift +22 -8
  24. package/ios/Tests/CapacitorUpdaterPluginTests/SessionKeyRequiredTests.swift +4 -0
  25. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +19 -3
  26. package/package.json +2 -2
@@ -66,6 +66,14 @@ private final class RealSendReadyCapacitorUpdaterPlugin: CapacitorUpdaterPlugin
66
66
  private var _appReadyNotifiedAt: Date?
67
67
  private var _appReadyNotifiedOnMainThread: Bool?
68
68
  private var _appReadyRetainUntilConsumed: Bool?
69
+ private var recordedAppReadyRawEventName: String?
70
+
71
+ /// The bridge event name the appReady notification went out under (v9: `updaterEvent`).
72
+ var appReadyRawEventName: String? {
73
+ eventLock.lock()
74
+ defer { eventLock.unlock() }
75
+ return recordedAppReadyRawEventName
76
+ }
69
77
 
70
78
  var appReadyNotifiedOnMainThread: Bool? {
71
79
  eventLock.lock()
@@ -106,6 +114,7 @@ private final class RealSendReadyCapacitorUpdaterPlugin: CapacitorUpdaterPlugin
106
114
  _appReadyNotifiedAt = Date()
107
115
  _appReadyNotifiedOnMainThread = Thread.isMainThread
108
116
  _appReadyRetainUntilConsumed = retain
117
+ recordedAppReadyRawEventName = eventName
109
118
  }
110
119
  if let payload = event.data {
111
120
  _notifiedEventPayloads[event.name] = payload
@@ -158,21 +167,37 @@ private class FreshDownloadCapgoUpdater: CapgoUpdater {
158
167
  return existingBundleValue
159
168
  }
160
169
 
170
+ /// Bundles listed after `existingBundleValue` when every same-version entry is requested.
171
+ var additionalVersionBundles: [BundleInfo] = []
172
+
173
+ override func getBundleInfosByVersionName(version: String) -> [BundleInfo] {
174
+ ([existingBundleValue].compactMap { $0 } + additionalVersionBundles)
175
+ .filter { $0.getVersionName() == version }
176
+ }
177
+
178
+ /// Stored records returned by getBundleInfo(id:) instead of the current bundle, e.g. a bundle marked ERROR.
179
+ var storedBundleInfoOverrides: [String: BundleInfo] = [:]
180
+
161
181
  override func getBundleInfo(id: String?) -> BundleInfo {
162
182
  if id == BundleInfo.ID_BUILTIN {
163
183
  return builtinBundleValue
164
184
  }
185
+ if let id, let override = storedBundleInfoOverrides[id] {
186
+ return override
187
+ }
165
188
  return currentBundleValue
166
189
  }
167
190
 
168
- override func downloadVerified(
191
+ override func downloadVerifiedWithTransferHook(
169
192
  url _: URL,
170
193
  version _: String,
171
194
  sessionKey _: String,
172
195
  expectedChecksum _: String,
173
- link _: String? = nil,
174
- comment _: String? = nil
196
+ link _: String?,
197
+ comment _: String?,
198
+ beforeTransfer: (() throws -> Void)?
175
199
  ) throws -> BundleInfo {
200
+ try beforeTransfer?()
176
201
  downloadCalls += 1
177
202
  onDownloadStart?()
178
203
  if let downloadedBundleValue {
@@ -190,6 +215,26 @@ private class FreshDownloadCapgoUpdater: CapgoUpdater {
190
215
  return true
191
216
  }
192
217
 
218
+ override func canSet(bundle: BundleInfo) -> Bool {
219
+ if let existingBundleValue, existingBundleValue.getId() == bundle.getId() {
220
+ return existingBundleValue.getStatus() == BundleStatus.PENDING.storedValue
221
+ }
222
+ if let downloadedBundleValue, downloadedBundleValue.getId() == bundle.getId() {
223
+ return downloadedBundleValue.getStatus() == BundleStatus.PENDING.storedValue
224
+ }
225
+ return super.canSet(bundle: bundle)
226
+ }
227
+
228
+ override func isBundleOnDisk(id: String) -> Bool {
229
+ if let existingBundleValue, existingBundleValue.getId() == id {
230
+ return self.canSet(bundle: existingBundleValue)
231
+ }
232
+ if let downloadedBundleValue, downloadedBundleValue.getId() == id {
233
+ return self.canSet(bundle: downloadedBundleValue)
234
+ }
235
+ return super.isBundleOnDisk(id: id)
236
+ }
237
+
193
238
  override func setNextBundle(next: String?) -> Bool {
194
239
  setNextBundleCalls += 1
195
240
  lastSetNextBundleId = next
@@ -231,19 +276,61 @@ private final class SplashTimeoutCapgoUpdater: FreshDownloadCapgoUpdater {
231
276
  return true
232
277
  }
233
278
 
234
- override func set(bundle: BundleInfo) -> Bool {
279
+ /// Fixture-only active bundle path. Production persists the active path and the queue (NEXT_VERSION) and
280
+ /// reset-state capture/restore read and write both; this fixture models that in memory so tests never
281
+ /// leave fixture state in the shared UserDefaults.
282
+ private static let fixturePathPrefix = "fixture-bundle/"
283
+ private var fixtureFallbackBundleId = BundleInfo.ID_BUILTIN
284
+ /// Every bundle the fixture has had active, so a restored path can resolve the initial bundle too.
285
+ private var knownActiveBundles: [String: BundleInfo] = [:]
286
+
287
+ private func activate(_ bundle: BundleInfo) {
288
+ knownActiveBundles[currentBundleValue.getId()] = currentBundleValue
289
+ knownActiveBundles[bundle.getId()] = bundle
235
290
  currentBundleValue = bundle
291
+ }
292
+
293
+ override func captureResetState() -> ResetState {
294
+ knownActiveBundles[currentBundleValue.getId()] = currentBundleValue
295
+ return ResetState(
296
+ currentBundlePath: Self.fixturePathPrefix + currentBundleValue.getId(),
297
+ fallbackBundleId: fixtureFallbackBundleId,
298
+ nextBundleId: queuedBundle?.getId()
299
+ )
300
+ }
301
+
302
+ override func restoreResetState(_ state: ResetState) {
303
+ let bundles = [existingBundleValue, downloadedBundleValue, builtinBundleValue, currentBundleValue].compactMap { $0 }
304
+ if state.currentBundlePath.hasPrefix(Self.fixturePathPrefix) {
305
+ let activeId = String(state.currentBundlePath.dropFirst(Self.fixturePathPrefix.count))
306
+ if let active = knownActiveBundles[activeId] ?? bundles.first(where: { $0.getId() == activeId }) {
307
+ currentBundleValue = active
308
+ }
309
+ }
310
+ fixtureFallbackBundleId = state.fallbackBundleId
311
+ queuedBundle = state.nextBundleId.flatMap { id in bundles.first(where: { $0.getId() == id }) }
312
+ }
313
+
314
+ override func prepareResetStateForTransition() {
315
+ // Production clears the active path, fallback and queue and activates the builtin bundle.
316
+ activate(builtinBundleValue)
317
+ fixtureFallbackBundleId = BundleInfo.ID_BUILTIN
318
+ queuedBundle = nil
319
+ }
320
+
321
+ override func set(bundle: BundleInfo) -> Bool {
322
+ activate(bundle)
236
323
  return true
237
324
  }
238
325
 
239
326
  override func stagePendingReload(bundle: BundleInfo) -> Bool {
240
327
  stagePendingReloadCalls += 1
328
+ // Production staging points the current bundle at the new one; finalization only sends stats.
329
+ activate(bundle)
241
330
  return true
242
331
  }
243
332
 
244
- override func finalizePendingReload(bundle: BundleInfo, previousBundleName: String) {
245
- currentBundleValue = bundle
246
- }
333
+ override func finalizePendingReload(bundle: BundleInfo, previousBundleName: String) {}
247
334
  }
248
335
 
249
336
  private final class SplashTimeoutCapacitorUpdaterPlugin: TestableCapacitorUpdaterPlugin {
@@ -253,9 +340,15 @@ private final class SplashTimeoutCapacitorUpdaterPlugin: TestableCapacitorUpdate
253
340
  override func beginDownloadBackgroundTask() {}
254
341
  override func checkAppReady() {}
255
342
 
343
+ var onReload: (() -> Void)?
344
+ /// Result of the n-th `reloadCurrentBundle()` call (1-based); nil means success.
345
+ var reloadResult: ((Int) -> Bool)?
346
+
256
347
  override func reloadCurrentBundle() -> Bool {
257
348
  reloadCalls += 1
258
- return true
349
+ let call = reloadCalls
350
+ onReload?()
351
+ return reloadResult?(call) ?? true
259
352
  }
260
353
 
261
354
  override func _reset(toLastSuccessful: Bool, usePendingBundle: Bool) -> Bool {
@@ -604,9 +697,12 @@ class CapacitorUpdaterTests: XCTestCase {
604
697
  super.setUp()
605
698
  plugin = TestableCapacitorUpdaterPlugin()
606
699
  implementation = CapgoUpdater()
700
+ // Retry budgets persist in UserDefaults until a successful install; start every test from a clean one.
701
+ resetRetryState()
607
702
  }
608
703
 
609
704
  override func tearDown() {
705
+ resetRetryState()
610
706
  plugin = nil
611
707
  implementation = nil
612
708
  super.tearDown()
@@ -623,6 +719,14 @@ class CapacitorUpdaterTests: XCTestCase {
623
719
  }
624
720
  for persistAfterSaving in [false, true] {
625
721
  let testPlugin = CapacitorUpdaterPlugin()
722
+ // The plugin's own updater persists its stats queue on shutdown (deinit): keep it off the real
723
+ // capgo_pending_stats.json. The teardown block removes the directory after every plugin is gone.
724
+ let statsDirectory = FileManager.default.temporaryDirectory
725
+ .appendingPathComponent("CustomIdTests-\(UUID().uuidString)", isDirectory: true)
726
+ testPlugin.implementation.pendingStatsDirectoryOverride = statsDirectory
727
+ addTeardownBlock {
728
+ try? FileManager.default.removeItem(at: statsDirectory)
729
+ }
626
730
  var resolved = 0
627
731
  for customId in ["alice", "bob", ""] {
628
732
  if customId != "alice" {
@@ -648,6 +752,12 @@ class CapacitorUpdaterTests: XCTestCase {
648
752
  }
649
753
  }
650
754
 
755
+ private func resetRetryState() {
756
+ for version in ["1.0.0", "2.0.0", "3.0.0"] {
757
+ implementation?.resetIncompleteDownloadRetryCount(version: version)
758
+ }
759
+ }
760
+
651
761
  private func makeOnlyDownloadBundle(
652
762
  id: String = "downloaded-id",
653
763
  version: String = "2.0.0",
@@ -1019,13 +1129,20 @@ class CapacitorUpdaterTests: XCTestCase {
1019
1129
  }
1020
1130
 
1021
1131
  func testShouldRetryDownloadForIncompleteExistingBundles() {
1022
- let pending = BundleInfo(
1132
+ let pendingOnDisk = BundleInfo(
1023
1133
  id: "pending-id",
1024
1134
  version: "2.0.0",
1025
1135
  status: .PENDING,
1026
1136
  downloaded: Date(),
1027
1137
  checksum: "abc123"
1028
1138
  )
1139
+ let pendingStale = BundleInfo(
1140
+ id: "pending-stale",
1141
+ version: "2.0.0",
1142
+ status: .PENDING,
1143
+ downloaded: Date(),
1144
+ checksum: "abc123"
1145
+ )
1029
1146
  let downloading = BundleInfo(
1030
1147
  id: "downloading-id",
1031
1148
  version: "2.0.0",
@@ -1047,11 +1164,191 @@ class CapacitorUpdaterTests: XCTestCase {
1047
1164
  downloaded: Date(),
1048
1165
  checksum: "abc123"
1049
1166
  )
1167
+ let interruptedError = BundleInfo(
1168
+ id: "error-id",
1169
+ version: "2.0.0",
1170
+ status: .ERROR,
1171
+ downloaded: Date(),
1172
+ checksum: ""
1173
+ )
1174
+
1175
+ XCTAssertFalse(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1176
+ pendingOnDisk,
1177
+ bundleOnDisk: true,
1178
+ incompleteRetryCount: 0,
1179
+ integrityBlocked: false,
1180
+ interruptedDownloadFailure: false,
1181
+ isCurrentBundle: false,
1182
+ isQueuedNext: true
1183
+ ))
1184
+ XCTAssertFalse(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1185
+ pendingStale,
1186
+ bundleOnDisk: true,
1187
+ incompleteRetryCount: 0,
1188
+ integrityBlocked: false,
1189
+ interruptedDownloadFailure: false,
1190
+ isCurrentBundle: false,
1191
+ isQueuedNext: false
1192
+ ))
1193
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1194
+ pendingStale,
1195
+ bundleOnDisk: false,
1196
+ incompleteRetryCount: 0,
1197
+ integrityBlocked: false,
1198
+ interruptedDownloadFailure: false,
1199
+ isCurrentBundle: false,
1200
+ isQueuedNext: false
1201
+ ))
1202
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1203
+ downloading,
1204
+ bundleOnDisk: false,
1205
+ incompleteRetryCount: 0,
1206
+ integrityBlocked: false,
1207
+ interruptedDownloadFailure: false,
1208
+ isCurrentBundle: false,
1209
+ isQueuedNext: false
1210
+ ))
1211
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1212
+ deleting,
1213
+ bundleOnDisk: true,
1214
+ incompleteRetryCount: 0,
1215
+ integrityBlocked: false,
1216
+ interruptedDownloadFailure: false,
1217
+ isCurrentBundle: false,
1218
+ isQueuedNext: false
1219
+ ))
1220
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1221
+ deleted,
1222
+ bundleOnDisk: false,
1223
+ incompleteRetryCount: 0,
1224
+ integrityBlocked: false,
1225
+ interruptedDownloadFailure: false,
1226
+ isCurrentBundle: false,
1227
+ isQueuedNext: false
1228
+ ))
1229
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1230
+ interruptedError,
1231
+ bundleOnDisk: false,
1232
+ incompleteRetryCount: 0,
1233
+ integrityBlocked: false,
1234
+ interruptedDownloadFailure: false,
1235
+ isCurrentBundle: false,
1236
+ isQueuedNext: false
1237
+ ))
1238
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1239
+ interruptedError,
1240
+ bundleOnDisk: false,
1241
+ incompleteRetryCount: 0,
1242
+ integrityBlocked: true,
1243
+ interruptedDownloadFailure: false,
1244
+ isCurrentBundle: false,
1245
+ isQueuedNext: false
1246
+ ))
1247
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1248
+ interruptedError,
1249
+ bundleOnDisk: false,
1250
+ incompleteRetryCount: 0,
1251
+ integrityBlocked: false,
1252
+ interruptedDownloadFailure: true,
1253
+ isCurrentBundle: false,
1254
+ isQueuedNext: false
1255
+ ))
1256
+ XCTAssertFalse(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1257
+ interruptedError,
1258
+ bundleOnDisk: false,
1259
+ incompleteRetryCount: CapgoUpdater.maxIncompleteDownloadRetries,
1260
+ integrityBlocked: false,
1261
+ interruptedDownloadFailure: true,
1262
+ isCurrentBundle: false,
1263
+ isQueuedNext: false
1264
+ ))
1265
+ XCTAssertTrue(CapgoUpdater.shouldRetryDownloadForExistingBundle(
1266
+ interruptedError,
1267
+ bundleOnDisk: false,
1268
+ incompleteRetryCount: 0,
1269
+ integrityBlocked: true,
1270
+ interruptedDownloadFailure: true,
1271
+ isCurrentBundle: false,
1272
+ isQueuedNext: false
1273
+ ))
1274
+ }
1275
+
1276
+ func testInterruptedDownloadingBundleRetriesDespiteVersionInProgress() {
1277
+ let plugin = TestableCapacitorUpdaterPlugin()
1278
+ let updater = CapgoUpdater()
1279
+ updater.setLogger(Logger(withTag: "TestLogger"))
1280
+ plugin.implementation = updater
1281
+ plugin.setVersionDownloadInProgressForTesting(version: "2.0.0")
1282
+
1283
+ let bundleId = "downloading-id"
1284
+ updater.markInterruptedDownloadBundle(bundleId: bundleId)
1285
+ defer {
1286
+ updater.clearInterruptedDownloadBundle(bundleId: bundleId)
1287
+ }
1288
+
1289
+ let downloading = BundleInfo(
1290
+ id: bundleId,
1291
+ version: "2.0.0",
1292
+ status: .DOWNLOADING,
1293
+ downloaded: Date(),
1294
+ checksum: ""
1295
+ )
1296
+ let current = BundleInfo(
1297
+ id: "current-id",
1298
+ version: "1.0.0",
1299
+ status: .SUCCESS,
1300
+ downloaded: Date(),
1301
+ checksum: "abc123"
1302
+ )
1303
+
1304
+ XCTAssertTrue(
1305
+ plugin.shouldRetryDownloadForExistingBundleForTesting(downloading, latestVersionName: "2.0.0", current: current)
1306
+ )
1307
+
1308
+ let otherDownloading = BundleInfo(
1309
+ id: "other-id",
1310
+ version: "2.0.0",
1311
+ status: .DOWNLOADING,
1312
+ downloaded: Date(),
1313
+ checksum: ""
1314
+ )
1315
+ XCTAssertFalse(
1316
+ plugin.shouldRetryDownloadForExistingBundleForTesting(otherDownloading, latestVersionName: "2.0.0", current: current)
1317
+ )
1318
+ }
1319
+
1320
+ func testIncompleteDownloadRetryReservationChargesNextStart() {
1321
+ let updater = CapgoUpdater()
1322
+ let version = "retry-accounting-\(UUID().uuidString)"
1323
+ defer {
1324
+ updater.resetIncompleteDownloadRetryCount(version: version)
1325
+ }
1050
1326
 
1051
- XCTAssertFalse(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(pending))
1052
- XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(downloading))
1053
- XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(deleting))
1054
- XCTAssertTrue(CapacitorUpdaterPlugin.shouldRetryDownloadForExistingBundle(deleted))
1327
+ // A first download with no admitted retry and no reservation is free.
1328
+ updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: false)
1329
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), 0)
1330
+
1331
+ // A reservation written before the old record is deleted survives process death and charges the restart.
1332
+ updater.reserveIncompleteDownloadRetry(version: version)
1333
+ XCTAssertTrue(updater.hasIncompleteDownloadRetryReservation(version: version))
1334
+ updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: false)
1335
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), 1)
1336
+ XCTAssertFalse(updater.hasIncompleteDownloadRetryReservation(version: version))
1337
+
1338
+ // Integrity-blocked versions keep their block and count until a successful install resets them.
1339
+ updater.markIntegrityBlockedVersion(version: version)
1340
+ updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: true)
1341
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), 2)
1342
+ XCTAssertTrue(updater.isIntegrityBlockedVersion(version: version))
1343
+
1344
+ // The cap check and charge are atomic: the last slot is charged once, then admitted retries are refused.
1345
+ XCTAssertTrue(updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: true))
1346
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), CapgoUpdater.maxIncompleteDownloadRetries)
1347
+ XCTAssertFalse(updater.chargeIncompleteDownloadRetry(version: version, admittedRetry: true))
1348
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), CapgoUpdater.maxIncompleteDownloadRetries)
1349
+ updater.resetIncompleteDownloadRetryCount(version: version)
1350
+ XCTAssertEqual(updater.incompleteDownloadRetryCount(version: version), 0)
1351
+ XCTAssertFalse(updater.isIntegrityBlockedVersion(version: version))
1055
1352
  }
1056
1353
 
1057
1354
  func testBuildUserAgentStripsNonIsoCharacters() {
@@ -2124,6 +2421,36 @@ class CapacitorUpdaterTests: XCTestCase {
2124
2421
  XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
2125
2422
  }
2126
2423
 
2424
+ func testResetToLastSuccessfulBelowNativeFloorFallsBackToBuiltin() {
2425
+ let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
2426
+ let resetImplementation = ResetTrackingCapgoUpdater()
2427
+ // A native upgrade to 2.0.0 left a 1.5.0 last successful bundle behind.
2428
+ resetImplementation.versionBuild = "2.0.0"
2429
+ resetImplementation.fallbackBundleValue = BundleInfo(
2430
+ id: "fallback-id",
2431
+ version: "1.5.0",
2432
+ status: .SUCCESS,
2433
+ downloaded: Date(),
2434
+ checksum: "fallback"
2435
+ )
2436
+ // Both the replaced default updater and the test updater write pending stats; keep them out of the real file.
2437
+ let statsDirectory = FileManager.default.temporaryDirectory
2438
+ .appendingPathComponent("ResetFloorTests-\(UUID().uuidString)", isDirectory: true)
2439
+ resetPlugin.implementation.pendingStatsDirectoryOverride = statsDirectory
2440
+ resetImplementation.pendingStatsDirectoryOverride = statsDirectory
2441
+ addTeardownBlock {
2442
+ try? FileManager.default.removeItem(at: statsDirectory)
2443
+ }
2444
+
2445
+ resetPlugin.implementation = resetImplementation
2446
+
2447
+ XCTAssertTrue(resetPlugin._reset(toLastSuccessful: true, usePendingBundle: false))
2448
+ XCTAssertEqual(resetImplementation.setCalls, 0)
2449
+ XCTAssertTrue(resetImplementation.prepareResetStateForTransitionCalled)
2450
+ XCTAssertTrue(resetImplementation.finalizeResetTransitionCalled)
2451
+ XCTAssertEqual(resetImplementation.restoreResetStateCalls, 0)
2452
+ }
2453
+
2127
2454
  func testResetToLastSuccessfulRestoresStateWhenSwitchFails() {
2128
2455
  let resetPlugin = ResetTestableCapacitorUpdaterPlugin()
2129
2456
  let resetImplementation = ResetTrackingCapgoUpdater()
@@ -2529,6 +2856,8 @@ class CapacitorUpdaterTests: XCTestCase {
2529
2856
  testPlugin.backgroundDownload()
2530
2857
 
2531
2858
  XCTAssertTrue(testPlugin.notifiedEventNames.contains("noNeedUpdate"))
2859
+ // Retained like updateAvailable and appReady, so a listener attached after the check still sees it.
2860
+ XCTAssertEqual(testPlugin.notifiedEventRetainValues["noNeedUpdate"], true)
2532
2861
  XCTAssertTrue(testPlugin.notifiedEventNames.contains("updateCheckResult"))
2533
2862
  XCTAssertFalse(testPlugin.notifiedEventNames.contains("downloadFailed"))
2534
2863
  XCTAssertFalse(noUpdateImplementation.sentStatsActions.contains("download_fail"))
@@ -2808,6 +3137,10 @@ class CapacitorUpdaterTests: XCTestCase {
2808
3137
  // Per-event listeners were removed in 9.0.0: one bridge call per event, always as updaterEvent.
2809
3138
  XCTAssertEqual(testPlugin.notifiedEvents.map { $0.name }, ["updaterEvent", "updaterEvent"])
2810
3139
  let events = testPlugin.notifiedEvents
3140
+ guard events.count == 2 else {
3141
+ XCTFail("Expected exactly two bridge events, got \(events.count)")
3142
+ return
3143
+ }
2811
3144
  XCTAssertEqual(events[0].data?["type"] as? String, "download")
2812
3145
  XCTAssertEqual((events[0].data?["data"] as? [String: Any])?["percent"] as? Int, 10)
2813
3146
  XCTAssertFalse(events[0].retain)
@@ -3097,6 +3430,14 @@ class CapacitorUpdaterTests: XCTestCase {
3097
3430
  implementation.latestResponse = makeOnlyDownloadLatest()
3098
3431
  implementation.downloadedBundleValue = makeOnlyDownloadBundle()
3099
3432
  let testPlugin = SplashTimeoutCapacitorUpdaterPlugin()
3433
+ // Both the replaced default updater and the test updater write pending stats; keep them out of the real file.
3434
+ let statsDirectory = FileManager.default.temporaryDirectory
3435
+ .appendingPathComponent("SplashTimeoutTests-\(UUID().uuidString)", isDirectory: true)
3436
+ testPlugin.implementation.pendingStatsDirectoryOverride = statsDirectory
3437
+ implementation.pendingStatsDirectoryOverride = statsDirectory
3438
+ addTeardownBlock {
3439
+ try? FileManager.default.removeItem(at: statsDirectory)
3440
+ }
3100
3441
  testPlugin.implementation = implementation
3101
3442
  testPlugin.configureDirectUpdateModeForTesting(mode)
3102
3443
  testPlugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
@@ -3163,6 +3504,20 @@ class CapacitorUpdaterTests: XCTestCase {
3163
3504
  assertDeferredBundleInstallsOnNextBackground(plugin: testPlugin, implementation: implementation, expectedBundleId: "downloaded-id")
3164
3505
  }
3165
3506
 
3507
+ /// Control for the expired case: without a splash timeout, `always` installs the download immediately.
3508
+ func testUnexpiredAlwaysDownloadInstallsImmediately() throws {
3509
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin(mode: "always")
3510
+ defer { clearDelayStorage() }
3511
+
3512
+ testPlugin.backgroundDownload()
3513
+
3514
+ XCTAssertEqual(implementation.downloadCalls, 1)
3515
+ XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
3516
+ XCTAssertEqual(testPlugin.reloadCalls, 1)
3517
+ XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
3518
+ XCTAssertNil(implementation.lastSetNextBundleId)
3519
+ }
3520
+
3166
3521
  func testExpiredLaunchCachedBundleStaysDeferredAfterBackgroundAndForeground() throws {
3167
3522
  let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3168
3523
  implementation.existingBundleValue = makeOnlyDownloadBundle()
@@ -3208,105 +3563,516 @@ class CapacitorUpdaterTests: XCTestCase {
3208
3563
  XCTAssertNil(implementation.lastSetNextBundleId)
3209
3564
  }
3210
3565
 
3211
- func testLaterAlwaysDownloadCanInstallAfterEarlierSplashTimeout() throws {
3212
- let (testPlugin, implementation) = try makeSplashTimeoutPlugin(mode: "always")
3213
- defer { implementation.onDownloadStart = nil; clearDelayStorage() }
3214
- implementation.onDownloadStart = { self.resumeAfterSplashTimeout(testPlugin) }
3215
- testPlugin.backgroundDownload()
3216
- XCTAssertEqual(testPlugin.reloadCalls, 0)
3566
+ private func makeNextCall(id: String, onResolve: @escaping () -> Void) -> CAPPluginCall? {
3567
+ CAPPluginCall(
3568
+ callbackId: "next-during-direct-reload-\(id)",
3569
+ options: ["id": id],
3570
+ success: { _, _ in onResolve() },
3571
+ error: { _ in }
3572
+ )
3573
+ }
3574
+
3575
+ func testDirectUpdateKeepsNextBundleQueuedByJsDuringReload() throws {
3576
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3577
+ defer { testPlugin.onReload = nil; clearDelayStorage() }
3578
+ var jsNextResolved = false
3579
+ testPlugin.onReload = {
3580
+ // JS queues another bundle while the direct update's reload is in flight.
3581
+ guard let call = self.makeNextCall(id: BundleInfo.ID_BUILTIN, onResolve: { jsNextResolved = true }) else {
3582
+ XCTFail("could not build next() call")
3583
+ return
3584
+ }
3585
+ testPlugin.next(call)
3586
+ }
3217
3587
 
3218
- implementation.onDownloadStart = nil
3219
3588
  testPlugin.backgroundDownload()
3220
3589
 
3590
+ XCTAssertTrue(jsNextResolved)
3221
3591
  XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
3222
3592
  XCTAssertEqual(testPlugin.reloadCalls, 1)
3593
+ // The direct update still completes the activation of 2.0.0 and publishes it...
3223
3594
  XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
3595
+ XCTAssertTrue(testPlugin.notifiedEventNames.contains("set"))
3596
+ // ...but keeps the bundle the app queued instead of clearing it.
3597
+ XCTAssertEqual(implementation.getNextBundle()?.getId(), BundleInfo.ID_BUILTIN)
3224
3598
  }
3225
3599
 
3226
- func testLaunchSplashDoesNotScheduleTimeoutAfterOnLaunchDirectUpdateConsumed() {
3227
- plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
3228
- plugin.configureDirectUpdateModeForTesting("onLaunch", onLaunchDirectUpdateUsed: true)
3600
+ func testDirectUpdateRollsBackBundleMarkedErrorDuringReload() throws {
3601
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3602
+ // The rollback restores persisted reset state, which logs through the updater.
3603
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3604
+ let savedResetState = implementation.captureResetState()
3605
+ defer {
3606
+ testPlugin.onReload = nil
3607
+ implementation.restoreResetState(savedResetState)
3608
+ clearDelayStorage()
3609
+ }
3610
+ let downloadedId = try XCTUnwrap(implementation.downloadedBundleValue?.getId())
3611
+ let downloadedVersion = try XCTUnwrap(implementation.downloadedBundleValue?.getVersionName())
3612
+ testPlugin.onReload = {
3613
+ // setBundleError fails the bundle while its direct-update reload is in flight.
3614
+ implementation.storedBundleInfoOverrides[downloadedId] = BundleInfo(
3615
+ id: downloadedId,
3616
+ version: downloadedVersion,
3617
+ status: .ERROR,
3618
+ downloaded: Date(),
3619
+ checksum: "abc"
3620
+ )
3621
+ }
3229
3622
 
3230
- plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
3623
+ testPlugin.backgroundDownload()
3231
3624
 
3232
- XCTAssertFalse(plugin.hasSplashscreenTimeoutScheduledForTesting())
3625
+ XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
3626
+ XCTAssertFalse(testPlugin.notifiedEventNames.contains("set"))
3627
+ XCTAssertNil(implementation.lastSetNextBundleId)
3628
+ XCTAssertNil(implementation.getNextBundle())
3233
3629
  }
3234
3630
 
3235
- func testLaunchSplashTimeoutDoesNotConsumeAtInstallDirectUpdateWindow() {
3236
- plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
3237
- plugin.configureDirectUpdateModeForTesting("atInstall", onLaunchDirectUpdateUsed: false)
3238
- plugin.setWasRecentlyInstalledOrUpdatedForTesting(true)
3631
+ func testDirectUpdateIsSupersededByJsReloadDuringItsReload() throws {
3632
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3633
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3634
+ let savedResetState = implementation.captureResetState()
3635
+ defer {
3636
+ testPlugin.onReload = nil
3637
+ implementation.restoreResetState(savedResetState)
3638
+ clearDelayStorage()
3639
+ }
3640
+ let directVersion = try XCTUnwrap(implementation.downloadedBundleValue?.getVersionName())
3641
+ var jsReloadStarted = false
3642
+ var jsReloadResolved = false
3643
+ testPlugin.onReload = {
3644
+ guard !jsReloadStarted else {
3645
+ return
3646
+ }
3647
+ jsReloadStarted = true
3648
+ // While the direct update reloads, JS queues the builtin bundle and calls reload(), which activates it.
3649
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3650
+ let call = CAPPluginCall(
3651
+ callbackId: "reload-during-direct-update",
3652
+ options: [:],
3653
+ success: { _, _ in jsReloadResolved = true },
3654
+ error: { _ in XCTFail("reload() should apply the queued bundle") }
3655
+ )
3656
+ if let call {
3657
+ testPlugin.reload(call)
3658
+ }
3659
+ }
3239
3660
 
3240
- plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
3661
+ testPlugin.backgroundDownload()
3241
3662
 
3242
- XCTAssertTrue(plugin.hasSplashscreenTimeoutScheduledForTesting())
3243
- XCTAssertTrue(plugin.shouldUseDirectUpdateForTesting())
3663
+ XCTAssertTrue(jsReloadResolved)
3664
+ let setBundleVersions = testPlugin.notifiedEvents
3665
+ .map { decodeUpdaterEvent($0.name, data: $0.data) }
3666
+ .filter { $0.name == "set" }
3667
+ .compactMap { ($0.data?["bundle"] as? [String: Any])?["version"] as? String }
3668
+ // Only reload() publishes its activation; the superseded direct update must not emit set(2.0.0) after it.
3669
+ XCTAssertFalse(setBundleVersions.contains(directVersion))
3670
+ XCTAssertEqual(setBundleVersions.count, 1)
3244
3671
  }
3245
3672
 
3246
- func testShowSplashscreenOptionsDisableAutoHide() {
3247
- let options = plugin.splashscreenOptionsForTesting(methodName: "show")
3248
-
3249
- XCTAssertEqual(options["autoHide"] as? Bool, false)
3250
- XCTAssertEqual(options["fadeInDuration"] as? Int, 0)
3251
- }
3673
+ func testDirectUpdateIsSupersededByBackgroundInstallDuringItsReload() throws {
3674
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3675
+ defer { testPlugin.onReload = nil; clearDelayStorage() }
3676
+ let builtin = implementation.builtinBundleValue
3677
+ let directVersion = try XCTUnwrap(implementation.downloadedBundleValue?.getVersionName())
3678
+ var backgroundInstalled = false
3679
+ testPlugin.onReload = {
3680
+ guard !backgroundInstalled else {
3681
+ return
3682
+ }
3683
+ backgroundInstalled = true
3684
+ // While the direct update reloads, the app goes to background and installs a queued bundle from
3685
+ // another thread, as the background-task path does.
3686
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3687
+ var installed = false
3688
+ let installDone = DispatchSemaphore(value: 0)
3689
+ DispatchQueue.global().async {
3690
+ installed = testPlugin.installNextForTesting()
3691
+ installDone.signal()
3692
+ }
3693
+ XCTAssertEqual(installDone.wait(timeout: .now() + 5), .success)
3694
+ XCTAssertTrue(installed)
3695
+ }
3252
3696
 
3253
- func testHideSplashscreenOptionsStayEmpty() {
3254
- let options = plugin.splashscreenOptionsForTesting(methodName: "hide")
3697
+ testPlugin.backgroundDownload()
3255
3698
 
3256
- XCTAssertTrue(options.isEmpty)
3699
+ XCTAssertTrue(backgroundInstalled)
3700
+ XCTAssertEqual(implementation.currentBundleValue.getId(), builtin.getId())
3701
+ let setBundleVersions = testPlugin.notifiedEvents
3702
+ .map { decodeUpdaterEvent($0.name, data: $0.data) }
3703
+ .filter { $0.name == "set" }
3704
+ .compactMap { ($0.data?["bundle"] as? [String: Any])?["version"] as? String }
3705
+ XCTAssertFalse(setBundleVersions.contains(directVersion))
3257
3706
  }
3258
3707
 
3259
- func testSplashscreenInvocationTokenRejectsStaleRequests() {
3260
- XCTAssertTrue(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
3708
+ func testBackgroundInstallIsSupersededByJsReloadDuringItsReload() throws {
3709
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3710
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3711
+ let savedResetState = implementation.captureResetState()
3712
+ defer {
3713
+ testPlugin.onReload = nil
3714
+ implementation.restoreResetState(savedResetState)
3715
+ clearDelayStorage()
3716
+ }
3717
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3718
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3719
+ var jsReloadStarted = false
3720
+ var jsReloadResolved = false
3721
+ testPlugin.onReload = {
3722
+ guard !jsReloadStarted else {
3723
+ return
3724
+ }
3725
+ jsReloadStarted = true
3726
+ // While the background install reloads, JS queues the builtin bundle and calls reload(), which activates it.
3727
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3728
+ let call = CAPPluginCall(
3729
+ callbackId: "reload-during-background-install",
3730
+ options: [:],
3731
+ success: { _, _ in jsReloadResolved = true },
3732
+ error: { _ in XCTFail("reload() should apply the queued bundle") }
3733
+ )
3734
+ if let call {
3735
+ testPlugin.reload(call)
3736
+ }
3737
+ }
3261
3738
 
3262
- plugin.advanceSplashscreenInvocationTokenForTesting()
3739
+ XCTAssertFalse(testPlugin.installNextForTesting())
3263
3740
 
3264
- XCTAssertFalse(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
3741
+ XCTAssertTrue(jsReloadResolved)
3742
+ XCTAssertTrue(implementation.getCurrentBundle().isBuiltin())
3743
+ let setBundleVersions = testPlugin.notifiedEvents
3744
+ .map { decodeUpdaterEvent($0.name, data: $0.data) }
3745
+ .filter { $0.name == "set" }
3746
+ .compactMap { ($0.data?["bundle"] as? [String: Any])?["version"] as? String }
3747
+ // Only reload() publishes its activation; the superseded install must not emit a stale set event after it.
3748
+ XCTAssertFalse(setBundleVersions.contains(downloaded.getVersionName()))
3749
+ XCTAssertEqual(setBundleVersions.count, 1)
3265
3750
  }
3266
3751
 
3267
- func testDelayUpdateUtilsSetMultiDelayStoresMultipleConditions() throws {
3268
- let utils = try makeDelayUpdateUtils()
3269
- clearDelayStorage()
3270
- defer { clearDelayStorage() }
3271
- let json = try makeDelayConditionsJSON()
3752
+ func testJsReloadIsSupersededByBackgroundInstallDuringItsReload() throws {
3753
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3754
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3755
+ let savedResetState = implementation.captureResetState()
3756
+ defer {
3757
+ testPlugin.onReload = nil
3758
+ implementation.restoreResetState(savedResetState)
3759
+ clearDelayStorage()
3760
+ }
3761
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3762
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3763
+ var backgroundInstalled = false
3764
+ testPlugin.onReload = {
3765
+ guard !backgroundInstalled else {
3766
+ return
3767
+ }
3768
+ backgroundInstalled = true
3769
+ // While reload() applies the queued bundle, the app goes to background and installs another queued bundle.
3770
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3771
+ XCTAssertTrue(testPlugin.installNextForTesting())
3772
+ }
3773
+ var jsReloadResolved = false
3774
+ let call = try XCTUnwrap(CAPPluginCall(
3775
+ callbackId: "reload-superseded-by-background-install",
3776
+ options: [:],
3777
+ success: { _, _ in jsReloadResolved = true },
3778
+ error: { _ in XCTFail("reload() should resolve once its reload succeeded") }
3779
+ ))
3272
3780
 
3273
- XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
3274
- XCTAssertEqual(UserDefaults.standard.string(forKey: delayPreferencesKey), json)
3275
- }
3781
+ testPlugin.reload(call)
3276
3782
 
3277
- func testDelayUpdateUtilsCheckCancelDelayKilledKeepsOtherConditions() throws {
3278
- let utils = try makeDelayUpdateUtils()
3279
- clearDelayStorage()
3280
- defer { clearDelayStorage() }
3281
- let json = try makeDelayConditionsJSON()
3282
- XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
3783
+ XCTAssertTrue(backgroundInstalled)
3784
+ XCTAssertTrue(jsReloadResolved)
3785
+ XCTAssertTrue(implementation.currentBundleValue.isBuiltin())
3786
+ let setBundleVersions = testPlugin.notifiedEvents
3787
+ .map { decodeUpdaterEvent($0.name, data: $0.data) }
3788
+ .filter { $0.name == "set" }
3789
+ .compactMap { ($0.data?["bundle"] as? [String: Any])?["version"] as? String }
3790
+ // Only the background install publishes its activation; the superseded reload must not emit set(2.0.0) after it.
3791
+ XCTAssertFalse(setBundleVersions.contains(downloaded.getVersionName()))
3792
+ XCTAssertEqual(setBundleVersions.count, 1)
3793
+ }
3283
3794
 
3284
- utils.checkCancelDelay(source: .killed)
3795
+ func testFailedBackgroundInstallKeepsNextBundleQueuedByJsDuringReload() throws {
3796
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3797
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3798
+ let savedResetState = implementation.captureResetState()
3799
+ defer {
3800
+ testPlugin.onReload = nil
3801
+ testPlugin.reloadResult = nil
3802
+ implementation.restoreResetState(savedResetState)
3803
+ clearDelayStorage()
3804
+ }
3805
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3806
+ let previousActiveId = implementation.currentBundleValue.getId()
3807
+ XCTAssertNotEqual(previousActiveId, downloaded.getId())
3808
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3809
+ var jsNextResolved = false
3810
+ testPlugin.reloadResult = { _ in false }
3811
+ testPlugin.onReload = {
3812
+ // JS queues another bundle while the background install's reload is in flight; then the reload fails.
3813
+ guard let call = self.makeNextCall(id: BundleInfo.ID_BUILTIN, onResolve: { jsNextResolved = true }) else {
3814
+ XCTFail("could not build next() call")
3815
+ return
3816
+ }
3817
+ testPlugin.next(call)
3818
+ }
3285
3819
 
3286
- let stored = try XCTUnwrap(UserDefaults.standard.string(forKey: delayPreferencesKey))
3287
- let storedData = try XCTUnwrap(stored.data(using: .utf8))
3288
- let parsed = try XCTUnwrap(JSONSerialization.jsonObject(with: storedData) as? [[String: String]])
3820
+ XCTAssertFalse(testPlugin.installNextForTesting())
3289
3821
 
3290
- XCTAssertEqual(parsed.count, 1)
3291
- XCTAssertEqual(parsed.first?["kind"], "background")
3292
- XCTAssertEqual(parsed.first?["value"], "5000")
3822
+ XCTAssertTrue(jsNextResolved)
3823
+ // The rollback must not overwrite the app's newer queue with the pre-install snapshot.
3824
+ XCTAssertEqual(implementation.captureResetState().nextBundleId, BundleInfo.ID_BUILTIN)
3825
+ XCTAssertFalse(testPlugin.notifiedEventNames.contains("set"))
3826
+ // The failed activation is rolled back to the previously active bundle.
3827
+ XCTAssertEqual(implementation.getCurrentBundle().getId(), previousActiveId)
3293
3828
  }
3294
3829
 
3295
- func testDelayUpdateUtilsCheckCancelDelayOrModeKilledCancelsImmediately() throws {
3296
- let utils = try makeDelayUpdateUtils()
3297
- clearDelayStorage()
3298
- defer { clearDelayStorage() }
3299
- let json = try makeDelayConditionsJSON()
3300
- XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
3301
- XCTAssertTrue(utils.setConditionMode(DelayUpdateUtils.DELAY_CONDITION_MODE_OR))
3830
+ func testFailedBackgroundInstallKeepsBuiltinQueuedByUpdateCheckDuringReload() throws {
3831
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3832
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3833
+ let savedResetState = implementation.captureResetState()
3834
+ defer {
3835
+ testPlugin.onReload = nil
3836
+ testPlugin.reloadResult = nil
3837
+ implementation.restoreResetState(savedResetState)
3838
+ clearDelayStorage()
3839
+ }
3840
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3841
+ let previousActiveId = implementation.currentBundleValue.getId()
3842
+ XCTAssertNotEqual(previousActiveId, downloaded.getId())
3843
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3844
+ testPlugin.reloadResult = { _ in false }
3845
+ testPlugin.onReload = {
3846
+ // An update check whose latest version is builtin queues it while the background install reloads.
3847
+ XCTAssertTrue(testPlugin.queueBuiltinBundleAsNextForTesting())
3848
+ }
3302
3849
 
3303
- utils.checkCancelDelay(source: .killed)
3850
+ XCTAssertFalse(testPlugin.installNextForTesting())
3304
3851
 
3305
- XCTAssertNil(UserDefaults.standard.string(forKey: delayPreferencesKey))
3306
- XCTAssertNil(UserDefaults.standard.string(forKey: delayConditionModeKey))
3852
+ XCTAssertEqual(implementation.captureResetState().nextBundleId, BundleInfo.ID_BUILTIN)
3853
+ // The failed activation is rolled back to the previously active bundle.
3854
+ XCTAssertEqual(implementation.getCurrentBundle().getId(), previousActiveId)
3307
3855
  }
3308
3856
 
3309
- func testDelayUpdateUtilsSetConditionModePersistsValue() throws {
3857
+ func testFailedJsReloadKeepsNextBundleQueuedByJsDuringReload() throws {
3858
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3859
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3860
+ let savedResetState = implementation.captureResetState()
3861
+ defer {
3862
+ testPlugin.onReload = nil
3863
+ testPlugin.reloadResult = nil
3864
+ implementation.restoreResetState(savedResetState)
3865
+ clearDelayStorage()
3866
+ }
3867
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3868
+ let previousActiveId = implementation.currentBundleValue.getId()
3869
+ XCTAssertNotEqual(previousActiveId, downloaded.getId())
3870
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3871
+ var jsNextResolved = false
3872
+ testPlugin.reloadResult = { _ in false }
3873
+ testPlugin.onReload = {
3874
+ guard let call = self.makeNextCall(id: BundleInfo.ID_BUILTIN, onResolve: { jsNextResolved = true }) else {
3875
+ XCTFail("could not build next() call")
3876
+ return
3877
+ }
3878
+ testPlugin.next(call)
3879
+ }
3880
+ var reloadRejected = false
3881
+ let call = try XCTUnwrap(CAPPluginCall(
3882
+ callbackId: "failed-reload-with-next",
3883
+ options: [:],
3884
+ success: { _, _ in XCTFail("reload() should reject when its reload fails") },
3885
+ error: { _ in reloadRejected = true }
3886
+ ))
3887
+
3888
+ testPlugin.reload(call)
3889
+
3890
+ XCTAssertTrue(jsNextResolved)
3891
+ XCTAssertTrue(reloadRejected)
3892
+ XCTAssertEqual(implementation.captureResetState().nextBundleId, BundleInfo.ID_BUILTIN)
3893
+ // The failed activation is rolled back to the previously active bundle.
3894
+ XCTAssertEqual(implementation.getCurrentBundle().getId(), previousActiveId)
3895
+ }
3896
+
3897
+ func testFailedBackgroundInstallDoesNotRevertConcurrentJsReload() throws {
3898
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3899
+ implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3900
+ let savedResetState = implementation.captureResetState()
3901
+ defer {
3902
+ testPlugin.onReload = nil
3903
+ testPlugin.reloadResult = nil
3904
+ implementation.restoreResetState(savedResetState)
3905
+ clearDelayStorage()
3906
+ }
3907
+ let downloaded = try XCTUnwrap(implementation.downloadedBundleValue)
3908
+ XCTAssertTrue(implementation.setNextBundle(next: downloaded.getId()))
3909
+ // The background install's own reload (call 1) fails; the nested JS reload (call 2) succeeds.
3910
+ testPlugin.reloadResult = { call in call != 1 }
3911
+ var stateAfterJsReload: CapgoUpdater.ResetState?
3912
+ testPlugin.onReload = {
3913
+ guard stateAfterJsReload == nil, testPlugin.reloadCalls == 1 else {
3914
+ return
3915
+ }
3916
+ // JS queues the builtin bundle and reloads into it while the background install reloads.
3917
+ _ = implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
3918
+ if let call = CAPPluginCall(
3919
+ callbackId: "reload-during-failed-background-install",
3920
+ options: [:],
3921
+ success: { _, _ in },
3922
+ error: { _ in XCTFail("reload() should apply the queued bundle") }
3923
+ ) {
3924
+ testPlugin.reload(call)
3925
+ }
3926
+ stateAfterJsReload = implementation.captureResetState()
3927
+ }
3928
+
3929
+ XCTAssertFalse(testPlugin.installNextForTesting())
3930
+
3931
+ let expected = try XCTUnwrap(stateAfterJsReload)
3932
+ let actual = implementation.captureResetState()
3933
+ // The failed install must not roll back over the activation JS completed during its reload.
3934
+ XCTAssertEqual(actual.currentBundlePath, expected.currentBundlePath)
3935
+ XCTAssertEqual(actual.fallbackBundleId, expected.fallbackBundleId)
3936
+ XCTAssertEqual(actual.nextBundleId, expected.nextBundleId)
3937
+ // The bundle JS activated stays active.
3938
+ XCTAssertTrue(implementation.getCurrentBundle().isBuiltin())
3939
+ }
3940
+
3941
+ func testCompletedDownloadFingerprintsArePrunedForBundlesWithoutStoredRecord() {
3942
+ // Ids with no stored record behave like bundles removed by autoDeletePrevious; getBundleInfo(id:)
3943
+ // returns a PENDING placeholder for them, which previously kept their fingerprints forever.
3944
+ plugin.implementation.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
3945
+ let staleIds = (0..<40).map { "pruned-fingerprint-\($0)-\(UUID().uuidString)" }
3946
+ for id in staleIds {
3947
+ plugin.recordCompletedZipDownloadForTesting(bundleId: id)
3948
+ }
3949
+
3950
+ // Pruning runs once the map exceeds 16 entries and always keeps the id just recorded.
3951
+ let remaining = plugin.completedDownloadFingerprintIdsForTesting
3952
+ XCTAssertLessThanOrEqual(remaining.count, 17)
3953
+ XCTAssertTrue(remaining.contains(staleIds[staleIds.count - 1]))
3954
+ }
3955
+
3956
+ func testDirectUpdateIgnoresRejectedNextDuringReload() throws {
3957
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin()
3958
+ defer { testPlugin.onReload = nil; clearDelayStorage() }
3959
+ var rejectedNextResolved = false
3960
+ testPlugin.onReload = {
3961
+ // A next() for a bundle that is not installed changes nothing and must not invalidate the update.
3962
+ guard let call = self.makeNextCall(id: "not-installed", onResolve: { rejectedNextResolved = true }) else {
3963
+ XCTFail("could not build next() call")
3964
+ return
3965
+ }
3966
+ testPlugin.next(call)
3967
+ }
3968
+
3969
+ testPlugin.backgroundDownload()
3970
+
3971
+ XCTAssertFalse(rejectedNextResolved)
3972
+ XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
3973
+ XCTAssertTrue(testPlugin.notifiedEventNames.contains("set"))
3974
+ XCTAssertNil(implementation.getNextBundle())
3975
+ }
3976
+
3977
+ func testLaterAlwaysDownloadCanInstallAfterEarlierSplashTimeout() throws {
3978
+ let (testPlugin, implementation) = try makeSplashTimeoutPlugin(mode: "always")
3979
+ defer { implementation.onDownloadStart = nil; clearDelayStorage() }
3980
+ implementation.onDownloadStart = { self.resumeAfterSplashTimeout(testPlugin) }
3981
+ testPlugin.backgroundDownload()
3982
+ XCTAssertEqual(testPlugin.reloadCalls, 0)
3983
+
3984
+ implementation.onDownloadStart = nil
3985
+ testPlugin.backgroundDownload()
3986
+
3987
+ XCTAssertEqual(implementation.stagePendingReloadCalls, 1)
3988
+ XCTAssertEqual(testPlugin.reloadCalls, 1)
3989
+ XCTAssertEqual(implementation.currentBundleValue.getVersionName(), "2.0.0")
3990
+ }
3991
+
3992
+ func testLaunchSplashDoesNotScheduleTimeoutAfterOnLaunchDirectUpdateConsumed() {
3993
+ plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
3994
+ plugin.configureDirectUpdateModeForTesting("onLaunch", onLaunchDirectUpdateUsed: true)
3995
+
3996
+ plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
3997
+
3998
+ XCTAssertFalse(plugin.hasSplashscreenTimeoutScheduledForTesting())
3999
+ }
4000
+
4001
+ func testLaunchSplashTimeoutDoesNotConsumeAtInstallDirectUpdateWindow() {
4002
+ plugin.configureAutoSplashscreenForTesting(enabled: true, timeoutMs: 5000)
4003
+ plugin.configureDirectUpdateModeForTesting("atInstall", onLaunchDirectUpdateUsed: false)
4004
+ plugin.setWasRecentlyInstalledOrUpdatedForTesting(true)
4005
+
4006
+ plugin.scheduleLaunchSplashscreenTimeoutIfNeededForTesting()
4007
+
4008
+ XCTAssertTrue(plugin.hasSplashscreenTimeoutScheduledForTesting())
4009
+ XCTAssertTrue(plugin.shouldUseDirectUpdateForTesting())
4010
+ }
4011
+
4012
+ func testShowSplashscreenOptionsDisableAutoHide() {
4013
+ let options = plugin.splashscreenOptionsForTesting(methodName: "show")
4014
+
4015
+ XCTAssertEqual(options["autoHide"] as? Bool, false)
4016
+ XCTAssertEqual(options["fadeInDuration"] as? Int, 0)
4017
+ }
4018
+
4019
+ func testHideSplashscreenOptionsStayEmpty() {
4020
+ let options = plugin.splashscreenOptionsForTesting(methodName: "hide")
4021
+
4022
+ XCTAssertTrue(options.isEmpty)
4023
+ }
4024
+
4025
+ func testSplashscreenInvocationTokenRejectsStaleRequests() {
4026
+ XCTAssertTrue(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
4027
+
4028
+ plugin.advanceSplashscreenInvocationTokenForTesting()
4029
+
4030
+ XCTAssertFalse(plugin.isCurrentSplashscreenInvocationTokenForTesting(0))
4031
+ }
4032
+
4033
+ func testDelayUpdateUtilsSetMultiDelayStoresMultipleConditions() throws {
4034
+ let utils = try makeDelayUpdateUtils()
4035
+ clearDelayStorage()
4036
+ defer { clearDelayStorage() }
4037
+ let json = try makeDelayConditionsJSON()
4038
+
4039
+ XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
4040
+ XCTAssertEqual(UserDefaults.standard.string(forKey: delayPreferencesKey), json)
4041
+ }
4042
+
4043
+ func testDelayUpdateUtilsCheckCancelDelayKilledKeepsOtherConditions() throws {
4044
+ let utils = try makeDelayUpdateUtils()
4045
+ clearDelayStorage()
4046
+ defer { clearDelayStorage() }
4047
+ let json = try makeDelayConditionsJSON()
4048
+ XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
4049
+
4050
+ utils.checkCancelDelay(source: .killed)
4051
+
4052
+ let stored = try XCTUnwrap(UserDefaults.standard.string(forKey: delayPreferencesKey))
4053
+ let storedData = try XCTUnwrap(stored.data(using: .utf8))
4054
+ let parsed = try XCTUnwrap(JSONSerialization.jsonObject(with: storedData) as? [[String: String]])
4055
+
4056
+ XCTAssertEqual(parsed.count, 1)
4057
+ XCTAssertEqual(parsed.first?["kind"], "background")
4058
+ XCTAssertEqual(parsed.first?["value"], "5000")
4059
+ }
4060
+
4061
+ func testDelayUpdateUtilsCheckCancelDelayOrModeKilledCancelsImmediately() throws {
4062
+ let utils = try makeDelayUpdateUtils()
4063
+ clearDelayStorage()
4064
+ defer { clearDelayStorage() }
4065
+ let json = try makeDelayConditionsJSON()
4066
+ XCTAssertTrue(utils.setMultiDelay(delayConditions: json))
4067
+ XCTAssertTrue(utils.setConditionMode(DelayUpdateUtils.DELAY_CONDITION_MODE_OR))
4068
+
4069
+ utils.checkCancelDelay(source: .killed)
4070
+
4071
+ XCTAssertNil(UserDefaults.standard.string(forKey: delayPreferencesKey))
4072
+ XCTAssertNil(UserDefaults.standard.string(forKey: delayConditionModeKey))
4073
+ }
4074
+
4075
+ func testDelayUpdateUtilsSetConditionModePersistsValue() throws {
3310
4076
  let utils = try makeDelayUpdateUtils()
3311
4077
  clearDelayStorage()
3312
4078
  defer { clearDelayStorage() }
@@ -3779,6 +4545,7 @@ class CapacitorUpdaterTests: XCTestCase {
3779
4545
  wait(for: [expectation], timeout: 2.0)
3780
4546
  XCTAssertEqual(testPlugin.appReadyNotifiedOnMainThread, true)
3781
4547
  XCTAssertEqual(testPlugin.appReadyRetainUntilConsumed, true)
4548
+ XCTAssertEqual(testPlugin.appReadyRawEventName, CapacitorUpdaterPlugin.updaterEvent)
3782
4549
  }
3783
4550
 
3784
4551
  func testSendReadyToJsWaitsOnlyWhenArmed() {
@@ -3902,4 +4669,1865 @@ class CapacitorUpdaterTests: XCTestCase {
3902
4669
  XCTAssertFalse(script.contains("plugin.notifyAppReady="))
3903
4670
  }
3904
4671
 
4672
+ func testRunGetLatestWorkUsesUserInitiatedQoS() {
4673
+ let basePlugin = CapacitorUpdaterPlugin()
4674
+ let executed = expectation(description: "runGetLatestWork executed")
4675
+ var observedQoS: qos_class_t = QOS_CLASS_UNSPECIFIED
4676
+
4677
+ basePlugin.runGetLatestWork {
4678
+ observedQoS = qos_class_self()
4679
+ executed.fulfill()
4680
+ }
4681
+
4682
+ wait(for: [executed], timeout: 5.0)
4683
+ XCTAssertGreaterThanOrEqual(observedQoS.rawValue, QOS_CLASS_USER_INITIATED.rawValue)
4684
+ XCTAssertNotEqual(observedQoS, QOS_CLASS_BACKGROUND)
4685
+ }
4686
+
4687
+ func testConcurrentJsDownloadAndBackgroundDownloadCoalesceWithoutDeletingActiveBundle() throws {
4688
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
4689
+ CryptoCipher.setLogger(testLogger)
4690
+ let downloadEntered = OnceSignal()
4691
+ let waiterJoined = OnceSignal()
4692
+ let allowDownloadFinish = OnceSignal()
4693
+ let backgroundFinished = expectation(description: "backgroundDownload finished")
4694
+ let jsDownloadFinished = expectation(description: "JS download resolved")
4695
+
4696
+ let current = BundleInfo(
4697
+ id: "current-id",
4698
+ version: "1.0.0",
4699
+ status: .SUCCESS,
4700
+ downloaded: Date(),
4701
+ checksum: "current-checksum"
4702
+ )
4703
+ let inFlightDownloading = BundleInfo(
4704
+ id: "in-flight-id",
4705
+ version: "2.0.0",
4706
+ status: .DOWNLOADING,
4707
+ downloaded: Date(),
4708
+ checksum: ""
4709
+ )
4710
+ let completedBundle = BundleInfo(
4711
+ id: "fresh-id",
4712
+ version: "2.0.0",
4713
+ status: .PENDING,
4714
+ downloaded: Date(),
4715
+ checksum: "abc123"
4716
+ )
4717
+ let latest = AppVersion()
4718
+ latest.version = "2.0.0"
4719
+ latest.url = "https://example.com/update-2.0.0.zip"
4720
+ latest.checksum = "abc123"
4721
+
4722
+ let updater = CoalescingDownloadCapgoUpdater()
4723
+ updater.setLogger(testLogger)
4724
+ updater.currentBundleValue = current
4725
+ updater.latestResponse = latest
4726
+ updater.downloadedBundleValue = completedBundle
4727
+ updater.onDownloadStart = {
4728
+ updater.existingBundleValue = inFlightDownloading
4729
+ downloadEntered.signal()
4730
+ _ = allowDownloadFinish.wait(timeout: .now() + 5.0)
4731
+ updater.existingBundleValue = completedBundle
4732
+ }
4733
+ updater.onSetNextBundle = {
4734
+ backgroundFinished.fulfill()
4735
+ }
4736
+
4737
+ let concurrentPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
4738
+ concurrentPlugin.implementation = updater
4739
+ concurrentPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
4740
+ concurrentPlugin.setUpdateUrlForTesting("https://example.com/channel")
4741
+ concurrentPlugin.onCoalesceWaiterJoinedForTesting = { version in
4742
+ if version == "2.0.0" {
4743
+ waiterJoined.signal()
4744
+ }
4745
+ }
4746
+
4747
+ var resolvedId: String?
4748
+ let call = try XCTUnwrap(CAPPluginCall(
4749
+ callbackId: "coalesce-js-download",
4750
+ options: [
4751
+ "url": "https://example.com/update-2.0.0.zip",
4752
+ "version": "2.0.0",
4753
+ "checksum": "abc123"
4754
+ ],
4755
+ success: { result, _ in
4756
+ resolvedId = result?.data?["id"] as? String
4757
+ jsDownloadFinished.fulfill()
4758
+ },
4759
+ error: { error in
4760
+ XCTFail("JS download should coalesce and succeed: \(error?.message ?? "unknown")")
4761
+ jsDownloadFinished.fulfill()
4762
+ }
4763
+ ))
4764
+
4765
+ concurrentPlugin.download(call)
4766
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
4767
+
4768
+ concurrentPlugin.backgroundDownload()
4769
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
4770
+ allowDownloadFinish.signal()
4771
+
4772
+ wait(for: [jsDownloadFinished, backgroundFinished], timeout: 5.0)
4773
+ XCTAssertEqual(resolvedId, "fresh-id")
4774
+ XCTAssertEqual(updater.downloadCalls, 1)
4775
+ XCTAssertEqual(updater.deleteCalls, 0)
4776
+ XCTAssertEqual(updater.lastSetNextBundleId, "fresh-id")
4777
+ }
4778
+
4779
+ func testCoalescedDownloadPropagatesErrorAndClearsInFlightSlotForRetry() throws {
4780
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
4781
+ CryptoCipher.setLogger(testLogger)
4782
+ let downloadEntered = OnceSignal()
4783
+ let waiterJoined = OnceSignal()
4784
+ let allowFailure = OnceSignal()
4785
+ let updater = CoalescingDownloadCapgoUpdater()
4786
+ updater.setLogger(testLogger)
4787
+ updater.currentBundleValue = BundleInfo(
4788
+ id: "current-id",
4789
+ version: "1.0.0",
4790
+ status: .SUCCESS,
4791
+ downloaded: Date(),
4792
+ checksum: "current-checksum"
4793
+ )
4794
+ updater.downloadedBundleValue = nil
4795
+ updater.onDownloadStart = {
4796
+ downloadEntered.signal()
4797
+ _ = allowFailure.wait(timeout: .now() + 5.0)
4798
+ }
4799
+
4800
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
4801
+ testPlugin.implementation = updater
4802
+ testPlugin.onCoalesceWaiterJoinedForTesting = { version in
4803
+ if version == "3.0.0" {
4804
+ waiterJoined.signal()
4805
+ }
4806
+ }
4807
+
4808
+ let firstDone = expectation(description: "first download failed")
4809
+ let secondDone = expectation(description: "coalesced download failed")
4810
+ var firstFailed = false
4811
+ var secondFailed = false
4812
+
4813
+ DispatchQueue.global(qos: .userInitiated).async {
4814
+ do {
4815
+ _ = try testPlugin.downloadBundleForTesting(
4816
+ urlString: "https://example.com/update-3.0.0.zip",
4817
+ version: "3.0.0",
4818
+ sessionKey: "",
4819
+ checksum: "abc123",
4820
+ manifestEntries: nil
4821
+ )
4822
+ } catch {
4823
+ firstFailed = true
4824
+ }
4825
+ firstDone.fulfill()
4826
+ }
4827
+
4828
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
4829
+
4830
+ DispatchQueue.global(qos: .userInitiated).async {
4831
+ do {
4832
+ _ = try testPlugin.downloadBundleForTesting(
4833
+ urlString: "https://example.com/update-3.0.0.zip",
4834
+ version: "3.0.0",
4835
+ sessionKey: "",
4836
+ checksum: "abc123",
4837
+ manifestEntries: nil
4838
+ )
4839
+ } catch {
4840
+ secondFailed = true
4841
+ }
4842
+ secondDone.fulfill()
4843
+ }
4844
+
4845
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
4846
+ allowFailure.signal()
4847
+ wait(for: [firstDone, secondDone], timeout: 5.0)
4848
+
4849
+ XCTAssertTrue(firstFailed)
4850
+ XCTAssertTrue(secondFailed)
4851
+ XCTAssertEqual(updater.downloadCalls, 1)
4852
+
4853
+ // Slot must be cleared so a subsequent retry executes cleanly.
4854
+ let recovered = BundleInfo(
4855
+ id: "recovered-id",
4856
+ version: "3.0.0",
4857
+ status: .PENDING,
4858
+ downloaded: Date(),
4859
+ checksum: "abc123"
4860
+ )
4861
+ updater.downloadedBundleValue = recovered
4862
+ updater.onDownloadStart = nil
4863
+
4864
+ let retryBundle = try testPlugin.downloadBundleForTesting(
4865
+ urlString: "https://example.com/update-3.0.0.zip",
4866
+ version: "3.0.0",
4867
+ sessionKey: "",
4868
+ checksum: "abc123",
4869
+ manifestEntries: nil
4870
+ )
4871
+ XCTAssertEqual(retryBundle.getId(), "recovered-id")
4872
+ XCTAssertEqual(updater.downloadCalls, 2)
4873
+ }
4874
+
4875
+ func testCoalescedDownloadEnforcesHttpsOnlyForJoiningZipAndManifestCallers() throws {
4876
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
4877
+ CryptoCipher.setLogger(testLogger)
4878
+ let downloadEntered = OnceSignal()
4879
+ let allowFinish = OnceSignal()
4880
+
4881
+ let completedBundle = BundleInfo(
4882
+ id: "secure-id",
4883
+ version: "4.0.0",
4884
+ status: .PENDING,
4885
+ downloaded: Date(),
4886
+ checksum: "abc123"
4887
+ )
4888
+ let updater = CoalescingDownloadCapgoUpdater()
4889
+ updater.setLogger(testLogger)
4890
+ updater.httpsOnly = true
4891
+ updater.downloadedBundleValue = completedBundle
4892
+ updater.onDownloadStart = {
4893
+ downloadEntered.signal()
4894
+ _ = allowFinish.wait(timeout: .now() + 5.0)
4895
+ }
4896
+
4897
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
4898
+ testPlugin.implementation = updater
4899
+ var waiterJoinedCount = 0
4900
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in
4901
+ waiterJoinedCount += 1
4902
+ }
4903
+
4904
+ let firstDone = expectation(description: "https download succeeded")
4905
+ DispatchQueue.global(qos: .userInitiated).async {
4906
+ defer { firstDone.fulfill() }
4907
+ do {
4908
+ let bundle = try testPlugin.downloadBundleForTesting(
4909
+ urlString: "https://example.com/update-4.0.0.zip",
4910
+ version: "4.0.0",
4911
+ sessionKey: "",
4912
+ checksum: "abc123",
4913
+ manifestEntries: nil
4914
+ )
4915
+ XCTAssertEqual(bundle.getId(), "secure-id")
4916
+ } catch {
4917
+ XCTFail("HTTPS download should succeed: \(error.localizedDescription)")
4918
+ }
4919
+ }
4920
+
4921
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
4922
+
4923
+ // Plain HTTP zip caller must fail httpsOnly before joining the in-flight HTTPS download.
4924
+ XCTAssertThrowsError(
4925
+ try testPlugin.downloadBundleForTesting(
4926
+ urlString: "http://example.com/update-4.0.0.zip",
4927
+ version: "4.0.0",
4928
+ sessionKey: "",
4929
+ checksum: "abc123",
4930
+ manifestEntries: nil
4931
+ )
4932
+ ) { error in
4933
+ XCTAssertEqual((error as NSError).code, 7)
4934
+ }
4935
+
4936
+ // Manifest caller containing a plain HTTP entry URL must also fail httpsOnly before joining.
4937
+ let insecureManifest = [
4938
+ ManifestEntry(
4939
+ file_name: "index.html",
4940
+ file_hash: "deadbeef",
4941
+ download_url: "http://example.com/index.html"
4942
+ )
4943
+ ]
4944
+ XCTAssertThrowsError(
4945
+ try testPlugin.downloadBundleForTesting(
4946
+ urlString: "https://example.com/manifest-4.0.0",
4947
+ version: "4.0.0",
4948
+ sessionKey: "",
4949
+ checksum: "",
4950
+ manifestEntries: insecureManifest
4951
+ )
4952
+ ) { error in
4953
+ XCTAssertEqual((error as NSError).code, 7)
4954
+ }
4955
+
4956
+ XCTAssertEqual(waiterJoinedCount, 0)
4957
+ allowFinish.signal()
4958
+ wait(for: [firstDone], timeout: 5.0)
4959
+ }
4960
+
4961
+ func testConcurrentManifestAndZipDownloadsSerializeWithoutDeletingCompletedBundle() throws {
4962
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
4963
+ CryptoCipher.setLogger(testLogger)
4964
+ let manifestEntered = OnceSignal()
4965
+ let waiterJoined = OnceSignal()
4966
+ let allowManifestFinish = OnceSignal()
4967
+
4968
+ let current = BundleInfo(
4969
+ id: "current-id",
4970
+ version: "1.0.0",
4971
+ status: .SUCCESS,
4972
+ downloaded: Date(),
4973
+ checksum: "current-checksum"
4974
+ )
4975
+ let manifestBundle = BundleInfo(
4976
+ id: "manifest-id",
4977
+ version: "5.0.0",
4978
+ status: .PENDING,
4979
+ downloaded: Date(),
4980
+ checksum: ""
4981
+ )
4982
+ let zipBundle = BundleInfo(
4983
+ id: "zip-id",
4984
+ version: "5.0.0",
4985
+ status: .PENDING,
4986
+ downloaded: Date(),
4987
+ checksum: "zip-checksum"
4988
+ )
4989
+ let latest = AppVersion()
4990
+ latest.version = "5.0.0"
4991
+ latest.url = "https://example.com/update-5.0.0.zip"
4992
+ latest.checksum = "zip-checksum"
4993
+
4994
+ let updater = CoalescingDownloadCapgoUpdater()
4995
+ updater.setLogger(testLogger)
4996
+ updater.currentBundleValue = current
4997
+ updater.latestResponse = latest
4998
+ updater.downloadedManifestBundleValue = manifestBundle
4999
+ updater.downloadedBundleValue = zipBundle
5000
+ updater.onManifestDownloadStart = {
5001
+ updater.existingBundleValue = BundleInfo(
5002
+ id: "manifest-id",
5003
+ version: "5.0.0",
5004
+ status: .DOWNLOADING,
5005
+ downloaded: Date(),
5006
+ checksum: ""
5007
+ )
5008
+ manifestEntered.signal()
5009
+ _ = allowManifestFinish.wait(timeout: .now() + 5.0)
5010
+ updater.existingBundleValue = manifestBundle
5011
+ }
5012
+ let backgroundFinished = expectation(description: "background zip download finished")
5013
+ updater.onSetNextBundle = {
5014
+ backgroundFinished.fulfill()
5015
+ }
5016
+
5017
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5018
+ testPlugin.implementation = updater
5019
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5020
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5021
+ testPlugin.onCoalesceWaiterJoinedForTesting = { version in
5022
+ if version == "5.0.0" {
5023
+ waiterJoined.signal()
5024
+ }
5025
+ }
5026
+
5027
+ let manifestDone = expectation(description: "manifest download finished")
5028
+ var manifestResultId: String?
5029
+ let manifest = [
5030
+ ManifestEntry(
5031
+ file_name: "index.html",
5032
+ file_hash: "file-hash-1",
5033
+ download_url: "https://example.com/index.html"
5034
+ )
5035
+ ]
5036
+
5037
+ DispatchQueue.global(qos: .userInitiated).async {
5038
+ defer { manifestDone.fulfill() }
5039
+ do {
5040
+ let bundle = try testPlugin.downloadBundleForTesting(
5041
+ urlString: "https://example.com/manifest-5.0.0",
5042
+ version: "5.0.0",
5043
+ sessionKey: "",
5044
+ checksum: "",
5045
+ manifestEntries: manifest
5046
+ )
5047
+ manifestResultId = bundle.getId()
5048
+ } catch {
5049
+ XCTFail("Manifest download should succeed: \(error.localizedDescription)")
5050
+ }
5051
+ }
5052
+
5053
+ XCTAssertEqual(manifestEntered.wait(timeout: .now() + 5.0), .success)
5054
+
5055
+ testPlugin.backgroundDownload()
5056
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5057
+ XCTAssertEqual(updater.downloadCalls, 0)
5058
+
5059
+ allowManifestFinish.signal()
5060
+ wait(for: [manifestDone, backgroundFinished], timeout: 5.0)
5061
+
5062
+ XCTAssertEqual(manifestResultId, "manifest-id")
5063
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5064
+ XCTAssertEqual(updater.downloadCalls, 1)
5065
+ XCTAssertEqual(updater.deleteCalls, 0)
5066
+ XCTAssertEqual(updater.lastSetNextBundleId, "zip-id")
5067
+ }
5068
+
5069
+ func testConcurrentManifestDownloadsCoalesceOnlyWhenManifestMatches() throws {
5070
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5071
+ CryptoCipher.setLogger(testLogger)
5072
+
5073
+ let manifestA = [
5074
+ ManifestEntry(file_name: "index.html.br", file_hash: "hash-index", download_url: "https://cdn-a.example.com/index.html.br"),
5075
+ ManifestEntry(file_name: "app.js", file_hash: "hash-app", download_url: "https://cdn-a.example.com/app.js")
5076
+ ]
5077
+ let manifestAEquivalent = [
5078
+ ManifestEntry(file_name: "app.js", file_hash: "hash-app", download_url: "https://cdn-b.example.com/app.js?sig=2"),
5079
+ ManifestEntry(file_name: "index.html", file_hash: "hash-index", download_url: "https://cdn-b.example.com/index.html?sig=2")
5080
+ ]
5081
+ let manifestB = [
5082
+ ManifestEntry(file_name: "index.html", file_hash: "different-hash", download_url: "https://cdn-a.example.com/index.html")
5083
+ ]
5084
+
5085
+ // 1. Equivalent manifests coalesce into a single download.
5086
+ do {
5087
+ let manifestEntered = OnceSignal()
5088
+ let waiterJoined = OnceSignal()
5089
+ let allowFinish = OnceSignal()
5090
+
5091
+ let updater = CoalescingDownloadCapgoUpdater()
5092
+ updater.setLogger(testLogger)
5093
+ updater.downloadedManifestBundleValue = BundleInfo(
5094
+ id: "manifest-shared",
5095
+ version: "6.0.0",
5096
+ status: .PENDING,
5097
+ downloaded: Date(),
5098
+ checksum: ""
5099
+ )
5100
+ updater.onManifestDownloadStart = {
5101
+ manifestEntered.signal()
5102
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5103
+ }
5104
+
5105
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5106
+ testPlugin.implementation = updater
5107
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5108
+
5109
+ let firstDone = expectation(description: "first matching manifest finished")
5110
+ let secondDone = expectation(description: "second matching manifest finished")
5111
+ var secondId: String?
5112
+
5113
+ DispatchQueue.global(qos: .userInitiated).async {
5114
+ defer { firstDone.fulfill() }
5115
+ _ = try? testPlugin.downloadBundleForTesting(
5116
+ urlString: "https://example.com/m",
5117
+ version: "6.0.0",
5118
+ sessionKey: "",
5119
+ checksum: "",
5120
+ manifestEntries: manifestA
5121
+ )
5122
+ }
5123
+ XCTAssertEqual(manifestEntered.wait(timeout: .now() + 5.0), .success)
5124
+
5125
+ DispatchQueue.global(qos: .userInitiated).async {
5126
+ defer { secondDone.fulfill() }
5127
+ secondId = try? testPlugin.downloadBundleForTesting(
5128
+ urlString: "https://example.com/m",
5129
+ version: "6.0.0",
5130
+ sessionKey: "",
5131
+ checksum: "",
5132
+ manifestEntries: manifestAEquivalent
5133
+ ).getId()
5134
+ }
5135
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5136
+ allowFinish.signal()
5137
+ wait(for: [firstDone, secondDone], timeout: 5.0)
5138
+
5139
+ XCTAssertEqual(secondId, "manifest-shared")
5140
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5141
+ }
5142
+
5143
+ // 2. Different manifests for the same version serialize and both execute.
5144
+ do {
5145
+ let manifestEntered = OnceSignal()
5146
+ let waiterJoined = OnceSignal()
5147
+ let allowFinish = OnceSignal()
5148
+
5149
+ let updater = CoalescingDownloadCapgoUpdater()
5150
+ updater.setLogger(testLogger)
5151
+ updater.manifestDownloadBundles = [
5152
+ BundleInfo(id: "manifest-a", version: "6.0.1", status: .PENDING, downloaded: Date(), checksum: ""),
5153
+ BundleInfo(id: "manifest-b", version: "6.0.1", status: .PENDING, downloaded: Date(), checksum: "")
5154
+ ]
5155
+ updater.onManifestDownloadStart = {
5156
+ if manifestEntered.signal() {
5157
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5158
+ }
5159
+ }
5160
+
5161
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5162
+ testPlugin.implementation = updater
5163
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5164
+
5165
+ let firstDone = expectation(description: "manifest A finished")
5166
+ let secondDone = expectation(description: "manifest B finished")
5167
+ var firstId: String?
5168
+ var secondId: String?
5169
+
5170
+ DispatchQueue.global(qos: .userInitiated).async {
5171
+ defer { firstDone.fulfill() }
5172
+ firstId = try? testPlugin.downloadBundleForTesting(
5173
+ urlString: "https://example.com/m",
5174
+ version: "6.0.1",
5175
+ sessionKey: "",
5176
+ checksum: "",
5177
+ manifestEntries: manifestA
5178
+ ).getId()
5179
+ }
5180
+ XCTAssertEqual(manifestEntered.wait(timeout: .now() + 5.0), .success)
5181
+
5182
+ DispatchQueue.global(qos: .userInitiated).async {
5183
+ defer { secondDone.fulfill() }
5184
+ secondId = try? testPlugin.downloadBundleForTesting(
5185
+ urlString: "https://example.com/m",
5186
+ version: "6.0.1",
5187
+ sessionKey: "",
5188
+ checksum: "",
5189
+ manifestEntries: manifestB
5190
+ ).getId()
5191
+ }
5192
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5193
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5194
+
5195
+ allowFinish.signal()
5196
+ wait(for: [firstDone, secondDone], timeout: 5.0)
5197
+
5198
+ XCTAssertEqual(firstId, "manifest-a")
5199
+ XCTAssertEqual(secondId, "manifest-b")
5200
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
5201
+ }
5202
+ }
5203
+
5204
+ func testBackgroundDownloadWithMissingChecksumCleansStaleIncompleteBundleOnlyWhenIdle() throws {
5205
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5206
+ CryptoCipher.setLogger(testLogger)
5207
+
5208
+ // 1. Idle: stale DOWNLOADING bundle is cleaned before reporting checksum_required.
5209
+ do {
5210
+ let stale = makeOnlyDownloadBundle(id: "stale-id", status: .DOWNLOADING, checksum: "")
5211
+ let (testPlugin, implementation) = makeAtBackgroundPlugin(existing: stale)
5212
+ implementation.setLogger(testLogger)
5213
+ implementation.latestResponse.checksum = ""
5214
+
5215
+ testPlugin.backgroundDownload()
5216
+
5217
+ XCTAssertEqual(implementation.deleteCalls, 1)
5218
+ XCTAssertEqual(implementation.lastDeletedId, "stale-id")
5219
+ XCTAssertTrue(implementation.sentStatsActions.contains("checksum_required"))
5220
+ }
5221
+
5222
+ // 2. Active in-flight download: checksum-less background response does not delete it.
5223
+ do {
5224
+ let downloadEntered = OnceSignal()
5225
+ let allowFinish = OnceSignal()
5226
+
5227
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
5228
+ let inFlight = BundleInfo(id: "active-id", version: "7.0.0", status: .DOWNLOADING, downloaded: Date(), checksum: "")
5229
+ let completed = BundleInfo(id: "active-id", version: "7.0.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
5230
+ let latest = AppVersion()
5231
+ latest.version = "7.0.0"
5232
+ latest.url = "https://example.com/update-7.0.0.zip"
5233
+ latest.checksum = ""
5234
+
5235
+ let updater = CoalescingDownloadCapgoUpdater()
5236
+ updater.setLogger(testLogger)
5237
+ updater.currentBundleValue = current
5238
+ updater.latestResponse = latest
5239
+ updater.downloadedBundleValue = completed
5240
+ updater.onDownloadStart = {
5241
+ updater.existingBundleValue = inFlight
5242
+ downloadEntered.signal()
5243
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5244
+ updater.existingBundleValue = completed
5245
+ }
5246
+
5247
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5248
+ testPlugin.implementation = updater
5249
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5250
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5251
+
5252
+ let bgDone = expectation(description: "background checksum_required completed")
5253
+ testPlugin.onSendReadyToJs = { msg in
5254
+ if msg == "Checksum required" {
5255
+ bgDone.fulfill()
5256
+ }
5257
+ }
5258
+
5259
+ let jsDone = expectation(description: "active JS download finished")
5260
+ DispatchQueue.global(qos: .userInitiated).async {
5261
+ defer { jsDone.fulfill() }
5262
+ _ = try? testPlugin.downloadBundleForTesting(
5263
+ urlString: "https://example.com/update-7.0.0.zip",
5264
+ version: "7.0.0",
5265
+ sessionKey: "",
5266
+ checksum: "abc123",
5267
+ manifestEntries: nil
5268
+ )
5269
+ }
5270
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5271
+
5272
+ testPlugin.backgroundDownload()
5273
+ wait(for: [bgDone], timeout: 5.0)
5274
+ XCTAssertEqual(updater.deleteCalls, 0)
5275
+ XCTAssertTrue(updater.sentStatsActions.contains("checksum_required"))
5276
+
5277
+ allowFinish.signal()
5278
+ wait(for: [jsDone], timeout: 5.0)
5279
+ }
5280
+ }
5281
+
5282
+ func testBackgroundDownloadDoesNotRegressAlreadyActiveBundleToPending() throws {
5283
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5284
+ CryptoCipher.setLogger(testLogger)
5285
+ let downloadEntered = OnceSignal()
5286
+ let waiterJoined = OnceSignal()
5287
+ let allowFinish = OnceSignal()
5288
+
5289
+ let initialCurrent = BundleInfo(
5290
+ id: "old-id",
5291
+ version: "1.0.0",
5292
+ status: .SUCCESS,
5293
+ downloaded: Date(),
5294
+ checksum: "old-checksum"
5295
+ )
5296
+ let downloaded = BundleInfo(
5297
+ id: "active-2.0.0",
5298
+ version: "2.0.0",
5299
+ status: .PENDING,
5300
+ downloaded: Date(),
5301
+ checksum: "abc123"
5302
+ )
5303
+ let activated = BundleInfo(
5304
+ id: "active-2.0.0",
5305
+ version: "2.0.0",
5306
+ status: .SUCCESS,
5307
+ downloaded: Date(),
5308
+ checksum: "abc123"
5309
+ )
5310
+ let latest = AppVersion()
5311
+ latest.version = "2.0.0"
5312
+ latest.url = "https://example.com/update-2.0.0.zip"
5313
+ latest.checksum = "abc123"
5314
+
5315
+ let updater = CoalescingDownloadCapgoUpdater()
5316
+ updater.setLogger(testLogger)
5317
+ updater.currentBundleValue = initialCurrent
5318
+ updater.latestResponse = latest
5319
+ updater.downloadedBundleValue = downloaded
5320
+ updater.onDownloadStart = {
5321
+ downloadEntered.signal()
5322
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5323
+ // Simulate JS activating and confirming the bundle before backgroundDownload queues next.
5324
+ updater.currentBundleValue = activated
5325
+ }
5326
+
5327
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5328
+ testPlugin.implementation = updater
5329
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5330
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5331
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5332
+
5333
+ let bgDone = expectation(description: "backgroundDownload skipped queueing active bundle")
5334
+ testPlugin.onSendReadyToJs = { msg in
5335
+ if msg == "No need to update" {
5336
+ bgDone.fulfill()
5337
+ }
5338
+ }
5339
+
5340
+ let jsDone = expectation(description: "JS download finished")
5341
+ DispatchQueue.global(qos: .userInitiated).async {
5342
+ defer { jsDone.fulfill() }
5343
+ _ = try? testPlugin.downloadBundleForTesting(
5344
+ urlString: "https://example.com/update-2.0.0.zip",
5345
+ version: "2.0.0",
5346
+ sessionKey: "",
5347
+ checksum: "abc123",
5348
+ manifestEntries: nil
5349
+ )
5350
+ }
5351
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5352
+
5353
+ testPlugin.backgroundDownload()
5354
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5355
+ allowFinish.signal()
5356
+
5357
+ wait(for: [jsDone, bgDone], timeout: 5.0)
5358
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
5359
+ XCTAssertEqual(updater.getCurrentBundle().getStatus(), BundleStatus.SUCCESS.storedValue)
5360
+ }
5361
+
5362
+ func testCoalescedDownloadRequiresExactVersionMatchAndValidSessionKey() throws {
5363
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5364
+ CryptoCipher.setLogger(testLogger)
5365
+
5366
+ // 1. Whitespace-differing version strings serialize instead of sharing a mismatched version.
5367
+ do {
5368
+ let downloadEntered = OnceSignal()
5369
+ let waiterJoined = OnceSignal()
5370
+ let allowFinish = OnceSignal()
5371
+
5372
+ let updater = CoalescingDownloadCapgoUpdater()
5373
+ updater.setLogger(testLogger)
5374
+ updater.zipDownloadBundles = [
5375
+ BundleInfo(id: "padded-id", version: " 8.0.0 ", status: .PENDING, downloaded: Date(), checksum: "abc123"),
5376
+ BundleInfo(id: "trimmed-id", version: "8.0.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
5377
+ ]
5378
+ updater.onDownloadStart = {
5379
+ if downloadEntered.signal() {
5380
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5381
+ }
5382
+ }
5383
+
5384
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5385
+ testPlugin.implementation = updater
5386
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5387
+
5388
+ let firstDone = expectation(description: "padded version finished")
5389
+ let secondDone = expectation(description: "trimmed version finished")
5390
+ var firstVersion: String?
5391
+ var secondVersion: String?
5392
+
5393
+ DispatchQueue.global(qos: .userInitiated).async {
5394
+ defer { firstDone.fulfill() }
5395
+ firstVersion = try? testPlugin.downloadBundleForTesting(
5396
+ urlString: "https://example.com/update-8.0.0.zip",
5397
+ version: " 8.0.0 ",
5398
+ sessionKey: "",
5399
+ checksum: "abc123",
5400
+ manifestEntries: nil
5401
+ ).getVersionName()
5402
+ }
5403
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5404
+
5405
+ DispatchQueue.global(qos: .userInitiated).async {
5406
+ defer { secondDone.fulfill() }
5407
+ secondVersion = try? testPlugin.downloadBundleForTesting(
5408
+ urlString: "https://example.com/update-8.0.0.zip",
5409
+ version: "8.0.0",
5410
+ sessionKey: "",
5411
+ checksum: "abc123",
5412
+ manifestEntries: nil
5413
+ ).getVersionName()
5414
+ }
5415
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5416
+ XCTAssertEqual(updater.downloadCalls, 1)
5417
+
5418
+ allowFinish.signal()
5419
+ wait(for: [firstDone, secondDone], timeout: 5.0)
5420
+
5421
+ XCTAssertEqual(firstVersion, " 8.0.0 ")
5422
+ XCTAssertEqual(secondVersion, "8.0.0")
5423
+ XCTAssertEqual(updater.downloadCalls, 2)
5424
+ }
5425
+
5426
+ // 2. Undecodable sessionKey fails immediately even when a valid encrypted download is in flight.
5427
+ do {
5428
+ let directory = try XCTUnwrap(CliCryptoFixtureTests.fixtureDirectories().first)
5429
+ let json = try Data(contentsOf: directory.appendingPathComponent("cli-crypto.json"))
5430
+ let fixture = try XCTUnwrap(try JSONSerialization.jsonObject(with: json) as? [String: Any])
5431
+ let publicKeyPem = try XCTUnwrap(fixture["publicKey"] as? String)
5432
+ let bundle = try XCTUnwrap((fixture["bundles"] as? [[String: Any]])?.first)
5433
+ let encryptedChecksumHex = try XCTUnwrap(bundle["checksum"] as? String)
5434
+ let expectedDecryptedChecksum = try XCTUnwrap(bundle["sha256"] as? String)
5435
+ let validSessionKey = try XCTUnwrap(bundle["ivSessionKey"] as? String)
5436
+
5437
+ let downloadEntered = OnceSignal()
5438
+ let allowFinish = OnceSignal()
5439
+
5440
+ let updater = CoalescingDownloadCapgoUpdater()
5441
+ updater.setLogger(testLogger)
5442
+ updater.setPublicKey(publicKeyPem)
5443
+ updater.downloadedBundleValue = BundleInfo(
5444
+ id: "encrypted-id",
5445
+ version: "8.1.0",
5446
+ status: .PENDING,
5447
+ downloaded: Date(),
5448
+ checksum: expectedDecryptedChecksum
5449
+ )
5450
+ updater.onDownloadStart = {
5451
+ downloadEntered.signal()
5452
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5453
+ }
5454
+
5455
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5456
+ testPlugin.implementation = updater
5457
+ var waiterJoinedCount = 0
5458
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoinedCount += 1 }
5459
+
5460
+ let ownerDone = expectation(description: "encrypted owner finished")
5461
+ DispatchQueue.global(qos: .userInitiated).async {
5462
+ defer { ownerDone.fulfill() }
5463
+ do {
5464
+ let bundle = try testPlugin.downloadBundleForTesting(
5465
+ urlString: "https://example.com/update-8.1.0.zip",
5466
+ version: "8.1.0",
5467
+ sessionKey: validSessionKey,
5468
+ checksum: encryptedChecksumHex,
5469
+ manifestEntries: nil
5470
+ )
5471
+ XCTAssertEqual(bundle.getId(), "encrypted-id")
5472
+ } catch {
5473
+ XCTFail("Valid encrypted download should succeed: \(error.localizedDescription)")
5474
+ }
5475
+ }
5476
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5477
+
5478
+ XCTAssertThrowsError(
5479
+ try testPlugin.downloadBundleForTesting(
5480
+ urlString: "https://example.com/update-8.1.0.zip",
5481
+ version: "8.1.0",
5482
+ sessionKey: "not-base64:not-a-valid-key",
5483
+ checksum: encryptedChecksumHex,
5484
+ manifestEntries: nil
5485
+ )
5486
+ )
5487
+ XCTAssertEqual(waiterJoinedCount, 0)
5488
+
5489
+ allowFinish.signal()
5490
+ wait(for: [ownerDone], timeout: 5.0)
5491
+ }
5492
+ }
5493
+
5494
+ func testBackgroundDownloadSerializesDifferingManifestEvenAfterInFlightPersistsPending() throws {
5495
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5496
+ CryptoCipher.setLogger(testLogger)
5497
+ let manifestEntered = OnceSignal()
5498
+ let waiterJoined = OnceSignal()
5499
+ let allowFinish = OnceSignal()
5500
+
5501
+ let current = BundleInfo(
5502
+ id: "current-id",
5503
+ version: "1.0.0",
5504
+ status: .SUCCESS,
5505
+ downloaded: Date(),
5506
+ checksum: "cur"
5507
+ )
5508
+ let manifestABundle = BundleInfo(
5509
+ id: "manifest-a-pending",
5510
+ version: "8.2.0",
5511
+ status: .PENDING,
5512
+ downloaded: Date(),
5513
+ checksum: ""
5514
+ )
5515
+ let manifestBBundle = BundleInfo(
5516
+ id: "manifest-b-pending",
5517
+ version: "8.2.0",
5518
+ status: .PENDING,
5519
+ downloaded: Date(),
5520
+ checksum: ""
5521
+ )
5522
+ let manifestA = [
5523
+ ManifestEntry(file_name: "index.html", file_hash: "hash-a", download_url: "https://example.com/a/index.html")
5524
+ ]
5525
+ let manifestB = [
5526
+ ManifestEntry(file_name: "index.html", file_hash: "hash-b", download_url: "https://example.com/b/index.html")
5527
+ ]
5528
+
5529
+ let latest = AppVersion()
5530
+ latest.version = "8.2.0"
5531
+ latest.url = "https://example.com/manifest-8.2.0"
5532
+ latest.manifest = manifestB
5533
+
5534
+ let updater = CoalescingDownloadCapgoUpdater()
5535
+ updater.setLogger(testLogger)
5536
+ updater.currentBundleValue = current
5537
+ updater.latestResponse = latest
5538
+ updater.manifestDownloadBundles = [manifestABundle, manifestBBundle]
5539
+ updater.onManifestDownloadStart = {
5540
+ if manifestEntered.signal() {
5541
+ // Simulate downloadManifest persisting PENDING before the in-flight slot is released.
5542
+ updater.existingBundleValue = manifestABundle
5543
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5544
+ }
5545
+ }
5546
+ let bgFinished = expectation(description: "background downloaded manifest B")
5547
+ updater.onSetNextBundle = {
5548
+ bgFinished.fulfill()
5549
+ }
5550
+
5551
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5552
+ testPlugin.implementation = updater
5553
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5554
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5555
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5556
+
5557
+ let jsDone = expectation(description: "JS manifest A finished")
5558
+ DispatchQueue.global(qos: .userInitiated).async {
5559
+ defer { jsDone.fulfill() }
5560
+ _ = try? testPlugin.downloadBundleForTesting(
5561
+ urlString: "https://example.com/manifest-8.2.0",
5562
+ version: "8.2.0",
5563
+ sessionKey: "",
5564
+ checksum: "",
5565
+ manifestEntries: manifestA
5566
+ )
5567
+ }
5568
+ XCTAssertEqual(manifestEntered.wait(timeout: .now() + 5.0), .success)
5569
+
5570
+ testPlugin.backgroundDownload()
5571
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5572
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5573
+
5574
+ allowFinish.signal()
5575
+ wait(for: [jsDone, bgFinished], timeout: 5.0)
5576
+
5577
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
5578
+ XCTAssertEqual(updater.lastSetNextBundleId, "manifest-b-pending")
5579
+ }
5580
+
5581
+ func testCoalescedDownloadRetriesDifferentSourceUrlAfterLeaderFailure() throws {
5582
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5583
+ CryptoCipher.setLogger(testLogger)
5584
+ let downloadEntered = OnceSignal()
5585
+ let waiterJoined = OnceSignal()
5586
+ let allowFailure = OnceSignal()
5587
+
5588
+ let recovered = BundleInfo(
5589
+ id: "fallback-url-id",
5590
+ version: "9.0.0",
5591
+ status: .PENDING,
5592
+ downloaded: Date(),
5593
+ checksum: "abc123"
5594
+ )
5595
+ let updater = CoalescingDownloadCapgoUpdater()
5596
+ updater.setLogger(testLogger)
5597
+ updater.zipDownloadBundles = [nil, recovered]
5598
+ updater.onDownloadStart = {
5599
+ if downloadEntered.signal() {
5600
+ _ = allowFailure.wait(timeout: .now() + 5.0)
5601
+ }
5602
+ }
5603
+
5604
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5605
+ testPlugin.implementation = updater
5606
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5607
+
5608
+ let firstDone = expectation(description: "first URL failed")
5609
+ let secondDone = expectation(description: "different URL retried and succeeded")
5610
+ var firstFailed = false
5611
+ var secondId: String?
5612
+
5613
+ DispatchQueue.global(qos: .userInitiated).async {
5614
+ defer { firstDone.fulfill() }
5615
+ do {
5616
+ _ = try testPlugin.downloadBundleForTesting(
5617
+ urlString: "https://cdn-a.example.com/update-9.0.0.zip",
5618
+ version: "9.0.0",
5619
+ sessionKey: "",
5620
+ checksum: "abc123",
5621
+ manifestEntries: nil
5622
+ )
5623
+ } catch {
5624
+ firstFailed = true
5625
+ }
5626
+ }
5627
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5628
+
5629
+ DispatchQueue.global(qos: .userInitiated).async {
5630
+ defer { secondDone.fulfill() }
5631
+ secondId = try? testPlugin.downloadBundleForTesting(
5632
+ urlString: "https://cdn-b.example.com/update-9.0.0.zip",
5633
+ version: "9.0.0",
5634
+ sessionKey: "",
5635
+ checksum: "abc123",
5636
+ manifestEntries: nil
5637
+ ).getId()
5638
+ }
5639
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
5640
+ allowFailure.signal()
5641
+ wait(for: [firstDone, secondDone], timeout: 5.0)
5642
+
5643
+ XCTAssertTrue(firstFailed)
5644
+ XCTAssertEqual(secondId, "fallback-url-id")
5645
+ XCTAssertEqual(updater.downloadCalls, 2)
5646
+ }
5647
+
5648
+ func testBackgroundDownloadRejectsRetainedErrorBundleEvenWhileJsDownloadsSameVersion() throws {
5649
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5650
+ CryptoCipher.setLogger(testLogger)
5651
+ let downloadEntered = OnceSignal()
5652
+ let allowFinish = OnceSignal()
5653
+
5654
+ let current = BundleInfo(
5655
+ id: "current-id",
5656
+ version: "1.0.0",
5657
+ status: .SUCCESS,
5658
+ downloaded: Date(),
5659
+ checksum: "cur"
5660
+ )
5661
+ let retainedError = BundleInfo(
5662
+ id: "failed-9.1.0",
5663
+ version: "9.1.0",
5664
+ status: .ERROR,
5665
+ downloaded: Date(),
5666
+ checksum: "abc123"
5667
+ )
5668
+ let jsBundle = BundleInfo(
5669
+ id: "js-9.1.0",
5670
+ version: "9.1.0",
5671
+ status: .PENDING,
5672
+ downloaded: Date(),
5673
+ checksum: "abc123"
5674
+ )
5675
+ let latest = AppVersion()
5676
+ latest.version = "9.1.0"
5677
+ latest.url = "https://example.com/update-9.1.0.zip"
5678
+ latest.checksum = "abc123"
5679
+
5680
+ let updater = CoalescingDownloadCapgoUpdater()
5681
+ updater.setLogger(testLogger)
5682
+ updater.currentBundleValue = current
5683
+ updater.existingBundleValue = retainedError
5684
+ updater.latestResponse = latest
5685
+ updater.downloadedBundleValue = jsBundle
5686
+ updater.onDownloadStart = {
5687
+ downloadEntered.signal()
5688
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5689
+ }
5690
+
5691
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5692
+ testPlugin.implementation = updater
5693
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5694
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5695
+
5696
+ let bgRejected = expectation(description: "backgroundDownload rejected retained ERROR bundle")
5697
+ testPlugin.onSendReadyToJs = { msg in
5698
+ if msg == "Latest version is in error state. Aborting update." {
5699
+ bgRejected.fulfill()
5700
+ }
5701
+ }
5702
+
5703
+ let jsDone = expectation(description: "JS download succeeded")
5704
+ DispatchQueue.global(qos: .userInitiated).async {
5705
+ defer { jsDone.fulfill() }
5706
+ _ = try? testPlugin.downloadBundleForTesting(
5707
+ urlString: "https://example.com/update-9.1.0.zip",
5708
+ version: "9.1.0",
5709
+ sessionKey: "",
5710
+ checksum: "abc123",
5711
+ manifestEntries: nil
5712
+ )
5713
+ }
5714
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5715
+
5716
+ testPlugin.backgroundDownload()
5717
+ wait(for: [bgRejected], timeout: 5.0)
5718
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
5719
+
5720
+ allowFinish.signal()
5721
+ wait(for: [jsDone], timeout: 5.0)
5722
+ }
5723
+
5724
+ func testBackgroundDownloadDoesNotReuseMismatchedCompletedManifestBundle() throws {
5725
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5726
+ CryptoCipher.setLogger(testLogger)
5727
+
5728
+ let current = BundleInfo(
5729
+ id: "current-id",
5730
+ version: "1.0.0",
5731
+ status: .SUCCESS,
5732
+ downloaded: Date(),
5733
+ checksum: "cur"
5734
+ )
5735
+ let manifestABundle = BundleInfo(
5736
+ id: "manifest-a-id",
5737
+ version: "9.2.0",
5738
+ status: .PENDING,
5739
+ downloaded: Date(),
5740
+ checksum: ""
5741
+ )
5742
+ let manifestBBundle = BundleInfo(
5743
+ id: "manifest-b-id",
5744
+ version: "9.2.0",
5745
+ status: .PENDING,
5746
+ downloaded: Date(),
5747
+ checksum: ""
5748
+ )
5749
+ let manifestA = [
5750
+ ManifestEntry(
5751
+ file_name: "index.html",
5752
+ file_hash: "hash-manifest-a",
5753
+ download_url: "https://example.com/a/index.html"
5754
+ )
5755
+ ]
5756
+ let manifestB = [
5757
+ ManifestEntry(
5758
+ file_name: "index.html",
5759
+ file_hash: "hash-manifest-b",
5760
+ download_url: "https://example.com/b/index.html"
5761
+ )
5762
+ ]
5763
+
5764
+ let latest = AppVersion()
5765
+ latest.version = "9.2.0"
5766
+ latest.url = "https://example.com/manifest-9.2.0"
5767
+ latest.manifest = manifestB
5768
+
5769
+ let updater = CoalescingDownloadCapgoUpdater()
5770
+ updater.setLogger(testLogger)
5771
+ updater.currentBundleValue = current
5772
+ updater.latestResponse = latest
5773
+ updater.manifestDownloadBundles = [manifestABundle, manifestBBundle]
5774
+
5775
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5776
+ testPlugin.implementation = updater
5777
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5778
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5779
+
5780
+ let jsBundle = try testPlugin.downloadBundleForTesting(
5781
+ urlString: "https://example.com/manifest-9.2.0",
5782
+ version: "9.2.0",
5783
+ sessionKey: "",
5784
+ checksum: "",
5785
+ manifestEntries: manifestA
5786
+ )
5787
+ XCTAssertEqual(jsBundle.getId(), "manifest-a-id")
5788
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
5789
+ updater.existingBundleValue = manifestABundle
5790
+
5791
+ let mismatchHandled = expectation(description: "backgroundDownload downloaded manifest B instead of reusing manifest A")
5792
+ testPlugin.onSendReadyToJs = { _ in
5793
+ mismatchHandled.fulfill()
5794
+ }
5795
+ testPlugin.backgroundDownload()
5796
+ wait(for: [mismatchHandled], timeout: 5.0)
5797
+
5798
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
5799
+ XCTAssertEqual(updater.lastSetNextBundleId, "manifest-b-id")
5800
+
5801
+ // A subsequent backgroundDownload requesting the same manifest B should reuse it.
5802
+ updater.existingBundleValue = manifestBBundle
5803
+ let matchReused = expectation(description: "backgroundDownload reused matching manifest B")
5804
+ testPlugin.onSendReadyToJs = { _ in
5805
+ matchReused.fulfill()
5806
+ }
5807
+ testPlugin.backgroundDownload()
5808
+ wait(for: [matchReused], timeout: 5.0)
5809
+
5810
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
5811
+ XCTAssertEqual(updater.lastSetNextBundleId, "manifest-b-id")
5812
+ }
5813
+
5814
+ func testBackgroundDownloadRejectsRetainedErrorBundleListedAfterNewerSameVersionBundle() throws {
5815
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5816
+ CryptoCipher.setLogger(testLogger)
5817
+ let downloadEntered = OnceSignal()
5818
+ let allowFinish = OnceSignal()
5819
+
5820
+ let current = BundleInfo(
5821
+ id: "current-id",
5822
+ version: "1.0.0",
5823
+ status: .SUCCESS,
5824
+ downloaded: Date(),
5825
+ checksum: "cur"
5826
+ )
5827
+ let retainedError = BundleInfo(
5828
+ id: "failed-9.3.0",
5829
+ version: "9.3.0",
5830
+ status: .ERROR,
5831
+ downloaded: Date(),
5832
+ checksum: "abc123"
5833
+ )
5834
+ let jsBundle = BundleInfo(
5835
+ id: "js-9.3.0",
5836
+ version: "9.3.0",
5837
+ status: .PENDING,
5838
+ downloaded: Date(),
5839
+ checksum: "abc123"
5840
+ )
5841
+ let latest = AppVersion()
5842
+ latest.version = "9.3.0"
5843
+ latest.url = "https://example.com/update-9.3.0.zip"
5844
+ latest.checksum = "abc123"
5845
+
5846
+ let updater = CoalescingDownloadCapgoUpdater()
5847
+ updater.setLogger(testLogger)
5848
+ updater.currentBundleValue = current
5849
+ updater.latestResponse = latest
5850
+ updater.downloadedBundleValue = jsBundle
5851
+ // The retained ERROR copy is listed after the new JS copy, so a first-match lookup would miss it.
5852
+ updater.additionalVersionBundles = [retainedError]
5853
+ updater.onDownloadStart = {
5854
+ updater.existingBundleValue = jsBundle
5855
+ downloadEntered.signal()
5856
+ _ = allowFinish.wait(timeout: .now() + 5.0)
5857
+ }
5858
+
5859
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5860
+ testPlugin.implementation = updater
5861
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5862
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5863
+
5864
+ let bgRejected = expectation(description: "backgroundDownload rejected retained ERROR bundle listed second")
5865
+ testPlugin.onSendReadyToJs = { msg in
5866
+ if msg == "Latest version is in error state. Aborting update." {
5867
+ bgRejected.fulfill()
5868
+ }
5869
+ }
5870
+
5871
+ let jsDone = expectation(description: "JS download succeeded")
5872
+ DispatchQueue.global(qos: .userInitiated).async {
5873
+ defer { jsDone.fulfill() }
5874
+ _ = try? testPlugin.downloadBundleForTesting(
5875
+ urlString: "https://example.com/update-9.3.0.zip",
5876
+ version: "9.3.0",
5877
+ sessionKey: "",
5878
+ checksum: "abc123",
5879
+ manifestEntries: nil
5880
+ )
5881
+ }
5882
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
5883
+ XCTAssertEqual(updater.getBundleInfoByVersionName(version: "9.3.0")?.getId(), "js-9.3.0")
5884
+
5885
+ testPlugin.backgroundDownload()
5886
+ wait(for: [bgRejected], timeout: 5.0)
5887
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
5888
+ XCTAssertEqual(updater.downloadCalls, 1)
5889
+
5890
+ allowFinish.signal()
5891
+ wait(for: [jsDone], timeout: 5.0)
5892
+ }
5893
+
5894
+ func testBackgroundDownloadDoesNotReuseManifestBundlePublishedBetweenInFlightCheckAndLookup() throws {
5895
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
5896
+ CryptoCipher.setLogger(testLogger)
5897
+ let jsManifestPersisted = OnceSignal()
5898
+ let allowJsFinish = OnceSignal()
5899
+ let backgroundLookupStarted = OnceSignal()
5900
+ let waiterJoined = OnceSignal()
5901
+ let jsReachedSlotAcquire = OnceSignal()
5902
+
5903
+ let current = BundleInfo(
5904
+ id: "current-id",
5905
+ version: "1.0.0",
5906
+ status: .SUCCESS,
5907
+ downloaded: Date(),
5908
+ checksum: "cur"
5909
+ )
5910
+ let manifestABundle = BundleInfo(
5911
+ id: "race-manifest-a",
5912
+ version: "9.4.0",
5913
+ status: .PENDING,
5914
+ downloaded: Date(),
5915
+ checksum: ""
5916
+ )
5917
+ let manifestBBundle = BundleInfo(
5918
+ id: "race-manifest-b",
5919
+ version: "9.4.0",
5920
+ status: .PENDING,
5921
+ downloaded: Date(),
5922
+ checksum: ""
5923
+ )
5924
+ let manifestA = [
5925
+ ManifestEntry(file_name: "index.html", file_hash: "race-hash-a", download_url: "https://example.com/a/index.html")
5926
+ ]
5927
+ let manifestB = [
5928
+ ManifestEntry(file_name: "index.html", file_hash: "race-hash-b", download_url: "https://example.com/b/index.html")
5929
+ ]
5930
+
5931
+ let latest = AppVersion()
5932
+ latest.version = "9.4.0"
5933
+ latest.url = "https://example.com/manifest-9.4.0"
5934
+ latest.manifest = manifestB
5935
+
5936
+ let updater = CoalescingDownloadCapgoUpdater()
5937
+ updater.setLogger(testLogger)
5938
+ updater.currentBundleValue = current
5939
+ updater.latestResponse = latest
5940
+ updater.manifestBundlesByFirstHash = [
5941
+ "race-hash-a": manifestABundle,
5942
+ "race-hash-b": manifestBBundle
5943
+ ]
5944
+ updater.onManifestDownload = { manifest in
5945
+ guard manifest.first?.file_hash == "race-hash-a" else {
5946
+ return
5947
+ }
5948
+ // Simulate downloadManifest persisting PENDING A before its fingerprint is recorded.
5949
+ updater.existingBundleValue = manifestABundle
5950
+ jsManifestPersisted.signal()
5951
+ _ = allowJsFinish.wait(timeout: .now() + 5.0)
5952
+ }
5953
+
5954
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
5955
+ testPlugin.implementation = updater
5956
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
5957
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
5958
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
5959
+ // The background check is inside its lookup when this first fires, so the first caller is the JS worker.
5960
+ testPlugin.onDownloadSlotAcquireAttemptForTesting = { _ in jsReachedSlotAcquire.signal() }
5961
+
5962
+ let jsDone = expectation(description: "JS manifest A finished")
5963
+ var jsAtSlotDuringLookup: DispatchTimeoutResult?
5964
+ var persistDuringLookup: DispatchTimeoutResult?
5965
+ // Start the JS download for manifest A exactly when the background check looks up the stored bundle,
5966
+ // i.e. after it decided whether a download is in flight, and give it time to persist A before the lookup
5967
+ // returns. With an atomic snapshot the JS download cannot claim its slot (and so cannot persist A) until the
5968
+ // lookup is done; without it, A is persisted here and was previously reused without a fingerprint check.
5969
+ updater.onVersionLookup = {
5970
+ guard backgroundLookupStarted.signal() else {
5971
+ return
5972
+ }
5973
+ DispatchQueue.global(qos: .userInitiated).async {
5974
+ defer { jsDone.fulfill() }
5975
+ _ = try? testPlugin.downloadBundleForTesting(
5976
+ urlString: "https://example.com/manifest-9.4.0",
5977
+ version: "9.4.0",
5978
+ sessionKey: "",
5979
+ checksum: "",
5980
+ manifestEntries: manifestA
5981
+ )
5982
+ }
5983
+ // The JS worker must actually reach slot acquisition before the lookup returns.
5984
+ jsAtSlotDuringLookup = jsReachedSlotAcquire.wait(timeout: .now() + 5.0)
5985
+ persistDuringLookup = jsManifestPersisted.wait(timeout: .now() + 0.5)
5986
+ }
5987
+
5988
+ let bgFinished = expectation(description: "background queued a bundle")
5989
+ updater.onSetNextBundle = {
5990
+ bgFinished.fulfill()
5991
+ }
5992
+
5993
+ testPlugin.backgroundDownload()
5994
+ XCTAssertEqual(backgroundLookupStarted.wait(timeout: .now() + 5.0), .success)
5995
+ // Usually one download waits behind the other, but they may also serialize without overlapping
5996
+ // (the background check finishes B before JS takes the slot), so a waiter is not required.
5997
+ _ = waiterJoined.wait(timeout: .now() + 2.0)
5998
+ allowJsFinish.signal()
5999
+ wait(for: [bgFinished, jsDone], timeout: 5.0)
6000
+
6001
+ // The JS worker was at the slot boundary, yet the lookup snapshot holds downloadLock, so JS manifest A
6002
+ // could not be published mid-lookup.
6003
+ XCTAssertEqual(jsAtSlotDuringLookup, .success)
6004
+ XCTAssertEqual(persistDuringLookup, .timedOut)
6005
+ XCTAssertEqual(jsManifestPersisted.wait(timeout: .now()), .success)
6006
+
6007
+ XCTAssertEqual(updater.lastSetNextBundleId, "race-manifest-b")
6008
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
6009
+ }
6010
+
6011
+ func testBackgroundDownloadDoesNotReuseCompletedZipForManifestRequest() throws {
6012
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6013
+ CryptoCipher.setLogger(testLogger)
6014
+
6015
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6016
+ let zipBundle = BundleInfo(id: "zip-9.5.0", version: "9.5.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
6017
+ let manifestBundle = BundleInfo(id: "manifest-9.5.0", version: "9.5.0", status: .PENDING, downloaded: Date(), checksum: "")
6018
+ let manifestB = [
6019
+ ManifestEntry(file_name: "index.html", file_hash: "zip-vs-manifest-b", download_url: "https://example.com/b/index.html")
6020
+ ]
6021
+ let latest = AppVersion()
6022
+ latest.version = "9.5.0"
6023
+ latest.url = "https://example.com/manifest-9.5.0"
6024
+ latest.manifest = manifestB
6025
+
6026
+ let updater = CoalescingDownloadCapgoUpdater()
6027
+ updater.setLogger(testLogger)
6028
+ updater.currentBundleValue = current
6029
+ updater.latestResponse = latest
6030
+ updater.downloadedBundleValue = zipBundle
6031
+ updater.manifestBundlesByFirstHash = ["zip-vs-manifest-b": manifestBundle]
6032
+
6033
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6034
+ testPlugin.implementation = updater
6035
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6036
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6037
+
6038
+ // JS completes a ZIP download of the same version before the automatic check runs.
6039
+ let jsBundle = try testPlugin.downloadBundleForTesting(
6040
+ urlString: "https://example.com/update-9.5.0.zip",
6041
+ version: "9.5.0",
6042
+ sessionKey: "",
6043
+ checksum: "abc123",
6044
+ manifestEntries: nil
6045
+ )
6046
+ XCTAssertEqual(jsBundle.getId(), "zip-9.5.0")
6047
+ updater.existingBundleValue = zipBundle
6048
+
6049
+ let bgFinished = expectation(description: "background downloaded the requested manifest")
6050
+ updater.onSetNextBundle = { bgFinished.fulfill() }
6051
+ testPlugin.backgroundDownload()
6052
+ wait(for: [bgFinished], timeout: 5.0)
6053
+
6054
+ XCTAssertEqual(updater.manifestDownloadCalls, 1)
6055
+ XCTAssertEqual(updater.lastSetNextBundleId, "manifest-9.5.0")
6056
+ }
6057
+
6058
+ func testBackgroundDownloadReusesMatchingManifestCopyListedAfterAnotherCompleteCopy() throws {
6059
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6060
+ CryptoCipher.setLogger(testLogger)
6061
+
6062
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6063
+ let manifestABundle = BundleInfo(id: "copies-manifest-a", version: "9.6.0", status: .PENDING, downloaded: Date(), checksum: "")
6064
+ let manifestBBundle = BundleInfo(id: "copies-manifest-b", version: "9.6.0", status: .PENDING, downloaded: Date(), checksum: "")
6065
+ let manifestA = [
6066
+ ManifestEntry(file_name: "index.html", file_hash: "copies-hash-a", download_url: "https://example.com/a/index.html")
6067
+ ]
6068
+ let manifestB = [
6069
+ ManifestEntry(file_name: "index.html", file_hash: "copies-hash-b", download_url: "https://example.com/b/index.html")
6070
+ ]
6071
+ let latest = AppVersion()
6072
+ latest.version = "9.6.0"
6073
+ latest.url = "https://example.com/manifest-9.6.0"
6074
+ latest.manifest = manifestB
6075
+
6076
+ let updater = CoalescingDownloadCapgoUpdater()
6077
+ updater.setLogger(testLogger)
6078
+ updater.currentBundleValue = current
6079
+ updater.latestResponse = latest
6080
+ updater.manifestBundlesByFirstHash = [
6081
+ "copies-hash-a": manifestABundle,
6082
+ "copies-hash-b": manifestBBundle
6083
+ ]
6084
+
6085
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6086
+ testPlugin.implementation = updater
6087
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6088
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6089
+
6090
+ for manifest in [manifestA, manifestB] {
6091
+ _ = try testPlugin.downloadBundleForTesting(
6092
+ urlString: "https://example.com/manifest-9.6.0",
6093
+ version: "9.6.0",
6094
+ sessionKey: "",
6095
+ checksum: "",
6096
+ manifestEntries: manifest
6097
+ )
6098
+ }
6099
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
6100
+ // Manifest A is listed first; the requested manifest B is a later complete copy.
6101
+ updater.existingBundleValue = manifestABundle
6102
+ updater.additionalVersionBundles = [manifestBBundle]
6103
+
6104
+ let slotAttemptLock = NSLock()
6105
+ var backgroundSlotAttempts = 0
6106
+ testPlugin.onDownloadSlotAcquireAttemptForTesting = { _ in
6107
+ slotAttemptLock.lock()
6108
+ backgroundSlotAttempts += 1
6109
+ slotAttemptLock.unlock()
6110
+ }
6111
+ let bgFinished = expectation(description: "background reused manifest B")
6112
+ updater.onSetNextBundle = { bgFinished.fulfill() }
6113
+ testPlugin.backgroundDownload()
6114
+ wait(for: [bgFinished], timeout: 5.0)
6115
+
6116
+ XCTAssertEqual(updater.manifestDownloadCalls, 2)
6117
+ XCTAssertEqual(updater.lastSetNextBundleId, "copies-manifest-b")
6118
+ // The snapshot itself picked the matching copy, so the check never needed a download slot.
6119
+ slotAttemptLock.lock()
6120
+ XCTAssertEqual(backgroundSlotAttempts, 0)
6121
+ slotAttemptLock.unlock()
6122
+ }
6123
+
6124
+ func testBackgroundDownloadRejectsVersionMarkedErrorWhileWaitingOnSharedDownload() throws {
6125
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6126
+ CryptoCipher.setLogger(testLogger)
6127
+ let downloadEntered = OnceSignal()
6128
+ let waiterJoined = OnceSignal()
6129
+ let allowFinish = OnceSignal()
6130
+
6131
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6132
+ let jsBundle = BundleInfo(id: "wait-js-9.7.0", version: "9.7.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
6133
+ let markedError = BundleInfo(id: "wait-error-9.7.0", version: "9.7.0", status: .ERROR, downloaded: Date(), checksum: "abc123")
6134
+ let latest = AppVersion()
6135
+ latest.version = "9.7.0"
6136
+ latest.url = "https://example.com/update-9.7.0.zip"
6137
+ latest.checksum = "abc123"
6138
+
6139
+ let updater = CoalescingDownloadCapgoUpdater()
6140
+ updater.setLogger(testLogger)
6141
+ updater.currentBundleValue = current
6142
+ updater.latestResponse = latest
6143
+ updater.downloadedBundleValue = jsBundle
6144
+ updater.onDownloadStart = {
6145
+ downloadEntered.signal()
6146
+ _ = allowFinish.wait(timeout: .now() + 5.0)
6147
+ }
6148
+
6149
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6150
+ testPlugin.implementation = updater
6151
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6152
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6153
+ testPlugin.onCoalesceWaiterJoinedForTesting = { _ in waiterJoined.signal() }
6154
+
6155
+ let bgRejected = expectation(description: "backgroundDownload rejected the version marked ERROR during the wait")
6156
+ testPlugin.onSendReadyToJs = { msg in
6157
+ if msg == "Latest version is in error state. Aborting update." {
6158
+ bgRejected.fulfill()
6159
+ }
6160
+ }
6161
+
6162
+ let jsDone = expectation(description: "JS download finished")
6163
+ DispatchQueue.global(qos: .userInitiated).async {
6164
+ defer { jsDone.fulfill() }
6165
+ _ = try? testPlugin.downloadBundleForTesting(
6166
+ urlString: "https://example.com/update-9.7.0.zip",
6167
+ version: "9.7.0",
6168
+ sessionKey: "",
6169
+ checksum: "abc123",
6170
+ manifestEntries: nil
6171
+ )
6172
+ }
6173
+ XCTAssertEqual(downloadEntered.wait(timeout: .now() + 5.0), .success)
6174
+
6175
+ testPlugin.backgroundDownload()
6176
+ XCTAssertEqual(waiterJoined.wait(timeout: .now() + 5.0), .success)
6177
+ // Another copy of the version is marked ERROR (e.g. via setBundleError) while the check waits.
6178
+ updater.additionalVersionBundles = [markedError]
6179
+ updater.existingBundleValue = jsBundle
6180
+ allowFinish.signal()
6181
+
6182
+ wait(for: [bgRejected, jsDone], timeout: 5.0)
6183
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
6184
+ XCTAssertEqual(updater.downloadCalls, 1)
6185
+ }
6186
+
6187
+ func testBackgroundDownloadFillsServerMetadataWhenSlotOwnerReusesStoredBundle() throws {
6188
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6189
+ CryptoCipher.setLogger(testLogger)
6190
+
6191
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6192
+ let jsBundle = BundleInfo(id: "reuse-js-9.8.0", version: "9.8.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
6193
+ let latest = AppVersion()
6194
+ latest.version = "9.8.0"
6195
+ latest.url = "https://example.com/update-9.8.0.zip"
6196
+ latest.checksum = "abc123"
6197
+ latest.link = "https://example.com/release-notes"
6198
+ latest.comment = "server comment"
6199
+
6200
+ let updater = CoalescingDownloadCapgoUpdater()
6201
+ updater.setLogger(testLogger)
6202
+ updater.currentBundleValue = current
6203
+ updater.latestResponse = latest
6204
+ updater.downloadedBundleValue = jsBundle
6205
+ updater.onDownloadStart = {
6206
+ updater.existingBundleValue = jsBundle
6207
+ }
6208
+
6209
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6210
+ testPlugin.implementation = updater
6211
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6212
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6213
+
6214
+ // JS completes its download after the background snapshot but before the background check takes the slot.
6215
+ let jsRan = OnceSignal()
6216
+ testPlugin.onDownloadSlotAcquireAttemptForTesting = { _ in
6217
+ guard jsRan.signal() else {
6218
+ return
6219
+ }
6220
+ _ = try? testPlugin.downloadBundleForTesting(
6221
+ urlString: "https://example.com/update-9.8.0.zip",
6222
+ version: "9.8.0",
6223
+ sessionKey: "",
6224
+ checksum: "abc123",
6225
+ manifestEntries: nil
6226
+ )
6227
+ }
6228
+
6229
+ let metadataNotified = expectation(description: "updateAvailable emitted for the reused bundle")
6230
+ var notifiedBundle: [String: Any]?
6231
+ testPlugin.onUpdateAvailable = { bundle in
6232
+ guard bundle["id"] as? String == "reuse-js-9.8.0" else {
6233
+ return
6234
+ }
6235
+ notifiedBundle = bundle
6236
+ metadataNotified.fulfill()
6237
+ }
6238
+ testPlugin.backgroundDownload()
6239
+ wait(for: [metadataNotified], timeout: 5.0)
6240
+
6241
+ // Only the JS download hit the network; the slot owner reused its bundle by checksum.
6242
+ XCTAssertEqual(updater.downloadCalls, 1)
6243
+ XCTAssertEqual(updater.lastSetNextBundleId, "reuse-js-9.8.0")
6244
+ XCTAssertEqual(notifiedBundle?["link"] as? String, "https://example.com/release-notes")
6245
+ XCTAssertEqual(notifiedBundle?["comment"] as? String, "server comment")
6246
+ }
6247
+
6248
+ func testBackgroundDownloadDoesNotQueueBundleMarkedErrorBeforeCommit() throws {
6249
+ let testLogger = Logger(withTag: "TestLogger", options: Logger.Options(level: .silent))
6250
+ CryptoCipher.setLogger(testLogger)
6251
+
6252
+ let current = BundleInfo(id: "current-id", version: "1.0.0", status: .SUCCESS, downloaded: Date(), checksum: "cur")
6253
+ let downloaded = BundleInfo(id: "commit-9.9.0", version: "9.9.0", status: .PENDING, downloaded: Date(), checksum: "abc123")
6254
+ let latest = AppVersion()
6255
+ latest.version = "9.9.0"
6256
+ latest.url = "https://example.com/update-9.9.0.zip"
6257
+ latest.checksum = "abc123"
6258
+
6259
+ let updater = CoalescingDownloadCapgoUpdater()
6260
+ updater.setLogger(testLogger)
6261
+ updater.currentBundleValue = current
6262
+ updater.latestResponse = latest
6263
+ updater.downloadedBundleValue = downloaded
6264
+ updater.onDownloadStart = {
6265
+ // setBundleError marks the bundle after the automatic check scanned the version for ERROR copies.
6266
+ updater.storedBundleInfoOverrides["commit-9.9.0"] = BundleInfo(
6267
+ id: "commit-9.9.0",
6268
+ version: "9.9.0",
6269
+ status: .ERROR,
6270
+ downloaded: Date(),
6271
+ checksum: "abc123"
6272
+ )
6273
+ }
6274
+
6275
+ let testPlugin = ConcurrentDownloadCapacitorUpdaterPlugin()
6276
+ testPlugin.implementation = updater
6277
+ testPlugin.setAutoUpdateModeForTesting(CapacitorUpdaterPlugin.autoUpdateModeBackground)
6278
+ testPlugin.setUpdateUrlForTesting("https://example.com/channel")
6279
+
6280
+ let bgRejected = expectation(description: "commit rejected the bundle marked ERROR")
6281
+ testPlugin.onSendReadyToJs = { msg in
6282
+ if msg == "Latest version is in error state. Aborting update." {
6283
+ bgRejected.fulfill()
6284
+ }
6285
+ }
6286
+ testPlugin.backgroundDownload()
6287
+ wait(for: [bgRejected], timeout: 5.0)
6288
+
6289
+ XCTAssertEqual(updater.downloadCalls, 1)
6290
+ XCTAssertEqual(updater.setNextBundleCalls, 0)
6291
+ }
6292
+
6293
+ func testFillStoredBundleMetadataDoesNotRecreateDeletedRecord() {
6294
+ let updater = CapgoUpdater()
6295
+ updater.setLogger(Logger(withTag: "TestLogger", options: Logger.Options(level: .silent)))
6296
+ let id = "deletedMeta"
6297
+ UserDefaults.standard.removeObject(forKey: "\(id)_info")
6298
+
6299
+ let filled = updater.fillStoredBundleMetadataIfPresent(id: id, link: "https://example.com", comment: "c")
6300
+
6301
+ XCTAssertNil(filled)
6302
+ XCTAssertNil(UserDefaults.standard.object(forKey: "\(id)_info"))
6303
+ }
6304
+
6305
+ func testApplyCurrentBundleToBridgeReloadsAtomicallyOnMainThread() throws {
6306
+ let serverURL = try XCTUnwrap(URL(string: "capacitor://localhost"))
6307
+ let targetPath = "/var/mobile/Containers/Data/Application/bundle-2.0.0"
6308
+ var activeBasePath = "/var/mobile/Containers/Data/Application/public"
6309
+ var events: [String] = []
6310
+ var loadedURL: URL?
6311
+ var basePathAtLoadTime: String?
6312
+
6313
+ CapacitorUpdaterPlugin.reloadServerBasePathAtomically(
6314
+ path: targetPath,
6315
+ serverURL: serverURL,
6316
+ setServerBasePath: { nextPath in
6317
+ activeBasePath = nextPath
6318
+ events.append("setServerBasePath")
6319
+ },
6320
+ loadRequest: { request in
6321
+ loadedURL = request.url
6322
+ basePathAtLoadTime = activeBasePath
6323
+ events.append("load")
6324
+ }
6325
+ )
6326
+
6327
+ XCTAssertEqual(events, ["setServerBasePath", "load"])
6328
+ XCTAssertEqual(loadedURL, serverURL)
6329
+ XCTAssertEqual(basePathAtLoadTime, targetPath)
6330
+ }
6331
+
6332
+ }
6333
+
6334
+ private final class OnceSignal {
6335
+ private let lock = NSLock()
6336
+ private let group = DispatchGroup()
6337
+ private var signaled = false
6338
+
6339
+ init() {
6340
+ group.enter()
6341
+ }
6342
+
6343
+ @discardableResult
6344
+ func signal() -> Bool {
6345
+ lock.lock()
6346
+ let shouldLeave = !signaled
6347
+ signaled = true
6348
+ lock.unlock()
6349
+ if shouldLeave {
6350
+ group.leave()
6351
+ }
6352
+ return shouldLeave
6353
+ }
6354
+
6355
+ func wait(timeout: DispatchTime) -> DispatchTimeoutResult {
6356
+ group.wait(timeout: timeout)
6357
+ }
6358
+ }
6359
+
6360
+ private final class CoalescingDownloadCapgoUpdater: FreshDownloadCapgoUpdater {
6361
+ private let stateLock = NSLock()
6362
+ var onSetNextBundle: (() -> Void)?
6363
+ var onManifestDownloadStart: (() -> Void)?
6364
+ var downloadedManifestBundleValue: BundleInfo?
6365
+ var manifestDownloadBundles: [BundleInfo] = []
6366
+ /// When set, manifest downloads return the bundle keyed by the first entry's file hash instead of call order.
6367
+ var manifestBundlesByFirstHash: [String: BundleInfo] = [:]
6368
+ var onManifestDownload: (([ManifestEntry]) -> Void)?
6369
+ var onVersionLookup: (() -> Void)?
6370
+ var zipDownloadBundles: [BundleInfo?] = []
6371
+ private var manifestCallCount = 0
6372
+
6373
+ var manifestDownloadCalls: Int {
6374
+ stateLock.lock()
6375
+ defer { stateLock.unlock() }
6376
+ return manifestCallCount
6377
+ }
6378
+
6379
+ override var currentBundleValue: BundleInfo! {
6380
+ get {
6381
+ stateLock.lock()
6382
+ defer { stateLock.unlock() }
6383
+ return super.currentBundleValue
6384
+ }
6385
+ set {
6386
+ stateLock.lock()
6387
+ super.currentBundleValue = newValue
6388
+ stateLock.unlock()
6389
+ }
6390
+ }
6391
+
6392
+ override var existingBundleValue: BundleInfo? {
6393
+ get {
6394
+ stateLock.lock()
6395
+ defer { stateLock.unlock() }
6396
+ return super.existingBundleValue
6397
+ }
6398
+ set {
6399
+ stateLock.lock()
6400
+ super.existingBundleValue = newValue
6401
+ stateLock.unlock()
6402
+ }
6403
+ }
6404
+
6405
+ override func downloadVerifiedWithTransferHook(
6406
+ url: URL,
6407
+ version: String,
6408
+ sessionKey: String,
6409
+ expectedChecksum: String,
6410
+ link: String?,
6411
+ comment: String?,
6412
+ beforeTransfer: (() throws -> Void)?
6413
+ ) throws -> BundleInfo {
6414
+ try beforeTransfer?()
6415
+ return try self.downloadVerified(
6416
+ url: url,
6417
+ version: version,
6418
+ sessionKey: sessionKey,
6419
+ expectedChecksum: expectedChecksum,
6420
+ link: link,
6421
+ comment: comment
6422
+ )
6423
+ }
6424
+
6425
+ override func downloadManifestWithTransferHook(
6426
+ manifest: [ManifestEntry],
6427
+ version: String,
6428
+ sessionKey: String,
6429
+ link: String?,
6430
+ comment: String?,
6431
+ beforeTransfer: (() throws -> Void)?
6432
+ ) throws -> BundleInfo {
6433
+ try beforeTransfer?()
6434
+ return try self.downloadManifest(
6435
+ manifest: manifest,
6436
+ version: version,
6437
+ sessionKey: sessionKey,
6438
+ link: link,
6439
+ comment: comment
6440
+ )
6441
+ }
6442
+
6443
+ override func downloadVerified(
6444
+ url _: URL,
6445
+ version _: String,
6446
+ sessionKey _: String,
6447
+ expectedChecksum _: String,
6448
+ link _: String? = nil,
6449
+ comment _: String? = nil
6450
+ ) throws -> BundleInfo {
6451
+ stateLock.lock()
6452
+ let index = downloadCalls
6453
+ downloadCalls += 1
6454
+ let bundle: BundleInfo? = index < zipDownloadBundles.count
6455
+ ? zipDownloadBundles[index]
6456
+ : downloadedBundleValue
6457
+ stateLock.unlock()
6458
+
6459
+ onDownloadStart?()
6460
+ if let bundle {
6461
+ return bundle
6462
+ }
6463
+ throw NSError(domain: "CapacitorUpdaterPluginTests", code: 1)
6464
+ }
6465
+
6466
+ override func getBundleInfosByVersionName(version: String) -> [BundleInfo] {
6467
+ onVersionLookup?()
6468
+ return super.getBundleInfosByVersionName(version: version)
6469
+ }
6470
+
6471
+ override func downloadManifest(
6472
+ manifest: [ManifestEntry],
6473
+ version _: String,
6474
+ sessionKey _: String,
6475
+ link _: String? = nil,
6476
+ comment _: String? = nil
6477
+ ) throws -> BundleInfo {
6478
+ stateLock.lock()
6479
+ manifestCallCount += 1
6480
+ let index = manifestCallCount - 1
6481
+ let bundle: BundleInfo?
6482
+ if let hash = manifest.first?.file_hash, let mapped = manifestBundlesByFirstHash[hash] {
6483
+ bundle = mapped
6484
+ } else {
6485
+ bundle = index < manifestDownloadBundles.count
6486
+ ? manifestDownloadBundles[index]
6487
+ : downloadedManifestBundleValue
6488
+ }
6489
+ stateLock.unlock()
6490
+
6491
+ onManifestDownloadStart?()
6492
+ onManifestDownload?(manifest)
6493
+ if let bundle {
6494
+ return bundle
6495
+ }
6496
+ throw NSError(domain: "CapacitorUpdaterPluginTests", code: 2)
6497
+ }
6498
+
6499
+ override func setNextBundle(next: String?) -> Bool {
6500
+ let result = super.setNextBundle(next: next)
6501
+ onSetNextBundle?()
6502
+ return result
6503
+ }
6504
+ }
6505
+
6506
+ private final class ConcurrentDownloadCapacitorUpdaterPlugin: CapacitorUpdaterPlugin {
6507
+ var onSendReadyToJs: ((String) -> Void)?
6508
+ var onUpdateAvailable: (([String: Any]) -> Void)?
6509
+ private let eventsLock = NSLock()
6510
+ private var updateAvailableBundles: [[String: Any]] = []
6511
+
6512
+ var notifiedUpdateAvailableBundles: [[String: Any]] {
6513
+ eventsLock.lock()
6514
+ defer { eventsLock.unlock() }
6515
+ return updateAvailableBundles
6516
+ }
6517
+
6518
+ override func beginDownloadBackgroundTask() {}
6519
+ override func endBackGroundTask() {}
6520
+ override func notifyListeners(_ eventName: String, data: [String: Any]?, retainUntilConsumed retain: Bool) {
6521
+ let event = decodeUpdaterEvent(eventName, data: data)
6522
+ guard event.name == "updateAvailable", let bundle = event.data?["bundle"] as? [String: Any] else {
6523
+ return
6524
+ }
6525
+ eventsLock.lock()
6526
+ updateAvailableBundles.append(bundle)
6527
+ eventsLock.unlock()
6528
+ onUpdateAvailable?(bundle)
6529
+ }
6530
+ override func sendReadyToJs(current: BundleInfo, msg: String) {
6531
+ onSendReadyToJs?(msg)
6532
+ }
3905
6533
  }