@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.1

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 (185) hide show
  1. package/CHANGELOG.md +473 -2
  2. package/LICENSE +21 -0
  3. package/README.md +279 -47
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +20 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/GENERATED.md +1 -0
  14. package/android/vendor/java/com/appswissknife/SwissKnife.kt +111 -38
  15. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  16. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  17. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  18. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  19. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  20. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  21. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  22. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  23. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  24. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  25. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  26. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  27. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  32. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  34. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  35. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +312 -65
  36. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  37. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +705 -96
  38. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  39. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +29 -0
  40. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +24 -0
  41. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  44. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  45. package/app.plugin.js +343 -0
  46. package/ios/SwissKnifeJSON.swift +24 -2
  47. package/ios/SwissKnifePurchases.m +20 -0
  48. package/ios/SwissKnifePurchases.swift +97 -3
  49. package/ios/SwissKnifePushBootstrap.m +34 -0
  50. package/ios/vendor/GENERATED.md +1 -0
  51. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  52. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  53. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  54. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  55. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  56. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  57. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  58. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  59. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  60. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  61. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  62. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
  63. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  64. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  65. package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
  66. package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
  67. package/ios-notification-service/vendor/GENERATED.md +11 -0
  68. package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
  69. package/lib/commonjs/attribution.js +4 -3
  70. package/lib/commonjs/attribution.js.map +1 -1
  71. package/lib/commonjs/identity.js +12 -11
  72. package/lib/commonjs/identity.js.map +1 -1
  73. package/lib/commonjs/index.js +16 -5
  74. package/lib/commonjs/index.js.map +1 -1
  75. package/lib/commonjs/internal/config.js +105 -8
  76. package/lib/commonjs/internal/config.js.map +1 -1
  77. package/lib/commonjs/internal/telemetry-context.js +70 -0
  78. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  79. package/lib/commonjs/modules/analytics.js +18 -25
  80. package/lib/commonjs/modules/analytics.js.map +1 -1
  81. package/lib/commonjs/modules/crash-reporting.js +27 -6
  82. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  83. package/lib/commonjs/modules/log.js +1 -1
  84. package/lib/commonjs/modules/notifications.js +500 -0
  85. package/lib/commonjs/modules/notifications.js.map +1 -0
  86. package/lib/commonjs/modules/performance.js +57 -8
  87. package/lib/commonjs/modules/performance.js.map +1 -1
  88. package/lib/commonjs/native/module.js +6 -0
  89. package/lib/commonjs/native/module.js.map +1 -1
  90. package/lib/commonjs/native/spec.js +12 -5
  91. package/lib/commonjs/native/spec.js.map +1 -1
  92. package/lib/commonjs/purchases.js +4 -4
  93. package/lib/commonjs/types.js +12 -15
  94. package/lib/commonjs/types.js.map +1 -1
  95. package/lib/module/attribution.js +4 -3
  96. package/lib/module/attribution.js.map +1 -1
  97. package/lib/module/identity.js +12 -11
  98. package/lib/module/identity.js.map +1 -1
  99. package/lib/module/index.js +8 -4
  100. package/lib/module/index.js.map +1 -1
  101. package/lib/module/internal/config.js +103 -8
  102. package/lib/module/internal/config.js.map +1 -1
  103. package/lib/module/internal/telemetry-context.js +63 -0
  104. package/lib/module/internal/telemetry-context.js.map +1 -0
  105. package/lib/module/modules/analytics.js +18 -25
  106. package/lib/module/modules/analytics.js.map +1 -1
  107. package/lib/module/modules/crash-reporting.js +27 -6
  108. package/lib/module/modules/crash-reporting.js.map +1 -1
  109. package/lib/module/modules/log.js +1 -1
  110. package/lib/module/modules/notifications.js +491 -0
  111. package/lib/module/modules/notifications.js.map +1 -0
  112. package/lib/module/modules/performance.js +57 -8
  113. package/lib/module/modules/performance.js.map +1 -1
  114. package/lib/module/native/module.js +6 -1
  115. package/lib/module/native/module.js.map +1 -1
  116. package/lib/module/native/spec.js +11 -4
  117. package/lib/module/native/spec.js.map +1 -1
  118. package/lib/module/purchases.js +4 -4
  119. package/lib/module/types.js +12 -15
  120. package/lib/module/types.js.map +1 -1
  121. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  122. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  123. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/index.d.ts +2 -0
  125. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  127. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  128. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  129. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  130. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  131. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  133. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  135. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  136. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  137. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  138. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  139. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  140. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  141. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  142. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  143. package/lib/typescript/commonjs/types.d.ts +4 -5
  144. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  145. package/lib/typescript/module/attribution.d.ts +3 -2
  146. package/lib/typescript/module/attribution.d.ts.map +1 -1
  147. package/lib/typescript/module/identity.d.ts.map +1 -1
  148. package/lib/typescript/module/index.d.ts +2 -0
  149. package/lib/typescript/module/index.d.ts.map +1 -1
  150. package/lib/typescript/module/internal/config.d.ts +16 -2
  151. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  152. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  153. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  154. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  155. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  156. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  157. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  158. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  159. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  160. package/lib/typescript/module/modules/performance.d.ts +13 -0
  161. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  162. package/lib/typescript/module/native/module.d.ts +2 -0
  163. package/lib/typescript/module/native/module.d.ts.map +1 -1
  164. package/lib/typescript/module/native/spec.d.ts +33 -4
  165. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  166. package/lib/typescript/module/purchases.d.ts +4 -4
  167. package/lib/typescript/module/types.d.ts +4 -5
  168. package/lib/typescript/module/types.d.ts.map +1 -1
  169. package/package.json +13 -4
  170. package/src/attribution.ts +4 -3
  171. package/src/identity.ts +12 -11
  172. package/src/index.ts +16 -4
  173. package/src/internal/config.ts +113 -8
  174. package/src/internal/telemetry-context.ts +76 -0
  175. package/src/modules/analytics.ts +24 -33
  176. package/src/modules/crash-reporting.ts +50 -9
  177. package/src/modules/log.ts +1 -1
  178. package/src/modules/notifications.ts +557 -0
  179. package/src/modules/performance.ts +94 -14
  180. package/src/native/module.ts +6 -0
  181. package/src/native/spec.ts +45 -10
  182. package/src/purchases.ts +4 -4
  183. package/src/types.ts +12 -15
  184. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  185. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -0,0 +1,322 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Notifications/PushRegistrar.swift
