@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,503 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/analytics/SKAnalytics.kt
2
+ //
3
+ // Amplitude/Mixpanel-compatible analytics SDK for swiss-knife (Android).
4
+ // Drop-in replacement — migrate from Amplitude by changing the import.
5
+ //
6
+ // Phase 2.2 change (persistent event queue):
7
+ // - track() now writes the event synchronously to EventQueueStore on disk
8
+ // (cacheDir/swissknife/events.jsonl). Events survive process death.
9
+ // - flush() enqueues a unique-named WorkManager OneTimeWorkRequest for
10
+ // FlushEventsWorker, which handles HTTP + exponential backoff + 5-attempt
11
+ // cap + dead-letter. Pending events are drained from any prior session
12
+ // on the next foreground flush.
13
+ // - In-memory eventQueue is gone — disk is the only queue.
14
+
15
+ package com.appswissknife.analytics
16
+
17
+ import android.content.Context
18
+ import android.os.Build
19
+ import androidx.annotation.VisibleForTesting
20
+ import androidx.work.BackoffPolicy
21
+ import androidx.work.Constraints
22
+ import androidx.work.ExistingWorkPolicy
23
+ import androidx.work.NetworkType
24
+ import androidx.work.OneTimeWorkRequestBuilder
25
+ import androidx.work.WorkManager
26
+ import com.appswissknife.context.IDs
27
+ import com.appswissknife.device.DeviceID
28
+ import com.appswissknife.net.IngestClient
29
+ import com.appswissknife.net.IngestItem
30
+ import com.appswissknife.net.IngestItemType
31
+ import org.json.JSONObject
32
+ import java.util.UUID
33
+ import java.util.concurrent.Executors
34
+ import java.util.concurrent.ScheduledFuture
35
+ import java.util.concurrent.TimeUnit
36
+
37
+ // MARK: - Configuration
38
+
39
+ data class SKAnalyticsConfiguration(
40
+ val apiKey: String,
41
+ val serverURL: String = "",
42
+ val flushQueueSize: Int = 30,
43
+ val flushIntervalSeconds: Long = 30,
44
+ val optOut: Boolean = false,
45
+ val logLevel: SKLogLevel = SKLogLevel.WARN,
46
+ val trackingSessionEvents: Boolean = true,
47
+ val minTimeBetweenSessionsMillis: Long = 300_000,
48
+ )
49
+
50
+ enum class SKLogLevel { DEBUG, INFO, WARN, ERROR, OFF }
51
+
52
+ // MARK: - Identify
53
+
54
+ class SKIdentify {
55
+ internal val operations = mutableListOf<Map<String, Any?>>()
56
+
57
+ fun set(property: String, value: Any): SKIdentify {
58
+ operations.add(mapOf("op" to "\$set", "key" to property, "value" to value))
59
+ return this
60
+ }
61
+
62
+ fun setOnce(property: String, value: Any): SKIdentify {
63
+ operations.add(mapOf("op" to "\$setOnce", "key" to property, "value" to value))
64
+ return this
65
+ }
66
+
67
+ fun unset(property: String): SKIdentify {
68
+ operations.add(mapOf("op" to "\$unset", "key" to property))
69
+ return this
70
+ }
71
+
72
+ fun add(property: String, value: Double): SKIdentify {
73
+ operations.add(mapOf("op" to "\$add", "key" to property, "value" to value))
74
+ return this
75
+ }
76
+
77
+ fun append(property: String, value: Any): SKIdentify {
78
+ operations.add(mapOf("op" to "\$append", "key" to property, "value" to value))
79
+ return this
80
+ }
81
+
82
+ fun prepend(property: String, value: Any): SKIdentify {
83
+ operations.add(mapOf("op" to "\$prepend", "key" to property, "value" to value))
84
+ return this
85
+ }
86
+
87
+ fun remove(property: String, value: Any): SKIdentify {
88
+ operations.add(mapOf("op" to "\$remove", "key" to property, "value" to value))
89
+ return this
90
+ }
91
+
92
+ fun clearAll(): SKIdentify {
93
+ operations.add(mapOf("op" to "\$clearAll"))
94
+ return this
95
+ }
96
+ }
97
+
98
+ // MARK: - Revenue
99
+
100
+ class SKRevenue {
101
+ var productId: String = ""
102
+ var quantity: Int = 1
103
+ var price: Double = 0.0
104
+ var revenueType: String? = null
105
+ var receipt: String? = null
106
+ var eventProperties: Map<String, Any>? = null
107
+ }
108
+
109
+ // MARK: - Main SDK
110
+
111
+ class SKAnalytics private constructor() {
112
+
113
+ companion object {
114
+ @JvmStatic
115
+ val instance = SKAnalytics()
116
+
117
+ @JvmStatic
118
+ fun initialize(context: Context, configuration: SKAnalyticsConfiguration) {
119
+ // Always pin appContext to the Application context to avoid leaking
120
+ // an Activity. DeviceID also internally does .applicationContext but
121
+ // we want the same guarantee for our cached reference.
122
+ val appCtx = context.applicationContext ?: context
123
+ instance.config = configuration
124
+ instance.appContext = appCtx
125
+ // Resolve and cache the persistent device_id BEFORE the first event
126
+ // is enqueued. Subsequent reads (via [getDeviceId]) are in-memory.
127
+ instance.deviceId = DeviceID.get(appCtx)
128
+ instance.sessionId = System.currentTimeMillis()
129
+ // (Re)build the on-disk queue handle bound to this Context.
130
+ instance.eventStore = EventQueueStore(appCtx)
131
+ instance.startFlushTimer()
132
+
133
+ if (configuration.trackingSessionEvents) {
134
+ instance.track("[SwissKnife] Session Start")
135
+ }
136
+
137
+ // Best-effort: drain any pending events left over from a prior
138
+ // session (process killed before they flushed). Safe because
139
+ // event_id idempotency guarantees no double-counting on retry.
140
+ instance.flush()
141
+ }
142
+ }
143
+
144
+ private var config: SKAnalyticsConfiguration? = null
145
+ private var appContext: Context? = null
146
+ private var userId: String? = null
147
+ // Initialized to a process-scoped placeholder so any code path that reads
148
+ // [deviceId] before [initialize] runs still gets a non-empty string.
149
+ // [initialize] replaces it with the persistent value from [DeviceID].
150
+ private var deviceId: String = UUID.randomUUID().toString()
151
+ private var sessionId: Long = 0
152
+
153
+ /**
154
+ * Persistent on-disk event queue. Created in [initialize]; null until then.
155
+ * track() before initialize() is a no-op (matches prior behavior — we'd
156
+ * have nothing to persist against without a Context anyway).
157
+ */
158
+ @VisibleForTesting
159
+ internal var eventStore: EventQueueStore? = null
160
+ private val userProperties = mutableMapOf<String, Any>()
161
+ private val groups = mutableMapOf<String, Any>()
162
+ private val superProperties = mutableMapOf<String, Any>()
163
+ private val timedEvents = mutableMapOf<String, Long>()
164
+ private val executor = Executors.newSingleThreadScheduledExecutor()
165
+ private var flushFuture: ScheduledFuture<*>? = null
166
+
167
+ // MARK: Track
168
+
169
+ fun track(eventType: String, eventProperties: Map<String, Any?>? = null) {
170
+ if (config?.optOut == true) return
171
+ val ctx = appContext ?: return
172
+
173
+ // Merge super properties (event props override)
174
+ val mergedProps = HashMap(superProperties.mapValues { it.value })
175
+ eventProperties?.forEach { (k, v) -> if (v != null) mergedProps[k] = v }
176
+ timedEvents.remove(eventType)?.let { start ->
177
+ mergedProps["\$duration"] = (System.currentTimeMillis() - start) / 1000.0
178
+ }
179
+
180
+ // Round-C: route through IngestClient. Event identity (event_id),
181
+ // device_id, user_id, session_id, timestamp and platform metadata
182
+ // come from the ContextSnapshot envelope stamped at flush time —
183
+ // we no longer build them here. The legacy shim in IngestClient
184
+ // also injects anonymous_id / user_id into `data` for the
185
+ // analytics consumer until it migrates to read from `context`.
186
+ val data = JSONObject().apply {
187
+ put("event_type", eventType)
188
+ put("event_properties", JSONObject(mergedProps))
189
+ put("user_properties", JSONObject(userProperties as Map<String, Any>))
190
+ put("groups", JSONObject(groups as Map<String, Any>))
191
+ // session_id retained for back-compat with the SKAnalytics-
192
+ // local sessionId concept until consumers migrate to the
193
+ // unified envelope `session_id`.
194
+ put("session_id", sessionId)
195
+ // device_id retained for legacy parity until consumers read
196
+ // from `context.device.*` exclusively.
197
+ put("device_id", deviceId)
198
+ // userId may have been set via setUserId(). If present, mirror
199
+ // it on data so consumers keyed off the legacy field see it.
200
+ userId?.let { put("user_id", it) }
201
+ }
202
+ enqueueAnalyticsItem(data, ctx)
203
+ }
204
+
205
+ fun track(eventType: String) = track(eventType, null)
206
+
207
+ /**
208
+ * Round-C ingest path. Enqueues an analytics-typed IngestItem on the
209
+ * unified IngestClient queue. Falls back to the legacy EventQueueStore
210
+ * + FlushEventsWorker only when IngestClient.shared is null (i.e. the
211
+ * SDK wasn't configured via SwissKnife.configure).
212
+ */
213
+ private fun enqueueAnalyticsItem(data: JSONObject, ctx: Context) {
214
+ val client = IngestClient.shared
215
+ if (client != null) {
216
+ client.enqueue(IngestItemType.Analytics, data, ctx)
217
+ return
218
+ }
219
+ // Legacy fallback — pre-Round-C path. Kept so unit tests that
220
+ // exercise initialize() without configure() still observe events
221
+ // on disk.
222
+ val store = eventStore ?: return
223
+ val legacy = JSONObject(data.toString()).apply {
224
+ put("event_id", IDs.eventId())
225
+ put("time", System.currentTimeMillis())
226
+ put("platform", "Android")
227
+ put("os_name", "android")
228
+ put("os_version", Build.VERSION.RELEASE)
229
+ }
230
+ store.append(legacy)
231
+ val threshold = config?.flushQueueSize ?: 30
232
+ if (store.count() >= threshold) flush()
233
+ }
234
+
235
+ /**
236
+ * Persist a pre-built event map directly to the disk-backed queue.
237
+ *
238
+ * **For the React Native bridge.** The RN JS layer builds the full event
239
+ * payload (with `event_id`, `device_id`, super properties, timed-event
240
+ * duration, identify merges) and hands it off here. We bypass [track]'s
241
+ * event-construction logic — that logic lives in JS so JS-only state
242
+ * (super properties, timed events) is honored without round-tripping
243
+ * through native. Native owns the *queue* (disk persistence, WorkManager
244
+ * back-off, dead-letter); JS owns the *payload shape*.
245
+ *
246
+ * The event map must already carry an `event_id` (idempotency key) and
247
+ * `device_id`. Anything JSON-serializable is accepted.
248
+ */
249
+ fun trackPreBuiltEvent(event: Map<String, Any?>) {
250
+ if (config?.optOut == true) return
251
+ val ctx = appContext ?: return
252
+ // Round-C: the RN JS layer builds the full event; we pass it
253
+ // verbatim into the IngestClient data block. ContextSnapshot still
254
+ // wraps it on flush.
255
+ val data = toJSONObject(event)
256
+ val client = IngestClient.shared
257
+ if (client != null) {
258
+ client.enqueue(IngestItemType.Analytics, data, ctx)
259
+ return
260
+ }
261
+ val store = eventStore ?: return
262
+ store.append(data)
263
+ val threshold = config?.flushQueueSize ?: 30
264
+ if (store.count() >= threshold) flush()
265
+ }
266
+
267
+ /**
268
+ * Recursively wrap a Map/List tree into JSONObject / JSONArray. The RN
269
+ * bridge marshals `ReadableMap` into `HashMap<String, Any?>` via
270
+ * `toHashMap()` — nested maps come through as `HashMap`, lists as
271
+ * `ArrayList`. `JSONObject(Map)` only handles the top level; nested
272
+ * structure needs explicit conversion or it serializes as `.toString()`
273
+ * which the backend ingests as opaque strings.
274
+ */
275
+ private fun toJSONObject(map: Map<String, Any?>): JSONObject {
276
+ val out = JSONObject()
277
+ for ((k, v) in map) {
278
+ out.put(k, wrap(v))
279
+ }
280
+ return out
281
+ }
282
+
283
+ private fun wrap(v: Any?): Any {
284
+ return when (v) {
285
+ null -> JSONObject.NULL
286
+ is Map<*, *> -> {
287
+ val o = JSONObject()
288
+ for ((kk, vv) in v) {
289
+ if (kk is String) o.put(kk, wrap(vv))
290
+ }
291
+ o
292
+ }
293
+ is List<*> -> {
294
+ val a = org.json.JSONArray()
295
+ for (item in v) a.put(wrap(item))
296
+ a
297
+ }
298
+ else -> v
299
+ }
300
+ }
301
+
302
+ // MARK: Screen tracking (Mixpanel-compatible)
303
+
304
+ fun trackScreen(name: String, properties: Map<String, Any?>? = null) {
305
+ val props = (properties ?: emptyMap()).toMutableMap()
306
+ props["[SwissKnife] Screen Name"] = name
307
+ track("[SwissKnife] Screen Viewed", props)
308
+ }
309
+
310
+ // MARK: User identity
311
+
312
+ fun setUserId(userId: String?) {
313
+ this.userId = userId
314
+ }
315
+
316
+ fun getUserId(): String? = userId
317
+
318
+ fun setDeviceId(deviceId: String) {
319
+ this.deviceId = deviceId
320
+ }
321
+
322
+ fun getDeviceId(): String = deviceId
323
+
324
+ fun getSessionId(): Long = sessionId
325
+
326
+ fun identify(identify: SKIdentify) {
327
+ val ctx = appContext ?: return
328
+ val data = JSONObject().apply {
329
+ put("event_type", "\$identify")
330
+ put("user_properties", JSONObject(mapOf("\$set" to identify.operations)))
331
+ put("device_id", deviceId)
332
+ userId?.let { put("user_id", it) }
333
+ }
334
+ enqueueAnalyticsItem(data, ctx)
335
+
336
+ for (op in identify.operations) {
337
+ if (op["op"] == "\$set") {
338
+ val key = op["key"] as? String ?: continue
339
+ userProperties[key] = op["value"] ?: continue
340
+ }
341
+ }
342
+ }
343
+
344
+ // Super properties (Mixpanel-compatible)
345
+ fun registerSuperProperties(properties: Map<String, Any>) {
346
+ superProperties.putAll(properties)
347
+ }
348
+
349
+ fun registerSuperPropertiesOnce(properties: Map<String, Any>) {
350
+ for ((k, v) in properties) { if (k !in superProperties) superProperties[k] = v }
351
+ }
352
+
353
+ fun getSuperProperties(): Map<String, Any> = superProperties.toMap()
354
+
355
+ fun unregisterSuperProperty(property: String) {
356
+ superProperties.remove(property)
357
+ }
358
+
359
+ fun clearSuperProperties() = superProperties.clear()
360
+
361
+ // Time events (Mixpanel-compatible)
362
+ fun timeEvent(eventName: String) {
363
+ timedEvents[eventName] = System.currentTimeMillis()
364
+ }
365
+
366
+ // Group helper (Mixpanel-compatible)
367
+ fun addGroup(groupType: String, groupName: String) {
368
+ val existing = groups[groupType]
369
+ if (existing is List<*>) {
370
+ val list = existing.toMutableList()
371
+ if (groupName !in list) list.add(groupName)
372
+ groups[groupType] = list
373
+ } else {
374
+ groups[groupType] = listOf(groupName)
375
+ }
376
+ }
377
+
378
+ fun reset() {
379
+ userId = null
380
+ deviceId = UUID.randomUUID().toString()
381
+ userProperties.clear()
382
+ groups.clear()
383
+ superProperties.clear()
384
+ timedEvents.clear()
385
+ sessionId = System.currentTimeMillis()
386
+ }
387
+
388
+ // MARK: Groups (Amplitude-compatible)
389
+
390
+ fun setGroup(groupType: String, groupName: String) {
391
+ groups[groupType] = groupName
392
+ }
393
+
394
+ fun setGroup(groupType: String, groupNames: Array<String>) {
395
+ groups[groupType] = groupNames.toList()
396
+ }
397
+
398
+ fun groupIdentify(groupType: String, groupName: String, identify: SKIdentify) {
399
+ val ctx = appContext ?: return
400
+ val data = JSONObject().apply {
401
+ put("event_type", "\$groupidentify")
402
+ put("groups", JSONObject(mapOf(groupType to groupName)))
403
+ put("group_properties", JSONObject(mapOf("\$set" to identify.operations)))
404
+ put("device_id", deviceId)
405
+ userId?.let { put("user_id", it) }
406
+ }
407
+ enqueueAnalyticsItem(data, ctx)
408
+ }
409
+
410
+ // MARK: Revenue
411
+
412
+ fun revenue(revenue: SKRevenue) {
413
+ val props = (revenue.eventProperties ?: emptyMap()).toMutableMap()
414
+ props["\$productId"] = revenue.productId
415
+ props["\$quantity"] = revenue.quantity
416
+ props["\$price"] = revenue.price
417
+ revenue.revenueType?.let { props["\$revenueType"] = it }
418
+ track("revenue_amount", props)
419
+ }
420
+
421
+ // Mixpanel-compatible
422
+ fun trackCharge(amount: Double, properties: Map<String, Any?>? = null) {
423
+ val props = (properties ?: emptyMap()).toMutableMap()
424
+ props["\$amount"] = amount
425
+ track("revenue_amount", props)
426
+ }
427
+
428
+ // MARK: Flush
429
+
430
+ /**
431
+ * Enqueue a [FlushEventsWorker] run. Idempotent: calling this multiple
432
+ * times in quick succession coalesces into a single run via the
433
+ * KEEP existing-work policy on the unique work name.
434
+ *
435
+ * Why KEEP (not REPLACE)?
436
+ * - REPLACE cancels the in-flight worker, which causes its IDs to NOT
437
+ * be removed from disk even if its HTTP request is mid-fly — the
438
+ * follow-up enqueue then re-reads the same events. That's harmless
439
+ * correctness-wise (backend idempotency dedupes), but it doubles the
440
+ * network spend and the wall-clock latency.
441
+ * - KEEP preserves the in-flight attempt's retry chain. If the running
442
+ * worker is in backoff state, follow-up flush() calls coalesce into
443
+ * the existing chain rather than restarting backoff from 1s.
444
+ * - KEEP also avoids the well-known WM 1.x/2.x bug where REPLACE on a
445
+ * unique work name briefly leaves the queue in REPLACED state and
446
+ * drops the enqueue.
447
+ */
448
+ fun flush() {
449
+ val ctx = appContext ?: return
450
+ val cfg = config ?: return
451
+
452
+ // Route the flush to whichever queue trackPreBuiltEvent enqueues into.
453
+ // When the unified IngestClient is wired, events go to ITS disk queue
454
+ // (POST /ingest), so we must drain that — not the legacy EventQueueStore
455
+ // via FlushEventsWorker. Without this, IngestClient-queued events are
456
+ // only flushed at batchSize (100) or on a reachability transition, so a
457
+ // handful of events never get sent.
458
+ val ingest = IngestClient.shared
459
+ if (ingest != null) {
460
+ ingest.scheduleFlush(ctx)
461
+ return
462
+ }
463
+
464
+ val constraints = Constraints.Builder()
465
+ .setRequiredNetworkType(NetworkType.CONNECTED)
466
+ .build()
467
+
468
+ val request = OneTimeWorkRequestBuilder<FlushEventsWorker>()
469
+ .setConstraints(constraints)
470
+ // Exponential backoff with a 1s initial delay. WM caps the
471
+ // backoff at 5h regardless; for our 5-attempt budget the
472
+ // delays are 1s/2s/4s/8s (next attempt would be 16s but we
473
+ // DLQ at attempt 5).
474
+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.SECONDS)
475
+ .setInputData(
476
+ FlushEventsWorker.buildInput(
477
+ apiKey = cfg.apiKey,
478
+ serverURL = cfg.serverURL,
479
+ )
480
+ )
481
+ .build()
482
+
483
+ WorkManager.getInstance(ctx).enqueueUniqueWork(
484
+ FlushEventsWorker.UNIQUE_WORK_NAME,
485
+ ExistingWorkPolicy.KEEP,
486
+ request,
487
+ )
488
+ }
489
+
490
+ fun setOptOut(optOut: Boolean) {
491
+ config = config?.copy(optOut = optOut)
492
+ }
493
+
494
+ // MARK: Private
495
+
496
+ private fun startFlushTimer() {
497
+ val interval = config?.flushIntervalSeconds ?: return
498
+ flushFuture?.cancel(false)
499
+ flushFuture = executor.scheduleAtFixedRate(
500
+ { flush() }, interval, interval, TimeUnit.SECONDS
501
+ )
502
+ }
503
+ }
@@ -0,0 +1,188 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/attributes/AttributesClient.kt
2
+ //
3
+ // Phase 3 of the RC rip-and-replace — user attributes now flow to our own
4
+ // `/api/sdk/users/attributes` endpoint instead of RevenueCat's attribution
5
+ // service. Mirrors the iOS `AttributesClient`: the entry-point setters on
6
+ // [com.appswissknife.SwissKnife] (`setEmail`, `setPhoneNumber`,
7
+ // `setDisplayName`, `setPushToken`, `setAttributes`) delegate here.
8
+ //
9
+ // Why a separate file from FlushEventsWorker?
10
+ // - Attributes are infrequent (a handful per session), unlike analytics
11
+ // events (one per user action). Coalescing all attribute writes into the
12
+ // analytics flush would couple attribute latency to the threshold-driven
13
+ // event flush cadence — the dashboard would not see a freshly-set email
14
+ // until the user did 30 things.
15
+ // - Endpoint is different (`/users/attributes` vs `/events/batch`) and the
16
+ // payload shape is incompatible. Sharing a worker would mean branching
17
+ // inside doWork(), which is exactly the thing the per-worker pattern
18
+ // avoids.
19
+ // - WorkManager's unique-work-name policy is per-name; using separate
20
+ // workers gives each pipeline its own retry chain. A burst of setEmail
21
+ // calls won't block the analytics flush, and vice versa.
22
+ //
23
+ // Delivery guarantee
24
+ // ------------------
25
+ // - On enqueue we hand the payload (JSON-serialized + anonymous_id + maybe
26
+ // user_id) directly to WorkManager as Worker input Data. We do NOT
27
+ // persist to disk first — the payload IS the persisted state (WM stores
28
+ // queued work in its own SQLite DB and survives process death).
29
+ // - Multiple in-flight setters do NOT coalesce — each enqueue uses a
30
+ // uniqueWorkName suffixed with the run id, so concurrent setEmail +
31
+ // setPhoneNumber both make it through without one overwriting the other.
32
+ // - Retry policy is BackoffPolicy.EXPONENTIAL (1/2/4/8/16s) capped at 5
33
+ // attempts via [SetAttributesWorker.MAX_ATTEMPTS] — same shape as the
34
+ // analytics flush. Once the cap is hit, the worker returns success with
35
+ // `dead_lettered=true` in its output and the payload is dropped.
36
+
37
+ package com.appswissknife.attributes
38
+
39
+ import android.content.Context
40
+ import android.util.Log
41
+ import androidx.work.BackoffPolicy
42
+ import androidx.work.Constraints
43
+ import androidx.work.ExistingWorkPolicy
44
+ import androidx.work.NetworkType
45
+ import androidx.work.OneTimeWorkRequestBuilder
46
+ import androidx.work.OneTimeWorkRequest
47
+ import androidx.work.WorkManager
48
+ import org.json.JSONObject
49
+ import java.util.UUID
50
+ import java.util.concurrent.TimeUnit
51
+
52
+ /**
53
+ * Process-wide singleton that owns the attributes-POST pipeline.
54
+ *
55
+ * Configured once via [configure] (from `SwissKnife.configure`), thereafter
56
+ * the entry-point setters enqueue a [SetAttributesWorker] per call.
57
+ *
58
+ * Threading: thread-safe — configuration is read under a synchronized lock,
59
+ * and [set] / [setAttributes] both call into WorkManager which is itself
60
+ * thread-safe.
61
+ */
62
+ class AttributesClient private constructor() {
63
+
64
+ companion object {
65
+ private const val TAG = "SwissKnife.Attrs"
66
+
67
+ @JvmStatic
68
+ val instance: AttributesClient by lazy { AttributesClient() }
69
+
70
+ /**
71
+ * Convenience accessor mirroring iOS `AttributesClient.shared`. The
72
+ * `context` arg is needed because WorkManager.getInstance requires a
73
+ * Context; we don't cache a Context on the singleton to avoid leak
74
+ * paths from passing in a non-Application Context at the wrong time.
75
+ */
76
+ @JvmStatic
77
+ fun getInstance(context: Context): AttributesClient {
78
+ instance.appContext = context.applicationContext ?: context
79
+ return instance
80
+ }
81
+ }
82
+
83
+ @Volatile private var appContext: Context? = null
84
+ @Volatile private var serverURL: String? = null
85
+ @Volatile private var apiKey: String? = null
86
+ @Volatile private var anonymousIdProvider: () -> String? = { null }
87
+ @Volatile private var userIdProvider: () -> String? = { null }
88
+
89
+ /**
90
+ * Called from [com.appswissknife.SwissKnife.configure]. Idempotent — the
91
+ * last call wins. Both serverURL and apiKey may be empty; setters
92
+ * short-circuit on missing apiKey.
93
+ */
94
+ fun configure(
95
+ context: Context,
96
+ serverURL: String?,
97
+ apiKey: String,
98
+ anonymousIdProvider: () -> String?,
99
+ userIdProvider: () -> String?,
100
+ ) {
101
+ synchronized(this) {
102
+ this.appContext = context.applicationContext ?: context
103
+ this.serverURL = serverURL?.takeIf { it.isNotEmpty() }
104
+ this.apiKey = apiKey
105
+ this.anonymousIdProvider = anonymousIdProvider
106
+ this.userIdProvider = userIdProvider
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Set a single attribute (reserved or arbitrary). `null` clears it.
112
+ */
113
+ fun set(key: String, value: String?) {
114
+ val attrs = JSONObject().apply { put(key, value ?: JSONObject.NULL) }
115
+ enqueue(attrs)
116
+ }
117
+
118
+ /**
119
+ * Set a bag of attributes in one POST. Values map to JSON null when null
120
+ * so the server clears them — same contract as iOS.
121
+ */
122
+ fun setAttributes(attributes: Map<String, String?>) {
123
+ if (attributes.isEmpty()) return
124
+ val attrs = JSONObject()
125
+ for ((k, v) in attributes) {
126
+ attrs.put(k, v ?: JSONObject.NULL)
127
+ }
128
+ enqueue(attrs)
129
+ }
130
+
131
+ private fun enqueue(attributes: JSONObject) {
132
+ val ctx = appContext
133
+ val key = apiKey
134
+ if (ctx == null || key.isNullOrEmpty()) {
135
+ Log.w(TAG, "skipping setAttributes — AttributesClient.configure not called")
136
+ return
137
+ }
138
+ val anonymousId = anonymousIdProvider()
139
+ if (anonymousId.isNullOrEmpty()) {
140
+ Log.w(TAG, "skipping setAttributes — anonymous id unavailable")
141
+ return
142
+ }
143
+ val userId = userIdProvider()
144
+
145
+ val payload = JSONObject().apply {
146
+ put("anonymous_id", anonymousId)
147
+ if (!userId.isNullOrEmpty()) put("user_id", userId)
148
+ put("attributes", attributes)
149
+ }
150
+
151
+ val request: OneTimeWorkRequest = OneTimeWorkRequestBuilder<SetAttributesWorker>()
152
+ .setConstraints(
153
+ Constraints.Builder()
154
+ .setRequiredNetworkType(NetworkType.CONNECTED)
155
+ .build()
156
+ )
157
+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.SECONDS)
158
+ .setInputData(
159
+ SetAttributesWorker.buildInput(
160
+ apiKey = key,
161
+ serverURL = serverURL.orEmpty(),
162
+ body = payload.toString(),
163
+ )
164
+ )
165
+ .build()
166
+
167
+ // Unique name per enqueue so concurrent setEmail + setPhoneNumber both
168
+ // get their own retry chain. REPLACE on a unique-per-call name is
169
+ // functionally equivalent to APPEND but is the one variant WM cannot
170
+ // silently drop under any internal race.
171
+ val uniqueName = "swissknife.attributes.${UUID.randomUUID()}"
172
+ // WorkManager.getInstance throws IllegalStateException if the host
173
+ // Application hasn't initialized it (e.g. custom Application that
174
+ // disabled WorkManagerInitializer and didn't call WM.initialize).
175
+ // We don't want a missing setEmail telemetry path to crash the host
176
+ // app — log a warning and drop. The host can opt in to WM by
177
+ // restoring the manifest provider or calling WorkManager.initialize.
178
+ try {
179
+ WorkManager.getInstance(ctx).enqueueUniqueWork(
180
+ uniqueName,
181
+ ExistingWorkPolicy.REPLACE,
182
+ request,
183
+ )
184
+ } catch (e: IllegalStateException) {
185
+ Log.w(TAG, "WorkManager not initialized; dropping setAttributes (${e.message})")
186
+ }
187
+ }
188
+ }