@opensourcekd/ng-common-libs 1.2.8 → 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.
package/README.md CHANGED
@@ -2,18 +2,33 @@
2
2
 
3
3
  Angular 18 library with Auth0 authentication service and MicroFrontend event bus.
4
4
 
5
- ## 🎯 Dual-Layer Architecture
5
+ ## 🎯 Simple Architecture
6
6
 
7
- This library features a **dual-layer architecture**:
7
+ **One import path. Everything you need.**
8
8
 
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.
9
+ All services, utilities, and types are exported from a single package:
10
+
11
+ ```typescript
12
+ import {
13
+ AuthService,
14
+ EventBusService,
15
+ getAuthService,
16
+ getEventBusService,
17
+ configureAuth0,
18
+ UserInfo,
19
+ EventBus
20
+ } from '@opensourcekd/ng-common-libs';
21
+ ```
22
+
23
+ > 📖 **Complete Guide**: See [CONSUMPTION_GUIDE.md](./CONSUMPTION_GUIDE.md) for detailed usage instructions.
11
24
 
12
25
  ## 🚀 Features
13
26
 
14
- - **APP_CONFIG**: Framework-agnostic configuration utility for all environment variables (Auth0, API URLs)
15
- - **EventBusService**: MicroFrontend-ready event bus with replay buffer for cross-app communication
16
- - **Auth0 Integration**: Complete Auth0 authentication service with token management
27
+ - **AuthService**: Complete Auth0 authentication with token management
28
+ - **EventBusService**: MicroFrontend-ready event bus with replay buffer
29
+ - **Module Federation Support**: Singleton pattern works across shell + MFEs
30
+ - **AOT-Safe**: No JIT compiler required, works in production builds
31
+ - **Framework-Agnostic Core**: EventBus can be used in React, Vue, or vanilla JS
17
32
 
18
33
  ## 📦 Installation
19
34
 
@@ -21,17 +36,13 @@ This library features a **dual-layer architecture**:
21
36
  npm install @opensourcekd/ng-common-libs
22
37
  ```
23
38
 
24
- > **Note:** `mitt` and `@auth0/auth0-spa-js` are bundled with the library. You don't need to install them separately.
25
- >
26
- > **Module Federation**: Just configure `@opensourcekd/ng-common-libs` as shared in your webpack config. The bundled dependencies (`mitt`, `@auth0/auth0-spa-js`) will be included automatically, ensuring they're loaded only once across all micro-frontends.
39
+ > **Note:** `mitt` and `@auth0/auth0-spa-js` are bundled. No separate installation needed.
27
40
 
28
- ## 🔧 Usage
41
+ ## 🔧 Quick Start
29
42
 
30
- ### ⚠️ IMPORTANT: Setup for Module Federation / MicroFrontends
43
+ ### For Module Federation (Shell + MFEs)
31
44
 
32
- If you're using **Module Federation** with multiple Angular applications (shell + MFEs), you **MUST** configure the services as singletons using factory functions. This ensures ONE instance is shared across all applications.
33
-
34
- **In your shell app AND each MFE's `app.config.ts` (standalone) or `app.module.ts` (NgModule):**
45
+ **In your shell app AND each MFE's `app.config.ts`:**
35
46
 
36
47
  ```typescript
37
48
  import { ApplicationConfig } from '@angular/core';
@@ -42,264 +53,92 @@ import {
42
53
  getEventBusService,
43
54
  configureAuth0
44
55
  } from '@opensourcekd/ng-common-libs';
45
- import { APP_CONFIG } from '@opensourcekd/ng-common-libs/core';
46
56
 
47
- // Configure Auth0 (do this once in shell or each MFE)
57
+ // Configure Auth0 once in shell (use your environment config)
48
58
  configureAuth0({
49
- domain: APP_CONFIG.auth0Domain,
50
- clientId: APP_CONFIG.auth0ClientId,
51
- audience: APP_CONFIG.apiUrl,
59
+ domain: 'your-tenant.auth0.com',
60
+ clientId: 'your-client-id',
61
+ audience: 'https://your-api.example.com',
52
62
  });
53
63
 
54
64
  export const appConfig: ApplicationConfig = {
55
65
  providers: [
56
- // REQUIRED: Use factory functions for singleton behavior across MFEs
66
+ // Factory functions ensure singleton across all MFEs
57
67
  { provide: EventBusService, useFactory: getEventBusService },
58
68
  { provide: AuthService, useFactory: getAuthService },
59
- // ... your other providers
60
69
  ]
61
70
  };
