@opensourcekd/ng-common-libs 1.2.3 → 1.2.5

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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Observable } from 'rxjs';
2
- import { CanActivateFn } from '@angular/router';
3
- import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
1
+ import { Observable, ReplaySubject } from 'rxjs';
2
+ import { HttpClient } from '@angular/common/http';
3
+ import { EventType } from 'mitt';
4
4
 
5
5
  /**
6
6
  * Event payload interface
@@ -56,636 +56,347 @@ declare class EventBus {
56
56
  }
57
57
 
58
58
  /**
59
- * Token configuration interface
60
- */
61
- interface TokenConfig {
62
- tokenKey?: string;
63
- refreshTokenKey?: string;
64
- useSessionStorage?: boolean;
65
- }
66
- /**
67
- * TokenManager - Manages authentication tokens
68
- * Framework-agnostic implementation using browser storage APIs
69
- * Handles storage, retrieval, and validation of JWT tokens
70
- *
71
- * @example
72
- * ```typescript
73
- * const tokenManager = new TokenManager();
74
- *
75
- * // Store a token
76
- * tokenManager.setToken('your-jwt-token');
59
+ * EventBusService - Angular service for cross-application event communication
60
+ * Uses mitt library for efficient event handling and RxJS ReplaySubject for observable stream
77
61
  *
78
- * // Check if authenticated
79
- * if (tokenManager.isAuthenticated()) {
80
- * const userData = tokenManager.getUserFromToken();
81
- * }
82
- * ```
83
- */
84
- declare class TokenManager {
85
- private TOKEN_KEY;
86
- private REFRESH_TOKEN_KEY;
87
- private useSessionStorage;
88
- /**
89
- * Configure token manager
90
- */
91
- configure(config: TokenConfig): void;
92
- /**
93
- * Get the storage mechanism based on configuration
94
- */
95
- private getStorage;
96
- /**
97
- * Set authentication token
98
- */
99
- setToken(token: string): void;
100
- /**
101
- * Get authentication token
102
- */
103
- getToken(): string | null;
104
- /**
105
- * Remove authentication token
106
- */
107
- removeToken(): void;
108
- /**
109
- * Set refresh token
110
- */
111
- setRefreshToken(token: string): void;
112
- /**
113
- * Get refresh token
114
- */
115
- getRefreshToken(): string | null;
116
- /**
117
- * Remove refresh token
118
- */
119
- removeRefreshToken(): void;
120
- /**
121
- * Clear all tokens
122
- */
123
- clearTokens(): void;
124
- /**
125
- * Check if token exists
126
- */
127
- hasToken(): boolean;
128
- /**
129
- * Decode JWT token (without verification)
130
- * @param token - JWT token to decode
131
- * @returns Decoded token payload or null if invalid
132
- */
133
- decodeToken(token?: string): any;
134
- /**
135
- * Check if token is expired
136
- * @param token - Optional token to check (defaults to stored token)
137
- * @returns true if token is expired or invalid
138
- */
139
- isTokenExpired(token?: string): boolean;
140
- /**
141
- * Check if user is authenticated (has valid, non-expired token)
142
- */
143
- isAuthenticated(): boolean;
144
- /**
145
- * Get token expiration date
146
- */
147
- getTokenExpirationDate(token?: string): Date | null;
148
- /**
149
- * Get user data from token
150
- */
151
- getUserFromToken(token?: string): any;
152
- }
153
-
154
- /**
155
- * StorageManager - Type-safe wrapper for browser storage
156
- * Framework-agnostic implementation using browser storage APIs
157
- * Provides JSON serialization/deserialization and error handling
62
+ * This service is designed for MicroFrontend architectures where different apps need to communicate
63
+ * The ReplaySubject keeps last 100 events in memory for late subscribers
158
64
  *
159
65
  * @example
160
66
  * ```typescript
161
- * const storage = new StorageManager();
67
+ * import { Component, inject, OnInit } from '@angular/core';
68
+ * import { EventBusService } from '@opensourcekd/ng-common-libs';
162
69
  *
163
- * // Store data
164
- * storage.setLocal('user-prefs', { theme: 'dark', lang: 'en' });
70
+ * @Component({
71
+ * selector: 'app-example',
72
+ * template: '...'
73
+ * })
74
+ * export class ExampleComponent implements OnInit {
75
+ * private eventBus = inject(EventBusService);
165
76
  *
166
- * // Retrieve data
167
- * const prefs = storage.getLocal('user-prefs');
77
+ * ngOnInit() {
78
+ * // Subscribe to all events
79
+ * this.eventBus.onePlusNEvents.subscribe(event => {
80
+ * console.log('Event received:', event);
81
+ * });
82
+ * }
83
+ *
84
+ * sendCustomEvent() {
85
+ * // Send a custom event
86
+ * this.eventBus.sendEvent('user:action');
168
87
  *
169
- * // With expiration
170
- * storage.setWithExpiration('temp-data', someData, 3600000); // 1 hour
88
+ * // Or send structured event with data
89
+ * this.eventBus.sendEvent(JSON.stringify({
90
+ * type: 'user:login',
91
+ * payload: { userId: '123' },
92
+ * timestamp: new Date().toISOString()
93
+ * }));
94
+ * }
95
+ * }
171
96
  * ```
172
97
  */
