@app-swiss-knife/react-native-sdk 0.3.1 → 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.
Files changed (28) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  3. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +315 -41
  4. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +13 -4
  5. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +229 -36
  6. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +6 -0
  7. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  8. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +186 -56
  9. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +182 -0
  10. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +164 -8
  11. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +418 -58
  12. package/lib/commonjs/index.js.map +1 -1
  13. package/lib/commonjs/modules/crash-reporting.js +525 -35
  14. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/module/modules/crash-reporting.js +525 -35
  17. package/lib/module/modules/crash-reporting.js.map +1 -1
  18. package/lib/typescript/commonjs/index.d.ts +1 -1
  19. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  20. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +32 -7
  21. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  22. package/lib/typescript/module/index.d.ts +1 -1
  23. package/lib/typescript/module/index.d.ts.map +1 -1
  24. package/lib/typescript/module/modules/crash-reporting.d.ts +32 -7
  25. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  26. package/package.json +2 -1
  27. package/src/index.ts +2 -0
  28. package/src/modules/crash-reporting.ts +625 -68
@@ -91,7 +91,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
91
91
  const DEFAULT_MAX_CACHE_ITEMS = 30;
92
92
  const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
93
93
  const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
94
+ /** Started/ended session events waiting on a retry (see Session Outbox). */
95
+ const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
96
+ /** Cap on queued session events — drop-oldest beyond this. */
97
+ const MAX_PENDING_SESSIONS = 50;
94
98
  const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
99
+ /** JS-side install id, only for apps without the native Identity bridge. */
100
+ const INSTALL_ID_KEY = "@swissknife:crash:install_id";
95
101
 
96
102
  // MARK: - Stack Trace Parsing
97
103
 
@@ -171,7 +177,24 @@ let _breadcrumbs = new RingBuffer(100);
171
177
  let _tags = {};
172
178
  let _extra = {};
173
179
  let _user = null;
180
+ /** Scope-level fingerprint (configureScope → setFingerprint). */
181
+ let _fingerprint = null;
174
182
  let _pendingEvents = [];
183
+ /**
184
+ * Events handed to an in-flight POST: already out of `_pendingEvents`, not
185
+ * yet acknowledged by the server. Keyed by `eventId` because two flushes
186
+ * can be in the air at once — the fatal path fires its own bounded send
187
+ * while a debounced one is still running — and each must settle only its
188
+ * own batch.
189
+ *
190
+ * This exists because `persistQueue()` mirrors the whole queue by
191
+ * overwriting a single storage key. Deriving that snapshot from
192
+ * `_pendingEvents` alone made an in-flight batch invisible to it, so the
193
+ * next `enqueueEvent()` — one more tap, landing mid-send — rewrote the key
194
+ * WITHOUT it. The first event then existed only in a local `const batch`
195
+ * and died with the process: two taps, two captured errors, one row.
196
+ */
197
+ let _inFlightEvents = new Map();
175
198
  let _flushTimer = null;
176
199
  let _originalGlobalHandler = null;
177
200
  let _sessionId = null;
@@ -221,8 +244,20 @@ let _screenshotCaptureOverride;
221
244
  // `Identity.current()` also carries an `anonymousId`, and stamping it into
222
245
  // `user.id` would make "affected users" non-zero for every app that never
223
246
  // logs in. That both inflates the number and diverges from Analytics, whose
224
- // `user_id` is the identified subject only. The anonymous id already travels
225
- // separately on the ingest envelope. Only `userId` is used here.
247
+ // `user_id` is the identified subject only. The anonymous id travels
248
+ // separately, as the wire event's `installId` (see below) — the server counts
249
+ // affected users by user id, else install id, without conflating the two.
250
+
251
+ // ## installId — the stable per-install id
252
+ //
253
+ // Most crashes have no identified subject, so the server counts affected
254
+ // users by `installId` when `user.id` is absent. It is the Identity bridge's
255
+ // `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
256
+ // carry on their ingest envelope and `app_users.anonymous_id` stores, so the
257
+ // dashboard can link an anonymous install to its profile). Apps without the
258
+ // native Identity bridge get a random id persisted in AsyncStorage; without
259
+ // AsyncStorage no installId is sent at all, because a per-launch id would
260
+ // count every relaunch as a new user.
226
261
 
227
262
  /**
228
263
  * Last resolved identified subject id from the native Identity bridge.
@@ -231,6 +266,14 @@ let _screenshotCaptureOverride;
231
266
  * stamped, which is exactly today's behaviour for apps that never log in.
232
267
  */
233
268
  let _identityUserId = null;
269
+ /** Last resolved `Identity.current().anonymousId` (stable per install). */
270
+ let _identityAnonymousId = null;
271
+ /** AsyncStorage-persisted install id; used only when no Identity bridge. */
272
+ let _jsInstallId = null;
273
+ /** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
274
+ let _jsInstallIdLoad = null;
275
+ /** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
276
+ let _jsInstallIdSettled = false;
234
277
  /** In-flight read, so N events in a burst share one bridge hop. */
235
278
  let _identityRefresh = null;
236
279
  /** Monotonic read counter — a superseded read must not clobber a newer one. */
