@app-swiss-knife/react-native-sdk 0.2.7 → 0.3.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 (66) hide show
  1. package/README.md +100 -47
  2. package/SwissKnifePurchases.podspec +8 -5
  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/SwissKnifeCrashReporting.swift +59 -18
  6. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  7. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +1 -1
  8. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +24 -0
  9. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +22 -1
  10. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +49 -0
  11. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +14 -0
  12. package/lib/commonjs/attributes.js +103 -0
  13. package/lib/commonjs/attributes.js.map +1 -0
  14. package/lib/commonjs/index.js +31 -2
  15. package/lib/commonjs/index.js.map +1 -1
  16. package/lib/commonjs/internal/config.js +237 -0
  17. package/lib/commonjs/internal/config.js.map +1 -0
  18. package/lib/commonjs/purchases.js +152 -209
  19. package/lib/commonjs/purchases.js.map +1 -1
  20. package/lib/commonjs/swiss-knife.js +115 -0
  21. package/lib/commonjs/swiss-knife.js.map +1 -0
  22. package/lib/commonjs/types.js +11 -0
  23. package/lib/commonjs/types.js.map +1 -1
  24. package/lib/module/attributes.js +100 -0
  25. package/lib/module/attributes.js.map +1 -0
  26. package/lib/module/index.js +19 -2
  27. package/lib/module/index.js.map +1 -1
  28. package/lib/module/internal/config.js +225 -0
  29. package/lib/module/internal/config.js.map +1 -0
  30. package/lib/module/purchases.js +132 -198
  31. package/lib/module/purchases.js.map +1 -1
  32. package/lib/module/swiss-knife.js +112 -0
  33. package/lib/module/swiss-knife.js.map +1 -0
  34. package/lib/module/types.js +11 -0
  35. package/lib/module/types.js.map +1 -1
  36. package/lib/typescript/commonjs/attributes.d.ts +41 -0
  37. package/lib/typescript/commonjs/attributes.d.ts.map +1 -0
  38. package/lib/typescript/commonjs/index.d.ts +2 -0
  39. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  40. package/lib/typescript/commonjs/internal/config.d.ts +121 -0
  41. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -0
  42. package/lib/typescript/commonjs/purchases.d.ts +47 -91
  43. package/lib/typescript/commonjs/purchases.d.ts.map +1 -1
  44. package/lib/typescript/commonjs/swiss-knife.d.ts +56 -0
  45. package/lib/typescript/commonjs/swiss-knife.d.ts.map +1 -0
  46. package/lib/typescript/commonjs/types.d.ts +13 -0
  47. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  48. package/lib/typescript/module/attributes.d.ts +41 -0
  49. package/lib/typescript/module/attributes.d.ts.map +1 -0
  50. package/lib/typescript/module/index.d.ts +2 -0
  51. package/lib/typescript/module/index.d.ts.map +1 -1
  52. package/lib/typescript/module/internal/config.d.ts +121 -0
  53. package/lib/typescript/module/internal/config.d.ts.map +1 -0
  54. package/lib/typescript/module/purchases.d.ts +47 -91
  55. package/lib/typescript/module/purchases.d.ts.map +1 -1
  56. package/lib/typescript/module/swiss-knife.d.ts +56 -0
  57. package/lib/typescript/module/swiss-knife.d.ts.map +1 -0
  58. package/lib/typescript/module/types.d.ts +13 -0
  59. package/lib/typescript/module/types.d.ts.map +1 -1
  60. package/package.json +1 -1
  61. package/src/attributes.ts +97 -0
  62. package/src/index.ts +19 -2
  63. package/src/internal/config.ts +233 -0
  64. package/src/purchases.ts +142 -213
  65. package/src/swiss-knife.ts +134 -0
  66. package/src/types.ts +14 -0
package/README.md CHANGED
@@ -48,9 +48,13 @@ anything under `ios/vendor` or `android/vendor`.
48
48
  `SwissKnifeJSON`). Because the vendored Swift compiles into the **same** pod
49
49
  module as the bridge, the bridge files use
