@app-swiss-knife/react-native-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +182 -0
  2. package/SwissKnifePurchases.podspec +40 -0
  3. package/android/build.gradle +89 -0
  4. package/android/gradle.properties +3 -0
  5. package/android/src/main/AndroidManifest.xml +26 -0
  6. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
  7. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
  8. package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
  11. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
  12. package/android/vendor/GENERATED.md +10 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
  14. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
  15. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
  16. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
  17. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
  18. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
  19. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
  20. package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
  21. package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
  22. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
  23. package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
  24. package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
  25. package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
  26. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
  27. package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
  28. package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
  29. package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
  30. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
  31. package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
  32. package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
  33. package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
  34. package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
  35. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
  36. package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
  37. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
  38. package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
  39. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
  40. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
  41. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
  42. package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
  43. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
  44. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
  45. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
  46. package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
  47. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
  48. package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
  49. package/ios/SwissKnifeCrashReporting.m +32 -0
  50. package/ios/SwissKnifeCrashReporting.swift +186 -0
  51. package/ios/SwissKnifeJSON.swift +347 -0
  52. package/ios/SwissKnifePurchases.m +124 -0
  53. package/ios/SwissKnifePurchases.swift +523 -0
  54. package/ios/vendor/GENERATED.md +10 -0
  55. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
  56. package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
  57. package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
  58. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
  59. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
  60. package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
  61. package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
  62. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
  63. package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
  64. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
  65. package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
  66. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
  67. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
  68. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
  69. package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
  70. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
  71. package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
  72. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
  73. package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
  74. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
  75. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
  76. package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
  77. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
  78. package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
  79. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
  80. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
  81. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
  82. package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
  83. package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
  84. package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
  85. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
  86. package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
  87. package/lib/commonjs/attribution.js +55 -0
  88. package/lib/commonjs/attribution.js.map +1 -0
  89. package/lib/commonjs/identity.js +126 -0
  90. package/lib/commonjs/identity.js.map +1 -0
  91. package/lib/commonjs/index.js +118 -0
  92. package/lib/commonjs/index.js.map +1 -0
  93. package/lib/commonjs/modules/analytics.js +646 -0
  94. package/lib/commonjs/modules/analytics.js.map +1 -0
  95. package/lib/commonjs/modules/attachments.js +169 -0
  96. package/lib/commonjs/modules/attachments.js.map +1 -0
  97. package/lib/commonjs/modules/crash-reporting.js +1327 -0
  98. package/lib/commonjs/modules/crash-reporting.js.map +1 -0
  99. package/lib/commonjs/modules/ids.js +50 -0
  100. package/lib/commonjs/modules/ids.js.map +1 -0
  101. package/lib/commonjs/modules/log.js +59 -0
  102. package/lib/commonjs/modules/log.js.map +1 -0
  103. package/lib/commonjs/modules/offline-store.js +44 -0
  104. package/lib/commonjs/modules/offline-store.js.map +1 -0
  105. package/lib/commonjs/modules/performance.js +494 -0
  106. package/lib/commonjs/modules/performance.js.map +1 -0
  107. package/lib/commonjs/native/module.js +41 -0
  108. package/lib/commonjs/native/module.js.map +1 -0
  109. package/lib/commonjs/native/spec.js +26 -0
  110. package/lib/commonjs/native/spec.js.map +1 -0
  111. package/lib/commonjs/package.json +1 -0
  112. package/lib/commonjs/purchases.js +194 -0
  113. package/lib/commonjs/purchases.js.map +1 -0
  114. package/lib/commonjs/types.js +236 -0
  115. package/lib/commonjs/types.js.map +1 -0
  116. package/lib/module/attribution.js +51 -0
  117. package/lib/module/attribution.js.map +1 -0
  118. package/lib/module/identity.js +122 -0
  119. package/lib/module/identity.js.map +1 -0
  120. package/lib/module/index.js +36 -0
  121. package/lib/module/index.js.map +1 -0
  122. package/lib/module/modules/analytics.js +642 -0
  123. package/lib/module/modules/analytics.js.map +1 -0
  124. package/lib/module/modules/attachments.js +162 -0
  125. package/lib/module/modules/attachments.js.map +1 -0
  126. package/lib/module/modules/crash-reporting.js +1320 -0
  127. package/lib/module/modules/crash-reporting.js.map +1 -0
  128. package/lib/module/modules/ids.js +44 -0
  129. package/lib/module/modules/ids.js.map +1 -0
  130. package/lib/module/modules/log.js +54 -0
  131. package/lib/module/modules/log.js.map +1 -0
  132. package/lib/module/modules/offline-store.js +39 -0
  133. package/lib/module/modules/offline-store.js.map +1 -0
  134. package/lib/module/modules/performance.js +491 -0
  135. package/lib/module/modules/performance.js.map +1 -0
  136. package/lib/module/native/module.js +34 -0
  137. package/lib/module/native/module.js.map +1 -0
  138. package/lib/module/native/spec.js +22 -0
  139. package/lib/module/native/spec.js.map +1 -0
  140. package/lib/module/package.json +1 -0
  141. package/lib/module/purchases.js +187 -0
  142. package/lib/module/purchases.js.map +1 -0
  143. package/lib/module/types.js +230 -0
  144. package/lib/module/types.js.map +1 -0
  145. package/lib/typescript/commonjs/attribution.d.ts +24 -0
  146. package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/identity.d.ts +37 -0
  148. package/lib/typescript/commonjs/identity.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/index.d.ts +15 -0
  150. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
  152. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
  153. package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
  154. package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
  155. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
  156. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
  157. package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
  158. package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
  159. package/lib/typescript/commonjs/modules/log.d.ts +12 -0
  160. package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
  161. package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
  162. package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
  163. package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
  164. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
  165. package/lib/typescript/commonjs/native/module.d.ts +6 -0
  166. package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
  167. package/lib/typescript/commonjs/native/spec.d.ts +119 -0
  168. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
  169. package/lib/typescript/commonjs/package.json +1 -0
  170. package/lib/typescript/commonjs/purchases.d.ts +68 -0
  171. package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/types.d.ts +384 -0
  173. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  174. package/lib/typescript/module/attribution.d.ts +24 -0
  175. package/lib/typescript/module/attribution.d.ts.map +1 -0
  176. package/lib/typescript/module/identity.d.ts +37 -0
  177. package/lib/typescript/module/identity.d.ts.map +1 -0
  178. package/lib/typescript/module/index.d.ts +15 -0
  179. package/lib/typescript/module/index.d.ts.map +1 -0
  180. package/lib/typescript/module/modules/analytics.d.ts +127 -0
  181. package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
  182. package/lib/typescript/module/modules/attachments.d.ts +50 -0
  183. package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
  184. package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
  185. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
  186. package/lib/typescript/module/modules/ids.d.ts +17 -0
  187. package/lib/typescript/module/modules/ids.d.ts.map +1 -0
  188. package/lib/typescript/module/modules/log.d.ts +12 -0
  189. package/lib/typescript/module/modules/log.d.ts.map +1 -0
  190. package/lib/typescript/module/modules/offline-store.d.ts +9 -0
  191. package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
  192. package/lib/typescript/module/modules/performance.d.ts +75 -0
  193. package/lib/typescript/module/modules/performance.d.ts.map +1 -0
  194. package/lib/typescript/module/native/module.d.ts +6 -0
  195. package/lib/typescript/module/native/module.d.ts.map +1 -0
  196. package/lib/typescript/module/native/spec.d.ts +119 -0
  197. package/lib/typescript/module/native/spec.d.ts.map +1 -0
  198. package/lib/typescript/module/package.json +1 -0
  199. package/lib/typescript/module/purchases.d.ts +68 -0
  200. package/lib/typescript/module/purchases.d.ts.map +1 -0
  201. package/lib/typescript/module/types.d.ts +384 -0
  202. package/lib/typescript/module/types.d.ts.map +1 -0
  203. package/package.json +115 -0
  204. package/react-native.config.js +23 -0
  205. package/src/attribution.ts +56 -0
  206. package/src/identity.ts +133 -0
  207. package/src/index.ts +54 -0
  208. package/src/modules/analytics.ts +689 -0
  209. package/src/modules/attachments.ts +222 -0
  210. package/src/modules/crash-reporting.ts +1577 -0
  211. package/src/modules/ids.ts +41 -0
  212. package/src/modules/log.ts +56 -0
  213. package/src/modules/offline-store.ts +51 -0
  214. package/src/modules/performance.ts +589 -0
  215. package/src/native/module.ts +47 -0
  216. package/src/native/spec.ts +183 -0
  217. package/src/purchases.ts +214 -0
  218. package/src/types.ts +470 -0
