slicejs-web-framework 2.3.1 → 2.3.2

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.
@@ -1,598 +1,720 @@
1
- export default class Router {
2
- constructor(routes) {
3
- this.routes = routes;
4
- this.activeRoute = null;
5
- this.pathToRouteMap = this.createPathToRouteMap(routes);
6
-
7
- // Navigation Guards
8
- this._beforeEachGuard = null;
9
- this._afterEachGuard = null;
10
-
11
- // Router state
12
- this._started = false;
13
- this._autoStartTimeout = null;
14
-
15
- // Sistema de caché optimizado
16
- this.routeContainersCache = new Map();
17
- this.lastCacheUpdate = 0;
18
- this.CACHE_DURATION = 100; // ms - caché muy corto pero efectivo
19
-
20
- // Observer para invalidar caché automáticamente
21
- this.setupMutationObserver();
22
- }
23
-
24
- /**
25
- * Inicializa el router
26
- * Si el usuario no llama start() manualmente, se auto-inicia después de un delay
27
- */
28
- init() {
29
- window.addEventListener('popstate', this.onRouteChange.bind(this));
30
-
31
- // Auto-start después de 50ms si el usuario no llama start() manualmente
32
- // Esto da tiempo para que el usuario configure guards si lo necesita
33
- this._autoStartTimeout = setTimeout(async () => {
34
- if (!this._started) {
35
- slice.logger.logInfo('Router', 'Auto-starting router (no manual start() called)');
36
- await this.start();
37
- }
38
- }, 50);
39
- }
40
-
41
- /**
42
- * Inicia el router y carga la ruta inicial
43
- * OPCIONAL: Solo necesario si usas guards (beforeEach/afterEach)
44
- * Si no lo llamas, el router se auto-inicia después de 50ms
45
- */
46
- async start() {
47
- // Prevenir múltiples llamadas
48
- if (this._started) {
49
- slice.logger.logWarning('Router', 'start() already called');
50
- return;
51
- }
52
-
53
- // Cancelar auto-start si existe
54
- if (this._autoStartTimeout) {
55
- clearTimeout(this._autoStartTimeout);
56
- this._autoStartTimeout = null;
57
- }
58
-
59
- this._started = true;
60
- await this.loadInitialRoute();
61
- }
62
-
63
- // ============================================
64
- // NAVIGATION GUARDS API
65
- // ============================================
66
-
67
- /**
68
- * Registra un guard que se ejecuta ANTES de cada navegación
69
- * Puede bloquear o redirigir la navegación
70
- * @param {Function} guard - Función (to, from, next) => {}
71
- */
72
- beforeEach(guard) {
73
- if (typeof guard !== 'function') {
74
- slice.logger.logError('Router', 'beforeEach expects a function');
75
- return;
76
- }
77
- this._beforeEachGuard = guard;
78
- }
79
-
80
- /**
81
- * Registra un guard que se ejecuta DESPUÉS de cada navegación
82
- * No puede bloquear la navegación
83
- * @param {Function} guard - Función (to, from) => {}
84
- */
85
- afterEach(guard) {
86
- if (typeof guard !== 'function') {
87
- slice.logger.logError('Router', 'afterEach expects a function');
88
- return;
89
- }
90
- this._afterEachGuard = guard;
91
- }
92
-
93
- /**
94
- * Crea un objeto con información de ruta para los guards
95
- * @param {Object} route - Objeto de ruta
96
- * @param {Object} params - Parámetros de la ruta
97
- * @param {String} requestedPath - Path original solicitado
98
- * @returns {Object} Objeto con path, component, params, query, metadata
99
- */
100
- _createRouteInfo(route, params = {}, requestedPath = null) {
101
- if (!route) {
102
- return {
103
- path: requestedPath || '/404',
104
- component: 'NotFound',
105
- params: {},
106
- query: this._parseQueryParams(),
107
- metadata: {},
108
- };
109
- }
110
-
111
- return {
112
- path: requestedPath || route.fullPath || route.path,
113
- component: route.parentRoute ? route.parentRoute.component : route.component,
114
- params: params,
115
- query: this._parseQueryParams(),
116
- metadata: route.metadata || {},
117
- };
118
- }
119
-
120
- /**
121
- * Parsea los query parameters de la URL actual
122
- * @returns {Object} Objeto con los query params
123
- */
124
- _parseQueryParams() {
125
- const queryString = window.location.search;
126
- if (!queryString) return {};
127
-
128
- const params = {};
129
- const urlParams = new URLSearchParams(queryString);
130
-
131
- for (const [key, value] of urlParams) {
132
- params[key] = value;
133
- }
134
-
135
- return params;
136
- }
137
-
138
- /**
139
- * Ejecuta el beforeEach guard si existe
140
- * @param {Object} to - Información de ruta destino
141
- * @param {Object} from - Información de ruta origen
142
- * @returns {Object|null} Objeto con redirectPath y options, o null si continúa
143
- */
144
- async _executeBeforeEachGuard(to, from) {
145
- if (!this._beforeEachGuard) {
146
- return null;
147
- }
148
-
149
- let redirectPath = null;
150
- let redirectOptions = {};
151
- let nextCalled = false;
152
-
153
- const next = (arg) => {
154
- if (nextCalled) {
155
- slice.logger.logWarning('Router', 'next() called multiple times in guard');
156
- return;
157
- }
158
- nextCalled = true;
159
-
160
- // Caso 1: Sin argumentos - continuar navegación
161
- if (arg === undefined) {
162
- return;
163
- }
164
-
165
- // Caso 2: false - cancelar navegación
166
- if (arg === false) {
167
- redirectPath = false;
168
- return;
169
- }
170
-
171
- // Caso 3: String - redirección simple (backward compatibility)
172
- if (typeof arg === 'string') {
173
- redirectPath = arg;
174
- redirectOptions = { replace: false };
175
- return;
176
- }
177
-
178
- // Caso 4: Objeto - redirección con opciones
179
- if (typeof arg === 'object' && arg.path) {
180
- redirectPath = arg.path;
181
- redirectOptions = {
182
- replace: arg.replace || false,
183
- };
184
- return;
185
- }
186
-
187
- // Argumento inválido
188
- slice.logger.logError(
189
- 'Router',
190
- 'Invalid argument passed to next(). Expected string, object with path, false, or undefined.'
191
- );
192
- };
193
-
194
- try {
195
- await this._beforeEachGuard(to, from, next);
196
-
197
- // Si no se llamó next(), loguear advertencia pero continuar
198
- if (!nextCalled) {
199
- slice.logger.logWarning('Router', 'beforeEach guard did not call next(). Navigation will continue.');
200
- }
201
-
202
- // Retornar tanto el path como las opciones
203
- return redirectPath ? { path: redirectPath, options: redirectOptions } : null;
204
- } catch (error) {
205
- slice.logger.logError('Router', 'Error in beforeEach guard', error);
206
- return null; // En caso de error, continuar con la navegación
207
- }
208
- }
209
-
210
- /**
211
- * Ejecuta el afterEach guard si existe
212
- * @param {Object} to - Información de ruta destino
213
- * @param {Object} from - Información de ruta origen
214
- */
215
- _executeAfterEachGuard(to, from) {
216
- if (!this._afterEachGuard) {
217
- return;
218
- }
219
-
220
- try {
221
- this._afterEachGuard(to, from);
222
- } catch (error) {
223
- slice.logger.logError('Router', 'Error in afterEach guard', error);
224
- }
225
- }
226
-
227
- // ============================================
228
- // ROUTING CORE (MODIFICADO CON GUARDS)
229
- // ============================================
230
-
231
- async navigate(path, _redirectChain = [], _options = {}) {
232
- const currentPath = window.location.pathname;
233
-
234
- // Detectar loops infinitos: si ya visitamos esta ruta en la cadena de redirecciones
235
- if (_redirectChain.includes(path)) {
236
- slice.logger.logError('Router', `Guard redirection loop detected: ${_redirectChain.join(' → ')} → ${path}`);
237
- return;
238
- }
239
-
240
- // Límite de seguridad: máximo 10 redirecciones
241
- if (_redirectChain.length >= 10) {
242
- slice.logger.logError('Router', `Too many redirections: ${_redirectChain.join(' ')} → ${path}`);
243
- return;
244
- }
245
-
246
- // Obtener información de ruta actual
247
- const { route: fromRoute, params: fromParams } = this.matchRoute(currentPath);
248
- const from = this._createRouteInfo(fromRoute, fromParams, currentPath);
249
-
250
- // Obtener información de ruta destino
251
- const { route: toRoute, params: toParams } = this.matchRoute(path);
252
- const to = this._createRouteInfo(toRoute, toParams, path);
253
-
254
- // EJECUTAR BEFORE EACH GUARD
255
- const guardResult = await this._executeBeforeEachGuard(to, from);
256
-
257
- // Si el guard redirige
258
- if (guardResult && guardResult.path) {
259
- const newChain = [..._redirectChain, path];
260
- return this.navigate(guardResult.path, newChain, guardResult.options);
261
- }
262
-
263
- // Si el guard cancela la navegación (next(false))
264
- if (guardResult && guardResult.path === false) {
265
- slice.logger.logInfo('Router', 'Navigation cancelled by guard');
266
- return;
267
- }
268
-
269
- // No hay redirección - continuar con la navegación normal
270
- // Usar replace o push según las opciones
271
- if (_options.replace) {
272
- window.history.replaceState({}, path, window.location.origin + path);
273
- } else {
274
- window.history.pushState({}, path, window.location.origin + path);
275
- }
276
-
277
- await this._performNavigation(to, from);
278
- }
279
-
280
- /**
281
- * Método interno para ejecutar la navegación después de pasar los guards
282
- * @param {Object} to - Información de ruta destino
283
- * @param {Object} from - Información de ruta origen
284
- */
285
- async _performNavigation(to, from) {
286
- // Renderizar la nueva ruta
287
- await this.onRouteChange();
288
-
289
- // EJECUTAR AFTER EACH GUARD
290
- this._executeAfterEachGuard(to, from);
291
-
292
- // Emitir evento de cambio de ruta
293
- this._emitRouteChange(to, from);
294
- }
295
-
296
- async onRouteChange() {
297
- // Cancelar el timeout anterior si existe
298
- if (this.routeChangeTimeout) {
299
- clearTimeout(this.routeChangeTimeout);
300
- }
301
-
302
- // Debounce de 10ms para evitar múltiples llamadas seguidas
303
- this.routeChangeTimeout = setTimeout(async () => {
304
- const path = window.location.pathname;
305
- const routeContainersFlag = await this.renderRoutesComponentsInPage();
306
-
307
- if (routeContainersFlag) {
308
- return;
309
- }
310
-
311
- const { route, params } = this.matchRoute(path);
312
- if (route) {
313
- await this.handleRoute(route, params);
314
- }
315
- }, 10);
316
- }
317
-
318
- async handleRoute(route, params) {
319
- const targetElement = document.querySelector('#app');
320
-
321
- const componentName = route.parentRoute ? route.parentRoute.component : route.component;
322
- const sliceId = `route-${componentName}`;
323
-
324
- const existingComponent = slice.controller.getComponent(sliceId);
325
-
326
- if (slice.loading) {
327
- slice.loading.start();
328
- }
329
-
330
- if (existingComponent) {
331
- targetElement.innerHTML = '';
332
- if (existingComponent.update) {
333
- existingComponent.props = { ...existingComponent.props, ...params };
334
- await existingComponent.update();
335
- }
336
- targetElement.appendChild(existingComponent);
337
- await this.renderRoutesInComponent(existingComponent);
338
- } else {
339
- const component = await slice.build(componentName, {
340
- params,
341
- sliceId: sliceId,
342
- });
343
-
344
- targetElement.innerHTML = '';
345
- targetElement.appendChild(component);
346
-
347
- await this.renderRoutesInComponent(component);
348
- }
349
-
350
- // Invalidar caché después de cambios importantes en el DOM
351
- this.invalidateCache();
352
-
353
- if (slice.loading) {
354
- slice.loading.stop();
355
- }
356
-
357
- slice.router.activeRoute = route;
358
- }
359
-
360
- async loadInitialRoute() {
361
- const path = window.location.pathname;
362
- const { route, params } = this.matchRoute(path);
363
-
364
- // Para la carga inicial, también ejecutar guards
365
- const from = this._createRouteInfo(null, {}, null);
366
- const to = this._createRouteInfo(route, params, path);
367
-
368
- // EJECUTAR BEFORE EACH GUARD en carga inicial
369
- const guardResult = await this._executeBeforeEachGuard(to, from);
370
-
371
- if (guardResult && guardResult.path) {
372
- return this.navigate(guardResult.path, [], guardResult.options);
373
- }
374
-
375
- // Si el guard cancela la navegación inicial (caso raro pero posible)
376
- if (guardResult && guardResult.path === false) {
377
- slice.logger.logWarning('Router', 'Initial route navigation cancelled by guard');
378
- return;
379
- }
380
-
381
- await this.handleRoute(route, params);
382
-
383
- // EJECUTAR AFTER EACH GUARD en carga inicial
384
- this._executeAfterEachGuard(to, from);
385
-
386
- // Emitir evento de cambio de ruta
387
- this._emitRouteChange(to, from);
388
- }
389
-
390
- /**
391
- * Emitir evento de cambio de ruta
392
- * @param {Object} to
393
- * @param {Object} from
394
- */
395
- _emitRouteChange(to, from) {
396
- const payload = { to, from };
397
-
398
- if (slice.eventsConfig?.enabled && slice.events && typeof slice.events.emit === 'function') {
399
- slice.events.emit('router:change', payload);
400
- return;
401
- }
402
-
403
- window.dispatchEvent(new CustomEvent('router:change', { detail: payload }));
404
- }
405
-
406
- // ============================================
407
- // MÉTODOS EXISTENTES (SIN CAMBIOS)
408
- // ============================================
409
-
410
- setupMutationObserver() {
411
- if (typeof MutationObserver !== 'undefined') {
412
- this.observer = new MutationObserver((mutations) => {
413
- let shouldInvalidateCache = false;
414
-
415
- mutations.forEach((mutation) => {
416
- if (mutation.type === 'childList') {
417
- const addedNodes = Array.from(mutation.addedNodes);
418
- const removedNodes = Array.from(mutation.removedNodes);
419
-
420
- const hasRouteNodes = [...addedNodes, ...removedNodes].some(
421
- (node) =>
422
- node.nodeType === Node.ELEMENT_NODE &&
423
- (node.tagName === 'SLICE-ROUTE' ||
424
- node.tagName === 'SLICE-MULTI-ROUTE' ||
425
- node.querySelector?.('slice-route, slice-multi-route'))
426
- );
427
-
428
- if (hasRouteNodes) {
429
- shouldInvalidateCache = true;
430
- }
431
- }
432
- });
433
-
434
- if (shouldInvalidateCache) {
435
- this.invalidateCache();
436
- }
437
- });
438
-
439
- this.observer.observe(document.body, {
440
- childList: true,
441
- subtree: true,
442
- });
443
- }
444
- }
445
-
446
- invalidateCache() {
447
- this.routeContainersCache.clear();
448
- this.lastCacheUpdate = 0;
449
- }
450
-
451
- createPathToRouteMap(routes, basePath = '', parentRoute = null) {
452
- const pathToRouteMap = new Map();
453
-
454
- for (const route of routes) {
455
- const fullPath = `${basePath}${route.path}`.replace(/\/+/g, '/');
456
-
457
- const routeWithParent = {
458
- ...route,
459
- fullPath,
460
- parentPath: parentRoute ? parentRoute.fullPath : null,
461
- parentRoute: parentRoute,
462
- };
463
-
464
- pathToRouteMap.set(fullPath, routeWithParent);
465
-
466
- if (route.children) {
467
- const childPathToRouteMap = this.createPathToRouteMap(route.children, fullPath, routeWithParent);
468
-
469
- for (const [childPath, childRoute] of childPathToRouteMap.entries()) {
470
- pathToRouteMap.set(childPath, childRoute);
471
- }
472
- }
473
- }
474
-
475
- return pathToRouteMap;
476
- }
477
-
478
- async renderRoutesComponentsInPage(searchContainer = document) {
479
- let routerContainersFlag = false;
480
- const routeContainers = this.getCachedRouteContainers(searchContainer);
481
-
482
- for (const routeContainer of routeContainers) {
483
- try {
484
- if (!routeContainer.isConnected) {
485
- this.invalidateCache();
486
- continue;
487
- }
488
-
489
- let response = await routeContainer.renderIfCurrentRoute();
490
- if (response) {
491
- this.activeRoute = routeContainer.props;
492
- routerContainersFlag = true;
493
- }
494
- } catch (error) {
495
- slice.logger.logError('Router', `Error rendering route container`, error);
496
- }
497
- }
498
-
499
- return routerContainersFlag;
500
- }
501
-
502
- getCachedRouteContainers(container) {
503
- const containerKey = container === document ? 'document' : container.sliceId || 'anonymous';
504
- const now = Date.now();
505
-
506
- if (this.routeContainersCache.has(containerKey) && now - this.lastCacheUpdate < this.CACHE_DURATION) {
507
- return this.routeContainersCache.get(containerKey);
508
- }
509
-
510
- const routeContainers = this.findAllRouteContainersOptimized(container);
511
- this.routeContainersCache.set(containerKey, routeContainers);
512
- this.lastCacheUpdate = now;
513
-
514
- return routeContainers;
515
- }
516
-
517
- findAllRouteContainersOptimized(container) {
518
- const routeContainers = [];
519
-
520
- const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
521
- acceptNode: (node) => {
522
- if (node.tagName === 'SLICE-ROUTE' || node.tagName === 'SLICE-MULTI-ROUTE') {
523
- return NodeFilter.FILTER_ACCEPT;
524
- }
525
- return NodeFilter.FILTER_SKIP;
526
- },
527
- });
528
-
529
- let node;
530
- while ((node = walker.nextNode())) {
531
- routeContainers.push(node);
532
- }
533
-
534
- return routeContainers;
535
- }
536
-
537
- async renderRoutesInComponent(component) {
538
- if (!component) {
539
- slice.logger.logWarning('Router', 'No component provided for route rendering');
540
- return false;
541
- }
542
-
543
- return await this.renderRoutesComponentsInPage(component);
544
- }
545
-
546
- matchRoute(path) {
547
- const exactMatch = this.pathToRouteMap.get(path);
548
- if (exactMatch) {
549
- if (exactMatch.parentRoute) {
550
- return {
551
- route: exactMatch.parentRoute,
552
- params: {},
553
- childRoute: exactMatch,
554
- };
555
- }
556
- return { route: exactMatch, params: {} };
557
- }
558
-
559
- for (const [routePattern, route] of this.pathToRouteMap.entries()) {
560
- if (routePattern.includes('${')) {
561
- const { regex, paramNames } = this.compilePathPattern(routePattern);
562
- const match = path.match(regex);
563
- if (match) {
564
- const params = {};
565
- paramNames.forEach((name, i) => {
566
- params[name] = match[i + 1];
567
- });
568
-
569
- if (route.parentRoute) {
570
- return {
571
- route: route.parentRoute,
572
- params: params,
573
- childRoute: route,
574
- };
575
- }
576
-
577
- return { route, params };
578
- }
579
- }
580
- }
581
-
582
- const notFoundRoute = this.pathToRouteMap.get('/404');
583
- return { route: notFoundRoute, params: {} };
584
- }
585
-
586
- compilePathPattern(pattern) {
587
- const paramNames = [];
588
- const regexPattern =
589
- '^' +
590
- pattern.replace(/\$\{([^}]+)\}/g, (_, paramName) => {
591
- paramNames.push(paramName);
592
- return '([^/]+)';
593
- }) +
594
- '$';
595
-
596
- return { regex: new RegExp(regexPattern), paramNames };
597
- }
598
- }
1
+ /**
2
+ * @typedef {Object} RouteConfig
3
+ * @property {string} path
4
+ * @property {string} component
5
+ * @property {RouteConfig[]} [children]
6
+ * @property {Object} [metadata]
7
+ * @property {string} [fullPath]
8
+ * @property {string|null} [parentPath]
9
+ * @property {RouteConfig|null} [parentRoute]
10
+ */
11
+
12
+ /**
13
+ * @typedef {Object} RouteInfo
14
+ * @property {string} path
15
+ * @property {string} component
16
+ * @property {Object} params
17
+ * @property {Object} query
18
+ * @property {Object} metadata
19
+ */
20
+
21
+ /**
22
+ * @typedef {Object} GuardRedirect
23
+ * @property {string} path
24
+ * @property {boolean} [replace]
25
+ */
26
+
27
+ /**
28
+ * @typedef {Object} RouteMatch
29
+ * @property {RouteConfig|null} route
30
+ * @property {Object} params
31
+ * @property {RouteConfig} [childRoute]
32
+ */
33
+
34
+ /**
35
+ * @callback RouterNext
36
+ * @param {void|false|string|{ path: string, replace?: boolean }} [arg]
37
+ * @returns {void}
38
+ */
39
+
40
+ export default class Router {
41
+ /**
42
+ * @param {RouteConfig[]} routes
43
+ */
44
+ constructor(routes) {
45
+ this.routes = routes;
46
+ this.activeRoute = null;
47
+ this.pathToRouteMap = this.createPathToRouteMap(routes);
48
+
49
+ // Navigation Guards
50
+ this._beforeEachGuard = null;
51
+ this._afterEachGuard = null;
52
+
53
+ // Router state
54
+ this._started = false;
55
+ this._autoStartTimeout = null;
56
+
57
+ // Sistema de caché optimizado
58
+ this.routeContainersCache = new Map();
59
+ this.lastCacheUpdate = 0;
60
+ this.CACHE_DURATION = 100; // ms - caché muy corto pero efectivo
61
+
62
+ // Observer para invalidar caché automáticamente
63
+ this.setupMutationObserver();
64
+ }
65
+
66
+ /**
67
+ * Inicializa el router
68
+ * Si el usuario no llama start() manualmente, se auto-inicia despues de un delay
69
+ * @returns {void}
70
+ */
71
+ init() {
72
+ window.addEventListener('popstate', this.onRouteChange.bind(this));
73
+
74
+ // Auto-start después de 50ms si el usuario no llama start() manualmente
75
+ // Esto da tiempo para que el usuario configure guards si lo necesita
76
+ this._autoStartTimeout = setTimeout(async () => {
77
+ if (!this._started) {
78
+ slice.logger.logInfo('Router', 'Auto-starting router (no manual start() called)');
79
+ await this.start();
80
+ }
81
+ }, 50);
82
+ }
83
+
84
+ /**
85
+ * Inicia el router y carga la ruta inicial
86
+ * OPCIONAL: Solo necesario si usas guards (beforeEach/afterEach)
87
+ * Si no lo llamas, el router se auto-inicia despues de 50ms
88
+ * @returns {Promise<void>}
89
+ */
90
+ async start() {
91
+ // Prevenir múltiples llamadas
92
+ if (this._started) {
93
+ slice.logger.logWarning('Router', 'start() already called');
94
+ return;
95
+ }
96
+
97
+ // Cancelar auto-start si existe
98
+ if (this._autoStartTimeout) {
99
+ clearTimeout(this._autoStartTimeout);
100
+ this._autoStartTimeout = null;
101
+ }
102
+
103
+ this._started = true;
104
+ await this.loadInitialRoute();
105
+ }
106
+
107
+ // ============================================
108
+ // NAVIGATION GUARDS API
109
+ // ============================================
110
+
111
+ /**
112
+ * Registra un guard que se ejecuta ANTES de cada navegacion.
113
+ * Puede bloquear o redirigir la navegacion mediante next().
114
+ * @param {(to: RouteInfo, from: RouteInfo, next: RouterNext) => void|Promise<void>} guard
115
+ * @returns {void}
116
+ */
117
+ beforeEach(guard) {
118
+ if (typeof guard !== 'function') {
119
+ slice.logger.logError('Router', 'beforeEach expects a function');
120
+ return;
121
+ }
122
+ this._beforeEachGuard = guard;
123
+ }
124
+
125
+ /**
126
+ * Registra un guard que se ejecuta DESPUES de cada navegacion.
127
+ * No puede bloquear la navegacion.
128
+ * @param {(to: RouteInfo, from: RouteInfo) => void} guard
129
+ * @returns {void}
130
+ */
131
+ afterEach(guard) {
132
+ if (typeof guard !== 'function') {
133
+ slice.logger.logError('Router', 'afterEach expects a function');
134
+ return;
135
+ }
136
+ this._afterEachGuard = guard;
137
+ }
138
+
139
+ /**
140
+ * Crea un objeto con información de ruta para los guards
141
+ * @param {Object} route - Objeto de ruta
142
+ * @param {Object} params - Parámetros de la ruta
143
+ * @param {String} requestedPath - Path original solicitado
144
+ * @returns {Object} Objeto con path, component, params, query, metadata
145
+ */
146
+ /**
147
+ * Build route info used by guards and events.
148
+ * @param {RouteConfig|null} route
149
+ * @param {Object} [params]
150
+ * @param {string|null} [requestedPath]
151
+ * @returns {RouteInfo}
152
+ */
153
+ _createRouteInfo(route, params = {}, requestedPath = null) {
154
+ if (!route) {
155
+ return {
156
+ path: requestedPath || '/404',
157
+ component: 'NotFound',
158
+ params: {},
159
+ query: this._parseQueryParams(),
160
+ metadata: {},
161
+ };
162
+ }
163
+
164
+ return {
165
+ path: requestedPath || route.fullPath || route.path,
166
+ component: route.parentRoute ? route.parentRoute.component : route.component,
167
+ params: params,
168
+ query: this._parseQueryParams(),
169
+ metadata: route.metadata || {},
170
+ };
171
+ }
172
+
173
+ /**
174
+ * Parsea los query parameters de la URL actual
175
+ * @returns {Object} Objeto con los query params
176
+ */
177
+ /**
178
+ * Parse query params from current URL.
179
+ * @returns {Object}
180
+ */
181
+ _parseQueryParams() {
182
+ const queryString = window.location.search;
183
+ if (!queryString) return {};
184
+
185
+ const params = {};
186
+ const urlParams = new URLSearchParams(queryString);
187
+
188
+ for (const [key, value] of urlParams) {
189
+ params[key] = value;
190
+ }
191
+
192
+ return params;
193
+ }
194
+
195
+ /**
196
+ * Ejecuta el beforeEach guard si existe
197
+ * @param {Object} to - Información de ruta destino
198
+ * @param {Object} from - Información de ruta origen
199
+ * @returns {Object|null} Objeto con redirectPath y options, o null si continúa
200
+ */
201
+ /**
202
+ * Execute beforeEach guard if defined.
203
+ * @param {RouteInfo} to
204
+ * @param {RouteInfo} from
205
+ * @returns {Promise<{ path: string|false, options: { replace?: boolean } }|null>}
206
+ */
207
+ async _executeBeforeEachGuard(to, from) {
208
+ if (!this._beforeEachGuard) {
209
+ return null;
210
+ }
211
+
212
+ let redirectPath = null;
213
+ let redirectOptions = {};
214
+ let nextCalled = false;
215
+
216
+ const next = (arg) => {
217
+ if (nextCalled) {
218
+ slice.logger.logWarning('Router', 'next() called multiple times in guard');
219
+ return;
220
+ }
221
+ nextCalled = true;
222
+
223
+ // Caso 1: Sin argumentos - continuar navegación
224
+ if (arg === undefined) {
225
+ return;
226
+ }
227
+
228
+ // Caso 2: false - cancelar navegación
229
+ if (arg === false) {
230
+ redirectPath = false;
231
+ return;
232
+ }
233
+
234
+ // Caso 3: String - redirección simple (backward compatibility)
235
+ if (typeof arg === 'string') {
236
+ redirectPath = arg;
237
+ redirectOptions = { replace: false };
238
+ return;
239
+ }
240
+
241
+ // Caso 4: Objeto - redirección con opciones
242
+ if (typeof arg === 'object' && arg.path) {
243
+ redirectPath = arg.path;
244
+ redirectOptions = {
245
+ replace: arg.replace || false,
246
+ };
247
+ return;
248
+ }
249
+
250
+ // Argumento inválido
251
+ slice.logger.logError(
252
+ 'Router',
253
+ 'Invalid argument passed to next(). Expected string, object with path, false, or undefined.'
254
+ );
255
+ };
256
+
257
+ try {
258
+ await this._beforeEachGuard(to, from, next);
259
+
260
+ // Si no se llamó next(), loguear advertencia pero continuar
261
+ if (!nextCalled) {
262
+ slice.logger.logWarning('Router', 'beforeEach guard did not call next(). Navigation will continue.');
263
+ }
264
+
265
+ // Retornar tanto el path como las opciones
266
+ return redirectPath ? { path: redirectPath, options: redirectOptions } : null;
267
+ } catch (error) {
268
+ slice.logger.logError('Router', 'Error in beforeEach guard', error);
269
+ return null; // En caso de error, continuar con la navegación
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Ejecuta el afterEach guard si existe
275
+ * @param {Object} to - Información de ruta destino
276
+ * @param {Object} from - Información de ruta origen
277
+ */
278
+ /**
279
+ * Execute afterEach guard if defined.
280
+ * @param {RouteInfo} to
281
+ * @param {RouteInfo} from
282
+ * @returns {void}
283
+ */
284
+ _executeAfterEachGuard(to, from) {
285
+ if (!this._afterEachGuard) {
286
+ return;
287
+ }
288
+
289
+ try {
290
+ this._afterEachGuard(to, from);
291
+ } catch (error) {
292
+ slice.logger.logError('Router', 'Error in afterEach guard', error);
293
+ }
294
+ }
295
+
296
+ // ============================================
297
+ // ROUTING CORE (MODIFICADO CON GUARDS)
298
+ // ============================================
299
+
300
+ /**
301
+ * Navigate to a route path with guards support. Add replace to do router.replace() instead of push.
302
+ * @param {string} path
303
+ * @param {string[]} [_redirectChain]
304
+ * @param {{ replace?: boolean }} [_options]
305
+ * @returns {Promise<void>}
306
+ */
307
+ async navigate(path, _redirectChain = [], _options = {}) {
308
+ const currentPath = window.location.pathname;
309
+
310
+ // Detectar loops infinitos: si ya visitamos esta ruta en la cadena de redirecciones
311
+ if (_redirectChain.includes(path)) {
312
+ slice.logger.logError('Router', `Guard redirection loop detected: ${_redirectChain.join(' → ')} → ${path}`);
313
+ return;
314
+ }
315
+
316
+ // Límite de seguridad: máximo 10 redirecciones
317
+ if (_redirectChain.length >= 10) {
318
+ slice.logger.logError('Router', `Too many redirections: ${_redirectChain.join(' → ')} → ${path}`);
319
+ return;
320
+ }
321
+
322
+ // Obtener información de ruta actual
323
+ const { route: fromRoute, params: fromParams } = this.matchRoute(currentPath);
324
+ const from = this._createRouteInfo(fromRoute, fromParams, currentPath);
325
+
326
+ // Obtener información de ruta destino
327
+ const { route: toRoute, params: toParams } = this.matchRoute(path);
328
+ const to = this._createRouteInfo(toRoute, toParams, path);
329
+
330
+ // EJECUTAR BEFORE EACH GUARD
331
+ const guardResult = await this._executeBeforeEachGuard(to, from);
332
+
333
+ // Si el guard redirige
334
+ if (guardResult && guardResult.path) {
335
+ const newChain = [..._redirectChain, path];
336
+ return this.navigate(guardResult.path, newChain, guardResult.options);
337
+ }
338
+
339
+ // Si el guard cancela la navegación (next(false))
340
+ if (guardResult && guardResult.path === false) {
341
+ slice.logger.logInfo('Router', 'Navigation cancelled by guard');
342
+ return;
343
+ }
344
+
345
+ // No hay redirección - continuar con la navegación normal
346
+ // Usar replace o push según las opciones
347
+ if (_options.replace) {
348
+ window.history.replaceState({}, path, window.location.origin + path);
349
+ } else {
350
+ window.history.pushState({}, path, window.location.origin + path);
351
+ }
352
+
353
+ await this._performNavigation(to, from);
354
+ }
355
+
356
+ /**
357
+ * Método interno para ejecutar la navegación después de pasar los guards
358
+ * @param {Object} to - Información de ruta destino
359
+ * @param {Object} from - Información de ruta origen
360
+ */
361
+ /**
362
+ * Perform navigation after guards.
363
+ * @param {RouteInfo} to
364
+ * @param {RouteInfo} from
365
+ * @returns {Promise<void>}
366
+ */
367
+ async _performNavigation(to, from) {
368
+ // Renderizar la nueva ruta
369
+ await this.onRouteChange();
370
+
371
+ // EJECUTAR AFTER EACH GUARD
372
+ this._executeAfterEachGuard(to, from);
373
+
374
+ // Emitir evento de cambio de ruta
375
+ this._emitRouteChange(to, from);
376
+ }
377
+
378
+ /**
379
+ * React to URL changes and render routes.
380
+ * @returns {Promise<void>}
381
+ */
382
+ async onRouteChange() {
383
+ // Cancelar el timeout anterior si existe
384
+ if (this.routeChangeTimeout) {
385
+ clearTimeout(this.routeChangeTimeout);
386
+ }
387
+
388
+ // Debounce de 10ms para evitar múltiples llamadas seguidas
389
+ this.routeChangeTimeout = setTimeout(async () => {
390
+ const path = window.location.pathname;
391
+ const routeContainersFlag = await this.renderRoutesComponentsInPage();
392
+
393
+ if (routeContainersFlag) {
394
+ return;
395
+ }
396
+
397
+ const { route, params } = this.matchRoute(path);
398
+ if (route) {
399
+ await this.handleRoute(route, params);
400
+ }
401
+ }, 10);
402
+ }
403
+
404
+ /**
405
+ * Build or update the active route component.
406
+ * @param {RouteConfig} route
407
+ * @param {Object} params
408
+ * @returns {Promise<void>}
409
+ */
410
+ async handleRoute(route, params) {
411
+ const targetElement = document.querySelector('#app');
412
+
413
+ const componentName = route.parentRoute ? route.parentRoute.component : route.component;
414
+ const sliceId = `route-${componentName}`;
415
+
416
+ const existingComponent = slice.controller.getComponent(sliceId);
417
+
418
+ if (slice.loading) {
419
+ slice.loading.start();
420
+ }
421
+
422
+ if (existingComponent) {
423
+ targetElement.innerHTML = '';
424
+ if (existingComponent.update) {
425
+ existingComponent.props = { ...existingComponent.props, ...params };
426
+ await existingComponent.update();
427
+ }
428
+ targetElement.appendChild(existingComponent);
429
+ await this.renderRoutesInComponent(existingComponent);
430
+ } else {
431
+ const component = await slice.build(componentName, {
432
+ params,
433
+ sliceId: sliceId,
434
+ });
435
+
436
+ targetElement.innerHTML = '';
437
+ targetElement.appendChild(component);
438
+
439
+ await this.renderRoutesInComponent(component);
440
+ }
441
+
442
+ // Invalidar caché después de cambios importantes en el DOM
443
+ this.invalidateCache();
444
+
445
+ if (slice.loading) {
446
+ slice.loading.stop();
447
+ }
448
+
449
+ slice.router.activeRoute = route;
450
+ }
451
+
452
+ /**
453
+ * Load initial route and run guards.
454
+ * @returns {Promise<void>}
455
+ */
456
+ async loadInitialRoute() {
457
+ const path = window.location.pathname;
458
+ const { route, params } = this.matchRoute(path);
459
+
460
+ // Para la carga inicial, también ejecutar guards
461
+ const from = this._createRouteInfo(null, {}, null);
462
+ const to = this._createRouteInfo(route, params, path);
463
+
464
+ // EJECUTAR BEFORE EACH GUARD en carga inicial
465
+ const guardResult = await this._executeBeforeEachGuard(to, from);
466
+
467
+ if (guardResult && guardResult.path) {
468
+ return this.navigate(guardResult.path, [], guardResult.options);
469
+ }
470
+
471
+ // Si el guard cancela la navegación inicial (caso raro pero posible)
472
+ if (guardResult && guardResult.path === false) {
473
+ slice.logger.logWarning('Router', 'Initial route navigation cancelled by guard');
474
+ return;
475
+ }
476
+
477
+ await this.handleRoute(route, params);
478
+
479
+ // EJECUTAR AFTER EACH GUARD en carga inicial
480
+ this._executeAfterEachGuard(to, from);
481
+
482
+ // Emitir evento de cambio de ruta
483
+ this._emitRouteChange(to, from);
484
+ }
485
+
486
+ /**
487
+ * Emitir evento de cambio de ruta
488
+ * @param {Object} to
489
+ * @param {Object} from
490
+ */
491
+ /**
492
+ * Emit route change event.
493
+ * @param {RouteInfo} to
494
+ * @param {RouteInfo} from
495
+ * @returns {void}
496
+ */
497
+ _emitRouteChange(to, from) {
498
+ const payload = { to, from };
499
+
500
+ if (slice.eventsConfig?.enabled && slice.events && typeof slice.events.emit === 'function') {
501
+ slice.events.emit('router:change', payload);
502
+ return;
503
+ }
504
+
505
+ window.dispatchEvent(new CustomEvent('router:change', { detail: payload }));
506
+ }
507
+
508
+ // ============================================
509
+ // MÉTODOS EXISTENTES (SIN CAMBIOS)
510
+ // ============================================
511
+
512
+ setupMutationObserver() {
513
+ if (typeof MutationObserver !== 'undefined') {
514
+ this.observer = new MutationObserver((mutations) => {
515
+ let shouldInvalidateCache = false;
516
+
517
+ mutations.forEach((mutation) => {
518
+ if (mutation.type === 'childList') {
519
+ const addedNodes = Array.from(mutation.addedNodes);
520
+ const removedNodes = Array.from(mutation.removedNodes);
521
+
522
+ const hasRouteNodes = [...addedNodes, ...removedNodes].some(
523
+ (node) =>
524
+ node.nodeType === Node.ELEMENT_NODE &&
525
+ (node.tagName === 'SLICE-ROUTE' ||
526
+ node.tagName === 'SLICE-MULTI-ROUTE' ||
527
+ node.querySelector?.('slice-route, slice-multi-route'))
528
+ );
529
+
530
+ if (hasRouteNodes) {
531
+ shouldInvalidateCache = true;
532
+ }
533
+ }
534
+ });
535
+
536
+ if (shouldInvalidateCache) {
537
+ this.invalidateCache();
538
+ }
539
+ });
540
+
541
+ this.observer.observe(document.body, {
542
+ childList: true,
543
+ subtree: true,
544
+ });
545
+ }
546
+ }
547
+
548
+ invalidateCache() {
549
+ this.routeContainersCache.clear();
550
+ this.lastCacheUpdate = 0;
551
+ }
552
+
553
+ createPathToRouteMap(routes, basePath = '', parentRoute = null) {
554
+ const pathToRouteMap = new Map();
555
+
556
+ for (const route of routes) {
557
+ const fullPath = `${basePath}${route.path}`.replace(/\/+/g, '/');
558
+
559
+ const routeWithParent = {
560
+ ...route,
561
+ fullPath,
562
+ parentPath: parentRoute ? parentRoute.fullPath : null,
563
+ parentRoute: parentRoute,
564
+ };
565
+
566
+ pathToRouteMap.set(fullPath, routeWithParent);
567
+
568
+ if (route.children) {
569
+ const childPathToRouteMap = this.createPathToRouteMap(route.children, fullPath, routeWithParent);
570
+
571
+ for (const [childPath, childRoute] of childPathToRouteMap.entries()) {
572
+ pathToRouteMap.set(childPath, childRoute);
573
+ }
574
+ }
575
+ }
576
+
577
+ return pathToRouteMap;
578
+ }
579
+
580
+ /**
581
+ * Render any Route/MultiRoute components in a container.
582
+ * @param {Document|HTMLElement} [searchContainer]
583
+ * @returns {Promise<boolean>}
584
+ */
585
+ async renderRoutesComponentsInPage(searchContainer = document) {
586
+ let routerContainersFlag = false;
587
+ const routeContainers = this.getCachedRouteContainers(searchContainer);
588
+
589
+ for (const routeContainer of routeContainers) {
590
+ try {
591
+ if (!routeContainer.isConnected) {
592
+ this.invalidateCache();
593
+ continue;
594
+ }
595
+
596
+ let response = await routeContainer.renderIfCurrentRoute();
597
+ if (response) {
598
+ this.activeRoute = routeContainer.props;
599
+ routerContainersFlag = true;
600
+ }
601
+ } catch (error) {
602
+ slice.logger.logError('Router', `Error rendering route container`, error);
603
+ }
604
+ }
605
+
606
+ return routerContainersFlag;
607
+ }
608
+
609
+ getCachedRouteContainers(container) {
610
+ const containerKey = container === document ? 'document' : container.sliceId || 'anonymous';
611
+ const now = Date.now();
612
+
613
+ if (this.routeContainersCache.has(containerKey) && now - this.lastCacheUpdate < this.CACHE_DURATION) {
614
+ return this.routeContainersCache.get(containerKey);
615
+ }
616
+
617
+ const routeContainers = this.findAllRouteContainersOptimized(container);
618
+ this.routeContainersCache.set(containerKey, routeContainers);
619
+ this.lastCacheUpdate = now;
620
+
621
+ return routeContainers;
622
+ }
623
+
624
+ findAllRouteContainersOptimized(container) {
625
+ const routeContainers = [];
626
+
627
+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
628
+ acceptNode: (node) => {
629
+ if (node.tagName === 'SLICE-ROUTE' || node.tagName === 'SLICE-MULTI-ROUTE') {
630
+ return NodeFilter.FILTER_ACCEPT;
631
+ }
632
+ return NodeFilter.FILTER_SKIP;
633
+ },
634
+ });
635
+
636
+ let node;
637
+ while ((node = walker.nextNode())) {
638
+ routeContainers.push(node);
639
+ }
640
+
641
+ return routeContainers;
642
+ }
643
+
644
+ /**
645
+ * Render route containers inside a component.
646
+ * @param {HTMLElement} component
647
+ * @returns {Promise<boolean>}
648
+ */
649
+ async renderRoutesInComponent(component) {
650
+ if (!component) {
651
+ slice.logger.logWarning('Router', 'No component provided for route rendering');
652
+ return false;
653
+ }
654
+
655
+ return await this.renderRoutesComponentsInPage(component);
656
+ }
657
+
658
+ /**
659
+ * Match a path to a configured route.
660
+ * @param {string} path
661
+ * @returns {RouteMatch}
662
+ */
663
+ matchRoute(path) {
664
+ const exactMatch = this.pathToRouteMap.get(path);
665
+ if (exactMatch) {
666
+ if (exactMatch.parentRoute) {
667
+ return {
668
+ route: exactMatch.parentRoute,
669
+ params: {},
670
+ childRoute: exactMatch,
671
+ };
672
+ }
673
+ return { route: exactMatch, params: {} };
674
+ }
675
+
676
+ for (const [routePattern, route] of this.pathToRouteMap.entries()) {
677
+ if (routePattern.includes('${')) {
678
+ const { regex, paramNames } = this.compilePathPattern(routePattern);
679
+ const match = path.match(regex);
680
+ if (match) {
681
+ const params = {};
682
+ paramNames.forEach((name, i) => {
683
+ params[name] = match[i + 1];
684
+ });
685
+
686
+ if (route.parentRoute) {
687
+ return {
688
+ route: route.parentRoute,
689
+ params: params,
690
+ childRoute: route,
691
+ };
692
+ }
693
+
694
+ return { route, params };
695
+ }
696
+ }
697
+ }
698
+
699
+ const notFoundRoute = this.pathToRouteMap.get('/404');
700
+ return { route: notFoundRoute, params: {} };
701
+ }
702
+
703
+ /**
704
+ * Compile a path pattern with ${param} segments.
705
+ * @param {string} pattern
706
+ * @returns {{ regex: RegExp, paramNames: string[] }}
707
+ */
708
+ compilePathPattern(pattern) {
709
+ const paramNames = [];
710
+ const regexPattern =
711
+ '^' +
712
+ pattern.replace(/\$\{([^}]+)\}/g, (_, paramName) => {
713
+ paramNames.push(paramName);
714
+ return '([^/]+)';
715
+ }) +
716
+ '$';
717
+
718
+ return { regex: new RegExp(regexPattern), paramNames };
719
+ }
720
+ }