wu-framework 1.0.6 → 1.1.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.
@@ -0,0 +1,570 @@
1
+ /**
2
+ * 🚀 WU-FRAMEWORK VUE ADAPTER
3
+ *
4
+ * Simplifica la integración de Vue 3 con Wu Framework.
5
+ * Convierte componentes Vue en microfrontends con UNA línea de código.
6
+ *
7
+ * @example
8
+ * // Microfrontend (main.ts)
9
+ * import { wuVue } from 'wu-framework/adapters/vue';
10
+ * import App from './App.vue';
11
+ *
12
+ * wuVue.register('my-app', App);
13
+ *
14
+ * @example
15
+ * // Shell (cargar microfrontend)
16
+ * import { WuSlot } from 'wu-framework/adapters/vue';
17
+ *
18
+ * <WuSlot name="my-app" url="http://localhost:3001" />
19
+ */
20
+
21
+ // Estado global del adapter
22
+ const adapterState = {
23
+ apps: new Map(),
24
+ Vue: null,
25
+ createApp: null,
26
+ initialized: false
27
+ };
28
+
29
+ /**
30
+ * Detecta y obtiene Vue del contexto global o lo importa
31
+ */
32
+ async function ensureVue() {
33
+ if (adapterState.initialized) return true;
34
+
35
+ try {
36
+ // Intentar obtener de window
37
+ if (typeof window !== 'undefined' && window.Vue) {
38
+ adapterState.Vue = window.Vue;
39
+ adapterState.createApp = window.Vue.createApp;
40
+ adapterState.initialized = true;
41
+ return true;
42
+ }
43
+
44
+ // Intentar import dinámico
45
+ const Vue = await import('vue');
46
+ adapterState.Vue = Vue;
47
+ adapterState.createApp = Vue.createApp;
48
+ adapterState.initialized = true;
49
+ return true;
50
+
51
+ } catch (error) {
52
+ console.error('[WuVue] Failed to load Vue:', error);
53
+ return false;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Obtiene la instancia de Wu Framework
59
+ */
60
+ function getWuInstance() {
61
+ if (typeof window === 'undefined') return null;
62
+
63
+ return window.wu
64
+ || window.parent?.wu
65
+ || window.top?.wu
66
+ || null;
67
+ }
68
+
69
+ /**
70
+ * Espera a que Wu Framework esté disponible
71
+ */
72
+ function waitForWu(timeout = 5000) {
73
+ return new Promise((resolve, reject) => {
74
+ const wu = getWuInstance();
75
+ if (wu) {
76
+ resolve(wu);
77
+ return;
78
+ }
79
+
80
+ const startTime = Date.now();
81
+
82
+ const handleWuReady = () => {
83
+ cleanup();
84
+ resolve(getWuInstance());
85
+ };
86
+
87
+ window.addEventListener('wu:ready', handleWuReady);
88
+ window.addEventListener('wu:app:ready', handleWuReady);
89
+
90
+ const checkInterval = setInterval(() => {
91
+ const wu = getWuInstance();
92
+ if (wu) {
93
+ cleanup();
94
+ resolve(wu);
95
+ return;
96
+ }
97
+
98
+ if (Date.now() - startTime > timeout) {
99
+ cleanup();
100
+ reject(new Error(`Wu Framework not found after ${timeout}ms`));
101
+ }
102
+ }, 200);
103
+
104
+ function cleanup() {
105
+ clearInterval(checkInterval);
106
+ window.removeEventListener('wu:ready', handleWuReady);
107
+ window.removeEventListener('wu:app:ready', handleWuReady);
108
+ }
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Registra un componente Vue como microfrontend
114
+ *
115
+ * @param {string} appName - Nombre único del microfrontend (debe coincidir con wu.json)
116
+ * @param {Object} RootComponent - Componente Vue principal (App.vue)
117
+ * @param {Object} options - Opciones adicionales
118
+ * @param {Function} options.setup - Función para configurar la app Vue (plugins, router, etc.)
119
+ * @param {Object} options.props - Props iniciales para el componente
120
+ * @param {Function} options.onMount - Callback después de montar
121
+ * @param {Function} options.onUnmount - Callback antes de desmontar
122
+ * @param {boolean} options.standalone - Permitir ejecución standalone (default: true)
123
+ * @param {string} options.standaloneContainer - Selector para modo standalone (default: '#app')
124
+ *
125
+ * @example
126
+ * // Básico
127
+ * wuVue.register('my-app', App);
128
+ *
129
+ * @example
130
+ * // Con plugins (Pinia, Router, etc.)
131
+ * wuVue.register('my-app', App, {
132
+ * setup: (app) => {
133
+ * app.use(createPinia());
134
+ * app.use(router);
135
+ * app.component('MyGlobal', MyComponent);
136
+ * }
137
+ * });
138
+ */
139
+ async function register(appName, RootComponent, options = {}) {
140
+ const {
141
+ setup = null,
142
+ props = {},
143
+ onMount = null,
144
+ onUnmount = null,
145
+ standalone = true,
146
+ standaloneContainer = '#app'
147
+ } = options;
148
+
149
+ // Asegurar que Vue está disponible
150
+ const hasVue = await ensureVue();
151
+ if (!hasVue) {
152
+ console.error(`[WuVue] Cannot register ${appName}: Vue not available`);
153
+ return false;
154
+ }
155
+
156
+ const { createApp } = adapterState;
157
+
158
+ // Función de mount interna
159
+ const mountApp = (container) => {
160
+ if (!container) {
161
+ console.error(`[WuVue] Mount failed for ${appName}: container is null`);
162
+ return;
163
+ }
164
+
165
+ // Evitar doble mount
166
+ if (adapterState.apps.has(appName)) {
167
+ console.warn(`[WuVue] ${appName} already mounted, unmounting first`);
168
+ unmountApp();
169
+ }
170
+
171
+ try {
172
+ // Crear la aplicación Vue
173
+ const app = createApp(RootComponent, props);
174
+
175
+ // Ejecutar setup personalizado (plugins, router, etc.)
176
+ if (setup && typeof setup === 'function') {
177
+ setup(app);
178
+ }
179
+
180
+ // Proveer información del contexto Wu
181
+ app.provide('wuAppName', appName);
182
+ app.provide('wuInstance', getWuInstance());
183
+
184
+ // Montar
185
+ app.mount(container);
186
+
187
+ // Guardar referencia
188
+ adapterState.apps.set(appName, { app, container });
189
+
190
+ console.log(`[WuVue] ✅ ${appName} mounted successfully`);
191
+
192
+ if (onMount) {
193
+ onMount(container, app);
194
+ }
195
+ } catch (error) {
196
+ console.error(`[WuVue] Mount error for ${appName}:`, error);
197
+ throw error;
198
+ }
199
+ };
200
+
201
+ // Función de unmount interna
202
+ const unmountApp = (container) => {
203
+ const instance = adapterState.apps.get(appName);
204
+
205
+ if (instance) {
206
+ try {
207
+ if (onUnmount) {
208
+ onUnmount(instance.container, instance.app);
209
+ }
210
+
211
+ instance.app.unmount();
212
+ adapterState.apps.delete(appName);
213
+
214
+ console.log(`[WuVue] ✅ ${appName} unmounted successfully`);
215
+ } catch (error) {
216
+ console.error(`[WuVue] Unmount error for ${appName}:`, error);
217
+ }
218
+ }
219
+
220
+ // Limpiar container si se proporciona
221
+ if (container) {
222
+ container.innerHTML = '';
223
+ }
224
+ };
225
+
226
+ // Intentar registrar con Wu Framework
227
+ try {
228
+ const wu = await waitForWu(3000);
229
+
230
+ wu.define(appName, {
231
+ mount: mountApp,
232
+ unmount: unmountApp
233
+ });
234
+
235
+ console.log(`[WuVue] ✅ ${appName} registered with Wu Framework`);
236
+ return true;
237
+
238
+ } catch (error) {
239
+ console.warn(`[WuVue] Wu Framework not available for ${appName}`);
240
+
241
+ // Modo standalone si está habilitado
242
+ if (standalone) {
243
+ const containerElement = document.querySelector(standaloneContainer);
244
+
245
+ if (containerElement) {
246
+ console.log(`[WuVue] Running ${appName} in standalone mode`);
247
+ mountApp(containerElement);
248
+ return true;
249
+ } else {
250
+ console.warn(`[WuVue] Standalone container ${standaloneContainer} not found`);
251
+ }
252
+ }
253
+
254
+ return false;
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Crea un componente Vue para cargar microfrontends (para el Shell)
260
+ *
261
+ * @example
262
+ * <script setup>
263
+ * import { WuSlot } from 'wu-framework/adapters/vue';
264
+ * </script>
265
+ *
266
+ * <template>
267
+ * <WuSlot name="my-app" url="http://localhost:3001" />
268
+ * </template>
269
+ */
270
+ const WuSlot = {
271
+ name: 'WuSlot',
272
+
273
+ props: {
274
+ name: {
275
+ type: String,
276
+ required: true
277
+ },
278
+ url: {
279
+ type: String,
280
+ required: true
281
+ },
282
+ appName: {
283
+ type: String,
284
+ default: null
285
+ },
286
+ fallbackText: {
287
+ type: String,
288
+ default: 'Loading...'
289
+ }
290
+ },
291
+
292
+ emits: ['load', 'error', 'mount', 'unmount'],
293
+
294
+ data() {
295
+ return {
296
+ loading: true,
297
+ error: null,
298
+ appInstance: null,
299
+ containerId: null
300
+ };
301
+ },
302
+
303
+ computed: {
304
+ actualAppName() {
305
+ return this.appName || this.name;
306
+ }
307
+ },
308
+
309
+ async mounted() {
310
+ await this.mountMicrofrontend();
311
+ },
312
+
313
+ beforeUnmount() {
314
+ this.unmountMicrofrontend();
315
+ },
316
+
317
+ methods: {
318
+ async mountMicrofrontend() {
319
+ try {
320
+ this.loading = true;
321
+ this.error = null;
322
+
323
+ const wu = getWuInstance();
324
+ if (!wu) {
325
+ throw new Error('Wu Framework not initialized');
326
+ }
327
+
328
+ // Crear container único
329
+ this.containerId = `wu-slot-${this.actualAppName}-${Date.now()}`;
330
+ const innerContainer = document.createElement('div');
331
+ innerContainer.id = this.containerId;
332
+ innerContainer.style.width = '100%';
333
+ innerContainer.style.height = '100%';
334
+
335
+ this.$refs.container.innerHTML = '';
336
+ this.$refs.container.appendChild(innerContainer);
337
+
338
+ // Crear y montar la app
339
+ const app = wu.app(this.actualAppName, {
340
+ url: this.url,
341
+ container: `#${this.containerId}`,
342
+ autoInit: true
343
+ });
344
+
345
+ this.appInstance = app;
346
+ await app.mount();
347
+
348
+ this.loading = false;
349
+ this.$emit('load', { name: this.actualAppName, url: this.url });
350
+ this.$emit('mount', { name: this.actualAppName, container: innerContainer });
351
+
352
+ } catch (err) {
353
+ console.error(`[WuSlot] Error loading ${this.actualAppName}:`, err);
354
+ this.error = err.message || 'Failed to load microfrontend';
355
+ this.loading = false;
356
+ this.$emit('error', err);
357
+ }
358
+ },
359
+
360
+ async unmountMicrofrontend() {
361
+ if (this.appInstance) {
362
+ this.$emit('unmount', { name: this.actualAppName });
363
+
364
+ try {
365
+ await this.appInstance.unmount();
366
+ } catch (err) {
367
+ console.warn(`[WuSlot] Error unmounting ${this.actualAppName}:`, err);
368
+ }
369
+
370
+ this.appInstance = null;
371
+ }
372
+ }
373
+ },
374
+
375
+ template: `
376
+ <div
377
+ ref="container"
378
+ class="wu-slot"
379
+ :class="{ 'wu-slot-loading': loading, 'wu-slot-error': error }"
380
+ :data-wu-app="actualAppName"
381
+ :data-wu-url="url"
382
+ style="min-height: 100px; position: relative;"
383
+ >
384
+ <div v-if="error" class="wu-slot-error-message" style="padding: 1rem; border: 1px solid #f5c6cb; border-radius: 4px; background: #f8d7da; color: #721c24;">
385
+ <strong>Error loading {{ name }}</strong>
386
+ <p style="margin: 0.5rem 0 0 0;">{{ error }}</p>
387
+ </div>
388
+ <div v-else-if="loading" class="wu-slot-loading-message" style="display: flex; align-items: center; justify-content: center; padding: 2rem; color: #666;">
389
+ {{ fallbackText || 'Loading ' + name + '...' }}
390
+ </div>
391
+ </div>
392
+ `
393
+ };
394
+
395
+ /**
396
+ * Composable para usar el EventBus de Wu Framework en Vue 3
397
+ *
398
+ * @example
399
+ * <script setup>
400
+ * import { useWuEvents } from 'wu-framework/adapters/vue';
401
+ *
402
+ * const { emit, on } = useWuEvents();
403
+ *
404
+ * onMounted(() => {
405
+ * on('user:login', (data) => console.log(data));
406
+ * });
407
+ * </script>
408
+ */
409
+ function useWuEvents() {
410
+ const subscriptions = [];
411
+
412
+ const emit = (event, data, options) => {
413
+ const wu = getWuInstance();
414
+ if (wu?.eventBus) {
415
+ wu.eventBus.emit(event, data, options);
416
+ } else {
417
+ console.warn('[useWuEvents] Wu Framework not available');
418
+ }
419
+ };
420
+
421
+ const on = (event, callback) => {
422
+ const wu = getWuInstance();
423
+ if (wu?.eventBus) {
424
+ const unsubscribe = wu.eventBus.on(event, callback);
425
+ subscriptions.push(unsubscribe);
426
+ return unsubscribe;
427
+ }
428
+ console.warn('[useWuEvents] Wu Framework not available');
429
+ return () => {};
430
+ };
431
+
432
+ const once = (event, callback) => {
433
+ const wu = getWuInstance();
434
+ if (wu?.eventBus) {
435
+ return wu.eventBus.once(event, callback);
436
+ }
437
+ console.warn('[useWuEvents] Wu Framework not available');
438
+ return () => {};
439
+ };
440
+
441
+ const off = (event, callback) => {
442
+ const wu = getWuInstance();
443
+ if (wu?.eventBus) {
444
+ wu.eventBus.off(event, callback);
445
+ }
446
+ };
447
+
448
+ // Cleanup - llamar en onUnmounted
449
+ const cleanup = () => {
450
+ subscriptions.forEach(unsub => unsub());
451
+ subscriptions.length = 0;
452
+ };
453
+
454
+ return { emit, on, once, off, cleanup };
455
+ }
456
+
457
+ /**
458
+ * Composable para usar el Store de Wu Framework en Vue 3
459
+ *
460
+ * @example
461
+ * <script setup>
462
+ * import { useWuStore } from 'wu-framework/adapters/vue';
463
+ *
464
+ * const { state, setState, getState } = useWuStore('user');
465
+ *
466
+ * // state es reactivo!
467
+ * console.log(state.value);
468
+ * </script>
469
+ */
470
+ function useWuStore(namespace = '') {
471
+ // Importar ref y watch de Vue si están disponibles
472
+ const Vue = adapterState.Vue;
473
+ let state;
474
+ let unsubscribe = null;
475
+
476
+ // Crear estado reactivo si Vue está disponible
477
+ if (Vue?.ref) {
478
+ const wu = getWuInstance();
479
+ const initialValue = wu?.store?.get(namespace) || null;
480
+ state = Vue.ref(initialValue);
481
+
482
+ // Suscribirse a cambios
483
+ if (wu?.store) {
484
+ const pattern = namespace ? `${namespace}.*` : '*';
485
+ unsubscribe = wu.store.on(pattern, () => {
486
+ state.value = wu.store.get(namespace);
487
+ });
488
+ }
489
+ } else {
490
+ // Fallback sin reactividad
491
+ state = { value: null };
492
+ }
493
+
494
+ const setState = (path, value) => {
495
+ const wu = getWuInstance();
496
+ if (wu?.store) {
497
+ const fullPath = namespace ? `${namespace}.${path}` : path;
498
+ wu.store.set(fullPath, value);
499
+ }
500
+ };
501
+
502
+ const getState = (path = '') => {
503
+ const wu = getWuInstance();
504
+ if (wu?.store) {
505
+ const fullPath = namespace ? (path ? `${namespace}.${path}` : namespace) : path;
506
+ return wu.store.get(fullPath);
507
+ }
508
+ return null;
509
+ };
510
+
511
+ const cleanup = () => {
512
+ if (unsubscribe) {
513
+ unsubscribe();
514
+ unsubscribe = null;
515
+ }
516
+ };
517
+
518
+ return { state, setState, getState, cleanup };
519
+ }
520
+
521
+ /**
522
+ * Plugin de Vue para instalar Wu Framework globalmente
523
+ *
524
+ * @example
525
+ * import { createApp } from 'vue';
526
+ * import { wuVuePlugin } from 'wu-framework/adapters/vue';
527
+ *
528
+ * const app = createApp(App);
529
+ * app.use(wuVuePlugin);
530
+ */
531
+ const wuVuePlugin = {
532
+ install(app, options = {}) {
533
+ // Registrar componente WuSlot globalmente
534
+ app.component('WuSlot', WuSlot);
535
+
536
+ // Proveer acceso global a Wu
537
+ app.provide('wu', getWuInstance());
538
+
539
+ // Agregar propiedades globales
540
+ app.config.globalProperties.$wu = getWuInstance();
541
+ app.config.globalProperties.$wuEvents = useWuEvents();
542
+ app.config.globalProperties.$wuStore = (ns) => useWuStore(ns);
543
+
544
+ console.log('[WuVue] Plugin installed');
545
+ }
546
+ };
547
+
548
+ // API pública del adapter
549
+ export const wuVue = {
550
+ register,
551
+ WuSlot,
552
+ useWuEvents,
553
+ useWuStore,
554
+ wuVuePlugin,
555
+ getWuInstance,
556
+ waitForWu
557
+ };
558
+
559
+ // Named exports para conveniencia
560
+ export {
561
+ register,
562
+ WuSlot,
563
+ useWuEvents,
564
+ useWuStore,
565
+ wuVuePlugin,
566
+ getWuInstance,
567
+ waitForWu
568
+ };
569
+
570
+ export default wuVue;