@@ -0,0 +1,488 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Analytics/SKAnalytics.swift
2
+ //
3
+ // Amplitude/Mixpanel-compatible analytics SDK for swiss-knife.
4
+ // Drop-in replacement interface — migrate from Amplitude by changing the import.
5
+ //
6
+ // Round A migrated the write path to `IngestClient.shared.enqueue(...)`,
7
+ // which owns its own OfflineQueueStore + retry/backoff loop. Round E
8
+ // then deleted the legacy `EventQueueStore` / `EventTransport` /
9
+ // `BackoffPolicy` / `RetryScheduler` graph that used to live alongside
10
+ // SKAnalytics — nothing in production or tests called into it.
11
+
12
+ import Foundation
13
+ import os.log
14
+
15
+ // MARK: - Configuration
16
+
17
+ public struct SKAnalyticsConfiguration {
18
+ public let apiKey: String
19
+ public var serverURL: String
20
+ public var flushQueueSize: Int
21
+ public var flushIntervalSeconds: TimeInterval
22
+ public var optOut: Bool
23
+ public var logLevel: SKLogLevel
24
+ public var autocaptureOptions: Set<SKAutocaptureOption>
25
+ public var trackingSessionEvents: Bool
26
+ public var minTimeBetweenSessionsMillis: Int
27
+
28
+ public init(
29
+ apiKey: String,
30
+ serverURL: String = "",
31
+ flushQueueSize: Int = 30,
32
+ flushIntervalSeconds: TimeInterval = 30,
33
+ optOut: Bool = false,
34
+ logLevel: SKLogLevel = .warn,
35
+ autocaptureOptions: Set<SKAutocaptureOption> = [.sessions, .appLifecycles],
36
+ trackingSessionEvents: Bool = true,
37
+ minTimeBetweenSessionsMillis: Int = 300_000
38
+ ) {
39
+ self.apiKey = apiKey
40
+ self.serverURL = serverURL
41
+ self.flushQueueSize = flushQueueSize
42
+ self.flushIntervalSeconds = flushIntervalSeconds
43
+ self.optOut = optOut
44
+ self.logLevel = logLevel
45
+ self.autocaptureOptions = autocaptureOptions
46
+ self.trackingSessionEvents = trackingSessionEvents
47
+ self.minTimeBetweenSessionsMillis = minTimeBetweenSessionsMillis
48
+ }
49
+ }
50
+
51
+ public enum SKLogLevel: Int, Comparable {
52
+ case debug = 0, info, warn, error, off
53
+ public static func < (lhs: SKLogLevel, rhs: SKLogLevel) -> Bool { lhs.rawValue < rhs.rawValue }
54
+ }
55
+
56
+ public enum SKAutocaptureOption: String {
57
+ case sessions
58
+ case appLifecycles
59
+ case screenViews
60
+ }
61
+
62
+ // MARK: - Identify (user properties)
63
+
64
+ public final class SKIdentify {
65
+ var operations: [[String: Any]] = []
66
+
67
+ public init() {}
68
+
69
+ @discardableResult
70
+ public func set(property: String, value: Any) -> SKIdentify {
71
+ operations.append(["op": "$set", "key": property, "value": value])
72
+ return self
73
+ }
74
+
75
+ @discardableResult
76
+ public func setOnce(property: String, value: Any) -> SKIdentify {
77
+ operations.append(["op": "$setOnce", "key": property, "value": value])
78
+ return self
79
+ }
80
+
81
+ @discardableResult
82
+ public func unset(property: String) -> SKIdentify {
83
+ operations.append(["op": "$unset", "key": property])
84
+ return self
85
+ }
86
+
87
+ @discardableResult
88
+ public func add(property: String, value: Double) -> SKIdentify {
89
+ operations.append(["op": "$add", "key": property, "value": value])
90
+ return self
91
+ }
92
+
93
+ @discardableResult
94
+ public func append(property: String, value: Any) -> SKIdentify {
95
+ operations.append(["op": "$append", "key": property, "value": value])
96
+ return self
97
+ }
98
+
99
+ @discardableResult
100
+ public func prepend(property: String, value: Any) -> SKIdentify {
101
+ operations.append(["op": "$prepend", "key": property, "value": value])
102
+ return self
103
+ }
104
+
105
+ @discardableResult
106
+ public func remove(property: String, value: Any) -> SKIdentify {
107
+ operations.append(["op": "$remove", "key": property, "value": value])
108
+ return self
109
+ }
110
+
111
+ /// Mixpanel-compatible: append unique values to a list property.
112
+ @discardableResult
113
+ public func union(property: String, values: [Any]) -> SKIdentify {
114
+ operations.append(["op": "$union", "key": property, "value": values])
115
+ return self
116
+ }
117
+
118
+ @discardableResult
119
+ public func clearAll() -> SKIdentify {
120
+ operations.append(["op": "$clearAll"])
121
+ return self
122
+ }
123
+
124
+ func toDict() -> [[String: Any]] { operations }
125
+ }
126
+
127
+ // MARK: - Revenue
128
+
129
+ public final class SKRevenue {
130
+ public var productId: String = ""
131
+ public var quantity: Int = 1
132
+ public var price: Double = 0
133
+ public var revenueType: String?
134
+ public var receipt: String?
135
+ public var eventProperties: [String: Any]?
136
+
137
+ public init() {}
138
+
139
+ func toDict() -> [String: Any] {
140
+ var d: [String: Any] = [
141
+ "productId": productId,
142
+ "quantity": quantity,
143
+ "price": price,
144
+ ]
145
+ if let rt = revenueType { d["revenueType"] = rt }
146
+ if let r = receipt { d["receipt"] = r }
147
+ if let ep = eventProperties { d["eventProperties"] = ep }
148
+ return d
149
+ }
150
+ }
151
+
152
+ // MARK: - Main SDK
153
+
154
+ public final class SKAnalytics {
155
+
156
+ public static let shared = SKAnalytics()
157
+
158
+ private var configuration: SKAnalyticsConfiguration?
159
+ private var userId: String?
160
+ /// Persistent per-device identifier. Resolved lazily on first access and
161
+ /// stored in the Keychain (see `DeviceID`) so it survives app restarts
162
+ /// AND reinstalls — fragmenting analytics by cold-start was the bug this
163
+ /// fixes. `lazy var` because `DeviceID.get()` cannot be a default-value
164
+ /// expression on a stored property.
165
+ private lazy var deviceId: String = DeviceID.get()
166
+ private var sessionId: Int64 = 0
167
+ private var userProperties: [String: Any] = [:]
168
+ private var groups: [String: Any] = [:]
169
+ private var superProperties: [String: Any] = [:]
170
+ private var timedEvents: [String: TimeInterval] = [:]
171
+ private let queue = DispatchQueue(label: "com.swissknife.analytics", qos: .utility)
172
+ private var flushTimer: Timer?
173
+
174
+ /// IngestClient seam — production wires to the shared singleton;
175
+ /// integration tests inject a custom instance backed by a temp-dir
176
+ /// queue and a CapturingTransport so they can assert on the outgoing
177
+ /// envelope shape end-to-end. As of Round E this is the ONLY write
178
+ /// path — the legacy EventQueueStore / EventTransport / BackoffPolicy
179
+ /// / RetryScheduler graph that used to live here was deleted because
180
+ /// nothing called into it after the Round A migration.
181
+ internal var ingest: IngestClient = IngestClient.shared
182
+
183
+ private let log = OSLog(subsystem: "com.swissknife.analytics", category: "SKAnalytics")
184
+
185
+ private var serverURL: String { configuration?.serverURL ?? "" }
186
+
187
+ private init() {}
188
+
189
+ // MARK: Initialize
190
+
191
+ public static func initialize(configuration: SKAnalyticsConfiguration) {
192
+ shared.configuration = configuration
193
+ shared.sessionId = Int64(Date().timeIntervalSince1970 * 1000)
194
+ shared.startFlushTimer()
195
+
196
+ if configuration.autocaptureOptions.contains(.appLifecycles) {
197
+ shared.trackAppLifecycle()
198
+ }
199
+ if configuration.autocaptureOptions.contains(.sessions) {
200
+ shared.track(eventType: "[SwissKnife] Session Start")
201
+ }
202
+ }
203
+
204
+ // MARK: Track events (Amplitude-compatible)
205
+
206
+ public func track(eventType: String, eventProperties: [String: Any]? = nil) {
207
+ guard configuration?.optOut != true else { return }
208
+
209
+ // Merge super properties under event properties (event props override)
210
+ var mergedProps = superProperties
211
+ if let ep = eventProperties {
212
+ for (k, v) in ep { mergedProps[k] = v }
213
+ }
214
+
215
+ // If this event was timed, compute duration
216
+ if let startTime = timedEvents.removeValue(forKey: eventType) {
217
+ mergedProps["$duration"] = Date().timeIntervalSince1970 - startTime
218
+ }
219
+
220
+ // Round-A migration: the event payload is now pure domain data —
221
+ // event_id, user_id, device_id, session_id, timestamp all come from
222
+ // IngestClient's ContextSnapshot stamping at flush time. We just
223
+ // pass `{ event_type, properties }` and let the central pipeline
224
+ // handle context.
225
+ var payload: [String: Any] = [
226
+ "event_type": eventType,
227
+ "properties": mergedProps,
228
+ ]
229
+ // User-scoped props that are still domain-shape, not context.
230
+ if !userProperties.isEmpty {
231
+ payload["user_properties"] = userProperties
232
+ }
233
+ if !groups.isEmpty {
234
+ payload["groups"] = groups
235
+ }
236
+ ingestEnqueue(payload: payload)
237
+ }
238
+
239
+ /// Round-A IngestClient path. Replaces `persistAndMaybeFlush` for the
240
+ /// standard `track(...)` flow. Items land in IngestClient's own
241
+ /// OfflineQueueStore; the cross-cutting ContextSnapshot (event_id,
242
+ /// identity, session, device, timestamp) gets stamped at flush time.
243
+ ///
244
+ /// Opt-out is still checked here even though `track(...)` also gates
245
+ /// on it — defense in depth against future call sites bypassing the
246
+ /// public entry.
247
+ private func ingestEnqueue(payload: [String: Any]) {
248
+ guard configuration?.optOut != true else { return }
249
+ ingest.enqueue(type: .analytics, jsonObject: payload)
250
+ }
251
+
252
+ // Amplitude `track(event:)` overload
253
+ public func track(eventType: String) {
254
+ track(eventType: eventType, eventProperties: nil)
255
+ }
256
+
257
+ /// Persist a pre-built event dictionary directly to the disk-backed queue.
258
+ ///
259
+ /// **For the React Native bridge.** The RN JS layer builds the full event
260
+ /// payload (with `event_id`, `device_id`, super properties, timed-event
261
+ /// duration, identify merges) and hands it off here. We bypass `track(...)`'s
262
+ /// event-construction logic — that logic lives in JS so JS-only state
263
+ /// (super properties, timed events) is honored without round-tripping
264
+ /// through native. Native owns the *queue* (disk persistence, back-off,
265
+ /// dead-letter); JS owns the *payload shape*.
266
+ ///
267
+ /// The event dict must already carry an `event_id` (idempotency key) and
268
+ /// `device_id`. We accept anything JSONSerializable.
269
+ public func trackPreBuiltEvent(_ event: [String: Any]) {
270
+ guard configuration?.optOut != true else { return }
271
+ // Pre-built events from the RN bridge already carry their own
272
+ // event_id, device_id, super-property merges, etc. We pass them
273
+ // through unchanged — IngestClient's ContextSnapshot stamping is
274
+ // additive (it tops up missing fields rather than overwriting).
275
+ ingestEnqueue(payload: event)
276
+ }
277
+
278
+ // MARK: Screen tracking (Mixpanel-compatible)
279
+
280
+ public func trackScreen(name: String, properties: [String: Any]? = nil) {
281
+ var props = properties ?? [:]
282
+ props["[SwissKnife] Screen Name"] = name
283
+ track(eventType: "[SwissKnife] Screen Viewed", eventProperties: props)
284
+ }
285
+
286
+ // MARK: User identity
287
+
288
+ public func setUserId(_ userId: String?) {
289
+ self.userId = userId
290
+ }
291
+
292
+ public func getUserId() -> String? { userId }
293
+
294
+ public func setDeviceId(_ deviceId: String) {
295
+ self.deviceId = deviceId
296
+ }
297
+
298
+ public func getDeviceId() -> String { deviceId }
299
+
300
+ public func getSessionId() -> Int64 { sessionId }
301
+
302
+ public func identify(identify: SKIdentify) {
303
+ let payload: [String: Any] = [
304
+ "event_type": "$identify",
305
+ "user_properties": ["$set": identify.toDict()],
306
+ ]
307
+ ingestEnqueue(payload: payload)
308
+
309
+ // Also apply locally
310
+ for op in identify.operations {
311
+ if let key = op["key"] as? String, let value = op["value"],
312
+ (op["op"] as? String) == "$set" {
313
+ userProperties[key] = value
314
+ }
315
+ }
316
+ }
317
+
318
+ // MARK: Super properties (Mixpanel-compatible)
319
+
320
+ public func registerSuperProperties(_ properties: [String: Any]) {
321
+ for (k, v) in properties { superProperties[k] = v }
322
+ }
323
+
324
+ public func registerSuperPropertiesOnce(_ properties: [String: Any]) {
325
+ for (k, v) in properties where superProperties[k] == nil {
326
+ superProperties[k] = v
327
+ }
328
+ }
329
+
330
+ public func getSuperProperties() -> [String: Any] { superProperties }
331
+
332
+ public func unregisterSuperProperty(_ property: String) {
333
+ superProperties.removeValue(forKey: property)
334
+ }
335
+
336
+ public func clearSuperProperties() {
337
+ superProperties = [:]
338
+ }
339
+
340
+ // MARK: Time events (Mixpanel-compatible)
341
+
342
+ public func timeEvent(_ eventName: String) {
343
+ timedEvents[eventName] = Date().timeIntervalSince1970
344
+ }
345
+
346
+ // MARK: Group helpers (Mixpanel-compatible)
347
+
348
+ public func addGroup(groupType: String, groupName: String) {
349
+ if var existing = groups[groupType] as? [String] {
350
+ if !existing.contains(groupName) { existing.append(groupName) }
351
+ groups[groupType] = existing
352
+ } else {
353
+ groups[groupType] = [groupName]
354
+ }
355
+ }
356
+
357
+ public func reset() {
358
+ userId = nil
359
+ // `reset()` is the explicit "fresh user" path — we rotate the
360
+ // in-memory deviceId but leave the persisted Keychain ID intact so
361
+ // the device continues to be recognisable across launches. If a
362
+ // consumer ever needs to fully wipe the persisted ID, expose a
363
+ // dedicated API; doing it implicitly from reset() would defeat the
364
+ // whole point of Keychain-backed persistence.
365
+ deviceId = IDs.eventId()
366
+ userProperties = [:]
367
+ groups = [:]
368
+ superProperties = [:]
369
+ timedEvents = [:]
370
+ sessionId = Int64(Date().timeIntervalSince1970 * 1000)
371
+ }
372
+
373
+ // MARK: Groups (Amplitude-compatible)
374
+
375
+ public func setGroup(groupType: String, groupName: String) {
376
+ groups[groupType] = groupName
377
+ }
378
+
379
+ public func setGroup(groupType: String, groupNames: [String]) {
380
+ groups[groupType] = groupNames
381
+ }
382
+
383
+ public func groupIdentify(groupType: String, groupName: String, identify: SKIdentify) {
384
+ let payload: [String: Any] = [
385
+ "event_type": "$groupidentify",
386
+ "groups": [groupType: groupName],
387
+ "group_properties": ["$set": identify.toDict()],
388
+ ]
389
+ ingestEnqueue(payload: payload)
390
+ }
391
+
392
+ // MARK: Revenue tracking (Amplitude + Mixpanel compatible)
393
+
394
+ public func revenue(_ revenue: SKRevenue) {
395
+ var props = revenue.eventProperties ?? [:]
396
+ props["$productId"] = revenue.productId
397
+ props["$quantity"] = revenue.quantity
398
+ props["$price"] = revenue.price
399
+ if let rt = revenue.revenueType { props["$revenueType"] = rt }
400
+ track(eventType: "revenue_amount", eventProperties: props)
401
+ }
402
+
403
+ // Mixpanel-compatible alias
404
+ public func trackCharge(amount: Double, properties: [String: Any]? = nil) {
405
+ var props = properties ?? [:]
406
+ props["$amount"] = amount
407
+ track(eventType: "revenue_amount", eventProperties: props)
408
+ }
409
+
410
+ // MARK: Flush
411
+
412
+ /// Public flush entry — idempotent. Delegates to the unified
413
+ /// IngestClient (Round A migration) which owns the retry/backoff
414
+ /// loop, OfflineQueueStore, and dead-letter handling.
415
+ ///
416
+ /// Fire-and-forget by design — the SDK doesn't surface a completion
417
+ /// handler in its public contract.
418
+ public func flush() {
419
+ Task { [ingest] in
420
+ await ingest.flushBestEffort()
421
+ }
422
+ }
423
+
424
+ // MARK: Opt out
425
+
426
+ public func setOptOut(_ optOut: Bool) {
427
+ configuration?.optOut = optOut
428
+ }
429
+
430
+ // MARK: Private
431
+
432
+ private func startFlushTimer() {
433
+ guard let interval = configuration?.flushIntervalSeconds, interval > 0 else { return }
434
+ DispatchQueue.main.async {
435
+ self.flushTimer?.invalidate()
436
+ self.flushTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
437
+ self?.flush()
438
+ }
439
+ }
440
+ }
441
+
442
+ // MARK: Test hooks (internal — visible via `@testable import`)
443
+
444
+ /// Force re-resolution of the deviceId via `DeviceID.get()`. Pairs with
445
+ /// `DeviceID._resetCache_forTesting()` to simulate a fresh process where
446
+ /// the SKAnalytics singleton is rebuilt from Keychain state.
447
+ internal func _resetDeviceIdForTesting() {
448
+ deviceId = DeviceID.get()
449
+ }
450
+
451
+ /// Swap in a test-controlled IngestClient — usually one wired to a
452
+ /// CapturingTransport so the test can assert on the outgoing envelope
453
+ /// shape end-to-end.
454
+ internal func _setIngestForTesting(_ client: IngestClient) {
455
+ queue.sync {
456
+ self.ingest = client
457
+ }
458
+ }
459
+
460
+ /// Block until prior `track(...)` work has drained from the internal
461
+ /// serial queue. Tests use this before reading the IngestClient queue.
462
+ internal func _awaitFlushSettleForTesting() {
463
+ queue.sync { }
464
+ }
465
+
466
+ /// Tear back down the configuration so a fresh `initialize()` from a
467
+ /// later test sets up cleanly.
468
+ internal func _resetConfigurationForTesting() {
469
+ queue.sync {
470
+ self.configuration = nil
471
+ }
472
+ }
473
+
474
+ private func trackAppLifecycle() {
475
+ let info = Bundle.main.infoDictionary
476
+ let version = info?["CFBundleShortVersionString"] as? String ?? "unknown"
477
+ let build = info?["CFBundleVersion"] as? String ?? "unknown"
478
+ track(eventType: "[SwissKnife] Application Installed", eventProperties: [
479
+ "[SwissKnife] App Version": version,
480
+ "[SwissKnife] App Build": build,
481
+ ])
482
+ }
483
+ }
484
+
485
+ // Round E: `FlushOutcome`, `FlushFailureReason`, `RetryScheduler`, and
486
+ // `GCDRetryScheduler` were deleted together with the legacy retry loop
487
+ // they served. IngestClient owns the only production retry path now;
488
+ // nothing in the SDK or tests references these types.