@explorins/pers-sdk-react-native 1.3.2

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 (63) hide show
  1. package/README.md +200 -0
  2. package/dist/hooks/index.d.ts +8 -0
  3. package/dist/hooks/index.d.ts.map +1 -0
  4. package/dist/hooks/index.js +8 -0
  5. package/dist/hooks/useAuth.d.ts +12 -0
  6. package/dist/hooks/useAuth.d.ts.map +1 -0
  7. package/dist/hooks/useAuth.js +16 -0
  8. package/dist/hooks/useBusiness.d.ts +7 -0
  9. package/dist/hooks/useBusiness.d.ts.map +1 -0
  10. package/dist/hooks/useBusiness.js +64 -0
  11. package/dist/hooks/useCampaigns.d.ts +8 -0
  12. package/dist/hooks/useCampaigns.d.ts.map +1 -0
  13. package/dist/hooks/useCampaigns.js +90 -0
  14. package/dist/hooks/useRedemptions.d.ts +9 -0
  15. package/dist/hooks/useRedemptions.d.ts.map +1 -0
  16. package/dist/hooks/useRedemptions.js +121 -0
  17. package/dist/hooks/useTokens.d.ts +6 -0
  18. package/dist/hooks/useTokens.d.ts.map +1 -0
  19. package/dist/hooks/useTokens.js +48 -0
  20. package/dist/hooks/useTransactions.d.ts +7 -0
  21. package/dist/hooks/useTransactions.d.ts.map +1 -0
  22. package/dist/hooks/useTransactions.js +78 -0
  23. package/dist/hooks/useWeb3.d.ts +11 -0
  24. package/dist/hooks/useWeb3.d.ts.map +1 -0
  25. package/dist/hooks/useWeb3.js +63 -0
  26. package/dist/index.d.ts +7 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.esm.js +1057 -0
  29. package/dist/index.esm.js.map +1 -0
  30. package/dist/index.js +1077 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/polyfills/index.d.ts +3 -0
  33. package/dist/polyfills/index.d.ts.map +1 -0
  34. package/dist/polyfills/index.js +13 -0
  35. package/dist/polyfills/index.simple.d.ts +2 -0
  36. package/dist/polyfills/index.simple.d.ts.map +1 -0
  37. package/dist/polyfills/index.simple.js +17 -0
  38. package/dist/providers/PersSDKProvider.d.ts +29 -0
  39. package/dist/providers/PersSDKProvider.d.ts.map +1 -0
  40. package/dist/providers/PersSDKProvider.js +194 -0
  41. package/dist/providers/react-native-auth-provider.d.ts +92 -0
  42. package/dist/providers/react-native-auth-provider.d.ts.map +1 -0
  43. package/dist/providers/react-native-auth-provider.js +268 -0
  44. package/dist/providers/react-native-http-client.d.ts +29 -0
  45. package/dist/providers/react-native-http-client.d.ts.map +1 -0
  46. package/dist/providers/react-native-http-client.js +94 -0
  47. package/package.json +157 -0
  48. package/src/hooks/index.ts +8 -0
  49. package/src/hooks/useAuth.ts +43 -0
  50. package/src/hooks/useBusiness.ts +69 -0
  51. package/src/hooks/useCampaigns.ts +96 -0
  52. package/src/hooks/useRedemptions.ts +129 -0
  53. package/src/hooks/useTokens.ts +53 -0
  54. package/src/hooks/useTransactions.ts +85 -0
  55. package/src/hooks/useWeb3.ts +70 -0
  56. package/src/index.ts +51 -0
  57. package/src/polyfills/index.simple.ts +22 -0
  58. package/src/polyfills/index.ts +16 -0
  59. package/src/providers/PersSDKProvider.tsx +274 -0
  60. package/src/providers/react-native-auth-provider.ts +332 -0
  61. package/src/providers/react-native-http-client.ts +129 -0
  62. package/src/types/external-modules.d.ts +13 -0
  63. package/src/types/react-native-globals.d.ts +46 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,3 @@
