@scalebun/react-native 2.0.0 → 2.0.2

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 (70) hide show
  1. package/android/src/main/java/com/scalebun/rn/ota/BundleDownloader.kt +10 -0
  2. package/android/src/main/java/com/scalebun/rn/ota/DeviceIntegrity.kt +75 -0
  3. package/android/src/main/java/com/scalebun/rn/ota/ScaleBunOtaModule.kt +18 -3
  4. package/android/src/main/java/com/scalebun/rn/ota/SlotManager.kt +62 -1
  5. package/android/src/main/java/com/scalebun/rn/ota/TlsPinning.kt +118 -0
  6. package/android/src/oldarch/java/com/scalebun/rn/ota/ScaleBunOtaSpec.kt +2 -0
  7. package/dist/scalebun.full.js +840 -114
  8. package/dist/scalebun.slim.js +838 -112
  9. package/ios/ReplaySdk.swift +65 -2
  10. package/lib/commonjs/bootstrap/SDKBootstrapper.js +30 -0
  11. package/lib/commonjs/core/config/schema.js +16 -0
  12. package/lib/commonjs/core/constants/version.js +1 -1
  13. package/lib/commonjs/features/journey/ScaleBunDebugRoot.js +293 -5
  14. package/lib/commonjs/features/journey/ScaleBunScrollView.js +28 -0
  15. package/lib/commonjs/features/journey/autoInstrumentScroll.js +161 -0
  16. package/lib/commonjs/features/journey/interactionProtocol.js +131 -10
  17. package/lib/commonjs/features/journey/scrollContext.js +146 -0
  18. package/lib/commonjs/features/journey/targetGeometry.js +164 -0
  19. package/lib/commonjs/features/journey/touchTarget.js +152 -24
  20. package/lib/commonjs/features/journey/uiState.js +81 -1
  21. package/lib/commonjs/features/navigation/AutoScreenDetector.js +74 -5
  22. package/lib/commonjs/features/ota/OtaOrchestrator.js +69 -22
  23. package/lib/commonjs/features/session/SessionManager.js +63 -0
  24. package/lib/commonjs/public/ScaleBunFacade.js +18 -16
  25. package/lib/module/bootstrap/SDKBootstrapper.js +30 -0
  26. package/lib/module/core/config/schema.js +16 -0
  27. package/lib/module/core/constants/version.js +1 -1
  28. package/lib/module/features/journey/ScaleBunDebugRoot.js +295 -7
  29. package/lib/module/features/journey/ScaleBunScrollView.js +28 -0
  30. package/lib/module/features/journey/autoInstrumentScroll.js +155 -0
  31. package/lib/module/features/journey/interactionProtocol.js +128 -8
  32. package/lib/module/features/journey/scrollContext.js +135 -0
  33. package/lib/module/features/journey/targetGeometry.js +155 -0
  34. package/lib/module/features/journey/touchTarget.js +151 -24
  35. package/lib/module/features/journey/uiState.js +78 -1
  36. package/lib/module/features/navigation/AutoScreenDetector.js +74 -5
  37. package/lib/module/features/ota/OtaOrchestrator.js +69 -22
  38. package/lib/module/features/session/SessionManager.js +63 -0
  39. package/lib/module/public/ScaleBunFacade.js +18 -16
  40. package/lib/typescript/core/config/schema.d.ts +2 -0
  41. package/lib/typescript/core/constants/version.d.ts +1 -1
  42. package/lib/typescript/features/journey/autoInstrumentScroll.d.ts +46 -0
  43. package/lib/typescript/features/journey/interactionProtocol.d.ts +139 -1
  44. package/lib/typescript/features/journey/scrollContext.d.ts +85 -0
  45. package/lib/typescript/features/journey/targetGeometry.d.ts +114 -0
  46. package/lib/typescript/features/journey/touchTarget.d.ts +148 -15
  47. package/lib/typescript/features/journey/uiState.d.ts +39 -0
  48. package/lib/typescript/features/navigation/AutoScreenDetector.d.ts +48 -2
  49. package/lib/typescript/features/ota/OtaOrchestrator.d.ts +7 -0
  50. package/lib/typescript/features/session/SessionManager.d.ts +55 -0
  51. package/lib/typescript/public/types.d.ts +10 -0
  52. package/lib/typescript/specs/NativeScaleBunOta.d.ts +2 -0
  53. package/package.json +2 -2
  54. package/src/bootstrap/SDKBootstrapper.ts +40 -0
  55. package/src/core/config/schema.ts +18 -0
  56. package/src/core/constants/version.ts +1 -1
  57. package/src/features/journey/ScaleBunDebugRoot.tsx +288 -7
  58. package/src/features/journey/ScaleBunScrollView.tsx +29 -0
  59. package/src/features/journey/autoInstrumentScroll.ts +155 -0
  60. package/src/features/journey/interactionProtocol.ts +188 -10
  61. package/src/features/journey/scrollContext.ts +137 -0
  62. package/src/features/journey/targetGeometry.ts +176 -0
  63. package/src/features/journey/touchTarget.ts +237 -26
  64. package/src/features/journey/uiState.ts +80 -1
  65. package/src/features/navigation/AutoScreenDetector.ts +65 -5
  66. package/src/features/ota/OtaOrchestrator.ts +76 -22
  67. package/src/features/session/SessionManager.ts +113 -0
  68. package/src/public/ScaleBunFacade.ts +18 -16
  69. package/src/public/types.ts +10 -0
  70. package/src/specs/NativeScaleBunOta.ts +3 -0