50
50
  `#if canImport(SwissKnifeiOS) / import SwissKnifeiOS` (false, and unnecessary,
51
- in the pod) and the podspec defines `SWISSKNIFE_VENDORED` so conditional code
52
- paths stay live. The vendored Swift imports only system frameworks — zero
53
- third-party pods.
51
+ in the pod) purely to satisfy SPM consumers. **No bridge method body is
52
+ conditionally compiled.** They used to be gated on the podspec's
53
+ `SWISSKNIFE_VENDORED` flag, which meant a Podfile `post_install` that assigned
54
+ rather than appended to `SWIFT_ACTIVE_COMPILATION_CONDITIONS` silently
55
+ compiled the native crash reporter down to empty method bodies while the
56
+ build stayed green. A missing SDK is now a compile error instead. The
57
+ vendored Swift imports only system frameworks — zero third-party pods.
54
58
 
55
59
  Phase 7 of the SDK rip-and-replace removed every RevenueCat / PHC dependency
56
60
  from the bridge — neither the iOS pod graph nor the Android AAR graph pulls
@@ -88,39 +92,76 @@ npm install @react-native-async-storage/async-storage react-native-webview
88
92
  ## Quick Start
89
93
 
90
94
  ```typescript
91
- import { SwissKnifeClient } from "@app-swiss-knife/react-native-sdk";
95
+ import {
96
+ SwissKnife,
97
+ Purchases,
98
+ Identity,
99
+ Attributes,
100
+ } from "@app-swiss-knife/react-native-sdk";
92
101
 
93
- const client = new SwissKnifeClient({
94
- apiKey: "your-api-key",
95
- baseURL: "https://your-app.com",
96
- debug: true, // Enable request/response logging
102
+ // Once, at app start.
103
+ SwissKnife.configure({
104
+ apiKey: "sk_...",
105
+ proxyURL: "https://your-swiss-knife-host",
97
106
  });
98
107
 
99
- // Fetch SDK config
100
- const config = await client.get("/api/sdk/config");
101
-
102
- // Track events
103
- await client.post("/api/sdk/events/batch", {
104
- user_id: "user-123",
105
- events: [
106
- {
107
- name: "app_open",
108
- properties: { screen: "home" },
109
- timestamp: new Date().toISOString(),
110
- },
111
- ],
112
- });
108
+ // Who is this device?
109
+ await Identity.logIn("user_42");
113
110
 
114
- // Evaluate feature flags
115
- const flags = await client.get("/api/sdk/flags/evaluate", {
116
- user_id: "user-123",
117
- });
111
+ // What do we know about them? (This is the dashboard person card.)
112
+ await Attributes.setEmail("ann@example.com");
113
+ await Attributes.set({ plan: "gold", cohort: "2026-08" });
114
+
115
+ // Sell them something.
116
+ const offerings = await Purchases.getOfferings();
117
+ const pkg = offerings.current?.availablePackages[0];
118
+ if (pkg) await Purchases.purchasePackage(pkg);
118
119
  ```
119
120
 
121
+ ## The namespaces
122
+
123
+ Everything hangs off `SwissKnife`, the same way it does in the native iOS and
124
+ Android SDKs. Each namespace is also exported by name, so
125
+ `SwissKnife.Identity` and `Identity` are the same object — import whichever
126
+ reads better.
127
+
128
+ | Namespace | What it is | Needs |
129
+ | ---------------- | ------------------------------------------------------------------------------------------ | ----------- |
130
+ | `SwissKnife` | Bootstrap: `configure`, `configureCore`, `isConfigured`, `isCoreConfigured`, `setLogLevel` | — |
131
+ | `Purchases` | The store: offerings, purchases, restores, `CustomerInfo` | `configure` |
132
+ | `Identity` | `logIn` / `logOut` / `current` / `reset` / `wipe` | core |
133
+ | `Attributes` | Subscriber attributes — **the dashboard person card** | core |
134
+ | `Attribution` | Install attribution: ATT / IDFA / advertising id / referrer | core |
135
+ | `Analytics` | `init` / `track` / `identify` / `screen` | — |
136
+ | `CrashReporting` | Crash + error reporting | — |
137
+ | `Performance` | Transactions and spans | — |
138
+
139
+ "core" means `SwissKnife.configure(...)`, `SwissKnife.configureCore(...)` **or**
140
+ `Analytics.init(...)` — no store required.
141
+
142
+ ### Migrating from `react-native-purchases`?
143
+
144
+ Change nothing. `Purchases` keeps every member it has ever had, including
145
+ `Purchases.configure`, `Purchases.configureCore`, `Purchases.isConfigured`,
146
+ `Purchases.isCoreConfigured`, `Purchases.setLogLevel`, `Purchases.setAttributes`,
147
+ `Purchases.setEmail`, `Purchases.setDisplayName`, `Purchases.setPhoneNumber` and
148
+ `Purchases.setPushToken`. They are **not deprecated** and they are not wrappers —
149
+ `Purchases.configure === SwissKnife.configure` and
150
+ `Purchases.setAttributes === Attributes.set` are literally true, so the two
151
+ spellings share one bootstrap state and cannot drift apart. Mix them freely
152
+ while you migrate, or never migrate at all.
153
+
154
+ The four identity aliases (`Purchases.logIn`, `logOut`, `getAppUserID`,
155
+ `isAnonymous`) are the exception and stay marked deprecated: they still work, but
156
+ `Identity.*` is the canonical home and the RC return types misdescribe what those
157
+ calls do in a store-less app.
158
+
159
+ New namespaces require SDK `>= 0.3.0`.
160
+
120
161
  ## Already using another IAP library? Use `configureCore`
