@outerjoyn/react-native 1.1.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.
@@ -0,0 +1,369 @@
1
+ /**
2
+ * PostCheckoutSavePrompt — Post-checkout Joyn Wallet conversion modal.
3
+ *
4
+ * Shown after a successful pay-with-points transaction, prompting the user
5
+ * to save their linked programs via phone verification (OTP).
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * <PostCheckoutSavePrompt
10
+ * visible={showSavePrompt}
11
+ * onSave={(result) => console.log('Saved:', result)}
12
+ * onSkip={() => setShowSavePrompt(false)}
13
+ * />
14
+ * ```
15
+ */
16
+ import React, { useState, useCallback } from 'react';
17
+ import {
18
+ View,
19
+ Text,
20
+ TextInput,
21
+ Pressable,
22
+ Modal,
23
+ StyleSheet,
24
+ KeyboardAvoidingView,
25
+ Platform,
26
+ ActivityIndicator,
27
+ } from 'react-native';
28
+ import { useOuterJoyn } from '../useOuterJoyn';
29
+ import { OJ_COLORS } from '../core/colors';
30
+ import { SDKError } from '../core/api-client';
31
+
32
+ const PRIMARY = OJ_COLORS.primary;
33
+ const NAVY = OJ_COLORS.navy;
34
+ const SUCCESS = OJ_COLORS.success;
35
+
36
+ type PromptStep = 'phone' | 'otp' | 'success';
37
+
38
+ export interface SaveResult {
39
+ phone: string;
40
+ verified: boolean;
41
+ }
42
+
43
+ export interface PostCheckoutSavePromptProps {
44
+ /** Whether the modal is visible */
45
+ visible: boolean;
46
+ /** Called on successful phone verification */
47
+ onSave?: (result: SaveResult) => void;
48
+ /** Called when user skips / dismisses */
49
+ onSkip?: () => void;
50
+ }
51
+
52
+ export function PostCheckoutSavePrompt({
53
+ visible,
54
+ onSave,
55
+ onSkip,
56
+ }: PostCheckoutSavePromptProps) {
57
+ const { linkedPrograms, apiClient, t } = useOuterJoyn();
58
+
59
+ const [step, setStep] = useState<PromptStep>('phone');
60
+ const [phone, setPhone] = useState('');
61
+ const [otp, setOtp] = useState('');
62
+ const [sending, setSending] = useState(false);
63
+ const [error, setError] = useState<string | null>(null);
64
+ const [unavailable, setUnavailable] = useState(false);
65
+
66
+ const resetState = useCallback(() => {
67
+ setStep('phone');
68
+ setPhone('');
69
+ setOtp('');
70
+ setSending(false);
71
+ setError(null);
72
+ setUnavailable(false);
73
+ }, []);
74
+
75
+ const handleSkip = useCallback(() => {
76
+ resetState();
77
+ onSkip?.();
78
+ }, [onSkip, resetState]);
79
+
80
+ const handleSendCode = useCallback(async () => {
81
+ if (!apiClient) {
82
+ setError('Configure OuterJoynProvider to enable this feature');
83
+ return;
84
+ }
85
+ if (phone.replace(/\D/g, '').length < 10) {
86
+ setError(t('postcheckout.phone_placeholder'));
87
+ return;
88
+ }
89
+ setError(null);
90
+ setSending(true);
91
+ try {
92
+ await apiClient.post('/api/sdk/wallet/otp/send', { phone });
93
+ setStep('otp');
94
+ } catch (e: any) {
95
+ if (e instanceof SDKError && e.code === 'NOT_FOUND') {
96
+ setUnavailable(true);
97
+ setError('This feature is coming soon');
98
+ } else {
99
+ setError(e?.message ?? 'Failed to send code');
100
+ }
101
+ } finally {
102
+ setSending(false);
103
+ }
104
+ }, [phone, apiClient, t]);
105
+
106
+ const handleVerify = useCallback(async () => {
107
+ if (!apiClient) {
108
+ setError('Configure OuterJoynProvider to enable this feature');
109
+ return;
110
+ }
111
+ if (otp.replace(/\D/g, '').length < 4) {
112
+ setError(t('postcheckout.enter_code'));
113
+ return;
114
+ }
115
+ setError(null);
116
+ setSending(true);
117
+ try {
118
+ await apiClient.post('/api/sdk/wallet/otp/verify', { phone, code: otp });
119
+ setStep('success');
120
+ onSave?.({ phone, verified: true });
121
+ } catch (e: any) {
122
+ if (e instanceof SDKError && e.code === 'NOT_FOUND') {
123
+ setUnavailable(true);
124
+ setError('This feature is coming soon');
125
+ } else {
126
+ setError(e?.message ?? 'Verification failed');
127
+ }
128
+ } finally {
129
+ setSending(false);
130
+ }
131
+ }, [otp, phone, onSave, apiClient, t]);
132
+
133
+ const programCount = linkedPrograms.length;
134
+
135
+ return (
136
+ <Modal
137
+ visible={visible}
138
+ transparent
139
+ animationType="slide"
140
+ onRequestClose={handleSkip}
141
+ >
142
+ <KeyboardAvoidingView
143
+ behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
144
+ style={styles.overlay}
145
+ >
146
+ <Pressable style={styles.backdrop} onPress={handleSkip} />
147
+
148
+ <View style={styles.sheet}>
149
+ {/* Handle bar */}
150
+ <View style={styles.handleBar} />
151
+
152
+ {step === 'phone' && (
153
+ <>
154
+ <Text style={styles.title}>{t('postcheckout.save_title')}</Text>
155
+ <Text style={styles.subtitle}>
156
+ {t('postcheckout.save_desc')}
157
+ </Text>
158
+
159
+ <Text style={styles.inputLabel}>{t('postcheckout.phone_placeholder')}</Text>
160
+ <TextInput
161
+ style={styles.input}
162
+ placeholder="+1 (555) 123-4567"
163
+ placeholderTextColor="#9CA3AF"
164
+ keyboardType="phone-pad"
165
+ autoComplete="tel"
166
+ value={phone}
167
+ onChangeText={setPhone}
168
+ editable={!sending && !unavailable}
169
+ accessibilityLabel={t('postcheckout.phone_placeholder')}
170
+ />
171
+
172
+ {error && <Text style={styles.errorText}>{error}</Text>}
173
+
174
+ <Pressable
175
+ style={[styles.primaryButton, (sending || unavailable) && styles.buttonDisabled]}
176
+ onPress={handleSendCode}
177
+ disabled={sending || unavailable}
178
+ accessibilityRole="button"
179
+ accessibilityLabel={t('postcheckout.send_code')}
180
+ >
181
+ {sending ? (
182
+ <ActivityIndicator size="small" color="#FFFFFF" />
183
+ ) : (
184
+ <Text style={styles.primaryButtonText}>{t('postcheckout.send_code')}</Text>
185
+ )}
186
+ </Pressable>
187
+
188
+ <Pressable style={styles.skipButton} onPress={handleSkip} accessibilityRole="button" accessibilityLabel={t('postcheckout.skip')}>
189
+ <Text style={styles.skipButtonText}>{t('postcheckout.skip')}</Text>
190
+ </Pressable>
191
+ </>
192
+ )}
193
+
194
+ {step === 'otp' && (
195
+ <>
196
+ <Text style={styles.title}>{t('postcheckout.enter_code')}</Text>
197
+ <Text style={styles.subtitle}>
198
+ We sent a code to {phone}
199
+ </Text>
200
+
201
+ <TextInput
202
+ style={[styles.input, styles.otpInput]}
203
+ placeholder={t('postcheckout.enter_code')}
204
+ placeholderTextColor="#9CA3AF"
205
+ keyboardType="number-pad"
206
+ maxLength={6}
207
+ autoComplete="one-time-code"
208
+ value={otp}
209
+ onChangeText={setOtp}
210
+ editable={!sending && !unavailable}
211
+ accessibilityLabel={t('postcheckout.enter_code')}
212
+ />
213
+
214
+ {error && <Text style={styles.errorText}>{error}</Text>}
215
+
216
+ <Pressable
217
+ style={[styles.primaryButton, (sending || unavailable) && styles.buttonDisabled]}
218
+ onPress={handleVerify}
219
+ disabled={sending || unavailable}
220
+ >
221
+ {sending ? (
222
+ <ActivityIndicator size="small" color="#FFFFFF" />
223
+ ) : (
224
+ <Text style={styles.primaryButtonText}>{t('postcheckout.verify')}</Text>
225
+ )}
226
+ </Pressable>
227
+
228
+ <Pressable style={styles.skipButton} onPress={() => setStep('phone')}>
229
+ <Text style={styles.skipButtonText}>{t('common.cancel')}</Text>
230
+ </Pressable>
231
+ </>
232
+ )}
233
+
234
+ {step === 'success' && (
235
+ <>
236
+ <Text style={styles.successIcon}>{'V'}</Text>
237
+ <Text style={styles.title}>{t('connect.success')}</Text>
238
+ <Text style={styles.subtitle}>
239
+ {t('postcheckout.secured')}
240
+ </Text>
241
+
242
+ <Pressable
243
+ style={styles.primaryButton}
244
+ onPress={handleSkip}
245
+ >
246
+ <Text style={styles.primaryButtonText}>{t('common.done')}</Text>
247
+ </Pressable>
248
+ </>
249
+ )}
250
+
251
+ {/* Footer */}
252
+ <View style={styles.footer}>
253
+ <Text style={styles.footerText}>{t('connect.secured')}</Text>
254
+ </View>
255
+ </View>
256
+ </KeyboardAvoidingView>
257
+ </Modal>
258
+ );
259
+ }
260
+
261
+ const styles = StyleSheet.create({
262
+ overlay: {
263
+ flex: 1,
264
+ justifyContent: 'flex-end',
265
+ },
266
+ backdrop: {
267
+ ...StyleSheet.absoluteFillObject,
268
+ backgroundColor: 'rgba(0,0,0,0.4)',
269
+ },
270
+ sheet: {
271
+ backgroundColor: '#FFFFFF',
272
+ borderTopLeftRadius: 20,
273
+ borderTopRightRadius: 20,
274
+ paddingHorizontal: 24,
275
+ paddingTop: 12,
276
+ paddingBottom: 34,
277
+ },
278
+ handleBar: {
279
+ width: 36,
280
+ height: 4,
281
+ borderRadius: 2,
282
+ backgroundColor: '#D1D5DB',
283
+ alignSelf: 'center',
284
+ marginBottom: 20,
285
+ },
286
+ title: {
287
+ fontSize: 20,
288
+ fontWeight: '700',
289
+ color: NAVY,
290
+ textAlign: 'center',
291
+ marginBottom: 8,
292
+ },
293
+ subtitle: {
294
+ fontSize: 14,
295
+ color: '#6B7280',
296
+ textAlign: 'center',
297
+ lineHeight: 20,
298
+ marginBottom: 24,
299
+ },
300
+ inputLabel: {
301
+ fontSize: 13,
302
+ fontWeight: '600',
303
+ color: '#374151',
304
+ marginBottom: 6,
305
+ },
306
+ input: {
307
+ borderWidth: 1,
308
+ borderColor: '#D1D5DB',
309
+ borderRadius: 10,
310
+ paddingHorizontal: 14,
311
+ paddingVertical: 12,
312
+ fontSize: 16,
313
+ color: NAVY,
314
+ marginBottom: 12,
315
+ },
316
+ otpInput: {
317
+ textAlign: 'center',
318
+ fontSize: 22,
319
+ letterSpacing: 8,
320
+ fontWeight: '600',
321
+ },
322
+ errorText: {
323
+ fontSize: 13,
324
+ color: '#EF4444',
325
+ marginBottom: 10,
326
+ },
327
+ primaryButton: {
328
+ backgroundColor: PRIMARY,
329
+ borderRadius: 12,
330
+ paddingVertical: 14,
331
+ alignItems: 'center',
332
+ marginBottom: 10,
333
+ },
334
+ buttonDisabled: {
335
+ opacity: 0.6,
336
+ },
337
+ primaryButtonText: {
338
+ color: '#FFFFFF',
339
+ fontSize: 16,
340
+ fontWeight: '600',
341
+ },
342
+ skipButton: {
343
+ alignItems: 'center',
344
+ paddingVertical: 8,
345
+ marginBottom: 8,
346
+ },
347
+ skipButtonText: {
348
+ fontSize: 14,
349
+ color: '#6B7280',
350
+ },
351
+ successIcon: {
352
+ fontSize: 40,
353
+ fontWeight: '700',
354
+ color: SUCCESS,
355
+ textAlign: 'center',
356
+ marginBottom: 12,
357
+ },
358
+ footer: {
359
+ flexDirection: 'row',
360
+ alignItems: 'center',
361
+ justifyContent: 'center',
362
+ marginTop: 16,
363
+ gap: 4,
364
+ },
365
+ footerText: {
366
+ fontSize: 11,
367
+ color: '#B0B7C3',
368
+ },
369
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Inline React Native components for the OuterJoyn SDK.
3
+ *
4
+ * These are pure RN components (no WebView) that read from the
5
+ * OuterJoyn context via useOuterJoyn(). They must be rendered
6
+ * inside an <OuterJoynProvider>.
7
+ */
8
+
9
+ export { LoyaltyBanner } from './LoyaltyBanner';
10
+ export type { LoyaltyBannerProps } from './LoyaltyBanner';
11
+
12
+ export { BalanceSummary } from './BalanceSummary';
13
+ export type { BalanceSummaryProps } from './BalanceSummary';
14
+
15
+ export { CheckoutPointsApply } from './CheckoutPointsApply';
16
+ export type {
17
+ CheckoutPointsApplyProps,
18
+ CheckoutPointsApplyHandle,
19
+ AppliedPoints,
20
+ PointsChangedPayload,
21
+ } from './CheckoutPointsApply';
22
+
23
+ export { LoyaltyProfileSection } from './LoyaltyProfileSection';
24
+ export type { LoyaltyProfileSectionProps } from './LoyaltyProfileSection';
25
+
26
+ export { PostCheckoutSavePrompt } from './PostCheckoutSavePrompt';
27
+ export type {
28
+ PostCheckoutSavePromptProps,
29
+ SaveResult,
30
+ } from './PostCheckoutSavePrompt';
@@ -0,0 +1,51 @@
1
+ /**
2
+ * OuterJoynErrorBoundary — Catches render errors to prevent SDK crashes in the host app.
3
+ *
4
+ * Wraps provider children and individual sheets. On error, renders nothing
5
+ * (or a minimal fallback) and calls the optional onError callback.
6
+ */
7
+ import React from 'react';
8
+ import { View, Text, Pressable, StyleSheet } from 'react-native';
9
+
10
+ export interface ErrorBoundaryProps {
11
+ /** Called when a render error is caught */
12
+ onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
13
+ /** Optional fallback UI. If omitted, renders nothing on error. */
14
+ fallback?: React.ReactNode;
15
+ children: React.ReactNode;
16
+ }
17
+
18
+ interface ErrorBoundaryState {
19
+ hasError: boolean;
20
+ error: Error | null;
21
+ }
22
+
23
+ export class OuterJoynErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
24
+ state: ErrorBoundaryState = { hasError: false, error: null };
25
+
26
+ static getDerivedStateFromError(error: Error): ErrorBoundaryState {
27
+ return { hasError: true, error };
28
+ }
29
+
30
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
31
+ this.props.onError?.(error, errorInfo);
32
+ if (__DEV__) {
33
+ console.error('[OuterJoyn SDK] Render error caught by ErrorBoundary:', error, errorInfo);
34
+ }
35
+ }
36
+
37
+ handleRetry = () => {
38
+ this.setState({ hasError: false, error: null });
39
+ };
40
+
41
+ render() {
42
+ if (this.state.hasError) {
43
+ if (this.props.fallback) {
44
+ return this.props.fallback;
45
+ }
46
+ // Minimal fallback — don't crash the host app
47
+ return null;
48
+ }
49
+ return this.props.children;
50
+ }
51
+ }
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Funnel Analytics — SDK-side event tracking for conversion analysis
3
+ *
4
+ * Batches events and sends to /api/sdk/telemetry.
5
+ * Queues offline events and replays when connection restored.
6
+ * No PII collected — only: widget, step, duration, outcome, business_unit_id, is_test.
7
+ *
8
+ * Events follow the funnel:
9
+ * banner.viewed → banner.tapped → connect.started → connect.completed
10
+ * → pay.opened → pay.applied → pay.confirmed
11
+ */
12
+
13
+ import { AppState } from 'react-native';
14
+ import type { StorageAdapter } from './types';
15
+ import { SDK_VERSION } from './version';
16
+
17
+ // =============================================================================
18
+ // Types
19
+ // =============================================================================
20
+
21
+ export interface FunnelEvent {
22
+ event: string;
23
+ widget: string;
24
+ step: string;
25
+ duration_ms: number;
26
+ step_duration_ms: number;
27
+ outcome?: 'success' | 'error' | 'abandoned';
28
+ error_code?: string;
29
+ sdk_version: string;
30
+ is_test: boolean;
31
+ business_unit_id?: string;
32
+ session_id: string;
33
+ sequence: number;
34
+ timestamp: string;
35
+ platform: 'ios' | 'android' | 'web';
36
+ }
37
+
38
+ /** Flat telemetry payload expected by POST /api/sdk/telemetry */
39
+ interface TelemetryPayload {
40
+ widget: string;
41
+ duration_ms: number;
42
+ outcome: 'success' | 'error' | 'closed';
43
+ error_code?: string;
44
+ sdk_version: string;
45
+ is_test: boolean;
46
+ business_unit_id?: string;
47
+ }
48
+
49
+ /** Map internal outcome to server-accepted values */
50
+ function mapOutcome(outcome?: string): 'success' | 'error' | 'closed' {
51
+ if (outcome === 'success') return 'success';
52
+ if (outcome === 'error') return 'error';
53
+ return 'closed'; // 'abandoned' or undefined → 'closed'
54
+ }
55
+
56
+ // =============================================================================
57
+ // Analytics Tracker
58
+ // =============================================================================
59
+
60
+ const BATCH_SIZE = 20;
61
+ const FLUSH_INTERVAL_MS = 10_000; // 10 seconds
62
+ const MAX_STORED_EVENTS = 500;
63
+ const STORAGE_KEY = 'oj_sdk_analytics_queue';
64
+
65
+ export class AnalyticsTracker {
66
+ private apiBaseUrl: string;
67
+ private sessionToken: string;
68
+ private isTest: boolean;
69
+ private businessUnitId?: string;
70
+ private queue: FunnelEvent[] = [];
71
+ private flushTimer: ReturnType<typeof setTimeout> | null = null;
72
+ private sequenceCounter = 0;
73
+ private sessionId: string;
74
+ private widgetStartTimes = new Map<string, number>();
75
+ private stepStartTimes = new Map<string, number>();
76
+ private storage?: StorageAdapter;
77
+ private appStateSubscription: any = null;
78
+ private enabled = true;
79
+
80
+ constructor(opts: {
81
+ apiBaseUrl: string;
82
+ sessionToken: string;
83
+ isTest: boolean;
84
+ businessUnitId?: string;
85
+ storage?: StorageAdapter;
86
+ enabled?: boolean;
87
+ }) {
88
+ this.apiBaseUrl = opts.apiBaseUrl.replace(/\/+$/, '');
89
+ this.sessionToken = opts.sessionToken;
90
+ this.isTest = opts.isTest;
91
+ this.businessUnitId = opts.businessUnitId;
92
+ this.storage = opts.storage;
93
+ this.enabled = opts.enabled ?? true;
94
+ this.sessionId = this.generateSessionId();
95
+
96
+ // Load queued events from storage
97
+ this.loadPersistedQueue();
98
+
99
+ // Flush on app background
100
+ this.appStateSubscription = AppState.addEventListener('change', (state) => {
101
+ if (state === 'background') this.flush();
102
+ });
103
+ }
104
+
105
+ /** Track a funnel event */
106
+ track(event: string, widget: string, step: string, extras?: Partial<FunnelEvent>) {
107
+ if (!this.enabled) return;
108
+
109
+ const now = Date.now();
110
+ const widgetKey = `${widget}_${this.sessionId}`;
111
+ const stepKey = `${widget}_${step}_${this.sessionId}`;
112
+
113
+ if (!this.widgetStartTimes.has(widgetKey)) {
114
+ this.widgetStartTimes.set(widgetKey, now);
115
+ }
116
+ if (!this.stepStartTimes.has(stepKey)) {
117
+ this.stepStartTimes.set(stepKey, now);
118
+ }
119
+
120
+ const funnelEvent: FunnelEvent = {
121
+ event,
122
+ widget,
123
+ step,
124
+ duration_ms: now - (this.widgetStartTimes.get(widgetKey) ?? now),
125
+ step_duration_ms: now - (this.stepStartTimes.get(stepKey) ?? now),
126
+ sdk_version: SDK_VERSION,
127
+ is_test: this.isTest,
128
+ business_unit_id: this.businessUnitId,
129
+ session_id: this.sessionId,
130
+ sequence: this.sequenceCounter++,
131
+ timestamp: new Date().toISOString(),
132
+ platform: this.detectPlatform(),
133
+ ...extras,
134
+ };
135
+
136
+ this.queue.push(funnelEvent);
137
+ this.persistQueue();
138
+
139
+ if (this.queue.length >= BATCH_SIZE) {
140
+ this.flush();
141
+ } else if (!this.flushTimer) {
142
+ this.flushTimer = setTimeout(() => this.flush(), FLUSH_INTERVAL_MS);
143
+ }
144
+ }
145
+
146
+ /** Convenience: track widget open */
147
+ trackOpen(widget: string) {
148
+ this.widgetStartTimes.set(`${widget}_${this.sessionId}`, Date.now());
149
+ this.track(`sdk.${widget}.opened`, widget, 'opened');
150
+ }
151
+
152
+ /** Convenience: track widget close/success/error */
153
+ trackClose(widget: string, outcome: 'success' | 'error' | 'abandoned', errorCode?: string) {
154
+ this.track(`sdk.${widget}.${outcome}`, widget, outcome, { outcome, error_code: errorCode });
155
+ this.widgetStartTimes.delete(`${widget}_${this.sessionId}`);
156
+ }
157
+
158
+ /** Flush queued events — sends one summary per widget session to the server */
159
+ async flush() {
160
+ if (this.flushTimer) {
161
+ clearTimeout(this.flushTimer);
162
+ this.flushTimer = null;
163
+ }
164
+ if (this.queue.length === 0) return;
165
+
166
+ const batch = this.queue.splice(0);
167
+
168
+ // Deduplicate: keep only the LAST event per widget (summary of that widget session)
169
+ const lastPerWidget = new Map<string, FunnelEvent>();
170
+ for (const evt of batch) {
171
+ lastPerWidget.set(evt.widget, evt);
172
+ }
173
+
174
+ const failedEvents: FunnelEvent[] = [];
175
+
176
+ for (const evt of lastPerWidget.values()) {
177
+ const payload: TelemetryPayload = {
178
+ widget: evt.widget,
179
+ duration_ms: evt.duration_ms,
180
+ outcome: mapOutcome(evt.outcome),
181
+ sdk_version: SDK_VERSION,
182
+ is_test: this.isTest,
183
+ business_unit_id: this.businessUnitId,
184
+ };
185
+ if (evt.error_code) {
186
+ payload.error_code = evt.error_code;
187
+ }
188
+
189
+ try {
190
+ await fetch(`${this.apiBaseUrl}/api/sdk/telemetry`, {
191
+ method: 'POST',
192
+ headers: {
193
+ 'Content-Type': 'application/json',
194
+ 'Authorization': `Bearer ${this.sessionToken}`,
195
+ },
196
+ body: JSON.stringify(payload),
197
+ });
198
+ } catch {
199
+ // Re-queue failed events for retry
200
+ failedEvents.push(evt);
201
+ }
202
+ }
203
+
204
+ if (failedEvents.length === 0) {
205
+ this.storage?.remove(STORAGE_KEY);
206
+ } else {
207
+ this.queue.unshift(...failedEvents);
208
+ if (this.queue.length > MAX_STORED_EVENTS) {
209
+ this.queue = this.queue.slice(-MAX_STORED_EVENTS);
210
+ }
211
+ this.persistQueue();
212
+ }
213
+ }
214
+
215
+ /** Clean up */
216
+ destroy() {
217
+ this.flush();
218
+ this.appStateSubscription?.remove();
219
+ if (this.flushTimer) clearTimeout(this.flushTimer);
220
+ }
221
+
222
+ // ==========================================================================
223
+ // Internal
224
+ // ==========================================================================
225
+
226
+ private generateSessionId(): string {
227
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
228
+ const r = Math.floor(Math.random() * 16);
229
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
230
+ return v.toString(16);
231
+ });
232
+ }
233
+
234
+ private detectPlatform(): 'ios' | 'android' | 'web' {
235
+ try {
236
+ const { Platform } = require('react-native');
237
+ return Platform.OS === 'ios' ? 'ios' : 'android';
238
+ } catch {
239
+ return 'web';
240
+ }
241
+ }
242
+
243
+ private async persistQueue() {
244
+ if (!this.storage || this.queue.length === 0) return;
245
+ try {
246
+ await this.storage.set(STORAGE_KEY, JSON.stringify(this.queue.slice(-MAX_STORED_EVENTS)));
247
+ } catch {
248
+ // storage full or unavailable — drop silently
249
+ }
250
+ }
251
+
252
+ private async loadPersistedQueue() {
253
+ if (!this.storage) return;
254
+ try {
255
+ const stored = await this.storage.get(STORAGE_KEY);
256
+ if (stored) {
257
+ const events: FunnelEvent[] = JSON.parse(stored);
258
+ this.queue.unshift(...events);
259
+ }
260
+ } catch {
261
+ // corrupted storage — ignore
262
+ }
263
+ }
264
+ }