@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.
@@ -97,7 +97,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
97
97
  const DEFAULT_MAX_CACHE_ITEMS = 30;
98
98
  const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
99
99
  const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
100
+ /** Started/ended session events waiting on a retry (see Session Outbox). */
101
+ const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
102
+ /** Cap on queued session events — drop-oldest beyond this. */
103
+ const MAX_PENDING_SESSIONS = 50;
100
104
  const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
105
+ /** JS-side install id, only for apps without the native Identity bridge. */
106
+ const INSTALL_ID_KEY = "@swissknife:crash:install_id";
101
107
 
102
108
  // MARK: - Stack Trace Parsing
103
109
 
@@ -177,6 +183,8 @@ let _breadcrumbs = new RingBuffer(100);
177
183
  let _tags = {};
178
184
  let _extra = {};
179
185
  let _user = null;
186
+ /** Scope-level fingerprint (configureScope → setFingerprint). */
187
+ let _fingerprint = null;
180
188
  let _pendingEvents = [];
181
189
  /**
182
190
  * Events handed to an in-flight POST: already out of `_pendingEvents`, not
@@ -242,8 +250,20 @@ let _screenshotCaptureOverride;
242
250
  // `Identity.current()` also carries an `anonymousId`, and stamping it into
243
251
  // `user.id` would make "affected users" non-zero for every app that never
244
252
  // logs in. That both inflates the number and diverges from Analytics, whose
245
- // `user_id` is the identified subject only. The anonymous id already travels
246
- // separately on the ingest envelope. Only `userId` is used here.
253
+ // `user_id` is the identified subject only. The anonymous id travels
254
+ // separately, as the wire event's `installId` (see below) — the server counts
255
+ // affected users by user id, else install id, without conflating the two.
256
+
257
+ // ## installId — the stable per-install id
258
+ //
259
+ // Most crashes have no identified subject, so the server counts affected
260
+ // users by `installId` when `user.id` is absent. It is the Identity bridge's
261
+ // `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
262
+ // carry on their ingest envelope and `app_users.anonymous_id` stores, so the
263
+ // dashboard can link an anonymous install to its profile). Apps without the
264
+ // native Identity bridge get a random id persisted in AsyncStorage; without
265
+ // AsyncStorage no installId is sent at all, because a per-launch id would
266
+ // count every relaunch as a new user.
247
267
 
248
268
  /**
249
269
  * Last resolved identified subject id from the native Identity bridge.
@@ -252,6 +272,14 @@ let _screenshotCaptureOverride;
252
272
  * stamped, which is exactly today's behaviour for apps that never log in.
253
273
  */
254
274
  let _identityUserId = null;
275
+ /** Last resolved `Identity.current().anonymousId` (stable per install). */
276
+ let _identityAnonymousId = null;
277
+ /** AsyncStorage-persisted install id; used only when no Identity bridge. */
278
+ let _jsInstallId = null;
279
+ /** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
280
+ let _jsInstallIdLoad = null;
281
+ /** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
282
+ let _jsInstallIdSettled = false;
255
283
  /** In-flight read, so N events in a burst share one bridge hop. */
256
284
  let _identityRefresh = null;
257
285
  /** Monotonic read counter — a superseded read must not clobber a newer one. */
@@ -265,6 +293,8 @@ let _identityGeneration = 0;
265
293
  */
266
294
  let _identityResolverOverride;
267
295
 
296
+ /** The fields of the native `Identity.current()` snapshot this module reads. */
297
+
268
298
  /** Budget for the send-time identity re-resolve. Kept well under
269
299
  * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
270
300
  * one chance to deliver before the process dies. */
@@ -312,6 +342,11 @@ function startIdentityRead() {
312
342
  if (generation !== _identityGeneration) return; // superseded
313
343
  const userId = snapshot?.userId;
314
344
  _identityUserId = typeof userId === "string" && userId.length > 0 ? userId : null;
345
+ // Never blanked by a later empty answer: the id is per install.
346
+ const anonymousId = snapshot?.anonymousId;
347
+ if (typeof anonymousId === "string" && anonymousId.length > 0) {
348
+ _identityAnonymousId = anonymousId;
349
+ }
315
350
  } catch {
316
351
  // Bridge hiccup — keep the last known subject.
317
352
  } finally {
@@ -390,6 +425,61 @@ function mergeIdentityInto(user) {
390
425
  };
391
426
  }
