@app-swiss-knife/react-native-sdk 0.5.0 → 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 (50) hide show
  1. package/CHANGELOG.md +165 -2
  2. package/README.md +75 -19
  3. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +17 -4
  4. package/android/vendor/GENERATED.md +1 -0
  5. package/android/vendor/java/com/appswissknife/SwissKnife.kt +4 -0
  6. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  7. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  8. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +47 -2
  9. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +185 -33
  10. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +8 -0
  11. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +10 -0
  12. package/app.plugin.js +61 -5
  13. package/ios/SwissKnifeJSON.swift +24 -2
  14. package/ios/SwissKnifePurchases.swift +9 -1
  15. package/ios/vendor/GENERATED.md +1 -0
  16. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  17. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +7 -0
  18. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +2 -3
  19. package/ios/vendor/SwissKnifeiOS/Services/EntitlementSync.swift +104 -0
  20. package/ios/vendor/SwissKnifeiOS/Services/IntroEligibility.swift +137 -0
  21. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +37 -5
  22. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +368 -52
  23. package/ios/vendor/SwissKnifeiOS/Services/TransactionEvents.swift +371 -0
  24. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +73 -8
  25. package/ios/vendor/SwissKnifeiOS/Types.swift +31 -1
  26. package/ios-notification-service/SwissKnifeNotificationService.podspec +37 -0
  27. package/ios-notification-service/vendor/GENERATED.md +11 -0
  28. package/ios-notification-service/vendor/SwissKnifeNotificationService/SwissKnifeNotificationServiceExtension.swift +177 -0
  29. package/lib/commonjs/internal/config.js +3 -0
  30. package/lib/commonjs/internal/config.js.map +1 -1
  31. package/lib/commonjs/native/spec.js.map +1 -1
  32. package/lib/commonjs/types.js.map +1 -1
  33. package/lib/module/internal/config.js +3 -0
  34. package/lib/module/internal/config.js.map +1 -1
  35. package/lib/module/native/spec.js.map +1 -1
  36. package/lib/module/types.js.map +1 -1
  37. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  38. package/lib/typescript/commonjs/native/spec.d.ts +2 -0
  39. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  40. package/lib/typescript/commonjs/types.d.ts +13 -0
  41. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  42. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  43. package/lib/typescript/module/native/spec.d.ts +2 -0
  44. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  45. package/lib/typescript/module/types.d.ts +13 -0
  46. package/lib/typescript/module/types.d.ts.map +1 -1
  47. package/package.json +3 -2
  48. package/src/internal/config.ts +3 -0
  49. package/src/native/spec.ts +4 -0
  50. package/src/types.ts +13 -0
