@app-swiss-knife/react-native-sdk 0.3.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/CHANGELOG.md +465 -0
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +641 -208
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +69 -35
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +531 -100
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +353 -31
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +353 -31
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +3 -1
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +50 -12
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +3 -1
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +50 -12
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +13 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +18 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +476 -67
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
package/src/identity.ts CHANGED
@@ -1,19 +1,16 @@
1
1
  // packages/react-native-sdk/src/identity.ts
2
2
  //
3
- // Wave 1 — unified `Identity` JS surface. Mirror of `SwissKnife.Identity`
4
- // on iOS (Swift) and `com.appswissknife.identity.Identity` on Android
5
- // (Kotlin). All logic lives natively — this module is a thin
6
- // passthrough.
3
+ // The `Identity` JS surface. Mirror of `SwissKnife.Identity` on iOS (Swift)
4
+ // and `com.appswissknife.identity.Identity` on Android (Kotlin). All logic
5
+ // lives natively — this module is a thin passthrough.
7
6
  //
8
7
  // Why JS doesn't keep its own state
9
8
  // ---------------------------------
10
- // Before Wave 1, `modules/analytics.ts` kept a JS-local `_userId` that
11
- // drifted from the native state. After `Purchases.logIn("u_42")`, an
12
- // immediate `Analytics.track(...)` emitted with `user_id: ""` because
13
- // the JS module never heard about the new user id. The fix is to make
14
- // native the single source of truth and have JS derive `user_id` from
15
- // the native `Identity.current()` snapshot at event-build time. See
16
- // `modules/analytics.ts` for that derivation.
9
+ // Native is the single source of truth for who the user is. A JS-local copy
10
+ // would drift from it: an `Analytics.track(...)` right after
11
+ // `Identity.logIn("u_42")` must already carry `u_42`, so `modules/analytics.ts`
12
+ // derives `user_id` from the native `Identity.current()` snapshot at
13
+ // event-build time instead of from any JS state.
17
14
  //
18
15
  // Observers
19
16
  // ---------
@@ -25,6 +22,7 @@
25
22
  // rebinding). When we need that, add a `Purchases-IdentityChanged`
26
23
  // event to the native event emitter and subscribe here.
27
24
 
25
+ import { notifyExplicitLogout } from "./modules/notifications";
28
26
  import { getNativeModule } from "./native/module";
29
27
  import type { IdentityChange, IdentitySnapshot, LogInResult } from "./types";
30
28
 
