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