@opensourcekd/ng-common-libs 1.2.4 → 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.mjs CHANGED
@@ -1,8 +1,7 @@
1
- import { Subject, ReplaySubject, BehaviorSubject, throwError, timer, Observable } from 'rxjs';
2
- import { filter, map, retry, catchError, tap } from 'rxjs/operators';
3
- import { Injectable, inject } from '@angular/core';
4
- import { HttpClient, HttpResponse } from '@angular/common/http';
5
- import { Router } from '@angular/router';
1
+ import { Subject, ReplaySubject, BehaviorSubject } from 'rxjs';
2
+ import { filter, map } from 'rxjs/operators';
3
+ import { Injectable } from '@angular/core';
4
+ import { HttpClient } from '@angular/common/http';
6
5
 
7
6
  /**
8
7
  * EventBus - A centralized event bus for application-wide communication
@@ -61,531 +60,6 @@ class EventBus {
61
60
  }
62
61
  }
63
62
 
64
- /**
65
- * TokenManager - Manages authentication tokens
66
- * Framework-agnostic implementation using browser storage APIs
67
- * Handles storage, retrieval, and validation of JWT tokens
68
- *
69
- * @example
70
- * ```typescript
71
- * const tokenManager = new TokenManager();
72
- *
73
- * // Store a token
74
- * tokenManager.setToken('your-jwt-token');
75
- *
76
- * // Check if authenticated
77
- * if (tokenManager.isAuthenticated()) {
78
- * const userData = tokenManager.getUserFromToken();
79
- * }
80
- * ```
81
- */
82
- class TokenManager {
83
- TOKEN_KEY = 'auth_token';
84
- REFRESH_TOKEN_KEY = 'refresh_token';
85
- useSessionStorage = false;
86
- /**
87
- * Configure token manager
88
- */
89
- configure(config) {
90
- if (config.tokenKey) {
91
- this.TOKEN_KEY = config.tokenKey;
92
- }
93
- if (config.refreshTokenKey) {
94
- this.REFRESH_TOKEN_KEY = config.refreshTokenKey;
95
- }
96
- if (config.useSessionStorage !== undefined) {
97
- this.useSessionStorage = config.useSessionStorage;
98
- }
99
- }
100
- /**
101
- * Get the storage mechanism based on configuration
102
- */
103
- getStorage() {
104
- return this.useSessionStorage ? sessionStorage : localStorage;
105
- }
106
- /**
107
- * Set authentication token
108
- */
109
- setToken(token) {
110
- this.getStorage().setItem(this.TOKEN_KEY, token);
111
- }
112
- /**
113
- * Get authentication token
114
- */
115
- getToken() {
116
- return this.getStorage().getItem(this.TOKEN_KEY);
117
- }
118
- /**
119
- * Remove authentication token
120
- */
121
- removeToken() {
122
- this.getStorage().removeItem(this.TOKEN_KEY);
123
- }
124
- /**
125
- * Set refresh token
126
- */
127
- setRefreshToken(token) {
128
- this.getStorage().setItem(this.REFRESH_TOKEN_KEY, token);
129
- }
130
- /**
131
- * Get refresh token
132
- */
133
- getRefreshToken() {
134
- return this.getStorage().getItem(this.REFRESH_TOKEN_KEY);
135
- }
136
- /**
137
- * Remove refresh token
138
- */
139
- removeRefreshToken() {
140
- this.getStorage().removeItem(this.REFRESH_TOKEN_KEY);
141
- }
142
- /**
143
- * Clear all tokens
144
- */
145
- clearTokens() {
146
- this.removeToken();
147
- this.removeRefreshToken();
148
- }
149
- /**
150
- * Check if token exists
151
- */
152
- hasToken() {
153
- return !!this.getToken();
154
- }
155
- /**
156
- * Decode JWT token (without verification)
157
- * @param token - JWT token to decode
158
- * @returns Decoded token payload or null if invalid
159
- */
160
- decodeToken(token) {
161
- const tokenToDecode = token || this.getToken();
162
- if (!tokenToDecode)
163
- return null;
164
- try {
165
- const parts = tokenToDecode.split('.');
166
- if (parts.length !== 3)
167
- return null;
168
- const payload = parts[1];
169
- const decoded = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
170
- return decoded;
171
- }
172
- catch (error) {
173
- console.error('Error decoding token:', error);
174
- return null;
175
- }
176
- }
177
- /**
178
- * Check if token is expired
179
- * @param token - Optional token to check (defaults to stored token)
180
- * @returns true if token is expired or invalid
181
- */
182
- isTokenExpired(token) {
183
- const decoded = this.decodeToken(token);
184
- if (!decoded || !decoded.exp)
185
- return true;
186
- const expirationDate = new Date(decoded.exp * 1000);
187
- return expirationDate <= new Date();
188
- }
189
- /**
190
- * Check if user is authenticated (has valid, non-expired token)
191
- */
192
- isAuthenticated() {
193
- return this.hasToken() && !this.isTokenExpired();
194
- }
195
- /**
196
- * Get token expiration date
197
- */
198
- getTokenExpirationDate(token) {
199
- const decoded = this.decodeToken(token);
200
- if (!decoded || !decoded.exp)
201
- return null;
202
- return new Date(decoded.exp * 1000);
203
- }
204
- /**
205
- * Get user data from token
206
- */
207
- getUserFromToken(token) {
208
- return this.decodeToken(token);
209
- }
210
- }
211
-
212
- /**
213
- * StorageManager - Type-safe wrapper for browser storage
214
- * Framework-agnostic implementation using browser storage APIs
215
- * Provides JSON serialization/deserialization and error handling
216
- *
217
- * @example
218
- * ```typescript
219
- * const storage = new StorageManager();
220
- *
221
- * // Store data
222
- * storage.setLocal('user-prefs', { theme: 'dark', lang: 'en' });
223
- *
224
- * // Retrieve data
225
- * const prefs = storage.getLocal('user-prefs');
226
- *
227
- * // With expiration
228
- * storage.setWithExpiration('temp-data', someData, 3600000); // 1 hour
229
- * ```
230
- */
231
- class StorageManager {
232
- /**
233
- * Set item in localStorage with JSON serialization
234
- */
235
- setLocal(key, value) {
236
- try {
237
- const serialized = JSON.stringify(value);
238
- localStorage.setItem(key, serialized);
239
- return true;
240
- }
241
- catch (error) {
242
- console.error('Error setting localStorage item:', error);
243
- return false;
244
- }
245
- }
246
- /**
247
- * Get item from localStorage with JSON deserialization
248
- */
249
- getLocal(key, defaultValue) {
250
- try {
251
- const item = localStorage.getItem(key);
252
- if (item === null) {
253
- return defaultValue !== undefined ? defaultValue : null;
254
- }
255
- return JSON.parse(item);
256
- }
257
- catch (error) {
258
- console.error('Error getting localStorage item:', error);
259
- return defaultValue !== undefined ? defaultValue : null;
260
- }
261
- }
262
- /**
263
- * Remove item from localStorage
264
- */
265
- removeLocal(key) {
266
- try {
267
- localStorage.removeItem(key);
268
- }
269
- catch (error) {
270
- console.error('Error removing localStorage item:', error);
271
- }
272
- }
273
- /**
274
- * Clear all localStorage items
275
- */
276
- clearLocal() {
277
- try {
278
- localStorage.clear();
279
- }
280
- catch (error) {
281
- console.error('Error clearing localStorage:', error);
282
- }
283
- }
284
- /**
285
- * Check if key exists in localStorage
286
- */
287
- hasLocal(key) {
288
- try {
289
- return localStorage.getItem(key) !== null;
290
- }
291
- catch (error) {
292
- console.error('Error checking localStorage key:', error);
293
- return false;
294
- }
295
- }
296
- /**
297
- * Get all localStorage keys
298
- */
299
- getLocalKeys() {
300
- try {
301
- return Object.keys(localStorage);
302
- }
303
- catch (error) {
304
- console.error('Error getting localStorage keys:', error);
305
- return [];
306
- }
307
- }
308
- /**
309
- * Set item in sessionStorage with JSON serialization
310
- */
311
- setSession(key, value) {
312
- try {
313
- const serialized = JSON.stringify(value);
314
- sessionStorage.setItem(key, serialized);
315
- return true;
316
- }
317
- catch (error) {
318
- console.error('Error setting sessionStorage item:', error);
319
- return false;
320
- }
321
- }
322
- /**
323
- * Get item from sessionStorage with JSON deserialization
324
- */
325
- getSession(key, defaultValue) {
326
- try {
327
- const item = sessionStorage.getItem(key);
328
- if (item === null) {
329
- return defaultValue !== undefined ? defaultValue : null;
330
- }
331
- return JSON.parse(item);
332
- }
333
- catch (error) {
334
- console.error('Error getting sessionStorage item:', error);
335
- return defaultValue !== undefined ? defaultValue : null;
336
- }
337
- }
338
- /**
339
- * Remove item from sessionStorage
340
- */
341
- removeSession(key) {
342
- try {
343
- sessionStorage.removeItem(key);
344
- }
345
- catch (error) {
346
- console.error('Error removing sessionStorage item:', error);
347
- }
348
- }
349
- /**
350
- * Clear all sessionStorage items
351
- */
352
- clearSession() {
353
- try {
354
- sessionStorage.clear();
355
- }
356
- catch (error) {
357
- console.error('Error clearing sessionStorage:', error);
358
- }
359
- }
360
- /**
361
- * Check if key exists in sessionStorage
362
- */
363
- hasSession(key) {
364
- try {
365
- return sessionStorage.getItem(key) !== null;
366
- }
367
- catch (error) {
368
- console.error('Error checking sessionStorage key:', error);
369
- return false;
370
- }
371
- }
372
- /**
373
- * Get all sessionStorage keys
374
- */
375
- getSessionKeys() {
376
- try {
377
- return Object.keys(sessionStorage);
378
- }
379
- catch (error) {
380
- console.error('Error getting sessionStorage keys:', error);
381
- return [];
382
- }
383
- }
384
- /**
385
- * Set item with expiration time
386
- * @param key - Storage key
387
- * @param value - Value to store
388
- * @param expirationMs - Expiration time in milliseconds
389
- * @param useSession - Use sessionStorage instead of localStorage
390
- */
391
- setWithExpiration(key, value, expirationMs, useSession = false) {
392
- const item = {
393
- value,
394
- expiration: Date.now() + expirationMs
395
- };
396
- return useSession
397
- ? this.setSession(key, item)
398
- : this.setLocal(key, item);
399
- }
400
- /**
401
- * Get item with expiration check
402
- * Returns null if item is expired
403
- */
404
- getWithExpiration(key, useSession = false) {
405
- const item = useSession
406
- ? this.getSession(key)
407
- : this.getLocal(key);
408
- if (!item)
409
- return null;
410
- if (Date.now() > item.expiration) {
411
- // Item expired, remove it
412
- if (useSession) {
413
- this.removeSession(key);
414
- }
415
- else {
416
- this.removeLocal(key);
417
- }
418
- return null;
419
- }
420
- return item.value;
421
- }
422
- }
423
-
424
- /**
425
- * Log level enum
426
- */
427
- var LogLevel;
428
- (function (LogLevel) {
429
- LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
430
- LogLevel[LogLevel["INFO"] = 1] = "INFO";
431
- LogLevel[LogLevel["WARN"] = 2] = "WARN";
432
- LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
433
- LogLevel[LogLevel["NONE"] = 4] = "NONE";
434
- })(LogLevel || (LogLevel = {}));
435
- /**
436
- * Logger - Centralized logging utility
437
- * Framework-agnostic implementation using browser console APIs
438
- * Supports different log levels and can be configured globally
439
- *
440
- * @example
441
- * ```typescript
442
- * const logger = new Logger();
443
- *
444
- * // Configure
445
- * logger.configure({
446
- * level: LogLevel.DEBUG,
447
- * enableTimestamp: true,
448
- * prefix: 'MyApp'
449
- * });
450
- *
451
- * // Use
452
- * logger.info('User logged in', { userId: '123' });
453
- * logger.error('Failed to load data', error);
454
- * ```
455
- */
456
- class Logger {
457
- config = {
458
- level: LogLevel.INFO,
459
- enableTimestamp: true,
460
- enableStackTrace: false,
461
- prefix: ''
462
- };
463
- /**
464
- * Configure the logger
465
- */
466
- configure(config) {
467
- this.config = { ...this.config, ...config };
468
- }
469
- /**
470
- * Set log level
471
- */
472
- setLevel(level) {
473
- this.config.level = level;
474
- }
475
- /**
476
- * Get current log level
477
- */
478
- getLevel() {
479
- return this.config.level;
480
- }
481
- /**
482
- * Format log message with timestamp and prefix
483
- */
484
- formatMessage(message, level) {
485
- const parts = [];
486
- if (this.config.enableTimestamp) {
487
- parts.push(`[${new Date().toISOString()}]`);
488
- }
489
- if (this.config.prefix) {
490
- parts.push(`[${this.config.prefix}]`);
491
- }
492
- parts.push(`[${level}]`);
493
- parts.push(message);
494
- return parts.join(' ');
495
- }
496
- /**
497
- * Check if log level should be logged
498
- */
499
- shouldLog(level) {
500
- return level >= this.config.level;
501
- }
502
- /**
503
- * Log debug message
504
- */
505
- debug(message, ...args) {
506
- if (this.shouldLog(LogLevel.DEBUG)) {
507
- console.debug(this.formatMessage(message, 'DEBUG'), ...args);
508
- }
509
- }
510
- /**
511
- * Log info message
512
- */
513
- info(message, ...args) {
514
- if (this.shouldLog(LogLevel.INFO)) {
515
- console.info(this.formatMessage(message, 'INFO'), ...args);
516
- }
517
- }
518
- /**
519
- * Log warning message
520
- */
521
- warn(message, ...args) {
522
- if (this.shouldLog(LogLevel.WARN)) {
523
- console.warn(this.formatMessage(message, 'WARN'), ...args);
524
- }
525
- }
526
- /**
527
- * Log error message
528
- */
529
- error(message, error, ...args) {
530
- if (this.shouldLog(LogLevel.ERROR)) {
531
- console.error(this.formatMessage(message, 'ERROR'), ...args);
532
- if (error) {
533
- console.error(error);
534
- if (this.config.enableStackTrace && error?.stack) {
535
- console.error('Stack trace:', error.stack);
536
- }
537
- }
538
- }
539
- }
540
- /**
541
- * Log a group of messages
542
- */
543
- group(label, callback) {
544
- if (this.shouldLog(LogLevel.INFO)) {
545
- console.group(this.formatMessage(label, 'GROUP'));
546
- callback();
547
- console.groupEnd();
548
- }
549
- }
550
- /**
551
- * Log a collapsed group of messages
552
- */
553
- groupCollapsed(label, callback) {
554
- if (this.shouldLog(LogLevel.INFO)) {
555
- console.groupCollapsed(this.formatMessage(label, 'GROUP'));
556
- callback();
557
- console.groupEnd();
558
- }
559
- }
560
- /**
561
- * Log a table (useful for arrays of objects)
562
- */
563
- table(data, columns) {
564
- if (this.shouldLog(LogLevel.INFO)) {
565
- console.table(data, columns);
566
- }
567
- }
568
- /**
569
- * Log execution time of a function
570
- */
571
- async time(label, fn) {
572
- const start = performance.now();
573
- try {
574
- const result = await fn();
575
- const end = performance.now();
576
- const duration = (end - start).toFixed(2);
577
- this.info(`${label} completed in ${duration}ms`);
578
- return result;
579
- }
580
- catch (error) {
581
- const end = performance.now();
582
- const duration = (end - start).toFixed(2);
583
- this.error(`${label} failed after ${duration}ms`, error);
584
- throw error;
585
- }
586
- }
587
- }
588
-
589
63
  /******************************************************************************
590
64
  Copyright (c) Microsoft Corporation.
591
65
 
@@ -619,239 +93,6 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
619
93
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
620
94
  };
621
95
 
622
- /**
623
- * NgEventEmitter - Angular service wrapper for EventBus
624
- * Provides Angular dependency injection support for the framework-agnostic EventBus
625
- *
626
- * @example
627
- * ```typescript
628
- * import { Component, inject } from '@angular/core';
629
- * import { NgEventEmitter } from 'common-libs';
630
- *
631
- * @Component({
632
- * selector: 'app-example',
633
- * template: '...'
634
- * })
635
- * export class ExampleComponent {
636
- * private eventEmitter = inject(NgEventEmitter);
637
- *
638
- * ngOnInit() {
639
- * this.eventEmitter.on('user:login').subscribe(data => {
640
- * console.log('User logged in:', data);
641
- * });
642
- * }
643
- *
644
- * login() {
645
- * this.eventEmitter.emit('user:login', { userId: '123' });
646
- * }
647
- * }
648
- * ```
649
- */
650
- let NgEventEmitter = class NgEventEmitter extends EventBus {
651
- constructor() {
652
- super();
653
- }
654
- };
655
- NgEventEmitter = __decorate([
656
- Injectable({
657
- providedIn: 'root'
658
- }),
659
- __metadata("design:paramtypes", [])
660
- ], NgEventEmitter);
661
-
662
- /**
663
- * TokenService - Angular service wrapper for TokenManager
664
- * Provides Angular dependency injection support for the framework-agnostic TokenManager
665
- *
666
- * @example
667
- * ```typescript
668
- * import { Component, inject } from '@angular/core';
669
- * import { TokenService } from 'common-libs';
670
- *
671
- * export class AuthService {
672
- * private tokenService = inject(TokenService);
673
- *
674
- * login(token: string) {
675
- * this.tokenService.setToken(token);
676
- * }
677
- *
678
- * isAuthenticated(): boolean {
679
- * return this.tokenService.isAuthenticated();
680
- * }
681
- * }
682
- * ```
683
- */
684
- let TokenService = class TokenService extends TokenManager {
685
- constructor() {
686
- console.log("In TokenService of opensourcekd 2");
687
- super();
688
- }
689
- };
690
- TokenService = __decorate([
691
- Injectable({
692
- providedIn: 'root'
693
- }),
694
- __metadata("design:paramtypes", [])
695
- ], TokenService);
696
-
697
- /**
698
- * StorageService - Angular service wrapper for StorageManager
699
- * Provides Angular dependency injection support for the framework-agnostic StorageManager
700
- *
701
- * @example
702
- * ```typescript
703
- * import { Component, inject } from '@angular/core';
704
- * import { StorageService } from 'common-libs';
705
- *
706
- * export class UserPreferencesService {
707
- * private storage = inject(StorageService);
708
- *
709
- * savePreferences(prefs: any) {
710
- * this.storage.setLocal('user-prefs', prefs);
711
- * }
712
- *
713
- * getPreferences() {
714
- * return this.storage.getLocal('user-prefs');
715
- * }
716
- * }
717
- * ```
718
- */
719
- let StorageService = class StorageService extends StorageManager {
720
- constructor() {
721
- super();
722
- }
723
- };
724
- StorageService = __decorate([
725
- Injectable({
726
- providedIn: 'root'
727
- }),
728
- __metadata("design:paramtypes", [])
729
- ], StorageService);
730
-
731
- /**
732
- * LoggerService - Angular service wrapper for Logger
733
- * Provides Angular dependency injection support for the framework-agnostic Logger
734
- *
735
- * @example
736
- * ```typescript
737
- * import { Component, inject } from '@angular/core';
738
- * import { LoggerService, LogLevel } from 'common-libs';
739
- *
740
- * export class MyService {
741
- * private logger = inject(LoggerService);
742
- *
743
- * constructor() {
744
- * this.logger.configure({
745
- * level: LogLevel.DEBUG,
746
- * prefix: 'MyApp'
747
- * });
748
- * }
749
- *
750
- * doSomething() {
751
- * this.logger.info('Doing something');
752
- * }
753
- * }
754
- * ```
755
- */
756
- let LoggerService = class LoggerService extends Logger {
757
- constructor() {
758
- super();
759
- }
760
- };
761
- LoggerService = __decorate([
762
- Injectable({
763
- providedIn: 'root'
764
- }),
765
- __metadata("design:paramtypes", [])
766
- ], LoggerService);
767
-
768
- /**
769
- * PermissionService - Manages user permissions and roles
770
- */
771
- let PermissionService = class PermissionService {
772
- tokenService = inject(TokenService);
773
- /**
774
- * Check if user has a specific permission
775
- */
776
- hasPermission(permission) {
777
- const user = this.tokenService.getUserFromToken();
778
- const permissions = user?.permissions || [];
779
- return permissions.includes(permission);
780
- }
781
- /**
782
- * Check if user has any of the specified permissions
783
- */
784
- hasAnyPermission(permissions) {
785
- return permissions.some(permission => this.hasPermission(permission));
786
- }
787
- /**
788
- * Check if user has all of the specified permissions
789
- */
790
- hasAllPermissions(permissions) {
791
- return permissions.every(permission => this.hasPermission(permission));
792
- }
793
- /**
794
- * Check if user has a specific role
795
- */
796
- hasRole(role) {
797
- const user = this.tokenService.getUserFromToken();
798
- const roles = user?.roles || [];
799
- return roles.includes(role);
800
- }
801
- /**
802
- * Check if user has any of the specified roles
803
- */
804
- hasAnyRole(roles) {
805
- return roles.some(role => this.hasRole(role));
806
- }
807
- /**
808
- * Check if user has all of the specified roles
809
- */
810
- hasAllRoles(roles) {
811
- return roles.every(role => this.hasRole(role));
812
- }
813
- /**
814
- * Get all user permissions
815
- */
816
- getPermissions() {
817
- const user = this.tokenService.getUserFromToken();
818
- return user?.permissions || [];
819
- }
820
- /**
821
- * Get all user roles
822
- */
823
- getRoles() {
824
- const user = this.tokenService.getUserFromToken();
825
- return user?.roles || [];
826
- }
827
- /**
828
- * Get user ID from token
829
- */
830
- getUserId() {
831
- const user = this.tokenService.getUserFromToken();
832
- return user?.sub || user?.id || user?.userId || null;
833
- }
834
- /**
835
- * Get username from token
836
- */
837
- getUsername() {
838
- const user = this.tokenService.getUserFromToken();
839
- return user?.username || user?.name || user?.email || null;
840
- }
841
- /**
842
- * Get user email from token
843
- */
844
- getUserEmail() {
845
- const user = this.tokenService.getUserFromToken();
846
- return user?.email || null;
847
- }
848
- };
849
- PermissionService = __decorate([
850
- Injectable({
851
- providedIn: 'root'
852
- })
853
- ], PermissionService);
854
-
855
96
  function mitt(n){return {all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e]);},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]));},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e);}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e);});}}}
