@app-swiss-knife/react-native-sdk 0.5.1 → 0.6.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 (36) hide show
  1. package/CHANGELOG.md +77 -2
  2. package/README.md +19 -8
  3. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  4. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  5. package/ios/SwissKnifePurchases.swift +9 -1
  6. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  7. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +7 -0
  8. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +2 -3
  9. package/ios/vendor/SwissKnifeiOS/Services/EntitlementSync.swift +104 -0
  10. package/ios/vendor/SwissKnifeiOS/Services/IntroEligibility.swift +137 -0
  11. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +368 -52
  12. package/ios/vendor/SwissKnifeiOS/Services/TransactionEvents.swift +371 -0
  13. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +73 -8
  14. package/ios-notification-service/SwissKnifeNotificationService.podspec +1 -1
  15. package/lib/commonjs/internal/config.js +3 -0
  16. package/lib/commonjs/internal/config.js.map +1 -1
  17. package/lib/commonjs/native/spec.js.map +1 -1
  18. package/lib/commonjs/types.js.map +1 -1
  19. package/lib/module/internal/config.js +3 -0
  20. package/lib/module/internal/config.js.map +1 -1
  21. package/lib/module/native/spec.js.map +1 -1
  22. package/lib/module/types.js.map +1 -1
  23. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  24. package/lib/typescript/commonjs/native/spec.d.ts +2 -0
  25. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  26. package/lib/typescript/commonjs/types.d.ts +13 -0
  27. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  28. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  29. package/lib/typescript/module/native/spec.d.ts +2 -0
  30. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  31. package/lib/typescript/module/types.d.ts +13 -0
  32. package/lib/typescript/module/types.d.ts.map +1 -1
  33. package/package.json +1 -1
  34. package/src/internal/config.ts +3 -0
  35. package/src/native/spec.ts +4 -0
  36. package/src/types.ts +13 -0
package/CHANGELOG.md CHANGED
@@ -7,11 +7,86 @@ this package follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
  While the major version is `0`, a minor bump may carry behavioral changes that a
8
8
  `1.x` package would treat as breaking; each one is called out under **Changed**.
9
9
 