1
+ export declare const initializeReactNativePolyfills: () => boolean;
2
+ export declare const isReactNative: () => boolean;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/polyfills/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,8BAA8B,QAAO,OAGjD,CAAC;AAGF,eAAO,MAAM,aAAa,QAAO,OAEhC,CAAC"}
@@ -0,0 +1,13 @@
1
+ // Minimal React Native environment setup
2
+ // No polyfills needed - modules are disabled at Metro level
3
+ // Simple initialization function for compatibility
4
+ export const initializeReactNativePolyfills = () => {
5
+ console.log('✅ [PERS SDK] React Native environment ready (no polyfills needed)');
6
+ return true;
7
+ };
8
+ // Platform detection
9
+ export const isReactNative = () => {
10
+ return typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
11
+ };
12
+ // Auto-initialize
13
+ initializeReactNativePolyfills();
@@ -0,0 +1,2 @@
1
+ export declare const initializeReactNativePolyfills: () => boolean;
2
+ //# sourceMappingURL=index.simple.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.simple.d.ts","sourceRoot":"","sources":["../../src/polyfills/index.simple.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,8BAA8B,QAAO,OAGjD,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { Buffer } from 'buffer';
2
+ // Simple polyfills based on proven web project pattern
3
+ // Minimal setup that actually works
4
+ // Set up global environment
5
+ global.global = global;
6
+ global.Buffer = Buffer;
7
+ // Only add what's actually needed for React Native
8
+ if (typeof global !== 'undefined' && !global.process) {
9
+ global.process = { env: {} };
10
+ }
11
+ // Export initialization function for compatibility
12
+ export const initializeReactNativePolyfills = () => {
13
+ console.log('✅ [PERS SDK] Simple polyfills initialized');
14
+ return true;
15
+ };
16
+ // Auto-initialize
17
+ initializeReactNativePolyfills();
@@ -0,0 +1,29 @@
1
+ import React, { ReactNode } from 'react';
2
+ import { PersApiClient } from '@explorins/pers-sdk/core';
3
+ export interface PersSDKConfig {
4
+ apiProjectKey: string;
5
+ environment?: 'development' | 'staging' | 'production';
6
+ timeout?: number;
7
+ }
8
+ export interface PersSDKContext {
9
+ tokens: any | null;
10
+ transactions: any | null;
11
+ business: any | null;
12
+ campaigns: any | null;
13
+ redemptions: any | null;
14
+ web3: any | null;
15
+ apiClient: PersApiClient | null;
16
+ isInitialized: boolean;
17
+ isAuthenticated: boolean;
18
+ user: any | null;
19
+ accountAddress: string | null;
20
+ initialize: (config: PersSDKConfig) => Promise<void>;
21
+ login: (jwtToken: string, userType?: 'user' | 'admin') => Promise<any>;
22
+ loginWithRawData: (rawUserData: any) => Promise<any>;
23
+ logout: () => Promise<void>;
24
+ }
25
+ export declare const PersSDKProvider: React.FC<{
26
+ children: ReactNode;
27
+ }>;
28
+ export declare const usePersSDK: () => PersSDKContext;
29
+ //# sourceMappingURL=PersSDKProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PersSDKProvider.d.ts","sourceRoot":"","sources":["../../src/providers/PersSDKProvider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAkD,SAAS,EAAuB,MAAM,OAAO,CAAC;AAC9G,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAWzD,MAAM,WAAW,aAAa;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,YAAY,CAAC;IACvD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,cAAc;IAE7B,MAAM,EAAE,GAAG,GAAG,IAAI,CAAC;IACnB,YAAY,EAAE,GAAG,GAAG,IAAI,CAAC;IACzB,QAAQ,EAAE,GAAG,GAAG,IAAI,CAAC;IACrB,SAAS,EAAE,GAAG,GAAG,IAAI,CAAC;IACtB,WAAW,EAAE,GAAG,GAAG,IAAI,CAAC;IACxB,IAAI,EAAE,GAAG,GAAG,IAAI,CAAC;IACjB,SAAS,EAAE,aAAa,GAAG,IAAI,CAAC;IAGhC,aAAa,EAAE,OAAO,CAAC;IACvB,eAAe,EAAE,OAAO,CAAC;IACzB,IAAI,EAAE,GAAG,GAAG,IAAI,CAAC;IACjB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAG9B,UAAU,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACvE,gBAAgB,EAAE,CAAC,WAAW,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACrD,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AAiCD,eAAO,MAAM,eAAe,EAAE,KAAK,CAAC,EAAE,CAAC;IACrC,QAAQ,EAAE,SAAS,CAAC;CACrB,CA4LA,CAAC;AAGF,eAAO,MAAM,UAAU,QAAO,cAQ7B,CAAC"}
@@ -0,0 +1,194 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useState, useCallback, useRef } from 'react';
3
+ import { PersApiClient } from '@explorins/pers-sdk/core';
4
+ import { TokenSDK } from '@explorins/pers-sdk/token';
5
+ import { createTransactionSDK } from '@explorins/pers-sdk/transaction';
6
+ import { createBusinessSDK } from '@explorins/pers-sdk/business';
7
+ import { createCampaignSDK } from '@explorins/pers-sdk/campaign';
8
+ import { createRedemptionSDK } from '@explorins/pers-sdk/redemption';
9
+ import { createWeb3SDK } from '@explorins/pers-sdk/web3';
10
+ import { ReactNativeHttpClient } from './react-native-http-client';
11
+ import { BaseReactNativeAuthProvider } from './react-native-auth-provider';
12
+ // Create the context
13
+ const SDKContext = createContext(null);
14
+ // Custom auth provider for React Native
15
+ class ReactNativeSDKAuthProvider extends BaseReactNativeAuthProvider {
16
+ constructor(projectKey) {
17
+ super(projectKey);
18
+ this.projectKey = projectKey;
19
+ this.authType = 'user';
20
+ this._token = null;
21
+ }
22
+ async getToken() {
23
+ return this._token;
24
+ }
25
+ async setToken(token) {
26
+ this._token = token;
27
+ }
28
+ async getProjectKey() {
29
+ return this.projectKey;
30
+ }
31
+ async onTokenExpired() {
32
+ console.log('Token expired - clearing token');
33
+ this._token = null;
34
+ }
35
+ }
36
+ // Provider component
37
+ export const PersSDKProvider = ({ children }) => {
38
+ const initializingRef = useRef(false);
39
+ const [apiClient, setApiClient] = useState(null);
40
+ const [authProvider, setAuthProvider] = useState(null);
41
+ const [sdks, setSdks] = useState({
42
+ tokens: null,
43
+ transactions: null,
44
+ business: null,
45
+ campaigns: null,
46
+ redemptions: null,
47
+ web3: null,
48
+ });
49
+ const [isInitialized, setIsInitialized] = useState(false);
50
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
51
+ const [user, setUser] = useState(null);
52
+ const [accountAddress, setAccountAddress] = useState(null);
53
+ const initialize = useCallback(async (config) => {
54
+ // Prevent multiple initializations
55
+ if (isInitialized || initializingRef.current) {
56
+ console.log('⚠️ SDK already initialized or initializing, skipping...');
57
+ return;
58
+ }
59
+ initializingRef.current = true;
60
+ try {
61
+ console.log('🚀 Initializing PERS SDK with config:', config);
62
+ // Create auth provider
63
+ const auth = new ReactNativeSDKAuthProvider(config.apiProjectKey);
64
+ setAuthProvider(auth);
65
+ // Create HTTP client
66
+ const httpClient = new ReactNativeHttpClient();
67
+ // Create API client
68
+ const client = new PersApiClient(httpClient, {
69
+ apiProjectKey: config.apiProjectKey,
70
+ authProvider: auth,
71
+ environment: config.environment || 'development',
72
+ });
73
+ setApiClient(client);
74
+ // Initialize domain SDKs
75
+ const domainSDKs = {
76
+ tokens: new TokenSDK(client),
77
+ transactions: createTransactionSDK(client),
78
+ business: createBusinessSDK(client),
79
+ campaigns: createCampaignSDK(client),
80
+ redemptions: createRedemptionSDK(client),
81
+ web3: createWeb3SDK(client),
82
+ };
83
+ setSdks(domainSDKs);
84
+ setIsInitialized(true);
85
+ console.log('✅ PERS SDK initialized successfully');
86
+ }
87
+ catch (error) {
88
+ console.error('❌ Failed to initialize PERS SDK:', error);
89
+ initializingRef.current = false;
90
+ throw error;
91
+ }
92
+ finally {
93
+ initializingRef.current = false;
94
+ }
95
+ }, []);
96
+ const login = useCallback(async (jwtToken, userType = 'user') => {
97
+ if (!apiClient || !authProvider) {
98
+ throw new Error('SDK not initialized. Call initialize() first.');
99
+ }
100
+ try {
101
+ console.log(`🔐 Logging in as ${userType}...`);
102
+ // Set token in auth provider
103
+ await authProvider.setToken(jwtToken);
104
+ // Perform login with API client
105
+ const result = userType === 'admin'
106
+ ? await apiClient.loginAdmin(jwtToken)
107
+ : await apiClient.loginUser(jwtToken);
108
+ const userData = result.user || result.admin;
109
+ const userAccountAddress = userData?.accountAddress ||
110
+ userData?.wallets?.[0]?.address ||
111
+ null;
112
+ setUser(userData);
113
+ setAccountAddress(userAccountAddress);
114
+ setIsAuthenticated(true);
115
+ console.log('✅ Login successful');
116
+ return result;
117
+ }
118
+ catch (error) {
119
+ console.error('❌ Login failed:', error);
120
+ throw error;
121
+ }
122
+ }, [apiClient, authProvider]);
123
+ const loginWithRawData = useCallback(async (rawUserData) => {
124
+ if (!apiClient || !authProvider) {
125
+ throw new Error('SDK not initialized. Call initialize() first.');
126
+ }
127
+ try {
128
+ console.log('🔐 Logging in with raw user data...');
129
+ const result = await apiClient.loginUserWithRawData(rawUserData);
130
+ // Set token from result
131
+ if (result.accessToken) {
132
+ await authProvider.setToken(result.accessToken);
133
+ }
134
+ const userData = result.user;
135
+ const userAccountAddress = userData?.accountAddress ||
136
+ userData?.wallets?.[0]?.address ||
137
+ null;
138
+ setUser(userData);
139
+ setAccountAddress(userAccountAddress);
140
+ setIsAuthenticated(true);
141
+ console.log('✅ Raw data login successful');
142
+ return result;
143
+ }
144
+ catch (error) {
145
+ console.error('❌ Raw data login failed:', error);
146
+ throw error;
147
+ }
148
+ }, [apiClient, authProvider]);
149
+ const logout = useCallback(async () => {
150
+ try {
151
+ console.log('🔓 Logging out...');
152
+ if (authProvider) {
153
+ await authProvider.setToken(null);
154
+ }
155
+ setUser(null);
156
+ setAccountAddress(null);
157
+ setIsAuthenticated(false);
158
+ console.log('✅ Logout successful');
159
+ }
160
+ catch (error) {
161
+ console.error('❌ Logout failed:', error);
162
+ throw error;
163
+ }
164
+ }, [authProvider]);
165
+ const contextValue = {
166
+ // SDK instances
167
+ tokens: sdks.tokens,
168
+ transactions: sdks.transactions,
169
+ business: sdks.business,
170
+ campaigns: sdks.campaigns,
171
+ redemptions: sdks.redemptions,
172
+ web3: sdks.web3,
173
+ apiClient,
174
+ // State
175
+ isInitialized,
176
+ isAuthenticated,
177
+ user,
178
+ accountAddress,
179
+ // Methods
180
+ initialize,
181
+ login,
182
+ loginWithRawData,
183
+ logout,
184
+ };
185
+ return (_jsx(SDKContext.Provider, { value: contextValue, children: children }));
186
+ };
187
+ // Custom hook to use the SDK context
188
+ export const usePersSDK = () => {
189
+ const context = useContext(SDKContext);
190
+ if (!context) {
191
+ throw new Error('usePersSDK must be used within a PersSDKProvider');
192
+ }
193
+ return context;
194
+ };
@@ -0,0 +1,92 @@
1
+ import type { PersAuthProvider } from '@explorins/pers-sdk/core';
2
+ /**
3
+ * Storage strategy for different types of data
4
+ */
5
+ export declare enum StorageStrategy {
6
+ /** Use AsyncStorage for general app data */
7
+ ASYNC_STORAGE = "async_storage",
8
+ /** Use Keychain for sensitive tokens (when available) */
9
+ KEYCHAIN = "keychain",
10
+ /** Use in-memory storage (fallback) */
11
+ MEMORY = "memory"
12
+ }
13
+ /**
14
+ * Configuration options for React Native Auth Provider
15
+ */
16
+ export interface ReactNativeAuthConfig {
17
+ /** Storage strategy for access tokens */
18
+ accessTokenStrategy?: StorageStrategy;
19
+ /** Storage strategy for refresh tokens */
20
+ refreshTokenStrategy?: StorageStrategy;
21
+ /** Custom key prefix for storage */
22
+ keyPrefix?: string;
23
+ /** Enable debug logging */
24
+ debug?: boolean;
25
+ }
26
+ /**
27
+ * Base React Native Authentication Provider
28
+ *
29
+ * This serves as a blueprint for native implementations and can be extended
30
+ * by consuming applications to integrate with their specific auth systems.
31
+ *
32
+ * Features:
33
+ * - Multiple storage strategies (AsyncStorage, Keychain, Memory)
34
+ * - Configurable security levels per token type
35
+ * - Cross-platform compatibility (iOS/Android/Web)
36
+ * - Blueprint for native iOS/Android implementations
37
+ */
38
+ export declare abstract class BaseReactNativeAuthProvider implements PersAuthProvider {
39
+ abstract readonly authType: 'admin' | 'user';
40
+ abstract getProjectKey(): Promise<string | null>;
41
+ abstract onTokenExpired(): Promise<void>;
42
+ protected readonly config: Required<ReactNativeAuthConfig>;
43
+ protected readonly ACCESS_TOKEN_KEY: string;
44
+ protected readonly REFRESH_TOKEN_KEY: string;
45
+ protected readonly PROJECT_KEY_KEY: string;
46
+ private memoryStorage;
47
+ constructor(projectKey: string, config?: ReactNativeAuthConfig);
48
+ getToken(): Promise<string | null>;
49
+ setAccessToken(token: string): Promise<void>;
50
+ setRefreshToken(token: string): Promise<void>;
51
+ getRefreshToken(): Promise<string | null>;
52
+ clearTokens(): Promise<void>;
53
+ hasValidToken(): boolean;
54
+ hasRefreshToken(): boolean;
55
+ hasValidTokenAsync(): Promise<boolean>;
56
+ hasRefreshTokenAsync(): Promise<boolean>;
57
+ setToken(token: string): void;
58
+ clearToken(): void;
59
+ protected storeValue(key: string, value: string, strategy: StorageStrategy): Promise<void>;
60
+ protected getStoredValue(key: string, strategy: StorageStrategy): Promise<string | null>;
61
+ protected removeStoredValue(key: string, strategy: StorageStrategy): Promise<void>;
62
+ private isKeychainAvailable;
63
+ private storeInKeychain;
64
+ private getFromKeychain;
65
+ private removeFromKeychain;
66
+ }
67
+ /**
68
+ * React Native Authentication Provider
69
+ *
70
+ * A ready-to-use implementation for basic use cases.
71
+ * Uses AsyncStorage for access tokens and Keychain for refresh tokens (when available).
72
+ */
73
+ export declare class ReactNativeAuthProvider extends BaseReactNativeAuthProvider {
74
+ private projectKey;
75
+ readonly authType: 'user';
76
+ constructor(projectKey: string, config?: ReactNativeAuthConfig);
77
+ getProjectKey(): Promise<string | null>;
78
+ onTokenExpired(): Promise<void>;
79
+ }
80
+ /**
81
+ * Secure React Native Authentication Provider
82
+ *
83
+ * Maximum security implementation using Keychain for all sensitive data.
84
+ */
85
+ export declare class SecureReactNativeAuthProvider extends BaseReactNativeAuthProvider {
86
+ private projectKey;
87
+ readonly authType: 'user';
88
+ constructor(projectKey: string, config?: Omit<ReactNativeAuthConfig, 'accessTokenStrategy' | 'refreshTokenStrategy'>);
89
+ getProjectKey(): Promise<string | null>;
90
+ onTokenExpired(): Promise<void>;
91
+ }
92
+ //# sourceMappingURL=react-native-auth-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react-native-auth-provider.d.ts","sourceRoot":"","sources":["../../src/providers/react-native-auth-provider.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,268 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage';
2
+ /**
3
+ * Storage strategy for different types of data
4
+ */
5
+ export var StorageStrategy;
6
+ (function (StorageStrategy) {
7
+ /** Use AsyncStorage for general app data */
8
+ StorageStrategy["ASYNC_STORAGE"] = "async_storage";
9
+ /** Use Keychain for sensitive tokens (when available) */
10
+ StorageStrategy["KEYCHAIN"] = "keychain";
11
+ /** Use in-memory storage (fallback) */
12
+ StorageStrategy["MEMORY"] = "memory";
13
+ })(StorageStrategy || (StorageStrategy = {}));
14
+ /**
15
+ * Base React Native Authentication Provider
16
+ *
17
+ * This serves as a blueprint for native implementations and can be extended
18
+ * by consuming applications to integrate with their specific auth systems.
19
+ *
20
+ * Features:
21
+ * - Multiple storage strategies (AsyncStorage, Keychain, Memory)
22
+ * - Configurable security levels per token type
23
+ * - Cross-platform compatibility (iOS/Android/Web)
24
+ * - Blueprint for native iOS/Android implementations
25
+ */
26
+ export class BaseReactNativeAuthProvider {
27
+ constructor(projectKey, config = {}) {
28
+ // In-memory fallback storage
29
+ this.memoryStorage = new Map();
30
+ // Validate projectKey
31
+ if (!projectKey || typeof projectKey !== 'string') {
32
+ throw new Error('ReactNativeAuthProvider: projectKey is required and must be a string');
33
+ }
34
+ // Set default configuration
35
+ this.config = {
36
+ accessTokenStrategy: StorageStrategy.ASYNC_STORAGE,
37
+ refreshTokenStrategy: StorageStrategy.KEYCHAIN,
38
+ keyPrefix: `pers_${projectKey.slice(0, 8)}`,
39
+ debug: false,
40
+ ...config
41
+ };
42
+ // Create storage keys
43
+ this.ACCESS_TOKEN_KEY = `${this.config.keyPrefix}_access_token`;
44
+ this.REFRESH_TOKEN_KEY = `${this.config.keyPrefix}_refresh_token`;
45
+ this.PROJECT_KEY_KEY = `${this.config.keyPrefix}_project_key`;
46
+ if (this.config.debug) {
47
+ console.log('🔧 ReactNativeAuthProvider initialized with config:', this.config);
48
+ }
49
+ }
50
+ // Core token management methods
51
+ async getToken() {
52
+ return this.getStoredValue(this.ACCESS_TOKEN_KEY, this.config.accessTokenStrategy);
53
+ }
54
+ async setAccessToken(token) {
55
+ await this.storeValue(this.ACCESS_TOKEN_KEY, token, this.config.accessTokenStrategy);
56
+ if (this.config.debug) {
57
+ console.log('✅ Access token stored securely');
58
+ }
59
+ }
60
+ async setRefreshToken(token) {
61
+ await this.storeValue(this.REFRESH_TOKEN_KEY, token, this.config.refreshTokenStrategy);
62
+ if (this.config.debug) {
63
+ console.log('✅ Refresh token stored securely');
64
+ }
65
+ }
66
+ async getRefreshToken() {
67
+ return this.getStoredValue(this.REFRESH_TOKEN_KEY, this.config.refreshTokenStrategy);
68
+ }
69
+ async clearTokens() {
70
+ await Promise.all([
71
+ this.removeStoredValue(this.ACCESS_TOKEN_KEY, this.config.accessTokenStrategy),
72
+ this.removeStoredValue(this.REFRESH_TOKEN_KEY, this.config.refreshTokenStrategy)
73
+ ]);
74
+ if (this.config.debug) {
75
+ console.log('✅ All tokens cleared from storage');
76
+ }
77
+ }
78
+ // Token validation methods
79
+ hasValidToken() {
80
+ // Synchronous check - for async check use hasValidTokenAsync()
81
+ return true; // Actual validation happens in getToken()
82
+ }
83
+ hasRefreshToken() {
84
+ // Synchronous check - for async check use hasRefreshTokenAsync()
85
+ return true; // Actual validation happens in getRefreshToken()
86
+ }
87
+ // Async token validation methods
88
+ async hasValidTokenAsync() {
89
+ const token = await this.getToken();
90
+ return !!token;
91
+ }
92
+ async hasRefreshTokenAsync() {
93
+ const refreshToken = await this.getRefreshToken();
94
+ return !!refreshToken;
95
+ }
96
+ // Legacy methods for backward compatibility
97
+ setToken(token) {
98
+ this.setAccessToken(token).catch(error => {
99
+ console.error('Legacy setToken failed:', error);
100
+ });
101
+ }
102
+ clearToken() {
103
+ this.clearTokens().catch(error => {
104
+ console.error('Legacy clearToken failed:', error);
105
+ });
106
+ }
107
+ // Protected storage implementation methods
108
+ async storeValue(key, value, strategy) {
109
+ try {
110
+ switch (strategy) {
111
+ case StorageStrategy.KEYCHAIN:
112
+ // Try Keychain first, fallback to AsyncStorage
113
+ if (await this.isKeychainAvailable()) {
114
+ await this.storeInKeychain(key, value);
115
+ }
116
+ else {
117
+ await AsyncStorage.setItem(key, value);
118
+ }
119
+ break;
120
+ case StorageStrategy.ASYNC_STORAGE:
121
+ await AsyncStorage.setItem(key, value);
122
+ break;
123
+ case StorageStrategy.MEMORY:
124
+ default:
125
+ this.memoryStorage.set(key, value);
126
+ break;
127
+ }
128
+ }
129
+ catch (error) {
130
+ console.error(`Failed to store value with strategy ${strategy}:`, error);
131
+ // Fallback to memory storage
132
+ this.memoryStorage.set(key, value);
133
+ }
134
+ }
135
+ async getStoredValue(key, strategy) {
136
+ try {
137
+ switch (strategy) {
138
+ case StorageStrategy.KEYCHAIN:
139
+ // Try Keychain first, fallback to AsyncStorage
140
+ if (await this.isKeychainAvailable()) {
141
+ return await this.getFromKeychain(key);
142
+ }
143
+ else {
144
+ return await AsyncStorage.getItem(key);
145
+ }
146
+ case StorageStrategy.ASYNC_STORAGE:
147
+ return await AsyncStorage.getItem(key);
148
+ case StorageStrategy.MEMORY:
149
+ default:
150
+ return this.memoryStorage.get(key) || null;
151
+ }
152
+ }
153
+ catch (error) {
154
+ console.warn(`Failed to get value with strategy ${strategy}:`, error);
155
+ // Fallback to memory storage
156
+ return this.memoryStorage.get(key) || null;
157
+ }
158
+ }
159
+ async removeStoredValue(key, strategy) {
160
+ try {
161
+ switch (strategy) {
162
+ case StorageStrategy.KEYCHAIN:
163
+ // Try Keychain first, fallback to AsyncStorage
164
+ if (await this.isKeychainAvailable()) {
165
+ await this.removeFromKeychain(key);
166
+ }
167
+ else {
168
+ await AsyncStorage.removeItem(key);
169
+ }
170
+ break;
171
+ case StorageStrategy.ASYNC_STORAGE:
172
+ await AsyncStorage.removeItem(key);
173
+ break;
174
+ case StorageStrategy.MEMORY:
175
+ default:
176
+ this.memoryStorage.delete(key);
177
+ break;
178
+ }
179
+ }
180
+ catch (error) {
181
+ console.error(`Failed to remove value with strategy ${strategy}:`, error);
182
+ // Ensure memory fallback is also cleared
183
+ this.memoryStorage.delete(key);
184
+ }
185
+ }
186
+ // Keychain helper methods
187
+ async isKeychainAvailable() {
188
+ try {
189
+ // Check if react-native-keychain is available
190
+ const Keychain = require('react-native-keychain');
191
+ return !!Keychain && typeof Keychain.setInternetCredentials === 'function';
192
+ }
193
+ catch {
194
+ return false;
195
+ }
196
+ }
197
+ async storeInKeychain(key, value) {
198
+ const Keychain = require('react-native-keychain');
199
+ await Keychain.setInternetCredentials(key, 'pers-token', value);
200
+ }
201
+ async getFromKeychain(key) {
202
+ const Keychain = require('react-native-keychain');
203
+ const credentials = await Keychain.getInternetCredentials(key);
204
+ return credentials ? credentials.password : null;
205
+ }
206
+ async removeFromKeychain(key) {
207
+ const Keychain = require('react-native-keychain');
208
+ await Keychain.resetInternetCredentials(key);
209
+ }
210
+ }
211
+ /**
212
+ * React Native Authentication Provider
213
+ *
214
+ * A ready-to-use implementation for basic use cases.
215
+ * Uses AsyncStorage for access tokens and Keychain for refresh tokens (when available).
216
+ */
217
+ export class ReactNativeAuthProvider extends BaseReactNativeAuthProvider {
218
+ constructor(projectKey, config = {}) {
219
+ // Validate projectKey
220
+ if (!projectKey || typeof projectKey !== 'string') {
221
+ throw new Error('ReactNativeAuthProvider: projectKey is required and must be a string');
222
+ }
223
+ super(projectKey, {
224
+ accessTokenStrategy: StorageStrategy.ASYNC_STORAGE,
225
+ refreshTokenStrategy: StorageStrategy.KEYCHAIN,
226
+ debug: false,
227
+ ...config
228
+ });
229
+ this.projectKey = projectKey;
230
+ this.authType = 'user';
231
+ }
232
+ async getProjectKey() {
233
+ return this.projectKey;
234
+ }
235
+ async onTokenExpired() {
236
+ if (this.config.debug) {
237
+ console.warn('ReactNativeAuthProvider: Token expired - no refresh logic implemented');
238
+ }
239
+ }
240
+ }
241
+ /**
242
+ * Secure React Native Authentication Provider
243
+ *
244
+ * Maximum security implementation using Keychain for all sensitive data.
245
+ */
246
+ export class SecureReactNativeAuthProvider extends BaseReactNativeAuthProvider {
247
+ constructor(projectKey, config = {}) {
248
+ // Validate projectKey
249
+ if (!projectKey || typeof projectKey !== 'string') {
250
+ throw new Error('SecureReactNativeAuthProvider: projectKey is required and must be a string');
251
+ }
252
+ super(projectKey, {
253
+ ...config,
254
+ accessTokenStrategy: StorageStrategy.KEYCHAIN,
255
+ refreshTokenStrategy: StorageStrategy.KEYCHAIN,
256
+ });
257
+ this.projectKey = projectKey;
258
+ this.authType = 'user';
259
+ }
260
+ async getProjectKey() {
261
+ return this.projectKey;
262
+ }
263
+ async onTokenExpired() {
264
+ if (this.config.debug) {
265
+ console.warn('SecureReactNativeAuthProvider: Token expired - implement refresh logic');
266
+ }
267
+ }
268
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * HTTP Client implementation for React Native
3
+ *
4
+ * This implementation properly implements the core SDK's HttpClient interface
5
+ * and uses fetch API which is available in React Native.
6
+ */
7
+ export interface RequestOptions {
8
+ headers?: Record<string, string>;
9
+ params?: Record<string, string>;
10
+ timeout?: number;
11
+ responseType?: 'json' | 'blob' | 'text' | 'arraybuffer';
12
+ }
13
+ export interface HttpClient {
14
+ get<T>(url: string, options?: RequestOptions): Promise<T>;
15
+ post<T>(url: string, body: any, options?: RequestOptions): Promise<T>;
16
+ put<T>(url: string, body: any, options?: RequestOptions): Promise<T>;
17
+ delete<T>(url: string, options?: RequestOptions): Promise<T>;
18
+ }
19
+ export declare class ReactNativeHttpClient implements HttpClient {
20
+ private baseURL?;
21
+ constructor(baseURL?: string);
22
+ get<T = any>(url: string, options?: RequestOptions): Promise<T>;
23
+ post<T = any>(url: string, body?: any, options?: RequestOptions): Promise<T>;
24
+ put<T = any>(url: string, body?: any, options?: RequestOptions): Promise<T>;
25
+ delete<T = any>(url: string, options?: RequestOptions): Promise<T>;
26
+ private request;
27
+ private buildUrl;
28
+ }
29
+ //# sourceMappingURL=react-native-http-client.d.ts.map