121
162
 
122
- `Purchases.configure(...)` sets up two independent things: the **core** (event
123
- ingest, `Identity`, `Attribution`, subscriber attributes) and the **purchase
163
+ `SwissKnife.configure(...)` sets up two independent things: the **core** (event
164
+ ingest, `Identity`, `Attribution`, `Attributes`) and the **purchase
124
165
  engine** (StoreKit 2 on iOS, Google Play Billing on Android).
125
166
 
126
167
  The purchase engine is not passive. On iOS it starts a process-wide
@@ -133,40 +174,46 @@ So the two halves are separately callable:
133
174
 
134
175
  ```typescript
135
176
  import {
136
- Purchases,
177
+ SwissKnife,
137
178
  Identity,
179
+ Attributes,
138
180
  Attribution,
139
- Analytics,
140
181
  } from "@app-swiss-knife/react-native-sdk";
141
182
 
142
- // Analytics + identity + attribution. No StoreKit observer. No BillingClient.
143
- // No install registered as a side effect.
144
- Purchases.configureCore({
183
+ // Analytics + identity + attribution + attributes. No StoreKit observer.
184
+ // No BillingClient. No install registered as a side effect.
185
+ SwissKnife.configureCore({
145
186
  apiKey: "sk_...",
146
187
  proxyURL: "https://your-swiss-knife-host",
147
188
  });
148
189
 
149
190
  await Identity.logIn("user_42");
191
+ await Attributes.setEmail("ann@example.com"); // person card, no store needed
150
192
  await Attribution.registerInstall(); // explicit — core never does this for you
151
193
  ```
152
194
 
153
195
  - **Analytics only?** `Analytics.init({ apiKey, serverURL })` already wires core
154
- natively — identity and attribution work from that call alone. Reach for
155
- `configureCore` when you also want to pass an `appUserID`, an attribution
156
- configuration, or a log level up front.
157
- - **`Purchases.configure(...)` is unchanged** — it is exactly core + purchases,
196
+ natively — identity, attribution and attributes work from that call alone.
197
+ Reach for `configureCore` when you also want to pass an `appUserID`, an
198
+ attribution configuration, or a log level up front.
199
+ - **`SwissKnife.configure(...)` is unchanged** — it is exactly core + purchases,
158
200
  including the first-launch install registration
159
201
  (`sendInstallOnFirstLaunch`, default `true`). Existing integrations need no
160
202
  changes.
161
- - `Purchases.isConfigured()` reports the **purchase engine** and stays `false`
162
- in a core-only app; `Purchases.isCoreConfigured()` reports the core. Both read
203
+ - **`Attributes.*` works here.** All five setters need core only, which is why
204
+ they are a namespace of their own rather than members of `Purchases`: an app
205
+ that never sells anything still wants its person card filled in. They are the
206
+ only path to `POST /api/sdk/users/attributes`.
207
+ - `SwissKnife.isConfigured()` reports the **purchase engine** and stays `false`
208
+ in a core-only app; `SwissKnife.isCoreConfigured()` reports the core. Both read
163
209
  the answer from native — which is what makes `isCoreConfigured()` return
164
210
  `true` in an `Analytics.init`-only app, where no JS configure call ever
165
211
  happened. Neither ever throws or rejects: if the native module is not linked
