@mixpanel/react-native-session-replay 1.3.0 → 1.4.1

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 (25) hide show
  1. package/MixpanelReactNativeSessionReplay.podspec +1 -1
  2. package/README.md +1 -1
  3. package/android/build.gradle +10 -3
  4. package/android/src/main/java/com/mixpanelreactnativesessionreplay/MixpanelReactNativeSessionReplayModule.kt +54 -0
  5. package/android/src/main/java/com/mixpanelreactnativesessionreplay/MixpanelSessionReplayView.kt +56 -0
  6. package/android/src/main/java/com/mixpanelreactnativesessionreplay/MixpanelSessionReplayViewManager.kt +5 -0
  7. package/android/src/test/java/com/mixpanelreactnativesessionreplay/WireframeTextDeclarationTest.kt +41 -0
  8. package/ios/MixpanelReactNativeSessionReplay.h +7 -2
  9. package/ios/MixpanelReactNativeSessionReplay.mm +35 -2
  10. package/ios/MixpanelSessionReplayViewManager.mm +9 -0
  11. package/ios/MixpanelSwiftSessionReplay.swift +43 -1
  12. package/lib/module/MixpanelSessionReplayView.js.map +1 -1
  13. package/lib/module/NativeMixpanelReactNativeSessionReplay.js.map +1 -1
  14. package/lib/module/index.js +468 -23
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/typescript/src/MixpanelSessionReplayView.d.ts +32 -0
  17. package/lib/typescript/src/MixpanelSessionReplayView.d.ts.map +1 -1
  18. package/lib/typescript/src/NativeMixpanelReactNativeSessionReplay.d.ts +2 -0
  19. package/lib/typescript/src/NativeMixpanelReactNativeSessionReplay.d.ts.map +1 -1
  20. package/lib/typescript/src/index.d.ts +259 -10
  21. package/lib/typescript/src/index.d.ts.map +1 -1
  22. package/package.json +1 -1
  23. package/src/MixpanelSessionReplayView.tsx +33 -0
  24. package/src/NativeMixpanelReactNativeSessionReplay.ts +7 -0
  25. package/src/index.tsx +515 -22
package/src/index.tsx CHANGED
@@ -1,4 +1,11 @@
1
- import { Platform, processColor, type ColorValue } from 'react-native';
1
+ import {
2
+ NativeEventEmitter,
3
+ Platform,
4
+ processColor,
5
+ type ColorValue,
6
+ type EmitterSubscription,
7
+ type NativeModule,
8
+ } from 'react-native';
2
9
  import MixpanelReactNativeSessionReplay from './NativeMixpanelReactNativeSessionReplay';
3
10
 
