@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,332 @@
1
+ import { Observable } from 'rxjs';
2
+
3
+ /**
4
+ * Event payload interface
5
+ */
6
+ interface EventPayload<T = any> {
7
+ type: string;
8
+ data: T;
9
+ timestamp?: number;
10
+ }
11
+ /**
12
+ * EventBus - A centralized event bus for application-wide communication
13
+ * Framework-agnostic implementation using only RxJS
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * // Create an instance
18
+ * const eventBus = new EventBus();
19
+ *
20
+ * // Emit an event
21
+ * eventBus.emit('user:login', { userId: '123', username: 'john' });
22
+ *
23
+ * // Subscribe to an event
24
+ * eventBus.on('user:login').subscribe(data => {
25
+ * console.log('User logged in:', data);
26
+ * });
27
+ * ```
28
+ */
29
+ declare class EventBus {
30
+ private eventSubject;
31
+ /**
32
+ * Emit an event with optional data
33
+ * @param eventType - The type/name of the event
34
+ * @param data - Optional data to send with the event
35
+ */
36
+ emit<T = any>(eventType: string, data?: T): void;
37
+ /**
38
+ * Subscribe to a specific event type
39
+ * @param eventType - The type/name of the event to listen for
40
+ * @returns Observable that emits the event data
41
+ */
42
+ on<T = any>(eventType: string): Observable<T>;
43
+ /**
44
+ * Subscribe to multiple event types
45
+ * @param eventTypes - Array of event types to listen for
46
+ * @returns Observable that emits the full event payload
47
+ */
48
+ onMultiple(eventTypes: string[]): Observable<EventPayload>;
49
+ /**
50
+ * Subscribe to all events
51
+ * @returns Observable that emits all event payloads
52
+ */
53
+ onAll(): Observable<EventPayload>;
54
+ }
55
+
56
+ /**
57
+ * Token configuration interface
58
+ */
59
+ interface TokenConfig {
60
+ tokenKey?: string;
61
+ refreshTokenKey?: string;
62
+ useSessionStorage?: boolean;
63
+ }
64
+ /**
65
+ * TokenManager - Manages authentication tokens
66
+ * Framework-agnostic implementation using browser storage APIs
67
+ * Handles storage, retrieval, and validation of JWT tokens
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const tokenManager = new TokenManager();
72
+ *
73
+ * // Store a token
74
+ * tokenManager.setToken('your-jwt-token');
75
+ *
76
+ * // Check if authenticated
77
+ * if (tokenManager.isAuthenticated()) {
78
+ * const userData = tokenManager.getUserFromToken();
79
+ * }
80
+ * ```
81
+ */
82
+ declare class TokenManager {
83
+ private TOKEN_KEY;
84
+ private REFRESH_TOKEN_KEY;
85
+ private useSessionStorage;
86
+ /**
87
+ * Configure token manager
88
+ */
89
+ configure(config: TokenConfig): void;
90
+ /**
91
+ * Get the storage mechanism based on configuration
92
+ */
93
+ private getStorage;
94
+ /**
95
+ * Set authentication token
96
+ */
97
+ setToken(token: string): void;
98
+ /**
99
+ * Get authentication token
100
+ */
101
+ getToken(): string | null;
102
+ /**
103
+ * Remove authentication token
104
+ */
105
+ removeToken(): void;
106
+ /**
107
+ * Set refresh token
108
+ */
109
+ setRefreshToken(token: string): void;
110
+ /**
111
+ * Get refresh token
112
+ */
113
+ getRefreshToken(): string | null;
114
+ /**
115
+ * Remove refresh token
116
+ */
117
+ removeRefreshToken(): void;
118
+ /**
119
+ * Clear all tokens
120
+ */
121
+ clearTokens(): void;
122
+ /**
123
+ * Check if token exists
124
+ */
125
+ hasToken(): boolean;
126
+ /**
127
+ * Decode JWT token (without verification)
128
+ * @param token - JWT token to decode
129
+ * @returns Decoded token payload or null if invalid
130
+ */
131
+ decodeToken(token?: string): any;
132
+ /**
133
+ * Check if token is expired
134
+ * @param token - Optional token to check (defaults to stored token)
135
+ * @returns true if token is expired or invalid
136
+ */
137
+ isTokenExpired(token?: string): boolean;
138
+ /**
139
+ * Check if user is authenticated (has valid, non-expired token)
140
+ */
141
+ isAuthenticated(): boolean;
142
+ /**
143
+ * Get token expiration date
144
+ */
145
+ getTokenExpirationDate(token?: string): Date | null;
146
+ /**
147
+ * Get user data from token
148
+ */
149
+ getUserFromToken(token?: string): any;
150
+ }
151
+
152
+ /**
153
+ * StorageManager - Type-safe wrapper for browser storage
154
+ * Framework-agnostic implementation using browser storage APIs
155
+ * Provides JSON serialization/deserialization and error handling
156
+ *
157
+ * @example
158
+ * ```typescript
159
+ * const storage = new StorageManager();
160
+ *
161
+ * // Store data
162
+ * storage.setLocal('user-prefs', { theme: 'dark', lang: 'en' });
163
+ *
164
+ * // Retrieve data
165
+ * const prefs = storage.getLocal('user-prefs');
166
+ *
167
+ * // With expiration
168
+ * storage.setWithExpiration('temp-data', someData, 3600000); // 1 hour
169
+ * ```
170
+ */
171
+ declare class StorageManager {
172
+ /**
173
+ * Set item in localStorage with JSON serialization
174
+ */
175
+ setLocal<T>(key: string, value: T): boolean;
176
+ /**
177
+ * Get item from localStorage with JSON deserialization
178
+ */
179
+ getLocal<T>(key: string, defaultValue?: T): T | null;
180
+ /**
181
+ * Remove item from localStorage
182
+ */
183
+ removeLocal(key: string): void;
184
+ /**
185
+ * Clear all localStorage items
186
+ */
187
+ clearLocal(): void;
188
+ /**
189
+ * Check if key exists in localStorage
190
+ */
191
+ hasLocal(key: string): boolean;
192
+ /**
193
+ * Get all localStorage keys
194
+ */
195
+ getLocalKeys(): string[];
196
+ /**
197
+ * Set item in sessionStorage with JSON serialization
198
+ */
199
+ setSession<T>(key: string, value: T): boolean;
200
+ /**
201
+ * Get item from sessionStorage with JSON deserialization
202
+ */
203
+ getSession<T>(key: string, defaultValue?: T): T | null;
204
+ /**
205
+ * Remove item from sessionStorage
206
+ */
207
+ removeSession(key: string): void;
208
+ /**
209
+ * Clear all sessionStorage items
210
+ */
211
+ clearSession(): void;
212
+ /**
213
+ * Check if key exists in sessionStorage
214
+ */
215
+ hasSession(key: string): boolean;
216
+ /**
217
+ * Get all sessionStorage keys
218
+ */
219
+ getSessionKeys(): string[];
220
+ /**
221
+ * Set item with expiration time
222
+ * @param key - Storage key
223
+ * @param value - Value to store
224
+ * @param expirationMs - Expiration time in milliseconds
225
+ * @param useSession - Use sessionStorage instead of localStorage
226
+ */
227
+ setWithExpiration<T>(key: string, value: T, expirationMs: number, useSession?: boolean): boolean;
228
+ /**
229
+ * Get item with expiration check
230
+ * Returns null if item is expired
231
+ */
232
+ getWithExpiration<T>(key: string, useSession?: boolean): T | null;
233
+ }
234
+
235
+ /**
236
+ * Log level enum
237
+ */
238
+ declare enum LogLevel {
239
+ DEBUG = 0,
240
+ INFO = 1,
241
+ WARN = 2,
242
+ ERROR = 3,
243
+ NONE = 4
244
+ }
245
+ /**
246
+ * Logger configuration
247
+ */
248
+ interface LoggerConfig {
249
+ level?: LogLevel;
250
+ enableTimestamp?: boolean;
251
+ enableStackTrace?: boolean;
252
+ prefix?: string;
253
+ }
254
+ /**
255
+ * Logger - Centralized logging utility
256
+ * Framework-agnostic implementation using browser console APIs
257
+ * Supports different log levels and can be configured globally
258
+ *
259
+ * @example
260
+ * ```typescript
261
+ * const logger = new Logger();
262
+ *
263
+ * // Configure
264
+ * logger.configure({
265
+ * level: LogLevel.DEBUG,
266
+ * enableTimestamp: true,
267
+ * prefix: 'MyApp'
268
+ * });
269
+ *
270
+ * // Use
271
+ * logger.info('User logged in', { userId: '123' });
272
+ * logger.error('Failed to load data', error);
273
+ * ```
274
+ */
275
+ declare class Logger {
276
+ private config;
277
+ /**
278
+ * Configure the logger
279
+ */
280
+ configure(config: LoggerConfig): void;
281
+ /**
282
+ * Set log level
283
+ */
284
+ setLevel(level: LogLevel): void;
285
+ /**
286
+ * Get current log level
287
+ */
288
+ getLevel(): LogLevel;
289
+ /**
290
+ * Format log message with timestamp and prefix
291
+ */
292
+ private formatMessage;
293
+ /**
294
+ * Check if log level should be logged
295
+ */
296
+ private shouldLog;
297
+ /**
298
+ * Log debug message
299
+ */
300
+ debug(message: string, ...args: any[]): void;
301
+ /**
302
+ * Log info message
303
+ */
304
+ info(message: string, ...args: any[]): void;
305
+ /**
306
+ * Log warning message
307
+ */
308
+ warn(message: string, ...args: any[]): void;
309
+ /**
310
+ * Log error message
311
+ */
312
+ error(message: string, error?: any, ...args: any[]): void;
313
+ /**
314
+ * Log a group of messages
315
+ */
316
+ group(label: string, callback: () => void): void;
317
+ /**
318
+ * Log a collapsed group of messages
319
+ */
320
+ groupCollapsed(label: string, callback: () => void): void;
321
+ /**
322
+ * Log a table (useful for arrays of objects)
323
+ */
324
+ table(data: any, columns?: string[]): void;
325
+ /**
326
+ * Log execution time of a function
327
+ */
328
+ time<T>(label: string, fn: () => Promise<T> | T): Promise<T>;
329
+ }
330
+
331
+ export { EventBus, LogLevel, Logger, StorageManager, TokenManager };
332
+ export type { EventPayload, LoggerConfig, TokenConfig };