62
71
  ```
63
72
 
64
- **Why is this needed?**
65
- Angular's `providedIn: 'root'` creates one instance per Angular application. In Module Federation, each MFE is a separate Angular app, so you'd get multiple instances. Factory functions create a **JavaScript module-level singleton** that's shared across ALL applications.
73
+ **Why factory functions?**
74
+ They create a **JavaScript module-level singleton** shared across ALL applications (shell + MFEs). Module Federation ensures the module loads once, so all apps get the same instance.
66
75
 
67
- **For NgModule-based apps:**
68
- ```typescript
69
- import { NgModule } from '@angular/core';
70
- import {
71
- AuthService,
72
- EventBusService,
73
- getAuthService,
74
- getEventBusService
75
- } from '@opensourcekd/ng-common-libs';
76
-
77
- @NgModule({
78
- providers: [
79
- { provide: EventBusService, useFactory: getEventBusService },
80
- { provide: AuthService, useFactory: getAuthService }
81
- ]
82
- })
83
- export class AppModule { }
84
- ```
76
+ ### For Standalone Components
85
77
 
86
- Then use normally in components with `inject()`:
78
+ Then use normally with `inject()`:
87
79
  ```typescript
80
+ import { Component, inject } from '@angular/core';
81
+ import { AuthService, EventBusService } from '@opensourcekd/ng-common-libs';
82
+
88
83
  export class MyComponent {
89
84
  private authService = inject(AuthService);
90
85
  private eventBus = inject(EventBusService);
86
+
87
+ login() { this.authService.login(); }
91
88
  }
92
89
  ```
93
90
 
94
- ### Configuration (Framework-Agnostic)
95
-
96
- The library provides a framework-agnostic configuration utility with **statically configured values** from GitHub repository variables:
97
-
98
- ```typescript
99
- // Import from /core for framework-agnostic usage
100
- import { APP_CONFIG } from '@opensourcekd/ng-common-libs/core';
101
-
102
- // Access pre-configured values anywhere in your app
103
- console.log(APP_CONFIG.apiUrl); // Configured during build from GitHub vars
104
- console.log(APP_CONFIG.auth0Domain); // Configured during build from GitHub vars
105
- console.log(APP_CONFIG.auth0ClientId); // Configured during build from GitHub vars
106
- ```
107
-
108
- **Key Features:**
109
- - Values are **statically baked** into the library during build time from GitHub repository variables
110
- - No runtime configuration needed - values are available immediately
111
- - Can be used across any framework: Angular, React, Vue, Svelte, vanilla JS
112
- - Perfect for MicroFrontends (MFEs) and shell applications
113
-
114
- ### Auth0 Authentication
115
-
116
- Complete Auth0 integration with automatic token management and event emission.
117
-
118
- **Note:** Make sure you've configured the providers as shown in the [Module Federation setup](#️-important-setup-for-module-federation--microfrontends) above first!
119
-
120
- ```typescript
121
- import { Component, inject } from '@angular/core';
122
- import { AuthService } from '@opensourcekd/ng-common-libs';
123
-
124
- @Component({
125
- selector: 'app-login',
126
- template: `
127
- <button (click)="login()">Login with Auth0</button>
128
- <button (click)="logout()" *ngIf="user">Logout</button>
129
- <div *ngIf="user">Welcome, {{ user.name }}!</div>
130
- `
131
- })
132
- export class LoginComponent {
133
- private authService = inject(AuthService);
134
- user = this.authService.getUser();
135
-
136
- async login() {
137
- await this.authService.login();
138
- }
139
-
140
- async logout() {
141
- await this.authService.logout();
142
- }
143
- }
144
- ```
145
-
146
- See the [Auth0 Service Usage Guide](./docs/AUTH_SERVICE_USAGE.md) for complete integration instructions.
91
+ ### Configuration
147
92
 
148
- ### EventBusService
149
-
150
- Cross-application event communication for MicroFrontend architectures.
151
-
152
- **Note:** Make sure you've configured the providers as shown in the [Module Federation setup](#️-important-setup-for-module-federation--microfrontends) above first!
93
+ **Use your own environment configuration** (recommended):
153
94
 
154
95
  ```typescript
