@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,417 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/SwissKnife.swift
2
+ //
3
+ // Phase 5 step 5 — SwissKnife now routes through our own services
4
+ // (`EntitlementsService`, `PurchaseService`, `OfferingsService`,
5
+ // `AttributesClient`) and an inline identity client. The RevenueCat
6
+ // purchases-ios SDK is no longer touched by this file. Commit 6 drops the
7
+ // RC dependency from `Package.swift` / podspec; this commit removes the
8
+ // last `import RevenueCat` from the main type.
9
+ //
10
+ // Public API surface is unchanged — every method has the same signature
11
+ // and returns the same Swiss Knife types as before. The internal plumbing
12
+ // is ours end-to-end.
13
+
14
+ import Foundation
15
+ import os.log
16
+
17
+ /// Swiss Knife — clean Swift subscriptions SDK for native iOS apps.
18
+ public final class SwissKnife: NSObject {
19
+
20
+ /// Result of a successful purchase.
21
+ public struct PurchaseResult {
22
+ public let transaction: StoreTransaction?
23
+ public let customerInfo: CustomerInfo
24
+ }
25
+
26
+ internal static let shared = SwissKnife()
27
+ private let log = OSLog(subsystem: "com.swissknife", category: "swissknife")
28
+
29
+ // MARK: State managed entirely by SwissKnife now (no more Purchases.shared)
30
+
31
+ private let stateQueue = DispatchQueue(label: "com.swissknife.state")
32
+ private var configured: Bool = false
33
+ private var configuredApiKey: String?
34
+ private var configuredServerURL: String?
35
+ private var currentAppUserID: String?
36
+ private var currentIsAnonymous: Bool = true
37
+ private var resolvedLogLevel: LogLevel = .warn
38
+
39
+ // MARK: Identity client seam (LEGACY — kept for back-compat)
40
+ //
41
+ // The Wave 1 Identity module owns the production identify-POST path
42
+ // through `SwissKnife.Identity.network` + `BackendHttpClientIdentityNetwork`.
43
+ // This pre-Wave-1 seam stays on the type so the few existing tests that
44
+ // injected fakes via `SwissKnife.shared.identityClient = ...` still
45
+ // compile. New tests should use `Identity._setNetworkForTesting(...)`.
46
+ internal var identityClient: IdentityClient = BackendHttpClientIdentityClient()
47
+
48
+ /// Configure the SDK. After this returns:
49
+ /// - The three services (entitlements, purchases, offerings) are wired
50
+ /// with the proxyURL + apiKey.
51
+ /// - The attributes client (Phase 3) is wired the same way.
52
+ /// - `appUserID` is set to the provided id when supplied, else the
53
+ /// anonymous Keychain-backed device id.
54
+ public static func configure(
55
+ apiKey: String,
56
+ appUserID: String? = nil,
57
+ proxyURL: String? = nil,
58
+ storeKitVersion: String = "DEFAULT",
59
+ logLevel: String? = nil,
60
+ attribution: SwissKnife.Attribution.Configuration = .init()
61
+ ) {
62
+ precondition(!apiKey.isEmpty, "configure requires a non-empty apiKey")
63
+ os_log(
64
+ "SwissKnife.configure called (apiKey prefix %{public}@…, proxyURL %{public}@)",
65
+ log: shared.log,
66
+ type: .info,
67
+ String(apiKey.prefix(8)),
68
+ proxyURL ?? "nil"
69
+ )
70
+
71
+ let level = logLevel.flatMap(parseLogLevel) ?? .warn
72
+ let resolvedAppUserID: String
73
+ let isAnonymous: Bool
74
+ if let provided = appUserID, !provided.isEmpty {
75
+ resolvedAppUserID = provided
76
+ isAnonymous = false
77
+ } else {
78
+ // Anonymous flow: use the keychain-backed device id, prefixed
79
+ // to match the convention upstream consumers grep for (similar
80
+ // to RC's `$RCAnonymousID:` prefix but our own).
81
+ resolvedAppUserID = "$SKAnonymousID:" + DeviceID.get()
82
+ isAnonymous = true
83
+ }
84
+
85
+ shared.stateQueue.sync {
86
+ shared.configured = true
87
+ shared.configuredApiKey = apiKey
88
+ shared.configuredServerURL = proxyURL
89
+ shared.currentAppUserID = resolvedAppUserID
90
+ shared.currentIsAnonymous = isAnonymous
91
+ shared.resolvedLogLevel = level
92
+ }
93
+ // Seed the Identity namespace so `SwissKnife.Identity.current`
94
+ // reflects the configure-time identity from the very first access.
95
+ SwissKnife.Identity._seedConfiguredUser(isAnonymous ? nil : resolvedAppUserID)
96
+
97
+ AttributesClient.shared.configure(serverURL: proxyURL, apiKey: apiKey)
98
+ os_log(
99
+ "SwissKnife.configure wired AttributesClient",
100
+ log: shared.log,
101
+ type: .info
102
+ )
103
+ EntitlementsService.shared.configure(
104
+ serverURL: proxyURL,
105
+ apiKey: apiKey,
106
+ userId: resolvedAppUserID
107
+ )
108
+ PurchaseService.shared.configure(serverURL: proxyURL, apiKey: apiKey)
109
+ OfferingsService.shared.configure(serverURL: proxyURL, apiKey: apiKey)
110
+
111
+ // `storeKitVersion` is preserved on the public API for source
112
+ // compatibility but is a no-op now — we always use StoreKit 2
113
+ // (PurchaseService is hard-coded to it). Pre-iOS 15 callers should
114
+ // not have been calling this SDK in the first place; we keep the
115
+ // parameter so existing call sites compile.
116
+ _ = storeKitVersion
117
+
118
+ // Wave 2 — wire the Attribution module so the first launch
119
+ // auto-registers the install (and optionally shows the ATT
120
+ // prompt). Fire-and-forget — configure(...) does not block on
121
+ // the network call.
122
+ SwissKnife.Attribution._configure(attribution)
123
+
124
+ // Round A — wire cross-cutting context observers. Session needs
125
+ // AppLifecycle to drive background-timeout-based restarts;
126
+ // IngestClient needs Reachability (pause/resume flush) and
127
+ // AppLifecycle (flush on background). The MainActor hop is
128
+ // because both observers subscribe to UIApplication notifications.
129
+ Task { @MainActor in
130
+ Session.shared.startObservingLifecycle()
131
+ IngestClient.shared.startObservingContext()
132
+ }
133
+ }
134
+
135
+ public static var isConfigured: Bool {
136
+ shared.stateQueue.sync { shared.configured }
137
+ }
138
+
139
+ /// Current app user id (identified or anonymous).
140
+ ///
141
+ /// Prefer `SwissKnife.Identity.current` for new code — the Identity
142
+ /// snapshot exposes the anonymous/identified distinction without
143
+ /// callers having to consult `isAnonymous` separately. This accessor
144
+ /// stays on the surface so existing host apps keep compiling.
145
+ @available(*, deprecated, message: "Use SwissKnife.Identity.current.userId ?? SwissKnife.Identity.current.anonymousId instead")
146
+ public static var appUserID: String {
147
+ shared.stateQueue.sync { shared.currentAppUserID ?? "" }
148
+ }
149
+
150
+ /// Whether the current identity is the SDK-generated anonymous id.
151
+ @available(*, deprecated, message: "Use SwissKnife.Identity.current.isAnonymous instead")
152
+ public static var isAnonymous: Bool {
153
+ shared.stateQueue.sync { shared.currentIsAnonymous }
154
+ }
155
+
156
+ // MARK: Reads / offerings (typed, async)
157
+
158
+ public static func getCustomerInfo() async throws -> CustomerInfo {
159
+ guard isConfigured else { throw PurchasesError.notConfigured }
160
+ // Fast path: cache hit (inside 24h grace).
161
+ if let cached = EntitlementsService.shared.current() {
162
+ return cached
163
+ }
164
+ // Cache miss or expired → refresh from backend.
165
+ return try await EntitlementsService.shared.refresh()
166
+ }
167
+
168
+ public static func getOfferings() async throws -> Offerings {
169
+ guard isConfigured else { throw PurchasesError.notConfigured }
170
+ return try await OfferingsService.shared.current()
171
+ }
172
+
173
+ // MARK: Purchasing (typed, async)
174
+
175
+ public static func purchasePackage(_ package: Package) async throws -> PurchaseResult {
176
+ guard isConfigured else { throw PurchasesError.notConfigured }
177
+ if #available(iOS 15.0, macOS 12.0, *) {
178
+ return try await PurchaseService.shared.purchase(package: package)
179
+ }
180
+ throw PurchasesError.unknown(message: "StoreKit 2 purchases require iOS 15+ / macOS 12+")
181
+ }
182
+
183
+ public static func purchaseStoreProduct(_ product: StoreProduct) async throws -> PurchaseResult {
184
+ guard isConfigured else { throw PurchasesError.notConfigured }
185
+ if #available(iOS 15.0, macOS 12.0, *) {
186
+ return try await PurchaseService.shared.purchase(productIdentifier: product.productIdentifier)
187
+ }
188
+ throw PurchasesError.unknown(message: "StoreKit 2 purchases require iOS 15+ / macOS 12+")
189
+ }
190
+
191
+ public static func restorePurchases() async throws -> CustomerInfo {
192
+ guard isConfigured else { throw PurchasesError.notConfigured }
193
+ if #available(iOS 15.0, macOS 12.0, *) {
194
+ return try await PurchaseService.shared.restorePurchases()
195
+ }
196
+ throw PurchasesError.unknown(message: "Restore via StoreKit 2 requires iOS 15+ / macOS 12+")
197
+ }
198
+
199
+ // MARK: Identity (facades — production code lives in SwissKnife.Identity)
200
+
201
+ /// Identify the user. Posts the (anonymous_id, user_id) pair to our
202
+ /// backend identify endpoint, then invalidates the entitlements cache
203
+ /// so the next read fetches under the new identity.
204
+ ///
205
+ /// New code should call `SwissKnife.Identity.logIn(_:)` directly. This
206
+ /// facade preserves the tuple-shaped return for back-compat.
207
+ @available(*, deprecated, message: "Use SwissKnife.Identity.logIn(_:) instead")
208
+ @discardableResult
209
+ public static func logIn(_ appUserID: String) async throws -> (customerInfo: CustomerInfo, created: Bool) {
210
+ let result = try await Identity.logIn(appUserID)
211
+ return (result.customerInfo, result.created)
212
+ }
213
+
214
+ /// Log out: drop the identified user, return to anonymous.
215
+ ///
216
+ /// New code should call `SwissKnife.Identity.logOut()` directly.
217
+ @available(*, deprecated, message: "Use SwissKnife.Identity.logOut() instead")
218
+ @discardableResult
219
+ public static func logOut() async throws -> CustomerInfo {
220
+ try await Identity.logOut()
221
+ // Mirror the historical contract — return the (now empty/refreshed)
222
+ // CustomerInfo so callers that branch on entitlements keep working.
223
+ if let cached = EntitlementsService.shared.current() {
224
+ return cached
225
+ }
226
+ return CustomerInfo.empty(originalAppUserId: Identity.current.anonymousId)
227
+ }
228
+
229
+ // MARK: - Identity bridge helpers (consumed by SwissKnife.Identity)
230
+
231
+ /// Snapshot the API key + server URL captured at `configure(...)` time.
232
+ /// Identity needs both for the POST to `/api/sdk/users/identify`.
233
+ internal static func identityConfigSnapshot() -> (apiKey: String, baseURL: String?) {
234
+ shared.stateQueue.sync {
235
+ (shared.configuredApiKey ?? "", shared.configuredServerURL)
236
+ }
237
+ }
238
+
239
+ /// Update the legacy `currentAppUserID` / `currentIsAnonymous` state
240
+ /// after Identity transitions to an identified user. Keeps the
241
+ /// deprecated facade accessors (`SwissKnife.appUserID`,
242
+ /// `SwissKnife.isAnonymous`) in lockstep with the new namespace.
243
+ internal static func identityDidChangeToIdentifiedUser(_ userId: String) {
244
+ shared.stateQueue.sync {
245
+ shared.currentAppUserID = userId
246
+ shared.currentIsAnonymous = false
247
+ }
248
+ }
249
+
250
+ /// Update legacy state after a transition to the anonymous identity.
251
+ internal static func identityDidChangeToAnonymousUser(_ anonymousId: String) {
252
+ shared.stateQueue.sync {
253
+ shared.currentAppUserID = anonymousId
254
+ shared.currentIsAnonymous = true
255
+ }
256
+ }
257
+
258
+ /// Test seam — drops the SDK's configured state. Used by tests that
259
+ /// need to exercise the "called before configure()" branch in
260
+ /// Attribution/Identity. Production code MUST NOT call this.
261
+ internal static func _dangerouslyResetConfigForTesting() {
262
+ shared.stateQueue.sync {
263
+ shared.configured = false
264
+ shared.configuredApiKey = nil
265
+ shared.configuredServerURL = nil
266
+ shared.currentAppUserID = nil
267
+ shared.currentIsAnonymous = true
268
+ shared.resolvedLogLevel = .warn
269
+ }
270
+ }
271
+
272
+ /// Reset legacy state to a fresh anonymous identity. Used by
273
+ /// `Identity.reset()` and `Identity.wipe()` so the deprecated
274
+ /// accessors reflect the post-reset world.
275
+ internal static func identityResetLocalState() {
276
+ let anonId = "$SKAnonymousID:" + DeviceID.get()
277
+ shared.stateQueue.sync {
278
+ shared.currentAppUserID = anonId
279
+ shared.currentIsAnonymous = true
280
+ }
281
+ }
282
+
283
+ // MARK: Subscriber attributes (unchanged from Phase 3 — AttributesClient)
284
+
285
+ public static func setAttributes(_ attributes: [String: String]) {
286
+ var asNullable: [String: String?] = [:]
287
+ for (k, v) in attributes { asNullable[k] = v }
288
+ AttributesClient.shared.setAttributes(
289
+ asNullable,
290
+ anonymousId: currentAnonymousIdForAttributes(),
291
+ userId: currentExternalUserIdForAttributes()
292
+ )
293
+ }
294
+ public static func setEmail(_ email: String?) {
295
+ AttributesClient.shared.set(
296
+ reservedKey: "$email",
297
+ value: email,
298
+ anonymousId: currentAnonymousIdForAttributes(),
299
+ userId: currentExternalUserIdForAttributes()
300
+ )
301
+ }
302
+ public static func setPhoneNumber(_ phoneNumber: String?) {
303
+ AttributesClient.shared.set(
304
+ reservedKey: "$phone",
305
+ value: phoneNumber,
306
+ anonymousId: currentAnonymousIdForAttributes(),
307
+ userId: currentExternalUserIdForAttributes()
308
+ )
309
+ }
310
+ public static func setDisplayName(_ displayName: String?) {
311
+ AttributesClient.shared.set(
312
+ reservedKey: "$displayName",
313
+ value: displayName,
314
+ anonymousId: currentAnonymousIdForAttributes(),
315
+ userId: currentExternalUserIdForAttributes()
316
+ )
317
+ }
318
+ public static func setPushToken(_ pushToken: String?) {
319
+ AttributesClient.shared.set(
320
+ reservedKey: "$pushToken",
321
+ value: pushToken,
322
+ anonymousId: currentAnonymousIdForAttributes(),
323
+ userId: currentExternalUserIdForAttributes()
324
+ )
325
+ }
326
+
327
+ private static func currentAnonymousIdForAttributes() -> String? {
328
+ guard isConfigured else { return nil }
329
+ return shared.stateQueue.sync { shared.currentAppUserID }
330
+ }
331
+
332
+ private static func currentExternalUserIdForAttributes() -> String? {
333
+ guard isConfigured else { return nil }
334
+ return shared.stateQueue.sync {
335
+ shared.currentIsAnonymous ? nil : shared.currentAppUserID
336
+ }
337
+ }
338
+
339
+ public static func setLogLevel(_ level: String) {
340
+ if let parsed = parseLogLevel(level) {
341
+ shared.stateQueue.sync { shared.resolvedLogLevel = parsed }
342
+ }
343
+ }
344
+
345
+ /// Internal — current log-level threshold. Wave 4 wires this into
346
+ /// `SKLog` so `setLogLevel(.warn)` actually filters across the SDK
347
+ /// (pre-Wave-4 the level was stored but no callsite consulted it).
348
+ internal static func resolvedLogLevelInternal() -> LogLevel {
349
+ shared.stateQueue.sync { shared.resolvedLogLevel }
350
+ }
351
+
352
+ // MARK: Helpers
353
+
354
+ private static func parseLogLevel(_ raw: String) -> LogLevel? {
355
+ switch raw.uppercased() {
356
+ case "VERBOSE": return .verbose
357
+ case "DEBUG": return .debug
358
+ case "INFO": return .info
359
+ case "WARN", "WARNING": return .warn
360
+ case "ERROR": return .error
361
+ default: return nil
362
+ }
363
+ }
364
+
365
+ // MARK: CustomerInfo update stream
366
+
367
+ /// Live stream of CustomerInfo updates. Fires whenever
368
+ /// `EntitlementsService.refresh()` completes successfully — that
369
+ /// includes the post-purchase refresh, the Transaction.updates-driven
370
+ /// refresh from `PurchaseService`, and the silent-push refresh.
371
+ public static var customerInfoStream: AsyncStream<CustomerInfo> {
372
+ EntitlementsService.shared.customerInfoStream
373
+ }
374
+ }
375
+
376
+ // MARK: - Identity client
377
+
378
+ /// Tiny inline identity client. Posts to `/api/sdk/users/identify` so the
379
+ /// backend can merge the anonymous → identified user record. Returns
380
+ /// `(user, created)` so the SDK can mirror RC's `LogInResult.created`
381
+ /// boolean semantic.
382
+ internal protocol IdentityClient {
383
+ func identify(
384
+ anonymousId: String,
385
+ userId: String,
386
+ apiKey: String,
387
+ baseURL: String?
388
+ ) async throws -> (created: Bool, body: Data)
389
+ }
390
+
391
+ /// Legacy `IdentityClient` implementation — kept for back-compat with
392
+ /// pre-Wave-1 tests that injected `SwissKnife.shared.identityClient`. It
393
+ /// now delegates to `BackendHttpClient` via the same path the Wave-1
394
+ /// `BackendHttpClientIdentityNetwork` uses, so there's no direct HTTP
395
+ /// transport reference left. New tests should prefer
396
+ /// `Identity._setNetworkForTesting(...)`.
397
+ internal final class BackendHttpClientIdentityClient: IdentityClient {
398
+ private let inner: BackendHttpClientIdentityNetwork
399
+
400
+ init(http: BackendHttpClient = .shared) {
401
+ self.inner = BackendHttpClientIdentityNetwork(http: http)
402
+ }
403
+
404
+ func identify(
405
+ anonymousId: String,
406
+ userId: String,
407
+ apiKey: String,
408
+ baseURL: String?
409
+ ) async throws -> (created: Bool, body: Data) {
410
+ try await inner.identify(
411
+ anonymousId: anonymousId,
412
+ userId: userId,
413
+ apiKey: apiKey,
414
+ baseURL: baseURL
415
+ )
416
+ }
417
+ }