@app-swiss-knife/react-native-sdk 0.4.0 → 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 +385 -2
  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 +365 -206
  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 +56 -31
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  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 +345 -44
  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 +27 -6
  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 +27 -6
  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 +2 -0
  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 +18 -5
  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 +2 -0
  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 +18 -5
  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 +12 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +16 -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 +50 -9
  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
@@ -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
  },
@@ -1,3 +1,7 @@
1
+ import {
2
+ captureTelemetryContext,
3
+ currentTelemetryTraceId,
4
+ } from "../internal/telemetry-context";
1
5
  // packages/react-native-sdk/src/modules/crash-reporting.ts
2
6
  //
3
7
  // Sentry-compatible crash reporting SDK for swiss-knife (React Native).
@@ -25,7 +29,7 @@
25
29
  // require new native impls on both platforms + spec.ts + tests, well
26
30
  // beyond Round-D's "wrap-up the audit" scope.
27
31
  //
28
- // Native crash capture (Mach exceptions, signal crashes, ANR, NDK)
32
+ // Native crash capture (iOS signals + NSException, ANR, Android NDK)
29
33
  // already goes through the native `SKCrashReporting` module (see the
30
34
  // `getNativeCrashModule()` branch below) — those native-side captures
31
35
  // ARE on the unified transport. JS-captured errors stay on this fetch
@@ -42,14 +46,18 @@ import { base64ToUint8Array, uploadAttachmentWithRetry } from "./attachments";
42
46
  /**
43
47
  * Optional native module for crash reporting. If the host app has linked
44
48
  * the SwissKnife iOS/Android native crash SDKs, this module delegates
45
- * init/setUser/addBreadcrumb to the native layer — catching Mach exceptions,
46
- * signal crashes (iOS), and NDK native crashes (Android) that JS can't see.
49
+ * init/setUser/addBreadcrumb to the native layer — catching signal crashes and
50
+ * uncaught NSExceptions (iOS) and NDK native crashes (Android) that JS can't
51
+ * see. iOS installs no Mach exception handler.
47
52
  */