@@ -147,6 +145,7 @@ export const Identity = {
147
145
  async logOut(): Promise<void> {
148
146
  lastLogIn = null;
149
147
  await getNativeModule().identityLogOut();
148
+ notifyExplicitLogout();
150
149
  await snapshotAndNotify("logOut");
151
150
  },
152
151
 
@@ -157,6 +156,7 @@ export const Identity = {
157
156
  async reset(): Promise<void> {
158
157
  lastLogIn = null;
159
158
  await getNativeModule().identityReset();
159
+ notifyExplicitLogout();
160
160
  await snapshotAndNotify("reset");
161
161
  },
162
162
 
@@ -167,6 +167,7 @@ export const Identity = {
167
167
  async wipe(): Promise<void> {
168
168
  lastLogIn = null;
169
169
  await getNativeModule().identityWipe();
170
+ notifyExplicitLogout();
170
171
  await snapshotAndNotify("wipe");
171
172
  },
172
173
 
package/src/index.ts CHANGED
@@ -25,11 +25,11 @@ export { Attributes } from "./attributes";
25
25
 
26
26
  // Public type/enum/error surface (CustomerInfo, PurchasesOfferings,
27
27
  // PURCHASES_ERROR_CODE, LOG_LEVEL, ConfigureOptions, the enums,
28
- // PurchasesError, etc.) — defined in ./types (Phase 7: own definitions, no RC
29
- // dependency).
28
+ // PurchasesError, etc.) — defined in ./types, this package's own definitions
29
+ // (no RevenueCat dependency).
30
30
  export * from "./types";
31
31
 
32
- // Wave 1 — unified Identity surface. Routes through native
32
+ // Identity. Routes through native
33
33
  // `SwissKnife.Identity` (iOS) / `com.appswissknife.identity.Identity`
34
34
  // (Android). Decoupled from analytics: `Identity.logIn(...)` does NOT
35
35
  // auto-emit a `$identify` event; call `Analytics.identify(...)`
@@ -37,7 +37,7 @@ export * from "./types";
37
37
  export { Identity } from "./identity";
38
38
  export type { IdentitySnapshot, IdentityChange } from "./identity";
39
39
 
40
- // Wave 2 — Attribution. Routes through native
40
+ // Attribution. Routes through native
41
41
  // `SwissKnife.Attribution` (iOS) / `com.appswissknife.attribution.Attribution`
42
42
  // (Android). Native owns the ATT prompt orchestration, IDFA /
43
43
  // AdvertisingId / InstallReferrer collection, and the disk-backed
@@ -61,6 +61,8 @@ export type {
61
61
  SKCrashEvent,
62
62
  SKCrashBreadcrumb,
63
63
  SKCrashUser,
64
+ SKCrashScope,
65
+ SKCaptureExceptionOptions,
64
66
  } from "./modules/crash-reporting";
65
67
  export { Performance } from "./modules/performance";
66
68
  export type {
@@ -69,3 +71,15 @@ export type {
69
71
  SKSpan,
70
72
  SKStallMeasurements,
71
73
  } from "./modules/performance";
74
+
75
+ // Push notifications (swiss-push v1). Native mode (SDK owns the OS token) and
76
+ // manual mode (`expo-notifications` / RNFirebase hand us the token) share one
77
+ // API — see README "Push notifications".
78
+ export { Notifications } from "./modules/notifications";
79
+ export type {
80
+ PushProvider,
81
+ PushPayload,
82
+ PermissionStatus as PushPermissionStatus,
83
+ NotificationOpen as PushNotificationOpen,
84
+ RegisterDeviceTokenOptions as PushRegisterOptions,
85
+ } from "./modules/notifications";
@@ -31,7 +31,56 @@ import type {
31
31
 
32
32
  let configured = false;
33
33
  let configuredApiKey: string | null = null;
34
+ let configuredServerURL: string | null = null;
34
35
  let coreConfigured = false;
36
+ /**
37
+ * Why the last native configure failed, if it did. `throwIfNotConfigured`
38
+ * attaches it as the `cause` of the error it throws, so a purchase made after
39
+ * a failed configure names the real reason instead of "not configured".
40
+ */
41
+ let lastConfigureError: unknown = null;
42
+ /**
43
+ * Bumped by every configure call. A native rejection only resets the JS state
44
+ * when no later configure has replaced it — a slow failure of an old call must
45
+ * not undo a newer one that succeeded.
46
+ */
47
+ let configureGeneration = 0;
48
+
49
+ /**
50
+ * Reject an empty or whitespace-only API key synchronously, before any state
51
+ * changes. The native bridges reject an empty key asynchronously, which the old
52
+ * fire-and-forget call turned into an unhandled rejection while JS went on to
53
+ * report the SDK as configured. Typical cause: a missing env var at build time.
54
+ */
55
+ function assertApiKey(apiKey: unknown, entryPoint: string): asserts apiKey is string {
56
+ if (typeof apiKey !== "string" || apiKey.trim() === "") {
57
+ throw new Error(
58
+ `${entryPoint} requires a non-empty apiKey (got ${
59
+ typeof apiKey === "string" ? JSON.stringify(apiKey) : String(apiKey)
60
+ }).`
61
+ );
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Observe a native configure promise without awaiting it: `configure` stays
67
+ * synchronous (RC parity), but a rejection is logged, kept for
68
+ * {@link throwIfNotConfigured}, and undoes the JS state `onFailure` names so the
69
+ * next configure with the same key retries instead of returning early.
70
+ */
71
+ function observeNativeConfigure(
72
+ result: Promise<void> | void,
73
+ entryPoint: string,
74
+ onFailure: () => void
75
+ ): void {
76
+ const generation = configureGeneration;
77
+ Promise.resolve(result).catch((error: unknown) => {
78
+ if (generation !== configureGeneration) return;
79
+ onFailure();
80
+ lastConfigureError = error;
81
+ console.warn(`[SwissKnife] native ${entryPoint} failed:`, error);
82
+ });
83
+ }
35
84
 
36
85
  /**
37
86
  * Read a boolean off the native module without ever letting a missing native
@@ -60,12 +109,31 @@ export function nativeBoolean(
60
109
  }
61
110
  }
62
111
 
112
+ /**
113
+ * The API key + backend URL this process was configured with, for the few JS
114
+ * modules that talk to the backend directly (push manual registration).
115
+ * `serverURL` is "" when the default host applies. Null until something
116
+ * configured — `configure`, `configureCore` or `Analytics.init`.
117
+ */
118
+ export function getServerConfig(): { apiKey: string; serverURL: string } | null {
119
+ return configuredApiKey ? { apiKey: configuredApiKey, serverURL: configuredServerURL ?? "" } : null;
120
+ }
121
+
122
+ /** Record key + URL for consumers of {@link getServerConfig}. */
123
+ export function recordServerConfig(apiKey: string, serverURL?: string | null): void {
124
+ configuredApiKey = apiKey;
125
+ configuredServerURL = serverURL ?? "";
126
+ }
127
+
63
128
  /**
64
129
  * Configure the SDK. Must be called before any other method. Calling again
65
- * with the same API key is a no-op (matches the common "configure once" guard);
66
- * the native layer owns full reconfiguration.
130
+ * with the same API key is a no-op (matches the common "configure once" guard)
131
+ * unless the native configure failed, in which case it retries; the native
132
+ * layer owns full reconfiguration. Throws synchronously on an empty or
133
+ * whitespace-only `apiKey`.
67
134
  */
68
135
  export function configure(options: ConfigureOptions): void {
136
+ assertApiKey(options?.apiKey, "configure");
69
137
  if (configured && configuredApiKey === options.apiKey) return;
70
138
  const native = getNativeModule();
71
139
  const nativeOptions: NativeConfigureOptions = {
@@ -85,11 +153,20 @@ export function configure(options: ConfigureOptions): void {
85
153
  sendInstallOnFirstLaunch: options.sendInstallOnFirstLaunch,
86
154
  logLevel: options.logLevel,
87
155
  };
88
- // Fire-and-forget: native configure resolves async but RC's configure is sync.
89
- void native.configure(nativeOptions);
156
+ // Not awaited: native configure resolves async but RC's configure is sync.
157
+ // A rejection is observed, never left unhandled — see observeNativeConfigure.
158
+ const result = native.configure(nativeOptions);
159
+ configureGeneration += 1;
160
+ lastConfigureError = null;
90
161
  configured = true;
91
162
  coreConfigured = true;
92
- configuredApiKey = options.apiKey;
163
+ recordServerConfig(options.apiKey, options.proxyURL);
164
+ observeNativeConfigure(result, "configure", () => {
165
+ configured = false;
166
+ coreConfigured = false;
167
+ configuredApiKey = null;
168
+ configuredServerURL = null;
169
+ });
93
170
  }
94
171
 
95
172
  /**
@@ -107,6 +184,7 @@ export function configure(options: ConfigureOptions): void {
107
184
  * `appUserID`, an attribution configuration, or a log level up front.
108
185
  */
109
186
  export function configureCore(options: ConfigureOptions): void {
187
+ assertApiKey(options?.apiKey, "configureCore");
110
188
  if (coreConfigured && configuredApiKey === options.apiKey) return;
111
189
  const native = getNativeModule();
112
190
  const nativeOptions: NativeConfigureOptions = {
@@ -121,9 +199,18 @@ export function configureCore(options: ConfigureOptions): void {
121
199
  sendInstallOnFirstLaunch: options.sendInstallOnFirstLaunch,
122
200
  logLevel: options.logLevel,
123
201
  };
124
- void native.configureCore(nativeOptions);
202
+ const result = native.configureCore(nativeOptions);
203
+ configureGeneration += 1;
204
+ lastConfigureError = null;
125
205
  coreConfigured = true;
126
- configuredApiKey = options.apiKey;
206
+ recordServerConfig(options.apiKey, options.proxyURL);
207
+ // The purchase engine flag is left alone: configureCore never set it, and a
208
+ // store configured earlier is still configured natively.
209
+ observeNativeConfigure(result, "configureCore", () => {
210
+ coreConfigured = false;
211
+ configuredApiKey = null;
212
+ configuredServerURL = null;
213
+ });
127
214
  }
128
215
 
129
216
  /**
@@ -187,8 +274,23 @@ export function setLogLevel(level: LOG_LEVEL): Promise<void> {
187
274
  */
188
275
  export function throwIfNotConfigured(): void {
189
276
  if (!configured) {
190
- throw new UninitializedPurchasesError();
277
+ if (lastConfigureError == null) throw new UninitializedPurchasesError();
278
+ const error = new UninitializedPurchasesError(
279
+ "Purchases is not configured: the native configure call failed (" +
280
+ describe(lastConfigureError) +
281
+ "). Fix the cause and call Purchases.configure() again."
282
+ );
283
+ error.cause = lastConfigureError;
284
+ throw error;
285
+ }
286
+ }
287
+
288
+ function describe(error: unknown): string {
289
+ if (error instanceof Error) return error.message;
290
+ if (error && typeof error === "object" && "message" in error) {
291
+ return String((error as { message: unknown }).message);
191
292
  }
293
+ return String(error);
192
294
  }
193
295
 
194
296
  /**
@@ -230,4 +332,7 @@ export function resetConfigForTests(): void {
230
332
  configured = false;
231
333
  coreConfigured = false;
232
334
  configuredApiKey = null;
335
+ configuredServerURL = null;
336
+ lastConfigureError = null;
337
+ configureGeneration += 1;
233
338
  }
@@ -0,0 +1,76 @@
1
+ /** Capture once, before a queued event can outlive its user or session. */
2
+ export interface TelemetryContext {
3
+ userId?: string;
4
+ installId?: string;
5
+ sessionId?: string;
6
+ }
7
+ interface Bridge {
8
+ identityCurrent?: () => Promise<{
9
+ userId?: string | null;
10
+ anonymousId?: string | null;
11
+ }>;
12
+ sessionCurrent?: () => Promise<{ id: string }>;
13
+ }
14
+ let override: Bridge | null | undefined;
15
+ function bridge(): Bridge | null {
16
+ if (override !== undefined) return override;
17
+ try {
18
+ // Optional native bridge: JS-only instrumentation remains usable without it.
19
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
20
+ return (
21
+ require("../native/module") as { getNativeModule(): Bridge }
22
+ ).getNativeModule();
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+ export function captureTelemetryContext(): Promise<TelemetryContext> {
28
+ const native = bridge();
29
+ if (!native) return Promise.resolve({});
30
+ const result: TelemetryContext = {};
31
+ // Invoke both bridge reads now, rather than in a later flush microtask.
32
+ let identity: Promise<unknown> = Promise.resolve();
33
+ let session: Promise<unknown> = Promise.resolve();
34
+ try {
35
+ identity =
36
+ native.identityCurrent?.().then((s) => {
37
+ result.userId = s.userId ?? "";
38
+ result.installId = s.anonymousId ?? "";
39
+ }) ?? identity;
40
+ } catch {
41
+ /* Missing information stays unknown. */
42
+ }
43
+ try {
44
+ session =
45
+ native.sessionCurrent?.().then((s) => {
46
+ result.sessionId = s.id;
47
+ }) ?? session;
48
+ } catch {
49
+ /* Never invent a second session id. */
50
+ }
51
+ return new Promise((resolve) => {
52
+ let finished = false;
53
+ const finish = () => {
54
+ if (finished) return;
55
+ finished = true;
56
+ clearTimeout(timer);
57
+ resolve({ ...result });
58
+ };
59
+ const timer = setTimeout(finish, 250);
60
+ void Promise.allSettled([identity, session]).then(finish);
61
+ });
62
+ }
63
+ /** Internal seam; never exported by the SDK public entry point. */
64
+ export function setTelemetryBridgeForTests(
65
+ value: Bridge | null | undefined
66
+ ): void {
67
+ override = value;
68
+ }
69
+
70
+ let traceReader: (() => string | undefined) | undefined;
71
+ export function setTelemetryTraceReader(read: () => string | undefined): void {
72
+ traceReader = read;
73
+ }
74
+ export function currentTelemetryTraceId(): string | undefined {
75
+ return traceReader?.();
76
+ }
@@ -5,8 +5,7 @@
5
5
  //
6
6
  // ## Architecture: thin pass-through to native
7
7
  //
8
- // Phase 2.3 of the RC rip-and-replace makes the RN Analytics layer a thin
9
- // pass-through to the native event queue:
8
+ // The RN Analytics layer is a thin pass-through to the native event queue:
10
9
  //
11
10
  // - **JS owns the payload shape** — `event_id`, `device_id`, super
12
11
  // properties, timed-event duration, identify merging, session id, user
@@ -66,6 +65,7 @@
66
65
  // constant.
67
66
 
68
67
  import { getNativeModule } from "../native/module";
68
+ import { recordServerConfig } from "../internal/config";
69
69
 
70
70
  // MARK: - Types
71
71
 
@@ -90,18 +90,16 @@ export interface SKEvent {
90
90
  event_properties?: Record<string, unknown>;
91
91
  user_id?: string;
92
92
  /**
93
- * Wave 1: derived from the native Identity snapshot at event-build
94
- * time. Carries the unified `$SKAnonymousID:` prefix on both iOS and
95
- * Android.
93
+ * Derived from the native Identity snapshot at event-build time. Carries
94
+ * the `$SKAnonymousID:` prefix on both iOS and Android.
96
95
  */
97
96
  anonymous_id?: string;
98
97
  device_id?: string;
99
98
  /**
100
- * Post-#136 audit: now a UUID string sourced from the native
101
- * `Session.shared` primitive (was `Date.now()` number which diverged
102
- * from envelope-level `ContextSnapshot.session_id`). Optional so
103
- * synthetic events constructed by callers (tests / overrides) can
104
- * still omit it without a typecheck error.
99
+ * A UUID string from the native `Session.shared` primitive, the same id
100
+ * the envelope-level `ContextSnapshot.session_id` carries. Optional so
101
+ * synthetic events constructed by callers (tests / overrides) can still
102
+ * omit it without a typecheck error.
105
103
  */
106
104
  session_id?: string;
107
105
  time?: number;
@@ -212,9 +210,7 @@ let _superProperties: Record<string, unknown> = {};
212
210
  let _timedEvents: Record<string, number> = {};
213
211
  let _flushTimer: ReturnType<typeof setInterval> | null = null;
214
212
 
215
- // Post-#136 audit: `generateUUID` used to live inline here. It has been
216
- // centralized in `./ids.ts` so future callers can import rather than
217
- // copy-paste.
213
+ // `generateUUID` lives in `./ids.ts`, shared with the other modules.
218
214
  import { generateUUID } from "./ids";
219
215
 
220
216
  /**
@@ -317,12 +313,10 @@ function sendToNativeFireAndForget(event: SKEvent): void {
317
313
  * Awaits the native device-id promise when the cached id is still null.
318
314
  * The returned event is ready to hand to the native bridge.
319
315
  *
320
- * Wave 1: `user_id` is derived from the native `Identity.current()`
321
- * snapshot at event-build time — NOT from the JS-local `_userId` cache
322
- * that historically drifted from native. Pre-Wave-1: calling
323
- * `Purchases.logIn("u_42")` and immediately `Analytics.track(...)`
324
- * emitted with `user_id: ""` because the JS-side `setUserId(...)` was
325
- * never called. Now native is the single source of truth.
316
+ * `user_id` is derived from the native `Identity.current()` snapshot at
317
+ * event-build time, not from the JS-local `_userId` cache, so an
318
+ * `Analytics.track(...)` right after `Identity.logIn("u_42")` already
319
+ * carries `u_42`. Native is the single source of truth for identity.
326
320
  */
327
321
  async function buildEvent(
328
322
  eventType: string,
@@ -349,16 +343,15 @@ async function buildEvent(
349
343
 
350
344
  // Resolve session_id from the canonical native primitive. Same lazy
351
345
  // pattern as device_id — synchronous when cached, otherwise await the
352
- // in-flight promise kicked off in init(). Pre-audit this was a JS-side
353
- // `Date.now()` which diverged from envelope-level
354
- // ContextSnapshot.session_id.
346
+ // in-flight promise kicked off in init() — so it matches the
347
+ // envelope-level ContextSnapshot.session_id.
355
348
  let sessionId = _sessionId;
356
349
  if (sessionId == null) {
357
350
  if (_sessionIdPromise == null) loadSessionIdFromNative();
358
351
  sessionId = (await _sessionIdPromise) ?? String(Date.now());
359
352
  }
360
353
 
361
- // Wave 1: derive user_id from the native Identity snapshot. Fall back
354
+ // Derive user_id from the native Identity snapshot. Fall back
362
355
  // to the JS-local `_userId` only when the native call throws (e.g.
363
356
  // test harness without the Identity bridge methods stubbed) — that
364
357
  // preserves the legacy `Analytics.setUserId(...)` test seam.
@@ -394,8 +387,8 @@ async function buildEvent(
394
387
  ...(Object.keys(_groups).length > 0 ? { groups: { ..._groups } } : {}),
395
388
  ...overrides,
396
389
  };
397
- // Stamp anonymous_id when we resolved it from native — Wave 1's
398
- // unified $SKAnonymousID: prefix flows through here.
390
+ // Stamp anonymous_id when we resolved it from native; it carries the
391
+ // $SKAnonymousID: prefix.
399
392
  if (anonymousId !== undefined) {
400
393
  (event as SKEvent & { anonymous_id?: string }).anonymous_id = anonymousId;
401
394
  }
@@ -421,7 +414,7 @@ export const Analytics = {
421
414
  ...config,
422
415
  };
423
416
  // Reset cached session id so the next track() refetches from the
424
- // canonical native primitive. Pre-audit this was `Date.now()`.
417
+ // canonical native primitive.
425
418
  _sessionId = null;
426
419
  _sessionIdPromise = null;
427
420
 
@@ -435,6 +428,7 @@ export const Analytics = {
435
428
  // (there used to be, and it made `Analytics.init({ apiKey })` — no
436
429
  // serverURL — a silent no-op on both platforms).
437
430
  // Fire-and-forget: events queue natively regardless and flush once wired.
431
+ recordServerConfig(config.apiKey, config.serverURL);
438
432
  try {
439
433
  void getNativeModule()
440
434
  .configureObservability(config.apiKey, config.serverURL ?? "")
@@ -530,9 +524,8 @@ export const Analytics = {
530
524
  /**
531
525
  * Current session id from the native `Session.shared` primitive.
532
526
  * Returns `null` until the first `track()` (or explicit await on
533
- * `init()`'s session warm) has resolved the native call. Pre-audit
534
- * this returned a `Date.now()` number; the new return type is `string |
535
- * null` reflecting both the native UUID format and the lazy resolution.
527
+ * `init()`'s session warm) has resolved the native call. The id is the
528
+ * native session UUID.
536
529
  */
537
530
  getSessionId(): string | null {
538
531
  return _sessionId;
@@ -611,10 +604,8 @@ export const Analytics = {
611
604
  _superProperties = {};
612
605
  _timedEvents = {};
613
606
  // Drop the cached session id so the next track() refetches from the
614
- // native primitive (`Session.shared`). Pre-audit this was set to
615
- // `Date.now()` here, which fragmented the analytics timeline at
616
- // every reset because the JS-side number drifted from the native
617
- // session UUID stamped on the envelope.
607
+ // native primitive (`Session.shared`), the same session UUID that is
608
+ // stamped on the envelope.
618
609
  _sessionId = null;
619
610
  _sessionIdPromise = null;
620
611
  },