@@ -0,0 +1,371 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Services/TransactionEvents.swift
2
+ //
3
+ // A public way to observe the transactions the purchase engine handles:
4
+ // purchases, renewals, restores, silent syncs and revocations, each delivered
5
+ // once the backend has answered for it (or with `serverConfirmed == false`
6
+ // when it could not be reached or refused it, or, for a sync, kept it with
7
+ // another user: `ownedByAnotherUser`).
8
+ //
9
+ // Where events come from (all inside `PurchaseService`):
10
+ // - `purchase(...)` → `.purchase`
11
+ // - the `Transaction.updates` task → `.purchase` (another device, an
12
+ // approved Ask to Buy), `.renewal`,
13
+ // `.revocation` (refund / revoke)
14
+ // - `restorePurchases()` → `.restore`
15
+ // - `syncCurrentEntitlements()` and the automatic sync → `.sync`
16
+ //
17
+ // Delivery never blocks StoreKit: the SDK finishes (or deliberately leaves
18
+ // unfinished) the transaction exactly as before, then hands the event to a
19
+ // serial background queue. Observers run there; hop to the main actor for UI.
20
+ //
21
+ // Only the purchase engine emits. An app that owns StoreKit itself
22
+ // (`configureCore(...)` only) gets no events and no behaviour change: the SDK
23
+ // never observes or finishes its transactions.
24
+
25
+ import Foundation
26
+ import StoreKit
27
+
28
+ extension SwissKnife {
29
+
30
+ /// One transaction the SDK handled, after the backend answered for it.
31
+ public struct TransactionEvent: Sendable, Equatable {
32
+
33
+ /// Why the SDK saw the transaction.
34
+ public enum Kind: String, Sendable, Codable {
35
+ /// `purchasePackage` / `purchaseStoreProduct`, or a purchase that
36
+ /// arrived through `Transaction.updates` (made on another device,
37
+ /// an approved Ask to Buy, a purchase from the App Store page).
38
+ case purchase
39
+ /// An auto-renewal delivered through `Transaction.updates`.
40
+ case renewal
41
+ /// `restorePurchases()`.
42
+ case restore
43
+ /// `syncCurrentEntitlements()` or the automatic sync after
44
+ /// configure / logIn.
45
+ case sync
46
+ /// A refund or revocation (`revocationDate` is set).
47
+ case revocation
48
+ }
49
+
50
+ /// The offer the transaction was bought with.
51
+ public enum OfferType: String, Sendable, Codable {
52
+ case none
53
+ /// An introductory offer with a free trial.
54
+ case trial
55
+ /// An introductory offer that is paid (pay as you go / up front).
56
+ case introductory
57
+ case promotional
58
+ case offerCode = "offer_code"
59
+ case winBack = "win_back"
60
+ }
61
+
62
+ /// The App Store environment that signed the transaction.
63
+ public enum Environment: String, Sendable, Codable {
64
+ case production
65
+ case sandbox
66
+ /// StoreKit Testing in Xcode (or `SKTestSession`).
67
+ case xcode
68
+ case unknown
69
+ }
70
+
71
+ public let kind: Kind
72
+ public let productIdentifier: String
73
+ public let transactionIdentifier: String
74
+ public let originalTransactionIdentifier: String
75
+ public let purchaseDate: Date
76
+ /// Subscription expiry, when the transaction has one.
77
+ public let expirationDate: Date?
78
+ /// Set for a refunded / revoked transaction.
79
+ public let revocationDate: Date?
80
+ /// What the customer paid, in `currencyCode`. Nil when StoreKit does
81
+ /// not report it (older OS versions for some transactions).
82
+ public let price: Decimal?
83
+ /// ISO 4217 code of `price`.
84
+ public let currencyCode: String?
85
+ public let offerType: OfferType
86
+ public let environment: Environment
87
+ /// The `appAccountToken` the purchase carries, if any.
88
+ public let appAccountToken: UUID?
89
+ public let quantity: Int
90
+ /// True when the Swiss Knife backend accepted the transaction for
91
+ /// the current user. False when it could not be reached or refused
92
+ /// it: the SDK retries (an unfinished transaction is redelivered by
93
+ /// StoreKit; a sync posts it again), so a later event for the same
94
+ /// `transactionIdentifier` can follow with `true`. De-duplicate on
95
+ /// `transactionIdentifier`. Also false when `ownedByAnotherUser`.
96
+ public let serverConfirmed: Bool
97
+ /// `.sync` only: the backend holds this purchase for another user of
98
+ /// the app (bought or restored under another account on this Apple
99
+ /// ID) and the sync left it there: a sync never moves a purchase
100
+ /// between users. `restorePurchases()` moves it when the app's
101
+ /// transfer setting allows. Each later sync reports it again.
102
+ public let ownedByAnotherUser: Bool
103
+
104
+ public init(
105
+ kind: Kind,
106
+ productIdentifier: String,
107
+ transactionIdentifier: String,
108
+ originalTransactionIdentifier: String,
109
+ purchaseDate: Date,
110
+ expirationDate: Date?,
111
+ revocationDate: Date?,
112
+ price: Decimal?,
113
+ currencyCode: String?,
114
+ offerType: OfferType,
115
+ environment: Environment,
116
+ appAccountToken: UUID?,
117
+ quantity: Int,
118
+ serverConfirmed: Bool,
119
+ ownedByAnotherUser: Bool = false
120
+ ) {
121
+ self.kind = kind
122
+ self.productIdentifier = productIdentifier
123
+ self.transactionIdentifier = transactionIdentifier
124
+ self.originalTransactionIdentifier = originalTransactionIdentifier
125
+ self.purchaseDate = purchaseDate
126
+ self.expirationDate = expirationDate
127
+ self.revocationDate = revocationDate
128
+ self.price = price
129
+ self.currencyCode = currencyCode
130
+ self.offerType = offerType
131
+ self.environment = environment
132
+ self.appAccountToken = appAccountToken
133
+ self.quantity = quantity
134
+ self.serverConfirmed = serverConfirmed
135
+ self.ownedByAnotherUser = ownedByAnotherUser
136
+ }
137
+ }
138
+
139
+ /// Observe every transaction event. `block` runs on a background queue,
140
+ /// in order. Returns a token for `removeTransactionObserver(_:)`.
141
+ @discardableResult
142
+ public static func addTransactionObserver(
143
+ _ block: @escaping @Sendable (TransactionEvent) -> Void
144
+ ) -> UUID {
145
+ TransactionEventHub.shared.addObserver(block)
146
+ }
147
+
148
+ public static func removeTransactionObserver(_ token: UUID) {
149
+ TransactionEventHub.shared.removeObserver(token)
150
+ }
151
+
152
+ /// Transaction events as an `AsyncStream`. Each access is a new
153
+ /// subscriber; it ends when the consuming task is cancelled.
154
+ public static var transactionEvents: AsyncStream<TransactionEvent> {
155
+ TransactionEventHub.shared.stream
156
+ }
157
+ }
158
+
159
+ // MARK: - What the SDK reads off a StoreKit transaction
160
+
161
+ /// The fields of a verified transaction the SDK posts and reports. Built from
162
+ /// a `StoreKit.Transaction` in production and directly in tests (StoreKit
163
+ /// transactions cannot be constructed outside a StoreKit session).
164
+ internal struct TransactionFacts: Sendable, Equatable {
165
+ var transactionId: String
166
+ var originalTransactionId: String
167
+ var productId: String
168
+ var purchaseDate: Date
169
+ var expirationDate: Date? = nil
170
+ var revocationDate: Date? = nil
171
+ var price: Decimal? = nil
172
+ var currencyCode: String? = nil
173
+ var offerType: SwissKnife.TransactionEvent.OfferType = .none
174
+ var environment: SwissKnife.TransactionEvent.Environment = .unknown
175
+ var appAccountToken: UUID? = nil
176
+ var quantity: Int = 1
177
+ /// `Transaction.reason == .renewal`.
178
+ var isRenewal: Bool = false
179
+
180
+ /// The kind a `Transaction.updates` delivery reports.
181
+ var updateKind: SwissKnife.TransactionEvent.Kind {
182
+ if revocationDate != nil { return .revocation }
183
+ return isRenewal ? .renewal : .purchase
184
+ }
185
+
186
+ func event(
187
+ kind: SwissKnife.TransactionEvent.Kind,
188
+ serverConfirmed: Bool,
189
+ ownedByAnotherUser: Bool = false
190
+ ) -> SwissKnife.TransactionEvent {
191
+ SwissKnife.TransactionEvent(
192
+ kind: kind,
193
+ productIdentifier: productId,
194
+ transactionIdentifier: transactionId,
195
+ originalTransactionIdentifier: originalTransactionId,
196
+ purchaseDate: purchaseDate,
197
+ expirationDate: expirationDate,
198
+ revocationDate: revocationDate,
199
+ price: price,
200
+ currencyCode: currencyCode,
201
+ offerType: offerType,
202
+ environment: environment,
203
+ appAccountToken: appAccountToken,
204
+ quantity: quantity,
205
+ serverConfirmed: serverConfirmed,
206
+ ownedByAnotherUser: ownedByAnotherUser
207
+ )
208
+ }
209
+
210
+ /// Offer type from the signed payload's `offerType` (1 introductory,
211
+ /// 2 promotional, 3 offer code, 4 win-back) and `offerDiscountType`
212
+ /// (`FREE_TRIAL`, `PAY_AS_YOU_GO`, `PAY_UP_FRONT`). An introductory offer
213
+ /// whose payment mode is unknown counts as a trial when nothing was paid.
214
+ static func offerType(
215
+ rawType: Int?,
216
+ isFreeTrial: Bool?,
217
+ price: Decimal?
218
+ ) -> SwissKnife.TransactionEvent.OfferType {
219
+ switch rawType {
220
+ case 1:
221
+ if let isFreeTrial { return isFreeTrial ? .trial : .introductory }
222
+ if let price, price == 0 { return .trial }
223
+ return .introductory
224
+ case 2: return .promotional
225
+ case 3: return .offerCode
226
+ case 4: return .winBack
227
+ default: return .none
228
+ }
229
+ }
230
+
231
+ static func environment(_ raw: String?) -> SwissKnife.TransactionEvent.Environment {
232
+ switch raw?.lowercased() {
233
+ case "production": return .production
234
+ case "sandbox": return .sandbox
235
+ case "xcode", "localtesting": return .xcode
236
+ default: return .unknown
237
+ }
238
+ }
239
+ }
240
+
241
+ @available(iOS 15.0, macOS 12.0, *)
242
+ extension TransactionFacts {
243
+
244
+ /// Typed StoreKit APIs where the OS has them, the signed payload
245
+ /// (`jsonRepresentation`, the same JSON Apple signs) below that, so the
246
+ /// floor stays iOS 15 without calling deprecated accessors.
247
+ init(_ transaction: StoreKit.Transaction) {
248
+ let json = (try? JSONSerialization.jsonObject(with: transaction.jsonRepresentation))
249
+ as? [String: Any] ?? [:]
250
+
251
+ var price: Decimal? = nil
252
+ if #available(iOS 15.4, macOS 12.3, *) {
253
+ price = transaction.price
254
+ } else if let milli = json["price"] as? NSNumber {
255
+ price = milli.decimalValue / 1000
256
+ }
257
+
258
+ let currency: String?
259
+ if #available(iOS 16.0, macOS 13.0, *) {
260
+ currency = transaction.currency?.identifier
261
+ } else {
262
+ currency = json["currency"] as? String
263
+ }
264
+
265
+ let environment: String?
266
+ if #available(iOS 16.0, macOS 13.0, *) {
267
+ environment = transaction.environment.rawValue
268
+ } else {
269
+ environment = json["environment"] as? String
270
+ }
271
+
272
+ let rawOfferType: Int?
273
+ let isFreeTrial: Bool?
274
+ if #available(iOS 17.2, macOS 14.2, *) {
275
+ rawOfferType = transaction.offer?.type.rawValue
276
+ isFreeTrial = transaction.offer?.paymentMode.map { $0 == .freeTrial }
277
+ } else {
278
+ rawOfferType = (json["offerType"] as? NSNumber)?.intValue
279
+ isFreeTrial = (json["offerDiscountType"] as? String).map { $0 == "FREE_TRIAL" }
280
+ }
281
+
282
+ let isRenewal: Bool
283
+ if #available(iOS 17.0, macOS 14.0, *) {
284
+ isRenewal = transaction.reason == .renewal
285
+ } else {
286
+ isRenewal = (json["transactionReason"] as? String) == "RENEWAL"
287
+ }
288
+
289
+ self.init(
290
+ transactionId: String(transaction.id),
291
+ originalTransactionId: String(transaction.originalID),
292
+ productId: transaction.productID,
293
+ purchaseDate: transaction.purchaseDate,
294
+ expirationDate: transaction.expirationDate,
295
+ revocationDate: transaction.revocationDate,
296
+ price: price,
297
+ currencyCode: currency,
298
+ offerType: TransactionFacts.offerType(
299
+ rawType: rawOfferType,
300
+ isFreeTrial: isFreeTrial,
301
+ price: price
302
+ ),
303
+ environment: TransactionFacts.environment(environment),
304
+ appAccountToken: transaction.appAccountToken,
305
+ quantity: transaction.purchasedQuantity,
306
+ isRenewal: isRenewal
307
+ )
308
+ }
309
+ }
310
+
311
+ // MARK: - Fan-out
312
+
313
+ /// Delivers transaction events to observers and stream subscribers on one
314
+ /// serial background queue, so a slow observer never holds up StoreKit.
315
+ internal final class TransactionEventHub: @unchecked Sendable {
316
+
317
+ static let shared = TransactionEventHub()
318
+
319
+ private let lock = NSLock()
320
+ private let deliveryQueue = DispatchQueue(label: "com.swissknife.transaction-events")
321
+ private var observers: [UUID: @Sendable (SwissKnife.TransactionEvent) -> Void] = [:]
322
+ private var continuations: [UUID: AsyncStream<SwissKnife.TransactionEvent>.Continuation] = [:]
323
+
324
+ func addObserver(_ block: @escaping @Sendable (SwissKnife.TransactionEvent) -> Void) -> UUID {
325
+ let token = UUID()
326
+ lock.lock(); observers[token] = block; lock.unlock()
327
+ return token
328
+ }
329
+
330
+ func removeObserver(_ token: UUID) {
331
+ lock.lock(); observers[token] = nil; lock.unlock()
332
+ }
333
+
334
+ var stream: AsyncStream<SwissKnife.TransactionEvent> {
335
+ AsyncStream { continuation in
336
+ let id = UUID()
337
+ self.lock.lock(); self.continuations[id] = continuation; self.lock.unlock()
338
+ continuation.onTermination = { [weak self] _ in
339
+ guard let self else { return }
340
+ self.lock.lock(); self.continuations[id] = nil; self.lock.unlock()
341
+ }
342
+ }
343
+ }
344
+
345
+ /// Queue `event` for delivery and return at once.
346
+ func emit(_ event: SwissKnife.TransactionEvent) {
347
+ deliveryQueue.async { [self] in
348
+ lock.lock()
349
+ let blocks = Array(observers.values)
350
+ let streams = Array(continuations.values)
351
+ lock.unlock()
352
+ for block in blocks { block(event) }
353
+ for stream in streams { stream.yield(event) }
354
+ }
355
+ }
356
+
357
+ /// Test seam: wait until every event emitted so far has been delivered.
358
+ internal func _drainForTesting() {
359
+ deliveryQueue.sync {}
360
+ }
361
+
362
+ internal func _resetForTesting() {
363
+ deliveryQueue.sync {}
364
+ lock.lock()
365
+ observers.removeAll()
366
+ let streams = Array(continuations.values)
367
+ continuations.removeAll()
368
+ lock.unlock()
369
+ for stream in streams { stream.finish() }
370
+ }
371
+ }
@@ -78,13 +78,17 @@ public final class SwissKnife: NSObject {
78
78
  /// - The attributes client (Phase 3) is wired the same way.
79
79
  /// - `appUserID` is set to the provided id when supplied, else the
80
80
  /// anonymous Keychain-backed device id.
81
+ /// - `purchases` sets the purchase engine's automatic entitlement sync
82
+ /// and automatic `appAccountToken` (both on by default; see
83
+ /// `PurchasesConfiguration`).
81
84
  public static func configure(
82
85
  apiKey: String,
83
86
  appUserID: String? = nil,
84
87
  proxyURL: String? = nil,
85
88
  storeKitVersion: String = "DEFAULT",
86
89
  logLevel: String? = nil,
87
- attribution: SwissKnife.Attribution.Configuration = .init()
90
+ attribution: SwissKnife.Attribution.Configuration = .init(),
91
+ purchases: SwissKnife.PurchasesConfiguration = .init()
88
92
  ) {
89
93
  if rejectsBlankApiKey(apiKey, entryPoint: "configure") { return }
90
94
  os_log(
@@ -105,7 +109,8 @@ public final class SwissKnife: NSObject {
105
109
  apiKey: apiKey,
106
110
  appUserID: appUserID,
107
111
  proxyURL: proxyURL,
108
- storeKitVersion: storeKitVersion
112
+ storeKitVersion: storeKitVersion,
113
+ purchases: purchases
109
114
  )
110
115
  }
111
116
 
@@ -208,7 +213,8 @@ public final class SwissKnife: NSObject {
208
213
  apiKey: String,
209
214
  appUserID: String? = nil,
210
215
  proxyURL: String? = nil,
211
- storeKitVersion: String = "DEFAULT"
216
+ storeKitVersion: String = "DEFAULT",
217
+ purchases: SwissKnife.PurchasesConfiguration = .init()
212
218
  ) {
213
219
  if rejectsBlankApiKey(apiKey, entryPoint: "configurePurchases") { return }
214
220
  os_log(
@@ -239,7 +245,7 @@ public final class SwissKnife: NSObject {
239
245
  apiKey: apiKey,
240
246
  userId: resolvedAppUserID
241
247
  )
242
- PurchaseService.shared.configure(serverURL: proxyURL, apiKey: apiKey)
248
+ PurchaseService.shared.configure(serverURL: proxyURL, apiKey: apiKey, settings: purchases)
243
249
  OfferingsService.shared.configure(serverURL: proxyURL, apiKey: apiKey)
244
250
 
245
251
  // `storeKitVersion` is preserved on the public API for source
@@ -252,6 +258,11 @@ public final class SwissKnife: NSObject {
252
258
  // Wave 2 — first launch auto-registers the install (and optionally
253
259
  // shows the ATT prompt). Fire-and-forget; never blocks configure.
254
260
  SwissKnife.Attribution._sendInstallOnFirstLaunchIfEnabled()
261
+
262
+ // Post the device's entitlements the backend has not seen (debounced,
263
+ // no UI, nothing sent when nothing is new). Off with
264
+ // `PurchasesConfiguration(syncEntitlementsAutomatically: false)`.
265
+ PurchaseService.shared.scheduleAutomaticSync(trigger: .configure)
255
266
  }
256
267
 
257
268
  /// True (after logging an error) when `apiKey` is empty or whitespace.
@@ -442,6 +453,16 @@ public final class SwissKnife: NSObject {
442
453
  shared.stateQueue.sync { shared.currentIsAnonymous }
443
454
  }
444
455
 
456
+ /// The `appAccountToken` a purchase gets by default: the current app
457
+ /// user id when the user is identified and the id is a UUID, else nil.
458
+ internal static func defaultAppAccountToken() -> UUID? {
459
+ let (userId, isAnonymous) = shared.stateQueue.sync {
460
+ (shared.currentAppUserID, shared.currentIsAnonymous)
461
+ }
462
+ guard !isAnonymous, let userId else { return nil }
463
+ return UUID(uuidString: userId)
464
+ }
465
+
445
466
  /// The **subject identifier** the backend keys rows against — the value
446
467
  /// that goes into `user_id` on `POST /api/sdk/subscriptions/validate` and
447
468
  /// `GET /api/sdk/entitlements/list`. Server-side it lands in
@@ -517,22 +538,45 @@ public final class SwissKnife: NSObject {
517
538
 
518
539
  // MARK: Purchasing (typed, async)
519
540
 
520
- public static func purchasePackage(_ package: Package) async throws -> PurchaseResult {
541
+ /// Purchase a package.
542
+ ///
543
+ /// `appAccountToken` is attached to the StoreKit purchase (Apple repeats
544
+ /// it in every transaction and server notification of the purchase).
545
+ /// When nil, the current app user id is used if it is a UUID, unless
546
+ /// `PurchasesConfiguration.automaticAppAccountToken` is off.
547
+ public static func purchasePackage(
548
+ _ package: Package,
549
+ appAccountToken: UUID? = nil
550
+ ) async throws -> PurchaseResult {
521
551
  guard isConfigured else { throw PurchasesError.notConfigured }
522
552
  if #available(iOS 15.0, macOS 12.0, *) {
523
- return try await PurchaseService.shared.purchase(package: package)
553
+ return try await PurchaseService.shared.purchase(
554
+ package: package,
555
+ appAccountToken: appAccountToken
556
+ )
524
557
  }
525
558
  throw PurchasesError.unknown(message: "StoreKit 2 purchases require iOS 15+ / macOS 12+")
526
559
  }
527
560
 
528
- public static func purchaseStoreProduct(_ product: StoreProduct) async throws -> PurchaseResult {
561
+ /// Purchase a product directly. `appAccountToken` as in
562
+ /// `purchasePackage(_:appAccountToken:)`.
563
+ public static func purchaseStoreProduct(
564
+ _ product: StoreProduct,
565
+ appAccountToken: UUID? = nil
566
+ ) async throws -> PurchaseResult {
529
567
  guard isConfigured else { throw PurchasesError.notConfigured }
530
568
  if #available(iOS 15.0, macOS 12.0, *) {
531
- return try await PurchaseService.shared.purchase(productIdentifier: product.productIdentifier)
569
+ return try await PurchaseService.shared.purchase(
570
+ productIdentifier: product.productIdentifier,
571
+ appAccountToken: appAccountToken
572
+ )
532
573
  }
533
574
  throw PurchasesError.unknown(message: "StoreKit 2 purchases require iOS 15+ / macOS 12+")
534
575
  }
535
576
 
577
+ /// Restore purchases for a Restore button: asks the App Store to sync
578
+ /// this Apple ID first (it may show the Apple ID sheet), then posts every
579
+ /// current entitlement.
536
580
  public static func restorePurchases() async throws -> CustomerInfo {
537
581
  guard isConfigured else { throw PurchasesError.notConfigured }
538
582
  if #available(iOS 15.0, macOS 12.0, *) {
@@ -541,6 +585,23 @@ public final class SwissKnife: NSObject {
541
585
  throw PurchasesError.unknown(message: "Restore via StoreKit 2 requires iOS 15+ / macOS 12+")
542
586
  }
543
587
 
588
+ /// Silently sync the device's current entitlements: posts the ones the
589
+ /// backend has not accepted for the current user and returns
590
+ /// `CustomerInfo`. Never calls `AppStore.sync()`, so no Apple ID sheet;
591
+ /// with nothing new it sends nothing. Never moves a purchase the backend
592
+ /// holds for another user, whatever the app's transfer setting: it is
593
+ /// reported as a `.sync` `TransactionEvent` with `ownedByAnotherUser`
594
+ /// (`restorePurchases()` applies the transfer setting). Runs by itself
595
+ /// after configure and logIn unless
596
+ /// `PurchasesConfiguration.syncEntitlementsAutomatically` is off.
597
+ public static func syncCurrentEntitlements() async throws -> CustomerInfo {
598
+ guard isConfigured else { throw PurchasesError.notConfigured }
599
+ if #available(iOS 15.0, macOS 12.0, *) {
600
+ return try await PurchaseService.shared.syncCurrentEntitlements()
601
+ }
602
+ throw PurchasesError.unknown(message: "StoreKit 2 sync requires iOS 15+ / macOS 12+")
603
+ }
604
+
544
605
  // MARK: Identity (facades — production code lives in SwissKnife.Identity)
545
606
 
546
607
  /// Identify the user. Posts the (anonymous_id, user_id) pair to our
@@ -591,6 +652,10 @@ public final class SwissKnife: NSObject {
591
652
  shared.currentIsAnonymous = false
592
653
  }
593
654
  Notifications.identityChanged()
655
+ // Attach this device's entitlements to the user who just signed in
656
+ // (a no-op unless the purchase engine is configured with the
657
+ // automatic sync on).
658
+ PurchaseService.shared.scheduleAutomaticSync(trigger: .logIn)
594
659
  }
595
660
 
596
661
  /// Update legacy state after a transition to the anonymous identity.
@@ -158,6 +158,28 @@ public struct StoreProductDiscount: Sendable, Codable, Equatable {
158
158
  }
159
159
  }
160
160
 
161
+ // MARK: - StoreProductType
162
+
163
+ /// What kind of in-app product a `StoreProduct` is: StoreKit 2's
164
+ /// `Product.ProductType`, without importing StoreKit. Raw values are the
165
+ /// backend's product-type vocabulary (`auto_renewable`, `non_renewing`,
166
+ /// `consumable`, `non_consumable`).
167
+ public enum StoreProductType: String, Sendable, Codable, CaseIterable {
168
+ case autoRenewableSubscription = "auto_renewable"
169
+ case nonRenewableSubscription = "non_renewing"
170
+ case consumable
171
+ case nonConsumable = "non_consumable"
172
+ /// Not known: a StoreKit type this SDK does not recognise, or a one-time
173
+ /// product described only by the backend, which does not say whether it
174
+ /// is consumable.
175
+ case unknown
176
+
177
+ /// True only for an auto-renewable subscription (RevenueCat's
178
+ /// `ProductCategory.subscription`). A non-renewing subscription is a
179
+ /// one-time purchase with no billing period, as consumables are.
180
+ public var isSubscription: Bool { self == .autoRenewableSubscription }
181
+ }
182
+
161
183
  // MARK: - StoreProduct
162
184
 
163
185
  /// A single product as returned by the App Store. We populate this directly
@@ -173,9 +195,14 @@ public struct StoreProduct: Sendable, Equatable {
173
195
  /// Pre-formatted display price (e.g. `"$9.99"`) — passes through StoreKit's
174
196
  /// localized formatter so we don't re-derive the locale ourselves.
175
197
  public let displayPrice: String
198
+ /// The SDK sets this only for an auto-renewable subscription.
176
199
  public let subscriptionPeriod: SubscriptionPeriod?
200
+ /// The SDK sets this only for an auto-renewable subscription.
177
201
  public let introductoryDiscount: StoreProductDiscount?
178
202
  public let discounts: [StoreProductDiscount]
203
+ /// StoreKit's product type (`Product.type`), or what the backend says for
204
+ /// a product StoreKit did not return.
205
+ public let productType: StoreProductType
179
206
 
180
207
  /// Number formatter pre-configured for this product's currency. Recreating
181
208
  /// it on demand is cheap; we surface it so consumers can format derived
@@ -196,7 +223,9 @@ public struct StoreProduct: Sendable, Equatable {
196
223
  displayPrice: String,
197
224
  subscriptionPeriod: SubscriptionPeriod?,
198
225
  introductoryDiscount: StoreProductDiscount?,
199
- discounts: [StoreProductDiscount]
226
+ discounts: [StoreProductDiscount],
227
+ // Defaulted so code that builds a StoreProduct by hand keeps compiling.
228
+ productType: StoreProductType = .unknown
200
229
  ) {
201
230
  self.productIdentifier = productIdentifier
202
231
  self.localizedTitle = localizedTitle
@@ -207,6 +236,7 @@ public struct StoreProduct: Sendable, Equatable {
207
236
  self.subscriptionPeriod = subscriptionPeriod
208
237
  self.introductoryDiscount = introductoryDiscount
209
238
  self.discounts = discounts
239
+ self.productType = productType
210
240
  }
211
241
  }
212
242
 
@@ -0,0 +1,37 @@
1
+ # packages/react-native-sdk/ios-notification-service/SwissKnifeNotificationService.podspec
2
+ #
3
+ # Notification Service Extension base class for swiss-push rich notifications,
4
+ # shipped in the npm package so a React Native app can add it from
5
+ # node_modules. In the app's Podfile, inside the extension's target:
6
+ #
7
+ # target 'YourNotificationService' do
8
+ # pod 'SwissKnifeNotificationService', :path => '../node_modules/@app-swiss-knife/react-native-sdk/ios-notification-service'
9
+ # end
10
+ #
11
+ # Foundation + UserNotifications only, so the extension stays under its memory
12
+ # cap. The sources under vendor/ are copied from
13
+ # packages/swiss-knife-ios/Sources/SwissKnifeNotificationService by
14
+ # scripts/vendor-native.mjs at build/prepack time (gitignored here).
15
+ #
16
+ # This podspec lives in its own folder on purpose. React Native and Expo
17
+ # autolinking link the FIRST *.podspec at the package root into the app target
18
+ # (Expo sorts them, and "SwissKnifeNotificationService" sorts before
19
+ # "SwissKnifePurchases"), so a second podspec at the root would replace the
20
+ # SDK's pod in every app. Keep exactly one podspec at the root. For the same
21
+ # reason, the folder is not under ios/, which SwissKnifePurchases.podspec
22
+ # compiles whole (`ios/**`): the app pod must not gain this extension class.
23
+ Pod::Spec.new do |s|
24
+ s.name = "SwissKnifeNotificationService"
25
+ s.version = "0.6.0"
26
+ s.summary = "Swiss Knife push: UNNotificationServiceExtension base class (image attachments, received tracking)."
27
+ s.homepage = "https://github.com/Remneys/swiss-knife"
28
+ s.license = "MIT"
29
+ s.authors = "App Swiss Knife"
30
+ s.platforms = { :ios => "15.0" }
31
+ s.source = { :git => "https://github.com/Remneys/swiss-knife.git", :tag => "#{s.version}" }
32
+ s.source_files = "vendor/SwissKnifeNotificationService/**/*.swift"
33
+ s.swift_version = "5.9"
34
+ s.frameworks = "UserNotifications"
35
+ # App extensions may only link extension-safe API.
36
+ s.pod_target_xcconfig = { "APPLICATION_EXTENSION_API_ONLY" => "YES" }
37
+ end
@@ -0,0 +1,11 @@
1
+ GENERATED — DO NOT EDIT.
2
+
3
+ Copied verbatim by packages/react-native-sdk/scripts/vendor-native.mjs from the
4
+ standalone native SDK sources in the monorepo. Edit those instead:
5
+
6
+ packages/swiss-knife-ios/Sources/SwissKnifeiOS/**
7
+ packages/swiss-knife-ios/Sources/SwissKnifeNotificationService/**
8
+ packages/swiss-knife-android/src/main/{java,res}/**
9
+
10
+ This directory is gitignored and regenerated on every `build` / `prepack`.
11
+ It ships inside the npm tarball so the package is self-contained.