@mixpanel/react-native-session-replay 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/MixpanelReactNativeSessionReplay.podspec +1 -1
  2. package/README.md +2 -0
  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 +623 -5
  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 +351 -1
  21. package/lib/typescript/src/index.d.ts.map +1 -1
  22. package/package.json +2 -24
  23. package/src/MixpanelSessionReplayView.tsx +33 -0
  24. package/src/NativeMixpanelReactNativeSessionReplay.ts +7 -0
  25. package/src/index.tsx +688 -4
  26. package/android/app/build/generated/source/codegen/java/com/facebook/fbreact/specs/NativeMixpanelReactNativeSessionReplaySpec.java +0 -62
  27. package/android/app/build/generated/source/codegen/jni/CMakeLists.txt +0 -36
  28. package/android/app/build/generated/source/codegen/jni/MixpanelReactNativeSessionReplaySpec-generated.cpp +0 -68
  29. package/android/app/build/generated/source/codegen/jni/MixpanelReactNativeSessionReplaySpec.h +0 -31
  30. package/android/app/build/generated/source/codegen/jni/react/renderer/components/MixpanelReactNativeSessionReplaySpec/MixpanelReactNativeSessionReplaySpecJSI-generated.cpp +0 -67
  31. package/android/app/build/generated/source/codegen/jni/react/renderer/components/MixpanelReactNativeSessionReplaySpec/MixpanelReactNativeSessionReplaySpecJSI.h +0 -125
  32. package/android/generated/java/com/mpsessionreplay/NativeMpSessionReplaySpec.java +0 -49
  33. package/android/generated/jni/CMakeLists.txt +0 -36
  34. package/android/generated/jni/RNMpSessionReplaySpec-generated.cpp +0 -50
  35. package/android/generated/jni/RNMpSessionReplaySpec.h +0 -31
  36. package/android/generated/jni/react/renderer/components/RNMpSessionReplaySpec/RNMpSessionReplaySpecJSI-generated.cpp +0 -51
  37. package/android/generated/jni/react/renderer/components/RNMpSessionReplaySpec/RNMpSessionReplaySpecJSI.h +0 -98
