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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/CHANGELOG.md +473 -2
  2. package/LICENSE +21 -0
  3. package/README.md +279 -47
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +20 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/GENERATED.md +1 -0
  14. package/android/vendor/java/com/appswissknife/SwissKnife.kt +111 -38
  15. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  16. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  17. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  18. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  19. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  20. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  21. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  22. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  23. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  24. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  25. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  26. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  27. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  32. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  34. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  35. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +312 -65
  36. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  37. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +705 -96
  38. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  39. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +29 -0
  40. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +24 -0
  41. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  44. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  45. package/app.plugin.js +343 -0
  46. package/ios/SwissKnifeJSON.swift +24 -2
  47. package/ios/SwissKnifePurchases.m +20 -0
  48. package/ios/SwissKnifePurchases.swift +97 -3
  49. package/ios/SwissKnifePushBootstrap.m +34 -0
  50. package/ios/vendor/GENERATED.md +1 -0
  51. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  52. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  53. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  54. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  55. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  56. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  57. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  58. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  59. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  60. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  61. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  62. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
  63. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  64. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  65. package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
  66. package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
  67. package/ios-notification-service/vendor/GENERATED.md +11 -0
  68. package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
  69. package/lib/commonjs/attribution.js +4 -3
  70. package/lib/commonjs/attribution.js.map +1 -1
  71. package/lib/commonjs/identity.js +12 -11
  72. package/lib/commonjs/identity.js.map +1 -1
  73. package/lib/commonjs/index.js +16 -5
  74. package/lib/commonjs/index.js.map +1 -1
  75. package/lib/commonjs/internal/config.js +105 -8
  76. package/lib/commonjs/internal/config.js.map +1 -1
  77. package/lib/commonjs/internal/telemetry-context.js +70 -0
  78. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  79. package/lib/commonjs/modules/analytics.js +18 -25
  80. package/lib/commonjs/modules/analytics.js.map +1 -1
  81. package/lib/commonjs/modules/crash-reporting.js +27 -6
  82. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  83. package/lib/commonjs/modules/log.js +1 -1
  84. package/lib/commonjs/modules/notifications.js +500 -0
  85. package/lib/commonjs/modules/notifications.js.map +1 -0
  86. package/lib/commonjs/modules/performance.js +57 -8
  87. package/lib/commonjs/modules/performance.js.map +1 -1
  88. package/lib/commonjs/native/module.js +6 -0
  89. package/lib/commonjs/native/module.js.map +1 -1
  90. package/lib/commonjs/native/spec.js +12 -5
  91. package/lib/commonjs/native/spec.js.map +1 -1
  92. package/lib/commonjs/purchases.js +4 -4
  93. package/lib/commonjs/types.js +12 -15
  94. package/lib/commonjs/types.js.map +1 -1
  95. package/lib/module/attribution.js +4 -3
  96. package/lib/module/attribution.js.map +1 -1
  97. package/lib/module/identity.js +12 -11
  98. package/lib/module/identity.js.map +1 -1
  99. package/lib/module/index.js +8 -4
  100. package/lib/module/index.js.map +1 -1
  101. package/lib/module/internal/config.js +103 -8
  102. package/lib/module/internal/config.js.map +1 -1
  103. package/lib/module/internal/telemetry-context.js +63 -0
  104. package/lib/module/internal/telemetry-context.js.map +1 -0
  105. package/lib/module/modules/analytics.js +18 -25
  106. package/lib/module/modules/analytics.js.map +1 -1
  107. package/lib/module/modules/crash-reporting.js +27 -6
  108. package/lib/module/modules/crash-reporting.js.map +1 -1
  109. package/lib/module/modules/log.js +1 -1
  110. package/lib/module/modules/notifications.js +491 -0
  111. package/lib/module/modules/notifications.js.map +1 -0
  112. package/lib/module/modules/performance.js +57 -8
  113. package/lib/module/modules/performance.js.map +1 -1
  114. package/lib/module/native/module.js +6 -1
  115. package/lib/module/native/module.js.map +1 -1
  116. package/lib/module/native/spec.js +11 -4
  117. package/lib/module/native/spec.js.map +1 -1
  118. package/lib/module/purchases.js +4 -4
  119. package/lib/module/types.js +12 -15
  120. package/lib/module/types.js.map +1 -1
  121. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  122. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  123. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/index.d.ts +2 -0
  125. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  127. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  128. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  129. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  130. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  131. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  133. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  135. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  136. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  137. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  138. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  139. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  140. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  141. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  142. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  143. package/lib/typescript/commonjs/types.d.ts +4 -5
  144. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  145. package/lib/typescript/module/attribution.d.ts +3 -2
  146. package/lib/typescript/module/attribution.d.ts.map +1 -1
  147. package/lib/typescript/module/identity.d.ts.map +1 -1
  148. package/lib/typescript/module/index.d.ts +2 -0
  149. package/lib/typescript/module/index.d.ts.map +1 -1
  150. package/lib/typescript/module/internal/config.d.ts +16 -2
  151. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  152. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  153. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  154. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  155. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  156. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  157. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  158. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  159. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  160. package/lib/typescript/module/modules/performance.d.ts +13 -0
  161. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  162. package/lib/typescript/module/native/module.d.ts +2 -0
  163. package/lib/typescript/module/native/module.d.ts.map +1 -1
  164. package/lib/typescript/module/native/spec.d.ts +33 -4
  165. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  166. package/lib/typescript/module/purchases.d.ts +4 -4
  167. package/lib/typescript/module/types.d.ts +4 -5
  168. package/lib/typescript/module/types.d.ts.map +1 -1
  169. package/package.json +13 -4
  170. package/src/attribution.ts +4 -3
  171. package/src/identity.ts +12 -11
  172. package/src/index.ts +16 -4
  173. package/src/internal/config.ts +113 -8
  174. package/src/internal/telemetry-context.ts +76 -0
  175. package/src/modules/analytics.ts +24 -33
  176. package/src/modules/crash-reporting.ts +50 -9
  177. package/src/modules/log.ts +1 -1
  178. package/src/modules/notifications.ts +557 -0
  179. package/src/modules/performance.ts +94 -14
  180. package/src/native/module.ts +6 -0
  181. package/src/native/spec.ts +45 -10
  182. package/src/purchases.ts +4 -4
  183. package/src/types.ts +12 -15
  184. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  185. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -1,36 +1,37 @@