392
427
 
428
+ /** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
429
+ function withTimeout(p, ms) {
430
+ return new Promise(resolve => {
431
+ const timer = setTimeout(resolve, ms);
432
+ void p.then(() => {
433
+ clearTimeout(timer);
434
+ resolve();
435
+ }, () => {
436
+ clearTimeout(timer);
437
+ resolve();
438
+ });
439
+ });
440
+ }
441
+
442
+ /**
443
+ * The install id to stamp on outgoing events, or undefined when none is
444
+ * known. The Identity bridge's anonymous id wins; the JS-persisted id is used
445
+ * only when there is no bridge at all — mixing the two on one device (e.g. a
446
+ * slow bridge read) would count that device twice.
447
+ */
448
+ function resolveInstallId() {
449
+ if (_identityAnonymousId) return _identityAnonymousId;
450
+ if (getIdentityResolver() !== null) return undefined;
451
+ return _jsInstallId ?? undefined;
452
+ }
453
+
454
+ /**
455
+ * Load (or mint and persist) the JS-side install id. Only for apps without
456
+ * the Identity bridge; a no-op without AsyncStorage. Never throws.
457
+ */
458
+ function loadJsInstallId() {
459
+ _jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
460
+ _jsInstallIdSettled = true;
461
+ });
462
+ return _jsInstallIdLoad;
463
+ }
464
+ async function readOrMintJsInstallId() {
465
+ if (_jsInstallId || getIdentityResolver() !== null) return;
466
+ const storage = (0, _offlineStore.getOfflineStorage)();
467
+ if (!storage) return;
468
+ try {
469
+ const stored = await storage.getItem(INSTALL_ID_KEY);
470
+ if (stored) {
471
+ _jsInstallId = stored;
472
+ return;
473
+ }
474
+ const minted = (0, _ids.generateUUID)();
475
+ await storage.setItem(INSTALL_ID_KEY, minted);
476
+ // Only use an id that made it to disk — see the module note above.
477
+ _jsInstallId = minted;
478
+ } catch {
479
+ // Storage hiccup: send no installId rather than a per-launch one.
480
+ }
481
+ }
482
+
393
483
  // MARK: - Pending Queue (memory + best-effort disk mirror)
394
484
 
395
485
  function enqueueEvent(event) {
@@ -654,6 +744,21 @@ function clearAmbiguousStreak() {
654
744
 
655
745
  // MARK: - Session Tracking
656
746
 
747
+ /**
748
+ * Request headers for every `/api/sdk/errors/*` call. Carries the install id
749
+ * (when known) so the server's per-device rate limit buckets this install
750
+ * separately from every other device of the app.
751
+ */
752
+ function requestHeaders(apiKey) {
753
+ const installId = resolveInstallId();
754
+ return {
755
+ "Content-Type": "application/json",
756
+ "X-API-Key": apiKey,
757
+ ...(installId ? {
758
+ "X-SK-Install-Id": installId
759
+ } : {})
760
+ };
761
+ }
657
762
  function buildSessionPayload(status) {
658
763
  const duration = _sessionStartTime !== null ? (Date.now() - _sessionStartTime) / 1000 : 0;
659
764
  const contexts = getStaticContexts();
@@ -681,8 +786,24 @@ function buildSessionPayload(status) {
681
786
  } : {})
682
787
  };
683
788
  }
