@vnb/mfe-events 0.0.1-rc.1

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/dist/index.js ADDED
@@ -0,0 +1,852 @@
1
+ /**
2
+ * @vnb/mfe-events v0.0.1-rc.1
3
+ * Micro frontend event plugin for cross-app communication with type safety
4
+ * License: MIT
5
+ */
6
+ 'use strict';
7
+
8
+ Object.defineProperty(exports, '__esModule', { value: true });
9
+
10
+ /**
11
+ * @xxxx/mfe-events — Transport Layer
12
+ *
13
+ * Provides abstraction for event transmission across different environments:
14
+ * - MemoryTransport: Shell internal (no window)
15
+ * - WindowTransport: MF/NF Remote Apps (CustomEvent)
16
+ * - PostMessageTransport: iframe Remote Apps (postMessage)
17
+ * - IframeProxyTransport: Shell → iframe proxy (postMessage)
18
+ */
19
+ /**
20
+ * MemoryTransport — Shell internal event bus
21
+ * Uses in-memory EventTarget, does not touch window
22
+ */
23
+ class MemoryTransport {
24
+ constructor() {
25
+ this.target = new EventTarget();
26
+ }
27
+ emit(event, data) {
28
+ this.target.dispatchEvent(new CustomEvent(event, { detail: data }));
29
+ }
30
+ on(event, handler) {
31
+ const wrapper = (e) => handler(e.detail);
32
+ this.target.addEventListener(event, wrapper);
33
+ return () => this.target.removeEventListener(event, wrapper);
34
+ }
35
+ }
36
+ /**
37
+ * WindowTransport — MF/NF Remote Apps communication
38
+ * Uses window.CustomEvent for same-tab communication
39
+ */
40
+ class WindowTransport {
41
+ emit(event, data) {
42
+ window.dispatchEvent(new CustomEvent(event, { detail: data }));
43
+ }
44
+ on(event, handler) {
45
+ const wrapper = (e) => handler(e.detail);
46
+ window.addEventListener(event, wrapper);
47
+ return () => window.removeEventListener(event, wrapper);
48
+ }
49
+ }
50
+ /**
51
+ * PostMessageTransport — iframe Remote Apps communication
52
+ * Uses window.postMessage for cross-origin communication
53
+ */
54
+ class PostMessageTransport {
55
+ constructor(options = {}) {
56
+ this.targetWindow = options.targetWindow || window.parent;
57
+ this.targetOrigin = options.targetOrigin || '*';
58
+ }
59
+ emit(event, data) {
60
+ this.targetWindow.postMessage({ scope: 'mfe', event, data, ts: Date.now() }, this.targetOrigin);
61
+ }
62
+ on(event, handler) {
63
+ const wrapper = (e) => {
64
+ if (e.data?.scope === 'mfe' && e.data?.event === event) {
65
+ handler(e.data.data);
66
+ }
67
+ };
68
+ window.addEventListener('message', wrapper);
69
+ return () => window.removeEventListener('message', wrapper);
70
+ }
71
+ }
72
+ /**
73
+ * IframeProxyTransport — Shell side proxy for iframe communication
74
+ * Sends postMessage to specific iframe and receives messages from it
75
+ */
76
+ class IframeProxyTransport {
77
+ constructor(iframe, targetOrigin = '*') {
78
+ this.iframe = iframe;
79
+ this.targetOrigin = targetOrigin;
80
+ }
81
+ emit(event, data) {
82
+ this.iframe.contentWindow?.postMessage({ scope: 'mfe', event, data, ts: Date.now() }, this.targetOrigin);
83
+ }
84
+ on(event, handler) {
85
+ const wrapper = (e) => {
86
+ // Only receive messages from this specific iframe
87
+ if (e.source === this.iframe.contentWindow &&
88
+ e.data?.scope === 'mfe' &&
89
+ e.data?.event === event) {
90
+ handler(e.data.data);
91
+ }
92
+ };
93
+ window.addEventListener('message', wrapper);
94
+ return () => window.removeEventListener('message', wrapper);
95
+ }
96
+ }
97
+
98
+ var transport = /*#__PURE__*/Object.freeze({
99
+ __proto__: null,
100
+ IframeProxyTransport: IframeProxyTransport,
101
+ MemoryTransport: MemoryTransport,
102
+ PostMessageTransport: PostMessageTransport,
103
+ WindowTransport: WindowTransport
104
+ });
105
+
106
+ /**
107
+ * @xxxx/mfe-events — Type-safe Event Bus
108
+ *
109
+ * Provides compile-time type checking for event names and payloads.
110
+ * Wraps Transport with generic type constraints.
111
+ */
112
+ class Bus {
113
+ constructor(transport) {
114
+ this.transport = transport;
115
+ }
116
+ /**
117
+ * Emit an event with type-safe payload
118
+ */
119
+ emit(event, data) {
120
+ this.transport.emit(event, data);
121
+ }
122
+ /**
123
+ * Subscribe to an event with type-safe handler
124
+ * Returns unsubscribe function
125
+ */
126
+ on(event, handler, options) {
127
+ if (options?.once) {
128
+ return this.once(event, handler);
129
+ }
130
+ return this.transport.on(event, handler);
131
+ }
132
+ /**
133
+ * Subscribe to an event once
134
+ * Returns unsubscribe function
135
+ */
136
+ once(event, handler) {
137
+ const off = this.on(event, (data) => {
138
+ off();
139
+ handler(data);
140
+ });
141
+ return off;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * @xxxx/mfe-events — Event Constants
147
+ *
148
+ * Three scopes:
149
+ * - EvtShl: Shell internal (no window, memory only)
150
+ * - EvtMfe: Cross-app (Shell + Remote Apps)
151
+ * - EvtApp: Remote App internal (framework-specific)
152
+ *
153
+ * Naming convention: {scope}:{domain}-{action}
154
+ * - State/notification events: must have -{action} suffix
155
+ * - Event markers (error, shell-ready, raw): no suffix
156
+ */
157
+ // ─────────────────────────────────────────────
158
+ // Shell Internal — no window, memory only
159
+ // ─────────────────────────────────────────────
160
+ const EvtShl = {
161
+ TabOverflow: 'shl:tab-overflow',
162
+ TabClose: 'shl:tab-close',
163
+ RouteReuse: 'shl:route-reuse',
164
+ AuthSync: 'shl:auth-sync',
165
+ StateSync: 'shl:state-sync',
166
+ AppMounted: 'shl:app-mounted',
167
+ AppUnmounted: 'shl:app-unmounted',
168
+ };
169
+ // ─────────────────────────────────────────────
170
+ // Cross-App — Shell and Remote Apps shared protocol
171
+ // ─────────────────────────────────────────────
172
+ const EvtMfe = {
173
+ // Global state domain
174
+ ThemeUpdate: 'mfe:theme-update',
175
+ LocaleUpdate: 'mfe:locale-update',
176
+ BreakpointUpdate: 'mfe:breakpoint-update',
177
+ StateUpdate: 'mfe:state-update',
178
+ ShellReady: 'mfe:shell-ready',
179
+ Error: 'mfe:error',
180
+ Raw: 'mfe:raw',
181
+ Custom: 'mfe:raw',
182
+ // Auth domain
183
+ AuthLogin: 'mfe:auth-login',
184
+ AuthLogout: 'mfe:auth-logout',
185
+ AuthTokenUpdate: 'mfe:auth-token-update',
186
+ AuthTokenClear: 'mfe:auth-token-clear',
187
+ AuthPermissionUpdate: 'mfe:auth-permission-update',
188
+ AuthExpired: 'mfe:auth-expired',
189
+ // Route domain
190
+ RouteNavigate: 'mfe:route-navigate',
191
+ RouteRefresh: 'mfe:route-refresh',
192
+ RouteChange: 'mfe:route-change',
193
+ // Lifecycle domain
194
+ LifecycleAppClose: 'mfe:lifecycle-app-close',
195
+ LifecycleAppReady: 'mfe:lifecycle-app-ready',
196
+ LifecycleAppUnmount: 'mfe:lifecycle-app-unmount',
197
+ // Notification domain
198
+ NotifyShow: 'mfe:notify-show',
199
+ NotifyClose: 'mfe:notify-close',
200
+ NotifyCloseAll: 'mfe:notify-close-all',
201
+ };
202
+ // ─────────────────────────────────────────────
203
+ // Remote App Internal — defined by each app
204
+ // ─────────────────────────────────────────────
205
+ function EvtApp(appId, name) {
206
+ return `app:${appId}-${name}`;
207
+ }
208
+
209
+ /**
210
+ * @xxxx/mfe-events — Plugin Core
211
+ *
212
+ * MfeEventPlugin manages Remote App registration and provides:
213
+ * - register/unregister for Remote Apps
214
+ * - emitTo for targeted communication
215
+ * - emit for broadcast communication
216
+ * - Notification API (success/info/warning/danger)
217
+ * - Automatic iframe message proxying
218
+ */
219
+ class MfeEventPlugin {
220
+ // ── Console helpers ─────────────────────────────────────────────────────────
221
+ static _log(method, label, labelBg, message, detail) {
222
+ const TAG = `color:#fff;background:${labelBg};padding:2px 6px;border-radius:4px 0 0 4px;font-weight:bold;`;
223
+ const LBL = `${labelBg.replace('background:', 'color:;background:')};padding:2px 4px;border-radius:0 4px 4px 0;`;
224
+ const MSG = 'color:#374151;padding:2px 4px;border-radius:0 4px 4px 0;';
225
+ const DETAIL = 'color:#6b7280;padding:0 4px;';
226
+ if (detail !== undefined) {
227
+ console[method](`%c[mfe-events]%c ${label}%c ${message}%c ${detail}`, TAG, LBL, MSG, DETAIL);
228
+ }
229
+ else {
230
+ console[method](`%c[mfe-events]%c ${label}%c ${message}`, TAG, LBL, MSG);
231
+ }
232
+ }
233
+ static _logError(label, message, detail) {
234
+ this._log('error', label, '#dc2626', message, detail);
235
+ }
236
+ static _logWarn(label, message, detail) {
237
+ this._log('warn', label, '#d97706', message, detail);
238
+ }
239
+ constructor() {
240
+ this.registry = new Map();
241
+ this._notifyId = 0;
242
+ this._shellReady = false;
243
+ this._notifyContainer = null;
244
+ this._notifyItems = new Map();
245
+ this._pendingClosers = new Map();
246
+ this._customRenderer = null;
247
+ this._customCloser = null;
248
+ this._customClear = null;
249
+ if (typeof window === 'undefined')
250
+ return;
251
+ // Shell side: globally listen for iframe messages and forward as CustomEvent
252
+ if (window.self === window.top) {
253
+ window.addEventListener('message', (e) => {
254
+ if (e.data?.scope === 'mfe' && e.data?.event) {
255
+ window.dispatchEvent(new CustomEvent(e.data.event, { detail: e.data.data }));
256
+ }
257
+ });
258
+ }
259
+ // Always init DOM fallback for notifications
260
+ this._initDOMFallback();
261
+ }
262
+ // ─────────────────────────────────────────
263
+ // Custom Renderer (for Shell integration)
264
+ // ─────────────────────────────────────────
265
+ /**
266
+ * Register custom notification renderer (Shell use)
267
+ * When registered, DOM fallback is disabled
268
+ */
269
+ useRenderer(render, close, clear) {
270
+ this._customRenderer = render;
271
+ this._customCloser = close || null;
272
+ this._customClear = clear || null;
273
+ }
274
+ // ─────────────────────────────────────────
275
+ // DOM Fallback Renderer
276
+ // ─────────────────────────────────────────
277
+ _initDOMFallback() {
278
+ // Inject styles
279
+ const styleId = 'mfe-notify-styles';
280
+ if (!document.getElementById(styleId)) {
281
+ const style = document.createElement('style');
282
+ style.id = styleId;
283
+ style.textContent = `
284
+ .mfe-notify-host {
285
+ position: fixed;
286
+ top: 16px;
287
+ left: 50%;
288
+ transform: translateX(-50%);
289
+ z-index: 99999;
290
+ display: flex;
291
+ flex-direction: column;
292
+ gap: 8px;
293
+ max-width: 480px;
294
+ width: calc(100% - 32px);
295
+ pointer-events: none;
296
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
297
+ }
298
+ .mfe-notify-item {
299
+ display: flex;
300
+ align-items: flex-start;
301
+ gap: 10px;
302
+ padding: 12px 14px;
303
+ background: #ffffff;
304
+ border: 1px solid rgba(0, 0, 0, 0.08);
305
+ border-left: 4px solid var(--mfe-notify-color, #6b7280);
306
+ border-radius: 8px;
307
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
308
+ pointer-events: auto;
309
+ animation: mfe-notify-slide-in 180ms ease-out;
310
+ }
311
+ .mfe-notify-item[data-type="success"] { --mfe-notify-color: #16a34a; }
312
+ .mfe-notify-item[data-type="info"] { --mfe-notify-color: #3b82f6; }
313
+ .mfe-notify-item[data-type="warning"] { --mfe-notify-color: #d97706; }
314
+ .mfe-notify-item[data-type="danger"] { --mfe-notify-color: #dc2626; }
315
+ .mfe-notify-icon {
316
+ flex: 0 0 24px;
317
+ width: 24px;
318
+ height: 24px;
319
+ border-radius: 50%;
320
+ display: flex;
321
+ align-items: center;
322
+ justify-content: center;
323
+ font-size: 14px;
324
+ font-weight: 700;
325
+ color: #fff;
326
+ background: var(--mfe-notify-color, #6b7280);
327
+ }
328
+ .mfe-notify-body { flex: 1; min-width: 0; }
329
+ .mfe-notify-title {
330
+ font-size: 13px;
331
+ font-weight: 600;
332
+ color: #1f2937;
333
+ margin-bottom: 2px;
334
+ }
335
+ .mfe-notify-message {
336
+ font-size: 13px;
337
+ line-height: 1.4;
338
+ color: #374151;
339
+ word-break: break-word;
340
+ }
341
+ .mfe-notify-close {
342
+ flex: 0 0 24px;
343
+ width: 24px;
344
+ height: 24px;
345
+ border: none;
346
+ background: none;
347
+ color: #6b7280;
348
+ cursor: pointer;
349
+ font-size: 18px;
350
+ line-height: 1;
351
+ border-radius: 4px;
352
+ }
353
+ .mfe-notify-close:hover { background: rgba(0, 0, 0, 0.06); color: #111827; }
354
+ .mfe-notify-actions {
355
+ display: flex;
356
+ gap: 8px;
357
+ margin-top: 8px;
358
+ }
359
+ .mfe-notify-btn {
360
+ padding: 4px 12px;
361
+ font-size: 12px;
362
+ font-weight: 500;
363
+ border: 1px solid rgba(0, 0, 0, 0.15);
364
+ border-radius: 4px;
365
+ background: #fff;
366
+ color: #374151;
367
+ cursor: pointer;
368
+ transition: background 0.15s, border-color 0.15s;
369
+ }
370
+ .mfe-notify-btn:hover {
371
+ background: #f3f4f6;
372
+ border-color: rgba(0, 0, 0, 0.25);
373
+ }
374
+ .mfe-notify-btn:active {
375
+ background: #e5e7eb;
376
+ }
377
+ @keyframes mfe-notify-slide-in {
378
+ from { transform: translateY(-12px); opacity: 0; }
379
+ to { transform: translateY(0); opacity: 1; }
380
+ }
381
+ `;
382
+ document.head.appendChild(style);
383
+ }
384
+ // Create container
385
+ this._notifyContainer = document.createElement('div');
386
+ this._notifyContainer.className = 'mfe-notify-host';
387
+ this._notifyContainer.setAttribute('aria-live', 'polite');
388
+ document.body.appendChild(this._notifyContainer);
389
+ }
390
+ _renderToast(config) {
391
+ if (!this._notifyContainer)
392
+ return;
393
+ const { id, type = 'info', message = '', title, duration = 3000, buttons = [] } = config;
394
+ const icons = {
395
+ success: '✓',
396
+ info: 'i',
397
+ warning: '!',
398
+ danger: '✕',
399
+ };
400
+ // Escape HTML to prevent XSS
401
+ const escapeHtml = (str) => {
402
+ const div = document.createElement('div');
403
+ div.textContent = str;
404
+ return div.innerHTML;
405
+ };
406
+ const item = document.createElement('div');
407
+ item.className = 'mfe-notify-item';
408
+ item.setAttribute('data-type', type);
409
+ item.setAttribute('data-notify-id', id);
410
+ // Build buttons HTML
411
+ let buttonsHtml = '';
412
+ if (buttons.length > 0) {
413
+ buttonsHtml = `<div class="mfe-notify-actions">${buttons.map((btn, idx) => `<button class="mfe-notify-btn" data-btn-idx="${idx}">${escapeHtml(btn.text)}</button>`).join('')}</div>`;
414
+ }
415
+ item.innerHTML = `
416
+ <div class="mfe-notify-icon">${icons[type] || 'i'}</div>
417
+ <div class="mfe-notify-body">
418
+ ${title ? `<div class="mfe-notify-title">${escapeHtml(title)}</div>` : ''}
419
+ <div class="mfe-notify-message">${escapeHtml(message)}</div>
420
+ ${buttonsHtml}
421
+ </div>
422
+ <button class="mfe-notify-close" type="button" aria-label="Dismiss">×</button>
423
+ `;
424
+ // Bind button handlers
425
+ buttons.forEach((btn, idx) => {
426
+ const btnEl = item.querySelector(`[data-btn-idx="${idx}"]`);
427
+ if (btnEl && btn.handler) {
428
+ btnEl.addEventListener('click', () => {
429
+ btn.handler();
430
+ if (btn.role !== 'sticky') {
431
+ this._removeToast(id);
432
+ }
433
+ });
434
+ }
435
+ });
436
+ const closeBtn = item.querySelector('.mfe-notify-close');
437
+ closeBtn.addEventListener('click', () => this._removeToast(id));
438
+ this._notifyContainer.appendChild(item);
439
+ this._notifyItems.set(id, item);
440
+ if (duration > 0) {
441
+ setTimeout(() => this._removeToast(id), duration);
442
+ }
443
+ }
444
+ _removeToast(id) {
445
+ const item = this._notifyItems.get(id);
446
+ if (item) {
447
+ item.remove();
448
+ this._notifyItems.delete(id);
449
+ }
450
+ this._pendingClosers.delete(id);
451
+ }
452
+ _removeAllToasts() {
453
+ this._notifyItems.forEach((item) => item.remove());
454
+ this._notifyItems.clear();
455
+ this._pendingClosers.clear();
456
+ }
457
+ // ─────────────────────────────────────────
458
+ // Remote App Registration
459
+ // ─────────────────────────────────────────
460
+ /**
461
+ * Register a Remote App with event handlers
462
+ */
463
+ register(options) {
464
+ if (this.registry.has(options.appId)) {
465
+ this.unregister(options.appId);
466
+ }
467
+ const meta = {
468
+ appId: options.appId,
469
+ type: options.type || 'mf',
470
+ };
471
+ const cleanups = [];
472
+ // Auto-subscribe handlers
473
+ Object.entries(options.handlers).forEach(([event, handler]) => {
474
+ if (!handler)
475
+ return;
476
+ if (options.type === 'iframe') {
477
+ // iframe: listen via postMessage
478
+ const wrapper = (e) => {
479
+ if (e.data?.scope === 'mfe' && e.data?.event === event) {
480
+ handler(e.data.data);
481
+ }
482
+ };
483
+ window.addEventListener('message', wrapper);
484
+ cleanups.push(() => window.removeEventListener('message', wrapper));
485
+ }
486
+ else {
487
+ // MF/NF: listen via window.CustomEvent
488
+ const wrapper = (e) => handler(e.detail);
489
+ window.addEventListener(event, wrapper);
490
+ cleanups.push(() => window.removeEventListener(event, wrapper));
491
+ }
492
+ });
493
+ this.registry.set(options.appId, { meta, options, cleanups });
494
+ // fallback 存入 registry,不覆盖全局 _customRenderer
495
+ // 全局渲染器仅由 Shell 的 useRenderer() 设置
496
+ }
497
+ /**
498
+ * Register an iframe Remote App (Shell side)
499
+ */
500
+ registerIframe(appId, iframe, targetOrigin) {
501
+ const TIMEOUT_MS = 5000;
502
+ Promise.resolve().then(function () { return transport; })
503
+ .then(({ IframeProxyTransport }) => {
504
+ const transport = new IframeProxyTransport(iframe, targetOrigin);
505
+ this.registry.set(appId, {
506
+ meta: { appId, type: 'iframe', transport },
507
+ options: { appId, type: 'iframe', handlers: {} },
508
+ cleanups: [],
509
+ });
510
+ })
511
+ .catch((err) => {
512
+ MfeEventPlugin._logError('registerIframe', 'failed to load transport for', `"${appId}": ${err}`);
513
+ });
514
+ // Timeout protection — if import hangs, registry stays clean and caller knows nothing
515
+ setTimeout(() => {
516
+ if (!this.registry.has(appId)) {
517
+ MfeEventPlugin._logError('registerIframe', 'timeout', `${TIMEOUT_MS}ms for "${appId}"`);
518
+ }
519
+ }, TIMEOUT_MS);
520
+ }
521
+ /**
522
+ * Unregister a Remote App
523
+ */
524
+ unregister(appId) {
525
+ const entry = this.registry.get(appId);
526
+ if (entry) {
527
+ entry.cleanups.forEach((fn) => fn());
528
+ }
529
+ this.registry.delete(appId);
530
+ }
531
+ // ─────────────────────────────────────────
532
+ // Shell Targeted Communication
533
+ // ─────────────────────────────────────────
534
+ /**
535
+ * Send event to a specific Remote App
536
+ */
537
+ emitTo(appId, event, data) {
538
+ const app = this.registry.get(appId);
539
+ if (!app) {
540
+ MfeEventPlugin._logWarn('emitTo', 'app not registered', `"${appId}" (event: ${event})`);
541
+ return;
542
+ }
543
+ if (app.meta.type === 'iframe' && app.meta.transport) {
544
+ // iframe: send via postMessage
545
+ app.meta.transport.emit(event, data);
546
+ }
547
+ else {
548
+ // MF/NF: call the registered handler directly
549
+ const handler = app.options.handlers[event];
550
+ if (handler) {
551
+ handler(data);
552
+ }
553
+ }
554
+ }
555
+ // ─────────────────────────────────────────
556
+ // Shell Broadcast Communication
557
+ // ─────────────────────────────────────────
558
+ /**
559
+ * Broadcast event to all Remote Apps (MF + iframe)
560
+ */
561
+ emit(event, data) {
562
+ // Broadcast to all MF Remote Apps
563
+ window.dispatchEvent(new CustomEvent(event, { detail: data }));
564
+ // Broadcast to all iframe Remote Apps
565
+ this.registry.forEach(({ meta }) => {
566
+ if (meta.type === 'iframe' && meta.transport) {
567
+ meta.transport.emit(event, data);
568
+ }
569
+ });
570
+ }
571
+ // ─────────────────────────────────────────
572
+ // Notification API
573
+ // ─────────────────────────────────────────
574
+ /**
575
+ * Build notification config from flexible arguments
576
+ * Supports: success("msg"), success({message:"msg",duration:5000}), success("msg","title",{duration:5000})
577
+ */
578
+ _buildConfig(type, message, args) {
579
+ const config = { type };
580
+ if (typeof message === 'string') {
581
+ config.message = message;
582
+ }
583
+ else if (message && typeof message === 'object') {
584
+ const { type: _ignored, ...rest } = message;
585
+ Object.assign(config, rest);
586
+ }
587
+ args.forEach((arg) => {
588
+ if (typeof arg === 'string') {
589
+ config.title = arg;
590
+ }
591
+ else if (arg && typeof arg === 'object') {
592
+ const { type: _ignored, ...rest } = arg;
593
+ Object.assign(config, rest);
594
+ }
595
+ });
596
+ return config;
597
+ }
598
+ /**
599
+ * Show a notification
600
+ */
601
+ notify(config) {
602
+ if (typeof window === 'undefined')
603
+ return { close: () => { } };
604
+ const id = `mfe-${++this._notifyId}`;
605
+ const finalConfig = {
606
+ duration: 3000,
607
+ ...config,
608
+ id,
609
+ };
610
+ // 1. Always dispatch CustomEvent (for Shell listeners)
611
+ window.dispatchEvent(new CustomEvent(EvtMfe.NotifyShow, {
612
+ detail: finalConfig,
613
+ bubbles: true,
614
+ cancelable: true,
615
+ }));
616
+ // 2. Render: custom renderer > fallback > DOM fallback
617
+ if (this._customRenderer) {
618
+ this._customRenderer(finalConfig);
619
+ }
620
+ else {
621
+ // Check if any registered app provided a fallback renderer
622
+ const appWithFallback = [...this.registry.values()].find((app) => app.options.fallback);
623
+ if (appWithFallback) {
624
+ const closer = appWithFallback.options.fallback(finalConfig);
625
+ this._pendingClosers.set(id, () => {
626
+ window.dispatchEvent(new CustomEvent(EvtMfe.NotifyClose, {
627
+ detail: { id },
628
+ bubbles: true,
629
+ }));
630
+ closer.close();
631
+ this._pendingClosers.delete(id);
632
+ });
633
+ }
634
+ else {
635
+ this._renderToast(finalConfig);
636
+ }
637
+ }
638
+ // 3. Track closer for closeAll()
639
+ const closeFn = () => {
640
+ // Dispatch close event
641
+ window.dispatchEvent(new CustomEvent(EvtMfe.NotifyClose, {
642
+ detail: { id },
643
+ bubbles: true,
644
+ }));
645
+ // Remove DOM toast
646
+ if (this._customCloser) {
647
+ this._customCloser(id);
648
+ }
649
+ else {
650
+ this._removeToast(id);
651
+ }
652
+ };
653
+ this._pendingClosers.set(id, closeFn);
654
+ return {
655
+ close: () => {
656
+ const closer = this._pendingClosers.get(id);
657
+ if (closer) {
658
+ closer();
659
+ }
660
+ },
661
+ };
662
+ }
663
+ /**
664
+ * Close a notification by id
665
+ */
666
+ close(id) {
667
+ const closer = this._pendingClosers.get(id);
668
+ if (closer)
669
+ closer();
670
+ }
671
+ /**
672
+ * Show success notification
673
+ */
674
+ success(message, ...args) {
675
+ return this.notify(this._buildConfig('success', message, args));
676
+ }
677
+ /**
678
+ * Show info notification
679
+ */
680
+ info(message, ...args) {
681
+ return this.notify(this._buildConfig('info', message, args));
682
+ }
683
+ /**
684
+ * Show warning notification
685
+ */
686
+ warning(message, ...args) {
687
+ return this.notify(this._buildConfig('warning', message, args));
688
+ }
689
+ /**
690
+ * Show danger notification
691
+ */
692
+ danger(message, ...args) {
693
+ return this.notify(this._buildConfig('danger', message, args));
694
+ }
695
+ /**
696
+ * Close all notifications
697
+ */
698
+ closeAll() {
699
+ // Call all pending closers
700
+ this._pendingClosers.forEach((closer) => closer());
701
+ this._pendingClosers.clear();
702
+ // Dispatch close-all event
703
+ window.dispatchEvent(new CustomEvent(EvtMfe.NotifyCloseAll, {
704
+ detail: {},
705
+ bubbles: true,
706
+ }));
707
+ // Clear DOM toasts
708
+ if (this._customClear) {
709
+ this._customClear();
710
+ }
711
+ else {
712
+ this._removeAllToasts();
713
+ }
714
+ }
715
+ // ─────────────────────────────────────────
716
+ // Lifecycle Helpers
717
+ // ─────────────────────────────────────────
718
+ /**
719
+ * Mark Shell as ready
720
+ */
721
+ shellReady() {
722
+ setTimeout(() => {
723
+ window.dispatchEvent(new CustomEvent(EvtMfe.ShellReady, {
724
+ detail: {},
725
+ bubbles: true,
726
+ cancelable: true,
727
+ }));
728
+ this._shellReady = true;
729
+ }, 100);
730
+ }
731
+ /**
732
+ * Check if Shell is ready
733
+ */
734
+ isShellReady() {
735
+ return !!this._shellReady;
736
+ }
737
+ // ─────────────────────────────────────────
738
+ // Auth Helpers (convenience methods)
739
+ // ─────────────────────────────────────────
740
+ /**
741
+ * Broadcast auth login event
742
+ */
743
+ authLogin(user) {
744
+ this.emit(EvtMfe.AuthLogin, { user, token: '' });
745
+ }
746
+ /**
747
+ * Broadcast auth logout event
748
+ */
749
+ authLogout(reason) {
750
+ this.emit(EvtMfe.AuthLogout, { reason: reason || 'user' });
751
+ }
752
+ /**
753
+ * Broadcast token update event
754
+ */
755
+ tokenUpdate(data) {
756
+ this.emit(EvtMfe.AuthTokenUpdate, data);
757
+ }
758
+ /**
759
+ * Broadcast auth expired event
760
+ */
761
+ authExpired() {
762
+ this.emit(EvtMfe.AuthExpired, {});
763
+ }
764
+ /**
765
+ * Broadcast token cleared event
766
+ */
767
+ tokenClear() {
768
+ this.emit(EvtMfe.AuthTokenClear, {});
769
+ }
770
+ /**
771
+ * Broadcast permission update event
772
+ */
773
+ permissionUpdate(permissions) {
774
+ this.emit(EvtMfe.AuthPermissionUpdate, { permissions });
775
+ }
776
+ /**
777
+ * Broadcast locale update event
778
+ */
779
+ locale(locale) {
780
+ this.emit(EvtMfe.LocaleUpdate, { locale });
781
+ }
782
+ }
783
+ // Singleton export
784
+ const mfeEventPlugin = new MfeEventPlugin();
785
+
786
+ /**
787
+ * @xxxx/mfe-events — Micro Frontend Event Plugin
788
+ *
789
+ * Unified event communication for Module Federation / Native Federation / iframe architectures.
790
+ *
791
+ * Features:
792
+ * - Three scopes: EvtShl (Shell internal), EvtMfe (cross-app), EvtApp (Remote App internal)
793
+ * - Type-safe event bus with compile-time checking
794
+ * - Automatic Transport adaptation (CustomEvent for MF, postMessage for iframe)
795
+ * - Plugin API for Remote App registration and communication
796
+ * - Notification API with fallback support
797
+ *
798
+ * Usage:
799
+ * ```typescript
800
+ * import mfeEventPlugin, { mfeBus, shlBus } from '@xxxx/mfe-events'
801
+ * import { EvtMfe, EvtShl, EvtApp } from '@xxxx/mfe-events'
802
+ * ```
803
+ */
804
+ // Transport layer
805
+ /**
806
+ * Shell internal bus — isolated, does not touch window
807
+ * Use for Shell-internal state synchronization
808
+ */
809
+ const shlBus = new Bus(new MemoryTransport());
810
+ /**
811
+ * Cross-app bus — auto-detects environment and selects Transport
812
+ * - Shell/MF/NF: WindowTransport (CustomEvent)
813
+ * - iframe: PostMessageTransport (postMessage)
814
+ */
815
+ function createMfeBus() {
816
+ if (typeof window === 'undefined') {
817
+ // SSR fallback — use MemoryTransport
818
+ return new Bus(new MemoryTransport());
819
+ }
820
+ if (window.self !== window.top) {
821
+ // iframe environment → send to parent via postMessage
822
+ return new Bus(new PostMessageTransport());
823
+ }
824
+ // Shell/MF/NF environment → use window.CustomEvent
825
+ // Federation modules may not share the same instance,
826
+ // so window is used as the shared channel fallback
827
+ return new Bus(new WindowTransport());
828
+ }
829
+ const mfeBus = createMfeBus();
830
+ // ─────────────────────────────────────────────
831
+ // Global variable for backward compatibility
832
+ // ─────────────────────────────────────────────
833
+ if (typeof window !== 'undefined') {
834
+ const win = window;
835
+ if (!win.__MFE_EVENT_PLUGIN__) {
836
+ win.__MFE_EVENT_PLUGIN__ = mfeEventPlugin;
837
+ }
838
+ }
839
+
840
+ exports.Bus = Bus;
841
+ exports.EvtApp = EvtApp;
842
+ exports.EvtMfe = EvtMfe;
843
+ exports.EvtShl = EvtShl;
844
+ exports.IframeProxyTransport = IframeProxyTransport;
845
+ exports.MemoryTransport = MemoryTransport;
846
+ exports.PostMessageTransport = PostMessageTransport;
847
+ exports.WindowTransport = WindowTransport;
848
+ exports.default = mfeEventPlugin;
849
+ exports.mfeBus = mfeBus;
850
+ exports.mfeEventPlugin = mfeEventPlugin;
851
+ exports.shlBus = shlBus;
852
+ //# sourceMappingURL=index.js.map