@pubflow/react-native
Version:
React Native adapter for Pubflow framework
307 lines (306 loc) • 14.2 kB
JavaScript
/**
* Pubflow Provider for React Native
*
* Provides a context provider for Pubflow in React Native applications
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.PubflowContext = void 0;
exports.PubflowProvider = PubflowProvider;
const react_1 = __importStar(require("react"));
const react_native_1 = require("react-native");
const swr_1 = require("swr");
const core_1 = require("@pubflow/core");
const secureStorage_1 = require("../storage/secureStorage");
const debugConfig_1 = require("./debugConfig");
/**
* Create Pubflow context
*/
exports.PubflowContext = (0, react_1.createContext)({
instances: {},
defaultInstance: 'default'
});
/**
* Pubflow provider for React Native
*/
function PubflowProvider({ children, config, instances, defaultInstance = 'default', onSessionExpired, onSessionRefreshed, showSessionAlerts = false, persistentCache = { enabled: false }, enableDebugTools = false }) {
const [isInitialized, setIsInitialized] = (0, react_1.useState)(false);
const [contextValue, setContextValue] = (0, react_1.useState)({
instances: {},
defaultInstance
});
// Configure debug tools
(0, react_1.useEffect)(() => {
(0, debugConfig_1.setDebugConfig)({ enabled: enableDebugTools });
if (enableDebugTools) {
console.log('Pubflow debug tools enabled');
}
}, [enableDebugTools]);
// Handle session expiration
const handleSessionExpired = (0, react_1.useCallback)(() => {
if (showSessionAlerts) {
react_native_1.Alert.alert('Session Expired', 'Your session has expired. Please log in again.', [{ text: 'OK' }]);
}
if (onSessionExpired) {
onSessionExpired();
}
}, [onSessionExpired, showSessionAlerts]);
// Handle session refresh
const handleSessionRefreshed = (0, react_1.useCallback)(() => {
if (showSessionAlerts) {
react_native_1.Alert.alert('Session Refreshed', 'Your session has been refreshed.', [{ text: 'OK' }]);
}
if (onSessionRefreshed) {
onSessionRefreshed();
}
}, [onSessionRefreshed, showSessionAlerts]);
(0, react_1.useEffect)(() => {
const initialize = async () => {
var _a, _b;
try {
// Initialize instances
const instancesMap = {};
if (instances && instances.length > 0) {
// Initialize multiple instances
for (const instanceConfig of instances) {
// Initialize configuration
const fullConfig = (0, core_1.initConfig)({
...instanceConfig,
sessionConfig: {
...instanceConfig.sessionConfig,
onSessionExpired: handleSessionExpired,
onSessionRefreshed: handleSessionRefreshed
}
}, instanceConfig.id);
// Create storage adapter
const storage = new secureStorage_1.SecureStorageAdapter({
prefix: (_a = fullConfig.storageConfig) === null || _a === void 0 ? void 0 : _a.prefix,
useSecureStorage: fullConfig.useSecureStorage
});
// Create API client
const apiClient = new core_1.ApiClient(fullConfig, storage);
// Create auth service
const authService = new core_1.AuthService(apiClient, storage, fullConfig);
// Get current user
let user = null;
let isAuthenticated = false;
try {
user = await authService.getCurrentUser();
isAuthenticated = !!user;
}
catch (error) {
console.error(`Error getting current user for instance ${instanceConfig.id}:`, error);
}
// Create instance
instancesMap[instanceConfig.id] = {
config: fullConfig,
apiClient,
authService,
user,
isAuthenticated,
isLoading: false,
login: async (credentials) => {
const result = await authService.login(credentials);
if (result.success && result.user) {
// Update instance
setContextValue(prev => ({
...prev,
instances: {
...prev.instances,
[instanceConfig.id]: {
...prev.instances[instanceConfig.id],
user: result.user,
isAuthenticated: true
}
}
}));
}
return result;
},
logout: async () => {
await authService.logout();
// Update instance
setContextValue(prev => ({
...prev,
instances: {
...prev.instances,
[instanceConfig.id]: {
...prev.instances[instanceConfig.id],
user: null,
isAuthenticated: false
}
}
}));
},
validateSession: async () => {
const result = await authService.validateSession();
// Update instance
setContextValue(prev => ({
...prev,
instances: {
...prev.instances,
[instanceConfig.id]: {
...prev.instances[instanceConfig.id],
user: result.user || null,
isAuthenticated: result.isValid
}
}
}));
return result;
}
};
}
}
else if (config) {
// Initialize single instance
// Initialize configuration
const fullConfig = (0, core_1.initConfig)({
...config,
sessionConfig: {
...config.sessionConfig,
onSessionExpired: handleSessionExpired,
onSessionRefreshed: handleSessionRefreshed
}
}, defaultInstance);
// Create storage adapter
const storage = new secureStorage_1.SecureStorageAdapter({
prefix: (_b = fullConfig.storageConfig) === null || _b === void 0 ? void 0 : _b.prefix,
useSecureStorage: fullConfig.useSecureStorage
});
// Create API client
const apiClient = new core_1.ApiClient(fullConfig, storage);
// Create auth service
const authService = new core_1.AuthService(apiClient, storage, fullConfig);
// Get current user
let user = null;
let isAuthenticated = false;
try {
user = await authService.getCurrentUser();
isAuthenticated = !!user;
}
catch (error) {
console.error('Error getting current user:', error);
}
// Create instance
instancesMap[defaultInstance] = {
config: fullConfig,
apiClient,
authService,
user,
isAuthenticated,
isLoading: false,
login: async (credentials) => {
const result = await authService.login(credentials);
if (result.success && result.user) {
// Update instance
setContextValue(prev => ({
...prev,
instances: {
...prev.instances,
[defaultInstance]: {
...prev.instances[defaultInstance],
user: result.user,
isAuthenticated: true
}
}
}));
}
return result;
},
logout: async () => {
await authService.logout();
// Update instance
setContextValue(prev => ({
...prev,
instances: {
...prev.instances,
[defaultInstance]: {
...prev.instances[defaultInstance],
user: null,
isAuthenticated: false
}
}
}));
},
validateSession: async () => {
const result = await authService.validateSession();
// Update instance
setContextValue(prev => ({
...prev,
instances: {
...prev.instances,
[defaultInstance]: {
...prev.instances[defaultInstance],
user: result.user || null,
isAuthenticated: result.isValid
}
}
}));
return result;
}
};
}
// Set context value
setContextValue({
instances: instancesMap,
defaultInstance
});
// Set initialized
setIsInitialized(true);
}
catch (error) {
console.error('Error initializing Pubflow:', error);
}
};
initialize();
}, [config, instances, defaultInstance, handleSessionExpired, handleSessionRefreshed]);
// Show loading state
if (!isInitialized) {
return null;
}
// If persistent cache is enabled, wrap with SWRConfig
if (persistentCache.enabled && persistentCache.provider) {
return (<swr_1.SWRConfig value={{ provider: persistentCache.provider }}>
<exports.PubflowContext.Provider value={contextValue}>
{children}
</exports.PubflowContext.Provider>
</swr_1.SWRConfig>);
}
// Otherwise, just use the regular provider
return (<exports.PubflowContext.Provider value={contextValue}>
{children}
</exports.PubflowContext.Provider>);
}
;