166
212
  (Expo Go, a build without `pod install` / a Gradle sync, web) they both
167
213
  resolve `false`, because an unlinked module cannot have configured anything.
168
214
  - Native equivalents: `SwissKnife.configureCore(...)` /
169
- `SwissKnife.configurePurchases(...)` on both iOS and Android.
215
+ `SwissKnife.configurePurchases(...)` on both iOS and Android — the JS root is
216
+ named to match.
170
217
 
171
218
  ## IDFA/GAID Collection (Advertising ID)
172
219
 
@@ -196,16 +243,22 @@ The SDK automatically:
196
243
  - Includes `advertising_id` in the install attribution request
197
244
  - Falls back gracefully if the user denies tracking or the libraries are not installed
198
245
 
199
- You can also use the helpers directly:
246
+ You can also drive it yourself through the `Attribution` namespace — prompt
247
+ orchestration and the idempotency cache live natively, so a second call returns
248
+ the cached resolution without re-prompting or re-POSTing:
200
249
 
201
250
  ```typescript
202
- import {
203
- requestTrackingPermission,
204
- getAdvertisingId,
205
- } from "@app-swiss-knife/react-native-sdk";
251
+ import { Attribution } from "@app-swiss-knife/react-native-sdk";
252
+
253
+ // Auto-collect (ATT prompt + IDFA on iOS, advertising id + referrer on Android)
254
+ // and register the install.
255
+ const resolved = await Attribution.requestAndRegister();
256
+
257
+ // Or collect consent yourself and hand us the id (pass null if denied):
258
+ await Attribution.registerInstall(advertisingId);
206
259
 
207
- const status = await requestTrackingPermission(); // 'authorized' | 'denied' | 'not-determined' | 'restricted'
208
- const { id, isLimitedAdTracking } = await getAdvertisingId();
260
+ // Read the cached resolution without touching the network:
261
+ const current = await Attribution.resolved();
209
262
  ```
210
263
 
211
264
  ## Custom Storage
@@ -13,11 +13,14 @@ Pod::Spec.new do |s|
13
13
  # 15.1 == the React Native / Expo default `ios.deploymentTarget`, so this pod
14
14
  # resolves in a stock app with no `expo-build-properties` override.
15
15
  #
16
- # This is deliberately NOT the `.iOS(.v16)` from the standalone SPM package
17
- # (packages/swiss-knife-ios/Package.swift). That floor is an SPM-consumer
18
- # contract; here the SDK's Swift is VENDORED and compiled in-tree, so the real
19
- # floor is whatever the code needs. Verified empirically: the vendored sources
20
- # compile clean at 15.1 and use no iOS 16 API. Everything StoreKit 2 is behind
16
+ # Deliberately 15.1 rather than the standalone SPM package's 15.0
17
+ # (packages/swiss-knife-ios/Package.swift). Both floors sit above the real
18
+ # requirement; this one is pinned to the RN/Expo default so a stock app
19
+ # resolves without touching its config, while the SPM package declares the
20
+ # true minimum for consumers who set their own target. The SDK's Swift is
21
+ # VENDORED here and compiled in-tree, so the real floor is whatever the code
22
+ # needs. Verified empirically: the vendored sources compile clean at 15.1 and
23
+ # at 15.0, and use no iOS 16 API. Everything StoreKit 2 is behind
21
24
  # `@available(iOS 15.0, *)` (Services/PurchaseService.swift,
22
25
  # Services/OfferingsService.swift), which is what sets the true floor —
23
26
  # do not drop below 15.0 or the entire purchase path becomes dead code.
@@ -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.2.7"
45
+ const val SDK_VERSION: String = "0.3.0"
46
46
 
47
47
  private val cacheLock = Any()
48
48
 
@@ -208,7 +208,7 @@ internal object IngestPlaceholderDevice {
208
208
  appBuild = "unknown",
209
209
  locale = Locale.getDefault().toString(),
210
210
  timezone = TimeZone.getDefault().id,
211
- sdkVersion = "0.2.7",
211
+ sdkVersion = "0.3.0",
212
212
  bundleIdentifier = null,
213
213
  )
214
214
  }
@@ -12,14 +12,30 @@
12
12
  // Two link modes, one source file:
13
13
  // * CocoaPods (the RN package) — the SDK's Swift sources are VENDORED into
14
14
  // this same module from ios/vendor/SwissKnifeiOS/**, so there is no
