@explorins/pers-sdk 1.2.6 → 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 (106) hide show
  1. package/README.md +416 -0
  2. package/dist/business/api/business-api.d.ts.map +1 -1
  3. package/dist/business.cjs +6 -8
  4. package/dist/business.cjs.map +1 -1
  5. package/dist/business.js +6 -8
  6. package/dist/business.js.map +1 -1
  7. package/dist/campaign/api/campaign-api.d.ts +19 -65
  8. package/dist/campaign/api/campaign-api.d.ts.map +1 -1
  9. package/dist/campaign.cjs +51 -105
  10. package/dist/campaign.cjs.map +1 -1
  11. package/dist/campaign.js +49 -103
  12. package/dist/campaign.js.map +1 -1
  13. package/dist/chunks/base-token-service-BA81_Ouq.js +532 -0
  14. package/dist/chunks/base-token-service-BA81_Ouq.js.map +1 -0
  15. package/dist/chunks/base-token-service-BQ6uFoki.cjs +537 -0
  16. package/dist/chunks/base-token-service-BQ6uFoki.cjs.map +1 -0
  17. package/dist/chunks/environment-C2AkkLPd.js +46 -0
  18. package/dist/chunks/environment-C2AkkLPd.js.map +1 -0
  19. package/dist/chunks/environment-CRROnwAY.cjs +50 -0
  20. package/dist/chunks/environment-CRROnwAY.cjs.map +1 -0
  21. package/dist/chunks/jwt.function-BYiyl-z_.cjs +25 -0
  22. package/dist/chunks/jwt.function-BYiyl-z_.cjs.map +1 -0
  23. package/dist/chunks/jwt.function-d6jPtBqI.js +23 -0
  24. package/dist/chunks/jwt.function-d6jPtBqI.js.map +1 -0
  25. package/dist/chunks/pers-sdk-Ct_uUMJl.cjs +1424 -0
  26. package/dist/chunks/pers-sdk-Ct_uUMJl.cjs.map +1 -0
  27. package/dist/chunks/pers-sdk-tKHGQr5x.js +1417 -0
  28. package/dist/chunks/pers-sdk-tKHGQr5x.js.map +1 -0
  29. package/dist/core/auth/api/auth-api.d.ts +5 -2
  30. package/dist/core/auth/api/auth-api.d.ts.map +1 -1
  31. package/dist/core/auth/auth-constants.d.ts +33 -0
  32. package/dist/core/auth/auth-constants.d.ts.map +1 -0
  33. package/dist/core/auth/auth-errors.d.ts +8 -0
  34. package/dist/core/auth/auth-errors.d.ts.map +1 -0
  35. package/dist/core/auth/auth-provider.interface.d.ts +49 -3
  36. package/dist/core/auth/auth-provider.interface.d.ts.map +1 -1
  37. package/dist/core/auth/create-auth-provider.d.ts.map +1 -1
  38. package/dist/core/auth/default-auth-provider.d.ts +71 -0
  39. package/dist/core/auth/default-auth-provider.d.ts.map +1 -0
  40. package/dist/core/auth/index.d.ts +1 -22
  41. package/dist/core/auth/index.d.ts.map +1 -1
  42. package/dist/core/auth/services/auth-service.d.ts +10 -1
  43. package/dist/core/auth/services/auth-service.d.ts.map +1 -1
  44. package/dist/core/auth/token-refresh.d.ts +91 -0
  45. package/dist/core/auth/token-refresh.d.ts.map +1 -0
  46. package/dist/core/auth/token-storage.d.ts +74 -0
  47. package/dist/core/auth/token-storage.d.ts.map +1 -0
  48. package/dist/core/environment.d.ts +26 -0
  49. package/dist/core/environment.d.ts.map +1 -0
  50. package/dist/core/errors/index.d.ts +80 -0
  51. package/dist/core/errors/index.d.ts.map +1 -0
  52. package/dist/core/index.d.ts +2 -1
  53. package/dist/core/index.d.ts.map +1 -1
  54. package/dist/core/pers-api-client.d.ts +184 -19
  55. package/dist/core/pers-api-client.d.ts.map +1 -1
  56. package/dist/core/pers-config.d.ts +36 -1
  57. package/dist/core/pers-config.d.ts.map +1 -1
  58. package/dist/core/utils/jwt.function.d.ts.map +1 -1
  59. package/dist/core.cjs +12 -814
  60. package/dist/core.cjs.map +1 -1
  61. package/dist/core.js +3 -803
  62. package/dist/core.js.map +1 -1
  63. package/dist/index.cjs +82 -4912
  64. package/dist/index.cjs.map +1 -1
  65. package/dist/index.d.ts +1 -0
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +21 -4857
  68. package/dist/index.js.map +1 -1
  69. package/dist/package.json +147 -129
  70. package/dist/pers-sdk.d.ts +49 -7
  71. package/dist/pers-sdk.d.ts.map +1 -1
  72. package/dist/redemption/api/redemption-api.d.ts +12 -13
  73. package/dist/redemption/api/redemption-api.d.ts.map +1 -1
  74. package/dist/redemption.cjs +24 -24
  75. package/dist/redemption.cjs.map +1 -1
  76. package/dist/redemption.js +24 -24
  77. package/dist/redemption.js.map +1 -1
  78. package/dist/shared/index.d.ts +5 -0
  79. package/dist/shared/index.d.ts.map +1 -0
  80. package/dist/shared/interfaces/pers-shared-lib.interfaces.d.ts +1 -0
  81. package/dist/shared/interfaces/pers-shared-lib.interfaces.d.ts.map +1 -1
  82. package/dist/tenant/api/tenant-api.d.ts +28 -10
  83. package/dist/tenant/api/tenant-api.d.ts.map +1 -1
  84. package/dist/tenant/index.d.ts +4 -4
  85. package/dist/tenant.cjs +40 -11
  86. package/dist/tenant.cjs.map +1 -1
  87. package/dist/tenant.js +40 -11
  88. package/dist/tenant.js.map +1 -1
  89. package/dist/token.cjs +7 -534
  90. package/dist/token.cjs.map +1 -1
  91. package/dist/token.js +1 -532
  92. package/dist/token.js.map +1 -1
  93. package/dist/web3/index.d.ts.map +1 -1
  94. package/dist/web3-chain/services/getWeb3FCD.service.d.ts +1 -1
  95. package/dist/web3-chain/services/getWeb3FCD.service.d.ts.map +1 -1
  96. package/dist/web3-chain.cjs +12 -152
  97. package/dist/web3-chain.cjs.map +1 -1
  98. package/dist/web3-chain.js +8 -148
  99. package/dist/web3-chain.js.map +1 -1
  100. package/dist/web3.cjs +12 -538
  101. package/dist/web3.cjs.map +1 -1
  102. package/dist/web3.js +10 -536
  103. package/dist/web3.js.map +1 -1
  104. package/package.json +147 -129
  105. package/dist/core/auth/simple-sdk-auth-provider.d.ts +0 -27
  106. package/dist/core/auth/simple-sdk-auth-provider.d.ts.map +0 -1
