@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/README.md CHANGED
@@ -1,24 +1,18 @@
1
1
  # ng-common-libs
2
2
 
3
- Angular 18 shareable utility library with framework-agnostic core and Angular wrappers for event handling, authorization, storage management, logging, and HTTP operations.
3
+ Angular 18 library with Auth0 authentication service and MicroFrontend event bus.
4
4
 
5
5
  ## 🎯 Dual-Layer Architecture
6
6
 
7
7
  This library features a **dual-layer architecture**:
8
8
 
9
- - **Core Layer** (`@opensourcekd/ng-common-libs/core`): Framework-agnostic utilities using only RxJS and browser APIs. Use these in React, Vue, Svelte, or vanilla JavaScript projects.
10
- - **Angular Layer** (`@opensourcekd/ng-common-libs` or `/angular`): Angular-specific wrappers with dependency injection, plus guards and interceptors that require Angular.
9
+ - **Core Layer** (`@opensourcekd/ng-common-libs/core`): Framework-agnostic event bus using only RxJS. Use in React, Vue, Svelte, or vanilla JavaScript projects.
10
+ - **Angular Layer** (`@opensourcekd/ng-common-libs` or `/angular`): Angular-specific services with dependency injection.
11
11
 
12
12
  ## 🚀 Features
13
13
 
14
- - **Event Bus**: Centralized event communication (framework-agnostic)
15
14
  - **EventBusService**: MicroFrontend-ready event bus with replay buffer for cross-app communication
16
15
  - **Auth0 Integration**: Complete Auth0 authentication service with token management
17
- - **Token Manager**: JWT token management and validation (framework-agnostic)
18
- - **Storage Manager**: Type-safe localStorage/sessionStorage wrapper (framework-agnostic)
19
- - **Logger**: Configurable logging with multiple levels (framework-agnostic)
20
- - **Authorization**: Angular guards, interceptors, and permission handling
21
- - **HTTP Utilities**: Error handling, caching, and retry logic for Angular HTTP requests
22
16
 
23
17
  ## 📦 Installation
24
18
 
@@ -32,69 +26,6 @@ npm install @opensourcekd/ng-common-libs
32
26
 
33
27
  ## 🔧 Usage
34
28
 
35
- ### For Angular Projects
36
-
37
- Use the Angular-specific imports that provide dependency injection:
38
-
39
- ```typescript
40
- import { Component, OnInit, inject } from '@angular/core';
41
- import { NgEventEmitter } from '@opensourcekd/ng-common-libs';
42
-
43
- @Component({
44
- selector: 'app-example',
45
- template: `...`
46
- })
47
- export class ExampleComponent implements OnInit {
48
- private eventEmitter = inject(NgEventEmitter);
49
-
50
- ngOnInit() {
51
- // Subscribe to events
52
- this.eventEmitter.on('user:login').subscribe(data => {
53
- console.log('User logged in:', data);
54
- });
55
- }
56
-
57
- login() {
58
- // Emit events
59
- this.eventEmitter.emit('user:login', {
60
- userId: '123',
61
- username: 'john'
62
- });
63
- }
64
- }
65
- ```
66
-
67
- ### Authorization
68
-
69
- #### Token Service
70
-
71
- Manage authentication tokens with ease:
72
-
73
- ```typescript
74
- import { inject } from '@angular/core';
75
- import { TokenService } from '@opensourcekd/ng-common-libs';
76
-
77
- export class AuthService {
78
- private tokenService = inject(TokenService);
79
-
80
- login(token: string) {
81
- this.tokenService.setToken(token);
82
- }
83
-
84
- logout() {
85
- this.tokenService.clearTokens();
86
- }
87
-
88
- isAuthenticated(): boolean {
89
- return this.tokenService.isAuthenticated();
90
- }
91
-
92
- getUserData() {
93
- return this.tokenService.getUserFromToken();
94
- }
95
- }
96
- ```
97
-
98
29
  ### Auth0 Authentication
99
30
 
100
31
  Complete Auth0 integration with automatic token management and event emission:
