-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathApp.tsx
More file actions
268 lines (226 loc) · 9.35 KB
/
App.tsx
File metadata and controls
268 lines (226 loc) · 9.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useRef } from 'react';
import { Alert, AppState, AppStateStatus, LogBox } from 'react-native';
import StorybookUI from './.rnstorybook';
import './global.css';
import * as Font from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';
import { ErrorBoundary } from './src/components/common/ErrorBoundary';
import { initializeLogging } from './src/config/logging';
import { AuthProvider, useAdaptiveTheme, useReviewMetrics } from './src/hooks';
import AppNavigator from './src/navigation/AppNavigator';
import { setupNotificationNavigation } from './src/navigation/linking';
import { apiClient } from './src/services/api';
import { crashReportingService } from './src/services/cashReporting';
import { featureCapabilities } from './src/services/featureCapabilities';
import { inAppReviewService } from './src/services/inAppReview';
import { mobileAuthService } from './src/services/mobileAuth';
import {
addNotificationReceivedListener,
getLastNotificationResponse,
removeNotificationListener,
registerForPushNotifications, // Added missing native push helpers
registerTokenWithBackend,
} from './src/services/pushNotifications';
import { requestQueue } from './src/services/requestQueue';
import socketService from './src/services/socket';
import { syncService } from './src/services/syncService'; // Fixed naming convention from the merge conflict
import { useAppStore, useNotificationStore } from './src/store'; // Added missing store imports
import { useDegradationStore } from './src/store/degradationStore';
import { handleCacheVersionUpdate } from './src/utils/cacheVersioning';
import { requireEnvVariables } from './src/utils/env';
import { appLogger } from './src/utils/logger';
import { handleNotificationReceived } from './src/utils/notificationHandlers';
import { initializeSecureStorage } from './src/services/secureStorage'; // Added missing storage helper mock path
// Keep the splash screen visible while we fetch resources
SplashScreen.preventAutoHideAsync();
// SHOW_STORYBOOK flag based on environment variable
const SHOW_STORYBOOK = process.env.EXPO_PUBLIC_STORYBOOK === 'true';
// Centralized structured logging initialized on startup
requireEnvVariables();
// Initialize centralized logging on app start
initializeLogging().catch(err => {
console.error('[App] Failed to initialize logging:', err);
});
if (__DEV__) {
appLogger.infoSync('Development mode: centralized logger active');
LogBox.ignoreLogs(['Non-serializable values were found in the navigation state']);
} else {
// Strip all logs except errors in production for performance
console.log = () => {};
console.info = () => {};
console.warn = () => {};
console.debug = () => {};
}
const App = () => {
const theme = useAppStore((state) => state.theme);
useAdaptiveTheme();
// Using imported hook from the merge logic if needed downstream
useReviewMetrics();
const appStateRef = useRef<AppStateStatus>(AppState.currentState);
const [appIsReady, setAppIsReady] = React.useState(false);
useEffect(() => {
async function prepareApp() {
try {
// 1. Load fonts
await Font.loadAsync({
// You can add custom fonts here later if needed
});
// 2. Version-based cache invalidation: clear stale caches on app/data version bump
const appVersion = require('./package.json').version as string;
await handleCacheVersionUpdate(appVersion);
// 3. Initial data fetch (simulate or add real fetch)
await new Promise(resolve => setTimeout(resolve, 500));
} catch (e) {
console.warn('Error during app initialization:', e);
} finally {
setAppIsReady(true);
await SplashScreen.hideAsync();
}
}
prepareApp();
}, []);
const SESSION_REFRESH_WINDOW_MS = 5 * 60 * 1000;
useEffect(() => {
// Initialize crash reporting at app startup
crashReportingService.init();
// Initialize secure storage (Keychain/Keystore) for encrypted token storage
initializeSecureStorage().catch((error) => {
appLogger.errorSync('Failed to initialize secure storage:', error); // Fixed 'logger.error' to 'appLogger.errorSync'
});
// Add global handler for unhandled promise rejections
const unhandledRejectionHandler = (reason: any) => {
const error = reason instanceof Error ? reason : new Error(String(reason));
appLogger.errorSync('Unhandled Promise Rejection', error);
crashReportingService.reportError(error, 'UnhandledPromiseRejection');
};
// Register unhandled rejection listener
if (global.onunhandledrejection === undefined) {
// @ts-ignore - Setting global error handler
global.onunhandledrejection = unhandledRejectionHandler;
}
// Connect to socket when app starts
socketService.connect();
// Initialize feature capability detection (non-blocking)
featureCapabilities.checkAllCapabilities()
.then(capabilities => {
const degradationStore = useDegradationStore.getState();
appLogger.infoSync('[App] Feature capabilities checked', {
camera: capabilities.camera.status,
notifications: capabilities.pushNotifications.status,
location: capabilities.location.status,
});
// Update degradation store with current feature statuses
Object.entries(capabilities).forEach(([feature, info]) => {
if (feature !== 'checkedAt' && 'status' in info) {
degradationStore.setFeatureStatus(feature as any, info.status);
}
});
})
.catch(error => {
appLogger.errorSync('[App] Error checking feature capabilities', error instanceof Error ? error : new Error(String(error)));
});
// Initialize push notifications: request permissions and get device token
registerForPushNotifications().then(async (token) => {
if (token) {
const { setPushToken, setTokenRegistered } = useNotificationStore.getState();
setPushToken(token);
const registered = await registerTokenWithBackend(token);
setTokenRegistered(registered);
}
});
// Start request queue monitoring
requestQueue.startMonitoring(apiClient);
// Initialize and start sync service for background sync
syncService.startAutoSync();
// Initialize In-App Review metrics if applicable
inAppReviewService.init?.();
// Set up notification navigation handler
const notificationCleanup = setupNotificationNavigation();
// Listen for notifications received while app is foregrounded
const subscription = addNotificationReceivedListener(handleNotificationReceived);
// Check if app was launched from a notification
getLastNotificationResponse().then(response => {
if (response) {
appLogger.infoSync('App launched from notification', { response });
}
});
// Cleanup on unmount
return () => {
socketService.disconnect();
syncService.stopAutoSync();
notificationCleanup();
removeNotificationListener(subscription);
// Clean up the unhandled rejection handler
// @ts-ignore
global.onunhandledrejection = undefined;
};
}, []);
useEffect(() => {
const checkSessionOnForeground = async () => {
const {
isAuthenticated,
refreshToken,
sessionExpiresAt,
setUser,
setTokens,
setSessionExpiringSoon,
logout,
} = useAppStore.getState();
if (!isAuthenticated || !refreshToken || !sessionExpiresAt) {
return;
}
const now = Date.now();
const msUntilExpiry = sessionExpiresAt - now;
if (msUntilExpiry <= 0) {
logout();
Alert.alert('Session expired', 'Your session has expired. Please log in again.');
return;
}
if (msUntilExpiry <= SESSION_REFRESH_WINDOW_MS) {
setSessionExpiringSoon(true);
Alert.alert('Session expiring soon', 'Refreshing your session to keep you signed in.');
try {
const refreshedSession = await mobileAuthService.refreshSession();
setUser(refreshedSession.user);
setTokens(
refreshedSession.tokens.accessToken,
refreshedSession.tokens.refreshToken,
refreshedSession.tokens.expiresAt
);
setSessionExpiringSoon(false);
} catch (error) {
appLogger.errorSync('Failed to refresh session on app foreground', error as Error);
logout();
Alert.alert('Session expired', 'We could not refresh your session. Please log in again.');
}
} else {
setSessionExpiringSoon(false);
}
};
checkSessionOnForeground();
const appStateSubscription = AppState.addEventListener('change', nextAppState => {
const wasInBackground = appStateRef.current.match(/inactive|background/);
const isForegrounded = nextAppState === 'active';
if (wasInBackground && isForegrounded) {
void checkSessionOnForeground();
}
appStateRef.current = nextAppState;
});
return () => {
appStateSubscription.remove();
};
}, [SESSION_REFRESH_WINDOW_MS]);
if (!appIsReady) {
return null;
}
return (
<ErrorBoundary>
<AuthProvider>
<StatusBar style={theme === 'dark' ? 'light' : 'dark'} />
<AppNavigator />
</AuthProvider>
</ErrorBoundary>
);
};
export default SHOW_STORYBOOK ? StorybookUI : App;