4
11
  export enum MPSessionReplayMask {
@@ -30,6 +37,94 @@ export const MPDataResidency: Readonly<Record<'US' | 'EU' | 'IN', string>> = {
30
37
  IN: 'https://api-in.mixpanel.com',
31
38
  };
32
39
 
40
+ /**
41
+ * Why a wireframe element's text was kept, rewritten, or dropped.
42
+ *
43
+ * Reported through {@link MPDebugOptions.wireframeEmitter} for local inspection only.
44
+ * These are the same `SCREAMING_SNAKE_CASE` tokens Android, iOS and Flutter report, so
45
+ * the same decision reads identically on every platform.
46
+ *
47
+ * ⚠️ **Not a stable contract.** Values may be added or renamed; treat an unrecognized
48
+ * one as "some kind of masking" rather than matching exhaustively. That is also why
49
+ * {@link MPWireframeElement.maskDecision} is typed `string` rather than a closed union —
50
+ * a new native value should not become a type error.
51
+ */
52
+ export const MPMaskDecision = {
53
+ /** Text emitted as-is. */
54
+ None: 'NONE',
55
+ /** Text you declared with the `wireframeText` prop. Sent even when masked. */
56
+ Declared: 'DECLARED',
57
+ /** Explicitly masked — `<MPSessionReplayView sensitive>` or a registered class. */
58
+ Explicit: 'EXPLICIT',
59
+ /** Auto-masked by an `autoMaskedViews` category. */
60
+ Auto: 'AUTO',
61
+ /** A text-entry field. Always masked, cannot be overridden. */
62
+ TextEntry: 'TEXT_ENTRY',
63
+ /** Bounds intersected a mask rect the screenshot painted over. */
64
+ Geometric: 'GEOMETRIC',
65
+ /** Matched a strip rule; text was dropped. */
66
+ RuleStrip: 'RULE_STRIP',
67
+ /** Matched a redact rule; text was rewritten. */
68
+ RuleRedact: 'RULE_REDACT',
69
+ } as const;
70
+
71
+ /** One element of a captured wireframe. See {@link MPWireframeSnapshot}. */
72
+ export interface MPWireframeElement {
73
+ /** `text`, `button`, `input` or `image`. */
74
+ role: string;
75
+ /** The text this element ships with, or `null` for a textless shell. */
76
+ text: string | null;
77
+ /** `[x, y, width, height]`, in the same units the wireframe event carries. */
78
+ bounds: number[];
79
+ /** One of {@link MPMaskDecision}'s values — see the note there about matching. */
80
+ maskDecision: string;
81
+ }
82
+
83
+ /**
84
+ * One captured wireframe, exactly as the SDK built it.
85
+ *
86
+ * ⚠️ **Not a stable contract** — a debugging aid, not a schema to build tooling on.
87
+ */
88
+ export interface MPWireframeSnapshot {
89
+ /** Capture instant in milliseconds, matching the screenshot it accompanies. */
90
+ timestamp: number;
91
+ /** `[width, height]` of the captured viewport. */
92
+ viewport: number[];
93
+ elements: MPWireframeElement[];
94
+ }
95
+
96
+ /**
97
+ * Native event carrying one wireframe snapshot as JSON.
98
+ *
99
+ * The payload crosses as a *string* rather than a structured map on purpose: both SDKs
100
+ * already own a `toJson()` for their debug snapshot, so forwarding it verbatim keeps the
101
+ * bridge from becoming a third place where the shape can drift.
102
+ */
103
+ const WIREFRAME_EVENT = 'MixpanelSessionReplayWireframe';
104
+
105
+ let wireframeEventEmitter: NativeEventEmitter | null = null;
106
+
107
+ // The one live subscription, owned by `initialize`. Replaced on every initialize so a
108
+ // re-init cannot leave the previous config's callback attached.
109
+ let wireframeSubscription: EmitterSubscription | null = null;
110
+
111
+ // Which `initialize` call the live subscription belongs to. Bumped on every attach, so a
112
+ // call that fails can tell whether the subscription still in place is its own — see
113
+ // `attachWireframeEmitter`.
114
+ let wireframeGeneration = 0;
115
+
116
+ function getWireframeEventEmitter(): NativeEventEmitter {
117
+ if (wireframeEventEmitter === null) {
118
+ // Constructed lazily: importing this module must not create an emitter for an app
119
+ // that never listens. The module is passed on both platforms because a TurboModule
120
+ // has to supply `addListener`/`removeListeners` itself.
121
+ wireframeEventEmitter = new NativeEventEmitter(
122
+ MixpanelReactNativeSessionReplay as unknown as NativeModule
123
+ );
124
+ }
125
+ return wireframeEventEmitter;
126
+ }
127
+
33
128
  /**
34
129
  * Color configuration for the on-device debug mask overlay.
35
130
  *
@@ -38,8 +133,8 @@ export const MPDataResidency: Readonly<Record<'US' | 'EU' | 'IN', string>> = {
38
133
  * Setting any of `maskColor`, `autoMaskColor`, or `unmaskColor` to `null` hides that
39
134
  * category from the overlay.
40
135
  *
41
- * The overlay only renders when `__DEV__` is `true` — `debugOptions` is ignored in
42
- * production bundles regardless of what is passed.
136
+ * The overlay only renders in a debuggable build. That is enforced by the native SDKs
137
+ * themselves, so it is safe to leave `overlayColors` set unconditionally.
43
138
  */
44
139
  export class MPDebugOverlayColors {
45
140
  /**
@@ -94,9 +189,10 @@ export class MPDebugOverlayColors {
94
189
  * `overlayColors` to `null` to disable the overlay while keeping `MPDebugOptions`
95
190
  * available for future debug features.
96
191
  *
97
- * Debug features only render when `__DEV__` is `true`. In production bundles
98
- * (`__DEV__ === false`), `debugOptions` is dropped before reaching the native SDK so
99
- * the overlay never ships to end users.
192
+ * `debugOptions` reaches the native SDK in every bundle, exactly as it would if you
193
+ * configured it natively. Each feature decides for itself what a release build may do:
194
+ * the overlay is restricted to debuggable builds by the native SDKs, while
195
+ * {@link MPDebugOptions.wireframeEmitter} runs wherever you configure it.
100
196
  */
101
197
  export class MPDebugOptions {
102
198
  /**
@@ -106,10 +202,48 @@ export class MPDebugOptions {
106
202
  */
107
203
  overlayColors: MPDebugOverlayColors | null;
108
204
 
205
+ /**
206
+ * Hands each captured wireframe back to JavaScript as it is captured, so you can check
207
+ * what you are sending while you develop.
208
+ *
209
+ * You get exactly the elements that go to Mixpanel, plus the reason each one's text was
210
+ * kept or removed. Nothing delivered here leaves the device.
211
+ *
212
+ * This *observes* wireframe capture; it does not enable it. Wireframes are only captured
213
+ * when {@link MPSessionReplayConfig.wireframesOptions} is set, so a callback on its own is
214
+ * harmless but never fires.
215
+ *
216
+ * It runs in whichever bundle you configure it in, matching the native SDKs. Nothing it
217
+ * delivers leaves the device, but building each snapshot is work the SDK otherwise skips
218
+ * and every frame crosses the bridge — so leave it unset once you are done checking.
219
+ *
220
+ * Configuration only, and deliberately so: declaring the callback is what turns snapshot
221
+ * building on, so there is no way to pay for the work with nothing listening. Set it before
222
+ * {@link MPSessionReplay.initialize}, which is where the destination is attached — a later
223
+ * `initialize` replaces it, and there is no runtime subscribe.
224
+ *
225
+ * Snapshots arrive on a background thread natively and are delivered one per frame, so a
226
+ * slow callback queues work on the bridge. Keep it cheap.
227
+ *
228
+ * ```ts
229
+ * config.debugOptions = new MPDebugOptions({
230
+ * wireframeEmitter: (frame) => {
231
+ * const withText = frame.elements.filter((e) => e.text !== null).length;
232
+ * console.log(`[wireframe] ${frame.elements.length} elements, ${withText} with text`);
233
+ * },
234
+ * });
235
+ * ```
236
+ *
237
+ * - **Default:** `null` (no snapshots are built)
238
+ */
239
+ wireframeEmitter: ((snapshot: MPWireframeSnapshot) => void) | null;
240
+
109
241
  constructor({
110
242
  overlayColors = new MPDebugOverlayColors(),
243
+ wireframeEmitter = null,
111
244
  }: Partial<MPDebugOptions> = {}) {
112
245
  this.overlayColors = overlayColors;
246
+ this.wireframeEmitter = wireframeEmitter;
113
247
  }
114
248
  }
115
249
 
@@ -137,18 +271,11 @@ function serializeDebugOptions(
137
271
  if (debugOptions === null) {
138
272
  return null;
139
273
  }
140
- // Hard-gate debug features on `__DEV__` so they are never sent to native in
141
- // production bundles. The Android SDK already restricts the overlay to debuggable
142
- // builds, but the iOS SDK ships as a release XCFramework and would otherwise
143
- // render the overlay in production if a customer forgot to gate the call site.
144
- if (!__DEV__) {
145
- if (debugOptions.overlayColors !== null) {
146
- console.warn(
147
- 'MixpanelSessionReplay: `debugOptions` is ignored in production builds (__DEV__ is false).'
148
- );
149
- }
150
- return null;
151
- }
274
+ // No `__DEV__` gate: `debugOptions` is passed through in every bundle, the same as
275
+ // configuring it natively. Each SDK decides for itself what a release build may do —
276
+ // the overlay is restricted to debuggable builds by the native SDKs (`FLAG_DEBUGGABLE`
277
+ // on Android, `#if DEBUG` on iOS, which holds because the pod ships source, not a
278
+ // prebuilt binary) — so JavaScript does not need a second, differently-shaped opinion.
152
279
  const overlayColors = debugOptions.overlayColors;
153
280
  return {
154
281
  overlayColors:
@@ -160,6 +287,241 @@ function serializeDebugOptions(
160
287
  unmaskColor: processOverlayColor(overlayColors.unmaskColor),
161
288
  alpha: overlayColors.alpha,
162
289
  },
290
+ // This package's own debug switch, not SDK configuration: neither SDK models the key, and
291
+ // both ignore it when they decode this payload. Their `wireframeEmitter` is a callback and
292
+ // cannot travel here, so each bridge reads the flag and attaches the destination itself.
293
+ // Keeping it out of the SDKs' public `DebugOptions` keeps an RN-only knob off their native
294
+ // API surface, where it would do nothing.
295
+ //
296
+ // Derived rather than declared: a caller who wants snapshots supplies a callback, and the
297
+ // flag follows from that. It is never possible to ask the SDKs to build snapshots that
298
+ // nothing in JavaScript is waiting for.
299
+ emitWireframes: debugOptions.wireframeEmitter !== null,
300
+ };
301
+ }
302
+
303
+ /**
304
+ * A rule that rewrites or drops the text of a wireframe element when it matches.
305
+ *
306
+ * Build rules with the {@link MPSensitiveRule} factories rather than by hand — the object
307
+ * shape below is the wire format the native SDKs decode, not an API to write literals
308
+ * against.
309
+ *
310
+ * Rules run in the order you list them in {@link MPWireframesOptions.sensitiveRules},
311
+ * after the SDK's own masking, over whatever text is left — including text you declared
312
+ * with the `wireframeText` prop on {@link MPSessionReplayView}. A matching strip rule
313
+ * drops the text and stops immediately; a matching redact rule rewrites the text, and any
314
+ * rule after it sees the rewritten value.
315
+ */
316
+ export type MPSensitiveRule =
317
+ | { type: 'redact'; text: string; replacement: string }
318
+ | { type: 'strip'; text: string }
319
+ | { type: 'redactRegex'; regex: RegExp; replacement: string }
320
+ | { type: 'stripRegex'; regex: RegExp };
321
+
322
+ /** Replacement used by the redact rules when you do not supply one. */
323
+ export const MP_DEFAULT_REPLACEMENT = '[REDACTED]';
324
+
325
+ /**
326
+ * Factories for the four {@link MPSensitiveRule} variants.
327
+ *
328
+ * ```ts
329
+ * new MPWireframesOptions({
330
+ * sensitiveRules: [
331
+ * MPSensitiveRule.strip('password'),
332
+ * MPSensitiveRule.redactRegex(/[\w.+-]+@[\w-]+\.[\w.]+/g, '[EMAIL]'),
333
+ * ],
334
+ * });
335
+ * ```
336
+ */
337
+ export const MPSensitiveRule = {
338
+ /**
339
+ * Replaces case-insensitive substring matches of `text` with `replacement`, leaving the
340
+ * surrounding text intact.
341
+ */
342
+ redact(
343
+ text: string,
344
+ replacement: string = MP_DEFAULT_REPLACEMENT
345
+ ): MPSensitiveRule {
346
+ return { type: 'redact', text, replacement };
347
+ },
348
+
349
+ /** Drops the element's text entirely if it contains `text` (case-insensitive). */
350
+ strip(text: string): MPSensitiveRule {
351
+ return { type: 'strip', text };
352
+ },
353
+
354
+ /**
355
+ * Replaces matches of `regex` with `replacement`, leaving surrounding text intact.
356
+ *
357
+ * Only the `i`, `m` and `s` flags carry over to native; see
358
+ * {@link MPWireframesOptions} for what the regex itself is subject to.
359
+ */
360
+ redactRegex(
361
+ regex: RegExp,
362
+ replacement: string = MP_DEFAULT_REPLACEMENT
363
+ ): MPSensitiveRule {
364
+ return { type: 'redactRegex', regex, replacement };
365
+ },
366
+
367
+ /** Drops the element's text entirely if `regex` finds a match anywhere in the text. */
368
+ stripRegex(regex: RegExp): MPSensitiveRule {
369
+ return { type: 'stripRegex', regex };
370
+ },
371
+ };
372
+
373
+ /**
374
+ * Enables wireframe capture for Session Replay.
375
+ *
376
+ * **Beta.** Wireframes are in beta. Before shipping to production, inspect the wireframes
377
+ * your app produces with {@link MPDebugOptions.wireframeEmitter} and confirm that no
378
+ * sensitive information is captured.
379
+ *
380
+ * A wireframe is a lightweight text outline of a screen: the visible elements, what kind
381
+ * each one is (text, button, input, image), what it says, and where it sits. One is
382
+ * captured alongside each screenshot, which lets Mixpanel summarize what your users saw
383
+ * and did without anyone having to watch the replay.
384
+ *
385
+ * Pass one to {@link MPSessionReplayConfig.wireframesOptions} to turn wireframes on.
386
+ * Leave it `null` — the default — and none are captured.
387
+ *
388
+ * Mixpanel can also turn wireframe capture off for a project from the server. The native
389
+ * SDKs honor that switch: the rest of session replay keeps recording, only the wireframe
390
+ * payload is dropped, and the reason is logged at init.
391
+ *
392
+ * ### Your masking settings are respected
393
+ *
394
+ * Anything hidden in the replay video is also removed from the wireframe. The element is
395
+ * still listed so the shape of the screen is preserved, but its text is dropped. That
396
+ * includes anything inside a `<MPSessionReplayView sensitive>`, anything covered by
397
+ * {@link MPSessionReplayConfig.autoMaskedViews}, every `TextInput`, and anything sitting
398
+ * underneath a masked area even if it was never marked sensitive itself.
399
+ *
400
+ * Note what this means for the defaults: `autoMaskedViews` masks `Text` out of the box, so
401
+ * with the default configuration every element ships as a textless shell. Narrow
402
+ * `autoMaskedViews` (and mask what matters with `<MPSessionReplayView sensitive>`) for
403
+ * wireframes to carry readable copy.
404
+ *
405
+ * ### Describing an element yourself
406
+ *
407
+ * The `wireframeText` prop on {@link MPSessionReplayView} supplies the text for an element
408
+ * — useful for custom-drawn content, or anywhere the text picked up automatically isn't
409
+ * meaningful. Because you authored it rather than the SDK scraping it off the screen, it is
410
+ * sent even for an element you've masked in the video.
411
+ *
412
+ * ### Catching sensitive content by pattern
413
+ *
414
+ * {@link sensitiveRules} match on the text itself and run last, over everything above,
415
+ * including text you supplied with `wireframeText`.
416
+ */
417
+ export class MPWireframesOptions {
418
+ /**
419
+ * Rules applied to each element's text before it is sent, in the order you declare them.
420
+ * Elements are always kept; only their text is affected.
421
+ *
422
+ * - A matching strip rule drops the text and stops — no later rule runs.
423
+ * - Redact rules build on one another: a rule declared later sees the result of the ones
424
+ * before it, not the original text.
425
+ *
426
+ * A `RegExp` is compiled by the platform's own engine — `java.util.regex` on Android,
427
+ * ICU on iOS — not by JavaScript. A pattern that is valid JS may behave differently, or
428
+ * be rejected outright, on one of them; a rejected pattern fails `initialize` rather
429
+ * than silently matching nothing. Only the `i`, `m` and `s` flags cross the bridge (they
430
+ * are the three that mean the same thing in all three engines); `g` is implied, since
431
+ * every match is replaced, and any other flag is ignored with a warning. Replacement
432
+ * strings are literal — `$1` is emitted verbatim, not as a back-reference.
433
+ *
434
+ * - **Default:** `[]`
435
+ */
436
+ sensitiveRules: MPSensitiveRule[];
437
+
438
+ /**
439
+ * Whether an element with no text of its own may fall back to its accessibility label
440
+ * (React Native's `accessibilityLabel` prop). Off by default: a label is not drawn on
441
+ * screen, so unlike visible text you cannot confirm what it contains by watching the
442
+ * replay, and labels sometimes hold more than what is shown.
443
+ *
444
+ * Turn it on if you want icons and image buttons named. For an icon-only control the
445
+ * label is usually the only description of what the element is for, and with the fallback
446
+ * off it is sent as a bare shell instead — `wireframeText` is then the only way to
447
+ * describe it.
448
+ *
449
+ * The label is only ever a fallback. Text you set with `wireframeText` wins over it, an
450
+ * element's own visible text wins over it, and a masked element stays textless either way.
451
+ *
452
+ * - **Default:** `false`
453
+ */
454
+ useAccessibilityLabelFallback: boolean;
455
+
456
+ constructor({
457
+ sensitiveRules = [],
458
+ useAccessibilityLabelFallback = false,
459
+ }: Partial<MPWireframesOptions> = {}) {
460
+ this.sensitiveRules = sensitiveRules;
461
+ this.useAccessibilityLabelFallback = useAccessibilityLabelFallback;
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Flags a `RegExp` carries that mean the same thing in JavaScript, `java.util.regex` and
467
+ * ICU. `g` is deliberately accepted and dropped: the native rules always replace every
468
+ * match, so a global regex is what a caller means either way.
469
+ */
470
+ const SUPPORTED_REGEX_FLAGS = 'imsg';
471
+
472
+ function serializeRegex(regex: RegExp, ruleType: string): object {
473
+ const unsupported = [...regex.flags].filter(
474
+ (flag) => !SUPPORTED_REGEX_FLAGS.includes(flag)
475
+ );
476
+ if (unsupported.length > 0) {
477
+ console.warn(
478
+ `MixpanelSessionReplay: the ${unsupported.join('')} flag(s) on ${regex} (${ruleType}) are not supported by the native regex engines and will be ignored.`
479
+ );
480
+ }
481
+ return {
482
+ pattern: regex.source,
483
+ caseInsensitive: regex.flags.includes('i'),
484
+ multiline: regex.flags.includes('m'),
485
+ dotMatchesAll: regex.flags.includes('s'),
486
+ };
487
+ }
488
+
489
+ /**
490
+ * The `wireframesOptions` payload, in the one shape both native SDKs decode.
491
+ *
492
+ * Unlike `autoMaskedViews` and `remoteSettingsMode`, this needs no per-platform
493
+ * transformation: Android's `SensitiveRuleSerializer` and iOS's `MPSensitiveRule`
494
+ * decoder were written against the same field names and `type` tokens, and each
495
+ * platform's suite pins them as literal text.
496
+ */
497
+ function serializeWireframesOptions(
498
+ options: MPWireframesOptions | null
499
+ ): object | null {
500
+ if (options === null || options === undefined) {
501
+ return null;
502
+ }
503
+ return {
504
+ sensitiveRules: options.sensitiveRules.map((rule) => {
505
+ switch (rule.type) {
506
+ case 'redact':
507
+ return {
508
+ type: rule.type,
509
+ text: rule.text,
510
+ replacement: rule.replacement,
511
+ };
512
+ case 'strip':
513
+ return { type: rule.type, text: rule.text };
514
+ case 'redactRegex':
515
+ return {
516
+ type: rule.type,
517
+ ...serializeRegex(rule.regex, rule.type),
518
+ replacement: rule.replacement,
519
+ };
520
+ case 'stripRegex':
521
+ return { type: rule.type, ...serializeRegex(rule.regex, rule.type) };
522
+ }
523
+ }),
524
+ useAccessibilityLabelFallback: options.useAccessibilityLabelFallback,
163
525
  };
164
526
  }
165
527
 
@@ -251,9 +613,10 @@ export class MPSessionReplayConfig {
251
613
  * masking coverage during development. Pass `new MPDebugOptions()` to enable the
252
614
  * overlay with default colors, or customize via `MPDebugOverlayColors`.
253
615
  *
254
- * `debugOptions` is only honored when `__DEV__` is `true`. In production bundles
255
- * it is dropped before reaching the native SDK, so it is safe to leave the option
256
- * set unconditionally — the overlay will not render for end users.
616
+ * The overlay only renders in a debuggable build — the native SDKs enforce that, so it
617
+ * is safe to leave the option set unconditionally and the overlay will not reach end
618
+ * users. {@link MPDebugOptions.wireframeEmitter}, the other member, has no such
619
+ * restriction and runs wherever you configure it.
257
620
  *
258
621
  * - **Default:** `null` (disabled)
259
622
  */
@@ -275,6 +638,23 @@ export class MPSessionReplayConfig {
275
638
  */
276
639
  serverURL: string;
277
640
 
641
+ /**
642
+ * Enables wireframe capture: a text outline of each captured screen — the visible
643
+ * elements, what they say, and where they sit — recorded alongside the replay so
644
+ * sessions can be summarized without watching them.
645
+ *
646
+ * Pass `new MPWireframesOptions()` to turn it on with the defaults, or customize the
647
+ * content rules and the accessibility-label fallback. Your masking settings apply to
648
+ * it; see {@link MPWireframesOptions}.
649
+ *
650
+ * **Beta.** Wireframes are in beta. Before shipping to production, inspect the wireframes
651
+ * your app produces and confirm that no sensitive information is captured; see
652
+ * {@link MPWireframesOptions}.
653
+ *
654
+ * - **Default:** `null` (wireframe capture disabled)
655
+ */
656
+ wireframesOptions: MPWireframesOptions | null;
657
+
278
658
  constructor({
279
659
  wifiOnly = true,
280
660
  autoStartRecording = true,
@@ -290,6 +670,7 @@ export class MPSessionReplayConfig {
290
670
  remoteSettingsMode = MPSessionReplayRemoteSettingsMode.Disabled,
291
671
  debugOptions = null,
292
672
  serverURL = MPDataResidency.US,
673
+ wireframesOptions = null,
293
674
  }: Partial<MPSessionReplayConfig> = {}) {
294
675
  this.wifiOnly = wifiOnly;
295
676
  this.autoStartRecording = autoStartRecording;
@@ -300,6 +681,7 @@ export class MPSessionReplayConfig {
300
681
  this.remoteSettingsMode = remoteSettingsMode;
301
682
  this.debugOptions = debugOptions;
302
683
  this.serverURL = serverURL;
684
+ this.wireframesOptions = wireframesOptions;
303
685
  }
304
686
 
305
687
  private transformMaskValueForPlatform(value: string): string {
@@ -333,6 +715,7 @@ export class MPSessionReplayConfig {
333
715
  enableLogging: this.enableLogging,
334
716
  remoteSettingsMode: transformedRemoteSettingsMode,
335
717
  debugOptions: serializeDebugOptions(this.debugOptions),
718
+ wireframesOptions: serializeWireframesOptions(this.wireframesOptions),
336
719
  // The native SDKs spell the server URL field differently — Android's
337
720
  // kotlinx.serialization expects `serverUrl`, iOS's Codable expects `serverURL`.
338
721
  ...Platform.select({
@@ -385,7 +768,34 @@ async function initialize(
385
768
  throw new Error('recordingSessionsPercent must be between 0 and 100');
386
769
  }
387
770
  const json = config.toJSON();
388
- return MixpanelReactNativeSessionReplay.initialize(token, distinctId, json);
771
+ // Attached before the native call so no frame can be emitted before the destination
772
+ // exists, then reconciled once the call settles.
773
+ //
774
+ // `initialize` is async and nothing stops an app calling it twice, so the two paths
775
+ // below hold one invariant between them: a call that succeeds ends up owning the
776
+ // subscription, and a call that fails never leaves one behind that outlives it.
777
+ // Without both halves an overlap silently ends with no destination attached at all —
778
+ // the newer call tears its own down on failure, while the older one has already had
779
+ // its callback replaced and would never restore it.
780
+ const generation = attachWireframeEmitter(
781
+ config.debugOptions?.wireframeEmitter
782
+ );
783
+ try {
784
+ const result = await MixpanelReactNativeSessionReplay.initialize(
785
+ token,
786
+ distinctId,
787
+ json
788
+ );
789
+ if (generation !== wireframeGeneration) {
790
+ // Another initialize attached after this one started. This call is the one that
791
+ // succeeded, so its configuration is the one that should be delivering.
792
+ attachWireframeEmitter(config.debugOptions?.wireframeEmitter);
793
+ }
794
+ return result;
795
+ } catch (error) {
796
+ detachWireframeEmitterIfCurrent(generation);
797
+ throw error;
798
+ }
389
799
  }
390
800
 
391
801
  /**
@@ -466,6 +876,89 @@ async function flush(): Promise<void> {
466
876
  return MixpanelReactNativeSessionReplay.flush();
467
877
  }
468
878
 
879
+ /**
880
+ * Presents one shape to JavaScript regardless of which SDK produced the payload.
881
+ *
882
+ * A textless element is `"text": null` on both platforms now, but iOS used to *omit* the
883
+ * key — Swift's synthesized `Encodable` uses `encodeIfPresent` for optionals — which
884
+ * reached JS as `undefined` and printed as the string `"undefined"` in anything that only
885
+ * checked for `null`. The SDK is fixed; this keeps the declared
886
+ * `text: string | null` contract true against an older one too.
887
+ */
888
+ function normalizeSnapshot(raw: MPWireframeSnapshot): MPWireframeSnapshot {
889
+ return {
890
+ ...raw,
891
+ elements: (raw.elements ?? []).map((element) => ({
892
+ ...element,
893
+ text: element.text ?? null,
894
+ })),
895
+ };
896
+ }
897
+
898
+ /**
899
+ * Points the native wireframe event at {@link MPDebugOptions.wireframeEmitter}, replacing
900
+ * whatever a previous `initialize` attached.
901
+ *
902
+ * There is no public subscribe. The callback is declared on the config beside the switch that
903
+ * turns wireframes on, which is how Android, iOS and Flutter spell it too, and it means the
904
+ * one-callback lifetime is the instance's rather than something a caller has to remember to
905
+ * tear down.
906
+ */
907
+ function attachWireframeEmitter(
908
+ listener: ((snapshot: MPWireframeSnapshot) => void) | null | undefined
909
+ ): number {
910
+ wireframeSubscription?.remove();
911
+ wireframeSubscription = null;
912
+ const generation = ++wireframeGeneration;
913
+
914
+ if (!listener) {
915
+ return generation;
916
+ }
917
+
918
+ wireframeSubscription = getWireframeEventEmitter().addListener(
919
+ WIREFRAME_EVENT,
920
+ (payload: string) => {
921
+ let snapshot: MPWireframeSnapshot;
922
+ try {
923
+ snapshot = normalizeSnapshot(JSON.parse(payload));
924
+ } catch (error) {
925
+ // The payload is whichever SDK's `toJson()` produced it. Report and drop the
926
+ // frame rather than throwing out of the emitter callback, which would take the
927
+ // subscription down with it.
928
+ console.warn(
929
+ `MixpanelSessionReplay: could not parse a wireframe snapshot: ${error}`
930
+ );
931
+ return;
932
+ }
933
+ try {
934
+ listener(snapshot);
935
+ } catch (error) {
936
+ // A consumer callback is application code. Keep it from escaping through React
937
+ // Native's synchronous EventEmitter and destabilizing the host app or later frames.
938
+ console.warn(
939
+ `MixpanelSessionReplay: wireframe callback threw: ${error}`
940
+ );
941
+ }
942
+ }
943
+ );
944
+ return generation;
945
+ }
946
+
947
+ /**
948
+ * Detaches only if the live subscription is still the one `generation` installed.
949
+ *
950
+ * `initialize` is async and nothing stops an app calling it twice. Without this check, an
951
+ * earlier call that rejects would tear down the subscription a *later*, successful call had
952
+ * already installed, and that configuration would silently stop receiving snapshots.
953
+ */
954
+ function detachWireframeEmitterIfCurrent(generation: number): void {
955
+ if (generation !== wireframeGeneration) {
956
+ return;
957
+ }
958
+ wireframeSubscription?.remove();
959
+ wireframeSubscription = null;
960
+ }
961
+
469
962
  export { MPSessionReplayView } from './MixpanelSessionReplayView';
470
963
 
471
964
  export const MPSessionReplay = {