@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
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ import { captureTelemetryContext, currentTelemetryTraceId } from "../internal/telemetry-context.js";
3
4
  // packages/react-native-sdk/src/modules/crash-reporting.ts
4
5
  //
5
6
  // Sentry-compatible crash reporting SDK for swiss-knife (React Native).
@@ -27,7 +28,7 @@
27
28
  // require new native impls on both platforms + spec.ts + tests, well
28
29
  // beyond Round-D's "wrap-up the audit" scope.
29
30
  //
30
- // Native crash capture (Mach exceptions, signal crashes, ANR, NDK)
31
+ // Native crash capture (iOS signals + NSException, ANR, Android NDK)
31
32
  // already goes through the native `SKCrashReporting` module (see the
32
33
  // `getNativeCrashModule()` branch below) — those native-side captures
33
34
  // ARE on the unified transport. JS-captured errors stay on this fetch
@@ -43,8 +44,9 @@ import { base64ToUint8Array, uploadAttachmentWithRetry } from "./attachments.js"
43
44
  /**
44
45
  * Optional native module for crash reporting. If the host app has linked
45
46
  * the SwissKnife iOS/Android native crash SDKs, this module delegates
46
- * init/setUser/addBreadcrumb to the native layer — catching Mach exceptions,
47
- * signal crashes (iOS), and NDK native crashes (Android) that JS can't see.
47
+ * init/setUser/addBreadcrumb to the native layer — catching signal crashes and
48
+ * uncaught NSExceptions (iOS) and NDK native crashes (Android) that JS can't
49
+ * see. iOS installs no Mach exception handler.
48
50
  */
49
51
 
50
52
  /** Test seam (same shape as `_screenshotCaptureOverride`): `undefined` =
@@ -91,7 +93,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
91
93
  const DEFAULT_MAX_CACHE_ITEMS = 30;
92
94
  const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
93
95
  const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
96
+ /** Started/ended session events waiting on a retry (see Session Outbox). */
97
+ const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
98
+ /** Cap on queued session events — drop-oldest beyond this. */
99
+ const MAX_PENDING_SESSIONS = 50;
94
100
  const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
101
+ /** JS-side install id, only for apps without the native Identity bridge. */
102
+ const INSTALL_ID_KEY = "@swissknife:crash:install_id";
95
103
 
96
104
  // MARK: - Stack Trace Parsing
97
105
 
@@ -171,6 +179,8 @@ let _breadcrumbs = new RingBuffer(100);
171
179
  let _tags = {};
172
180
  let _extra = {};
173
181
  let _user = null;
182
+ /** Scope-level fingerprint (configureScope → setFingerprint). */
183
+ let _fingerprint = null;
174
184
  let _pendingEvents = [];
175
185
  /**
176
186
  * Events handed to an in-flight POST: already out of `_pendingEvents`, not
@@ -236,8 +246,20 @@ let _screenshotCaptureOverride;
236
246
  // `Identity.current()` also carries an `anonymousId`, and stamping it into
237
247
  // `user.id` would make "affected users" non-zero for every app that never
238
248
  // logs in. That both inflates the number and diverges from Analytics, whose
239
- // `user_id` is the identified subject only. The anonymous id already travels
240
- // separately on the ingest envelope. Only `userId` is used here.
249
+ // `user_id` is the identified subject only. The anonymous id travels
250
+ // separately, as the wire event's `installId` (see below) — the server counts
251
+ // affected users by user id, else install id, without conflating the two.
252
+
253
+ // ## installId — the stable per-install id
254
+ //
255
+ // Most crashes have no identified subject, so the server counts affected
256
+ // users by `installId` when `user.id` is absent. It is the Identity bridge's
257
+ // `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
258
+ // carry on their ingest envelope and `app_users.anonymous_id` stores, so the
259
+ // dashboard can link an anonymous install to its profile). Apps without the
260
+ // native Identity bridge get a random id persisted in AsyncStorage; without
261
+ // AsyncStorage no installId is sent at all, because a per-launch id would
262
+ // count every relaunch as a new user.
241
263
 
242
264
  /**
243
265
  * Last resolved identified subject id from the native Identity bridge.
@@ -246,6 +268,14 @@ let _screenshotCaptureOverride;
246
268
  * stamped, which is exactly today's behaviour for apps that never log in.
247
269
  */
