@croacroa/react-native-template 1.0.0 → 2.0.1

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 (70) hide show
  1. package/.github/workflows/ci.yml +187 -184
  2. package/.github/workflows/eas-build.yml +55 -55
  3. package/.github/workflows/eas-update.yml +50 -50
  4. package/CHANGELOG.md +106 -106
  5. package/CONTRIBUTING.md +377 -377
  6. package/README.md +399 -399
  7. package/__tests__/components/snapshots.test.tsx +131 -0
  8. package/__tests__/integration/auth-api.test.tsx +227 -0
  9. package/__tests__/performance/VirtualizedList.perf.test.tsx +362 -0
  10. package/app/(public)/onboarding.tsx +5 -5
  11. package/app.config.ts +45 -2
  12. package/assets/images/.gitkeep +7 -7
  13. package/components/onboarding/OnboardingScreen.tsx +370 -370
  14. package/components/onboarding/index.ts +2 -2
  15. package/components/providers/SuspenseBoundary.tsx +357 -0
  16. package/components/providers/index.ts +21 -0
  17. package/components/ui/Avatar.tsx +316 -316
  18. package/components/ui/Badge.tsx +416 -416
  19. package/components/ui/BottomSheet.tsx +307 -307
  20. package/components/ui/Checkbox.tsx +261 -261
  21. package/components/ui/OptimizedImage.tsx +369 -369
  22. package/components/ui/Select.tsx +240 -240
  23. package/components/ui/VirtualizedList.tsx +285 -0
  24. package/components/ui/index.ts +23 -18
  25. package/constants/config.ts +97 -54
  26. package/docs/adr/001-state-management.md +79 -79
  27. package/docs/adr/002-styling-approach.md +130 -130
  28. package/docs/adr/003-data-fetching.md +155 -155
  29. package/docs/adr/004-auth-adapter-pattern.md +144 -144
  30. package/docs/adr/README.md +78 -78
  31. package/hooks/index.ts +27 -25
  32. package/hooks/useApi.ts +102 -5
  33. package/hooks/useAuth.tsx +82 -0
  34. package/hooks/useBiometrics.ts +295 -295
  35. package/hooks/useDeepLinking.ts +256 -256
  36. package/hooks/useMFA.ts +499 -0
  37. package/hooks/useNotifications.ts +39 -0
  38. package/hooks/useOffline.ts +60 -6
  39. package/hooks/usePerformance.ts +434 -434
  40. package/hooks/useTheme.tsx +76 -0
  41. package/hooks/useUpdates.ts +358 -358
  42. package/i18n/index.ts +194 -77
  43. package/i18n/locales/ar.json +101 -0
  44. package/i18n/locales/de.json +101 -0
  45. package/i18n/locales/en.json +101 -101
  46. package/i18n/locales/es.json +101 -0
  47. package/i18n/locales/fr.json +101 -101
  48. package/jest.config.js +4 -4
  49. package/maestro/README.md +113 -113
  50. package/maestro/config.yaml +35 -35
  51. package/maestro/flows/login.yaml +62 -62
  52. package/maestro/flows/mfa-login.yaml +92 -0
  53. package/maestro/flows/mfa-setup.yaml +86 -0
  54. package/maestro/flows/navigation.yaml +68 -68
  55. package/maestro/flows/offline-conflict.yaml +101 -0
  56. package/maestro/flows/offline-sync.yaml +128 -0
  57. package/maestro/flows/offline.yaml +60 -60
  58. package/maestro/flows/register.yaml +94 -94
  59. package/package.json +175 -170
  60. package/services/analytics.ts +428 -428
  61. package/services/api.ts +340 -340
  62. package/services/authAdapter.ts +333 -333
  63. package/services/backgroundSync.ts +626 -0
  64. package/services/index.ts +54 -22
  65. package/services/security.ts +286 -0
  66. package/tailwind.config.js +47 -47
  67. package/utils/accessibility.ts +446 -446
  68. package/utils/index.ts +52 -43
  69. package/utils/validation.ts +2 -1
  70. package/utils/withAccessibility.tsx +272 -0
