@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,253 @@
1
+ /**
2
+ * API Client for React Native SDK
3
+ *
4
+ * Ported from src/sdk/core/api-client.ts with RN-specific adaptations:
5
+ * - Uses plain fetch() (available in Hermes)
6
+ * - AbortController for timeouts (available in Hermes)
7
+ * - No browser-specific APIs (credentials, mode, DOMException)
8
+ * - Same retry logic: GET retries on network+5xx, POST retries on network only
9
+ * - Same error code mapping from backend
10
+ * - Session expiry detection (401 → onSessionExpired callback)
11
+ */
12
+
13
+ import { SDK_VERSION } from './version';
14
+
15
+ // =============================================================================
16
+ // Types
17
+ // =============================================================================
18
+
19
+ export class SDKError extends Error {
20
+ code: string;
21
+ requestId?: string;
22
+ param?: string;
23
+ docUrl?: string;
24
+ details?: Record<string, unknown>;
25
+
26
+ constructor(code: string, message: string, extras?: Partial<SDKError>) {
27
+ super(message);
28
+ this.name = 'SDKError';
29
+ this.code = code;
30
+ if (extras) {
31
+ this.requestId = extras.requestId;
32
+ this.param = extras.param;
33
+ this.docUrl = extras.docUrl;
34
+ this.details = extras.details;
35
+ }
36
+ }
37
+ }
38
+
39
+ export type ErrorCode =
40
+ | 'SESSION_EXPIRED'
41
+ | 'LINK_REQUIRED'
42
+ | 'FORBIDDEN'
43
+ | 'NOT_FOUND'
44
+ | 'VALIDATION_ERROR'
45
+ | 'INSUFFICIENT_BALANCE'
46
+ | 'OUT_OF_STOCK'
47
+ | 'RATE_LIMITED'
48
+ | 'DUPLICATE_REQUEST'
49
+ | 'SCOPE_DENIED'
50
+ | 'CURRENCY_NOT_FOUND'
51
+ | 'RATE_CHANGED'
52
+ | 'PROGRAM_INACTIVE'
53
+ | 'TIMEOUT'
54
+ | 'NETWORK_ERROR'
55
+ | 'API_ERROR';
56
+
57
+ interface APIClientOptions {
58
+ onSessionExpired?: () => void;
59
+ debug?: boolean;
60
+ timeoutMs?: number;
61
+ }
62
+
63
+ // =============================================================================
64
+ // Non-retryable error codes
65
+ // =============================================================================
66
+
67
+ const NON_RETRYABLE_CODES = new Set<string>([
68
+ 'SESSION_EXPIRED', 'FORBIDDEN', 'NOT_FOUND', 'VALIDATION_ERROR',
69
+ 'LINK_REQUIRED', 'SCOPE_DENIED', 'INSUFFICIENT_BALANCE', 'OUT_OF_STOCK',
70
+ 'RATE_LIMITED', 'DUPLICATE_REQUEST', 'CURRENCY_NOT_FOUND', 'RATE_CHANGED',
71
+ 'PROGRAM_INACTIVE',
72
+ ]);
73
+
74
+ // Backend code → SDK code mapping
75
+ const CODE_MAP: Record<string, ErrorCode> = {
76
+ insufficient_balance: 'INSUFFICIENT_BALANCE',
77
+ out_of_stock: 'OUT_OF_STOCK',
78
+ exchange_rate_changed: 'RATE_CHANGED',
79
+ program_inactive: 'PROGRAM_INACTIVE',
80
+ currency_not_found: 'CURRENCY_NOT_FOUND',
81
+ duplicate_request: 'DUPLICATE_REQUEST',
82
+ scope_denied: 'SCOPE_DENIED',
83
+ link_required: 'LINK_REQUIRED',
84
+ };
85
+
86
+ // =============================================================================
87
+ // API Client
88
+ // =============================================================================
89
+
90
+ export class APIClient {
91
+ private sessionToken: string;
92
+ private baseUrl: string;
93
+ private options: APIClientOptions;
94
+ private timeoutMs: number;
95
+
96
+ constructor(sessionToken: string, baseUrl: string = 'https://api.outerjoyn.com', options: APIClientOptions = {}) {
97
+ this.sessionToken = sessionToken;
98
+ this.baseUrl = baseUrl.replace(/\/+$/, '');
99
+ this.options = options;
100
+ this.timeoutMs = options.timeoutMs ?? 30000;
101
+ }
102
+
103
+ updateToken(token: string) {
104
+ this.sessionToken = token;
105
+ }
106
+
107
+ async get<T = any>(path: string, params?: Record<string, string>): Promise<T> {
108
+ let url = `${this.baseUrl}${path}`;
109
+ if (params) {
110
+ const qs = new URLSearchParams(params).toString();
111
+ if (qs) url += `?${qs}`;
112
+ }
113
+ return this.requestWithRetry<T>('GET', url, undefined, true);
114
+ }
115
+
116
+ async post<T = any>(path: string, body?: any): Promise<T> {
117
+ const url = `${this.baseUrl}${path}`;
118
+ return this.requestWithRetry<T>('POST', url, body, false);
119
+ }
120
+
121
+ async patch<T = any>(path: string, body?: any): Promise<T> {
122
+ const url = `${this.baseUrl}${path}`;
123
+ return this.requestWithRetry<T>('PATCH', url, body, false);
124
+ }
125
+
126
+ // ==========================================================================
127
+ // Internal
128
+ // ==========================================================================
129
+
130
+ private async requestWithRetry<T>(
131
+ method: string,
132
+ url: string,
133
+ body: any | undefined,
134
+ retryOnServerError: boolean,
135
+ attempt: number = 0,
136
+ ): Promise<T> {
137
+ const MAX_RETRIES = 3;
138
+ const BASE_DELAY_MS = 200;
139
+
140
+ try {
141
+ return await this.request<T>(method, url, body);
142
+ } catch (error: any) {
143
+ const isSDKError = error instanceof SDKError;
144
+ const isNonRetryable = isSDKError && NON_RETRYABLE_CODES.has(error.code);
145
+
146
+ if (isNonRetryable || attempt >= MAX_RETRIES) {
147
+ throw error;
148
+ }
149
+
150
+ // For POST/PATCH, only retry on network errors (not 5xx — prevents duplicate mutations)
151
+ const isNetworkError = !isSDKError || error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT';
152
+ const isServerError = isSDKError && error.code === 'API_ERROR';
153
+
154
+ if (!isNetworkError && !(retryOnServerError && isServerError)) {
155
+ throw error;
156
+ }
157
+
158
+ // Exponential backoff with jitter
159
+ const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 100;
160
+ await new Promise((r) => setTimeout(r, delay));
161
+
162
+ return this.requestWithRetry<T>(method, url, body, retryOnServerError, attempt + 1);
163
+ }
164
+ }
165
+
166
+ private async request<T>(method: string, url: string, body?: any): Promise<T> {
167
+ const controller = new AbortController();
168
+ const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
169
+ const startTime = Date.now();
170
+
171
+ try {
172
+ const headers: Record<string, string> = {
173
+ 'Authorization': `Bearer ${this.sessionToken}`,
174
+ 'X-SDK-Version': SDK_VERSION,
175
+ 'X-SDK-Platform': 'react-native',
176
+ };
177
+
178
+ if (body !== undefined) {
179
+ headers['Content-Type'] = 'application/json';
180
+ }
181
+
182
+ const response = await fetch(url, {
183
+ method,
184
+ headers,
185
+ body: body !== undefined ? JSON.stringify(body) : undefined,
186
+ signal: controller.signal,
187
+ });
188
+
189
+ clearTimeout(timeoutId);
190
+
191
+ if (this.options.debug) {
192
+ const duration = Date.now() - startTime;
193
+ console.debug(`[OuterJoyn SDK] ${method} ${url} → ${response.status} (${duration}ms)`);
194
+ }
195
+
196
+ // Parse response
197
+ const text = await response.text();
198
+ let data: any;
199
+ try {
200
+ data = JSON.parse(text);
201
+ } catch {
202
+ data = { error: { message: text.slice(0, 200) } };
203
+ }
204
+
205
+ if (!response.ok) {
206
+ return this.handleErrorResponse(response.status, data);
207
+ }
208
+
209
+ return data as T;
210
+ } catch (error: any) {
211
+ clearTimeout(timeoutId);
212
+
213
+ if (error instanceof SDKError) throw error;
214
+
215
+ if (error.name === 'AbortError') {
216
+ throw new SDKError('TIMEOUT', 'Request timed out');
217
+ }
218
+
219
+ throw new SDKError('NETWORK_ERROR', error.message || 'Network request failed');
220
+ }
221
+ }
222
+
223
+ private handleErrorResponse(status: number, data: any): never {
224
+ // Parse nested error format: { error: { code, message, request_id, ... } }
225
+ const err = data?.error || data;
226
+ const backendCode = err?.code || '';
227
+ const message = err?.message || `Request failed with status ${status}`;
228
+ const requestId = err?.request_id;
229
+ const param = err?.param;
230
+ const docUrl = err?.doc_url;
231
+
232
+ // Session expiry
233
+ if (status === 401) {
234
+ this.options.onSessionExpired?.();
235
+ throw new SDKError('SESSION_EXPIRED', message, { requestId });
236
+ }
237
+
238
+ // Link required (special 403)
239
+ if (status === 403 && backendCode === 'link_required') {
240
+ throw new SDKError('LINK_REQUIRED', message, { requestId });
241
+ }
242
+
243
+ // Map backend code to SDK code
244
+ const sdkCode: ErrorCode = CODE_MAP[backendCode]
245
+ || (status === 403 ? 'FORBIDDEN'
246
+ : status === 404 ? 'NOT_FOUND'
247
+ : status === 422 ? 'VALIDATION_ERROR'
248
+ : status === 429 ? 'RATE_LIMITED'
249
+ : 'API_ERROR');
250
+
251
+ throw new SDKError(sdkCode, message, { requestId, param, docUrl });
252
+ }
253
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Shared color constants for the OuterJoyn RN SDK.
3
+ *
4
+ * Import from here instead of hardcoding hex values in components.
5
+ */
6
+
7
+ export const OJ_COLORS = {
8
+ primary: '#0c90eb',
9
+ navy: '#0D1B4C',
10
+ accent: '#3B82F6',
11
+ success: '#16A34A',
12
+ error: '#DC2626',
13
+ warning: '#F59E0B',
14
+ textPrimary: '#111827',
15
+ textSecondary: '#6B7280',
16
+ textMuted: '#9CA3AF',
17
+ border: '#E5E7EB',
18
+ surface: '#F9FAFB',
19
+ white: '#FFFFFF',
20
+ };
@@ -0,0 +1,229 @@
1
+ /**
2
+ * SSE Event Stream — Real-time updates for the OuterJoyn RN SDK
3
+ *
4
+ * Uses react-native-sse (pure JS, works in Expo Go).
5
+ * Connects to /api/sdk/events for live balance/status updates.
6
+ *
7
+ * Lifecycle:
8
+ * - Connect when app is in foreground
9
+ * - Disconnect on app background (iOS/Android suspend connections anyway)
10
+ * - Reconnect with exponential backoff on errors
11
+ * - Full state sync on reconnect (catch up on missed events)
12
+ *
13
+ * Events:
14
+ * - balance_changed: points earned/redeemed externally
15
+ * - link_status_changed: program linked/unlinked from another device
16
+ * - reward_available: new reward unlocked
17
+ * - tier_changed: tier upgrade/downgrade
18
+ */
19
+
20
+ import { AppState, type AppStateStatus } from 'react-native';
21
+
22
+ // =============================================================================
23
+ // Types
24
+ // =============================================================================
25
+
26
+ export type SDKEventType =
27
+ | 'balance_changed'
28
+ | 'link_status_changed'
29
+ | 'reward_available'
30
+ | 'tier_changed';
31
+
32
+ export interface SDKEvent {
33
+ type: SDKEventType;
34
+ data: Record<string, any>;
35
+ timestamp: string;
36
+ }
37
+
38
+ export type EventHandler = (event: SDKEvent) => void;
39
+
40
+ // =============================================================================
41
+ // Event Stream
42
+ // =============================================================================
43
+
44
+ export class EventStream {
45
+ private apiBaseUrl: string;
46
+ private sessionToken: string;
47
+ private handlers = new Map<string, Set<EventHandler>>();
48
+ private eventSource: any = null; // react-native-sse EventSource
49
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
50
+ private reconnectDelay = 1000;
51
+ private maxReconnectDelay = 30000;
52
+ private appStateSubscription: any = null;
53
+ private connected = false;
54
+ private endpointMissing = false; // true if server returned 404 — stops reconnect
55
+
56
+ constructor(apiBaseUrl: string, sessionToken: string) {
57
+ this.apiBaseUrl = apiBaseUrl.replace(/\/+$/, '');
58
+ this.sessionToken = sessionToken;
59
+ }
60
+
61
+ /**
62
+ * Start listening for events.
63
+ * Auto-disconnects on app background, reconnects on foreground.
64
+ */
65
+ connect() {
66
+ this.setupAppStateListener();
67
+ this.openConnection();
68
+ }
69
+
70
+ /**
71
+ * Stop listening and clean up all resources.
72
+ */
73
+ disconnect() {
74
+ this.closeConnection();
75
+ this.clearReconnectTimer();
76
+ if (this.appStateSubscription) {
77
+ this.appStateSubscription.remove();
78
+ this.appStateSubscription = null;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Register an event handler.
84
+ * Returns unsubscribe function.
85
+ */
86
+ on(event: SDKEventType | '*', handler: EventHandler): () => void {
87
+ if (!this.handlers.has(event)) {
88
+ this.handlers.set(event, new Set());
89
+ }
90
+ this.handlers.get(event)!.add(handler);
91
+ return () => this.handlers.get(event)?.delete(handler);
92
+ }
93
+
94
+ /**
95
+ * Update the session token (e.g., after refresh).
96
+ * Reconnects with the new token.
97
+ */
98
+ updateToken(token: string) {
99
+ this.sessionToken = token;
100
+ if (this.connected) {
101
+ this.closeConnection();
102
+ this.openConnection();
103
+ }
104
+ }
105
+
106
+ // ==========================================================================
107
+ // Internal
108
+ // ==========================================================================
109
+
110
+ private async openConnection() {
111
+ if (this.endpointMissing) return; // endpoint confirmed missing — don't retry
112
+
113
+ try {
114
+ // Pre-flight check: verify the endpoint exists before opening SSE
115
+ try {
116
+ const checkResp = await fetch(`${this.apiBaseUrl}/api/sdk/events`, {
117
+ method: 'HEAD',
118
+ headers: { 'Authorization': `Bearer ${this.sessionToken}` },
119
+ });
120
+ if (checkResp.status === 404) {
121
+ this.endpointMissing = true;
122
+ console.debug('[OuterJoyn SDK] SSE endpoint not found (404). Real-time updates disabled.');
123
+ return;
124
+ }
125
+ } catch {
126
+ // Network error during pre-flight — proceed to SSE (it will retry on error)
127
+ }
128
+
129
+ // Dynamically import react-native-sse to keep it optional
130
+ const { default: EventSource } = await import('react-native-sse');
131
+
132
+ const url = `${this.apiBaseUrl}/api/sdk/events`;
133
+
134
+ this.eventSource = new EventSource(url, {
135
+ headers: {
136
+ 'Authorization': `Bearer ${this.sessionToken}`,
137
+ 'Accept': 'text/event-stream',
138
+ },
139
+ });
140
+
141
+ this.eventSource.addEventListener('open', () => {
142
+ this.connected = true;
143
+ this.reconnectDelay = 1000; // reset on success
144
+ });
145
+
146
+ // Listen for typed events
147
+ for (const eventType of ['balance_changed', 'link_status_changed', 'reward_available', 'tier_changed']) {
148
+ this.eventSource.addEventListener(eventType, (e: any) => {
149
+ try {
150
+ const data = JSON.parse(e.data);
151
+ const event: SDKEvent = { type: eventType as SDKEventType, data, timestamp: new Date().toISOString() };
152
+ this.emit(event);
153
+ } catch {
154
+ // ignore malformed events
155
+ }
156
+ });
157
+ }
158
+
159
+ // Generic message handler for untyped events
160
+ this.eventSource.addEventListener('message', (e: any) => {
161
+ try {
162
+ const data = JSON.parse(e.data);
163
+ if (data.type) {
164
+ const event: SDKEvent = { type: data.type, data: data.data || data, timestamp: new Date().toISOString() };
165
+ this.emit(event);
166
+ }
167
+ } catch {
168
+ // ignore
169
+ }
170
+ });
171
+
172
+ this.eventSource.addEventListener('error', () => {
173
+ this.connected = false;
174
+ this.scheduleReconnect();
175
+ });
176
+ } catch {
177
+ // react-native-sse not installed — SSE disabled silently
178
+ console.debug('[OuterJoyn SDK] SSE not available (react-native-sse not installed). Real-time updates disabled.');
179
+ }
180
+ }
181
+
182
+ private closeConnection() {
183
+ if (this.eventSource) {
184
+ this.eventSource.close();
185
+ this.eventSource = null;
186
+ }
187
+ this.connected = false;
188
+ }
189
+
190
+ private scheduleReconnect() {
191
+ this.clearReconnectTimer();
192
+ this.closeConnection();
193
+ this.reconnectTimer = setTimeout(() => {
194
+ this.openConnection();
195
+ }, this.reconnectDelay);
196
+ this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay);
197
+ }
198
+
199
+ private clearReconnectTimer() {
200
+ if (this.reconnectTimer) {
201
+ clearTimeout(this.reconnectTimer);
202
+ this.reconnectTimer = null;
203
+ }
204
+ }
205
+
206
+ private setupAppStateListener() {
207
+ this.appStateSubscription = AppState.addEventListener('change', (state: AppStateStatus) => {
208
+ if (state === 'active') {
209
+ // Reconnect and sync when coming to foreground
210
+ this.openConnection();
211
+ } else if (state === 'background' || state === 'inactive') {
212
+ // Disconnect to save battery — iOS/Android will drop the connection anyway
213
+ this.closeConnection();
214
+ this.clearReconnectTimer();
215
+ }
216
+ });
217
+ }
218
+
219
+ private emit(event: SDKEvent) {
220
+ // Fire specific handlers
221
+ this.handlers.get(event.type)?.forEach((handler) => {
222
+ try { handler(event); } catch { /* don't crash on handler error */ }
223
+ });
224
+ // Fire wildcard handlers
225
+ this.handlers.get('*')?.forEach((handler) => {
226
+ try { handler(event); } catch { /* don't crash on handler error */ }
227
+ });
228
+ }
229
+ }