15
- // `SwissKnifeiOS` module to import and the podspec defines
16
- // SWISSKNIFE_VENDORED to keep the code paths live.
15
+ // `SwissKnifeiOS` module to import and the types are already in scope.
17
16
  // * SPM / a separately-linked SwissKnifeiOS module — `canImport` is true and
18
17
  // the import supplies the types.
19
- // If somehow neither holds, the module degrades to a safe no-op (JS-side
20
- // reporting still works) rather than failing to compile.
18
+ //
19
+ // EVERY METHOD BODY BELOW IS UNCONDITIONAL. They used to be wrapped in
20
+ // `#if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)`, which made the whole
21
+ // native crash reporter contingent on one xcconfig string surviving into the
22
+ // pod's build settings. `SWISSKNIFE_VENDORED` is set by `s.pod_target_xcconfig`
23
+ // in SwissKnifePurchases.podspec, and a Podfile `post_install` hook that
24
+ // ASSIGNS `SWIFT_ACTIVE_COMPILATION_CONDITIONS` instead of appending to it — a
25
+ // routine RN/Expo workaround — drops it. The failure was total and completely
26
+ // silent: the vendored sources still compiled, `SwissKnifePurchases.swift`
27
+ // (which never carried these guards) kept working, the build stayed green,
28
+ // `crashNative*` still crashed the app because those hooks sit OUTSIDE the
29
+ // guard, and `start(...)` compiled down to an empty body — so no signal
30
+ // handler was ever installed and not one native crash was ever reported.
31
+ //
32
+ // A missing SDK is now a COMPILE ERROR, exactly as it already is in
33
+ // SwissKnifePurchases.swift. "Degrades to a safe no-op" reads as safe and is
34
+ // not: it turns a build misconfiguration into a production outage nobody can
35
+ // see from the outside.
21
36
 
22
37
  import Foundation
38
+ import os.log
23
39
  #if canImport(SwissKnifeiOS)
24
40
  import SwissKnifeiOS
25
41
  #endif