@@ -28,12 +28,15 @@ import React, {
28
28
  type ReactNode,
29
29
  } from 'react';
30
30
  import { View, NativeEventEmitter, NativeModules } from 'react-native';
31
- import { resolveTouchTarget, describeTouchTarget } from './touchTarget';
31
+ import { resolveTouchTarget, describeTouchTarget, targetIdentity } from './touchTarget';
32
+ import { localPoint, normalizeRect, readRectSync, type NormalizedRect } from './targetGeometry';
33
+ import { nativeTagOf, nearestRecordedOffset } from './scrollContext';
32
34
  import { resolvePlatformOS } from '../../core/context/device';
33
35
  import {
34
36
  INTERACTION_PROTOCOL_VERSION,
35
37
  generateInteractionId,
36
- nearestInteractionStart,
38
+ correlateInteraction,
39
+ pruneInteractionStarts,
37
40
  type InteractionStartContext,
38
41
  } from './interactionProtocol';
39
42
 
@@ -53,6 +56,15 @@ function getBootstrap() {
53
56
 
54
57
  const JourneyContext = createContext<any>(null);
55
58
 
59
+ /**
60
+ * Floor on how often a UI-state change may request a screenshot.
61
+ *
62
+ * One frame per second is far finer than any state a person perceives changing, and far coarser
63
+ * than a render loop — which is the case that matters, because a host may legitimately declare
64
+ * state from inside render and an oscillating dimension would otherwise capture continuously.
65
+ */
66
+ const UI_STATE_CAPTURE_MIN_INTERVAL_MS = 1000;
67
+
56
68
  // ─── ScaleBunDebugRoot ───────────────────────────────────────────────────────────
57
69
 
58
70
  interface ScaleBunDebugRootProps {
@@ -275,6 +287,50 @@ export function ScaleBunDebugRoot({
275
287
  };
276
288
  }, [navigationRef]);
277
289
 
290
+ /**
291
+ * RN-11 — CAPTURE A FRAME WHEN THE UI CHANGES SHAPE.
292
+ *
293
+ * A declared state used to have no picture of its own. Nothing captured on `setUiState`, so a
294
+ * state's visual existed only if a screenshot happened to be taken for another reason — a
295
+ * navigation, a timer, or the interaction capture that fires AFTER the touch and therefore
296
+ * photographs the outcome. A drawer could be recorded as open with no frame showing it open,
297
+ * or with the frame of the screen that replaced it.
298
+ *
299
+ * The native capture reasons are NAVIGATION, MANUAL, INTERACTION and TIMER; none of them means
300
+ * "the UI changed shape". This routes through the MANUAL path, which is the only one reachable
301
+ * from JS. A dedicated native reason would let the backend tell a state capture from a
302
+ * developer-requested one, and that is a native change on both platforms — worth doing, not
303
+ * doable from here.
304
+ *
305
+ * RATE LIMITED, and the limit is not politeness. A screenshot is expensive, and while
306
+ * `uiState` already collapses redundant declarations, a genuinely oscillating dimension (a
307
+ * spinner toggling, a live-updating badge) would otherwise capture continuously. One frame per
308
+ * second is far finer than any state a person can perceive changing and far coarser than a
309
+ * render loop.
310
+ *
311
+ * Requests only; never awaits and never throws. If the session is not recording,
312
+ * `captureManualFrame` declines and the state simply has no frame — which is the honest
313
+ * outcome and is exactly what the analytics-only lane already reports elsewhere.
314
+ */
315
+ useEffect(() => {
316
+ let lastCaptureTs = 0;
317
+ const { onUiStateChange } = require('./uiState');
318
+ const unsubscribe = onUiStateChange(() => {
319
+ const now = Date.now();
320
+ if (now - lastCaptureTs < UI_STATE_CAPTURE_MIN_INTERVAL_MS) return;
321
+ lastCaptureTs = now;
322
+ try {
323
+ const { SessionManager } = require('../session/SessionManager');
324
+ const sm = SessionManager.getExistingInstance();
325
+ if (sm && typeof (sm as any).captureManualFrame === 'function') {
326
+ /* Fire and forget: the tap that follows must not wait on a screenshot. */
327
+ void (sm as any).captureManualFrame();
328
+ }
329
+ } catch { /* no-throw */ }
330
+ });
331
+ return unsubscribe;
332
+ }, []);
333
+
278
334
  // ─── Native Interaction Listener ────────────────────────────────────
279
335
  // Receives high-confidence ScaleBunNativeInteraction events from the native tracker
280
336
  // and forwards them to SessionManager as USER_ACTION events.
@@ -301,7 +357,30 @@ export function ScaleBunDebugRoot({
301
357
  ? event.occurredAt
302
358
  : (typeof event.timestamp === 'number' ? event.timestamp : Date.now()) -
303
359
  (typeof event.durationMs === 'number' ? event.durationMs : 0);
304
- const start = nearestInteractionStart(interactionStartsRef.current, nativeOccurredAt);
360
+ /**
361
+ * RN-6 — correlate, then CONSUME. See interactionProtocol.ts for why
362
+ * the join is on time at all, and why a refusal is the important part.
363
+ *
364
+ * Pruning first is part of the correctness, not tidying: a start older
365
+ * than the tolerance can never be paired, but while it sits in the list
366
+ * it is still counted by the ambiguity test, so a stale entry can turn a
367
+ * clear pairing into a refusal — and the list only grows.
368
+ */
369
+ pruneInteractionStarts(interactionStartsRef.current, nativeOccurredAt);
370
+ const correlation = correlateInteraction(
371
+ interactionStartsRef.current,
372
+ nativeOccurredAt,
373
+ );
374
+ const start = correlation.start;
375
+ /**
376
+ * ONE-TO-ONE. Without removing the matched start, a second native event
377
+ * arriving within the window claims the SAME js evidence, so one tap's
378
+ * target is stamped onto another tap that never had one — a duplicate
379
+ * identity that reads as two genuine interactions on the same control.
380
+ */
381
+ if (correlation.index >= 0) {
382
+ interactionStartsRef.current.splice(correlation.index, 1);
383
+ }
305
384
 
306
385
  // Cancel only this physical touch's fallback. A single timer used to cancel a
307
386
  // previous rapid tap and silently lose it on devices without native tracking.
@@ -330,11 +409,63 @@ export function ScaleBunDebugRoot({
330
409
  interactionId: event.interactionId || start?.interactionId || generateInteractionId(),
331
410
  interactionProtocol: event.interactionProtocol || INTERACTION_PROTOCOL_VERSION,
332
411
  occurredAt: nativeOccurredAt,
412
+ /**
413
+ * RN-6 — THESE FIVE FIELDS ARE THE ONLY ONES THE JOIN CARRIES, AND
414
+ * THEREFORE THE ONLY ONES A BAD JOIN CAN FALSIFY.
415
+ *
416
+ * Coordinates below come from native and are right regardless. So a
417
+ * mispairing does not produce visibly broken data: it produces heat
418
+ * in the correct position attributed to the wrong control, in the
419
+ * wrong UI state, on the wrong screen. Every field is individually
420
+ * well-formed and nothing downstream can tell.
421
+ *
422
+ * When the correlation is not 'exact' they are left UNDEFINED rather
423
+ * than filled from a best guess. An interaction with no target is
424
+ * honest and visibly incomplete — the accounting lane can count it as
425
+ * unplaceable and say why. An interaction with the WRONG target is
426
+ * indistinguishable from a correct one and silently corrupts every
427
+ * aggregate it enters. `null` is not `0`, and a guess is not a
428
+ * measurement.
429
+ */
333
430
  ui: start?.ui,
334
431
  stateStatus: start?.stateStatus ?? 'not_captured',
335
432
  target: start?.target,
336
433
  targetId: start?.targetId,
434
+ targetSource: start?.targetSource,
337
435
  screenName: start?.screenName,
436
+ screenSource: start?.screenSource ?? 'none',
437
+ targetRect: start?.targetRect,
438
+ /**
439
+ * RN-15 — WHERE IN THE CONTROL, computed where both halves exist: the
440
+ * point comes from the native event and the rect was measured at
441
+ * finger-down, in the same capture base. Pairing them here rather than
442
+ * downstream stops anything later reaching for a different rect.
443
+ */
444
+ ...(() => {
445
+ const lp = localPoint(
446
+ start?.targetRect ?? null,
447
+ event.normalizedX,
448
+ event.normalizedY,
449
+ );
450
+ return lp ? { localU: lp.u, localV: lp.v } : {};
451
+ })(),
452
+ scrollX: start?.scrollX,
453
+ scrollY: start?.scrollY,
454
+ scrollSource: start?.scrollSource ?? 'none',
455
+ itemKey: start?.itemKey,
456
+ itemIndex: start?.itemIndex,
457
+ /**
458
+ * The join's own verdict, shipped with the row so it is auditable
459
+ * rather than a claim made in a comment. 'ambiguous' and 'none' are
460
+ * deliberately distinguished: 'none' means the JS handler never fired
461
+ * (a real capture gap on this platform), 'ambiguous' means it fired
462
+ * more than once too close together to attribute. Those have
463
+ * different fixes, and collapsing them would hide which one is
464
+ * actually happening in production.
465
+ */
466
+ correlation: correlation.outcome,
467
+ correlationDeltaMs: correlation.deltaMs,
468
+ correlationRunnerUpDeltaMs: correlation.runnerUpDeltaMs,
338
469
  emitAutomaticAnalytics: start?.emitAutomaticAnalytics ?? captureAutomaticInteractions,
339
470
  x: event.rawX,
340
471
  y: event.rawY,
@@ -411,13 +542,28 @@ export function ScaleBunDebugRoot({
411
542
  const target = resolveTouchTarget(e);
412
543
  let ui: string | undefined;
413
544
  let screenName: string | undefined;
545
+ /**
546
+ * RN-8 — WHERE the screen name came from, carried with the interaction.
547
+ *
548
+ * Production shows 13.8% of Android interactions with a screen and 0.5% on iOS, and
549
+ * those figures cannot distinguish three unrelated causes: nothing was instrumented,
550
+ * a manual beacon was instrumented but never reached interactions, or auto-detection
551
+ * ran and failed. Each has a different owner. Recording the source turns one
552
+ * unactionable percentage into three answerable ones.
553
+ */
554
+ let screenSource: 'manual' | 'navigation' | 'none' = 'none';
414
555
  try {
415
556
  const { uiStateSignature } = require('./uiState');
416
557
  ui = uiStateSignature();
417
558
  } catch { /* no-throw */ }
418
559
  try {
419
560
  const { AutoScreenDetector } = require('../navigation/AutoScreenDetector');
420
- screenName = AutoScreenDetector.getInstance().getCurrentScreen() || undefined;
561
+ const detector = AutoScreenDetector.getInstance();
562
+ screenName = detector.getCurrentScreen() || undefined;
563
+ /* Read from the SAME call site as the name, so the two can never describe
564
+ different moments — the detector is polled and its answer can change between
565
+ two reads a few milliseconds apart. */
566
+ screenSource = screenName ? detector.getCurrentScreenSource() : 'none';
421
567
  } catch { /* no-throw */ }
422
568
  const start: TouchStartContext = {
423
569
  interactionId: generateInteractionId(),
@@ -426,9 +572,88 @@ export function ScaleBunDebugRoot({
426
572
  y: touch.pageY,
427
573
  locationX: touch.locationX,
428
574
  locationY: touch.locationY,
575
+ /**
576
+ * RN-1 + RN-2 — the identity that is persisted, and it is now code-derived.
577
+ *
578
+ * `describeTouchTarget` returns `testID` -> structural path -> component name,
579
+ * and never a caption or an accessibilityLabel. Before RN-2 it preferred free
580
+ * text, so this line was writing user data ("Pay EGP 1,442", an order row
581
+ * labelled with an email address, a contact's name) into the analytics store —
582
+ * and, because `target` is an aggregation key, splitting one button into one
583
+ * bucket per person at the same time.
584
+ *
585
+ * `targetId` used to be `target?.testID` alone, which is `undefined` in the
586
+ * overwhelming majority of apps — no testIDs authored — so the field the
587
+ * backend keys on was empty almost always. It now falls back to the structural
588
+ * path, with `targetSource` recording WHICH it got.
589
+ */
429
590
  target: describeTouchTarget(target),
430
- targetId: target?.testID,
591
+ targetId: targetIdentity(target).id,
592
+ /**
593
+ * WHICH KIND of identity this is, because they are not equally trustworthy: a
594
+ * `testID` is a promise from the app's authors that this control is this
595
+ * control; a `path` is an inference that breaks when the tree is refactored.
596
+ * Without this the accounting lane cannot distinguish "the control had no
597
+ * identity" from "the identity is a structural guess", and both would render
598
+ * as an equally confident target.
599
+ */
600
+ targetSource: targetIdentity(target).source,
601
+ /* RN-4 — row identity from the app's own keyExtractor; see touchTarget.ts. */
602
+ itemKey: target?.itemKey,
603
+ itemIndex: target?.itemIndex,
604
+ /**
605
+ * RN-13 — the control's rectangle, so `heat ∈ target` is decidable.
606
+ *
607
+ * Read SYNCHRONOUSLY here, in the same tick as the touch, and normalized against
608
+ * the SAME measured root the tap's own coordinates use. Both halves matter:
609
+ *
610
+ * - A callback measurement (`measureInWindow`) would resolve after this handler
611
+ * returns, so the rect attached to a tap could be the previous tap's, with
612
+ * nothing afterwards able to tell. `targetGeometry` refuses to guess: it reads
613
+ * now or reports null.
614
+ * - Normalizing against a window size instead of the root view is off by the
615
+ * status bar on most devices, which would read as "the heat is just outside
616
+ * the button" everywhere rather than as a measurement bug.
617
+ *
618
+ * `measureRoot()` is called first because the cached root rect is populated
619
+ * asynchronously at mount; without it the first taps of a session normalize
620
+ * against nothing and get a null rect for a reason that has nothing to do with
621
+ * the control.
622
+ */
623
+ /**
624
+ * RN-3 — WHERE IN THE CONTENT, not just where on the glass.
625
+ *
626
+ * Two taps at the same screen coordinate one viewport apart are two different
627
+ * controls. Without an offset they merge into one hotspot, and the heatmap shows
628
+ * heavy engagement at a position where, in content terms, nothing in particular
629
+ * is. The offset is also a CACHE dimension — two scroll states of one route must
630
+ * not share a backdrop — so its absence corrupts the picture as well as the count.
631
+ *
632
+ * `ancestors` is innermost-first, so this takes the NEAREST scroller that has a
633
+ * recorded position: a tap inside a horizontal carousel belongs to the carousel's
634
+ * content, not to how far the page behind it had scrolled.
635
+ *
636
+ * Null when no ancestor has one — never zero. Zero is a real scroll position (the
637
+ * top of a list), and reporting it for "unknown" would place every unmeasured tap
638
+ * at the top of its content, indistinguishable from a genuine tap there.
639
+ */
640
+ ...(() => {
641
+ const hit = nearestRecordedOffset(
642
+ (target?.ancestors ?? []).map((n) => nativeTagOf(n)),
643
+ );
644
+ return hit
645
+ ? { scrollX: hit.x, scrollY: hit.y, scrollSource: 'wrapper' as const }
646
+ : { scrollSource: 'none' as const };
647
+ })(),
648
+ targetRect: (() => {
649
+ measureRoot();
650
+ const root = rootRectRef.current;
651
+ /* null -> undefined: the context field is optional, and an explicit null would
652
+ serialise as a JSON null claiming "measured, and it was nothing". */
653
+ return normalizeRect(readRectSync(target?.node), root ? { w: root.w, h: root.h } : null) ?? undefined;
654
+ })(),
431
655
  screenName,
656
+ screenSource,
432
657
  ui,
433
658
  stateStatus: ui ? 'captured_nonempty' : 'not_instrumented',
434
659
  emitAutomaticAnalytics: captureAutomaticInteractions,
@@ -473,7 +698,20 @@ export function ScaleBunDebugRoot({
473
698
  // WHAT was tapped, resolved from the React fiber on the touch event. Without this the tap
474
699
  // carries only coordinates, so every tap in the app groups into one row per gesture type.
475
700
  // Defensive by construction — returns undefined rather than throwing (see touchTarget.ts).
476
- const tapped = start?.target ?? describeTouchTarget(resolveTouchTarget(e));
701
+ /**
702
+ * Resolved ONCE, so `target` and `targetId` cannot disagree about the same tap.
703
+ *
704
+ * The previous shape called `resolveTouchTarget(e)` inline for `target` while
705
+ * `targetId` came only from `start` — so on the fallback path (no JS start, or a
706
+ * refused correlation) the tap carried a description with NO id, and the two fields
707
+ * were computed from different sources. Anything joining on `targetId` therefore
708
+ * saw nothing for a tap that visibly had a target.
709
+ */
710
+ const freshTarget = start ? null : resolveTouchTarget(e);
711
+ const tapped = start?.target ?? describeTouchTarget(freshTarget);
712
+ const identity = start
713
+ ? { id: start.targetId, source: start.targetSource }
714
+ : targetIdentity(freshTarget);
477
715
 
478
716
  const gestureDetails: any = {
479
717
  target: tapped,
@@ -482,8 +720,16 @@ export function ScaleBunDebugRoot({
482
720
  occurredAt: start?.occurredAt ?? Date.now(),
483
721
  ui: start?.ui,
484
722
  stateStatus: start?.stateStatus ?? 'not_captured',
485
- targetId: start?.targetId,
723
+ targetId: identity.id,
724
+ targetSource: identity.source,
486
725
  screenName: start?.screenName,
726
+ screenSource: start?.screenSource ?? 'none',
727
+ targetRect: start?.targetRect,
728
+ scrollX: start?.scrollX,
729
+ scrollY: start?.scrollY,
730
+ scrollSource: start?.scrollSource ?? 'none',
731
+ itemKey: start?.itemKey,
732
+ itemIndex: start?.itemIndex,
487
733
  emitAutomaticAnalytics: start?.emitAutomaticAnalytics ?? captureAutomaticInteractions,
488
734
  x: start?.x ?? touch.pageX,
489
735
  y: start?.y ?? touch.pageY,
@@ -506,6 +752,19 @@ export function ScaleBunDebugRoot({
506
752
  const ny = Math.max(0, Math.min(1, (start?.y ?? touch.pageY) / rootRect.h));
507
753
  gestureDetails.normalizedX = nx;
508
754
  gestureDetails.normalizedY = ny;
755
+ /**
756
+ * RN-15 on the JS-fallback lane.
757
+ *
758
+ * Computed here rather than in the literal above because that is where nx/ny first
759
+ * exist. The rect is the SAME one the native lane uses, so one physical tap yields
760
+ * the same local position whichever lane captured it — two lanes disagreeing about
761
+ * where in a control a tap landed would be worse than neither reporting it.
762
+ */
763
+ const lp = localPoint(start?.targetRect ?? null, nx, ny);
764
+ if (lp) {
765
+ gestureDetails.localU = lp.u;
766
+ gestureDetails.localV = lp.v;
767
+ }
509
768
  gestureDetails.normalizedPrecomputed = true;
510
769
  gestureDetails.viewportWidth = rootRect.w;
511
770
  gestureDetails.viewportHeight = rootRect.h;
@@ -695,6 +954,28 @@ export function useScaleBunScreen(name: string): void {
695
954
  }
696
955
  } catch { /* no-throw */ }
697
956
 
957
+ /**
958
+ * RN-8 — TELL THE DETECTOR TOO, because interactions read their screen from IT.
959
+ *
960
+ * This hook fed SessionManager, PerformanceFeature, ProfilerFeature and JourneyManager
961
+ * — four consumers — and never `AutoScreenDetector`. But `handleTouchStart` resolves an
962
+ * interaction's `screenName` from `AutoScreenDetector.getCurrentScreen()`, so a
963
+ * manually-instrumented app produced perfectly-named SCREEN_VIEW events while every TAP
964
+ * carried no screen at all. `setManualScreen` existed and was called only by tests.
965
+ *
966
+ * That is the whole story for apps the auto-hook cannot help: expo-router, a custom
967
+ * navigator, anything not `@react-navigation/native`. The documented manual escape hatch
968
+ * did not reach the one field that partitions every heatmap.
969
+ *
970
+ * Requires the last-writer-wins fix in `_currentScreen()` to be useful: under the
971
+ * previous rule a manual screen was readable for only 2000 ms, so wiring this alone
972
+ * would have handed interactions a name that expired before most taps happened.
973
+ */
974
+ try {
975
+ const { AutoScreenDetector } = require('../navigation/AutoScreenDetector');
976
+ AutoScreenDetector.getInstance().setManualScreen(name);
977
+ } catch { /* no-throw */ }
978
+
698
979
  // Feed PerformanceFeature (screen context for perf metrics)
699
980
  // NOTE: Only sets screen identity. Does NOT call markScreenLoadStart/End.
700
981
  // AutoScreenLoadCollector handles timing independently via rAF + InteractionManager.
@@ -52,6 +52,35 @@ export const ScaleBunScrollView = React.forwardRef<ScrollView, ScrollViewProps>(
52
52
  }
53
53
  } catch { /* no-throw */ }
54
54
 
55
+ /**
56
+ * RN-3 — record WHERE THIS scroller sits, keyed by its own native tag, so a later
57
+ * tap can say which content was under the finger.
58
+ *
59
+ * OUTSIDE the `isActive` guard above, deliberately. That guard is correct for the
60
+ * gesture tracker, which produces scroll EVENTS and should only do so while
61
+ * recording. This is a different thing: it is the position a tap needs in order to
62
+ * be placed in content rather than on glass, and a tap is captured on the always-on
63
+ * analytics lane even when no recording is active. Gating this the same way would
64
+ * make content depth absent in exactly the sessions the heatmap is built from.
65
+ *
66
+ * The tag is taken from the EVENT's target rather than from this component's ref,
67
+ * so it identifies the scroller that actually moved. With nested scrollers the
68
+ * event may come from an inner one, and keying by the wrapper would file the
69
+ * carousel's offset under the list.
70
+ */
71
+ try {
72
+ const { recordScrollOffset, nativeTagOf } = require('./scrollContext');
73
+ const { contentOffset, target } = event.nativeEvent as unknown as {
74
+ contentOffset: { x: number; y: number };
75
+ target?: unknown;
76
+ };
77
+ recordScrollOffset(
78
+ typeof target === 'number' ? target : nativeTagOf(target),
79
+ contentOffset.x,
80
+ contentOffset.y,
81
+ );
82
+ } catch { /* no-throw */ }
83
+
55
84
  // Forward to user's onScroll handler
56
85
  if (userOnScroll) {
57
86
  userOnScroll(event);
@@ -0,0 +1,155 @@
1
+ import { nativeTagOf, recordScrollOffset } from './scrollContext';
2
+
3
+ /**
4
+ * RN-3, ZERO-CONFIG — make every ScrollView report its offset, not just the wrapped ones.
5
+ *
6
+ * THE PROBLEM THIS SOLVES. Scroll offsets reach the SDK from `ScaleBunScrollView` and nowhere
7
+ * else, so an app using React Native's own `<ScrollView>` — which is most apps — produces taps
8
+ * with no content depth at all. Two taps at the same screen coordinate one viewport apart then
9
+ * merge into one hotspot, and the heatmap shows heavy engagement at a position where, in content
10
+ * terms, nothing in particular is. Asking every integration to swap its scroll views is a real
11
+ * migration cost and will never reach the long tail.
12
+ *
13
+ * WHY IT IS OFF BY DEFAULT, and why that is not timidity. This patches React Native's own module
14
+ * exports. Every scroll view in the host app — including ones inside third-party libraries the
15
+ * app did not write — starts routing through an SDK component. The failure mode of getting that
16
+ * wrong is not a wrong number in a dashboard, it is the host's UI behaving differently because an
17
+ * analytics SDK replaced a primitive. That is a decision an integrator makes with their eyes open,
18
+ * not a default they discover afterwards.
19
+ *
20
+ * THE PRECEDENT, AND ITS LESSON. The SDK already patches `@react-navigation/native` this way
21
+ * (`AutoScreenDetector._autoHookReactNavigation`). That hook shipped BROKEN: it assigned to module
22
+ * exports that are getters, which throws in strict mode, inside a `catch` that discarded the
23
+ * error. It reported success, captured no ref, and the whole screen-name pipeline stayed empty
24
+ * with nothing to indicate it. So this uses the same defence that fixed it — define the property
25
+ * rather than assign to it, then READ IT BACK — and refuses to claim success it has not verified.
26
+ *
27
+ * WHAT IT DELIBERATELY DOES NOT PATCH. `FlatList` and `SectionList` render a `ScrollView`
28
+ * internally, so patching that one export covers them without touching three. Fewer patch points
29
+ * is fewer ways to be wrong, and RN-4's row identity comes off the fiber regardless of which
30
+ * component rendered it.
31
+ */
32
+
33
+ interface PatchResult {
34
+ /** True only when the replacement was verified by reading it back. */
35
+ installed: boolean;
36
+ /** Why not, when it did not install — for a diagnostic the host can act on. */
37
+ reason?: string;
38
+ }
39
+
40
+ let alreadyPatched = false;
41
+
42
+ /**
43
+ * Replace an export on a module whose exports are GETTERS.
44
+ *
45
+ * React Native's index is compiled re-exports, which bundlers emit as accessors with a getter and
46
+ * no setter. Plain assignment throws in strict mode and silently does nothing in sloppy mode.
47
+ * Defining the property works where assigning does not, and the read-back is what turns a future
48
+ * failure into a visible one instead of a silent no-op.
49
+ */
50
+ function redefine(target: Record<string, unknown>, key: string, value: unknown): boolean {
51
+ try {
52
+ Object.defineProperty(target, key, {
53
+ configurable: true,
54
+ enumerable: true,
55
+ writable: true,
56
+ value,
57
+ });
58
+ return target[key] === value;
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Wrap a scroll component so its offsets are recorded, forwarding everything else untouched.
66
+ *
67
+ * The host's own `onScroll` is called AFTER the offset is recorded and is never replaced: an SDK
68
+ * that swallows a host's handler breaks the app, which is a far worse outcome than missing
69
+ * analytics. Recording first also means a throwing host handler cannot cost us the measurement.
70
+ */
71
+ function instrument(Original: any, React: any): any {
72
+ const Wrapped = React.forwardRef((props: any, ref: unknown) => {
73
+ const onScroll = (event: any) => {
74
+ try {
75
+ const target = event?.nativeEvent?.target;
76
+ const offset = event?.nativeEvent?.contentOffset;
77
+ if (offset) {
78
+ recordScrollOffset(
79
+ typeof target === 'number' ? target : nativeTagOf(target),
80
+ offset.x,
81
+ offset.y,
82
+ );
83
+ }
84
+ } catch {
85
+ /* no-throw: a scroll offset is never worth breaking a gesture over */
86
+ }
87
+ try {
88
+ props?.onScroll?.(event);
89
+ } catch (e) {
90
+ /* The host's handler is the host's problem, but it must still run and still throw where
91
+ they can see it — rethrow on a later tick so this wrapper is not in the stack. */
92
+ setTimeout(() => {
93
+ throw e;
94
+ }, 0);
95
+ }
96
+ };
97
+ /**
98
+ * `scrollEventThrottle` defaults to 16 only when the host has not chosen one. Overriding a
99
+ * host's explicit value would change how often their own handler runs — a behaviour change
100
+ * for a measurement, which is exactly the trade this module is not allowed to make.
101
+ */
102
+ const throttle = props?.scrollEventThrottle ?? 16;
103
+ return React.createElement(Original, {
104
+ ...props,
105
+ scrollEventThrottle: throttle,
106
+ onScroll,
107
+ ref,
108
+ });
109
+ });
110
+ Wrapped.displayName = 'ScaleBunAutoScrollView';
111
+ return Wrapped;
112
+ }
113
+
114
+ /**
115
+ * Patch React Native's `ScrollView` export so every scroll view reports its offset.
116
+ *
117
+ * Idempotent, no-throw, and honest about failure: returns `installed: false` with a reason rather
118
+ * than claiming a success it did not verify.
119
+ */
120
+ export function autoInstrumentScrollViews(): PatchResult {
121
+ if (alreadyPatched) return { installed: true };
122
+ try {
123
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
124
+ const RN = require('react-native') as Record<string, unknown>;
125
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
126
+ const React = require('react');
127
+ const Original = RN.ScrollView;
128
+ if (typeof Original !== 'function' && typeof Original !== 'object') {
129
+ return { installed: false, reason: 'react-native has no ScrollView export to wrap' };
130
+ }
131
+ if ((Original as { __scalebunInstrumented?: boolean }).__scalebunInstrumented) {
132
+ alreadyPatched = true;
133
+ return { installed: true };
134
+ }
135
+ const Wrapped = instrument(Original, React);
136
+ (Wrapped as { __scalebunInstrumented?: boolean }).__scalebunInstrumented = true;
137
+ if (!redefine(RN, 'ScrollView', Wrapped)) {
138
+ return {
139
+ installed: false,
140
+ reason:
141
+ "react-native's ScrollView export could not be replaced — it is a getter with no " +
142
+ 'configurable descriptor on this bundler. Use ScaleBunScrollView explicitly instead.',
143
+ };
144
+ }
145
+ alreadyPatched = true;
146
+ return { installed: true };
147
+ } catch (e) {
148
+ return { installed: false, reason: (e as Error)?.message ?? 'unknown failure' };
149
+ }
150
+ }
151
+
152
+ /** Test seam: forget that the patch ran, so a suite can exercise it more than once. */
153
+ export function resetAutoInstrumentForTests(): void {
154
+ alreadyPatched = false;
155
+ }