173
- declare class StorageManager {
98
+ declare class EventBusService {
174
99
  /**
175
- * Set item in localStorage with JSON serialization
100
+ * ReplaySubject that buffers the last 100 events for late subscribers
101
+ * Subscribe to this observable to receive all events
176
102
  */
177
- setLocal<T>(key: string, value: T): boolean;
103
+ onePlusNEvents: ReplaySubject<EventType>;
178
104
  /**
179
- * Get item from localStorage with JSON deserialization
105
+ * mitt event emitter instance
106
+ * Lightweight event emitter library
180
107
  */
181
- getLocal<T>(key: string, defaultValue?: T): T | null;
182
- /**
183
- * Remove item from localStorage
184
- */
185
- removeLocal(key: string): void;
186
- /**
187
- * Clear all localStorage items
188
- */
189
- clearLocal(): void;
190
- /**
191
- * Check if key exists in localStorage
192
- */
193
- hasLocal(key: string): boolean;
194
- /**
195
- * Get all localStorage keys
196
- */
197
- getLocalKeys(): string[];
198
- /**
199
- * Set item in sessionStorage with JSON serialization
200
- */
201
- setSession<T>(key: string, value: T): boolean;
202
- /**
203
- * Get item from sessionStorage with JSON deserialization
204
- */
205
- getSession<T>(key: string, defaultValue?: T): T | null;
206
- /**
207
- * Remove item from sessionStorage
208
- */
209
- removeSession(key: string): void;
210
- /**
211
- * Clear all sessionStorage items
212
- */
213
- clearSession(): void;
214
- /**
215
- * Check if key exists in sessionStorage
216
- */
217
- hasSession(key: string): boolean;
218
- /**
219
- * Get all sessionStorage keys
220
- */
221
- getSessionKeys(): string[];
222
- /**
223
- * Set item with expiration time
224
- * @param key - Storage key
225
- * @param value - Value to store
226
- * @param expirationMs - Expiration time in milliseconds
227
- * @param useSession - Use sessionStorage instead of localStorage
228
- */
229
- setWithExpiration<T>(key: string, value: T, expirationMs: number, useSession?: boolean): boolean;
108
+ private emitter;
109
+ constructor();
230
110
  /**
231
- * Get item with expiration check
232
- * Returns null if item is expired
233
- */
234
- getWithExpiration<T>(key: string, useSession?: boolean): T | null;
111
+ * Send an event through the event bus
112
+ * The event will be forwarded to all subscribers via the ReplaySubject
113
+ *
114
+ * @param s - Event string, can be a simple event name or JSON stringified structured data
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * // Simple event
119
+ * eventBus.sendEvent('user:logout');
120
+ *
121
+ * // Structured event
122
+ * eventBus.sendEvent(JSON.stringify({
123
+ * type: 'auth:token_updated',
124
+ * payload: { token: 'abc123' },
125
+ * timestamp: new Date().toISOString()
126
+ * }));
127
+ * ```
128
+ */
129
+ sendEvent(s: string): void;
235
130
  }
236
131
 
237
132
  /**
238
- * Log level enum
239
- */
240
- declare enum LogLevel {
241
- DEBUG = 0,
242
- INFO = 1,
243
- WARN = 2,
244
- ERROR = 3,
245
- NONE = 4
133
+ * User information from ID token
134
+ * Standard OIDC claims compatible with Auth0
135
+ */
136
+ interface UserInfo {
137
+ sub: string;
138
+ name?: string;
139
+ email?: string;
140
+ email_verified?: boolean;
141
+ preferred_username?: string;
142
+ given_name?: string;
143
+ family_name?: string;
144
+ nickname?: string;
145
+ locale?: string;
146
+ picture?: string;
147
+ phone?: string;
148
+ phone_verified?: boolean;
149
+ updated_at?: string;
150
+ role?: string;
151
+ org?: string;
152
+ organization?: string;
153
+ [key: string]: any;
246
154
  }
247
155
  /**
248
- * Logger configuration
156
+ * Simplified user data extracted from token
249
157
  */
250
- interface LoggerConfig {
251
- level?: LogLevel;
252
- enableTimestamp?: boolean;
253
- enableStackTrace?: boolean;
254
- prefix?: string;
158
+ interface UserData {
159
+ id: string;
160
+ name: string;
161
+ email: string;
162
+ role: string;
163
+ org: string;
255
164
  }
256
165
  /**
257
- * Logger - Centralized logging utility
258
- * Framework-agnostic implementation using browser console APIs
259
- * Supports different log levels and can be configured globally
166
+ * Authentication service for Auth0 integration
167
+ * Handles login, logout, token management, and user session
168
+ * Uses sessionStorage for sensitive data and emits authentication events for MicroApps
260
169
  *
261
- * @example
262
- * ```typescript
263
- * const logger = new Logger();
170
+ * Configuration is centralized in config/auth.config.ts for easy management
264
171
  *
265
- * // Configure
266
- * logger.configure({
267
- * level: LogLevel.DEBUG,
268
- * enableTimestamp: true,
269
- * prefix: 'MyApp'
270
- * });
271
- *
272
- * // Use
273
- * logger.info('User logged in', { userId: '123' });
274
- * logger.error('Failed to load data', error);
275
- * ```
172
+ * NOTE: All navigation logic using setTimeout is commented out as per requirements.
173
+ * To enable navigation after auth operations, uncomment the marked sections in consuming components.
276
174
  */
277
- declare class Logger {
278
- private config;
279
- /**
280
- * Configure the logger
281
- */
282
- configure(config: LoggerConfig): void;
175
+ declare class AuthService {
176
+ private http;
177
+ private eventBus;
178
+ id: string;
179
+ private readonly STANDARD_JWT_CLAIMS;
180
+ private auth0Client;
181
+ private initializationPromise;
182
+ private userSubject;
183
+ user$: Observable<UserInfo | null>;
184
+ constructor(http: HttpClient, eventBus: EventBusService);
283
185
  /**
284
- * Set log level
186
+ * Initialize Auth0 client
285
187
  */
286
- setLevel(level: LogLevel): void;
188
+ private initializeAuth0;
287
189
  /**
288
- * Get current log level
190
+ * Ensure Auth0 client is initialized before use
289
191
  */
290
- getLevel(): LogLevel;
192
+ private ensureInitialized;
291
193
  /**
292
- * Format log message with timestamp and prefix
194
+ * Login with Auth0
195
+ * Redirects to Auth0 Universal Login
196
+ * Preserves current URL parameters (like invitation tokens) through the auth flow
197
+ *
198
+ * @param user - Optional user identifier for logging
199
+ * @param options - Optional login options including invitation and organization parameters
293
200
  */
294
- private formatMessage;
201
+ login(user?: string, options?: {
202
+ invitation?: string;
203
+ organization?: string;
204
+ }): Promise<void>;
295
205
  /**
296
- * Check if log level should be logged
206
+ * Handle OAuth2 callback after successful authorization
207
+ * Processes the callback and retrieves user info
208
+ *
209
+ * NOTE: Navigation after successful/failed authentication should be handled in the calling component
210
+ * using setTimeout. See commented examples in app.component.ts
211
+ *
212
+ * @returns Promise<{ success: boolean, appState?: any }> - Success status and preserved appState
297
213
  */
298
- private shouldLog;
214
+ handleCallback(): Promise<{
215
+ success: boolean;
216
+ appState?: any;
217
+ }>;
299
218
  /**
300
- * Log debug message
219
+ * Log all user claims for debugging
220
+ * @param user - User info from Auth0
301
221
  */
302
- debug(message: string, ...args: any[]): void;
222
+ private logUserClaims;
303
223
  /**
304
- * Log info message
224
+ * Log standard OIDC claims
225
+ * @param user - User info from Auth0
305
226
  */
306
- info(message: string, ...args: any[]): void;
227
+ private logStandardClaims;
307
228
  /**
308
- * Log warning message
229
+ * Log claims with consistent formatting
230
+ * @param header - Section header to display
231
+ * @param claims - Array of claim keys to log
232
+ * @param user - User info object
309
233
  */
310
- warn(message: string, ...args: any[]): void;
234
+ private logClaims;
311
235
  /**
312
- * Log error message
236
+ * Get custom namespaced claims from user info
237
+ * @param user - User info object
238
+ * @returns Array of custom claim keys
313
239
  */
314
- error(message: string, error?: any, ...args: any[]): void;
240
+ private getCustomClaims;
315
241
  /**
316
- * Log a group of messages
242
+ * Get additional non-namespaced claims from user info
243
+ * @param user - User info object
244
+ * @returns Array of additional claim keys
317
245
  */
318
- group(label: string, callback: () => void): void;
246
+ private getAdditionalClaims;
319
247
  /**
320
- * Log a collapsed group of messages
248
+ * Check if a claim key is namespaced
249
+ * @param key - Claim key to check
250
+ * @returns True if the key starts with http:// or https://
321
251
  */
322
- groupCollapsed(label: string, callback: () => void): void;
252
+ private isNamespacedClaim;
323
253
  /**
324
- * Log a table (useful for arrays of objects)
254
+ * Logout user and clear authentication state
255
+ * Redirects to Auth0 logout endpoint and clears local state
325
256
  */
326
- table(data: any, columns?: string[]): void;
327
- /**
328
- * Log execution time of a function
329
- */
330
- time<T>(label: string, fn: () => Promise<T> | T): Promise<T>;
331
- }
332
-
333
- /**
334
- * NgEventEmitter - Angular service wrapper for EventBus
335
- * Provides Angular dependency injection support for the framework-agnostic EventBus
336
- *
337
- * @example
338
- * ```typescript
339
- * import { Component, inject } from '@angular/core';
340
- * import { NgEventEmitter } from 'common-libs';
341
- *
342
- * @Component({
343
- * selector: 'app-example',
344
- * template: '...'
345
- * })
346
- * export class ExampleComponent {
347
- * private eventEmitter = inject(NgEventEmitter);
348
- *
349
- * ngOnInit() {
350
- * this.eventEmitter.on('user:login').subscribe(data => {
351
- * console.log('User logged in:', data);
352
- * });
353
- * }
354
- *
355
- * login() {
356
- * this.eventEmitter.emit('user:login', { userId: '123' });
357
- * }
358
- * }
359
- * ```
360
- */
361
- declare class NgEventEmitter extends EventBus {
362
- constructor();
363
- }
364
-
365
- /**
366
- * TokenService - Angular service wrapper for TokenManager
367
- * Provides Angular dependency injection support for the framework-agnostic TokenManager
368
- *
369
- * @example
370
- * ```typescript
371
- * import { Component, inject } from '@angular/core';
372
- * import { TokenService } from 'common-libs';
373
- *
374
- * export class AuthService {
375
- * private tokenService = inject(TokenService);
376
- *
377
- * login(token: string) {
378
- * this.tokenService.setToken(token);
379
- * }
380
- *
381
- * isAuthenticated(): boolean {
382
- * return this.tokenService.isAuthenticated();
383
- * }
384
- * }
385
- * ```
386
- */
387
- declare class TokenService extends TokenManager {
388
- constructor();
389
- }
390
-
391
- /**
392
- * StorageService - Angular service wrapper for StorageManager
393
- * Provides Angular dependency injection support for the framework-agnostic StorageManager
394
- *
395
- * @example
396
- * ```typescript
397
- * import { Component, inject } from '@angular/core';
398
- * import { StorageService } from 'common-libs';
399
- *
400
- * export class UserPreferencesService {
401
- * private storage = inject(StorageService);
402
- *
403
- * savePreferences(prefs: any) {
404
- * this.storage.setLocal('user-prefs', prefs);
405
- * }
406
- *
407
- * getPreferences() {
408
- * return this.storage.getLocal('user-prefs');
409
- * }
410
- * }
411
- * ```
412
- */
413
- declare class StorageService extends StorageManager {
414
- constructor();
415
- }
416
-
417
- /**
418
- * LoggerService - Angular service wrapper for Logger
419
- * Provides Angular dependency injection support for the framework-agnostic Logger
420
- *
421
- * @example
422
- * ```typescript
423
- * import { Component, inject } from '@angular/core';
424
- * import { LoggerService, LogLevel } from 'common-libs';
425
- *
426
- * export class MyService {
427
- * private logger = inject(LoggerService);
428
- *
429
- * constructor() {
430
- * this.logger.configure({
431
- * level: LogLevel.DEBUG,
432
- * prefix: 'MyApp'
433
- * });
434
- * }
435
- *
436
- * doSomething() {
437
- * this.logger.info('Doing something');
438
- * }
439
- * }
440
- * ```
441
- */
442
- declare class LoggerService extends Logger {
443
- constructor();
444
- }
445
-
446
- /**
447
- * PermissionService - Manages user permissions and roles
448
- */
449
- declare class PermissionService {
450
- private tokenService;
257
+ logout(): Promise<void>;
451
258
  /**
452
- * Check if user has a specific permission
259
+ * Get current access token from storage or Auth0 client
260
+ * @returns string | null - Access token or null if not authenticated
453
261
  */
454
- hasPermission(permission: string): boolean;
262
+ getToken(): Promise<string | null>;
455
263
  /**
456
- * Check if user has any of the specified permissions
264
+ * Get current access token synchronously from storage only
265
+ * Use this for synchronous operations like interceptors
266
+ * @returns string | null - Access token or null if not authenticated
457
267
  */
458
- hasAnyPermission(permissions: string[]): boolean;
268
+ getTokenSync(): string | null;
459
269
  /**
460
- * Check if user has all of the specified permissions
270
+ * Set access token in storage and emit event for MicroApps
271
+ * @param token - Access token to store
461
272
  */
462
- hasAllPermissions(permissions: string[]): boolean;
273
+ private setToken;
463
274
  /**
464
- * Check if user has a specific role
275
+ * Check if user is authenticated
276
+ * @returns boolean - True if user has valid token
465
277
  */
466
- hasRole(role: string): boolean;
278
+ isAuthenticated(): Promise<boolean>;
467
279
  /**
468
- * Check if user has any of the specified roles
280
+ * Check if user is authenticated synchronously
281
+ * Only checks storage, doesn't verify with Auth0
282
+ * @returns boolean - True if user has token in storage
469
283
  */
470
- hasAnyRole(roles: string[]): boolean;
284
+ isAuthenticatedSync(): boolean;
471
285
  /**
472
- * Check if user has all of the specified roles
286
+ * Get current user information
287
+ * @returns UserInfo | null - Current user or null if not authenticated
473
288
  */
474
- hasAllRoles(roles: string[]): boolean;
289
+ getUser(): UserInfo | null;
475
290
  /**
476
- * Get all user permissions
291
+ * Get simplified user data from token
292
+ * Extracts user details, role, and organization from ID token claims
293
+ * Checks both top-level claims and namespaced custom claims
294
+ * @returns UserData | null - Simplified user data or null if not authenticated
477
295
  */
478
- getPermissions(): string[];
296
+ getUserData(): UserData | null;
479
297
  /**
480
- * Get all user roles
298
+ * Extract claim value from user info, checking both direct properties and namespaced custom claims
299
+ * @param userInfo - User info object
300
+ * @param claimNames - Single claim name or array of claim names to search for
301
+ * @param defaultValue - Default value if claim is not found
302
+ * @returns Extracted claim value or default value
481
303
  */
482
- getRoles(): string[];
304
+ private extractClaimValue;
483
305
  /**
484
- * Get user ID from token
306
+ * Get user information from storage
307
+ * @returns UserInfo | null - Stored user info or null
485
308
  */
486
- getUserId(): string | null;
309
+ private getUserInfoFromStorage;
487
310
  /**
488
- * Get username from token
311
+ * Set user information in storage, update observable and emit event for MicroApps
312
+ * Logs all Auth0 claims for debugging
313
+ * @param userInfo - User information to store
489
314
  */
490
- getUsername(): string | null;
315
+ private setUserInfo;
491
316
  /**
492
- * Get user email from token
317
+ * Emit authentication event for MicroApps to consume
318
+ * Events are emitted via EventBus for cross-MFE communication
319
+ * @param eventType - Type of authentication event
320
+ * @param payload - Event payload
493
321
  */
494
- getUserEmail(): string | null;
322
+ private emitAuthEvent;
495
323
  }
496
324
 
497
325
  /**
498
- * Auth guard configuration
499
- */
500
- interface AuthGuardConfig {
501
- redirectUrl?: string;
502
- checkExpiration?: boolean;
503
- }
504
- /**
505
- * Factory function to create an auth guard with configuration
326
+ * Auth0 Configuration
327
+ * Centralized configuration for Auth0 integration
506
328
  *
507
- * @example
508
- * ```typescript
509
- * // In routes
510
- * {
511
- * path: 'dashboard',
512
- * component: DashboardComponent,
513
- * canActivate: [createAuthGuard({ redirectUrl: '/login' })]
514
- * }
515
- * ```
329
+ * Environment variables are typically set in consuming applications
330
+ * Default values are provided for development/testing
516
331
  */
517
- declare function createAuthGuard(config?: AuthGuardConfig): CanActivateFn;
518
332
  /**
519
- * Default auth guard - redirects to '/login' if not authenticated
333
+ * Auth0 client configuration
334
+ * Override these values in your consuming application by setting them before importing AuthService
520
335
  */
521
- declare const authGuard: CanActivateFn;
336
+ declare const AUTH0_CONFIG: {
337
+ domain: string;
338
+ clientId: string;
339
+ redirectUri: string;
340
+ logoutUri: string;
341
+ audience: string;
342
+ scope: string;
343
+ connection: string | undefined;
344
+ };
522
345
  /**
523
- * Permission-based guard factory
524
- * Checks if user has required permissions from token
525
- *
526
- * @example
527
- * ```typescript
528
- * {
529
- * path: 'admin',
530
- * component: AdminComponent,
531
- * canActivate: [createPermissionGuard(['admin', 'editor'])]
532
- * }
533
- * ```
346
+ * Storage configuration
347
+ * Controls where sensitive data is stored
534
348
  */
535
- declare function createPermissionGuard(requiredPermissions: string[], config?: AuthGuardConfig): CanActivateFn;
349
+ declare const STORAGE_CONFIG: {
350
+ TOKEN_STORAGE: "localStorage" | "sessionStorage";
351
+ USER_INFO_STORAGE: "localStorage" | "sessionStorage";
352
+ };
536
353
  /**
537
- * Role-based guard factory
538
- * Checks if user has required role from token
539
- *
540
- * @example
541
- * ```typescript
542
- * {
543
- * path: 'admin',
544
- * component: AdminComponent,
545
- * canActivate: [createRoleGuard(['admin'])]
546
- * }
547
- * ```
354
+ * Storage keys for auth data
548
355
  */
549
- declare function createRoleGuard(requiredRoles: string[], config?: AuthGuardConfig): CanActivateFn;
550
-
551
- /**
552
- * Auth interceptor configuration
553
- */
554
- interface AuthInterceptorConfig {
555
- headerName?: string;
556
- tokenPrefix?: string;
557
- excludedUrls?: string[];
558
- }
559
- /**
560
- * Configure the auth interceptor
561
- */
562
- declare function configureAuthInterceptor(config: AuthInterceptorConfig): void;
563
- /**
564
- * Auth Interceptor - Automatically adds authentication token to HTTP requests
565
- *
566
- * @example
567
- * ```typescript
568
- * // In app.config.ts
569
- * export const appConfig: ApplicationConfig = {
570
- * providers: [
571
- * provideHttpClient(
572
- * withInterceptors([authInterceptor])
573
- * )
574
- * ]
575
- * };
576
- * ```
577
- */
578
- declare const authInterceptor: HttpInterceptorFn;
579
-
356
+ declare const STORAGE_KEYS: {
357
+ ACCESS_TOKEN: string;
358
+ USER_INFO: string;
359
+ };
580
360
  /**
581
- * Error handling configuration
361
+ * Helper functions for storage operations
362
+ * These work with both localStorage and sessionStorage
582
363
  */
583
- interface ErrorHandlingConfig {
584
- enableLogging?: boolean;
585
- retryAttempts?: number;
586
- retryDelay?: number;
587
- retryStatusCodes?: number[];
588
- excludedUrls?: string[];
589
- }
590
- /**
591
- * Configure the error handling interceptor
592
- */
593
- declare function configureErrorHandling(config: ErrorHandlingConfig): void;
594
- /**
595
- * Error handling interceptor - Handles HTTP errors and retries
596
- *
597
- * @example
598
- * ```typescript
599
- * // In app.config.ts
600
- * export const appConfig: ApplicationConfig = {
601
- * providers: [
602
- * provideHttpClient(
603
- * withInterceptors([errorHandlingInterceptor])
604
- * )
605
- * ]
606
- * };
607
- *
608
- * // Configure retry behavior
609
- * configureErrorHandling({
610
- * retryAttempts: 3,
611
- * retryDelay: 2000,
612
- * retryStatusCodes: [500, 502, 503]
613
- * });
614
- * ```
615
- */
616
- declare const errorHandlingInterceptor: HttpInterceptorFn;
617
- /**
618
- * HTTP Error class with additional context
619
- */
620
- declare class HttpError extends Error {
621
- status: number;
622
- statusText: string;
623
- url: string;
624
- originalError: HttpErrorResponse;
625
- constructor(status: number, statusText: string, url: string, originalError: HttpErrorResponse);
626
- }
627
- /**
628
- * Parse HTTP error and return user-friendly message
629
- */
630
- declare function parseHttpError(error: HttpErrorResponse): string;
631
- /**
632
- * Check if error is a network error
633
- */
634
- declare function isNetworkError(error: HttpErrorResponse): boolean;
635
- /**
636
- * Check if error is a server error (5xx)
637
- */
638
- declare function isServerError(error: HttpErrorResponse): boolean;
639
- /**
640
- * Check if error is a client error (4xx)
641
- */
642
- declare function isClientError(error: HttpErrorResponse): boolean;
643
-
644
- /**
645
- * Cache configuration
646
- */
647
- interface CacheConfig {
648
- enabled?: boolean;
649
- maxAge?: number;
650
- excludedUrls?: string[];
651
- cacheableUrls?: string[];
652
- cacheMethods?: string[];
653
- }
654
364
  /**
655
- * Configure the caching interceptor
365
+ * Get item from storage
366
+ * @param key - Storage key
367
+ * @param storageType - Type of storage to use
368
+ * @returns Stored value or null
656
369
  */
657
- declare function configureCaching(config: CacheConfig): void;
370
+ declare function getStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): string | null;
658
371
  /**
659
- * Clear all cached entries
372
+ * Set item in storage
373
+ * @param key - Storage key
374
+ * @param value - Value to store
375
+ * @param storageType - Type of storage to use
660
376
  */
661
- declare function clearCache(): void;
377
+ declare function setStorageItem(key: string, value: string, storageType?: 'localStorage' | 'sessionStorage'): void;
662
378
  /**
663
- * Clear cache entry for specific URL
379
+ * Remove item from storage
380
+ * @param key - Storage key
381
+ * @param storageType - Type of storage to use
664
382
  */
665
- declare function clearCacheEntry(url: string): void;
383
+ declare function removeStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): void;
666
384
  /**
667
- * Caching interceptor - Caches HTTP GET requests
385
+ * Configure Auth0 settings
386
+ * Call this function in your consuming application before using AuthService
668
387
  *
669
388
  * @example
670
389
  * ```typescript
671
- * // In app.config.ts
672
- * export const appConfig: ApplicationConfig = {
673
- * providers: [
674
- * provideHttpClient(
675
- * withInterceptors([cachingInterceptor])
676
- * )
677
- * ]
678
- * };
390
+ * import { configureAuth0 } from '@opensourcekd/ng-common-libs';
679
391
  *
680
- * // Configure caching
681
- * configureCaching({
682
- * enabled: true,
683
- * maxAge: 300000, // 5 minutes
684
- * cacheableUrls: ['/api/users', '/api/products']
392
+ * configureAuth0({
393
+ * domain: 'your-domain.auth0.com',
394
+ * clientId: 'your-client-id',
395
+ * audience: 'https://your-api.com'
685
396
  * });
686
397
  * ```
687
398
  */
688
- declare const cachingInterceptor: HttpInterceptorFn;
399
+ declare function configureAuth0(config: Partial<typeof AUTH0_CONFIG>): void;
689
400
 
690
- export { EventBus, HttpError, LogLevel, Logger, LoggerService, NgEventEmitter, PermissionService, StorageManager, StorageService, TokenManager, TokenService, authGuard, authInterceptor, cachingInterceptor, clearCache, clearCacheEntry, configureAuthInterceptor, configureCaching, configureErrorHandling, createAuthGuard, createPermissionGuard, createRoleGuard, errorHandlingInterceptor, isClientError, isNetworkError, isServerError, parseHttpError };
691
- export type { AuthGuardConfig, AuthInterceptorConfig, CacheConfig, ErrorHandlingConfig, EventPayload, LoggerConfig, TokenConfig };
401
+ export { AUTH0_CONFIG, AuthService, EventBus, EventBusService, STORAGE_CONFIG, STORAGE_KEYS, configureAuth0, getStorageItem, removeStorageItem, setStorageItem };
402
+ export type { EventPayload, UserData, UserInfo };