@opensourcekd/ng-common-libs 1.1.8

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.
@@ -0,0 +1,1273 @@
1
+ 'use strict';
2
+
3
+ var core = require('@angular/core');
4
+ var rxjs = require('rxjs');
5
+ var operators = require('rxjs/operators');
6
+ var router = require('@angular/router');
7
+ var http = require('@angular/common/http');
8
+
9
+ /******************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
24
+
25
+
26
+ function __decorate(decorators, target, key, desc) {
27
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
28
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
29
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
30
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
31
+ }
32
+
33
+ function __metadata(metadataKey, metadataValue) {
34
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
35
+ }
36
+
37
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
38
+ var e = new Error(message);
39
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
40
+ };
41
+
42
+ /**
43
+ * EventBus - A centralized event bus for application-wide communication
44
+ * Framework-agnostic implementation using only RxJS
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * // Create an instance
49
+ * const eventBus = new EventBus();
50
+ *
51
+ * // Emit an event
52
+ * eventBus.emit('user:login', { userId: '123', username: 'john' });
53
+ *
54
+ * // Subscribe to an event
55
+ * eventBus.on('user:login').subscribe(data => {
56
+ * console.log('User logged in:', data);
57
+ * });
58
+ * ```
59
+ */
60
+ class EventBus {
61
+ eventSubject = new rxjs.Subject();
62
+ /**
63
+ * Emit an event with optional data
64
+ * @param eventType - The type/name of the event
65
+ * @param data - Optional data to send with the event
66
+ */
67
+ emit(eventType, data) {
68
+ this.eventSubject.next({
69
+ type: eventType,
70
+ data,
71
+ timestamp: Date.now()
72
+ });
73
+ }
74
+ /**
75
+ * Subscribe to a specific event type
76
+ * @param eventType - The type/name of the event to listen for
77
+ * @returns Observable that emits the event data
78
+ */
79
+ on(eventType) {
80
+ return this.eventSubject.asObservable().pipe(operators.filter(event => event.type === eventType), operators.map(event => event.data));
81
+ }
82
+ /**
83
+ * Subscribe to multiple event types
84
+ * @param eventTypes - Array of event types to listen for
85
+ * @returns Observable that emits the full event payload
86
+ */
87
+ onMultiple(eventTypes) {
88
+ return this.eventSubject.asObservable().pipe(operators.filter(event => eventTypes.includes(event.type)));
89
+ }
90
+ /**
91
+ * Subscribe to all events
92
+ * @returns Observable that emits all event payloads
93
+ */
94
+ onAll() {
95
+ return this.eventSubject.asObservable();
96
+ }
97
+ }
98
+
99
+ /**
100
+ * NgEventEmitter - Angular service wrapper for EventBus
101
+ * Provides Angular dependency injection support for the framework-agnostic EventBus
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import { Component, inject } from '@angular/core';
106
+ * import { NgEventEmitter } from 'common-libs';
107
+ *
108
+ * @Component({
109
+ * selector: 'app-example',
110
+ * template: '...'
111
+ * })
112
+ * export class ExampleComponent {
113
+ * private eventEmitter = inject(NgEventEmitter);
114
+ *
115
+ * ngOnInit() {
116
+ * this.eventEmitter.on('user:login').subscribe(data => {
117
+ * console.log('User logged in:', data);
118
+ * });
119
+ * }
120
+ *
121
+ * login() {
122
+ * this.eventEmitter.emit('user:login', { userId: '123' });
123
+ * }
124
+ * }
125
+ * ```
126
+ */
127
+ exports.NgEventEmitter = class NgEventEmitter extends EventBus {
128
+ constructor() {
129
+ super();
130
+ }
131
+ };
132
+ exports.NgEventEmitter = __decorate([
133
+ core.Injectable({
134
+ providedIn: 'root'
135
+ }),
136
+ __metadata("design:paramtypes", [])
137
+ ], exports.NgEventEmitter);
138
+
139
+ /**
140
+ * TokenManager - Manages authentication tokens
141
+ * Framework-agnostic implementation using browser storage APIs
142
+ * Handles storage, retrieval, and validation of JWT tokens
143
+ *
144
+ * @example
145
+ * ```typescript
146
+ * const tokenManager = new TokenManager();
147
+ *
148
+ * // Store a token
149
+ * tokenManager.setToken('your-jwt-token');
150
+ *
151
+ * // Check if authenticated
152
+ * if (tokenManager.isAuthenticated()) {
153
+ * const userData = tokenManager.getUserFromToken();
154
+ * }
155
+ * ```
156
+ */
157
+ class TokenManager {
158
+ TOKEN_KEY = 'auth_token';
159
+ REFRESH_TOKEN_KEY = 'refresh_token';
160
+ useSessionStorage = false;
161
+ /**
162
+ * Configure token manager
163
+ */
164
+ configure(config) {
165
+ if (config.tokenKey) {
166
+ this.TOKEN_KEY = config.tokenKey;
167
+ }
168
+ if (config.refreshTokenKey) {
169
+ this.REFRESH_TOKEN_KEY = config.refreshTokenKey;
170
+ }
171
+ if (config.useSessionStorage !== undefined) {
172
+ this.useSessionStorage = config.useSessionStorage;
173
+ }
174
+ }
175
+ /**
176
+ * Get the storage mechanism based on configuration
177
+ */
178
+ getStorage() {
179
+ return this.useSessionStorage ? sessionStorage : localStorage;
180
+ }
181
+ /**
182
+ * Set authentication token
183
+ */
184
+ setToken(token) {
185
+ this.getStorage().setItem(this.TOKEN_KEY, token);
186
+ }
187
+ /**
188
+ * Get authentication token
189
+ */
190
+ getToken() {
191
+ return this.getStorage().getItem(this.TOKEN_KEY);
192
+ }
193
+ /**
194
+ * Remove authentication token
195
+ */
196
+ removeToken() {
197
+ this.getStorage().removeItem(this.TOKEN_KEY);
198
+ }
199
+ /**
200
+ * Set refresh token
201
+ */
202
+ setRefreshToken(token) {
203
+ this.getStorage().setItem(this.REFRESH_TOKEN_KEY, token);
204
+ }
205
+ /**
206
+ * Get refresh token
207
+ */
208
+ getRefreshToken() {
209
+ return this.getStorage().getItem(this.REFRESH_TOKEN_KEY);
210
+ }
211
+ /**
212
+ * Remove refresh token
213
+ */
214
+ removeRefreshToken() {
215
+ this.getStorage().removeItem(this.REFRESH_TOKEN_KEY);
216
+ }
217
+ /**
218
+ * Clear all tokens
219
+ */
220
+ clearTokens() {
221
+ this.removeToken();
222
+ this.removeRefreshToken();
223
+ }
224
+ /**
225
+ * Check if token exists
226
+ */
227
+ hasToken() {
228
+ return !!this.getToken();
229
+ }
230
+ /**
231
+ * Decode JWT token (without verification)
232
+ * @param token - JWT token to decode
233
+ * @returns Decoded token payload or null if invalid
234
+ */
235
+ decodeToken(token) {
236
+ const tokenToDecode = token || this.getToken();
237
+ if (!tokenToDecode)
238
+ return null;
239
+ try {
240
+ const parts = tokenToDecode.split('.');
241
+ if (parts.length !== 3)
242
+ return null;
243
+ const payload = parts[1];
244
+ const decoded = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
245
+ return decoded;
246
+ }
247
+ catch (error) {
248
+ console.error('Error decoding token:', error);
249
+ return null;
250
+ }
251
+ }
252
+ /**
253
+ * Check if token is expired
254
+ * @param token - Optional token to check (defaults to stored token)
255
+ * @returns true if token is expired or invalid
256
+ */
257
+ isTokenExpired(token) {
258
+ const decoded = this.decodeToken(token);
259
+ if (!decoded || !decoded.exp)
260
+ return true;
261
+ const expirationDate = new Date(decoded.exp * 1000);
262
+ return expirationDate <= new Date();
263
+ }
264
+ /**
265
+ * Check if user is authenticated (has valid, non-expired token)
266
+ */
267
+ isAuthenticated() {
268
+ return this.hasToken() && !this.isTokenExpired();
269
+ }
270
+ /**
271
+ * Get token expiration date
272
+ */
273
+ getTokenExpirationDate(token) {
274
+ const decoded = this.decodeToken(token);
275
+ if (!decoded || !decoded.exp)
276
+ return null;
277
+ return new Date(decoded.exp * 1000);
278
+ }
279
+ /**
280
+ * Get user data from token
281
+ */
282
+ getUserFromToken(token) {
283
+ return this.decodeToken(token);
284
+ }
285
+ }
286
+
287
+ /**
288
+ * TokenService - Angular service wrapper for TokenManager
289
+ * Provides Angular dependency injection support for the framework-agnostic TokenManager
290
+ *
291
+ * @example
292
+ * ```typescript
293
+ * import { Component, inject } from '@angular/core';
294
+ * import { TokenService } from 'common-libs';
295
+ *
296
+ * export class AuthService {
297
+ * private tokenService = inject(TokenService);
298
+ *
299
+ * login(token: string) {
300
+ * this.tokenService.setToken(token);
301
+ * }
302
+ *
303
+ * isAuthenticated(): boolean {
304
+ * return this.tokenService.isAuthenticated();
305
+ * }
306
+ * }
307
+ * ```
308
+ */
309
+ exports.TokenService = class TokenService extends TokenManager {
310
+ constructor() {
311
+ console.log("Hey Jude in TokenService of common-libs");
312
+ super();
313
+ }
314
+ };
315
+ exports.TokenService = __decorate([
316
+ core.Injectable({
317
+ providedIn: 'root'
318
+ }),
319
+ __metadata("design:paramtypes", [])
320
+ ], exports.TokenService);
321
+
322
+ /**
323
+ * StorageManager - Type-safe wrapper for browser storage
324
+ * Framework-agnostic implementation using browser storage APIs
325
+ * Provides JSON serialization/deserialization and error handling
326
+ *
327
+ * @example
328
+ * ```typescript
329
+ * const storage = new StorageManager();
330
+ *
331
+ * // Store data
332
+ * storage.setLocal('user-prefs', { theme: 'dark', lang: 'en' });
333
+ *
334
+ * // Retrieve data
335
+ * const prefs = storage.getLocal('user-prefs');
336
+ *
337
+ * // With expiration
338
+ * storage.setWithExpiration('temp-data', someData, 3600000); // 1 hour
339
+ * ```
340
+ */
341
+ class StorageManager {
342
+ /**
343
+ * Set item in localStorage with JSON serialization
344
+ */
345
+ setLocal(key, value) {
346
+ try {
347
+ const serialized = JSON.stringify(value);
348
+ localStorage.setItem(key, serialized);
349
+ return true;
350
+ }
351
+ catch (error) {
352
+ console.error('Error setting localStorage item:', error);
353
+ return false;
354
+ }
355
+ }
356
+ /**
357
+ * Get item from localStorage with JSON deserialization
358
+ */
359
+ getLocal(key, defaultValue) {
360
+ try {
361
+ const item = localStorage.getItem(key);
362
+ if (item === null) {
363
+ return defaultValue !== undefined ? defaultValue : null;
364
+ }
365
+ return JSON.parse(item);
366
+ }
367
+ catch (error) {
368
+ console.error('Error getting localStorage item:', error);
369
+ return defaultValue !== undefined ? defaultValue : null;
370
+ }
371
+ }
372
+ /**
373
+ * Remove item from localStorage
374
+ */
375
+ removeLocal(key) {
376
+ try {
377
+ localStorage.removeItem(key);
378
+ }
379
+ catch (error) {
380
+ console.error('Error removing localStorage item:', error);
381
+ }
382
+ }
383
+ /**
384
+ * Clear all localStorage items
385
+ */
386
+ clearLocal() {
387
+ try {
388
+ localStorage.clear();
389
+ }
390
+ catch (error) {
391
+ console.error('Error clearing localStorage:', error);
392
+ }
393
+ }
394
+ /**
395
+ * Check if key exists in localStorage
396
+ */
397
+ hasLocal(key) {
398
+ try {
399
+ return localStorage.getItem(key) !== null;
400
+ }
401
+ catch (error) {
402
+ console.error('Error checking localStorage key:', error);
403
+ return false;
404
+ }
405
+ }
406
+ /**
407
+ * Get all localStorage keys
408
+ */
409
+ getLocalKeys() {
410
+ try {
411
+ return Object.keys(localStorage);
412
+ }
413
+ catch (error) {
414
+ console.error('Error getting localStorage keys:', error);
415
+ return [];
416
+ }
417
+ }
418
+ /**
419
+ * Set item in sessionStorage with JSON serialization
420
+ */
421
+ setSession(key, value) {
422
+ try {
423
+ const serialized = JSON.stringify(value);
424
+ sessionStorage.setItem(key, serialized);
425
+ return true;
426
+ }
427
+ catch (error) {
428
+ console.error('Error setting sessionStorage item:', error);
429
+ return false;
430
+ }
431
+ }
432
+ /**
433
+ * Get item from sessionStorage with JSON deserialization
434
+ */
435
+ getSession(key, defaultValue) {
436
+ try {
437
+ const item = sessionStorage.getItem(key);
438
+ if (item === null) {
439
+ return defaultValue !== undefined ? defaultValue : null;
440
+ }
441
+ return JSON.parse(item);
442
+ }
443
+ catch (error) {
444
+ console.error('Error getting sessionStorage item:', error);
445
+ return defaultValue !== undefined ? defaultValue : null;
446
+ }
447
+ }
448
+ /**
449
+ * Remove item from sessionStorage
450
+ */
451
+ removeSession(key) {
452
+ try {
453
+ sessionStorage.removeItem(key);
454
+ }
455
+ catch (error) {
456
+ console.error('Error removing sessionStorage item:', error);
457
+ }
458
+ }
459
+ /**
460
+ * Clear all sessionStorage items
461
+ */
462
+ clearSession() {
463
+ try {
464
+ sessionStorage.clear();
465
+ }
466
+ catch (error) {
467
+ console.error('Error clearing sessionStorage:', error);
468
+ }
469
+ }
470
+ /**
471
+ * Check if key exists in sessionStorage
472
+ */
473
+ hasSession(key) {
474
+ try {
475
+ return sessionStorage.getItem(key) !== null;
476
+ }
477
+ catch (error) {
478
+ console.error('Error checking sessionStorage key:', error);
479
+ return false;
480
+ }
481
+ }
482
+ /**
483
+ * Get all sessionStorage keys
484
+ */
485
+ getSessionKeys() {
486
+ try {
487
+ return Object.keys(sessionStorage);
488
+ }
489
+ catch (error) {
490
+ console.error('Error getting sessionStorage keys:', error);
491
+ return [];
492
+ }
493
+ }
494
+ /**
495
+ * Set item with expiration time
496
+ * @param key - Storage key
497
+ * @param value - Value to store
498
+ * @param expirationMs - Expiration time in milliseconds
499
+ * @param useSession - Use sessionStorage instead of localStorage
500
+ */
501
+ setWithExpiration(key, value, expirationMs, useSession = false) {
502
+ const item = {
503
+ value,
504
+ expiration: Date.now() + expirationMs
505
+ };
506
+ return useSession
507
+ ? this.setSession(key, item)
508
+ : this.setLocal(key, item);
509
+ }
510
+ /**
511
+ * Get item with expiration check
512
+ * Returns null if item is expired
513
+ */
514
+ getWithExpiration(key, useSession = false) {
515
+ const item = useSession
516
+ ? this.getSession(key)
517
+ : this.getLocal(key);
518
+ if (!item)
519
+ return null;
520
+ if (Date.now() > item.expiration) {
521
+ // Item expired, remove it
522
+ if (useSession) {
523
+ this.removeSession(key);
524
+ }
525
+ else {
526
+ this.removeLocal(key);
527
+ }
528
+ return null;
529
+ }
530
+ return item.value;
531
+ }
532
+ }
533
+
534
+ /**
535
+ * StorageService - Angular service wrapper for StorageManager
536
+ * Provides Angular dependency injection support for the framework-agnostic StorageManager
537
+ *
538
+ * @example
539
+ * ```typescript
540
+ * import { Component, inject } from '@angular/core';
541
+ * import { StorageService } from 'common-libs';
542
+ *
543
+ * export class UserPreferencesService {
544
+ * private storage = inject(StorageService);
545
+ *
546
+ * savePreferences(prefs: any) {
547
+ * this.storage.setLocal('user-prefs', prefs);
548
+ * }
549
+ *
550
+ * getPreferences() {
551
+ * return this.storage.getLocal('user-prefs');
552
+ * }
553
+ * }
554
+ * ```
555
+ */
556
+ exports.StorageService = class StorageService extends StorageManager {
557
+ constructor() {
558
+ super();
559
+ }
560
+ };
561
+ exports.StorageService = __decorate([
562
+ core.Injectable({
563
+ providedIn: 'root'
564
+ }),
565
+ __metadata("design:paramtypes", [])
566
+ ], exports.StorageService);
567
+
568
+ /**
569
+ * Log level enum
570
+ */
571
+ exports.LogLevel = void 0;
572
+ (function (LogLevel) {
573
+ LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
574
+ LogLevel[LogLevel["INFO"] = 1] = "INFO";
575
+ LogLevel[LogLevel["WARN"] = 2] = "WARN";
576
+ LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
577
+ LogLevel[LogLevel["NONE"] = 4] = "NONE";
578
+ })(exports.LogLevel || (exports.LogLevel = {}));
579
+ /**
580
+ * Logger - Centralized logging utility
581
+ * Framework-agnostic implementation using browser console APIs
582
+ * Supports different log levels and can be configured globally
583
+ *
584
+ * @example
585
+ * ```typescript
586
+ * const logger = new Logger();
587
+ *
588
+ * // Configure
589
+ * logger.configure({
590
+ * level: LogLevel.DEBUG,
591
+ * enableTimestamp: true,
592
+ * prefix: 'MyApp'
593
+ * });
594
+ *
595
+ * // Use
596
+ * logger.info('User logged in', { userId: '123' });
597
+ * logger.error('Failed to load data', error);
598
+ * ```
599
+ */
600
+ class Logger {
601
+ config = {
602
+ level: exports.LogLevel.INFO,
603
+ enableTimestamp: true,
604
+ enableStackTrace: false,
605
+ prefix: ''
606
+ };
607
+ /**
608
+ * Configure the logger
609
+ */
610
+ configure(config) {
611
+ this.config = { ...this.config, ...config };
612
+ }
613
+ /**
614
+ * Set log level
615
+ */
616
+ setLevel(level) {
617
+ this.config.level = level;
618
+ }
619
+ /**
620
+ * Get current log level
621
+ */
622
+ getLevel() {
623
+ return this.config.level;
624
+ }
625
+ /**
626
+ * Format log message with timestamp and prefix
627
+ */
628
+ formatMessage(message, level) {
629
+ const parts = [];
630
+ if (this.config.enableTimestamp) {
631
+ parts.push(`[${new Date().toISOString()}]`);
632
+ }
633
+ if (this.config.prefix) {
634
+ parts.push(`[${this.config.prefix}]`);
635
+ }
636
+ parts.push(`[${level}]`);
637
+ parts.push(message);
638
+ return parts.join(' ');
639
+ }
640
+ /**
641
+ * Check if log level should be logged
642
+ */
643
+ shouldLog(level) {
644
+ return level >= this.config.level;
645
+ }
646
+ /**
647
+ * Log debug message
648
+ */
649
+ debug(message, ...args) {
650
+ if (this.shouldLog(exports.LogLevel.DEBUG)) {
651
+ console.debug(this.formatMessage(message, 'DEBUG'), ...args);
652
+ }
653
+ }
654
+ /**
655
+ * Log info message
656
+ */
657
+ info(message, ...args) {
658
+ if (this.shouldLog(exports.LogLevel.INFO)) {
659
+ console.info(this.formatMessage(message, 'INFO'), ...args);
660
+ }
661
+ }
662
+ /**
663
+ * Log warning message
664
+ */
665
+ warn(message, ...args) {
666
+ if (this.shouldLog(exports.LogLevel.WARN)) {
667
+ console.warn(this.formatMessage(message, 'WARN'), ...args);
668
+ }
669
+ }
670
+ /**
671
+ * Log error message
672
+ */
673
+ error(message, error, ...args) {
674
+ if (this.shouldLog(exports.LogLevel.ERROR)) {
675
+ console.error(this.formatMessage(message, 'ERROR'), ...args);
676
+ if (error) {
677
+ console.error(error);
678
+ if (this.config.enableStackTrace && error?.stack) {
679
+ console.error('Stack trace:', error.stack);
680
+ }
681
+ }
682
+ }
683
+ }
684
+ /**
685
+ * Log a group of messages
686
+ */
687
+ group(label, callback) {
688
+ if (this.shouldLog(exports.LogLevel.INFO)) {
689
+ console.group(this.formatMessage(label, 'GROUP'));
690
+ callback();
691
+ console.groupEnd();
692
+ }
693
+ }
694
+ /**
695
+ * Log a collapsed group of messages
696
+ */
697
+ groupCollapsed(label, callback) {
698
+ if (this.shouldLog(exports.LogLevel.INFO)) {
699
+ console.groupCollapsed(this.formatMessage(label, 'GROUP'));
700
+ callback();
701
+ console.groupEnd();
702
+ }
703
+ }
704
+ /**
705
+ * Log a table (useful for arrays of objects)
706
+ */
707
+ table(data, columns) {
708
+ if (this.shouldLog(exports.LogLevel.INFO)) {
709
+ console.table(data, columns);
710
+ }
711
+ }
712
+ /**
713
+ * Log execution time of a function
714
+ */
715
+ async time(label, fn) {
716
+ const start = performance.now();
717
+ try {
718
+ const result = await fn();
719
+ const end = performance.now();
720
+ const duration = (end - start).toFixed(2);
721
+ this.info(`${label} completed in ${duration}ms`);
722
+ return result;
723
+ }
724
+ catch (error) {
725
+ const end = performance.now();
726
+ const duration = (end - start).toFixed(2);
727
+ this.error(`${label} failed after ${duration}ms`, error);
728
+ throw error;
729
+ }
730
+ }
731
+ }
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
+ /**
858
+ * Factory function to create an auth guard with configuration
859
+ *
860
+ * @example
861
+ * ```typescript
862
+ * // In routes
863
+ * {
864
+ * path: 'dashboard',
865
+ * component: DashboardComponent,
866
+ * canActivate: [createAuthGuard({ redirectUrl: '/login' })]
867
+ * }
868
+ * ```
869
+ */
870
+ function createAuthGuard(config = {}) {
871
+ return (route, state) => {
872
+ const tokenService = core.inject(exports.TokenService);
873
+ const router$1 = core.inject(router.Router);
874
+ const redirectUrl = config.redirectUrl || '/login';
875
+ const checkExpiration = config.checkExpiration !== false;
876
+ const hasToken = tokenService.hasToken();
877
+ const isExpired = checkExpiration ? tokenService.isTokenExpired() : false;
878
+ if (hasToken && !isExpired) {
879
+ return true;
880
+ }
881
+ // Store the attempted URL for redirecting after login
882
+ const returnUrl = state.url;
883
+ router$1.navigate([redirectUrl], {
884
+ queryParams: { returnUrl },
885
+ queryParamsHandling: 'merge'
886
+ });
887
+ return false;
888
+ };
889
+ }
890
+ /**
891
+ * Default auth guard - redirects to '/login' if not authenticated
892
+ */
893
+ const authGuard = createAuthGuard();
894
+ /**
895
+ * Permission-based guard factory
896
+ * Checks if user has required permissions from token
897
+ *
898
+ * @example
899
+ * ```typescript
900
+ * {
901
+ * path: 'admin',
902
+ * component: AdminComponent,
903
+ * canActivate: [createPermissionGuard(['admin', 'editor'])]
904
+ * }
905
+ * ```
906
+ */
907
+ function createPermissionGuard(requiredPermissions, config = {}) {
908
+ return (route, state) => {
909
+ const tokenService = core.inject(exports.TokenService);
910
+ const router$1 = core.inject(router.Router);
911
+ const redirectUrl = config.redirectUrl || '/unauthorized';
912
+ // First check authentication
913
+ if (!tokenService.isAuthenticated()) {
914
+ router$1.navigate(['/login'], {
915
+ queryParams: { returnUrl: state.url }
916
+ });
917
+ return false;
918
+ }
919
+ // Check permissions
920
+ const user = tokenService.getUserFromToken();
921
+ const userPermissions = user?.permissions || user?.roles || [];
922
+ const hasPermission = requiredPermissions.some(permission => userPermissions.includes(permission));
923
+ if (!hasPermission) {
924
+ router$1.navigate([redirectUrl]);
925
+ return false;
926
+ }
927
+ return true;
928
+ };
929
+ }
930
+ /**
931
+ * Role-based guard factory
932
+ * Checks if user has required role from token
933
+ *
934
+ * @example
935
+ * ```typescript
936
+ * {
937
+ * path: 'admin',
938
+ * component: AdminComponent,
939
+ * canActivate: [createRoleGuard(['admin'])]
940
+ * }
941
+ * ```
942
+ */
943
+ function createRoleGuard(requiredRoles, config = {}) {
944
+ return createPermissionGuard(requiredRoles, config);
945
+ }
946
+
947
+ const defaultConfig$1 = {
948
+ headerName: 'Authorization',
949
+ tokenPrefix: 'Bearer',
950
+ excludedUrls: []
951
+ };
952
+ let interceptorConfig = { ...defaultConfig$1 };
953
+ /**
954
+ * Configure the auth interceptor
955
+ */
956
+ function configureAuthInterceptor(config) {
957
+ interceptorConfig = { ...defaultConfig$1, ...config };
958
+ }
959
+ /**
960
+ * Auth Interceptor - Automatically adds authentication token to HTTP requests
961
+ *
962
+ * @example
963
+ * ```typescript
964
+ * // In app.config.ts
965
+ * export const appConfig: ApplicationConfig = {
966
+ * providers: [
967
+ * provideHttpClient(
968
+ * withInterceptors([authInterceptor])
969
+ * )
970
+ * ]
971
+ * };
972
+ * ```
973
+ */
974
+ const authInterceptor = (req, next) => {
975
+ const tokenService = core.inject(exports.TokenService);
976
+ const config = interceptorConfig;
977
+ // Check if URL should be excluded
978
+ const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
979
+ if (isExcluded) {
980
+ return next(req);
981
+ }
982
+ // Get token and add to request if available
983
+ const token = tokenService.getToken();
984
+ if (token) {
985
+ const authReq = req.clone({
986
+ setHeaders: {
987
+ [config.headerName]: `${config.tokenPrefix} ${token}`
988
+ }
989
+ });
990
+ return next(authReq);
991
+ }
992
+ return next(req);
993
+ };
994
+
995
+ const defaultConfig = {
996
+ enableLogging: true,
997
+ retryAttempts: 0,
998
+ retryDelay: 1000,
999
+ retryStatusCodes: [408, 429, 500, 502, 503, 504],
1000
+ excludedUrls: []
1001
+ };
1002
+ let errorConfig = { ...defaultConfig };
1003
+ /**
1004
+ * Configure the error handling interceptor
1005
+ */
1006
+ function configureErrorHandling(config) {
1007
+ errorConfig = { ...defaultConfig, ...config };
1008
+ }
1009
+ /**
1010
+ * Error handling interceptor - Handles HTTP errors and retries
1011
+ *
1012
+ * @example
1013
+ * ```typescript
1014
+ * // In app.config.ts
1015
+ * export const appConfig: ApplicationConfig = {
1016
+ * providers: [
1017
+ * provideHttpClient(
1018
+ * withInterceptors([errorHandlingInterceptor])
1019
+ * )
1020
+ * ]
1021
+ * };
1022
+ *
1023
+ * // Configure retry behavior
1024
+ * configureErrorHandling({
1025
+ * retryAttempts: 3,
1026
+ * retryDelay: 2000,
1027
+ * retryStatusCodes: [500, 502, 503]
1028
+ * });
1029
+ * ```
1030
+ */
1031
+ const errorHandlingInterceptor = (req, next) => {
1032
+ const logger = core.inject(exports.LoggerService);
1033
+ const config = errorConfig;
1034
+ // Check if URL should be excluded
1035
+ const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
1036
+ if (isExcluded) {
1037
+ return next(req);
1038
+ }
1039
+ return next(req).pipe(
1040
+ // Retry logic with exponential backoff
1041
+ operators.retry({
1042
+ count: config.retryAttempts,
1043
+ delay: (error, retryCount) => {
1044
+ // Only retry for specific status codes
1045
+ if (!config.retryStatusCodes?.includes(error.status)) {
1046
+ return rxjs.throwError(() => error);
1047
+ }
1048
+ const delay = config.retryDelay * Math.pow(2, retryCount - 1);
1049
+ if (config.enableLogging) {
1050
+ logger.warn(`Retrying request (attempt ${retryCount}) after ${delay}ms`, { url: req.url, status: error.status });
1051
+ }
1052
+ return rxjs.timer(delay);
1053
+ }
1054
+ }),
1055
+ // Error handling
1056
+ operators.catchError((error) => {
1057
+ if (config.enableLogging) {
1058
+ logger.error('HTTP request failed', error, {
1059
+ url: req.url,
1060
+ status: error.status,
1061
+ message: error.message
1062
+ });
1063
+ }
1064
+ return rxjs.throwError(() => error);
1065
+ }));
1066
+ };
1067
+ /**
1068
+ * HTTP Error class with additional context
1069
+ */
1070
+ class HttpError extends Error {
1071
+ status;
1072
+ statusText;
1073
+ url;
1074
+ originalError;
1075
+ constructor(status, statusText, url, originalError) {
1076
+ super(`HTTP ${status} ${statusText}: ${url}`);
1077
+ this.status = status;
1078
+ this.statusText = statusText;
1079
+ this.url = url;
1080
+ this.originalError = originalError;
1081
+ this.name = 'HttpError';
1082
+ }
1083
+ }
1084
+ /**
1085
+ * Parse HTTP error and return user-friendly message
1086
+ */
1087
+ function parseHttpError(error) {
1088
+ if (error.error instanceof ErrorEvent) {
1089
+ // Client-side error
1090
+ return `Network error: ${error.error.message}`;
1091
+ }
1092
+ else {
1093
+ // Server-side error
1094
+ const errorMessage = error.error?.message || error.message || 'Unknown error';
1095
+ return `Server error (${error.status}): ${errorMessage}`;
1096
+ }
1097
+ }
1098
+ /**
1099
+ * Check if error is a network error
1100
+ */
1101
+ function isNetworkError(error) {
1102
+ return error.error instanceof ErrorEvent || error.status === 0;
1103
+ }
1104
+ /**
1105
+ * Check if error is a server error (5xx)
1106
+ */
1107
+ function isServerError(error) {
1108
+ return error.status >= 500 && error.status < 600;
1109
+ }
1110
+ /**
1111
+ * Check if error is a client error (4xx)
1112
+ */
1113
+ function isClientError(error) {
1114
+ return error.status >= 400 && error.status < 500;
1115
+ }
1116
+
1117
+ const defaultCacheConfig = {
1118
+ enabled: true,
1119
+ maxAge: 60000, // 1 minute
1120
+ excludedUrls: [],
1121
+ cacheableUrls: [],
1122
+ cacheMethods: ['GET']
1123
+ };
1124
+ let cacheConfig = { ...defaultCacheConfig };
1125
+ const cache = new Map();
1126
+ const MAX_CACHE_SIZE = 100; // Maximum number of cached entries
1127
+ /**
1128
+ * Configure the caching interceptor
1129
+ */
1130
+ function configureCaching(config) {
1131
+ cacheConfig = { ...defaultCacheConfig, ...config };
1132
+ }
1133
+ /**
1134
+ * Clean up expired cache entries
1135
+ */
1136
+ function cleanupCache() {
1137
+ const now = Date.now();
1138
+ const keysToDelete = [];
1139
+ cache.forEach((entry, key) => {
1140
+ const age = now - entry.timestamp;
1141
+ if (age >= cacheConfig.maxAge) {
1142
+ keysToDelete.push(key);
1143
+ }
1144
+ });
1145
+ keysToDelete.forEach(key => cache.delete(key));
1146
+ }
1147
+ /**
1148
+ * Evict oldest cache entry if cache is full
1149
+ */
1150
+ function evictOldestIfFull() {
1151
+ if (cache.size >= MAX_CACHE_SIZE) {
1152
+ let oldestKey = null;
1153
+ let oldestTimestamp = Infinity;
1154
+ cache.forEach((entry, key) => {
1155
+ if (entry.timestamp < oldestTimestamp) {
1156
+ oldestTimestamp = entry.timestamp;
1157
+ oldestKey = key;
1158
+ }
1159
+ });
1160
+ if (oldestKey) {
1161
+ cache.delete(oldestKey);
1162
+ }
1163
+ }
1164
+ }
1165
+ /**
1166
+ * Clear all cached entries
1167
+ */
1168
+ function clearCache() {
1169
+ cache.clear();
1170
+ }
1171
+ /**
1172
+ * Clear cache entry for specific URL
1173
+ */
1174
+ function clearCacheEntry(url) {
1175
+ cache.delete(url);
1176
+ }
1177
+ /**
1178
+ * Caching interceptor - Caches HTTP GET requests
1179
+ *
1180
+ * @example
1181
+ * ```typescript
1182
+ * // In app.config.ts
1183
+ * export const appConfig: ApplicationConfig = {
1184
+ * providers: [
1185
+ * provideHttpClient(
1186
+ * withInterceptors([cachingInterceptor])
1187
+ * )
1188
+ * ]
1189
+ * };
1190
+ *
1191
+ * // Configure caching
1192
+ * configureCaching({
1193
+ * enabled: true,
1194
+ * maxAge: 300000, // 5 minutes
1195
+ * cacheableUrls: ['/api/users', '/api/products']
1196
+ * });
1197
+ * ```
1198
+ */
1199
+ const cachingInterceptor = (req, next) => {
1200
+ const logger = core.inject(exports.LoggerService);
1201
+ const config = cacheConfig;
1202
+ // Only cache if enabled
1203
+ if (!config.enabled) {
1204
+ return next(req);
1205
+ }
1206
+ // Only cache specific methods (default: GET)
1207
+ if (!config.cacheMethods?.includes(req.method)) {
1208
+ return next(req);
1209
+ }
1210
+ // Check if URL should be excluded
1211
+ const isExcluded = config.excludedUrls?.some(url => req.url.includes(url));
1212
+ if (isExcluded) {
1213
+ return next(req);
1214
+ }
1215
+ // Check if URL is explicitly cacheable (if list is provided)
1216
+ if (config.cacheableUrls && config.cacheableUrls.length > 0) {
1217
+ const isCacheable = config.cacheableUrls.some(url => req.url.includes(url));
1218
+ if (!isCacheable) {
1219
+ return next(req);
1220
+ }
1221
+ }
1222
+ const cacheKey = req.urlWithParams;
1223
+ // Check cache
1224
+ const cached = cache.get(cacheKey);
1225
+ if (cached) {
1226
+ const age = Date.now() - cached.timestamp;
1227
+ if (age < config.maxAge) {
1228
+ logger.debug(`Cache hit for ${cacheKey}`, { age });
1229
+ return new rxjs.Observable(observer => {
1230
+ observer.next(cached.response.clone());
1231
+ observer.complete();
1232
+ });
1233
+ }
1234
+ else {
1235
+ // Cache expired
1236
+ cache.delete(cacheKey);
1237
+ }
1238
+ }
1239
+ // Clean up expired entries periodically
1240
+ if (Math.random() < 0.1) { // 10% chance on each request
1241
+ cleanupCache();
1242
+ }
1243
+ // Make request and cache response
1244
+ return next(req).pipe(operators.tap(event => {
1245
+ if (event instanceof http.HttpResponse) {
1246
+ evictOldestIfFull();
1247
+ cache.set(cacheKey, {
1248
+ response: event.clone(),
1249
+ timestamp: Date.now()
1250
+ });
1251
+ logger.debug(`Cached response for ${cacheKey}`);
1252
+ }
1253
+ }));
1254
+ };
1255
+
1256
+ exports.HttpError = HttpError;
1257
+ exports.authGuard = authGuard;
1258
+ exports.authInterceptor = authInterceptor;
1259
+ exports.cachingInterceptor = cachingInterceptor;
1260
+ exports.clearCache = clearCache;
1261
+ exports.clearCacheEntry = clearCacheEntry;
1262
+ exports.configureAuthInterceptor = configureAuthInterceptor;
1263
+ exports.configureCaching = configureCaching;
1264
+ exports.configureErrorHandling = configureErrorHandling;
1265
+ exports.createAuthGuard = createAuthGuard;
1266
+ exports.createPermissionGuard = createPermissionGuard;
1267
+ exports.createRoleGuard = createRoleGuard;
1268
+ exports.errorHandlingInterceptor = errorHandlingInterceptor;
1269
+ exports.isClientError = isClientError;
1270
+ exports.isNetworkError = isNetworkError;
1271
+ exports.isServerError = isServerError;
1272
+ exports.parseHttpError = parseHttpError;
1273
+ //# sourceMappingURL=index.cjs.map