eleva 1.1.0 → 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.
Files changed (56) hide show
  1. package/README.md +2 -2
  2. package/dist/eleva-plugins.cjs +25 -21
  3. package/dist/eleva-plugins.cjs.map +1 -1
  4. package/dist/eleva-plugins.js +25 -21
  5. package/dist/eleva-plugins.js.map +1 -1
  6. package/dist/eleva-plugins.umd.js +25 -21
  7. package/dist/eleva-plugins.umd.js.map +1 -1
  8. package/dist/eleva-plugins.umd.min.js +1 -1
  9. package/dist/eleva-plugins.umd.min.js.map +1 -1
  10. package/dist/eleva.cjs +9 -13
  11. package/dist/eleva.cjs.map +1 -1
  12. package/dist/eleva.d.cts +4 -15
  13. package/dist/eleva.d.cts.map +1 -1
  14. package/dist/eleva.d.ts +4 -15
  15. package/dist/eleva.d.ts.map +1 -1
  16. package/dist/eleva.js +9 -13
  17. package/dist/eleva.js.map +1 -1
  18. package/dist/eleva.umd.js +9 -13
  19. package/dist/eleva.umd.js.map +1 -1
  20. package/dist/eleva.umd.min.js +1 -1
  21. package/dist/eleva.umd.min.js.map +1 -1
  22. package/dist/plugins/attr.cjs +2 -2
  23. package/dist/plugins/attr.cjs.map +1 -1
  24. package/dist/plugins/attr.js +2 -2
  25. package/dist/plugins/attr.js.map +1 -1
  26. package/dist/plugins/attr.umd.js +2 -2
  27. package/dist/plugins/attr.umd.js.map +1 -1
  28. package/dist/plugins/attr.umd.min.js +1 -1
  29. package/dist/plugins/attr.umd.min.js.map +1 -1
  30. package/dist/plugins/router.cjs +23 -19
  31. package/dist/plugins/router.cjs.map +1 -1
  32. package/dist/plugins/router.js +23 -19
  33. package/dist/plugins/router.js.map +1 -1
  34. package/dist/plugins/router.umd.js +23 -19
  35. package/dist/plugins/router.umd.js.map +1 -1
  36. package/dist/plugins/router.umd.min.js +1 -1
  37. package/dist/plugins/router.umd.min.js.map +1 -1
  38. package/dist/plugins/store.cjs +2 -2
  39. package/dist/plugins/store.cjs.map +1 -1
  40. package/dist/plugins/store.js +2 -2
  41. package/dist/plugins/store.js.map +1 -1
  42. package/dist/plugins/store.umd.js +2 -2
  43. package/dist/plugins/store.umd.js.map +1 -1
  44. package/dist/plugins/store.umd.min.js +1 -1
  45. package/dist/plugins/store.umd.min.js.map +1 -1
  46. package/package.json +5 -5
  47. package/src/core/Eleva.js +4 -11
  48. package/src/modules/TemplateEngine.js +3 -3
  49. package/src/plugins/Attr.js +1 -1
  50. package/src/plugins/Router.js +24 -21
  51. package/src/plugins/Store.js +1 -1
  52. package/types/core/Eleva.d.ts +2 -13
  53. package/types/core/Eleva.d.ts.map +1 -1
  54. package/types/modules/TemplateEngine.d.ts +1 -1
  55. package/types/modules/TemplateEngine.d.ts.map +1 -1
  56. package/types/plugins/Router.d.ts.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"eleva-plugins.js","sources":["../src/plugins/Attr.js","../src/plugins/Router.js","../src/plugins/Store.js"],"sourcesContent":["\"use strict\";\n\n/**\n * @module eleva/plugins/attr\n * @fileoverview Attribute plugin providing ARIA, data, boolean, and dynamic attribute handling.\n */\n\n// ============================================================================\n// TYPE DEFINITIONS\n// ============================================================================\n\n// -----------------------------------------------------------------------------\n// External Type Imports\n// -----------------------------------------------------------------------------\n\n/**\n * Type imports from the Eleva core library.\n * @typedef {import('eleva').Eleva} Eleva\n */\n\n// -----------------------------------------------------------------------------\n// Attr Type Definitions\n// -----------------------------------------------------------------------------\n\n/**\n * Configuration options for the AttrPlugin.\n * @typedef {Object} AttrPluginOptions\n * @property {boolean} [enableAria=true]\n * Enable ARIA attribute handling.\n * @property {boolean} [enableData=true]\n * Enable data attribute handling.\n * @property {boolean} [enableBoolean=true]\n * Enable boolean attribute handling.\n * @property {boolean} [enableDynamic=true]\n * Enable dynamic property detection.\n * @description Configuration options passed to AttrPlugin.install().\n */\n\n/**\n * Function signature for attribute update operations.\n * @typedef {(oldEl: HTMLElement, newEl: HTMLElement) => void} AttributeUpdateFunction\n * @description Updates attributes on oldEl to match newEl's attributes.\n */\n\n/**\n * A regular expression to match hyphenated lowercase letters.\n * @private\n * @type {RegExp}\n */\nconst CAMEL_RE = /-([a-z])/g;\n\n/**\n * @class 🎯 AttrPlugin\n * @classdesc A plugin that provides advanced attribute handling for Eleva components.\n * This plugin extends the renderer with sophisticated attribute processing including:\n * - ARIA attribute handling with proper property mapping\n * - Data attribute management\n * - Boolean attribute processing\n * - Dynamic property detection and mapping\n * - Attribute cleanup and removal\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n * app.use(AttrPlugin);\n *\n * // Use advanced attributes in components\n * app.component(\"myComponent\", {\n * template: (ctx) => `\n * <button\n * aria-expanded=\"${ctx.isExpanded.value}\"\n * data-user-id=\"${ctx.userId.value}\"\n * disabled=\"${ctx.isLoading.value}\"\n * class=\"btn ${ctx.variant.value}\"\n * >\n * ${ctx.text.value}\n * </button>\n * `\n * });\n */\nexport const AttrPlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"attr\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.1.0\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description: \"Advanced attribute handling for Eleva components\",\n\n /**\n * Installs the plugin into the Eleva instance.\n *\n * @public\n * Method wrapping behavior:\n * - Stores original `_patchNode` in `renderer._originalPatchNode`\n * - Overrides `renderer._patchNode` to use enhanced attribute handling\n * - Adds `renderer.updateAttributes` and `eleva.updateElementAttributes` helpers\n * - Call `uninstall()` to restore original behavior\n *\n * @param {Eleva} eleva - The Eleva instance to enhance.\n * @param {AttrPluginOptions} options - Plugin configuration options.\n * @param {boolean} [options.enableAria=true] - Enable ARIA attribute handling.\n * Maps aria-* attributes to DOM properties (e.g., aria-expanded → ariaExpanded).\n * @param {boolean} [options.enableData=true] - Enable data attribute handling.\n * Syncs data-* attributes with element.dataset for consistent access.\n * @param {boolean} [options.enableBoolean=true] - Enable boolean attribute handling.\n * Treats empty strings and attribute names as true, \"false\" string as false.\n * @param {boolean} [options.enableDynamic=true] - Enable dynamic property detection.\n * Searches element prototype chain for property matches (useful for custom elements).\n * @returns {void}\n * @example\n * // Basic installation with defaults\n * app.use(AttrPlugin);\n *\n * @example\n * // Custom configuration\n * app.use(AttrPlugin, {\n * enableAria: true,\n * enableData: true,\n * enableBoolean: true,\n * enableDynamic: false // Disable for performance\n * });\n *\n * @example\n * // Using ARIA attributes in templates\n * template: (ctx) => `\n * <div role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"title\">\n * <h2 id=\"title\">Modal Title</h2>\n * <button aria-expanded=\"${ctx.isOpen.value}\">Toggle</button>\n * </div>\n * `\n * @see uninstall - Remove the plugin and restore original behavior.\n */\n install(eleva, options = {}) {\n const {\n enableAria = true,\n enableData = true,\n enableBoolean = true,\n enableDynamic = true,\n } = options;\n\n /**\n * Updates the attributes of an element to match a new element's attributes.\n *\n * Processing order:\n * 1. Skip event attributes (@click, @input) - handled by Eleva's event system\n * 2. Skip unchanged attributes - optimization\n * 3. ARIA attributes (aria-*): Map to DOM properties (aria-expanded → ariaExpanded)\n * 4. Data attributes (data-*): Update both dataset and attribute\n * 5. Boolean attributes: Handle empty string as true, \"false\" as false\n * 6. Other attributes: Map to properties with dynamic detection for custom elements\n * 7. Remove old attributes not present in new element\n *\n * Dynamic property detection (when enableDynamic=true):\n * - Checks if property exists directly on element\n * - Searches element's prototype chain for case-insensitive matches\n * - Enables compatibility with custom elements and Web Components\n *\n * @inner\n * @param {HTMLElement} oldEl - The original element to update (modified in-place).\n * @param {HTMLElement} newEl - The reference element with desired attributes.\n * @returns {void}\n */\n const updateAttributes = (oldEl, newEl) => {\n const oldAttrs = oldEl.attributes;\n const newAttrs = newEl.attributes;\n\n // Process new attributes\n for (let i = 0; i < newAttrs.length; i++) {\n const { name, value } = newAttrs[i];\n\n // Skip event attributes (handled by event system)\n if (name.startsWith(\"@\")) continue;\n\n // Skip if attribute hasn't changed\n if (oldEl.getAttribute(name) === value) continue;\n\n // Handle ARIA attributes\n if (enableAria && name.startsWith(\"aria-\")) {\n const prop =\n \"aria\" + name.slice(5).replace(CAMEL_RE, (_, l) => l.toUpperCase());\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n // Handle data attributes\n else if (enableData && name.startsWith(\"data-\")) {\n oldEl.dataset[name.slice(5)] = value;\n oldEl.setAttribute(name, value);\n }\n // Handle other attributes\n else {\n let prop = name.replace(CAMEL_RE, (_, l) => l.toUpperCase());\n\n // Dynamic property detection\n if (\n enableDynamic &&\n !(prop in oldEl) &&\n !Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop)\n ) {\n const elementProps = Object.getOwnPropertyNames(\n Object.getPrototypeOf(oldEl)\n );\n const matchingProp = elementProps.find(\n (p) =>\n p.toLowerCase() === name.toLowerCase() ||\n p.toLowerCase().includes(name.toLowerCase()) ||\n name.toLowerCase().includes(p.toLowerCase())\n );\n\n if (matchingProp) {\n prop = matchingProp;\n }\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(oldEl),\n prop\n );\n const hasProperty = prop in oldEl || descriptor;\n\n if (hasProperty) {\n // Boolean attribute handling\n if (enableBoolean) {\n const isBoolean =\n typeof oldEl[prop] === \"boolean\" ||\n (descriptor?.get &&\n typeof descriptor.get.call(oldEl) === \"boolean\");\n\n if (isBoolean) {\n const boolValue =\n value !== \"false\" &&\n (value === \"\" || value === prop || value === \"true\");\n oldEl[prop] = boolValue;\n\n if (boolValue) {\n oldEl.setAttribute(name, \"\");\n } else {\n oldEl.removeAttribute(name);\n }\n } else {\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n } else {\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n } else {\n oldEl.setAttribute(name, value);\n }\n }\n }\n\n // Remove old attributes that are no longer present\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const name = oldAttrs[i].name;\n if (!newEl.hasAttribute(name)) {\n oldEl.removeAttribute(name);\n }\n }\n };\n\n // Extend the renderer with the advanced attribute handler\n if (eleva.renderer) {\n eleva.renderer.updateAttributes = updateAttributes;\n\n // Store the original _patchNode method\n const originalPatchNode = eleva.renderer._patchNode;\n eleva.renderer._originalPatchNode = originalPatchNode;\n\n /**\n * Overridden _patchNode method that uses enhanced attribute handling.\n * Delegates to `updateAttributes` instead of the basic `_updateAttributes`.\n *\n * @param {Node} oldNode - The original DOM node to update.\n * @param {Node} newNode - The new DOM node with desired state.\n * @returns {void}\n */\n eleva.renderer._patchNode = function (oldNode, newNode) {\n if (oldNode?._eleva_instance) return;\n\n if (oldNode.nodeType === Node.TEXT_NODE) {\n if (oldNode.nodeValue !== newNode.nodeValue) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n } else if (oldNode.nodeType === Node.ELEMENT_NODE) {\n // Use advanced attribute handler instead of basic _updateAttributes\n updateAttributes(oldNode, newNode);\n this._diff(oldNode, newNode);\n }\n };\n }\n\n // Add plugin metadata to the Eleva instance\n if (!eleva.plugins) {\n eleva.plugins = new Map();\n }\n eleva.plugins.set(this.name, {\n name: this.name,\n version: this.version,\n description: this.description,\n options,\n });\n\n // Add utility methods for manual attribute updates\n /** @type {AttributeUpdateFunction} */\n eleva.updateElementAttributes = updateAttributes;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance.\n *\n * @public\n * @param {Eleva} eleva - The Eleva instance.\n * @returns {void}\n * @description\n * Restores the original renderer patching behavior and removes\n * `eleva.updateElementAttributes`.\n * @example\n * // Uninstall the plugin\n * AttrPlugin.uninstall(app);\n * @see install - Install the plugin.\n */\n uninstall(eleva) {\n // Restore original _patchNode method if it exists\n if (eleva.renderer && eleva.renderer._originalPatchNode) {\n eleva.renderer._patchNode = eleva.renderer._originalPatchNode;\n delete eleva.renderer._originalPatchNode;\n }\n\n // Remove plugin metadata\n if (eleva.plugins) {\n eleva.plugins.delete(this.name);\n }\n\n // Remove utility methods\n delete eleva.updateElementAttributes;\n },\n};\n\n// Short name export for convenience\nexport { AttrPlugin as Attr };\n","\"use strict\";\n\n/**\n * @module eleva/plugins/router\n * @fileoverview Client-side router plugin with hash, history, and query modes,\n * navigation guards, and lifecycle hooks.\n */\n\n// ============================================================================\n// TYPE DEFINITIONS\n// ============================================================================\n\n// -----------------------------------------------------------------------------\n// External Type Imports\n// -----------------------------------------------------------------------------\n\n/**\n * Type imports from the Eleva core library.\n * @typedef {import('eleva').Eleva} Eleva\n * @typedef {import('eleva').ComponentDefinition} ComponentDefinition\n * @typedef {import('eleva').Emitter} Emitter\n * @typedef {import('eleva').MountResult} MountResult\n * @typedef {import('eleva').UnsubscribeFunction} UnsubscribeFunction\n */\n\n/**\n * Generic type import.\n * @template T\n * @typedef {import('eleva').Signal<T>} Signal\n */\n\n// -----------------------------------------------------------------------------\n// Router Events\n// -----------------------------------------------------------------------------\n\n/**\n * Fired when the router initialization completes successfully.\n * @event router:ready\n * @type {Router}\n */\n\n/**\n * Fired when an error occurs during navigation or route handling.\n * @event router:error\n * @type {Error}\n */\n\n/**\n * Fired when no matching route is found for the requested path.\n * @event router:notFound\n * @type {{to: RouteLocation, from: RouteLocation | null, path: string}}\n */\n\n/**\n * Fired before guards run, allowing plugins to block or redirect navigation.\n * @event router:beforeEach\n * @type {NavigationContext}\n */\n\n/**\n * Fired before component resolution, allowing plugins to modify the resolve context.\n * @event router:beforeResolve\n * @type {ResolveContext}\n */\n\n/**\n * Fired after components are resolved successfully.\n * @event router:afterResolve\n * @type {ResolveContext}\n */\n\n/**\n * Fired after leaving the previous route.\n * @event router:afterLeave\n * @type {{to: RouteLocation, from: RouteLocation}}\n */\n\n/**\n * Fired before DOM rendering begins.\n * @event router:beforeRender\n * @type {RenderContext}\n */\n\n/**\n * Fired after DOM rendering completes.\n * @event router:afterRender\n * @type {RenderContext}\n */\n\n/**\n * Fired after render for scroll behavior handling.\n * @event router:scroll\n * @type {ScrollContext}\n */\n\n/**\n * Fired after entering the new route.\n * @event router:afterEnter\n * @type {{to: RouteLocation, from: RouteLocation | null}}\n */\n\n/**\n * Fired after navigation completes successfully.\n * @event router:afterEach\n * @type {{to: RouteLocation, from: RouteLocation | null}}\n */\n\n/**\n * Fired when a route is dynamically added.\n * @event router:routeAdded\n * @type {RouteDefinition}\n */\n\n/**\n * Fired when a route is dynamically removed.\n * @event router:routeRemoved\n * @type {RouteDefinition}\n */\n\n// -----------------------------------------------------------------------------\n// Router Data Types\n// -----------------------------------------------------------------------------\n\n/**\n * The routing mode determines how the router manages URL state.\n * - `hash`: Uses URL hash (e.g., `/#/path`) - works without server config\n * - `history`: Uses HTML5 History API (e.g., `/path`) - requires server config\n * - `query`: Uses query parameters (e.g., `?view=/path`) - useful for embedded apps\n * @typedef {'hash' | 'history' | 'query'} RouterMode\n */\n\n/**\n * Route parameters extracted from the URL path.\n * @typedef {Record<string, string>} RouteParams\n * @description Key-value pairs extracted from dynamic route segments (e.g., `/users/:id` → `{ id: '123' }`).\n */\n\n/**\n * Query parameters from the URL query string.\n * @typedef {Record<string, string>} QueryParams\n * @description Key-value pairs from the URL query string (e.g., `?page=1&sort=name`).\n */\n\n/**\n * Navigation input parameters supporting multiple value types.\n * @typedef {Record<string, string | number | boolean>} NavigationParams\n * @description Parameters passed to navigation functions, automatically converted to strings in URLs.\n */\n\n/**\n * Function signature for programmatic navigation.\n * @typedef {(location: string | NavigationTarget, params?: NavigationParams) => Promise<boolean>} NavigateFunction\n * @description Returns true if navigation succeeded, false if blocked by a guard.\n */\n\n/**\n * Router configuration options.\n * @typedef {Object} RouterOptions\n * @property {RouterMode} [mode='hash']\n * The routing mode to use.\n * @property {string} [queryParam='view']\n * Query parameter name for 'query' mode.\n * @property {string} [viewSelector='view']\n * Base selector for the view element.\n * @property {string} mount\n * CSS selector for the mount point element.\n * @property {RouteDefinition[]} routes\n * Array of route definitions.\n * @property {RouteComponent} [globalLayout]\n * Default layout for all routes.\n * @property {NavigationGuard} [onBeforeEach]\n * Global navigation guard.\n * @property {boolean} [autoStart=true]\n * Whether to start the router automatically.\n * @description Configuration options for the Router plugin.\n */\n\n/**\n * Object describing a navigation target for `router.navigate()`.\n * @typedef {Object} NavigationTarget\n * @property {string} path\n * The target path (can include params like '/users/:id').\n * @property {NavigationParams} [params]\n * Route parameters to inject.\n * @property {NavigationParams} [query]\n * Query parameters to append.\n * @property {boolean} [replace=false]\n * Whether to replace current history entry.\n * @property {unknown} [state]\n * History state to pass.\n * @description Object describing a navigation target for `router.navigate()`.\n */\n\n/**\n * Saved scroll position.\n * @typedef {Object} ScrollPosition\n * @property {number} x\n * Horizontal scroll position.\n * @property {number} y\n * Vertical scroll position.\n * @description Represents a saved scroll position.\n */\n\n/**\n * Internal representation of a parsed route path segment.\n * @typedef {Object} RouteSegment\n * @property {'static' | 'param'} type\n * The segment type.\n * @property {string} [value]\n * The segment value (static segments).\n * @property {string} [name]\n * The parameter name (param segments).\n * @description Internal representation of a parsed route path segment.\n * @private\n */\n\n/**\n * Result of matching a path against route definitions.\n * @typedef {Object} RouteMatch\n * @property {RouteDefinition} route\n * The matched route definition.\n * @property {RouteParams} params\n * The extracted route parameters.\n * @description Result of matching a path against route definitions.\n * @private\n */\n\n/**\n * Arbitrary metadata attached to routes for use in guards and components.\n * @typedef {Record<string, unknown>} RouteMeta\n * @description Common properties include:\n * - `requiresAuth: boolean` - Whether the route requires authentication\n * - `title: string` - Page title for the route\n * - `roles: string[]` - Required user roles\n * @example\n * {\n * path: '/admin',\n * component: AdminPage,\n * meta: { requiresAuth: true, roles: ['admin'], title: 'Admin Dashboard' }\n * }\n */\n\n/**\n * Interface for the router's error handling system.\n * @typedef {Object} RouterErrorHandler\n * @property {(error: Error, context: string, details?: Record<string, unknown>) => void} handle\n * Throws a formatted error.\n * @property {(message: string, details?: Record<string, unknown>) => void} warn\n * Logs a warning.\n * @property {(message: string, error: Error, details?: Record<string, unknown>) => void} log\n * Logs an error without throwing.\n * @description Interface for the router's error handling system.\n */\n\n// -----------------------------------------------------------------------------\n// Event Callback Types\n// -----------------------------------------------------------------------------\n\n/**\n * Callback for `router:beforeEach` event.\n * @callback NavigationContextCallback\n * @param {NavigationContext} context\n * The navigation context (can be modified to block/redirect).\n * @returns {void | Promise<void>}\n * @description Modify context to control navigation flow.\n */\n\n/**\n * Callback for `router:beforeResolve` and `router:afterResolve` events.\n * @callback ResolveContextCallback\n * @param {ResolveContext} context\n * The resolve context (can be modified to block/redirect).\n * @returns {void | Promise<void>}\n * @description Callback for `router:beforeResolve` and `router:afterResolve` events.\n */\n\n/**\n * Callback for `router:beforeRender` and `router:afterRender` events.\n * @callback RenderContextCallback\n * @param {RenderContext} context\n * The render context.\n * @returns {void | Promise<void>}\n * @description Callback for `router:beforeRender` and `router:afterRender` events.\n */\n\n/**\n * Callback for `router:scroll` event.\n * @callback ScrollContextCallback\n * @param {ScrollContext} context\n * The scroll context with saved position info.\n * @returns {void | Promise<void>}\n * @description Use to implement custom scroll behavior.\n */\n\n/**\n * Callback for `router:afterEnter`, `router:afterLeave`, `router:afterEach` events.\n * @callback RouteChangeCallback\n * @param {RouteLocation} to\n * The target route location.\n * @param {RouteLocation | null} from\n * The source route location.\n * @returns {void | Promise<void>}\n * @description Callback for `router:afterEnter`, `router:afterLeave`, `router:afterEach` events.\n */\n\n/**\n * Router context injected into component setup as `ctx.router`.\n * @typedef {Object} RouterContext\n * @property {NavigateFunction} navigate\n * Programmatic navigation function.\n * @property {Signal<RouteLocation | null>} current\n * Reactive signal for current route.\n * @property {Signal<RouteLocation | null>} previous\n * Reactive signal for previous route.\n * @property {RouteParams} params\n * Current route params (getter).\n * @property {QueryParams} query\n * Current route query (getter).\n * @property {string} path\n * Current route path (getter).\n * @property {string} fullUrl\n * Current routed URL string (getter).\n * @property {RouteMeta} meta\n * Current route meta (getter).\n * @description Injected into component setup as `ctx.router`.\n */\n\n/**\n * Callback for `router:error` event.\n * @callback RouterErrorCallback\n * @param {Error} error\n * The error that occurred.\n * @param {RouteLocation} [to]\n * The target route (if available).\n * @param {RouteLocation | null} [from]\n * The source route (if available).\n * @returns {void | Promise<void>}\n * @description Callback for `router:error` event.\n */\n\n/**\n * Callback for `router:ready` event.\n * @callback RouterReadyCallback\n * @param {Router} router\n * The router instance.\n * @returns {void | Promise<void>}\n * @description Callback for `router:ready` event.\n */\n\n/**\n * Callback for `router:routeAdded` event.\n * @callback RouteAddedCallback\n * @param {RouteDefinition} route\n * The added route definition.\n * @returns {void | Promise<void>}\n * @description Callback for `router:routeAdded` event.\n */\n\n/**\n * Callback for `router:routeRemoved` event.\n * @callback RouteRemovedCallback\n * @param {RouteDefinition} route\n * The removed route definition.\n * @returns {void | Promise<void>}\n * @description Callback for `router:routeRemoved` event.\n */\n\n// ============================================================================\n// CORE IMPLEMENTATION\n// ============================================================================\n\n/**\n * Simple error handler for the core router.\n * @private\n */\nconst CoreErrorHandler = {\n /**\n * Handles router errors with basic formatting.\n * @param {Error} error - The error to handle.\n * @param {string} context - The context where the error occurred.\n * @param {Record<string, unknown>} details - Additional error details.\n * @throws {Error} The formatted error.\n */\n handle(error, context, details = {}) {\n const message = `[ElevaRouter] ${context}: ${error.message}`;\n const formattedError = new Error(message);\n\n // Preserve original error details\n formattedError.originalError = error;\n formattedError.context = context;\n formattedError.details = details;\n\n console.error(message, { error, context, details });\n throw formattedError;\n },\n\n /**\n * Logs a warning without throwing an error.\n * @param {string} message - The warning message.\n * @param {Record<string, unknown>} details - Additional warning details.\n */\n warn(message, details = {}) {\n console.warn(`[ElevaRouter] ${message}`, details);\n },\n\n /**\n * Logs an error without throwing.\n * @param {string} message - The error message.\n * @param {Error} error - The original error.\n * @param {Record<string, unknown>} details - Additional error details.\n */\n log(message, error, details = {}) {\n console.error(`[ElevaRouter] ${message}`, { error, details });\n },\n};\n\n/**\n * Represents the current or target location in the router.\n * @typedef {Object} RouteLocation\n * @property {string} path\n * The path of the route (e.g., '/users/123').\n * @property {QueryParams} query\n * Query parameters as key-value pairs.\n * @property {string} fullUrl\n * The routed URL string (path plus query).\n * @property {RouteParams} params\n * Dynamic route parameters.\n * @property {RouteMeta} meta\n * Metadata associated with the matched route.\n * @property {string} [name]\n * The optional name of the matched route.\n * @property {RouteDefinition} matched\n * The raw route definition that was matched.\n * @description Represents the current or target location in the router.\n */\n\n/**\n * Return value of a navigation guard.\n * - `true` or `undefined/void`: Allow navigation\n * - `false`: Abort navigation\n * - `string`: Redirect to path\n * - `NavigationTarget`: Redirect with options\n * @typedef {boolean | string | NavigationTarget | void} NavigationGuardResult\n */\n\n/**\n * Navigation guard function that controls navigation flow.\n * @callback NavigationGuard\n * @param {RouteLocation} to\n * The target route location.\n * @param {RouteLocation | null} from\n * The source route location (null on initial).\n * @returns {NavigationGuardResult | Promise<NavigationGuardResult>}\n * @description A function that controls navigation flow. Runs before navigation is confirmed.\n * @example\n * // Simple auth guard\n * const authGuard = (to, from) => {\n * if (to.meta.requiresAuth && !isLoggedIn()) {\n * return '/login'; // Redirect\n * }\n * // Allow navigation (implicit return undefined)\n * };\n */\n\n/**\n * Navigation hook for side effects. Does not affect navigation flow.\n * @callback NavigationHook\n * @param {RouteLocation} to\n * The target route location.\n * @param {RouteLocation | null} from\n * The source route location.\n * @returns {void | Promise<void>}\n * @description A lifecycle hook for side effects. Does not affect navigation flow.\n * @example\n * // Analytics hook\n * const analyticsHook = (to, from) => {\n * analytics.trackPageView(to.path);\n * };\n */\n\n/**\n * Interface for router plugins.\n * @typedef {Object} RouterPlugin\n * @property {string} name\n * Unique plugin identifier.\n * @property {string} [version]\n * Plugin version (recommended to match router version).\n * @property {(router: Router, options?: Record<string, unknown>) => void} install\n * Installation function.\n * @property {(router: Router) => void | Promise<void>} [destroy]\n * Cleanup function called on router.destroy().\n * @description Interface for router plugins. Plugins can extend router functionality.\n * @example\n * const AnalyticsPlugin = {\n * name: 'analytics',\n * version: '1.0.0',\n * install(router, options) {\n * router.emitter.on('router:afterEach', (to, from) => {\n * analytics.track(to.path);\n * });\n * }\n * };\n */\n\n/**\n * Context object for navigation events that plugins can modify.\n * @typedef {Object} NavigationContext\n * @property {RouteLocation} to\n * The target route location.\n * @property {RouteLocation | null} from\n * The source route location.\n * @property {boolean} cancelled\n * Whether navigation has been cancelled.\n * @property {string | NavigationTarget | null} redirectTo\n * Redirect target if set.\n * @description Passed to navigation events. Plugins can modify to control navigation flow.\n */\n\n/**\n * Context object for component resolution events.\n * @typedef {Object} ResolveContext\n * @property {RouteLocation} to\n * The target route location.\n * @property {RouteLocation | null} from\n * The source route location.\n * @property {RouteDefinition} route\n * The matched route definition.\n * @property {ComponentDefinition | null} layoutComponent\n * The resolved layout component (available in afterResolve).\n * @property {ComponentDefinition | null} pageComponent\n * The resolved page component (available in afterResolve).\n * @property {boolean} cancelled\n * Whether navigation has been cancelled.\n * @property {string | NavigationTarget | null} redirectTo\n * Redirect target if set.\n * @description Passed to component resolution events.\n */\n\n/**\n * Context object for render events.\n * @typedef {Object} RenderContext\n * @property {RouteLocation} to\n * The target route location.\n * @property {RouteLocation | null} from\n * The source route location.\n * @property {ComponentDefinition | null} layoutComponent\n * The layout component being rendered.\n * @property {ComponentDefinition} pageComponent\n * The page component being rendered.\n * @description Passed to render events.\n */\n\n/**\n * Context object for scroll events.\n * @typedef {Object} ScrollContext\n * @property {RouteLocation} to\n * The target route location.\n * @property {RouteLocation | null} from\n * The source route location.\n * @property {{x: number, y: number} | null} savedPosition\n * Saved position (back/forward nav).\n * @description Passed to scroll events for plugins to handle scroll behavior.\n */\n\n/**\n * A component that can be rendered for a route.\n * - `string`: Name of a registered component\n * - `ComponentDefinition`: Inline component definition\n * - `() => ComponentDefinition`: Factory function returning a component\n * - `() => Promise<ComponentDefinition>`: Async factory function\n * - `() => Promise<{default: ComponentDefinition}>`: Lazy-loaded module (e.g., `() => import('./Page.js')`)\n * @typedef {string | ComponentDefinition | (() => ComponentDefinition | Promise<ComponentDefinition | {default: ComponentDefinition}>)} RouteComponent\n */\n\n/**\n * Defines a route in the application.\n * @typedef {Object} RouteDefinition\n * @property {string} path\n * URL path pattern. Supports:\n * - Static: '/about'\n * - Dynamic params: '/users/:id'\n * - Wildcard: '*' (catch-all, conventionally last)\n * @property {RouteComponent} component\n * The component to render for this route.\n * @property {RouteComponent} [layout]\n * Optional layout component to wrap the route component.\n * @property {string} [name]\n * Optional route name for programmatic navigation.\n * @property {RouteMeta} [meta]\n * Optional metadata (auth flags, titles, etc.).\n * @property {NavigationGuard} [beforeEnter]\n * Route-specific guard before entering.\n * @property {NavigationHook} [afterEnter]\n * Hook after entering and component is mounted.\n * @property {NavigationGuard} [beforeLeave]\n * Guard before leaving this route.\n * @property {NavigationHook} [afterLeave]\n * Hook after leaving and component is unmounted.\n * @property {RouteSegment[]} [segments]\n * Internal: parsed path segments (added by router).\n * @description Defines a route in the application.\n * @note Nested routes are not supported. Use shared layouts with flat routes instead.\n * @example\n * // Static route\n * { path: '/about', component: AboutPage }\n *\n * // Dynamic route with params\n * { path: '/users/:id', component: UserPage, meta: { requiresAuth: true } }\n *\n * // Lazy-loaded route with layout\n * {\n * path: '/dashboard',\n * component: () => import('./Dashboard.js'),\n * layout: DashboardLayout,\n * beforeEnter: (to, from) => isLoggedIn() || '/login'\n * }\n *\n * // Catch-all 404 route (conventionally last)\n * { path: '*', component: NotFoundPage }\n */\n\n/**\n * @class 🛤️ Router\n * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.\n * This class manages all routing logic, including state, navigation, and rendering.\n *\n * ## Features\n * - Multiple routing modes (hash, history, query)\n * - Reactive route state via Signals\n * - Navigation guards and lifecycle hooks\n * - Lazy-loaded components\n * - Layout system\n * - Plugin architecture\n * - Scroll position management\n *\n * ## Events Reference\n * | Event | Callback Type | Can Block | Description |\n * |-------|--------------|-----------|-------------|\n * | `router:ready` | {@link RouterReadyCallback} | No | Router initialized |\n * | `router:beforeEach` | {@link NavigationContextCallback} | Yes | Before guards run |\n * | `router:beforeResolve` | {@link ResolveContextCallback} | Yes | Before component loading |\n * | `router:afterResolve` | {@link ResolveContextCallback} | No | After components loaded |\n * | `router:afterLeave` | {@link RouteChangeCallback} | No | After leaving route |\n * | `router:beforeRender` | {@link RenderContextCallback} | No | Before DOM update |\n * | `router:afterRender` | {@link RenderContextCallback} | No | After DOM update |\n * | `router:scroll` | {@link ScrollContextCallback} | No | For scroll behavior |\n * | `router:afterEnter` | {@link RouteChangeCallback} | No | After entering route |\n * | `router:afterEach` | {@link RouteChangeCallback} | No | Navigation complete |\n * | `router:error` | {@link RouterErrorCallback} | No | Navigation error |\n * | `router:routeAdded` | {@link RouteAddedCallback} | No | Dynamic route added |\n * | `router:routeRemoved` | {@link RouteRemovedCallback} | No | Dynamic route removed |\n *\n * ## Reactive Signals\n * - `currentRoute: Signal<RouteLocation | null>` - Current route info\n * - `previousRoute: Signal<RouteLocation | null>` - Previous route info\n * - `currentParams: Signal<RouteParams>` - Current route params\n * - `currentQuery: Signal<QueryParams>` - Current query params\n * - `currentLayout: Signal<MountResult | null>` - Mounted layout instance\n * - `currentView: Signal<MountResult | null>` - Mounted view instance\n * - `isReady: Signal<boolean>` - Router readiness state\n *\n * @note Internal API Access Policy:\n * As a core Eleva plugin, the Router may access internal Eleva APIs (prefixed with _)\n * such as `eleva._components`. This is intentional and these internal APIs are\n * considered stable for official plugins. Third-party plugins should avoid\n * accessing internal APIs as they may change without notice.\n *\n * @example\n * // Basic setup\n * const router = new Router(eleva, {\n * mode: 'hash',\n * mount: '#app',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/users/:id', component: UserPage },\n * { path: '*', component: NotFoundPage }\n * ]\n * });\n *\n * // Start router\n * await router.start();\n *\n * // Navigate programmatically\n * const success = await router.navigate('/users/123');\n *\n * // Watch for route changes\n * router.currentRoute.watch((route) => {\n * document.title = route?.meta?.title || 'My App';\n * });\n *\n * @private\n */\nclass Router {\n /**\n * Creates an instance of the Router.\n * @param {Eleva} eleva - The Eleva framework instance.\n * @param {RouterOptions} options - The configuration options for the router.\n * @throws {Error} If the routing mode is invalid.\n */\n constructor(eleva, options = {}) {\n /** @type {Eleva} The Eleva framework instance. */\n this.eleva = eleva;\n\n /** @type {RouterOptions} The merged router options. */\n this.options = {\n mode: \"hash\",\n queryParam: \"view\",\n viewSelector: \"view\",\n ...options,\n };\n\n /** @private @type {RouteDefinition[]} The processed list of route definitions. */\n this.routes = this._processRoutes(options.routes || []);\n\n /** @private @type {Emitter} The shared Eleva event emitter for global hooks. */\n this.emitter = this.eleva.emitter;\n\n /** @private @type {boolean} A flag indicating if the router has been started. */\n this.isStarted = false;\n\n /** @private @type {boolean} A flag to prevent navigation loops from history events. */\n this._isNavigating = false;\n\n /** @private @type {number} Counter for tracking navigation operations to prevent race conditions. */\n this._navigationId = 0;\n\n /** @private @type {UnsubscribeFunction[]} A collection of cleanup functions for event listeners. */\n this.eventListeners = [];\n\n /** @type {Signal<RouteLocation | null>} A reactive signal holding the current route's information. */\n this.currentRoute = new this.eleva.signal(null);\n\n /** @type {Signal<RouteLocation | null>} A reactive signal holding the previous route's information. */\n this.previousRoute = new this.eleva.signal(null);\n\n /** @type {Signal<RouteParams>} A reactive signal holding the current route's parameters. */\n this.currentParams = new this.eleva.signal({});\n\n /** @type {Signal<QueryParams>} A reactive signal holding the current route's query parameters. */\n this.currentQuery = new this.eleva.signal({});\n\n /** @type {Signal<MountResult | null>} A reactive signal for the currently mounted layout instance. */\n this.currentLayout = new this.eleva.signal(null);\n\n /** @type {Signal<MountResult | null>} A reactive signal for the currently mounted view (page) instance. */\n this.currentView = new this.eleva.signal(null);\n\n /** @type {Signal<boolean>} A reactive signal indicating if the router is ready (started and initial navigation complete). */\n this.isReady = new this.eleva.signal(false);\n\n /** @private @type {Map<string, RouterPlugin>} Map of registered plugins by name. */\n this.plugins = new Map();\n\n /** @private @type {NavigationGuard[]} Array of global before-each navigation guards. */\n this._beforeEachGuards = [];\n\n // If onBeforeEach was provided in options, add it to the guards array\n if (options.onBeforeEach) {\n this._beforeEachGuards.push(options.onBeforeEach);\n }\n\n /** @type {RouterErrorHandler} The error handler instance. Can be overridden by plugins. */\n this.errorHandler = CoreErrorHandler;\n\n /** @private @type {Map<string, {x: number, y: number}>} Saved scroll positions by route path. */\n this._scrollPositions = new Map();\n\n this._validateOptions();\n }\n\n /**\n * Validates the provided router options.\n * @private\n * @throws {Error} If the routing mode is invalid.\n */\n _validateOptions() {\n if (![\"hash\", \"query\", \"history\"].includes(this.options.mode)) {\n this.errorHandler.handle(\n new Error(\n `Invalid routing mode: ${this.options.mode}. Must be \"hash\", \"query\", or \"history\".`\n ),\n \"Configuration validation failed\"\n );\n }\n }\n\n /**\n * Pre-processes route definitions to parse their path segments for efficient matching.\n * @private\n * @param {RouteDefinition[]} routes - The raw route definitions.\n * @returns {RouteDefinition[]} The processed routes.\n */\n _processRoutes(routes) {\n const processedRoutes = [];\n for (const route of routes) {\n try {\n processedRoutes.push({\n ...route,\n segments: this._parsePathIntoSegments(route.path),\n });\n } catch (error) {\n this.errorHandler.warn(\n `Invalid path in route definition \"${route.path || \"undefined\"}\": ${error.message}`,\n { route, error }\n );\n }\n }\n return processedRoutes;\n }\n\n /**\n * Parses a route path string into an array of static and parameter segments.\n * @private\n * @param {string} path - The path pattern to parse.\n * @returns {{type: 'static' | 'param', value?: string, name?: string}[]} An array of segment objects.\n * @throws {Error} If the route path is not a valid string.\n */\n _parsePathIntoSegments(path) {\n if (!path || typeof path !== \"string\") {\n this.errorHandler.handle(\n new Error(\"Route path must be a non-empty string\"),\n \"Path parsing failed\",\n { path }\n );\n }\n\n const normalizedPath = path.replace(/\\/+/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n\n if (normalizedPath === \"/\") {\n return [];\n }\n\n return normalizedPath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n if (segment.startsWith(\":\")) {\n const paramName = segment.substring(1);\n if (!paramName) {\n this.errorHandler.handle(\n new Error(`Invalid parameter segment: ${segment}`),\n \"Path parsing failed\",\n { segment, path }\n );\n }\n return { type: \"param\", name: paramName };\n }\n return { type: \"static\", value: segment };\n });\n }\n\n /**\n * Finds the view element within a container using multiple selector strategies.\n * @private\n * @param {HTMLElement} container - The parent element to search within.\n * @returns {HTMLElement} The found view element or the container itself as a fallback.\n */\n _findViewElement(container) {\n const selector = this.options.viewSelector;\n return (\n container.querySelector(`#${selector}`) ||\n container.querySelector(`.${selector}`) ||\n container.querySelector(`[data-${selector}]`) ||\n container.querySelector(selector) ||\n container\n );\n }\n\n /**\n * Starts the router, initializes event listeners, and performs the initial navigation.\n * @returns {Promise<Router>} The router instance for method chaining.\n * @listens window:hashchange In hash mode, triggers route changes.\n * @listens window:popstate In history/query mode, triggers route changes.\n * @emits router:ready When initialization completes successfully.\n * @see destroy - Stop the router and clean up listeners.\n * @see navigate - Programmatically navigate to a route.\n *\n * @example\n * // Basic usage\n * await router.start();\n *\n * // Method chaining\n * await router.start().then(r => r.navigate('/home'));\n *\n * // Reactive readiness\n * router.isReady.watch((ready) => {\n * if (ready) console.log('Router is ready!');\n * });\n */\n async start() {\n if (this.isStarted) {\n this.errorHandler.warn(\"Router is already started\");\n return this;\n }\n if (typeof window === \"undefined\") {\n this.errorHandler.warn(\n \"Router start skipped: `window` object not available (SSR environment)\"\n );\n return this;\n }\n if (\n typeof document !== \"undefined\" &&\n !document.querySelector(this.options.mount)\n ) {\n this.errorHandler.warn(\n `Mount element \"${this.options.mount}\" was not found in the DOM. The router will not start.`,\n { mountSelector: this.options.mount }\n );\n return this;\n }\n const handler = () => this._handleRouteChange();\n if (this.options.mode === \"hash\") {\n window.addEventListener(\"hashchange\", handler);\n this.eventListeners.push(() =>\n window.removeEventListener(\"hashchange\", handler)\n );\n } else {\n window.addEventListener(\"popstate\", handler);\n this.eventListeners.push(() =>\n window.removeEventListener(\"popstate\", handler)\n );\n }\n this.isStarted = true;\n // Initial navigation is not a popstate event\n await this._handleRouteChange(false);\n // Set isReady to true after initial navigation completes\n this.isReady.value = true;\n await this.emitter.emit(\"router:ready\", this);\n return this;\n }\n\n /**\n * Stops the router and cleans up event listeners.\n * Unmounts the current layout instance if present.\n * @async\n * @returns {Promise<void>}\n * @see start - Restart the router after destroying.\n */\n async destroy() {\n if (!this.isStarted) return;\n\n // Clean up plugins\n for (const plugin of this.plugins.values()) {\n if (typeof plugin.destroy === \"function\") {\n try {\n await plugin.destroy(this);\n } catch (error) {\n this.errorHandler.log(`Plugin ${plugin.name} destroy failed`, error);\n }\n }\n }\n\n this.eventListeners.forEach((cleanup) => cleanup());\n this.eventListeners = [];\n if (this.currentLayout.value) {\n await this.currentLayout.value.unmount();\n }\n this.isStarted = false;\n this.isReady.value = false;\n }\n\n /**\n * Alias for destroy(). Stops the router and cleans up all resources.\n * Provided for semantic consistency (start/stop pattern).\n * @async\n * @returns {Promise<void>}\n *\n * @example\n * await router.start();\n * // ... later\n * await router.stop();\n */\n async stop() {\n return this.destroy();\n }\n\n /**\n * Programmatically navigates to a new route.\n * @async\n * @param {string | NavigationTarget} location - The target location as a path string or navigation target object.\n * @param {NavigationParams} [params] - Route parameters (only used when location is a string).\n * @returns {Promise<boolean>} True if navigation succeeded, false if blocked by guards or failed.\n * @emits router:error When navigation fails due to an exception.\n * @see start - Initialize the router before navigating.\n * @see currentRoute - Access the current route after navigation.\n *\n * @example\n * // Basic navigation\n * await router.navigate('/users/123');\n *\n * // Check if navigation succeeded\n * const success = await router.navigate('/protected');\n * if (!success) {\n * console.log('Navigation was blocked by a guard');\n * }\n *\n * // Navigate with options\n * await router.navigate({\n * path: '/users/:id',\n * params: { id: '123' },\n * query: { tab: 'profile' },\n * replace: true\n * });\n */\n async navigate(location, params = {}) {\n try {\n const target =\n typeof location === \"string\" ? { path: location, params } : location;\n let path = this._buildPath(target.path, target.params || {});\n const query = target.query || {};\n\n if (Object.keys(query).length > 0) {\n const queryString = new URLSearchParams(query).toString();\n if (queryString) path += `?${queryString}`;\n }\n\n if (this._isSameRoute(path, target.params, query)) {\n return true; // Already at this route, consider it successful\n }\n\n const navigationSuccessful = await this._proceedWithNavigation(path);\n\n if (navigationSuccessful) {\n // Increment navigation ID and capture it for this navigation\n const currentNavId = ++this._navigationId;\n this._isNavigating = true;\n\n const state = target.state || {};\n const replace = target.replace || false;\n const historyMethod = replace ? \"replaceState\" : \"pushState\";\n\n if (this.options.mode === \"hash\") {\n if (replace) {\n const newUrl = `${window.location.pathname}${window.location.search}#${path}`;\n window.history.replaceState(state, \"\", newUrl);\n } else {\n window.location.hash = path;\n }\n } else {\n const url =\n this.options.mode === \"query\" ? this._buildQueryUrl(path) : path;\n history[historyMethod](state, \"\", url);\n }\n\n // Only reset the flag if no newer navigation has started\n queueMicrotask(() => {\n if (this._navigationId === currentNavId) {\n this._isNavigating = false;\n }\n });\n }\n\n return navigationSuccessful;\n } catch (error) {\n this.errorHandler.log(\"Navigation failed\", error);\n await this.emitter.emit(\"router:error\", error);\n return false;\n }\n }\n\n /**\n * Builds a URL for query mode.\n * @private\n * @param {string} path - The path to set as the query parameter.\n * @returns {string} The full URL with the updated query string.\n */\n _buildQueryUrl(path) {\n const urlParams = new URLSearchParams(window.location.search);\n urlParams.set(this.options.queryParam, path.split(\"?\")[0]);\n return `${window.location.pathname}?${urlParams.toString()}`;\n }\n\n /**\n * Checks if the target route is identical to the current route.\n * @private\n * @param {string} path - The target path with query string.\n * @param {object} params - The target params.\n * @param {object} query - The target query.\n * @returns {boolean} True if the routes are the same.\n */\n _isSameRoute(path, params, query) {\n const current = this.currentRoute.value;\n if (!current) return false;\n const [targetPath, queryString] = path.split(\"?\");\n const targetQuery = query || this._parseQuery(queryString || \"\");\n return (\n current.path === targetPath &&\n JSON.stringify(current.params) === JSON.stringify(params || {}) &&\n JSON.stringify(current.query) === JSON.stringify(targetQuery)\n );\n }\n\n /**\n * Injects dynamic parameters into a path string.\n * Replaces `:param` placeholders with URL-encoded values from the params object.\n *\n * @private\n * @param {string} path - The path pattern containing `:param` placeholders.\n * @param {RouteParams} params - Key-value pairs to inject into the path.\n * @returns {string} The path with all parameters replaced.\n *\n * @example\n * this._buildPath('/users/:id/posts/:postId', { id: '123', postId: '456' });\n * // Returns: '/users/123/posts/456'\n */\n _buildPath(path, params) {\n let result = path;\n for (const [key, value] of Object.entries(params)) {\n // Fix: Handle special characters and ensure proper encoding\n const encodedValue = encodeURIComponent(String(value));\n result = result.replace(new RegExp(`:${key}\\\\b`, \"g\"), encodedValue);\n }\n return result;\n }\n\n /**\n * The handler for browser-initiated route changes (e.g., back/forward buttons).\n *\n * @private\n * @async\n * @param {boolean} [isPopState=true] - Whether this is a popstate event (back/forward navigation).\n * @returns {Promise<void>}\n * @emits router:error When route change handling fails.\n */\n async _handleRouteChange(isPopState = true) {\n if (this._isNavigating) return;\n\n try {\n const from = this.currentRoute.value;\n const toLocation = this._getCurrentLocation();\n\n const navigationSuccessful = await this._proceedWithNavigation(\n toLocation.fullUrl,\n isPopState\n );\n\n // If navigation was blocked by a guard, revert the URL change\n if (!navigationSuccessful && from) {\n this.navigate({ path: from.path, query: from.query, replace: true });\n }\n } catch (error) {\n this.errorHandler.log(\"Route change handling failed\", error, {\n currentUrl: typeof window !== \"undefined\" ? window.location.href : \"\",\n });\n await this.emitter.emit(\"router:error\", error);\n }\n }\n\n /**\n * Manages the core navigation lifecycle. Runs guards before committing changes.\n *\n * @private\n * @async\n * @param {string} fullPath - The full path (e.g., '/users/123?foo=bar') to navigate to.\n * @param {boolean} [isPopState=false] - Whether this navigation was triggered by popstate (back/forward).\n * @returns {Promise<boolean>} `true` if navigation succeeded, `false` if aborted.\n * @emits router:notFound When no matching route is found.\n * @emits router:beforeResolve Before component resolution (can block/redirect).\n * @emits router:afterResolve After components are resolved.\n * @emits router:afterLeave After leaving the previous route.\n * @emits router:beforeRender Before DOM rendering.\n * @emits router:afterRender After DOM rendering completes.\n * @emits router:scroll After render, for scroll behavior handling.\n * @emits router:afterEnter After entering the new route.\n * @emits router:afterEach After navigation completes successfully.\n * @emits router:error When an error occurs during navigation.\n * @see _runGuards - Guard execution.\n * @see _resolveComponents - Component resolution.\n * @see _render - DOM rendering.\n */\n async _proceedWithNavigation(fullPath, isPopState = false) {\n const from = this.currentRoute.value;\n const [path, queryString] = (fullPath || \"/\").split(\"?\");\n const toLocation = {\n path: path.startsWith(\"/\") ? path : `/${path}`,\n query: this._parseQuery(queryString),\n fullUrl: fullPath,\n };\n\n let toMatch = this._matchRoute(toLocation.path);\n\n if (!toMatch) {\n const notFoundRoute = this.routes.find((route) => route.path === \"*\");\n if (notFoundRoute) {\n toMatch = {\n route: notFoundRoute,\n params: {\n pathMatch: decodeURIComponent(toLocation.path.substring(1)),\n },\n };\n } else {\n await this.emitter.emit(\n \"router:error\",\n new Error(`Route not found: ${toLocation.path}`),\n toLocation,\n from\n );\n return false;\n }\n }\n\n const to = {\n ...toLocation,\n params: toMatch.params,\n meta: toMatch.route.meta || {},\n name: toMatch.route.name,\n matched: toMatch.route,\n };\n\n try {\n // 1. Run all *pre-navigation* guards.\n const canNavigate = await this._runGuards(to, from, toMatch.route);\n if (!canNavigate) return false;\n\n // 2. Save current scroll position before navigating away\n if (from && typeof window !== \"undefined\") {\n this._scrollPositions.set(from.path, {\n x: window.scrollX || window.pageXOffset || 0,\n y: window.scrollY || window.pageYOffset || 0,\n });\n }\n\n // 3. Emit beforeResolve event - plugins can show loading indicators\n /** @type {ResolveContext} */\n const resolveContext = {\n to,\n from,\n route: toMatch.route,\n layoutComponent: null,\n pageComponent: null,\n cancelled: false,\n redirectTo: null,\n };\n await this.emitter.emit(\"router:beforeResolve\", resolveContext);\n\n // Check if resolution was cancelled or redirected\n if (resolveContext.cancelled) return false;\n if (resolveContext.redirectTo) {\n this.navigate(resolveContext.redirectTo);\n return false;\n }\n\n // 4. Resolve async components *before* touching the DOM.\n const { layoutComponent, pageComponent } = await this._resolveComponents(\n toMatch.route\n );\n\n // 5. Emit afterResolve event - plugins can hide loading indicators\n resolveContext.layoutComponent = layoutComponent;\n resolveContext.pageComponent = pageComponent;\n await this.emitter.emit(\"router:afterResolve\", resolveContext);\n\n // 6. Unmount the previous view/layout.\n if (from) {\n const toLayout = toMatch.route.layout || this.options.globalLayout;\n const fromLayout = from.matched.layout || this.options.globalLayout;\n\n const tryUnmount = async (instance) => {\n if (!instance) return;\n\n try {\n await instance.unmount();\n } catch (error) {\n this.errorHandler.warn(\"Error during component unmount\", {\n error,\n instance,\n });\n }\n };\n\n if (toLayout !== fromLayout) {\n await tryUnmount(this.currentLayout.value);\n this.currentLayout.value = null;\n } else {\n await tryUnmount(this.currentView.value);\n this.currentView.value = null;\n }\n\n // Call `afterLeave` hook *after* the old component has been unmounted.\n if (from.matched.afterLeave) {\n await from.matched.afterLeave(to, from);\n }\n await this.emitter.emit(\"router:afterLeave\", to, from);\n }\n\n // 7. Update reactive state.\n this.previousRoute.value = from;\n this.currentRoute.value = to;\n this.currentParams.value = to.params || {};\n this.currentQuery.value = to.query || {};\n\n // 8. Emit beforeRender event - plugins can add transitions\n /** @type {RenderContext} */\n const renderContext = {\n to,\n from,\n layoutComponent,\n pageComponent,\n };\n await this.emitter.emit(\"router:beforeRender\", renderContext);\n\n // 9. Render the new components.\n await this._render(layoutComponent, pageComponent);\n\n // 10. Emit afterRender event - plugins can trigger animations\n await this.emitter.emit(\"router:afterRender\", renderContext);\n\n // 11. Emit scroll event - plugins can handle scroll restoration\n /** @type {ScrollContext} */\n const scrollContext = {\n to,\n from,\n savedPosition: isPopState\n ? this._scrollPositions.get(to.path) || null\n : null,\n };\n await this.emitter.emit(\"router:scroll\", scrollContext);\n\n // 12. Run post-navigation hooks.\n if (toMatch.route.afterEnter) {\n await toMatch.route.afterEnter(to, from);\n }\n await this.emitter.emit(\"router:afterEnter\", to, from);\n await this.emitter.emit(\"router:afterEach\", to, from);\n\n return true;\n } catch (error) {\n this.errorHandler.log(\"Error during navigation\", error, { to, from });\n await this.emitter.emit(\"router:error\", error, to, from);\n return false;\n }\n }\n\n /**\n * Executes all applicable navigation guards for a transition in order.\n * Guards are executed in the following order:\n * 1. Global beforeEach event (emitter-based, can block via context)\n * 2. Global beforeEach guards (registered via onBeforeEach)\n * 3. Route-specific beforeLeave guard (from the route being left)\n * 4. Route-specific beforeEnter guard (from the route being entered)\n *\n * @private\n * @param {RouteLocation} to - The target route location.\n * @param {RouteLocation | null} from - The current route location (null on initial navigation).\n * @param {RouteDefinition} route - The matched route definition.\n * @returns {Promise<boolean>} `false` if navigation should be aborted.\n * @emits router:beforeEach Before guards run (can block/redirect via context).\n */\n async _runGuards(to, from, route) {\n // Create navigation context that plugins can modify to block navigation\n /** @type {NavigationContext} */\n const navContext = {\n to,\n from,\n cancelled: false,\n redirectTo: null,\n };\n\n // Emit beforeEach event with context - plugins can block by modifying context\n await this.emitter.emit(\"router:beforeEach\", navContext);\n\n // Check if navigation was cancelled or redirected by event listeners\n if (navContext.cancelled) return false;\n if (navContext.redirectTo) {\n this.navigate(navContext.redirectTo);\n return false;\n }\n\n // Collect all guards in execution order\n const guards = [\n ...this._beforeEachGuards,\n ...(from && from.matched.beforeLeave ? [from.matched.beforeLeave] : []),\n ...(route.beforeEnter ? [route.beforeEnter] : []),\n ];\n\n for (const guard of guards) {\n const result = await guard(to, from);\n if (result === false) return false;\n if (typeof result === \"string\" || typeof result === \"object\") {\n this.navigate(result);\n return false;\n }\n }\n return true;\n }\n\n /**\n * Resolves a string component definition to a component object.\n * @private\n * @param {string} def - The component name to resolve.\n * @returns {ComponentDefinition} The resolved component.\n * @throws {Error} If the component is not registered.\n *\n * @note Core plugins (Router, Attr, Store) may access eleva._components\n * directly. This is intentional and stable for official Eleva plugins shipped\n * with the framework. Third-party plugins should use eleva.component() for\n * registration and avoid direct access to internal APIs.\n */\n _resolveStringComponent(def) {\n const componentDef = this.eleva._components.get(def);\n if (!componentDef) {\n this.errorHandler.handle(\n new Error(`Component \"${def}\" not registered.`),\n \"Component resolution failed\",\n {\n componentName: def,\n availableComponents: Array.from(this.eleva._components.keys()),\n }\n );\n }\n return componentDef;\n }\n\n /**\n * Resolves a function component definition to a component object.\n * @private\n * @async\n * @param {() => ComponentDefinition | Promise<ComponentDefinition | { default: ComponentDefinition }>} def - The function to resolve.\n * @returns {Promise<ComponentDefinition>} The resolved component.\n * @throws {Error} If the function fails to load the component.\n */\n async _resolveFunctionComponent(def) {\n try {\n const funcStr = def.toString();\n const isAsyncImport =\n funcStr.includes(\"import(\") || funcStr.startsWith(\"() =>\");\n\n const result = await def();\n return isAsyncImport ? result.default || result : result;\n } catch (error) {\n this.errorHandler.handle(\n new Error(`Failed to load async component: ${error.message}`),\n \"Component resolution failed\",\n { function: def.toString(), error }\n );\n }\n }\n\n /**\n * Validates a component definition object.\n * @private\n * @param {unknown} def - The component definition to validate.\n * @returns {ComponentDefinition} The validated component.\n * @throws {Error} If the component definition is invalid.\n */\n _validateComponentDefinition(def) {\n if (!def || typeof def !== \"object\") {\n this.errorHandler.handle(\n new Error(`Invalid component definition: ${typeof def}`),\n \"Component validation failed\",\n { definition: def }\n );\n }\n\n if (\n typeof def.template !== \"function\" &&\n typeof def.template !== \"string\"\n ) {\n this.errorHandler.handle(\n new Error(\"Component missing template property\"),\n \"Component validation failed\",\n { definition: def }\n );\n }\n\n return def;\n }\n\n /**\n * Resolves a component definition to a component object.\n * @private\n * @param {unknown} def - The component definition to resolve.\n * @returns {Promise<ComponentDefinition | null>} The resolved component or null.\n */\n async _resolveComponent(def) {\n if (def === null || def === undefined) {\n return null;\n }\n\n if (typeof def === \"string\") {\n return this._resolveStringComponent(def);\n }\n\n if (typeof def === \"function\") {\n return await this._resolveFunctionComponent(def);\n }\n\n if (def && typeof def === \"object\") {\n return this._validateComponentDefinition(def);\n }\n\n this.errorHandler.handle(\n new Error(`Invalid component definition: ${typeof def}`),\n \"Component resolution failed\",\n { definition: def }\n );\n }\n\n /**\n * Asynchronously resolves the layout and page components for a route.\n * @private\n * @async\n * @param {RouteDefinition} route - The route to resolve components for.\n * @returns {Promise<{layoutComponent: ComponentDefinition | null, pageComponent: ComponentDefinition}>}\n * @throws {Error} If page component cannot be resolved.\n */\n async _resolveComponents(route) {\n const effectiveLayout = route.layout || this.options.globalLayout;\n\n try {\n const [layoutComponent, pageComponent] = await Promise.all([\n this._resolveComponent(effectiveLayout),\n this._resolveComponent(route.component),\n ]);\n\n if (!pageComponent) {\n this.errorHandler.handle(\n new Error(\n `Page component is null or undefined for route: ${route.path}`\n ),\n \"Component resolution failed\",\n { route: route.path }\n );\n }\n\n return { layoutComponent, pageComponent };\n } catch (error) {\n this.errorHandler.log(\n `Error resolving components for route ${route.path}`,\n error,\n { route: route.path }\n );\n throw error;\n }\n }\n\n /**\n * Renders the components for the current route into the DOM.\n *\n * Rendering algorithm:\n * 1. Find the mount element using options.mount selector\n * 2. If layoutComponent exists:\n * a. Mount layout to mount element\n * b. Find view element within layout (using viewSelector)\n * c. Mount page component to view element\n * 3. If no layoutComponent:\n * a. Mount page component directly to mount element\n * b. Set currentLayout to null\n *\n * @private\n * @async\n * @param {ComponentDefinition | null} layoutComponent - The pre-loaded layout component.\n * @param {ComponentDefinition} pageComponent - The pre-loaded page component.\n * @returns {Promise<void>}\n * @throws {Error} If mount element is not found in the DOM.\n * @throws {Error} If component mounting fails (propagated from eleva.mount).\n */\n async _render(layoutComponent, pageComponent) {\n const mountEl = document.querySelector(this.options.mount);\n if (!mountEl) {\n this.errorHandler.handle(\n new Error(`Mount element \"${this.options.mount}\" not found.`),\n { mountSelector: this.options.mount }\n );\n }\n\n if (layoutComponent) {\n const layoutInstance = await this.eleva.mount(\n mountEl,\n this._wrapComponentWithChildren(layoutComponent)\n );\n this.currentLayout.value = layoutInstance;\n const viewEl = this._findViewElement(layoutInstance.container);\n const viewInstance = await this.eleva.mount(\n viewEl,\n this._wrapComponentWithChildren(pageComponent)\n );\n this.currentView.value = viewInstance;\n } else {\n const viewInstance = await this.eleva.mount(\n mountEl,\n this._wrapComponentWithChildren(pageComponent)\n );\n this.currentView.value = viewInstance;\n this.currentLayout.value = null;\n }\n }\n\n /**\n * Creates a getter function for router context properties.\n * @private\n * @param {string} property - The property name to access.\n * @param {unknown} defaultValue - The default value if property is undefined.\n * @returns {() => unknown} A getter function.\n */\n _createRouteGetter(property, defaultValue) {\n return () => this.currentRoute.value?.[property] ?? defaultValue;\n }\n\n /**\n * Wraps a component definition to inject router-specific context into its setup function.\n * @private\n * @param {ComponentDefinition} component - The component to wrap.\n * @returns {ComponentDefinition} The wrapped component definition.\n */\n _wrapComponent(component) {\n const originalSetup = component.setup;\n const self = this;\n\n return {\n ...component,\n async setup(ctx) {\n /** @type {RouterContext} */\n ctx.router = {\n navigate: self.navigate.bind(self),\n current: self.currentRoute,\n previous: self.previousRoute,\n\n // Route property getters\n get params() {\n return self._createRouteGetter(\"params\", {})();\n },\n get query() {\n return self._createRouteGetter(\"query\", {})();\n },\n get path() {\n return self._createRouteGetter(\"path\", \"/\")();\n },\n get fullUrl() {\n return self._createRouteGetter(\"fullUrl\", window.location.href)();\n },\n get meta() {\n return self._createRouteGetter(\"meta\", {})();\n },\n };\n\n return originalSetup ? await originalSetup(ctx) : {};\n },\n };\n }\n\n /**\n * Recursively wraps all child components to ensure they have access to router context.\n * String component references are returned as-is (context injected during mount).\n * Objects are wrapped with router context and their children are recursively wrapped.\n *\n * @private\n * @param {ComponentDefinition | string} component - The component to wrap (can be a definition object or a registered component name).\n * @returns {ComponentDefinition | string} The wrapped component definition or the original string reference.\n * @see _wrapComponent - Single component wrapping.\n */\n _wrapComponentWithChildren(component) {\n // If the component is a string (registered component name), return as-is\n // The router context will be injected when the component is resolved during mounting\n if (typeof component === \"string\") {\n return component;\n }\n\n // If not a valid component object, return as-is\n if (!component || typeof component !== \"object\") {\n return component;\n }\n\n const wrappedComponent = this._wrapComponent(component);\n\n // If the component has children, wrap them too\n if (\n wrappedComponent.children &&\n typeof wrappedComponent.children === \"object\"\n ) {\n const wrappedChildren = {};\n for (const [selector, childComponent] of Object.entries(\n wrappedComponent.children\n )) {\n wrappedChildren[selector] =\n this._wrapComponentWithChildren(childComponent);\n }\n wrappedComponent.children = wrappedChildren;\n }\n\n return wrappedComponent;\n }\n\n /**\n * Gets the current location information from the browser's window object.\n * @private\n * @returns {Omit<RouteLocation, 'params' | 'meta' | 'name' | 'matched'>}\n */\n _getCurrentLocation() {\n if (typeof window === \"undefined\")\n return { path: \"/\", query: {}, fullUrl: \"\" };\n let path, queryString, fullUrl;\n switch (this.options.mode) {\n case \"hash\":\n fullUrl = window.location.hash.slice(1) || \"/\";\n [path, queryString] = fullUrl.split(\"?\");\n break;\n case \"query\":\n const urlParams = new URLSearchParams(window.location.search);\n path = urlParams.get(this.options.queryParam) || \"/\";\n queryString = window.location.search.slice(1);\n fullUrl = path;\n break;\n default: // 'history' mode\n path = window.location.pathname || \"/\";\n queryString = window.location.search.slice(1);\n fullUrl = `${path}${queryString ? \"?\" + queryString : \"\"}`;\n }\n return {\n path: path.startsWith(\"/\") ? path : `/${path}`,\n query: this._parseQuery(queryString),\n fullUrl,\n };\n }\n\n /**\n * Parses a query string into a key-value object.\n * Uses URLSearchParams for robust parsing of encoded values.\n *\n * @private\n * @param {string} queryString - The query string to parse (without leading '?').\n * @returns {QueryParams} Key-value pairs from the query string.\n *\n * @example\n * this._parseQuery('foo=bar&baz=qux');\n * // Returns: { foo: 'bar', baz: 'qux' }\n */\n _parseQuery(queryString) {\n const query = {};\n if (queryString) {\n new URLSearchParams(queryString).forEach((value, key) => {\n query[key] = value;\n });\n }\n return query;\n }\n\n /**\n * Matches a given path against the registered routes.\n * @private\n * @param {string} path - The path to match.\n * @returns {{route: RouteDefinition, params: Object<string, string>} | null} The matched route and its params, or null.\n */\n _matchRoute(path) {\n const pathSegments = path.split(\"/\").filter(Boolean);\n\n for (const route of this.routes) {\n // Handle the root path as a special case.\n if (route.path === \"/\") {\n if (pathSegments.length === 0) return { route, params: {} };\n continue;\n }\n\n if (route.segments.length !== pathSegments.length) continue;\n\n const params = {};\n let isMatch = true;\n for (let i = 0; i < route.segments.length; i++) {\n const routeSegment = route.segments[i];\n const pathSegment = pathSegments[i];\n if (routeSegment.type === \"param\") {\n params[routeSegment.name] = decodeURIComponent(pathSegment);\n } else if (routeSegment.value !== pathSegment) {\n isMatch = false;\n break;\n }\n }\n if (isMatch) return { route, params };\n }\n return null;\n }\n\n // ============================================\n // Dynamic Route Management API\n // ============================================\n\n /**\n * Adds a new route dynamically at runtime.\n * The route will be processed and available for navigation immediately.\n * Routes are inserted before the wildcard (*) route if one exists.\n *\n * @param {RouteDefinition} route - The route definition to add.\n * @param {RouteDefinition} [parentRoute] - Optional parent route to add as a child (not yet implemented).\n * @returns {() => void} A function to remove the added route (returns no-op if route was invalid).\n * @emits router:routeAdded When a route is successfully added.\n *\n * @example\n * // Add a route dynamically\n * const removeRoute = router.addRoute({\n * path: '/dynamic',\n * component: DynamicPage,\n * meta: { title: 'Dynamic Page' }\n * });\n *\n * // Later, remove the route\n * removeRoute();\n */\n addRoute(route, parentRoute = null) {\n if (!route || !route.path) {\n this.errorHandler.warn(\"Invalid route definition: missing path\", {\n route,\n });\n return () => {};\n }\n\n // Check if route already exists\n if (this.hasRoute(route.path)) {\n this.errorHandler.warn(`Route \"${route.path}\" already exists`, { route });\n return () => {};\n }\n\n // Process the route (parse segments)\n const processedRoute = {\n ...route,\n segments: this._parsePathIntoSegments(route.path),\n };\n\n // Add to routes array (before wildcard if exists)\n const wildcardIndex = this.routes.findIndex((r) => r.path === \"*\");\n if (wildcardIndex !== -1) {\n this.routes.splice(wildcardIndex, 0, processedRoute);\n } else {\n this.routes.push(processedRoute);\n }\n\n // Emit event for plugins\n this.emitter.emit(\"router:routeAdded\", processedRoute);\n\n // Return removal function\n return () => this.removeRoute(route.path);\n }\n\n /**\n * Removes a route by its path.\n *\n * @param {string} path - The path of the route to remove.\n * @returns {boolean} True if the route was removed, false if not found.\n * @emits router:routeRemoved When a route is successfully removed.\n *\n * @example\n * router.removeRoute('/dynamic');\n */\n removeRoute(path) {\n const index = this.routes.findIndex((r) => r.path === path);\n if (index === -1) {\n return false;\n }\n\n const [removedRoute] = this.routes.splice(index, 1);\n\n // Emit event for plugins\n this.emitter.emit(\"router:routeRemoved\", removedRoute);\n\n return true;\n }\n\n /**\n * Checks if a route with the given path exists.\n *\n * @param {string} path - The path to check.\n * @returns {boolean} True if the route exists.\n *\n * @example\n * if (router.hasRoute('/users/:id')) {\n * console.log('User route exists');\n * }\n */\n hasRoute(path) {\n return this.routes.some((r) => r.path === path);\n }\n\n /**\n * Gets all registered routes.\n *\n * @returns {RouteDefinition[]} A copy of the routes array.\n *\n * @example\n * const routes = router.getRoutes();\n * console.log('Available routes:', routes.map(r => r.path));\n */\n getRoutes() {\n return [...this.routes];\n }\n\n /**\n * Gets a route by its path.\n *\n * @param {string} path - The path of the route to get.\n * @returns {RouteDefinition | undefined} The route definition or undefined.\n *\n * @example\n * const route = router.getRoute('/users/:id');\n * if (route) {\n * console.log('Route meta:', route.meta);\n * }\n */\n getRoute(path) {\n return this.routes.find((r) => r.path === path);\n }\n\n // ============================================\n // Hook Registration Methods\n // ============================================\n\n /**\n * Registers a global pre-navigation guard.\n * Multiple guards can be registered and will be executed in order.\n * Guards can also be registered via the emitter using `router:beforeEach` event.\n *\n * @param {NavigationGuard} guard - The guard function to register.\n * @returns {() => void} A function to unregister the guard.\n *\n * @example\n * // Register a guard\n * const unregister = router.onBeforeEach((to, from) => {\n * if (to.meta.requiresAuth && !isAuthenticated()) {\n * return '/login';\n * }\n * });\n *\n * // Later, unregister the guard\n * unregister();\n */\n onBeforeEach(guard) {\n this._beforeEachGuards.push(guard);\n return () => {\n const index = this._beforeEachGuards.indexOf(guard);\n if (index > -1) {\n this._beforeEachGuards.splice(index, 1);\n }\n };\n }\n /**\n * Registers a global hook that runs after a new route component has been mounted.\n * @param {NavigationHook} hook - The hook function to register.\n * @returns {() => void} A function to unregister the hook.\n * @listens router:afterEnter\n */\n onAfterEnter(hook) {\n return this.emitter.on(\"router:afterEnter\", hook);\n }\n\n /**\n * Registers a global hook that runs after a route component has been unmounted.\n * @param {NavigationHook} hook - The hook function to register.\n * @returns {() => void} A function to unregister the hook.\n * @listens router:afterLeave\n */\n onAfterLeave(hook) {\n return this.emitter.on(\"router:afterLeave\", hook);\n }\n\n /**\n * Registers a global hook that runs after a navigation has been confirmed and all hooks have completed.\n * @param {NavigationHook} hook - The hook function to register.\n * @returns {() => void} A function to unregister the hook.\n * @listens router:afterEach\n */\n onAfterEach(hook) {\n return this.emitter.on(\"router:afterEach\", hook);\n }\n\n /**\n * Registers a global error handler for navigation errors.\n * @param {(error: Error, to?: RouteLocation, from?: RouteLocation) => void} handler - The error handler function.\n * @returns {() => void} A function to unregister the handler.\n * @listens router:error\n */\n onError(handler) {\n return this.emitter.on(\"router:error\", handler);\n }\n\n /**\n * Registers a plugin with the router.\n * Logs a warning if the plugin is already registered.\n *\n * @param {RouterPlugin} plugin - The plugin to register (must have install method).\n * @param {Record<string, unknown>} [options={}] - Options to pass to plugin.install().\n * @returns {void}\n * @throws {Error} If plugin does not have an install method.\n */\n use(plugin, options = {}) {\n if (typeof plugin.install !== \"function\") {\n this.errorHandler.handle(\n new Error(\"Plugin must have an install method\"),\n \"Plugin registration failed\",\n { plugin }\n );\n }\n\n // Check if plugin is already registered\n if (this.plugins.has(plugin.name)) {\n this.errorHandler.warn(`Plugin \"${plugin.name}\" is already registered`, {\n existingPlugin: this.plugins.get(plugin.name),\n });\n return;\n }\n\n this.plugins.set(plugin.name, plugin);\n plugin.install(this, options);\n }\n\n /**\n * Gets all registered plugins.\n * @returns {RouterPlugin[]} Array of registered plugins.\n */\n getPlugins() {\n return Array.from(this.plugins.values());\n }\n\n /**\n * Gets a plugin by name.\n * @param {string} name - The plugin name.\n * @returns {RouterPlugin | undefined} The plugin or undefined.\n */\n getPlugin(name) {\n return this.plugins.get(name);\n }\n\n /**\n * Removes a plugin from the router.\n * @param {string} name - The plugin name.\n * @returns {boolean} True if the plugin was removed.\n */\n removePlugin(name) {\n const plugin = this.plugins.get(name);\n if (!plugin) return false;\n\n // Call destroy if available\n if (typeof plugin.destroy === \"function\") {\n try {\n plugin.destroy(this);\n } catch (error) {\n this.errorHandler.log(`Plugin ${name} destroy failed`, error);\n }\n }\n\n return this.plugins.delete(name);\n }\n\n /**\n * Sets a custom error handler. Used by error handling plugins.\n * Logs a warning if the provided handler is invalid (missing required methods).\n * @param {RouterErrorHandler} errorHandler - The error handler object with handle, warn, and log methods.\n * @returns {void}\n */\n setErrorHandler(errorHandler) {\n if (\n errorHandler &&\n typeof errorHandler.handle === \"function\" &&\n typeof errorHandler.warn === \"function\" &&\n typeof errorHandler.log === \"function\"\n ) {\n this.errorHandler = errorHandler;\n } else {\n console.warn(\n \"[ElevaRouter] Invalid error handler provided. Must have handle, warn, and log methods.\"\n );\n }\n }\n}\n\n/**\n * @class 🚀 RouterPlugin\n * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva applications.\n * This plugin provides comprehensive client-side routing functionality including:\n * - Multiple routing modes (hash, history, query)\n * - Navigation guards and lifecycle hooks\n * - Reactive state management\n * - Component resolution and lazy loading\n * - Layout and page component separation\n * - Plugin system for extensibility\n * - Advanced error handling\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n *\n * const HomePage = { template: () => `<h1>Home</h1>` };\n * const AboutPage = { template: () => `<h1>About Us</h1>` };\n * const UserPage = {\n * template: (ctx) => `<h1>User: ${ctx.router.params.id}</h1>`\n * };\n *\n * app.use(RouterPlugin, {\n * mount: '#app',\n * mode: 'hash',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/about', component: AboutPage },\n * { path: '/users/:id', component: UserPage }\n * ]\n * });\n */\nexport const RouterPlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"router\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.1.0\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description: \"Client-side routing for Eleva applications\",\n\n /**\n * Installs the RouterPlugin into an Eleva instance.\n *\n * @public\n * @param {Eleva} eleva - The Eleva instance.\n * @param {RouterOptions} options - Router configuration options.\n * @param {string} options.mount - A CSS selector for the main element where the app is mounted.\n * @param {RouteDefinition[]} options.routes - An array of route definitions.\n * @param {'hash' | 'query' | 'history'} [options.mode='hash'] - The routing mode.\n * @param {string} [options.queryParam='view'] - The query parameter to use in 'query' mode.\n * @param {string} [options.viewSelector='view'] - Base selector for the view element (matched as #id, .class, [data-*], or raw selector).\n * @param {boolean} [options.autoStart=true] - Whether to start the router automatically.\n * @param {NavigationGuard} [options.onBeforeEach] - A global guard executed before every navigation.\n * @param {RouteComponent} [options.globalLayout] - A global layout for all routes.\n * @returns {Router} The created router instance.\n * @throws {Error} If 'mount' option is not provided.\n * @throws {Error} If 'routes' option is not an array.\n * @throws {Error} If component registration fails during route processing.\n * @description\n * Registers route/layout components, sets `eleva.router`, and adds helpers\n * (`eleva.navigate`, `eleva.getCurrentRoute`, `eleva.getRouteParams`, `eleva.getRouteQuery`).\n * When `autoStart` is enabled, startup is scheduled via microtask.\n *\n * @example\n * // main.js\n * import Eleva from 'eleva';\n * import { RouterPlugin } from './plugins/RouterPlugin.js';\n *\n * const app = new Eleva('myApp');\n *\n * const HomePage = { template: () => `<h1>Home</h1>` };\n * const AboutPage = { template: () => `<h1>About Us</h1>` };\n *\n * app.use(RouterPlugin, {\n * mount: '#app',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/about', component: AboutPage }\n * ]\n * });\n */\n install(eleva, options = {}) {\n if (!options.mount) {\n throw new Error(\"[RouterPlugin] 'mount' option is required\");\n }\n\n if (!options.routes || !Array.isArray(options.routes)) {\n throw new Error(\"[RouterPlugin] 'routes' option must be an array\");\n }\n\n /**\n * Registers a component definition with the Eleva instance.\n * This method handles both inline component objects and pre-registered component names.\n *\n * @inner\n * @param {unknown} def - The component definition to register.\n * @param {string} type - The type of component for naming (e.g., \"Route\", \"Layout\").\n * @returns {string | null} The registered component name or null if no definition provided.\n */\n const register = (def, type) => {\n if (!def) return null;\n\n if (typeof def === \"object\" && def !== null && !def.name) {\n const name = `Eleva${type}Component_${Math.random()\n .toString(36)\n .slice(2, 11)}`;\n\n try {\n eleva.component(name, def);\n return name;\n } catch (error) {\n throw new Error(\n `[RouterPlugin] Failed to register ${type} component: ${error.message}`\n );\n }\n }\n return def;\n };\n\n if (options.globalLayout) {\n options.globalLayout = register(options.globalLayout, \"GlobalLayout\");\n }\n\n (options.routes || []).forEach((route) => {\n route.component = register(route.component, \"Route\");\n if (route.layout) {\n route.layout = register(route.layout, \"RouteLayout\");\n }\n });\n\n const router = new Router(eleva, options);\n /** @type {Router} */\n eleva.router = router;\n\n if (options.autoStart !== false) {\n queueMicrotask(() => router.start());\n }\n\n // Add plugin metadata to the Eleva instance\n if (!eleva.plugins) {\n eleva.plugins = new Map();\n }\n eleva.plugins.set(this.name, {\n name: this.name,\n version: this.version,\n description: this.description,\n options,\n });\n\n // Add utility methods for manual router access\n /** @type {NavigateFunction} */\n eleva.navigate = router.navigate.bind(router);\n /** @type {() => RouteLocation | null} */\n eleva.getCurrentRoute = () => router.currentRoute.value;\n /** @type {() => RouteParams} */\n eleva.getRouteParams = () => router.currentParams.value;\n /** @type {() => QueryParams} */\n eleva.getRouteQuery = () => router.currentQuery.value;\n\n return router;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance.\n *\n * @public\n * @async\n * @param {Eleva} eleva - The Eleva instance.\n * @returns {Promise<void>}\n * @description\n * Destroys the router instance, removes `eleva.router`, and deletes helper methods\n * (`eleva.navigate`, `eleva.getCurrentRoute`, `eleva.getRouteParams`, `eleva.getRouteQuery`).\n */\n async uninstall(eleva) {\n if (eleva.router) {\n await eleva.router.destroy();\n delete eleva.router;\n }\n\n // Remove plugin metadata\n if (eleva.plugins) {\n eleva.plugins.delete(this.name);\n }\n\n // Remove utility methods\n delete eleva.navigate;\n delete eleva.getCurrentRoute;\n delete eleva.getRouteParams;\n delete eleva.getRouteQuery;\n },\n};\n\n// Short name export for convenience\nexport { RouterPlugin as Router };\n","\"use strict\";\n\n/**\n * @module eleva/plugins/store\n * @fileoverview Reactive state management plugin with namespaced modules,\n * persistence, and subscription system.\n */\n\n// ============================================================================\n// TYPE DEFINITIONS\n// ============================================================================\n\n// -----------------------------------------------------------------------------\n// External Type Imports\n// -----------------------------------------------------------------------------\n\n/**\n * Type imports from the Eleva core library.\n * @typedef {import('eleva').Eleva} Eleva\n * @typedef {import('eleva').ComponentDefinition} ComponentDefinition\n * @typedef {import('eleva').ComponentContext} ComponentContext\n * @typedef {import('eleva').SetupResult} SetupResult\n * @typedef {import('eleva').ComponentProps} ComponentProps\n * @typedef {import('eleva').ChildrenMap} ChildrenMap\n * @typedef {import('eleva').MountResult} MountResult\n */\n\n/**\n * Generic type import.\n * @template T\n * @typedef {import('eleva').Signal<T>} Signal\n */\n\n// -----------------------------------------------------------------------------\n// Store Type Definitions\n// -----------------------------------------------------------------------------\n\n/**\n * Mutation record emitted to subscribers.\n * @typedef {Object} StoreMutation\n * @property {string} type\n * The action name that was dispatched.\n * @property {unknown} payload\n * The payload passed to the action.\n * @property {number} timestamp\n * Unix timestamp of when the mutation occurred.\n * @description Record passed to subscribers when state changes via dispatch.\n * @example\n * store.subscribe((mutation, state) => {\n * console.log(`Action: ${mutation.type}`);\n * console.log(`Payload: ${mutation.payload}`);\n * console.log(`Time: ${new Date(mutation.timestamp)}`);\n * });\n */\n\n/**\n * Store configuration options.\n * @typedef {Object} StoreOptions\n * @property {Record<string, unknown>} [state]\n * Initial state object.\n * @property {Record<string, ActionFunction>} [actions]\n * Action functions for state mutations.\n * @property {Record<string, StoreModule>} [namespaces]\n * Namespaced modules for organizing store.\n * @property {StorePersistenceOptions} [persistence]\n * Persistence configuration.\n * @property {boolean} [devTools]\n * Enable development tools integration.\n * @property {StoreErrorHandler} [onError]\n * Error handler function.\n * @description Configuration options passed to StorePlugin.install().\n * @example\n * app.use(StorePlugin, {\n * state: { count: 0, user: null },\n * actions: {\n * increment: (state) => state.count.value++,\n * setUser: (state, user) => state.user.value = user\n * },\n * persistence: { enabled: true, key: 'my-app' }\n * });\n */\n\n/**\n * Namespaced store module definition.\n * @typedef {Object} StoreModule\n * @property {Record<string, unknown>} state\n * Module state.\n * @property {Record<string, ActionFunction>} [actions]\n * Module actions.\n * @description Defines a namespaced module for organizing related state and actions.\n * @example\n * // Define a module\n * const authModule = {\n * state: { user: null, token: null },\n * actions: {\n * login: (state, { user, token }) => {\n * state.auth.user.value = user;\n * state.auth.token.value = token;\n * }\n * }\n * };\n *\n * // Register dynamically\n * store.registerModule('auth', authModule);\n */\n\n/**\n * Store persistence configuration.\n * @typedef {Object} StorePersistenceOptions\n * @property {boolean} [enabled]\n * Enable state persistence.\n * @property {string} [key]\n * Storage key (default: \"eleva-store\").\n * @property {'localStorage' | 'sessionStorage'} [storage]\n * Storage type.\n * @property {string[]} [include]\n * Dot-path prefixes to persist (e.g., \"auth.user\").\n * @property {string[]} [exclude]\n * Dot-path prefixes to exclude.\n * @description Configuration for persisting store state to localStorage or sessionStorage.\n * @example\n * // Persist only specific state paths\n * persistence: {\n * enabled: true,\n * key: 'my-app-store',\n * storage: 'localStorage',\n * include: ['user', 'settings.theme']\n * }\n *\n * @example\n * // Exclude sensitive data\n * persistence: {\n * enabled: true,\n * exclude: ['auth.token', 'temp']\n * }\n */\n\n/**\n * Store error handler callback.\n * @typedef {(error: Error, context: string) => void} StoreErrorHandler\n * @description Custom error handler for store operations.\n * @example\n * app.use(StorePlugin, {\n * onError: (error, context) => {\n * console.error(`Store error in ${context}:`, error);\n * // Send to error tracking service\n * errorTracker.capture(error, { context });\n * }\n * });\n */\n\n/**\n * Reactive state tree containing signals and nested namespaces.\n * @typedef {Record<string, Signal<unknown> | Record<string, unknown>>} StoreState\n * @description Represents the store's reactive state structure with support for nested modules.\n */\n\n/**\n * Action function signature for store actions.\n * @typedef {(state: StoreState, payload?: unknown) => unknown} ActionFunction\n * @description Function that receives state and optional payload, returns action result.\n */\n\n/**\n * Dispatch function signature for triggering actions.\n * @typedef {(actionName: string, payload?: unknown) => Promise<unknown>} DispatchFunction\n * @description Dispatches an action by name with optional payload, returns action result.\n */\n\n/**\n * Subscribe callback signature for mutation listeners.\n * @typedef {(mutation: StoreMutation, state: StoreState) => void} SubscribeCallback\n * @description Called after each successful action dispatch with mutation details and current state.\n */\n\n/**\n * Store API exposed to components via ctx.store.\n * @typedef {Object} StoreApi\n * @property {StoreState} state\n * Reactive state signals (supports nested modules).\n * @property {DispatchFunction} dispatch\n * Dispatch an action by name with optional payload.\n * @property {(callback: SubscribeCallback) => () => void} subscribe\n * Subscribe to state mutations. Returns unsubscribe function.\n * @property {() => Record<string, unknown>} getState\n * Get a snapshot of current state values.\n * @property {(namespace: string, module: StoreModule) => void} registerModule\n * Register a namespaced module dynamically.\n * @property {(namespace: string) => void} unregisterModule\n * Unregister a namespaced module.\n * @property {(key: string, initialValue: unknown) => Signal<unknown>} createState\n * Create a new state signal dynamically.\n * @property {(name: string, actionFn: ActionFunction) => void} createAction\n * Register a new action dynamically.\n * @property {new <T>(value: T) => Signal<T>} signal\n * Signal class constructor for manual state creation.\n * @description The store API injected into component setup as `ctx.store`.\n * @example\n * app.component('Counter', {\n * setup({ store }) {\n * // Access reactive state\n * const count = store.state.count;\n *\n * // Dispatch actions\n * const increment = () => store.dispatch('increment');\n *\n * // Subscribe to changes\n * const unsub = store.subscribe((mutation) => {\n * console.log('State changed:', mutation.type);\n * });\n *\n * return { count, increment, onUnmount: () => unsub() };\n * },\n * template: (ctx) => `<button @click=\"increment\">${ctx.count.value}</button>`\n * });\n * @see StoreMutation - Mutation record structure.\n * @see StoreModule - Module definition for namespaces.\n */\n\n/**\n * @class 🏪 StorePlugin\n * @classdesc A powerful reactive state management plugin for Eleva that enables sharing\n * reactive data across the entire application. The Store plugin provides a centralized,\n * reactive data store that can be accessed from any component's setup function.\n *\n * Core Features:\n * - Centralized reactive state management using Eleva's signal system\n * - Global state accessibility through component setup functions\n * - Namespace support for organizing store modules\n * - Built-in persistence with localStorage/sessionStorage support\n * - Action-based state mutations with validation\n * - Subscription system for reactive updates\n * - DevTools integration for debugging\n * - Plugin architecture for extensibility\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n * app.use(StorePlugin, {\n * state: {\n * user: { name: \"John\", email: \"john@example.com\" },\n * counter: 0,\n * todos: []\n * },\n * actions: {\n * increment: (state) => state.counter.value++,\n * addTodo: (state, todo) => state.todos.value = [...state.todos.value, todo],\n * setUser: (state, user) => state.user.value = user\n * },\n * persistence: {\n * enabled: true,\n * key: \"myApp-store\",\n * storage: \"localStorage\"\n * }\n * });\n *\n * // Use store in components\n * app.component(\"Counter\", {\n * setup({ store }) {\n * return {\n * count: store.state.counter,\n * increment: () => store.dispatch(\"increment\"),\n * user: store.state.user\n * };\n * },\n * template: (ctx) => `\n * <div>\n * <p>Hello ${ctx.user.value.name}!</p>\n * <p>Count: ${ctx.count.value}</p>\n * <button @click=\"increment\">+</button>\n * </div>\n * `\n * });\n */\nexport const StorePlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"store\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.1.0\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description:\n \"Reactive state management for sharing data across the entire Eleva application\",\n\n /**\n * Installs the plugin into the Eleva instance.\n *\n * @public\n * @param {Eleva} eleva - The Eleva instance.\n * @param {StoreOptions} options - Plugin configuration options.\n * @param {Record<string, unknown>} [options.state={}] - Initial state object.\n * @param {Record<string, ActionFunction>} [options.actions={}] - Action functions for state mutations.\n * @param {Record<string, StoreModule>} [options.namespaces={}] - Namespaced modules for organizing store.\n * @param {StorePersistenceOptions} [options.persistence] - Persistence configuration.\n * @param {boolean} [options.persistence.enabled=false] - Enable state persistence.\n * @param {string} [options.persistence.key=\"eleva-store\"] - Storage key.\n * @param {'localStorage' | 'sessionStorage'} [options.persistence.storage=\"localStorage\"] - Storage type.\n * @param {string[]} [options.persistence.include] - Dot-path prefixes to persist (e.g., \"auth.user\")\n * @param {string[]} [options.persistence.exclude] - Dot-path prefixes to exclude (applies when include is empty).\n * @param {boolean} [options.devTools=false] - Enable development tools integration.\n * @param {(error: Error, context: string) => void} [options.onError=null] - Error handler function.\n * @returns {void}\n * @description\n * Installs the store and injects `store` into component setup context by wrapping\n * `eleva.mount` and `eleva._mountComponents`. Also exposes `eleva.store` and\n * helper methods (`eleva.dispatch`, `eleva.getState`, `eleva.subscribe`, `eleva.createAction`).\n * Uninstall restores the originals.\n *\n * @example\n * // Basic installation\n * app.use(StorePlugin, {\n * state: { count: 0, user: null },\n * actions: {\n * increment: (state) => state.count.value++,\n * setUser: (state, user) => state.user.value = user\n * }\n * });\n *\n * // Advanced installation with persistence and namespaces\n * app.use(StorePlugin, {\n * state: { theme: \"light\" },\n * namespaces: {\n * auth: {\n * state: { user: null, token: null },\n * actions: {\n * login: (state, { user, token }) => {\n * state.auth.user.value = user;\n * state.auth.token.value = token;\n * },\n * logout: (state) => {\n * state.auth.user.value = null;\n * state.auth.token.value = null;\n * }\n * }\n * }\n * },\n * persistence: {\n * enabled: true,\n * include: [\"theme\", \"auth.user\"]\n * }\n * });\n */\n install(eleva, options = {}) {\n const {\n state = {},\n actions = {},\n namespaces = {},\n persistence = {},\n devTools = false,\n onError = null,\n } = options;\n\n /**\n * @class Store\n * @classdesc Store instance that manages all state and provides the API.\n * @private\n */\n class Store {\n /**\n * Creates a new Store instance.\n * Initializes state signals, actions, persistence, and devtools integration.\n *\n * @constructor\n */\n constructor() {\n /** @type {Record<string, Signal | Record<string, unknown>>} */\n this.state = {};\n /** @type {Record<string, ActionFunction | Record<string, ActionFunction>>} */\n this.actions = {};\n /** @type {Set<SubscribeCallback>} */\n this.subscribers = new Set();\n /** @type {StoreMutation[]} */\n this.mutations = [];\n /** @type {{enabled: boolean, key: string, storage: string, include: string[]|null, exclude: string[]|null}} */\n this.persistence = {\n enabled: false,\n key: \"eleva-store\",\n storage: \"localStorage\",\n include: null,\n exclude: null,\n ...persistence,\n };\n /** @type {boolean} */\n this.devTools = devTools;\n /** @type {((error: Error, context: string) => void)|null} */\n this.onError = onError;\n\n this._initializeState(state, actions);\n this._initializeNamespaces(namespaces);\n this._loadPersistedState();\n this._setupDevTools();\n }\n\n /**\n * Initializes the root state and actions.\n * Creates reactive signals for each state property and copies actions.\n *\n * @private\n * @param {Record<string, unknown>} initialState - The initial state key-value pairs.\n * @param {Record<string, ActionFunction>} initialActions - The action functions to register.\n * @returns {void}\n */\n _initializeState(initialState, initialActions) {\n // Create reactive signals for each state property\n Object.entries(initialState).forEach(([key, value]) => {\n this.state[key] = new eleva.signal(value);\n });\n\n // Set up actions\n this.actions = { ...initialActions };\n }\n\n /**\n * Initializes namespaced modules.\n * Creates namespace objects and populates them with state signals and actions.\n *\n * @private\n * @param {Record<string, StoreModule>} namespaces - Map of namespace names to module definitions.\n * @returns {void}\n */\n _initializeNamespaces(namespaces) {\n Object.entries(namespaces).forEach(([namespace, module]) => {\n const { state: moduleState = {}, actions: moduleActions = {} } =\n module;\n\n // Create namespace object if it doesn't exist\n if (!this.state[namespace]) {\n this.state[namespace] = {};\n }\n if (!this.actions[namespace]) {\n this.actions[namespace] = {};\n }\n\n // Initialize namespaced state\n Object.entries(moduleState).forEach(([key, value]) => {\n this.state[namespace][key] = new eleva.signal(value);\n });\n\n // Set up namespaced actions\n this.actions[namespace] = { ...moduleActions };\n });\n }\n\n /**\n * Loads persisted state from storage.\n * Reads from localStorage/sessionStorage and applies values to state signals.\n * Does nothing if persistence is disabled or running in SSR environment.\n *\n * @private\n * @returns {void}\n */\n _loadPersistedState() {\n if (!this.persistence.enabled || typeof window === \"undefined\") {\n return;\n }\n\n try {\n const storage = window[this.persistence.storage];\n const persistedData = storage.getItem(this.persistence.key);\n\n if (persistedData) {\n const data = JSON.parse(persistedData);\n this._applyPersistedData(data);\n }\n } catch (error) {\n if (this.onError) {\n this.onError(error, \"Failed to load persisted state\");\n } else {\n console.warn(\n \"[StorePlugin] Failed to load persisted state:\",\n error\n );\n }\n }\n }\n\n /**\n * Applies persisted data to the current state.\n * Recursively updates signal values for paths that should be persisted.\n *\n * @private\n * @param {Record<string, unknown>} data - The persisted data object to apply.\n * @param {Record<string, unknown>} [currentState=this.state] - The current state object to update.\n * @param {string} [path=\"\"] - The current dot-notation path (for include/exclude filtering).\n * @returns {void}\n */\n _applyPersistedData(data, currentState = this.state, path = \"\") {\n Object.entries(data).forEach(([key, value]) => {\n const fullPath = path ? `${path}.${key}` : key;\n\n if (this._shouldPersist(fullPath)) {\n if (\n currentState[key] &&\n typeof currentState[key] === \"object\" &&\n \"value\" in currentState[key]\n ) {\n // This is a signal, update its value\n currentState[key].value = value;\n } else if (\n typeof value === \"object\" &&\n value !== null &&\n currentState[key]\n ) {\n // This is a nested object, recurse\n this._applyPersistedData(value, currentState[key], fullPath);\n }\n }\n });\n }\n\n /**\n * Determines if a state path should be persisted.\n * Checks against include/exclude filters configured in persistence options.\n *\n * @private\n * @param {string} path - The dot-notation path to check (e.g., \"auth.user\").\n * @returns {boolean} True if the path should be persisted, false otherwise.\n */\n _shouldPersist(path) {\n const { include, exclude } = this.persistence;\n\n if (include && include.length > 0) {\n return include.some((includePath) => path.startsWith(includePath));\n }\n\n if (exclude && exclude.length > 0) {\n return !exclude.some((excludePath) => path.startsWith(excludePath));\n }\n\n return true;\n }\n\n /**\n * Saves current state to storage.\n * Extracts persistable data and writes to localStorage/sessionStorage.\n * Does nothing if persistence is disabled or running in SSR environment.\n *\n * @private\n * @returns {void}\n */\n _saveState() {\n if (!this.persistence.enabled || typeof window === \"undefined\") {\n return;\n }\n\n try {\n const storage = window[this.persistence.storage];\n const dataToSave = this._extractPersistedData();\n storage.setItem(this.persistence.key, JSON.stringify(dataToSave));\n } catch (error) {\n if (this.onError) {\n this.onError(error, \"Failed to save state\");\n } else {\n console.warn(\"[StorePlugin] Failed to save state:\", error);\n }\n }\n }\n\n /**\n * Extracts data that should be persisted.\n * Recursively extracts signal values for paths that pass persistence filters.\n *\n * @private\n * @param {Record<string, unknown>} [currentState=this.state] - The state object to extract from.\n * @param {string} [path=\"\"] - The current dot-notation path (for include/exclude filtering).\n * @returns {Record<string, unknown>} The extracted data object with raw values (not signals).\n */\n _extractPersistedData(currentState = this.state, path = \"\") {\n const result = {};\n\n Object.entries(currentState).forEach(([key, value]) => {\n const fullPath = path ? `${path}.${key}` : key;\n\n if (this._shouldPersist(fullPath)) {\n if (value && typeof value === \"object\" && \"value\" in value) {\n // This is a signal, extract its value\n result[key] = value.value;\n } else if (typeof value === \"object\" && value !== null) {\n // This is a nested object, recurse\n const nestedData = this._extractPersistedData(value, fullPath);\n if (Object.keys(nestedData).length > 0) {\n result[key] = nestedData;\n }\n }\n }\n });\n\n return result;\n }\n\n /**\n * Sets up development tools integration.\n * Registers the store with Eleva DevTools if available and enabled.\n * Does nothing if devTools is disabled, running in SSR, or DevTools not installed.\n *\n * @private\n * @returns {void}\n */\n _setupDevTools() {\n if (\n !this.devTools ||\n typeof window === \"undefined\" ||\n !window.__ELEVA_DEVTOOLS__\n ) {\n return;\n }\n\n window.__ELEVA_DEVTOOLS__.registerStore(this);\n }\n\n /**\n * Dispatches an action to mutate the state.\n *\n * Execution flow:\n * 1. Retrieves the action function (supports namespaced actions like \"auth.login\")\n * 2. Records mutation for devtools/history (keeps last 100 mutations)\n * 3. Executes action with await (actions can be sync or async)\n * 4. Saves state if persistence is enabled\n * 5. Notifies all subscribers with (mutation, state)\n * 6. Notifies devtools if enabled\n *\n * @note Always returns a Promise regardless of whether the action is sync or async.\n * Subscriber callbacks that throw are caught and passed to onError handler.\n *\n * @async\n * @param {string} actionName - The name of the action to dispatch (supports dot notation for namespaces).\n * @param {unknown} payload - The payload to pass to the action.\n * @returns {Promise<unknown>} The result of the action (undefined if action returns nothing).\n * @throws {Error} If action is not found or action function throws.\n * @see subscribe - Listen for mutations triggered by dispatch.\n * @see getState - Get current state values.\n */\n async dispatch(actionName, payload) {\n try {\n const action = this._getAction(actionName);\n\n if (!action) {\n const error = new Error(`Action \"${actionName}\" not found`);\n if (this.onError) {\n this.onError(error, actionName);\n }\n throw error;\n }\n\n const mutation = {\n type: actionName,\n payload,\n timestamp: Date.now(),\n };\n\n // Record mutation for devtools\n this.mutations.push(mutation);\n if (this.mutations.length > 100) {\n this.mutations.shift(); // Keep only last 100 mutations\n }\n\n // Execute the action\n const result = await action.call(null, this.state, payload);\n\n // Save state if persistence is enabled\n this._saveState();\n\n // Notify subscribers\n this.subscribers.forEach((callback) => {\n try {\n callback(mutation, this.state);\n } catch (error) {\n if (this.onError) {\n this.onError(error, \"Subscriber callback failed\");\n }\n }\n });\n\n // Notify devtools\n if (\n this.devTools &&\n typeof window !== \"undefined\" &&\n window.__ELEVA_DEVTOOLS__\n ) {\n window.__ELEVA_DEVTOOLS__.notifyMutation(mutation, this.state);\n }\n\n return result;\n } catch (error) {\n if (this.onError) {\n this.onError(error, `Action dispatch failed: ${actionName}`);\n }\n throw error;\n }\n }\n\n /**\n * Gets an action by name (supports namespaced actions).\n * Traverses the actions object using dot-notation path segments.\n *\n * @private\n * @param {string} actionName - The action name, supports dot notation for namespaces (e.g., \"auth.login\").\n * @returns {ActionFunction | null} The action function if found and is a function, null otherwise.\n */\n _getAction(actionName) {\n const parts = actionName.split(\".\");\n let current = this.actions;\n\n for (const part of parts) {\n if (current[part] === undefined) {\n return null;\n }\n current = current[part];\n }\n\n return typeof current === \"function\" ? current : null;\n }\n\n /**\n * Subscribes to store mutations.\n * Callback is invoked after every successful action dispatch.\n *\n * @param {SubscribeCallback} callback\n * Called after each mutation with:\n * - mutation.type: The action name that was dispatched\n * - mutation.payload: The payload passed to the action\n * - mutation.timestamp: When the mutation occurred (Date.now())\n * - state: The current state object (contains Signals)\n * @returns {() => void} Unsubscribe function. Call to stop receiving notifications.\n * @throws {Error} If callback is not a function.\n * @see dispatch - Triggers mutations that notify subscribers.\n */\n subscribe(callback) {\n if (typeof callback !== \"function\") {\n throw new Error(\"Subscribe callback must be a function\");\n }\n\n this.subscribers.add(callback);\n\n // Return unsubscribe function\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n /**\n * Gets current state values (not signals).\n *\n * @note When persistence include/exclude filters are configured,\n * this returns only the filtered subset of state.\n * @returns {Record<string, unknown>} The current state values (filtered by persistence config if set).\n * @see replaceState - Set state values.\n * @see subscribe - Listen for state changes.\n */\n getState() {\n return this._extractPersistedData();\n }\n\n /**\n * Replaces state values (useful for testing or state hydration).\n *\n * @note When persistence include/exclude filters are configured,\n * this only updates the filtered subset of state.\n * @param {Record<string, unknown>} newState - The new state object.\n * @returns {void}\n * @see getState - Get current state values.\n */\n replaceState(newState) {\n this._applyPersistedData(newState);\n this._saveState();\n }\n\n /**\n * Clears persisted state from storage.\n * Does nothing if persistence is disabled or running in SSR.\n * @returns {void}\n */\n clearPersistedState() {\n if (!this.persistence.enabled || typeof window === \"undefined\") {\n return;\n }\n\n try {\n const storage = window[this.persistence.storage];\n storage.removeItem(this.persistence.key);\n } catch (error) {\n if (this.onError) {\n this.onError(error, \"Failed to clear persisted state\");\n }\n }\n }\n\n /**\n * Registers a new namespaced module at runtime.\n * Logs a warning if the namespace already exists.\n * Module state is nested under `state[namespace]` and actions under `actions[namespace]`.\n * @param {string} namespace - The namespace for the module.\n * @param {StoreModule} module - The module definition.\n * @param {Record<string, unknown>} module.state - The module's initial state.\n * @param {Record<string, ActionFunction>} module.actions - The module's actions.\n * @returns {void}\n */\n registerModule(namespace, module) {\n if (this.state[namespace] || this.actions[namespace]) {\n console.warn(`[StorePlugin] Module \"${namespace}\" already exists`);\n return;\n }\n\n // Initialize the module\n this.state[namespace] = {};\n this.actions[namespace] = {};\n\n const namespaces = { [namespace]: module };\n this._initializeNamespaces(namespaces);\n\n this._saveState();\n }\n\n /**\n * Unregisters a namespaced module.\n * Logs a warning if the namespace doesn't exist.\n * Removes both state and actions under the namespace.\n * @param {string} namespace - The namespace to unregister.\n * @returns {void}\n */\n unregisterModule(namespace) {\n if (!this.state[namespace] && !this.actions[namespace]) {\n console.warn(`[StorePlugin] Module \"${namespace}\" does not exist`);\n return;\n }\n\n delete this.state[namespace];\n delete this.actions[namespace];\n this._saveState();\n }\n\n /**\n * Creates a new reactive state property at runtime.\n *\n * @param {string} key - The state key.\n * @param {*} initialValue - The initial value.\n * @returns {Signal} The created signal, or existing signal if key exists.\n */\n createState(key, initialValue) {\n if (this.state[key]) {\n return this.state[key]; // Return existing state\n }\n\n this.state[key] = new eleva.signal(initialValue);\n this._saveState();\n return this.state[key];\n }\n\n /**\n * Creates a new action at runtime.\n * Overwrites existing action if name already exists.\n * Supports dot-notation for namespaced actions (e.g., \"auth.login\").\n * @param {string} name - The action name (supports dot notation for namespaces).\n * @param {ActionFunction} actionFn - The action function (receives state and payload).\n * @returns {void}\n * @throws {Error} If actionFn is not a function.\n * @example\n * // Root-level action\n * store.createAction(\"increment\", (state) => state.count.value++);\n *\n * // Namespaced action\n * store.createAction(\"auth.login\", async (state, credentials) => {\n * // ... login logic\n * });\n */\n createAction(name, actionFn) {\n if (typeof actionFn !== \"function\") {\n throw new Error(\"Action must be a function\");\n }\n\n // Fast path: no dot means simple action (avoids array allocation)\n if (name.indexOf(\".\") === -1) {\n this.actions[name] = actionFn;\n return;\n }\n\n // Namespaced action, traverse/create nested structure\n const parts = name.split(\".\");\n const lastIndex = parts.length - 1;\n let current = this.actions;\n\n for (let i = 0; i < lastIndex; i++) {\n current = current[parts[i]] || (current[parts[i]] = {});\n }\n current[parts[lastIndex]] = actionFn;\n }\n }\n\n // Create the store instance\n const store = new Store();\n\n // Store the original mount method to override it\n const originalMount = eleva.mount;\n\n /**\n * Overridden mount method that injects store context into components.\n * Wraps the original mount to add `ctx.store` to the component's setup context.\n *\n * @param {HTMLElement} container - The DOM element where the component will be mounted.\n * @param {string | ComponentDefinition} compName - Component name or definition.\n * @param {ComponentProps} [props={}] - Optional properties to pass to the component.\n * @returns {Promise<MountResult>} The mount result.\n */\n eleva.mount = async (container, compName, props = {}) => {\n // Get the component definition\n const componentDef =\n typeof compName === \"string\"\n ? eleva._components.get(compName) || compName\n : compName;\n\n if (!componentDef) {\n return await originalMount.call(eleva, container, compName, props);\n }\n\n // Create a wrapped component that injects store into setup\n const wrappedComponent = {\n ...componentDef,\n async setup(ctx) {\n /** @type {StoreApi} */\n ctx.store = {\n // Core store functionality\n state: store.state,\n dispatch: store.dispatch.bind(store),\n subscribe: store.subscribe.bind(store),\n getState: store.getState.bind(store),\n\n // Module management\n registerModule: store.registerModule.bind(store),\n unregisterModule: store.unregisterModule.bind(store),\n\n // Utilities for dynamic state/action creation\n createState: store.createState.bind(store),\n createAction: store.createAction.bind(store),\n\n // Access to signal constructor for manual state creation\n signal: eleva.signal,\n };\n\n // Call original setup if it exists\n const originalSetup = componentDef.setup;\n const result = originalSetup ? await originalSetup(ctx) : {};\n\n return result;\n },\n };\n\n // Call original mount with wrapped component\n return await originalMount.call(\n eleva,\n container,\n wrappedComponent,\n props\n );\n };\n\n // Override _mountComponents to ensure child components also get store context\n const originalMountComponents = eleva._mountComponents;\n\n /**\n * Overridden _mountComponents method that injects store context into child components.\n * Wraps each child component's setup function to add `ctx.store` before mounting.\n *\n * @param {HTMLElement} container - The parent container element.\n * @param {ChildrenMap} children - Map of selectors to component definitions.\n * @param {MountResult[]} childInstances - Array to store mounted instances.\n * @param {ComponentContext & SetupResult} context - Parent component context.\n * @returns {Promise<void>}\n */\n eleva._mountComponents = async (\n container,\n children,\n childInstances,\n context\n ) => {\n // Create wrapped children with store injection\n const wrappedChildren = {};\n\n for (const [selector, childComponent] of Object.entries(children)) {\n const componentDef =\n typeof childComponent === \"string\"\n ? eleva._components.get(childComponent) || childComponent\n : childComponent;\n\n if (componentDef && typeof componentDef === \"object\") {\n wrappedChildren[selector] = {\n ...componentDef,\n async setup(ctx) {\n /** @type {StoreApi} */\n ctx.store = {\n // Core store functionality\n state: store.state,\n dispatch: store.dispatch.bind(store),\n subscribe: store.subscribe.bind(store),\n getState: store.getState.bind(store),\n\n // Module management\n registerModule: store.registerModule.bind(store),\n unregisterModule: store.unregisterModule.bind(store),\n\n // Utilities for dynamic state/action creation\n createState: store.createState.bind(store),\n createAction: store.createAction.bind(store),\n\n // Access to signal constructor for manual state creation\n signal: eleva.signal,\n };\n\n // Call original setup if it exists\n const originalSetup = componentDef.setup;\n const result = originalSetup ? await originalSetup(ctx) : {};\n\n return result;\n },\n };\n } else {\n wrappedChildren[selector] = childComponent;\n }\n }\n\n // Call original _mountComponents with wrapped children\n return await originalMountComponents.call(\n eleva,\n container,\n wrappedChildren,\n childInstances,\n context\n );\n };\n\n // Expose store instance and utilities on the Eleva instance\n /** @type {StoreApi} */\n eleva.store = store;\n\n /**\n * Expose utility methods on the Eleva instance.\n * These are top-level helpers (e.g., `eleva.dispatch`) in addition to `eleva.store`.\n */\n /** @type {(name: string, actionFn: ActionFunction) => void} */\n eleva.createAction = (name, actionFn) => {\n store.createAction(name, actionFn);\n };\n\n /** @type {DispatchFunction} */\n eleva.dispatch = (actionName, payload) => {\n return store.dispatch(actionName, payload);\n };\n\n /** @type {() => Record<string, unknown>} */\n eleva.getState = () => {\n return store.getState();\n };\n\n /** @type {(callback: SubscribeCallback) => () => void} */\n eleva.subscribe = (callback) => {\n return store.subscribe(callback);\n };\n\n // Store original methods for cleanup\n eleva._originalMount = originalMount;\n eleva._originalMountComponents = originalMountComponents;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance.\n *\n * @public\n * @param {Eleva} eleva - The Eleva instance.\n * @returns {void}\n * @description\n * Restores the original Eleva methods and removes all plugin-specific\n * functionality. This method should be called when the plugin is no\n * longer needed.\n * Also removes `eleva.store` and top-level helpers (`eleva.dispatch`,\n * `eleva.getState`, `eleva.subscribe`, `eleva.createAction`).\n *\n * @example\n * // Uninstall the plugin\n * StorePlugin.uninstall(app);\n */\n uninstall(eleva) {\n // Restore original mount method\n if (eleva._originalMount) {\n eleva.mount = eleva._originalMount;\n delete eleva._originalMount;\n }\n\n // Restore original _mountComponents method\n if (eleva._originalMountComponents) {\n eleva._mountComponents = eleva._originalMountComponents;\n delete eleva._originalMountComponents;\n }\n\n // Remove store instance and utility methods\n if (eleva.store) {\n delete eleva.store;\n }\n if (eleva.createAction) {\n delete eleva.createAction;\n }\n if (eleva.dispatch) {\n delete eleva.dispatch;\n }\n if (eleva.getState) {\n delete eleva.getState;\n }\n if (eleva.subscribe) {\n delete eleva.subscribe;\n }\n },\n};\n\n// Short name export for convenience\nexport { StorePlugin as Store };\n"],"names":["CAMEL_RE","AttrPlugin","name","version","description","install","eleva","options","enableAria","enableData","enableBoolean","enableDynamic","updateAttributes","oldEl","newEl","oldAttrs","attributes","newAttrs","i","length","value","startsWith","getAttribute","prop","slice","replace","_","l","toUpperCase","setAttribute","dataset","Object","getOwnPropertyDescriptor","getPrototypeOf","elementProps","getOwnPropertyNames","matchingProp","find","p","toLowerCase","includes","descriptor","hasProperty","isBoolean","get","call","boolValue","removeAttribute","hasAttribute","renderer","originalPatchNode","_patchNode","_originalPatchNode","oldNode","newNode","_eleva_instance","nodeType","Node","TEXT_NODE","nodeValue","ELEMENT_NODE","_diff","plugins","Map","set","updateElementAttributes","uninstall","delete","CoreErrorHandler","handle","error","context","details","message","formattedError","Error","originalError","console","warn","log","Router","_validateOptions","mode","errorHandler","_processRoutes","routes","processedRoutes","route","push","segments","_parsePathIntoSegments","path","normalizedPath","split","filter","Boolean","map","segment","paramName","substring","type","_findViewElement","container","selector","viewSelector","querySelector","start","isStarted","window","document","mount","mountSelector","handler","_handleRouteChange","addEventListener","eventListeners","removeEventListener","isReady","emitter","emit","destroy","plugin","values","forEach","cleanup","currentLayout","unmount","stop","navigate","location","params","target","_buildPath","query","keys","queryString","URLSearchParams","toString","_isSameRoute","navigationSuccessful","_proceedWithNavigation","currentNavId","_navigationId","_isNavigating","state","historyMethod","newUrl","pathname","search","history","replaceState","hash","url","_buildQueryUrl","queueMicrotask","urlParams","queryParam","current","currentRoute","targetPath","targetQuery","_parseQuery","JSON","stringify","result","key","entries","encodedValue","encodeURIComponent","String","RegExp","isPopState","from","toLocation","_getCurrentLocation","fullUrl","currentUrl","href","fullPath","toMatch","_matchRoute","notFoundRoute","pathMatch","decodeURIComponent","to","meta","matched","canNavigate","_runGuards","_scrollPositions","x","scrollX","pageXOffset","y","scrollY","pageYOffset","resolveContext","layoutComponent","pageComponent","cancelled","redirectTo","_resolveComponents","toLayout","layout","globalLayout","fromLayout","tryUnmount","instance","currentView","afterLeave","previousRoute","currentParams","currentQuery","renderContext","_render","scrollContext","savedPosition","afterEnter","navContext","guards","_beforeEachGuards","beforeLeave","beforeEnter","guard","_resolveStringComponent","def","componentDef","_components","componentName","availableComponents","Array","_resolveFunctionComponent","funcStr","isAsyncImport","default","function","_validateComponentDefinition","definition","template","_resolveComponent","undefined","effectiveLayout","Promise","all","component","mountEl","layoutInstance","_wrapComponentWithChildren","viewEl","viewInstance","_createRouteGetter","property","defaultValue","_wrapComponent","originalSetup","setup","self","ctx","router","bind","previous","wrappedComponent","children","wrappedChildren","childComponent","pathSegments","isMatch","routeSegment","pathSegment","addRoute","parentRoute","hasRoute","processedRoute","wildcardIndex","findIndex","r","splice","removeRoute","index","removedRoute","some","getRoutes","getRoute","onBeforeEach","indexOf","onAfterEnter","hook","on","onAfterLeave","onAfterEach","onError","use","has","existingPlugin","getPlugins","getPlugin","removePlugin","setErrorHandler","signal","RouterPlugin","isArray","register","Math","random","autoStart","getCurrentRoute","getRouteParams","getRouteQuery","StorePlugin","actions","namespaces","persistence","devTools","Store","_initializeState","initialState","initialActions","_initializeNamespaces","namespace","module","moduleState","moduleActions","_loadPersistedState","enabled","storage","persistedData","getItem","data","parse","_applyPersistedData","currentState","_shouldPersist","include","exclude","includePath","excludePath","_saveState","dataToSave","_extractPersistedData","setItem","nestedData","_setupDevTools","__ELEVA_DEVTOOLS__","registerStore","dispatch","actionName","payload","action","_getAction","mutation","timestamp","Date","now","mutations","shift","subscribers","callback","notifyMutation","parts","part","subscribe","add","getState","newState","clearPersistedState","removeItem","registerModule","unregisterModule","createState","initialValue","createAction","actionFn","lastIndex","Set","store","originalMount","compName","props","originalMountComponents","_mountComponents","childInstances","_originalMount","_originalMountComponents"],"mappings":";AAEA;;;AAGC;AAGD;AACA;AAEA;AACA;AACA;AAEA;;;AAGC;AAGD;AACA;AAEA;;;;;;;;;;;;;;;;;;;;AAwBC,IACD,MAAMA,QAAAA,GAAW,WAAA;AAEjB;;;;;;;;;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AA,CAAMwX,wBAAwB,GAAGJ,uBAAAA;AACnC,IAAA,CAAA;AAEA;;;;;;;;;;;;;;;;AAgBC,MACDxT,WAAU5D,KAAK,EAAA;;QAEb,IAAIA,KAAAA,CAAMuX,cAAc,EAAE;YACxBvX,KAAAA,CAAMwG,KAAK,GAAGxG,KAAAA,CAAMuX,cAAc;AAClC,YAAA,OAAOvX,MAAMuX,cAAc;AAC7B,QAAA;;QAGA,IAAIvX,KAAAA,CAAMwX,wBAAwB,EAAE;YAClCxX,KAAAA,CAAMqX,gBAAgB,GAAGrX,KAAAA,CAAMwX,wBAAwB;AACvD,YAAA,OAAOxX,MAAMwX,wBAAwB;AACvC,QAAA;;QAGA,IAAIxX,KAAAA,CAAMgX,KAAK,EAAE;AACf,YAAA,OAAOhX,MAAMgX,KAAK;AACpB,QAAA;QACA,IAAIhX,KAAAA,CAAM4W,YAAY,EAAE;AACtB,YAAA,OAAO5W,MAAM4W,YAAY;AAC3B,QAAA;QACA,IAAI5W,KAAAA,CAAMkV,QAAQ,EAAE;AAClB,YAAA,OAAOlV,MAAMkV,QAAQ;AACvB,QAAA;QACA,IAAIlV,KAAAA,CAAMoW,QAAQ,EAAE;AAClB,YAAA,OAAOpW,MAAMoW,QAAQ;AACvB,QAAA;QACA,IAAIpW,KAAAA,CAAMkW,SAAS,EAAE;AACnB,YAAA,OAAOlW,MAAMkW,SAAS;AACxB,QAAA;AACF,IAAA;AACF;;;;"}
