@app-swiss-knife/react-native-sdk 0.3.2 → 0.4.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.
@@ -35,10 +35,7 @@ import React from "react";
35
35
 
36
36
  import { generateUUID } from "./ids";
37
37
  import { getOfflineStorage } from "./offline-store";
38
- import {
39
- base64ToUint8Array,
40
- uploadAttachmentWithRetry,
41
- } from "./attachments";
38
+ import { base64ToUint8Array, uploadAttachmentWithRetry } from "./attachments";
42
39
 
43
40
  // MARK: - Native Bridge
44
41
 
@@ -56,7 +53,9 @@ interface SKCrashReportingNative {
56
53
  environment: string;
57
54
  release: string;
58
55
  }): void;
59
- setUser(user: { id?: string; email?: string; username?: string } | null): void;
56
+ setUser(
57
+ user: { id?: string; email?: string; username?: string } | null
58
+ ): void;
60
59
  addBreadcrumb(breadcrumb: {
61
60
  category?: string;
62
61
  message?: string;
@@ -227,6 +226,15 @@ export interface SKCrashEvent {
227
226
  dist?: string;
228
227
  platform: string;
229
228
  mechanism?: string;
229
+ /**
230
+ * Custom grouping key (Sentry-compatible). Events with the same
231
+ * fingerprint are one issue. Entries may be templates the server expands:
232
+ * `{{ default }}` (the normal grouping), `{{ type }}`, `{{ value }}`,
233
+ * `{{ message }}`, `{{ tags.<key> }}` — e.g.
234
+ * `["{{ default }}", "{{ tags.region }}"]` splits the default issue by
235
+ * region.
236
+ */
237
+ fingerprint?: string[];
230
238
  /** `false` for events captured by the SDK's global hooks (fatal errors,
231
239
  * unhandled promise rejections); unset for manual captures. */
232
240
  handled?: boolean;
@@ -235,10 +243,22 @@ export interface SKCrashEvent {
235
243
 
236
244
  // MARK: - Scope
237
245
 
238
- interface SKCrashScope {
246
+ export interface SKCrashScope {
239
247
  setTag: (key: string, value: string) => void;
240
248
  setExtra: (key: string, value: unknown) => void;
241
249
  setUser: (user: SKCrashUser | null) => void;
250
+ /**
251
+ * Fingerprint for every event captured after this call (until cleared
252
+ * with `null` / `[]`). A per-call `captureException(err, { fingerprint })`
253
+ * wins over it. See `SKCrashEvent.fingerprint` for templates.
254
+ */
255
+ setFingerprint: (fingerprint: string[] | null) => void;
256
+ }
257
+
258
+ export interface SKCaptureExceptionOptions {
259
+ tags?: Record<string, string>;
260
+ /** Custom grouping key for this event; overrides the scope's. */
261
+ fingerprint?: string[];
242
262
  }
243
263
 
244
264
  // MARK: - Internals
@@ -254,7 +274,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
254
274
  const DEFAULT_MAX_CACHE_ITEMS = 30;
255
275
  const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
256
276
  const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
277
+ /** Started/ended session events waiting on a retry (see Session Outbox). */
278
+ const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
279
+ /** Cap on queued session events — drop-oldest beyond this. */
280
+ const MAX_PENDING_SESSIONS = 50;
257
281
  const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
282
+ /** JS-side install id, only for apps without the native Identity bridge. */
283
+ const INSTALL_ID_KEY = "@swissknife:crash:install_id";
258
284
 
259
285
  // MARK: - Stack Trace Parsing
260
286
 
@@ -346,6 +372,8 @@ let _breadcrumbs: RingBuffer<SKCrashBreadcrumb> = new RingBuffer(100);
346
372
  let _tags: Record<string, string> = {};
347
373
  let _extra: Record<string, unknown> = {};
348
374
  let _user: SKCrashUser | null = null;
375
+ /** Scope-level fingerprint (configureScope → setFingerprint). */
376
+ let _fingerprint: string[] | null = null;
349
377
  let _pendingEvents: SKCrashEvent[] = [];
350
378
  /**
351
379
  * Events handed to an in-flight POST: already out of `_pendingEvents`, not
@@ -363,7 +391,9 @@ let _pendingEvents: SKCrashEvent[] = [];
363
391
  */
364
392
  let _inFlightEvents: Map<string, SKCrashEvent> = new Map();
365
393
  let _flushTimer: ReturnType<typeof setTimeout> | null = null;
366
- let _originalGlobalHandler: ((error: unknown, isFatal?: boolean) => void) | null = null;
394
+ let _originalGlobalHandler:
395
+ | ((error: unknown, isFatal?: boolean) => void)
396
+ | null = null;
367
397
  let _sessionId: string | null = null;
368
398
  let _sessionStartTime: number | null = null;
369
399
  let _sessionErrorCount = 0;
@@ -414,8 +444,20 @@ let _screenshotCaptureOverride:
414
444
  // `Identity.current()` also carries an `anonymousId`, and stamping it into
415
445
  // `user.id` would make "affected users" non-zero for every app that never
416
446
  // logs in. That both inflates the number and diverges from Analytics, whose
417
- // `user_id` is the identified subject only. The anonymous id already travels
418
- // separately on the ingest envelope. Only `userId` is used here.
447
+ // `user_id` is the identified subject only. The anonymous id travels
448
+ // separately, as the wire event's `installId` (see below) — the server counts
449
+ // affected users by user id, else install id, without conflating the two.
450
+
451
+ // ## installId — the stable per-install id
452
+ //
453
+ // Most crashes have no identified subject, so the server counts affected
454
+ // users by `installId` when `user.id` is absent. It is the Identity bridge's
455
+ // `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
456
+ // carry on their ingest envelope and `app_users.anonymous_id` stores, so the
457
+ // dashboard can link an anonymous install to its profile). Apps without the
458
+ // native Identity bridge get a random id persisted in AsyncStorage; without
459
+ // AsyncStorage no installId is sent at all, because a per-launch id would
460
+ // count every relaunch as a new user.
419
461
 
420
462
  /**
421
463
  * Last resolved identified subject id from the native Identity bridge.
@@ -424,6 +466,14 @@ let _screenshotCaptureOverride:
424
466
  * stamped, which is exactly today's behaviour for apps that never log in.
425
467
  */
426
468
  let _identityUserId: string | null = null;
469
+ /** Last resolved `Identity.current().anonymousId` (stable per install). */
470
+ let _identityAnonymousId: string | null = null;
471
+ /** AsyncStorage-persisted install id; used only when no Identity bridge. */
472
+ let _jsInstallId: string | null = null;
473
+ /** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
474
+ let _jsInstallIdLoad: Promise<void> | null = null;
475
+ /** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
476
+ let _jsInstallIdSettled = false;
427
477
  /** In-flight read, so N events in a burst share one bridge hop. */
428
478
  let _identityRefresh: Promise<void> | null = null;
429
479
  /** Monotonic read counter — a superseded read must not clobber a newer one. */
@@ -436,18 +486,22 @@ let _identityGeneration = 0;
436
486
  * unreachable and "we did read Identity" would pass vacuously.
437
487
  */
438
488
  let _identityResolverOverride:
439
- | (() => Promise<{ userId?: string | null }>)
489
+ | (() => Promise<IdentitySnapshot>)
440
490
  | null
441
491
  | undefined;
442
492
 
493
+ /** The fields of the native `Identity.current()` snapshot this module reads. */
494
+ interface IdentitySnapshot {
495
+ userId?: string | null;
496
+ anonymousId?: string | null;
497
+ }
498
+
443
499
  /** Budget for the send-time identity re-resolve. Kept well under
444
500
  * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
445
501
  * one chance to deliver before the process dies. */
446
502
  const IDENTITY_RESOLVE_TIMEOUT_MS = 250;
447
503
 
448
- function getIdentityResolver():
449
- | (() => Promise<{ userId?: string | null }>)
450
- | null {
504
+ function getIdentityResolver(): (() => Promise<IdentitySnapshot>) | null {
451
505
  if (_identityResolverOverride !== undefined) {
452
506
  return _identityResolverOverride;
453
507
  }
@@ -461,8 +515,7 @@ function getIdentityResolver():
461
515
  };
462
516
  const native = mod.getNativeModule();
463
517
  if (typeof native?.identityCurrent !== "function") return null;
464
- return () =>
465
- native.identityCurrent!() as Promise<{ userId?: string | null }>;
518
+ return () => native.identityCurrent!() as Promise<IdentitySnapshot>;
466
519
  } catch {
467
520
  // Identity bridge not linked (bare Expo app, tests, plain Node).
468
521
  return null;
@@ -494,6 +547,11 @@ function startIdentityRead(): Promise<void> {
494
547
  const userId = snapshot?.userId;
495
548
  _identityUserId =
496
549
  typeof userId === "string" && userId.length > 0 ? userId : null;
550
+ // Never blanked by a later empty answer: the id is per install.
551
+ const anonymousId = snapshot?.anonymousId;
552
+ if (typeof anonymousId === "string" && anonymousId.length > 0) {
553
+ _identityAnonymousId = anonymousId;
554
+ }
497
555
  } catch {
498
556
  // Bridge hiccup — keep the last known subject.
499
557
  } finally {
@@ -571,6 +629,65 @@ function mergeIdentityInto(
571
629
  return { ...(user ?? {}), id };
572
630
  }
573
631
 
632
+ /** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
633
+ function withTimeout(p: Promise<void>, ms: number): Promise<void> {
634
+ return new Promise<void>((resolve) => {
635
+ const timer = setTimeout(resolve, ms);
636
+ void p.then(
637
+ () => {
638
+ clearTimeout(timer);
639
+ resolve();
640
+ },
641
+ () => {
642
+ clearTimeout(timer);
643
+ resolve();
644
+ }
645
+ );
646
+ });
647
+ }
648
+
649
+ /**
650
+ * The install id to stamp on outgoing events, or undefined when none is
651
+ * known. The Identity bridge's anonymous id wins; the JS-persisted id is used
652
+ * only when there is no bridge at all — mixing the two on one device (e.g. a
653
+ * slow bridge read) would count that device twice.
654
+ */
655
+ function resolveInstallId(): string | undefined {
656
+ if (_identityAnonymousId) return _identityAnonymousId;
657
+ if (getIdentityResolver() !== null) return undefined;
658
+ return _jsInstallId ?? undefined;
659
+ }
660
+
661
+ /**
662
+ * Load (or mint and persist) the JS-side install id. Only for apps without
663
+ * the Identity bridge; a no-op without AsyncStorage. Never throws.
664
+ */
665
+ function loadJsInstallId(): Promise<void> {
666
+ _jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
667
+ _jsInstallIdSettled = true;
668
+ });
669
+ return _jsInstallIdLoad;
670
+ }
671
+
672
+ async function readOrMintJsInstallId(): Promise<void> {
673
+ if (_jsInstallId || getIdentityResolver() !== null) return;
674
+ const storage = getOfflineStorage();
675
+ if (!storage) return;
676
+ try {
677
+ const stored = await storage.getItem(INSTALL_ID_KEY);
678
+ if (stored) {
679
+ _jsInstallId = stored;
680
+ return;
681
+ }
682
+ const minted = generateUUID();
683
+ await storage.setItem(INSTALL_ID_KEY, minted);
684
+ // Only use an id that made it to disk — see the module note above.
685
+ _jsInstallId = minted;
686
+ } catch {
687
+ // Storage hiccup: send no installId rather than a per-launch one.
688
+ }
689
+ }
690
+
574
691
  // MARK: - Pending Queue (memory + best-effort disk mirror)
575
692
 
576
693
  function enqueueEvent(event: SKCrashEvent): void {
@@ -661,7 +778,10 @@ function persistQueue(): void {
661
778
  // In-flight events are older than anything pending, so they lead and
662
779
  // drop-oldest still trims from the front. Dedupe defensively: a batch
663
780
  // mid-requeue can briefly be reachable from both sides.
664
- const live = dedupeEventsById([..._inFlightEvents.values(), ..._pendingEvents]);
781
+ const live = dedupeEventsById([
782
+ ..._inFlightEvents.values(),
783
+ ..._pendingEvents,
784
+ ]);
665
785
  // NB: slice(-0) would return the WHOLE array — guard the zero-cap case.
666
786
  const snapshot = eventCap > 0 ? live.slice(-eventCap) : [];
667
787
  void (async () => {
@@ -845,6 +965,20 @@ function clearAmbiguousStreak(): void {
845
965
 
846
966
  // MARK: - Session Tracking
847
967
 
968
+ /**
969
+ * Request headers for every `/api/sdk/errors/*` call. Carries the install id
970
+ * (when known) so the server's per-device rate limit buckets this install
971
+ * separately from every other device of the app.
972
+ */
973
+ function requestHeaders(apiKey: string): Record<string, string> {
974
+ const installId = resolveInstallId();
975
+ return {
976
+ "Content-Type": "application/json",
977
+ "X-API-Key": apiKey,
978
+ ...(installId ? { "X-SK-Install-Id": installId } : {}),
979
+ };
980
+ }
981
+
848
982
  interface SessionPayload {
849
983
  sessionId: string;
850
984
  status: "started" | "ended" | "crashed";
@@ -880,11 +1014,26 @@ function buildSessionPayload(status: SessionPayload["status"]): SessionPayload {
880
1014
  };
881
1015
  }
882
1016
 
1017
+ /**
1018
+ * Outcome of one session POST. `retryable` covers 429, 5xx and transport
1019
+ * errors — the server (or network) may answer differently in a moment;
1020
+ * any other 4xx is a permanent reject. `retryAfterMs` is the server's
1021
+ * `Retry-After`, when it sent one.
1022
+ */
1023
+ type SessionSendResult =
1024
+ | { ok: true }
1025
+ | { ok: false; retryable: boolean; retryAfterMs: number | null };
1026
+
1027
+ function parseRetryAfterMs(header: string | null): number | null {
1028
+ const sec = header ? Number(header) : NaN;
1029
+ return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
1030
+ }
1031
+
883
1032
  async function postSessionPayload(
884
1033
  payload: SessionPayload,
885
1034
  timeoutMs?: number
886
- ): Promise<boolean> {
887
- if (!_config) return false;
1035
+ ): Promise<SessionSendResult> {
1036
+ if (!_config) return { ok: false, retryable: false, retryAfterMs: null };
888
1037
 
889
1038
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
890
1039
  const url = `${baseURL}/api/sdk/errors/session`;
@@ -899,22 +1048,107 @@ async function postSessionPayload(
899
1048
  try {
900
1049
  const res = await fetch(url, {
901
1050
  method: "POST",
902
- headers: {
903
- "Content-Type": "application/json",
904
- "X-API-Key": _config.apiKey,
905
- },
1051
+ headers: requestHeaders(_config.apiKey),
906
1052
  body: JSON.stringify(payload),
907
1053
  ...(controller ? { signal: controller.signal } : {}),
908
1054
  });
909
- return res.ok;
1055
+ if (res.ok) return { ok: true };
1056
+ return {
1057
+ ok: false,
1058
+ retryable: res.status === 429 || res.status >= 500,
1059
+ retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After")),
1060
+ };
910
1061
  } catch (e) {
911
1062
  console.warn("[SwissKnife CrashReporting] session event error:", e);
912
- return false;
1063
+ return { ok: false, retryable: true, retryAfterMs: null };
913
1064
  } finally {
914
1065
  if (timer) clearTimeout(timer);
915
1066
  }
916
1067
  }
917
1068
 
1069
+ // MARK: - Session Outbox
1070
+ //
1071
+ // `started` / `ended` session events used to be fire-and-forget: a 429 or a
1072
+ // 5xx dropped them, and crash-free-session rates quietly lost their
1073
+ // denominator. A failed retryable send now waits here — in order, persisted
1074
+ // to the offline store, capped — and is retried after the server's
1075
+ // `Retry-After` (or an exponential backoff when it sent none). The crashed
1076
+ // session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
1077
+
1078
+ /** Session events awaiting a retry, oldest first. */
1079
+ let _pendingSessions: SessionPayload[] = [];
1080
+ let _sessionRetryTimer: ReturnType<typeof setTimeout> | null = null;
1081
+ let _sessionBackoffMs = BACKOFF_INITIAL_MS;
1082
+ let _sessionDrainInFlight = false;
1083
+ /**
1084
+ * False from `init` until `restorePersistedState` has merged the previous
1085
+ * launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
1086
+ * (it would overwrite the stored outbox before restore reads it) nor drain
1087
+ * (the older events must go first). Restore persists + drains once merged.
1088
+ */
1089
+ let _sessionsRestored = true;
1090
+
1091
+ function persistPendingSessions(): void {
1092
+ if (!_sessionsRestored) return;
1093
+ const storage = getOfflineStorage();
1094
+ if (!storage) return;
1095
+ const write =
1096
+ _pendingSessions.length === 0
1097
+ ? storage.removeItem(OFFLINE_SESSIONS_KEY)
1098
+ : storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
1099
+ void write.catch(() => {});
1100
+ }
1101
+
1102
+ function scheduleSessionRetry(retryAfterMs: number | null): void {
1103
+ const delayMs = retryAfterMs ?? _sessionBackoffMs;
1104
+ _sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
1105
+ if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
1106
+ _sessionRetryTimer = setTimeout(() => {
1107
+ _sessionRetryTimer = null;
1108
+ void drainPendingSessions();
1109
+ }, delayMs);
1110
+ }
1111
+
1112
+ function queueSessionForRetry(
1113
+ payload: SessionPayload,
1114
+ retryAfterMs: number | null
1115
+ ): void {
1116
+ _pendingSessions.push(payload);
1117
+ if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
1118
+ _pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
1119
+ }
1120
+ // Before restore has merged the stored outbox, just hold it in memory:
1121
+ // restore persists and drains the merged queue.
1122
+ if (!_sessionsRestored) return;
1123
+ persistPendingSessions();
1124
+ // A drain in flight, or a retry already booked, will pick this one up.
1125
+ if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
1126
+ scheduleSessionRetry(retryAfterMs);
1127
+ }
1128
+ }
1129
+
1130
+ /** Send queued session events in order until one fails retryably. */
1131
+ async function drainPendingSessions(): Promise<void> {
1132
+ if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
1133
+ _sessionDrainInFlight = true;
1134
+ try {
1135
+ while (_pendingSessions.length > 0) {
1136
+ const head = _pendingSessions[0];
1137
+ const result = await postSessionPayload(head);
1138
+ if (!result.ok && result.retryable) {
1139
+ scheduleSessionRetry(result.retryAfterMs);
1140
+ return;
1141
+ }
1142
+ // Delivered, or permanently rejected (a retry would only spin).
1143
+ if (_pendingSessions[0] === head) _pendingSessions.shift();
1144
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
1145
+ persistPendingSessions();
1146
+ }
1147
+ } finally {
1148
+ _sessionDrainInFlight = false;
1149
+ }
1150
+ }
1151
+
918
1152
  /**
919
1153
  * Deliberately has NO `await` before `postSessionPayload` — not even to
920
1154
  * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
@@ -927,7 +1161,18 @@ async function sendSessionEvent(
927
1161
  status: "started" | "ended" | "crashed"
928
1162
  ): Promise<void> {
929
1163
  if (!_config || !_sessionId) return;
930
- await postSessionPayload(buildSessionPayload(status));
1164
+ const payload = buildSessionPayload(status);
1165
+ // Something is already waiting on a backoff: queue behind it so the
1166
+ // server still sees `started` before `ended`, and so we do not hammer a
1167
+ // server that just told us to wait.
1168
+ if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
1169
+ queueSessionForRetry(payload, null);
1170
+ return;
1171
+ }
1172
+ const result = await postSessionPayload(payload);
1173
+ if (!result.ok && result.retryable) {
1174
+ queueSessionForRetry(payload, result.retryAfterMs);
1175
+ }
931
1176
  }
932
1177
 
933
1178
  function startSession(): void {
@@ -970,7 +1215,7 @@ async function deliverCrashedSession(): Promise<void> {
970
1215
  _sessionStartTime = null;
971
1216
  _sessionErrorCount = 0;
972
1217
  if (!payload) return;
973
- const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
1218
+ const { ok } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
974
1219
  if (ok) {
975
1220
  const storage = getOfflineStorage();
976
1221
  if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
@@ -988,7 +1233,12 @@ function handleAppStateChange(nextState: string): void {
988
1233
  /** Test seam — see `_nativeCrashModuleOverride` for why. `undefined` =
989
1234
  * resolve from react-native. */
990
1235
  let _appStateOverride:
991
- | { addEventListener: (e: string, h: (s: string) => void) => { remove: () => void } }
1236
+ | {
1237
+ addEventListener: (
1238
+ e: string,
1239
+ h: (s: string) => void
1240
+ ) => { remove: () => void };
1241
+ }
992
1242
  | null
993
1243
  | undefined;
994
1244
 
@@ -996,7 +1246,8 @@ function installAppStateListener(): void {
996
1246
  if (_appStateSubscription) return; // double-init guard
997
1247
  if (_appStateOverride !== undefined) {
998
1248
  _appStateSubscription =
999
- _appStateOverride?.addEventListener("change", handleAppStateChange) ?? null;
1249
+ _appStateOverride?.addEventListener("change", handleAppStateChange) ??
1250
+ null;
1000
1251
  return;
1001
1252
  }
1002
1253
  // AppState is a React Native API. Guard so tests/Node imports don't blow up.
@@ -1024,13 +1275,48 @@ function installAppStateListener(): void {
1024
1275
  */
1025
1276
  function restorePersistedState(): void {
1026
1277
  const storage = getOfflineStorage();
1027
- if (!storage) return;
1278
+ if (!storage) {
1279
+ _sessionsRestored = true;
1280
+ return;
1281
+ }
1282
+ _sessionsRestored = false;
1028
1283
  _restorePromise = (async () => {
1284
+ // Read the stored session outbox FIRST, before any other await: nothing
1285
+ // this launch does may replace it before it is merged (see
1286
+ // `_sessionsRestored`).
1287
+ let storedSessions: SessionPayload[] = [];
1288
+ try {
1289
+ const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
1290
+ if (rawSessions) {
1291
+ const restored = JSON.parse(rawSessions) as SessionPayload[];
1292
+ if (Array.isArray(restored)) {
1293
+ storedSessions = restored.filter(
1294
+ (p) => p && typeof p.sessionId === "string"
1295
+ );
1296
+ }
1297
+ }
1298
+ } catch {
1299
+ // Unreadable outbox: dropped; the merged persist below overwrites it.
1300
+ }
1301
+ // Earlier launch's sessions go first; anything this launch has already
1302
+ // queued stays behind them. Dedupe on (sessionId, status).
1303
+ const seen = new Set<string>();
1304
+ _pendingSessions = [...storedSessions, ..._pendingSessions]
1305
+ .filter((p) => {
1306
+ const k = `${p.sessionId}|${p.status}`;
1307
+ if (seen.has(k)) return false;
1308
+ seen.add(k);
1309
+ return true;
1310
+ })
1311
+ .slice(-MAX_PENDING_SESSIONS);
1312
+ _sessionsRestored = true;
1313
+ persistPendingSessions();
1314
+
1029
1315
  try {
1030
1316
  const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
1031
1317
  if (rawSession) {
1032
1318
  const payload = JSON.parse(rawSession) as SessionPayload;
1033
- if (payload?.sessionId && (await postSessionPayload(payload))) {
1319
+ if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
1034
1320
  await storage.removeItem(OFFLINE_SESSION_KEY);
1035
1321
  }
1036
1322
  }
@@ -1038,6 +1324,14 @@ function restorePersistedState(): void {
1038
1324
  // undeliverable this launch — keep for the next one
1039
1325
  }
1040
1326
 
1327
+ if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
1328
+ try {
1329
+ await drainPendingSessions();
1330
+ } catch {
1331
+ // retried on the next backoff / launch
1332
+ }
1333
+ }
1334
+
1041
1335
  try {
1042
1336
  const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
1043
1337
  if (rawShots) {
@@ -1048,9 +1342,7 @@ function restorePersistedState(): void {
1048
1342
  if (Array.isArray(shots)) {
1049
1343
  _offlineScreenshots = shots.filter(
1050
1344
  (s) =>
1051
- s &&
1052
- typeof s.eventId === "string" &&
1053
- typeof s.base64 === "string"
1345
+ s && typeof s.eventId === "string" && typeof s.base64 === "string"
1054
1346
  );
1055
1347
  }
1056
1348
  }
@@ -1271,7 +1563,9 @@ export function buildStaticContexts(
1271
1563
  : platform.OS === "android"
1272
1564
  ? "Android"
1273
1565
  : String(platform.OS)),
1274
- version: String(constants.Release ?? constants.osVersion ?? platform.Version ?? ""),
1566
+ version: String(
1567
+ constants.Release ?? constants.osVersion ?? platform.Version ?? ""
1568
+ ),
1275
1569
  };
1276
1570
  const device: Record<string, unknown> = {};
1277
1571
  if (typeof constants.Model === "string") device.model = constants.Model;
@@ -1307,6 +1601,15 @@ function getStaticContexts(): Record<string, unknown> {
1307
1601
 
1308
1602
  // MARK: - Build Event
1309
1603
 
1604
+ /** A usable fingerprint: the string entries, or null when none remain. */
1605
+ function normalizeFingerprint(fingerprint: unknown): string[] | null {
1606
+ if (!Array.isArray(fingerprint)) return null;
1607
+ const entries = fingerprint.filter(
1608
+ (entry): entry is string => typeof entry === "string" && entry.length > 0
1609
+ );
1610
+ return entries.length > 0 ? entries : null;
1611
+ }
1612
+
1310
1613
  function buildEvent(
1311
1614
  level: SKCrashEvent["level"],
1312
1615
  partial: Partial<SKCrashEvent> = {}
@@ -1329,6 +1632,7 @@ function buildEvent(
1329
1632
  extra: { ..._extra },
1330
1633
  user: resolveSubject(),
1331
1634
  breadcrumbs: _breadcrumbs.snapshot(),
1635
+ ...(_fingerprint ? { fingerprint: [..._fingerprint] } : {}),
1332
1636
  ...partial,
1333
1637
  contexts,
1334
1638
  };
@@ -1340,10 +1644,22 @@ function installGlobalHandler(): void {
1340
1644
  if (_originalGlobalHandler) return; // double-init guard
1341
1645
  // ErrorUtils is a React Native global. We guard with typeof so this module
1342
1646
  // can also be imported in plain Node (tests) without blowing up.
1343
- const ErrorUtils = (globalThis as { ErrorUtils?: { getGlobalHandler: () => Function; setGlobalHandler: (h: (error: unknown, isFatal?: boolean) => void) => void } }).ErrorUtils;
1647
+ const ErrorUtils = (
1648
+ globalThis as {
1649
+ ErrorUtils?: {
1650
+ getGlobalHandler: () => Function;
1651
+ setGlobalHandler: (
1652
+ h: (error: unknown, isFatal?: boolean) => void
1653
+ ) => void;
1654
+ };
1655
+ }
1656
+ ).ErrorUtils;
1344
1657
  if (!ErrorUtils) return;
1345
1658
 
1346
- _originalGlobalHandler = ErrorUtils.getGlobalHandler() as (error: unknown, isFatal?: boolean) => void;
1659
+ _originalGlobalHandler = ErrorUtils.getGlobalHandler() as (
1660
+ error: unknown,
1661
+ isFatal?: boolean
1662
+ ) => void;
1347
1663
  ErrorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {
1348
1664
  const err = error instanceof Error ? error : new Error(String(error));
1349
1665
  const level: SKCrashEvent["level"] = isFatal ? "fatal" : "error";
@@ -1576,7 +1892,11 @@ function installPromiseRejectionTracking(): void {
1576
1892
  // Mirror image of the install: only restore what we managed to replace,
1577
1893
  // and go through the same non-throwing path.
1578
1894
  if (composed) {
1579
- trySetHostProperty(hermes, "enablePromiseRejectionTracker", engineEnable);
1895
+ trySetHostProperty(
1896
+ hermes,
1897
+ "enablePromiseRejectionTracker",
1898
+ engineEnable
1899
+ );
1580
1900
  }
1581
1901
  original({ allRejections: false, onUnhandled: () => {} });
1582
1902
  };
@@ -1718,6 +2038,7 @@ export const CrashReporting = {
1718
2038
  // path re-resolves anyway — this only shortens the window in which an
1719
2039
  // early event has to fall back to the send-time pull.
1720
2040
  void refreshIdentitySubject();
2041
+ void loadJsInstallId();
1721
2042
  // Every global-slot install is best-effort. `initSwissKnife()` is normally
1722
2043
  // called in module scope, so anything that throws here takes the host's
1723
2044
  // root module down with it and the app never boots (v0.2.3 did exactly
@@ -1749,7 +2070,10 @@ export const CrashReporting = {
1749
2070
  });
1750
2071
  } catch (e) {
1751
2072
  // Non-fatal — JS crash reporting still works
1752
- console.warn("[SwissKnife CrashReporting] native module init failed:", e);
2073
+ console.warn(
2074
+ "[SwissKnife CrashReporting] native module init failed:",
2075
+ e
2076
+ );
1753
2077
  }
1754
2078
  }
1755
2079
 
@@ -1760,15 +2084,20 @@ export const CrashReporting = {
1760
2084
  }
1761
2085
  },
1762
2086
 
1763
- captureException(error: Error, options?: { tags?: Record<string, string> }): { eventId: string } {
2087
+ captureException(
2088
+ error: Error,
2089
+ options?: SKCaptureExceptionOptions
2090
+ ): { eventId: string } {
1764
2091
  const fallbackId = generateUUID();
1765
2092
  if (!_config) return { eventId: fallbackId };
1766
2093
  _sessionErrorCount++;
2094
+ const fingerprint = normalizeFingerprint(options?.fingerprint);
1767
2095
  let event: SKCrashEvent | null = buildEvent("error", {
1768
2096
  exceptionType: error.name,
1769
2097
  exceptionValue: error.message,
1770
2098
  stacktrace: error.stack ? parseStackTrace(error.stack) : undefined,
1771
2099
  tags: options?.tags ? { ..._tags, ...options.tags } : { ..._tags },
2100
+ ...(fingerprint ? { fingerprint } : {}),
1772
2101
  });
1773
2102
  event = applyBeforeSend(event);
1774
2103
  if (!event) return { eventId: fallbackId };
@@ -1828,10 +2157,7 @@ export const CrashReporting = {
1828
2157
 
1829
2158
  fetch(url, {
1830
2159
  method: "POST",
1831
- headers: {
1832
- "Content-Type": "application/json",
1833
- "X-API-Key": _config.apiKey,
1834
- },
2160
+ headers: requestHeaders(_config.apiKey),
1835
2161
  body: JSON.stringify(feedback),
1836
2162
  }).catch((e) => {
1837
2163
  console.warn("[SwissKnife CrashReporting] feedback error:", e);
@@ -1872,7 +2198,9 @@ export const CrashReporting = {
1872
2198
  message: crumb.message,
1873
2199
  level: crumb.level,
1874
2200
  });
1875
- } catch { /* non-fatal */ }
2201
+ } catch {
2202
+ /* non-fatal */
2203
+ }
1876
2204
  }
1877
2205
  },
1878
2206
 
@@ -1916,7 +2244,9 @@ export const CrashReporting = {
1916
2244
  if (nativeMod) {
1917
2245
  try {
1918
2246
  nativeMod.setUser(user);
1919
- } catch { /* non-fatal */ }
2247
+ } catch {
2248
+ /* non-fatal */
2249
+ }
1920
2250
  }
1921
2251
  },
1922
2252
 
@@ -1927,7 +2257,9 @@ export const CrashReporting = {
1927
2257
  if (nativeMod) {
1928
2258
  try {
1929
2259
  nativeMod.setTag(key, value);
1930
- } catch { /* non-fatal */ }
2260
+ } catch {
2261
+ /* non-fatal */
2262
+ }
1931
2263
  }
1932
2264
  },
1933
2265
 
@@ -1937,9 +2269,18 @@ export const CrashReporting = {
1937
2269
 
1938
2270
  configureScope(callback: (scope: SKCrashScope) => void): void {
1939
2271
  callback({
1940
- setTag: (key, value) => { _tags[key] = value; },
1941
- setExtra: (key, value) => { _extra[key] = value; },
1942
- setUser: (user) => { _user = user; },
2272
+ setTag: (key, value) => {
2273
+ _tags[key] = value;
2274
+ },
2275
+ setExtra: (key, value) => {
2276
+ _extra[key] = value;
2277
+ },
2278
+ setUser: (user) => {
2279
+ _user = user;
2280
+ },
2281
+ setFingerprint: (fingerprint) => {
2282
+ _fingerprint = normalizeFingerprint(fingerprint);
2283
+ },
1943
2284
  });
1944
2285
  },
1945
2286
 
@@ -1972,11 +2313,17 @@ export const CrashReporting = {
1972
2313
  // `init` and `init` before `logIn` both end up stamped. Bounded by
1973
2314
  // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1974
2315
  await resolveIdentitySubjectNow();
2316
+ // A flush racing `init` waits for the AsyncStorage read, bounded like the
2317
+ // identity pull (no timer when there is nothing in flight).
2318
+ if (_jsInstallIdLoad && !_jsInstallIdSettled) {
2319
+ await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
2320
+ }
1975
2321
 
1976
2322
  // The /api/sdk/errors/event/batch endpoint:
1977
2323
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1978
2324
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1979
2325
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
2326
+ const installId = resolveInstallId();
1980
2327
  const serialized = batch.map((e) => {
1981
2328
  const { user: builtUser, ...rest } = e;
1982
2329
  // Idempotent: leaves an id that build time already resolved alone.
@@ -1984,6 +2331,9 @@ export const CrashReporting = {
1984
2331
  return {
1985
2332
  ...rest,
1986
2333
  ...(user ? { user } : {}),
2334
+ // Stamped at send time, like the subject: an event captured before
2335
+ // the bridge first answered still ships with it.
2336
+ ...(installId ? { installId } : {}),
1987
2337
  timestamp:
1988
2338
  typeof e.timestamp === "number"
1989
2339
  ? new Date(e.timestamp).toISOString()
@@ -2001,10 +2351,7 @@ export const CrashReporting = {
2001
2351
  try {
2002
2352
  const res = await fetch(url, {
2003
2353
  method: "POST",
2004
- headers: {
2005
- "Content-Type": "application/json",
2006
- "X-API-Key": _config.apiKey,
2007
- },
2354
+ headers: requestHeaders(_config.apiKey),
2008
2355
  body: JSON.stringify({ events: serialized }),
2009
2356
  ...(controller ? { signal: controller.signal } : {}),
2010
2357
  });
@@ -2124,6 +2471,7 @@ export const CrashReporting = {
2124
2471
  _tags = {};
2125
2472
  _extra = {};
2126
2473
  _user = null;
2474
+ _fingerprint = null;
2127
2475
  _pendingEvents = [];
2128
2476
  _inFlightEvents = new Map();
2129
2477
  if (_flushTimer !== null) {
@@ -2136,6 +2484,14 @@ export const CrashReporting = {
2136
2484
  _sessionErrorCount = 0;
2137
2485
  _backoffMs = BACKOFF_INITIAL_MS;
2138
2486
  _backoffUntil = 0;
2487
+ _pendingSessions = [];
2488
+ if (_sessionRetryTimer !== null) {
2489
+ clearTimeout(_sessionRetryTimer);
2490
+ _sessionRetryTimer = null;
2491
+ }
2492
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
2493
+ _sessionDrainInFlight = false;
2494
+ _sessionsRestored = true;
2139
2495
  clearAmbiguousStreak();
2140
2496
  if (_disableRejectionTracking) {
2141
2497
  // Teardown is the mirror image of install and can fail the same way —
@@ -2152,6 +2508,10 @@ export const CrashReporting = {
2152
2508
  _screenshotCaptureOverride = undefined;
2153
2509
  _nativeCrashModuleOverride = undefined;
2154
2510
  _identityUserId = null;
2511
+ _identityAnonymousId = null;
2512
+ _jsInstallId = null;
2513
+ _jsInstallIdLoad = null;
2514
+ _jsInstallIdSettled = false;
2155
2515
  _identityRefresh = null;
2156
2516
  // Bump the generation so a read still in flight cannot land after the
2157
2517
  // reset and repopulate the subject the reset just cleared.
@@ -2195,6 +2555,13 @@ export const CrashReporting = {
2195
2555
  return _sessionId;
2196
2556
  },
2197
2557
 
2558
+ _snapshotPendingSessions(): Array<{ sessionId: string; status: string }> {
2559
+ return _pendingSessions.map((p) => ({
2560
+ sessionId: p.sessionId,
2561
+ status: p.status,
2562
+ }));
2563
+ },
2564
+
2198
2565
  _restorePromiseForTests(): Promise<void> | null {
2199
2566
  return _restorePromise;
2200
2567
  },
@@ -2231,13 +2598,11 @@ export const CrashReporting = {
2231
2598
  * `null` = Identity bridge absent; `undefined` = resolve from react-native.
2232
2599
  * Clears the cached subject so the next resolve goes through the seam. */
2233
2600
  _setIdentityResolverForTests(
2234
- resolver:
2235
- | (() => Promise<{ userId?: string | null }>)
2236
- | null
2237
- | undefined
2601
+ resolver: (() => Promise<IdentitySnapshot>) | null | undefined
2238
2602
  ): void {
2239
2603
  _identityResolverOverride = resolver;
2240
2604
  _identityUserId = null;
2605
+ _identityAnonymousId = null;
2241
2606
  _identityRefresh = null;
2242
2607
  _identityGeneration++;
2243
2608
  },
@@ -2276,7 +2641,10 @@ export interface SKErrorBoundaryState {
2276
2641
  error: Error | null;
2277
2642
  }
2278
2643
 
2279
- export class SKErrorBoundary extends React.Component<SKErrorBoundaryProps, SKErrorBoundaryState> {
2644
+ export class SKErrorBoundary extends React.Component<
2645
+ SKErrorBoundaryProps,
2646
+ SKErrorBoundaryState
2647
+ > {
2280
2648
  constructor(props: SKErrorBoundaryProps) {
2281
2649
  super(props);
2282
2650
  this.state = { hasError: false, error: null };