@app-swiss-knife/react-native-sdk 0.1.0 → 0.2.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 (60) hide show
  1. package/README.md +51 -0
  2. package/android/build.gradle +7 -0
  3. package/android/consumer-rules.pro +64 -0
  4. package/android/src/main/java/com/swissknife/purchases/Conversions.kt +85 -0
  5. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +53 -33
  6. package/android/vendor/java/com/appswissknife/SwissKnife.kt +239 -44
  7. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +177 -25
  8. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  9. package/android/vendor/java/com/appswissknife/identity/Identity.kt +15 -0
  10. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  11. package/ios/SwissKnifePurchases.m +15 -0
  12. package/ios/SwissKnifePurchases.swift +69 -0
  13. package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +25 -7
  14. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  15. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +8 -2
  16. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +32 -1
  17. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +35 -5
  18. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +39 -22
  19. package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +12 -2
  20. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +359 -28
  21. package/lib/commonjs/identity.js +59 -4
  22. package/lib/commonjs/identity.js.map +1 -1
  23. package/lib/commonjs/modules/analytics.js +14 -10
  24. package/lib/commonjs/modules/analytics.js.map +1 -1
  25. package/lib/commonjs/native/spec.js.map +1 -1
  26. package/lib/commonjs/purchases.js +95 -3
  27. package/lib/commonjs/purchases.js.map +1 -1
  28. package/lib/commonjs/types.js.map +1 -1
  29. package/lib/module/identity.js +59 -4
  30. package/lib/module/identity.js.map +1 -1
  31. package/lib/module/modules/analytics.js +14 -10
  32. package/lib/module/modules/analytics.js.map +1 -1
  33. package/lib/module/native/spec.js.map +1 -1
  34. package/lib/module/purchases.js +95 -3
  35. package/lib/module/purchases.js.map +1 -1
  36. package/lib/module/types.js.map +1 -1
  37. package/lib/typescript/commonjs/identity.d.ts +30 -4
  38. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  39. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  40. package/lib/typescript/commonjs/native/spec.d.ts +42 -10
  41. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  42. package/lib/typescript/commonjs/purchases.d.ts +46 -1
  43. package/lib/typescript/commonjs/purchases.d.ts.map +1 -1
  44. package/lib/typescript/commonjs/types.d.ts +11 -2
  45. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  46. package/lib/typescript/module/identity.d.ts +30 -4
  47. package/lib/typescript/module/identity.d.ts.map +1 -1
  48. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  49. package/lib/typescript/module/native/spec.d.ts +42 -10
  50. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  51. package/lib/typescript/module/purchases.d.ts +46 -1
  52. package/lib/typescript/module/purchases.d.ts.map +1 -1
  53. package/lib/typescript/module/types.d.ts +11 -2
  54. package/lib/typescript/module/types.d.ts.map +1 -1
  55. package/package.json +1 -1
  56. package/src/identity.ts +63 -4
  57. package/src/modules/analytics.ts +16 -12
  58. package/src/native/spec.ts +46 -11
  59. package/src/purchases.ts +103 -4
  60. package/src/types.ts +11 -2
