@app-swiss-knife/react-native-sdk 0.2.3 → 0.2.5

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.
@@ -372,6 +372,190 @@ let _screenshotCaptureOverride:
372
372
  | null
373
373
  | undefined;
374
374
 
375
+ // MARK: - Identity-derived Subject
376
+ //
377
+ // ## Why the subject is PULLED, never pushed
378
+ //
379
+ // Attaching a person to a crash used to require a `CrashReporting.setUser(...)`
380
+ // call that nothing enforced and nothing validated. Forget it and every crash
381
+ // arrives with `user.id === ""`; the dashboard then reports "Affected users:
382
+ // No identified users" and the integration looks like broken crash reporting
383
+ // when it is actually complete. `Identity.logIn(...)` — the canonical "this is
384
+ // who this is" statement — did not reach this module at all.
385
+ //
386
+ // `modules/analytics.ts` already fixed this exact bug class (see the comment
387
+ // above its `buildEvent`, and `identity.ts` lines 8-16): `user_id` is derived
388
+ // from the native `Identity.current()` snapshot at event-build time rather
389
+ // than being pushed in by whoever calls `logIn`. A pull is immune to
390
+ // initialisation order, and crash reporting is precisely the module that
391
+ // starts before the identity is known — you want the handler armed on the
392
+ // first frame, long before auth state has been read.
393
+ //
394
+ // So: the crash subject is resolved from Identity at report time (and
395
+ // re-resolved at send time, see `flush`), not at login time.
396
+ //
397
+ // ## Deliberately not the anonymous id
398
+ //
399
+ // `Identity.current()` also carries an `anonymousId`, and stamping it into
400
+ // `user.id` would make "affected users" non-zero for every app that never
401
+ // logs in. That both inflates the number and diverges from Analytics, whose
402
+ // `user_id` is the identified subject only. The anonymous id already travels
403
+ // separately on the ingest envelope. Only `userId` is used here.
404
+
405
+ /**
406
+ * Last resolved identified subject id from the native Identity bridge.
407
+ * `null` means "no identified subject" — either genuinely anonymous, or the
408
+ * bridge has not answered yet. Both cases are treated the same: nothing is
409
+ * stamped, which is exactly today's behaviour for apps that never log in.
410
+ */
411
+ let _identityUserId: string | null = null;
412
+ /** In-flight read, so N events in a burst share one bridge hop. */
413
+ let _identityRefresh: Promise<void> | null = null;
414
+ /** Monotonic read counter — a superseded read must not clobber a newer one. */
415
+ let _identityGeneration = 0;
416
+ /**
417
+ * Test seam (same shape as `_nativeCrashModuleOverride`): `undefined` =
418
+ * resolve from the native bridge, `null` = pretend the Identity bridge is
419
+ * absent. Needed because `require("react-native")` under vitest reaches the
420
+ * real Flow-syntax entry point and throws, so the bridge branch is otherwise
421
+ * unreachable and "we did read Identity" would pass vacuously.
422
+ */
423
+ let _identityResolverOverride:
424
+ | (() => Promise<{ userId?: string | null }>)
425
+ | null
426
+ | undefined;
427
+
428
+ /** Budget for the send-time identity re-resolve. Kept well under
429
+ * FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
430
+ * one chance to deliver before the process dies. */
431
+ const IDENTITY_RESOLVE_TIMEOUT_MS = 250;
432
+
433
+ function getIdentityResolver():
434
+ | (() => Promise<{ userId?: string | null }>)
435
+ | null {
436
+ if (_identityResolverOverride !== undefined) {
437
+ return _identityResolverOverride;
438
+ }
439
+ try {
440
+ // Lazy require for the same reason as `getNativeCrashModule()` — a static
441
+ // import would drag react-native's Flow entry point into plain-Node and
442
+ // vitest contexts where this module must stay importable.
443
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
444
+ const mod = require("../native/module") as {
445
+ getNativeModule: () => { identityCurrent?: () => Promise<unknown> };
446
+ };
447
+ const native = mod.getNativeModule();
448
+ if (typeof native?.identityCurrent !== "function") return null;
449
+ return () =>
450
+ native.identityCurrent!() as Promise<{ userId?: string | null }>;
451
+ } catch {
452
+ // Identity bridge not linked (bare Expo app, tests, plain Node).
453
+ return null;
454
+ }
455
+ }
456
+
457
+ /**
458
+ * Issue a FRESH read of `Identity.current()` into `_identityUserId`.
459
+ *
460
+ * Never throws and never rejects — a failed read leaves the previous value in
461
+ * place rather than blanking a subject we already knew about.
462
+ *
463
+ * A generation counter discards the answer of any read that a newer read has
464
+ * already superseded, so two overlapping reads can never let the older one's
465
+ * (pre-`logIn`) snapshot win on arrival order.
466
+ */
467
+ function startIdentityRead(): Promise<void> {
468
+ const resolver = getIdentityResolver();
469
+ if (!resolver) return Promise.resolve();
470
+ const generation = ++_identityGeneration;
471
+ // `p` is only read inside the `finally`, which cannot run before the
472
+ // assignment below completes — TS can't see that, hence the explicit
473
+ // `undefined` seed rather than a definite-assignment lie.
474
+ let p: Promise<void> | undefined;
475
+ p = (async () => {
476
+ try {
477
+ const snapshot = await resolver();
478
+ if (generation !== _identityGeneration) return; // superseded
479
+ const userId = snapshot?.userId;
480
+ _identityUserId =
481
+ typeof userId === "string" && userId.length > 0 ? userId : null;
482
+ } catch {
483
+ // Bridge hiccup — keep the last known subject.
484
+ } finally {
485
+ if (_identityRefresh === p) _identityRefresh = null;
486
+ }
487
+ })();
488
+ _identityRefresh = p;
489
+ return p;
490
+ }
491
+
492
+ /**
493
+ * Warm the cache. Joins a read that is already in flight — this is only ever
494
+ * used for the opportunistic warm-up at `init`, where an answer a few
495
+ * milliseconds old is fine.
496
+ */
497
+ function refreshIdentitySubject(): Promise<void> {
498
+ return _identityRefresh ?? startIdentityRead();
499
+ }
500
+
501
+ /**
502
+ * Send-time resolve, capped at `IDENTITY_RESOLVE_TIMEOUT_MS`.
503
+ *
504
+ * Deliberately does NOT join an in-flight read. `init` kicks a warm-up read
505
+ * immediately, and the host typically calls `Identity.logIn(...)` a moment
506
+ * later — a send that piggybacked on that warm-up would be answered with the
507
+ * pre-`logIn` snapshot and ship a subject-less crash, which is the exact bug
508
+ * this whole pull exists to kill. (Found by evaluating the built bundle in
509
+ * Node, not by the unit suite: a `settle()` in the test masked the race.)
510
+ * One fresh read per flush — not per event.
511
+ *
512
+ * Returns an already-resolved promise (and arms no timer) when there is no
513
+ * Identity bridge to ask — apps without the native module, and every test
514
+ * that has not installed the seam, must not pay a timer or a scheduling hop
515
+ * for a question that has no answer.
516
+ */
517
+ function resolveIdentitySubjectNow(): Promise<void> {
518
+ if (getIdentityResolver() === null) return Promise.resolve();
519
+ const read = startIdentityRead();
520
+ return new Promise<void>((resolve) => {
521
+ const timer = setTimeout(resolve, IDENTITY_RESOLVE_TIMEOUT_MS);
522
+ void read.then(() => {
523
+ clearTimeout(timer);
524
+ resolve();
525
+ });
526
+ });
527
+ }
528
+
529
+ /**
530
+ * Merge the explicit `setUser` override with the Identity-derived subject.
531
+ *
532
+ * Precedence is **field-by-field, explicit wins**:
533
+ * - `id` — `setUser`'s id if set, else `Identity.current().userId`
534
+ * - `email` — explicit only (Identity has no such field)
535
+ * - `username` — explicit only
536
+ *
537
+ * When nothing resolves, `null` is returned and the `user` key is omitted
538
+ * from the wire payload entirely — byte-identical to today for an app that
539
+ * neither logs in nor calls `setUser`.
540
+ */
541
+ function resolveSubject(): SKCrashUser | null {
542
+ return mergeIdentityInto(_user);
543
+ }
544
+
545
+ /**
546
+ * Fill in the Identity-derived `id` on a subject that does not already carry
547
+ * one. Idempotent: a subject that already has an `id` is returned untouched,
548
+ * so applying this at build time and again at send time cannot change it.
549
+ */
550
+ function mergeIdentityInto(
551
+ user: SKCrashUser | null | undefined
552
+ ): SKCrashUser | null {
553
+ if (user?.id) return user;
554
+ const id = _identityUserId;
555
+ if (!id) return user ?? null;
556
+ return { ...(user ?? {}), id };
557
+ }
558
+
375
559
  // MARK: - Pending Queue (memory + best-effort disk mirror)
