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