1
1
  // packages/swiss-knife-android/src/main/java/com/appswissknife/offerings/OfferingsRepository.kt
2
2
  //
3
- // Phase 6 commit 4 — fetch offerings from the backend and enrich with live
4
- // Play Billing prices.
3
+ // Offerings from the backend, priced live by the store.
5
4
  //
6
- // Backend contract: we use the existing /api/sdk/paywalls/show endpoint
7
- // (keyed by paywall_slug) as the source of truth for which products exist
8
- // in the user's current paywall variant. Output shape:
9
- // { paywall_id, slug, render_url, config, products_with_prices: [{
10
- // id, product_id, name, platform, duration_days, price, position,
11
- // badge_text, is_highlighted }], experiment_id, variant_id }
5
+ // Two reads, the same two iOS has:
12
6
  //
13
- // Why paywalls/show and not a brand-new /api/sdk/offerings endpoint:
14
- // - paywalls/show is the only endpoint today that returns the product set
15
- // in a per-user, experiment-resolved shape. Building a separate
16
- // /api/sdk/offerings would duplicate the variant-resolution logic that
17
- // paywalls/show already owns.
18
- // - The host app already knows the paywall slug it wants to render (paywall
19
- // selection is a product decision, not an SDK auto-resolution).
20
- // - Phase 5 (iOS) hasn't added a /api/sdk/offerings either as of branch
21
- // creation, so contracts stay aligned across platforms.
7
+ // - current(): the project's offerings, from `GET /api/sdk/offerings`. Every
8
+ // active paywall is an Offering whose packages are its products, and the
9
+ // server names the current one. This is what `SwissKnife.getOfferings()`
10
+ // (and React Native's `Purchases.getOfferings()`) returns, with the same
11
+ // contract as iOS `OfferingsService.current()`. Shape:
12
+ // { current_offering_id, offerings: [{ identifier, server_description,
13
+ // metadata, packages: [{ identifier, package_type, product_identifier,
14
+ // platform, duration_days, price, name }] }] }
22
15
  //