10
- The native iOS and Android SDKs are not published separately — their sources are
11
- vendored into this npm tarball at pack time, so a version here covers all three.
10
+ The native iOS and Android SDKs' sources are vendored into this npm tarball at
11
+ pack time, so a version here covers all three. The iOS SDK is also published as
12
+ a Swift package (https://github.com/Remneys/swiss-knife-ios) under the same
13
+ version.
12
14
 
13
15
  ## [Unreleased]
14
16
 
17
+ ## [0.6.0] - 2026-11-26
18
+
19
+ Four StoreKit 2 additions to the native iOS SDK (`SwissKnifeiOS`), asked for
20
+ by a native SwiftUI app, and the same SDK published as a Swift package. The
21
+ additions are in native code, so React Native apps get them only through a new
22
+ store build; of the four, React Native reaches only the two configuration
23
+ switches below from JS so far. Android is unchanged.
24
+
25
+ ### Added
26
+
27
+ - **iOS: `appAccountToken` on purchases.** `purchasePackage(_:appAccountToken:)`
28
+ and `purchaseStoreProduct(_:appAccountToken:)` take an optional UUID. Without
29
+ one, the SDK sends the signed-in app user id when it is a UUID (StoreKit
30
+ signs it lower-case). The backend reads the token from the verified
31
+ transaction, remembers which user it stands for when it is not the user id
32
+ itself, and resolves App Store Server Notifications and outgoing webhooks
33
+ to that user.
34
+ - **iOS: `syncCurrentEntitlements()`.** Posts the device's current
35
+ entitlements (`Transaction.currentEntitlements`) that the backend has not
36
+ accepted for the current user, without `AppStore.sync()` and so without the
37
+ Apple ID sheet, and returns `CustomerInfo`. Hashed fingerprints of accepted
38
+ transactions on the device mean a launch with nothing new sends nothing.
39
+ A sync never moves a purchase between users: it posts with
40
+ `silent_sync: true`, and the backend records what belongs to the current
41
+ user but leaves a purchase it holds for another user where it is, whatever
42
+ the app's transfer setting, and says so (`owned_elsewhere`). The SDK
43
+ reports it as a `.sync` transaction event with `ownedByAnotherUser: true`.
44
+ `restorePurchases()` still calls `AppStore.sync()` first, posts everything
45
+ and applies the transfer setting.
46
+ - **iOS: `checkTrialOrIntroDiscountEligibility(productIdentifiers:)` and
47
+ `checkTrialOrIntroDiscountEligibility(subscriptionGroupIdentifier:)`.**
48
+ Answer `.eligible`, `.ineligible`, `.noIntroOfferExists` or `.unknown` from
49
+ StoreKit 2. The per-product form asks StoreKit once per subscription group.
50
+ - **iOS: transaction events.** `addTransactionObserver(_:)` /
51
+ `removeTransactionObserver(_:)` and the `transactionEvents` stream report
52
+ each purchase, renewal, restore, sync and refund/revocation the SDK handles.
53
+ An event carries the product, transaction and original transaction ids,
54
+ dates, price and currency, offer type (trial, introductory, promotional,
55
+ offer code, win-back or none), environment, `appAccountToken`, and
56
+ `serverConfirmed`, and `ownedByAnotherUser` on a sync that left another
57
+ user's purchase with them. It fires after the backend answers, or with
58
+ `serverConfirmed: false` when the backend could not be reached or refused
59
+ the transaction. In that case a later event for the same transaction can
60
+ follow, so de-duplicate on `transactionIdentifier`. Observers never delay
61
+ `finish()`.
62
+ - **The native iOS SDK as a Swift package.** Each release is now also published
63
+ to the public repository https://github.com/Remneys/swiss-knife-ios, tagged
64
+ with the SDK version (no `v`), so a native iOS app adds it with
65
+ `.package(url: "https://github.com/Remneys/swiss-knife-ios", from: "<version>")`
66
+ and the `SwissKnifeiOS` product; a Notification Service Extension adds the
67
+ `SwissKnifeNotificationService` product. The package holds the same Swift
68
+ sources this npm package vendors, byte for byte. Nothing changes for React
69
+ Native apps.
70
+ - **React Native: `syncEntitlementsAutomatically` and
71
+ `automaticAppAccountToken` options on `Purchases.configure`** (iOS only,
72
+ both default `true`).
73
+
74
+ ### Changed
75
+
76
+ - **iOS: the SDK now syncs entitlements by itself** after `configure` and
77
+ after each `Identity.logIn`. The sync is debounced by a second and runs at
78
+ most once a minute per user. The automatic run does not post a transaction
79
+ whose `appAccountToken` belongs to another account of the app, and nothing
80
+ runs in `configureCore` mode. It never moves a purchase between users:
81
+ a subscription or one-time purchase the backend holds for another app user
82
+ stays with them under every transfer behaviour, `transfer_to_new_user`
83
+ included, until the user taps Restore. Turn the sync off with
84
+ `PurchasesConfiguration(syncEntitlementsAutomatically: false)` natively, or
85
+ with `syncEntitlementsAutomatically: false` in `Purchases.configure`.
86
+ - **iOS: purchases by a signed-in user whose app user id is a UUID now carry
87
+ that id as `appAccountToken`.** Turn this off with
88
+ `automaticAppAccountToken: false`.
89
+
15
90
  ## [0.5.1] - 2026-11-24
16
91
 
17
92
  Google Play consumables can be bought again, both platforms report each
package/README.md CHANGED
@@ -12,15 +12,18 @@ This SDK is part of a three-package split:
12
12
  | Package | Language | Purpose |
13
13
  | -------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------- |
14
14
  | `packages/swiss-knife-android` (not published; vendored by this package) | Kotlin | Native Android SDK — Play Billing v8 directly, own typed model layer. Owns `configure`, proxyURL. |
15
- | `packages/swiss-knife-ios` (not published; vendored by this package) | Swift | Native iOS SDK — StoreKit 2 directly, own typed model layer. Owns `configure`, proxyURL. |
15
+ | `packages/swiss-knife-ios` (SwiftPM: Remneys/swiss-knife-ios; vendored here) | Swift | Native iOS SDK — StoreKit 2 directly, own typed model layer. Owns `configure`, proxyURL. |
16
16
  | `packages/react-native-sdk` · `@app-swiss-knife/react-native-sdk` (this package) | TypeScript + Kotlin/Swift bridge | React Native bridge, on npm. **Vendors both native SDKs** into its own tarball. |
17
17
 
18
- Only the npm package is published. A native (non-React-Native) app cannot
19
- install the two native SDKs from SPM, CocoaPods or Maven today; it vendors their
20
- sources out of this package's tarball (`ios/vendor/SwissKnifeiOS` as a local Swift
21
- package, `android/vendor/java` and `android/vendor/res` as Kotlin source in the app
22
- module). The `setup-native` skill of the Swiss-Knife plugin
23
- (github.com/Remneys/swiss-knife-plugin) does that for you.
18
+ Only the npm package is published to a package registry. A native
19
+ (non-React-Native) iOS app adds the iOS SDK as a Swift package from its public
20
+ repository, https://github.com/Remneys/swiss-knife-ios (tagged with this
21
+ package's version), or vendors `ios/vendor/SwissKnifeiOS` out of this package's
22
+ tarball as a local Swift package; there is no CocoaPods pod. A native Android app
23
+ cannot install the Android SDK from Maven; it vendors `android/vendor/java` and
24
+ `android/vendor/res` as Kotlin source in the app module. The `setup-native` skill
25
+ of the Swiss-Knife plugin (github.com/Remneys/swiss-knife-plugin) does that for
26
+ you.
24
27
 