376
560
 
377
561
  function enqueueEvent(event: SKCrashEvent): void {
@@ -552,6 +736,9 @@ function buildSessionPayload(status: SessionPayload["status"]): SessionPayload {
552
736
  const contexts = getStaticContexts();
553
737
  const os = contexts.os as { name?: string; version?: string } | undefined;
554
738
  const device = contexts.device as { model?: string } | undefined;
739
+ // Same pull as events: explicit `setUser` id wins, else the Identity
740
+ // subject. Synchronous, so it reads the cache `flush`/`init` keep warm.
741
+ const subject = resolveSubject();
555
742
  return {
556
743
  sessionId: _sessionId!,
557
744
  status,
@@ -559,7 +746,7 @@ function buildSessionPayload(status: SessionPayload["status"]): SessionPayload {
559
746
  errorsCount: _sessionErrorCount,
560
747
  releaseVersion: _config?.release,
561
748
  environment: _config?.environment,
562
- ...(_user?.id ? { userId: _user.id } : {}),
749
+ ...(subject?.id ? { userId: subject.id } : {}),
563
750
  ...(os?.name ? { osName: os.name, osVersion: os.version } : {}),
564
751
  ...(device?.model ? { deviceModel: device.model } : {}),
565
752
  };
@@ -600,6 +787,14 @@ async function postSessionPayload(
600
787
  }
601
788
  }
602
789
 
790
+ /**
791
+ * Deliberately has NO `await` before `postSessionPayload` — not even to
792
+ * re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
793
+ * error count the instant this function yields, and callers rely on the POST
794
+ * being issued in the same tick. Session payloads therefore take the subject
795
+ * from the warm cache only (see `buildSessionPayload`); the authoritative
796
+ * re-resolve happens on the event path in `flush`.
797
+ */
603
798
  async function sendSessionEvent(
604
799
  status: "started" | "ended" | "crashed"
605
800
  ): Promise<void> {
@@ -1004,7 +1199,7 @@ function buildEvent(
1004
1199
  ...(_config?.dist ? { dist: _config.dist } : {}),
1005
1200
  tags: { ..._tags },
1006
1201
  extra: { ..._extra },
1007
- user: _user,
1202
+ user: resolveSubject(),
1008
1203
  breadcrumbs: _breadcrumbs.snapshot(),
1009
1204
  ...partial,
1010
1205
  contexts,
@@ -1101,8 +1296,69 @@ interface RejectionTrackingOptions {
1101
1296
  type RejectionEnableFn = (opts: RejectionTrackingOptions) => void;
1102
1297
 
1103
1298
  /**
1104
- * Wrap a single-slot `enable(options)` entry point so a LATER caller composes
1105
- * with us instead of evicting us.
1299
+ * Run a global-slot installer so that a failure costs that one feature and
1300
+ * nothing else. Crash reporting is strictly an add-on to the host app; there
1301
+ * is no failure here worth taking the app down for.
1302
+ */
1303
+ function neverThrow(what: string, fn: () => void): void {
1304
+ try {
1305
+ fn();
1306
+ } catch (e) {
1307
+ console.warn(`[SwissKnife CrashReporting] ${what} unavailable:`, e);
1308
+ }
1309
+ }
1310
+
1311
+ /**
1312
+ * Replace a property on an object we do not own, without ever throwing.
1313
+ *
1314
+ * A bare `target.key = value` is not safe on host objects. `HermesInternal` is
1315
+ * **frozen** on every real Hermes build, so its properties are non-writable
1316
+ * and non-configurable; because this module is strict-mode (ES module), the
1317
+ * assignment throws `TypeError: Cannot assign to read-only property` rather
1318
+ * than failing silently. That throw propagated out of `CrashReporting.init`
1319
+ * and — since `initSwissKnife()` is normally called in module scope — aborted
1320
+ * evaluation of the host's root module, so the app never booted. Frozen host
1321
+ * globals must be *probed*, and a refusal must degrade, never escalate.
1322
+ *
1323
+ * Returns true only if the slot genuinely now holds `value`.
1324
+ */
1325
+ function trySetHostProperty(
1326
+ target: object,
1327
+ key: string,
1328
+ value: unknown
1329
+ ): boolean {
1330
+ try {
1331
+ if (Object.isFrozen(target)) return false;
1332
+ const desc = Object.getOwnPropertyDescriptor(target, key);
1333
+ // Non-configurable data property with writable:false — nothing can
1334
+ // replace it. Bail before we provoke a TypeError.
1335
+ if (desc && !desc.configurable && !desc.writable) return false;
1336
+ if (desc === undefined || desc.configurable) {
1337
+ // defineProperty also covers own accessor properties (a getter with no
1338
+ // setter would silently swallow a plain assignment), and never walks
1339
+ // the prototype chain the way `=` does.
1340
+ Object.defineProperty(target, key, {
1341
+ value,
1342
+ writable: desc?.writable ?? true,
1343
+ enumerable: desc?.enumerable ?? true,
1344
+ configurable: true,
1345
+ });
1346
+ } else {
1347
+ // Non-configurable but writable — assignment is the only route.
1348
+ (target as Record<string, unknown>)[key] = value;
1349
+ }
1350
+ // Confirm it actually took. Proxies and exotic host objects can accept a
1351
+ // write and keep the old value; treating that as success would leave us
1352
+ // believing we own a slot we do not.
1353
+ return (target as Record<string, unknown>)[key] === value;
1354
+ } catch {
1355
+ return false;
1356
+ }
1357
+ }
1358
+
1359
+ /**
1360
+ * Build a wrapper around a single-slot `enable(options)` entry point so a
1361
+ * LATER caller composes with us instead of evicting us.
1106
1362
  *
1107
1363
  * Promise-rejection tracking is the one global in this SDK that offers no way
1108
1364
  * to read the incumbent handler back out — see
@@ -1118,14 +1374,16 @@ type RejectionEnableFn = (opts: RejectionTrackingOptions) => void;
1118
1374
  * silently forcing it back to true would make the API a lie (our own
1119
1375
  * `_disableRejectionTracking` uses it).
1120
1376
  *
1121
- * Returns the un-wrapped original so the caller can restore it on teardown.
1377
+ * Installing the returned wrapper is the caller's job and is strictly an
1378
+ * enhancement: tracking is already live from the direct `original(options)`
1379
+ * call, so a host that refuses the swap keeps full rejection capture and only
1380
+ * loses the compose-with-a-later-reporter nicety.
1122
1381
  */
1123
- function composeRejectionEnable(
1124
- install: (fn: RejectionEnableFn) => void,
1382
+ function makeComposingRejectionEnable(
1125
1383
  original: RejectionEnableFn,
1126
1384
  ours: RejectionTrackingOptions
1127
- ): void {
1128
- install((theirs: RejectionTrackingOptions) => {
1385
+ ): RejectionEnableFn {
1386
+ return (theirs: RejectionTrackingOptions) => {
1129
1387
  if (!theirs || theirs.allRejections === false) {
1130
1388
  original(theirs);
1131
1389
  return;
@@ -1149,7 +1407,7 @@ function composeRejectionEnable(
1149
1407
  theirs.onHandled?.(id);
1150
1408
  },
1151
1409
  });
1152
- });
1410
+ };
1153
1411
  }
1154
1412
 
1155
1413
  function installPromiseRejectionTracking(): void {
@@ -1174,17 +1432,24 @@ function installPromiseRejectionTracking(): void {
1174
1432
  // host's own function object back, not a bound copy of it.
1175
1433
  const engineEnable = hermes.enablePromiseRejectionTracker;
1176
1434
  const original = engineEnable.bind(hermes);
1435
+ // This one call IS the tracking. Everything below is enhancement.
1177
1436
  original(options);
1178
- composeRejectionEnable(
1179
- (fn) => {
1180
- hermes.enablePromiseRejectionTracker = fn;
1181
- },
1182
- original,
1183
- options
1184
- );
1185
1437
  _rejectionTrackingInstalled = true;
1438
+
1439
+ // `HermesInternal` is frozen on real devices, so this swap usually fails —
1440
+ // that is expected and harmless. Never let it throw out of init().
1441
+ const composed = trySetHostProperty(
1442
+ hermes,
1443
+ "enablePromiseRejectionTracker",
1444
+ makeComposingRejectionEnable(original, options)
1445
+ );
1446
+
1186
1447
  _disableRejectionTracking = () => {
1187
- hermes.enablePromiseRejectionTracker = engineEnable;
1448
+ // Mirror image of the install: only restore what we managed to replace,
1449
+ // and go through the same non-throwing path.
1450
+ if (composed) {
1451
+ trySetHostProperty(hermes, "enablePromiseRejectionTracker", engineEnable);
1452
+ }
1188
1453
  original({ allRejections: false, onUnhandled: () => {} });
1189
1454
  };
1190
1455
  return;
@@ -1200,17 +1465,23 @@ function installPromiseRejectionTracking(): void {
1200
1465
  };
1201
1466
  const moduleEnable = tracking.enable;
1202
1467
  const original = moduleEnable.bind(tracking);
1468
+ // As above: this call is the tracking; the swap below is enhancement.
1203
1469
  original(options);
1204
- composeRejectionEnable(
1205
- (fn) => {
1206
- tracking.enable = fn;
1207
- },
1208
- original,
1209
- options
1210
- );
1211
1470
  _rejectionTrackingInstalled = true;
1471
+
1472
+ // Metro hands back a mutable CommonJS `module.exports` here, but any
1473
+ // bundler that gives this module ES-namespace semantics makes `enable`
1474
+ // read-only — same failure mode as HermesInternal, so same guard.
1475
+ const composed = trySetHostProperty(
1476
+ tracking,
1477
+ "enable",
1478
+ makeComposingRejectionEnable(original, options)
1479
+ );
1480
+
1212
1481
  _disableRejectionTracking = () => {
1213
- tracking.enable = moduleEnable;
1482
+ if (composed) {
1483
+ trySetHostProperty(tracking, "enable", moduleEnable);
1484
+ }
1214
1485
  tracking.disable();
1215
1486
  };
1216
1487
  } catch {
@@ -1314,8 +1585,21 @@ export const CrashReporting = {
1314
1585
  ...config,
1315
1586
  };
1316
1587
  _breadcrumbs = new RingBuffer(_config.maxBreadcrumbs!);
1317
- if (_config.enableGlobalErrorHandler) installGlobalHandler();
1318
- if (_config.enablePromiseRejectionTracking) installPromiseRejectionTracking();
1588
+ // Warm the Identity subject cache. Fire-and-forget: crash reporting must
1589
+ // arm on the first frame and cannot wait on a bridge hop, and every send
1590
+ // path re-resolves anyway — this only shortens the window in which an
1591
+ // early event has to fall back to the send-time pull.
1592
+ void refreshIdentitySubject();
1593
+ // Every global-slot install is best-effort. `initSwissKnife()` is normally
1594
+ // called in module scope, so anything that throws here takes the host's
1595
+ // root module down with it and the app never boots (v0.2.3 did exactly
1596
+ // that against frozen `HermesInternal`). Degrade the feature, not the app.
1597
+ if (_config.enableGlobalErrorHandler) {
1598
+ neverThrow("global error handler", installGlobalHandler);
1599
+ }
1600
+ if (_config.enablePromiseRejectionTracking) {
1601
+ neverThrow("promise rejection tracking", installPromiseRejectionTracking);
1602
+ }
1319
1603
  restorePersistedState();
1320
1604
  startSession();
1321
1605
  if (_config.enableAppStateTracking) installAppStateListener();
@@ -1343,8 +1627,8 @@ export const CrashReporting = {
1343
1627
 
1344
1628
  // Install automatic breadcrumbs
1345
1629
  if (_config.enableAutoBreadcrumbs) {
1346
- installHTTPBreadcrumbs();
1347
- installConsoleBreadcrumbs();
1630
+ neverThrow("http breadcrumbs", installHTTPBreadcrumbs);
1631
+ neverThrow("console breadcrumbs", installConsoleBreadcrumbs);
1348
1632
  }
1349
1633
  },
1350
1634
 
@@ -1464,9 +1748,42 @@ export const CrashReporting = {
1464
1748
  }
1465
1749
  },
1466
1750
 
1751
+ /**
1752
+ * Explicitly override the crash subject.
1753
+ *
1754
+ * **You do not need this to get a subject onto crash reports.** The `id` is
1755
+ * pulled from `Identity.current()` at report time, so a plain
1756
+ * `Identity.logIn("u_42")` is enough — see the "Identity-derived Subject"
1757
+ * section in this file. `setUser` exists for the two things Identity cannot
1758
+ * express: extra fields, and a subject that deliberately differs from the
1759
+ * identity in effect.
1760
+ *
1761
+ * ## Precedence — field-by-field, explicit wins
1762
+ *
1763
+ * | field | source |
1764
+ * | ---------- | --------------------------------------------------- |
1765
+ * | `id` | this call's `id` if set, else `Identity.current().userId` |
1766
+ * | `email` | this call only — Identity has no email |
1767
+ * | `username` | this call only — Identity has no username |
1768
+ *
1769
+ * So `setUser({ email })` after `Identity.logIn("u_42")` yields
1770
+ * `{ id: "u_42", email }`, and `setUser({ id: "other" })` yields
1771
+ * `{ id: "other" }` — the identity is not allowed to overwrite an id the
1772
+ * host stated on purpose.
1773
+ *
1774
+ * `setUser(null)` clears **only this override**. It does not suppress the
1775
+ * Identity-derived id; call `Identity.logOut()` for that. (With no identity
1776
+ * and no override, `user` is omitted from the payload entirely, exactly as
1777
+ * before this pull existed.)
1778
+ *
1779
+ * Resolution happens at report time, never at login time, so the order of
1780
+ * `init` / `logIn` / `setUser` does not matter.
1781
+ */
1467
1782
  setUser(user: SKCrashUser | null): void {
1468
1783
  _user = user;
1469
- // Forward to native layer for crash-time user context
1784
+ // Forward the EXPLICIT override to native, unmerged. The native crash
1785
+ // SDKs run the same precedence against their own `Identity.current`, so
1786
+ // sending a merged subject here would pin the id and defeat their pull.
1470
1787
  const nativeMod = getNativeCrashModule();
1471
1788
  if (nativeMod) {
1472
1789
  try {
@@ -1515,12 +1832,23 @@ export const CrashReporting = {
1515
1832
  const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
1516
1833
  const url = `${baseURL}/api/sdk/errors/event/batch`;
1517
1834
 
1835
+ // Re-resolve the subject at SEND time. `buildEvent` is synchronous and
1836
+ // can only read the cached snapshot, so an event captured before the
1837
+ // Identity bridge first answered would otherwise ship subject-less —
1838
+ // which is the whole failure mode this pull exists to kill. Doing it
1839
+ // here makes ordering irrelevant in both directions: `logIn` before
1840
+ // `init` and `init` before `logIn` both end up stamped. Bounded by
1841
+ // IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
1842
+ await resolveIdentitySubjectNow();
1843
+
1518
1844
  // The /api/sdk/errors/event/batch endpoint:
1519
1845
  // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1520
1846
  // - rejects `user: null` (schema marks `user` optional, not nullable)
1521
1847
  // Coerce both on the wire so the internal SDK shape stays ergonomic.
1522
1848
  const serialized = batch.map((e) => {
1523
- const { user, ...rest } = e;
1849
+ const { user: builtUser, ...rest } = e;
1850
+ // Idempotent: leaves an id that build time already resolved alone.
1851
+ const user = mergeIdentityInto(builtUser);
1524
1852
  return {
1525
1853
  ...rest,
1526
1854
  ...(user ? { user } : {}),
@@ -1621,7 +1949,10 @@ export const CrashReporting = {
1621
1949
  _backoffMs = BACKOFF_INITIAL_MS;
1622
1950
  _backoffUntil = 0;
1623
1951
  if (_disableRejectionTracking) {
1624
- _disableRejectionTracking();
1952
+ // Teardown is the mirror image of install and can fail the same way —
1953
+ // restoring a slot on a frozen host object, or an engine `enable` that
1954
+ // throws. Drop the reference either way so a failure can't wedge reset.
1955
+ neverThrow("promise rejection teardown", _disableRejectionTracking);
1625
1956
  _disableRejectionTracking = null;
1626
1957
  }
1627
1958
  _rejectionTrackingInstalled = false;
@@ -1631,22 +1962,30 @@ export const CrashReporting = {
1631
1962
  _offlineScreenshots = [];
1632
1963
  _screenshotCaptureOverride = undefined;
1633
1964
  _nativeCrashModuleOverride = undefined;
1965
+ _identityUserId = null;
1966
+ _identityRefresh = null;
1967
+ // Bump the generation so a read still in flight cannot land after the
1968
+ // reset and repopulate the subject the reset just cleared.
1969
+ _identityGeneration++;
1970
+ _identityResolverOverride = undefined;
1634
1971
  _appStateOverride = undefined;
1635
1972
  if (_appStateSubscription) {
1636
1973
  _appStateSubscription.remove();
1637
1974
  _appStateSubscription = null;
1638
1975
  }
1639
- // Restore patched globals
1976
+ // Restore patched globals. These three slots are writable everywhere RN
1977
+ // runs (RN itself repatches them), but restoring is still a write to an
1978
+ // object we do not own, so it goes through the same non-throwing path.
1640
1979
  if (_originalFetch) {
1641
- globalThis.fetch = _originalFetch;
1980
+ trySetHostProperty(globalThis, "fetch", _originalFetch);
1642
1981
  _originalFetch = null;
1643
1982
  }
1644
1983
  if (_originalConsoleWarn) {
1645
- console.warn = _originalConsoleWarn;
1984
+ trySetHostProperty(console, "warn", _originalConsoleWarn);
1646
1985
  _originalConsoleWarn = null;
1647
1986
  }
1648
1987
  if (_originalConsoleError) {
1649
- console.error = _originalConsoleError;
1988
+ trySetHostProperty(console, "error", _originalConsoleError);
1650
1989
  _originalConsoleError = null;
1651
1990
  }
1652
1991
  },
@@ -1699,6 +2038,26 @@ export const CrashReporting = {
1699
2038
  _nativeCrashModuleOverride = mod;
1700
2039
  },
1701
2040
 
2041
+ /** Test seam: stand in for the native `Identity.current()` bridge call.
2042
+ * `null` = Identity bridge absent; `undefined` = resolve from react-native.
2043
+ * Clears the cached subject so the next resolve goes through the seam. */
2044
+ _setIdentityResolverForTests(
2045
+ resolver:
2046
+ | (() => Promise<{ userId?: string | null }>)
2047
+ | null
2048
+ | undefined
2049
+ ): void {
2050
+ _identityResolverOverride = resolver;
2051
+ _identityUserId = null;
2052
+ _identityRefresh = null;
2053
+ _identityGeneration++;
2054
+ },
2055
+
2056
+ /** @internal Current Identity-derived subject id, for assertions. */
2057
+ _identitySubjectForTests(): string | null {
2058
+ return _identityUserId;
2059
+ },
2060
+
1702
2061
  /** Test seam: stand in for react-native's `AppState`. */
1703
2062
  _setAppStateForTests(
1704
2063
  appState: