@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,691 @@
1
+ import { Observable } from 'rxjs';
2
+ import { CanActivateFn } from '@angular/router';
3
+ import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
4
+
5
+ /**
6
+ * Event payload interface
7
+ */
8
+ interface EventPayload<T = any> {
9
+ type: string;
10
+ data: T;
11
+ timestamp?: number;
12
+ }
13
+ /**
14
+ * EventBus - A centralized event bus for application-wide communication
15
+ * Framework-agnostic implementation using only RxJS
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // Create an instance
20
+ * const eventBus = new EventBus();
21
+ *
22
+ * // Emit an event
23
+ * eventBus.emit('user:login', { userId: '123', username: 'john' });
24
+ *
25
+ * // Subscribe to an event
26
+ * eventBus.on('user:login').subscribe(data => {
27
+ * console.log('User logged in:', data);
28
+ * });
29
+ * ```
30
+ */
31
+ declare class EventBus {
32
+ private eventSubject;
33
+ /**
34
+ * Emit an event with optional data
35
+ * @param eventType - The type/name of the event
36
+ * @param data - Optional data to send with the event
37
+ */
38
+ emit<T = any>(eventType: string, data?: T): void;
39
+ /**
40
+ * Subscribe to a specific event type
41
+ * @param eventType - The type/name of the event to listen for
42
+ * @returns Observable that emits the event data
43
+ */
44
+ on<T = any>(eventType: string): Observable<T>;
45
+ /**
46
+ * Subscribe to multiple event types
47
+ * @param eventTypes - Array of event types to listen for
48
+ * @returns Observable that emits the full event payload
49
+ */
50
+ onMultiple(eventTypes: string[]): Observable<EventPayload>;
51
+ /**
52
+ * Subscribe to all events
53
+ * @returns Observable that emits all event payloads
54
+ */
55
+ onAll(): Observable<EventPayload>;
56
+ }
57
+
58
+ /**
59
+ * NgEventEmitter - Angular service wrapper for EventBus
60
+ * Provides Angular dependency injection support for the framework-agnostic EventBus
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * import { Component, inject } from '@angular/core';
65
+ * import { NgEventEmitter } from 'common-libs';
66
+ *
67
+ * @Component({
68
+ * selector: 'app-example',
69
+ * template: '...'
70
+ * })
71
+ * export class ExampleComponent {
72
+ * private eventEmitter = inject(NgEventEmitter);
73
+ *
74
+ * ngOnInit() {
75
+ * this.eventEmitter.on('user:login').subscribe(data => {
76
+ * console.log('User logged in:', data);
77
+ * });
78
+ * }
79
+ *
80
+ * login() {
81
+ * this.eventEmitter.emit('user:login', { userId: '123' });
82
+ * }
83
+ * }
84
+ * ```
85
+ */
86
+ declare class NgEventEmitter extends EventBus {
87
+ constructor();
88
+ }
89
+
90
+ /**
91
+ * Token configuration interface
92
+ */
93
+ interface TokenConfig {
94
+ tokenKey?: string;
95
+ refreshTokenKey?: string;
96
+ useSessionStorage?: boolean;
97
+ }
98
+ /**
99
+ * TokenManager - Manages authentication tokens
100
+ * Framework-agnostic implementation using browser storage APIs
101
+ * Handles storage, retrieval, and validation of JWT tokens
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const tokenManager = new TokenManager();
106
+ *
107
+ * // Store a token
108
+ * tokenManager.setToken('your-jwt-token');
109
+ *
110
+ * // Check if authenticated
111
+ * if (tokenManager.isAuthenticated()) {
112
+ * const userData = tokenManager.getUserFromToken();
113
+ * }
114
+ * ```
115
+ */
116
+ declare class TokenManager {
117
+ private TOKEN_KEY;
118
+ private REFRESH_TOKEN_KEY;
119
+ private useSessionStorage;
120
+ /**
121
+ * Configure token manager
122
+ */
123
+ configure(config: TokenConfig): void;
124
+ /**
125
+ * Get the storage mechanism based on configuration
126
+ */
127
+ private getStorage;
128
+ /**
129
+ * Set authentication token
130
+ */
131
+ setToken(token: string): void;
132
+ /**
133
+ * Get authentication token
134
+ */
135
+ getToken(): string | null;
136
+ /**
137
+ * Remove authentication token
138
+ */
139
+ removeToken(): void;
140
+ /**
141
+ * Set refresh token
142
+ */
143
+ setRefreshToken(token: string): void;
144
+ /**
145
+ * Get refresh token
146
+ */
147
+ getRefreshToken(): string | null;
148
+ /**
149
+ * Remove refresh token
150
+ */
151
+ removeRefreshToken(): void;
152
+ /**
153
+ * Clear all tokens
154
+ */
155
+ clearTokens(): void;
156
+ /**
157
+ * Check if token exists
158
+ */
159
+ hasToken(): boolean;
160
+ /**
161
+ * Decode JWT token (without verification)
162
+ * @param token - JWT token to decode
163
+ * @returns Decoded token payload or null if invalid
164
+ */
165
+ decodeToken(token?: string): any;
166
+ /**
167
+ * Check if token is expired
168
+ * @param token - Optional token to check (defaults to stored token)
169
+ * @returns true if token is expired or invalid
170
+ */
171
+ isTokenExpired(token?: string): boolean;
172
+ /**
173
+ * Check if user is authenticated (has valid, non-expired token)
174
+ */
175
+ isAuthenticated(): boolean;
176
+ /**
177
+ * Get token expiration date
178
+ */
179
+ getTokenExpirationDate(token?: string): Date | null;
180
+ /**
181
+ * Get user data from token
182
+ */
183
+ getUserFromToken(token?: string): any;
184
+ }
185
+
186
+ /**
187
+ * TokenService - Angular service wrapper for TokenManager
188
+ * Provides Angular dependency injection support for the framework-agnostic TokenManager
189
+ *
190
+ * @example
191
+ * ```typescript
192
+ * import { Component, inject } from '@angular/core';
193
+ * import { TokenService } from 'common-libs';
194
+ *
195
+ * export class AuthService {
196
+ * private tokenService = inject(TokenService);
197
+ *
198
+ * login(token: string) {
199
+ * this.tokenService.setToken(token);
200
+ * }
201
+ *
202
+ * isAuthenticated(): boolean {
203
+ * return this.tokenService.isAuthenticated();
204
+ * }
205
+ * }
206
+ * ```
207
+ */
208
+ declare class TokenService extends TokenManager {
209
+ constructor();
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
+ declare class StorageManager {
232
+ /**
233
+ * Set item in localStorage with JSON serialization
234
+ */
235
+ setLocal<T>(key: string, value: T): boolean;
236
+ /**
237
+ * Get item from localStorage with JSON deserialization
238
+ */
239
+ getLocal<T>(key: string, defaultValue?: T): T | null;
240
+ /**
241
+ * Remove item from localStorage
242
+ */
243
+ removeLocal(key: string): void;
244
+ /**
245
+ * Clear all localStorage items
246
+ */
247
+ clearLocal(): void;
248
+ /**
249
+ * Check if key exists in localStorage
250
+ */
251
+ hasLocal(key: string): boolean;
252
+ /**
253
+ * Get all localStorage keys
254
+ */
255
+ getLocalKeys(): string[];
256
+ /**
257
+ * Set item in sessionStorage with JSON serialization
258
+ */
259
+ setSession<T>(key: string, value: T): boolean;
260
+ /**
261
+ * Get item from sessionStorage with JSON deserialization
262
+ */
263
+ getSession<T>(key: string, defaultValue?: T): T | null;
264
+ /**
265
+ * Remove item from sessionStorage
266
+ */
267
+ removeSession(key: string): void;
268
+ /**
269
+ * Clear all sessionStorage items
270
+ */
271
+ clearSession(): void;
272
+ /**
273
+ * Check if key exists in sessionStorage
274
+ */
275
+ hasSession(key: string): boolean;
276
+ /**
277
+ * Get all sessionStorage keys
278
+ */
279
+ getSessionKeys(): string[];
280
+ /**
281
+ * Set item with expiration time
282
+ * @param key - Storage key
283
+ * @param value - Value to store
284
+ * @param expirationMs - Expiration time in milliseconds
285
+ * @param useSession - Use sessionStorage instead of localStorage
286
+ */
287
+ setWithExpiration<T>(key: string, value: T, expirationMs: number, useSession?: boolean): boolean;
288
+ /**
289
+ * Get item with expiration check
290
+ * Returns null if item is expired
291
+ */
292
+ getWithExpiration<T>(key: string, useSession?: boolean): T | null;
293
+ }
294
+
295
+ /**
296
+ * StorageService - Angular service wrapper for StorageManager
297
+ * Provides Angular dependency injection support for the framework-agnostic StorageManager
298
+ *
299
+ * @example
300
+ * ```typescript
301
+ * import { Component, inject } from '@angular/core';
302
+ * import { StorageService } from 'common-libs';
303
+ *
304
+ * export class UserPreferencesService {
305
+ * private storage = inject(StorageService);
306
+ *
307
+ * savePreferences(prefs: any) {
308
+ * this.storage.setLocal('user-prefs', prefs);
309
+ * }
310
+ *
311
+ * getPreferences() {
312
+ * return this.storage.getLocal('user-prefs');
313
+ * }
314
+ * }
315
+ * ```
316
+ */
317
+ declare class StorageService extends StorageManager {
318
+ constructor();
319
+ }
320
+
321
+ /**
322
+ * Log level enum
323
+ */
324
+ declare enum LogLevel {
325
+ DEBUG = 0,
326
+ INFO = 1,
327
+ WARN = 2,
328
+ ERROR = 3,
329
+ NONE = 4
330
+ }
331
+ /**
332
+ * Logger configuration
333
+ */
334
+ interface LoggerConfig {
335
+ level?: LogLevel;
336
+ enableTimestamp?: boolean;
337
+ enableStackTrace?: boolean;
338
+ prefix?: string;
339
+ }
340
+ /**
341
+ * Logger - Centralized logging utility
342
+ * Framework-agnostic implementation using browser console APIs
343
+ * Supports different log levels and can be configured globally
344
+ *
345
+ * @example
346
+ * ```typescript
347
+ * const logger = new Logger();
348
+ *
349
+ * // Configure
350
+ * logger.configure({
351
+ * level: LogLevel.DEBUG,
352
+ * enableTimestamp: true,
353
+ * prefix: 'MyApp'
354
+ * });
355
+ *
356
+ * // Use
357
+ * logger.info('User logged in', { userId: '123' });
358
+ * logger.error('Failed to load data', error);
359
+ * ```
360
+ */
361
+ declare class Logger {
362
+ private config;
363
+ /**
364
+ * Configure the logger
365
+ */
366
+ configure(config: LoggerConfig): void;
367
+ /**
368
+ * Set log level
369
+ */
370
+ setLevel(level: LogLevel): void;
371
+ /**
372
+ * Get current log level
373
+ */
374
+ getLevel(): LogLevel;
375
+ /**
376
+ * Format log message with timestamp and prefix
377
+ */
378
+ private formatMessage;
379
+ /**
380
+ * Check if log level should be logged
381
+ */
382
+ private shouldLog;
383
+ /**
384
+ * Log debug message
385
+ */
386
+ debug(message: string, ...args: any[]): void;
387
+ /**
388
+ * Log info message
389
+ */
390
+ info(message: string, ...args: any[]): void;
391
+ /**
392
+ * Log warning message
393
+ */
394
+ warn(message: string, ...args: any[]): void;
395
+ /**
396
+ * Log error message
397
+ */
398
+ error(message: string, error?: any, ...args: any[]): void;
399
+ /**
400
+ * Log a group of messages
401
+ */
402
+ group(label: string, callback: () => void): void;
403
+ /**
404
+ * Log a collapsed group of messages
405
+ */
406
+ groupCollapsed(label: string, callback: () => void): void;
407
+ /**
408
+ * Log a table (useful for arrays of objects)
409
+ */
410
+ table(data: any, columns?: string[]): void;
411
+ /**
412
+ * Log execution time of a function
413
+ */
414
+ time<T>(label: string, fn: () => Promise<T> | T): Promise<T>;
415
+ }
416
+
417
+ /**
418
+ * LoggerService - Angular service wrapper for Logger
419
+ * Provides Angular dependency injection support for the framework-agnostic Logger
420
+ *
421
+ * @example
422
+ * ```typescript
423
+ * import { Component, inject } from '@angular/core';
424
+ * import { LoggerService, LogLevel } from 'common-libs';
425
+ *
426
+ * export class MyService {
427
+ * private logger = inject(LoggerService);
428
+ *
429
+ * constructor() {
430
+ * this.logger.configure({
431
+ * level: LogLevel.DEBUG,
432
+ * prefix: 'MyApp'
433
+ * });
434
+ * }
435
+ *
436
+ * doSomething() {
437
+ * this.logger.info('Doing something');
438
+ * }
439
+ * }
440
+ * ```
441
+ */
442
+ declare class LoggerService extends Logger {
443
+ constructor();
444
+ }
445
+
446
+ /**
447
+ * PermissionService - Manages user permissions and roles
448
+ */
449
+ declare class PermissionService {
450
+ private tokenService;
451
+ /**
452
+ * Check if user has a specific permission
453
+ */
454
+ hasPermission(permission: string): boolean;
455
+ /**
456
+ * Check if user has any of the specified permissions
457
+ */
458
+ hasAnyPermission(permissions: string[]): boolean;
459
+ /**
460
+ * Check if user has all of the specified permissions
461
+ */
462
+ hasAllPermissions(permissions: string[]): boolean;
463
+ /**
464
+ * Check if user has a specific role
465
+ */
466
+ hasRole(role: string): boolean;
467
+ /**
468
+ * Check if user has any of the specified roles
469
+ */
470
+ hasAnyRole(roles: string[]): boolean;
471
+ /**
472
+ * Check if user has all of the specified roles
473
+ */
474
+ hasAllRoles(roles: string[]): boolean;
475
+ /**
476
+ * Get all user permissions
477
+ */
478
+ getPermissions(): string[];
479
+ /**
480
+ * Get all user roles
481
+ */
482
+ getRoles(): string[];
483
+ /**
484
+ * Get user ID from token
485
+ */
486
+ getUserId(): string | null;
487
+ /**
488
+ * Get username from token
489
+ */
490
+ getUsername(): string | null;
491
+ /**
492
+ * Get user email from token
493
+ */
494
+ getUserEmail(): string | null;
495
+ }
496
+
497
+ /**
498
+ * Auth guard configuration
499
+ */
500
+ interface AuthGuardConfig {
501
+ redirectUrl?: string;
502
+ checkExpiration?: boolean;
503
+ }
504
+ /**
505
+ * Factory function to create an auth guard with configuration
506
+ *
507
+ * @example
508
+ * ```typescript
509
+ * // In routes
510
+ * {
511
+ * path: 'dashboard',
512
+ * component: DashboardComponent,
513
+ * canActivate: [createAuthGuard({ redirectUrl: '/login' })]
514
+ * }
515
+ * ```
516
+ */
517
+ declare function createAuthGuard(config?: AuthGuardConfig): CanActivateFn;
518
+ /**
519
+ * Default auth guard - redirects to '/login' if not authenticated
520
+ */
521
+ declare const authGuard: CanActivateFn;
522
+ /**
523
+ * Permission-based guard factory
524
+ * Checks if user has required permissions from token
525
+ *
526
+ * @example
527
+ * ```typescript
528
+ * {
529
+ * path: 'admin',
530
+ * component: AdminComponent,
531
+ * canActivate: [createPermissionGuard(['admin', 'editor'])]
532
+ * }
533
+ * ```
534
+ */
535
+ declare function createPermissionGuard(requiredPermissions: string[], config?: AuthGuardConfig): CanActivateFn;
536
+ /**
537
+ * Role-based guard factory
538
+ * Checks if user has required role from token
539
+ *
540
+ * @example
541
+ * ```typescript
542
+ * {
543
+ * path: 'admin',
544
+ * component: AdminComponent,
545
+ * canActivate: [createRoleGuard(['admin'])]
546
+ * }
547
+ * ```
548
+ */
549
+ declare function createRoleGuard(requiredRoles: string[], config?: AuthGuardConfig): CanActivateFn;
550
+
551
+ /**
552
+ * Auth interceptor configuration
553
+ */
554
+ interface AuthInterceptorConfig {
555
+ headerName?: string;
556
+ tokenPrefix?: string;
557
+ excludedUrls?: string[];
558
+ }
559
+ /**
560
+ * Configure the auth interceptor
561
+ */
562
+ declare function configureAuthInterceptor(config: AuthInterceptorConfig): void;
563
+ /**
564
+ * Auth Interceptor - Automatically adds authentication token to HTTP requests
565
+ *
566
+ * @example
567
+ * ```typescript
568
+ * // In app.config.ts
569
+ * export const appConfig: ApplicationConfig = {
570
+ * providers: [
571
+ * provideHttpClient(
572
+ * withInterceptors([authInterceptor])
573
+ * )
574
+ * ]
575
+ * };
576
+ * ```
577
+ */
578
+ declare const authInterceptor: HttpInterceptorFn;
579
+
580
+ /**
581
+ * Error handling configuration
582
+ */
583
+ interface ErrorHandlingConfig {
584
+ enableLogging?: boolean;
585
+ retryAttempts?: number;
586
+ retryDelay?: number;
587
+ retryStatusCodes?: number[];
588
+ excludedUrls?: string[];
589
+ }
590
+ /**
591
+ * Configure the error handling interceptor
592
+ */
593
+ declare function configureErrorHandling(config: ErrorHandlingConfig): void;
594
+ /**
595
+ * Error handling interceptor - Handles HTTP errors and retries
596
+ *
597
+ * @example
598
+ * ```typescript
599
+ * // In app.config.ts
600
+ * export const appConfig: ApplicationConfig = {
601
+ * providers: [
602
+ * provideHttpClient(
603
+ * withInterceptors([errorHandlingInterceptor])
604
+ * )
605
+ * ]
606
+ * };
607
+ *
608
+ * // Configure retry behavior
609
+ * configureErrorHandling({
610
+ * retryAttempts: 3,
611
+ * retryDelay: 2000,
612
+ * retryStatusCodes: [500, 502, 503]
613
+ * });
614
+ * ```
615
+ */
616
+ declare const errorHandlingInterceptor: HttpInterceptorFn;
617
+ /**
618
+ * HTTP Error class with additional context
619
+ */
620
+ declare class HttpError extends Error {
621
+ status: number;
622
+ statusText: string;
623
+ url: string;
624
+ originalError: HttpErrorResponse;
625
+ constructor(status: number, statusText: string, url: string, originalError: HttpErrorResponse);
626
+ }
627
+ /**
628
+ * Parse HTTP error and return user-friendly message
629
+ */
630
+ declare function parseHttpError(error: HttpErrorResponse): string;
631
+ /**
632
+ * Check if error is a network error
633
+ */
634
+ declare function isNetworkError(error: HttpErrorResponse): boolean;
635
+ /**
636
+ * Check if error is a server error (5xx)
637
+ */
638
+ declare function isServerError(error: HttpErrorResponse): boolean;
639
+ /**
640
+ * Check if error is a client error (4xx)
641
+ */
642
+ declare function isClientError(error: HttpErrorResponse): boolean;
643
+
644
+ /**
645
+ * Cache configuration
646
+ */
647
+ interface CacheConfig {
648
+ enabled?: boolean;
649
+ maxAge?: number;
650
+ excludedUrls?: string[];
651
+ cacheableUrls?: string[];
652
+ cacheMethods?: string[];
653
+ }
654
+ /**
655
+ * Configure the caching interceptor
656
+ */
657
+ declare function configureCaching(config: CacheConfig): void;
658
+ /**
659
+ * Clear all cached entries
660
+ */
661
+ declare function clearCache(): void;
662
+ /**
663
+ * Clear cache entry for specific URL
664
+ */
665
+ declare function clearCacheEntry(url: string): void;
666
+ /**
667
+ * Caching interceptor - Caches HTTP GET requests
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * // In app.config.ts
672
+ * export const appConfig: ApplicationConfig = {
673
+ * providers: [
674
+ * provideHttpClient(
675
+ * withInterceptors([cachingInterceptor])
676
+ * )
677
+ * ]
678
+ * };
679
+ *
680
+ * // Configure caching
681
+ * configureCaching({
682
+ * enabled: true,
683
+ * maxAge: 300000, // 5 minutes
684
+ * cacheableUrls: ['/api/users', '/api/products']
685
+ * });
686
+ * ```
687
+ */
688
+ declare const cachingInterceptor: HttpInterceptorFn;
689
+
690
+ export { HttpError, LogLevel, LoggerService, NgEventEmitter, PermissionService, StorageService, TokenService, authGuard, authInterceptor, cachingInterceptor, clearCache, clearCacheEntry, configureAuthInterceptor, configureCaching, configureErrorHandling, createAuthGuard, createPermissionGuard, createRoleGuard, errorHandlingInterceptor, isClientError, isNetworkError, isServerError, parseHttpError };
691
+ export type { AuthGuardConfig, AuthInterceptorConfig, CacheConfig, ErrorHandlingConfig, LoggerConfig, TokenConfig };