789
+
790
+ /**
791
+ * Outcome of one session POST. `retryable` covers 429, 5xx and transport
792
+ * errors — the server (or network) may answer differently in a moment;
793
+ * any other 4xx is a permanent reject. `retryAfterMs` is the server's
794
+ * `Retry-After`, when it sent one.
795
+ */
796
+
797
+ function parseRetryAfterMs(header) {
798
+ const sec = header ? Number(header) : NaN;
799
+ return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
800
+ }
684
801
  async function postSessionPayload(payload, timeoutMs) {
685
- if (!_config) return false;
802
+ if (!_config) return {
803
+ ok: false,
804
+ retryable: false,
805
+ retryAfterMs: null
806
+ };
686
807
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
687
808
  const url = `${baseURL}/api/sdk/errors/session`;
688
809
  let controller = null;
@@ -694,24 +815,106 @@ async function postSessionPayload(payload, timeoutMs) {
694
815
  try {
695
816
  const res = await fetch(url, {
696
817
  method: "POST",
697
- headers: {
698
- "Content-Type": "application/json",
699
- "X-API-Key": _config.apiKey
700
- },
818
+ headers: requestHeaders(_config.apiKey),
701
819
  body: JSON.stringify(payload),
702
820
  ...(controller ? {
703
821
  signal: controller.signal
704
822
  } : {})
705
823
  });
706
- return res.ok;
824
+ if (res.ok) return {
825
+ ok: true
826
+ };
827
+ return {
828
+ ok: false,
829
+ retryable: res.status === 429 || res.status >= 500,
830
+ retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After"))
831
+ };
707
832
  } catch (e) {
708
833
  console.warn("[SwissKnife CrashReporting] session event error:", e);
709
- return false;
834
+ return {
835
+ ok: false,
836
+ retryable: true,
837
+ retryAfterMs: null
838
+ };
710
839
  } finally {
711
840
  if (timer) clearTimeout(timer);
712
841
  }
713
842
  }
714
843
 
844
+ // MARK: - Session Outbox
845
+ //
846
+ // `started` / `ended` session events used to be fire-and-forget: a 429 or a
847
+ // 5xx dropped them, and crash-free-session rates quietly lost their
848
+ // denominator. A failed retryable send now waits here — in order, persisted
849
+ // to the offline store, capped — and is retried after the server's
850
+ // `Retry-After` (or an exponential backoff when it sent none). The crashed
851
+ // session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
852
+
853
+ /** Session events awaiting a retry, oldest first. */
854
+ let _pendingSessions = [];
855
+ let _sessionRetryTimer = null;
856
+ let _sessionBackoffMs = BACKOFF_INITIAL_MS;
857
+ let _sessionDrainInFlight = false;
858
+ /**
859
+ * False from `init` until `restorePersistedState` has merged the previous
860
+ * launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
861
+ * (it would overwrite the stored outbox before restore reads it) nor drain
862
+ * (the older events must go first). Restore persists + drains once merged.
863
+ */
864
+ let _sessionsRestored = true;
865
+ function persistPendingSessions() {
866
+ if (!_sessionsRestored) return;
867
+ const storage = (0, _offlineStore.getOfflineStorage)();
868
+ if (!storage) return;
869
+ const write = _pendingSessions.length === 0 ? storage.removeItem(OFFLINE_SESSIONS_KEY) : storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
870
+ void write.catch(() => {});
871
+ }
872
+ function scheduleSessionRetry(retryAfterMs) {
873
+ const delayMs = retryAfterMs ?? _sessionBackoffMs;
874
+ _sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
875
+ if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
876
+ _sessionRetryTimer = setTimeout(() => {
877
+ _sessionRetryTimer = null;
878
+ void drainPendingSessions();
879
+ }, delayMs);
880
+ }
881
+ function queueSessionForRetry(payload, retryAfterMs) {
882
+ _pendingSessions.push(payload);
883
+ if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
884
+ _pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
885
+ }
886
+ // Before restore has merged the stored outbox, just hold it in memory:
887
+ // restore persists and drains the merged queue.
888
+ if (!_sessionsRestored) return;
889
+ persistPendingSessions();
890
+ // A drain in flight, or a retry already booked, will pick this one up.
891
+ if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
892
+ scheduleSessionRetry(retryAfterMs);
893
+ }
894
+ }
895
+
896
+ /** Send queued session events in order until one fails retryably. */
897
+ async function drainPendingSessions() {
898
+ if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
899
+ _sessionDrainInFlight = true;
900
+ try {
901
+ while (_pendingSessions.length > 0) {
902
+ const head = _pendingSessions[0];
903
+ const result = await postSessionPayload(head);
904
+ if (!result.ok && result.retryable) {
905
+ scheduleSessionRetry(result.retryAfterMs);
906
+ return;
907
+ }
908
+ // Delivered, or permanently rejected (a retry would only spin).
909
+ if (_pendingSessions[0] === head) _pendingSessions.shift();
910
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
911
+ persistPendingSessions();
912
+ }
913
+ } finally {
914
+ _sessionDrainInFlight = false;
915
+ }
916
+ }
917
+
715
918
  /**
716
919
  * Deliberately has NO `await` before `postSessionPayload` — not even to
717
920
  * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
@@ -722,7 +925,18 @@ async function postSessionPayload(payload, timeoutMs) {
722
925
  */
