@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,533 @@
1
+ // packages/swiss-knife-android/src/main/java/com/appswissknife/SwissKnife.kt
2
+ package com.appswissknife
3
+
4
+ import android.app.Activity
5
+ import android.content.Context
6
+ import androidx.annotation.VisibleForTesting
7
+ import com.appswissknife.analytics.SKAnalytics
8
+ import com.appswissknife.attributes.AttributesClient
9
+ import com.appswissknife.attribution.Attribution
10
+ import com.appswissknife.device.DeviceID
11
+ import com.appswissknife.identity.Identity
12
+ import com.appswissknife.models.CustomerInfo
13
+ import com.appswissknife.models.LogLevel
14
+ import com.appswissknife.models.Offerings
15
+ import com.appswissknife.models.Package
16
+ import com.appswissknife.models.PurchasesError
17
+ import com.appswissknife.models.StoreProduct
18
+ import com.appswissknife.models.StoreTransaction
19
+ import com.appswissknife.purchases.BillingClientGateway
20
+ import com.appswissknife.purchases.PurchasesGateway
21
+
22
+ /**
23
+ * Swiss Knife — clean Kotlin subscriptions SDK for native Android apps.
24
+ *
25
+ * Phase 6 of the RC rip-and-replace removed RevenueCat's
26
+ * `purchases-hybrid-common` from the dependency graph; the production gateway
27
+ * is now [com.appswissknife.purchases.BillingClientGateway], a direct Google
28
+ * Play Billing v8 implementation that pushes receipts to our own
29
+ * `/api/sdk/subscriptions/validate` and reads entitlements via
30
+ * [com.appswissknife.entitlements.EntitlementsRepository].
31
+ *
32
+ * The gateway abstraction exists so:
33
+ *
34
+ * - Unit tests can inject [com.appswissknife.purchases.FakePurchasesGateway]
35
+ * via [setGateway] and assert against recorded calls.
36
+ * - Type leaks are clean: every public type on this object is from
37
+ * [com.appswissknife.models] (own data classes), not RC.
38
+ *
39
+ * Public surface is preserved verbatim from the pre-Phase-6 facade — only the
40
+ * package of the model types changed (`com.revenuecat.purchases.*` →
41
+ * `com.appswissknife.models.*`). Field names are RC parity per the
42
+ * user-locked decision.
43
+ */
44
+ object SwissKnife {
45
+
46
+ // Default production gateway — direct Google Play Billing v8 via
47
+ // [BillingClientGateway]. Tests override via [setGateway] BEFORE configure
48
+ // so the production gateway is never invoked in unit tests.
49
+ private var gateway: PurchasesGateway = BillingClientGateway()
50
+
51
+ /**
52
+ * Swap the underlying [PurchasesGateway]. Test-only — production code MUST
53
+ * NOT call this. Marked @VisibleForTesting to keep the seam discoverable
54
+ * without bumping it to a public API.
55
+ */
56
+ @VisibleForTesting
57
+ @JvmStatic
58
+ fun setGateway(gateway: PurchasesGateway) {
59
+ this.gateway = gateway
60
+ }
61
+
62
+ /** Test-only accessor for the current gateway. */
63
+ @VisibleForTesting
64
+ @JvmStatic
65
+ fun getGateway(): PurchasesGateway = gateway
66
+
67
+ /**
68
+ * Production seam for optional store add-ons (e.g. swiss-knife-android-rustore)
69
+ * to install their [PurchasesGateway] before [configure]. The base SDK never
70
+ * names a concrete store other than the Play default; an add-on calls this
71
+ * from a manifest-merged initializer (ContentProvider) at process start, so a
72
+ * build that links the add-on swaps the gateway with zero app-code change, and
73
+ * a build that doesn't keeps the [BillingClientGateway] default.
74
+ */
75
+ @JvmStatic
76
+ fun registerGatewayFactory(factory: () -> PurchasesGateway) {
77
+ gateway = factory()
78
+ }
79
+
80
+ /**
81
+ * Configure the SDK. Wires the production [com.appswissknife.purchases.BillingClientGateway]
82
+ * (unless a test injected a different gateway first via [setGateway]) and
83
+ * starts the [AttributesClient] for the Phase 3 attribute-write path.
84
+ * Must be called before any other method.
85
+ */
86
+ @JvmStatic
87
+ @JvmOverloads
88
+ fun configure(
89
+ context: Context,
90
+ apiKey: String,
91
+ appUserID: String? = null,
92
+ proxyURL: String? = null,
93
+ useAmazon: Boolean = false,
94
+ logLevel: String? = null,
95
+ attribution: Attribution.Configuration = Attribution.Configuration(),
96
+ ) {
97
+ require(apiKey.isNotEmpty()) { "configure requires a non-empty apiKey" }
98
+ gateway.configure(context, apiKey, appUserID, proxyURL, useAmazon)
99
+ // Phase 3 of the RC rip-and-replace — wire AttributesClient so the
100
+ // setEmail/setPhoneNumber/etc. methods below have somewhere to send to.
101
+ // Anonymous-id / user-id come from the gateway lazily (per-call), not
102
+ // captured at configure time, so logIn() between configure() and a
103
+ // setEmail() resolves to the right user_id.
104
+ AttributesClient.getInstance(context).configure(
105
+ context = context,
106
+ serverURL = proxyURL,
107
+ apiKey = apiKey,
108
+ anonymousIdProvider = {
109
+ if (gateway.isConfigured()) gateway.getAppUserID() else null
110
+ },
111
+ userIdProvider = {
112
+ if (gateway.isConfigured() && !gateway.isAnonymous()) gateway.getAppUserID() else null
113
+ },
114
+ )
115
+ // Wire OfferingsRepository for any store that supplies a price-enrichment
116
+ // provider (Play via BillingClientGateway, RuStore via the add-on). Test
117
+ // fakes return null → no repo, preserving the prior "production gateway
118
+ // only" guard so a [FakePurchasesGateway] never hits a real store query.
119
+ val gw = gateway
120
+ val priceProvider = gw.priceEnrichmentProvider()
121
+ if (priceProvider != null && !proxyURL.isNullOrEmpty()) {
122
+ offeringsRepository = com.appswissknife.offerings.OfferingsRepository(
123
+ httpClient = com.appswissknife.net.BackendHttpClientAdapter(),
124
+ serverUrl = proxyURL.trimEnd('/'),
125
+ apiKey = apiKey,
126
+ platformTags = priceProvider.platformTags(),
127
+ priceProvider = priceProvider,
128
+ )
129
+ }
130
+ // Wave 1 — wire the unified [Identity] namespace so its anonymous-id /
131
+ // identified-id snapshot stays in lockstep with the gateway. Identity
132
+ // owns the `/api/sdk/users/identify` POST that previously was
133
+ // missing on Android (the audit's real-bug-closed item).
134
+ // Same store-agnostic gate as the offerings wiring: real store gateways
135
+ // (Play, RuStore) supply a price provider; test fakes don't, so identity's
136
+ // entitlements repo stays null for them exactly as before.
137
+ val entitlementsRepoForIdentity = if (priceProvider != null) {
138
+ com.appswissknife.entitlements.EntitlementsRepository.get(
139
+ context = context.applicationContext,
140
+ serverUrl = proxyURL?.trimEnd('/').orEmpty(),
141
+ apiKey = apiKey,
142
+ userIdProvider = { gateway.getAppUserID() },
143
+ )
144
+ } else null
145
+ Identity.configure(
146
+ context = context,
147
+ serverUrl = proxyURL?.trimEnd('/').orEmpty(),
148
+ apiKey = apiKey,
149
+ seedUserId = appUserID,
150
+ entitlementsRepository = entitlementsRepoForIdentity,
151
+ )
152
+ // Wave 2 — Attribution module. Auto-registers the install on the
153
+ // first launch (configurable) and persists the resolved attribution
154
+ // to EncryptedSharedPreferences so subsequent launches read from
155
+ // disk without re-POSTing.
156
+ Attribution.configure(
157
+ context = context,
158
+ serverUrl = proxyURL?.trimEnd('/').orEmpty(),
159
+ apiKey = apiKey,
160
+ configuration = attribution,
161
+ )
162
+ // Round C — wire the unified Net + Context primitives (BackendHttpClient +
163
+ // IngestClient + context suppliers). Extracted into ensureObservabilityBackend
164
+ // so observability can also be wired WITHOUT configure() / the purchase engine.
165
+ ensureObservabilityBackend(context, apiKey, proxyURL?.trimEnd('/').orEmpty())
166
+ logLevel?.let { applyLogLevel(it) }
167
+ }
168
+
169
+ @Volatile
170
+ private var observabilityWired = false
171
+
172
+ /**
173
+ * Wire the observability backend (analytics / crash / performance ingest)
174
+ * WITHOUT requiring [configure] or the purchase engine. Idempotent — safe to
175
+ * call from both [configure] and the RN analytics-init path; the first call
176
+ * wins, so the BackendHttpClient/IngestClient are never double-installed.
177
+ *
178
+ * This decouples observability from purchases: a build that uses a non-SDK
179
+ * store (e.g. RuStore) and never calls [configure] still gets working
180
+ * analytics by calling this from Analytics.init with the same serverURL.
181
+ */
182
+ @JvmStatic
183
+ @Synchronized
184
+ fun ensureObservabilityBackend(context: Context, apiKey: String, serverUrl: String) {
185
+ if (observabilityWired) return
186
+ observabilityWired = true
187
+ // Configure Identity if the purchase `configure()` path hasn't already.
188
+ // Without this, the observability-only path (RuStore / analytics-without-
189
+ // configure) leaves Identity unconfigured, so Identity.current() returns an
190
+ // EMPTY anonymousId and every ingested event is stamped anonymous_id="" —
191
+ // breaking per-install stitching and diverging from iOS. We seed an
192
+ // anonymous identity (no user / no entitlements repo); the full configure()
193
+ // path, which runs Identity.configure() FIRST with the real seed user, is
194
+ // left untouched by the isConfigured() guard.
195
+ runCatching {
196
+ if (!com.appswissknife.identity.Identity.isConfigured()) {
197
+ com.appswissknife.identity.Identity.configure(
198
+ context = context,
199
+ serverUrl = serverUrl,
200
+ apiKey = apiKey,
201
+ seedUserId = null,
202
+ entitlementsRepository = null,
203
+ )
204
+ }
205
+ }
206
+ // Each step is wrapped in runCatching so a transient init failure
207
+ // (e.g. Robolectric not exposing ProcessLifecycleOwner cleanly,
208
+ // sandboxed ConnectivityManager) doesn't break the rest of the flow.
209
+ runCatching {
210
+ com.appswissknife.net.ConfigBridge.register {
211
+ com.appswissknife.net.BackendConfig(apiKey = apiKey, baseUrl = serverUrl.ifBlank { null })
212
+ }
213
+ com.appswissknife.net.BackendHttpClient.shared = com.appswissknife.net.BackendHttpClient(
214
+ configResolver = { com.appswissknife.net.ConfigBridge.snapshot() },
215
+ onServerDate = { server, local -> com.appswissknife.context.Clock.applyServerTime(server, local) },
216
+ )
217
+ }
218
+ runCatching { com.appswissknife.context.DeviceContextProvider.install(context) }
219
+ runCatching {
220
+ com.appswissknife.context.Session.shared(context).apply {
221
+ startObservingLifecycle()
222
+ installAsIngestSupplier()
223
+ }
224
+ }
225
+ runCatching { com.appswissknife.context.Clock.installAsIngestSupplier() }
226
+ runCatching {
227
+ val ingestClient = com.appswissknife.net.IngestClient.build(
228
+ context = context,
229
+ http = com.appswissknife.net.BackendHttpClient.shared,
230
+ )
231
+ com.appswissknife.net.IngestClient.install(ingestClient)
232
+ com.appswissknife.context.Reachability.shared(context).installAsIngestObserver()
233
+ }
234
+ // Initialize SKAnalytics — this sets its appContext, WITHOUT which
235
+ // trackPreBuiltEvent() early-returns and silently drops every event. This
236
+ // is required for analytics to work at all on Android (SKAnalytics.initialize
237
+ // had no caller before this), and routes events through IngestClient.shared
238
+ // (installed above) → POST /ingest.
239
+ runCatching {
240
+ com.appswissknife.analytics.SKAnalytics.initialize(
241
+ context,
242
+ com.appswissknife.analytics.SKAnalyticsConfiguration(
243
+ apiKey = apiKey,
244
+ serverURL = serverUrl,
245
+ ),
246
+ )
247
+ }
248
+ }
249
+
250
+ @JvmStatic
251
+ val isConfigured: Boolean
252
+ get() = gateway.isConfigured()
253
+
254
+ @JvmStatic
255
+ val appUserID: String
256
+ get() = gateway.getAppUserID()
257
+
258
+ @JvmStatic
259
+ fun isAnonymous(): Boolean = gateway.isAnonymous()
260
+
261
+ // ----- Reads / offerings (typed) -----
262
+
263
+ @JvmStatic
264
+ fun getCustomerInfo(onSuccess: (CustomerInfo) -> Unit, onError: (PurchasesError) -> Unit) {
265
+ gateway.getCustomerInfo(onSuccess, onError)
266
+ }
267
+
268
+ /**
269
+ * Fetch offerings via the [PurchasesGateway].
270
+ *
271
+ * Phase 6 note: the production [com.appswissknife.purchases.BillingClientGateway]
272
+ * intentionally returns an error from this method because Google Play
273
+ * Billing has no equivalent "offerings" concept - that belongs to
274
+ * [com.appswissknife.offerings.OfferingsRepository], which is keyed by
275
+ * paywall slug. Call [getOfferingsForPaywall] for production. This
276
+ * no-arg variant stays on the surface for RC parity (tests that inject
277
+ * a [FakePurchasesGateway] still drive it).
278
+ */
279
+ @JvmStatic
280
+ fun getOfferings(onSuccess: (Offerings) -> Unit, onError: (PurchasesError) -> Unit) {
281
+ gateway.getOfferings(onSuccess, onError)
282
+ }
283
+
284
+ /**
285
+ * Fetch offerings for a specific paywall. Production path - uses
286
+ * [com.appswissknife.offerings.OfferingsRepository] which calls
287
+ * /api/sdk/paywalls/show and enriches product prices via the live Play
288
+ * Billing client.
289
+ *
290
+ * Must be called AFTER [configure]. The host app is responsible for
291
+ * knowing which paywall slug to render (paywall selection is a product
292
+ * decision the SDK does not auto-resolve).
293
+ */
294
+ @JvmStatic
295
+ fun getOfferingsForPaywall(
296
+ paywallSlug: String,
297
+ onSuccess: (Offerings) -> Unit,
298
+ onError: (PurchasesError) -> Unit,
299
+ ) {
300
+ val repo = offeringsRepository
301
+ ?: run { onError(PurchasesError.Unknown("SDK not configured")); return }
302
+ Thread({
303
+ runCatching { repo.current(paywallSlug, appUserID) }
304
+ .onSuccess(onSuccess)
305
+ .onFailure { onError(PurchasesError.NetworkError(it.message ?: "Network error", it)) }
306
+ }, "swissknife-offerings-fetch").apply { isDaemon = true }.start()
307
+ }
308
+
309
+ /** Test seam for the OfferingsRepository - production builds it inside [configure]. */
310
+ @VisibleForTesting
311
+ @JvmStatic
312
+ internal fun setOfferingsRepositoryForTesting(repo: com.appswissknife.offerings.OfferingsRepository?) {
313
+ offeringsRepository = repo
314
+ }
315
+
316
+ @Volatile
317
+ private var offeringsRepository: com.appswissknife.offerings.OfferingsRepository? = null
318
+
319
+ // ----- Purchasing (typed) -----
320
+
321
+ @JvmStatic
322
+ fun purchasePackage(
323
+ activity: Activity,
324
+ packageToPurchase: Package,
325
+ onSuccess: (StoreTransactionResult) -> Unit,
326
+ onError: (PurchasesError, userCancelled: Boolean) -> Unit,
327
+ ) {
328
+ gateway.purchasePackage(activity, packageToPurchase, onSuccess, onError)
329
+ }
330
+
331
+ @JvmStatic
332
+ fun purchaseStoreProduct(
333
+ activity: Activity,
334
+ product: StoreProduct,
335
+ onSuccess: (StoreTransactionResult) -> Unit,
336
+ onError: (PurchasesError, userCancelled: Boolean) -> Unit,
337
+ ) {
338
+ gateway.purchaseStoreProduct(activity, product, onSuccess, onError)
339
+ }
340
+
341
+ @JvmStatic
342
+ fun restorePurchases(onSuccess: (CustomerInfo) -> Unit, onError: (PurchasesError) -> Unit) {
343
+ gateway.restorePurchases(onSuccess, onError)
344
+ }
345
+
346
+ // ----- Identity (facades — production lives in com.appswissknife.identity.Identity) -----
347
+ //
348
+ // Wave 1: identity primitives moved to [com.appswissknife.identity.Identity].
349
+ // The facades below stay public so existing host apps keep compiling,
350
+ // but route through Identity so the backend identify POST (the bug
351
+ // closed in Wave 1) and observer dispatch happen the same way as in
352
+ // direct Identity.logIn calls.
353
+
354
+ @JvmStatic
355
+ @Deprecated(
356
+ "Use SwissKnife.Identity.logIn(...) instead",
357
+ ReplaceWith("com.appswissknife.identity.Identity.logIn(appUserID, { onSuccess(it.customerInfo, it.created) }, onError)"),
358
+ )
359
+ fun logIn(
360
+ appUserID: String,
361
+ onSuccess: (CustomerInfo, created: Boolean) -> Unit,
362
+ onError: (PurchasesError) -> Unit,
363
+ ) {
364
+ Identity.logIn(
365
+ userId = appUserID,
366
+ onSuccess = { result -> onSuccess(result.customerInfo, result.created) },
367
+ onError = onError,
368
+ )
369
+ }
370
+
371
+ @JvmStatic
372
+ @Deprecated(
373
+ "Use SwissKnife.Identity.logOut(...) instead",
374
+ ReplaceWith("com.appswissknife.identity.Identity.logOut({ /* CustomerInfo not surfaced; read via getCustomerInfo */ }, onError)"),
375
+ )
376
+ fun logOut(onSuccess: (CustomerInfo) -> Unit, onError: (PurchasesError) -> Unit) {
377
+ // The legacy facade returns whatever CustomerInfo the gateway
378
+ // surfaces from logOut. Identity.logOut() drops the CustomerInfo
379
+ // (the new contract is "fire-and-forget" — read via getCustomerInfo
380
+ // when needed), so we go through the gateway directly and let
381
+ // Identity update its snapshot off the same call. This preserves
382
+ // the old tests that asserted `gateway.logOut`'s response shape
383
+ // round-trips through the facade.
384
+ val previousSnapshot = Identity.current()
385
+ gateway.logOut(
386
+ onSuccess = { info ->
387
+ // Sync Identity's in-memory snapshot so observers and
388
+ // Identity.current() see the post-logout state.
389
+ Identity._syncAnonymousFromFacade(previousSnapshot)
390
+ onSuccess(info)
391
+ },
392
+ onError = onError,
393
+ )
394
+ }
395
+
396
+ // ----- Subscriber attributes -----
397
+ //
398
+ // Phase 3 of the RC rip-and-replace — these setters POST to our own
399
+ // /api/sdk/users/attributes endpoint via [AttributesClient] rather than to
400
+ // RevenueCat's attribution service. Reserved keys keep the `$` prefix RC's
401
+ // API used (`$email`, `$phone`, `$displayName`, `$pushToken`) so the
402
+ // server-side dashboard / outgoing webhooks see a consistent vocabulary
403
+ // before and after the cut-over.
404
+ //
405
+ // Public signatures unchanged — calling code does not need to change.
406
+
407
+ @JvmStatic fun setAttributes(attributes: Map<String, String?>) =
408
+ AttributesClient.instance.setAttributes(attributes)
409
+
410
+ @JvmStatic fun setEmail(email: String?) =
411
+ AttributesClient.instance.set("\$email", email)
412
+
413
+ @JvmStatic fun setPhoneNumber(phoneNumber: String?) =
414
+ AttributesClient.instance.set("\$phone", phoneNumber)
415
+
416
+ @JvmStatic fun setDisplayName(displayName: String?) =
417
+ AttributesClient.instance.set("\$displayName", displayName)
418
+
419
+ @JvmStatic fun setPushToken(pushToken: String?) =
420
+ AttributesClient.instance.set("\$pushToken", pushToken)
421
+
422
+ // ----- Device identifier (RN bridge facade) -----
423
+
424
+ /**
425
+ * Persistent per-install device identifier, backed by EncryptedSharedPreferences.
426
+ *
427
+ * **For the React Native bridge only** ([SwissKnifePurchasesModule]). Native-
428
+ * Android consumers should not call this directly — use [com.appswissknife.analytics.SKAnalytics]
429
+ * for analytics identity (which reads this value via the internal [DeviceID.get]).
430
+ *
431
+ * The underlying [DeviceID] type stays `internal` by design — the device-id
432
+ * is an SDK implementation detail, not a general consumer API. This facade
433
+ * exists solely because the RN bridge module cannot reach `internal` symbols
434
+ * from this package. See [DeviceID] for the full storage/threat-model rationale.
435
+ */
436
+ @JvmStatic
437
+ fun getDeviceId(context: Context): String = DeviceID.get(context)
438
+
439
+ /**
440
+ * Plain-data snapshot of the canonical Session, exposed for the RN
441
+ * bridge. Mirrors `SessionSnapshot` but stripped of internal types so
442
+ * a separate Kotlin module can read it.
443
+ *
444
+ * **For the React Native bridge only.** Native-Android consumers should
445
+ * not depend on this — `Session.shared(ctx).current` works directly
446
+ * inside the package.
447
+ */
448
+ data class SessionInfo(
449
+ @JvmField val id: String,
450
+ @JvmField val sessionNumber: Int,
451
+ @JvmField val startedAtMs: Long,
452
+ )
453
+
454
+ /**
455
+ * Current session snapshot from `Session.shared` — the same source that
456
+ * stamps envelope-level `ContextSnapshot.session_id`. Read by the RN
457
+ * bridge so JS-side analytics' legacy `session_id` field agrees with
458
+ * the envelope. Replaces the JS `Date.now()` fallback.
459
+ */
460
+ @JvmStatic
461
+ fun currentSession(context: Context): SessionInfo {
462
+ val snap = com.appswissknife.context.Session.shared(context).current
463
+ return SessionInfo(
464
+ id = snap.id,
465
+ sessionNumber = snap.sessionNumber,
466
+ startedAtMs = snap.startedAtMs,
467
+ )
468
+ }
469
+
470
+ // ----- Analytics passthrough (RN bridge facade) -----
471
+
472
+ /**
473
+ * Enqueue a pre-built analytics event onto the disk-backed queue.
474
+ *
475
+ * **For the React Native bridge only** ([SwissKnifePurchasesModule]). The
476
+ * JS layer constructs the full event payload (including `event_id`,
477
+ * `device_id`, super properties, timed-event duration, identify merges)
478
+ * and passes it here. Native owns the queue; JS owns the payload shape.
479
+ *
480
+ * Synchronous on the calling thread up to the disk write — once this
481
+ * returns, the event has hit disk and survives a process kill. See Phase
482
+ * 2.3 of the RC rip-and-replace plan for the full rationale.
483
+ */
484
+ @JvmStatic
485
+ fun trackEvent(event: Map<String, Any?>) {
486
+ SKAnalytics.instance.trackPreBuiltEvent(event)
487
+ }
488
+
489
+ /**
490
+ * Kick off a flush of the disk-backed queue via WorkManager. Fire-and-
491
+ * forget — the actual HTTP work runs on a [com.appswissknife.analytics.FlushEventsWorker]
492
+ * with WorkManager-backed exponential back-off and dead-letter on permanent
493
+ * failure.
494
+ */
495
+ @JvmStatic
496
+ fun flushEvents() {
497
+ SKAnalytics.instance.flush()
498
+ }
499
+
500
+ // ----- Log level -----
501
+
502
+ @JvmStatic
503
+ fun setLogLevel(level: String) = applyLogLevel(level)
504
+
505
+ // Own LogLevel: VERBOSE/DEBUG/INFO/WARN/ERROR. Unknown strings ignored.
506
+ // Wave 4 — wire into SKLog so the SDK actually filters across all
507
+ // modules (pre-Wave-4, the gateway.setLogLevel call was a no-op).
508
+ private fun applyLogLevel(level: String) {
509
+ runCatching {
510
+ val parsed = LogLevel.valueOf(level.uppercase())
511
+ gateway.setLogLevel(parsed)
512
+ com.appswissknife.diagnostics.SKLog.setLevel(parsed)
513
+ }
514
+ }
515
+
516
+ // ----- CustomerInfo update stream -----
517
+
518
+ @JvmStatic
519
+ fun addCustomerInfoListener(listener: (CustomerInfo) -> Unit) {
520
+ gateway.addCustomerInfoListener(listener)
521
+ }
522
+
523
+ @JvmStatic
524
+ fun removeCustomerInfoListener(listener: (CustomerInfo) -> Unit) {
525
+ gateway.removeCustomerInfoListener(listener)
526
+ }
527
+ }
528
+
529
+ /** Result of a successful purchase: the store transaction + resulting CustomerInfo. */
530
+ data class StoreTransactionResult(
531
+ val transaction: StoreTransaction?,
532
+ val customerInfo: CustomerInfo,
533
+ )