25
28
  ### How the bridge gets the native SDKs (vendoring)
26
29
 
@@ -126,6 +129,14 @@ const pkg = offerings.current?.availablePackages[0];
126
129
  if (pkg) await Purchases.purchasePackage(pkg);
127
130
  ```
128
131
 
132
+ An email or phone number the app sends (`Attributes.setEmail`,
133
+ `Attributes.setPhoneNumber`, or `$email` / `$phone` in identify properties)
134
+ goes with the public key, so it is recorded as an unverified claim: it never
135
+ links two people and never opens the person's support history to whoever
136
+ writes from that address. Only your server can assert one as the person's
137
+ own, by calling `POST /api/sdk/users/identify` with an agent credential (an
138
+ admin's `sk_mcp_` token with the `write` scope).
139
+
129
140
  ## The namespaces
130
141
 
131
142
  Everything hangs off `SwissKnife`, the same way it does in the native iOS and
@@ -427,7 +438,7 @@ project rewrite). Manual steps:
427
438
  It is deliberately separate from the SDK's pod and imports only Foundation +
428
439
  UserNotifications, so the extension stays under its memory cap. (A native
429
440
  app without React Native adds the `SwissKnifeNotificationService` product of
430
- the Swift package in `packages/swiss-knife-ios` instead.)
441
+ the Swift package https://github.com/Remneys/swiss-knife-ios instead.)
431
442
 
432
443
  3. Replace the generated class:
433
444
 
@@ -42,7 +42,7 @@ internal object DeviceContextProvider {
42
42
  * eventually inject this via `BuildConfig`, but for now keep it in
43
43
  * source so we don't have to thread build settings through every test.
44
44
  */
45
- const val SDK_VERSION: String = "0.5.1"
45
+ const val SDK_VERSION: String = "0.6.0"
46
46
 
47
47
  private val cacheLock = Any()
48
48
 
@@ -241,7 +241,7 @@ internal object IngestPlaceholderDevice {
241
241
  appBuild = "unknown",
242
242
  locale = Locale.getDefault().toString(),
243
243
  timezone = TimeZone.getDefault().id,
244
- sdkVersion = "0.5.1",
244
+ sdkVersion = "0.6.0",
245
245
  bundleIdentifier = null,
246
246
  )
247
247
  }
@@ -121,6 +121,13 @@ class SwissKnifePurchases: RCTEventEmitter {
121
121
  sendInstallOnFirstLaunch: (options["sendInstallOnFirstLaunch"] as? Bool) ?? true
122
122
  )
123
123
 
124
+ // Silent entitlement sync after configure / logIn, and the user's UUID as
125
+ // the default appAccountToken. Both default on, as in a native app.
126
+ let purchases = SwissKnife.PurchasesConfiguration(
127
+ syncEntitlementsAutomatically: (options["syncEntitlementsAutomatically"] as? Bool) ?? true,
128
+ automaticAppAccountToken: (options["automaticAppAccountToken"] as? Bool) ?? true
129
+ )
130
+
124
131
  // Phase 5: SwissKnife owns the entire native subscription stack — StoreKit 2,
125
132
  // proxyURL, diagnostics, identity. RN + native-app paths configure identically.
126
133
  SwissKnife.configure(
@@ -129,7 +136,8 @@ class SwissKnifePurchases: RCTEventEmitter {
129
136
  proxyURL: proxyURL,
130
137
  storeKitVersion: storeKitVersion,
131
138
  logLevel: logLevel,
132
- attribution: attribution
139
+ attribution: attribution,
140
+ purchases: purchases
133
141
  )
134
142
 
135
143
  // Bridge the native SDK's CustomerInfo stream to the JS event channel.
@@ -99,7 +99,7 @@ internal enum DeviceContextProvider {
99
99
  /// Round A baseline. The build pipeline (`swiss-build`) will eventually
100
100
  /// inject this via `-D` flag, but for now keep it in source so we don't
101
101
  /// have to thread build settings through the SPM Package.swift.
102
- static let sdkVersionConstant: String = "0.5.1"
102
+ static let sdkVersionConstant: String = "0.6.0"
103
103
 
104
104
  private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
105
105
  private static var cached: DeviceContext?
@@ -382,6 +382,13 @@ public extension SwissKnife {
382
382
  }
383
383
  }
384
384
 
385
+ /// Whether a `logIn` is still resolving. The automatic entitlement
386
+ /// sync scheduled at configure time stands down for it: the login
387
+ /// syncs for its own user when it lands.
388
+ internal static var _hasLogInInFlight: Bool {
389
+ queue.sync { !inFlightLogIns.isEmpty }
390
+ }
391
+
385
392
  /// Test seam — drop all in-memory state and observers, restore
386
393
  /// the production network. Production code MUST NOT call this.
387
394
  internal static func _resetForTesting() {
@@ -16,7 +16,6 @@
16
16
  // `type` is one of:
17
17
  // "error" | "error_batch" | "analytics" | "transaction" | "session"
18
18
  // | "feedback" | "paywall" | "funnel"
19
- // (`store_notification` is server-side only — webhooks land there.)
20
19
  //
21
20
  // Architecture:
22
21
  // - `enqueue(_ item: IngestItem)` writes to `OfflineQueueStore<IngestItem>`
@@ -103,8 +102,8 @@ import os.log
103
102
  /// `errorBatch` case wraps an array of `error` payloads — used by the
104
103
  /// crash reporter when it has multiple buffered crashes to send.
105
104
  ///
106
- /// `storeNotification` is intentionally absent: it's an Apple/Google
107
- /// webhook path the server handles directly, never originated by the SDK.
105
+ /// There is no store notification type: Apple and Google notifications go
106
+ /// to the web app's verified webhook routes, never through `/ingest`.
108
107
  internal enum IngestItemType: String, Codable, Sendable {
109
108
  case error
110
109
  case errorBatch = "error_batch"
@@ -0,0 +1,104 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Services/EntitlementSync.swift
2
+ //
3
+ // Purchase-engine settings, and the on-device record of which transactions
4
+ // the backend already accepted for which subject, so the silent entitlement
5
+ // sync (`PurchaseService.syncCurrentEntitlements`) sends nothing when nothing
6
+ // is new.
7
+
8
+ import CryptoKit
9
+ import Foundation
10
+
11
+ extension SwissKnife {
12
+
13
+ /// Settings for the purchase engine (`configure(...)` /
14
+ /// `configurePurchases(...)`). The defaults are what most apps want.
15
+ public struct PurchasesConfiguration: Sendable, Equatable {
16
+
17
+ /// Silently sync the device's current entitlements with the backend
18
+ /// after `configure` and after every `Identity.logIn`: transactions
19
+ /// the backend has not accepted for the current user are posted, and
20
+ /// nothing is sent when there are none. It never calls
21
+ /// `AppStore.sync()`, so it never shows the Apple ID sheet
22
+ /// (`restorePurchases()` still does, for a Restore button).
23
+ ///
24
+ /// A sync, automatic or `syncCurrentEntitlements()`, never moves a
25
+ /// purchase between users: the backend leaves one it holds for
26
+ /// another user where it is, whatever the app's transfer setting, and
27
+ /// the SDK reports it (`TransactionEvent.ownedByAnotherUser`). Only
28
+ /// `restorePurchases()` applies the transfer setting.
29
+ ///
30
+ /// The automatic run also skips a transaction whose `appAccountToken`
31
+ /// is a different UUID than the signed-in user's own id (while
32
+ /// `automaticAppAccountToken` is on): it was bought by another account
33
+ /// of this app on the same Apple ID, so it is not even posted.
34
+ public var syncEntitlementsAutomatically: Bool
35
+
36
+ /// When the current app user id is a UUID, attach it to every
37
+ /// purchase as StoreKit's `appAccountToken`, unless the call passes
38
+ /// one. Apple then repeats it in every transaction and App Store
39
+ /// Server Notification of that purchase, which ties a renewal or a
40
+ /// refund to the user even when it reaches the backend first.
41
+ public var automaticAppAccountToken: Bool
42
+
43
+ public init(
44
+ syncEntitlementsAutomatically: Bool = true,
45
+ automaticAppAccountToken: Bool = true
46
+ ) {
47
+ self.syncEntitlementsAutomatically = syncEntitlementsAutomatically
48
+ self.automaticAppAccountToken = automaticAppAccountToken
49
+ }
50
+ }
51
+ }
52
+
53
+ /// Fingerprints of `(project key, subject, transaction id)` the backend
54
+ /// accepted, persisted in `UserDefaults`. Hashed so the store holds no user
55
+ /// ids; bounded so it cannot grow without limit (the oldest entries go first,
56
+ /// which at worst re-posts an old transaction once — the backend is
57
+ /// idempotent on it).
58
+ internal final class SyncedTransactionLedger: @unchecked Sendable {
59
+
60
+ static let defaultsKey = "com.swissknife.purchases.syncedTransactions.v1"
61
+ static let capacity = 512
62
+
63
+ private let defaults: UserDefaults
64
+ private let lock = NSLock()
65
+ private var loaded: [String]?
66
+
67
+ init(defaults: UserDefaults = .standard) {
68
+ self.defaults = defaults
69
+ }
70
+
71
+ static func fingerprint(apiKey: String, subject: String, transactionId: String) -> String {
72
+ let digest = SHA256.hash(data: Data("\(apiKey)\n\(subject)\n\(transactionId)".utf8))
73
+ return digest.prefix(16).map { String(format: "%02x", $0) }.joined()
74
+ }
75
+
76
+ func contains(_ fingerprint: String) -> Bool {
77
+ lock.lock(); defer { lock.unlock() }
78
+ return entriesLocked().contains(fingerprint)
79
+ }
80
+
81
+ func insert(_ fingerprint: String) {
82
+ lock.lock(); defer { lock.unlock() }
83
+ var entries = entriesLocked()
84
+ guard !entries.contains(fingerprint) else { return }
85
+ entries.append(fingerprint)
86
+ if entries.count > Self.capacity {
87
+ entries.removeFirst(entries.count - Self.capacity)
88
+ }
89
+ loaded = entries
90
+ defaults.set(entries, forKey: Self.defaultsKey)
91
+ }
92
+
93
+ var count: Int {
94
+ lock.lock(); defer { lock.unlock() }
95
+ return entriesLocked().count
96
+ }
97
+
98
+ private func entriesLocked() -> [String] {
99
+ if let loaded { return loaded }
100
+ let stored = defaults.stringArray(forKey: Self.defaultsKey) ?? []
101
+ loaded = stored
102
+ return stored
103
+ }
104
+ }
@@ -0,0 +1,137 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Services/IntroEligibility.swift
2
+ //
3
+ // Whether the current Apple ID can still get a subscription's introductory
4
+ // offer (free trial or paid intro), straight from StoreKit 2
5
+ // (`Product.SubscriptionInfo.isEligibleForIntroOffer`). Apple decides
6
+ // eligibility per subscription group: once someone has had an intro offer for
7
+ // any product of a group, every product of that group answers "ineligible".
8
+ //
9
+ // Read-only: it asks StoreKit, never the backend, never shows UI, and works
10
+ // without `configure(...)`.
11
+
12
+ import Foundation
13
+ import StoreKit
14
+
15
+ /// Mirrors RevenueCat's `IntroEligibilityStatus`.
16
+ public enum IntroEligibilityStatus: String, Sendable, Codable, Equatable {
17
+ /// The product has an introductory offer and this Apple ID can get it.
18
+ case eligible
19
+ /// The product has an introductory offer, but this Apple ID already had
20
+ /// one in the product's subscription group.
21
+ case ineligible
22
+ /// The product is not a subscription or has no introductory offer.
23
+ case noIntroOfferExists = "no_intro_offer_exists"
24
+ /// StoreKit could not say: the product id is unknown to the App Store,
25
+ /// or the product request failed.
26
+ case unknown
27
+ }
28
+
29
+ extension SwissKnife {
30
+
31
+ /// Introductory-offer eligibility for each of `productIdentifiers`.
32
+ /// Every requested id gets an answer (`.unknown` when StoreKit does not
33
+ /// know it or cannot be reached).
34
+ public static func checkTrialOrIntroDiscountEligibility(
35
+ productIdentifiers: [String]
36
+ ) async -> [String: IntroEligibilityStatus] {
37
+ if #available(iOS 15.0, macOS 12.0, *) {
38
+ return await IntroEligibility.check(productIdentifiers: productIdentifiers)
39
+ }
40
+ return Dictionary(uniqueKeysWithValues: Set(productIdentifiers).map { ($0, .unknown) })
41
+ }
42
+
43
+ /// Introductory-offer eligibility for a whole subscription group
44
+ /// (`Product.SubscriptionInfo.subscriptionGroupID`). Answers
45
+ /// `.eligible` / `.ineligible` only: StoreKit's group check does not say
46
+ /// whether the group has an intro offer at all, so ask per product for
47
+ /// `.noIntroOfferExists`.
48
+ public static func checkTrialOrIntroDiscountEligibility(
49
+ subscriptionGroupIdentifier: String
50
+ ) async -> IntroEligibilityStatus {
51
+ if #available(iOS 15.0, macOS 12.0, *) {
52
+ return await IntroEligibility.groupEligibility(subscriptionGroupIdentifier)
53
+ ? .eligible : .ineligible
54
+ }
55
+ return .unknown
56
+ }
57
+ }
58
+
59
+ /// What the eligibility answer needs to know about one product. Built from a
60
+ /// StoreKit `Product` in production, directly in tests.
61
+ internal struct IntroOfferProbe: Sendable {
62
+ var isSubscription: Bool
63
+ var hasIntroOffer: Bool
64
+ var subscriptionGroupId: String?
65
+ }
66
+
67
+ internal enum IntroEligibility {
68
+
69
+ /// The answer for one product, given its probe and (for a subscription
70
+ /// with an intro offer) StoreKit's group verdict.
71
+ static func status(
72
+ probe: IntroOfferProbe?,
73
+ groupEligible: Bool?
74
+ ) -> IntroEligibilityStatus {
75
+ guard let probe else { return .unknown }
76
+ guard probe.isSubscription, probe.hasIntroOffer else { return .noIntroOfferExists }
77
+ guard let groupEligible else { return .unknown }
78
+ return groupEligible ? .eligible : .ineligible
79
+ }
80
+
81
+ /// Product lookup seam (tests replace it; production asks StoreKit).
82
+ /// Returns nil when the request itself failed.
83
+ static var loadProbes: @Sendable ([String]) async -> [String: IntroOfferProbe]? =
84
+ defaultLoadProbes
85
+
86
+ /// Group verdict seam.
87
+ static var groupEligibility: @Sendable (String) async -> Bool =
88
+ defaultGroupEligibility
89
+
90
+ static let defaultLoadProbes: @Sendable ([String]) async -> [String: IntroOfferProbe]? = { ids in
91
+ guard #available(iOS 15.0, macOS 12.0, *) else { return nil }
92
+ guard let products = try? await Product.products(for: Set(ids)) else { return nil }
93
+ var probes: [String: IntroOfferProbe] = [:]
94
+ for product in products {
95
+ probes[product.id] = IntroOfferProbe(
96
+ isSubscription: product.subscription != nil,
97
+ hasIntroOffer: product.subscription?.introductoryOffer != nil,
98
+ subscriptionGroupId: product.subscription?.subscriptionGroupID
99
+ )
100
+ }
101
+ return probes
102
+ }
103
+
104
+ static let defaultGroupEligibility: @Sendable (String) async -> Bool = { groupId in
105
+ guard #available(iOS 15.0, macOS 12.0, *) else { return false }
106
+ return await Product.SubscriptionInfo.isEligibleForIntroOffer(for: groupId)
107
+ }
108
+
109
+ static func check(productIdentifiers: [String]) async -> [String: IntroEligibilityStatus] {
110
+ let ids = Array(Set(productIdentifiers))
111
+ guard !ids.isEmpty else { return [:] }
112
+ guard let probes = await loadProbes(ids) else {
113
+ return Dictionary(uniqueKeysWithValues: ids.map { ($0, .unknown) })
114
+ }
115
+ // One StoreKit question per subscription group, however many of its
116
+ // products were asked about.
117
+ var groupVerdicts: [String: Bool] = [:]
118
+ for probe in probes.values where probe.isSubscription && probe.hasIntroOffer {
119
+ guard let group = probe.subscriptionGroupId, groupVerdicts[group] == nil else { continue }
120
+ groupVerdicts[group] = await groupEligibility(group)
121
+ }
122
+ var result: [String: IntroEligibilityStatus] = [:]
123
+ for id in ids {
124
+ let probe = probes[id]
125
+ result[id] = status(
126
+ probe: probe,
127
+ groupEligible: probe?.subscriptionGroupId.flatMap { groupVerdicts[$0] }
128
+ )
129
+ }
130
+ return result
131
+ }
132
+
133
+ static func _resetForTesting() {
134
+ loadProbes = defaultLoadProbes
135
+ groupEligibility = defaultGroupEligibility
136
+ }
137
+ }