48
53
  interface SKCrashReportingNative {
54
+ /**
55
+ * Both bridges read these keys. Telemetry goes to `serverURL`
56
+ * (`<serverURL>/ingest`); there is no separate ingest host.
57
+ */
49
58
  start(config: {
50
59
  apiKey: string;
51
60
  serverURL: string;
52
- ingestURL?: string;
53
61
  environment: string;
54
62
  release: string;
55
63
  }): void;
@@ -146,8 +154,15 @@ export interface CrashReportingConfig {
146
154
  */
147
155
  enableAppStateTracking?: boolean;
148
156
  /**
149
- * Start the NATIVE crash handler (iOS Mach/signal + NSException, Android
150
- * NDK + system ANR) via the native module. Default **true**.
157
+ * Start the NATIVE crash handler via the native module. Default **true**.
158
+ *
159
+ * iOS: `signal()` handlers for SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV and
160
+ * SIGTRAP, the uncaught-NSException handler, and a main-thread hang (ANR)
161
+ * watchdog. There is no Mach exception handler and no alternate signal
162
+ * stack, so a crash that never reaches one of those handlers (a stack
163
+ * overflow, for example) is not reported. Android: uncaught JVM exceptions,
164
+ * an ANR watchdog, and, on Android 11+, NDK native crashes and system ANRs
165
+ * from the previous launch.
151
166
  *
152
167
  * Our native handlers chain (they capture and re-invoke the previous
153
168
  * `NSSetUncaughtExceptionHandler` / `signal()` / Java
@@ -210,6 +225,8 @@ export interface SKParsedFrame {
210
225
  }
211
226
 
212
227
  export interface SKCrashEvent {
228
+ sessionId?: string;
229
+ traceId?: string;
213
230
  eventId: string;
214
231
  timestamp: number;
215
232
  level: "debug" | "info" | "warning" | "error" | "fatal";
@@ -690,7 +707,15 @@ async function readOrMintJsInstallId(): Promise<void> {
690
707
 
691
708
  // MARK: - Pending Queue (memory + best-effort disk mirror)
692
709
 
710
+ const capturedContexts = new WeakMap<SKCrashEvent, Promise<void>>();
711
+
693
712
  function enqueueEvent(event: SKCrashEvent): void {
713
+ event.traceId ??= currentTelemetryTraceId();
714
+ const captured = captureTelemetryContext().then((context) => {
715
+ event.sessionId ??= context.sessionId;
716
+ persistQueue();
717
+ });
718
+ capturedContexts.set(event, captured);
694
719
  _pendingEvents.push(event);
695
720
  if (_pendingEvents.length > MAX_PENDING_EVENTS) {
696
721
  const dropped = _pendingEvents.splice(
@@ -2018,6 +2043,22 @@ function installConsoleBreadcrumbs(): void {
2018
2043
 
2019
2044
  export const CrashReporting = {
2020
2045
  init(config: CrashReportingConfig): void {
2046
+ // An empty key (typically a build-time env var that was not set) can
2047
+ // never authenticate. Same rule as `configure()` (internal/config.ts
2048
+ // assertApiKey), but logged instead of thrown: `init` usually runs in
2049
+ // module scope, where a throw keeps the app from booting. Nothing is
2050
+ // installed and the native crash module is not started, so the native
2051
+ // layer is not wired with the empty key and a later `init` with the real
2052
+ // key works.
2053
+ const apiKey: unknown = config?.apiKey;
2054
+ if (typeof apiKey !== "string" || apiKey.trim() === "") {
2055
+ console.error(
2056
+ `[SwissKnife CrashReporting] init requires a non-empty apiKey (got ${
2057
+ typeof apiKey === "string" ? JSON.stringify(apiKey) : String(apiKey)
2058
+ }); crash reporting is off.`
2059
+ );
2060
+ return;
2061
+ }
2021
2062
  // Defaults keep today's behaviour byte-for-byte: every handler is on
2022
2063
  // unless the host explicitly opts out. The opt-outs exist for apps whose
2023
2064
  // incumbent reporter owns a given global — see each field's doc comment
@@ -2054,8 +2095,8 @@ export const CrashReporting = {
2054
2095
  if (_config.enableAppStateTracking) installAppStateListener();
2055
2096
 
2056
2097
  // Initialize native crash handler if the native module is linked.
2057
- // This catches Mach exceptions + signal crashes (iOS) and NDK native
2058
- // crashes + system ANRs (Android) that pure JS cannot observe.
2098
+ // This catches signal crashes + uncaught NSExceptions (iOS) and NDK
2099
+ // native crashes + system ANRs (Android) that pure JS cannot observe.
2059
2100
  const nativeMod = _config.enableNativeCrashHandler
2060
2101
  ? getNativeCrashModule()
2061
2102
  : null;
@@ -2064,7 +2105,6 @@ export const CrashReporting = {
2064
2105
  nativeMod.start({
2065
2106
  apiKey: config.apiKey,
2066
2107
  serverURL: config.serverURL || "",
2067
- ingestURL: (config as { ingestURL?: string }).ingestURL,
2068
2108
  environment: config.environment || "production",
2069
2109
  release: config.release || "",
2070
2110
  });
@@ -2323,6 +2363,7 @@ export const CrashReporting = {
2323
2363
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
2324
2364
  // - rejects `user: null` (schema marks `user` optional, not nullable)
2325
2365
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
2366
+ await Promise.all(batch.map((event) => capturedContexts.get(event)));
2326
2367
  const installId = resolveInstallId();
2327
2368
  const serialized = batch.map((e) => {
2328
2369
  const { user: builtUser, ...rest } = e;
@@ -1,6 +1,6 @@
1
1
  // packages/react-native-sdk/src/modules/log.ts
2
2
  //
3
- // Wave 4 — central log wrapper for the JS layer. Mirrors the iOS
3
+ // Central log wrapper for the JS layer. Mirrors the iOS
4
4
  // `SKLog` (Swift) and Android `SKLog` (Kotlin) abstractions. JS-side
5
5
  // is much smaller because RN modules already lean on `console.warn`
6
6
  // for the rare diagnostic that can't be routed through native — but