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