23
- // Price enrichment: paywalls/show returns the backend's last-known price
24
- // (set in the dashboard). For Play purchases the live price comes from
25
- // queryProductDetailsAsync at purchase time. We enrich each product with the
26
- // Play Billing ProductDetails when available so the dashboard's price drift
27
- // vs Play store is reflected in the UI.
16
+ // - current(paywallSlug, userId): one paywall, from `/api/sdk/paywalls/show`,
17
+ // with the variant an experiment assigned this user. Shape:
18
+ // { paywall_id, slug, render_url, config, products_with_prices: [{
19
+ // id, product_id, name, platform, duration_days, price, position,
20
+ // badge_text, is_highlighted }], experiment_id, variant_id }
28
21
  //
29
- // Cache: 1-hour in-memory cache. paywalls/show is keyed by user (assignment
30
- // is sticky) so the cache key includes (paywallSlug, userId).
22
+ // Both keep only the active store's products (`platform`), and price each one
23
+ // through the store's PriceEnrichmentProvider (Play or RuStore). A product the
24
+ // store cannot price (offline, not uploaded yet) keeps the dashboard price.
25
+ //
26
+ // Cache: 1 hour in memory. The catalogue is the same for every user; a
27
+ // paywall is keyed by (paywallSlug, userId) because experiment assignment is
28
+ // sticky per user. An answer the store priced none of (Play not connected,
29
+ // or its queries failed) is kept for a minute only, so the store's prices
30
+ // replace the dashboard's as soon as the store answers.
31
31
 
32
32
  package com.appswissknife.offerings
33
33
 
34
+ import android.util.Log
34
35
  import com.appswissknife.models.Offering
35
36
  import com.appswissknife.models.Offerings
36
37
  import com.appswissknife.models.Package
@@ -41,6 +42,9 @@ import com.appswissknife.models.StoreProductDiscount
41
42
  import com.appswissknife.models.SubscriptionPeriod
42
43
  import com.appswissknife.purchases.BillingHttpClient
43
44
  import com.appswissknife.purchases.PriceEnrichmentProvider
45
+ import com.appswissknife.purchases.ProductKindHint
46
+ import org.json.JSONArray
47
+ import org.json.JSONException
44
48
  import org.json.JSONObject
45
49
  import java.io.IOException
46
50
  import java.util.concurrent.ConcurrentHashMap