package/services/api.ts CHANGED
@@ -1,340 +1,340 @@
1
- import * as SecureStore from "expo-secure-store";
2
- import { router } from "expo-router";
3
- import Bottleneck from "bottleneck";
4
- import { API_URL } from "@/constants/config";
5
- import { toast } from "@/utils/toast";
6
- import type { AuthTokens } from "@/types";
7
-
8
- type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
9
-
10
- // ============================================================================
11
- // Rate Limiting Configuration
12
- // ============================================================================
13
-
14
- /**
15
- * Rate limiter to prevent API abuse and handle rate limiting gracefully
16
- * - maxConcurrent: Maximum concurrent requests
17
- * - minTime: Minimum time between requests (ms)
18
- * - reservoir: Number of requests allowed in the reservoir
19
- * - reservoirRefreshAmount: How many requests to add on refresh
20
- * - reservoirRefreshInterval: How often to refresh the reservoir (ms)
21
- */
22
- const limiter = new Bottleneck({
23
- maxConcurrent: 5, // Max 5 concurrent requests
24
- minTime: 100, // At least 100ms between requests
25
- reservoir: 50, // 50 requests per interval
26
- reservoirRefreshAmount: 50,
27
- reservoirRefreshInterval: 60 * 1000, // Refresh every minute
28
- });
29
-
30
- // Track rate limit errors
31
- let rateLimitRetryAfter = 0;
32
-
33
- limiter.on("failed", async (error, _jobInfo) => {
34
- // If we hit a rate limit, wait and retry
35
- if (error instanceof Error && error.message.includes("429")) {
36
- const retryAfter = rateLimitRetryAfter || 1000;
37
- console.warn(`Rate limited, retrying in ${retryAfter}ms`);
38
- return retryAfter;
39
- }
40
- return null;
41
- });
42
-
43
- limiter.on("retry", (error, jobInfo) => {
44
- console.log(`Retrying request (attempt ${jobInfo.retryCount + 1})`);
45
- });
46
-
47
- interface RequestOptions {
48
- method?: RequestMethod;
49
- body?: Record<string, unknown>;
50
- headers?: Record<string, string>;
51
- requiresAuth?: boolean;
52
- skipRefresh?: boolean;
53
- }
54
-
55
- interface ApiError extends Error {
56
- status: number;
57
- data?: unknown;
58
- }
59
-
60
- const TOKEN_KEY = "auth_tokens";
61
- const TOKEN_REFRESH_THRESHOLD = 5 * 60 * 1000;
62
-
63
- // Track if we're currently refreshing to prevent multiple refresh calls
64
- let isRefreshing = false;
65
- let refreshPromise: Promise<string | null> | null = null;
66
-
67
- /**
68
- * Get current auth tokens from secure storage
69
- */
70
- async function getTokens(): Promise<AuthTokens | null> {
71
- try {
72
- const stored = await SecureStore.getItemAsync(TOKEN_KEY);
73
- return stored ? JSON.parse(stored) : null;
74
- } catch {
75
- return null;
76
- }
77
- }
78
-
79
- /**
80
- * Save new tokens to secure storage
81
- */
82
- async function saveTokens(tokens: AuthTokens): Promise<void> {
83
- await SecureStore.setItemAsync(TOKEN_KEY, JSON.stringify(tokens));
84
- }
85
-
86
- /**
87
- * Clear tokens and redirect to login
88
- */
89
- async function handleAuthFailure(): Promise<void> {
90
- await SecureStore.deleteItemAsync(TOKEN_KEY);
91
- await SecureStore.deleteItemAsync("auth_user");
92
- toast.error("Session expired", "Please sign in again");
93
- router.replace("/(public)/login");
94
- }
95
-
96
- /**
97
- * Refresh the access token using the refresh token
98
- */
99
- async function refreshAccessToken(): Promise<string | null> {
100
- // If already refreshing, wait for that request
101
- if (isRefreshing && refreshPromise) {
102
- return refreshPromise;
103
- }
104
-
105
- isRefreshing = true;
106
- refreshPromise = (async () => {
107
- try {
108
- const tokens = await getTokens();
109
- if (!tokens?.refreshToken) {
110
- throw new Error("No refresh token");
111
- }
112
-
113
- // TODO: Replace with your actual refresh endpoint
114
- const response = await fetch(`${API_URL}/auth/refresh`, {
115
- method: "POST",
116
- headers: { "Content-Type": "application/json" },
117
- body: JSON.stringify({ refreshToken: tokens.refreshToken }),
118
- });
119
-
120
- if (!response.ok) {
121
- throw new Error("Refresh failed");
122
- }
123
-
124
- const data = await response.json();
125
- const newTokens: AuthTokens = {
126
- accessToken: data.accessToken,
127
- refreshToken: data.refreshToken || tokens.refreshToken,
128
- expiresAt: Date.now() + (data.expiresIn || 3600) * 1000,
129
- };
130
-
131
- await saveTokens(newTokens);
132
- return newTokens.accessToken;
133
- } catch (error) {
134
- console.error("Token refresh failed:", error);
135
- await handleAuthFailure();
136
- return null;
137
- } finally {
138
- isRefreshing = false;
139
- refreshPromise = null;
140
- }
141
- })();
142
-
143
- return refreshPromise;
144
- }
145
-
146
- /**
147
- * Get a valid access token, refreshing if necessary
148
- */
149
- async function getValidAccessToken(): Promise<string | null> {
150
- const tokens = await getTokens();
151
- if (!tokens) return null;
152
-
153
- // Check if token needs refresh
154
- const timeUntilExpiry = tokens.expiresAt - Date.now();
155
- if (timeUntilExpiry < TOKEN_REFRESH_THRESHOLD) {
156
- return refreshAccessToken();
157
- }
158
-
159
- return tokens.accessToken;
160
- }
161
-
162
- class ApiClient {
163
- private baseUrl: string;
164
- private defaultTimeout: number;
165
- private enableRateLimiting: boolean;
166
-
167
- constructor(baseUrl: string, timeout = 30000, enableRateLimiting = true) {
168
- this.baseUrl = baseUrl;
169
- this.defaultTimeout = timeout;
170
- this.enableRateLimiting = enableRateLimiting;
171
- }
172
-
173
- /**
174
- * Execute a request with rate limiting
175
- */
176
- private async executeWithRateLimiting<T>(fn: () => Promise<T>): Promise<T> {
177
- if (!this.enableRateLimiting) {
178
- return fn();
179
- }
180
- return limiter.schedule(fn);
181
- }
182
-
183
- private async request<T>(
184
- endpoint: string,
185
- options: RequestOptions = {}
186
- ): Promise<T> {
187
- const {
188
- method = "GET",
189
- body,
190
- headers = {},
191
- requiresAuth = true,
192
- skipRefresh = false,
193
- } = options;
194
-
195
- const requestHeaders: Record<string, string> = {
196
- "Content-Type": "application/json",
197
- ...headers,
198
- };
199
-
200
- // Add auth token if required
201
- if (requiresAuth) {
202
- const token = await getValidAccessToken();
203
- if (token) {
204
- requestHeaders.Authorization = `Bearer ${token}`;
205
- }
206
- }
207
-
208
- // Setup abort controller for timeout
209
- const controller = new AbortController();
210
- const timeoutId = setTimeout(() => controller.abort(), this.defaultTimeout);
211
-
212
- try {
213
- const config: RequestInit = {
214
- method,
215
- headers: requestHeaders,
216
- signal: controller.signal,
217
- };
218
-
219
- if (body && method !== "GET") {
220
- config.body = JSON.stringify(body);
221
- }
222
-
223
- const response = await this.executeWithRateLimiting(() =>
224
- fetch(`${this.baseUrl}${endpoint}`, config)
225
- );
226
-
227
- // Handle 401 - try refresh once
228
- if (response.status === 401 && requiresAuth && !skipRefresh) {
229
- const newToken = await refreshAccessToken();
230
- if (newToken) {
231
- // Retry the request with new token
232
- return this.request(endpoint, { ...options, skipRefresh: true });
233
- }
234
- throw new Error("Authentication failed");
235
- }
236
-
237
- // Handle rate limiting (429)
238
- if (response.status === 429) {
239
- const retryAfter = response.headers.get("Retry-After");
240
- rateLimitRetryAfter = retryAfter
241
- ? parseInt(retryAfter, 10) * 1000
242
- : 1000;
243
- const error = new Error("Rate limited - too many requests") as ApiError;
244
- error.status = 429;
245
- throw error;
246
- }
247
-
248
- // Handle other errors
249
- if (!response.ok) {
250
- const error = new Error(
251
- `API Error: ${response.status} ${response.statusText}`
252
- ) as ApiError;
253
- error.status = response.status;
254
- try {
255
- error.data = await response.json();
256
- } catch {
257
- // Response body is not JSON
258
- }
259
- throw error;
260
- }
261
-
262
- // Handle empty responses
263
- const text = await response.text();
264
- if (!text) {
265
- return {} as T;
266
- }
267
-
268
- return JSON.parse(text);
269
- } catch (error) {
270
- if (error instanceof Error) {
271
- // Handle abort (timeout)
272
- if (error.name === "AbortError") {
273
- const timeoutError = new Error("Request timeout") as ApiError;
274
- timeoutError.status = 408;
275
- throw timeoutError;
276
- }
277
-
278
- // Handle network errors
279
- if (
280
- error.message.includes("Network") ||
281
- error.message.includes("fetch")
282
- ) {
283
- const networkError = new Error("Network error") as ApiError;
284
- networkError.status = 0;
285
- throw networkError;
286
- }
287
- }
288
- throw error;
289
- } finally {
290
- clearTimeout(timeoutId);
291
- }
292
- }
293
-
294
- async get<T>(
295
- endpoint: string,
296
- options?: Omit<RequestOptions, "method" | "body">
297
- ) {
298
- return this.request<T>(endpoint, { ...options, method: "GET" });
299
- }
300
-
301
- async post<T>(
302
- endpoint: string,
303
- body?: Record<string, unknown>,
304
- options?: Omit<RequestOptions, "method">
305
- ) {
306
- return this.request<T>(endpoint, { ...options, method: "POST", body });
307
- }
308
-
309
- async put<T>(
310
- endpoint: string,
311
- body?: Record<string, unknown>,
312
- options?: Omit<RequestOptions, "method">
313
- ) {
314
- return this.request<T>(endpoint, { ...options, method: "PUT", body });
315
- }
316
-
317
- async patch<T>(
318
- endpoint: string,
319
- body?: Record<string, unknown>,
320
- options?: Omit<RequestOptions, "method">
321
- ) {
322
- return this.request<T>(endpoint, { ...options, method: "PATCH", body });
323
- }
324
-
325
- async delete<T>(
326
- endpoint: string,
327
- options?: Omit<RequestOptions, "method" | "body">
328
- ) {
329
- return this.request<T>(endpoint, { ...options, method: "DELETE" });
330
- }
331
- }
332
-
333
- // Export singleton instance
334
- export const api = new ApiClient(API_URL);
335
-
336
- // Export class for testing or creating additional instances
337
- export { ApiClient };
338
-
339
- // Export token utilities for auth hook
340
- export { getTokens, saveTokens, getValidAccessToken };
1
+ import * as SecureStore from "expo-secure-store";
2
+ import { router } from "expo-router";
3
+ import Bottleneck from "bottleneck";
4
+ import { API_URL } from "@/constants/config";
5
+ import { toast } from "@/utils/toast";
6
+ import type { AuthTokens } from "@/types";
7
+
8
+ type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
9
+
10
+ // ============================================================================
11
+ // Rate Limiting Configuration
12
+ // ============================================================================
13
+
14
+ /**
15
+ * Rate limiter to prevent API abuse and handle rate limiting gracefully
16
+ * - maxConcurrent: Maximum concurrent requests
17
+ * - minTime: Minimum time between requests (ms)
18
+ * - reservoir: Number of requests allowed in the reservoir
19
+ * - reservoirRefreshAmount: How many requests to add on refresh
20
+ * - reservoirRefreshInterval: How often to refresh the reservoir (ms)
21
+ */
22
+ const limiter = new Bottleneck({
23
+ maxConcurrent: 5, // Max 5 concurrent requests
24
+ minTime: 100, // At least 100ms between requests
25
+ reservoir: 50, // 50 requests per interval
26
+ reservoirRefreshAmount: 50,
27
+ reservoirRefreshInterval: 60 * 1000, // Refresh every minute
28
+ });
29
+
30
+ // Track rate limit errors
31
+ let rateLimitRetryAfter = 0;
32
+
33
+ limiter.on("failed", async (error, _jobInfo) => {
34
+ // If we hit a rate limit, wait and retry
35
+ if (error instanceof Error && error.message.includes("429")) {
36
+ const retryAfter = rateLimitRetryAfter || 1000;
37
+ console.warn(`Rate limited, retrying in ${retryAfter}ms`);
38
+ return retryAfter;
39
+ }
40
+ return null;
41
+ });
42
+
43
+ limiter.on("retry", (error, jobInfo) => {
44
+ console.log(`Retrying request (attempt ${jobInfo.retryCount + 1})`);
45
+ });
46
+
47
+ interface RequestOptions {
48
+ method?: RequestMethod;
49
+ body?: Record<string, unknown>;
50
+ headers?: Record<string, string>;
51
+ requiresAuth?: boolean;
52
+ skipRefresh?: boolean;
53
+ }
54
+
55
+ interface ApiError extends Error {
56
+ status: number;
57
+ data?: unknown;
58
+ }
59
+
60
+ const TOKEN_KEY = "auth_tokens";
61
+ const TOKEN_REFRESH_THRESHOLD = 5 * 60 * 1000;
62
+
63
+ // Track if we're currently refreshing to prevent multiple refresh calls
64
+ let isRefreshing = false;
65
+ let refreshPromise: Promise<string | null> | null = null;
66
+
67
+ /**
68
+ * Get current auth tokens from secure storage
69
+ */
70
+ async function getTokens(): Promise<AuthTokens | null> {
71
+ try {
72
+ const stored = await SecureStore.getItemAsync(TOKEN_KEY);
73
+ return stored ? JSON.parse(stored) : null;
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Save new tokens to secure storage
81
+ */
82
+ async function saveTokens(tokens: AuthTokens): Promise<void> {
83
+ await SecureStore.setItemAsync(TOKEN_KEY, JSON.stringify(tokens));
84
+ }
85
+
86
+ /**
87
+ * Clear tokens and redirect to login
88
+ */
89
+ async function handleAuthFailure(): Promise<void> {
90
+ await SecureStore.deleteItemAsync(TOKEN_KEY);
91
+ await SecureStore.deleteItemAsync("auth_user");
92
+ toast.error("Session expired", "Please sign in again");
93
+ router.replace("/(public)/login");
94
+ }
95
+
96
+ /**
97
+ * Refresh the access token using the refresh token
98
+ */
99
+ async function refreshAccessToken(): Promise<string | null> {
100
+ // If already refreshing, wait for that request
101
+ if (isRefreshing && refreshPromise) {
102
+ return refreshPromise;
103
+ }
104
+
105
+ isRefreshing = true;
106
+ refreshPromise = (async () => {
107
+ try {
108
+ const tokens = await getTokens();
109
+ if (!tokens?.refreshToken) {
110
+ throw new Error("No refresh token");
111
+ }
112
+
113
+ // TODO: Replace with your actual refresh endpoint
114
+ const response = await fetch(`${API_URL}/auth/refresh`, {
115
+ method: "POST",
116
+ headers: { "Content-Type": "application/json" },
117
+ body: JSON.stringify({ refreshToken: tokens.refreshToken }),
118
+ });
119
+
120
+ if (!response.ok) {
121
+ throw new Error("Refresh failed");
122
+ }
123
+
124
+ const data = await response.json();
125
+ const newTokens: AuthTokens = {
126
+ accessToken: data.accessToken,
127
+ refreshToken: data.refreshToken || tokens.refreshToken,
128
+ expiresAt: Date.now() + (data.expiresIn || 3600) * 1000,
129
+ };
130
+
131
+ await saveTokens(newTokens);
132
+ return newTokens.accessToken;
133
+ } catch (error) {
134
+ console.error("Token refresh failed:", error);
135
+ await handleAuthFailure();
136
+ return null;
137
+ } finally {
138
+ isRefreshing = false;
139
+ refreshPromise = null;
140
+ }
141
+ })();
142
+
143
+ return refreshPromise;
144
+ }
145
+
146
+ /**
147
+ * Get a valid access token, refreshing if necessary
148
+ */
149
+ async function getValidAccessToken(): Promise<string | null> {
150
+ const tokens = await getTokens();
151
+ if (!tokens) return null;
152
+
153
+ // Check if token needs refresh
154
+ const timeUntilExpiry = tokens.expiresAt - Date.now();
155
+ if (timeUntilExpiry < TOKEN_REFRESH_THRESHOLD) {
156
+ return refreshAccessToken();
157
+ }
158
+
159
+ return tokens.accessToken;
160
+ }
161
+
162
+ class ApiClient {
163
+ private baseUrl: string;
164
+ private defaultTimeout: number;
165
+ private enableRateLimiting: boolean;
166
+
167
+ constructor(baseUrl: string, timeout = 30000, enableRateLimiting = true) {
168
+ this.baseUrl = baseUrl;
169
+ this.defaultTimeout = timeout;
170
+ this.enableRateLimiting = enableRateLimiting;
171
+ }
172
+
173
+ /**
174
+ * Execute a request with rate limiting
175
+ */
176
+ private async executeWithRateLimiting<T>(fn: () => Promise<T>): Promise<T> {
177
+ if (!this.enableRateLimiting) {
178
+ return fn();
179
+ }
180
+ return limiter.schedule(fn);
181
+ }
182
+
183
+ private async request<T>(
184
+ endpoint: string,
185
+ options: RequestOptions = {}
186
+ ): Promise<T> {
187
+ const {
188
+ method = "GET",
189
+ body,
190
+ headers = {},
191
+ requiresAuth = true,
192
+ skipRefresh = false,
193
+ } = options;
194
+
195
+ const requestHeaders: Record<string, string> = {
196
+ "Content-Type": "application/json",
197
+ ...headers,
198
+ };
199
+
200
+ // Add auth token if required
201
+ if (requiresAuth) {
202
+ const token = await getValidAccessToken();
203
+ if (token) {
204
+ requestHeaders.Authorization = `Bearer ${token}`;
205
+ }
206
+ }
207
+
208
+ // Setup abort controller for timeout
209
+ const controller = new AbortController();
210
+ const timeoutId = setTimeout(() => controller.abort(), this.defaultTimeout);
211
+
212
+ try {
213
+ const config: RequestInit = {
214
+ method,
215
+ headers: requestHeaders,
216
+ signal: controller.signal,
217
+ };
218
+
219
+ if (body && method !== "GET") {
220
+ config.body = JSON.stringify(body);
221
+ }
222
+
223
+ const response = await this.executeWithRateLimiting(() =>
224
+ fetch(`${this.baseUrl}${endpoint}`, config)
225
+ );
226
+
227
+ // Handle 401 - try refresh once
228
+ if (response.status === 401 && requiresAuth && !skipRefresh) {
229
+ const newToken = await refreshAccessToken();
230
+ if (newToken) {
231
+ // Retry the request with new token
232
+ return this.request(endpoint, { ...options, skipRefresh: true });
233
+ }
234
+ throw new Error("Authentication failed");
235
+ }
236
+
237
+ // Handle rate limiting (429)
238
+ if (response.status === 429) {
239
+ const retryAfter = response.headers.get("Retry-After");
240
+ rateLimitRetryAfter = retryAfter
241
+ ? parseInt(retryAfter, 10) * 1000
242
+ : 1000;
243
+ const error = new Error("Rate limited - too many requests") as ApiError;
244
+ error.status = 429;
245
+ throw error;
246
+ }
247
+
248
+ // Handle other errors
249
+ if (!response.ok) {
250
+ const error = new Error(
251
+ `API Error: ${response.status} ${response.statusText}`
252
+ ) as ApiError;
253
+ error.status = response.status;
254
+ try {
255
+ error.data = await response.json();
256
+ } catch {
257
+ // Response body is not JSON
258
+ }
259
+ throw error;
260
+ }
261
+
262
+ // Handle empty responses
263
+ const text = await response.text();
264
+ if (!text) {
265
+ return {} as T;
266
+ }
267
+
268
+ return JSON.parse(text);
269
+ } catch (error) {
270
+ if (error instanceof Error) {
271
+ // Handle abort (timeout)
272
+ if (error.name === "AbortError") {
273
+ const timeoutError = new Error("Request timeout") as ApiError;
274
+ timeoutError.status = 408;
275
+ throw timeoutError;
276
+ }
277
+
278
+ // Handle network errors
279
+ if (
280
+ error.message.includes("Network") ||
281
+ error.message.includes("fetch")
282
+ ) {
283
+ const networkError = new Error("Network error") as ApiError;
284
+ networkError.status = 0;
285
+ throw networkError;
286
+ }
287
+ }
288
+ throw error;
289
+ } finally {
290
+ clearTimeout(timeoutId);
291
+ }
292
+ }
293
+
294
+ async get<T>(
295
+ endpoint: string,
296
+ options?: Omit<RequestOptions, "method" | "body">
297
+ ) {
298
+ return this.request<T>(endpoint, { ...options, method: "GET" });
299
+ }
300
+
301
+ async post<T>(
302
+ endpoint: string,
303
+ body?: Record<string, unknown>,
304
+ options?: Omit<RequestOptions, "method">
305
+ ) {
306
+ return this.request<T>(endpoint, { ...options, method: "POST", body });
307
+ }
308
+
309
+ async put<T>(
310
+ endpoint: string,
311
+ body?: Record<string, unknown>,
312
+ options?: Omit<RequestOptions, "method">
313
+ ) {
314
+ return this.request<T>(endpoint, { ...options, method: "PUT", body });
315
+ }
316
+
317
+ async patch<T>(
318
+ endpoint: string,
319
+ body?: Record<string, unknown>,
320
+ options?: Omit<RequestOptions, "method">
321
+ ) {
322
+ return this.request<T>(endpoint, { ...options, method: "PATCH", body });
323
+ }
324
+
325
+ async delete<T>(
326
+ endpoint: string,
327
+ options?: Omit<RequestOptions, "method" | "body">
328
+ ) {
329
+ return this.request<T>(endpoint, { ...options, method: "DELETE" });
330
+ }
331
+ }
332
+
333
+ // Export singleton instance
334
+ export const api = new ApiClient(API_URL);
335
+
336
+ // Export class for testing or creating additional instances
337
+ export { ApiClient };
338
+
339
+ // Export token utilities for auth hook
340
+ export { getTokens, saveTokens, getValidAccessToken };