package/src/index.tsx CHANGED
@@ -1,4 +1,11 @@
1
- import { Platform } 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 {
@@ -14,6 +21,510 @@ export enum MPSessionReplayRemoteSettingsMode {
14
21
  Fallback = 'fallback',
15
22
  }
16
23
 
24
+ /**
25
+ * Base URLs for Mixpanel's managed data residency regions.
26
+ *
27
+ * Pass one of these constants to {@link MPSessionReplayConfig.serverURL} to route
28
+ * session replay traffic to the matching region, or pass any other `https://` URL
29
+ * to send traffic through a custom endpoint (for example, a corporate proxy).
30
+ */
31
+ export const MPDataResidency: Readonly<Record<'US' | 'EU' | 'IN', string>> = {
32
+ /** US data residency (default): `https://api.mixpanel.com`. */
33
+ US: 'https://api.mixpanel.com',
34
+ /** EU data residency: `https://api-eu.mixpanel.com`. */
35
+ EU: 'https://api-eu.mixpanel.com',
36
+ /** India data residency: `https://api-in.mixpanel.com`. */
37
+ IN: 'https://api-in.mixpanel.com',
38
+ };
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
+
128
+ /**
129
+ * Color configuration for the on-device debug mask overlay.
130
+ *
131
+ * Each color accepts any React Native [`ColorValue`](https://reactnative.dev/docs/colors)
132
+ * — for example `'red'`, `'#FF0000'`, `'rgba(255, 0, 0, 0.5)'`, or `0xFFFF0000`.
133
+ * Setting any of `maskColor`, `autoMaskColor`, or `unmaskColor` to `null` hides that
134
+ * category from the overlay.
135
+ *
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.
138
+ */
139
+ export class MPDebugOverlayColors {
140
+ /**
141
+ * Color used to draw regions that are explicitly masked (sensitive views / text input).
142
+ * Set to `null` to hide masked regions from the overlay.
143
+ *
144
+ * - **Default:** `'red'`
145
+ */
146
+ maskColor: ColorValue | null;
147
+
148
+ /**
149
+ * Color used to draw regions that are auto-masked (text, images, web views, maps).
150
+ * Set to `null` to hide auto-masked regions from the overlay.
151
+ *
152
+ * - **Default:** `'orange'`
153
+ */
154
+ autoMaskColor: ColorValue | null;
155
+
156
+ /**
157
+ * Color used to draw regions explicitly excluded from masking (safe views).
158
+ * Set to `null` to hide unmask regions from the overlay.
159
+ *
160
+ * - **Default:** `'green'`
161
+ */
162
+ unmaskColor: ColorValue | null;
163
+
164
+ /**
165
+ * Opacity of the overlay, from `0.0` (fully transparent) to `1.0` (fully opaque).
166
+ *
167
+ * - **Default:** `0.5`
168
+ */
169
+ alpha: number;
170
+
171
+ constructor({
172
+ maskColor = 'red',
173
+ autoMaskColor = 'orange',
174
+ unmaskColor = 'green',
175
+ alpha = 0.5,
176
+ }: Partial<MPDebugOverlayColors> = {}) {
177
+ this.maskColor = maskColor;
178
+ this.autoMaskColor = autoMaskColor;
179
+ this.unmaskColor = unmaskColor;
180
+ this.alpha = alpha;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Configuration for Session Replay debug features.
186
+ *
187
+ * When `overlayColors` is non-null, the SDK renders a visual overlay on top of the app
188
+ * showing which regions are masked, auto-masked, or explicitly unmasked. Set
189
+ * `overlayColors` to `null` to disable the overlay while keeping `MPDebugOptions`
190
+ * available for future debug features.
191
+ *
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.
196
+ */
197
+ export class MPDebugOptions {
198
+ /**
199
+ * Color configuration for the debug mask overlay. When `null`, the overlay is disabled.
200
+ *
201
+ * - **Default:** `new MPDebugOverlayColors()` (overlay enabled with default colors)
202
+ */
203
+ overlayColors: MPDebugOverlayColors | null;
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
+
241
+ constructor({
242
+ overlayColors = new MPDebugOverlayColors(),
243
+ wireframeEmitter = null,
244
+ }: Partial<MPDebugOptions> = {}) {
245
+ this.overlayColors = overlayColors;
246
+ this.wireframeEmitter = wireframeEmitter;
247
+ }
248
+ }
249
+
250
+ function processOverlayColor(color: ColorValue | null): number | null {
251
+ if (color === null || color === undefined) {
252
+ return null;
253
+ }
254
+ // `processColor` returns the ARGB integer in the form expected by each native platform:
255
+ // a signed 32-bit Int on Android (kotlinx.serialization Int) and an unsigned 32-bit
256
+ // value on iOS (Swift Int is 64-bit, so it decodes without overflow). Invalid color
257
+ // strings yield `undefined` — treat those the same as `null` (hide the category).
258
+ const processed = processColor(color);
259
+ if (typeof processed !== 'number') {
260
+ console.warn(
261
+ `MixpanelSessionReplay: invalid debug overlay color ${JSON.stringify(color)} — that category will be hidden from the overlay.`
262
+ );
263
+ return null;
264
+ }
265
+ return processed;
266
+ }
267
+
268
+ function serializeDebugOptions(
269
+ debugOptions: MPDebugOptions | null
270
+ ): object | null {
271
+ if (debugOptions === null) {
272
+ return null;
273
+ }
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.
279
+ const overlayColors = debugOptions.overlayColors;
280
+ return {
281
+ overlayColors:
282
+ overlayColors === null
283
+ ? null
284
+ : {
285
+ maskColor: processOverlayColor(overlayColors.maskColor),
286
+ autoMaskColor: processOverlayColor(overlayColors.autoMaskColor),
287
+ unmaskColor: processOverlayColor(overlayColors.unmaskColor),
288
+ alpha: overlayColors.alpha,
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,
525
+ };
526
+ }
527
+
17
528
  export class MPSessionReplayConfig {
18
529
  /**
19
530
  * Determines whether replay events will only be flushed to the server when the device has a WiFi connection.
@@ -94,6 +605,56 @@ export class MPSessionReplayConfig {
94
605
  */
95
606
  remoteSettingsMode: MPSessionReplayRemoteSettingsMode;
96
607
 
608
+ /**
609
+ * Enables on-device debug features such as the visual mask overlay.
610
+ *
611
+ * When non-null, the SDK renders a colored overlay on top of the app showing which
612
+ * regions are masked, auto-masked, or explicitly unmasked — useful for verifying
613
+ * masking coverage during development. Pass `new MPDebugOptions()` to enable the
614
+ * overlay with default colors, or customize via `MPDebugOverlayColors`.
615
+ *
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.
620
+ *
621
+ * - **Default:** `null` (disabled)
622
+ */
623
+ debugOptions: MPDebugOptions | null;
624
+
625
+ /**
626
+ * Base URL used to send session replay data to Mixpanel.
627
+ *
628
+ * Use one of the {@link MPDataResidency} constants to target a managed region
629
+ * (`MPDataResidency.US`, `MPDataResidency.EU`, `MPDataResidency.IN`), or pass any
630
+ * fully-qualified `https://` URL to route traffic through a custom endpoint such
631
+ * as a corporate proxy.
632
+ *
633
+ * The URL must use `https://`. The underlying native SDKs validate the URL
634
+ * during `initialize` — invalid URLs cause `initialize` to reject with an error
635
+ * on both platforms.
636
+ *
637
+ * - **Default:** `MPDataResidency.US` (`https://api.mixpanel.com`)
638
+ */
639
+ serverURL: string;
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
+
97
658
  constructor({
98
659
  wifiOnly = true,
99
660
  autoStartRecording = true,
@@ -107,6 +668,9 @@ export class MPSessionReplayConfig {
107
668
  flushInterval = 10,
108
669
  enableLogging = false,
109
670
  remoteSettingsMode = MPSessionReplayRemoteSettingsMode.Disabled,
671
+ debugOptions = null,
672
+ serverURL = MPDataResidency.US,
673
+ wireframesOptions = null,
110
674
  }: Partial<MPSessionReplayConfig> = {}) {
111
675
  this.wifiOnly = wifiOnly;
112
676
  this.autoStartRecording = autoStartRecording;
@@ -115,6 +679,9 @@ export class MPSessionReplayConfig {
115
679
  this.flushInterval = flushInterval;
116
680
  this.enableLogging = enableLogging;
117
681
  this.remoteSettingsMode = remoteSettingsMode;
682
+ this.debugOptions = debugOptions;
683
+ this.serverURL = serverURL;
684
+ this.wireframesOptions = wireframesOptions;
118
685
  }
119
686
 
120
687
  private transformMaskValueForPlatform(value: string): string {
@@ -147,9 +714,16 @@ export class MPSessionReplayConfig {
147
714
  flushInterval: this.flushInterval,
148
715
  enableLogging: this.enableLogging,
149
716
  remoteSettingsMode: transformedRemoteSettingsMode,
150
- // iOS-specific config to enable session replay on iOS 26 and later
717
+ debugOptions: serializeDebugOptions(this.debugOptions),
718
+ wireframesOptions: serializeWireframesOptions(this.wireframesOptions),
719
+ // The native SDKs spell the server URL field differently — Android's
720
+ // kotlinx.serialization expects `serverUrl`, iOS's Codable expects `serverURL`.
151
721
  ...Platform.select({
152
- ios: { enableSessionReplayOniOS26AndLater: true },
722
+ ios: {
723
+ enableSessionReplayOniOS26AndLater: true,
724
+ serverURL: this.serverURL,
725
+ },
726
+ android: { serverUrl: this.serverURL },
153
727
  default: {},
154
728
  }),
155
729
  };
@@ -194,7 +768,34 @@ async function initialize(
194
768
  throw new Error('recordingSessionsPercent must be between 0 and 100');
195
769
  }
196
770
  const json = config.toJSON();
197
- 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
+ }
198
799
  }
199
800
 
200
801
  /**
@@ -275,6 +876,89 @@ async function flush(): Promise<void> {
275
876
  return MixpanelReactNativeSessionReplay.flush();
276
877
  }
277
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
+
278
962
  export { MPSessionReplayView } from './MixpanelSessionReplayView';
279
963
 
280
964
  export const MPSessionReplay = {