@@ -55,12 +59,49 @@ class OfferingsRepository(
55
59
  // Live price enrichment for the active store; null = backend prices only.
56
60
  private val priceProvider: PriceEnrichmentProvider?,
57
61
  private val clock: () -> Long = System::currentTimeMillis,
62
+ // Told the backend's product type of each of this store's products it reads
63
+ // (only those the backend names a type for). SwissKnife hands it to the
64
+ // gateway (PurchasesGateway.onServerProductTypes).
65
+ private val onServerProductTypes: (Map<String, String>) -> Unit = {},
58
66
  ) {
59
67
 
60
- private data class CacheEntry(val offerings: Offerings, val fetchedAt: Long)
68
+ private data class CacheEntry(val offerings: Offerings, val fetchedAt: Long, val ttlMillis: Long) {
69
+ fun isFreshAt(now: Long): Boolean = now - fetchedAt < ttlMillis
70
+ }
61
71
 
62
72
  private val cache = ConcurrentHashMap<String, CacheEntry>()
63
73
 
74
+ /** Guards [catalogCache]; held across the fetch so concurrent callers share one. */
75
+ private val catalogLock = Any()
76
+ @Volatile private var catalogCache: CacheEntry? = null
77
+
78
+ private val storeTags: Set<String> = platformTags.map { it.lowercase() }.toSet()
79
+
80
+ /**
81
+ * The project's offerings: every active paywall as an [Offering], from
82
+ * `GET /api/sdk/offerings`, each package priced by the store. Same contract
83
+ * as iOS `OfferingsService.current()`:
84
+ *
85
+ * - [Offerings.current] is the offering the server marks current
86
+ * (`current_offering_id`: the paywall flagged current, else the oldest
87
+ * active one), or the only offering when the server marks none;
88
+ * - each offering keeps only this store's packages, in the server's order;
89
+ * - a package's identifier and type are the server's.
90
+ *
91
+ * Served from a 1 hour in-memory cache (a minute when the store priced
92
+ * nothing); callers that arrive during a fetch wait for it instead of
93
+ * starting another.
94
+ */
95
+ @Throws(IOException::class)
96
+ fun current(): Offerings {
97
+ synchronized(catalogLock) {
98
+ catalogCache?.takeIf { it.isFreshAt(clock()) }?.let { return it.offerings }
99
+ val entry = parseCatalog(fetchJson("/api/sdk/offerings", emptyList()))
100
+ catalogCache = entry
101
+ return entry.offerings
102
+ }
103
+ }
104
+
64
105
  /**
65
106
  * Fetch the offerings for [paywallSlug] for the given [userId]. Goes to
66
107
  * /api/sdk/paywalls/show, optionally enriches each product with live
@@ -70,61 +111,105 @@ class OfferingsRepository(
70
111
  @Throws(IOException::class)
71
112
  fun current(paywallSlug: String, userId: String): Offerings {
72
113
  val key = "$paywallSlug:$userId"
73
- cache[key]?.takeIf { clock() - it.fetchedAt < CACHE_TTL_MILLIS }?.let { return it.offerings }
74
- val raw = fetchPaywallsShow(paywallSlug, userId)
75
- val parsed = parseAndEnrich(raw, paywallSlug)
76
- cache[key] = CacheEntry(parsed, clock())
77
- return parsed
114
+ cache[key]?.takeIf { it.isFreshAt(clock()) }?.let { return it.offerings }
115
+ val raw = fetchJson(
116
+ "/api/sdk/paywalls/show",
117
+ listOf("paywall_slug" to paywallSlug, "user_id" to userId),
118
+ )
119
+ val entry = parseAndEnrich(raw, paywallSlug)
120
+ cache[key] = entry
121
+ return entry.offerings
78
122
  }
79
123
 
80
124
  /** Invalidate the cache - useful on logIn/logOut (user assignment changes). */
81
125
  fun invalidate() {
82
126
  cache.clear()
127
+ catalogCache = null
83
128
  }
84
129
 
85
130
  // --- Internals ---------------------------------------------------------
86
131
 
132
+ /**
133
+ * GET [path] through the unified BackendHttpClient transport, which stamps
134
+ * the `X-API-Key` header the `withApiKeyAuth` routes read. A non-2xx answer
135
+ * or a body that is not a JSON object is an [IOException].
136
+ */
87
137
  @Throws(IOException::class)
88
- private fun fetchPaywallsShow(paywallSlug: String, userId: String): JSONObject {
89
- // Round-D: routed through the unified BackendHttpClient transport.
90
- // The pre-Round-D path issued the GET directly and (incorrectly) sent
91
- // `Authorization: Bearer ...` — the backend `paywalls/show` route
92
- // uses `withApiKeyAuth` (X-API-Key). simpleBackendGet stamps the
93
- // right header.
138
+ private fun fetchJson(path: String, query: List<Pair<String, String>>): JSONObject {
94
139
  val client = com.appswissknife.net.BackendHttpClient.create(apiKey, serverUrl)
95
- val (_, text) = client.simpleGet(
96
- path = "/api/sdk/paywalls/show",
97
- query = listOf(
98
- "paywall_slug" to paywallSlug,
99
- "user_id" to userId,
100
- ),
101
- )
102
- return JSONObject(text)
140
+ val (_, text) = client.simpleGet(path = path, query = query)
141
+ return try {
142
+ JSONObject(text)
143
+ } catch (e: JSONException) {
144
+ throw IOException("$path: malformed response", e)
145
+ }
103
146
  }
104
147
 
105
- private fun parseAndEnrich(raw: JSONObject, paywallSlug: String): Offerings {
106
- val productsJson = raw.optJSONArray("products_with_prices") ?: org.json.JSONArray()
148
+ private fun parseCatalog(raw: JSONObject): CacheEntry {
149
+ val offerings = raw.optJSONArray("offerings") ?: JSONArray()
150
+ val parsed = mutableListOf<CatalogOffering>()
151
+ for (i in 0 until offerings.length()) {
152
+ val o = offerings.optJSONObject(i) ?: continue
153
+ val identifier = o.optString("identifier")
154
+ if (identifier.isEmpty()) continue
155
+ val packages = o.optJSONArray("packages") ?: JSONArray()
156
+ val storePackages = (0 until packages.length())
157
+ .mapNotNull { packages.optJSONObject(it) }
158
+ .map { p ->
159
+ CatalogPackage(
160
+ identifier = p.stringOrNull("identifier"),
161
+ packageType = p.stringOrNull("package_type"),
162
+ product = backendProduct(p, idKey = "product_identifier"),
163
+ )
164
+ }
165
+ .filter { it.product.productId.isNotEmpty() && it.product.isForThisStore() }
166
+ parsed.add(
167
+ CatalogOffering(
168
+ identifier = identifier,
169
+ description = o.stringOrNull("server_description") ?: identifier,
170
+ metadata = o.optJSONObject("metadata").toMap(),
171
+ packages = storePackages,
172
+ )
173
+ )
174
+ }
175
+ val storeProducts = parsed.flatMap { o -> o.packages.map { it.product } }
176
+ reportProductTypes(storeProducts)
177
+ val priced = priceByStore(storeProducts)
178
+ val all = LinkedHashMap<String, Offering>()
179
+ for (o in parsed) {
180
+ all[o.identifier] = SimpleOffering(
181
+ identifier = o.identifier,
182
+ serverDescription = o.description,
183
+ metadata = o.metadata,
184
+ availablePackages = o.packages.map { p ->
185
+ SimplePackage(
186
+ identifier = p.identifier ?: p.product.productId,
187
+ packageType = p.packageType?.let(::packageTypeOf) ?: p.product.durationDays.toPackageType(),
188
+ product = withServerKind(priced[p.product.productId] ?: StoreProductFromBackend(p.product), p.product),
189
+ offeringIdentifier = o.identifier,
190
+ )
191
+ },
192
+ )
193
+ }
194
+ val current = raw.stringOrNull("current_offering_id")?.let { all[it] } ?: all.values.singleOrNull()
195
+ return cacheEntry(SimpleOfferings(all = all, current = current), storeProducts, priced)
196
+ }
197
+
198
+ private fun parseAndEnrich(raw: JSONObject, paywallSlug: String): CacheEntry {
199
+ val productsJson = raw.optJSONArray("products_with_prices") ?: JSONArray()
107
200
  val backendProducts = mutableListOf<BackendProduct>()
108
201
  for (i in 0 until productsJson.length()) {
109
202
  val o = productsJson.optJSONObject(i) ?: continue
110
- backendProducts.add(
111
- BackendProduct(
112
- productId = o.optString("product_id"),
113
- name = o.optString("name"),
114
- platform = o.optString("platform"),
115
- durationDays = o.optInt("duration_days"),
116
- backendPrice = o.optDouble("price", 0.0),
117
- )
118
- )
203
+ backendProducts.add(backendProduct(o, idKey = "product_id"))
119
204
  }
120
205
  // Filter to the active store's products (Play: play/android; RuStore: rustore).
121
- val tagsLower = platformTags.map { it.lowercase() }.toSet()
122
- val storeProducts = backendProducts.filter { it.platform.lowercase() in tagsLower }
206
+ val storeProducts = backendProducts.filter { it.isForThisStore() }
207
+ reportProductTypes(storeProducts)
123
208
  // Enrich with live store prices; ids the store can't resolve fall back to
124
209
  // the backend-priced product.
125
- val enriched = priceProvider?.enrich(storeProducts.associate { it.productId to it.name }) ?: emptyMap()
210
+ val enriched = priceByStore(storeProducts)
126
211
  val packages = storeProducts.map { bp ->
127
- val storeProduct = enriched[bp.productId] ?: StoreProductFromBackend(bp)
212
+ val storeProduct = withServerKind(enriched[bp.productId] ?: StoreProductFromBackend(bp), bp)
128
213
  SimplePackage(
129
214
  identifier = bp.productId,
130
215
  packageType = bp.durationDays.toPackageType(),
@@ -143,12 +228,88 @@ class OfferingsRepository(
143
228
  ),
144
229
  availablePackages = packages,
145
230
  )
146
- return SimpleOfferings(
147
- all = mapOf(paywallSlug to offering),
148
- current = offering,
231
+ return cacheEntry(
232
+ SimpleOfferings(all = mapOf(paywallSlug to offering), current = offering),
233
+ storeProducts,
234
+ enriched,
149
235
  )
150
236
  }
151
237
 
238
+ /**
239
+ * [offerings] as fetched now, kept for an hour, or for a minute when the
240
+ * store priced none of its [products] (dashboard prices only): Play not
241
+ * connected yet, or its queries failed.
242
+ */
243
+ private fun cacheEntry(
244
+ offerings: Offerings,
245
+ products: List<BackendProduct>,
246
+ priced: Map<String, StoreProduct>,
247
+ ): CacheEntry {
248
+ val storePricedNothing = priceProvider != null && products.isNotEmpty() && priced.isEmpty()
249
+ return CacheEntry(
250
+ offerings,
251
+ fetchedAt = clock(),
252
+ ttlMillis = if (storePricedNothing) UNPRICED_CACHE_TTL_MILLIS else CACHE_TTL_MILLIS,
253
+ )
254
+ }
255
+
256
+ private fun BackendProduct.isForThisStore(): Boolean = platform.lowercase() in storeTags
257
+
258
+ /**
259
+ * Tell [onServerProductTypes] the types the backend named; a failure there
260
+ * never fails the read. A LinkageError is caught too: a PurchasesGateway
261
+ * compiled separately against an SDK that predates
262
+ * `PurchasesGateway.onServerProductTypes` has no such method.
263
+ */
264
+ private fun reportProductTypes(products: List<BackendProduct>) {
265
+ val types = products.mapNotNull { p -> p.productType?.let { p.productId to it } }.toMap()
266
+ if (types.isEmpty()) return
267
+ try {
268
+ onServerProductTypes(types)
269
+ } catch (e: RuntimeException) {
270
+ Log.w(TAG, "product type listener failed", e)
271
+ } catch (e: LinkageError) {
272
+ Log.w(TAG, "product type listener failed", e)
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Live store prices for [products], keyed by product id. A store failure
278
+ * leaves every product on its dashboard price rather than failing the read.
279
+ */
280
+ private fun priceByStore(products: List<BackendProduct>): Map<String, StoreProduct> {
281
+ val provider = priceProvider ?: return emptyMap()
282
+ if (products.isEmpty()) return emptyMap()
283
+ return try {
284
+ provider.enrich(products.associate { it.productId to it.name })
285
+ } catch (e: RuntimeException) {
286
+ Log.w(TAG, "store price lookup failed; using dashboard prices", e)
287
+ emptyMap()
288
+ }
289
+ }
290
+
291
+ private fun backendProduct(o: JSONObject, idKey: String) = BackendProduct(
292
+ productId = o.optString(idKey),
293
+ name = o.optString("name"),
294
+ platform = o.optString("platform"),
295
+ durationDays = o.optInt("duration_days"),
296
+ backendPrice = o.optDouble("price", 0.0),
297
+ productType = o.stringOrNull("product_type"),
298
+ )
299
+
300
+ /** The server's `package_type` (see the offerings route); iOS maps the same strings. */
301
+ private fun packageTypeOf(raw: String): PackageType = when (raw) {
302
+ "monthly" -> PackageType.MONTHLY
303
+ "annual" -> PackageType.ANNUAL
304
+ "weekly" -> PackageType.WEEKLY
305
+ "lifetime" -> PackageType.LIFETIME
306
+ "six_month" -> PackageType.SIX_MONTH
307
+ "three_month" -> PackageType.THREE_MONTH
308
+ "two_month" -> PackageType.TWO_MONTH
309
+ "custom" -> PackageType.CUSTOM
310
+ else -> PackageType.UNKNOWN
311
+ }
312
+
152
313
  private fun Int.toPackageType(): PackageType = when (this) {
153
314
  in 0..0 -> PackageType.LIFETIME
154
315
  in 1..7 -> PackageType.WEEKLY
@@ -159,11 +320,47 @@ class OfferingsRepository(
159
320
  else -> PackageType.UNKNOWN
160
321
  }
161
322
 
323
+ private data class CatalogOffering(
324
+ val identifier: String,
325
+ val description: String,
326
+ val metadata: Map<String, Any?>,
327
+ val packages: List<CatalogPackage>,
328
+ )
329
+
330
+ private data class CatalogPackage(
331
+ val identifier: String?,
332
+ val packageType: String?,
333
+ val product: BackendProduct,
334
+ )
335
+
162
336
  companion object {
337
+ private const val TAG = "SwissKnife.Offerings"
163
338
  private const val CACHE_TTL_MILLIS: Long = 60L * 60 * 1000 // 1h
339
+ private const val UNPRICED_CACHE_TTL_MILLIS: Long = 60L * 1000 // 1 min
164
340
  }
165
341
  }
166
342
 
343
+ // --- JSON helpers ------------------------------------------------------------
344
+
345
+ /** A string field, or null when it is absent, JSON null or empty. */
346
+ private fun JSONObject.stringOrNull(key: String): String? =
347
+ if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() }
348
+
349
+ /** A JSON object as plain Kotlin values: nested objects as maps, arrays as lists. */
350
+ private fun JSONObject?.toMap(): Map<String, Any?> {
351
+ if (this == null) return emptyMap()
352
+ val out = LinkedHashMap<String, Any?>()
353
+ for (key in keys()) out[key] = opt(key).toPlain()
354
+ return out
355
+ }
356
+
357
+ private fun Any?.toPlain(): Any? = when (this) {
358
+ null, JSONObject.NULL -> null
359
+ is JSONObject -> toMap()
360
+ is JSONArray -> (0 until length()).map { opt(it).toPlain() }
361
+ else -> this
362
+ }
363
+
167
364
  // --- Backend DTO -----------------------------------------------------------
168
365
 
169
366
  private data class BackendProduct(
@@ -172,7 +369,17 @@ private data class BackendProduct(
172
369
  val platform: String,
173
370
  val durationDays: Int,
174
371
  val backendPrice: Double,
175
- )
372
+ /** The server's product type when it sends one (auto_renewable, non_renewing, consumable, non_consumable). */
373
+ val productType: String?,
374
+ ) {
375
+ /**
376
+ * One-time (Play INAPP) per what the server describes: a consumable or
377
+ * non-consumable, or, when the server sends no product type, a zero-day
378
+ * duration, which is how the server and iOS mark a lifetime unlock.
379
+ */
380
+ val isOneTime: Boolean
381
+ get() = productType?.let { it == "consumable" || it == "non_consumable" } ?: (durationDays == 0)
382
+ }
176
383
 
177
384
  // --- Public model impls ----------------------------------------------------
178
385
 
@@ -198,7 +405,7 @@ data class SimplePackage(
198
405
  /** StoreProduct sourced from a backend BackendProduct - used when
199
406
  * queryProductDetailsAsync hasn't returned anything for this id (offline /
200
407
  * not yet uploaded to Play). */
201
- private class StoreProductFromBackend(private val bp: BackendProduct) : StoreProduct {
408
+ private class StoreProductFromBackend(private val bp: BackendProduct) : StoreProduct, ProductKindHint {
202
409
  override val id: String = bp.productId
203
410
  override val localizedTitle: String = bp.name
204
411
  override val localizedDescription: String = bp.name
@@ -207,13 +414,53 @@ private class StoreProductFromBackend(private val bp: BackendProduct) : StorePro
207
414
  currencyCode = "USD",
208
415
  amountMicros = (bp.backendPrice * 1_000_000).toLong(),
209
416
  )
210
- override val subscriptionPeriod: SubscriptionPeriod? = null
417
+ override val isOneTime: Boolean = bp.isOneTime
418
+ override val productKind: String? = bp.productType
419
+ /** From the dashboard duration, as iOS's backend-priced product; null for a one-time product. */
420
+ override val subscriptionPeriod: SubscriptionPeriod? =
421
+ if (bp.isOneTime) null else subscriptionPeriodFromDays(bp.durationDays)
211
422
  override val introductoryDiscount: StoreProductDiscount? = null
212
423
  override val discounts: List<StoreProductDiscount> = emptyList()
213
424
  }
214
425
 
426
+ /**
427
+ * [product] with the server's product type attached ([ProductKindHint.productKind]),
428
+ * so the React Native bridge can label a store-priced one-time product
429
+ * CONSUMABLE or NON_CONSUMABLE. Unchanged when the server names no type. The
430
+ * store's own one-time/subscription answer ([ProductKindHint.isOneTime]) wins
431
+ * over the server's type.
432
+ */
433
+ private fun withServerKind(product: StoreProduct, bp: BackendProduct): StoreProduct {
434
+ val kind = bp.productType ?: return product
435
+ val hint = product as? ProductKindHint
436
+ if (hint?.productKind == kind) return product
437
+ return KindedStoreProduct(product, kind, hint?.isOneTime ?: bp.isOneTime)
438
+ }
439
+
440
+ private class KindedStoreProduct(
441
+ inner: StoreProduct,
442
+ override val productKind: String,
443
+ override val isOneTime: Boolean,
444
+ ) : StoreProduct by inner, ProductKindHint
445
+
446
+ /** iOS `OfferingsService.subscriptionPeriodFromDays`, for the same dashboard durations. */
447
+ private fun subscriptionPeriodFromDays(days: Int): SubscriptionPeriod? = when (days) {
448
+ 0 -> null
449
+ 7 -> SimpleSubscriptionPeriod(1, SubscriptionPeriod.Unit.WEEK)
450
+ in 28..32 -> SimpleSubscriptionPeriod(1, SubscriptionPeriod.Unit.MONTH)
451
+ in 85..95 -> SimpleSubscriptionPeriod(3, SubscriptionPeriod.Unit.MONTH)
452
+ in 175..190 -> SimpleSubscriptionPeriod(6, SubscriptionPeriod.Unit.MONTH)
453
+ in 360..370 -> SimpleSubscriptionPeriod(1, SubscriptionPeriod.Unit.YEAR)
454
+ else -> SimpleSubscriptionPeriod(days, SubscriptionPeriod.Unit.DAY)
455
+ }
456
+
215
457
  data class SimplePrice(
216
458
  override val formatted: String,
217
459
  override val currencyCode: String,
218
460
  override val amountMicros: Long,
219
461
  ) : Price
462
+
463
+ data class SimpleSubscriptionPeriod(
464
+ override val value: Int,
465
+ override val unit: SubscriptionPeriod.Unit,
466
+ ) : SubscriptionPeriod
@@ -158,6 +158,7 @@ class SKTransaction(
158
158
 
159
159
  internal fun toJSON(): JSONObject = JSONObject().apply {
160
160
  put("traceId", traceId)
161
+ put("spanId", spanId)
161
162
  put("name", name)
162
163
  put("op", op)
163
164
  put("startTimestamp", ISO_DATE.format(startTime))