2
+ //
3
+ // Device upsert (`POST /api/sdk/push/devices`) with a persisted fingerprint so
4
+ // identical state is never re-sent, plus the batched, disk-backed event queue
5
+ // (`POST /api/sdk/push/events`).
6
+
7
+ import CryptoKit
8
+ import Foundation
9
+
10
+ // MARK: - Transport seam
11
+
12
+ internal protocol PushTransport: Sendable {
13
+ func post(path: String, body: Data) async throws
14
+ }
15
+
16
+ internal struct BackendPushTransport: PushTransport {
17
+ func post(path: String, body: Data) async throws {
18
+ // Retries (and the 30s deadline) live in BackendHttpClient.
19
+ _ = try await BackendHttpClient.shared.postRaw(path: path, body: body, maxRetries: 3)
20
+ }
21
+ }
22
+
23
+ // MARK: - Device upsert body
24
+
25
+ internal struct PushDeviceUpsert: Codable, Equatable {
26
+ var installId: String
27
+ var platform = "ios"
28
+ var provider = "apns"
29
+ var token: String?
30
+ var environment: String
31
+ var bundleId: String
32
+ var permissionStatus: String
33
+ var userId: String?
34
+ var anonymousId: String?
35
+ var appVersion: String?
36
+ var sdkVersion: String?
37
+ var osVersion: String?
38
+ var locale: String?
39
+ var timezone: String?
40
+ /// Set only for an EXPLICIT logout: the body then carries `user_id: null`
41
+ /// (server unlinks). Otherwise a nil `userId` is omitted (server keeps the
42
+ /// link) — identity is in-memory only, so after a relaunch it is unknown,
43
+ /// not "logged out".
44
+ var unlinkUser = false
45
+
46
+ enum CodingKeys: String, CodingKey {
47
+ case installId = "install_id", platform, provider, token, environment
48
+ case bundleId = "bundle_id", permissionStatus = "permission_status"
49
+ case userId = "user_id", anonymousId = "anonymous_id"
50
+ case appVersion = "app_version", sdkVersion = "sdk_version", osVersion = "os_version"
51
+ case locale, timezone
52
+ }
53
+
54
+ /// Always emits `token` (null when absent) — null means "unregistered".
55
+ func encode(to encoder: Encoder) throws {
56
+ var c = encoder.container(keyedBy: CodingKeys.self)
57
+ try c.encode(installId, forKey: .installId)
58
+ try c.encode(platform, forKey: .platform)
59
+ try c.encode(provider, forKey: .provider)
60
+ try c.encode(token, forKey: .token)
61
+ try c.encode(environment, forKey: .environment)
62
+ try c.encode(bundleId, forKey: .bundleId)
63
+ try c.encode(permissionStatus, forKey: .permissionStatus)
64
+ if let userId {
65
+ try c.encode(userId, forKey: .userId)
66
+ } else if unlinkUser {
67
+ try c.encodeNil(forKey: .userId) // explicit logout: unlink
68
+ }
69
+ try c.encodeIfPresent(anonymousId, forKey: .anonymousId)
70
+ try c.encodeIfPresent(appVersion, forKey: .appVersion)
71
+ try c.encodeIfPresent(sdkVersion, forKey: .sdkVersion)
72
+ try c.encodeIfPresent(osVersion, forKey: .osVersion)
73
+ try c.encodeIfPresent(locale, forKey: .locale)
74
+ try c.encodeIfPresent(timezone, forKey: .timezone)
75
+ }
76
+
77
+ func encoded() -> Data {
78
+ let enc = JSONEncoder()
79
+ enc.outputFormatting = [.sortedKeys]
80
+ return (try? enc.encode(self)) ?? Data()
81
+ }
82
+
83
+ /// Stable digest of everything that would go on the wire.
84
+ var fingerprint: String {
85
+ // `unlinkUser` only changes HOW "no user" is spelled, not the state.
86
+ var copy = self
87
+ copy.unlinkUser = false
88
+ return SHA256.hash(data: copy.encoded()).map { String(format: "%02x", $0) }.joined()
89
+ }
90
+ }
91
+
92
+ // MARK: - Registrar
93
+
94
+ internal final class PushRegistrar: @unchecked Sendable {
95
+
96
+ static let shared = PushRegistrar()
97
+
98
+ private enum Key {
99
+ static let token = "com.swissknife.push.token"
100
+ static let fingerprint = "com.swissknife.push.fingerprint"
101
+ static let unlinkPending = "com.swissknife.push.unlinkPending"
102
+ }
103
+
104
+ private let defaults: UserDefaults
105
+ private let transport: PushTransport
106
+ private let lock = NSLock()
107
+ private var inFlight = false
108
+ private var dirty = false
109
+
110
+ /// Builds the upsert from current SDK state. Overridable for tests.
111
+ var snapshot: @Sendable (_ token: String?, _ permission: SwissKnife.Notifications.PermissionStatus) -> PushDeviceUpsert? =
112
+ { PushRegistrar.liveSnapshot(token: $0, permission: $1) }
113
+ var permissionProvider: @Sendable () async -> SwissKnife.Notifications.PermissionStatus =
114
+ { await PushPermission.current() }
115
+
116
+ init(defaults: UserDefaults = .standard, transport: PushTransport = BackendPushTransport()) {
117
+ self.defaults = defaults
118
+ self.transport = transport
119
+ }
120
+
121
+ var token: String? {
122
+ get { defaults.string(forKey: Key.token) }
123
+ set { defaults.set(newValue, forKey: Key.token) }
124
+ }
125
+
126
+ /// True once the app has engaged with push at all (token or a prior sync).
127
+ /// Apps that never use push never hit the endpoint from identity changes.
128
+ var isEngaged: Bool { token != nil || defaults.string(forKey: Key.fingerprint) != nil }
129
+
130
+ /// An explicit logout happened and the server has not been told yet.
131
+ /// Persisted so a failed/killed request is retried on a later launch.
132
+ var unlinkPending: Bool {
133
+ get { defaults.bool(forKey: Key.unlinkPending) }
134
+ set { defaults.set(newValue, forKey: Key.unlinkPending) }
135
+ }
136
+
137
+ var lastFingerprint: String? { defaults.string(forKey: Key.fingerprint) }
138
+
139
+ func reset() {
140
+ defaults.removeObject(forKey: Key.token)
141
+ defaults.removeObject(forKey: Key.fingerprint)
142
+ defaults.removeObject(forKey: Key.unlinkPending)
143
+ }
144
+
145
+ /// Upsert if (and only if) the state differs from what was last
146
+ /// acknowledged. Returns true when a request was sent successfully.
147
+ @discardableResult
148
+ func sync(force: Bool = false) async -> Bool {
149
+ // Coalesce: one request at a time; a state change during a request
150
+ // triggers exactly one more pass.
151
+ guard beginSync() else { return false }
152
+
153
+ var sent = false
154
+ while true {
155
+ clearDirty()
156
+ let permission = await permissionProvider()
157
+ if var body = snapshot(token, permission) {
158
+ body.unlinkUser = body.userId == nil && unlinkPending
159
+ let fp = body.fingerprint
160
+ if force || fp != lastFingerprint || body.unlinkUser {
161
+ do {
162
+ try await transport.post(path: "/api/sdk/push/devices", body: body.encoded())
163
+ defaults.set(fp, forKey: Key.fingerprint)
164
+ if body.userId != nil || body.unlinkUser { unlinkPending = false }
165
+ sent = true
166
+ } catch {
167
+ // Fingerprint stays stale, so the next trigger retries.
168
+ }
169
+ }
170
+ }
171
+ if !endSyncPass() { break }
172
+ }
173
+ return sent
174
+ }
175
+
176
+ /// Configure-time resume: upsert a stored token now (deduped by fingerprint).
177
+ func resume() async {
178
+ guard isEngaged else { return }
179
+ await sync()
180
+ }
181
+
182
+ // Sync lock helpers (NSLock must not be taken directly in async code).
183
+ private func beginSync() -> Bool {
184
+ lock.lock(); defer { lock.unlock() }
185
+ if inFlight { dirty = true; return false }
186
+ inFlight = true
187
+ return true
188
+ }
189
+ private func clearDirty() { lock.lock(); dirty = false; lock.unlock() }
190
+ /// true = state changed mid-request, run another pass.
191
+ private func endSyncPass() -> Bool {
192
+ lock.lock(); defer { lock.unlock() }
193
+ if dirty { return true }
194
+ inFlight = false
195
+ return false
196
+ }
197
+
198
+ static func liveSnapshot(
199
+ token: String?,
200
+ permission: SwissKnife.Notifications.PermissionStatus
201
+ ) -> PushDeviceUpsert? {
202
+ guard SwissKnife.isCoreConfigured else { return nil }
203
+ let ctx = DeviceContextProvider.current()
204
+ let identity = SwissKnife.Identity.current
205
+ return PushDeviceUpsert(
206
+ installId: DeviceID.get(),
207
+ token: token,
208
+ environment: PushEnvironment.detectFromBundle(),
209
+ bundleId: ctx.bundleIdentifier ?? "",
210
+ permissionStatus: permission.rawValue,
211
+ userId: identity.userId,
212
+ anonymousId: identity.anonymousId,
213
+ appVersion: ctx.appVersion,
214
+ sdkVersion: ctx.sdkVersion,
215
+ osVersion: ctx.osVersion,
216
+ locale: Locale.current.identifier.replacingOccurrences(of: "_", with: "-"),
217
+ timezone: ctx.timezone
218
+ )
219
+ }
220
+ }
221
+
222
+ // MARK: - Events
223
+
224
+ internal struct PushEventItem: Codable, Identifiable, Equatable {
225
+ let deliveryId: String
226
+ let messageId: String
227
+ let type: String // received | opened | action
228
+ let actionId: String?
229
+ let occurredAt: String
230
+
231
+ var id: String { "\(deliveryId):\(type):\(actionId ?? "")" }
232
+
233
+ enum CodingKeys: String, CodingKey {
234
+ case deliveryId = "delivery_id", messageId = "message_id", type
235
+ case actionId = "action_id", occurredAt = "occurred_at"
236
+ }
237
+
238
+ func encode(to encoder: Encoder) throws {
239
+ var c = encoder.container(keyedBy: CodingKeys.self)
240
+ try c.encode(deliveryId, forKey: .deliveryId)
241
+ try c.encode(messageId, forKey: .messageId)
242
+ try c.encode(type, forKey: .type)
243
+ try c.encodeIfPresent(actionId, forKey: .actionId)
244
+ try c.encode(occurredAt, forKey: .occurredAt)
245
+ }
246
+ }
247
+
248
+ internal final class PushEventQueue: @unchecked Sendable {
249
+
250
+ static let shared: PushEventQueue = {
251
+ if let q = try? OfflineQueueStore<PushEventItem>(name: "push-events") {
252
+ return PushEventQueue(store: q)
253
+ }
254
+ return PushEventQueue(store: OfflineQueueStore<PushEventItem>(inMemoryName: "push-events-mem"))
255
+ }()
256
+
257
+ static let batchSize = 100
258
+
259
+ private let store: OfflineQueueStore<PushEventItem>
260
+ private let transport: PushTransport
261
+ private let lock = NSLock()
262
+ private var flushing = false
263
+ private let autoFlush: Bool
264
+
265
+ init(store: OfflineQueueStore<PushEventItem>, transport: PushTransport = BackendPushTransport(), autoFlush: Bool = true) {
266
+ self.store = store
267
+ self.transport = transport
268
+ self.autoFlush = autoFlush
269
+ }
270
+
271
+ func track(_ payload: SwissKnife.Notifications.Payload, type: String, actionId: String? = nil) {
272
+ let item = PushEventItem(
273
+ deliveryId: payload.deliveryId,
274
+ messageId: payload.messageId,
275
+ type: type,
276
+ actionId: actionId,
277
+ occurredAt: ISO8601DateFormatter.withFractions.string(from: Date())
278
+ )
279
+ // Already queued (same delivery + type + action): don't double-append.
280
+ if let existing = try? store.readAll(), existing.contains(where: { $0.id == item.id }) { return }
281
+ try? store.append(item)
282
+ if autoFlush { Task { await self.flush() } }
283
+ }
284
+
285
+ private func beginFlush() -> Bool {
286
+ lock.lock(); defer { lock.unlock() }
287
+ if flushing { return false }
288
+ flushing = true
289
+ return true
290
+ }
291
+
292
+ private func endFlush() {
293
+ lock.lock(); flushing = false; lock.unlock()
294
+ }
295
+
296
+ func flush() async {
297
+ guard beginFlush() else { return }
298
+ defer { endFlush() }
299
+
300
+ while let items = try? store.readAll(), !items.isEmpty {
301
+ let batch = Array(items.prefix(Self.batchSize))
302
+ guard let body = try? JSONEncoder().encode(["events": batch]) else { return }
303
+ do {
304
+ try await transport.post(path: "/api/sdk/push/events", body: body)
305
+ try? store.remove(ids: Set(batch.map(\.id)))
306
+ } catch PurchasesError.backendRejected(let code, _) where code != 429 {
307
+ // Permanent rejection: drop the batch, don't retry forever.
308
+ try? store.remove(ids: Set(batch.map(\.id)))
309
+ } catch {
310
+ return // offline / 5xx: stays on disk for the next flush
311
+ }
312
+ }
313
+ }
314
+ }
315
+
316
+ internal extension ISO8601DateFormatter {
317
+ static let withFractions: ISO8601DateFormatter = {
318
+ let f = ISO8601DateFormatter()
319
+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
320
+ return f
321
+ }()
322
+ }