248
270
  let _identityUserId = null;
271
+ /** Last resolved `Identity.current().anonymousId` (stable per install). */
272
+ let _identityAnonymousId = null;
273
+ /** AsyncStorage-persisted install id; used only when no Identity bridge. */
274
+ let _jsInstallId = null;
275
+ /** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
276
+ let _jsInstallIdLoad = null;
277
+ /** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
278
+ let _jsInstallIdSettled = false;
249
279
  /** In-flight read, so N events in a burst share one bridge hop. */
250
280
  let _identityRefresh = null;
251
281
  /** Monotonic read counter — a superseded read must not clobber a newer one. */
@@ -259,6 +289,8 @@ let _identityGeneration = 0;
259
289
  */
260
290
  let _identityResolverOverride;
261
291
 
292
+ /** The fields of the native `Identity.current()` snapshot this module reads. */
293
+
262
294
  /** Budget for the send-time identity re-resolve. Kept well under
263
295
  * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
264
296
  * one chance to deliver before the process dies. */
@@ -306,6 +338,11 @@ function startIdentityRead() {
306
338
  if (generation !== _identityGeneration) return; // superseded
307
339
  const userId = snapshot?.userId;
308
340
  _identityUserId = typeof userId === "string" && userId.length > 0 ? userId : null;
341
+ // Never blanked by a later empty answer: the id is per install.
342
+ const anonymousId = snapshot?.anonymousId;
343
+ if (typeof anonymousId === "string" && anonymousId.length > 0) {
344
+ _identityAnonymousId = anonymousId;
345
+ }
309
346
  } catch {
310
347
  // Bridge hiccup — keep the last known subject.
311
348
  } finally {
@@ -384,9 +421,71 @@ function mergeIdentityInto(user) {
384
421
  };
385
422
  }
386
423
 
424
+ /** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
425
+ function withTimeout(p, ms) {
426
+ return new Promise(resolve => {
427
+ const timer = setTimeout(resolve, ms);
428
+ void p.then(() => {
429
+ clearTimeout(timer);
430
+ resolve();
431
+ }, () => {
432
+ clearTimeout(timer);
433
+ resolve();
434
+ });
435
+ });
436
+ }
437
+
438
+ /**
439
+ * The install id to stamp on outgoing events, or undefined when none is
440
+ * known. The Identity bridge's anonymous id wins; the JS-persisted id is used
441
+ * only when there is no bridge at all — mixing the two on one device (e.g. a
442
+ * slow bridge read) would count that device twice.
443
+ */
444
+ function resolveInstallId() {
445
+ if (_identityAnonymousId) return _identityAnonymousId;
446
+ if (getIdentityResolver() !== null) return undefined;
447
+ return _jsInstallId ?? undefined;
448
+ }
449
+
450
+ /**
451
+ * Load (or mint and persist) the JS-side install id. Only for apps without
452
+ * the Identity bridge; a no-op without AsyncStorage. Never throws.
453
+ */
454
+ function loadJsInstallId() {
455
+ _jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
456
+ _jsInstallIdSettled = true;
457
+ });
458
+ return _jsInstallIdLoad;
459
+ }
460
+ async function readOrMintJsInstallId() {
461
+ if (_jsInstallId || getIdentityResolver() !== null) return;
462
+ const storage = getOfflineStorage();
463
+ if (!storage) return;
464
+ try {
465
+ const stored = await storage.getItem(INSTALL_ID_KEY);
466
+ if (stored) {
467
+ _jsInstallId = stored;
468
+ return;
469
+ }
470
+ const minted = generateUUID();
471
+ await storage.setItem(INSTALL_ID_KEY, minted);
472
+ // Only use an id that made it to disk — see the module note above.
473
+ _jsInstallId = minted;
474
+ } catch {
475
+ // Storage hiccup: send no installId rather than a per-launch one.
476
+ }
477
+ }
478
+
387
479
  // MARK: - Pending Queue (memory + best-effort disk mirror)
388
480
 