@@ -29,12 +29,25 @@ public final class SwissKnife: NSObject {
29
29
  // MARK: State managed entirely by SwissKnife now (no more Purchases.shared)
30
30
 
31
31
  private let stateQueue = DispatchQueue(label: "com.swissknife.state")
32
+ /// The PURCHASE engine is live (StoreKit observer running, offerings
33
+ /// service wired). Set only by `configurePurchases(...)`.
32
34
  private var configured: Bool = false
35
+ /// The CORE (ingest / identity / attribution / attributes) is live. Set by
36
+ /// `configureCore(...)` and by `ensureObservabilityBackend(...)`.
37
+ ///
38
+ /// Split out from `configured` so an app can have identity + attribution +
39
+ /// analytics WITHOUT handing the SDK ownership of StoreKit. Hosts that keep
40
+ /// another IAP library (e.g. RevenueCat) cannot afford a second
41
+ /// `Transaction.updates` observer racing theirs on `transaction.finish()`.
42
+ private var coreConfigured: Bool = false
33
43
  private var configuredApiKey: String?
34
44
  private var configuredServerURL: String?
35
45
  private var currentAppUserID: String?
36
46
  private var currentIsAnonymous: Bool = true
37
47
  private var resolvedLogLevel: LogLevel = .warn
48
+ /// Once-flag for `ensureObservabilityBackend(apiKey:serverURL:)`. Guarded
49
+ /// by `stateQueue` like every other field on this type.
50
+ private var observabilityWired: Bool = false
38
51
 
39
52
  // MARK: Identity client seam (LEGACY — kept for back-compat)
40
53
  //
@@ -45,7 +58,21 @@ public final class SwissKnife: NSObject {
45
58
  // compile. New tests should use `Identity._setNetworkForTesting(...)`.
46
59
  internal var identityClient: IdentityClient = BackendHttpClientIdentityClient()
47
60
 
48
- /// Configure the SDK. After this returns:
61
+ /// Configure the WHOLE SDK — core (ingest / identity / attribution /
62
+ /// attributes) **and** the purchase engine (StoreKit 2).
63
+ ///
64
+ /// Exactly equivalent to `configureCore(...)` followed by
65
+ /// `configurePurchases(...)`, in that order, and kept bit-for-bit
66
+ /// behaviour-compatible with the pre-split entry point. Every existing
67
+ /// integration keeps working unchanged.
68
+ ///
69
+ /// **If your app already has another IAP library** (RevenueCat, StoreKit
70
+ /// wired by hand, …), call `configureCore(...)` instead: this method starts
71
+ /// a process-wide `StoreKit.Transaction.updates` observer that calls
72
+ /// `transaction.finish()`, which will race the other library's observer on
73
+ /// live renewals. `configureCore(...)` never touches StoreKit.
74
+ ///
75
+ /// After this returns:
49
76
  /// - The three services (entitlements, purchases, offerings) are wired
50
77
  /// with the proxyURL + apiKey.
51
78
  /// - The attributes client (Phase 3) is wired the same way.
@@ -67,23 +94,58 @@ public final class SwissKnife: NSObject {
67
94
  String(apiKey.prefix(8)),
68
95
  proxyURL ?? "nil"
69
96
  )
97
+ configureCore(
98
+ apiKey: apiKey,
99
+ appUserID: appUserID,
100
+ proxyURL: proxyURL,
101
+ logLevel: logLevel,
102
+ attribution: attribution
103
+ )
104
+ configurePurchases(
105
+ apiKey: apiKey,
106
+ appUserID: appUserID,
107
+ proxyURL: proxyURL,
108
+ storeKitVersion: storeKitVersion
109
+ )
110
+ }
111
+
112
+ /// Configure everything the SDK can do **without owning the store**:
113
+ /// analytics / crash / performance ingest, `SwissKnife.Identity`,
114
+ /// `SwissKnife.Attribution`, and the subscriber-attributes client.
115
+ ///
116
+ /// Guarantees — these are asserted by
117
+ /// `Tests/…/StoreOwnershipSeparationTests.swift`:
118
+ /// - **No StoreKit observer is started.** `PurchaseService` is not
119
+ /// configured, so `StoreKit.Transaction.updates` is never iterated and
120
+ /// `transaction.finish()` is never called by us. An app that keeps
121
+ /// RevenueCat (or its own StoreKit code) can adopt identity /
122
+ /// attribution / analytics with zero risk of two observers racing to
123
+ /// finish the same renewal.
124
+ /// - **No install is registered as a side effect.** Unlike
125
+ /// `configure(...)`, this does NOT honour
126
+ /// `Attribution.Configuration.sendInstallOnFirstLaunch` — see
127
+ /// `configurePurchases(...)` for where that moved and why. Hosts that
128
+ /// want the install POST from a core-only app call
129
+ /// `SwissKnife.Attribution.registerInstall(...)` (or
130
+ /// `requestTrackingAuthorizationAndRegister()`) explicitly.
131
+ ///
132
+ /// `attribution:` is still accepted here because the *configuration*
133
+ /// (`autoPromptATT`) is a core concern — it governs the explicit
134
+ /// registration calls above.
135
+ public static func configureCore(
136
+ apiKey: String,
137
+ appUserID: String? = nil,
138
+ proxyURL: String? = nil,
139
+ logLevel: String? = nil,
140
+ attribution: SwissKnife.Attribution.Configuration = .init()
141
+ ) {
142
+ precondition(!apiKey.isEmpty, "configureCore requires a non-empty apiKey")
70
143
 
71
144
  let level = logLevel.flatMap(parseLogLevel) ?? .warn
72
- let resolvedAppUserID: String
73
- let isAnonymous: Bool
74
- if let provided = appUserID, !provided.isEmpty {
75
- resolvedAppUserID = provided
76
- isAnonymous = false
77
- } else {
78
- // Anonymous flow: use the keychain-backed device id, prefixed
79
- // to match the convention upstream consumers grep for (similar
80
- // to RC's `$RCAnonymousID:` prefix but our own).
81
- resolvedAppUserID = "$SKAnonymousID:" + DeviceID.get()
82
- isAnonymous = true
83
- }
145
+ let (resolvedAppUserID, isAnonymous) = resolveConfiguredIdentity(appUserID)
84
146
 
85
147
  shared.stateQueue.sync {
86
- shared.configured = true
148
+ shared.coreConfigured = true
87
149
  shared.configuredApiKey = apiKey
88
150
  shared.configuredServerURL = proxyURL
89
151
  shared.currentAppUserID = resolvedAppUserID
@@ -95,11 +157,80 @@ public final class SwissKnife: NSObject {
95
157
  SwissKnife.Identity._seedConfiguredUser(isAnonymous ? nil : resolvedAppUserID)
96
158
 
97
159
  AttributesClient.shared.configure(serverURL: proxyURL, apiKey: apiKey)
160
+ // EntitlementsService is core, not store: it is a disk cache in front
161
+ // of `GET /api/sdk/entitlements/list` and imports no StoreKit. It lives
162
+ // here because `Identity.logIn/logOut` re-key and refresh it, so an
163
+ // analytics-only app still needs it wired for identity to work.
164
+ EntitlementsService.shared.configure(
165
+ serverURL: proxyURL,
166
+ apiKey: apiKey,
167
+ userId: resolvedAppUserID
168
+ )
169
+ // Snapshot only — the auto-install POST is deliberately NOT triggered
170
+ // from core (see the doc comment above).
171
+ SwissKnife.Attribution._configureCore(attribution)
98
172
  os_log(
99
- "SwissKnife.configure wired AttributesClient",
173
+ "SwissKnife.configureCore wired AttributesClient + Identity + Attribution",
100
174
  log: shared.log,
101
175
  type: .info
102
176
  )
177
+
178
+ // Round A — wire cross-cutting context observers (Session ← AppLifecycle,
179
+ // IngestClient ← Reachability + AppLifecycle). Extracted into
180
+ // `ensureObservabilityBackend` so observability can also be wired
181
+ // WITHOUT configure() / the purchase engine — see that method. The
182
+ // config seeding inside is a no-op here because `coreConfigured` is
183
+ // already true by this point, so configureCore's apiKey/serverURL stand.
184
+ ensureObservabilityBackend(apiKey: apiKey, serverURL: proxyURL)
185
+ }
186
+
187
+ /// Configure the purchase engine: StoreKit 2 transaction observation,
188
+ /// purchases / restore, and the offerings catalog.
189
+ ///
190
+ /// **This is the call that starts the process-wide
191
+ /// `StoreKit.Transaction.updates` listener** (via
192
+ /// `PurchaseService.configure`). Its handler calls `transaction.finish()`,
193
+ /// so do not call this in an app that lets another library own StoreKit.
194
+ ///
195
+ /// Also the home of `Attribution.Configuration.sendInstallOnFirstLaunch`.
196
+ /// Rationale: install→campaign resolution exists to attribute *revenue*,
197
+ /// so it belongs with the revenue engine; and keeping it here makes
198
+ /// `configure()` an exact composition of the two halves, so no existing
199
+ /// integration loses the install event. A core-only app registers installs
200
+ /// explicitly via `SwissKnife.Attribution.registerInstall(...)`.
201
+ ///
202
+ /// Safe to call without `configureCore(...)` — it seeds the backend config
203
+ /// itself in that case — but the normal shape is core first.
204
+ public static func configurePurchases(
205
+ apiKey: String,
206
+ appUserID: String? = nil,
207
+ proxyURL: String? = nil,
208
+ storeKitVersion: String = "DEFAULT"
209
+ ) {
210
+ precondition(!apiKey.isEmpty, "configurePurchases requires a non-empty apiKey")
211
+ os_log(
212
+ "SwissKnife.configurePurchases called (apiKey prefix %{public}@…, proxyURL %{public}@)",
213
+ log: shared.log,
214
+ type: .info,
215
+ String(apiKey.prefix(8)),
216
+ proxyURL ?? "nil"
217
+ )
218
+
219
+ let (resolvedAppUserID, isAnonymous) = resolveConfiguredIdentity(appUserID)
220
+ shared.stateQueue.sync {
221
+ shared.configured = true
222
+ // Purchases-without-core is a supported (if unusual) shape — seed
223
+ // the backend config so the validate POST can authenticate. When
224
+ // core already ran, its values are authoritative and left alone.
225
+ if !shared.coreConfigured {
226
+ shared.configuredApiKey = apiKey
227
+ shared.configuredServerURL = proxyURL
228
+ shared.currentAppUserID = resolvedAppUserID
229
+ shared.currentIsAnonymous = isAnonymous
230
+ }
231
+ }
232
+
233
+ // Idempotent when core already configured it with the same values.
103
234
  EntitlementsService.shared.configure(
104
235
  serverURL: proxyURL,
105
236
  apiKey: apiKey,
@@ -115,27 +246,163 @@ public final class SwissKnife: NSObject {
115
246
  // parameter so existing call sites compile.
116
247
  _ = storeKitVersion
117
248
 
118
- // Wave 2 — wire the Attribution module so the first launch
119
- // auto-registers the install (and optionally shows the ATT
120
- // prompt). Fire-and-forget — configure(...) does not block on
121
- // the network call.
122
- SwissKnife.Attribution._configure(attribution)
123
-
124
- // Round A — wire cross-cutting context observers. Session needs
125
- // AppLifecycle to drive background-timeout-based restarts;
126
- // IngestClient needs Reachability (pause/resume flush) and
127
- // AppLifecycle (flush on background). The MainActor hop is
128
- // because both observers subscribe to UIApplication notifications.
249
+ // Wave 2 — first launch auto-registers the install (and optionally
250
+ // shows the ATT prompt). Fire-and-forget; never blocks configure.
251
+ SwissKnife.Attribution._sendInstallOnFirstLaunchIfEnabled()
252
+ }
253
+
254
+ /// Resolve `(appUserID, isAnonymous)` the way both configure entry points
255
+ /// need it. Anonymous flow uses the keychain-backed device id, prefixed to
256
+ /// match the convention upstream consumers grep for (similar to RC's
257
+ /// `$RCAnonymousID:` prefix but our own).
258
+ private static func resolveConfiguredIdentity(
259
+ _ appUserID: String?
260
+ ) -> (resolved: String, isAnonymous: Bool) {
261
+ if let provided = appUserID, !provided.isEmpty {
262
+ return (provided, false)
263
+ }
264
+ return ("$SKAnonymousID:" + DeviceID.get(), true)
265
+ }
266
+
267
+ /// Wire the observability backend (analytics / crash / performance ingest)
268
+ /// WITHOUT requiring `configure(...)` or the purchase engine.
269
+ ///
270
+ /// Mirror of `SwissKnife.ensureObservabilityBackend` in
271
+ /// `packages/swiss-knife-android/.../SwissKnife.kt`. It exists so an
272
+ /// analytics-only app — or a non-SDK-store build (e.g. RuStore, where
273
+ /// `configure` is never called) — still ships events. Before this existed,
274
+ /// `SKAnalytics`/`SKCrashReporting` happily queued items on disk but every
275
+ /// flush threw `PurchasesError.notConfigured` out of
276
+ /// `BackendHttpClient.makeRequest` (empty apiKey) and nothing ever left the
277
+ /// device — silently.
278
+ ///
279
+ /// Semantics (identical on both platforms — keep them in lockstep):
280
+ ///
281
+ /// - **It marks CORE configured, never purchases.** The seeded apiKey +
282
+ /// server URL are exactly what `SwissKnife.Identity` and
283
+ /// `SwissKnife.Attribution` need, so an analytics-only app gets working
284
+ /// identity and attribution from this one call —
285
+ /// `SwissKnife.isCoreConfigured` flips to `true`, `SwissKnife.isConfigured`
286
+ /// (the purchase engine) stays `false`, and no StoreKit observer starts.
287
+ /// - **`configure(...)` is authoritative, regardless of call order.** It
288
+ /// always writes `configuredApiKey`/`configuredServerURL`; this method
289
+ /// only *seeds* them while the SDK is unconfigured. So
290
+ /// `ensureObservabilityBackend` → `configure` and `configure` →
291
+ /// `ensureObservabilityBackend` converge on the same end state
292
+ /// (configure's values). There is no "who ran first" hazard.
293
+ /// - **Idempotent, first call wins.** The observer wiring AND the config
294
+ /// seeding run at most once per process; subsequent calls (including the
295
+ /// one `configure` makes) return early. Matches Android, where
296
+ /// `ConfigBridge` is registered inside the same once-guard.
297
+ /// - **Config is read per request, not captured at wire time.**
298
+ /// `BackendHttpClient` resolves `SwissKnife.identityConfigSnapshot()`
299
+ /// inside `makeRequest`, so a *late* configure retroactively unblocks
300
+ /// everything already sitting in the durable ingest queue — nothing that
301
+ /// was tracked before the SDK knew its apiKey is lost.
302
+ /// - An empty `apiKey` is rejected (no-op): wiring the pipeline against a
303
+ /// key that can never authenticate would just re-create the silent
304
+ /// failure this method exists to remove.
305
+ ///
306
+ /// Deliberately does NOT call `SKAnalytics.initialize(...)` (Android does,
307
+ /// because its `SKAnalytics` drops events until it has an `appContext`).
308
+ /// On iOS `trackPreBuiltEvent` works with a nil configuration, and
309
+ /// `initialize` would emit `[SwissKnife] Session Start` /
310
+ /// `Application Installed` — duplicating the session event the RN JS layer
311
+ /// already tracks in `Analytics.init`. Flush scheduling is unchanged from
312
+ /// the configure path: batch-size threshold, reachability regain, app
313
+ /// background, plus the JS-side interval calling `flushEvents`.
314
+ ///
315
+ /// - Parameters:
316
+ /// - apiKey: the project's SDK key. Empty ⇒ no-op.
317
+ /// - serverURL: backend base URL. `nil` / empty ⇒ the default host
318
+ /// (`https://api.swiss-knife.dev`), matching `configure(proxyURL:)`.
319
+ public static func ensureObservabilityBackend(apiKey: String, serverURL: String?) {
320
+ guard !apiKey.isEmpty else { return }
321
+ let normalizedServerURL: String? = {
322
+ guard var trimmed = serverURL?.trimmingCharacters(in: .whitespacesAndNewlines) else {
323
+ return nil
324
+ }
325
+ while trimmed.hasSuffix("/") { trimmed.removeLast() }
326
+ return trimmed.isEmpty ? nil : trimmed
327
+ }()
328
+
329
+ // Computed outside the lock — DeviceID.get() hits the Keychain.
330
+ let anonymousFallbackId = "$SKAnonymousID:" + DeviceID.get()
331
+
332
+ var seededCore = false
333
+ let shouldWire: Bool = shared.stateQueue.sync {
334
+ if shared.observabilityWired { return false }
335
+ shared.observabilityWired = true
336
+ if !shared.coreConfigured {
337
+ // Unconfigured: seed the shared backend config so
338
+ // BackendHttpClient can authenticate — and mark CORE as
339
+ // configured, which is what Identity/Attribution gate on. A
340
+ // later `configureCore(...)` overwrites both fields
341
+ // unconditionally. Purchases stay untouched: no StoreKit.
342
+ shared.coreConfigured = true
343
+ shared.configuredApiKey = apiKey
344
+ shared.configuredServerURL = normalizedServerURL
345
+ if shared.currentAppUserID == nil {
346
+ shared.currentAppUserID = anonymousFallbackId
347
+ shared.currentIsAnonymous = true
348
+ }
349
+ seededCore = true
350
+ }
351
+ return true
352
+ }
353
+ guard shouldWire else { return }
354
+
355
+ if seededCore {
356
+ // Give Identity/attributes the same backend coordinates the ingest
357
+ // path just got, so `Identity.logIn(...)` and `setEmail(...)` work
358
+ // in an app that only ever called `Analytics.init`.
359
+ AttributesClient.shared.configure(serverURL: normalizedServerURL, apiKey: apiKey)
360
+ EntitlementsService.shared.configure(
361
+ serverURL: normalizedServerURL,
362
+ apiKey: apiKey,
363
+ userId: anonymousFallbackId
364
+ )
365
+ }
366
+
367
+ os_log(
368
+ "SwissKnife.ensureObservabilityBackend wired (apiKey prefix %{public}@…, serverURL %{public}@)",
369
+ log: shared.log,
370
+ type: .info,
371
+ String(apiKey.prefix(8)),
372
+ normalizedServerURL ?? "default"
373
+ )
374
+
375
+ // Session needs AppLifecycle to drive background-timeout-based
376
+ // restarts; IngestClient needs Reachability (pause/resume flush) and
377
+ // AppLifecycle (flush on background). The MainActor hop is because
378
+ // both observers subscribe to UIApplication notifications.
129
379
  Task { @MainActor in
130
380
  Session.shared.startObservingLifecycle()
131
381
  IngestClient.shared.startObservingContext()
132
382
  }
133
383
  }
134
384
 
385
+ /// Whether the PURCHASE engine is configured (`configure(...)` or
386
+ /// `configurePurchases(...)` ran). Gates `getOfferings`, `purchase*`,
387
+ /// `restorePurchases`, and `getCustomerInfo`.
388
+ ///
389
+ /// Deliberately stays `false` for a core-only app — those APIs genuinely
390
+ /// cannot work without the store, and a host that keeps its own IAP layer
391
+ /// must be able to tell the two states apart.
135
392
  public static var isConfigured: Bool {
136
393
  shared.stateQueue.sync { shared.configured }
137
394
  }
138
395
 
396
+ /// Whether the CORE is configured — ingest, `SwissKnife.Identity`,
397
+ /// `SwissKnife.Attribution`, subscriber attributes.
398
+ ///
399
+ /// `true` after ANY of `configure(...)`, `configureCore(...)`, or
400
+ /// `ensureObservabilityBackend(...)`. This — not `isConfigured` — is what
401
+ /// identity and attribution gate on.
402
+ public static var isCoreConfigured: Bool {
403
+ shared.stateQueue.sync { shared.coreConfigured }
404
+ }
405
+
139
406
  /// Current app user id (identified or anonymous).
140
407
  ///
141
408
  /// Prefer `SwissKnife.Identity.current` for new code — the Identity
@@ -153,6 +420,62 @@ public final class SwissKnife: NSObject {
153
420
  shared.stateQueue.sync { shared.currentIsAnonymous }
154
421
  }
155
422
 
423
+ /// The **subject identifier** the backend keys rows against — the value
424
+ /// that goes into `user_id` on `POST /api/sdk/subscriptions/validate` and
425
+ /// `GET /api/sdk/entitlements/list`. Server-side it lands in
426
+ /// `subscriptions.app_user_id`, is joined against
427
+ /// `app_users.external_user_id`, and is rendered in the dashboard.
428
+ ///
429
+ /// **It must never be the bare `DeviceID`.** The device id is a
430
+ /// Keychain-backed, reinstall-surviving, non-syncable value that the
431
+ /// server's device-binding control treats as unguessable. Writing it into
432
+ /// a user-visible column destroys that assumption. Two call sites used to
433
+ /// fall back to `DeviceID.get()` when *their own* configure step had not
434
+ /// run:
435
+ ///
436
+ /// - `PurchaseService.validateTransactionWithBackend` — reachable via
437
+ /// `configurePurchases(...)` **without** `configureCore(...)`, which
438
+ /// is a documented, supported shape. `isCoreConfigured` stays false
439
+ /// there, so the old `appUserIDOrNil()` returned nil.
440
+ /// - `EntitlementsService.performRefresh` — defensive only today (every
441
+ /// configure path seeds a non-empty user id), but one bad
442
+ /// `setCurrentUser(nil)` away from being live.
443
+ ///
444
+ /// Resolution order, and why:
445
+ ///
446
+ /// 1. `currentAppUserID` — set by **every** configure entry point
447
+ /// (`configureCore`, `configurePurchases`,
448
+ /// `ensureObservabilityBackend`) to either the host-supplied
449
+ /// `appUserID` or `"$SKAnonymousID:" + DeviceID.get()`, and kept in
450
+ /// lockstep with `Identity` by `identityDidChangeTo*`. This is the
451
+ /// same value handed to `EntitlementsService.configure(userId:)`, so
452
+ /// preferring it is what makes `validate` and `entitlements/list`
453
+ /// agree on the subject — including in the purchases-without-core
454
+ /// shape, where they previously disagreed.
455
+ /// 2. The `Identity` snapshot — always well-defined even before any
456
+ /// `configure(...)`, and always prefixed.
457
+ ///
458
+ /// Deliberately does NOT gate on `isCoreConfigured`: there is never a
459
+ /// reason to reach past a well-defined prefixed identity for a weaker one.
460
+ ///
461
+ /// **Known residual exposure.** The anonymous form is
462
+ /// `"$SKAnonymousID:" + DeviceID.get()`, so the device UUID is still
463
+ /// recoverable from the stored subject by stripping the prefix. This
464
+ /// method stops the id from being written *naked* and makes the two
465
+ /// endpoints agree; it does not make the device id unrecoverable. That
466
+ /// needs an opaque derivation (per-install random, or a one-way hash),
467
+ /// which re-keys every existing anonymous install and so must ship with a
468
+ /// server-side alias/backfill. Pinned by
469
+ /// `BackendSubjectIdTests.test_anonymousSubject_stillEmbedsDeviceId_knownLimitation`.
470
+ internal static func backendSubjectId() -> String {
471
+ let configured = shared.stateQueue.sync { shared.currentAppUserID }
472
+ if let configured, !configured.isEmpty {
473
+ return configured
474
+ }
475
+ let snapshot = Identity.current
476
+ return snapshot.userId ?? snapshot.anonymousId
477
+ }
478
+
156
479
  // MARK: Reads / offerings (typed, async)
157
480
 
158
481
  public static func getCustomerInfo() async throws -> CustomerInfo {
@@ -261,11 +584,16 @@ public final class SwissKnife: NSObject {
261
584
  internal static func _dangerouslyResetConfigForTesting() {
262
585
  shared.stateQueue.sync {
263
586
  shared.configured = false
587
+ shared.coreConfigured = false
264
588
  shared.configuredApiKey = nil
265
589
  shared.configuredServerURL = nil
266
590
  shared.currentAppUserID = nil
267
591
  shared.currentIsAnonymous = true
268
592
  shared.resolvedLogLevel = .warn
593
+ // Drop the once-flag too, so a follow-up `configure(...)` /
594
+ // `ensureObservabilityBackend(...)` re-runs the observer wiring
595
+ // exactly as it did before that guard existed.
596
+ shared.observabilityWired = false
269
597
  }
270
598
  }
271
599
 
@@ -324,13 +652,16 @@ public final class SwissKnife: NSObject {
324
652
  )
325
653
  }
326
654
 
655
+ // Attributes are a CORE concern (they describe the person, not the
656
+ // purchase), so these gate on `isCoreConfigured` — an analytics-only app
657
+ // can call `setEmail(...)` and have it land with the right ids.
327
658
  private static func currentAnonymousIdForAttributes() -> String? {
328
- guard isConfigured else { return nil }
659
+ guard isCoreConfigured else { return nil }
329
660
  return shared.stateQueue.sync { shared.currentAppUserID }
330
661
  }
331
662
 
332
663
  private static func currentExternalUserIdForAttributes() -> String? {
333
- guard isConfigured else { return nil }
664
+ guard isCoreConfigured else { return nil }
334
665
  return shared.stateQueue.sync {
335
666
  shared.currentIsAnonymous ? nil : shared.currentAppUserID
336
667
  }
@@ -34,6 +34,18 @@ var _module = require("./native/module.js");
34
34
 
35
35
  const observers = new Map();
36
36
  let lastSnapshot = null;
37
+
38
+ /**
39
+ * Result of the last `logIn` that actually reached native, so a repeat call
40
+ * with the same subject id can be answered without touching the bridge.
41
+ *
42
+ * Hosts are expected to call `logIn` on every app start and after every
43
+ * auth-state read — that is the correct usage, not a misuse — so the repeat
44
+ * case is the common case, and each one would otherwise cost a bridge hop
45
+ * plus a `/api/sdk/users/identify` round trip that can only ever conclude
46
+ * "nothing to merge".
47
+ */
48
+ let lastLogIn = null;
37
49
  function generateToken() {
38
50
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
39
51
  const r = Math.random() * 16 | 0;
@@ -77,18 +89,58 @@ const Identity = exports.Identity = {
77
89
  return current;
78
90
  },
79
91
  /**
80
- * Identify this device as a known user. Native posts the
81
- * `(anonymous_id, user_id)` pair to `/api/sdk/users/identify` (the
82
- * Wave 1 bug-fix; pre-Wave-1 Android did NOT post). Resolves once
83
- * the backend ack + post-identify entitlements refresh complete.
92
+ * Bind this device to a subject id.
93
+ *
94
+ * ## `logIn` does NOT mean "the human authenticated"
95
+ *
96
+ * The name is kept for RevenueCat parity, but the contract is narrower and
97
+ * more useful than the name suggests: it means *"from now on, this device's
98
+ * activity belongs to this subject id"*. Nothing about it asserts that a
99
+ * person proved who they are.
100
+ *
101
+ * It is therefore entirely legitimate — and often correct — to call this
102
+ * with an id that belongs to an anonymous subject. An app whose logged-out
103
+ * users are real rows in its own database (a deviceId-keyed row carrying
104
+ * progress and purchases) should pass that row's id here immediately, long
105
+ * before any sign-in. Doing so means the subsequent sign-in has a real
106
+ * previous subject to merge *from*, instead of stranding everything the
107
+ * person did while logged out.
108
+ *
109
+ * ## What happens on the wire
110
+ *
111
+ * Native posts the identifier pair to `/api/sdk/users/identify`, which
112
+ * re-points every row from the previous subject onto this one. That call
113
+ * either succeeds or rejects — a rejection means the device is identified
114
+ * locally but NOT merged server-side, so it must be retried rather than
115
+ * ignored. Resolves once the backend ack and the post-identify entitlements
116
+ * refresh complete.
117
+ *
118
+ * ## Repeat calls are free
119
+ *
120
+ * Calling this again with the id already in effect is a no-op: no bridge
121
+ * hop, no network request. Call it on every app start without a guard.
84
122
  */
85
123
  async logIn(userId) {
124
+ // Cheap no-op: the subject is already in effect for this process. Checked
125
+ // against the cached result AND the last known snapshot so a `logOut` /
126
+ // `reset` / `wipe` in between always forces a real call.
127
+ if (lastLogIn !== null && lastLogIn.userId === userId && lastSnapshot !== null && lastSnapshot.userId === userId && !lastSnapshot.isAnonymous) {
128
+ return lastLogIn.result;
129
+ }
86
130
  const result = await (0, _module.getNativeModule)().identityLogIn(userId);
131
+ // Only cache after native resolved. If the identify POST rejected, the
132
+ // throw propagates and nothing is cached, so the next call retries
133
+ // instead of silently reporting success for a merge that never happened.
134
+ lastLogIn = {
135
+ userId,
136
+ result
137
+ };
87
138
  await snapshotAndNotify("logIn");
88
139
  return result;
89
140
  },
90
141
  /** Revert to anonymous. DeviceID stays stable across logout. */
91
142
  async logOut() {
143
+ lastLogIn = null;
92
144
  await (0, _module.getNativeModule)().identityLogOut();
93
145
  await snapshotAndNotify("logOut");
94
146
  },
@@ -97,6 +149,7 @@ const Identity = exports.Identity = {
97
149
  * "switch test user" UX semantic.
98
150
  */
99
151
  async reset() {
152
+ lastLogIn = null;
100
153
  await (0, _module.getNativeModule)().identityReset();
101
154
  await snapshotAndNotify("reset");
102
155
  },
@@ -105,6 +158,7 @@ const Identity = exports.Identity = {
105
158
  * (Android) DeviceID. GDPR-delete / test-build cleanup.
106
159
  */
107
160
  async wipe() {
161
+ lastLogIn = null;
108
162
  await (0, _module.getNativeModule)().identityWipe();
109
163
  await snapshotAndNotify("wipe");
110
164
  },
@@ -120,6 +174,7 @@ const Identity = exports.Identity = {
120
174
  /** @internal Test seam — reset the cached snapshot + observers. */
121
175
  __resetForTests() {
122
176
  lastSnapshot = null;
177
+ lastLogIn = null;
123
178
  observers.clear();
124
179
  }
125
180
  };
@@ -1 +1 @@
1
- {"version":3,"names":["_module","require","observers","Map","lastSnapshot","generateToken","replace","c","r","Math","random","v","toString","snapshotAndNotify","reason","previous","current","getNativeModule","identityCurrent","size","change","Promise","resolve","then","observer","values","e","console","warn","Identity","exports","logIn","userId","result","identityLogIn","logOut","identityLogOut","reset","identityReset","wipe","identityWipe","addObserver","block","token","set","removeObserver","delete","__resetForTests","clear"],"sourceRoot":"../../src","sources":["identity.ts"],"mappings":";;;;;;AA2BA,IAAAA,OAAA,GAAAC,OAAA;AA3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,MAAMC,SAAS,GAAG,IAAIC,GAAG,CAAmB,CAAC;AAE7C,IAAIC,YAAqC,GAAG,IAAI;AAEhD,SAASC,aAAaA,CAAA,EAAW;EAC/B,OAAO,sCAAsC,CAACC,OAAO,CAAC,OAAO,EAAGC,CAAC,IAAK;IACpE,MAAMC,CAAC,GAAIC,IAAI,CAACC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAI,CAAC;IAClC,MAAMC,CAAC,GAAGJ,CAAC,KAAK,GAAG,GAAGC,CAAC,GAAIA,CAAC,GAAG,GAAG,GAAI,GAAG;IACzC,OAAOG,CAAC,CAACC,QAAQ,CAAC,EAAE,CAAC;EACvB,CAAC,CAAC;AACJ;AAEA,eAAeC,iBAAiBA,CAACC,MAA6C,EAA6B;EACzG,MAAMC,QAAQ,GAAGX,YAAY;EAC7B,MAAMY,OAAO,GAAG,MAAM,IAAAC,uBAAe,EAAC,CAAC,CAACC,eAAe,CAAC,CAAC;EACzDd,YAAY,GAAGY,OAAO;EACtB,IAAID,QAAQ,IAAIb,SAAS,CAACiB,IAAI,GAAG,CAAC,EAAE;IAClC,MAAMC,MAAsB,GAAG;MAAEL,QAAQ;MAAEC;IAAQ,CAAC;IACpD;IAC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IAAAtB,uBAAe,EAAC,CAAC,CAACuB,YAAY,CAAC,CAAC;IACtC,MAAM3B,iBAAiB,CAAC,MAAM,CAAC;EACjC,CAAC;EAED;EACA4B,WAAWA,CAACC,KAAe,EAAU;IACnC,MAAMC,KAAK,GAAGtC,aAAa,CAAC,CAAC;IAC7BH,SAAS,CAAC0C,GAAG,CAACD,KAAK,EAAED,KAAK,CAAC;IAC3B,OAAOC,KAAK;EACd,CAAC;EAEDE,cAAcA,CAACF,KAAa,EAAQ;IAClCzC,SAAS,CAAC4C,MAAM,CAACH,KAAK,CAAC;EACzB,CAAC;EAED;EACAI,eAAeA,CAAA,EAAS;IACtB3C,YAAY,GAAG,IAAI;IACnBF,SAAS,CAAC8C,KAAK,CAAC,CAAC;EACnB;AACF,CAAC","ignoreList":[]}
1
+ {"version":3,"names":["_module","require","observers","Map","lastSnapshot","lastLogIn","generateToken","replace","c","r","Math","random","v","toString","snapshotAndNotify","reason","previous","current","getNativeModule","identityCurrent","size","change","Promise","resolve","then","observer","values","e","console","warn","Identity","exports","logIn","userId","isAnonymous","result","identityLogIn","logOut","identityLogOut","reset","identityReset","wipe","identityWipe","addObserver","block","token","set","removeObserver","delete","__resetForTests","clear"],"sourceRoot":"../../src","sources":["identity.ts"],"mappings":";;;;;;AA2BA,IAAAA,OAAA,GAAAC,OAAA;AA3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,MAAMC,SAAS,GAAG,IAAIC,GAAG,CAAmB,CAAC;AAE7C,IAAIC,YAAqC,GAAG,IAAI;;AAEhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAIC,SAAyD,GAAG,IAAI;AAEpE,SAASC,aAAaA,CAAA,EAAW;EAC/B,OAAO,sCAAsC,CAACC,OAAO,CAAC,OAAO,EAAGC,CAAC,IAAK;IACpE,MAAMC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GAAGvC,aAAa,CAAC,CAAC;IAC7BJ,SAAS,CAAC4C,GAAG,CAACD,KAAK,EAAED,KAAK,CAAC;IAC3B,OAAOC,KAAK;EACd,CAAC;EAEDE,cAAcA,CAACF,KAAa,EAAQ;IAClC3C,SAAS,CAAC8C,MAAM,CAACH,KAAK,CAAC;EACzB,CAAC;EAED;EACAI,eAAeA,CAAA,EAAS;IACtB7C,YAAY,GAAG,IAAI;IACnBC,SAAS,GAAG,IAAI;IAChBH,SAAS,CAACgD,KAAK,CAAC,CAAC;EACnB;AACF,CAAC","ignoreList":[]}
@@ -399,17 +399,21 @@ const Analytics = exports.Analytics = {
399
399
  _sessionIdPromise = null;
400
400
 
401
401
  // Wire the native observability backend (BackendHttpClient + IngestClient)
402
- // independently of Purchases.configure, so builds that never configure the
403
- // purchase engine (e.g. RuStore-only Android) still send analytics. Android
404
- // implements `configureObservability`; on iOS it's absent (the backend is
405
- // wired by Purchases.configure), so the optional-chained call no-ops.
402
+ // independently of Purchases.configure, so an analytics-only app — or a
403
+ // build that never configures the purchase engine (e.g. RuStore-only
404
+ // Android) — still sends analytics. Implemented on BOTH platforms; the
405
+ // native side is idempotent and lets a later Purchases.configure win, so
406
+ // this is unconditional. `serverURL` is forwarded verbatim; "" means "use
407
+ // the SDK's default host", which is why there is no truthiness guard here
408
+ // (there used to be, and it made `Analytics.init({ apiKey })` — no
409
+ // serverURL — a silent no-op on both platforms).
406
410
  // Fire-and-forget: events queue natively regardless and flush once wired.
407
- if (config.serverURL) {
408
- try {
409
- void (0, _module.getNativeModule)().configureObservability?.(config.apiKey, config.serverURL)?.catch(() => {});
410
- } catch {
411
- // getNativeModule throws only when unlinked (web/Expo Go); harmless here.
412
- }
411
+ try {
412
+ void (0, _module.getNativeModule)().configureObservability(config.apiKey, config.serverURL ?? "").catch(() => {});
413
+ } catch {
414
+ // Two harmless cases: getNativeModule throws when the module is unlinked
415
+ // (web / Expo Go), and a TypeError lands here if the linked native module
416
+ // predates this method (JS updated without rebuilding the app).
413
417
  }
414
418
  if (_flushTimer) clearInterval(_flushTimer);
415
419
  // Native owns the authoritative flush scheduling (iOS Timer / Android