@@ -49,10 +65,16 @@ private final class SKResolveOnce {
49
65
  @objc(SKCrashReporting)
50
66
  class SwissKnifeCrashReporting: NSObject {
51
67
 
68
+ /// Log channel for the one thing the field could never establish from the
69
+ /// outside: whether the native handler armed at all. A crash reporter that
70
+ /// silently does nothing looks identical to one that has nothing to report.
71
+ private static let log = OSLog(
72
+ subsystem: "com.swissknife.rn", category: "CrashReporting"
73
+ )
74
+
52
75
  @objc
53
76
  func start(_ config: NSDictionary) {
54
77
  guard let apiKey = config["apiKey"] as? String, !apiKey.isEmpty else { return }
55
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
56
78
  let serverURL = (config["serverURL"] as? String) ?? ""
57
79
  let environment = (config["environment"] as? String) ?? "production"
58
80
  let release = config["release"] as? String
@@ -96,12 +118,22 @@ class SwissKnifeCrashReporting: NSObject {
96
118
  tracesSampleRate: tracesSampleRate
97
119
  )
98
120
  SKCrashReporting.shared.start(configuration: configuration)
99
- #endif
121
+
122
+ // Deliberately `.info` and unconditional. This one line is the difference
123
+ // between "no crashes happened" and "the crash reporter was never armed" —
124
+ // the two states the field could not tell apart. Grep the device log for
125
+ // `com.swissknife.rn`.
126
+ os_log(
127
+ "native crash handler armed (env %{public}@, serverURL %{public}@)",
128
+ log: Self.log,
129
+ type: .info,
130
+ environment,
131
+ serverURL.isEmpty ? "default" : serverURL
132
+ )
100
133
  }
101
134
 
102
135
  @objc
103
136
  func setUser(_ user: NSDictionary?) {
104
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
105
137
  guard let user else {
106
138
  SKCrashReporting.shared.setUser(nil)
107
139
  return
@@ -113,12 +145,10 @@ class SwissKnifeCrashReporting: NSObject {
113
145
  username: user["username"] as? String
114
146
  )
115
147
  )
116
- #endif
117
148
  }
118
149
 
119
150
  @objc
120
151
  func addBreadcrumb(_ breadcrumb: NSDictionary) {
121
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
122
152
  let level = SKErrorLevel(rawValue: breadcrumb["level"] as? String ?? "info") ?? .info
123
153
  SKCrashReporting.shared.addBreadcrumb(
124
154
  SKBreadcrumb(
@@ -128,14 +158,11 @@ class SwissKnifeCrashReporting: NSObject {
128
158
  data: breadcrumb["data"] as? [String: String]
129
159
  )
130
160
  )
131
- #endif
132
161
  }
133
162
 
134
163
  @objc
135
164
  func setTag(_ key: NSString, value: NSString) {
136
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
137
165
  SKCrashReporting.shared.setTag(key as String, value: value as String)
138
- #endif
139
166
  }
140
167
 
141
168
  // MARK: - Screenshot capture (wave-2 contract C1)
@@ -166,13 +193,9 @@ class SwissKnifeCrashReporting: NSObject {
166
193
  once.resolve(nil)
167
194
  }
168
195
 
169
- #if SWISSKNIFE_VENDORED || canImport(SwissKnifeiOS)
170
196
  DispatchQueue.main.async {
171
197
  once.resolve(SKScreenshot.captureMaskedBase64())
172
198
  }
173
- #else
174
- once.resolve(nil)
175
- #endif
176
199
  }
177
200
 
178
201
  // MARK: - Deliberate native crashes (e2e verification only)
@@ -192,11 +215,29 @@ class SwissKnifeCrashReporting: NSObject {
192
215
  /// Crash the app with SIGSEGV/SIGBUS by writing through a near-NULL
193
216
  /// pointer. Same next-launch recovery path as crashNative(), different
194
217
  /// signal.
218
+ ///
219
+ /// The store must be the ONLY thing that can fault here. The previous
220
+ /// implementation built the pointer with
221
+ /// `UnsafeMutablePointer<Int>(bitPattern: 0x10)!` — that initialiser is
222
+ /// failable purely because 0 is not a valid address, so the `!` is a
223
+ /// force-unwrap that can never actually fail. It still cost us: the
224
+ /// implicit-unwrap trap lives in the same frame as the store, and every
225
+ /// symbolicator (Sentry included) attributed the fault to "Unexpectedly
226
+ /// found nil while unwrapping an Optional value" rather than to the wild
227
+ /// write. A hook that claims "make a segfault" and reports as a nil unwrap
228
+ /// is a hook nobody can trust — the first thing a reader concludes is that
229
+ /// the harness broke before it could stage the crash.
230
+ ///
231
+ /// `unsafeBitCast` removes the Optional from the picture entirely, so the
232
+ /// only instruction that can trap is the store to 0x10 — which surfaces as
233
+ /// EXC_BAD_ACCESS / KERN_INVALID_ADDRESS at 0x10, i.e. what was asked for.
234
+ /// 0x10 rather than 0x0 keeps it a page-zero access without tripping the
235
+ /// "null pointer dereference" special-casing some tools apply to 0x0.
195
236
  @objc
196
237
  func crashNativeSegfault() {
197
238
  DispatchQueue.main.async {
198
- let pointer = UnsafeMutablePointer<Int>(bitPattern: 0x10)!
199
- pointer.pointee = 42
239
+ let pointer = unsafeBitCast(UInt(0x10), to: UnsafeMutableRawPointer.self)
240
+ pointer.storeBytes(of: UInt8(42), toByteOffset: 0, as: UInt8.self)
200
241
  }
201
242
  }
202
243
  }
@@ -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.2.7"
102
+ static let sdkVersionConstant: String = "0.3.0"
103
103
 
104
104
  private static let cacheLock = DispatchQueue(label: "com.swissknife.context.device")
105
105
  private static var cached: DeviceContext?
@@ -21,7 +21,7 @@
21
21
  // Cross-platform
22
22
  // --------------
23
23
  // Network.framework is available on iOS 12+ and macOS 10.14+ — within our
24
- // support floor (iOS 16, macOS 12). No `#if available` gating needed.
24
+ // support floor (iOS 15, macOS 12). No `#if available` gating needed.
25
25
 
26
26
  import Foundation
27
27
  import Network
@@ -407,6 +407,30 @@ public final class SKCrashReporting {
407
407
  self.configuration = configuration
408
408
  self.breadcrumbs = RingBuffer(capacity: configuration.maxBreadcrumbs)
409
409
 
410
+ // Wire the shared backend transport from THIS configuration.
411
+ //
412
+ // `Configuration` carries `apiKey` and `serverURL`, but nothing used
413
+ // them: every send goes IngestClient → BackendHttpClient, and that
414
+ // resolves its credentials from `SwissKnife.identityConfigSnapshot()`
415
+ // instead. A host that only calls `SKCrashReporting.start(...)` —
416
+ // which is the entire public contract of this type — therefore built
417
+ // perfectly good crash reports that could never be sent.
418
+ // `makeRequest` throws `.notConfigured` on an empty apiKey, `flush()`
419
+ // swallows it as best-effort, and the report sits on the durable disk
420
+ // queue for the life of the install. Silent, permanent, and invisible
421
+ // from the outside: detection worked, recovery worked, the report
422
+ // existed, and it went nowhere.
423
+ //
424
+ // `ensureObservabilityBackend` is idempotent (process-wide once-flag)
425
+ // and marks CORE configured only — it never starts the StoreKit
426
+ // observer, so the configureCore / configurePurchases split is
427
+ // preserved. The RN bridge already calls it immediately before this,
428
+ // so that path is unchanged.
429
+ SwissKnife.ensureObservabilityBackend(
430
+ apiKey: configuration.apiKey,
431
+ serverURL: configuration.serverURL.isEmpty ? nil : configuration.serverURL
432
+ )
433
+
410
434
  // Warm the identity cache before anything can build an event, so a
411
435
  // host that logged in BEFORE starting crash reporting is already
412
436
  // attributed. The observer below covers the opposite order.
@@ -48,10 +48,31 @@ internal enum DeviceID {
48
48
  private static var cache: [String: String] = [:]
49
49
  private static let lock = NSLock()
50
50
 
51
+ /// Environment variable that supplies the device ID outright, bypassing
52
+ /// the Keychain entirely.
53
+ ///
54
+ /// Exists for ONE caller: `SKCrashProbe`, the headless helper the live
55
+ /// crash tests spawn. A bare command-line binary has no code-signed
56
+ /// keychain identity, so `SecItemAdd` does not fail — it asks securityd to
57
+ /// prompt, and a prompt nobody can answer blocks the process forever. That
58
+ /// hung roughly three probe launches in five and papered the developer's
59
+ /// screen with keychain dialogs, all of it downstream of a device ID the
60
+ /// probe never actually needed to persist.
61
+ ///
62
+ /// Only ever read here, and only when the variable is present, so an app —
63
+ /// which never sets it — keeps the Keychain-backed path unchanged. It is
64
+ /// deliberately NOT a general override: hosts that want to choose their own
65
+ /// identifier go through `SKAnalytics.setDeviceId(_:)`.
66
+ static let overrideEnvVar = "SWISSKNIFE_DEVICE_ID_OVERRIDE"
67
+
51
68
  /// Production entry point. Returns the persistent device ID, generating
52
69
  /// and storing one on first run.
53
70
  static func get() -> String {
54
- get(service: productionService, account: defaultAccount)
71
+ if let injected = ProcessInfo.processInfo.environment[overrideEnvVar],
72
+ !injected.isEmpty {
73
+ return injected
74
+ }
75
+ return get(service: productionService, account: defaultAccount)
55
76
  }
56
77
 
57
78
  /// Test-friendly overload — allows passing a unique service per test so
@@ -119,6 +119,30 @@ public extension SwissKnife {
119
119
  }
120
120
  }
121
121
 
122
+ /// In-flight `logIn` calls, keyed by the user id they are installing.
123
+ ///
124
+ /// Auth-state listeners fire more than once per launch as a matter of
125
+ /// routine — typically once from cached credentials and again when the
126
+ /// network confirms them — so two `logIn(sameUser)` calls overlapping
127
+ /// is the normal case, not an edge one. Left to race, the second bumps
128
+ /// `identityGeneration`, the first fails its TOCTOU guard, and the host
129
+ /// is handed a `CancellationError` for a login that in fact succeeded:
130
+ /// `[swiss-knife] Identity.logIn failed: ... Swift.CancellationError`
131
+ /// on EVERY launch, with the subject nonetheless attached to every
132
+ /// event and crash report. That was a real field report, and the log
133
+ /// was the only symptom — which is worse than it sounds, because it
134
+ /// trained everyone to ignore identity errors.
135
+ ///
136
+ /// Coalescing removes the race at the source instead of teaching the
137
+ /// guard to forgive it: overlapping calls for the SAME id share one
138
+ /// identify POST and one result, so neither can supersede the other.
139
+ /// Calls for a DIFFERENT id (or a `logOut` / `reset` / `wipe`) still
140
+ /// race, and the generation counter still decides them — that conflict
141
+ /// is genuine and the loser must still be invalidated.
142
+ ///
143
+ /// Guarded by `queue`, like every other piece of state on this type.
144
+ private static var inFlightLogIns: [String: Task<LogInResult, Error>] = [:]
145
+
122
146
  /// Identify this device as a known user. POSTs the
123
147
  /// `(anonymous_id, user_id)` pair to `/api/sdk/users/identify` so
124
148
  /// the backend can merge the anonymous → identified user record,
@@ -129,6 +153,9 @@ public extension SwissKnife {
129
153
  /// The backend call uses a bounded exponential-backoff retry
130
154
  /// (1/2/4s with jitter, cap 3) so transient 5xx doesn't lose the
131
155
  /// identify side effect.
156
+ ///
157
+ /// Concurrent calls for the SAME user id are coalesced onto one
158
+ /// request — see `inFlightLogIns`.
132
159
  @discardableResult
133
160
  public static func logIn(_ userId: String) async throws -> LogInResult {
134
161
  // Gates on CORE, not on the purchase engine. Identity is a core
@@ -139,6 +166,25 @@ public extension SwissKnife {
139
166
  guard SwissKnife.isCoreConfigured else { throw PurchasesError.notConfigured }
140
167
  precondition(!userId.isEmpty, "logIn requires a non-empty userId")
141
168
 
169
+ // Join an identical login already in flight rather than starting a
170
+ // second one that would only race the first. Both callers await the
171
+ // same task, so both observe the same outcome — success or failure.
172
+ let work: Task<LogInResult, Error> = queue.sync {
173
+ if let existing = inFlightLogIns[userId] { return existing }
174
+ let started = Task { try await performLogIn(userId) }
175
+ inFlightLogIns[userId] = started
176
+ return started
177
+ }
178
+ return try await work.value
179
+ }
180
+
181
+ /// The actual login. Only ever entered once per (user id, in-flight
182
+ /// window) — see `inFlightLogIns`.
183
+ private static func performLogIn(_ userId: String) async throws -> LogInResult {
184
+ // Clear the slot on EVERY exit, including the throwing ones: a
185
+ // failed login must not pin its own failure onto later attempts.
186
+ defer { queue.sync { inFlightLogIns.removeValue(forKey: userId) } }
187
+
142
188
  let previous = current
143
189
  let (apiKey, baseURL) = SwissKnife.identityConfigSnapshot()
144
190
  // Bump and capture under the queue — any newer mutation
@@ -295,6 +341,9 @@ public extension SwissKnife {
295
341
  observers.removeAll()
296
342
  network = BackendHttpClientIdentityNetwork()
297
343
  identityGeneration = 0
344
+ // A task left over from a previous test would otherwise be
345
+ // joined by the next one and replay its result.
346
+ inFlightLogIns.removeAll()
298
347
  }
299
348
  }
300
349
 
@@ -471,6 +471,20 @@ internal final class IngestClient: @unchecked Sendable {
471
471
  }
472
472
  if !deadLetterItems.isEmpty {
473
473
  queue.deadLetter(deadLetterItems)
474
+ // Dead-lettering used to be completely silent. A crash report
475
+ // the server rejects for a schema mismatch is indistinguishable
476
+ // from a crash that never happened — same empty dashboard, no
477
+ // error anywhere, and the item is gone from the live queue. Say
478
+ // so, with the server's own reason and the item types, so the
479
+ // next "we get no crashes" investigation starts from a fact.
480
+ os_log(
481
+ "IngestClient dead-lettered %d item(s) rejected by the server: %{public}@ | reasons: %{public}@",
482
+ log: log,
483
+ type: .error,
484
+ deadLetterItems.count,
485
+ deadLetterItems.map { $0.type.rawValue }.joined(separator: ","),
486
+ result.errors.map { $0.error }.joined(separator: " | ")
487
+ )
474
488
  }
475
489
  try queue.remove(ids: Set(batch.map { $0.id }))
476
490
  // If the batch was the full size, there might be more — loop.