723
926
  async function sendSessionEvent(status) {
724
927
  if (!_config || !_sessionId) return;
725
- await postSessionPayload(buildSessionPayload(status));
928
+ const payload = buildSessionPayload(status);
929
+ // Something is already waiting on a backoff: queue behind it so the
930
+ // server still sees `started` before `ended`, and so we do not hammer a
931
+ // server that just told us to wait.
932
+ if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
933
+ queueSessionForRetry(payload, null);
934
+ return;
935
+ }
936
+ const result = await postSessionPayload(payload);
937
+ if (!result.ok && result.retryable) {
938
+ queueSessionForRetry(payload, result.retryAfterMs);
939
+ }
726
940
  }
727
941
  function startSession() {
728
942
  _sessionId = (0, _ids.generateUUID)();
@@ -762,7 +976,9 @@ async function deliverCrashedSession() {
762
976
  _sessionStartTime = null;
763
977
  _sessionErrorCount = 0;
764
978
  if (!payload) return;
765
- const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
979
+ const {
980
+ ok
981
+ } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
766
982
  if (ok) {
767
983
  const storage = (0, _offlineStore.getOfflineStorage)();
768
984
  if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
@@ -809,19 +1025,56 @@ function installAppStateListener() {
809
1025
  */
810
1026
  function restorePersistedState() {
811
1027
  const storage = (0, _offlineStore.getOfflineStorage)();
812
- if (!storage) return;
1028
+ if (!storage) {
1029
+ _sessionsRestored = true;
1030
+ return;
1031
+ }
1032
+ _sessionsRestored = false;
813
1033
  _restorePromise = (async () => {
1034
+ // Read the stored session outbox FIRST, before any other await: nothing
1035
+ // this launch does may replace it before it is merged (see
1036
+ // `_sessionsRestored`).
1037
+ let storedSessions = [];
1038
+ try {
1039
+ const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
1040
+ if (rawSessions) {
1041
+ const restored = JSON.parse(rawSessions);
1042
+ if (Array.isArray(restored)) {
1043
+ storedSessions = restored.filter(p => p && typeof p.sessionId === "string");
1044
+ }
1045
+ }
1046
+ } catch {
1047
+ // Unreadable outbox: dropped; the merged persist below overwrites it.
1048
+ }
1049
+ // Earlier launch's sessions go first; anything this launch has already
1050
+ // queued stays behind them. Dedupe on (sessionId, status).
1051
+ const seen = new Set();
1052
+ _pendingSessions = [...storedSessions, ..._pendingSessions].filter(p => {
1053
+ const k = `${p.sessionId}|${p.status}`;
1054
+ if (seen.has(k)) return false;
1055
+ seen.add(k);
1056
+ return true;
1057
+ }).slice(-MAX_PENDING_SESSIONS);
1058
+ _sessionsRestored = true;
1059
+ persistPendingSessions();
814
1060
  try {
815
1061
  const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
816
1062
  if (rawSession) {
817
1063
  const payload = JSON.parse(rawSession);
818
- if (payload?.sessionId && (await postSessionPayload(payload))) {
1064
+ if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
819
1065
  await storage.removeItem(OFFLINE_SESSION_KEY);
820
1066
  }
821
1067
  }
822
1068
  } catch {
823
1069
  // undeliverable this launch — keep for the next one
824
1070
  }
1071
+ if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
1072
+ try {
1073
+ await drainPendingSessions();
1074
+ } catch {
1075
+ // retried on the next backoff / launch
1076
+ }
1077
+ }
825
1078
  try {
826
1079
  const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
827
1080
  if (rawShots) {
@@ -1043,6 +1296,12 @@ function getStaticContexts() {
1043
1296
 
1044
1297
  // MARK: - Build Event
1045
1298
 
1299
+ /** A usable fingerprint: the string entries, or null when none remain. */
1300
+ function normalizeFingerprint(fingerprint) {
1301
+ if (!Array.isArray(fingerprint)) return null;
1302
+ const entries = fingerprint.filter(entry => typeof entry === "string" && entry.length > 0);
1303
+ return entries.length > 0 ? entries : null;
1304
+ }
1046
1305
  function buildEvent(level, partial = {}) {
1047
1306
  const contexts = {
1048
1307
  ...getStaticContexts()
@@ -1070,6 +1329,9 @@ function buildEvent(level, partial = {}) {
1070
1329
  },
1071
1330
  user: resolveSubject(),
1072
1331
  breadcrumbs: _breadcrumbs.snapshot(),
1332
+ ...(_fingerprint ? {
1333
+ fingerprint: [..._fingerprint]
1334
+ } : {}),
1073
1335
  ...partial,
1074
1336
  contexts
1075
1337
  };
@@ -1414,6 +1676,7 @@ const CrashReporting = exports.CrashReporting = {
1414
1676
  // path re-resolves anyway — this only shortens the window in which an
1415
1677
  // early event has to fall back to the send-time pull.
1416
1678
  void refreshIdentitySubject();
1679
+ void loadJsInstallId();
1417
1680
  // Every global-slot install is best-effort. `initSwissKnife()` is normally
1418
1681
  // called in module scope, so anything that throws here takes the host's
1419
1682
  // root module down with it and the app never boots (v0.2.3 did exactly
@@ -1459,6 +1722,7 @@ const CrashReporting = exports.CrashReporting = {
1459
1722
  eventId: fallbackId
1460
1723
  };
1461
1724
  _sessionErrorCount++;
1725
+ const fingerprint = normalizeFingerprint(options?.fingerprint);
1462
1726
  let event = buildEvent("error", {
1463
1727
  exceptionType: error.name,
1464
1728
  exceptionValue: error.message,
@@ -1468,7 +1732,10 @@ const CrashReporting = exports.CrashReporting = {
1468
1732
  ...options.tags
1469
1733
  } : {
1470
1734
  ..._tags
1471
- }
1735
+ },
1736
+ ...(fingerprint ? {
1737
+ fingerprint
1738
+ } : {})
1472
1739
  });
1473
1740
  event = applyBeforeSend(event);
1474
1741
  if (!event) return {
@@ -1523,10 +1790,7 @@ const CrashReporting = exports.CrashReporting = {
1523
1790
  const url = `${baseURL}/api/sdk/errors/feedback`;
1524
1791
  fetch(url, {
1525
1792
  method: "POST",
1526
- headers: {
1527
- "Content-Type": "application/json",
1528
- "X-API-Key": _config.apiKey
1529
- },
1793
+ headers: requestHeaders(_config.apiKey),
1530
1794
  body: JSON.stringify(feedback)
1531
1795
  }).catch(e => {
1532
1796
  console.warn("[SwissKnife CrashReporting] feedback error:", e);
@@ -1563,7 +1827,9 @@ const CrashReporting = exports.CrashReporting = {
1563
1827
  message: crumb.message,
1564
1828
  level: crumb.level
1565
1829
  });
1566
- } catch {/* non-fatal */}
1830
+ } catch {
1831
+ /* non-fatal */
1832
+ }
1567
1833
  }
1568
1834
  },
1569
1835
  /**
@@ -1606,7 +1872,9 @@ const CrashReporting = exports.CrashReporting = {
1606
1872
  if (nativeMod) {
1607
1873
  try {
1608
1874
  nativeMod.setUser(user);
1609
- } catch {/* non-fatal */}
1875
+ } catch {
1876
+ /* non-fatal */
1877
+ }
1610
1878
  }
1611
1879
  },
1612
1880
  setTag(key, value) {
@@ -1616,7 +1884,9 @@ const CrashReporting = exports.CrashReporting = {
1616
1884
  if (nativeMod) {
1617
1885
  try {
1618
1886
  nativeMod.setTag(key, value);
1619
- } catch {/* non-fatal */}
1887
+ } catch {
1888
+ /* non-fatal */
1889
+ }
1620
1890
  }
1621
1891
  },
1622
1892
  setExtra(key, value) {
@@ -1632,6 +1902,9 @@ const CrashReporting = exports.CrashReporting = {
1632
1902
  },
1633
1903
  setUser: user => {
1634
1904
  _user = user;
1905
+ },
1906
+ setFingerprint: fingerprint => {
1907
+ _fingerprint = normalizeFingerprint(fingerprint);
1635
1908
  }
1636
1909
  });
1637
1910
  },
@@ -1662,11 +1935,17 @@ const CrashReporting = exports.CrashReporting = {
1662
1935
  // `init` and `init` before `logIn` both end up stamped. Bounded by
1663
1936
  // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1664
1937
  await resolveIdentitySubjectNow();
1938
+ // A flush racing `init` waits for the AsyncStorage read, bounded like the
1939
+ // identity pull (no timer when there is nothing in flight).
1940
+ if (_jsInstallIdLoad && !_jsInstallIdSettled) {
1941
+ await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
1942
+ }
1665
1943
 
1666
1944
  // The /api/sdk/errors/event/batch endpoint:
1667
1945
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1668
1946
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1669
1947
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
1948
+ const installId = resolveInstallId();
1670
1949
  const serialized = batch.map(e => {
1671
1950
  const {
1672
1951
  user: builtUser,
@@ -1679,6 +1958,11 @@ const CrashReporting = exports.CrashReporting = {
1679
1958
  ...(user ? {
1680
1959
  user
1681
1960
  } : {}),
1961
+ // Stamped at send time, like the subject: an event captured before
1962
+ // the bridge first answered still ships with it.
1963
+ ...(installId ? {
1964
+ installId
1965
+ } : {}),
1682
1966
  timestamp: typeof e.timestamp === "number" ? new Date(e.timestamp).toISOString() : e.timestamp
1683
1967
  };
1684
1968
  });
@@ -1691,10 +1975,7 @@ const CrashReporting = exports.CrashReporting = {
1691
1975
  try {
1692
1976
  const res = await fetch(url, {
1693
1977
  method: "POST",
1694
- headers: {
1695
- "Content-Type": "application/json",
1696
- "X-API-Key": _config.apiKey
1697
- },
1978
+ headers: requestHeaders(_config.apiKey),
1698
1979
  body: JSON.stringify({
1699
1980
  events: serialized
1700
1981
  }),
@@ -1802,6 +2083,7 @@ const CrashReporting = exports.CrashReporting = {
1802
2083
  _tags = {};
1803
2084
  _extra = {};
1804
2085
  _user = null;
2086
+ _fingerprint = null;
1805
2087
  _pendingEvents = [];
1806
2088
  _inFlightEvents = new Map();
1807
2089
  if (_flushTimer !== null) {
@@ -1814,6 +2096,14 @@ const CrashReporting = exports.CrashReporting = {
1814
2096
  _sessionErrorCount = 0;
1815
2097
  _backoffMs = BACKOFF_INITIAL_MS;
1816
2098
  _backoffUntil = 0;
2099
+ _pendingSessions = [];
2100
+ if (_sessionRetryTimer !== null) {
2101
+ clearTimeout(_sessionRetryTimer);
2102
+ _sessionRetryTimer = null;
2103
+ }
2104
+ _sessionBackoffMs = BACKOFF_INITIAL_MS;
2105
+ _sessionDrainInFlight = false;
2106
+ _sessionsRestored = true;
1817
2107
  clearAmbiguousStreak();
1818
2108
  if (_disableRejectionTracking) {
1819
2109
  // Teardown is the mirror image of install and can fail the same way —
@@ -1830,6 +2120,10 @@ const CrashReporting = exports.CrashReporting = {
1830
2120
  _screenshotCaptureOverride = undefined;
1831
2121
  _nativeCrashModuleOverride = undefined;
1832
2122
  _identityUserId = null;
2123
+ _identityAnonymousId = null;
2124
+ _jsInstallId = null;
2125
+ _jsInstallIdLoad = null;
2126
+ _jsInstallIdSettled = false;
1833
2127
  _identityRefresh = null;
1834
2128
  // Bump the generation so a read still in flight cannot land after the
1835
2129
  // reset and repopulate the subject the reset just cleared.
@@ -1871,6 +2165,12 @@ const CrashReporting = exports.CrashReporting = {
1871
2165
  _snapshotSessionId() {
1872
2166
  return _sessionId;
1873
2167
  },
2168
+ _snapshotPendingSessions() {
2169
+ return _pendingSessions.map(p => ({
2170
+ sessionId: p.sessionId,
2171
+ status: p.status
2172
+ }));
2173
+ },
1874
2174
  _restorePromiseForTests() {
1875
2175
  return _restorePromise;
1876
2176
  },
@@ -1899,6 +2199,7 @@ const CrashReporting = exports.CrashReporting = {
1899
2199
  _setIdentityResolverForTests(resolver) {
1900
2200
  _identityResolverOverride = resolver;
1901
2201
  _identityUserId = null;
2202
+ _identityAnonymousId = null;
1902
2203
  _identityRefresh = null;
1903
2204
  _identityGeneration++;
1904
2205
  },