@@ -0,0 +1,1417 @@
1
+ import { AccountOwnerType } from '@explorins/pers-shared';
2
+
3
+ /**
4
+ * PERS SDK Configuration interfaces and utilities
5
+ *
6
+ * Provides type-safe configuration options for the PERS SDK
7
+ * with sensible defaults for production environments.
8
+ */
9
+ /**
10
+ * Default configuration values
11
+ */
12
+ const DEFAULT_PERS_CONFIG = {
13
+ environment: 'production',
14
+ apiVersion: 'v2',
15
+ timeout: 30000,
16
+ retries: 3,
17
+ tokenRefreshMargin: 60, // Refresh tokens 60 seconds before expiry
18
+ backgroundRefreshThreshold: 30 // Use background refresh if >30s remaining
19
+ };
20
+ /**
21
+ * Internal function to construct API root from environment
22
+ * Now defaults to production and v2
23
+ */
24
+ function buildApiRoot(environment = 'production', version = 'v2') {
25
+ const baseUrls = {
26
+ development: 'https://explorins-loyalty.ngrok.io',
27
+ staging: `https://dev.api.pers.ninja/${version}`,
28
+ production: `https://api.pers.ninja/${version}`
29
+ };
30
+ return `${baseUrls[environment]}`;
31
+ }
32
+ /**
33
+ * Merge user config with defaults
34
+ */
35
+ function mergeWithDefaults(config) {
36
+ return {
37
+ ...DEFAULT_PERS_CONFIG,
38
+ ...config,
39
+ environment: config.environment ?? DEFAULT_PERS_CONFIG.environment,
40
+ apiVersion: config.apiVersion ?? DEFAULT_PERS_CONFIG.apiVersion,
41
+ timeout: config.timeout ?? DEFAULT_PERS_CONFIG.timeout,
42
+ retries: config.retries ?? DEFAULT_PERS_CONFIG.retries
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Platform-Agnostic Auth Admin API Client
48
+ *
49
+ * Handles authentication and authorization admin operations using the PERS backend.
50
+ * Uses @explorins/pers-shared DTOs for consistency with backend.
51
+ *
52
+ * Note: Special header handling (bypass-auth-interceptor) may need to be implemented
53
+ * at the PersApiClient level or through a specialized auth client.
54
+ */
55
+ class AuthApi {
56
+ constructor(apiClient) {
57
+ this.apiClient = apiClient;
58
+ this.basePath = '/auth';
59
+ }
60
+ // ==========================================
61
+ // ADMIN AUTHENTICATION OPERATIONS
62
+ // ==========================================
63
+ /**
64
+ * ADMIN: Login tenant admin with JWT
65
+ * Note: JWT handling and auth bypass headers may need special implementation
66
+ */
67
+ async loginTenantAdmin(jwt) {
68
+ const body = {
69
+ authToken: jwt,
70
+ authType: AccountOwnerType.TENANT
71
+ };
72
+ return this.apiClient.post(`${this.basePath}/token`, body, { bypassAuth: true });
73
+ }
74
+ /**
75
+ * Login user with JWT - bypasses auth headers
76
+ */
77
+ async loginUser(jwt) {
78
+ const body = {
79
+ authToken: jwt,
80
+ authType: AccountOwnerType.USER
81
+ };
82
+ return this.apiClient.post(`${this.basePath}/token`, body, { bypassAuth: true });
83
+ }
84
+ async loginUnAuthenticated(rawLoginData) {
85
+ const body = {
86
+ authToken: '',
87
+ authType: AccountOwnerType.USER,
88
+ rawLoginData
89
+ };
90
+ return this.apiClient.post(`${this.basePath}/token`, body, { bypassAuth: true });
91
+ }
92
+ /**
93
+ * Refresh access token - bypasses auth headers to prevent circular dependency
94
+ */
95
+ async refreshAccessToken(refreshToken) {
96
+ // Bypass auth headers for refresh calls to prevent circular dependency
97
+ return this.apiClient.post(`${this.basePath}/refresh`, { refreshToken }, { bypassAuth: true });
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Platform-Agnostic Auth Admin Service
103
+ *
104
+ * Contains auth admin business logic and operations that work across platforms.
105
+ * No framework dependencies - pure TypeScript business logic.
106
+ *
107
+ * Focuses only on actual backend capabilities.
108
+ */
109
+ class AuthService {
110
+ constructor(authApi, authProvider) {
111
+ this.authApi = authApi;
112
+ this.authProvider = authProvider;
113
+ }
114
+ // ==========================================
115
+ // ADMIN AUTHENTICATION OPERATIONS
116
+ // ==========================================
117
+ /**
118
+ * ADMIN: Login tenant admin with JWT
119
+ * Automatically stores tokens if auth provider supports token storage
120
+ */
121
+ async loginTenantAdmin(jwt) {
122
+ const response = await this.authApi.loginTenantAdmin(jwt);
123
+ // Store tokens if auth provider supports it
124
+ if (this.authProvider && response.accessToken) {
125
+ await this.storeTokens(response.accessToken, response.refreshToken, 'admin', jwt);
126
+ }
127
+ return response;
128
+ }
129
+ /**
130
+ * Automatically stores tokens if auth provider supports token storage
131
+ */
132
+ async loginUser(jwt) {
133
+ const response = await this.authApi.loginUser(jwt);
134
+ // Store tokens if auth provider supports it
135
+ if (this.authProvider && response.accessToken) {
136
+ await this.storeTokens(response.accessToken, response.refreshToken, 'user', jwt);
137
+ }
138
+ return response;
139
+ }
140
+ /**
141
+ * Automatically stores tokens if auth provider supports token storage
142
+ */
143
+ async loginUserWithRawData(rawLoginData) {
144
+ const loginData = {
145
+ externalId: rawLoginData?.externalId,
146
+ email: rawLoginData?.email,
147
+ firstName: rawLoginData?.firstName,
148
+ lastName: rawLoginData?.lastName,
149
+ customData: rawLoginData?.customData
150
+ };
151
+ const response = await this.authApi.loginUnAuthenticated(loginData);
152
+ // Store tokens if auth provider supports it
153
+ if (this.authProvider && response.accessToken) {
154
+ await this.storeTokens(response.accessToken, response.refreshToken, 'user');
155
+ }
156
+ return response;
157
+ }
158
+ /**
159
+ * ADMIN: Refresh access token
160
+ * Automatically stores new tokens if auth provider supports token storage
161
+ */
162
+ async refreshAccessToken(refreshToken) {
163
+ // Use provided refresh token or get from auth provider
164
+ const tokenToUse = refreshToken || (this.authProvider?.getRefreshToken ? await this.authProvider.getRefreshToken() : null);
165
+ if (!tokenToUse) {
166
+ throw new Error('No refresh token available for token refresh');
167
+ }
168
+ const response = await this.authApi.refreshAccessToken(tokenToUse);
169
+ // Store new tokens if auth provider supports it
170
+ if (this.authProvider && response.accessToken) {
171
+ await this.storeTokens(response.accessToken, response.refreshToken);
172
+ }
173
+ return response;
174
+ }
175
+ /**
176
+ * Automatic token refresh using stored refresh token
177
+ * Convenience method for 401 error handling
178
+ */
179
+ async autoRefreshToken() {
180
+ return this.refreshAccessToken(); // Uses stored refresh token
181
+ }
182
+ /**
183
+ * Clear stored tokens if auth provider supports it
184
+ */
185
+ async clearTokens() {
186
+ if (this.authProvider?.clearTokens) {
187
+ await this.authProvider.clearTokens();
188
+ }
189
+ }
190
+ /**
191
+ * Check if we have valid tokens for authentication
192
+ */
193
+ hasValidAuth() {
194
+ return this.authProvider?.hasValidToken?.() ?? false;
195
+ }
196
+ // ==========================================
197
+ // PRIVATE HELPERS
198
+ // ==========================================
199
+ /**
200
+ * Store tokens using auth provider if it supports token storage
201
+ */
202
+ async storeTokens(accessToken, refreshToken, authType, providerToken) {
203
+ if (!this.authProvider)
204
+ return;
205
+ try {
206
+ // Store access token
207
+ if (this.authProvider.setAccessToken) {
208
+ await this.authProvider.setAccessToken(accessToken);
209
+ }
210
+ // Store refresh token if provided and supported
211
+ if (refreshToken && this.authProvider.setRefreshToken) {
212
+ await this.authProvider.setRefreshToken(refreshToken);
213
+ }
214
+ // Store provider token if provided and provider supports it
215
+ if (providerToken && 'setProviderToken' in this.authProvider &&
216
+ typeof this.authProvider.setProviderToken === 'function') {
217
+ await this.authProvider.setProviderToken(providerToken);
218
+ }
219
+ // Store auth type if provided and provider supports it
220
+ if (authType && 'setAuthType' in this.authProvider &&
221
+ typeof this.authProvider.setAuthType === 'function') {
222
+ await this.authProvider.setAuthType(authType);
223
+ }
224
+ }
225
+ catch (error) {
226
+ // Don't throw - token storage failure shouldn't break authentication
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Authentication-related constants for type safety
233
+ */
234
+ /**
235
+ * Storage keys for authentication tokens
236
+ */
237
+ const AUTH_STORAGE_KEYS = {
238
+ ACCESS_TOKEN: 'pers_access_token',
239
+ REFRESH_TOKEN: 'pers_refresh_token',
240
+ PROVIDER_TOKEN: 'pers_provider_token', // Generic external JWT (Firebase, Auth0, etc.)
241
+ AUTH_TYPE: 'pers_auth_type',
242
+ };
243
+ /**
244
+ * Authentication method types
245
+ */
246
+ const AUTH_METHODS = {
247
+ GET: 'GET',
248
+ POST: 'POST',
249
+ PUT: 'PUT',
250
+ DELETE: 'DELETE',
251
+ };
252
+
253
+ /**
254
+ * Token Storage Management
255
+ *
256
+ * Handles secure token storage with different strategies
257
+ */
258
+ /**
259
+ * LocalStorage-based token storage
260
+ */
261
+ class LocalStorageTokenStorage {
262
+ async setToken(key, value) {
263
+ if (typeof localStorage !== 'undefined') {
264
+ localStorage.setItem(key, value);
265
+ }
266
+ }
267
+ async getToken(key) {
268
+ if (typeof localStorage !== 'undefined') {
269
+ return localStorage.getItem(key);
270
+ }
271
+ return null;
272
+ }
273
+ async removeToken(key) {
274
+ if (typeof localStorage !== 'undefined') {
275
+ localStorage.removeItem(key);
276
+ }
277
+ }
278
+ async clear() {
279
+ if (typeof localStorage !== 'undefined') {
280
+ Object.values(AUTH_STORAGE_KEYS).forEach(key => {
281
+ localStorage.removeItem(key);
282
+ });
283
+ }
284
+ }
285
+ }
286
+ /**
287
+ * Token Manager - High-level token management
288
+ */
289
+ class TokenManager {
290
+ constructor(storage = new LocalStorageTokenStorage()) {
291
+ this.storage = storage;
292
+ }
293
+ async setAccessToken(token) {
294
+ await this.storage.setToken(AUTH_STORAGE_KEYS.ACCESS_TOKEN, token);
295
+ }
296
+ async getAccessToken() {
297
+ return this.storage.getToken(AUTH_STORAGE_KEYS.ACCESS_TOKEN);
298
+ }
299
+ async setRefreshToken(token) {
300
+ await this.storage.setToken(AUTH_STORAGE_KEYS.REFRESH_TOKEN, token);
301
+ }
302
+ async getRefreshToken() {
303
+ return this.storage.getToken(AUTH_STORAGE_KEYS.REFRESH_TOKEN);
304
+ }
305
+ async getProviderToken() {
306
+ return await this.storage.getToken(AUTH_STORAGE_KEYS.PROVIDER_TOKEN);
307
+ }
308
+ async setTokenData(data) {
309
+ if (data.accessToken) {
310
+ await this.setAccessToken(data.accessToken);
311
+ }
312
+ if (data.refreshToken) {
313
+ await this.setRefreshToken(data.refreshToken);
314
+ }
315
+ // Could store expiration time if needed
316
+ }
317
+ async getTokenData() {
318
+ const accessToken = await this.getAccessToken();
319
+ const refreshToken = await this.getRefreshToken();
320
+ return {
321
+ accessToken: accessToken || undefined,
322
+ refreshToken: refreshToken || undefined
323
+ };
324
+ }
325
+ async clearAllTokens() {
326
+ await this.storage.clear();
327
+ }
328
+ async hasValidTokens() {
329
+ const accessToken = await this.getAccessToken();
330
+ return !!accessToken;
331
+ }
332
+ async hasRefreshToken() {
333
+ const refreshToken = await this.getRefreshToken();
334
+ return !!refreshToken;
335
+ }
336
+ async removeToken(key) {
337
+ await this.storage.removeToken(key);
338
+ }
339
+ /**
340
+ * Set auth type (user or admin)
341
+ */
342
+ async setAuthType(authType) {
343
+ await this.storage.setToken(AUTH_STORAGE_KEYS.AUTH_TYPE, authType);
344
+ }
345
+ /**
346
+ * Get stored auth type
347
+ */
348
+ async getAuthType() {
349
+ const authType = await this.storage.getToken(AUTH_STORAGE_KEYS.AUTH_TYPE);
350
+ return authType;
351
+ }
352
+ /**
353
+ * Clear auth type from storage
354
+ */
355
+ async clearAuthType() {
356
+ await this.storage.removeToken(AUTH_STORAGE_KEYS.AUTH_TYPE);
357
+ }
358
+ /**
359
+ * Set provider token (generic external JWT)
360
+ */
361
+ async setProviderToken(token) {
362
+ await this.storage.setToken(AUTH_STORAGE_KEYS.PROVIDER_TOKEN, token);
363
+ }
364
+ /**
365
+ * Clear provider token
366
+ */
367
+ async clearProviderToken() {
368
+ await this.storage.removeToken(AUTH_STORAGE_KEYS.PROVIDER_TOKEN);
369
+ }
370
+ }
371
+
372
+ /**
373
+ * PERS SDK Error Handling - Optimized for Performance
374
+ *
375
+ * Consolidated API and auth errors for fast SDK performance
376
+ * Uses @explorins/pers-shared when available, fallback to SDK errors
377
+ */
378
+ // Fast type guards and utilities
379
+ class ErrorUtils {
380
+ /**
381
+ * Fast token expiration detection
382
+ */
383
+ static isTokenExpired(error) {
384
+ if (typeof error !== 'object' || error === null)
385
+ return false;
386
+ const err = error;
387
+ const apiError = err?.error || err?.response?.data || err;
388
+ const status = err?.status || err?.response?.status || err?.statusCode;
389
+ return apiError?.code === 'TOKEN_EXPIRED' ||
390
+ apiError?.errorCode === 'TOKEN_EXPIRED' ||
391
+ (status === 401 && apiError?.message?.toLowerCase()?.includes('token'));
392
+ }
393
+ /**
394
+ * Fast error message extraction
395
+ */
396
+ static getMessage(error) {
397
+ if (typeof error !== 'object' || error === null)
398
+ return 'Unknown error';
399
+ const err = error;
400
+ const apiError = err?.error || err?.response?.data || err;
401
+ return apiError?.message || apiError?.detail || err?.message || 'Request failed';
402
+ }
403
+ /**
404
+ * Fast status code extraction
405
+ */
406
+ static getStatus(error) {
407
+ if (typeof error !== 'object' || error === null)
408
+ return null;
409
+ const err = error;
410
+ return err?.status || err?.statusCode || err?.response?.status || null;
411
+ }
412
+ /**
413
+ * Fast retryability check
414
+ */
415
+ static isRetryable(error) {
416
+ if (typeof error !== 'object' || error === null)
417
+ return false;
418
+ const err = error;
419
+ // Check explicit retryable property first (fastest)
420
+ if (typeof err?.retryable === 'boolean')
421
+ return err.retryable;
422
+ // Fast status-based check
423
+ const status = ErrorUtils.getStatus(error);
424
+ return status === null || status >= 500 || status === 429;
425
+ }
426
+ /**
427
+ * Check if error is from PERS API (uses @explorins/pers-shared format)
428
+ */
429
+ static isPersApiError(error) {
430
+ return typeof error === 'object' && error !== null &&
431
+ 'errorCode' in error && 'domain' in error && 'category' in error;
432
+ }
433
+ }
434
+ // SDK-specific error classes for auth flows
435
+ class TokenRefreshNeeded extends Error {
436
+ constructor(refreshToken) {
437
+ super('Token refresh needed');
438
+ this.refreshToken = refreshToken;
439
+ this.errorCode = 'TOKEN_REFRESH_NEEDED';
440
+ this.domain = 'auth';
441
+ this.category = 'SECURITY';
442
+ this.retryable = true;
443
+ this.name = 'TokenRefreshNeeded';
444
+ }
445
+ }
446
+ class ProviderTokenRefreshNeeded extends Error {
447
+ constructor(providerToken) {
448
+ super('Provider token refresh needed');
449
+ this.providerToken = providerToken;
450
+ this.errorCode = 'PROVIDER_TOKEN_REFRESH_NEEDED';
451
+ this.domain = 'auth';
452
+ this.category = 'SECURITY';
453
+ this.retryable = true;
454
+ this.name = 'ProviderTokenRefreshNeeded';
455
+ }
456
+ }
457
+ class LogoutRequired extends Error {
458
+ constructor(message) {
459
+ super(message);
460
+ this.errorCode = 'LOGOUT_REQUIRED';
461
+ this.domain = 'auth';
462
+ this.category = 'SECURITY';
463
+ this.retryable = false;
464
+ this.name = 'LogoutRequired';
465
+ }
466
+ }
467
+ class PersApiError extends Error {
468
+ constructor(message, endpoint, method, status, retryable = false) {
469
+ super(`API request failed: ${message}`);
470
+ this.endpoint = endpoint;
471
+ this.method = method;
472
+ this.status = status;
473
+ this.errorCode = 'PERS_API_ERROR';
474
+ this.domain = 'api';
475
+ this.category = 'TECHNICAL';
476
+ this.name = 'PersApiError';
477
+ this.retryable = retryable;
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Token Refresh Management
483
+ *
484
+ * Handles the 6-step authentication process:
485
+ * 1. Check for provider token → get complete token set from PERS if missing
486
+ * 2. Store all tokens (access, refresh, provider)
487
+ * 3. Use access token for requests
488
+ * 4. Use refresh token if access expires → get new token set, keep provider
489
+ * 5. Fall back to provider token if refresh fails → get fresh token set from PERS
490
+ * 6. Clear all tokens if provider also fails
491
+ */
492
+ /**
493
+ * Token Refresh Manager
494
+ *
495
+ * Implements the 6-step authentication process:
496
+ * 1. Use provider token to retrieve complete token set from PERS if not present
497
+ * 2. Store all 3 tokens (access, refresh, provider)
498
+ * 3. Use access token for API requests
499
+ * 4. Use refresh token if access expires → get new token set, preserve provider token
500
+ * 5. Fall back to provider token if refresh fails → get fresh token set from PERS
501
+ * 6. Clear all tokens if provider also fails → force logout
502
+ */
503
+ class TokenRefreshManager {
504
+ constructor(tokenManager, refreshStrategy) {
505
+ this.refreshAttempts = new Map();
506
+ this.MAX_REFRESH_ATTEMPTS = 1;
507
+ this.loginRequiredListeners = [];
508
+ this.tokenManager = tokenManager;
509
+ this.refreshStrategy = refreshStrategy;
510
+ }
511
+ /**
512
+ * Add listener for login required events
513
+ */
514
+ onLoginRequired(listener) {
515
+ this.loginRequiredListeners.push(listener);
516
+ }
517
+ /**
518
+ * Remove listener for login required events
519
+ */
520
+ removeLoginRequiredListener(listener) {
521
+ const index = this.loginRequiredListeners.indexOf(listener);
522
+ if (index > -1) {
523
+ this.loginRequiredListeners.splice(index, 1);
524
+ }
525
+ }
526
+ /**
527
+ * Emit login required event to all listeners
528
+ */
529
+ emitLoginRequired(reason) {
530
+ const event = {
531
+ reason,
532
+ timestamp: new Date()
533
+ };
534
+ this.loginRequiredListeners.forEach(listener => {
535
+ try {
536
+ listener(event);
537
+ }
538
+ catch (error) {
539
+ // Listener error - continuing with other listeners
540
+ }
541
+ });
542
+ }
543
+ /**
544
+ * Handle token expiration - orchestrates the 6-step authentication process
545
+ * 1. Check for provider token → get complete token set from PERS if missing
546
+ * 2. Store all 3 tokens (access, refresh, provider)
547
+ * 3. Use access token for requests
548
+ * 4. Use refresh token if access expires → get new token set, keep provider
549
+ * 5. Fall back to provider token if refresh fails → get fresh token set from PERS
550
+ * 6. Clear all tokens if provider also fails
551
+ */
552
+ async handleTokenExpiration() {
553
+ try {
554
+ const accessToken = await this.tokenManager.getAccessToken();
555
+ const refreshToken = await this.tokenManager.getRefreshToken();
556
+ const providerToken = await this.tokenManager.getProviderToken();
557
+ // If we have no PERS tokens but have a provider token, use it to get the complete set
558
+ if (!accessToken && !refreshToken && providerToken) {
559
+ await this.executeProviderTokenFlow(providerToken);
560
+ return;
561
+ }
562
+ // Try refresh token if we have one
563
+ if (refreshToken) {
564
+ await this.executeRefreshTokenFlow(refreshToken);
565
+ return;
566
+ }
567
+ // No refresh token, try provider token
568
+ if (providerToken) {
569
+ await this.executeProviderTokenFlow(providerToken);
570
+ return;
571
+ }
572
+ // No tokens available, require login
573
+ await this.executeAuthCleanup('No authentication tokens available');
574
+ throw new LogoutRequired('No authentication tokens available');
575
+ }
576
+ catch (error) {
577
+ if (error instanceof TokenRefreshNeeded || error instanceof ProviderTokenRefreshNeeded || error instanceof LogoutRequired) {
578
+ throw error;
579
+ }
580
+ // Convert unexpected errors to login requirement
581
+ await this.executeAuthCleanup('Authentication process failed unexpectedly');
582
+ throw new LogoutRequired('Authentication process failed unexpectedly');
583
+ }
584
+ }
585
+ /**
586
+ * Execute refresh with refresh token (Step 4)
587
+ * Use refresh token to get new access token, preserve provider token
588
+ */
589
+ async executeRefreshTokenFlow(refreshToken) {
590
+ const attempts = this.refreshAttempts.get(refreshToken) || 0;
591
+ if (attempts >= this.MAX_REFRESH_ATTEMPTS) {
592
+ await this.fallbackToProviderToken();
593
+ return;
594
+ }
595
+ try {
596
+ this.refreshAttempts.set(refreshToken, attempts + 1);
597
+ const result = await this.refreshStrategy.refreshWithRefreshToken(refreshToken);
598
+ await this.storeTokenResult(result);
599
+ this.refreshAttempts.delete(refreshToken);
600
+ }
601
+ catch (error) {
602
+ await this.fallbackToProviderToken();
603
+ }
604
+ } /**
605
+ * Execute refresh with provider token (Step 5)
606
+ * Uses provider token to get a fresh token set from PERS backend
607
+ */
608
+ async executeProviderTokenFlow(providerToken) {
609
+ try {
610
+ const result = await this.refreshStrategy.refreshWithProviderToken(providerToken);
611
+ await this.storeTokenResult(result);
612
+ this.refreshAttempts.clear();
613
+ }
614
+ catch (error) {
615
+ await this.executeAuthCleanup('Provider token authentication failed - all methods exhausted');
616
+ throw new LogoutRequired('Provider token authentication failed - all methods exhausted');
617
+ }
618
+ }
619
+ async storeTokenResult(result) {
620
+ await this.tokenManager.setAccessToken(result.accessToken);
621
+ if (result.refreshToken) {
622
+ await this.tokenManager.setRefreshToken(result.refreshToken);
623
+ }
624
+ }
625
+ async fallbackToProviderToken() {
626
+ const providerToken = await this.tokenManager.getProviderToken();
627
+ if (providerToken) {
628
+ try {
629
+ await this.executeProviderTokenFlow(providerToken);
630
+ }
631
+ catch (providerError) {
632
+ await this.executeAuthCleanup('All authentication methods exhausted');
633
+ throw new LogoutRequired('All authentication methods exhausted');
634
+ }
635
+ }
636
+ else {
637
+ await this.executeAuthCleanup('Refresh failed and no provider token available');
638
+ throw new LogoutRequired('Refresh failed and no provider token available');
639
+ }
640
+ }
641
+ async clearAuthTokens() {
642
+ await this.tokenManager.removeToken(AUTH_STORAGE_KEYS.ACCESS_TOKEN);
643
+ await this.tokenManager.removeToken(AUTH_STORAGE_KEYS.REFRESH_TOKEN);
644
+ // Clear refresh attempts tracking
645
+ this.refreshAttempts.clear();
646
+ }
647
+ /**
648
+ * Execute authentication cleanup and notify login required (Step 6)
649
+ */
650
+ async executeAuthCleanup(reason = 'Authentication failed') {
651
+ await this.tokenManager.clearAllTokens();
652
+ this.refreshAttempts.clear();
653
+ this.emitLoginRequired(reason);
654
+ }
655
+ /**
656
+ * Check if an error should trigger token refresh (React Native compatible)
657
+ */
658
+ shouldRefreshToken(error) {
659
+ return ErrorUtils.isTokenExpired(error);
660
+ }
661
+ }
662
+
663
+ /**
664
+ * DefaultAuthRefreshStrategy - Implements the actual refresh logic
665
+ */
666
+ class DefaultAuthRefreshStrategy {
667
+ constructor(tokenManager, getProviderTokenFn, authApi) {
668
+ this.tokenManager = tokenManager;
669
+ this.getProviderTokenFn = getProviderTokenFn;
670
+ this.authApi = authApi;
671
+ }
672
+ async refreshWithRefreshToken(refreshToken) {
673
+ try {
674
+ const result = await this.authApi.refreshAccessToken(refreshToken);
675
+ if (!result.accessToken) {
676
+ throw new Error('Invalid refresh response: missing accessToken');
677
+ }
678
+ return {
679
+ accessToken: result.accessToken,
680
+ refreshToken: result.refreshToken || refreshToken
681
+ };
682
+ }
683
+ catch (error) {
684
+ throw new Error(`Refresh token invalid or expired: ${error instanceof Error ? error.message : 'Unknown error'}`);
685
+ }
686
+ }
687
+ async refreshWithProviderToken(providerToken) {
688
+ try {
689
+ const storedAuthType = await this.tokenManager.getAuthType();
690
+ let result;
691
+ if (storedAuthType === 'admin') {
692
+ result = await this.authApi.loginTenantAdmin(providerToken);
693
+ }
694
+ else if (storedAuthType === 'user') {
695
+ result = await this.authApi.loginUser(providerToken);
696
+ }
697
+ else {
698
+ try {
699
+ result = await this.authApi.loginUser(providerToken);
700
+ await this.tokenManager.setAuthType('user');
701
+ }
702
+ catch (userLoginError) {
703
+ result = await this.authApi.loginTenantAdmin(providerToken);
704
+ await this.tokenManager.setAuthType('admin');
705
+ }
706
+ }
707
+ if (!result.accessToken) {
708
+ throw new Error('Invalid provider login response: missing accessToken');
709
+ }
710
+ return {
711
+ accessToken: result.accessToken,
712
+ refreshToken: result.refreshToken
713
+ };
714
+ }
715
+ catch (error) {
716
+ throw new Error(`Provider token login failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
717
+ }
718
+ }
719
+ }
720
+ /**
721
+ * Default authentication provider with modular architecture
722
+ *
723
+ * Delegates token storage to TokenManager and refresh logic to TokenRefreshManager.
724
+ * Perfect for platform-agnostic usage with reliable error handling.
725
+ */
726
+ class DefaultAuthProvider {
727
+ constructor(projectKey, authApi) {
728
+ this.projectKey = null;
729
+ this.authApi = null;
730
+ this.authType = 'admin';
731
+ this.projectKey = projectKey || null;
732
+ this.authApi = authApi || null;
733
+ this.tokenManager = new TokenManager();
734
+ const refreshStrategy = new DefaultAuthRefreshStrategy(this.tokenManager, () => Promise.resolve(this.getProviderToken()), this.authApi);
735
+ this.tokenRefreshManager = new TokenRefreshManager(this.tokenManager, refreshStrategy);
736
+ }
737
+ async getToken() {
738
+ return await this.tokenManager.getAccessToken();
739
+ }
740
+ async getProjectKey() {
741
+ return this.projectKey;
742
+ }
743
+ /**
744
+ * Centralized token refresh handler - delegates to TokenRefreshManager
745
+ */
746
+ async onTokenExpired() {
747
+ await this.tokenRefreshManager.handleTokenExpiration();
748
+ }
749
+ /**
750
+ * Check if an error indicates token expiration (React Native compatible)
751
+ */
752
+ isTokenExpiredError(error) {
753
+ return ErrorUtils.isTokenExpired(error);
754
+ }
755
+ /**
756
+ * Get Firebase or other provider token for fresh JWT request
757
+ * Type-safe method that uses proper storage keys from AUTH_STORAGE_KEYS
758
+ */
759
+ getProviderToken() {
760
+ if (typeof localStorage !== 'undefined') {
761
+ return localStorage.getItem(AUTH_STORAGE_KEYS.PROVIDER_TOKEN);
762
+ }
763
+ return null;
764
+ }
765
+ async setAccessToken(token) {
766
+ await this.tokenManager.setAccessToken(token);
767
+ }
768
+ async setRefreshToken(token) {
769
+ await this.tokenManager.setRefreshToken(token);
770
+ }
771
+ async getRefreshToken() {
772
+ return await this.tokenManager.getRefreshToken();
773
+ }
774
+ async setProviderToken(token) {
775
+ await this.tokenManager.setProviderToken(token);
776
+ }
777
+ async clearProviderToken() {
778
+ await this.tokenManager.clearProviderToken();
779
+ }
780
+ async clearTokens() {
781
+ await this.tokenManager.clearAllTokens();
782
+ }
783
+ hasValidToken() {
784
+ if (typeof localStorage !== 'undefined') {
785
+ return !!localStorage.getItem(AUTH_STORAGE_KEYS.ACCESS_TOKEN);
786
+ }
787
+ return false;
788
+ }
789
+ hasRefreshToken() {
790
+ if (typeof localStorage !== 'undefined') {
791
+ return !!localStorage.getItem(AUTH_STORAGE_KEYS.REFRESH_TOKEN);
792
+ }
793
+ return false;
794
+ }
795
+ /**
796
+ * Proactively check token expiry and refresh if needed BEFORE making requests
797
+ * Uses smart refresh strategy based on time remaining:
798
+ * - >backgroundThreshold seconds: Background refresh (non-blocking)
799
+ * - <backgroundThreshold seconds: Immediate refresh (blocking)
800
+ */
801
+ async ensureValidToken(marginSeconds = 60, backgroundThreshold = 30) {
802
+ try {
803
+ const currentToken = await this.getToken();
804
+ // If no token, nothing to check
805
+ if (!currentToken) {
806
+ return;
807
+ }
808
+ // Check if token is expired or will expire within margin
809
+ if (await this.isTokenExpired(marginSeconds)) {
810
+ // Determine refresh strategy based on time remaining
811
+ const timeToExpiry = await this.getTokenTimeToExpiry(currentToken);
812
+ if (timeToExpiry > backgroundThreshold) {
813
+ // Token has enough time left - start background refresh (non-blocking)
814
+ this.startBackgroundRefresh();
815
+ }
816
+ else {
817
+ // Token expiring soon or expired - block and refresh immediately
818
+ const shouldSkipRefresh = await this.isRefreshTokenExpired(marginSeconds);
819
+ if (shouldSkipRefresh) {
820
+ // Both tokens expired - use provider token directly
821
+ await this.handleExpiredRefreshToken();
822
+ }
823
+ else {
824
+ // Normal refresh with refresh token
825
+ if (this.onTokenExpired) {
826
+ await this.onTokenExpired();
827
+ }
828
+ }
829
+ }
830
+ }
831
+ }
832
+ catch (error) {
833
+ // If token check/refresh fails, the error will be handled by the calling code
834
+ throw error;
835
+ }
836
+ }
837
+ /**
838
+ * Check if current access token is expired
839
+ */
840
+ async isTokenExpired(marginSeconds = 60) {
841
+ try {
842
+ const currentToken = await this.getToken();
843
+ if (!currentToken) {
844
+ return true;
845
+ }
846
+ // Import isTokenExpired function here to avoid circular imports
847
+ const { isTokenExpired } = await import('./jwt.function-d6jPtBqI.js');
848
+ return isTokenExpired(currentToken, marginSeconds);
849
+ }
850
+ catch (error) {
851
+ return true;
852
+ }
853
+ }
854
+ /**
855
+ * Check if refresh token is expired
856
+ */
857
+ async isRefreshTokenExpired(marginSeconds = 60) {
858
+ try {
859
+ const refreshToken = await this.tokenManager.getRefreshToken();
860
+ if (!refreshToken) {
861
+ return true; // No refresh token
862
+ }
863
+ // Import isTokenExpired function here to avoid circular imports
864
+ const { isTokenExpired } = await import('./jwt.function-d6jPtBqI.js');
865
+ return isTokenExpired(refreshToken, marginSeconds);
866
+ }
867
+ catch (error) {
868
+ return true; // Assume expired if we can't check
869
+ }
870
+ }
871
+ /**
872
+ * Check if both access and refresh tokens are expired
873
+ */
874
+ async areAllTokensExpired(marginSeconds = 60) {
875
+ const accessTokenExpired = await this.isTokenExpired(marginSeconds);
876
+ const refreshTokenExpired = await this.isRefreshTokenExpired(marginSeconds);
877
+ return accessTokenExpired && refreshTokenExpired;
878
+ }
879
+ /**
880
+ * Get seconds until token expires
881
+ */
882
+ async getTokenTimeToExpiry(token) {
883
+ try {
884
+ const { isTokenExpired } = await import('./jwt.function-d6jPtBqI.js');
885
+ const { jwtDecode } = await import('jwt-decode');
886
+ const decoded = jwtDecode(token);
887
+ const currentTime = Math.floor(Date.now() / 1000);
888
+ return Math.max(0, decoded.exp - currentTime);
889
+ }
890
+ catch (error) {
891
+ return 0; // Assume expired if can't decode
892
+ }
893
+ }
894
+ /**
895
+ * Start refresh in background without blocking current request
896
+ */
897
+ startBackgroundRefresh() {
898
+ // Use setTimeout to avoid blocking the current request
899
+ setTimeout(async () => {
900
+ try {
901
+ if (this.onTokenExpired) {
902
+ await this.onTokenExpired();
903
+ }
904
+ }
905
+ catch (error) {
906
+ // Background refresh failed - next request will trigger reactive refresh
907
+ }
908
+ }, 0);
909
+ }
910
+ /**
911
+ * Handle case where refresh token is also expired - use provider token directly
912
+ */
913
+ async handleExpiredRefreshToken() {
914
+ try {
915
+ // Get provider token if available
916
+ const providerToken = this.getProviderToken();
917
+ if (!providerToken) {
918
+ // No provider token available - let normal refresh handle the failure
919
+ if (this.onTokenExpired) {
920
+ await this.onTokenExpired();
921
+ }
922
+ return;
923
+ }
924
+ // Clear expired PERS tokens and use provider token to get fresh ones
925
+ await this.clearTokens();
926
+ // Trigger refresh which should now use provider token path
927
+ if (this.onTokenExpired) {
928
+ await this.onTokenExpired();
929
+ }
930
+ }
931
+ catch (error) {
932
+ // If provider token flow fails, let normal refresh handle it
933
+ if (this.onTokenExpired) {
934
+ await this.onTokenExpired();
935
+ }
936
+ }
937
+ }
938
+ }
939
+
940
+ // packages/pers-sdk/src/core/pers-api-client.ts
941
+ /**
942
+ * PERS API Client - Core platform-agnostic client for PERS backend
943
+ *
944
+ * Provides authenticated HTTP client with automatic token management,
945
+ * proactive refresh, and comprehensive error handling.
946
+ *
947
+ * Features:
948
+ * - Automatic token refresh before expiry
949
+ * - Background refresh for optimal performance
950
+ * - Provider token fallback for seamless authentication
951
+ * - Configurable retry and timeout settings
952
+ * - Platform-agnostic design
953
+ *
954
+ * @example
955
+ * ```typescript
956
+ * const client = new PersApiClient(httpClient, {
957
+ * environment: 'production',
958
+ * apiProjectKey: 'your-project-key',
959
+ * authProvider: createAuthProvider({
960
+ * tokenProvider: () => getFirebaseToken()
961
+ * })
962
+ * });
963
+ *
964
+ * // Make authenticated requests
965
+ * const data = await client.get('/users/me');
966
+ * ```
967
+ */
968
+ class PersApiClient {
969
+ /**
970
+ * Creates a new PERS API Client instance
971
+ *
972
+ * @param httpClient - Platform-specific HTTP client implementation
973
+ * @param config - Configuration options for the API client
974
+ */
975
+ constructor(httpClient, config) {
976
+ this.httpClient = httpClient;
977
+ this.config = config;
978
+ // Merge user config with defaults (production + v2)
979
+ this.mergedConfig = mergeWithDefaults(config);
980
+ // Build API root from merged environment and version
981
+ this.apiRoot = buildApiRoot(this.mergedConfig.environment, this.mergedConfig.apiVersion);
982
+ // Initialize auth services for direct authentication
983
+ this.authApi = new AuthApi(this);
984
+ // Auto-create auth provider if none provided
985
+ if (!this.mergedConfig.authProvider) {
986
+ this.mergedConfig.authProvider = new DefaultAuthProvider(this.mergedConfig.apiProjectKey, this.authApi);
987
+ }
988
+ this.authService = new AuthService(this.authApi, this.mergedConfig.authProvider);
989
+ }
990
+ /**
991
+ * Ensures valid authentication token before making requests
992
+ *
993
+ * Implements intelligent refresh strategy:
994
+ * - Tokens with sufficient time remaining: Background refresh (non-blocking)
995
+ * - Tokens expiring soon or expired: Immediate refresh (blocking)
996
+ *
997
+ * @private
998
+ * @returns Promise that resolves when token validation is complete
999
+ */
1000
+ async ensureValidToken() {
1001
+ if (!this.mergedConfig.authProvider?.ensureValidToken) {
1002
+ return; // Auth provider doesn't support proactive validation
1003
+ }
1004
+ try {
1005
+ const refreshMargin = this.mergedConfig.tokenRefreshMargin || 60;
1006
+ const backgroundThreshold = this.mergedConfig.backgroundRefreshThreshold || 30;
1007
+ await this.mergedConfig.authProvider.ensureValidToken(refreshMargin, backgroundThreshold);
1008
+ }
1009
+ catch (error) {
1010
+ // If token check/refresh fails, continue with request
1011
+ // The reactive error handling will catch any auth issues
1012
+ }
1013
+ }
1014
+ /**
1015
+ * Get request headers including auth token and project key
1016
+ */
1017
+ async getHeaders() {
1018
+ const headers = {
1019
+ 'Content-Type': 'application/json',
1020
+ };
1021
+ // Add authentication token
1022
+ if (this.mergedConfig.authProvider) {
1023
+ const token = await this.mergedConfig.authProvider.getToken();
1024
+ if (token) {
1025
+ headers['Authorization'] = `Bearer ${token}`;
1026
+ }
1027
+ }
1028
+ // Add project key
1029
+ if (this.mergedConfig.authProvider) {
1030
+ const projectKey = await this.mergedConfig.authProvider.getProjectKey();
1031
+ if (projectKey) {
1032
+ headers['x-project-key'] = projectKey;
1033
+ }
1034
+ }
1035
+ else if (this.mergedConfig.apiProjectKey) {
1036
+ // Fallback to config project key if no auth provider
1037
+ headers['x-project-key'] = this.mergedConfig.apiProjectKey;
1038
+ }
1039
+ return headers;
1040
+ }
1041
+ /**
1042
+ * Make a request with proper headers, auth, and error handling
1043
+ */
1044
+ async request(method, endpoint, body, options) {
1045
+ const { retryCount = 0, responseType = 'json', bypassAuth = false } = options || {};
1046
+ const url = `${this.apiRoot}${endpoint}`;
1047
+ // Proactive token expiry check and refresh BEFORE making the request
1048
+ if (!bypassAuth && this.mergedConfig.authProvider && retryCount === 0) {
1049
+ await this.ensureValidToken();
1050
+ }
1051
+ const requestOptions = {
1052
+ headers: bypassAuth ? await this.getHeadersWithoutAuth() : await this.getHeaders(),
1053
+ timeout: this.mergedConfig.timeout,
1054
+ responseType
1055
+ };
1056
+ // Log API request with auth info
1057
+ // const hasAuth = !!this.mergedConfig.authProvider;
1058
+ endpoint.includes('/export/csv');
1059
+ try {
1060
+ let result;
1061
+ switch (method) {
1062
+ case AUTH_METHODS.GET:
1063
+ result = await this.httpClient.get(url, requestOptions);
1064
+ break;
1065
+ case AUTH_METHODS.POST:
1066
+ result = await this.httpClient.post(url, body, requestOptions);
1067
+ break;
1068
+ case AUTH_METHODS.PUT:
1069
+ result = await this.httpClient.put(url, body, requestOptions);
1070
+ break;
1071
+ case AUTH_METHODS.DELETE:
1072
+ result = await this.httpClient.delete(url, requestOptions);
1073
+ break;
1074
+ default:
1075
+ throw new Error(`Unsupported HTTP method: ${method}`);
1076
+ }
1077
+ return result;
1078
+ }
1079
+ catch (error) {
1080
+ // Error handling - proactive token refresh should prevent most 401s
1081
+ const status = ErrorUtils.getStatus(error);
1082
+ const errorMessage = ErrorUtils.getMessage(error);
1083
+ // Fallback: reactive token refresh only if proactive check missed something
1084
+ if (retryCount === 0 && this.mergedConfig.authProvider && ErrorUtils.isTokenExpired(error)) {
1085
+ try {
1086
+ // Fallback token refresh delegation
1087
+ const result = await this.handleTokenRefreshDelegation(method, endpoint, body, options);
1088
+ if (result !== null) {
1089
+ return result;
1090
+ }
1091
+ }
1092
+ catch (refreshError) {
1093
+ throw new PersApiError(`Auth failed: ${refreshError.message || refreshError}`, endpoint, method, 401);
1094
+ }
1095
+ }
1096
+ throw new PersApiError(errorMessage, endpoint, method, status || undefined, ErrorUtils.isRetryable(error));
1097
+ }
1098
+ }
1099
+ /**
1100
+ * Delegate token refresh to auth provider and handle the results
1101
+ */
1102
+ async handleTokenRefreshDelegation(method, endpoint, body, options) {
1103
+ try {
1104
+ // Let auth provider handle the refresh process
1105
+ const authProvider = this.mergedConfig.authProvider;
1106
+ if (authProvider?.onTokenExpired) {
1107
+ await authProvider.onTokenExpired();
1108
+ }
1109
+ // If we get here, tokens should be refreshed - retry the request
1110
+ // Auth provider refresh succeeded, retrying...
1111
+ return this.request(method, endpoint, body, { ...options, retryCount: 1 });
1112
+ }
1113
+ catch (refreshError) {
1114
+ // Auth provider handled all refresh attempts and failed
1115
+ // Re-throw the error for the caller to handle
1116
+ throw refreshError;
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Performs an authenticated GET request
1121
+ *
1122
+ * @template T - Expected response type
1123
+ * @param endpoint - API endpoint path (without base URL)
1124
+ * @param responseType - Expected response format
1125
+ * @returns Promise resolving to typed response data
1126
+ *
1127
+ * @example
1128
+ * ```typescript
1129
+ * const user = await client.get<User>('/users/123');
1130
+ * const csvData = await client.get('/export/data', 'blob');
1131
+ * ```
1132
+ */
1133
+ async get(endpoint, responseType) {
1134
+ return this.request(AUTH_METHODS.GET, endpoint, undefined, { responseType });
1135
+ }
1136
+ /**
1137
+ * Performs an authenticated POST request
1138
+ *
1139
+ * @template T - Expected response type
1140
+ * @param endpoint - API endpoint path (without base URL)
1141
+ * @param body - Request payload data
1142
+ * @param options - Request options including auth bypass
1143
+ * @returns Promise resolving to typed response data
1144
+ *
1145
+ * @example
1146
+ * ```typescript
1147
+ * const user = await client.post<User>('/users', userData);
1148
+ * const publicData = await client.post('/public/contact', formData, { bypassAuth: true });
1149
+ * ```
1150
+ */
1151
+ async post(endpoint, body, options) {
1152
+ return this.request(AUTH_METHODS.POST, endpoint, body, options);
1153
+ }
1154
+ /**
1155
+ * Generic PUT request
1156
+ */
1157
+ async put(endpoint, body) {
1158
+ return this.request(AUTH_METHODS.PUT, endpoint, body);
1159
+ }
1160
+ /**
1161
+ * Generic DELETE request
1162
+ */
1163
+ async delete(endpoint) {
1164
+ return this.request(AUTH_METHODS.DELETE, endpoint);
1165
+ }
1166
+ /**
1167
+ * Get request headers WITHOUT auth token (for auth operations like refresh/login)
1168
+ */
1169
+ async getHeadersWithoutAuth() {
1170
+ const headers = {
1171
+ 'Content-Type': 'application/json',
1172
+ };
1173
+ // Add project key only (no auth token)
1174
+ if (this.mergedConfig.authProvider) {
1175
+ const projectKey = await this.mergedConfig.authProvider.getProjectKey();
1176
+ if (projectKey) {
1177
+ headers['x-project-key'] = projectKey;
1178
+ }
1179
+ }
1180
+ else if (this.mergedConfig.apiProjectKey) {
1181
+ headers['x-project-key'] = this.mergedConfig.apiProjectKey;
1182
+ }
1183
+ return headers;
1184
+ }
1185
+ // ==========================================
1186
+ // AUTHENTICATION METHODS
1187
+ // ==========================================
1188
+ /**
1189
+ * Authenticates an admin user using external JWT token
1190
+ *
1191
+ * Exchanges external provider token (Firebase, Auth0, etc.) for PERS access tokens.
1192
+ * Automatically stores received tokens for subsequent requests.
1193
+ *
1194
+ * @param externalJwt - JWT token from external authentication provider
1195
+ * @returns Promise resolving to session context with admin permissions
1196
+ *
1197
+ * @example
1198
+ * ```typescript
1199
+ * const firebaseToken = await getIdToken();
1200
+ * const session = await client.loginAdmin(firebaseToken);
1201
+ * console.log('Admin authenticated:', session.user.email);
1202
+ * ```
1203
+ */
1204
+ async loginAdmin(externalJwt) {
1205
+ return this.authService.loginTenantAdmin(externalJwt);
1206
+ }
1207
+ /**
1208
+ * Authenticates a regular user using external JWT token
1209
+ *
1210
+ * Exchanges external provider token for PERS access tokens with user-level permissions.
1211
+ * Automatically stores received tokens for subsequent requests.
1212
+ *
1213
+ * @param externalJwt - JWT token from external authentication provider
1214
+ * @returns Promise resolving to session context with user permissions
1215
+ *
1216
+ * @example
1217
+ * ```typescript
1218
+ * const firebaseToken = await getIdToken();
1219
+ * const session = await client.loginUser(firebaseToken);
1220
+ * console.log('User authenticated:', session.user.email);
1221
+ * ```
1222
+ */
1223
+ async loginUser(externalJwt) {
1224
+ return this.authService.loginUser(externalJwt);
1225
+ }
1226
+ /**
1227
+ * Authenticates a user using raw login data (no external JWT)
1228
+ *
1229
+ * Useful for custom authentication flows where user data is provided directly.
1230
+ * Automatically stores received tokens for subsequent requests.
1231
+ *
1232
+ * @param rawLoginData - Object containing user login data (email, name, etc.)
1233
+ * @return Promise resolving to session context with user permissions
1234
+ */
1235
+ async loginUserWithRawData(rawLoginData) {
1236
+ return this.authService.loginUserWithRawData(rawLoginData);
1237
+ }
1238
+ /**
1239
+ * Checks if current user has a valid authentication token
1240
+ *
1241
+ * Performs basic token availability check without network requests.
1242
+ * For comprehensive validation including expiry, use isTokenExpired().
1243
+ *
1244
+ * @returns True if valid token exists, false otherwise
1245
+ *
1246
+ * @example
1247
+ * ```typescript
1248
+ * if (client.hasValidAuth()) {
1249
+ * // User is authenticated, proceed with API calls
1250
+ * const data = await client.get('/protected-data');
1251
+ * } else {
1252
+ * // Redirect to login
1253
+ * redirectToLogin();
1254
+ * }
1255
+ * ```
1256
+ */
1257
+ hasValidAuth() {
1258
+ return this.mergedConfig.authProvider?.hasValidToken?.() || false;
1259
+ }
1260
+ /**
1261
+ * Checks if current access token is expired or expiring soon
1262
+ *
1263
+ * @param marginSeconds - Seconds before expiry to consider token as expired (default: 60)
1264
+ * @returns Promise resolving to true if token is expired/expiring, false if valid
1265
+ *
1266
+ * @example
1267
+ * ```typescript
1268
+ * if (await client.isTokenExpired(120)) {
1269
+ * console.log('Token expires within 2 minutes');
1270
+ * // Optionally trigger manual refresh
1271
+ * }
1272
+ * ```
1273
+ */
1274
+ async isTokenExpired(marginSeconds = 60) {
1275
+ if (!this.mergedConfig.authProvider?.isTokenExpired) {
1276
+ return true; // No auth provider or doesn't support expiry checking
1277
+ }
1278
+ try {
1279
+ return await this.mergedConfig.authProvider.isTokenExpired(marginSeconds);
1280
+ }
1281
+ catch (error) {
1282
+ return true;
1283
+ }
1284
+ }
1285
+ /**
1286
+ * Checks if both access and refresh tokens are expired
1287
+ *
1288
+ * Useful for determining if full re-authentication is required.
1289
+ *
1290
+ * @param marginSeconds - Seconds before expiry to consider tokens as expired (default: 60)
1291
+ * @returns Promise resolving to true if both tokens expired, false otherwise
1292
+ *
1293
+ * @example
1294
+ * ```typescript
1295
+ * if (await client.areAllTokensExpired()) {
1296
+ * // Full re-authentication required
1297
+ * await redirectToLogin();
1298
+ * }
1299
+ * ```
1300
+ */
1301
+ async areAllTokensExpired(marginSeconds = 60) {
1302
+ if (!this.mergedConfig.authProvider?.areAllTokensExpired) {
1303
+ // Fallback to checking access token only
1304
+ return await this.isTokenExpired(marginSeconds);
1305
+ }
1306
+ return await this.mergedConfig.authProvider.areAllTokensExpired(marginSeconds);
1307
+ }
1308
+ /**
1309
+ * Refresh access token using stored refresh token
1310
+ *
1311
+ * @param refreshToken - Optional refresh token, uses stored token if not provided
1312
+ * @returns Promise resolving to new auth tokens
1313
+ *
1314
+ * @example
1315
+ * ```typescript
1316
+ * try {
1317
+ * const tokens = await client.refreshTokens();
1318
+ * console.log('Tokens refreshed successfully');
1319
+ * } catch (error) {
1320
+ * console.error('Token refresh failed:', error);
1321
+ * }
1322
+ * ```
1323
+ */
1324
+ async refreshTokens(refreshToken) {
1325
+ return this.authService.refreshAccessToken(refreshToken);
1326
+ }
1327
+ /**
1328
+ * Get current configuration (returns merged config)
1329
+ */
1330
+ getConfig() {
1331
+ return this.mergedConfig;
1332
+ }
1333
+ /**
1334
+ * Get original user configuration
1335
+ */
1336
+ getOriginalConfig() {
1337
+ return this.config;
1338
+ }
1339
+ }
1340
+
1341
+ /**
1342
+ * PERS SDK - Platform-agnostic TypeScript SDK for PERS API
1343
+ *
1344
+ * Provides a simple wrapper around the core API client with
1345
+ * intelligent authentication and token management.
1346
+ */
1347
+ /**
1348
+ * Main PERS SDK class
1349
+ *
1350
+ * Minimal wrapper around PersApiClient providing a clean interface
1351
+ * for platform-specific implementations.
1352
+ *
1353
+ * @example
1354
+ * ```typescript
1355
+ * import { createPersSDK, createAuthProvider } from '@explorins/pers-sdk/core';
1356
+ * import { BrowserHttpClient } from '@explorins/pers-sdk/browser';
1357
+ *
1358
+ * const authProvider = createAuthProvider({
1359
+ * tokenProvider: () => getFirebaseToken()
1360
+ * });
1361
+ *
1362
+ * const sdk = new PersSDK(new BrowserHttpClient(), {
1363
+ * environment: 'production',
1364
+ * apiProjectKey: 'your-project-key',
1365
+ * authProvider
1366
+ * });
1367
+ *
1368
+ * const apiClient = sdk.api();
1369
+ * const user = await apiClient.get('/users/me');
1370
+ * ```
1371
+ */
1372
+ class PersSDK {
1373
+ /**
1374
+ * Creates a new PERS SDK instance
1375
+ *
1376
+ * @param httpClient Platform-specific HTTP client implementation
1377
+ * @param config SDK configuration options
1378
+ */
1379
+ constructor(httpClient, config) {
1380
+ this.apiClient = new PersApiClient(httpClient, config);
1381
+ }
1382
+ /**
1383
+ * Gets the API client for making PERS API requests
1384
+ *
1385
+ * This is the main interface for interacting with the PERS backend.
1386
+ * The returned client handles authentication, token refresh, and error handling automatically.
1387
+ *
1388
+ * @returns Configured PersApiClient instance
1389
+ *
1390
+ * @example
1391
+ * ```typescript
1392
+ * const apiClient = sdk.api();
1393
+ * const user = await apiClient.get<User>('/users/me');
1394
+ * await apiClient.post('/users', userData);
1395
+ * ```
1396
+ */
1397
+ api() {
1398
+ return this.apiClient;
1399
+ }
1400
+ /**
1401
+ * Checks if SDK is configured for production environment
1402
+ *
1403
+ * @returns True if environment is 'production', false otherwise
1404
+ */
1405
+ isProduction() {
1406
+ return this.apiClient.getConfig().environment === 'production';
1407
+ }
1408
+ }
1409
+ /**
1410
+ * Simple factory function
1411
+ */
1412
+ function createPersSDK(httpClient, config) {
1413
+ return new PersSDK(httpClient, config);
1414
+ }
1415
+
1416
+ export { DEFAULT_PERS_CONFIG as D, PersSDK as P, PersApiClient as a, buildApiRoot as b, createPersSDK as c, mergeWithDefaults as m };
1417
+ //# sourceMappingURL=pers-sdk-tKHGQr5x.js.map