1
+ {"version":3,"file":"eleva-plugins.js","sources":["../src/plugins/Attr.js","../src/plugins/Router.js","../src/plugins/Store.js"],"sourcesContent":["\"use strict\";\n\n/**\n * @module eleva/plugins/attr\n * @fileoverview Attribute plugin providing ARIA, data, boolean, and dynamic attribute handling.\n */\n\n// ============================================================================\n// TYPE DEFINITIONS\n// ============================================================================\n\n// -----------------------------------------------------------------------------\n// External Type Imports\n// -----------------------------------------------------------------------------\n\n/**\n * Type imports from the Eleva core library.\n * @typedef {import('eleva').Eleva} Eleva\n */\n\n// -----------------------------------------------------------------------------\n// Attr Type Definitions\n// -----------------------------------------------------------------------------\n\n/**\n * Configuration options for the AttrPlugin.\n * @typedef {Object} AttrPluginOptions\n * @property {boolean} [enableAria=true]\n * Enable ARIA attribute handling.\n * @property {boolean} [enableData=true]\n * Enable data attribute handling.\n * @property {boolean} [enableBoolean=true]\n * Enable boolean attribute handling.\n * @property {boolean} [enableDynamic=true]\n * Enable dynamic property detection.\n * @description Configuration options passed to AttrPlugin.install().\n */\n\n/**\n * Function signature for attribute update operations.\n * @typedef {(oldEl: HTMLElement, newEl: HTMLElement) => void} AttributeUpdateFunction\n * @description Updates attributes on oldEl to match newEl's attributes.\n */\n\n/**\n * A regular expression to match hyphenated lowercase letters.\n * @private\n * @type {RegExp}\n */\nconst CAMEL_RE = /-([a-z])/g;\n\n/**\n * @class 🎯 AttrPlugin\n * @classdesc A plugin that provides advanced attribute handling for Eleva components.\n * This plugin extends the renderer with sophisticated attribute processing including:\n * - ARIA attribute handling with proper property mapping\n * - Data attribute management\n * - Boolean attribute processing\n * - Dynamic property detection and mapping\n * - Attribute cleanup and removal\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n * app.use(AttrPlugin);\n *\n * // Use advanced attributes in components\n * app.component(\"myComponent\", {\n * template: (ctx) => `\n * <button\n * aria-expanded=\"${ctx.isExpanded.value}\"\n * data-user-id=\"${ctx.userId.value}\"\n * disabled=\"${ctx.isLoading.value}\"\n * class=\"btn ${ctx.variant.value}\"\n * >\n * ${ctx.text.value}\n * </button>\n * `\n * });\n */\nexport const AttrPlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"attr\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.1.1\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description: \"Advanced attribute handling for Eleva components\",\n\n /**\n * Installs the plugin into the Eleva instance.\n *\n * @public\n * Method wrapping behavior:\n * - Stores original `_patchNode` in `renderer._originalPatchNode`\n * - Overrides `renderer._patchNode` to use enhanced attribute handling\n * - Adds `renderer.updateAttributes` and `eleva.updateElementAttributes` helpers\n * - Call `uninstall()` to restore original behavior\n *\n * @param {Eleva} eleva - The Eleva instance to enhance.\n * @param {AttrPluginOptions} options - Plugin configuration options.\n * @param {boolean} [options.enableAria=true] - Enable ARIA attribute handling.\n * Maps aria-* attributes to DOM properties (e.g., aria-expanded → ariaExpanded).\n * @param {boolean} [options.enableData=true] - Enable data attribute handling.\n * Syncs data-* attributes with element.dataset for consistent access.\n * @param {boolean} [options.enableBoolean=true] - Enable boolean attribute handling.\n * Treats empty strings and attribute names as true, \"false\" string as false.\n * @param {boolean} [options.enableDynamic=true] - Enable dynamic property detection.\n * Searches element prototype chain for property matches (useful for custom elements).\n * @returns {void}\n * @example\n * // Basic installation with defaults\n * app.use(AttrPlugin);\n *\n * @example\n * // Custom configuration\n * app.use(AttrPlugin, {\n * enableAria: true,\n * enableData: true,\n * enableBoolean: true,\n * enableDynamic: false // Disable for performance\n * });\n *\n * @example\n * // Using ARIA attributes in templates\n * template: (ctx) => `\n * <div role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"title\">\n * <h2 id=\"title\">Modal Title</h2>\n * <button aria-expanded=\"${ctx.isOpen.value}\">Toggle</button>\n * </div>\n * `\n * @see uninstall - Remove the plugin and restore original behavior.\n */\n install(eleva, options = {}) {\n const {\n enableAria = true,\n enableData = true,\n enableBoolean = true,\n enableDynamic = true,\n } = options;\n\n /**\n * Updates the attributes of an element to match a new element's attributes.\n *\n * Processing order:\n * 1. Skip event attributes (@click, @input) - handled by Eleva's event system\n * 2. Skip unchanged attributes - optimization\n * 3. ARIA attributes (aria-*): Map to DOM properties (aria-expanded → ariaExpanded)\n * 4. Data attributes (data-*): Update both dataset and attribute\n * 5. Boolean attributes: Handle empty string as true, \"false\" as false\n * 6. Other attributes: Map to properties with dynamic detection for custom elements\n * 7. Remove old attributes not present in new element\n *\n * Dynamic property detection (when enableDynamic=true):\n * - Checks if property exists directly on element\n * - Searches element's prototype chain for case-insensitive matches\n * - Enables compatibility with custom elements and Web Components\n *\n * @inner\n * @param {HTMLElement} oldEl - The original element to update (modified in-place).\n * @param {HTMLElement} newEl - The reference element with desired attributes.\n * @returns {void}\n */\n const updateAttributes = (oldEl, newEl) => {\n const oldAttrs = oldEl.attributes;\n const newAttrs = newEl.attributes;\n\n // Process new attributes\n for (let i = 0; i < newAttrs.length; i++) {\n const { name, value } = newAttrs[i];\n\n // Skip event attributes (handled by event system)\n if (name.startsWith(\"@\")) continue;\n\n // Skip if attribute hasn't changed\n if (oldEl.getAttribute(name) === value) continue;\n\n // Handle ARIA attributes\n if (enableAria && name.startsWith(\"aria-\")) {\n const prop =\n \"aria\" + name.slice(5).replace(CAMEL_RE, (_, l) => l.toUpperCase());\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n // Handle data attributes\n else if (enableData && name.startsWith(\"data-\")) {\n oldEl.dataset[name.slice(5)] = value;\n oldEl.setAttribute(name, value);\n }\n // Handle other attributes\n else {\n let prop = name.replace(CAMEL_RE, (_, l) => l.toUpperCase());\n\n // Dynamic property detection\n if (\n enableDynamic &&\n !(prop in oldEl) &&\n !Object.getOwnPropertyDescriptor(Object.getPrototypeOf(oldEl), prop)\n ) {\n const elementProps = Object.getOwnPropertyNames(\n Object.getPrototypeOf(oldEl)\n );\n const matchingProp = elementProps.find(\n (p) =>\n p.toLowerCase() === name.toLowerCase() ||\n p.toLowerCase().includes(name.toLowerCase()) ||\n name.toLowerCase().includes(p.toLowerCase())\n );\n\n if (matchingProp) {\n prop = matchingProp;\n }\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(oldEl),\n prop\n );\n const hasProperty = prop in oldEl || descriptor;\n\n if (hasProperty) {\n // Boolean attribute handling\n if (enableBoolean) {\n const isBoolean =\n typeof oldEl[prop] === \"boolean\" ||\n (descriptor?.get &&\n typeof descriptor.get.call(oldEl) === \"boolean\");\n\n if (isBoolean) {\n const boolValue =\n value !== \"false\" &&\n (value === \"\" || value === prop || value === \"true\");\n oldEl[prop] = boolValue;\n\n if (boolValue) {\n oldEl.setAttribute(name, \"\");\n } else {\n oldEl.removeAttribute(name);\n }\n } else {\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n } else {\n oldEl[prop] = value;\n oldEl.setAttribute(name, value);\n }\n } else {\n oldEl.setAttribute(name, value);\n }\n }\n }\n\n // Remove old attributes that are no longer present\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const name = oldAttrs[i].name;\n if (!newEl.hasAttribute(name)) {\n oldEl.removeAttribute(name);\n }\n }\n };\n\n // Extend the renderer with the advanced attribute handler\n if (eleva.renderer) {\n eleva.renderer.updateAttributes = updateAttributes;\n\n // Store the original _patchNode method\n const originalPatchNode = eleva.renderer._patchNode;\n eleva.renderer._originalPatchNode = originalPatchNode;\n\n /**\n * Overridden _patchNode method that uses enhanced attribute handling.\n * Delegates to `updateAttributes` instead of the basic `_updateAttributes`.\n *\n * @param {Node} oldNode - The original DOM node to update.\n * @param {Node} newNode - The new DOM node with desired state.\n * @returns {void}\n */\n eleva.renderer._patchNode = function (oldNode, newNode) {\n if (oldNode?._eleva_instance) return;\n\n if (oldNode.nodeType === Node.TEXT_NODE) {\n if (oldNode.nodeValue !== newNode.nodeValue) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n } else if (oldNode.nodeType === Node.ELEMENT_NODE) {\n // Use advanced attribute handler instead of basic _updateAttributes\n updateAttributes(oldNode, newNode);\n this._diff(oldNode, newNode);\n }\n };\n }\n\n // Add plugin metadata to the Eleva instance\n if (!eleva.plugins) {\n eleva.plugins = new Map();\n }\n eleva.plugins.set(this.name, {\n name: this.name,\n version: this.version,\n description: this.description,\n options,\n });\n\n // Add utility methods for manual attribute updates\n /** @type {AttributeUpdateFunction} */\n eleva.updateElementAttributes = updateAttributes;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance.\n *\n * @public\n * @param {Eleva} eleva - The Eleva instance.\n * @returns {void}\n * @description\n * Restores the original renderer patching behavior and removes\n * `eleva.updateElementAttributes`.\n * @example\n * // Uninstall the plugin\n * AttrPlugin.uninstall(app);\n * @see install - Install the plugin.\n */\n uninstall(eleva) {\n // Restore original _patchNode method if it exists\n if (eleva.renderer && eleva.renderer._originalPatchNode) {\n eleva.renderer._patchNode = eleva.renderer._originalPatchNode;\n delete eleva.renderer._originalPatchNode;\n }\n\n // Remove plugin metadata\n if (eleva.plugins) {\n eleva.plugins.delete(this.name);\n }\n\n // Remove utility methods\n delete eleva.updateElementAttributes;\n },\n};\n\n// Short name export for convenience\nexport { AttrPlugin as Attr };\n","\"use strict\";\n\n/**\n * @module eleva/plugins/router\n * @fileoverview Client-side router plugin with hash, history, and query modes,\n * navigation guards, and lifecycle hooks.\n */\n\n// ============================================================================\n// TYPE DEFINITIONS\n// ============================================================================\n\n// -----------------------------------------------------------------------------\n// External Type Imports\n// -----------------------------------------------------------------------------\n\n/**\n * Type imports from the Eleva core library.\n * @typedef {import('eleva').Eleva} Eleva\n * @typedef {import('eleva').ComponentDefinition} ComponentDefinition\n * @typedef {import('eleva').Emitter} Emitter\n * @typedef {import('eleva').MountResult} MountResult\n * @typedef {import('eleva').UnsubscribeFunction} UnsubscribeFunction\n */\n\n/**\n * Generic type import.\n * @template T\n * @typedef {import('eleva').Signal<T>} Signal\n */\n\n// -----------------------------------------------------------------------------\n// Router Events\n// -----------------------------------------------------------------------------\n\n/**\n * Fired when the router initialization completes successfully.\n * @event router:ready\n * @type {Router}\n */\n\n/**\n * Fired when an error occurs during navigation or route handling.\n * @event router:error\n * @type {Error}\n */\n\n/**\n * Fired when no matching route is found for the requested path.\n * @event router:notFound\n * @type {{to: RouteLocation, from: RouteLocation | null, path: string}}\n */\n\n/**\n * Fired before guards run, allowing plugins to block or redirect navigation.\n * @event router:beforeEach\n * @type {NavigationContext}\n */\n\n/**\n * Fired before component resolution, allowing plugins to modify the resolve context.\n * @event router:beforeResolve\n * @type {ResolveContext}\n */\n\n/**\n * Fired after components are resolved successfully.\n * @event router:afterResolve\n * @type {ResolveContext}\n */\n\n/**\n * Fired after leaving the previous route.\n * @event router:afterLeave\n * @type {{to: RouteLocation, from: RouteLocation}}\n */\n\n/**\n * Fired before DOM rendering begins.\n * @event router:beforeRender\n * @type {RenderContext}\n */\n\n/**\n * Fired after DOM rendering completes.\n * @event router:afterRender\n * @type {RenderContext}\n */\n\n/**\n * Fired after render for scroll behavior handling.\n * @event router:scroll\n * @type {ScrollContext}\n */\n\n/**\n * Fired after entering the new route.\n * @event router:afterEnter\n * @type {{to: RouteLocation, from: RouteLocation | null}}\n */\n\n/**\n * Fired after navigation completes successfully.\n * @event router:afterEach\n * @type {{to: RouteLocation, from: RouteLocation | null}}\n */\n\n/**\n * Fired when a route is dynamically added.\n * @event router:routeAdded\n * @type {RouteDefinition}\n */\n\n/**\n * Fired when a route is dynamically removed.\n * @event router:routeRemoved\n * @type {RouteDefinition}\n */\n\n// -----------------------------------------------------------------------------\n// Router Data Types\n// -----------------------------------------------------------------------------\n\n/**\n * The routing mode determines how the router manages URL state.\n * - `hash`: Uses URL hash (e.g., `/#/path`) - works without server config\n * - `history`: Uses HTML5 History API (e.g., `/path`) - requires server config\n * - `query`: Uses query parameters (e.g., `?view=/path`) - useful for embedded apps\n * @typedef {'hash' | 'history' | 'query'} RouterMode\n */\n\n/**\n * Route parameters extracted from the URL path.\n * @typedef {Record<string, string>} RouteParams\n * @description Key-value pairs extracted from dynamic route segments (e.g., `/users/:id` → `{ id: '123' }`).\n */\n\n/**\n * Query parameters from the URL query string.\n * @typedef {Record<string, string>} QueryParams\n * @description Key-value pairs from the URL query string (e.g., `?page=1&sort=name`).\n */\n\n/**\n * Navigation input parameters supporting multiple value types.\n * @typedef {Record<string, string | number | boolean>} NavigationParams\n * @description Parameters passed to navigation functions, automatically converted to strings in URLs.\n */\n\n/**\n * Function signature for programmatic navigation.\n * @typedef {(location: string | NavigationTarget, params?: NavigationParams) => Promise<boolean>} NavigateFunction\n * @description Returns true if navigation succeeded, false if blocked by a guard.\n */\n\n/**\n * Router configuration options.\n * @typedef {Object} RouterOptions\n * @property {RouterMode} [mode='hash']\n * The routing mode to use.\n * @property {string} [queryParam='view']\n * Query parameter name for 'query' mode.\n * @property {string} [viewSelector='view']\n * Base selector for the view element.\n * @property {string} mount\n * CSS selector for the mount point element.\n * @property {RouteDefinition[]} routes\n * Array of route definitions.\n * @property {RouteComponent} [globalLayout]\n * Default layout for all routes.\n * @property {NavigationGuard} [onBeforeEach]\n * Global navigation guard.\n * @property {boolean} [autoStart=true]\n * Whether to start the router automatically.\n * @description Configuration options for the Router plugin.\n */\n\n/**\n * Object describing a navigation target for `router.navigate()`.\n * @typedef {Object} NavigationTarget\n * @property {string} path\n * The target path (can include params like '/users/:id').\n * @property {NavigationParams} [params]\n * Route parameters to inject.\n * @property {NavigationParams} [query]\n * Query parameters to append.\n * @property {boolean} [replace=false]\n * Whether to replace current history entry.\n * @property {unknown} [state]\n * History state to pass.\n * @description Object describing a navigation target for `router.navigate()`.\n */\n\n/**\n * Saved scroll position.\n * @typedef {Object} ScrollPosition\n * @property {number} x\n * Horizontal scroll position.\n * @property {number} y\n * Vertical scroll position.\n * @description Represents a saved scroll position.\n */\n\n/**\n * Internal representation of a parsed route path segment.\n * @typedef {Object} RouteSegment\n * @property {'static' | 'param'} type\n * The segment type.\n * @property {string} [value]\n * The segment value (static segments).\n * @property {string} [name]\n * The parameter name (param segments).\n * @description Internal representation of a parsed route path segment.\n * @private\n */\n\n/**\n * Result of matching a path against route definitions.\n * @typedef {Object} RouteMatch\n * @property {RouteDefinition} route\n * The matched route definition.\n * @property {RouteParams} params\n * The extracted route parameters.\n * @description Result of matching a path against route definitions.\n * @private\n */\n\n/**\n * Arbitrary metadata attached to routes for use in guards and components.\n * @typedef {Record<string, unknown>} RouteMeta\n * @description Common properties include:\n * - `requiresAuth: boolean` - Whether the route requires authentication\n * - `title: string` - Page title for the route\n * - `roles: string[]` - Required user roles\n * @example\n * {\n * path: '/admin',\n * component: AdminPage,\n * meta: { requiresAuth: true, roles: ['admin'], title: 'Admin Dashboard' }\n * }\n */\n\n/**\n * Interface for the router's error handling system.\n * @typedef {Object} RouterErrorHandler\n * @property {(error: Error, context: string, details?: Record<string, unknown>) => void} handle\n * Throws a formatted error.\n * @property {(message: string, details?: Record<string, unknown>) => void} warn\n * Logs a warning.\n * @property {(message: string, error: Error, details?: Record<string, unknown>) => void} log\n * Logs an error without throwing.\n * @description Interface for the router's error handling system.\n */\n\n// -----------------------------------------------------------------------------\n// Event Callback Types\n// -----------------------------------------------------------------------------\n\n/**\n * Callback for `router:beforeEach` event.\n * @callback NavigationContextCallback\n * @param {NavigationContext} context\n * The navigation context (can be modified to block/redirect).\n * @returns {void | Promise<void>}\n * @description Modify context to control navigation flow.\n */\n\n/**\n * Callback for `router:beforeResolve` and `router:afterResolve` events.\n * @callback ResolveContextCallback\n * @param {ResolveContext} context\n * The resolve context (can be modified to block/redirect).\n * @returns {void | Promise<void>}\n * @description Callback for `router:beforeResolve` and `router:afterResolve` events.\n */\n\n/**\n * Callback for `router:beforeRender` and `router:afterRender` events.\n * @callback RenderContextCallback\n * @param {RenderContext} context\n * The render context.\n * @returns {void | Promise<void>}\n * @description Callback for `router:beforeRender` and `router:afterRender` events.\n */\n\n/**\n * Callback for `router:scroll` event.\n * @callback ScrollContextCallback\n * @param {ScrollContext} context\n * The scroll context with saved position info.\n * @returns {void | Promise<void>}\n * @description Use to implement custom scroll behavior.\n */\n\n/**\n * Callback for `router:afterEnter`, `router:afterLeave`, `router:afterEach` events.\n * @callback RouteChangeCallback\n * @param {RouteLocation} to\n * The target route location.\n * @param {RouteLocation | null} from\n * The source route location.\n * @returns {void | Promise<void>}\n * @description Callback for `router:afterEnter`, `router:afterLeave`, `router:afterEach` events.\n */\n\n/**\n * Router context injected into component setup as `ctx.router`.\n * @typedef {Object} RouterContext\n * @property {NavigateFunction} navigate\n * Programmatic navigation function.\n * @property {Signal<RouteLocation | null>} current\n * Reactive signal for current route.\n * @property {Signal<RouteLocation | null>} previous\n * Reactive signal for previous route.\n * @property {RouteParams} params\n * Current route params (getter).\n * @property {QueryParams} query\n * Current route query (getter).\n * @property {string} path\n * Current route path (getter).\n * @property {string} fullUrl\n * Current routed URL string (getter).\n * @property {RouteMeta} meta\n * Current route meta (getter).\n * @description Injected into component setup as `ctx.router`.\n */\n\n/**\n * Callback for `router:error` event.\n * @callback RouterErrorCallback\n * @param {Error} error\n * The error that occurred.\n * @param {RouteLocation} [to]\n * The target route (if available).\n * @param {RouteLocation | null} [from]\n * The source route (if available).\n * @returns {void | Promise<void>}\n * @description Callback for `router:error` event.\n */\n\n/**\n * Callback for `router:ready` event.\n * @callback RouterReadyCallback\n * @param {Router} router\n * The router instance.\n * @returns {void | Promise<void>}\n * @description Callback for `router:ready` event.\n */\n\n/**\n * Callback for `router:routeAdded` event.\n * @callback RouteAddedCallback\n * @param {RouteDefinition} route\n * The added route definition.\n * @returns {void | Promise<void>}\n * @description Callback for `router:routeAdded` event.\n */\n\n/**\n * Callback for `router:routeRemoved` event.\n * @callback RouteRemovedCallback\n * @param {RouteDefinition} route\n * The removed route definition.\n * @returns {void | Promise<void>}\n * @description Callback for `router:routeRemoved` event.\n */\n\n// ============================================================================\n// CORE IMPLEMENTATION\n// ============================================================================\n\n/**\n * Simple error handler for the core router.\n * @private\n */\nconst CoreErrorHandler = {\n /**\n * Handles router errors with basic formatting.\n * @param {Error} error - The error to handle.\n * @param {string} context - The context where the error occurred.\n * @param {Record<string, unknown>} details - Additional error details.\n * @throws {Error} The formatted error.\n */\n handle(error, context, details = {}) {\n const message = `[ElevaRouter] ${context}: ${error.message}`;\n const formattedError = new Error(message);\n\n // Preserve original error details\n formattedError.originalError = error;\n formattedError.context = context;\n formattedError.details = details;\n\n console.error(message, { error, context, details });\n throw formattedError;\n },\n\n /**\n * Logs a warning without throwing an error.\n * @param {string} message - The warning message.\n * @param {Record<string, unknown>} details - Additional warning details.\n */\n warn(message, details = {}) {\n console.warn(`[ElevaRouter] ${message}`, details);\n },\n\n /**\n * Logs an error without throwing.\n * @param {string} message - The error message.\n * @param {Error} error - The original error.\n * @param {Record<string, unknown>} details - Additional error details.\n */\n log(message, error, details = {}) {\n console.error(`[ElevaRouter] ${message}`, { error, details });\n },\n};\n\n/**\n * Represents the current or target location in the router.\n * @typedef {Object} RouteLocation\n * @property {string} path\n * The path of the route (e.g., '/users/123').\n * @property {QueryParams} query\n * Query parameters as key-value pairs.\n * @property {string} fullUrl\n * The routed URL string (path plus query).\n * @property {RouteParams} params\n * Dynamic route parameters.\n * @property {RouteMeta} meta\n * Metadata associated with the matched route.\n * @property {string} [name]\n * The optional name of the matched route.\n * @property {RouteDefinition} matched\n * The raw route definition that was matched.\n * @description Represents the current or target location in the router.\n */\n\n/**\n * Return value of a navigation guard.\n * - `true` or `undefined/void`: Allow navigation\n * - `false`: Abort navigation\n * - `string`: Redirect to path\n * - `NavigationTarget`: Redirect with options\n * @typedef {boolean | string | NavigationTarget | void} NavigationGuardResult\n */\n\n/**\n * Navigation guard function that controls navigation flow.\n * @callback NavigationGuard\n * @param {RouteLocation} to\n * The target route location.\n * @param {RouteLocation | null} from\n * The source route location (null on initial).\n * @returns {NavigationGuardResult | Promise<NavigationGuardResult>}\n * @description A function that controls navigation flow. Runs before navigation is confirmed.\n * @example\n * // Simple auth guard\n * const authGuard = (to, from) => {\n * if (to.meta.requiresAuth && !isLoggedIn()) {\n * return '/login'; // Redirect\n * }\n * // Allow navigation (implicit return undefined)\n * };\n */\n\n/**\n * Navigation hook for side effects. Does not affect navigation flow.\n * @callback NavigationHook\n * @param {RouteLocation} to\n * The target route location.\n * @param {RouteLocation | null} from\n * The source route location.\n * @returns {void | Promise<void>}\n * @description A lifecycle hook for side effects. Does not affect navigation flow.\n * @example\n * // Analytics hook\n * const analyticsHook = (to, from) => {\n * analytics.trackPageView(to.path);\n * };\n */\n\n/**\n * Interface for router plugins.\n * @typedef {Object} RouterPlugin\n * @property {string} name\n * Unique plugin identifier.\n * @property {string} [version]\n * Plugin version (recommended to match router version).\n * @property {(router: Router, options?: Record<string, unknown>) => void} install\n * Installation function.\n * @property {(router: Router) => void | Promise<void>} [destroy]\n * Cleanup function called on router.destroy().\n * @description Interface for router plugins. Plugins can extend router functionality.\n * @example\n * const AnalyticsPlugin = {\n * name: 'analytics',\n * version: '1.0.0',\n * install(router, options) {\n * router.emitter.on('router:afterEach', (to, from) => {\n * analytics.track(to.path);\n * });\n * }\n * };\n */\n\n/**\n * Context object for navigation events that plugins can modify.\n * @typedef {Object} NavigationContext\n * @property {RouteLocation} to\n * The target route location.\n * @property {RouteLocation | null} from\n * The source route location.\n * @property {boolean} cancelled\n * Whether navigation has been cancelled.\n * @property {string | NavigationTarget | null} redirectTo\n * Redirect target if set.\n * @description Passed to navigation events. Plugins can modify to control navigation flow.\n */\n\n/**\n * Context object for component resolution events.\n * @typedef {Object} ResolveContext\n * @property {RouteLocation} to\n * The target route location.\n * @property {RouteLocation | null} from\n * The source route location.\n * @property {RouteDefinition} route\n * The matched route definition.\n * @property {ComponentDefinition | null} layoutComponent\n * The resolved layout component (available in afterResolve).\n * @property {ComponentDefinition | null} pageComponent\n * The resolved page component (available in afterResolve).\n * @property {boolean} cancelled\n * Whether navigation has been cancelled.\n * @property {string | NavigationTarget | null} redirectTo\n * Redirect target if set.\n * @description Passed to component resolution events.\n */\n\n/**\n * Context object for render events.\n * @typedef {Object} RenderContext\n * @property {RouteLocation} to\n * The target route location.\n * @property {RouteLocation | null} from\n * The source route location.\n * @property {ComponentDefinition | null} layoutComponent\n * The layout component being rendered.\n * @property {ComponentDefinition} pageComponent\n * The page component being rendered.\n * @description Passed to render events.\n */\n\n/**\n * Context object for scroll events.\n * @typedef {Object} ScrollContext\n * @property {RouteLocation} to\n * The target route location.\n * @property {RouteLocation | null} from\n * The source route location.\n * @property {{x: number, y: number} | null} savedPosition\n * Saved position (back/forward nav).\n * @description Passed to scroll events for plugins to handle scroll behavior.\n */\n\n/**\n * A component that can be rendered for a route.\n * - `string`: Name of a registered component\n * - `ComponentDefinition`: Inline component definition\n * - `() => ComponentDefinition`: Factory function returning a component\n * - `() => Promise<ComponentDefinition>`: Async factory function\n * - `() => Promise<{default: ComponentDefinition}>`: Lazy-loaded module (e.g., `() => import('./Page.js')`)\n * @typedef {string | ComponentDefinition | (() => ComponentDefinition | Promise<ComponentDefinition | {default: ComponentDefinition}>)} RouteComponent\n */\n\n/**\n * Defines a route in the application.\n * @typedef {Object} RouteDefinition\n * @property {string} path\n * URL path pattern. Supports:\n * - Static: '/about'\n * - Dynamic params: '/users/:id'\n * - Wildcard: '*' (catch-all, conventionally last)\n * @property {RouteComponent} component\n * The component to render for this route.\n * @property {RouteComponent} [layout]\n * Optional layout component to wrap the route component.\n * @property {string} [name]\n * Optional route name for programmatic navigation.\n * @property {RouteMeta} [meta]\n * Optional metadata (auth flags, titles, etc.).\n * @property {NavigationGuard} [beforeEnter]\n * Route-specific guard before entering.\n * @property {NavigationHook} [afterEnter]\n * Hook after entering and component is mounted.\n * @property {NavigationGuard} [beforeLeave]\n * Guard before leaving this route.\n * @property {NavigationHook} [afterLeave]\n * Hook after leaving and component is unmounted.\n * @property {RouteSegment[]} [segments]\n * Internal: parsed path segments (added by router).\n * @description Defines a route in the application.\n * @note Nested routes are not supported. Use shared layouts with flat routes instead.\n * @example\n * // Static route\n * { path: '/about', component: AboutPage }\n *\n * // Dynamic route with params\n * { path: '/users/:id', component: UserPage, meta: { requiresAuth: true } }\n *\n * // Lazy-loaded route with layout\n * {\n * path: '/dashboard',\n * component: () => import('./Dashboard.js'),\n * layout: DashboardLayout,\n * beforeEnter: (to, from) => isLoggedIn() || '/login'\n * }\n *\n * // Catch-all 404 route (conventionally last)\n * { path: '*', component: NotFoundPage }\n */\n\n/**\n * @class 🛤️ Router\n * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva.\n * This class manages all routing logic, including state, navigation, and rendering.\n *\n * ## Features\n * - Multiple routing modes (hash, history, query)\n * - Reactive route state via Signals\n * - Navigation guards and lifecycle hooks\n * - Lazy-loaded components\n * - Layout system\n * - Plugin architecture\n * - Scroll position management\n *\n * ## Events Reference\n * | Event | Callback Type | Can Block | Description |\n * |-------|--------------|-----------|-------------|\n * | `router:ready` | {@link RouterReadyCallback} | No | Router initialized |\n * | `router:beforeEach` | {@link NavigationContextCallback} | Yes | Before guards run |\n * | `router:beforeResolve` | {@link ResolveContextCallback} | Yes | Before component loading |\n * | `router:afterResolve` | {@link ResolveContextCallback} | No | After components loaded |\n * | `router:afterLeave` | {@link RouteChangeCallback} | No | After leaving route |\n * | `router:beforeRender` | {@link RenderContextCallback} | No | Before DOM update |\n * | `router:afterRender` | {@link RenderContextCallback} | No | After DOM update |\n * | `router:scroll` | {@link ScrollContextCallback} | No | For scroll behavior |\n * | `router:afterEnter` | {@link RouteChangeCallback} | No | After entering route |\n * | `router:afterEach` | {@link RouteChangeCallback} | No | Navigation complete |\n * | `router:error` | {@link RouterErrorCallback} | No | Navigation error |\n * | `router:routeAdded` | {@link RouteAddedCallback} | No | Dynamic route added |\n * | `router:routeRemoved` | {@link RouteRemovedCallback} | No | Dynamic route removed |\n *\n * ## Reactive Signals\n * - `currentRoute: Signal<RouteLocation | null>` - Current route info\n * - `previousRoute: Signal<RouteLocation | null>` - Previous route info\n * - `currentParams: Signal<RouteParams>` - Current route params\n * - `currentQuery: Signal<QueryParams>` - Current query params\n * - `currentLayout: Signal<MountResult | null>` - Mounted layout instance\n * - `currentView: Signal<MountResult | null>` - Mounted view instance\n * - `isReady: Signal<boolean>` - Router readiness state\n *\n * @note Internal API Access Policy:\n * As a core Eleva plugin, the Router may access internal Eleva APIs (prefixed with _)\n * such as `eleva._components`. This is intentional and these internal APIs are\n * considered stable for official plugins. Third-party plugins should avoid\n * accessing internal APIs as they may change without notice.\n *\n * @example\n * // Basic setup\n * const router = new Router(eleva, {\n * mode: 'hash',\n * mount: '#app',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/users/:id', component: UserPage },\n * { path: '*', component: NotFoundPage }\n * ]\n * });\n *\n * // Start router\n * await router.start();\n *\n * // Navigate programmatically\n * const success = await router.navigate('/users/123');\n *\n * // Watch for route changes\n * router.currentRoute.watch((route) => {\n * document.title = route?.meta?.title || 'My App';\n * });\n *\n * @private\n */\nclass Router {\n /**\n * Creates an instance of the Router.\n * @param {Eleva} eleva - The Eleva framework instance.\n * @param {RouterOptions} options - The configuration options for the router.\n * @throws {Error} If the routing mode is invalid.\n */\n constructor(eleva, options = {}) {\n /** @type {Eleva} The Eleva framework instance. */\n this.eleva = eleva;\n\n /** @type {RouterOptions} The merged router options. */\n this.options = {\n mode: \"hash\",\n queryParam: \"view\",\n viewSelector: \"view\",\n ...options,\n };\n\n /** @private @type {RouteDefinition[]} The processed list of route definitions. */\n this.routes = this._processRoutes(options.routes || []);\n\n /** @private @type {Emitter} The shared Eleva event emitter for global hooks. */\n this.emitter = this.eleva.emitter;\n\n /** @private @type {boolean} A flag indicating if the router has been started. */\n this.isStarted = false;\n\n /** @private @type {boolean} A flag to prevent navigation loops from history events. */\n this._isNavigating = false;\n\n /** @private @type {number} Counter for tracking navigation operations to prevent race conditions. */\n this._navigationId = 0;\n\n /** @private @type {UnsubscribeFunction[]} A collection of cleanup functions for event listeners. */\n this.eventListeners = [];\n\n /** @type {Signal<RouteLocation | null>} A reactive signal holding the current route's information. */\n this.currentRoute = new this.eleva.signal(null);\n\n /** @type {Signal<RouteLocation | null>} A reactive signal holding the previous route's information. */\n this.previousRoute = new this.eleva.signal(null);\n\n /** @type {Signal<RouteParams>} A reactive signal holding the current route's parameters. */\n this.currentParams = new this.eleva.signal({});\n\n /** @type {Signal<QueryParams>} A reactive signal holding the current route's query parameters. */\n this.currentQuery = new this.eleva.signal({});\n\n /** @type {Signal<MountResult | null>} A reactive signal for the currently mounted layout instance. */\n this.currentLayout = new this.eleva.signal(null);\n\n /** @type {Signal<MountResult | null>} A reactive signal for the currently mounted view (page) instance. */\n this.currentView = new this.eleva.signal(null);\n\n /** @type {Signal<boolean>} A reactive signal indicating if the router is ready (started and initial navigation complete). */\n this.isReady = new this.eleva.signal(false);\n\n /** @private @type {Map<string, RouterPlugin>} Map of registered plugins by name. */\n this.plugins = new Map();\n\n /** @private @type {NavigationGuard[]} Array of global before-each navigation guards. */\n this._beforeEachGuards = [];\n\n // If onBeforeEach was provided in options, add it to the guards array\n if (options.onBeforeEach) {\n this._beforeEachGuards.push(options.onBeforeEach);\n }\n\n /** @type {RouterErrorHandler} The error handler instance. Can be overridden by plugins. */\n this.errorHandler = CoreErrorHandler;\n\n /** @private @type {Map<string, {x: number, y: number}>} Saved scroll positions by route path. */\n this._scrollPositions = new Map();\n\n this._validateOptions();\n }\n\n /**\n * Validates the provided router options.\n * @private\n * @throws {Error} If the routing mode is invalid.\n */\n _validateOptions() {\n if (![\"hash\", \"query\", \"history\"].includes(this.options.mode)) {\n this.errorHandler.handle(\n new Error(\n `Invalid routing mode: ${this.options.mode}. Must be \"hash\", \"query\", or \"history\".`\n ),\n \"Configuration validation failed\"\n );\n }\n }\n\n /**\n * Pre-processes route definitions to parse their path segments for efficient matching.\n * @private\n * @param {RouteDefinition[]} routes - The raw route definitions.\n * @returns {RouteDefinition[]} The processed routes.\n */\n _processRoutes(routes) {\n const processedRoutes = [];\n for (const route of routes) {\n try {\n processedRoutes.push({\n ...route,\n segments: this._parsePathIntoSegments(route.path),\n });\n } catch (error) {\n this.errorHandler.warn(\n `Invalid path in route definition \"${route.path || \"undefined\"}\": ${error.message}`,\n { route, error }\n );\n }\n }\n return processedRoutes;\n }\n\n /**\n * Parses a route path string into an array of static and parameter segments.\n * @private\n * @param {string} path - The path pattern to parse.\n * @returns {{type: 'static' | 'param', value?: string, name?: string}[]} An array of segment objects.\n * @throws {Error} If the route path is not a valid string.\n */\n _parsePathIntoSegments(path) {\n if (!path || typeof path !== \"string\") {\n this.errorHandler.handle(\n new Error(\"Route path must be a non-empty string\"),\n \"Path parsing failed\",\n { path }\n );\n }\n\n const normalizedPath = path.replace(/\\/+/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n\n if (normalizedPath === \"/\") {\n return [];\n }\n\n return normalizedPath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n if (segment.startsWith(\":\")) {\n const paramName = segment.substring(1);\n if (!paramName) {\n this.errorHandler.handle(\n new Error(`Invalid parameter segment: ${segment}`),\n \"Path parsing failed\",\n { segment, path }\n );\n }\n return { type: \"param\", name: paramName };\n }\n return { type: \"static\", value: segment };\n });\n }\n\n /**\n * Finds the view element within a container using multiple selector strategies.\n * @private\n * @param {HTMLElement} container - The parent element to search within.\n * @returns {HTMLElement} The found view element or the container itself as a fallback.\n */\n _findViewElement(container) {\n const selector = this.options.viewSelector;\n return (\n container.querySelector(`#${selector}`) ||\n container.querySelector(`.${selector}`) ||\n container.querySelector(`[data-${selector}]`) ||\n container.querySelector(selector) ||\n container\n );\n }\n\n /**\n * Starts the router, initializes event listeners, and performs the initial navigation.\n * @returns {Promise<Router>} The router instance for method chaining.\n * @listens window:hashchange In hash mode, triggers route changes.\n * @listens window:popstate In history/query mode, triggers route changes.\n * @emits router:ready When initialization completes successfully.\n * @see destroy - Stop the router and clean up listeners.\n * @see navigate - Programmatically navigate to a route.\n *\n * @example\n * // Basic usage\n * await router.start();\n *\n * // Method chaining\n * await router.start().then(r => r.navigate('/home'));\n *\n * // Reactive readiness\n * router.isReady.watch((ready) => {\n * if (ready) console.log('Router is ready!');\n * });\n */\n async start() {\n if (this.isStarted) {\n this.errorHandler.warn(\"Router is already started\");\n return this;\n }\n if (typeof window === \"undefined\") {\n this.errorHandler.warn(\n \"Router start skipped: `window` object not available (SSR environment)\"\n );\n return this;\n }\n if (\n typeof document !== \"undefined\" &&\n !document.querySelector(this.options.mount)\n ) {\n this.errorHandler.warn(\n `Mount element \"${this.options.mount}\" was not found in the DOM. The router will not start.`,\n { mountSelector: this.options.mount }\n );\n return this;\n }\n const handler = () => this._handleRouteChange();\n if (this.options.mode === \"hash\") {\n window.addEventListener(\"hashchange\", handler);\n this.eventListeners.push(() =>\n window.removeEventListener(\"hashchange\", handler)\n );\n } else {\n window.addEventListener(\"popstate\", handler);\n this.eventListeners.push(() =>\n window.removeEventListener(\"popstate\", handler)\n );\n }\n this.isStarted = true;\n // Initial navigation is not a popstate event\n await this._handleRouteChange(false);\n // Set isReady to true after initial navigation completes\n this.isReady.value = true;\n await this.emitter.emit(\"router:ready\", this);\n return this;\n }\n\n /**\n * Stops the router and cleans up event listeners.\n * Unmounts the current layout instance if present.\n * @async\n * @returns {Promise<void>}\n * @see start - Restart the router after destroying.\n */\n async destroy() {\n if (!this.isStarted) return;\n\n // Clean up plugins\n for (const plugin of this.plugins.values()) {\n if (typeof plugin.destroy === \"function\") {\n try {\n await plugin.destroy(this);\n } catch (error) {\n this.errorHandler.log(`Plugin ${plugin.name} destroy failed`, error);\n }\n }\n }\n\n this.eventListeners.forEach((cleanup) => cleanup());\n this.eventListeners = [];\n if (this.currentLayout.value) {\n await this.currentLayout.value.unmount();\n }\n this.isStarted = false;\n this.isReady.value = false;\n }\n\n /**\n * Alias for destroy(). Stops the router and cleans up all resources.\n * Provided for semantic consistency (start/stop pattern).\n * @async\n * @returns {Promise<void>}\n *\n * @example\n * await router.start();\n * // ... later\n * await router.stop();\n */\n async stop() {\n return this.destroy();\n }\n\n /**\n * Programmatically navigates to a new route.\n * @async\n * @param {string | NavigationTarget} location - The target location as a path string or navigation target object.\n * @param {NavigationParams} [params] - Route parameters (only used when location is a string).\n * @returns {Promise<boolean>} True if navigation succeeded, false if blocked by guards or failed.\n * @emits router:error When navigation fails due to an exception.\n * @see start - Initialize the router before navigating.\n * @see currentRoute - Access the current route after navigation.\n *\n * @example\n * // Basic navigation\n * await router.navigate('/users/123');\n *\n * // Check if navigation succeeded\n * const success = await router.navigate('/protected');\n * if (!success) {\n * console.log('Navigation was blocked by a guard');\n * }\n *\n * // Navigate with options\n * await router.navigate({\n * path: '/users/:id',\n * params: { id: '123' },\n * query: { tab: 'profile' },\n * replace: true\n * });\n */\n async navigate(location, params = {}) {\n try {\n const target =\n typeof location === \"string\" ? { path: location, params } : location;\n let path = this._buildPath(target.path, target.params || {});\n const query = target.query || {};\n\n if (Object.keys(query).length > 0) {\n const queryString = new URLSearchParams(query).toString();\n if (queryString) path += `?${queryString}`;\n }\n\n if (this._isSameRoute(path, target.params, query)) {\n return true; // Already at this route, consider it successful\n }\n\n const navigationSuccessful = await this._proceedWithNavigation(path);\n\n if (navigationSuccessful) {\n // Increment navigation ID and capture it for this navigation\n const currentNavId = ++this._navigationId;\n this._isNavigating = true;\n\n try {\n const state = target.state || {};\n const replace = target.replace || false;\n const historyMethod = replace ? \"replaceState\" : \"pushState\";\n\n if (this.options.mode === \"hash\") {\n if (replace) {\n const newUrl = `${window.location.pathname}${window.location.search}#${path}`;\n window.history.replaceState(state, \"\", newUrl);\n } else {\n window.location.hash = path;\n }\n } else {\n const url =\n this.options.mode === \"query\" ? this._buildQueryUrl(path) : path;\n history[historyMethod](state, \"\", url);\n }\n } finally {\n // Always reset the flag via microtask, even if history manipulation throws\n // Only reset if no newer navigation has started\n queueMicrotask(() => {\n if (this._navigationId === currentNavId) {\n this._isNavigating = false;\n }\n });\n }\n }\n\n return navigationSuccessful;\n } catch (error) {\n this.errorHandler.log(\"Navigation failed\", error);\n await this.emitter.emit(\"router:error\", error);\n return false;\n }\n }\n\n /**\n * Builds a URL for query mode.\n * @private\n * @param {string} path - The path to set as the query parameter.\n * @returns {string} The full URL with the updated query string.\n */\n _buildQueryUrl(path) {\n const urlParams = new URLSearchParams(window.location.search);\n urlParams.set(this.options.queryParam, path.split(\"?\")[0]);\n return `${window.location.pathname}?${urlParams.toString()}`;\n }\n\n /**\n * Checks if the target route is identical to the current route.\n * @private\n * @param {string} path - The target path with query string.\n * @param {object} params - The target params.\n * @param {object} query - The target query.\n * @returns {boolean} True if the routes are the same.\n */\n _isSameRoute(path, params, query) {\n const current = this.currentRoute.value;\n if (!current) return false;\n const [targetPath, queryString] = path.split(\"?\");\n const targetQuery = query || this._parseQuery(queryString || \"\");\n return (\n current.path === targetPath &&\n JSON.stringify(current.params) === JSON.stringify(params || {}) &&\n JSON.stringify(current.query) === JSON.stringify(targetQuery)\n );\n }\n\n /**\n * Injects dynamic parameters into a path string.\n * Replaces `:param` placeholders with URL-encoded values from the params object.\n *\n * @private\n * @param {string} path - The path pattern containing `:param` placeholders.\n * @param {RouteParams} params - Key-value pairs to inject into the path.\n * @returns {string} The path with all parameters replaced.\n *\n * @example\n * this._buildPath('/users/:id/posts/:postId', { id: '123', postId: '456' });\n * // Returns: '/users/123/posts/456'\n */\n _buildPath(path, params) {\n let result = path;\n for (const [key, value] of Object.entries(params)) {\n // Fix: Handle special characters and ensure proper encoding\n const encodedValue = encodeURIComponent(String(value));\n result = result.replace(new RegExp(`:${key}\\\\b`, \"g\"), encodedValue);\n }\n return result;\n }\n\n /**\n * The handler for browser-initiated route changes (e.g., back/forward buttons).\n *\n * @private\n * @async\n * @param {boolean} [isPopState=true] - Whether this is a popstate event (back/forward navigation).\n * @returns {Promise<void>}\n * @emits router:error When route change handling fails.\n */\n async _handleRouteChange(isPopState = true) {\n if (this._isNavigating) return;\n\n try {\n const from = this.currentRoute.value;\n const toLocation = this._getCurrentLocation();\n\n const navigationSuccessful = await this._proceedWithNavigation(\n toLocation.fullUrl,\n isPopState\n );\n\n // If navigation was blocked by a guard, revert the URL change\n if (!navigationSuccessful && from) {\n this.navigate({ path: from.path, query: from.query, replace: true });\n }\n } catch (error) {\n this.errorHandler.log(\"Route change handling failed\", error, {\n currentUrl: typeof window !== \"undefined\" ? window.location.href : \"\",\n });\n await this.emitter.emit(\"router:error\", error);\n }\n }\n\n /**\n * Manages the core navigation lifecycle. Runs guards before committing changes.\n *\n * @private\n * @async\n * @param {string} fullPath - The full path (e.g., '/users/123?foo=bar') to navigate to.\n * @param {boolean} [isPopState=false] - Whether this navigation was triggered by popstate (back/forward).\n * @returns {Promise<boolean>} `true` if navigation succeeded, `false` if aborted.\n * @emits router:notFound When no matching route is found.\n * @emits router:beforeResolve Before component resolution (can block/redirect).\n * @emits router:afterResolve After components are resolved.\n * @emits router:afterLeave After leaving the previous route.\n * @emits router:beforeRender Before DOM rendering.\n * @emits router:afterRender After DOM rendering completes.\n * @emits router:scroll After render, for scroll behavior handling.\n * @emits router:afterEnter After entering the new route.\n * @emits router:afterEach After navigation completes successfully.\n * @emits router:error When an error occurs during navigation.\n * @see _runGuards - Guard execution.\n * @see _resolveComponents - Component resolution.\n * @see _render - DOM rendering.\n */\n async _proceedWithNavigation(fullPath, isPopState = false) {\n const from = this.currentRoute.value;\n const [path, queryString] = (fullPath || \"/\").split(\"?\");\n const toLocation = {\n path: path.startsWith(\"/\") ? path : `/${path}`,\n query: this._parseQuery(queryString),\n fullUrl: fullPath,\n };\n\n let toMatch = this._matchRoute(toLocation.path);\n\n if (!toMatch) {\n const notFoundRoute = this.routes.find((route) => route.path === \"*\");\n if (notFoundRoute) {\n toMatch = {\n route: notFoundRoute,\n params: {\n pathMatch: decodeURIComponent(toLocation.path.substring(1)),\n },\n };\n } else {\n await this.emitter.emit(\n \"router:error\",\n new Error(`Route not found: ${toLocation.path}`),\n toLocation,\n from\n );\n return false;\n }\n }\n\n const to = {\n ...toLocation,\n params: toMatch.params,\n meta: toMatch.route.meta || {},\n name: toMatch.route.name,\n matched: toMatch.route,\n };\n\n try {\n // 1. Run all *pre-navigation* guards.\n const canNavigate = await this._runGuards(to, from, toMatch.route);\n if (!canNavigate) return false;\n\n // 2. Save current scroll position before navigating away\n if (from && typeof window !== \"undefined\") {\n this._scrollPositions.set(from.path, {\n x: window.scrollX || window.pageXOffset || 0,\n y: window.scrollY || window.pageYOffset || 0,\n });\n }\n\n // 3. Emit beforeResolve event - plugins can show loading indicators\n /** @type {ResolveContext} */\n const resolveContext = {\n to,\n from,\n route: toMatch.route,\n layoutComponent: null,\n pageComponent: null,\n cancelled: false,\n redirectTo: null,\n };\n await this.emitter.emit(\"router:beforeResolve\", resolveContext);\n\n // Check if resolution was cancelled or redirected\n if (resolveContext.cancelled) return false;\n if (resolveContext.redirectTo) {\n this.navigate(resolveContext.redirectTo);\n return false;\n }\n\n // 4. Resolve async components *before* touching the DOM.\n const { layoutComponent, pageComponent } = await this._resolveComponents(\n toMatch.route\n );\n\n // 5. Emit afterResolve event - plugins can hide loading indicators\n resolveContext.layoutComponent = layoutComponent;\n resolveContext.pageComponent = pageComponent;\n await this.emitter.emit(\"router:afterResolve\", resolveContext);\n\n // 6. Unmount the previous view/layout.\n if (from) {\n const toLayout = toMatch.route.layout || this.options.globalLayout;\n const fromLayout = from.matched.layout || this.options.globalLayout;\n\n const tryUnmount = async (instance) => {\n if (!instance) return;\n\n try {\n await instance.unmount();\n } catch (error) {\n this.errorHandler.warn(\"Error during component unmount\", {\n error,\n instance,\n });\n }\n };\n\n if (toLayout !== fromLayout) {\n await tryUnmount(this.currentLayout.value);\n this.currentLayout.value = null;\n } else {\n await tryUnmount(this.currentView.value);\n this.currentView.value = null;\n }\n\n // Call `afterLeave` hook *after* the old component has been unmounted.\n if (from.matched.afterLeave) {\n await from.matched.afterLeave(to, from);\n }\n await this.emitter.emit(\"router:afterLeave\", to, from);\n }\n\n // 7. Update reactive state.\n this.previousRoute.value = from;\n this.currentRoute.value = to;\n this.currentParams.value = to.params || {};\n this.currentQuery.value = to.query || {};\n\n // 8. Emit beforeRender event - plugins can add transitions\n /** @type {RenderContext} */\n const renderContext = {\n to,\n from,\n layoutComponent,\n pageComponent,\n };\n await this.emitter.emit(\"router:beforeRender\", renderContext);\n\n // 9. Render the new components.\n await this._render(layoutComponent, pageComponent);\n\n // 10. Emit afterRender event - plugins can trigger animations\n await this.emitter.emit(\"router:afterRender\", renderContext);\n\n // 11. Emit scroll event - plugins can handle scroll restoration\n /** @type {ScrollContext} */\n const scrollContext = {\n to,\n from,\n savedPosition: isPopState\n ? this._scrollPositions.get(to.path) || null\n : null,\n };\n await this.emitter.emit(\"router:scroll\", scrollContext);\n\n // 12. Run post-navigation hooks.\n if (toMatch.route.afterEnter) {\n await toMatch.route.afterEnter(to, from);\n }\n await this.emitter.emit(\"router:afterEnter\", to, from);\n await this.emitter.emit(\"router:afterEach\", to, from);\n\n return true;\n } catch (error) {\n this.errorHandler.log(\"Error during navigation\", error, { to, from });\n await this.emitter.emit(\"router:error\", error, to, from);\n return false;\n }\n }\n\n /**\n * Executes all applicable navigation guards for a transition in order.\n * Guards are executed in the following order:\n * 1. Global beforeEach event (emitter-based, can block via context)\n * 2. Global beforeEach guards (registered via onBeforeEach)\n * 3. Route-specific beforeLeave guard (from the route being left)\n * 4. Route-specific beforeEnter guard (from the route being entered)\n *\n * @private\n * @param {RouteLocation} to - The target route location.\n * @param {RouteLocation | null} from - The current route location (null on initial navigation).\n * @param {RouteDefinition} route - The matched route definition.\n * @returns {Promise<boolean>} `false` if navigation should be aborted.\n * @emits router:beforeEach Before guards run (can block/redirect via context).\n */\n async _runGuards(to, from, route) {\n // Create navigation context that plugins can modify to block navigation\n /** @type {NavigationContext} */\n const navContext = {\n to,\n from,\n cancelled: false,\n redirectTo: null,\n };\n\n // Emit beforeEach event with context - plugins can block by modifying context\n await this.emitter.emit(\"router:beforeEach\", navContext);\n\n // Check if navigation was cancelled or redirected by event listeners\n if (navContext.cancelled) return false;\n if (navContext.redirectTo) {\n this.navigate(navContext.redirectTo);\n return false;\n }\n\n // Collect all guards in execution order\n const guards = [\n ...this._beforeEachGuards,\n ...(from && from.matched.beforeLeave ? [from.matched.beforeLeave] : []),\n ...(route.beforeEnter ? [route.beforeEnter] : []),\n ];\n\n for (const guard of guards) {\n const result = await guard(to, from);\n if (result === false) return false;\n if (typeof result === \"string\" || typeof result === \"object\") {\n this.navigate(result);\n return false;\n }\n }\n return true;\n }\n\n /**\n * Resolves a string component definition to a component object.\n * @private\n * @param {string} def - The component name to resolve.\n * @returns {ComponentDefinition} The resolved component.\n * @throws {Error} If the component is not registered.\n *\n * @note Core plugins (Router, Attr, Store) may access eleva._components\n * directly. This is intentional and stable for official Eleva plugins shipped\n * with the framework. Third-party plugins should use eleva.component() for\n * registration and avoid direct access to internal APIs.\n */\n _resolveStringComponent(def) {\n const componentDef = this.eleva._components.get(def);\n if (!componentDef) {\n this.errorHandler.handle(\n new Error(`Component \"${def}\" not registered.`),\n \"Component resolution failed\",\n {\n componentName: def,\n availableComponents: Array.from(this.eleva._components.keys()),\n }\n );\n }\n return componentDef;\n }\n\n /**\n * Resolves a function component definition to a component object.\n * @private\n * @async\n * @param {() => ComponentDefinition | Promise<ComponentDefinition | { default: ComponentDefinition }>} def - The function to resolve.\n * @returns {Promise<ComponentDefinition>} The resolved component.\n * @throws {Error} If the function fails to load the component.\n */\n async _resolveFunctionComponent(def) {\n try {\n const funcStr = def.toString();\n const isAsyncImport =\n funcStr.includes(\"import(\") || funcStr.startsWith(\"() =>\");\n\n const result = await def();\n return isAsyncImport ? result.default || result : result;\n } catch (error) {\n this.errorHandler.handle(\n new Error(`Failed to load async component: ${error.message}`),\n \"Component resolution failed\",\n { function: def.toString(), error }\n );\n }\n }\n\n /**\n * Validates a component definition object.\n * @private\n * @param {unknown} def - The component definition to validate.\n * @returns {ComponentDefinition} The validated component.\n * @throws {Error} If the component definition is invalid.\n */\n _validateComponentDefinition(def) {\n if (!def || typeof def !== \"object\") {\n this.errorHandler.handle(\n new Error(`Invalid component definition: ${typeof def}`),\n \"Component validation failed\",\n { definition: def }\n );\n }\n\n if (\n typeof def.template !== \"function\" &&\n typeof def.template !== \"string\"\n ) {\n this.errorHandler.handle(\n new Error(\"Component missing template property\"),\n \"Component validation failed\",\n { definition: def }\n );\n }\n\n return def;\n }\n\n /**\n * Resolves a component definition to a component object.\n * @private\n * @param {unknown} def - The component definition to resolve.\n * @returns {Promise<ComponentDefinition | null>} The resolved component or null.\n */\n async _resolveComponent(def) {\n if (def === null || def === undefined) {\n return null;\n }\n\n if (typeof def === \"string\") {\n return this._resolveStringComponent(def);\n }\n\n if (typeof def === \"function\") {\n return await this._resolveFunctionComponent(def);\n }\n\n if (def && typeof def === \"object\") {\n return this._validateComponentDefinition(def);\n }\n\n this.errorHandler.handle(\n new Error(`Invalid component definition: ${typeof def}`),\n \"Component resolution failed\",\n { definition: def }\n );\n }\n\n /**\n * Asynchronously resolves the layout and page components for a route.\n * @private\n * @async\n * @param {RouteDefinition} route - The route to resolve components for.\n * @returns {Promise<{layoutComponent: ComponentDefinition | null, pageComponent: ComponentDefinition}>}\n * @throws {Error} If page component cannot be resolved.\n */\n async _resolveComponents(route) {\n const effectiveLayout = route.layout || this.options.globalLayout;\n\n try {\n const [layoutComponent, pageComponent] = await Promise.all([\n this._resolveComponent(effectiveLayout),\n this._resolveComponent(route.component),\n ]);\n\n if (!pageComponent) {\n this.errorHandler.handle(\n new Error(\n `Page component is null or undefined for route: ${route.path}`\n ),\n \"Component resolution failed\",\n { route: route.path }\n );\n }\n\n return { layoutComponent, pageComponent };\n } catch (error) {\n this.errorHandler.log(\n `Error resolving components for route ${route.path}`,\n error,\n { route: route.path }\n );\n throw error;\n }\n }\n\n /**\n * Renders the components for the current route into the DOM.\n *\n * Rendering algorithm:\n * 1. Find the mount element using options.mount selector\n * 2. If layoutComponent exists:\n * a. Mount layout to mount element\n * b. Find view element within layout (using viewSelector)\n * c. Mount page component to view element\n * 3. If no layoutComponent:\n * a. Mount page component directly to mount element\n * b. Set currentLayout to null\n *\n * @private\n * @async\n * @param {ComponentDefinition | null} layoutComponent - The pre-loaded layout component.\n * @param {ComponentDefinition} pageComponent - The pre-loaded page component.\n * @returns {Promise<void>}\n * @throws {Error} If mount element is not found in the DOM.\n * @throws {Error} If component mounting fails (propagated from eleva.mount).\n */\n async _render(layoutComponent, pageComponent) {\n const mountEl = document.querySelector(this.options.mount);\n if (!mountEl) {\n this.errorHandler.handle(\n new Error(`Mount element \"${this.options.mount}\" not found.`),\n { mountSelector: this.options.mount }\n );\n }\n\n if (layoutComponent) {\n const layoutInstance = await this.eleva.mount(\n mountEl,\n this._wrapComponentWithChildren(layoutComponent)\n );\n this.currentLayout.value = layoutInstance;\n const viewEl = this._findViewElement(layoutInstance.container);\n const viewInstance = await this.eleva.mount(\n viewEl,\n this._wrapComponentWithChildren(pageComponent)\n );\n this.currentView.value = viewInstance;\n } else {\n const viewInstance = await this.eleva.mount(\n mountEl,\n this._wrapComponentWithChildren(pageComponent)\n );\n this.currentView.value = viewInstance;\n this.currentLayout.value = null;\n }\n }\n\n /**\n * Creates a getter function for router context properties.\n * @private\n * @param {string} property - The property name to access.\n * @param {unknown} defaultValue - The default value if property is undefined.\n * @returns {() => unknown} A getter function.\n */\n _createRouteGetter(property, defaultValue) {\n return () => this.currentRoute.value?.[property] ?? defaultValue;\n }\n\n /**\n * Wraps a component definition to inject router-specific context into its setup function.\n * @private\n * @param {ComponentDefinition} component - The component to wrap.\n * @returns {ComponentDefinition} The wrapped component definition.\n */\n _wrapComponent(component) {\n const originalSetup = component.setup;\n const self = this;\n\n return {\n ...component,\n async setup(ctx) {\n /** @type {RouterContext} */\n ctx.router = {\n navigate: self.navigate.bind(self),\n current: self.currentRoute,\n previous: self.previousRoute,\n\n // Route property getters\n get params() {\n return self._createRouteGetter(\"params\", {})();\n },\n get query() {\n return self._createRouteGetter(\"query\", {})();\n },\n get path() {\n return self._createRouteGetter(\"path\", \"/\")();\n },\n get fullUrl() {\n return self._createRouteGetter(\"fullUrl\", window.location.href)();\n },\n get meta() {\n return self._createRouteGetter(\"meta\", {})();\n },\n };\n\n return originalSetup ? await originalSetup(ctx) : {};\n },\n };\n }\n\n /**\n * Recursively wraps all child components to ensure they have access to router context.\n * String component references are returned as-is (context injected during mount).\n * Objects are wrapped with router context and their children are recursively wrapped.\n *\n * @private\n * @param {ComponentDefinition | string} component - The component to wrap (can be a definition object or a registered component name).\n * @returns {ComponentDefinition | string} The wrapped component definition or the original string reference.\n * @see _wrapComponent - Single component wrapping.\n */\n _wrapComponentWithChildren(component) {\n // If the component is a string (registered component name), return as-is\n // The router context will be injected when the component is resolved during mounting\n if (typeof component === \"string\") {\n return component;\n }\n\n // If not a valid component object, return as-is\n if (!component || typeof component !== \"object\") {\n return component;\n }\n\n const wrappedComponent = this._wrapComponent(component);\n\n // If the component has children, wrap them too\n if (\n wrappedComponent.children &&\n typeof wrappedComponent.children === \"object\"\n ) {\n const wrappedChildren = {};\n for (const [selector, childComponent] of Object.entries(\n wrappedComponent.children\n )) {\n wrappedChildren[selector] =\n this._wrapComponentWithChildren(childComponent);\n }\n wrappedComponent.children = wrappedChildren;\n }\n\n return wrappedComponent;\n }\n\n /**\n * Gets the current location information from the browser's window object.\n * @private\n * @returns {Omit<RouteLocation, 'params' | 'meta' | 'name' | 'matched'>}\n */\n _getCurrentLocation() {\n if (typeof window === \"undefined\")\n return { path: \"/\", query: {}, fullUrl: \"\" };\n let path, queryString, fullUrl;\n switch (this.options.mode) {\n case \"hash\":\n fullUrl = window.location.hash.slice(1) || \"/\";\n [path, queryString] = fullUrl.split(\"?\");\n break;\n case \"query\":\n const urlParams = new URLSearchParams(window.location.search);\n path = urlParams.get(this.options.queryParam) || \"/\";\n queryString = window.location.search.slice(1);\n fullUrl = path;\n break;\n default: // 'history' mode\n path = window.location.pathname || \"/\";\n queryString = window.location.search.slice(1);\n fullUrl = `${path}${queryString ? \"?\" + queryString : \"\"}`;\n }\n return {\n path: path.startsWith(\"/\") ? path : `/${path}`,\n query: this._parseQuery(queryString),\n fullUrl,\n };\n }\n\n /**\n * Parses a query string into a key-value object.\n * Uses URLSearchParams for robust parsing of encoded values.\n *\n * @private\n * @param {string} queryString - The query string to parse (without leading '?').\n * @returns {QueryParams} Key-value pairs from the query string.\n *\n * @example\n * this._parseQuery('foo=bar&baz=qux');\n * // Returns: { foo: 'bar', baz: 'qux' }\n */\n _parseQuery(queryString) {\n const query = {};\n if (queryString) {\n new URLSearchParams(queryString).forEach((value, key) => {\n query[key] = value;\n });\n }\n return query;\n }\n\n /**\n * Matches a given path against the registered routes.\n * @private\n * @param {string} path - The path to match.\n * @returns {{route: RouteDefinition, params: Object<string, string>} | null} The matched route and its params, or null.\n */\n _matchRoute(path) {\n const pathSegments = path.split(\"/\").filter(Boolean);\n\n for (const route of this.routes) {\n // Handle the root path as a special case.\n if (route.path === \"/\") {\n if (pathSegments.length === 0) return { route, params: {} };\n continue;\n }\n\n if (route.segments.length !== pathSegments.length) continue;\n\n const params = {};\n let isMatch = true;\n for (let i = 0; i < route.segments.length; i++) {\n const routeSegment = route.segments[i];\n const pathSegment = pathSegments[i];\n if (routeSegment.type === \"param\") {\n params[routeSegment.name] = decodeURIComponent(pathSegment);\n } else if (routeSegment.value !== pathSegment) {\n isMatch = false;\n break;\n }\n }\n if (isMatch) return { route, params };\n }\n return null;\n }\n\n // ============================================\n // Dynamic Route Management API\n // ============================================\n\n /**\n * Adds a new route dynamically at runtime.\n * The route will be processed and available for navigation immediately.\n * Routes are inserted before the wildcard (*) route if one exists.\n *\n * @param {RouteDefinition} route - The route definition to add.\n * @param {RouteDefinition} [parentRoute] - Optional parent route to add as a child (not yet implemented).\n * @returns {() => void} A function to remove the added route (returns no-op if route was invalid).\n * @emits router:routeAdded When a route is successfully added.\n *\n * @example\n * // Add a route dynamically\n * const removeRoute = router.addRoute({\n * path: '/dynamic',\n * component: DynamicPage,\n * meta: { title: 'Dynamic Page' }\n * });\n *\n * // Later, remove the route\n * removeRoute();\n */\n addRoute(route, parentRoute = null) {\n if (!route || !route.path) {\n this.errorHandler.warn(\"Invalid route definition: missing path\", {\n route,\n });\n return () => {};\n }\n\n // Check if route already exists\n if (this.hasRoute(route.path)) {\n this.errorHandler.warn(`Route \"${route.path}\" already exists`, { route });\n return () => {};\n }\n\n // Process the route (parse segments)\n const processedRoute = {\n ...route,\n segments: this._parsePathIntoSegments(route.path),\n };\n\n // Add to routes array (before wildcard if exists)\n const wildcardIndex = this.routes.findIndex((r) => r.path === \"*\");\n if (wildcardIndex !== -1) {\n this.routes.splice(wildcardIndex, 0, processedRoute);\n } else {\n this.routes.push(processedRoute);\n }\n\n // Emit event for plugins\n this.emitter.emit(\"router:routeAdded\", processedRoute);\n\n // Return removal function\n return () => this.removeRoute(route.path);\n }\n\n /**\n * Removes a route by its path.\n *\n * @param {string} path - The path of the route to remove.\n * @returns {boolean} True if the route was removed, false if not found.\n * @emits router:routeRemoved When a route is successfully removed.\n *\n * @example\n * router.removeRoute('/dynamic');\n */\n removeRoute(path) {\n const index = this.routes.findIndex((r) => r.path === path);\n if (index === -1) {\n return false;\n }\n\n const [removedRoute] = this.routes.splice(index, 1);\n\n // Emit event for plugins\n this.emitter.emit(\"router:routeRemoved\", removedRoute);\n\n return true;\n }\n\n /**\n * Checks if a route with the given path exists.\n *\n * @param {string} path - The path to check.\n * @returns {boolean} True if the route exists.\n *\n * @example\n * if (router.hasRoute('/users/:id')) {\n * console.log('User route exists');\n * }\n */\n hasRoute(path) {\n return this.routes.some((r) => r.path === path);\n }\n\n /**\n * Gets all registered routes.\n *\n * @returns {RouteDefinition[]} A copy of the routes array.\n *\n * @example\n * const routes = router.getRoutes();\n * console.log('Available routes:', routes.map(r => r.path));\n */\n getRoutes() {\n return [...this.routes];\n }\n\n /**\n * Gets a route by its path.\n *\n * @param {string} path - The path of the route to get.\n * @returns {RouteDefinition | undefined} The route definition or undefined.\n *\n * @example\n * const route = router.getRoute('/users/:id');\n * if (route) {\n * console.log('Route meta:', route.meta);\n * }\n */\n getRoute(path) {\n return this.routes.find((r) => r.path === path);\n }\n\n // ============================================\n // Hook Registration Methods\n // ============================================\n\n /**\n * Registers a global pre-navigation guard.\n * Multiple guards can be registered and will be executed in order.\n * Guards can also be registered via the emitter using `router:beforeEach` event.\n *\n * @param {NavigationGuard} guard - The guard function to register.\n * @returns {() => void} A function to unregister the guard.\n *\n * @example\n * // Register a guard\n * const unregister = router.onBeforeEach((to, from) => {\n * if (to.meta.requiresAuth && !isAuthenticated()) {\n * return '/login';\n * }\n * });\n *\n * // Later, unregister the guard\n * unregister();\n */\n onBeforeEach(guard) {\n this._beforeEachGuards.push(guard);\n return () => {\n const index = this._beforeEachGuards.indexOf(guard);\n if (index > -1) {\n this._beforeEachGuards.splice(index, 1);\n }\n };\n }\n /**\n * Registers a global hook that runs after a new route component has been mounted.\n * @param {NavigationHook} hook - The hook function to register.\n * @returns {() => void} A function to unregister the hook.\n * @listens router:afterEnter\n */\n onAfterEnter(hook) {\n return this.emitter.on(\"router:afterEnter\", hook);\n }\n\n /**\n * Registers a global hook that runs after a route component has been unmounted.\n * @param {NavigationHook} hook - The hook function to register.\n * @returns {() => void} A function to unregister the hook.\n * @listens router:afterLeave\n */\n onAfterLeave(hook) {\n return this.emitter.on(\"router:afterLeave\", hook);\n }\n\n /**\n * Registers a global hook that runs after a navigation has been confirmed and all hooks have completed.\n * @param {NavigationHook} hook - The hook function to register.\n * @returns {() => void} A function to unregister the hook.\n * @listens router:afterEach\n */\n onAfterEach(hook) {\n return this.emitter.on(\"router:afterEach\", hook);\n }\n\n /**\n * Registers a global error handler for navigation errors.\n * @param {(error: Error, to?: RouteLocation, from?: RouteLocation) => void} handler - The error handler function.\n * @returns {() => void} A function to unregister the handler.\n * @listens router:error\n */\n onError(handler) {\n return this.emitter.on(\"router:error\", handler);\n }\n\n /**\n * Registers a plugin with the router.\n * Logs a warning if the plugin is already registered.\n *\n * @param {RouterPlugin} plugin - The plugin to register (must have install method).\n * @param {Record<string, unknown>} [options={}] - Options to pass to plugin.install().\n * @returns {void}\n * @throws {Error} If plugin does not have an install method.\n */\n use(plugin, options = {}) {\n if (typeof plugin.install !== \"function\") {\n this.errorHandler.handle(\n new Error(\"Plugin must have an install method\"),\n \"Plugin registration failed\",\n { plugin }\n );\n }\n\n // Check if plugin is already registered\n if (this.plugins.has(plugin.name)) {\n this.errorHandler.warn(`Plugin \"${plugin.name}\" is already registered`, {\n existingPlugin: this.plugins.get(plugin.name),\n });\n return;\n }\n\n this.plugins.set(plugin.name, plugin);\n plugin.install(this, options);\n }\n\n /**\n * Gets all registered plugins.\n * @returns {RouterPlugin[]} Array of registered plugins.\n */\n getPlugins() {\n return Array.from(this.plugins.values());\n }\n\n /**\n * Gets a plugin by name.\n * @param {string} name - The plugin name.\n * @returns {RouterPlugin | undefined} The plugin or undefined.\n */\n getPlugin(name) {\n return this.plugins.get(name);\n }\n\n /**\n * Removes a plugin from the router.\n * @param {string} name - The plugin name.\n * @returns {boolean} True if the plugin was removed.\n */\n removePlugin(name) {\n const plugin = this.plugins.get(name);\n if (!plugin) return false;\n\n // Call destroy if available\n if (typeof plugin.destroy === \"function\") {\n try {\n plugin.destroy(this);\n } catch (error) {\n this.errorHandler.log(`Plugin ${name} destroy failed`, error);\n }\n }\n\n return this.plugins.delete(name);\n }\n\n /**\n * Sets a custom error handler. Used by error handling plugins.\n * Logs a warning if the provided handler is invalid (missing required methods).\n * @param {RouterErrorHandler} errorHandler - The error handler object with handle, warn, and log methods.\n * @returns {void}\n */\n setErrorHandler(errorHandler) {\n if (\n errorHandler &&\n typeof errorHandler.handle === \"function\" &&\n typeof errorHandler.warn === \"function\" &&\n typeof errorHandler.log === \"function\"\n ) {\n this.errorHandler = errorHandler;\n } else {\n console.warn(\n \"[ElevaRouter] Invalid error handler provided. Must have handle, warn, and log methods.\"\n );\n }\n }\n}\n\n/**\n * @class 🚀 RouterPlugin\n * @classdesc A powerful, reactive, and flexible Router Plugin for Eleva applications.\n * This plugin provides comprehensive client-side routing functionality including:\n * - Multiple routing modes (hash, history, query)\n * - Navigation guards and lifecycle hooks\n * - Reactive state management\n * - Component resolution and lazy loading\n * - Layout and page component separation\n * - Plugin system for extensibility\n * - Advanced error handling\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n *\n * const HomePage = { template: () => `<h1>Home</h1>` };\n * const AboutPage = { template: () => `<h1>About Us</h1>` };\n * const UserPage = {\n * template: (ctx) => `<h1>User: ${ctx.router.params.id}</h1>`\n * };\n *\n * app.use(RouterPlugin, {\n * mount: '#app',\n * mode: 'hash',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/about', component: AboutPage },\n * { path: '/users/:id', component: UserPage }\n * ]\n * });\n */\nexport const RouterPlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"router\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.1.1\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description: \"Client-side routing for Eleva applications\",\n\n /**\n * Installs the RouterPlugin into an Eleva instance.\n *\n * @public\n * @param {Eleva} eleva - The Eleva instance.\n * @param {RouterOptions} options - Router configuration options.\n * @param {string} options.mount - A CSS selector for the main element where the app is mounted.\n * @param {RouteDefinition[]} options.routes - An array of route definitions.\n * @param {'hash' | 'query' | 'history'} [options.mode='hash'] - The routing mode.\n * @param {string} [options.queryParam='view'] - The query parameter to use in 'query' mode.\n * @param {string} [options.viewSelector='view'] - Base selector for the view element (matched as #id, .class, [data-*], or raw selector).\n * @param {boolean} [options.autoStart=true] - Whether to start the router automatically.\n * @param {NavigationGuard} [options.onBeforeEach] - A global guard executed before every navigation.\n * @param {RouteComponent} [options.globalLayout] - A global layout for all routes.\n * @returns {Router} The created router instance.\n * @throws {Error} If 'mount' option is not provided.\n * @throws {Error} If 'routes' option is not an array.\n * @throws {Error} If component registration fails during route processing.\n * @description\n * Registers route/layout components, sets `eleva.router`, and adds helpers\n * (`eleva.navigate`, `eleva.getCurrentRoute`, `eleva.getRouteParams`, `eleva.getRouteQuery`).\n * When `autoStart` is enabled, startup is scheduled via microtask.\n *\n * @example\n * // main.js\n * import Eleva from 'eleva';\n * import { RouterPlugin } from './plugins/RouterPlugin.js';\n *\n * const app = new Eleva('myApp');\n *\n * const HomePage = { template: () => `<h1>Home</h1>` };\n * const AboutPage = { template: () => `<h1>About Us</h1>` };\n *\n * app.use(RouterPlugin, {\n * mount: '#app',\n * routes: [\n * { path: '/', component: HomePage },\n * { path: '/about', component: AboutPage }\n * ]\n * });\n */\n install(eleva, options = {}) {\n if (!options.mount) {\n throw new Error(\"[RouterPlugin] 'mount' option is required\");\n }\n\n if (!options.routes || !Array.isArray(options.routes)) {\n throw new Error(\"[RouterPlugin] 'routes' option must be an array\");\n }\n\n /**\n * Registers a component definition with the Eleva instance.\n * This method handles both inline component objects and pre-registered component names.\n *\n * @inner\n * @param {unknown} def - The component definition to register.\n * @param {string} type - The type of component for naming (e.g., \"Route\", \"Layout\").\n * @returns {string | null} The registered component name or null if no definition provided.\n */\n const register = (def, type) => {\n if (!def) return null;\n\n if (typeof def === \"object\" && def !== null && !def.name) {\n const name = `Eleva${type}Component_${Math.random()\n .toString(36)\n .slice(2, 11)}`;\n\n try {\n eleva.component(name, def);\n return name;\n } catch (error) {\n throw new Error(\n `[RouterPlugin] Failed to register ${type} component: ${error.message}`\n );\n }\n }\n return def;\n };\n\n if (options.globalLayout) {\n options.globalLayout = register(options.globalLayout, \"GlobalLayout\");\n }\n\n (options.routes || []).forEach((route) => {\n route.component = register(route.component, \"Route\");\n if (route.layout) {\n route.layout = register(route.layout, \"RouteLayout\");\n }\n });\n\n const router = new Router(eleva, options);\n /** @type {Router} */\n eleva.router = router;\n\n if (options.autoStart !== false) {\n queueMicrotask(() => router.start());\n }\n\n // Add plugin metadata to the Eleva instance\n if (!eleva.plugins) {\n eleva.plugins = new Map();\n }\n eleva.plugins.set(this.name, {\n name: this.name,\n version: this.version,\n description: this.description,\n options,\n });\n\n // Add utility methods for manual router access\n /** @type {NavigateFunction} */\n eleva.navigate = router.navigate.bind(router);\n /** @type {() => RouteLocation | null} */\n eleva.getCurrentRoute = () => router.currentRoute.value;\n /** @type {() => RouteParams} */\n eleva.getRouteParams = () => router.currentParams.value;\n /** @type {() => QueryParams} */\n eleva.getRouteQuery = () => router.currentQuery.value;\n\n return router;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance.\n *\n * @public\n * @async\n * @param {Eleva} eleva - The Eleva instance.\n * @returns {Promise<void>}\n * @description\n * Destroys the router instance, removes `eleva.router`, and deletes helper methods\n * (`eleva.navigate`, `eleva.getCurrentRoute`, `eleva.getRouteParams`, `eleva.getRouteQuery`).\n */\n async uninstall(eleva) {\n if (eleva.router) {\n await eleva.router.destroy();\n delete eleva.router;\n }\n\n // Remove plugin metadata\n if (eleva.plugins) {\n eleva.plugins.delete(this.name);\n }\n\n // Remove utility methods\n delete eleva.navigate;\n delete eleva.getCurrentRoute;\n delete eleva.getRouteParams;\n delete eleva.getRouteQuery;\n },\n};\n\n// Short name export for convenience\nexport { RouterPlugin as Router };\n","\"use strict\";\n\n/**\n * @module eleva/plugins/store\n * @fileoverview Reactive state management plugin with namespaced modules,\n * persistence, and subscription system.\n */\n\n// ============================================================================\n// TYPE DEFINITIONS\n// ============================================================================\n\n// -----------------------------------------------------------------------------\n// External Type Imports\n// -----------------------------------------------------------------------------\n\n/**\n * Type imports from the Eleva core library.\n * @typedef {import('eleva').Eleva} Eleva\n * @typedef {import('eleva').ComponentDefinition} ComponentDefinition\n * @typedef {import('eleva').ComponentContext} ComponentContext\n * @typedef {import('eleva').SetupResult} SetupResult\n * @typedef {import('eleva').ComponentProps} ComponentProps\n * @typedef {import('eleva').ChildrenMap} ChildrenMap\n * @typedef {import('eleva').MountResult} MountResult\n */\n\n/**\n * Generic type import.\n * @template T\n * @typedef {import('eleva').Signal<T>} Signal\n */\n\n// -----------------------------------------------------------------------------\n// Store Type Definitions\n// -----------------------------------------------------------------------------\n\n/**\n * Mutation record emitted to subscribers.\n * @typedef {Object} StoreMutation\n * @property {string} type\n * The action name that was dispatched.\n * @property {unknown} payload\n * The payload passed to the action.\n * @property {number} timestamp\n * Unix timestamp of when the mutation occurred.\n * @description Record passed to subscribers when state changes via dispatch.\n * @example\n * store.subscribe((mutation, state) => {\n * console.log(`Action: ${mutation.type}`);\n * console.log(`Payload: ${mutation.payload}`);\n * console.log(`Time: ${new Date(mutation.timestamp)}`);\n * });\n */\n\n/**\n * Store configuration options.\n * @typedef {Object} StoreOptions\n * @property {Record<string, unknown>} [state]\n * Initial state object.\n * @property {Record<string, ActionFunction>} [actions]\n * Action functions for state mutations.\n * @property {Record<string, StoreModule>} [namespaces]\n * Namespaced modules for organizing store.\n * @property {StorePersistenceOptions} [persistence]\n * Persistence configuration.\n * @property {boolean} [devTools]\n * Enable development tools integration.\n * @property {StoreErrorHandler} [onError]\n * Error handler function.\n * @description Configuration options passed to StorePlugin.install().\n * @example\n * app.use(StorePlugin, {\n * state: { count: 0, user: null },\n * actions: {\n * increment: (state) => state.count.value++,\n * setUser: (state, user) => state.user.value = user\n * },\n * persistence: { enabled: true, key: 'my-app' }\n * });\n */\n\n/**\n * Namespaced store module definition.\n * @typedef {Object} StoreModule\n * @property {Record<string, unknown>} state\n * Module state.\n * @property {Record<string, ActionFunction>} [actions]\n * Module actions.\n * @description Defines a namespaced module for organizing related state and actions.\n * @example\n * // Define a module\n * const authModule = {\n * state: { user: null, token: null },\n * actions: {\n * login: (state, { user, token }) => {\n * state.auth.user.value = user;\n * state.auth.token.value = token;\n * }\n * }\n * };\n *\n * // Register dynamically\n * store.registerModule('auth', authModule);\n */\n\n/**\n * Store persistence configuration.\n * @typedef {Object} StorePersistenceOptions\n * @property {boolean} [enabled]\n * Enable state persistence.\n * @property {string} [key]\n * Storage key (default: \"eleva-store\").\n * @property {'localStorage' | 'sessionStorage'} [storage]\n * Storage type.\n * @property {string[]} [include]\n * Dot-path prefixes to persist (e.g., \"auth.user\").\n * @property {string[]} [exclude]\n * Dot-path prefixes to exclude.\n * @description Configuration for persisting store state to localStorage or sessionStorage.\n * @example\n * // Persist only specific state paths\n * persistence: {\n * enabled: true,\n * key: 'my-app-store',\n * storage: 'localStorage',\n * include: ['user', 'settings.theme']\n * }\n *\n * @example\n * // Exclude sensitive data\n * persistence: {\n * enabled: true,\n * exclude: ['auth.token', 'temp']\n * }\n */\n\n/**\n * Store error handler callback.\n * @typedef {(error: Error, context: string) => void} StoreErrorHandler\n * @description Custom error handler for store operations.\n * @example\n * app.use(StorePlugin, {\n * onError: (error, context) => {\n * console.error(`Store error in ${context}:`, error);\n * // Send to error tracking service\n * errorTracker.capture(error, { context });\n * }\n * });\n */\n\n/**\n * Reactive state tree containing signals and nested namespaces.\n * @typedef {Record<string, Signal<unknown> | Record<string, unknown>>} StoreState\n * @description Represents the store's reactive state structure with support for nested modules.\n */\n\n/**\n * Action function signature for store actions.\n * @typedef {(state: StoreState, payload?: unknown) => unknown} ActionFunction\n * @description Function that receives state and optional payload, returns action result.\n */\n\n/**\n * Dispatch function signature for triggering actions.\n * @typedef {(actionName: string, payload?: unknown) => Promise<unknown>} DispatchFunction\n * @description Dispatches an action by name with optional payload, returns action result.\n */\n\n/**\n * Subscribe callback signature for mutation listeners.\n * @typedef {(mutation: StoreMutation, state: StoreState) => void} SubscribeCallback\n * @description Called after each successful action dispatch with mutation details and current state.\n */\n\n/**\n * Store API exposed to components via ctx.store.\n * @typedef {Object} StoreApi\n * @property {StoreState} state\n * Reactive state signals (supports nested modules).\n * @property {DispatchFunction} dispatch\n * Dispatch an action by name with optional payload.\n * @property {(callback: SubscribeCallback) => () => void} subscribe\n * Subscribe to state mutations. Returns unsubscribe function.\n * @property {() => Record<string, unknown>} getState\n * Get a snapshot of current state values.\n * @property {(namespace: string, module: StoreModule) => void} registerModule\n * Register a namespaced module dynamically.\n * @property {(namespace: string) => void} unregisterModule\n * Unregister a namespaced module.\n * @property {(key: string, initialValue: unknown) => Signal<unknown>} createState\n * Create a new state signal dynamically.\n * @property {(name: string, actionFn: ActionFunction) => void} createAction\n * Register a new action dynamically.\n * @property {new <T>(value: T) => Signal<T>} signal\n * Signal class constructor for manual state creation.\n * @description The store API injected into component setup as `ctx.store`.\n * @example\n * app.component('Counter', {\n * setup({ store }) {\n * // Access reactive state\n * const count = store.state.count;\n *\n * // Dispatch actions\n * const increment = () => store.dispatch('increment');\n *\n * // Subscribe to changes\n * const unsub = store.subscribe((mutation) => {\n * console.log('State changed:', mutation.type);\n * });\n *\n * return { count, increment, onUnmount: () => unsub() };\n * },\n * template: (ctx) => `<button @click=\"increment\">${ctx.count.value}</button>`\n * });\n * @see StoreMutation - Mutation record structure.\n * @see StoreModule - Module definition for namespaces.\n */\n\n/**\n * @class 🏪 StorePlugin\n * @classdesc A powerful reactive state management plugin for Eleva that enables sharing\n * reactive data across the entire application. The Store plugin provides a centralized,\n * reactive data store that can be accessed from any component's setup function.\n *\n * Core Features:\n * - Centralized reactive state management using Eleva's signal system\n * - Global state accessibility through component setup functions\n * - Namespace support for organizing store modules\n * - Built-in persistence with localStorage/sessionStorage support\n * - Action-based state mutations with validation\n * - Subscription system for reactive updates\n * - DevTools integration for debugging\n * - Plugin architecture for extensibility\n *\n * @example\n * // Install the plugin\n * const app = new Eleva(\"myApp\");\n * app.use(StorePlugin, {\n * state: {\n * user: { name: \"John\", email: \"john@example.com\" },\n * counter: 0,\n * todos: []\n * },\n * actions: {\n * increment: (state) => state.counter.value++,\n * addTodo: (state, todo) => state.todos.value = [...state.todos.value, todo],\n * setUser: (state, user) => state.user.value = user\n * },\n * persistence: {\n * enabled: true,\n * key: \"myApp-store\",\n * storage: \"localStorage\"\n * }\n * });\n *\n * // Use store in components\n * app.component(\"Counter\", {\n * setup({ store }) {\n * return {\n * count: store.state.counter,\n * increment: () => store.dispatch(\"increment\"),\n * user: store.state.user\n * };\n * },\n * template: (ctx) => `\n * <div>\n * <p>Hello ${ctx.user.value.name}!</p>\n * <p>Count: ${ctx.count.value}</p>\n * <button @click=\"increment\">+</button>\n * </div>\n * `\n * });\n */\nexport const StorePlugin = {\n /**\n * Unique identifier for the plugin\n * @type {string}\n */\n name: \"store\",\n\n /**\n * Plugin version\n * @type {string}\n */\n version: \"1.1.1\",\n\n /**\n * Plugin description\n * @type {string}\n */\n description:\n \"Reactive state management for sharing data across the entire Eleva application\",\n\n /**\n * Installs the plugin into the Eleva instance.\n *\n * @public\n * @param {Eleva} eleva - The Eleva instance.\n * @param {StoreOptions} options - Plugin configuration options.\n * @param {Record<string, unknown>} [options.state={}] - Initial state object.\n * @param {Record<string, ActionFunction>} [options.actions={}] - Action functions for state mutations.\n * @param {Record<string, StoreModule>} [options.namespaces={}] - Namespaced modules for organizing store.\n * @param {StorePersistenceOptions} [options.persistence] - Persistence configuration.\n * @param {boolean} [options.persistence.enabled=false] - Enable state persistence.\n * @param {string} [options.persistence.key=\"eleva-store\"] - Storage key.\n * @param {'localStorage' | 'sessionStorage'} [options.persistence.storage=\"localStorage\"] - Storage type.\n * @param {string[]} [options.persistence.include] - Dot-path prefixes to persist (e.g., \"auth.user\")\n * @param {string[]} [options.persistence.exclude] - Dot-path prefixes to exclude (applies when include is empty).\n * @param {boolean} [options.devTools=false] - Enable development tools integration.\n * @param {(error: Error, context: string) => void} [options.onError=null] - Error handler function.\n * @returns {void}\n * @description\n * Installs the store and injects `store` into component setup context by wrapping\n * `eleva.mount` and `eleva._mountComponents`. Also exposes `eleva.store` and\n * helper methods (`eleva.dispatch`, `eleva.getState`, `eleva.subscribe`, `eleva.createAction`).\n * Uninstall restores the originals.\n *\n * @example\n * // Basic installation\n * app.use(StorePlugin, {\n * state: { count: 0, user: null },\n * actions: {\n * increment: (state) => state.count.value++,\n * setUser: (state, user) => state.user.value = user\n * }\n * });\n *\n * // Advanced installation with persistence and namespaces\n * app.use(StorePlugin, {\n * state: { theme: \"light\" },\n * namespaces: {\n * auth: {\n * state: { user: null, token: null },\n * actions: {\n * login: (state, { user, token }) => {\n * state.auth.user.value = user;\n * state.auth.token.value = token;\n * },\n * logout: (state) => {\n * state.auth.user.value = null;\n * state.auth.token.value = null;\n * }\n * }\n * }\n * },\n * persistence: {\n * enabled: true,\n * include: [\"theme\", \"auth.user\"]\n * }\n * });\n */\n install(eleva, options = {}) {\n const {\n state = {},\n actions = {},\n namespaces = {},\n persistence = {},\n devTools = false,\n onError = null,\n } = options;\n\n /**\n * @class Store\n * @classdesc Store instance that manages all state and provides the API.\n * @private\n */\n class Store {\n /**\n * Creates a new Store instance.\n * Initializes state signals, actions, persistence, and devtools integration.\n *\n * @constructor\n */\n constructor() {\n /** @type {Record<string, Signal | Record<string, unknown>>} */\n this.state = {};\n /** @type {Record<string, ActionFunction | Record<string, ActionFunction>>} */\n this.actions = {};\n /** @type {Set<SubscribeCallback>} */\n this.subscribers = new Set();\n /** @type {StoreMutation[]} */\n this.mutations = [];\n /** @type {{enabled: boolean, key: string, storage: string, include: string[]|null, exclude: string[]|null}} */\n this.persistence = {\n enabled: false,\n key: \"eleva-store\",\n storage: \"localStorage\",\n include: null,\n exclude: null,\n ...persistence,\n };\n /** @type {boolean} */\n this.devTools = devTools;\n /** @type {((error: Error, context: string) => void)|null} */\n this.onError = onError;\n\n this._initializeState(state, actions);\n this._initializeNamespaces(namespaces);\n this._loadPersistedState();\n this._setupDevTools();\n }\n\n /**\n * Initializes the root state and actions.\n * Creates reactive signals for each state property and copies actions.\n *\n * @private\n * @param {Record<string, unknown>} initialState - The initial state key-value pairs.\n * @param {Record<string, ActionFunction>} initialActions - The action functions to register.\n * @returns {void}\n */\n _initializeState(initialState, initialActions) {\n // Create reactive signals for each state property\n Object.entries(initialState).forEach(([key, value]) => {\n this.state[key] = new eleva.signal(value);\n });\n\n // Set up actions\n this.actions = { ...initialActions };\n }\n\n /**\n * Initializes namespaced modules.\n * Creates namespace objects and populates them with state signals and actions.\n *\n * @private\n * @param {Record<string, StoreModule>} namespaces - Map of namespace names to module definitions.\n * @returns {void}\n */\n _initializeNamespaces(namespaces) {\n Object.entries(namespaces).forEach(([namespace, module]) => {\n const { state: moduleState = {}, actions: moduleActions = {} } =\n module;\n\n // Create namespace object if it doesn't exist\n if (!this.state[namespace]) {\n this.state[namespace] = {};\n }\n if (!this.actions[namespace]) {\n this.actions[namespace] = {};\n }\n\n // Initialize namespaced state\n Object.entries(moduleState).forEach(([key, value]) => {\n this.state[namespace][key] = new eleva.signal(value);\n });\n\n // Set up namespaced actions\n this.actions[namespace] = { ...moduleActions };\n });\n }\n\n /**\n * Loads persisted state from storage.\n * Reads from localStorage/sessionStorage and applies values to state signals.\n * Does nothing if persistence is disabled or running in SSR environment.\n *\n * @private\n * @returns {void}\n */\n _loadPersistedState() {\n if (!this.persistence.enabled || typeof window === \"undefined\") {\n return;\n }\n\n try {\n const storage = window[this.persistence.storage];\n const persistedData = storage.getItem(this.persistence.key);\n\n if (persistedData) {\n const data = JSON.parse(persistedData);\n this._applyPersistedData(data);\n }\n } catch (error) {\n if (this.onError) {\n this.onError(error, \"Failed to load persisted state\");\n } else {\n console.warn(\n \"[StorePlugin] Failed to load persisted state:\",\n error\n );\n }\n }\n }\n\n /**\n * Applies persisted data to the current state.\n * Recursively updates signal values for paths that should be persisted.\n *\n * @private\n * @param {Record<string, unknown>} data - The persisted data object to apply.\n * @param {Record<string, unknown>} [currentState=this.state] - The current state object to update.\n * @param {string} [path=\"\"] - The current dot-notation path (for include/exclude filtering).\n * @returns {void}\n */\n _applyPersistedData(data, currentState = this.state, path = \"\") {\n Object.entries(data).forEach(([key, value]) => {\n const fullPath = path ? `${path}.${key}` : key;\n\n if (this._shouldPersist(fullPath)) {\n if (\n currentState[key] &&\n typeof currentState[key] === \"object\" &&\n \"value\" in currentState[key]\n ) {\n // This is a signal, update its value\n currentState[key].value = value;\n } else if (\n typeof value === \"object\" &&\n value !== null &&\n currentState[key]\n ) {\n // This is a nested object, recurse\n this._applyPersistedData(value, currentState[key], fullPath);\n }\n }\n });\n }\n\n /**\n * Determines if a state path should be persisted.\n * Checks against include/exclude filters configured in persistence options.\n *\n * @private\n * @param {string} path - The dot-notation path to check (e.g., \"auth.user\").\n * @returns {boolean} True if the path should be persisted, false otherwise.\n */\n _shouldPersist(path) {\n const { include, exclude } = this.persistence;\n\n if (include && include.length > 0) {\n return include.some((includePath) => path.startsWith(includePath));\n }\n\n if (exclude && exclude.length > 0) {\n return !exclude.some((excludePath) => path.startsWith(excludePath));\n }\n\n return true;\n }\n\n /**\n * Saves current state to storage.\n * Extracts persistable data and writes to localStorage/sessionStorage.\n * Does nothing if persistence is disabled or running in SSR environment.\n *\n * @private\n * @returns {void}\n */\n _saveState() {\n if (!this.persistence.enabled || typeof window === \"undefined\") {\n return;\n }\n\n try {\n const storage = window[this.persistence.storage];\n const dataToSave = this._extractPersistedData();\n storage.setItem(this.persistence.key, JSON.stringify(dataToSave));\n } catch (error) {\n if (this.onError) {\n this.onError(error, \"Failed to save state\");\n } else {\n console.warn(\"[StorePlugin] Failed to save state:\", error);\n }\n }\n }\n\n /**\n * Extracts data that should be persisted.\n * Recursively extracts signal values for paths that pass persistence filters.\n *\n * @private\n * @param {Record<string, unknown>} [currentState=this.state] - The state object to extract from.\n * @param {string} [path=\"\"] - The current dot-notation path (for include/exclude filtering).\n * @returns {Record<string, unknown>} The extracted data object with raw values (not signals).\n */\n _extractPersistedData(currentState = this.state, path = \"\") {\n const result = {};\n\n Object.entries(currentState).forEach(([key, value]) => {\n const fullPath = path ? `${path}.${key}` : key;\n\n if (this._shouldPersist(fullPath)) {\n if (value && typeof value === \"object\" && \"value\" in value) {\n // This is a signal, extract its value\n result[key] = value.value;\n } else if (typeof value === \"object\" && value !== null) {\n // This is a nested object, recurse\n const nestedData = this._extractPersistedData(value, fullPath);\n if (Object.keys(nestedData).length > 0) {\n result[key] = nestedData;\n }\n }\n }\n });\n\n return result;\n }\n\n /**\n * Sets up development tools integration.\n * Registers the store with Eleva DevTools if available and enabled.\n * Does nothing if devTools is disabled, running in SSR, or DevTools not installed.\n *\n * @private\n * @returns {void}\n */\n _setupDevTools() {\n if (\n !this.devTools ||\n typeof window === \"undefined\" ||\n !window.__ELEVA_DEVTOOLS__\n ) {\n return;\n }\n\n window.__ELEVA_DEVTOOLS__.registerStore(this);\n }\n\n /**\n * Dispatches an action to mutate the state.\n *\n * Execution flow:\n * 1. Retrieves the action function (supports namespaced actions like \"auth.login\")\n * 2. Records mutation for devtools/history (keeps last 100 mutations)\n * 3. Executes action with await (actions can be sync or async)\n * 4. Saves state if persistence is enabled\n * 5. Notifies all subscribers with (mutation, state)\n * 6. Notifies devtools if enabled\n *\n * @note Always returns a Promise regardless of whether the action is sync or async.\n * Subscriber callbacks that throw are caught and passed to onError handler.\n *\n * @async\n * @param {string} actionName - The name of the action to dispatch (supports dot notation for namespaces).\n * @param {unknown} payload - The payload to pass to the action.\n * @returns {Promise<unknown>} The result of the action (undefined if action returns nothing).\n * @throws {Error} If action is not found or action function throws.\n * @see subscribe - Listen for mutations triggered by dispatch.\n * @see getState - Get current state values.\n */\n async dispatch(actionName, payload) {\n try {\n const action = this._getAction(actionName);\n\n if (!action) {\n const error = new Error(`Action \"${actionName}\" not found`);\n if (this.onError) {\n this.onError(error, actionName);\n }\n throw error;\n }\n\n const mutation = {\n type: actionName,\n payload,\n timestamp: Date.now(),\n };\n\n // Record mutation for devtools\n this.mutations.push(mutation);\n if (this.mutations.length > 100) {\n this.mutations.shift(); // Keep only last 100 mutations\n }\n\n // Execute the action\n const result = await action.call(null, this.state, payload);\n\n // Save state if persistence is enabled\n this._saveState();\n\n // Notify subscribers\n this.subscribers.forEach((callback) => {\n try {\n callback(mutation, this.state);\n } catch (error) {\n if (this.onError) {\n this.onError(error, \"Subscriber callback failed\");\n }\n }\n });\n\n // Notify devtools\n if (\n this.devTools &&\n typeof window !== \"undefined\" &&\n window.__ELEVA_DEVTOOLS__\n ) {\n window.__ELEVA_DEVTOOLS__.notifyMutation(mutation, this.state);\n }\n\n return result;\n } catch (error) {\n if (this.onError) {\n this.onError(error, `Action dispatch failed: ${actionName}`);\n }\n throw error;\n }\n }\n\n /**\n * Gets an action by name (supports namespaced actions).\n * Traverses the actions object using dot-notation path segments.\n *\n * @private\n * @param {string} actionName - The action name, supports dot notation for namespaces (e.g., \"auth.login\").\n * @returns {ActionFunction | null} The action function if found and is a function, null otherwise.\n */\n _getAction(actionName) {\n const parts = actionName.split(\".\");\n let current = this.actions;\n\n for (const part of parts) {\n if (current[part] === undefined) {\n return null;\n }\n current = current[part];\n }\n\n return typeof current === \"function\" ? current : null;\n }\n\n /**\n * Subscribes to store mutations.\n * Callback is invoked after every successful action dispatch.\n *\n * @param {SubscribeCallback} callback\n * Called after each mutation with:\n * - mutation.type: The action name that was dispatched\n * - mutation.payload: The payload passed to the action\n * - mutation.timestamp: When the mutation occurred (Date.now())\n * - state: The current state object (contains Signals)\n * @returns {() => void} Unsubscribe function. Call to stop receiving notifications.\n * @throws {Error} If callback is not a function.\n * @see dispatch - Triggers mutations that notify subscribers.\n */\n subscribe(callback) {\n if (typeof callback !== \"function\") {\n throw new Error(\"Subscribe callback must be a function\");\n }\n\n this.subscribers.add(callback);\n\n // Return unsubscribe function\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n /**\n * Gets current state values (not signals).\n *\n * @note When persistence include/exclude filters are configured,\n * this returns only the filtered subset of state.\n * @returns {Record<string, unknown>} The current state values (filtered by persistence config if set).\n * @see replaceState - Set state values.\n * @see subscribe - Listen for state changes.\n */\n getState() {\n return this._extractPersistedData();\n }\n\n /**\n * Replaces state values (useful for testing or state hydration).\n *\n * @note When persistence include/exclude filters are configured,\n * this only updates the filtered subset of state.\n * @param {Record<string, unknown>} newState - The new state object.\n * @returns {void}\n * @see getState - Get current state values.\n */\n replaceState(newState) {\n this._applyPersistedData(newState);\n this._saveState();\n }\n\n /**\n * Clears persisted state from storage.\n * Does nothing if persistence is disabled or running in SSR.\n * @returns {void}\n */\n clearPersistedState() {\n if (!this.persistence.enabled || typeof window === \"undefined\") {\n return;\n }\n\n try {\n const storage = window[this.persistence.storage];\n storage.removeItem(this.persistence.key);\n } catch (error) {\n if (this.onError) {\n this.onError(error, \"Failed to clear persisted state\");\n }\n }\n }\n\n /**\n * Registers a new namespaced module at runtime.\n * Logs a warning if the namespace already exists.\n * Module state is nested under `state[namespace]` and actions under `actions[namespace]`.\n * @param {string} namespace - The namespace for the module.\n * @param {StoreModule} module - The module definition.\n * @param {Record<string, unknown>} module.state - The module's initial state.\n * @param {Record<string, ActionFunction>} module.actions - The module's actions.\n * @returns {void}\n */\n registerModule(namespace, module) {\n if (this.state[namespace] || this.actions[namespace]) {\n console.warn(`[StorePlugin] Module \"${namespace}\" already exists`);\n return;\n }\n\n // Initialize the module\n this.state[namespace] = {};\n this.actions[namespace] = {};\n\n const namespaces = { [namespace]: module };\n this._initializeNamespaces(namespaces);\n\n this._saveState();\n }\n\n /**\n * Unregisters a namespaced module.\n * Logs a warning if the namespace doesn't exist.\n * Removes both state and actions under the namespace.\n * @param {string} namespace - The namespace to unregister.\n * @returns {void}\n */\n unregisterModule(namespace) {\n if (!this.state[namespace] && !this.actions[namespace]) {\n console.warn(`[StorePlugin] Module \"${namespace}\" does not exist`);\n return;\n }\n\n delete this.state[namespace];\n delete this.actions[namespace];\n this._saveState();\n }\n\n /**\n * Creates a new reactive state property at runtime.\n *\n * @param {string} key - The state key.\n * @param {*} initialValue - The initial value.\n * @returns {Signal} The created signal, or existing signal if key exists.\n */\n createState(key, initialValue) {\n if (this.state[key]) {\n return this.state[key]; // Return existing state\n }\n\n this.state[key] = new eleva.signal(initialValue);\n this._saveState();\n return this.state[key];\n }\n\n /**\n * Creates a new action at runtime.\n * Overwrites existing action if name already exists.\n * Supports dot-notation for namespaced actions (e.g., \"auth.login\").\n * @param {string} name - The action name (supports dot notation for namespaces).\n * @param {ActionFunction} actionFn - The action function (receives state and payload).\n * @returns {void}\n * @throws {Error} If actionFn is not a function.\n * @example\n * // Root-level action\n * store.createAction(\"increment\", (state) => state.count.value++);\n *\n * // Namespaced action\n * store.createAction(\"auth.login\", async (state, credentials) => {\n * // ... login logic\n * });\n */\n createAction(name, actionFn) {\n if (typeof actionFn !== \"function\") {\n throw new Error(\"Action must be a function\");\n }\n\n // Fast path: no dot means simple action (avoids array allocation)\n if (name.indexOf(\".\") === -1) {\n this.actions[name] = actionFn;\n return;\n }\n\n // Namespaced action, traverse/create nested structure\n const parts = name.split(\".\");\n const lastIndex = parts.length - 1;\n let current = this.actions;\n\n for (let i = 0; i < lastIndex; i++) {\n current = current[parts[i]] || (current[parts[i]] = {});\n }\n current[parts[lastIndex]] = actionFn;\n }\n }\n\n // Create the store instance\n const store = new Store();\n\n // Store the original mount method to override it\n const originalMount = eleva.mount;\n\n /**\n * Overridden mount method that injects store context into components.\n * Wraps the original mount to add `ctx.store` to the component's setup context.\n *\n * @param {HTMLElement} container - The DOM element where the component will be mounted.\n * @param {string | ComponentDefinition} compName - Component name or definition.\n * @param {ComponentProps} [props={}] - Optional properties to pass to the component.\n * @returns {Promise<MountResult>} The mount result.\n */\n eleva.mount = async (container, compName, props = {}) => {\n // Get the component definition\n const componentDef =\n typeof compName === \"string\"\n ? eleva._components.get(compName) || compName\n : compName;\n\n if (!componentDef) {\n return await originalMount.call(eleva, container, compName, props);\n }\n\n // Create a wrapped component that injects store into setup\n const wrappedComponent = {\n ...componentDef,\n async setup(ctx) {\n /** @type {StoreApi} */\n ctx.store = {\n // Core store functionality\n state: store.state,\n dispatch: store.dispatch.bind(store),\n subscribe: store.subscribe.bind(store),\n getState: store.getState.bind(store),\n\n // Module management\n registerModule: store.registerModule.bind(store),\n unregisterModule: store.unregisterModule.bind(store),\n\n // Utilities for dynamic state/action creation\n createState: store.createState.bind(store),\n createAction: store.createAction.bind(store),\n\n // Access to signal constructor for manual state creation\n signal: eleva.signal,\n };\n\n // Call original setup if it exists\n const originalSetup = componentDef.setup;\n const result = originalSetup ? await originalSetup(ctx) : {};\n\n return result;\n },\n };\n\n // Call original mount with wrapped component\n return await originalMount.call(\n eleva,\n container,\n wrappedComponent,\n props\n );\n };\n\n // Override _mountComponents to ensure child components also get store context\n const originalMountComponents = eleva._mountComponents;\n\n /**\n * Overridden _mountComponents method that injects store context into child components.\n * Wraps each child component's setup function to add `ctx.store` before mounting.\n *\n * @param {HTMLElement} container - The parent container element.\n * @param {ChildrenMap} children - Map of selectors to component definitions.\n * @param {MountResult[]} childInstances - Array to store mounted instances.\n * @param {ComponentContext & SetupResult} context - Parent component context.\n * @returns {Promise<void>}\n */\n eleva._mountComponents = async (\n container,\n children,\n childInstances,\n context\n ) => {\n // Create wrapped children with store injection\n const wrappedChildren = {};\n\n for (const [selector, childComponent] of Object.entries(children)) {\n const componentDef =\n typeof childComponent === \"string\"\n ? eleva._components.get(childComponent) || childComponent\n : childComponent;\n\n if (componentDef && typeof componentDef === \"object\") {\n wrappedChildren[selector] = {\n ...componentDef,\n async setup(ctx) {\n /** @type {StoreApi} */\n ctx.store = {\n // Core store functionality\n state: store.state,\n dispatch: store.dispatch.bind(store),\n subscribe: store.subscribe.bind(store),\n getState: store.getState.bind(store),\n\n // Module management\n registerModule: store.registerModule.bind(store),\n unregisterModule: store.unregisterModule.bind(store),\n\n // Utilities for dynamic state/action creation\n createState: store.createState.bind(store),\n createAction: store.createAction.bind(store),\n\n // Access to signal constructor for manual state creation\n signal: eleva.signal,\n };\n\n // Call original setup if it exists\n const originalSetup = componentDef.setup;\n const result = originalSetup ? await originalSetup(ctx) : {};\n\n return result;\n },\n };\n } else {\n wrappedChildren[selector] = childComponent;\n }\n }\n\n // Call original _mountComponents with wrapped children\n return await originalMountComponents.call(\n eleva,\n container,\n wrappedChildren,\n childInstances,\n context\n );\n };\n\n // Expose store instance and utilities on the Eleva instance\n /** @type {StoreApi} */\n eleva.store = store;\n\n /**\n * Expose utility methods on the Eleva instance.\n * These are top-level helpers (e.g., `eleva.dispatch`) in addition to `eleva.store`.\n */\n /** @type {(name: string, actionFn: ActionFunction) => void} */\n eleva.createAction = (name, actionFn) => {\n store.createAction(name, actionFn);\n };\n\n /** @type {DispatchFunction} */\n eleva.dispatch = (actionName, payload) => {\n return store.dispatch(actionName, payload);\n };\n\n /** @type {() => Record<string, unknown>} */\n eleva.getState = () => {\n return store.getState();\n };\n\n /** @type {(callback: SubscribeCallback) => () => void} */\n eleva.subscribe = (callback) => {\n return store.subscribe(callback);\n };\n\n // Store original methods for cleanup\n eleva._originalMount = originalMount;\n eleva._originalMountComponents = originalMountComponents;\n },\n\n /**\n * Uninstalls the plugin from the Eleva instance.\n *\n * @public\n * @param {Eleva} eleva - The Eleva instance.\n * @returns {void}\n * @description\n * Restores the original Eleva methods and removes all plugin-specific\n * functionality. This method should be called when the plugin is no\n * longer needed.\n * Also removes `eleva.store` and top-level helpers (`eleva.dispatch`,\n * `eleva.getState`, `eleva.subscribe`, `eleva.createAction`).\n *\n * @example\n * // Uninstall the plugin\n * StorePlugin.uninstall(app);\n */\n uninstall(eleva) {\n // Restore original mount method\n if (eleva._originalMount) {\n eleva.mount = eleva._originalMount;\n delete eleva._originalMount;\n }\n\n // Restore original _mountComponents method\n if (eleva._originalMountComponents) {\n eleva._mountComponents = eleva._originalMountComponents;\n delete eleva._originalMountComponents;\n }\n\n // Remove store instance and utility methods\n if (eleva.store) {\n delete eleva.store;\n }\n if (eleva.createAction) {\n delete eleva.createAction;\n }\n if (eleva.dispatch) {\n delete eleva.dispatch;\n }\n if (eleva.getState) {\n delete eleva.getState;\n }\n if (eleva.subscribe) {\n delete eleva.subscribe;\n }\n },\n};\n\n// Short name export for convenience\nexport { StorePlugin as Store };\n"],"names":["CAMEL_RE","AttrPlugin","name","version","description","install","eleva","options","enableAria","enableData","enableBoolean","enableDynamic","updateAttributes","oldEl","newEl","oldAttrs","attributes","newAttrs","i","length","value","startsWith","getAttribute","prop","slice","replace","_","l","toUpperCase","setAttribute","dataset","Object","getOwnPropertyDescriptor","getPrototypeOf","elementProps","getOwnPropertyNames","matchingProp","find","p","toLowerCase","includes","descriptor","hasProperty","isBoolean","get","call","boolValue","removeAttribute","hasAttribute","renderer","originalPatchNode","_patchNode","_originalPatchNode","oldNode","newNode","_eleva_instance","nodeType","Node","TEXT_NODE","nodeValue","ELEMENT_NODE","_diff","plugins","Map","set","updateElementAttributes","uninstall","delete","CoreErrorHandler","handle","error","context","details","message","formattedError","Error","originalError","console","warn","log","Router","_validateOptions","mode","errorHandler","_processRoutes","routes","processedRoutes","route","push","segments","_parsePathIntoSegments","path","normalizedPath","split","filter","Boolean","map","segment","paramName","substring","type","_findViewElement","container","selector","viewSelector","querySelector","start","isStarted","window","document","mount","mountSelector","handler","_handleRouteChange","addEventListener","eventListeners","removeEventListener","isReady","emitter","emit","destroy","plugin","values","forEach","cleanup","currentLayout","unmount","stop","navigate","location","params","target","_buildPath","query","keys","queryString","URLSearchParams","toString","_isSameRoute","navigationSuccessful","_proceedWithNavigation","currentNavId","_navigationId","_isNavigating","state","historyMethod","newUrl","pathname","search","history","replaceState","hash","url","_buildQueryUrl","queueMicrotask","urlParams","queryParam","current","currentRoute","targetPath","targetQuery","_parseQuery","JSON","stringify","result","key","entries","encodedValue","encodeURIComponent","String","RegExp","isPopState","from","toLocation","_getCurrentLocation","fullUrl","currentUrl","href","fullPath","toMatch","_matchRoute","notFoundRoute","pathMatch","decodeURIComponent","to","meta","matched","canNavigate","_runGuards","_scrollPositions","x","scrollX","pageXOffset","y","scrollY","pageYOffset","resolveContext","layoutComponent","pageComponent","cancelled","redirectTo","_resolveComponents","toLayout","layout","globalLayout","fromLayout","tryUnmount","instance","currentView","afterLeave","previousRoute","currentParams","currentQuery","renderContext","_render","scrollContext","savedPosition","afterEnter","navContext","guards","_beforeEachGuards","beforeLeave","beforeEnter","guard","_resolveStringComponent","def","componentDef","_components","componentName","availableComponents","Array","_resolveFunctionComponent","funcStr","isAsyncImport","default","function","_validateComponentDefinition","definition","template","_resolveComponent","undefined","effectiveLayout","Promise","all","component","mountEl","layoutInstance","_wrapComponentWithChildren","viewEl","viewInstance","_createRouteGetter","property","defaultValue","_wrapComponent","originalSetup","setup","self","ctx","router","bind","previous","wrappedComponent","children","wrappedChildren","childComponent","pathSegments","isMatch","routeSegment","pathSegment","addRoute","parentRoute","hasRoute","processedRoute","wildcardIndex","findIndex","r","splice","removeRoute","index","removedRoute","some","getRoutes","getRoute","onBeforeEach","indexOf","onAfterEnter","hook","on","onAfterLeave","onAfterEach","onError","use","has","existingPlugin","getPlugins","getPlugin","removePlugin","setErrorHandler","signal","RouterPlugin","isArray","register","Math","random","autoStart","getCurrentRoute","getRouteParams","getRouteQuery","StorePlugin","actions","namespaces","persistence","devTools","Store","_initializeState","initialState","initialActions","_initializeNamespaces","namespace","module","moduleState","moduleActions","_loadPersistedState","enabled","storage","persistedData","getItem","data","parse","_applyPersistedData","currentState","_shouldPersist","include","exclude","includePath","excludePath","_saveState","dataToSave","_extractPersistedData","setItem","nestedData","_setupDevTools","__ELEVA_DEVTOOLS__","registerStore","dispatch","actionName","payload","action","_getAction","mutation","timestamp","Date","now","mutations","shift","subscribers","callback","notifyMutation","parts","part","subscribe","add","getState","newState","clearPersistedState","removeItem","registerModule","unregisterModule","createState","initialValue","createAction","actionFn","lastIndex","Set","store","originalMount","compName","props","originalMountComponents","_mountComponents","childInstances","_originalMount","_originalMountComponents"],"mappings":";AAEA;;;AAGC;AAGD;AACA;AAEA;AACA;AACA;AAEA;;;AAGC;AAGD;AACA;AAEA;;;;;;;;;;;;;;;;;;;;AAwBC,IACD,MAAMA,QAAAA,GAAW,WAAA;AAEjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA6BaC,UAAAA,GAAa;AACxB;;;AAGC,MACDC,IAAAA,EAAM,MAAA;AAEN;;;AAGC,MACDC,OAAAA,EAAS,OAAA;AAET;;;AAGC,MACDC,WAAAA,EAAa,kDAAA;AAEb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CC,MACDC,OAAAA,CAAAA,CAAQC,KAAK,EAAEC,OAAAA,GAAU,EAAE,EAAA;AACzB,QAAA,MAAM,EACJC,UAAAA,GAAa,IAAI,EACjBC,UAAAA,GAAa,IAAI,EACjBC,aAAAA,GAAgB,IAAI,EACpBC,aAAAA,GAAgB,IAAI,EACrB,GAAGJ,OAAAA;AAEJ;;;;;;;;;;;;;;;;;;;;;QAsBA,MAAMK,gBAAAA,GAAmB,CAACC,KAAAA,EAAOC,KAAAA,GAAAA;YAC/B,MAAMC,QAAAA,GAAWF,MAAMG,UAAU;YACjC,MAAMC,QAAAA,GAAWH,MAAME,UAAU;;AAGjC,YAAA,IAAK,IAAIE,CAAAA,GAAI,CAAA,EAAGA,IAAID,QAAAA,CAASE,MAAM,EAAED,CAAAA,EAAAA,CAAK;gBACxC,MAAM,EAAEhB,IAAI,EAAEkB,KAAK,EAAE,GAAGH,QAAQ,CAACC,CAAAA,CAAE;;gBAGnC,IAAIhB,I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