155
- import { Component, OnInit, inject } from '@angular/core';
156
- import { EventBusService } from '@opensourcekd/ng-common-libs';
157
-
158
- @Component({
159
- selector: 'app-event-example',
160
- template: `<button (click)="sendEvent()">Send Event</button>`
161
- })
162
- export class EventExampleComponent implements OnInit {
163
- private eventBus = inject(EventBusService);
164
-
165
- ngOnInit() {
166
- // Subscribe to all events
167
- this.eventBus.onePlusNEvents.subscribe(event => {
168
- console.log('Event received:', event);
169
- });
170
- }
171
-
172
- sendEvent() {
173
- // Send structured event
174
- this.eventBus.sendEvent(JSON.stringify({
175
- type: 'user:action',
176
- payload: { userId: '123' },
177
- timestamp: new Date().toISOString()
178
- }));
179
- }
180
- }
181
- ```
96
+ import { configureAuth0 } from '@opensourcekd/ng-common-libs';
97
+ import { environment } from './environments/environment';
182
98
 
183
- See the [EventBus Service Usage Guide](./docs/EVENT_BUS_USAGE.md) for advanced patterns and MicroFrontend examples.
184
-
185
- ### For Non-Angular Projects (React, Vue, Svelte, Vanilla JS)
186
-
187
- Use the framework-agnostic core event bus:
188
-
189
- ```typescript
190
- // Import from /core
191
- import { EventBus } from '@opensourcekd/ng-common-libs/core';
192
-
193
- // Event Bus
194
- const eventBus = new EventBus();
195
- eventBus.emit('user:login', { userId: '123' });
196
- eventBus.on('user:login').subscribe(data => {
197
- console.log('User logged in:', data);
99
+ configureAuth0({
100
+ domain: environment.auth0Domain,
101
+ clientId: environment.auth0ClientId,
102
+ audience: environment.apiUrl,
198
103
  });
199
104
  ```
200
105
 
201
- #### React Example
106
+ > ⚠️ **Important**: Do not use `APP_CONFIG` from the library. It contains placeholder values. Always use your own environment configuration.
202
107
 
203
- ```typescript
204
- import { useEffect } from 'react';
205
- import { EventBus } from '@opensourcekd/ng-common-libs/core';
206
-
207
- const eventBus = new EventBus();
208
-
209
- function MyComponent() {
210
- useEffect(() => {
211
- const subscription = eventBus.on('user:login').subscribe(data => {
212
- console.log('User logged in:', data);
213
- });
214
- return () => subscription.unsubscribe();
215
- }, []);
108
+ ## 📚 Documentation
216
109
 
217
- const handleLogin = () => {
218
- eventBus.emit('user:login', { userId: '123' });
219
- };
110
+ - **[CONSUMPTION_GUIDE.md](./CONSUMPTION_GUIDE.md)** - Complete setup guide and API reference
111
+ - **[Auth0 Service Usage](./docs/AUTH_SERVICE_USAGE.md)** - Detailed Auth0 integration
112
+ - **[EventBus Service Usage](./docs/EVENT_BUS_USAGE.md)** - Cross-application event patterns
113
+ - **[Module Federation Guide](./docs/MODULE_FEDERATION.md)** - Runtime sharing configuration
220
114
 
221
- return <button onClick={handleLogin}>Login</button>;
222
- }
223
- ```
115
+ ## 📝 What's Exported
224
116
 
225
- #### Vue Example
117
+ Everything you need from one import:
226
118
 
227
119
  ```typescript
228
- import { onMounted, onUnmounted } from 'vue';
229
- import { EventBus } from '@opensourcekd/ng-common-libs/core';
230
-
231
- const eventBus = new EventBus();
232
-
233
- export default {
234
- setup() {
235
- let subscription;
236
-
237
- onMounted(() => {
238
- subscription = eventBus.on('user:login').subscribe(data => {
239
- console.log('User logged in:', data);
240
- });
241
- });
242
-
243
- onUnmounted(() => {
244
- subscription?.unsubscribe();
245
- });
246
-
247
- const handleLogin = () => {
248
- eventBus.emit('user:login', { userId: '123' });
249
- };
250
-
251
- return { handleLogin };
252
- }
253
- };
120
+ import {
121
+ // Services
122
+ AuthService,
123
+ EventBusService,
124
+
125
+ // Factory Functions
126
+ getAuthService,
127
+ getEventBusService,
128
+
129
+ // Configuration
130
+ configureAuth0,
131
+
132
+ // Core Utilities
133
+ EventBus,
134
+
135
+ // Types & Interfaces
136
+ UserInfo,
137
+ UserData,
138
+ EventPayload,
139
+ } from '@opensourcekd/ng-common-libs';
254
140
  ```
255
141
 
256
- ## 📚 Documentation
257
-
258
- - **[Auth0 Service Usage](./docs/AUTH_SERVICE_USAGE.md)** - Complete Auth0 authentication integration guide
259
- - **[EventBus Service Usage](./docs/EVENT_BUS_USAGE.md)** - Cross-application event communication guide
260
- - **[Deployment Guide](./docs/DEPLOYMENT.md)** - Publishing, versioning, and consumption
261
- - **[Microapp Triggering Guide](./docs/MICROAPP_TRIGGERING.md)** - Automatic build triggering for consuming microapps
262
- - **[Module Federation Guide](./docs/MODULE_FEDERATION.md)** - Runtime sharing with Module Federation
263
-
264
- ## 📝 API Documentation
265
-
266
- ### Core Configuration (Framework-Agnostic)
267
-
268
- - `APP_CONFIG` - Read-only application configuration object with values statically configured during build time:
269
- - `auth0Domain: string` - Auth0 tenant domain (from GitHub var `AUTH0_DOMAIN`)
270
- - `auth0ClientId: string` - Auth0 client ID (from GitHub var `AUTH0_CLIENT_ID`)
271
- - `apiUrl: string` - API base URL (from GitHub var `API_URL`)
272
-
273
- ### Angular Configuration
274
-
275
- - `configureAuth0(config: Partial<AUTH0_CONFIG>): void` - Configure Auth0 settings (domain, clientId, etc.)
276
- - `AUTH0_CONFIG` - Auth0 configuration object (domain, clientId, redirectUri, etc.)
277
-
278
- ### AuthService
279
-
280
- - `login(user?: string, options?: { invitation?: string; organization?: string }): Promise<void>` - Initiate Auth0 login with optional user identifier and organization invitation parameters
281
- - `logout(): Promise<void>` - Logout and clear session
282
- - `handleCallback(): Promise<{ success: boolean, appState?: any }>` - Handle Auth0 callback and return success status with preserved appState
283
- - `getToken(): Promise<string | null>` - Get access token asynchronously (checks storage first, then Auth0)
284
- - `getTokenSync(): string | null` - Get cached access token synchronously (storage only)
285
- - `getUser(): UserInfo | null` - Get current user information
286
- - `getUserData(): UserData | null` - Get simplified user data with role and organization extraction
287
- - `isAuthenticated(): Promise<boolean>` - Check authentication status asynchronously (verifies with Auth0)
288
- - `isAuthenticatedSync(): boolean` - Check authentication status synchronously (storage only)
289
- - `user$: Observable<UserInfo | null>` - Observable stream of user changes
290
-
291
- ### EventBusService
292
-
293
- - `sendEvent(event: string): void` - Send event to all subscribers
294
- - `onePlusNEvents: Observable<string>` - Subscribe to all events with replay buffer
295
-
296
- ### EventBus (Core)
297
-
298
- - `emit<T>(eventType: string, data?: T): void` - Emit an event
299
- - `on<T>(eventType: string): Observable<T>` - Subscribe to an event
300
- - `onMultiple(eventTypes: string[]): Observable<EventPayload>` - Subscribe to multiple events
301
- - `onAll(): Observable<EventPayload>` - Subscribe to all events
302
-
303
142
  ## 🛠️ Development
304
143
 
305
144
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opensourcekd/ng-common-libs",
3
- "version": "1.2.8",
3
+ "version": "2.0.0",
4
4
  "description": "Angular 18 shareable utility library with framework-agnostic core and Angular wrappers for event emitter, authorization, storage, and more",
5
5
  "keywords": [
6
6
  "angular",
@@ -31,16 +31,6 @@
31
31
  "import": "./dist/index.mjs",
32
32
  "require": "./dist/index.cjs",
33
33
  "types": "./dist/index.d.ts"
34
- },
35
- "./core": {
36
- "import": "./dist/core/index.mjs",
37
- "require": "./dist/core/index.cjs",
38
- "types": "./dist/core/index.d.ts"
39
- },
40
- "./angular": {
41
- "import": "./dist/angular/index.mjs",
42
- "require": "./dist/angular/index.cjs",
43
- "types": "./dist/angular/index.d.ts"
44
34
  }
45
35
  },
46
36
  "files": [