481
+ const capturedContexts = new WeakMap();
389
482
  function enqueueEvent(event) {
483
+ event.traceId ??= currentTelemetryTraceId();
484
+ const captured = captureTelemetryContext().then(context => {
485
+ event.sessionId ??= context.sessionId;
486
+ persistQueue();
487
+ });
488
+ capturedContexts.set(event, captured);
390
489
  _pendingEvents.push(event);
391
490
  if (_pendingEvents.length > MAX_PENDING_EVENTS) {
392
491
  const dropped = _pendingEvents.splice(0, _pendingEvents.length - MAX_PENDING_EVENTS);
@@ -648,6 +747,21 @@ function clearAmbiguousStreak() {
648
747
 
649
748
  // MARK: - Session Tracking
650
749
 
750
+ /**
751
+ * Request headers for every `/api/sdk/errors/*` call. Carries the install id
752
+ * (when known) so the server's per-device rate limit buckets this install
753
+ * separately from every other device of the app.
754
+ */
755
+ function requestHeaders(apiKey) {
756
+ const installId = resolveInstallId();
757
+ return {
758
+ "Content-Type": "application/json",
759
+ "X-API-Key": apiKey,
760
+ ...(installId ? {
761
+ "X-SK-Install-Id": installId
762
+ } : {})
763
+ };
764
+ }
651
765
  function buildSessionPayload(status) {
652
766
  const duration = _sessionStartTime !== null ? (Date.now() - _sessionStartTime) / 1000 : 0;
653
767
  const contexts = getStaticContexts();
@@ -675,8 +789,24 @@ function buildSessionPayload(status) {
675
789
  } : {})
676
790
  };
677
791
  }
792
+
793
+ /**
794
+ * Outcome of one session POST. `retryable` covers 429, 5xx and transport
795
+ * errors — the server (or network) may answer differently in a moment;
796
+ * any other 4xx is a permanent reject. `retryAfterMs` is the server's
797
+ * `Retry-After`, when it sent one.
798
+ */
799
+
800
+ function parseRetryAfterMs(header) {
801
+ const sec = header ? Number(header) : NaN;
802
+ return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
803
+ }
678
804
  async function postSessionPayload(payload, timeoutMs) {
679
- if (!_config) return false;
805
+ if (!_config) return {
806
+ ok: false,
807
+ retryable: false,
808
+ retryAfterMs: null
809
+ };
680
810
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
681
811
  const url = `${baseURL}/api/sdk/errors/session`;
682
812
  let controller = null;
@@ -688,24 +818,106 @@ async function postSessionPayload(payload, timeoutMs) {
688
818
  try {
689
819
  const res = await fetch(url, {
690
820
  method: "POST",
691
- headers: {
692
- "Content-Type": "application/json",
693
- "X-API-Key": _config.apiKey
694
- },
821
+ headers: requestHeaders(_config.apiKey),
695
822
  body: JSON.stringify(payload),
696
823
  ...(controller ? {
697
824
  signal: controller.signal
698
825
  } : {})
699
826
  });
700
- return res.ok;
827
+ if (res.ok) return {
828
+ ok: true
829
+ };
830
+ return {
831
+ ok: false,
832
+ retryable: res.status === 429 || res.status >= 500,
833
+ retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After"))
834
+ };
701
835
  } catch (e) {
702
836
  console.warn("[SwissKnife CrashReporting] session event error:", e);
703
- return false;
837
+ return {
838
+ ok: false,
839
+ retryable: true,
840
+ retryAfterMs: null
841
+ };
704
842
  } finally {
705
843
  if (timer) clearTimeout(timer);
706
844
  }
707
845
  }
708
846
 
847
+ // MARK: - Session Outbox
848
+ //
849
+ // `started` / `ended` session events used to be fire-and-forget: a 429 or a
850
+ // 5xx dropped them, and crash-free-session rates quietly lost their
851
+ // denominator. A failed retryable send now waits here — in order, persisted
852
+ // to the offline store, capped — and is retried after the server's
853
+ // `Retry-After` (or an exponential backoff when it sent none). The crashed
854
+ // session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
855
+
856
+ /** Session events awaiting a retry, oldest first. */
857
+ let _pendingSessions = [];
858
+ let _sessionRetryTimer = null;
859
+ let _sessionBackoffMs = BACKOFF_INITIAL_MS;
860
+ let _sessionDrainInFlight = false;
861
+ /**
862
+ * False from `init` until `restorePersistedState` has merged the previous
863
+ * launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
864
+ * (it would overwrite the stored outbox before restore reads it) nor drain
865
+ * (the older events must go first). Restore persists + drains once merged.
866
+ */
867
+ let _sessionsRestored = true;
868
+ function persistPendingSessions() {
869
+ if (!_sessionsRestored) return;
870
+ const storage = getOfflineStorage();
871
+ if (!storage) return;
872
+ const write = _pendingSessions.length === 0 ? storage.removeItem(OFFLINE_SESSIONS_KEY) : storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
873
+ void write.catch(() => {});
874
+ }
875
+ function scheduleSessionRetry(retryAfterMs) {
876
+ const delayMs = retryAfterMs ?? _sessionBackoffMs;
877
+ _sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
878
+ if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
879
+ _sessionRetryTimer = setTimeout(() => {
880
+ _sessionRetryTimer = null;
881
+ void drainPendingSessions();
882
+ }, delayMs);
883
+ }
884
+ function queueSessionForRetry(payload, retryAfterMs) {
885
+ _pendingSessions.push(payload);
886
+ if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
887
+ _pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
888
+ }
889
+ // Before restore has merged the stored outbox, just hold it in memory:
890
+ // restore persists and drains the merged queue.
891
+ if (!_sessionsRestored) return;
892
+ persistPendingSessions();
893
+ // A drain in flight, or a retry already booked, will pick this one up.
894
+ if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
895
+ scheduleSessionRetry(retryAfterMs);
896
+ }
897
+ }
898
+
899
+ /** Send queued session events in order until one fails retryably. */
900
+ async function drainPendingSessions() {
901
+ if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
902
+ _sessionDrainInFlight = true;
903
+ try {
904
+ while (_pendingSessions.length > 0) {
905
+ const head = _pendingSessions[0];
906
+ const result = await postSessionPayload(head);
907
+ if (!result.ok && result.retryable) {
908
+ scheduleSessionRetry(result.retryAfterMs);
909
+ return;
910
+ }
911
+ // Delivered, or permanently rejected (a retry would only spin).
912
+ if (_pendingSessions[0] === head) _pendingSessions.shift();
913
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
914
+ persistPendingSessions();
915
+ }
916
+ } finally {
917
+ _sessionDrainInFlight = false;
918
+ }
919
+ }
920
+
709
921
  /**
710
922
  * Deliberately has NO `await` before `postSessionPayload` — not even to
711
923
  * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
@@ -716,7 +928,18 @@ async function postSessionPayload(payload, timeoutMs) {
716
928
  */