@@ -244,6 +287,8 @@ let _identityGeneration = 0;
244
287
  */
245
288
  let _identityResolverOverride;
246
289
 
290
+ /** The fields of the native `Identity.current()` snapshot this module reads. */
291
+
247
292
  /** Budget for the send-time identity re-resolve. Kept well under
248
293
  * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
249
294
  * one chance to deliver before the process dies. */
@@ -291,6 +336,11 @@ function startIdentityRead() {
291
336
  if (generation !== _identityGeneration) return; // superseded
292
337
  const userId = snapshot?.userId;
293
338
  _identityUserId = typeof userId === "string" && userId.length > 0 ? userId : null;
339
+ // Never blanked by a later empty answer: the id is per install.
340
+ const anonymousId = snapshot?.anonymousId;
341
+ if (typeof anonymousId === "string" && anonymousId.length > 0) {
342
+ _identityAnonymousId = anonymousId;
343
+ }
294
344
  } catch {
295
345
  // Bridge hiccup — keep the last known subject.
296
346
  } finally {
@@ -369,6 +419,61 @@ function mergeIdentityInto(user) {
369
419
  };
370
420
  }
371
421
 
422
+ /** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
423
+ function withTimeout(p, ms) {
424
+ return new Promise(resolve => {
425
+ const timer = setTimeout(resolve, ms);
426
+ void p.then(() => {
427
+ clearTimeout(timer);
428
+ resolve();
429
+ }, () => {
430
+ clearTimeout(timer);
431
+ resolve();
432
+ });
433
+ });
434
+ }
435
+
436
+ /**
437
+ * The install id to stamp on outgoing events, or undefined when none is
438
+ * known. The Identity bridge's anonymous id wins; the JS-persisted id is used
439
+ * only when there is no bridge at all — mixing the two on one device (e.g. a
440
+ * slow bridge read) would count that device twice.
441
+ */
442
+ function resolveInstallId() {
443
+ if (_identityAnonymousId) return _identityAnonymousId;
444
+ if (getIdentityResolver() !== null) return undefined;
445
+ return _jsInstallId ?? undefined;
446
+ }
447
+
448
+ /**
449
+ * Load (or mint and persist) the JS-side install id. Only for apps without
450
+ * the Identity bridge; a no-op without AsyncStorage. Never throws.
451
+ */
452
+ function loadJsInstallId() {
453
+ _jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
454
+ _jsInstallIdSettled = true;
455
+ });
456
+ return _jsInstallIdLoad;
457
+ }
458
+ async function readOrMintJsInstallId() {
459
+ if (_jsInstallId || getIdentityResolver() !== null) return;
460
+ const storage = getOfflineStorage();
461
+ if (!storage) return;
462
+ try {
463
+ const stored = await storage.getItem(INSTALL_ID_KEY);
464
+ if (stored) {
465
+ _jsInstallId = stored;
466
+ return;
467
+ }
468
+ const minted = generateUUID();
469
+ await storage.setItem(INSTALL_ID_KEY, minted);
470
+ // Only use an id that made it to disk — see the module note above.
471
+ _jsInstallId = minted;
472
+ } catch {
473
+ // Storage hiccup: send no installId rather than a per-launch one.
474
+ }
475
+ }
476
+
372
477
  // MARK: - Pending Queue (memory + best-effort disk mirror)
373
478
 
