@opensourcekd/ng-common-libs 1.2.7 → 2.0.0

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.
@@ -1,369 +0,0 @@
1
- import { ReplaySubject, Observable } from 'rxjs';
2
- import { EventType } from 'mitt';
3
-
4
- /**
5
- * EventBusService - Angular service for cross-application event communication
6
- * Uses mitt library for efficient event handling and RxJS ReplaySubject for observable stream
7
- *
8
- * This service is designed for MicroFrontend architectures where different apps need to communicate
9
- * The ReplaySubject keeps last 100 events in memory for late subscribers
10
- *
11
- * @example
12
- * ```typescript
13
- * import { Component, inject, OnInit } from '@angular/core';
14
- * import { EventBusService } from '@opensourcekd/ng-common-libs';
15
- *
16
- * @Component({
17
- * selector: 'app-example',
18
- * template: '...'
19
- * })
20
- * export class ExampleComponent implements OnInit {
21
- * private eventBus = inject(EventBusService);
22
- *
23
- * ngOnInit() {
24
- * // Subscribe to all events
25
- * this.eventBus.onePlusNEvents.subscribe(event => {
26
- * console.log('Event received:', event);
27
- * });
28
- * }
29
- *
30
- * sendCustomEvent() {
31
- * // Send a custom event
32
- * this.eventBus.sendEvent('user:action');
33
- *
34
- * // Or send structured event with data
35
- * this.eventBus.sendEvent(JSON.stringify({
36
- * type: 'user:login',
37
- * payload: { userId: '123' },
38
- * timestamp: new Date().toISOString()
39
- * }));
40
- * }
41
- * }
42
- * ```
43
- */
44
- declare class EventBusService {
45
- /**
46
- * ReplaySubject that buffers the last 100 events for late subscribers
47
- * Subscribe to this observable to receive all events
48
- */
49
- onePlusNEvents: ReplaySubject<EventType>;
50
- /**
51
- * mitt event emitter instance
52
- * Lightweight event emitter library
53
- */
54
- private emitter;
55
- constructor();
56
- /**
57
- * Send an event through the event bus
58
- * The event will be forwarded to all subscribers via the ReplaySubject
59
- *
60
- * @param s - Event string, can be a simple event name or JSON stringified structured data
61
- *
62
- * @example
63
- * ```typescript
64
- * // Simple event
65
- * eventBus.sendEvent('user:logout');
66
- *
67
- * // Structured event
68
- * eventBus.sendEvent(JSON.stringify({
69
- * type: 'auth:token_updated',
70
- * payload: { token: 'abc123' },
71
- * timestamp: new Date().toISOString()
72
- * }));
73
- * ```
74
- */
75
- sendEvent(s: string): void;
76
- }
77
-
78
- /**
79
- * User information from ID token
80
- * Standard OIDC claims compatible with Auth0
81
- */
82
- interface UserInfo {
83
- sub: string;
84
- name?: string;
85
- email?: string;
86
- email_verified?: boolean;
87
- preferred_username?: string;
88
- given_name?: string;
89
- family_name?: string;
90
- nickname?: string;
91
- locale?: string;
92
- picture?: string;
93
- phone?: string;
94
- phone_verified?: boolean;
95
- updated_at?: string;
96
- role?: string;
97
- org?: string;
98
- organization?: string;
99
- [key: string]: any;
100
- }
101
- /**
102
- * Simplified user data extracted from token
103
- */
104
- interface UserData {
105
- id: string;
106
- name: string;
107
- email: string;
108
- role: string;
109
- org: string;
110
- }
111
- /**
112
- * Authentication service for Auth0 integration
113
- * Handles login, logout, token management, and user session
114
- * Uses sessionStorage for sensitive data and emits authentication events for MicroApps
115
- *
116
- * Configuration is centralized in config/auth.config.ts for easy management
117
- *
118
- * NOTE: All navigation logic using setTimeout is commented out as per requirements.
119
- * To enable navigation after auth operations, uncomment the marked sections in consuming components.
120
- */
121
- declare class AuthService {
122
- private eventBus;
123
- private readonly STANDARD_JWT_CLAIMS;
124
- private auth0Client;
125
- private initializationPromise;
126
- private userSubject;
127
- user$: Observable<UserInfo | null>;
128
- constructor(eventBus: EventBusService);
129
- /**
130
- * Initialize Auth0 client
131
- */
132
- private initializeAuth0;
133
- /**
134
- * Ensure Auth0 client is initialized before use
135
- */
136
- private ensureInitialized;
137
- /**
138
- * Login with Auth0
139
- * Redirects to Auth0 Universal Login
140
- * Preserves current URL parameters (like invitation tokens) through the auth flow
141
- *
142
- * @param user - Optional user identifier for logging
143
- * @param options - Optional login options including invitation and organization parameters
144
- */
145
- login(user?: string, options?: {
146
- invitation?: string;
147
- organization?: string;
148
- }): Promise<void>;
149
- /**
150
- * Handle OAuth2 callback after successful authorization
151
- * Processes the callback and retrieves user info
152
- *
153
- * NOTE: Navigation after successful/failed authentication should be handled in the calling component
154
- * using setTimeout. See commented examples in app.component.ts
155
- *
156
- * @returns Promise<{ success: boolean, appState?: any }> - Success status and preserved appState
157
- */
158
- handleCallback(): Promise<{
159
- success: boolean;
160
- appState?: any;
161
- }>;
162
- /**
163
- * Decode and log the access token to console
164
- * NOTE: This logs sensitive token information to console for debugging purposes.
165
- * In production environments, consider disabling this or filtering console logs.
166
- * @param token - The JWT access token
167
- */
168
- private decodeAndLogToken;
169
- /**
170
- * Log all user claims for debugging
171
- * @param user - User info from Auth0
172
- */
173
- private logUserClaims;
174
- /**
175
- * Log standard OIDC claims
176
- * @param user - User info from Auth0
177
- */
178
- private logStandardClaims;
179
- /**
180
- * Log claims with consistent formatting
181
- * @param header - Section header to display
182
- * @param claims - Array of claim keys to log
183
- * @param user - User info object
184
- */
185
- private logClaims;
186
- /**
187
- * Get custom namespaced claims from user info
188
- * @param user - User info object
189
- * @returns Array of custom claim keys
190
- */
191
- private getCustomClaims;
192
- /**
193
- * Get additional non-namespaced claims from user info
194
- * @param user - User info object
195
- * @returns Array of additional claim keys
196
- */
197
- private getAdditionalClaims;
198
- /**
199
- * Check if a claim key is namespaced
200
- * @param key - Claim key to check
201
- * @returns True if the key starts with http:// or https://
202
- */
203
- private isNamespacedClaim;
204
- /**
205
- * Logout user and clear authentication state
206
- * Redirects to Auth0 logout endpoint and clears local state
207
- */
208
- logout(): Promise<void>;
209
- /**
210
- * Get current access token from storage or Auth0 client
211
- * @returns string | null - Access token or null if not authenticated
212
- */
213
- getToken(): Promise<string | null>;
214
- /**
215
- * Get current access token synchronously from storage only
216
- * Use this for synchronous operations like interceptors
217
- * @returns string | null - Access token or null if not authenticated
218
- */
219
- getTokenSync(): string | null;
220
- /**
221
- * Set access token in storage and emit event for MicroApps
222
- * @param token - Access token to store
223
- */
224
- private setToken;
225
- /**
226
- * Check if user is authenticated
227
- * @returns boolean - True if user has valid token
228
- */
229
- isAuthenticated(): Promise<boolean>;
230
- /**
231
- * Check if user is authenticated synchronously
232
- * Only checks storage, doesn't verify with Auth0
233
- * @returns boolean - True if user has token in storage
234
- */
235
- isAuthenticatedSync(): boolean;
236
- /**
237
- * Get current user information
238
- * @returns UserInfo | null - Current user or null if not authenticated
239
- */
240
- getUser(): UserInfo | null;
241
- /**
242
- * Get simplified user data from token
243
- * Extracts user details, role, and organization from ID token claims
244
- * Checks both top-level claims and namespaced custom claims
245
- * @returns UserData | null - Simplified user data or null if not authenticated
246
- */
247
- getUserData(): UserData | null;
248
- /**
249
- * Extract claim value from user info, checking both direct properties and namespaced custom claims
250
- * @param userInfo - User info object
251
- * @param claimNames - Single claim name or array of claim names to search for
252
- * @param defaultValue - Default value if claim is not found
253
- * @returns Extracted claim value or default value
254
- */
255
- private extractClaimValue;
256
- /**
257
- * Get user information from storage
258
- * @returns UserInfo | null - Stored user info or null
259
- */
260
- private getUserInfoFromStorage;
261
- /**
262
- * Set user information in storage, update observable and emit event for MicroApps
263
- * Logs all Auth0 claims for debugging
264
- * @param userInfo - User information to store
265
- */
266
- private setUserInfo;
267
- /**
268
- * Emit authentication event for MicroApps to consume
269
- * Events are emitted via EventBus for cross-MFE communication
270
- * @param eventType - Type of authentication event
271
- * @param payload - Event payload
272
- */
273
- private emitAuthEvent;
274
- }
275
-
276
- /**
277
- * Auth0 Configuration
278
- * Centralized configuration for Auth0 integration
279
- *
280
- * Environment variables are typically set in consuming applications
281
- * Default values are provided for development/testing
282
- */
283
- /**
284
- * Auth0 client configuration
285
- * Override these values in your consuming application by setting them before importing AuthService
286
- *
287
- * Note: redirectUri defaults to window.location.origin (base URL without path).
288
- * Auth0 will redirect back to this URL after authentication.
289
- * You can override this to a specific callback URL (e.g., '/auth-callback') using configureAuth0().
290
- */
291
- declare const AUTH0_CONFIG: {
292
- domain: string;
293
- clientId: string;
294
- redirectUri: string;
295
- logoutUri: string;
296
- audience: string;
297
- scope: string;
298
- connection: string | undefined;
299
- };
300
- /**
301
- * Storage configuration
302
- * Controls where sensitive data is stored
303
- */
304
- declare const STORAGE_CONFIG: {
305
- TOKEN_STORAGE: "localStorage" | "sessionStorage";
306
- USER_INFO_STORAGE: "localStorage" | "sessionStorage";
307
- };
308
- /**
309
- * Storage keys for auth data
310
- */
311
- declare const STORAGE_KEYS: {
312
- ACCESS_TOKEN: string;
313
- USER_INFO: string;
314
- };
315
- /**
316
- * Helper functions for storage operations
317
- * These work with both localStorage and sessionStorage
318
- */
319
- /**
320
- * Get item from storage
321
- * @param key - Storage key
322
- * @param storageType - Type of storage to use
323
- * @returns Stored value or null
324
- */
325
- declare function getStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): string | null;
326
- /**
327
- * Set item in storage
328
- * @param key - Storage key
329
- * @param value - Value to store
330
- * @param storageType - Type of storage to use
331
- */
332
- declare function setStorageItem(key: string, value: string, storageType?: 'localStorage' | 'sessionStorage'): void;
333
- /**
334
- * Remove item from storage
335
- * @param key - Storage key
336
- * @param storageType - Type of storage to use
337
- */
338
- declare function removeStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): void;
339
- /**
340
- * Configure Auth0 settings (OPTIONAL)
341
- * Call this function in your consuming application to override default Auth0 configuration.
342
- * Only the values you provide will be overridden; all other defaults remain unchanged.
343
- *
344
- * Note: This function is optional. If not called, default values will be used.
345
- *
346
- * @param config - Partial Auth0 configuration object with values to override
347
- *
348
- * @example
349
- * ```typescript
350
- * import { configureAuth0 } from '@opensourcekd/ng-common-libs';
351
- *
352
- * // Only override specific values - others keep their defaults
353
- * configureAuth0({
354
- * domain: 'your-domain.auth0.com',
355
- * clientId: 'your-client-id',
356
- * audience: 'https://your-api.com'
357
- * // redirectUri, logoutUri, scope, etc. will use defaults
358
- * });
359
- *
360
- * // Or override just redirectUri to use a specific callback page
361
- * configureAuth0({
362
- * redirectUri: window.location.origin + '/auth-callback'
363
- * });
364
- * ```
365
- */
366
- declare function configureAuth0(config: Partial<typeof AUTH0_CONFIG>): void;
367
-
368
- export { AUTH0_CONFIG, AuthService, EventBusService, STORAGE_CONFIG, STORAGE_KEYS, configureAuth0, getStorageItem, removeStorageItem, setStorageItem };
369
- export type { UserData, UserInfo };