717
929
  async function sendSessionEvent(status) {
718
930
  if (!_config || !_sessionId) return;
719
- await postSessionPayload(buildSessionPayload(status));
931
+ const payload = buildSessionPayload(status);
932
+ // Something is already waiting on a backoff: queue behind it so the
933
+ // server still sees `started` before `ended`, and so we do not hammer a
934
+ // server that just told us to wait.
935
+ if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
936
+ queueSessionForRetry(payload, null);
937
+ return;
938
+ }
939
+ const result = await postSessionPayload(payload);
940
+ if (!result.ok && result.retryable) {
941
+ queueSessionForRetry(payload, result.retryAfterMs);
942
+ }
720
943
  }
721
944
  function startSession() {
722
945
  _sessionId = generateUUID();
@@ -756,7 +979,9 @@ async function deliverCrashedSession() {
756
979
  _sessionStartTime = null;
757
980
  _sessionErrorCount = 0;
758
981
  if (!payload) return;
759
- const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
982
+ const {
983
+ ok
984
+ } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
760
985
  if (ok) {
761
986
  const storage = getOfflineStorage();
762
987
  if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
@@ -803,19 +1028,56 @@ function installAppStateListener() {
803
1028
  */
804
1029
  function restorePersistedState() {
805
1030
  const storage = getOfflineStorage();
806
- if (!storage) return;
1031
+ if (!storage) {
1032
+ _sessionsRestored = true;
1033
+ return;
1034
+ }
1035
+ _sessionsRestored = false;
807
1036
  _restorePromise = (async () => {
1037
+ // Read the stored session outbox FIRST, before any other await: nothing
1038
+ // this launch does may replace it before it is merged (see
1039
+ // `_sessionsRestored`).
1040
+ let storedSessions = [];
1041
+ try {
1042
+ const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
1043
+ if (rawSessions) {
1044
+ const restored = JSON.parse(rawSessions);
1045
+ if (Array.isArray(restored)) {
1046
+ storedSessions = restored.filter(p => p && typeof p.sessionId === "string");
1047
+ }
1048
+ }
1049
+ } catch {
1050
+ // Unreadable outbox: dropped; the merged persist below overwrites it.
1051
+ }
1052
+ // Earlier launch's sessions go first; anything this launch has already
1053
+ // queued stays behind them. Dedupe on (sessionId, status).
1054
+ const seen = new Set();
1055
+ _pendingSessions = [...storedSessions, ..._pendingSessions].filter(p => {
1056
+ const k = `${p.sessionId}|${p.status}`;
1057
+ if (seen.has(k)) return false;
1058
+ seen.add(k);
1059
+ return true;
1060
+ }).slice(-MAX_PENDING_SESSIONS);
1061
+ _sessionsRestored = true;
1062
+ persistPendingSessions();
808
1063
  try {
809
1064
  const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
810
1065
  if (rawSession) {
811
1066
  const payload = JSON.parse(rawSession);
812
- if (payload?.sessionId && (await postSessionPayload(payload))) {
1067
+ if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
813
1068
  await storage.removeItem(OFFLINE_SESSION_KEY);
814
1069
  }
815
1070
  }
816
1071
  } catch {
817
1072
  // undeliverable this launch — keep for the next one
818
1073
  }
1074
+ if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
1075
+ try {
1076
+ await drainPendingSessions();
1077
+ } catch {
1078
+ // retried on the next backoff / launch
1079
+ }
1080
+ }
819
1081
  try {
820
1082
  const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
821
1083
  if (rawShots) {
@@ -1037,6 +1299,12 @@ function getStaticContexts() {
1037
1299
 
1038
1300
  // MARK: - Build Event
1039
1301
 
1302
+ /** A usable fingerprint: the string entries, or null when none remain. */
1303
+ function normalizeFingerprint(fingerprint) {
1304
+ if (!Array.isArray(fingerprint)) return null;
1305
+ const entries = fingerprint.filter(entry => typeof entry === "string" && entry.length > 0);
1306
+ return entries.length > 0 ? entries : null;
1307
+ }
1040
1308
  function buildEvent(level, partial = {}) {
1041
1309
  const contexts = {
1042
1310
  ...getStaticContexts()
@@ -1064,6 +1332,9 @@ function buildEvent(level, partial = {}) {
1064
1332
  },
1065
1333
  user: resolveSubject(),
1066
1334
  breadcrumbs: _breadcrumbs.snapshot(),
1335
+ ...(_fingerprint ? {
1336
+ fingerprint: [..._fingerprint]
1337
+ } : {}),
1067
1338
  ...partial,
1068
1339
  contexts
1069
1340
  };
@@ -1388,6 +1659,18 @@ function installConsoleBreadcrumbs() {
1388
1659
 
1389
1660
  export const CrashReporting = {
1390
1661
  init(config) {
1662
+ // An empty key (typically a build-time env var that was not set) can
1663
+ // never authenticate. Same rule as `configure()` (internal/config.ts
1664
+ // assertApiKey), but logged instead of thrown: `init` usually runs in
1665
+ // module scope, where a throw keeps the app from booting. Nothing is
1666
+ // installed and the native crash module is not started, so the native
1667
+ // layer is not wired with the empty key and a later `init` with the real
1668
+ // key works.
1669
+ const apiKey = config?.apiKey;
1670
+ if (typeof apiKey !== "string" || apiKey.trim() === "") {
1671
+ console.error(`[SwissKnife CrashReporting] init requires a non-empty apiKey (got ${typeof apiKey === "string" ? JSON.stringify(apiKey) : String(apiKey)}); crash reporting is off.`);
1672
+ return;
1673
+ }
1391
1674
  // Defaults keep today's behaviour byte-for-byte: every handler is on
1392
1675
  // unless the host explicitly opts out. The opt-outs exist for apps whose
1393
1676
  // incumbent reporter owns a given global — see each field's doc comment
@@ -1408,6 +1691,7 @@ export const CrashReporting = {
1408
1691
  // path re-resolves anyway — this only shortens the window in which an
1409
1692
  // early event has to fall back to the send-time pull.
1410
1693
  void refreshIdentitySubject();
1694
+ void loadJsInstallId();
1411
1695
  // Every global-slot install is best-effort. `initSwissKnife()` is normally
1412
1696
  // called in module scope, so anything that throws here takes the host's
1413
1697
  // root module down with it and the app never boots (v0.2.3 did exactly
@@ -1423,15 +1707,14 @@ export const CrashReporting = {
1423
1707
  if (_config.enableAppStateTracking) installAppStateListener();
1424
1708
 
1425
1709
  // Initialize native crash handler if the native module is linked.
1426
- // This catches Mach exceptions + signal crashes (iOS) and NDK native
1427
- // crashes + system ANRs (Android) that pure JS cannot observe.
1710
+ // This catches signal crashes + uncaught NSExceptions (iOS) and NDK
1711
+ // native crashes + system ANRs (Android) that pure JS cannot observe.
1428
1712
  const nativeMod = _config.enableNativeCrashHandler ? getNativeCrashModule() : null;
1429
1713
  if (nativeMod) {
1430
1714
  try {
1431
1715
  nativeMod.start({
1432
1716
  apiKey: config.apiKey,
1433
1717
  serverURL: config.serverURL || "",
1434
- ingestURL: config.ingestURL,
1435
1718
  environment: config.environment || "production",
1436
1719
  release: config.release || ""
1437
1720
  });
@@ -1453,6 +1736,7 @@ export const CrashReporting = {
1453
1736
  eventId: fallbackId
1454
1737
  };
1455
1738
  _sessionErrorCount++;
1739
+ const fingerprint = normalizeFingerprint(options?.fingerprint);
1456
1740
  let event = buildEvent("error", {
1457
1741
  exceptionType: error.name,
1458
1742
  exceptionValue: error.message,
@@ -1462,7 +1746,10 @@ export const CrashReporting = {
1462
1746
  ...options.tags
1463
1747
  } : {
1464
1748
  ..._tags
1465
- }
1749
+ },
1750
+ ...(fingerprint ? {
1751
+ fingerprint
1752
+ } : {})
1466
1753
  });
1467
1754
  event = applyBeforeSend(event);
1468
1755
  if (!event) return {
@@ -1517,10 +1804,7 @@ export const CrashReporting = {
1517
1804
  const url = `${baseURL}/api/sdk/errors/feedback`;
1518
1805
  fetch(url, {
1519
1806
  method: "POST",
1520
- headers: {
1521
- "Content-Type": "application/json",
1522
- "X-API-Key": _config.apiKey
1523
- },
1807
+ headers: requestHeaders(_config.apiKey),
1524
1808
  body: JSON.stringify(feedback)
1525
1809
  }).catch(e => {
1526
1810
  console.warn("[SwissKnife CrashReporting] feedback error:", e);
@@ -1557,7 +1841,9 @@ export const CrashReporting = {
1557
1841
  message: crumb.message,
1558
1842
  level: crumb.level
1559
1843
  });
1560
- } catch {/* non-fatal */}
1844
+ } catch {
1845
+ /* non-fatal */
1846
+ }
1561
1847
  }
1562
1848
  },
1563
1849
  /**
@@ -1600,7 +1886,9 @@ export const CrashReporting = {
1600
1886
  if (nativeMod) {
1601
1887
  try {
1602
1888
  nativeMod.setUser(user);
1603
- } catch {/* non-fatal */}
1889
+ } catch {
1890
+ /* non-fatal */
1891
+ }
1604
1892
  }
1605
1893
  },
1606
1894
  setTag(key, value) {
@@ -1610,7 +1898,9 @@ export const CrashReporting = {
1610
1898
  if (nativeMod) {
1611
1899
  try {
1612
1900
  nativeMod.setTag(key, value);
1613
- } catch {/* non-fatal */}
1901
+ } catch {
1902
+ /* non-fatal */
1903
+ }
1614
1904
  }
1615
1905
  },
1616
1906
  setExtra(key, value) {
@@ -1626,6 +1916,9 @@ export const CrashReporting = {
1626
1916
  },
1627
1917
  setUser: user => {
1628
1918
  _user = user;
1919
+ },
1920
+ setFingerprint: fingerprint => {
1921
+ _fingerprint = normalizeFingerprint(fingerprint);
1629
1922
  }
1630
1923
  });
1631
1924
  },
@@ -1656,11 +1949,18 @@ export const CrashReporting = {
1656
1949
  // `init` and `init` before `logIn` both end up stamped. Bounded by
1657
1950
  // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1658
1951
  await resolveIdentitySubjectNow();
1952
+ // A flush racing `init` waits for the AsyncStorage read, bounded like the
1953
+ // identity pull (no timer when there is nothing in flight).
1954
+ if (_jsInstallIdLoad && !_jsInstallIdSettled) {
1955
+ await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
1956
+ }
1659
1957
 
1660
1958
  // The /api/sdk/errors/event/batch endpoint:
1661
1959
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1662
1960
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1663
1961
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
1962
+ await Promise.all(batch.map(event => capturedContexts.get(event)));
1963
+ const installId = resolveInstallId();
1664
1964
  const serialized = batch.map(e => {
1665
1965
  const {
1666
1966
  user: builtUser,
@@ -1673,6 +1973,11 @@ export const CrashReporting = {
1673
1973
  ...(user ? {
1674
1974
  user
1675
1975
  } : {}),
1976
+ // Stamped at send time, like the subject: an event captured before
1977
+ // the bridge first answered still ships with it.
1978
+ ...(installId ? {
1979
+ installId
1980
+ } : {}),
1676
1981
  timestamp: typeof e.timestamp === "number" ? new Date(e.timestamp).toISOString() : e.timestamp
1677
1982
  };
1678
1983
  });
@@ -1685,10 +1990,7 @@ export const CrashReporting = {
1685
1990
  try {
1686
1991
  const res = await fetch(url, {
1687
1992
  method: "POST",
1688
- headers: {
1689
- "Content-Type": "application/json",
1690
- "X-API-Key": _config.apiKey
1691
- },
1993
+ headers: requestHeaders(_config.apiKey),
1692
1994
  body: JSON.stringify({
1693
1995
  events: serialized
1694
1996
  }),
@@ -1796,6 +2098,7 @@ export const CrashReporting = {
1796
2098
  _tags = {};
1797
2099
  _extra = {};
1798
2100
  _user = null;
2101
+ _fingerprint = null;
1799
2102
  _pendingEvents = [];
1800
2103
  _inFlightEvents = new Map();
1801
2104
  if (_flushTimer !== null) {
@@ -1808,6 +2111,14 @@ export const CrashReporting = {
1808
2111
  _sessionErrorCount = 0;
1809
2112
  _backoffMs = BACKOFF_INITIAL_MS;
1810
2113
  _backoffUntil = 0;
2114
+ _pendingSessions = [];
2115
+ if (_sessionRetryTimer !== null) {
2116
+ clearTimeout(_sessionRetryTimer);
2117
+ _sessionRetryTimer = null;
2118
+ }
2119
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
2120
+ _sessionDrainInFlight = false;
2121
+ _sessionsRestored = true;
1811
2122
  clearAmbiguousStreak();
1812
2123
  if (_disableRejectionTracking) {
1813
2124
  // Teardown is the mirror image of install and can fail the same way —
@@ -1824,6 +2135,10 @@ export const CrashReporting = {
1824
2135
  _screenshotCaptureOverride = undefined;
1825
2136
  _nativeCrashModuleOverride = undefined;
1826
2137
  _identityUserId = null;
2138
+ _identityAnonymousId = null;
2139
+ _jsInstallId = null;
2140
+ _jsInstallIdLoad = null;
2141
+ _jsInstallIdSettled = false;
1827
2142
  _identityRefresh = null;
1828
2143
  // Bump the generation so a read still in flight cannot land after the
1829
2144
  // reset and repopulate the subject the reset just cleared.
@@ -1865,6 +2180,12 @@ export const CrashReporting = {
1865
2180
  _snapshotSessionId() {
1866
2181
  return _sessionId;
1867
2182
  },
2183
+ _snapshotPendingSessions() {
2184
+ return _pendingSessions.map(p => ({
2185
+ sessionId: p.sessionId,
2186
+ status: p.status
2187
+ }));
2188
+ },
1868
2189
  _restorePromiseForTests() {
1869
2190
  return _restorePromise;
1870
2191
  },
@@ -1893,6 +2214,7 @@ export const CrashReporting = {
1893
2214
  _setIdentityResolverForTests(resolver) {
1894
2215
  _identityResolverOverride = resolver;
1895
2216
  _identityUserId = null;
2217
+ _identityAnonymousId = null;
1896
2218
  _identityRefresh = null;
1897
2219
  _identityGeneration++;
1898
2220
  },