374
479
  function enqueueEvent(event) {
@@ -382,12 +487,41 @@ function enqueueEvent(event) {
382
487
 
383
488
  /** Put failed sends back AHEAD of anything captured since; drop-oldest beyond cap. */
384
489
  function requeueEvents(events) {
490
+ // Back on the pending queue means no longer in flight. Clear first, or
491
+ // `persistQueue()` below counts them from both sides and the mirror
492
+ // carries each event twice.
493
+ clearInFlight(events);
385
494
  const merged = [...events, ..._pendingEvents];
386
495
  discardScreenshotsFor(merged.slice(0, -MAX_PENDING_EVENTS));
387
496
  _pendingEvents = merged.slice(-MAX_PENDING_EVENTS);
388
497
  persistQueue();
389
498
  }
390
499
 
500
+ /**
501
+ * A batch has reached a terminal outcome — acknowledged, requeued, or
502
+ * deliberately dropped — so it stops counting towards the disk mirror.
503
+ *
504
+ * Deliberately does NOT persist: every caller is about to write the
505
+ * mirror itself (via `requeueEvents` or its own `persistQueue`), and two
506
+ * overlapping fire-and-forget `setItem` calls on one key can land out of
507
+ * order.
508
+ */
509
+ function clearInFlight(events) {
510
+ for (const event of events) _inFlightEvents.delete(event.eventId);
511
+ }
512
+
513
+ /** First occurrence wins, so in-flight events keep their place at the front. */
514
+ function dedupeEventsById(events) {
515
+ const seen = new Set();
516
+ const out = [];
517
+ for (const event of events) {
518
+ if (seen.has(event.eventId)) continue;
519
+ seen.add(event.eventId);
520
+ out.push(event);
521
+ }
522
+ return out;
523
+ }
524
+
391
525
  /** Events that will never deliver must not pin their screenshots in memory. */
392
526
  function discardScreenshotsFor(dropped) {
393
527
  for (const event of dropped) {
@@ -412,13 +546,24 @@ function maxCacheItems() {
412
546
  * The slice respects `maxCacheItems`: persisted screenshots occupy cache
413
547
  * slots too, so the event slice shrinks by however many screenshots are
414
548
  * currently stored (newest events win — drop-oldest).
549
+ *
550
+ * IN-FLIGHT EVENTS COUNT. This writes the whole queue to one key, so
551
+ * whatever it leaves out is erased. An event that a POST is currently
552
+ * carrying is not delivered yet — until the server acknowledges it, it
553
+ * still has to survive a process kill exactly like a pending one. Leaving
554
+ * those out is what lost an event: capture, flush, capture again, and the
555
+ * second capture's `persistQueue()` overwrote the key without the first.
415
556
  */
416
557
  function persistQueue() {
417
558
  const storage = getOfflineStorage();
418
559
  if (!storage) return;
419
560
  const eventCap = Math.max(0, maxCacheItems() - _offlineScreenshots.length);
561
+ // In-flight events are older than anything pending, so they lead and
562
+ // drop-oldest still trims from the front. Dedupe defensively: a batch
563
+ // mid-requeue can briefly be reachable from both sides.
564
+ const live = dedupeEventsById([..._inFlightEvents.values(), ..._pendingEvents]);
420
565
  // NB: slice(-0) would return the WHOLE array — guard the zero-cap case.
421
- const snapshot = eventCap > 0 ? _pendingEvents.slice(-eventCap) : [];
566
+ const snapshot = eventCap > 0 ? live.slice(-eventCap) : [];
422
567
  void (async () => {
423
568
  try {
424
569
  if (_restorePromise) await _restorePromise;
@@ -484,20 +629,58 @@ function applyBackoff(retryAfterHeader) {
484
629
  // MARK: - Batch Response
485
630
 
486
631
  /**
487
- * Parse the batch response `{ accepted, results: [{index, eventId, status}] }`
632
+ * What we managed to learn from a 2xx batch response.
633
+ *
634
+ * `undecodable` is deliberately NOT folded into `parsed` with an empty
635
+ * `retryable` list: "the server accepted everything" and "we could not read
636
+ * the server's answer" are different facts, and only the first one licenses
637
+ * deleting the batch.
638
+ */
639
+
640
+ /**
641
+ * Read the batch response `{ accepted, results: [{index, eventId, status}] }`
488
642
  * and map 'retryable' entries back to their events (by eventId, falling back
489
- * to index). Anything else — 'accepted', 'duplicate', 'rejected', a legacy
490
- * response shape, or an unparseable body on HTTP 200 — is treated as terminal.
643
+ * to index). 'accepted', 'duplicate', 'rejected' and a legacy response shape
644
+ * are all terminal.
645
+ *
646
+ * A NON-EMPTY body that will not parse returns `undecodable`. It used to
647
+ * return "nothing is retryable", which the caller could not tell apart from a
648
+ * clean ack — so a truncated or corrupted 200 silently destroyed the batch.
649
+ * An empty body still counts as an ack: some deployments answer 200 with no
650
+ * content, and there is nothing there to have been a rejection.
491
651
  */
492
- async function extractRetryableEvents(res, batch) {
652
+ async function readBatchOutcome(res, batch) {
653
+ // Read as text first — `res.json()` cannot distinguish "empty body" from
654
+ // "malformed body", and that distinction is the whole point here.
655
+ let raw;
656
+ try {
657
+ raw = await res.text();
658
+ } catch (e) {
659
+ // The body stream itself failed mid-read: a truncated response by
660
+ // another name, so it is ambiguous for the same reason.
661
+ return {
662
+ kind: "undecodable",
663
+ preview: String(e).slice(0, 200)
664
+ };
665
+ }
666
+ if (raw.trim() === "") return {
667
+ kind: "parsed",
668
+ retryable: []
669
+ };
493
670
  let parsed = null;
494
671
  try {
495
- parsed = await res.json();
672
+ parsed = JSON.parse(raw);
496
673
  } catch {
497
- return [];
674
+ return {
675
+ kind: "undecodable",
676
+ preview: raw.slice(0, 200)
677
+ };
498
678
  }
499
679
  const results = parsed?.results;
500
- if (!Array.isArray(results)) return [];
680
+ if (!Array.isArray(results)) return {
681
+ kind: "parsed",
682
+ retryable: []
683
+ };
501
684
  const retryable = [];
502
685
  for (const entry of results) {
503
686
  if (!entry || entry.status !== "retryable") continue;
@@ -506,11 +689,70 @@ async function extractRetryableEvents(res, batch) {
506
689
  const event = byId ?? byIndex;
507
690
  if (event && !retryable.includes(event)) retryable.push(event);
508
691
  }
509
- return retryable;
692
+ return {
693
+ kind: "parsed",
694
+ retryable
695
+ };
696
+ }
697
+
698
+ // MARK: - Ambiguous-response budget
699
+
700
+ /**
701
+ * How many consecutive undecodable-2xx responses the SAME batch may collect
702
+ * before we stop retrying it.
703
+ *
704
+ * The bound is deliberate. Without it a backend permanently answering 200
705
+ * with garbage would keep the batch in `_pendingEvents` forever, re-sending
706
+ * it on every scheduled flush, while newly captured crashes pile in behind it
707
+ * until `maxCacheItems` starts dropping the OLDEST — reintroducing silent
708
+ * loss from the other end. 5 attempts, each spaced by the existing
709
+ * exponential backoff (1s doubling to a 60s ceiling), is several minutes of
710
+ * retrying before anything is given up on.
711
+ */
712
+ const MAX_AMBIGUOUS_ATTEMPTS = 5;
713
+
714
+ /** Consecutive undecodable-2xx answers for `_ambiguousBatchKey`. */
715
+ let _ambiguousAttempts = 0;
716
+ /** Identity of the batch those attempts belong to — the budget is per-batch,
717
+ * not a global "server has been flaky lately" tally. */
718
+ let _ambiguousBatchKey = null;
719
+ function batchKey(batch) {
720
+ return batch.map(e => e.eventId).join(",");
721
+ }
722
+
723
+ /** Record one ambiguous answer for `batch`; returns the running count. */
724
+ function noteAmbiguousResponse(batch) {
725
+ const key = batchKey(batch);
726
+ if (key === _ambiguousBatchKey) {
727
+ _ambiguousAttempts += 1;
728
+ } else {
729
+ _ambiguousBatchKey = key;
730
+ _ambiguousAttempts = 1;
731
+ }
732
+ return _ambiguousAttempts;
733
+ }
734
+ function clearAmbiguousStreak() {
735
+ _ambiguousAttempts = 0;
736
+ _ambiguousBatchKey = null;
510
737
  }
511
738
 
512
739
  // MARK: - Session Tracking
513
740
 
741
+ /**
742
+ * Request headers for every `/api/sdk/errors/*` call. Carries the install id
743
+ * (when known) so the server's per-device rate limit buckets this install
744
+ * separately from every other device of the app.
745
+ */
746
+ function requestHeaders(apiKey) {
747
+ const installId = resolveInstallId();
748
+ return {
749
+ "Content-Type": "application/json",
750
+ "X-API-Key": apiKey,
751
+ ...(installId ? {
752
+ "X-SK-Install-Id": installId
753
+ } : {})
754
+ };
755
+ }
514
756
  function buildSessionPayload(status) {
515
757
  const duration = _sessionStartTime !== null ? (Date.now() - _sessionStartTime) / 1000 : 0;
516
758
  const contexts = getStaticContexts();
@@ -538,8 +780,24 @@ function buildSessionPayload(status) {
538
780
  } : {})
539
781
  };
540
782
  }
783
+
784
+ /**
785
+ * Outcome of one session POST. `retryable` covers 429, 5xx and transport
786
+ * errors — the server (or network) may answer differently in a moment;
787
+ * any other 4xx is a permanent reject. `retryAfterMs` is the server's
788
+ * `Retry-After`, when it sent one.
789
+ */
790
+
791
+ function parseRetryAfterMs(header) {
792
+ const sec = header ? Number(header) : NaN;
793
+ return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
794
+ }
541
795
  async function postSessionPayload(payload, timeoutMs) {
542
- if (!_config) return false;
796
+ if (!_config) return {
797
+ ok: false,
798
+ retryable: false,
799
+ retryAfterMs: null
800
+ };
543
801
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
544
802
  const url = `${baseURL}/api/sdk/errors/session`;
545
803
  let controller = null;
@@ -551,24 +809,106 @@ async function postSessionPayload(payload, timeoutMs) {
551
809
  try {
552
810
  const res = await fetch(url, {
553
811
  method: "POST",
554
- headers: {
555
- "Content-Type": "application/json",
556
- "X-API-Key": _config.apiKey
557
- },
812
+ headers: requestHeaders(_config.apiKey),
558
813
  body: JSON.stringify(payload),
559
814
  ...(controller ? {
560
815
  signal: controller.signal
561
816
  } : {})
562
817
  });
563
- return res.ok;
818
+ if (res.ok) return {
819
+ ok: true
820
+ };
821
+ return {
822
+ ok: false,
823
+ retryable: res.status === 429 || res.status >= 500,
824
+ retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After"))
825
+ };
564
826
  } catch (e) {
565
827
  console.warn("[SwissKnife CrashReporting] session event error:", e);
566
- return false;
828
+ return {
829
+ ok: false,
830
+ retryable: true,
831
+ retryAfterMs: null
832
+ };
567
833
  } finally {
568
834
  if (timer) clearTimeout(timer);
569
835
  }
570
836
  }
571
837
 
838
+ // MARK: - Session Outbox
839
+ //
840
+ // `started` / `ended` session events used to be fire-and-forget: a 429 or a
841
+ // 5xx dropped them, and crash-free-session rates quietly lost their
842
+ // denominator. A failed retryable send now waits here — in order, persisted
843
+ // to the offline store, capped — and is retried after the server's
844
+ // `Retry-After` (or an exponential backoff when it sent none). The crashed
845
+ // session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
846
+
847
+ /** Session events awaiting a retry, oldest first. */
848
+ let _pendingSessions = [];
849
+ let _sessionRetryTimer = null;
850
+ let _sessionBackoffMs = BACKOFF_INITIAL_MS;
851
+ let _sessionDrainInFlight = false;
852
+ /**
853
+ * False from `init` until `restorePersistedState` has merged the previous
854
+ * launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
855
+ * (it would overwrite the stored outbox before restore reads it) nor drain
856
+ * (the older events must go first). Restore persists + drains once merged.
857
+ */
858
+ let _sessionsRestored = true;
859
+ function persistPendingSessions() {
860
+ if (!_sessionsRestored) return;
861
+ const storage = getOfflineStorage();
862
+ if (!storage) return;
863
+ const write = _pendingSessions.length === 0 ? storage.removeItem(OFFLINE_SESSIONS_KEY) : storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
864
+ void write.catch(() => {});
865
+ }
866
+ function scheduleSessionRetry(retryAfterMs) {
867
+ const delayMs = retryAfterMs ?? _sessionBackoffMs;
868
+ _sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
869
+ if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
870
+ _sessionRetryTimer = setTimeout(() => {
871
+ _sessionRetryTimer = null;
872
+ void drainPendingSessions();
873
+ }, delayMs);
874
+ }
875
+ function queueSessionForRetry(payload, retryAfterMs) {
876
+ _pendingSessions.push(payload);
877
+ if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
878
+ _pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
879
+ }
880
+ // Before restore has merged the stored outbox, just hold it in memory:
881
+ // restore persists and drains the merged queue.
882
+ if (!_sessionsRestored) return;
883
+ persistPendingSessions();
884
+ // A drain in flight, or a retry already booked, will pick this one up.
885
+ if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
886
+ scheduleSessionRetry(retryAfterMs);
887
+ }
888
+ }
889
+
890
+ /** Send queued session events in order until one fails retryably. */
891
+ async function drainPendingSessions() {
892
+ if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
893
+ _sessionDrainInFlight = true;
894
+ try {
895
+ while (_pendingSessions.length > 0) {
896
+ const head = _pendingSessions[0];
897
+ const result = await postSessionPayload(head);
898
+ if (!result.ok && result.retryable) {
899
+ scheduleSessionRetry(result.retryAfterMs);
900
+ return;
901
+ }
902
+ // Delivered, or permanently rejected (a retry would only spin).
903
+ if (_pendingSessions[0] === head) _pendingSessions.shift();
904
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
905
+ persistPendingSessions();
906
+ }
907
+ } finally {
908
+ _sessionDrainInFlight = false;
909
+ }
910
+ }
911
+
572
912
  /**
573
913
  * Deliberately has NO `await` before `postSessionPayload` — not even to
574
914
  * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
@@ -579,7 +919,18 @@ async function postSessionPayload(payload, timeoutMs) {
579
919
  */
580
920
  async function sendSessionEvent(status) {
581
921
  if (!_config || !_sessionId) return;
582
- await postSessionPayload(buildSessionPayload(status));
922
+ const payload = buildSessionPayload(status);
923
+ // Something is already waiting on a backoff: queue behind it so the
924
+ // server still sees `started` before `ended`, and so we do not hammer a
925
+ // server that just told us to wait.
926
+ if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
927
+ queueSessionForRetry(payload, null);
928
+ return;
929
+ }
930
+ const result = await postSessionPayload(payload);
931
+ if (!result.ok && result.retryable) {
932
+ queueSessionForRetry(payload, result.retryAfterMs);
933
+ }
583
934
  }
584
935
  function startSession() {
585
936
  _sessionId = generateUUID();
@@ -619,7 +970,9 @@ async function deliverCrashedSession() {
619
970
  _sessionStartTime = null;
620
971
  _sessionErrorCount = 0;
621
972
  if (!payload) return;
622
- const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
973
+ const {
974
+ ok
975
+ } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
623
976
  if (ok) {
624
977
  const storage = getOfflineStorage();
625
978
  if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
@@ -666,19 +1019,56 @@ function installAppStateListener() {
666
1019
  */
667
1020
  function restorePersistedState() {
668
1021
  const storage = getOfflineStorage();
669
- if (!storage) return;
1022
+ if (!storage) {
1023
+ _sessionsRestored = true;
1024
+ return;
1025
+ }
1026
+ _sessionsRestored = false;
670
1027
  _restorePromise = (async () => {
1028
+ // Read the stored session outbox FIRST, before any other await: nothing
1029
+ // this launch does may replace it before it is merged (see
1030
+ // `_sessionsRestored`).
1031
+ let storedSessions = [];
1032
+ try {
1033
+ const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
1034
+ if (rawSessions) {
1035
+ const restored = JSON.parse(rawSessions);
1036
+ if (Array.isArray(restored)) {
1037
+ storedSessions = restored.filter(p => p && typeof p.sessionId === "string");
1038
+ }
1039
+ }
1040
+ } catch {
1041
+ // Unreadable outbox: dropped; the merged persist below overwrites it.
1042
+ }
1043
+ // Earlier launch's sessions go first; anything this launch has already
1044
+ // queued stays behind them. Dedupe on (sessionId, status).
1045
+ const seen = new Set();
1046
+ _pendingSessions = [...storedSessions, ..._pendingSessions].filter(p => {
1047
+ const k = `${p.sessionId}|${p.status}`;
1048
+ if (seen.has(k)) return false;
1049
+ seen.add(k);
1050
+ return true;
1051
+ }).slice(-MAX_PENDING_SESSIONS);
1052
+ _sessionsRestored = true;
1053
+ persistPendingSessions();
671
1054
  try {
672
1055
  const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
673
1056
  if (rawSession) {
674
1057
  const payload = JSON.parse(rawSession);
675
- if (payload?.sessionId && (await postSessionPayload(payload))) {
1058
+ if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
676
1059
  await storage.removeItem(OFFLINE_SESSION_KEY);
677
1060
  }
678
1061
  }
679
1062
  } catch {
680
1063
  // undeliverable this launch — keep for the next one
681
1064
  }
1065
+ if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
1066
+ try {
1067
+ await drainPendingSessions();
1068
+ } catch {
1069
+ // retried on the next backoff / launch
1070
+ }
1071
+ }
682
1072
  try {
683
1073
  const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
684
1074
  if (rawShots) {
@@ -900,6 +1290,12 @@ function getStaticContexts() {
900
1290
 
901
1291
  // MARK: - Build Event
902
1292
 
1293
+ /** A usable fingerprint: the string entries, or null when none remain. */
1294
+ function normalizeFingerprint(fingerprint) {
1295
+ if (!Array.isArray(fingerprint)) return null;
1296
+ const entries = fingerprint.filter(entry => typeof entry === "string" && entry.length > 0);
1297
+ return entries.length > 0 ? entries : null;
1298
+ }
903
1299
  function buildEvent(level, partial = {}) {
904
1300
  const contexts = {
905
1301
  ...getStaticContexts()
@@ -927,6 +1323,9 @@ function buildEvent(level, partial = {}) {
927
1323
  },
928
1324
  user: resolveSubject(),
929
1325
  breadcrumbs: _breadcrumbs.snapshot(),
1326
+ ...(_fingerprint ? {
1327
+ fingerprint: [..._fingerprint]
1328
+ } : {}),
930
1329
  ...partial,
931
1330
  contexts
932
1331
  };
@@ -1271,6 +1670,7 @@ export const CrashReporting = {
1271
1670
  // path re-resolves anyway — this only shortens the window in which an
1272
1671
  // early event has to fall back to the send-time pull.
1273
1672
  void refreshIdentitySubject();
1673
+ void loadJsInstallId();
1274
1674
  // Every global-slot install is best-effort. `initSwissKnife()` is normally
1275
1675
  // called in module scope, so anything that throws here takes the host's
1276
1676
  // root module down with it and the app never boots (v0.2.3 did exactly
@@ -1316,6 +1716,7 @@ export const CrashReporting = {
1316
1716
  eventId: fallbackId
1317
1717
  };
1318
1718
  _sessionErrorCount++;
1719
+ const fingerprint = normalizeFingerprint(options?.fingerprint);
1319
1720
  let event = buildEvent("error", {
1320
1721
  exceptionType: error.name,
1321
1722
  exceptionValue: error.message,
@@ -1325,7 +1726,10 @@ export const CrashReporting = {
1325
1726
  ...options.tags
1326
1727
  } : {
1327
1728
  ..._tags
1328
- }
1729
+ },
1730
+ ...(fingerprint ? {
1731
+ fingerprint
1732
+ } : {})
1329
1733
  });
1330
1734
  event = applyBeforeSend(event);
1331
1735
  if (!event) return {
@@ -1380,10 +1784,7 @@ export const CrashReporting = {
1380
1784
  const url = `${baseURL}/api/sdk/errors/feedback`;
1381
1785
  fetch(url, {
1382
1786
  method: "POST",
1383
- headers: {
1384
- "Content-Type": "application/json",
1385
- "X-API-Key": _config.apiKey
1386
- },
1787
+ headers: requestHeaders(_config.apiKey),
1387
1788
  body: JSON.stringify(feedback)
1388
1789
  }).catch(e => {
1389
1790
  console.warn("[SwissKnife CrashReporting] feedback error:", e);
@@ -1420,7 +1821,9 @@ export const CrashReporting = {
1420
1821
  message: crumb.message,
1421
1822
  level: crumb.level
1422
1823
  });
1423
- } catch {/* non-fatal */}
1824
+ } catch {
1825
+ /* non-fatal */
1826
+ }
1424
1827
  }
1425
1828
  },
1426
1829
  /**
@@ -1463,7 +1866,9 @@ export const CrashReporting = {
1463
1866
  if (nativeMod) {
1464
1867
  try {
1465
1868
  nativeMod.setUser(user);
1466
- } catch {/* non-fatal */}
1869
+ } catch {
1870
+ /* non-fatal */
1871
+ }
1467
1872
  }
1468
1873
  },
1469
1874
  setTag(key, value) {
@@ -1473,7 +1878,9 @@ export const CrashReporting = {
1473
1878
  if (nativeMod) {
1474
1879
  try {
1475
1880
  nativeMod.setTag(key, value);
1476
- } catch {/* non-fatal */}
1881
+ } catch {
1882
+ /* non-fatal */
1883
+ }
1477
1884
  }
1478
1885
  },
1479
1886
  setExtra(key, value) {
@@ -1489,6 +1896,9 @@ export const CrashReporting = {
1489
1896
  },
1490
1897
  setUser: user => {
1491
1898
  _user = user;
1899
+ },
1900
+ setFingerprint: fingerprint => {
1901
+ _fingerprint = normalizeFingerprint(fingerprint);
1492
1902
  }
1493
1903
  });
1494
1904
  },
@@ -1504,6 +1914,10 @@ export const CrashReporting = {
1504
1914
  }
1505
1915
  const batch = [..._pendingEvents];
1506
1916
  _pendingEvents = [];
1917
+ // The batch has left `_pendingEvents` but nothing has acknowledged it
1918
+ // yet, so it must stay in the disk mirror. Every exit below settles
1919
+ // it — see the `finally` for the backstop.
1920
+ for (const event of batch) _inFlightEvents.set(event.eventId, event);
1507
1921
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
1508
1922
  const url = `${baseURL}/api/sdk/errors/event/batch`;
1509
1923
 
@@ -1515,11 +1929,17 @@ export const CrashReporting = {
1515
1929
  // `init` and `init` before `logIn` both end up stamped. Bounded by
1516
1930
  // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1517
1931
  await resolveIdentitySubjectNow();
1932
+ // A flush racing `init` waits for the AsyncStorage read, bounded like the
1933
+ // identity pull (no timer when there is nothing in flight).
1934
+ if (_jsInstallIdLoad && !_jsInstallIdSettled) {
1935
+ await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
1936
+ }
1518
1937
 
1519
1938
  // The /api/sdk/errors/event/batch endpoint:
1520
1939
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1521
1940
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1522
1941
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
1942
+ const installId = resolveInstallId();
1523
1943
  const serialized = batch.map(e => {
1524
1944
  const {
1525
1945
  user: builtUser,
@@ -1532,6 +1952,11 @@ export const CrashReporting = {
1532
1952
  ...(user ? {
1533
1953
  user
1534
1954
  } : {}),
1955
+ // Stamped at send time, like the subject: an event captured before
1956
+ // the bridge first answered still ships with it.
1957
+ ...(installId ? {
1958
+ installId
1959
+ } : {}),
1535
1960
  timestamp: typeof e.timestamp === "number" ? new Date(e.timestamp).toISOString() : e.timestamp
1536
1961
  };
1537
1962
  });
@@ -1544,10 +1969,7 @@ export const CrashReporting = {
1544
1969
  try {
1545
1970
  const res = await fetch(url, {
1546
1971
  method: "POST",
1547
- headers: {
1548
- "Content-Type": "application/json",
1549
- "X-API-Key": _config.apiKey
1550
- },
1972
+ headers: requestHeaders(_config.apiKey),
1551
1973
  body: JSON.stringify({
1552
1974
  events: serialized
1553
1975
  }),
@@ -1556,11 +1978,47 @@ export const CrashReporting = {
1556
1978
  } : {})
1557
1979
  });
1558
1980
  if (res.ok) {
1981
+ const outcome = await readBatchOutcome(res, batch);
1982
+ if (outcome.kind === "undecodable") {
1983
+ // A 2xx we cannot read is NOT an ack. We have no evidence the
1984
+ // server stored anything, so the batch goes back on the queue and
1985
+ // is retried under the normal backoff — the same treatment a 5xx
1986
+ // gets, because we know exactly as much as we do about a 5xx.
1987
+ //
1988
+ // Note the backoff reset stays in the decodable branch below: an
1989
+ // ambiguous answer must not reset the schedule it is about to use.
1990
+ const attempts = noteAmbiguousResponse(batch);
1991
+ if (attempts >= MAX_AMBIGUOUS_ATTEMPTS) {
1992
+ // Budget spent. Unlike the native SDKs there is no dead-letter
1993
+ // file to park these in, so the batch is dropped — but LOUDLY
1994
+ // and only after a bounded, documented number of attempts,
1995
+ // rather than silently on the first bad byte.
1996
+ clearAmbiguousStreak();
1997
+ console.warn(`[SwissKnife CrashReporting] dropping ${batch.length} event(s) after ` + `${attempts} undecodable HTTP ${res.status} responses; last body: ${outcome.preview}`);
1998
+ for (const e of batch) {
1999
+ _screenshotPromises.delete(e.eventId);
2000
+ removeOfflineScreenshot(e.eventId);
2001
+ }
2002
+ clearInFlight(batch);
2003
+ persistQueue();
2004
+ return;
2005
+ }
2006
+ console.warn(`[SwissKnife CrashReporting] undecodable HTTP ${res.status} response ` + `(attempt ${attempts}/${MAX_AMBIGUOUS_ATTEMPTS}) — requeueing ${batch.length} event(s); ` + `body: ${outcome.preview}`);
2007
+ const delayMs = applyBackoff(res.headers.get("Retry-After"));
2008
+ requeueEvents(batch);
2009
+ if (!options?.timeoutMs) scheduledFlush(delayMs);
2010
+ return;
2011
+ }
1559
2012
  _backoffMs = BACKOFF_INITIAL_MS;
1560
2013
  _backoffUntil = 0;
2014
+ clearAmbiguousStreak();
1561
2015
  // Per-event statuses: requeue ONLY 'retryable' (transient server
1562
2016
  // failure); 'accepted'/'duplicate'/'rejected' are terminal.
1563
- const retryable = await extractRetryableEvents(res, batch);
2017
+ const retryable = outcome.retryable;
2018
+ // The server has answered on the whole batch, so nothing in it is
2019
+ // in flight any more — including the retryable part, which
2020
+ // `requeueEvents` is about to put back on the pending queue.
2021
+ clearInFlight(batch);
1564
2022
  if (retryable.length > 0) {
1565
2023
  requeueEvents(retryable);
1566
2024
  scheduledFlush();
@@ -1591,6 +2049,7 @@ export const CrashReporting = {
1591
2049
  _screenshotPromises.delete(e.eventId);
1592
2050
  removeOfflineScreenshot(e.eventId);
1593
2051
  }
2052
+ clearInFlight(batch);
1594
2053
  persistQueue();
1595
2054
  } catch (e) {
1596
2055
  console.warn("[SwissKnife CrashReporting] flush error:", e);
@@ -1599,6 +2058,15 @@ export const CrashReporting = {
1599
2058
  if (!options?.timeoutMs) scheduledFlush(delayMs);
1600
2059
  } finally {
1601
2060
  if (timer) clearTimeout(timer);
2061
+ // Backstop. Every branch above settles the batch, but an entry left
2062
+ // behind by one that does not would pin its event in the disk
2063
+ // mirror forever and re-deliver it on every launch. Requeue rather
2064
+ // than drop: the same trade the native SDKs make — a duplicate is
2065
+ // visible and deduped server-side by the `errorEventSeen` ledger, a
2066
+ // silently lost crash report is neither.
2067
+ if (batch.some(event => _inFlightEvents.has(event.eventId))) {
2068
+ requeueEvents(batch);
2069
+ }
1602
2070
  }
1603
2071
  },
1604
2072
  // MARK: - Test Hooks
@@ -1609,7 +2077,9 @@ export const CrashReporting = {
1609
2077
  _tags = {};
1610
2078
  _extra = {};
1611
2079
  _user = null;
2080
+ _fingerprint = null;
1612
2081
  _pendingEvents = [];
2082
+ _inFlightEvents = new Map();
1613
2083
  if (_flushTimer !== null) {
1614
2084
  clearTimeout(_flushTimer);
1615
2085
  _flushTimer = null;
@@ -1620,6 +2090,15 @@ export const CrashReporting = {
1620
2090
  _sessionErrorCount = 0;
1621
2091
  _backoffMs = BACKOFF_INITIAL_MS;
1622
2092
  _backoffUntil = 0;
2093
+ _pendingSessions = [];
2094
+ if (_sessionRetryTimer !== null) {
2095
+ clearTimeout(_sessionRetryTimer);
2096
+ _sessionRetryTimer = null;
2097
+ }
2098
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
2099
+ _sessionDrainInFlight = false;
2100
+ _sessionsRestored = true;
2101
+ clearAmbiguousStreak();
1623
2102
  if (_disableRejectionTracking) {
1624
2103
  // Teardown is the mirror image of install and can fail the same way —
1625
2104
  // restoring a slot on a frozen host object, or an engine `enable` that
@@ -1635,6 +2114,10 @@ export const CrashReporting = {
1635
2114
  _screenshotCaptureOverride = undefined;
1636
2115
  _nativeCrashModuleOverride = undefined;
1637
2116
  _identityUserId = null;
2117
+ _identityAnonymousId = null;
2118
+ _jsInstallId = null;
2119
+ _jsInstallIdLoad = null;
2120
+ _jsInstallIdSettled = false;
1638
2121
  _identityRefresh = null;
1639
2122
  // Bump the generation so a read still in flight cannot land after the
1640
2123
  // reset and repopulate the subject the reset just cleared.
@@ -1676,6 +2159,12 @@ export const CrashReporting = {
1676
2159
  _snapshotSessionId() {
1677
2160
  return _sessionId;
1678
2161
  },
2162
+ _snapshotPendingSessions() {
2163
+ return _pendingSessions.map(p => ({
2164
+ sessionId: p.sessionId,
2165
+ status: p.status
2166
+ }));
2167
+ },
1679
2168
  _restorePromiseForTests() {
1680
2169
  return _restorePromise;
1681
2170
  },
@@ -1704,6 +2193,7 @@ export const CrashReporting = {
1704
2193
  _setIdentityResolverForTests(resolver) {
1705
2194
  _identityResolverOverride = resolver;
1706
2195
  _identityUserId = null;
2196
+ _identityAnonymousId = null;
1707
2197
  _identityRefresh = null;
1708
2198
  _identityGeneration++;
1709
2199
  },