856
97
 
857
98
  /**
@@ -1490,404 +731,5 @@ AuthService = __decorate([
1490
731
  EventBusService])
1491
732
  ], AuthService);
1492
733
 
1493
- /**
1494
- * Factory function to create an auth guard with configuration
1495
- *
1496
- * @example
1497
- * ```typescript
1498
- * // In routes
1499
- * {
1500
- * path: 'dashboard',
1501
- * component: DashboardComponent,
1502
- * canActivate: [createAuthGuard({ redirectUrl: '/login' })]
1503
- * }
1504
- * ```
1505
- */
1506
- function createAuthGuard(config = {}) {
1507
- return (route, state) => {
1508
- const tokenService = inject(TokenService);
1509
- const router = inject(Router);
1510
- const redirectUrl = config.redirectUrl || '/login';
1511
- const checkExpiration = config.checkExpiration !== false;
1512
- const hasToken = tokenService.hasToken();
1513
- const isExpired = checkExpiration ? tokenService.isTokenExpired() : false;
1514
- if (hasToken && !isExpired) {
1515
- return true;
1516
- }
1517
- // Store the attempted URL for redirecting after login
1518
- const returnUrl = state.url;
1519
- router.navigate([redirectUrl], {
1520
- queryParams: { returnUrl },
1521
- queryParamsHandling: 'merge'
1522
- });
1523
- return false;
1524
- };
1525
- }
1526
- /**
1527
- * Default auth guard - redirects to '/login' if not authenticated
1528
- */
1529
- const authGuard = createAuthGuard();
1530
- /**
1531
- * Permission-based guard factory
1532
- * Checks if user has required permissions from token
1533
- *
1534
- * @example
1535
- * ```typescript
1536
- * {
1537
- * path: 'admin',
1538
- * component: AdminComponent,
1539
- * canActivate: [createPermissionGuard(['admin', 'editor'])]
1540
- * }
1541
- * ```
1542
- */
1543
- function createPermissionGuard(requiredPermissions, config = {}) {
1544
- return (route, state) => {
1545
- const tokenService = inject(TokenService);
1546
- const router = inject(Router);
1547
- const redirectUrl = config.redirectUrl || '/unauthorized';
1548
- // First check authentication
1549
- if (!tokenService.isAuthenticated()) {
1550
- router.navigate(['/login'], {
1551
- queryParams: { returnUrl: state.url }
1552
- });
1553
- return false;
1554
- }
1555
- // Check permissions
1556
- const user = tokenService.getUserFromToken();
1557
- const userPermissions = user?.permissions || user?.roles || [];
1558
- const hasPermission = requiredPermissions.some(permission => userPermissions.includes(permission));
1559
- if (!hasPermission) {
1560
- router.navigate([redirectUrl]);
1561
- return false;
1562
- }
1563
- return true;
1564
- };
1565
- }
1566
- /**
1567
- * Role-based guard factory
1568
- * Checks if user has required role from token
1569
- *
1570
- * @example
1571
- * ```typescript
1572
- * {
1573
- * path: 'admin',
1574
- * component: AdminComponent,
1575
- * canActivate: [createRoleGuard(['admin'])]
1576
- * }
1577
- * ```
1578
- */
1579
- function createRoleGuard(requiredRoles, config = {}) {
1580
- return createPermissionGuard(requiredRoles, config);
1581
- }
1582
-
1583
- const defaultConfig$1 = {
1584
- headerName: 'Authorization',
1585
- tokenPrefix: 'Bearer',
1586
- excludedUrls: []
1587
- };
1588
- let interceptorConfig = { ...defaultConfig$1 };
1589
- /**
1590
- * Configure the auth interceptor
1591
- */
1592
- function configureAuthInterceptor(config) {
1593
- interceptorConfig = { ...defaultConfig$1, ...config };
1594
- }
1595
- /**
1596
- * Auth Interceptor - Automatically adds authentication token to HTTP requests
1597
- *
1598
- * @example
1599
- * ```typescript
1600
- * // In app.config.ts
1601
- * export const appConfig: ApplicationConfig = {
1602
- * providers: [
1603
- * provideHttpClient(
1604
- * withInterceptors([authInterceptor])
1605
- * )
1606
- * ]
1607
- * };
1608
- * ```
1609
- */
1610
- const authInterceptor = (req, next) => {
1611
- const tokenService = inject(TokenService);
1612
- const config = interceptorConfig;
1613
- // Check if URL should be excluded
1614
- const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
1615
- if (isExcluded) {
1616
- return next(req);
1617
- }
1618
- // Get token and add to request if available
1619
- const token = tokenService.getToken();
1620
- if (token) {
1621
- const authReq = req.clone({
1622
- setHeaders: {
1623
- [config.headerName]: `${config.tokenPrefix} ${token}`
1624
- }
1625
- });
1626
- return next(authReq);
1627
- }
1628
- return next(req);
1629
- };
1630
-
1631
- const defaultConfig = {
1632
- enableLogging: true,
1633
- retryAttempts: 0,
1634
- retryDelay: 1000,
1635
- retryStatusCodes: [408, 429, 500, 502, 503, 504],
1636
- excludedUrls: []
1637
- };
1638
- let errorConfig = { ...defaultConfig };
1639
- /**
1640
- * Configure the error handling interceptor
1641
- */
1642
- function configureErrorHandling(config) {
1643
- errorConfig = { ...defaultConfig, ...config };
1644
- }
1645
- /**
1646
- * Error handling interceptor - Handles HTTP errors and retries
1647
- *
1648
- * @example
1649
- * ```typescript
1650
- * // In app.config.ts
1651
- * export const appConfig: ApplicationConfig = {
1652
- * providers: [
1653
- * provideHttpClient(
1654
- * withInterceptors([errorHandlingInterceptor])
1655
- * )
1656
- * ]
1657
- * };
1658
- *
1659
- * // Configure retry behavior
1660
- * configureErrorHandling({
1661
- * retryAttempts: 3,
1662
- * retryDelay: 2000,
1663
- * retryStatusCodes: [500, 502, 503]
1664
- * });
1665
- * ```
1666
- */
1667
- const errorHandlingInterceptor = (req, next) => {
1668
- const logger = inject(LoggerService);
1669
- const config = errorConfig;
1670
- // Check if URL should be excluded
1671
- const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
1672
- if (isExcluded) {
1673
- return next(req);
1674
- }
1675
- return next(req).pipe(
1676
- // Retry logic with exponential backoff
1677
- retry({
1678
- count: config.retryAttempts,
1679
- delay: (error, retryCount) => {
1680
- // Only retry for specific status codes
1681
- if (!config.retryStatusCodes?.includes(error.status)) {
1682
- return throwError(() => error);
1683
- }
1684
- const delay = config.retryDelay * Math.pow(2, retryCount - 1);
1685
- if (config.enableLogging) {
1686
- logger.warn(`Retrying request (attempt ${retryCount}) after ${delay}ms`, { url: req.url, status: error.status });
1687
- }
1688
- return timer(delay);
1689
- }
1690
- }),
1691
- // Error handling
1692
- catchError((error) => {
1693
- if (config.enableLogging) {
1694
- logger.error('HTTP request failed', error, {
1695
- url: req.url,
1696
- status: error.status,
1697
- message: error.message
1698
- });
1699
- }
1700
- return throwError(() => error);
1701
- }));
1702
- };
1703
- /**
1704
- * HTTP Error class with additional context
1705
- */
1706
- class HttpError extends Error {
1707
- status;
1708
- statusText;
1709
- url;
1710
- originalError;
1711
- constructor(status, statusText, url, originalError) {
1712
- super(`HTTP ${status} ${statusText}: ${url}`);
1713
- this.status = status;
1714
- this.statusText = statusText;
1715
- this.url = url;
1716
- this.originalError = originalError;
1717
- this.name = 'HttpError';
1718
- }
1719
- }
1720
- /**
1721
- * Parse HTTP error and return user-friendly message
1722
- */
1723
- function parseHttpError(error) {
1724
- if (error.error instanceof ErrorEvent) {
1725
- // Client-side error
1726
- return `Network error: ${error.error.message}`;
1727
- }
1728
- else {
1729
- // Server-side error
1730
- const errorMessage = error.error?.message || error.message || 'Unknown error';
1731
- return `Server error (${error.status}): ${errorMessage}`;
1732
- }
1733
- }
1734
- /**
1735
- * Check if error is a network error
1736
- */
1737
- function isNetworkError(error) {
1738
- return error.error instanceof ErrorEvent || error.status === 0;
1739
- }
1740
- /**
1741
- * Check if error is a server error (5xx)
1742
- */
1743
- function isServerError(error) {
1744
- return error.status >= 500 && error.status < 600;
1745
- }
1746
- /**
1747
- * Check if error is a client error (4xx)
1748
- */
1749
- function isClientError(error) {
1750
- return error.status >= 400 && error.status < 500;
1751
- }
1752
-
1753
- const defaultCacheConfig = {
1754
- enabled: true,
1755
- maxAge: 60000, // 1 minute
1756
- excludedUrls: [],
1757
- cacheableUrls: [],
1758
- cacheMethods: ['GET']
1759
- };
1760
- let cacheConfig = { ...defaultCacheConfig };
1761
- const cache = new Map();
1762
- const MAX_CACHE_SIZE = 100; // Maximum number of cached entries
1763
- /**
1764
- * Configure the caching interceptor
1765
- */
1766
- function configureCaching(config) {
1767
- cacheConfig = { ...defaultCacheConfig, ...config };
1768
- }
1769
- /**
1770
- * Clean up expired cache entries
1771
- */
1772
- function cleanupCache() {
1773
- const now = Date.now();
1774
- const keysToDelete = [];
1775
- cache.forEach((entry, key) => {
1776
- const age = now - entry.timestamp;
1777
- if (age >= cacheConfig.maxAge) {
1778
- keysToDelete.push(key);
1779
- }
1780
- });
1781
- keysToDelete.forEach(key => cache.delete(key));
1782
- }
1783
- /**
1784
- * Evict oldest cache entry if cache is full
1785
- */
1786
- function evictOldestIfFull() {
1787
- if (cache.size >= MAX_CACHE_SIZE) {
1788
- let oldestKey = null;
1789
- let oldestTimestamp = Infinity;
1790
- cache.forEach((entry, key) => {
1791
- if (entry.timestamp < oldestTimestamp) {
1792
- oldestTimestamp = entry.timestamp;
1793
- oldestKey = key;
1794
- }
1795
- });
1796
- if (oldestKey) {
1797
- cache.delete(oldestKey);
1798
- }
1799
- }
1800
- }
1801
- /**
1802
- * Clear all cached entries
1803
- */
1804
- function clearCache() {
1805
- cache.clear();
1806
- }
1807
- /**
1808
- * Clear cache entry for specific URL
1809
- */
1810
- function clearCacheEntry(url) {
1811
- cache.delete(url);
1812
- }
1813
- /**
1814
- * Caching interceptor - Caches HTTP GET requests
1815
- *
1816
- * @example
1817
- * ```typescript
1818
- * // In app.config.ts
1819
- * export const appConfig: ApplicationConfig = {
1820
- * providers: [
1821
- * provideHttpClient(
1822
- * withInterceptors([cachingInterceptor])
1823
- * )
1824
- * ]
1825
- * };
1826
- *
1827
- * // Configure caching
1828
- * configureCaching({
1829
- * enabled: true,
1830
- * maxAge: 300000, // 5 minutes
1831
- * cacheableUrls: ['/api/users', '/api/products']
1832
- * });
1833
- * ```
1834
- */
1835
- const cachingInterceptor = (req, next) => {
1836
- const logger = inject(LoggerService);
1837
- const config = cacheConfig;
1838
- // Only cache if enabled
1839
- if (!config.enabled) {
1840
- return next(req);
1841
- }
1842
- // Only cache specific methods (default: GET)
1843
- if (!config.cacheMethods?.includes(req.method)) {
1844
- return next(req);
1845
- }
1846
- // Check if URL should be excluded
1847
- const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
1848
- if (isExcluded) {
1849
- return next(req);
1850
- }
1851
- // Check if URL is explicitly cacheable (if list is provided)
1852
- if (config.cacheableUrls && config.cacheableUrls.length > 0) {
1853
- const isCacheable = config.cacheableUrls.some(url => req.url.includes(url));
1854
- if (!isCacheable) {
1855
- return next(req);
1856
- }
1857
- }
1858
- const cacheKey = req.urlWithParams;
1859
- // Check cache
1860
- const cached = cache.get(cacheKey);
1861
- if (cached) {
1862
- const age = Date.now() - cached.timestamp;
1863
- if (age < config.maxAge) {
1864
- logger.debug(`Cache hit for ${cacheKey}`, { age });
1865
- return new Observable(observer => {
1866
- observer.next(cached.response.clone());
1867
- observer.complete();
1868
- });
1869
- }
1870
- else {
1871
- // Cache expired
1872
- cache.delete(cacheKey);
1873
- }
1874
- }
1875
- // Clean up expired entries periodically
1876
- if (Math.random() < 0.1) { // 10% chance on each request
1877
- cleanupCache();
1878
- }
1879
- // Make request and cache response
1880
- return next(req).pipe(tap(event => {
1881
- if (event instanceof HttpResponse) {
1882
- evictOldestIfFull();
1883
- cache.set(cacheKey, {
1884
- response: event.clone(),
1885
- timestamp: Date.now()
1886
- });
1887
- logger.debug(`Cached response for ${cacheKey}`);
1888
- }
1889
- }));
1890
- };
1891
-
1892
- export { AUTH0_CONFIG, AuthService, EventBus, EventBusService, HttpError, LogLevel, Logger, LoggerService, NgEventEmitter, PermissionService, STORAGE_CONFIG, STORAGE_KEYS, StorageManager, StorageService, TokenManager, TokenService, authGuard, authInterceptor, cachingInterceptor, clearCache, clearCacheEntry, configureAuth0, configureAuthInterceptor, configureCaching, configureErrorHandling, createAuthGuard, createPermissionGuard, createRoleGuard, errorHandlingInterceptor, getStorageItem, isClientError, isNetworkError, isServerError, parseHttpError, removeStorageItem, setStorageItem };
734
+ export { AUTH0_CONFIG, AuthService, EventBus, EventBusService, STORAGE_CONFIG, STORAGE_KEYS, configureAuth0, getStorageItem, removeStorageItem, setStorageItem };
1893
735
  //# sourceMappingURL=index.mjs.map