@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,828 @@
1
+ /**
2
+ * OuterJoynProvider — React Native context provider for the OuterJoyn SDK.
3
+ *
4
+ * Initializes an SDK session, fetches payable balances and brand config,
5
+ * manages token refresh, and provides sheet-based widget orchestration.
6
+ *
7
+ * Falls back to demo mode automatically if the API is unreachable (8s timeout).
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * <OuterJoynProvider sessionToken={token} onReady={ctx => console.log(ctx)}>
12
+ * <App />
13
+ * </OuterJoynProvider>
14
+ * ```
15
+ */
16
+
17
+ import React, {
18
+ createContext,
19
+ useCallback,
20
+ useEffect,
21
+ useMemo,
22
+ useRef,
23
+ useState,
24
+ } from 'react';
25
+
26
+ import { Platform, NativeModules } from 'react-native';
27
+
28
+ import { APIClient, SDKError } from './core/api-client';
29
+ import { EventStream } from './core/event-stream';
30
+ import { AnalyticsTracker } from './core/analytics';
31
+ import { i18n } from './core/i18n';
32
+ import { OfflineCache } from './core/offline';
33
+ import { OuterJoynErrorBoundary } from './core/ErrorBoundary';
34
+ import { PaySheet, ConnectSheet, ExchangeSheet, RedeemSheet, _setContextRef } from './widgets';
35
+ import { OuterJoynSheet } from './OuterJoynSheet';
36
+
37
+ import { OJ_COLORS } from './core/colors';
38
+ import type {
39
+ OuterJoynProviderProps,
40
+ OuterJoynContextValue,
41
+ SessionContextResponse,
42
+ PayableBalance,
43
+ LinkedProgram,
44
+ BrandConfig,
45
+ SheetType,
46
+ AppearanceConfig,
47
+ StorageAdapter,
48
+ } from './core/types';
49
+
50
+ // =============================================================================
51
+ // Default Storage Adapter (AsyncStorage fallback)
52
+ // =============================================================================
53
+
54
+ let defaultStorageAdapter: StorageAdapter | null = null;
55
+ try {
56
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
57
+ const AsyncStorage = require('@react-native-async-storage/async-storage').default;
58
+ defaultStorageAdapter = {
59
+ get: (key: string) => AsyncStorage.getItem(key),
60
+ set: (key: string, value: string) => AsyncStorage.setItem(key, value),
61
+ remove: (key: string) => AsyncStorage.removeItem(key),
62
+ };
63
+ } catch {
64
+ // AsyncStorage not installed — offline caching will be silently skipped
65
+ }
66
+
67
+ // =============================================================================
68
+ // Context
69
+ // =============================================================================
70
+
71
+ export const OuterJoynContext = createContext<OuterJoynContextValue | null>(null);
72
+
73
+ // Wire context ref so widget sheets can auto-read from provider (fix #10)
74
+ _setContextRef(OuterJoynContext);
75
+
76
+ // =============================================================================
77
+ // Demo Data
78
+ // =============================================================================
79
+
80
+ const DEMO_PROGRAMS: LinkedProgram[] = [
81
+ {
82
+ id: 'prog_delta',
83
+ brandName: 'Delta SkyMiles',
84
+ membershipId: 'SKY-8472-1039',
85
+ pointsBalance: 125000,
86
+ currencyName: 'SkyMiles',
87
+ currencyCode: 'SKY',
88
+ iconColor: '#0D1B4C',
89
+ conversionRate: 80,
90
+ memberCurrencyId: -101,
91
+ currencyId: -1,
92
+ pointValueAmount: 0.012,
93
+ brandLogoUrl: 'https://img.logo.dev/delta.com?token=pk_VAZ6tvAVQHCDwKeaNRVyjQ',
94
+ brandColor: '#003366',
95
+ },
96
+ {
97
+ id: 'prog_marriott',
98
+ brandName: 'Marriott Bonvoy',
99
+ membershipId: 'MBV-291-847',
100
+ pointsBalance: 87000,
101
+ currencyName: 'Bonvoy Points',
102
+ currencyCode: 'MBV',
103
+ iconColor: '#0c90eb',
104
+ conversionRate: 100,
105
+ memberCurrencyId: -102,
106
+ currencyId: -2,
107
+ pointValueAmount: 0.008,
108
+ brandLogoUrl: 'https://img.logo.dev/marriott.com?token=pk_VAZ6tvAVQHCDwKeaNRVyjQ',
109
+ brandColor: '#8B0000',
110
+ },
111
+ {
112
+ id: 'prog_amex',
113
+ brandName: 'Amex Rewards',
114
+ membershipId: 'MR-4821',
115
+ pointsBalance: 210000,
116
+ currencyName: 'MR Points',
117
+ currencyCode: 'MR',
118
+ iconColor: '#3B82F6',
119
+ conversionRate: 50,
120
+ memberCurrencyId: -103,
121
+ currencyId: -3,
122
+ pointValueAmount: 0.02,
123
+ brandLogoUrl: 'https://img.logo.dev/americanexpress.com?token=pk_VAZ6tvAVQHCDwKeaNRVyjQ',
124
+ brandColor: '#006FCF',
125
+ },
126
+ ];
127
+
128
+ // =============================================================================
129
+ // Helpers
130
+ // =============================================================================
131
+
132
+ /** Parse a PayableBalance (camelCase or snake_case) into a normalized LinkedProgram. */
133
+ function balanceToProgram(b: PayableBalance, index: number): LinkedProgram {
134
+ const fallbackColors = [OJ_COLORS.navy, OJ_COLORS.primary, OJ_COLORS.accent, '#002244', '#003B5C', '#1A4480'];
135
+
136
+ const memberCurrencyId = b.memberCurrencyId ?? b.member_currency_id ?? 0;
137
+ const currencyId = b.currencyId ?? b.currency_id ?? 0;
138
+ const brandName = b.brandName ?? b.brand_name ?? 'Unknown';
139
+ const brandLogoUrl = b.brandLogoUrl ?? b.brand_logo_url ?? null;
140
+ const brandColor = b.brandColor ?? b.brand_color ?? null;
141
+ const currencyName = b.currencyName ?? b.currency_name ?? 'Points';
142
+ const currencyCode = b.currencyCode ?? b.currency_code ?? 'PTS';
143
+ const pointValueAmount = b.pointValueAmount ?? b.point_value_amount ?? 0;
144
+ const balance = b.balance ?? 0;
145
+
146
+ return {
147
+ id: `prog_${memberCurrencyId}`,
148
+ brandName,
149
+ membershipId: `MBR-${memberCurrencyId}`,
150
+ pointsBalance: balance,
151
+ currencyName,
152
+ currencyCode,
153
+ iconColor: brandColor ?? fallbackColors[index % fallbackColors.length],
154
+ conversionRate: pointValueAmount > 0 ? Math.round(1 / pointValueAmount) : 100,
155
+ memberCurrencyId,
156
+ currencyId,
157
+ pointValueAmount,
158
+ brandLogoUrl,
159
+ brandColor,
160
+ partnershipId: b.partnershipId ?? b.partnership_id ?? undefined,
161
+ };
162
+ }
163
+
164
+ /** Detect device locale from react-native NativeModules. */
165
+ function getDeviceLocale(): string {
166
+ try {
167
+ if (Platform.OS === 'ios') {
168
+ return (
169
+ NativeModules.SettingsManager?.settings?.AppleLocale ??
170
+ NativeModules.SettingsManager?.settings?.AppleLanguages?.[0] ??
171
+ 'en'
172
+ );
173
+ }
174
+ return NativeModules.I18nManager?.localeIdentifier ?? 'en';
175
+ } catch {
176
+ return 'en';
177
+ }
178
+ }
179
+
180
+ // =============================================================================
181
+ // Provider
182
+ // =============================================================================
183
+
184
+ /**
185
+ * Root provider for the OuterJoyn React Native SDK.
186
+ *
187
+ * Wrap your app (or the relevant subtree) with this provider to enable
188
+ * all OuterJoyn widgets and the `useOuterJoyn()` hook.
189
+ *
190
+ * On mount it validates the session token, fetches payable balances and
191
+ * brand configuration, and schedules automatic token refresh. If the API
192
+ * is unreachable within 8 seconds it falls back to demo mode with sample data.
193
+ */
194
+ export function OuterJoynProvider({
195
+ sessionToken,
196
+ apiBaseUrl = 'https://api.outerjoyn.com',
197
+ appearance,
198
+ identityHints,
199
+ storageAdapter,
200
+ locale,
201
+ realTimeUpdates = false,
202
+ onReady,
203
+ onError,
204
+ children,
205
+ }: OuterJoynProviderProps) {
206
+ // Resolve storage adapter: explicit prop > default AsyncStorage > null
207
+ const resolvedStorage = storageAdapter ?? defaultStorageAdapter;
208
+
209
+ // ---------------------------------------------------------------------------
210
+ // State
211
+ // ---------------------------------------------------------------------------
212
+
213
+ const [isReady, setIsReady] = useState(false);
214
+ const [loading, setLoading] = useState(true);
215
+ const [error, setError] = useState<Error | null>(null);
216
+ const [demoMode, setDemoMode] = useState(false);
217
+ const [linkedPrograms, setLinkedPrograms] = useState<LinkedProgram[]>([]);
218
+ const [brandConfig, setBrandConfig] = useState<BrandConfig | null>(null);
219
+ const [sessionStatus, setSessionStatus] = useState<
220
+ 'idle' | 'loading' | 'ready' | 'link_required' | 'error'
221
+ >('idle');
222
+
223
+ // Sheet state
224
+ const [activeSheet, setActiveSheet] = useState<SheetType>(null);
225
+ const [sheetProps, setSheetProps] = useState<Record<string, any>>({});
226
+
227
+ // Refs
228
+ const clientRef = useRef<APIClient | null>(null);
229
+ const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
230
+ const mountedRef = useRef(true);
231
+ const lastInitTokenRef = useRef<string | null>(null);
232
+ const eventStreamRef = useRef<EventStream | null>(null);
233
+ const analyticsRef = useRef<AnalyticsTracker | null>(null);
234
+ const offlineCacheRef = useRef<OfflineCache | null>(null);
235
+
236
+ const [isReturningUser, setIsReturningUser] = useState(false);
237
+ const [portablePrograms, setPortablePrograms] = useState<LinkedProgram[]>([]);
238
+ const [consumerIdentityId, setConsumerIdentityId] = useState<string | null>(null);
239
+
240
+ // Derived — include portable programs in linked count for checkout availability
241
+ const allPrograms = useMemo(() => [...linkedPrograms, ...portablePrograms], [linkedPrograms, portablePrograms]);
242
+ const isLinked = allPrograms.length > 0;
243
+ const totalAvailablePoints = useMemo(
244
+ () => allPrograms.reduce((sum, p) => sum + p.pointsBalance, 0),
245
+ [allPrograms],
246
+ );
247
+ const totalAvailableValue = useMemo(
248
+ () =>
249
+ allPrograms.reduce(
250
+ (sum, p) => sum + Math.round(p.pointsBalance * p.pointValueAmount),
251
+ 0,
252
+ ),
253
+ [allPrograms],
254
+ );
255
+
256
+ // Wire i18n: set locale from prop or device
257
+ useMemo(() => {
258
+ i18n.setLocale(locale || getDeviceLocale());
259
+ }, [locale]);
260
+ const t = useCallback(
261
+ (key: string, params?: Record<string, string | number>) => i18n.t(key, params),
262
+ [locale], // eslint-disable-line react-hooks/exhaustive-deps
263
+ );
264
+
265
+ // ---------------------------------------------------------------------------
266
+ // Cleanup
267
+ // ---------------------------------------------------------------------------
268
+
269
+ useEffect(() => {
270
+ mountedRef.current = true;
271
+ return () => {
272
+ mountedRef.current = false;
273
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
274
+ // Clean up EventStream and AnalyticsTracker on unmount (fix #7)
275
+ eventStreamRef.current?.disconnect();
276
+ eventStreamRef.current = null;
277
+ analyticsRef.current?.destroy();
278
+ analyticsRef.current = null;
279
+ };
280
+ }, []);
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // Token refresh scheduling
284
+ // ---------------------------------------------------------------------------
285
+
286
+ const scheduleRefresh = useCallback(
287
+ (expiresAt: string) => {
288
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
289
+ // Refresh 2 minutes before expiry
290
+ const refreshMs =
291
+ new Date(expiresAt).getTime() - Date.now() - 2 * 60 * 1000;
292
+ if (refreshMs > 0) {
293
+ refreshTimerRef.current = setTimeout(() => {
294
+ if (!mountedRef.current) return;
295
+ // Re-fetch context to refresh the session
296
+ refreshBalancesInternal();
297
+ }, refreshMs);
298
+ }
299
+ },
300
+ [], // stable — refreshBalancesInternal captured via ref below
301
+ );
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // Demo mode fallback
305
+ // ---------------------------------------------------------------------------
306
+
307
+ const enableDemoMode = useCallback(() => {
308
+ if (!mountedRef.current) return;
309
+ console.warn('[OuterJoyn RN SDK] API unreachable — entering demo mode');
310
+ setDemoMode(true);
311
+ setLinkedPrograms(DEMO_PROGRAMS);
312
+ setBrandConfig({
313
+ brand_name: 'Demo Brand',
314
+ theme: {
315
+ primaryColor: OJ_COLORS.primary,
316
+ accentColor: OJ_COLORS.accent,
317
+ backgroundColor: OJ_COLORS.white,
318
+ textColor: OJ_COLORS.navy,
319
+ },
320
+ });
321
+ setSessionStatus('ready');
322
+ setIsReady(true);
323
+ setLoading(false);
324
+ setError(null);
325
+ }, []);
326
+
327
+ // ---------------------------------------------------------------------------
328
+ // Refresh balances
329
+ // ---------------------------------------------------------------------------
330
+
331
+ const refreshBalancesInternal = useCallback(async () => {
332
+ const client = clientRef.current;
333
+ if (!client || !mountedRef.current) return;
334
+
335
+ try {
336
+ const ctx = await client.get<SessionContextResponse>(
337
+ '/api/sdk/sessions/context',
338
+ );
339
+ if (!mountedRef.current) return;
340
+
341
+ // Trust the server as the source of truth. Previously this
342
+ // guarded on `length > 0`, which silently preserved stale state
343
+ // when the server (correctly) returned an empty list. That
344
+ // masked linking failures and made the checkout UI lie about
345
+ // the user's actual linked programs.
346
+ //
347
+ // If `payable_balances` is undefined, the session response
348
+ // didn't include it (e.g., session lacks the `pay` scope) —
349
+ // leave `linkedPrograms` alone. If it's present (even as an
350
+ // empty array), we overwrite.
351
+ if (Array.isArray(ctx.payable_balances)) {
352
+ setLinkedPrograms(ctx.payable_balances.map(balanceToProgram));
353
+ }
354
+
355
+ if (ctx.brand_config) {
356
+ setBrandConfig(ctx.brand_config);
357
+ }
358
+
359
+ if (ctx.expires_at) {
360
+ scheduleRefresh(ctx.expires_at);
361
+ }
362
+ } catch (err: any) {
363
+ console.warn('[OuterJoyn RN SDK] Balance refresh failed:', err.message);
364
+ }
365
+ }, [scheduleRefresh]);
366
+
367
+ const refreshBalances = useCallback(async () => {
368
+ if (demoMode) return;
369
+ return refreshBalancesInternal();
370
+ }, [demoMode, refreshBalancesInternal]);
371
+
372
+ // ---------------------------------------------------------------------------
373
+ // Initialize session on mount / token change
374
+ // ---------------------------------------------------------------------------
375
+
376
+ useEffect(() => {
377
+ if (lastInitTokenRef.current === sessionToken) return;
378
+ lastInitTokenRef.current = sessionToken;
379
+
380
+ let cancelled = false;
381
+
382
+ async function init() {
383
+ if (!sessionToken) {
384
+ setError(new Error('sessionToken is required'));
385
+ setSessionStatus('error');
386
+ setLoading(false);
387
+ return;
388
+ }
389
+
390
+ setSessionStatus('loading');
391
+ setLoading(true);
392
+ setError(null);
393
+
394
+ const client = new APIClient(sessionToken, apiBaseUrl, {
395
+ timeoutMs: 8000,
396
+ debug: __DEV__,
397
+ onSessionExpired: () => {
398
+ if (!mountedRef.current) return;
399
+ setSessionStatus('error');
400
+ setError(new Error('Session expired'));
401
+ },
402
+ });
403
+ clientRef.current = client;
404
+
405
+ // Initialize offline cache with resolved storage adapter
406
+ if (resolvedStorage) {
407
+ offlineCacheRef.current = new OfflineCache(resolvedStorage, sessionToken);
408
+ }
409
+
410
+ try {
411
+ // Build identity hint query params
412
+ const identityParams: Record<string, string> = {};
413
+ if (identityHints?.phone) identityParams.identity_phone = identityHints.phone;
414
+ if (identityHints?.email) identityParams.identity_email = identityHints.email;
415
+
416
+ const ctx = await client.get<SessionContextResponse>(
417
+ '/api/sdk/sessions/context',
418
+ Object.keys(identityParams).length > 0 ? identityParams : undefined,
419
+ );
420
+ if (cancelled) return;
421
+
422
+ // Detect returning user from server response
423
+ setIsReturningUser(ctx.returning_user === true);
424
+
425
+ // Parse balances
426
+ const programs =
427
+ ctx.payable_balances && ctx.payable_balances.length > 0
428
+ ? ctx.payable_balances.map(balanceToProgram)
429
+ : [];
430
+
431
+ setLinkedPrograms(programs);
432
+ setBrandConfig(ctx.brand_config ?? null);
433
+
434
+ // Persist to offline cache
435
+ if (offlineCacheRef.current) {
436
+ if (programs.length > 0) {
437
+ offlineCacheRef.current.savePrograms(programs);
438
+ }
439
+ if (ctx.brand_config) {
440
+ offlineCacheRef.current.saveBrandConfig(ctx.brand_config);
441
+ }
442
+ }
443
+
444
+ const status =
445
+ ctx.status === 'link_required' ? 'link_required' : 'ready';
446
+ setSessionStatus(status);
447
+ setIsReady(true);
448
+ setLoading(false);
449
+
450
+ if (ctx.expires_at) {
451
+ scheduleRefresh(ctx.expires_at);
452
+ }
453
+
454
+ // Fetch cross-BU portable programs (non-blocking).
455
+ // These are programs the consumer linked in Joyn Wallet or other
456
+ // brand apps that this BU's partnerships accept.
457
+ client.get<{
458
+ consumer_identity_id: string | null;
459
+ portable_programs: Array<{
460
+ currency_id: string;
461
+ currency_name: string;
462
+ currency_code: string;
463
+ partner_brand_name: string;
464
+ partner_brand_logo_url: string | null;
465
+ cached_balance: number | null;
466
+ point_value_amount: number;
467
+ estimated_value_cents: number | null;
468
+ partnership_id: string;
469
+ link_id: string;
470
+ linked_at: string;
471
+ }>;
472
+ consent_status: string;
473
+ }>('/api/sdk/portable-programs').then((portableData) => {
474
+ if (cancelled || !mountedRef.current) return;
475
+ if (portableData.consumer_identity_id) {
476
+ setConsumerIdentityId(portableData.consumer_identity_id);
477
+ }
478
+ if (portableData.portable_programs?.length > 0) {
479
+ const mapped = portableData.portable_programs.map((pp, i): LinkedProgram => ({
480
+ id: `portable_${pp.link_id}`,
481
+ brandName: pp.partner_brand_name,
482
+ membershipId: `PORT-${pp.link_id}`,
483
+ pointsBalance: pp.cached_balance ?? 0,
484
+ currencyName: pp.currency_name,
485
+ currencyCode: pp.currency_code,
486
+ iconColor: OJ_COLORS.primary,
487
+ conversionRate: pp.point_value_amount > 0 ? Math.round(1 / pp.point_value_amount) : 100,
488
+ memberCurrencyId: pp.currency_id ? String(pp.currency_id) : -(1000 + i),
489
+ currencyId: pp.currency_id ? String(pp.currency_id) : -(1000 + i),
490
+ pointValueAmount: pp.point_value_amount,
491
+ brandLogoUrl: pp.partner_brand_logo_url,
492
+ brandColor: null,
493
+ }));
494
+ setPortablePrograms(mapped);
495
+ }
496
+ }).catch(() => {
497
+ // Portable programs are optional — silently ignore errors
498
+ });
499
+
500
+ // --- Fix #7: Wire EventStream after successful session init (opt-in) ---
501
+ if (realTimeUpdates) {
502
+ const es = new EventStream(apiBaseUrl, sessionToken);
503
+ es.on('balance_changed', () => {
504
+ refreshBalancesInternal();
505
+ });
506
+ es.connect();
507
+ eventStreamRef.current = es;
508
+ }
509
+
510
+ // --- Fix #7: Wire AnalyticsTracker ---
511
+ const isTest = ctx.status === 'link_required' || false;
512
+ const analytics = new AnalyticsTracker({
513
+ apiBaseUrl,
514
+ sessionToken,
515
+ isTest,
516
+ businessUnitId: ctx.business_unit_id ? String(ctx.business_unit_id) : undefined,
517
+ storage: resolvedStorage ?? undefined,
518
+ });
519
+ analyticsRef.current = analytics;
520
+ analytics.track('sdk.provider.ready', 'provider', 'ready');
521
+
522
+ onReady?.(ctx);
523
+ } catch (err: any) {
524
+ if (cancelled) return;
525
+
526
+ // Network/timeout errors -> try offline cache, then demo mode
527
+ if (
528
+ err instanceof SDKError &&
529
+ (err.code === 'NETWORK_ERROR' || err.code === 'TIMEOUT')
530
+ ) {
531
+ if (offlineCacheRef.current) {
532
+ try {
533
+ const cached = await offlineCacheRef.current.getCachedState();
534
+ if (cached.linkedPrograms && cached.linkedPrograms.length > 0) {
535
+ setLinkedPrograms(cached.linkedPrograms);
536
+ setBrandConfig(cached.brandConfig ?? null);
537
+ setSessionStatus('ready');
538
+ setIsReady(true);
539
+ setLoading(false);
540
+ return;
541
+ }
542
+ } catch {
543
+ // cache read failed — fall through to demo
544
+ }
545
+ }
546
+ enableDemoMode();
547
+ return;
548
+ }
549
+
550
+ // Other errors (auth, validation, etc.)
551
+ const e = err instanceof Error ? err : new Error(String(err));
552
+ setError(e);
553
+ setSessionStatus('error');
554
+ setLoading(false);
555
+ onError?.(e);
556
+ }
557
+ }
558
+
559
+ init();
560
+
561
+ return () => {
562
+ cancelled = true;
563
+ };
564
+ }, [sessionToken]); // eslint-disable-line react-hooks/exhaustive-deps
565
+
566
+ // Re-init is handled by the main init effect via lastInitTokenRef keyed on sessionToken.
567
+ // EventStream token updates happen automatically on re-init.
568
+
569
+ // ---------------------------------------------------------------------------
570
+ // Sheet actions (with analytics tracking — fix #7)
571
+ // ---------------------------------------------------------------------------
572
+
573
+ const openSheet = useCallback(
574
+ (sheet: SheetType, props: Record<string, any> = {}) => {
575
+ setSheetProps(props);
576
+ setActiveSheet(sheet);
577
+ },
578
+ [],
579
+ );
580
+
581
+ const closeSheet = useCallback(() => {
582
+ setActiveSheet(null);
583
+ setSheetProps({});
584
+ }, []);
585
+
586
+ const openConnect = useCallback(
587
+ (opts?: { institutionId?: string }) => {
588
+ analyticsRef.current?.trackOpen('connect');
589
+ openSheet('connect', opts ?? {});
590
+ },
591
+ [openSheet],
592
+ );
593
+
594
+ const openExchange = useCallback(
595
+ (opts?: { sourceCurrencyId?: number }) => {
596
+ analyticsRef.current?.trackOpen('exchange');
597
+ openSheet('exchange', opts ?? {});
598
+ },
599
+ [openSheet],
600
+ );
601
+
602
+ const openRedeem = useCallback(
603
+ (opts?: { category?: string }) => {
604
+ analyticsRef.current?.trackOpen('redeem');
605
+ openSheet('redeem', opts ?? {});
606
+ },
607
+ [openSheet],
608
+ );
609
+
610
+ const openPay = useCallback(
611
+ (opts: { orderTotalCents: number; merchantOrderId?: string }) => {
612
+ analyticsRef.current?.trackOpen('pay');
613
+ openSheet('pay', opts);
614
+ },
615
+ [openSheet],
616
+ );
617
+
618
+ const openAccount = useCallback(() => {
619
+ analyticsRef.current?.trackOpen('account');
620
+ openSheet('account', {});
621
+ }, [openSheet]);
622
+
623
+ const unlinkProgram = useCallback((programId: string) => {
624
+ setLinkedPrograms((prev) => prev.filter((p) => p.id !== programId));
625
+ }, []);
626
+
627
+ // ---------------------------------------------------------------------------
628
+ // Sheet event handlers
629
+ // ---------------------------------------------------------------------------
630
+
631
+ const handleSheetSuccess = useCallback(
632
+ async (_result: any) => {
633
+ // Refresh balances after a successful widget action, then close
634
+ // the sheet. Awaiting is important: if the sheet closes before
635
+ // the refresh lands, `CheckoutPointsApply` and other consumers
636
+ // re-render with stale `linkedPrograms` and the user sees their
637
+ // old balances for one frame. See HOSTED-OAUTH-PROVIDER-PLAN.md
638
+ // ("race between handleSheetSuccess and refreshBalances").
639
+ try {
640
+ await refreshBalances();
641
+ } catch (err) {
642
+ // refreshBalances never throws in practice — it catches and
643
+ // logs internally — but be defensive so we still close the
644
+ // sheet on unexpected errors.
645
+ console.warn('[OuterJoyn RN SDK] refreshBalances threw unexpectedly:', err);
646
+ }
647
+ closeSheet();
648
+ },
649
+ [refreshBalances, closeSheet],
650
+ );
651
+
652
+ const handleSheetError = useCallback(
653
+ (err: any) => {
654
+ console.warn('[OuterJoyn RN SDK] Sheet error:', err);
655
+ // Keep sheet open — let the user retry or close manually
656
+ },
657
+ [],
658
+ );
659
+
660
+ // ---------------------------------------------------------------------------
661
+ // Resolve theme for sheets
662
+ // ---------------------------------------------------------------------------
663
+
664
+ const resolvedTheme = useMemo(() => {
665
+ const bcTheme = brandConfig?.theme;
666
+ return {
667
+ primaryColor: appearance?.colors?.primary ?? bcTheme?.primaryColor ?? OJ_COLORS.primary,
668
+ accentColor: appearance?.colors?.accent ?? bcTheme?.accentColor ?? OJ_COLORS.accent,
669
+ backgroundColor: appearance?.colors?.background ?? bcTheme?.backgroundColor ?? OJ_COLORS.white,
670
+ textColor: appearance?.colors?.text ?? bcTheme?.textColor ?? OJ_COLORS.navy,
671
+ };
672
+ }, [appearance, brandConfig]);
673
+
674
+ // ---------------------------------------------------------------------------
675
+ // Context value (fix #11: expose apiClient via context)
676
+ // ---------------------------------------------------------------------------
677
+
678
+ const contextValue = useMemo<OuterJoynContextValue>(
679
+ () => ({
680
+ // State
681
+ isReady,
682
+ isLinked,
683
+ isReturningUser,
684
+ linkedPrograms,
685
+ portablePrograms,
686
+ consumerIdentityId,
687
+ totalAvailablePoints,
688
+ totalAvailableValue,
689
+ loading,
690
+ error,
691
+ demoMode,
692
+ brandConfig,
693
+
694
+ // Actions
695
+ refreshBalances,
696
+ openConnect,
697
+ openExchange,
698
+ openRedeem,
699
+ openPay,
700
+ openAccount,
701
+ closeSheet,
702
+ unlinkProgram,
703
+
704
+ // Session
705
+ sessionToken,
706
+ sessionStatus,
707
+
708
+ // Shared API client (fix #11)
709
+ apiClient: clientRef.current,
710
+ apiBaseUrl,
711
+
712
+ // i18n
713
+ t,
714
+ }),
715
+ [
716
+ isReady,
717
+ isLinked,
718
+ isReturningUser,
719
+ linkedPrograms,
720
+ portablePrograms,
721
+ consumerIdentityId,
722
+ totalAvailablePoints,
723
+ totalAvailableValue,
724
+ loading,
725
+ error,
726
+ demoMode,
727
+ brandConfig,
728
+ refreshBalances,
729
+ openConnect,
730
+ openExchange,
731
+ openRedeem,
732
+ openPay,
733
+ openAccount,
734
+ closeSheet,
735
+ unlinkProgram,
736
+ sessionToken,
737
+ sessionStatus,
738
+ t,
739
+ ],
740
+ );
741
+
742
+ // ---------------------------------------------------------------------------
743
+ // Render
744
+ // ---------------------------------------------------------------------------
745
+
746
+ return (
747
+ <OuterJoynContext.Provider value={contextValue}>
748
+ <OuterJoynErrorBoundary onError={(err) => onError?.(err)}>
749
+ {children}
750
+ </OuterJoynErrorBoundary>
751
+
752
+ {/* Sheet widgets — rendered conditionally based on activeSheet */}
753
+ {activeSheet === 'pay' && (
754
+ <OuterJoynErrorBoundary onError={(err) => { handleSheetError(err); closeSheet(); }}>
755
+ <PaySheet
756
+ visible
757
+ sessionToken={sessionToken}
758
+ apiBaseUrl={apiBaseUrl}
759
+ theme={resolvedTheme}
760
+ orderTotal={sheetProps.orderTotalCents}
761
+ currencyCode={sheetProps.currencyCode}
762
+ onSuccess={handleSheetSuccess}
763
+ onError={handleSheetError}
764
+ onClose={closeSheet}
765
+ />
766
+ </OuterJoynErrorBoundary>
767
+ )}
768
+
769
+ {activeSheet === 'connect' && (
770
+ <OuterJoynErrorBoundary onError={(err) => { handleSheetError(err); closeSheet(); }}>
771
+ <ConnectSheet
772
+ visible
773
+ sessionToken={sessionToken}
774
+ apiBaseUrl={apiBaseUrl}
775
+ theme={resolvedTheme}
776
+ onSuccess={handleSheetSuccess}
777
+ onError={handleSheetError}
778
+ onClose={closeSheet}
779
+ />
780
+ </OuterJoynErrorBoundary>
781
+ )}
782
+
783
+ {activeSheet === 'exchange' && (
784
+ <OuterJoynErrorBoundary onError={(err) => { handleSheetError(err); closeSheet(); }}>
785
+ <ExchangeSheet
786
+ visible
787
+ sessionToken={sessionToken}
788
+ apiBaseUrl={apiBaseUrl}
789
+ theme={resolvedTheme}
790
+ onSuccess={handleSheetSuccess}
791
+ onError={handleSheetError}
792
+ onClose={closeSheet}
793
+ />
794
+ </OuterJoynErrorBoundary>
795
+ )}
796
+
797
+ {activeSheet === 'redeem' && (
798
+ <OuterJoynErrorBoundary onError={(err) => { handleSheetError(err); closeSheet(); }}>
799
+ <RedeemSheet
800
+ visible
801
+ sessionToken={sessionToken}
802
+ apiBaseUrl={apiBaseUrl}
803
+ theme={resolvedTheme}
804
+ onSuccess={handleSheetSuccess}
805
+ onError={handleSheetError}
806
+ onClose={closeSheet}
807
+ />
808
+ </OuterJoynErrorBoundary>
809
+ )}
810
+
811
+ {activeSheet === 'account' && (
812
+ <OuterJoynErrorBoundary onError={(err) => { handleSheetError(err); closeSheet(); }}>
813
+ <OuterJoynSheet
814
+ visible
815
+ sessionToken={sessionToken}
816
+ apiBaseUrl={apiBaseUrl}
817
+ theme={resolvedTheme}
818
+ module="account"
819
+ title="Account"
820
+ onSuccess={handleSheetSuccess}
821
+ onError={handleSheetError}
822
+ onClose={closeSheet}
823
+ />
824
+ </OuterJoynErrorBoundary>
825
+ )}
826
+ </OuterJoynContext.Provider>
827
+ );
828
+ }