@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.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 (177) hide show
  1. package/CHANGELOG.md +385 -2
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  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 +7 -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/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +27 -6
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +27 -6
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +2 -0
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +2 -0
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +12 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +16 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +50 -9
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -0,0 +1,43 @@
1
+ // packages/swiss-knife-android-rustore/src/main/java/com/appswissknife/rustore/RuStoreInitProvider.kt
2
+ package com.appswissknife.rustore
3
+
4
+ import android.content.ContentProvider
5
+ import android.content.ContentValues
6
+ import android.database.Cursor
7
+ import android.net.Uri
8
+ import com.appswissknife.SwissKnife
9
+
10
+ /**
11
+ * Zero-config opt-in: a manifest-merged ContentProvider whose onCreate runs at
12
+ * process start (before Application.onCreate returns and well before
13
+ * SwissKnife.configure). Linking this add-on therefore swaps the base SDK's
14
+ * default Play gateway for the RuStoreGateway with no consumer code change. A
15
+ * build that doesn't depend on this module never merges the provider, so the
16
+ * base BillingClientGateway default holds.
17
+ *
18
+ * Standard "androidx.startup-style" no-op provider — it stores no data.
19
+ */
20
+ class RuStoreInitProvider : ContentProvider() {
21
+ override fun onCreate(): Boolean {
22
+ SwissKnife.registerGatewayFactory { RuStoreGateway() }
23
+ return false
24
+ }
25
+
26
+ override fun query(
27
+ uri: Uri,
28
+ projection: Array<out String>?,
29
+ selection: String?,
30
+ selectionArgs: Array<out String>?,
31
+ sortOrder: String?,
32
+ ): Cursor? = null
33
+
34
+ override fun getType(uri: Uri): String? = null
35
+ override fun insert(uri: Uri, values: ContentValues?): Uri? = null
36
+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
37
+ override fun update(
38
+ uri: Uri,
39
+ values: ContentValues?,
40
+ selection: String?,
41
+ selectionArgs: Array<out String>?,
42
+ ): Int = 0
43
+ }
@@ -0,0 +1,85 @@
1
+ // packages/swiss-knife-android-rustore/src/main/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt
2
+ //
3
+ // RuStore implementation of the base SDK's PriceEnrichmentProvider, on the
4
+ // RuStore **Pay** SDK. Lets OfferingsRepository enrich backend paywall products
5
+ // tagged platform "rustore" with live RuStore prices. RuStore types isolated here.
6
+ //
7
+ // Compile-verified against ru.rustore.sdk:pay:10.3.0 (Product getters + the
8
+ // value-class `.value` accessors for ProductId/Title/AmountLabel/Currency/Price).
9
+ package com.appswissknife.rustore
10
+
11
+ import android.util.Log
12
+ import com.appswissknife.models.Price
13
+ import com.appswissknife.models.StoreProduct
14
+ import com.appswissknife.models.StoreProductDiscount
15
+ import com.appswissknife.models.SubscriptionPeriod
16
+ import com.appswissknife.offerings.SimplePrice
17
+ import com.appswissknife.purchases.PriceEnrichmentProvider
18
+ import java.util.concurrent.CountDownLatch
19
+ import java.util.concurrent.TimeUnit
20
+ // RUSTORE SDK — Pay
21
+ import ru.rustore.sdk.pay.RuStorePayClient
22
+ import ru.rustore.sdk.pay.model.ProductId
23
+
24
+ class RuStorePriceEnrichmentProvider : PriceEnrichmentProvider {
25
+
26
+ override fun platformTags(): Set<String> = setOf("rustore")
27
+
28
+ override fun enrich(products: Map<String, String>): Map<String, StoreProduct> {
29
+ if (products.isEmpty()) return emptyMap()
30
+
31
+ val latch = CountDownLatch(1)
32
+ val out = HashMap<String, StoreProduct>()
33
+ // RUSTORE SDK — query live product details via the Pay product interactor.
34
+ // Blocks (≤5s) on the Task via a latch; the caller is already on
35
+ // OfferingsRepository's background thread.
36
+ RuStorePayClient.instance.getProductInteractor()
37
+ .getProducts(products.keys.map { ProductId(it) })
38
+ .addOnSuccessListener { resolved ->
39
+ for (p in resolved) {
40
+ val id = p.productId.value
41
+ out[id] = RuStoreStoreProduct(
42
+ id = id,
43
+ localizedTitle = runCatching { p.title.value }.getOrDefault("").ifEmpty { products[id].orEmpty() },
44
+ localizedDescription = runCatching { p.description?.value }.getOrNull() ?: products[id].orEmpty(),
45
+ priceLabel = runCatching { p.amountLabel.value }.getOrDefault(""),
46
+ currencyCode = runCatching { p.currency.value }.getOrDefault(""),
47
+ priceMinorUnits = runCatching { p.price?.value }.getOrNull(),
48
+ )
49
+ }
50
+ latch.countDown()
51
+ }
52
+ .addOnFailureListener { e ->
53
+ Log.w(TAG, "RuStore getProducts failed: ${e.message}")
54
+ latch.countDown()
55
+ }
56
+ runCatching { latch.await(5, TimeUnit.SECONDS) }
57
+ return out
58
+ }
59
+
60
+ private companion object {
61
+ const val TAG = "SwissKnife.RuStore"
62
+ }
63
+ }
64
+
65
+ /** StoreProduct backed by RuStore Pay product fields (already unwrapped to
66
+ * plain types so the value-class accessors stay isolated in enrich()). */
67
+ private class RuStoreStoreProduct(
68
+ override val id: String,
69
+ override val localizedTitle: String,
70
+ override val localizedDescription: String,
71
+ priceLabel: String,
72
+ currencyCode: String,
73
+ priceMinorUnits: Int?,
74
+ ) : StoreProduct {
75
+ // RuStore `price` is an Int in minor currency units (kopecks).
76
+ // micros = minorUnits * 10_000 (1 unit = 100 minor units = 1_000_000 micros).
77
+ override val price: Price = SimplePrice(
78
+ formatted = priceLabel,
79
+ currencyCode = currencyCode,
80
+ amountMicros = (priceMinorUnits?.toLong() ?: 0L) * 10_000L,
81
+ )
82
+ override val subscriptionPeriod: SubscriptionPeriod? = null
83
+ override val introductoryDiscount: StoreProductDiscount? = null
84
+ override val discounts: List<StoreProductDiscount> = emptyList()
85
+ }
package/app.plugin.js ADDED
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Expo config plugin for @app-swiss-knife/react-native-sdk push notifications.
3
+ *
4
+ * // app.json
5
+ * { "expo": { "plugins": [
6
+ * ["@app-swiss-knife/react-native-sdk", {
7
+ * "ios": { "mode": "development" },
8
+ * "android": { "googleServicesFile": "./google-services.json",
9
+ * "defaultChannel": { "id": "default", "name": "General" } }
10
+ * }]
11
+ * ] } }
12
+ *
13
+ * iOS
14
+ * - adds the `aps-environment` entitlement (`mode`: development | production,
15
+ * default `development`, same as expo-notifications — Xcode's distribution
16
+ * signing/export rewrites it to `production` for App Store/TestFlight builds;
17
+ * set `"production"` explicitly only for ad-hoc/enterprise builds that need it)
18
+ * - adds `remote-notification` to UIBackgroundModes
19
+ * - `notificationServiceExtension: true` is accepted but NOT generated (an
20
+ * extension target needs an Xcode project rewrite); a warning points at the
21
+ * manual steps in the README.
22
+ * Android
23
+ * - adds the POST_NOTIFICATIONS permission (Android 13+)
24
+ * - registers `com.appswissknife.notifications.SwissKnifeMessagingService`
25
+ * for `com.google.firebase.MESSAGING_EVENT` unless `registerMessagingService`
26
+ * is false. It defaults to false (with a warning) when expo-notifications or
27
+ * @react-native-firebase/messaging is in the project, because two services
28
+ * cannot both own FCM delivery: use the manual path then
29
+ * (Notifications.registerDeviceToken + trackReceived/trackOpened).
30
+ * - `googleServicesFile` is forwarded to Expo's own `android.googleServicesFile`
31
+ * (Expo copies the file and applies the google-services Gradle plugin); an
32
+ * explicit `expo.android.googleServicesFile` always wins.
33
+ * - adds `implementation "com.google.firebase:firebase-messaging:<ver>"` to the
34
+ * app module (the SDK declares it compileOnly so non-push apps stay clean)
35
+ * - `defaultChannel` is written as manifest meta-data
36
+ * (`com.appswissknife.notifications.default_channel_{id,name}`).
37
+ *
38
+ * The pure mutation helpers below are exported for unit tests; `expo/config-plugins`
39
+ * is loaded lazily so they can be used without Expo installed.
40
+ */
41
+
42
+ const MESSAGING_SERVICE = "com.appswissknife.notifications.SwissKnifeMessagingService";
43
+ const POST_NOTIFICATIONS = "android.permission.POST_NOTIFICATIONS";
44
+ const FCM_ACTION = "com.google.firebase.MESSAGING_EVENT";
45
+ const FIREBASE_MESSAGING = "com.google.firebase:firebase-messaging:24.0.3";
46
+ const CHANNEL_ID_KEY = "com.appswissknife.notifications.default_channel_id";
47
+ const CHANNEL_NAME_KEY = "com.appswissknife.notifications.default_channel_name";
48
+
49
+ /** Normalize plugin props, applying defaults. */
50
+ function normalizeProps(props) {
51
+ const p = props || {};
52
+ const ios = p.ios || {};
53
+ const android = p.android || {};
54
+ return {
55
+ ios: {
56
+ mode: ios.mode === "production" ? "production" : "development",
57
+ notificationServiceExtension: ios.notificationServiceExtension === true,
58
+ },
59
+ android: {
60
+ registerMessagingService:
61
+ typeof android.registerMessagingService === "boolean"
62
+ ? android.registerMessagingService
63
+ : undefined,
64
+ googleServicesFile:
65
+ typeof android.googleServicesFile === "string" ? android.googleServicesFile : undefined,
66
+ defaultChannel:
67
+ android.defaultChannel && android.defaultChannel.id
68
+ ? {
69
+ id: String(android.defaultChannel.id),
70
+ name: String(android.defaultChannel.name || android.defaultChannel.id),
71
+ }
72
+ : undefined,
73
+ },
74
+ };
75
+ }
76
+
77
+ /** entitlements mod: set `aps-environment`. */
78
+ function applyApsEnvironment(entitlements, mode) {
79
+ entitlements["aps-environment"] = mode;
80
+ return entitlements;
81
+ }
82
+
83
+ /** Info.plist mod: ensure `remote-notification` in UIBackgroundModes. */
84
+ function applyBackgroundModes(infoPlist) {
85
+ const modes = Array.isArray(infoPlist.UIBackgroundModes) ? infoPlist.UIBackgroundModes : [];
86
+ if (!modes.includes("remote-notification")) modes.push("remote-notification");
87
+ infoPlist.UIBackgroundModes = modes;
88
+ return infoPlist;
89
+ }
90
+
91
+ function upsertMetaData(application, name, value) {
92
+ const list = (application["meta-data"] = application["meta-data"] || []);
93
+ const existing = list.find((m) => m.$ && m.$["android:name"] === name);
94
+ if (existing) existing.$["android:value"] = value;
95
+ else list.push({ $: { "android:name": name, "android:value": value } });
96
+ }
97
+
98
+ /** AndroidManifest mod (operates on the parsed manifest object). Idempotent. */
99
+ function applyAndroidManifest(manifestRoot, android) {
100
+ const manifest = manifestRoot.manifest;
101
+
102
+ const perms = (manifest["uses-permission"] = manifest["uses-permission"] || []);
103
+ if (!perms.some((p) => p.$ && p.$["android:name"] === POST_NOTIFICATIONS)) {
104
+ perms.push({ $: { "android:name": POST_NOTIFICATIONS } });
105
+ }
106
+
107
+ const application = manifest.application && manifest.application[0];
108
+ if (!application) return manifestRoot;
109
+
110
+ const services = (application.service = application.service || []);
111
+ const register = !android || android.registerMessagingService !== false;
112
+ if (register && !services.some((s) => s.$ && s.$["android:name"] === MESSAGING_SERVICE)) {
113
+ services.push({
114
+ $: { "android:name": MESSAGING_SERVICE, "android:exported": "false" },
115
+ "intent-filter": [{ action: [{ $: { "android:name": FCM_ACTION } }] }],
116
+ });
117
+ }
118
+
119
+ if (android && android.defaultChannel) {
120
+ upsertMetaData(application, CHANNEL_ID_KEY, android.defaultChannel.id);
121
+ upsertMetaData(application, CHANNEL_NAME_KEY, android.defaultChannel.name);
122
+ }
123
+ return manifestRoot;
124
+ }
125
+
126
+ const CONFLICTING_LIBS = ["expo-notifications", "@react-native-firebase/messaging"];
127
+
128
+ /**
129
+ * Name of a push library in the project that already owns FCM delivery
130
+ * (in the Expo `plugins` list or the project's package.json), else null.
131
+ */
132
+ function detectMessagingConflict(config, pkgJson) {
133
+ const plugins = (config && config.plugins) || [];
134
+ for (const entry of plugins) {
135
+ const name = Array.isArray(entry) ? entry[0] : entry;
136
+ if (CONFLICTING_LIBS.includes(name)) return name;
137
+ }
138
+ const deps = Object.assign({}, pkgJson && pkgJson.dependencies, pkgJson && pkgJson.devDependencies);
139
+ return CONFLICTING_LIBS.find((n) => n in deps) || null;
140
+ }
141
+
142
+ function readProjectPackageJson() {
143
+ try {
144
+ return JSON.parse(require("fs").readFileSync(require("path").join(process.cwd(), "package.json"), "utf8"));
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+
150
+ /** Forward googleServicesFile to Expo's own field unless the app set one. */
151
+ function applyGoogleServicesFile(config, android) {
152
+ if (android && android.googleServicesFile) {
153
+ config.android = config.android || {};
154
+ if (!config.android.googleServicesFile) {
155
+ config.android.googleServicesFile = android.googleServicesFile;
156
+ }
157
+ }
158
+ return config;
159
+ }
160
+
161
+ /** app/build.gradle mod: add firebase-messaging to `dependencies` once. */
162
+ function applyAppBuildGradle(contents) {
163
+ if (contents.includes("com.google.firebase:firebase-messaging")) return contents;
164
+ const line = ` implementation "${FIREBASE_MESSAGING}"\n`;
165
+ const re = /dependencies\s*\{\n/;
166
+ if (re.test(contents)) return contents.replace(re, (m) => m + line);
167
+ return contents + `\ndependencies {\n${line}}\n`;
168
+ }
169
+
170
+ /**
171
+ * Load `expo/config-plugins` from the APP's dependency tree. This package has
172
+ * no `expo` dependency of its own, so under pnpm (or any symlinked workspace /
173
+ * store layout) a bare `require("expo/config-plugins")` from this file cannot
174
+ * resolve. `expo prebuild` happens to patch resolution, but the Xcode
175
+ * "Generate app.config for prebuilt Constants.manifest" script phase evaluates
176
+ * the config with plain Node and failed with MODULE_NOT_FOUND. Resolve from the
177
+ * project root (cwd) first, then from this file.
178
+ */
179
+ function loadConfigPlugins() {
180
+ const paths = [process.cwd(), __dirname];
181
+ try {
182
+ return require(require.resolve("expo/config-plugins", { paths }));
183
+ } catch {
184
+ return require("expo/config-plugins");
185
+ }
186
+ }
187
+
188
+ function withSwissKnifePush(config, props) {
189
+ const { withEntitlementsPlist, withInfoPlist, withAndroidManifest, withAppBuildGradle, withGradleProperties, withStringsXml } =
190
+ loadConfigPlugins();
191
+ const opts = normalizeProps(props);
192
+ const rustore = props?.android?.rustore;
193
+ config = withGradleProperties(config, (c) => {
194
+ c.modResults = c.modResults.filter((entry) => entry.key !== "swissKnifeStore");
195
+ c.modResults.push({ type: "property", key: "swissKnifeStore", value: rustore ? "rustore" : "play" });
196
+ return c;
197
+ });
198
+ if (rustore) {
199
+ if (!/^\d+$/.test(String(rustore.consoleAppId ?? "")) || !/^[a-z][a-z0-9+.-]*$/.test(rustore.scheme ?? "")) {
200
+ throw new Error("android.rustore requires consoleAppId (digits) and a valid deeplink scheme");
201
+ }
202
+ config = withStringsXml(config, (c) => {
203
+ c.modResults.resources.string = (c.modResults.resources.string || []).filter((entry) => entry.$?.name !== "swissknife_rustore_app_id");
204
+ c.modResults.resources.string.push({ $: { name: "swissknife_rustore_app_id", translatable: "false" }, _: String(rustore.consoleAppId) });
205
+ return c;
206
+ });
207
+ config = withAndroidManifest(config, (c) => {
208
+ applyRuStoreManifest(c.modResults, rustore.scheme);
209
+ return c;
210
+ });
211
+ }
212
+
213
+ config = withEntitlementsPlist(config, (c) => {
214
+ applyApsEnvironment(c.modResults, opts.ios.mode);
215
+ return c;
216
+ });
217
+ config = withInfoPlist(config, (c) => {
218
+ applyBackgroundModes(c.modResults);
219
+ return c;
220
+ });
221
+ if (opts.ios.notificationServiceExtension) {
222
+ console.warn(
223
+ "[swiss-knife] ios.notificationServiceExtension: the extension target is not generated " +
224
+ "automatically. Add a Notification Service Extension target and subclass " +
225
+ "SwissKnifeNotificationServiceExtension — see the README, \"Push notifications\"."
226
+ );
227
+ }
228
+
229
+ let registerService = opts.android.registerMessagingService;
230
+ if (registerService === undefined) {
231
+ const conflict = detectMessagingConflict(config, readProjectPackageJson());
232
+ registerService = !conflict;
233
+ if (conflict) {
234
+ console.warn(
235
+ "[swiss-knife] " + conflict + " detected: NOT registering SwissKnifeMessagingService " +
236
+ "(two FCM services cannot both own delivery). Register tokens with " +
237
+ "Notifications.registerDeviceToken and report events with trackReceived/trackOpened, " +
238
+ "or set android.registerMessagingService: true to override."
239
+ );
240
+ }
241
+ }
242
+ config = withAndroidManifest(config, (c) => {
243
+ applyAndroidManifest(c.modResults, Object.assign({}, opts.android, { registerMessagingService: registerService }));
244
+ return c;
245
+ });
246
+ config = withAppBuildGradle(config, (c) => {
247
+ if (c.modResults.language === "groovy") {
248
+ c.modResults.contents = applyAppBuildGradle(c.modResults.contents);
249
+ } else {
250
+ console.warn("[swiss-knife] app/build.gradle is not Groovy; add " + FIREBASE_MESSAGING + " to dependencies by hand.");
251
+ }
252
+ return c;
253
+ });
254
+ return applyGoogleServicesFile(config, opts.android);
255
+ }
256
+
257
+ module.exports = withSwissKnifePush;
258
+ module.exports.default = withSwissKnifePush;
259
+ module.exports.loadConfigPlugins = loadConfigPlugins;
260
+ module.exports.normalizeProps = normalizeProps;
261
+ module.exports.applyApsEnvironment = applyApsEnvironment;
262
+ module.exports.applyBackgroundModes = applyBackgroundModes;
263
+ module.exports.applyAndroidManifest = applyAndroidManifest;
264
+ module.exports.detectMessagingConflict = detectMessagingConflict;
265
+ module.exports.applyAppBuildGradle = applyAppBuildGradle;
266
+ module.exports.applyGoogleServicesFile = applyGoogleServicesFile;
267
+ module.exports.MESSAGING_SERVICE = MESSAGING_SERVICE;
268
+
269
+ function applyRuStoreManifest(manifest, scheme) {
270
+ const app = manifest.manifest.application[0];
271
+ app["meta-data"] = (app["meta-data"] || []).filter((entry) => !["console_app_id_value", "sdk_pay_scheme_value"].includes(entry.$["android:name"]));
272
+ app["meta-data"].push(
273
+ { $: { "android:name": "console_app_id_value", "android:value": "@string/swissknife_rustore_app_id" } },
274
+ { $: { "android:name": "sdk_pay_scheme_value", "android:value": scheme } },
275
+ );
276
+ const activity = (app.activity || []).find((a) => (a["intent-filter"] || []).some((f) => (f.action || []).some((v) => v.$["android:name"] === "android.intent.action.MAIN")));
277
+ if (!activity) throw new Error("RuStore requires a launcher Activity for payment return intents");
278
+ activity.$["android:launchMode"] = "singleTask";
279
+ activity["intent-filter"] = (activity["intent-filter"] || []).filter((f) => !(f.data || []).some((d) => d.$["android:scheme"] === scheme));
280
+ activity["intent-filter"].push({
281
+ action: [{ $: { "android:name": "android.intent.action.VIEW" } }],
282
+ category: ["DEFAULT", "BROWSABLE"].map((v) => ({ $: { "android:name": `android.intent.category.${v}` } })),
283
+ data: [{ $: { "android:scheme": scheme } }],
284
+ });
285
+ return manifest;
286
+ }
287
+ module.exports.applyRuStoreManifest = applyRuStoreManifest;
@@ -136,4 +136,24 @@ RCT_EXTERN_METHOD(removeListeners:(double)count)
136
136
  return YES;
137
137
  }
138
138
 
139
+ // Push notifications (swiss-push) — see src/modules/notifications.ts.
140
+ RCT_EXTERN_METHOD(pushRequestPermission:(BOOL)provisional
141
+ resolver:(RCTPromiseResolveBlock)resolve
142
+ rejecter:(RCTPromiseRejectBlock)reject)
143
+
144
+ RCT_EXTERN_METHOD(pushPermissionStatus:(RCTPromiseResolveBlock)resolve
145
+ rejecter:(RCTPromiseRejectBlock)reject)
146
+
147
+ RCT_EXTERN_METHOD(pushRegister:(RCTPromiseResolveBlock)resolve
148
+ rejecter:(RCTPromiseRejectBlock)reject)
149
+
150
+ RCT_EXTERN_METHOD(pushUnregister:(RCTPromiseResolveBlock)resolve
151
+ rejecter:(RCTPromiseRejectBlock)reject)
152
+
153
+ RCT_EXTERN_METHOD(pushGetInitialNotification:(RCTPromiseResolveBlock)resolve
154
+ rejecter:(RCTPromiseRejectBlock)reject)
155
+
156
+ RCT_EXTERN_METHOD(pushDeviceInfo:(RCTPromiseResolveBlock)resolve
157
+ rejecter:(RCTPromiseRejectBlock)reject)
158
+
139
159
  @end
@@ -28,6 +28,20 @@ class SwissKnifePurchases: RCTEventEmitter {
28
28
  // so re-configuring does not leak/stack duplicate stream subscribers.
29
29
  private var customerInfoTask: Task<Void, Never>?
30
30
 
31
+ override init() {
32
+ super.init()
33
+ // Runs before JS: if the app opted into native push on an earlier launch,
34
+ // install the notification delegate proxy NOW so a cold-start tap is
35
+ // captured (and buffered until JS listens / asks for the initial one).
36
+ SwissKnife.Notifications.resumeAutoIntegration()
37
+ }
38
+
39
+ /// Called from SwissKnifePushBootstrap.m when the app finishes launching (well
40
+ /// before JS), so a cold-start notification tap finds the delegate proxy.
41
+ @objc static func resumePushEarly() {
42
+ SwissKnife.Notifications.resumeAutoIntegration()
43
+ }
44
+
31
45
  deinit {
32
46
  customerInfoTask?.cancel()
33
47
  }
@@ -37,15 +51,42 @@ class SwissKnifePurchases: RCTEventEmitter {
37
51
  // Event names this module can emit. Must include the CustomerInfo updated event
38
52
  // whose JS constant is CUSTOMER_INFO_UPDATED_EVENT in src/native/spec.ts.
39
53
  override func supportedEvents() -> [String]! {
40
- return ["Purchases-CustomerInfoUpdated"]
54
+ return ["Purchases-CustomerInfoUpdated", "SwissKnife-PushOpened"]
41
55
  }
42
56
 
43
57
  override static func requiresMainQueueSetup() -> Bool {
44
58
  return true
45
59
  }
46
60
 
47
- override func startObserving() { hasListeners = true }
48
- override func stopObserving() { hasListeners = false }
61
+ override func startObserving() {
62
+ hasListeners = true
63
+ // Push opens: drain anything buffered before JS listened, then stream.
64
+ SwissKnife.Notifications.onOpened = { [weak self] open in
65
+ self?.sendPushOpened(open)
66
+ }
67
+ }
68
+ override func stopObserving() {
69
+ hasListeners = false
70
+ SwissKnife.Notifications.onOpened = nil
71
+ }
72
+
73
+ private static func encodeOpen(_ open: SwissKnife.Notifications.Opened) -> [String: Any] {
74
+ var out: [String: Any] = [
75
+ "messageId": open.payload.messageId,
76
+ "deliveryId": open.payload.deliveryId,
77
+ "data": (JSONSerialization.isValidJSONObject(open.userInfo) ? open.userInfo : [:]) as [AnyHashable: Any],
78
+ ]
79
+ if let link = open.payload.link { out["link"] = link.absoluteString }
80
+ if let action = open.actionId { out["actionId"] = action }
81
+ return out
82
+ }
83
+
84
+ private func sendPushOpened(_ open: SwissKnife.Notifications.Opened) {
85
+ DispatchQueue.main.async {
86
+ guard self.hasListeners else { return }
87
+ self.sendEvent(withName: "SwissKnife-PushOpened", body: Self.encodeOpen(open))
88
+ }
89
+ }
49
90
 
50
91
  private func sendCustomerInfo(_ customerInfo: [String: Any]) {
51
92
  // RCTEventEmitter is not thread-safe; the stream callback runs off-main.
@@ -497,10 +538,63 @@ class SwissKnifePurchases: RCTEventEmitter {
497
538
  func setPushToken(_ pushToken: NSString?,
498
539
  resolver resolve: @escaping RCTPromiseResolveBlock,
499
540
  rejecter reject: @escaping RCTPromiseRejectBlock) {
541
+ // Legacy attribute-only path, kept for source compatibility. New code
542
+ // uses pushRegister / registerDeviceToken (see src/modules/notifications.ts).
500
543
  SwissKnife.setPushToken(pushToken as String?)
501
544
  resolve(nil)
502
545
  }
503
546
 
547
+ // MARK: Push notifications (swiss-push)
548
+
549
+ @objc(pushRequestPermission:resolver:rejecter:)
550
+ func pushRequestPermission(_ provisional: Bool,
551
+ resolver resolve: @escaping RCTPromiseResolveBlock,
552
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
553
+ Task {
554
+ let status = await SwissKnife.Notifications.requestPermission(provisional: provisional)
555
+ resolve(status.rawValue)
556
+ }
557
+ }
558
+
559
+ @objc(pushPermissionStatus:rejecter:)
560
+ func pushPermissionStatus(_ resolve: @escaping RCTPromiseResolveBlock,
561
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
562
+ Task { resolve(await SwissKnife.Notifications.permissionStatus().rawValue) }
563
+ }
564
+
565
+ /// Installs the delegate proxy + APNs-token capture, then asks iOS for a token.
566
+ @objc(pushRegister:rejecter:)
567
+ func pushRegister(_ resolve: @escaping RCTPromiseResolveBlock,
568
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
569
+ SwissKnife.Notifications.enableAutoIntegration(captureDeviceToken: true)
570
+ SwissKnife.Notifications.registerForRemoteNotifications()
571
+ resolve(nil)
572
+ }
573
+
574
+ @objc(pushUnregister:rejecter:)
575
+ func pushUnregister(_ resolve: @escaping RCTPromiseResolveBlock,
576
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
577
+ SwissKnife.Notifications.unregister()
578
+ resolve(nil)
579
+ }
580
+
581
+ @objc(pushGetInitialNotification:rejecter:)
582
+ func pushGetInitialNotification(_ resolve: @escaping RCTPromiseResolveBlock,
583
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
584
+ if let open = SwissKnife.Notifications.takeInitialOpen() {
585
+ resolve(Self.encodeOpen(open))
586
+ } else {
587
+ resolve(nil)
588
+ }
589
+ }
590
+
591
+ /// Facts the JS-only registration path cannot know.
592
+ @objc(pushDeviceInfo:rejecter:)
593
+ func pushDeviceInfo(_ resolve: @escaping RCTPromiseResolveBlock,
594
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
595
+ resolve(SwissKnife.Notifications.deviceInfo())
596
+ }
597
+
504
598
  @objc(setLogLevel:resolver:rejecter:)
505
599
  func setLogLevel(_ level: String,
506
600
  resolver resolve: @escaping RCTPromiseResolveBlock,
@@ -0,0 +1,34 @@
1
+ // packages/react-native-sdk/ios/SwissKnifePushBootstrap.m
2
+ //
3
+ // Cold-start notification taps need the UNUserNotificationCenter delegate to
4
+ // exist by the time the app finishes launching; otherwise iOS answers the
5
+ // pending response with nothing and the tap is lost. React Native instantiates
6
+ // the `SwissKnifePurchases` module lazily (when JS first touches it), which is
7
+ // AFTER the launch response has already been dropped, so resuming push
8
+ // auto-integration from the module's init is too late. Hook the launch
9
+ // notification from +load instead (no AppDelegate edit needed) and re-install
10
+ // the delegate proxy when the app opted in on an earlier launch.
11
+ #import <Foundation/Foundation.h>
12
+ #import <UIKit/UIKit.h>
13
+
14
+ @interface SwissKnifePushBootstrap : NSObject
15
+ @end
16
+
17
+ @implementation SwissKnifePushBootstrap
18
+
19
+ + (void)load {
20
+ [[NSNotificationCenter defaultCenter]
21
+ addObserverForName:UIApplicationDidFinishLaunchingNotification
22
+ object:nil
23
+ queue:nil
24
+ usingBlock:^(NSNotification *note) {
25
+ Class moduleClass = NSClassFromString(@"SwissKnifePurchases");
26
+ SEL resume = NSSelectorFromString(@"resumePushEarly");
27
+ if (moduleClass && [moduleClass respondsToSelector:resume]) {
28
+ void (*call)(id, SEL) = (void (*)(id, SEL))[moduleClass methodForSelector:resume];
29
+ call(moduleClass, resume);
30
+ }
31
+ }];
32
+ }
33
+
34
+ @end