@@ -169,198 +100,13 @@ export class EventExampleComponent implements OnInit {
169
100
 
170
101
  See the [EventBus Service Usage Guide](./docs/EVENT_BUS_USAGE.md) for advanced patterns and MicroFrontend examples.
171
102
 
172
- #### Auth Guard
173
-
174
- Protect routes with authentication guards:
175
-
176
- ```typescript
177
- import { Routes } from '@angular/router';
178
- import { authGuard, createRoleGuard } from '@opensourcekd/ng-common-libs';
179
-
180
- export const routes: Routes = [
181
- {
182
- path: 'dashboard',
183
- component: DashboardComponent,
184
- canActivate: [authGuard]
185
- },
186
- {
187
- path: 'admin',
188
- component: AdminComponent,
189
- canActivate: [createRoleGuard(['admin'], { redirectUrl: '/unauthorized' })]
190
- }
191
- ];
192
- ```
193
-
194
- #### Auth Interceptor
195
-
196
- Automatically add authentication tokens to HTTP requests:
197
-
198
- ```typescript
199
- import { ApplicationConfig } from '@angular/core';
200
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
201
- import { authInterceptor, configureAuthInterceptor } from '@opensourcekd/ng-common-libs';
202
-
203
- // Configure the interceptor (optional)
204
- configureAuthInterceptor({
205
- headerName: 'Authorization',
206
- tokenPrefix: 'Bearer',
207
- excludedUrls: ['/auth/login', '/auth/register']
208
- });
209
-
210
- export const appConfig: ApplicationConfig = {
211
- providers: [
212
- provideHttpClient(
213
- withInterceptors([authInterceptor])
214
- )
215
- ]
216
- };
217
- ```
218
-
219
- #### Permission Service
220
-
221
- Check user permissions and roles:
222
-
223
- ```typescript
224
- import { inject } from '@angular/core';
225
- import { PermissionService } from '@opensourcekd/ng-common-libs';
226
-
227
- export class MyComponent {
228
- private permissionService = inject(PermissionService);
229
-
230
- canEditPost(): boolean {
231
- return this.permissionService.hasPermission('posts:edit');
232
- }
233
-
234
- isAdmin(): boolean {
235
- return this.permissionService.hasRole('admin');
236
- }
237
- }
238
- ```
239
-
240
- ### Storage Service
241
-
242
- Type-safe storage operations with JSON serialization:
243
-
244
- ```typescript
245
- import { inject } from '@angular/core';
246
- import { StorageService } from '@opensourcekd/ng-common-libs';
247
-
248
- export class UserPreferencesService {
249
- private storage = inject(StorageService);
250
-
251
- savePreferences(prefs: UserPreferences) {
252
- this.storage.setLocal('user-prefs', prefs);
253
- }
254
-
255
- getPreferences(): UserPreferences | null {
256
- return this.storage.getLocal<UserPreferences>('user-prefs');
257
- }
258
-
259
- // With expiration (1 hour)
260
- saveTempData(data: any) {
261
- this.storage.setWithExpiration('temp-data', data, 3600000);
262
- }
263
-
264
- getTempData() {
265
- return this.storage.getWithExpiration('temp-data');
266
- }
267
- }
268
- ```
269
-
270
- ### Logger Service
271
-
272
- Centralized logging with configurable levels:
273
-
274
- ```typescript
275
- import { inject } from '@angular/core';
276
- import { LoggerService, LogLevel } from '@opensourcekd/ng-common-libs';
277
-
278
- export class MyService {
279
- private logger = inject(LoggerService);
280
-
281
- constructor() {
282
- // Configure logger
283
- this.logger.configure({
284
- level: LogLevel.DEBUG,
285
- enableTimestamp: true,
286
- prefix: 'MyApp'
287
- });
288
- }
289
-
290
- doSomething() {
291
- this.logger.debug('Debug message');
292
- this.logger.info('Info message');
293
- this.logger.warn('Warning message');
294
- this.logger.error('Error message', new Error('Something went wrong'));
295
-
296
- // Measure execution time
297
- this.logger.time('fetchData', async () => {
298
- return await this.fetchData();
299
- });
300
- }
301
- }
302
- ```
303
-
304
- ### HTTP Utilities
305
-
306
- #### Error Handling Interceptor
307
-
308
- Handle HTTP errors with automatic retry:
309
-
310
- ```typescript
311
- import { ApplicationConfig } from '@angular/core';
312
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
313
- import { errorHandlingInterceptor, configureErrorHandling } from '@opensourcekd/ng-common-libs';
314
-
315
- // Configure error handling
316
- configureErrorHandling({
317
- enableLogging: true,
318
- retryAttempts: 3,
319
- retryDelay: 1000,
320
- retryStatusCodes: [500, 502, 503, 504]
321
- });
322
-
323
- export const appConfig: ApplicationConfig = {
324
- providers: [
325
- provideHttpClient(
326
- withInterceptors([errorHandlingInterceptor])
327
- )
328
- ]
329
- };
330
- ```
331
-
332
- #### Caching Interceptor
333
-
334
- Cache HTTP responses:
335
-
336
- ```typescript
337
- import { ApplicationConfig } from '@angular/core';
338
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
339
- import { cachingInterceptor, configureCaching } from '@opensourcekd/ng-common-libs';
340
-
341
- // Configure caching
342
- configureCaching({
343
- enabled: true,
344
- maxAge: 300000, // 5 minutes
345
- cacheableUrls: ['/api/users', '/api/products']
346
- });
347
-
348
- export const appConfig: ApplicationConfig = {
349
- providers: [
350
- provideHttpClient(
351
- withInterceptors([cachingInterceptor])
352
- )
353
- ]
354
- };
355
- ```
356
-
357
103
  ### For Non-Angular Projects (React, Vue, Svelte, Vanilla JS)
358
104
 
359
- Use the framework-agnostic core utilities:
105
+ Use the framework-agnostic core event bus:
360
106
 
361
107
  ```typescript
362
108
  // Import from /core
363
- import { EventBus, TokenManager, StorageManager, Logger, LogLevel } from '@opensourcekd/ng-common-libs/core';
109
+ import { EventBus } from '@opensourcekd/ng-common-libs/core';
364
110
 
365
111
  // Event Bus
366
112
  const eventBus = new EventBus();
@@ -368,23 +114,6 @@ eventBus.emit('user:login', { userId: '123' });
368
114
  eventBus.on('user:login').subscribe(data => {
369
115
  console.log('User logged in:', data);
370
116
  });
371
-
372
- // Token Manager
373
- const tokenManager = new TokenManager();
374
- tokenManager.setToken('your-jwt-token');
375
- if (tokenManager.isAuthenticated()) {
376
- const user = tokenManager.getUserFromToken();
377
- }
378
-
379
- // Storage Manager
380
- const storage = new StorageManager();
381
- storage.setLocal('preferences', { theme: 'dark' });
382
- const prefs = storage.getLocal('preferences');
383
-
384
- // Logger
385
- const logger = new Logger();
386
- logger.configure({ level: LogLevel.DEBUG, prefix: 'MyApp' });
387
- logger.info('Application started');
388
117
  ```
389
118
 
390
119
  #### React Example
@@ -444,51 +173,36 @@ export default {
444
173
 
445
174
  ## 📚 Documentation
446
175
 
447
- - **[Usage Guide](./docs/USAGE.md)** - Complete usage examples for all utilities
448
- - **[API Reference](./docs/API.md)** - Detailed API documentation
449
176
  - **[Auth0 Service Usage](./docs/AUTH_SERVICE_USAGE.md)** - Complete Auth0 authentication integration guide
450
177
  - **[EventBus Service Usage](./docs/EVENT_BUS_USAGE.md)** - Cross-application event communication guide
451
178
  - **[Deployment Guide](./docs/DEPLOYMENT.md)** - Publishing, versioning, and consumption
452
179
  - **[Microapp Triggering Guide](./docs/MICROAPP_TRIGGERING.md)** - Automatic build triggering for consuming microapps
453
180
  - **[Module Federation Guide](./docs/MODULE_FEDERATION.md)** - Runtime sharing with Module Federation
454
- - **[Architecture Decisions](./ARCHITECTURE_DECISIONS.md)** - Detailed architecture and design decisions
455
181
 
456
182
  ## 📝 API Documentation
457
183
 
458
- ### NgEventEmitter
459
-
460
- - `emit<T>(eventType: string, data?: T): void` - Emit an event
461
- - `on<T>(eventType: string): Observable<T>` - Subscribe to an event
462
- - `onMultiple(eventTypes: string[]): Observable<EventPayload>` - Subscribe to multiple events
463
- - `onAll(): Observable<EventPayload>` - Subscribe to all events
184
+ ### AuthService
464
185
 
465
- ### TokenService
186
+ - `login(options?: RedirectLoginOptions): Promise<void>` - Initiate Auth0 login
187
+ - `logout(options?: LogoutOptions): Promise<void>` - Logout and clear session
188
+ - `handleCallback(): Promise<{ success: boolean, appState?: any }>` - Handle Auth0 callback
189
+ - `getToken(): Promise<string | null>` - Get access token asynchronously
190
+ - `getTokenSync(): string | null` - Get cached access token synchronously
191
+ - `getUser(): Signal<UserInfo | null>` - Get user information as signal
192
+ - `isAuthenticated(): Signal<boolean>` - Check authentication status
193
+ - `isLoading(): Signal<boolean>` - Check if authentication is loading
466
194
 
467
- - `setToken(token: string): void` - Store authentication token
468
- - `getToken(): string | null` - Retrieve authentication token
469
- - `removeToken(): void` - Remove authentication token
470
- - `clearTokens(): void` - Clear all tokens
471
- - `isAuthenticated(): boolean` - Check if user is authenticated
472
- - `isTokenExpired(token?: string): boolean` - Check if token is expired
473
- - `getUserFromToken(token?: string): any` - Extract user data from token
474
-
475
- ### StorageService
195
+ ### EventBusService
476
196
 
477
- - `setLocal<T>(key: string, value: T): boolean` - Set item in localStorage
478
- - `getLocal<T>(key: string, defaultValue?: T): T | null` - Get item from localStorage
479
- - `removeLocal(key: string): void` - Remove item from localStorage
480
- - `setSession<T>(key: string, value: T): boolean` - Set item in sessionStorage
481
- - `getSession<T>(key: string, defaultValue?: T): T | null` - Get item from sessionStorage
482
- - `setWithExpiration<T>(key, value, expirationMs, useSession?): boolean` - Set item with expiration
483
- - `getWithExpiration<T>(key, useSession?): T | null` - Get item with expiration check
197
+ - `sendEvent(event: string): void` - Send event to all subscribers
198
+ - `onePlusNEvents: Observable<string>` - Subscribe to all events with replay buffer
484
199
 
485
- ### LoggerService
200
+ ### EventBus (Core)
486
201
 
487
- - `debug(message: string, ...args: any[]): void` - Log debug message
488
- - `info(message: string, ...args: any[]): void` - Log info message
489
- - `warn(message: string, ...args: any[]): void` - Log warning message
490
- - `error(message: string, error?: any, ...args: any[]): void` - Log error message
491
- - `time<T>(label: string, fn: () => Promise<T> | T): Promise<T>` - Measure execution time
202
+ - `emit<T>(eventType: string, data?: T): void` - Emit an event
203
+ - `on<T>(eventType: string): Observable<T>` - Subscribe to an event
204
+ - `onMultiple(eventTypes: string[]): Observable<EventPayload>` - Subscribe to multiple events
205
+ - `onAll(): Observable<EventPayload>` - Subscribe to all events
492
206
 
493
207
  ## 🛠️ Development
494
208
 
@@ -518,4 +232,3 @@ Contributions, issues, and feature requests are welcome!
518
232
  ## ⭐ Show your support
519
233
 
520
234
  Give a ⭐️ if this project helped you!
521
-