@coherent.js/client 1.1.1 → 2.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/hydration/state-serializer.js", "../src/hydration/mismatch-detector.js", "../src/hydrate.js", "../src/hmr/cleanup-tracker.js", "../src/hmr/state-capturer.js", "../src/hmr/overlay.js", "../src/hmr/indicator.js", "../src/hmr/module-tracker.js", "../src/hmr/client.js"],
4
- "sourcesContent": ["/**\n * State serialization utilities for Coherent.js hydration\n *\n * Uses base64 encoding to safely embed state in data attributes\n * without escaping issues.\n */\n\n/**\n * Serialize component state to base64-encoded JSON string\n *\n * @param {Object} state - Component state object\n * @returns {string|null} - Base64 encoded state or null if empty/invalid\n */\nexport function serializeState(state) {\n if (!state || typeof state !== 'object') return null;\n\n // Filter out non-serializable values (functions, symbols, undefined)\n const serializable = {};\n let hasSerializable = false;\n\n for (const [key, value] of Object.entries(state)) {\n if (isSerializable(value)) {\n serializable[key] = value;\n hasSerializable = true;\n }\n // Silently omit functions, symbols, undefined - they reconstruct on hydrate\n }\n\n if (!hasSerializable) return null;\n\n try {\n const json = JSON.stringify(serializable);\n // Use encodeURIComponent to handle unicode, then btoa for base64\n return btoa(encodeURIComponent(json));\n } catch (e) {\n console.warn('[Coherent.js] Failed to serialize state:', e);\n return null;\n }\n}\n\n/**\n * Deserialize state from base64-encoded JSON string\n *\n * @param {string} encoded - Base64 encoded state string\n * @returns {Object|null} - Deserialized state or null if invalid\n */\nexport function deserializeState(encoded) {\n if (!encoded || typeof encoded !== 'string') return null;\n\n try {\n const json = decodeURIComponent(atob(encoded));\n return JSON.parse(json);\n } catch (e) {\n console.warn('[Coherent.js] Failed to deserialize state:', e);\n return null;\n }\n}\n\n/**\n * Extract state from a DOM element's data-state attribute\n *\n * @param {HTMLElement} element - DOM element to extract state from\n * @returns {Object|null} - Extracted state or null\n */\nexport function extractState(element) {\n if (!element || typeof element.getAttribute !== 'function') {\n return null;\n }\n\n const encoded = element.getAttribute('data-state');\n return deserializeState(encoded);\n}\n\n/**\n * Check if a value is serializable to JSON\n * @private\n */\nfunction isSerializable(value) {\n if (value === undefined) return false;\n if (value === null) return true;\n if (typeof value === 'function') return false;\n if (typeof value === 'symbol') return false;\n if (typeof value === 'bigint') return false; // BigInt not JSON serializable\n\n // Arrays and objects need recursive check\n if (Array.isArray(value)) {\n return value.every(isSerializable);\n }\n\n if (typeof value === 'object') {\n // Check for circular references would be expensive here\n // JSON.stringify will catch them in serializeState\n return true;\n }\n\n return true; // primitives (string, number, boolean)\n}\n\n/**\n * Size warning threshold (bytes)\n * Warn if serialized state exceeds this\n */\nconst STATE_SIZE_WARNING_THRESHOLD = 10 * 1024; // 10KB\n\n/**\n * Serialize state with size warning\n *\n * @param {Object} state - Component state\n * @param {string} componentName - Component name for warning message\n * @returns {string|null} - Serialized state\n */\nexport function serializeStateWithWarning(state, componentName = 'Unknown') {\n const encoded = serializeState(state);\n\n if (encoded && encoded.length > STATE_SIZE_WARNING_THRESHOLD) {\n console.warn(\n `[Coherent.js] Large state detected for component \"${componentName}\": ` +\n `${Math.round(encoded.length / 1024)}KB. Consider using a state management ` +\n `solution for large datasets.`\n );\n }\n\n return encoded;\n}\n", "/**\n * Mismatch detection for Coherent.js hydration\n *\n * Compares server-rendered DOM against client virtual DOM to detect\n * hydration mismatches in development mode.\n */\n\n/**\n * Format path segments into readable string\n * @param {Array} segments - Path segments\n * @returns {string} - Formatted path\n */\nexport function formatPath(segments) {\n if (!segments || segments.length === 0) return 'root';\n return segments.join('.');\n}\n\n/**\n * Get children from virtual node\n * @private\n */\nfunction getVNodeChildren(vNode) {\n if (!vNode || typeof vNode !== 'object' || Array.isArray(vNode)) {\n return [];\n }\n const tagName = Object.keys(vNode)[0];\n const props = vNode[tagName];\n if (!props || typeof props !== 'object') {\n return [];\n }\n if (props.children) {\n return Array.isArray(props.children) ? props.children : [props.children];\n }\n if (props.text !== undefined) {\n return [String(props.text)];\n }\n return [];\n}\n\n/**\n * Detect mismatches between DOM and virtual DOM\n *\n * @param {Element} domElement - Real DOM element\n * @param {Object|string|number} virtualNode - Virtual DOM node\n * @param {Array} path - Current path for error reporting\n * @returns {Array} - Array of mismatch objects\n */\nexport function detectMismatch(domElement, virtualNode, path = []) {\n const mismatches = [];\n\n // Handle null/undefined virtual node\n if (virtualNode === null || virtualNode === undefined) {\n return mismatches;\n }\n\n // Handle text nodes (string or number in virtual DOM)\n if (typeof virtualNode === 'string' || typeof virtualNode === 'number') {\n const expectedText = String(virtualNode).trim();\n\n // DOM might be a text node or element containing text\n let actualText;\n if (domElement.nodeType === 3) { // Node.TEXT_NODE\n actualText = domElement.textContent?.trim() || '';\n } else {\n // For element nodes, get direct text content\n actualText = domElement.textContent?.trim() || '';\n }\n\n if (actualText !== expectedText) {\n mismatches.push({\n path: formatPath(path),\n type: 'text',\n expected: expectedText,\n actual: actualText,\n domPath: getDOMPath(domElement)\n });\n }\n return mismatches;\n }\n\n // Handle arrays\n if (Array.isArray(virtualNode)) {\n virtualNode.forEach((child, index) => {\n const domChild = getDOMChildAtIndex(domElement, index);\n if (domChild) {\n const childMismatches = detectMismatch(\n domChild,\n child,\n [...path, `[${index}]`]\n );\n mismatches.push(...childMismatches);\n } else {\n mismatches.push({\n path: formatPath([...path, `[${index}]`]),\n type: 'missing_element',\n expected: describeVNode(child),\n actual: null,\n domPath: `${getDOMPath(domElement)} > child[${index}]`\n });\n }\n });\n return mismatches;\n }\n\n // Handle element nodes\n if (typeof virtualNode !== 'object') {\n return mismatches;\n }\n\n const tagName = Object.keys(virtualNode)[0];\n const props = virtualNode[tagName] || {};\n\n // Check tag name\n const domTagName = domElement.tagName?.toLowerCase();\n if (domTagName !== tagName.toLowerCase()) {\n mismatches.push({\n path: formatPath(path),\n type: 'tagName',\n expected: tagName,\n actual: domTagName,\n domPath: getDOMPath(domElement)\n });\n // Can't continue comparing if tag is different\n return mismatches;\n }\n\n // Check critical attributes\n const attributeChecks = [\n { virtual: 'className', dom: 'class' },\n { virtual: 'id', dom: 'id' },\n { virtual: 'type', dom: 'type' },\n { virtual: 'value', dom: 'value' },\n { virtual: 'checked', dom: 'checked' },\n { virtual: 'disabled', dom: 'disabled' },\n { virtual: 'href', dom: 'href' },\n { virtual: 'src', dom: 'src' }\n ];\n\n attributeChecks.forEach(({ virtual, dom }) => {\n const expectedValue = props[virtual];\n if (expectedValue === undefined) return;\n\n const actualValue = domElement.getAttribute(dom);\n const expectedStr = String(expectedValue);\n\n // Handle boolean attributes\n if (typeof expectedValue === 'boolean') {\n const actualBool = actualValue !== null;\n if (expectedValue !== actualBool) {\n mismatches.push({\n path: formatPath([...path, `@${dom}`]),\n type: 'attribute',\n expected: expectedValue,\n actual: actualBool,\n domPath: getDOMPath(domElement)\n });\n }\n return;\n }\n\n if (expectedStr !== actualValue) {\n mismatches.push({\n path: formatPath([...path, `@${dom}`]),\n type: 'attribute',\n expected: expectedStr,\n actual: actualValue,\n domPath: getDOMPath(domElement)\n });\n }\n });\n\n // Recursively check children\n const vChildren = getVNodeChildren({ [tagName]: props });\n const dChildren = getSignificantDOMChildren(domElement);\n\n // Check for child count mismatch\n if (vChildren.length !== dChildren.length) {\n mismatches.push({\n path: formatPath([...path, 'children']),\n type: 'children_count',\n expected: vChildren.length,\n actual: dChildren.length,\n domPath: getDOMPath(domElement)\n });\n }\n\n // Compare each child\n const maxChildren = Math.max(vChildren.length, dChildren.length);\n for (let i = 0; i < maxChildren; i++) {\n const vChild = vChildren[i];\n const dChild = dChildren[i];\n\n if (vChild && dChild) {\n const childMismatches = detectMismatch(\n dChild,\n vChild,\n [...path, `children[${i}]`]\n );\n mismatches.push(...childMismatches);\n } else if (vChild && !dChild) {\n mismatches.push({\n path: formatPath([...path, `children[${i}]`]),\n type: 'missing_dom_child',\n expected: describeVNode(vChild),\n actual: null,\n domPath: getDOMPath(domElement)\n });\n } else if (!vChild && dChild) {\n mismatches.push({\n path: formatPath([...path, `children[${i}]`]),\n type: 'extra_dom_child',\n expected: null,\n actual: describeNode(dChild),\n domPath: getDOMPath(domElement)\n });\n }\n }\n\n return mismatches;\n}\n\n/**\n * Report mismatches to console with detailed information\n *\n * @param {Array} mismatches - Array of mismatch objects\n * @param {Object} options - Reporting options\n */\nexport function reportMismatches(mismatches, options = {}) {\n if (!mismatches || mismatches.length === 0) return;\n\n const { componentName = 'Unknown', strict = false } = options;\n\n const header = `[Coherent.js] Hydration mismatch detected in \"${componentName}\"!\\n` +\n `Found ${mismatches.length} difference(s) between server and client:\\n`;\n\n const details = mismatches.map((m, i) => {\n return `\\n${i + 1}. ${m.type} at ${m.path}\\n` +\n ` DOM path: ${m.domPath}\\n` +\n ` Expected: ${JSON.stringify(m.expected)}\\n` +\n ` Actual: ${JSON.stringify(m.actual)}`;\n }).join('');\n\n const advice = '\\n\\nThis usually happens when:\\n' +\n ' - Server renders with different data than client\\n' +\n ' - Using Date.now(), Math.random(), or browser-only APIs during render\\n' +\n ' - Component is not pure (has side effects during render)\\n';\n\n console.warn(header + details + advice);\n\n if (strict) {\n throw new Error(`Hydration failed: ${mismatches.length} mismatch(es) found. See console for details.`);\n }\n}\n\n/**\n * Get significant DOM children (elements and non-empty text nodes)\n * @private\n */\nfunction getSignificantDOMChildren(element) {\n if (!element || !element.childNodes) return [];\n\n return Array.from(element.childNodes).filter(node => {\n if (node.nodeType === 1) return true; // Element node\n if (node.nodeType === 3) { // Text node\n return node.textContent && node.textContent.trim().length > 0;\n }\n return false;\n });\n}\n\n/**\n * Get DOM child at specific index (considering only significant children)\n * @private\n */\nfunction getDOMChildAtIndex(parent, index) {\n const children = getSignificantDOMChildren(parent);\n return children[index] || null;\n}\n\n/**\n * Get a readable DOM path for debugging\n * @private\n */\nfunction getDOMPath(element) {\n if (!element || !element.tagName) return '(unknown)';\n\n const parts = [];\n let current = element;\n\n while (current && current.tagName) {\n let selector = current.tagName.toLowerCase();\n\n if (current.id) {\n selector += `#${current.id}`;\n } else if (current.className && typeof current.className === 'string') {\n const classes = current.className.trim().split(/\\s+/).slice(0, 2);\n if (classes.length > 0 && classes[0]) {\n selector += `.${classes.join('.')}`;\n }\n }\n\n parts.unshift(selector);\n current = current.parentElement;\n\n // Limit depth\n if (parts.length > 5) {\n parts.unshift('...');\n break;\n }\n }\n\n return parts.join(' > ');\n}\n\n/**\n * Describe a virtual node for error messages\n * @private\n */\nfunction describeVNode(vNode) {\n if (typeof vNode === 'string' || typeof vNode === 'number') {\n return `text: \"${String(vNode).substring(0, 50)}\"`;\n }\n if (Array.isArray(vNode)) {\n return `array[${vNode.length}]`;\n }\n if (typeof vNode === 'object' && vNode !== null) {\n const tagName = Object.keys(vNode)[0];\n return `<${tagName}>`;\n }\n return String(vNode);\n}\n\n/**\n * Describe a DOM node for error messages\n * @private\n */\nfunction describeNode(node) {\n if (!node) return '(null)';\n if (node.nodeType === 3) { // Text node\n return `text: \"${(node.textContent || '').substring(0, 50)}\"`;\n }\n if (node.nodeType === 1) { // Element\n return `<${node.tagName.toLowerCase()}>`;\n }\n return `node(type=${node.nodeType})`;\n}\n", "/**\n * Clean hydrate() API for Coherent.js\n *\n * Integrates event delegation, state serialization, and mismatch detection\n * into a simple function: hydrate(component, container, options)\n *\n * @module @coherent.js/client/hydrate\n */\n\nimport { eventDelegation, handlerRegistry } from './events/index.js';\nimport { extractState, detectMismatch, reportMismatches } from './hydration/index.js';\n\n/**\n * Hydrate a server-rendered component\n *\n * @param {Function} component - Component function that returns virtual DOM\n * @param {HTMLElement} container - DOM element containing server-rendered HTML\n * @param {Object} [options] - Hydration options\n * @param {Object} [options.initialState] - Initial state to override extracted state\n * @param {boolean} [options.detectMismatch=true] - Enable mismatch detection (dev mode)\n * @param {boolean} [options.strict=false] - Throw on mismatch instead of warning\n * @param {Function} [options.onMismatch] - Custom mismatch handler\n * @param {Object} [options.props] - Additional props to pass to component\n * @returns {Object} Control object with unmount(), rerender(), getState(), setState()\n */\nexport function hydrate(component, container, options = {}) {\n // Validate inputs\n if (typeof component !== 'function') {\n throw new Error(\n `hydrate() requires a component function, received: ${typeof component}`\n );\n }\n\n if (!container || typeof container.getAttribute !== 'function') {\n throw new Error(\n `hydrate() requires a valid DOM element as container, received: ${\n container === null ? 'null' : typeof container\n }`\n );\n }\n\n // Initialize event delegation (idempotent)\n eventDelegation.initialize();\n\n // Extract options with defaults\n const {\n initialState: providedState,\n // eslint-disable-next-line no-restricted-globals -- statically replaced by esbuild `define` at build time\n detectMismatch: shouldDetectMismatch = process.env.NODE_ENV !== 'production',\n strict = false,\n onMismatch,\n props: additionalProps = {},\n } = options;\n\n // Extract state from DOM data-state attribute, or use provided initial state\n let state = providedState ?? extractState(container) ?? {};\n\n // Store event listeners for cleanup\n const eventListeners = [];\n\n // Track registered handler IDs for cleanup\n const registeredHandlerIds = new Set();\n\n // Create component reference for handler registry\n const componentRef = {\n getState: () => state,\n setState: (newState) => {\n if (typeof newState === 'function') {\n state = { ...state, ...newState(state) };\n } else {\n state = { ...state, ...newState };\n }\n // Re-render on state change\n doRerender();\n },\n };\n\n // Generate virtual DOM from component\n const componentProps = { ...additionalProps, ...state };\n let virtualDOM = component(componentProps);\n\n // Detect mismatches if enabled\n if (shouldDetectMismatch) {\n const mismatches = detectMismatch(container, virtualDOM);\n\n if (mismatches.length > 0) {\n if (onMismatch) {\n onMismatch(mismatches);\n } else {\n reportMismatches(mismatches, {\n componentName: component.name || 'Anonymous',\n strict,\n });\n }\n }\n }\n\n // Walk virtual DOM and register event handlers\n registerEventHandlers(container, virtualDOM, componentRef, registeredHandlerIds);\n\n /**\n * Re-render the component with current state\n */\n function doRerender() {\n const newProps = { ...additionalProps, ...state };\n virtualDOM = component(newProps);\n\n // Update DOM with new virtual DOM\n // For now, we do a simple patch - just update text content and attributes\n // Full reconciliation would be in a separate module\n patchDOM(container, virtualDOM);\n\n // Re-register event handlers after DOM update\n registerEventHandlers(container, virtualDOM, componentRef, registeredHandlerIds);\n }\n\n /**\n * Unmount the component and clean up\n */\n function unmount() {\n // Remove registered event handlers\n for (const handlerId of registeredHandlerIds) {\n handlerRegistry.unregister(handlerId);\n }\n registeredHandlerIds.clear();\n\n // Remove direct event listeners\n for (const { element, event, handler, options } of eventListeners) {\n element.removeEventListener(event, handler, options);\n }\n eventListeners.length = 0;\n\n // Clear container's hydration marker\n container.removeAttribute('data-coherent-hydrated');\n }\n\n /**\n * Force re-render with optional new props\n * @param {Object} [newProps] - New props to merge\n */\n function rerender(newProps) {\n if (newProps) {\n Object.assign(additionalProps, newProps);\n }\n doRerender();\n }\n\n /**\n * Get current state\n * @returns {Object} Current state\n */\n function getState() {\n return { ...state };\n }\n\n /**\n * Set state and trigger re-render\n * @param {Object|Function} newState - New state or updater function\n */\n function setState(newState) {\n componentRef.setState(newState);\n }\n\n // Mark container as hydrated\n container.setAttribute('data-coherent-hydrated', 'true');\n\n // Return control object\n return {\n unmount,\n rerender,\n getState,\n setState,\n };\n}\n\n/**\n * Walk virtual DOM tree and register event handlers\n * @private\n */\nfunction registerEventHandlers(domElement, vNode, componentRef, handlerIds) {\n if (!vNode || typeof vNode !== 'object' || Array.isArray(vNode)) {\n return;\n }\n\n const tagName = Object.keys(vNode)[0];\n const props = vNode[tagName];\n\n if (!props || typeof props !== 'object') {\n return;\n }\n\n // Look for event handler props (on* functions)\n const eventProps = Object.keys(props).filter(\n (key) => key.startsWith('on') && typeof props[key] === 'function'\n );\n\n for (const eventProp of eventProps) {\n const eventType = eventProp.slice(2).toLowerCase(); // onClick -> click\n const handler = props[eventProp];\n\n // Generate unique handler ID\n const handlerId = `${tagName}-${eventType}-${Math.random().toString(36).slice(2, 9)}`;\n\n // Register handler\n handlerRegistry.register(handlerId, handler, componentRef);\n handlerIds.add(handlerId);\n\n // Set data attribute on DOM element for delegation\n const attrName = `data-coherent-${eventType}`;\n if (domElement.setAttribute) {\n domElement.setAttribute(attrName, handlerId);\n }\n }\n\n // Recursively process children\n const children = getVNodeChildren(props);\n const domChildren = getSignificantDOMChildren(domElement);\n\n children.forEach((child, index) => {\n if (child && typeof child === 'object' && !Array.isArray(child) && domChildren[index]) {\n registerEventHandlers(domChildren[index], child, componentRef, handlerIds);\n }\n });\n}\n\n/**\n * Simple DOM patching for re-renders\n * @private\n */\nfunction patchDOM(domElement, vNode) {\n if (!vNode || !domElement) {\n return;\n }\n\n // Handle text/number\n if (typeof vNode === 'string' || typeof vNode === 'number') {\n if (domElement.textContent !== String(vNode)) {\n domElement.textContent = String(vNode);\n }\n return;\n }\n\n // Handle arrays\n if (Array.isArray(vNode)) {\n return; // Array patching would need reconciliation\n }\n\n if (typeof vNode !== 'object') {\n return;\n }\n\n const tagName = Object.keys(vNode)[0];\n const props = vNode[tagName] || {};\n\n // Update attributes\n const attributeMap = {\n className: 'class',\n htmlFor: 'for',\n };\n\n for (const [key, value] of Object.entries(props)) {\n if (key === 'children' || key === 'text' || key.startsWith('on')) {\n continue;\n }\n\n const attrName = attributeMap[key] || key;\n\n if (value === true) {\n domElement.setAttribute(attrName, '');\n } else if (value === false || value === null || value === undefined) {\n domElement.removeAttribute(attrName);\n } else if (domElement.getAttribute(attrName) !== String(value)) {\n domElement.setAttribute(attrName, String(value));\n }\n }\n\n // Handle text content\n if (props.text !== undefined) {\n const textContent = String(props.text);\n if (domElement.textContent !== textContent) {\n domElement.textContent = textContent;\n }\n return;\n }\n\n // Recursively patch children\n const children = getVNodeChildren(props);\n const domChildren = getSignificantDOMChildren(domElement);\n\n children.forEach((child, index) => {\n if (domChildren[index]) {\n patchDOM(domChildren[index], child);\n }\n });\n}\n\n/**\n * Get children from virtual node props\n * @private\n */\nfunction getVNodeChildren(props) {\n if (!props) return [];\n if (props.children) {\n return Array.isArray(props.children) ? props.children : [props.children];\n }\n return [];\n}\n\n/**\n * Get significant DOM children (elements and non-whitespace text)\n * @private\n */\nfunction getSignificantDOMChildren(element) {\n if (!element || !element.childNodes) return [];\n\n return Array.from(element.childNodes).filter((node) => {\n if (node.nodeType === 1) return true; // Element\n if (node.nodeType === 3) {\n // Text node\n return node.textContent && node.textContent.trim().length > 0;\n }\n return false;\n });\n}\n\nexport default hydrate;\n", "/**\n * CleanupTracker - Tracks and automatically cleans up module resources during HMR\n *\n * Prevents memory leaks by tracking timers, intervals, event listeners, and fetch\n * requests created by modules. When a module is disposed during HMR, all its\n * tracked resources are automatically cleaned up.\n *\n * @module @coherent.js/client/hmr/cleanup-tracker\n */\n\n/**\n * Tracks module resources for cleanup during HMR\n */\nexport class CleanupTracker {\n constructor() {\n /**\n * Per-module resource tracking\n * @type {Map<string, { timers: Set<number>, intervals: Set<number>, listeners: Array, abortControllers: Set<AbortController> }>}\n */\n this.moduleResources = new Map();\n }\n\n /**\n * Create a tracked context for a module\n *\n * Returns an object with tracked versions of setTimeout, setInterval,\n * addEventListener, and fetch that automatically clean up on module disposal.\n *\n * @param {string} moduleId - Unique identifier for the module\n * @returns {Object} Tracked context with setTimeout, setInterval, etc.\n */\n createContext(moduleId) {\n const resources = {\n timers: new Set(),\n intervals: new Set(),\n listeners: [],\n abortControllers: new Set(),\n };\n\n this.moduleResources.set(moduleId, resources);\n\n const context = {\n /**\n * Tracked setTimeout - auto-removes from tracking on completion\n * @param {Function} callback - Function to execute\n * @param {number} delay - Delay in milliseconds\n * @param {...*} args - Additional arguments to pass to callback\n * @returns {number} Timer ID\n */\n setTimeout: (callback, delay, ...args) => {\n const id = setTimeout(\n (...a) => {\n resources.timers.delete(id);\n callback(...a);\n },\n delay,\n ...args\n );\n resources.timers.add(id);\n return id;\n },\n\n /**\n * Tracked setInterval - stores in intervals set until cleared\n * @param {Function} callback - Function to execute\n * @param {number} delay - Interval in milliseconds\n * @param {...*} args - Additional arguments to pass to callback\n * @returns {number} Interval ID\n */\n setInterval: (callback, delay, ...args) => {\n const id = setInterval(callback, delay, ...args);\n resources.intervals.add(id);\n return id;\n },\n\n /**\n * Clear a tracked timeout\n * @param {number} id - Timer ID to clear\n */\n clearTimeout: (id) => {\n resources.timers.delete(id);\n clearTimeout(id);\n },\n\n /**\n * Clear a tracked interval\n * @param {number} id - Interval ID to clear\n */\n clearInterval: (id) => {\n resources.intervals.delete(id);\n clearInterval(id);\n },\n\n /**\n * Tracked addEventListener - stores listener info for removal on cleanup\n * @param {EventTarget} target - Element or object to attach listener to\n * @param {string} event - Event type\n * @param {Function} handler - Event handler function\n * @param {Object|boolean} [options] - Listener options\n */\n addEventListener: (target, event, handler, options) => {\n target.addEventListener(event, handler, options);\n resources.listeners.push({ target, event, handler, options });\n },\n\n /**\n * Create a tracked AbortController\n * @returns {AbortController} Tracked AbortController\n */\n createAbortController: () => {\n const controller = new AbortController();\n resources.abortControllers.add(controller);\n return controller;\n },\n\n /**\n * Tracked fetch - creates AbortController automatically, cleans up on completion\n * @param {string|URL} url - URL to fetch\n * @param {Object} [options] - Fetch options\n * @returns {Promise<Response>} Fetch promise\n */\n fetch: (url, options = {}) => {\n const controller = new AbortController();\n resources.abortControllers.add(controller);\n\n // Merge signals if one was provided\n const mergedOptions = {\n ...options,\n signal: controller.signal,\n };\n\n return fetch(url, mergedOptions).finally(() => {\n resources.abortControllers.delete(controller);\n });\n },\n };\n\n return context;\n }\n\n /**\n * Cleanup all resources for a module\n *\n * Called during HMR module disposal. Clears all timers, intervals,\n * removes all event listeners, and aborts all pending fetch requests.\n *\n * @param {string} moduleId - Module identifier to clean up\n */\n cleanup(moduleId) {\n const resources = this.moduleResources.get(moduleId);\n if (!resources) return;\n\n // Clear all timers\n for (const id of resources.timers) {\n clearTimeout(id);\n }\n resources.timers.clear();\n\n // Clear all intervals\n for (const id of resources.intervals) {\n clearInterval(id);\n }\n resources.intervals.clear();\n\n // Remove all event listeners\n for (const { target, event, handler, options } of resources.listeners) {\n try {\n target.removeEventListener(event, handler, options);\n } catch {\n // Target may no longer exist\n }\n }\n resources.listeners.length = 0;\n\n // Abort all pending fetches\n for (const controller of resources.abortControllers) {\n try {\n controller.abort();\n } catch {\n // Ignore abort errors\n }\n }\n resources.abortControllers.clear();\n\n this.moduleResources.delete(moduleId);\n }\n\n /**\n * Check for potential resource leaks (for development mode)\n *\n * Logs warnings if resources weren't cleaned up before module disposal.\n * Call this before cleanup() to detect potential leaks.\n *\n * @param {string} moduleId - Module identifier to check\n */\n checkForLeaks(moduleId) {\n const resources = this.moduleResources.get(moduleId);\n if (!resources) return;\n\n const warnings = [];\n\n if (resources.timers.size > 0) {\n warnings.push(`${resources.timers.size} timer(s) not cleaned up`);\n }\n if (resources.intervals.size > 0) {\n warnings.push(`${resources.intervals.size} interval(s) not cleaned up`);\n }\n if (resources.listeners.length > 0) {\n warnings.push(`${resources.listeners.length} listener(s) not cleaned up`);\n }\n if (resources.abortControllers.size > 0) {\n warnings.push(\n `${resources.abortControllers.size} pending fetch(es) not aborted`\n );\n }\n\n if (warnings.length > 0) {\n console.warn(`[HMR] Potential leak in module ${moduleId}: ${warnings.join(', ')}`);\n }\n }\n\n /**\n * Check if a module has tracked resources\n * @param {string} moduleId - Module identifier\n * @returns {boolean} True if module has resources\n */\n hasResources(moduleId) {\n return this.moduleResources.has(moduleId);\n }\n\n /**\n * Get resource counts for a module (for testing/debugging)\n * @param {string} moduleId - Module identifier\n * @returns {Object|null} Resource counts or null if module not tracked\n */\n getResourceCounts(moduleId) {\n const resources = this.moduleResources.get(moduleId);\n if (!resources) return null;\n\n return {\n timers: resources.timers.size,\n intervals: resources.intervals.size,\n listeners: resources.listeners.length,\n abortControllers: resources.abortControllers.size,\n };\n }\n}\n\n/**\n * Singleton cleanup tracker instance\n * @type {CleanupTracker}\n */\nexport const cleanupTracker = new CleanupTracker();\n", "/**\n * StateCapturer - Captures and restores form input state and scroll positions during HMR\n *\n * Preserves user input and scroll positions across hot module replacement updates,\n * providing a seamless development experience. Only restores scroll position if\n * the page layout hasn't changed significantly.\n *\n * @module @coherent.js/client/hmr/state-capturer\n */\n\n/**\n * Captures and restores form/scroll state during HMR\n */\nexport class StateCapturer {\n constructor() {\n /**\n * Captured form input states\n * @type {Map<string, { value: string, type: string, selectionStart?: number, selectionEnd?: number, checked?: boolean }>}\n */\n this.capturedInputs = new Map();\n\n /**\n * Captured scroll positions\n * @type {Map<string, { top: number, left: number }>}\n */\n this.scrollPositions = new Map();\n\n /**\n * Layout snapshot for change detection\n * @type {Object|null}\n */\n this.layoutSnapshot = null;\n }\n\n /**\n * Generate a stable key for an input element\n *\n * Uses multiple factors to identify inputs across HMR updates:\n * 1. ID (most stable)\n * 2. Name + type\n * 3. Form context\n * 4. DOM path (fallback)\n *\n * @param {HTMLInputElement|HTMLTextAreaElement|HTMLSelectElement} input - Input element\n * @returns {string} Stable key for the input\n */\n getInputKey(input) {\n const parts = [];\n\n // ID is most stable\n if (input.id) {\n parts.push(`#${input.id}`);\n return parts.join(':');\n }\n\n // Name + type combination\n if (input.name) {\n parts.push(`[name=\"${input.name}\"]`);\n }\n\n if (input.type) {\n parts.push(`[type=\"${input.type}\"]`);\n }\n\n // Form context if available\n if (input.form?.id) {\n parts.push(`form#${input.form.id}`);\n }\n\n // Fallback: DOM path\n if (parts.length === 0) {\n parts.push(this.getElementPath(input));\n }\n\n return parts.join(':');\n }\n\n /**\n * Build a CSS-like path for an element\n *\n * @param {HTMLElement} element - Element to build path for\n * @returns {string} CSS-like path (e.g., \"form > div:nth-of-type(2) > input\")\n */\n getElementPath(element) {\n const path = [];\n let current = element;\n\n while (current && current !== document.body && path.length < 10) {\n let selector = current.tagName.toLowerCase();\n\n // Add class names (limited to avoid overly long selectors)\n if (current.className && typeof current.className === 'string') {\n const classes = current.className.trim().split(/\\s+/).slice(0, 2);\n if (classes.length > 0 && classes[0]) {\n selector += `.${classes.join('.')}`;\n }\n }\n\n // Add nth-of-type for disambiguation\n if (current.parentElement) {\n const siblings = current.parentElement.querySelectorAll(\n `:scope > ${current.tagName.toLowerCase()}`\n );\n if (siblings.length > 1) {\n const index = Array.from(siblings).indexOf(current);\n selector += `:nth-of-type(${index + 1})`;\n }\n }\n\n path.unshift(selector);\n current = current.parentElement;\n }\n\n return path.join(' > ');\n }\n\n /**\n * Capture all form input states\n *\n * Iterates through all input, textarea, and select elements,\n * capturing their values, selection state, and checked state.\n *\n * @returns {Map<string, Object>} Map of input keys to their captured state\n */\n captureFormState() {\n this.capturedInputs.clear();\n\n const inputs = document.querySelectorAll('input, textarea, select');\n\n for (const input of inputs) {\n const key = this.getInputKey(input);\n const state = {\n value: input.value,\n type: input.type || input.tagName.toLowerCase(),\n };\n\n // Capture selection for text-like inputs\n if (\n typeof input.selectionStart === 'number' &&\n (input.type === 'text' ||\n input.type === 'search' ||\n input.type === 'url' ||\n input.type === 'tel' ||\n input.type === 'password' ||\n input.tagName.toLowerCase() === 'textarea')\n ) {\n state.selectionStart = input.selectionStart;\n state.selectionEnd = input.selectionEnd;\n }\n\n // Capture checked state for checkboxes/radios\n if (input.type === 'checkbox' || input.type === 'radio') {\n state.checked = input.checked;\n }\n\n this.capturedInputs.set(key, state);\n }\n\n return this.capturedInputs;\n }\n\n /**\n * Restore form input states after HMR update\n *\n * Finds inputs by their captured keys and restores their values,\n * only if the input type matches (to avoid corrupting data).\n */\n restoreFormState() {\n for (const [key, state] of this.capturedInputs) {\n const inputs = this.findInputsByKey(key);\n\n for (const input of inputs) {\n // Only restore if type matches\n const currentType = input.type || input.tagName.toLowerCase();\n if (currentType !== state.type) {\n continue;\n }\n\n // Restore checkbox/radio checked state\n if (state.checked !== undefined) {\n input.checked = state.checked;\n continue;\n }\n\n // Restore value\n input.value = state.value;\n\n // Restore selection if applicable and input is not focused\n if (\n state.selectionStart !== undefined &&\n document.activeElement !== input\n ) {\n try {\n input.setSelectionRange(state.selectionStart, state.selectionEnd);\n } catch {\n // Some input types don't support setSelectionRange\n }\n }\n }\n }\n }\n\n /**\n * Find inputs matching a captured key\n *\n * @param {string} key - Captured input key\n * @returns {HTMLElement[]} Array of matching input elements\n */\n findInputsByKey(key) {\n // ID-based key\n if (key.startsWith('#')) {\n const id = key.slice(1);\n const el = document.getElementById(id);\n return el ? [el] : [];\n }\n\n // Name-based key\n const nameMatch = key.match(/\\[name=\"([^\"]+)\"\\]/);\n if (nameMatch) {\n const name = nameMatch[1];\n const typeMatch = key.match(/\\[type=\"([^\"]+)\"\\]/);\n const type = typeMatch ? typeMatch[1] : null;\n\n let selector = `[name=\"${name}\"]`;\n if (type) {\n selector += `[type=\"${type}\"]`;\n }\n\n return Array.from(document.querySelectorAll(selector));\n }\n\n // Path-based key - try to query directly\n try {\n const el = document.querySelector(key);\n return el ? [el] : [];\n } catch {\n return [];\n }\n }\n\n /**\n * Capture scroll positions for window and scrollable containers\n *\n * Captures scroll positions for:\n * - Window (scrollX/scrollY)\n * - Elements with [data-coherent-scroll-preserve] attribute\n * - Elements with overflow that have actual scrolling\n */\n captureScrollPositions() {\n this.scrollPositions.clear();\n\n // Window scroll\n this.scrollPositions.set('window', {\n top: window.scrollY,\n left: window.scrollX,\n });\n\n // Find scrollable containers with explicit marker\n const markedScrollables = document.querySelectorAll(\n '[data-coherent-scroll-preserve]'\n );\n for (const el of markedScrollables) {\n const key = this.getScrollableKey(el);\n this.scrollPositions.set(key, {\n top: el.scrollTop,\n left: el.scrollLeft,\n });\n }\n\n // Find elements with overflow that have actual scroll content\n const overflowElements = document.querySelectorAll(\n '[style*=\"overflow\"], [class]'\n );\n for (const el of overflowElements) {\n const style = window.getComputedStyle(el);\n const hasOverflow =\n style.overflow === 'auto' ||\n style.overflow === 'scroll' ||\n style.overflowY === 'auto' ||\n style.overflowY === 'scroll' ||\n style.overflowX === 'auto' ||\n style.overflowX === 'scroll';\n\n if (\n hasOverflow &&\n (el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth)\n ) {\n const key = this.getScrollableKey(el);\n if (!this.scrollPositions.has(key)) {\n this.scrollPositions.set(key, {\n top: el.scrollTop,\n left: el.scrollLeft,\n });\n }\n }\n }\n\n return this.scrollPositions;\n }\n\n /**\n * Generate a stable key for a scrollable element\n *\n * @param {HTMLElement} el - Scrollable element\n * @returns {string} Key for the element\n */\n getScrollableKey(el) {\n if (el.id) {\n return `#${el.id}`;\n }\n\n const component = el.getAttribute('data-coherent-component');\n if (component) {\n return `[data-coherent-component=\"${component}\"]`;\n }\n\n return this.getElementPath(el);\n }\n\n /**\n * Capture layout snapshot for change detection\n *\n * Captures body dimensions and positions of anchor elements\n * (elements with data-coherent-component attribute).\n */\n captureLayout() {\n this.layoutSnapshot = {\n bodyHeight: document.body.scrollHeight,\n bodyWidth: document.body.scrollWidth,\n anchors: new Map(),\n };\n\n // Capture positions of component elements as anchors\n const components = document.querySelectorAll('[data-coherent-component]');\n for (const el of components) {\n const rect = el.getBoundingClientRect();\n const key = this.getScrollableKey(el);\n this.layoutSnapshot.anchors.set(key, {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height,\n });\n }\n }\n\n /**\n * Check if layout changed significantly (>50px shift)\n *\n * Returns true if:\n * - Body dimensions changed by more than 50px\n * - Any anchor element position shifted by more than 50px\n *\n * @returns {boolean} True if layout changed significantly\n */\n layoutChangedSignificantly() {\n if (!this.layoutSnapshot) {\n return false;\n }\n\n const THRESHOLD = 50; // pixels\n\n // Check body dimensions\n const heightDiff = Math.abs(\n document.body.scrollHeight - this.layoutSnapshot.bodyHeight\n );\n const widthDiff = Math.abs(\n document.body.scrollWidth - this.layoutSnapshot.bodyWidth\n );\n\n if (heightDiff > THRESHOLD || widthDiff > THRESHOLD) {\n return true;\n }\n\n // Check anchor element positions\n for (const [key, oldRect] of this.layoutSnapshot.anchors) {\n const el = this.findElementByKey(key);\n if (!el) {\n continue;\n }\n\n const newRect = el.getBoundingClientRect();\n const topDiff = Math.abs(newRect.top - oldRect.top);\n const leftDiff = Math.abs(newRect.left - oldRect.left);\n\n if (topDiff > THRESHOLD || leftDiff > THRESHOLD) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Find an element by its scrollable key\n *\n * @param {string} key - Element key\n * @returns {HTMLElement|null} Found element or null\n */\n findElementByKey(key) {\n if (key === 'window') {\n return null;\n }\n\n if (key.startsWith('#')) {\n return document.getElementById(key.slice(1));\n }\n\n try {\n return document.querySelector(key);\n } catch {\n return null;\n }\n }\n\n /**\n * Restore scroll positions if layout hasn't changed significantly\n *\n * Logs a message if scroll restoration is skipped due to layout changes.\n */\n restoreScrollPositions() {\n if (this.layoutChangedSignificantly()) {\n console.log('[HMR] Layout changed significantly, not restoring scroll');\n return;\n }\n\n // Restore window scroll\n const windowPos = this.scrollPositions.get('window');\n if (windowPos) {\n window.scrollTo(windowPos.left, windowPos.top);\n }\n\n // Restore container scrolls\n for (const [key, pos] of this.scrollPositions) {\n if (key === 'window') {\n continue;\n }\n\n const el = this.findElementByKey(key);\n if (el) {\n el.scrollTop = pos.top;\n el.scrollLeft = pos.left;\n }\n }\n }\n\n /**\n * Capture all state (form + scroll + layout)\n *\n * Convenience method that calls all capture methods.\n */\n captureAll() {\n this.captureFormState();\n this.captureScrollPositions();\n this.captureLayout();\n }\n\n /**\n * Restore all state (form + scroll)\n *\n * Convenience method that calls all restore methods.\n */\n restoreAll() {\n this.restoreFormState();\n this.restoreScrollPositions();\n }\n\n /**\n * Clear all captured state\n */\n clear() {\n this.capturedInputs.clear();\n this.scrollPositions.clear();\n this.layoutSnapshot = null;\n }\n}\n\n/**\n * Singleton state capturer instance\n * @type {StateCapturer}\n */\nexport const stateCapturer = new StateCapturer();\n", "/**\n * HMR Error Overlay\n *\n * Displays error information in a full-screen overlay with Shadow DOM isolation.\n * Provides click-to-open editor support and keyboard/click dismissal.\n *\n * @module @coherent.js/client/hmr/overlay\n */\n\n/**\n * Escape HTML special characters to prevent XSS.\n * @param {string} str - String to escape\n * @returns {string} Escaped string\n */\nexport function escapeHtml(str) {\n return String(str)\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n\n/**\n * Format code frame with line numbers and highlight.\n * @param {string} frame - Code frame content\n * @param {number} highlightLine - Line number to highlight (1-based)\n * @param {number} [startLine=1] - Starting line number for the frame\n * @returns {string} Formatted HTML string\n */\n/**\n * Coerce a line or column to a positive integer, or null when it is not one.\n *\n * These values reach the overlay markup without escaping \u2014 `line` even lands\n * inside a quoted attribute \u2014 so they are narrowed to integers here rather\n * than trusting the shape of whatever built the error object.\n *\n * @param {*} value - Candidate line or column\n * @returns {number|null} A positive integer, or null\n */\nfunction toPositiveInt(value) {\n const parsed = Number(value);\n return Number.isInteger(parsed) && parsed > 0 ? parsed : null;\n}\n\nexport function formatCodeFrame(frame, highlightLine, startLine = 1) {\n if (!frame) return '';\n\n // Interpolated into markup below without escaping, so a non-numeric\n // startLine would be concatenated rather than added.\n const firstLine = toPositiveInt(startLine) ?? 1;\n\n const lines = frame.split('\\n');\n return lines.map((content, i) => {\n const lineNum = firstLine + i;\n const isHighlight = lineNum === highlightLine;\n return `<div class=\"line${isHighlight ? ' highlight' : ''}\">\n <span class=\"line-number\">${lineNum}</span>\n <span class=\"line-content\">${escapeHtml(content)}</span>\n </div>`;\n }).join('');\n}\n\n/**\n * Editor URL scheme map for click-to-open functionality.\n */\nconst EDITOR_URLS = {\n vscode: (file, line) => `vscode://file/${file}:${line}`,\n cursor: (file, line) => `cursor://file/${file}:${line}`,\n 'vscode-insiders': (file, line) => `vscode-insiders://file/${file}:${line}`,\n atom: (file, line) => `atom://core/open/file?filename=${file}&line=${line}`,\n sublime: (file, line) => `subl://open?url=file://${file}&line=${line}`,\n webstorm: (file, line) => `webstorm://open?file=${file}&line=${line}`,\n idea: (file, line) => `idea://open?file=${file}&line=${line}`\n};\n\n/**\n * CSS styles for the error overlay (Dracula-inspired color scheme).\n */\nconst OVERLAY_STYLES = `\n :host {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 99999;\n --bg: #181818;\n --text: #f8f8f2;\n --red: #ff5555;\n --yellow: #f1fa8c;\n --purple: #bd93f9;\n --cyan: #8be9fd;\n --code-bg: #282a36;\n --line-num: #6272a4;\n }\n .backdrop {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.66);\n }\n .container {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: min(800px, 90vw);\n max-height: 90vh;\n overflow: auto;\n background: var(--bg);\n border-radius: 8px;\n box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);\n font-family: 'SF Mono', Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;\n }\n .header {\n padding: 16px 20px;\n background: var(--red);\n color: white;\n display: flex;\n justify-content: space-between;\n align-items: center;\n border-radius: 8px 8px 0 0;\n }\n .title {\n font-weight: bold;\n font-size: 16px;\n }\n .close-btn {\n background: none;\n border: none;\n color: white;\n font-size: 24px;\n cursor: pointer;\n padding: 0 8px;\n line-height: 1;\n }\n .close-btn:hover {\n opacity: 0.8;\n }\n .content {\n padding: 20px;\n color: var(--text);\n }\n .message {\n font-size: 18px;\n color: var(--red);\n margin-bottom: 20px;\n word-break: break-word;\n }\n .file {\n color: var(--cyan);\n margin-bottom: 16px;\n cursor: pointer;\n text-decoration: underline;\n }\n .file:hover {\n color: var(--purple);\n }\n .code-frame {\n background: var(--code-bg);\n padding: 16px;\n border-radius: 4px;\n overflow-x: auto;\n font-size: 14px;\n line-height: 1.5;\n margin-bottom: 16px;\n }\n .line {\n display: flex;\n }\n .line-number {\n width: 50px;\n color: var(--line-num);\n text-align: right;\n padding-right: 16px;\n user-select: none;\n flex-shrink: 0;\n }\n .line-content {\n flex: 1;\n white-space: pre;\n }\n .line.highlight {\n background: rgba(255, 85, 85, 0.2);\n }\n .line.highlight .line-content {\n color: var(--red);\n }\n .stack {\n margin-top: 20px;\n font-size: 12px;\n color: var(--line-num);\n white-space: pre-wrap;\n max-height: 200px;\n overflow-y: auto;\n }\n .tip {\n margin-top: 16px;\n padding: 12px;\n background: rgba(189, 147, 249, 0.1);\n border-left: 3px solid var(--purple);\n font-size: 13px;\n color: var(--text);\n }\n .tip strong {\n color: var(--purple);\n }\n`;\n\n/**\n * Error overlay class for HMR error display.\n * Uses Shadow DOM for complete style isolation.\n */\nexport class ErrorOverlay {\n constructor() {\n /** @type {{ host: HTMLElement, shadow: ShadowRoot } | null} */\n this.overlay = null;\n /** @type {string} */\n this.editor = this._getStoredEditor();\n /** @type {((e: KeyboardEvent) => void) | null} */\n this.escapeHandler = null;\n }\n\n /**\n * Get stored editor preference from localStorage.\n * @returns {string} Editor name\n * @private\n */\n _getStoredEditor() {\n try {\n return localStorage.getItem('coherent-editor') || 'vscode';\n } catch {\n return 'vscode';\n }\n }\n\n /**\n * Create the overlay element with Shadow DOM.\n * @returns {{ host: HTMLElement, shadow: ShadowRoot }} Overlay elements\n */\n createOverlay() {\n if (this.overlay) return this.overlay;\n\n const host = document.createElement('div');\n host.id = 'coherent-error-overlay';\n const shadow = host.attachShadow({ mode: 'open' });\n\n const style = document.createElement('style');\n style.textContent = OVERLAY_STYLES;\n shadow.appendChild(style);\n\n this.overlay = { host, shadow };\n return this.overlay;\n }\n\n /**\n * Show the error overlay with error details.\n * @param {Object} error - Error details\n * @param {string} error.message - Error message\n * @param {string} [error.file] - File path\n * @param {number} [error.line] - Line number\n * @param {number} [error.column] - Column number\n * @param {string} [error.frame] - Code frame with context\n * @param {string} [error.stack] - Stack trace\n */\n show(error) {\n const { host, shadow } = this.createOverlay();\n\n // Clear previous content (but keep styles)\n const existingWrapper = shadow.querySelector('.wrapper');\n if (existingWrapper) existingWrapper.remove();\n\n const line = toPositiveInt(error.line);\n const column = toPositiveInt(error.column);\n\n // Calculate start line for code frame (center on error line)\n const frameLines = error.frame ? error.frame.split('\\n').length : 0;\n const startLine = line ? Math.max(1, line - Math.floor(frameLines / 2)) : 1;\n\n const wrapper = document.createElement('div');\n wrapper.className = 'wrapper';\n wrapper.innerHTML = `\n <div class=\"backdrop\"></div>\n <div class=\"container\">\n <div class=\"header\">\n <span class=\"title\">HMR Error</span>\n <button class=\"close-btn\" title=\"Close (Escape)\">&times;</button>\n </div>\n <div class=\"content\">\n <div class=\"message\">${escapeHtml(error.message || 'Unknown error')}</div>\n ${error.file ? `\n <div class=\"file\" data-file=\"${escapeHtml(error.file)}\" data-line=\"${line || 1}\">\n ${escapeHtml(error.file)}${line ? `:${line}` : ''}${column ? `:${column}` : ''}\n </div>\n ` : ''}\n ${error.frame ? `\n <div class=\"code-frame\">${formatCodeFrame(error.frame, line, startLine)}</div>\n ` : ''}\n ${error.stack ? `\n <div class=\"stack\">${escapeHtml(error.stack)}</div>\n ` : ''}\n <div class=\"tip\">\n Press <strong>Escape</strong> or click the X to dismiss.\n ${error.file ? ` Click the file path to open in ${escapeHtml(this.editor)}.` : ''}\n </div>\n </div>\n </div>\n `;\n\n shadow.appendChild(wrapper);\n\n // Event handlers\n const closeBtn = wrapper.querySelector('.close-btn');\n const backdrop = wrapper.querySelector('.backdrop');\n const fileLink = wrapper.querySelector('.file');\n\n closeBtn?.addEventListener('click', () => this.hide());\n backdrop?.addEventListener('click', () => this.hide());\n fileLink?.addEventListener('click', (e) => {\n const target = e.target;\n const file = target.dataset.file;\n const line = parseInt(target.dataset.line, 10) || 1;\n this.openInEditor(file, line);\n });\n\n // Escape key handler\n this.escapeHandler = (e) => {\n if (e.key === 'Escape') this.hide();\n };\n document.addEventListener('keydown', this.escapeHandler);\n\n // Add to DOM if not already\n if (!host.parentNode) {\n document.body.appendChild(host);\n }\n }\n\n /**\n * Hide and remove the error overlay.\n */\n hide() {\n if (this.overlay?.host.parentNode) {\n this.overlay.host.parentNode.removeChild(this.overlay.host);\n }\n if (this.escapeHandler) {\n document.removeEventListener('keydown', this.escapeHandler);\n this.escapeHandler = null;\n }\n // Reset overlay reference so it can be recreated\n this.overlay = null;\n }\n\n /**\n * Open file in configured editor.\n * @param {string} file - File path\n * @param {number} [line=1] - Line number\n */\n openInEditor(file, line = 1) {\n const urlGenerator = EDITOR_URLS[this.editor] || EDITOR_URLS.vscode;\n const url = urlGenerator(file, line);\n window.open(url, '_self');\n }\n\n /**\n * Set preferred editor and store in localStorage.\n * @param {string} editor - Editor name (vscode, cursor, vscode-insiders, atom, sublime, webstorm, idea)\n */\n setEditor(editor) {\n this.editor = editor;\n try {\n localStorage.setItem('coherent-editor', editor);\n } catch {\n // Ignore localStorage errors\n }\n }\n}\n\n/**\n * Singleton instance of ErrorOverlay.\n */\nexport const errorOverlay = new ErrorOverlay();\n", "/**\n * HMR Connection Status Indicator\n *\n * Displays a small colored dot in the bottom-right corner indicating\n * WebSocket connection status. Unobtrusive design per CONTEXT.md decision.\n *\n * @module @coherent.js/client/hmr/indicator\n */\n\n/**\n * Status color mapping for connection states.\n */\nconst STATUS_COLORS = {\n connected: '#10b981', // Green\n disconnected: '#ef4444', // Red\n reconnecting: '#f59e0b', // Yellow/amber\n error: '#ef4444' // Red\n};\n\n/**\n * Status title mapping for accessibility.\n */\nconst STATUS_TITLES = {\n connected: 'HMR: Connected',\n disconnected: 'HMR: Disconnected',\n reconnecting: 'HMR: Reconnecting...',\n error: 'HMR: Error'\n};\n\n/**\n * Default/initial color before status is set.\n */\nconst DEFAULT_COLOR = '#666';\n\n/**\n * Connection status indicator class.\n * Shows an 8px colored dot in the bottom-right corner of the viewport.\n */\nexport class ConnectionIndicator {\n constructor() {\n /** @type {HTMLElement | null} */\n this.indicator = null;\n }\n\n /**\n * Create the indicator element if it doesn't exist.\n * Uses inline styles to avoid external CSS dependencies.\n */\n create() {\n if (this.indicator) return;\n\n const el = document.createElement('div');\n el.id = 'coherent-hmr-indicator';\n el.style.cssText = `\n position: fixed;\n bottom: 8px;\n right: 8px;\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: ${DEFAULT_COLOR};\n z-index: 99998;\n pointer-events: none;\n transition: background 0.3s ease;\n `;\n el.title = 'HMR: Initializing';\n\n document.body.appendChild(el);\n this.indicator = el;\n }\n\n /**\n * Update the indicator status.\n * Creates the element if it doesn't exist (lazy initialization).\n *\n * @param {string} status - Status string: 'connected', 'disconnected', 'reconnecting', or 'error'\n */\n update(status) {\n if (!this.indicator) {\n this.create();\n }\n\n const color = STATUS_COLORS[status] || STATUS_COLORS.disconnected;\n const title = STATUS_TITLES[status] || 'HMR: Unknown';\n\n this.indicator.style.background = color;\n this.indicator.title = title;\n }\n\n /**\n * Remove the indicator from the DOM.\n */\n destroy() {\n if (this.indicator?.parentNode) {\n this.indicator.parentNode.removeChild(this.indicator);\n }\n this.indicator = null;\n }\n}\n\n/**\n * Singleton instance of ConnectionIndicator.\n */\nexport const connectionIndicator = new ConnectionIndicator();\n", "/**\n * ModuleTracker - Tracks module graph and HMR boundaries\n *\n * Provides a Vite-compatible hot context API for modules to declare\n * how they should be handled during HMR updates. Tracks accept/dispose\n * handlers and persistent data that survives updates.\n *\n * @module @coherent.js/client/hmr/module-tracker\n */\n\n/**\n * Tracks module HMR registrations and provides hot context API\n */\nexport class ModuleTracker {\n constructor() {\n /**\n * Module registrations map\n * @type {Map<string, { accept: Function|null, acceptDeps: { deps: string[], callback: Function }|null, dispose: Function|null, prune: Function|null, data: Object }>}\n */\n this.modules = new Map();\n\n /**\n * WebSocket reference for invalidation messages\n * @type {WebSocket|null}\n */\n this.socket = null;\n }\n\n /**\n * Set WebSocket reference for invalidation messages\n * @param {WebSocket|null} socket - WebSocket connection\n */\n setSocket(socket) {\n this.socket = socket;\n }\n\n /**\n * Create a hot context for a module (Vite-compatible API)\n *\n * Returns an object with:\n * - data: Persistent object that survives HMR updates\n * - accept(callback): Register self-update handler\n * - acceptDeps(deps, callback): Register dependency update handler\n * - dispose(callback): Register cleanup handler called before replacement\n * - prune(callback): Register handler for when module is removed\n * - invalidate(message): Signal that module cannot hot-update\n *\n * @param {string} moduleId - Unique identifier for the module\n * @returns {Object} Hot context object\n */\n createHotContext(moduleId) {\n // Get or create module data, preserving existing data object\n let moduleData = this.modules.get(moduleId);\n if (!moduleData) {\n moduleData = {\n accept: null,\n acceptDeps: null,\n dispose: null,\n prune: null,\n data: {},\n };\n this.modules.set(moduleId, moduleData);\n }\n\n const tracker = this;\n\n return {\n /**\n * Persistent data object that survives HMR updates.\n * Use this to preserve state across module replacements.\n */\n get data() {\n return moduleData.data;\n },\n\n /**\n * Accept self updates.\n * Called when this module is updated and can handle its own replacement.\n *\n * @param {Function} [callback] - Optional callback receiving the new module\n */\n accept(callback) {\n moduleData.accept = callback || (() => {});\n },\n\n /**\n * Accept dependency updates.\n * Called when one of the specified dependencies is updated.\n *\n * @param {string|string[]} deps - Dependency module ID(s)\n * @param {Function} callback - Callback receiving updated dependencies\n */\n acceptDeps(deps, callback) {\n const depsArray = Array.isArray(deps) ? deps : [deps];\n moduleData.acceptDeps = { deps: depsArray, callback };\n },\n\n /**\n * Register disposal callback.\n * Called before the module is replaced, receives the data object\n * to allow saving state for the next version.\n *\n * @param {Function} callback - Cleanup handler, receives data object\n */\n dispose(callback) {\n moduleData.dispose = callback;\n },\n\n /**\n * Register prune callback.\n * Called when the module is completely removed from the module graph.\n *\n * @param {Function} callback - Prune handler\n */\n prune(callback) {\n moduleData.prune = callback;\n },\n\n /**\n * Invalidate this module.\n * Signals that the module cannot be hot-updated and should propagate\n * the update to its importers.\n *\n * @param {string} [message] - Optional message explaining why\n */\n invalidate(message) {\n const WS_OPEN = typeof WebSocket !== 'undefined' ? WebSocket.OPEN : 1;\n if (tracker.socket?.readyState === WS_OPEN) {\n tracker.socket.send(JSON.stringify({\n type: 'invalidate',\n moduleId,\n message,\n }));\n }\n // Log for debugging\n console.log(`[HMR] Module ${moduleId} invalidated${message ? `: ${message}` : ''}`);\n },\n };\n }\n\n /**\n * Check if a module can be hot-updated\n *\n * Returns true if the module has registered an accept handler.\n *\n * @param {string} moduleId - Module identifier\n * @returns {boolean} True if module accepts HMR updates\n */\n canHotUpdate(moduleId) {\n const moduleData = this.modules.get(moduleId);\n return !!(moduleData?.accept || moduleData?.acceptDeps);\n }\n\n /**\n * Check if a module is an HMR boundary\n *\n * A module is considered a boundary if:\n * - It has an accept handler registered\n * - It exports __hmrBoundary = true\n * - It is associated with a data-coherent-component element\n *\n * @param {string} moduleId - Module identifier\n * @param {Object} [moduleExports] - Optional module exports to check for __hmrBoundary\n * @returns {boolean} True if module is an HMR boundary\n */\n isHmrBoundary(moduleId, moduleExports) {\n // Check for accept handler\n if (this.canHotUpdate(moduleId)) {\n return true;\n }\n\n // Check for explicit __hmrBoundary export\n if (moduleExports?.__hmrBoundary === true) {\n return true;\n }\n\n // Check for coherent component presence (by convention)\n // Extract component name from module path\n const componentName = this.extractComponentName(moduleId);\n if (componentName && typeof document !== 'undefined') {\n const hasComponent = document.querySelector(\n `[data-coherent-component=\"${componentName}\"]`\n );\n if (hasComponent) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Extract a potential component name from module path\n *\n * @param {string} moduleId - Module path\n * @returns {string|null} Component name or null\n * @private\n */\n extractComponentName(moduleId) {\n // Extract filename without extension\n const match = moduleId.match(/\\/([^/]+?)(?:\\.[^.]+)?$/);\n if (match) {\n return match[1];\n }\n return null;\n }\n\n /**\n * Execute dispose callback for a module\n *\n * Calls the registered dispose handler with the data object,\n * allowing the module to save state for the next version.\n *\n * @param {string} moduleId - Module identifier\n * @returns {Object|null} The data object (for passing to next version)\n */\n executeDispose(moduleId) {\n const moduleData = this.modules.get(moduleId);\n if (!moduleData) {\n return null;\n }\n\n // Call dispose handler with data object\n if (typeof moduleData.dispose === 'function') {\n try {\n moduleData.dispose(moduleData.data);\n } catch (err) {\n console.error(`[HMR] Error in dispose handler for ${moduleId}:`, err);\n }\n }\n\n return moduleData.data;\n }\n\n /**\n * Execute accept callback for a module\n *\n * Calls the registered accept handler with the new module.\n *\n * @param {string} moduleId - Module identifier\n * @param {Object} [newModule] - The newly imported module\n * @returns {boolean} True if accept handler was called\n */\n executeAccept(moduleId, newModule) {\n const moduleData = this.modules.get(moduleId);\n if (!moduleData?.accept) {\n return false;\n }\n\n try {\n moduleData.accept(newModule);\n return true;\n } catch (err) {\n console.error(`[HMR] Error in accept handler for ${moduleId}:`, err);\n return false;\n }\n }\n\n /**\n * Execute acceptDeps callback for a module\n *\n * Calls the registered acceptDeps handler with the updated dependencies.\n *\n * @param {string} moduleId - Module identifier\n * @param {Object} updatedDeps - Map of dependency moduleId -> new module\n * @returns {boolean} True if acceptDeps handler was called\n */\n executeAcceptDeps(moduleId, updatedDeps) {\n const moduleData = this.modules.get(moduleId);\n if (!moduleData?.acceptDeps) {\n return false;\n }\n\n try {\n const { deps, callback } = moduleData.acceptDeps;\n // Build array of updated modules in same order as deps\n const modules = deps.map((dep) => updatedDeps[dep]);\n callback(modules);\n return true;\n } catch (err) {\n console.error(`[HMR] Error in acceptDeps handler for ${moduleId}:`, err);\n return false;\n }\n }\n\n /**\n * Execute prune callback for a module\n *\n * Called when a module is removed from the module graph.\n *\n * @param {string} moduleId - Module identifier\n */\n executePrune(moduleId) {\n const moduleData = this.modules.get(moduleId);\n if (!moduleData?.prune) {\n return;\n }\n\n try {\n moduleData.prune();\n } catch (err) {\n console.error(`[HMR] Error in prune handler for ${moduleId}:`, err);\n }\n\n // Remove module from tracking\n this.modules.delete(moduleId);\n }\n\n /**\n * Check if module is registered\n *\n * @param {string} moduleId - Module identifier\n * @returns {boolean} True if module is registered\n */\n hasModule(moduleId) {\n return this.modules.has(moduleId);\n }\n\n /**\n * Get module data (for testing/debugging)\n *\n * @param {string} moduleId - Module identifier\n * @returns {Object|null} Module data or null\n */\n getModuleData(moduleId) {\n return this.modules.get(moduleId) || null;\n }\n\n /**\n * Clear all module registrations (for testing)\n */\n clear() {\n this.modules.clear();\n }\n}\n\n/**\n * Singleton module tracker instance\n * @type {ModuleTracker}\n */\nexport const moduleTracker = new ModuleTracker();\n\n/**\n * Convenience function to create a hot context for a module\n *\n * @param {string} moduleId - Module identifier\n * @returns {Object} Hot context object\n */\nexport function createHotContext(moduleId) {\n return moduleTracker.createHotContext(moduleId);\n}\n", "/**\n * HMRClient - Orchestrates WebSocket connection and HMR updates\n *\n * Integrates all HMR modules (cleanup tracker, state capturer, error overlay,\n * connection indicator) to provide seamless hot module replacement with\n * state preservation.\n *\n * @module @coherent.js/client/hmr/client\n */\n\nimport { cleanupTracker } from './cleanup-tracker.js';\nimport { stateCapturer } from './state-capturer.js';\nimport { errorOverlay } from './overlay.js';\nimport { connectionIndicator } from './indicator.js';\nimport { moduleTracker } from './module-tracker.js';\n\n/** Longest stack line worth parsing; real frames are far shorter. */\nconst MAX_STACK_LINE_LENGTH = 1024;\n\n/** Most frames worth parsing; V8's default Error.stackTraceLimit is 10. */\nconst MAX_STACK_LINES = 50;\n\n/**\n * Parse error stack to extract file/line info\n *\n * @param {Error} error - Error object\n * @returns {{ file: string|null, line: number|null, column: number|null }} Parsed location\n */\nfunction parseErrorLocation(error) {\n const result = { file: null, line: null, column: null };\n\n if (!error.stack) {\n return result;\n }\n\n // Match common stack trace formats:\n // Chrome/Node: \"at Function (file.js:10:5)\"\n // Firefox: \"Function@file.js:10:5\"\n // Safari: \"file.js:10:5\"\n const patterns = [\n /at\\s[^(]*\\(([^()]+):(\\d+):(\\d+)\\)/, // Chrome/Node with parens\n /at\\s+([^\\s].*):(\\d+):(\\d+)/, // Chrome/Node without parens\n /@([^@]+):(\\d+):(\\d+)/, // Firefox\n /^(.+?):(\\d+):(\\d+)/, // Safari\n ];\n\n // These patterns scan from every \"at\" or \"@\" in a line, so an oversized\n // line costs O(n^2): one 100,000-character line took 4.7s. Real frames are\n // short, and V8 caps a stack at 10 frames by default, so bounding both\n // makes the worst case constant without affecting any genuine stack.\n // CodeQL js/polynomial-redos.\n const lines = error.stack.split('\\n', MAX_STACK_LINES);\n for (const line of lines) {\n if (line.length > MAX_STACK_LINE_LENGTH) continue;\n for (const pattern of patterns) {\n const match = line.match(pattern);\n if (match) {\n result.file = match[1];\n result.line = parseInt(match[2], 10);\n result.column = parseInt(match[3], 10);\n return result;\n }\n }\n }\n\n return result;\n}\n\n/**\n * HMR Client class - manages WebSocket connection and update orchestration\n */\nexport class HMRClient {\n constructor() {\n /**\n * WebSocket connection\n * @type {WebSocket|null}\n */\n this.socket = null;\n\n /**\n * Connection state\n * @type {boolean}\n */\n this.connected = false;\n\n /**\n * Reconnection attempt counter\n * @type {number}\n */\n this.reconnectAttempts = 0;\n\n /**\n * Maximum reconnection attempts\n * @type {number}\n */\n this.maxReconnectAttempts = 10;\n\n /**\n * Base reconnection delay in ms\n * @type {number}\n */\n this.reconnectDelay = 1000;\n\n /**\n * Whether we've had a disconnect (for reload detection)\n * @type {boolean}\n */\n this.hadDisconnect = false;\n\n /**\n * Reconnect timeout ID\n * @type {number|null}\n */\n this.reconnectTimeout = null;\n\n /**\n * Initialization flag\n * @type {boolean}\n */\n this.initialized = false;\n }\n\n /**\n * Connect to the dev server WebSocket\n *\n * Establishes WebSocket connection with automatic reconnection using\n * exponential backoff with jitter.\n *\n * @returns {void}\n */\n connect() {\n if (typeof window === 'undefined') {\n return;\n }\n\n // Clear any pending reconnect\n if (this.reconnectTimeout !== null) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n try {\n const protocol = location.protocol === 'https:' ? 'wss' : 'ws';\n const wsUrl = `${protocol}://${location.host}`;\n this.socket = new WebSocket(wsUrl);\n\n // Share socket with module tracker for invalidation messages\n moduleTracker.setSocket(this.socket);\n\n this.socket.addEventListener('open', () => {\n console.log('[HMR] Connected');\n this.connected = true;\n this.reconnectAttempts = 0;\n connectionIndicator.update('connected');\n\n // Send connection acknowledgment\n this.socket.send(JSON.stringify({ type: 'connected' }));\n\n // If reconnecting after disconnect, reload (server may have restarted)\n if (this.hadDisconnect) {\n console.log('[HMR] Reconnected after disconnect, reloading page');\n setTimeout(() => location.reload(), 200);\n return;\n }\n });\n\n this.socket.addEventListener('close', () => {\n this.connected = false;\n this.hadDisconnect = true;\n connectionIndicator.update('disconnected');\n moduleTracker.setSocket(null);\n this.scheduleReconnect();\n });\n\n this.socket.addEventListener('error', (event) => {\n console.warn('[HMR] WebSocket error:', event);\n connectionIndicator.update('error');\n try {\n this.socket.close();\n } catch {\n // Ignore close errors\n }\n });\n\n this.socket.addEventListener('message', (event) => {\n this.handleMessage(event);\n });\n } catch (error) {\n console.warn('[HMR] Failed to connect:', error);\n this.scheduleReconnect();\n }\n }\n\n /**\n * Schedule a reconnection attempt with exponential backoff\n *\n * @private\n */\n scheduleReconnect() {\n if (this.reconnectAttempts >= this.maxReconnectAttempts) {\n console.warn('[HMR] Max reconnection attempts reached');\n connectionIndicator.update('disconnected');\n return;\n }\n\n connectionIndicator.update('reconnecting');\n\n // Exponential backoff with jitter\n const delay = Math.min(\n this.reconnectDelay * Math.pow(2, this.reconnectAttempts) + Math.random() * 1000,\n 30000\n );\n this.reconnectAttempts++;\n\n console.log(`[HMR] Reconnecting in ${Math.round(delay)}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);\n\n this.reconnectTimeout = setTimeout(() => {\n this.reconnectTimeout = null;\n this.connect();\n }, delay);\n }\n\n /**\n * Handle incoming WebSocket message\n *\n * @param {MessageEvent} event - WebSocket message event\n * @private\n */\n handleMessage(event) {\n let data;\n try {\n data = JSON.parse(event.data);\n } catch {\n return;\n }\n\n console.log('[HMR] message', data.type, data.filePath || data.webPath || '');\n\n switch (data.type) {\n case 'connected':\n // Connection acknowledged\n break;\n\n case 'hmr-full-reload':\n case 'reload':\n console.warn('[HMR] Server requested full reload');\n location.reload();\n break;\n\n case 'hmr-component-update':\n case 'hmr-update':\n this.handleUpdate(data);\n break;\n\n case 'hmr-error':\n this.showError(data.error || data);\n break;\n\n case 'preview-update':\n // No-op: used by dashboard for live preview panes\n break;\n\n default:\n // Unknown message type, ignore\n break;\n }\n }\n\n /**\n * Handle module update\n *\n * Orchestrates the full HMR update cycle:\n * 1. Capture form/scroll state\n * 2. Execute dispose handlers\n * 3. Clean up module resources\n * 4. Re-import module\n * 5. Execute accept handlers\n * 6. Restore state\n *\n * @param {Object} data - Update message data\n * @param {string} [data.filePath] - File path that changed\n * @param {string} [data.webPath] - Web-accessible path\n * @param {string} [data.updateType] - Type of update (component, style, etc.)\n */\n async handleUpdate(data) {\n const filePath = data.webPath || data.filePath || '';\n const moduleId = filePath;\n\n try {\n // 1. Capture current state\n stateCapturer.captureAll();\n\n // 2. Execute dispose handler if registered\n if (moduleTracker.hasModule(moduleId)) {\n moduleTracker.executeDispose(moduleId);\n }\n\n // 3. Clean up module resources\n if (cleanupTracker.hasResources(moduleId)) {\n cleanupTracker.checkForLeaks(moduleId);\n cleanupTracker.cleanup(moduleId);\n }\n\n // 4. Re-import module with cache bust\n const importPath = filePath.startsWith('/') ? filePath : `/${filePath}`;\n const newModule = await import(`${importPath}?t=${Date.now()}`);\n\n // 5. Execute accept handler if module can hot-update\n const accepted = moduleTracker.canHotUpdate(moduleId);\n if (accepted) {\n moduleTracker.executeAccept(moduleId, newModule);\n } else {\n // Fall back to autoHydrate for components without explicit accept\n await this.fallbackHydrate();\n }\n\n // 6. Restore state\n stateCapturer.restoreAll();\n\n // 7. Hide error overlay (in case previous error is now fixed)\n errorOverlay.hide();\n\n // 8. Log success\n console.log(`[HMR] Updated: ${data.updateType || 'module'} ${filePath}`);\n } catch (error) {\n this.handleUpdateError(error, filePath);\n }\n }\n\n /**\n * Fall back to autoHydrate for non-HMR-aware modules\n *\n * @private\n */\n async fallbackHydrate() {\n try {\n // Try to import autoHydrate from the hydration module\n const { autoHydrate } = await import('../hydration.js');\n\n // If examples register a component registry on window, prefer targeted hydrate\n if (typeof window !== 'undefined' && window.componentRegistry) {\n autoHydrate(window.componentRegistry);\n } else {\n autoHydrate();\n }\n } catch {\n // autoHydrate not available or failed\n console.warn('[HMR] autoHydrate not available, component may need manual refresh');\n }\n }\n\n /**\n * Handle update error\n *\n * @param {Error} error - Error that occurred\n * @param {string} filePath - File that was being updated\n * @private\n */\n handleUpdateError(error, filePath) {\n console.error('[HMR] Update failed:', error);\n\n // Parse error location from stack\n const location = parseErrorLocation(error);\n\n // Build error details for overlay\n const errorDetails = {\n message: error.message || 'Unknown error during HMR update',\n file: location.file || filePath,\n line: location.line,\n column: location.column,\n stack: error.stack,\n };\n\n this.showError(errorDetails);\n }\n\n /**\n * Show error overlay\n *\n * @param {Object} error - Error details\n */\n showError(error) {\n errorOverlay.show(error);\n }\n\n /**\n * Hide error overlay\n */\n hideError() {\n errorOverlay.hide();\n }\n\n /**\n * Initialize HMR client\n *\n * Guards against double initialization and connects to dev server.\n *\n * @returns {void}\n */\n initialize() {\n if (typeof window === 'undefined') {\n return;\n }\n\n // Guard against double initialization\n if (window.__coherent_hmr_initialized || this.initialized) {\n return;\n }\n\n window.__coherent_hmr_initialized = true;\n this.initialized = true;\n\n this.connect();\n }\n\n /**\n * Disconnect and clean up\n *\n * @returns {void}\n */\n disconnect() {\n if (this.reconnectTimeout !== null) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n\n if (this.socket) {\n try {\n this.socket.close();\n } catch {\n // Ignore close errors\n }\n this.socket = null;\n }\n\n this.connected = false;\n moduleTracker.setSocket(null);\n connectionIndicator.destroy();\n }\n\n /**\n * Check if client is connected\n *\n * @returns {boolean} True if connected\n */\n isConnected() {\n return this.connected;\n }\n}\n\n/**\n * Singleton HMR client instance\n * @type {HMRClient}\n */\nexport const hmrClient = new HMRClient();\n"],
5
- "mappings": ";;;;;;;;;AAaO,SAAS,eAAe,OAAO;AACpC,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAGhD,QAAM,eAAe,CAAC;AACtB,MAAI,kBAAkB;AAEtB,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,eAAe,KAAK,GAAG;AACzB,mBAAa,GAAG,IAAI;AACpB,wBAAkB;AAAA,IACpB;AAAA,EAEF;AAEA,MAAI,CAAC,gBAAiB,QAAO;AAE7B,MAAI;AACF,UAAM,OAAO,KAAK,UAAU,YAAY;AAExC,WAAO,KAAK,mBAAmB,IAAI,CAAC;AAAA,EACtC,SAAS,GAAG;AACV,YAAQ,KAAK,4CAA4C,CAAC;AAC1D,WAAO;AAAA,EACT;AACF;AAQO,SAAS,iBAAiB,SAAS;AACxC,MAAI,CAAC,WAAW,OAAO,YAAY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UAAS;AAAA,MACf,QAAQA,UAAS;AAAA,MACjB,OAAO,MAAM;AAAA,IACf;AAEA,SAAK,UAAU,YAAY;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,UAAU,OAAO;AACf,iBAAa,KAAK,KAAK;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY;AACV,iBAAa,KAAK;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,aAAa;AACX,QAAI,OAAO,WAAW,aAAa;AACjC;AAAA,IACF;AAGA,QAAI,OAAO,8BAA8B,KAAK,aAAa;AACzD;AAAA,IACF;AAEA,WAAO,6BAA6B;AACpC,SAAK,cAAc;AAEnB,SAAK,QAAQ;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,aAAa;AACX,QAAI,KAAK,qBAAqB,MAAM;AAClC,mBAAa,KAAK,gBAAgB;AAClC,WAAK,mBAAmB;AAAA,IAC1B;AAEA,QAAI,KAAK,QAAQ;AACf,UAAI;AACF,aAAK,OAAO,MAAM;AAAA,MACpB,QAAQ;AAAA,MAER;AACA,WAAK,SAAS;AAAA,IAChB;AAEA,SAAK,YAAY;AACjB,kBAAc,UAAU,IAAI;AAC5B,wBAAoB,QAAQ;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,cAAc;AACZ,WAAO,KAAK;AAAA,EACd;AACF;AAMO,IAAM,YAAY,IAAI,UAAU;",
6
- "names": ["options", "getVNodeChildren", "getSignificantDOMChildren", "line", "location"]
3
+ "sources": ["../src/hydration/state-serializer.js", "../src/hydration/vnode.js", "../src/hydration/mismatch-detector.js", "../src/hydration/patch.js", "../src/hydrate.js"],
4
+ "sourcesContent": ["/**\n * State serialization utilities for Coherent.js hydration\n *\n * Uses base64 encoding to safely embed state in data attributes\n * without escaping issues.\n */\n\n/**\n * Serialize component state to base64-encoded JSON string\n *\n * @param {Object} state - Component state object\n * @returns {string|null} - Base64 encoded state or null if empty/invalid\n */\nexport function serializeState(state) {\n if (!state || typeof state !== 'object') return null;\n\n // Filter out non-serializable values (functions, symbols, undefined)\n const serializable = {};\n let hasSerializable = false;\n\n for (const [key, value] of Object.entries(state)) {\n if (isSerializable(value)) {\n serializable[key] = value;\n hasSerializable = true;\n }\n // Silently omit functions, symbols, undefined - they reconstruct on hydrate\n }\n\n if (!hasSerializable) return null;\n\n try {\n const json = JSON.stringify(serializable);\n // Use encodeURIComponent to handle unicode, then btoa for base64\n return btoa(encodeURIComponent(json));\n } catch (e) {\n console.warn('[Coherent.js] Failed to serialize state:', e);\n return null;\n }\n}\n\n/**\n * Deserialize state from base64-encoded JSON string\n *\n * @param {string} encoded - Base64 encoded state string\n * @returns {Object|null} - Deserialized state or null if invalid\n */\nexport function deserializeState(encoded) {\n if (!encoded || typeof encoded !== 'string') return null;\n\n try {\n const json = decodeURIComponent(atob(encoded));\n return JSON.parse(json);\n } catch (e) {\n console.warn('[Coherent.js] Failed to deserialize state:', e);\n return null;\n }\n}\n\n/**\n * Extract state from a DOM element's data-state attribute\n *\n * @param {HTMLElement} element - DOM element to extract state from\n * @returns {Object|null} - Extracted state or null\n */\nexport function extractState(element) {\n if (!element || typeof element.getAttribute !== 'function') {\n return null;\n }\n\n const encoded = element.getAttribute('data-state');\n return deserializeState(encoded);\n}\n\n/**\n * Check if a value is serializable to JSON\n * @private\n */\nfunction isSerializable(value) {\n if (value === undefined) return false;\n if (value === null) return true;\n if (typeof value === 'function') return false;\n if (typeof value === 'symbol') return false;\n if (typeof value === 'bigint') return false; // BigInt not JSON serializable\n\n // Arrays and objects need recursive check\n if (Array.isArray(value)) {\n return value.every(isSerializable);\n }\n\n if (typeof value === 'object') {\n // Check for circular references would be expensive here\n // JSON.stringify will catch them in serializeState\n return true;\n }\n\n return true; // primitives (string, number, boolean)\n}\n\n/**\n * Size warning threshold (bytes)\n * Warn if serialized state exceeds this\n */\nconst STATE_SIZE_WARNING_THRESHOLD = 10 * 1024; // 10KB\n\n/**\n * Serialize state with size warning\n *\n * @param {Object} state - Component state\n * @param {string} componentName - Component name for warning message\n * @returns {string|null} - Serialized state\n */\nexport function serializeStateWithWarning(state, componentName = 'Unknown') {\n const encoded = serializeState(state);\n\n if (encoded && encoded.length > STATE_SIZE_WARNING_THRESHOLD) {\n console.warn(\n `[Coherent.js] Large state detected for component \"${componentName}\": ` +\n `${Math.round(encoded.length / 1024)}KB. Consider using a state management ` +\n `solution for large datasets.`\n );\n }\n\n return encoded;\n}\n", "/**\n * Virtual node helpers shared by hydration, mismatch detection and patching.\n *\n * A component's children are not a list of DOM nodes: they may contain null,\n * booleans, nested arrays, function components and adjacent strings that the\n * server merges into one text node. Everything that walks the virtual tree\n * next to the DOM must first reduce children to what the server actually\n * emitted, or indexes drift \u2014 a `null` before a button binds that button's\n * handler to the next element.\n *\n * @module @coherent.js/client/hydration/vnode\n */\n\n/** Elements the server renders without content or a closing tag. */\nexport const VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr',\n]);\n\n/**\n * Content marked with core's dangerouslySetInnerContent(), emitted verbatim.\n * @param {*} value\n * @returns {boolean}\n */\nexport function isTrustedContent(value) {\n // Same brand core's dangerouslySetInnerContent() sets: plain objects with\n // __trusted/__html keys (e.g. from JSON) are not trusted.\n return Boolean(value) &&\n typeof value === 'object' &&\n value[Symbol.for('coherent.js.trustedContent')] === true &&\n typeof value.__html === 'string';\n}\n\n/**\n * Call a function component the way core's renderer does: with no arguments,\n * following returned functions.\n * @returns {{ ok: boolean, value?: * }}\n */\nfunction callFunctionComponent(fn) {\n let result = fn;\n for (let guard = 0; typeof result === 'function'; guard++) {\n if (guard > 100) {\n return { ok: false };\n }\n try {\n result = result();\n } catch {\n // On the server a throwing component either failed the render or was\n // replaced through render()'s onError; neither is reproducible here,\n // so treat it as an opaque region.\n return { ok: false };\n }\n }\n return { ok: true, value: result };\n}\n\n/** What core's isCoherentObject (core/object-utils.js) accepts as a tag name. */\nconst TAG_NAME = /^[a-zA-Z][a-zA-Z0-9-]*$/;\n\n/**\n * Whether a value is an element virtual node (`{ tagName: props }`), as core\n * decides it: a non-empty object whose keys are all tag names. Core renders\n * an object with any other key (`{ my_tag: ... }`) as nothing.\n * @param {*} vNode\n * @returns {boolean}\n */\nexport function isElementVNode(vNode) {\n if (!vNode || typeof vNode !== 'object' || Array.isArray(vNode) || isTrustedContent(vNode)) {\n return false;\n }\n const keys = Object.keys(vNode);\n return keys.length > 0 && keys.every((key) => TAG_NAME.test(key));\n}\n\n/**\n * Split an element virtual node into its tag name and props, normalising the\n * shorthand forms core accepts (`{ span: 'text' }`, `{ br: null }`, function\n * content).\n *\n * Only the first key is read: an object with several keys is several sibling\n * elements, which getRenderedChildren() lists one by one.\n * @param {Object} vNode - Element virtual node\n * @returns {{ tagName: string, props: Object }}\n */\nexport function readElement(vNode) {\n const tagName = Object.keys(vNode)[0];\n let content = vNode[tagName];\n\n if (typeof content === 'function') {\n const called = callFunctionComponent(content);\n content = called.ok ? called.value : null;\n }\n\n if (content === null || content === undefined) {\n return { tagName, props: {} };\n }\n if (typeof content !== 'object') {\n return { tagName, props: { text: content } };\n }\n return { tagName, props: content };\n}\n\nfunction flatten(node, out) {\n if (node === null || node === undefined || typeof node === 'boolean') {\n return;\n }\n if (typeof node === 'string' || typeof node === 'number') {\n out.push({ type: 'text', text: String(node) });\n return;\n }\n if (Array.isArray(node)) {\n for (const child of node) flatten(child, out);\n return;\n }\n if (typeof node === 'function') {\n const called = callFunctionComponent(node);\n if (called.ok) flatten(called.value, out);\n else out.push({ type: 'opaque' });\n return;\n }\n if (isTrustedContent(node)) {\n out.push({ type: 'opaque', html: node.__html });\n return;\n }\n // A lazy() value: core renders what evaluate() returns.\n if (node.__isLazy === true && typeof node.evaluate === 'function') {\n const called = callFunctionComponent(() => node.evaluate());\n if (called.ok) flatten(called.value, out);\n else out.push({ type: 'opaque' });\n return;\n }\n if (!isElementVNode(node)) {\n return;\n }\n // Every key is an element: `{ span: ..., button: ... }` renders a span and\n // then a button, as core's renderer does.\n const tagNames = Object.keys(node);\n for (const tagName of tagNames) {\n out.push({ type: 'element', vNode: tagNames.length === 1 ? node : { [tagName]: node[tagName] } });\n }\n}\n\n/**\n * Evaluate an attribute value the way core's formatAttributes does: functions\n * are called with no arguments (a throwing one yields '').\n * @param {*} value\n * @returns {*}\n */\nexport function resolveAttributeValue(value) {\n if (typeof value !== 'function') return value;\n try {\n return value();\n } catch {\n return '';\n }\n}\n\n/** Props that are content or identity, never attributes. */\nconst NON_ATTRIBUTE_PROPS = new Set(['children', 'text', 'html', 'key']);\n\n/** Prop names that differ from their attribute name. */\nconst ATTRIBUTE_NAMES = { className: 'class', htmlFor: 'for' };\n\n/**\n * Enumerated attributes whose `false` is a value that must be written out,\n * as in core's ENUMERATED_BOOLEAN_ATTRIBUTES (core/html-utils.js).\n */\nconst ENUMERATED_BOOLEAN_ATTRIBUTES = new Set(['spellcheck', 'draggable', 'contenteditable']);\n\nfunction isEventProp(name, value) {\n return name.startsWith('on') && typeof value === 'function';\n}\n\nfunction toKebabCase(property) {\n return property.startsWith('--')\n ? property\n : property.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n}\n\n/**\n * Serialise a style object like core's formatAttributes does.\n * @param {Object} style\n * @returns {string}\n */\nfunction styleToCss(style) {\n return Object.entries(style)\n .filter(([, value]) => value !== null && value !== undefined && value !== false)\n .map(([property, value]) => `${toKebabCase(property)}: ${value}`)\n .join('; ');\n}\n\n/**\n * Normalise a class value like core's normalizeClassValue\n * (core/html-utils.js): strings as-is, arrays flattened with falsy entries\n * dropped, objects as the keys whose values are truthy (clsx-style).\n * @param {*} value\n * @returns {string}\n */\nfunction normalizeClassValue(value) {\n if (Array.isArray(value)) {\n return value.map(normalizeClassValue).filter(Boolean).join(' ');\n }\n if (value && typeof value === 'object') {\n return Object.keys(value).filter((name) => value[name]).join(' ');\n }\n if (value === null || value === undefined || value === false) return '';\n return String(value);\n}\n\n/**\n * The attributes a props object renders, as name \u2192 string ('' for a bare\n * attribute), in the order core's formatAttributes writes them. Omitted\n * names are absent.\n *\n * Functions are called, except `on*` handlers, which are not attributes;\n * `className`/`class` arrays and objects are joined like clsx, and the two\n * props together make one class attribute; style objects become\n * `prop: value` declarations; `true` is a bare attribute and `false`, `null`\n * and `undefined` omit it, except on `aria-*` and enumerated attributes\n * (`spellcheck`, `draggable`, `contenteditable`), where booleans are the\n * values \"true\" and \"false\".\n *\n * @param {Object} props\n * @returns {Map<string, string>}\n */\nexport function renderedAttributes(props) {\n const attributes = new Map();\n // Both given: one class attribute, in `class`'s place, `className` last\n const mergeClass = props.class !== undefined && props.className !== undefined;\n\n for (const [name, raw] of Object.entries(props)) {\n if (NON_ATTRIBUTE_PROPS.has(name) || isEventProp(name, raw)) continue;\n if (mergeClass && name === 'className') continue;\n\n const attrName = ATTRIBUTE_NAMES[name] ?? name;\n let value = mergeClass && name === 'class'\n ? [raw, props.className].map((v) => normalizeClassValue(resolveAttributeValue(v))).filter(Boolean).join(' ')\n : resolveAttributeValue(raw);\n\n if (attrName === 'class' && value !== null && typeof value === 'object') {\n value = normalizeClassValue(value);\n }\n if (\n typeof value === 'boolean' &&\n (attrName.startsWith('aria-') || ENUMERATED_BOOLEAN_ATTRIBUTES.has(attrName.toLowerCase()))\n ) {\n value = String(value);\n }\n\n if (attrName === 'style' && value && typeof value === 'object') {\n const css = styleToCss(value);\n if (css) attributes.set('style', css);\n } else if (value === true) {\n attributes.set(attrName, '');\n } else if (value !== false && value !== null && value !== undefined) {\n attributes.set(attrName, String(value));\n }\n }\n\n return attributes;\n}\n\n/**\n * The children an element's server output contains, in order: element nodes,\n * text nodes (adjacent strings merged, whitespace-only dropped) and opaque\n * regions (raw HTML or components whose output cannot be reproduced).\n *\n * Null, undefined and booleans render nothing (as does `text: null`); nested\n * arrays are flattened; an object with several tag keys is one element per\n * key, in key order; `text` precedes `children`; an `html` prop replaces both.\n * Each element entry's `vNode` has a single key.\n *\n * @param {string} tagName\n * @param {Object} props\n * @returns {Array<{type: 'element', vNode: Object}|{type: 'text', text: string}|{type: 'opaque', html?: string}>}\n * an opaque region carries its `html` when it is raw HTML rather than a\n * component this module cannot run\n */\nexport function getRenderedChildren(tagName, props) {\n if (!props || VOID_ELEMENTS.has(String(tagName).toLowerCase())) {\n return [];\n }\n // Null (or a function returning it) means \"no raw HTML\" / \"no text\" to\n // core, not the string \"null\"\n const html = resolveAttributeValue(props.html);\n if (html !== undefined && html !== null) {\n return [{ type: 'opaque', html: isTrustedContent(html) ? html.__html : String(html) }];\n }\n const text = resolveAttributeValue(props.text);\n if (isTrustedContent(text)) {\n return [{ type: 'opaque', html: text.__html }];\n }\n\n const raw = [];\n if (text !== undefined && text !== null) {\n raw.push({ type: 'text', text: String(text) });\n }\n flatten(props.children, raw);\n\n // Merge adjacent text the way the HTML parser does.\n const merged = [];\n for (const item of raw) {\n const last = merged[merged.length - 1];\n if (item.type === 'text' && last?.type === 'text') {\n last.text += item.text;\n } else {\n merged.push(item.type === 'text' ? { ...item } : item);\n }\n }\n\n return merged.filter((item) => item.type !== 'text' || item.text.trim() !== '');\n}\n\n/**\n * DOM children that correspond to rendered children: elements and text nodes\n * that are not whitespace-only.\n * @param {Node} element\n * @returns {Node[]}\n */\nexport function getSignificantDOMChildren(element) {\n if (!element || !element.childNodes) return [];\n\n return Array.from(element.childNodes).filter((node) => {\n if (node.nodeType === 1) return true;\n if (node.nodeType === 3) {\n return typeof node.textContent === 'string' && node.textContent.trim().length > 0;\n }\n return false;\n });\n}\n\n/**\n * Pair virtual children with DOM children.\n *\n * Without opaque regions the lists pair by position. Around opaque regions\n * only the children before the first one (from the start) and after the last\n * one (from the end) can be paired.\n *\n * @template V, D\n * @param {Array<V & {type: string}>} vList\n * @param {D[]} dList\n * @returns {{ pairs: Array<[V, D, number]>, exact: boolean }} `exact` is false\n * when opaque regions made the lengths incomparable\n */\nexport function alignChildren(vList, dList) {\n const firstOpaque = vList.findIndex((item) => item.type === 'opaque');\n const pairs = [];\n\n if (firstOpaque === -1) {\n const length = Math.min(vList.length, dList.length);\n for (let i = 0; i < length; i++) pairs.push([vList[i], dList[i], i]);\n return { pairs, exact: true };\n }\n\n let lastOpaque = firstOpaque;\n for (let i = vList.length - 1; i > firstOpaque; i--) {\n if (vList[i].type === 'opaque') {\n lastOpaque = i;\n break;\n }\n }\n\n for (let i = 0; i < firstOpaque && i < dList.length; i++) {\n pairs.push([vList[i], dList[i], i]);\n }\n const tail = vList.length - 1 - lastOpaque;\n for (let k = 1; k <= tail && dList.length - k >= firstOpaque; k++) {\n const vIndex = vList.length - k;\n pairs.push([vList[vIndex], dList[dList.length - k], vIndex]);\n }\n return { pairs, exact: false };\n}\n\n/**\n * Pair an element's virtual element children with its DOM element children,\n * ignoring text entirely \u2014 what handler binding needs.\n * @param {string} tagName\n * @param {Object} props\n * @param {Element} domElement\n * @returns {Array<[Object, Element]>} [child vNode, DOM element] pairs\n */\nexport function pairElementChildren(tagName, props, domElement) {\n const vElements = getRenderedChildren(tagName, props).filter((item) => item.type !== 'text');\n const dElements = Array.from(domElement?.childNodes ?? []).filter((node) => node.nodeType === 1);\n return alignChildren(vElements, dElements).pairs\n .filter(([item]) => item.type === 'element')\n .map(([item, node]) => [item.vNode, node]);\n}\n", "/**\n * Mismatch detection for Coherent.js hydration\n *\n * Compares server-rendered DOM against client virtual DOM to detect\n * hydration mismatches in development mode.\n */\n\nimport {\n isElementVNode,\n readElement,\n getRenderedChildren,\n getSignificantDOMChildren,\n alignChildren,\n resolveAttributeValue,\n renderedAttributes,\n} from './vnode.js';\n\n/**\n * Format path segments into readable string\n * @param {Array} segments - Path segments\n * @returns {string} - Formatted path\n */\nexport function formatPath(segments) {\n if (!segments || segments.length === 0) return 'root';\n return segments.join('.');\n}\n\n/** Attributes compared between the virtual node and the DOM. */\nconst ATTRIBUTE_CHECKS = [\n { virtual: 'className', dom: 'class' },\n { virtual: 'id', dom: 'id' },\n { virtual: 'type', dom: 'type' },\n { virtual: 'value', dom: 'value' },\n { virtual: 'checked', dom: 'checked' },\n { virtual: 'disabled', dom: 'disabled' },\n { virtual: 'href', dom: 'href' },\n { virtual: 'src', dom: 'src' }\n];\n\nfunction textOf(node) {\n return (node?.textContent ?? '').trim();\n}\n\n/**\n * Compare a list of rendered children (see getRenderedChildren) with the\n * significant DOM children of `parent`.\n * @private\n */\nfunction compareChildren(parent, vList, path, mismatches, childSegment) {\n const dList = getSignificantDOMChildren(parent);\n const { pairs, exact } = alignChildren(vList, dList);\n\n if (exact && vList.length !== dList.length) {\n mismatches.push({\n path: formatPath([...path, 'children']),\n type: 'children_count',\n expected: vList.length,\n actual: dList.length,\n domPath: getDOMPath(parent)\n });\n }\n\n for (const [item, node, index] of pairs) {\n const childPath = [...path, childSegment(index)];\n\n if (item.type === 'element') {\n mismatches.push(...detectMismatch(node, item.vNode, childPath));\n } else if (item.type === 'text') {\n const expected = item.text.trim();\n if (node.nodeType !== 3) {\n mismatches.push({\n path: formatPath(childPath),\n type: 'text',\n expected,\n actual: describeNode(node),\n domPath: getDOMPath(parent)\n });\n } else if (textOf(node) !== expected) {\n mismatches.push({\n path: formatPath(childPath),\n type: 'text',\n expected,\n actual: textOf(node),\n domPath: getDOMPath(parent)\n });\n }\n }\n }\n\n if (!exact) return;\n\n for (let i = dList.length; i < vList.length; i++) {\n mismatches.push({\n path: formatPath([...path, childSegment(i)]),\n type: 'missing_dom_child',\n expected: describeRendered(vList[i]),\n actual: null,\n domPath: getDOMPath(parent)\n });\n }\n for (let i = vList.length; i < dList.length; i++) {\n mismatches.push({\n path: formatPath([...path, childSegment(i)]),\n type: 'extra_dom_child',\n expected: null,\n actual: describeNode(dList[i]),\n domPath: getDOMPath(parent)\n });\n }\n}\n\n/**\n * Detect mismatches between DOM and virtual DOM\n *\n * Children are compared as the server rendered them: null, undefined and\n * booleans produce nothing, nested arrays are flattened, adjacent strings form\n * one text node and whitespace-only text is ignored on both sides.\n *\n * @param {Element} domElement - Real DOM element\n * @param {Object|string|number|Array} virtualNode - Virtual DOM node; an array\n * is compared against the children of `domElement`\n * @param {Array} path - Current path for error reporting\n * @returns {Array} - Array of mismatch objects\n */\nexport function detectMismatch(domElement, virtualNode, path = []) {\n const mismatches = [];\n\n if (virtualNode === null || virtualNode === undefined || typeof virtualNode === 'boolean') {\n return mismatches;\n }\n\n // Handle text nodes (string or number in virtual DOM)\n if (typeof virtualNode === 'string' || typeof virtualNode === 'number') {\n const expectedText = String(virtualNode).trim();\n const actualText = textOf(domElement);\n\n if (actualText !== expectedText) {\n mismatches.push({\n path: formatPath(path),\n type: 'text',\n expected: expectedText,\n actual: actualText,\n domPath: getDOMPath(domElement)\n });\n }\n return mismatches;\n }\n\n // A fragment (array or function component): compare against the children\n if (Array.isArray(virtualNode) || typeof virtualNode === 'function') {\n const vList = getRenderedChildren('fragment', { children: virtualNode });\n compareChildren(domElement, vList, path, mismatches, (i) => `[${i}]`);\n return mismatches;\n }\n\n if (!isElementVNode(virtualNode)) {\n return mismatches;\n }\n\n const { tagName, props } = readElement(virtualNode);\n\n // Check tag name\n const domTagName = domElement.tagName?.toLowerCase();\n if (domTagName !== tagName.toLowerCase()) {\n mismatches.push({\n path: formatPath(path),\n type: 'tagName',\n expected: tagName,\n actual: domTagName,\n domPath: getDOMPath(domElement)\n });\n // Can't continue comparing if tag is different\n return mismatches;\n }\n\n // Check critical attributes, evaluated the way core renders them\n const attributes = renderedAttributes(props);\n for (const { virtual, dom } of ATTRIBUTE_CHECKS) {\n const isClass = dom === 'class';\n if (props[virtual] === undefined && !(isClass && props.class !== undefined)) continue;\n\n // class comes from className, class or both, arrays and objects joined\n const expectedValue = isClass\n ? attributes.get('class') ?? null\n : resolveAttributeValue(props[virtual]);\n const actualValue = domElement.getAttribute(dom);\n\n // true renders a bare attribute; false and null render none\n if (typeof expectedValue === 'boolean' || expectedValue === null || expectedValue === undefined) {\n const expectedPresent = expectedValue === true;\n const actualPresent = actualValue !== null && actualValue !== undefined;\n if (expectedPresent !== actualPresent) {\n mismatches.push({\n path: formatPath([...path, `@${dom}`]),\n type: 'attribute',\n expected: expectedPresent,\n actual: actualPresent,\n domPath: getDOMPath(domElement)\n });\n }\n continue;\n }\n\n const expectedStr = String(expectedValue);\n if (expectedStr !== actualValue) {\n mismatches.push({\n path: formatPath([...path, `@${dom}`]),\n type: 'attribute',\n expected: expectedStr,\n actual: actualValue,\n domPath: getDOMPath(domElement)\n });\n }\n }\n\n // Recursively check children\n compareChildren(\n domElement,\n getRenderedChildren(tagName, props),\n path,\n mismatches,\n (i) => `children[${i}]`\n );\n\n return mismatches;\n}\n\n/**\n * Report mismatches to console with detailed information\n *\n * @param {Array} mismatches - Array of mismatch objects\n * @param {Object} options - Reporting options\n */\nexport function reportMismatches(mismatches, options = {}) {\n if (!mismatches || mismatches.length === 0) return;\n\n const { componentName = 'Unknown', strict = false } = options;\n\n const header = `[Coherent.js] Hydration mismatch detected in \"${componentName}\"!\\n` +\n `Found ${mismatches.length} difference(s) between server and client:\\n`;\n\n const details = mismatches.map((m, i) => {\n return `\\n${i + 1}. ${m.type} at ${m.path}\\n` +\n ` DOM path: ${m.domPath}\\n` +\n ` Expected: ${JSON.stringify(m.expected)}\\n` +\n ` Actual: ${JSON.stringify(m.actual)}`;\n }).join('');\n\n const advice = '\\n\\nThis usually happens when:\\n' +\n ' - Server renders with different data than client\\n' +\n ' - Using Date.now(), Math.random(), or browser-only APIs during render\\n' +\n ' - Component is not pure (has side effects during render)\\n';\n\n console.warn(header + details + advice);\n\n if (strict) {\n throw new Error(`Hydration failed: ${mismatches.length} mismatch(es) found. See console for details.`);\n }\n}\n\n\n/**\n * Get a readable DOM path for debugging\n * @private\n */\nfunction getDOMPath(element) {\n if (!element || !element.tagName) return '(unknown)';\n\n const parts = [];\n let current = element;\n\n while (current && current.tagName) {\n let selector = current.tagName.toLowerCase();\n\n if (current.id) {\n selector += `#${current.id}`;\n } else if (current.className && typeof current.className === 'string') {\n const classes = current.className.trim().split(/\\s+/).slice(0, 2);\n if (classes.length > 0 && classes[0]) {\n selector += `.${classes.join('.')}`;\n }\n }\n\n parts.unshift(selector);\n current = current.parentElement;\n\n // Limit depth\n if (parts.length > 5) {\n parts.unshift('...');\n break;\n }\n }\n\n return parts.join(' > ');\n}\n\n/**\n * Describe a rendered child (see getRenderedChildren) for error messages\n * @private\n */\nfunction describeRendered(item) {\n if (item.type === 'text') {\n return `text: \"${item.text.trim().substring(0, 50)}\"`;\n }\n if (item.type === 'element') {\n return `<${Object.keys(item.vNode)[0]}>`;\n }\n return 'raw content';\n}\n\n/**\n * Describe a DOM node for error messages\n * @private\n */\nfunction describeNode(node) {\n if (!node) return '(null)';\n if (node.nodeType === 3) { // Text node\n return `text: \"${(node.textContent || '').substring(0, 50)}\"`;\n }\n if (node.nodeType === 1) { // Element\n return `<${node.tagName.toLowerCase()}>`;\n }\n return `node(type=${node.nodeType})`;\n}\n", "/**\n * DOM patching for hydrated components.\n *\n * Diffs the previous virtual tree against the next one and applies the\n * difference to the DOM the previous tree produced: attributes and live form\n * properties, text, raw HTML, and children \u2014 added, removed, replaced, and\n * matched by `key` when every sibling has one.\n *\n * Attributes are the ones core's renderer writes (see renderedAttributes()\n * in vnode.js): functions are called, class arrays and objects are joined,\n * style objects become `prop: value` declarations, `true` is a bare attribute\n * and `false`/`null`/`undefined` remove it (aria-* and enumerated attributes\n * get \"true\"/\"false\"). `key`, `children`, `text`, `html` and `on*` handlers\n * are never attributes.\n *\n * @module @coherent.js/client/hydration/patch\n */\n\nimport {\n isElementVNode,\n readElement,\n getRenderedChildren,\n getSignificantDOMChildren,\n resolveAttributeValue,\n renderedAttributes,\n} from './vnode.js';\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\n\n/** Form state that lives in properties once the user has touched a field. */\nconst LIVE_PROPERTIES = new Set(['value', 'checked', 'selected']);\n\n/**\n * Bring an element's live form properties in line with its props. Setting the\n * attribute alone does not change a field the user has edited.\n */\nfunction applyLiveProperties(element, props) {\n for (const name of LIVE_PROPERTIES) {\n if (!(name in props) || !(name in element)) continue;\n\n const value = resolveAttributeValue(props[name]);\n if (name === 'value') {\n const next = value === null || value === undefined ? '' : String(value);\n if (element.value !== next) element.value = next;\n } else {\n const next = Boolean(value);\n if (element[name] !== next) element[name] = next;\n }\n }\n}\n\nfunction setAttributes(element, previous, next) {\n for (const name of previous.keys()) {\n if (!next.has(name)) element.removeAttribute(name);\n }\n for (const [name, value] of next) {\n if (element.getAttribute(name) !== value) element.setAttribute(name, value);\n }\n}\n\nfunction setRawHTML(element, html) {\n if (element.innerHTML !== html) element.innerHTML = html;\n}\n\n/**\n * Create DOM nodes for raw HTML.\n * @returns {Node[]}\n */\nfunction nodesFromHTML(html, doc) {\n const holder = doc.createElement('div');\n holder.innerHTML = html;\n return Array.from(holder.childNodes);\n}\n\n/**\n * Create DOM nodes for one rendered child (see getRenderedChildren).\n * @returns {Node[]}\n */\nfunction createNodes(item, doc, namespace) {\n if (item.type === 'text') return [doc.createTextNode(item.text)];\n if (item.type === 'element') return [createElement(item.vNode, doc, namespace)];\n // A component taking arguments cannot be run here; it renders nothing.\n return item.html === undefined ? [] : nodesFromHTML(item.html, doc);\n}\n\n/**\n * Create a DOM element (and its subtree) from an element virtual node.\n * @param {Object} vNode\n * @param {Document} [doc=document]\n * @param {string|null} [namespace]\n * @returns {Element}\n */\nexport function createElement(vNode, doc = document, namespace = null) {\n const { tagName, props } = readElement(vNode);\n const ns = tagName.toLowerCase() === 'svg' ? SVG_NS : namespace;\n const element = ns && typeof doc.createElementNS === 'function'\n ? doc.createElementNS(ns, tagName)\n : doc.createElement(tagName);\n\n setAttributes(element, new Map(), renderedAttributes(props));\n applyLiveProperties(element, props);\n\n const childNs = tagName.toLowerCase() === 'foreignobject' ? null : ns;\n for (const item of getRenderedChildren(tagName, props)) {\n for (const node of createNodes(item, doc, childNs)) element.appendChild(node);\n }\n return element;\n}\n\nfunction namespaceOf(element) {\n return element.namespaceURI === SVG_NS && element.localName !== 'foreignObject' ? SVG_NS : null;\n}\n\nfunction keyOf(item) {\n if (item.type !== 'element') return undefined;\n const { props } = readElement(item.vNode);\n return props.key;\n}\n\nfunction allKeyed(list) {\n if (list.length === 0) return false;\n const keys = new Set();\n for (const item of list) {\n const key = keyOf(item);\n if (key === undefined || key === null || keys.has(key)) return false;\n keys.add(key);\n }\n return true;\n}\n\nfunction sameTag(a, b) {\n return Object.keys(a)[0].toLowerCase() === Object.keys(b)[0].toLowerCase();\n}\n\nfunction isInsignificant(node) {\n return node.nodeType === 8 || (node.nodeType === 3 && node.textContent.trim() === '');\n}\n\n/** The first sibling from `node` on that is an element or non-blank text. */\nfunction significantFrom(node) {\n let current = node;\n while (current && isInsignificant(current)) current = current.nextSibling;\n return current;\n}\n\n/**\n * Put `nodes` in order as the element's significant children, moving only\n * the nodes that are out of place (a moved field loses focus).\n */\nfunction placeInOrder(parent, nodes) {\n let previous = null;\n for (const node of nodes) {\n const expected = significantFrom(previous ? previous.nextSibling : parent.firstChild);\n if (node !== expected) {\n parent.insertBefore(node, previous ? previous.nextSibling : parent.firstChild);\n }\n previous = node;\n }\n}\n\n/**\n * Patch one child: reuse the DOM node when the kind (and tag) matches,\n * otherwise create a replacement. Returns the node now representing `next`.\n */\nfunction patchChild(parent, node, previous, next) {\n const doc = parent.ownerDocument ?? globalThis.document;\n\n if (previous.type === 'text' && next.type === 'text' && node.nodeType === 3) {\n if (node.textContent !== next.text) node.textContent = next.text;\n return [node];\n }\n\n if (\n previous.type === 'element' &&\n next.type === 'element' &&\n node.nodeType === 1 &&\n sameTag(previous.vNode, next.vNode)\n ) {\n patchElement(node, previous.vNode, next.vNode);\n return [node];\n }\n\n return createNodes(next, doc, namespaceOf(parent));\n}\n\nfunction patchChildren(element, previousProps, nextProps, tagName) {\n const doc = element.ownerDocument ?? globalThis.document;\n const previousList = getRenderedChildren(tagName, previousProps);\n const nextList = getRenderedChildren(tagName, nextProps);\n const domList = getSignificantDOMChildren(element);\n const namespace = namespaceOf(element);\n\n // Raw HTML: set it when it changed, leave it alone otherwise.\n const previousHTML = previousList.length === 1 && previousList[0].type === 'opaque' ? previousList[0].html : undefined;\n const nextHTML = nextList.length === 1 && nextList[0].type === 'opaque' ? nextList[0].html : undefined;\n if (nextProps.html !== undefined && nextHTML !== undefined) {\n if (previousProps.html === undefined || previousHTML !== nextHTML) setRawHTML(element, nextHTML);\n return;\n }\n\n // Positions are only reliable when the DOM holds what the previous tree\n // rendered, one node per child; otherwise rebuild the children.\n const reliable =\n previousList.length === domList.length &&\n !previousList.some((item) => item.type === 'opaque') &&\n !nextList.some((item) => item.type === 'opaque');\n\n if (!reliable) {\n // Text-only content needs no node creation\n if (nextList.length === 0 || (nextList.length === 1 && nextList[0].type === 'text')) {\n const text = nextList.length === 0 ? '' : nextList[0].text;\n if (element.textContent !== text || domList.length !== nextList.length) {\n element.textContent = text;\n }\n return;\n }\n for (const node of Array.from(element.childNodes)) element.removeChild(node);\n for (const item of nextList) {\n for (const node of createNodes(item, doc, namespace)) element.appendChild(node);\n }\n return;\n }\n\n const nextNodes = [];\n\n if (allKeyed(previousList) && allKeyed(nextList)) {\n const byKey = new Map(previousList.map((item, i) => [keyOf(item), { item, node: domList[i] }]));\n for (const item of nextList) {\n const match = byKey.get(keyOf(item));\n if (match && sameTag(match.item.vNode, item.vNode)) {\n byKey.delete(keyOf(item));\n patchElement(match.node, match.item.vNode, item.vNode);\n nextNodes.push(match.node);\n } else {\n nextNodes.push(...createNodes(item, doc, namespace));\n }\n }\n for (const { node } of byKey.values()) element.removeChild(node);\n } else {\n const common = Math.min(previousList.length, nextList.length);\n for (let i = 0; i < common; i++) {\n const nodes = patchChild(element, domList[i], previousList[i], nextList[i]);\n if (nodes[0] !== domList[i]) element.removeChild(domList[i]);\n nextNodes.push(...nodes);\n }\n for (let i = common; i < domList.length; i++) element.removeChild(domList[i]);\n for (let i = common; i < nextList.length; i++) {\n nextNodes.push(...createNodes(nextList[i], doc, namespace));\n }\n }\n\n placeInOrder(element, nextNodes);\n}\n\n/**\n * Patch `element`, which the server or a previous patch rendered from\n * `previousVNode`, to match `nextVNode`. Tags must match; see patchRoot().\n * @param {Element} element\n * @param {Object} previousVNode\n * @param {Object} nextVNode\n */\nexport function patchElement(element, previousVNode, nextVNode) {\n const previous = readElement(previousVNode);\n const next = readElement(nextVNode);\n\n setAttributes(element, renderedAttributes(previous.props), renderedAttributes(next.props));\n applyLiveProperties(element, next.props);\n patchChildren(element, previous.props, next.props, next.tagName);\n}\n\n/**\n * Patch a component's root element, replacing it when the tag changed.\n * @param {Element} element - Current root element\n * @param {*} previousVNode - Tree `element` was rendered from\n * @param {*} nextVNode - Tree to render\n * @returns {Element} The root element afterwards (a new one if replaced)\n */\nexport function patchRoot(element, previousVNode, nextVNode) {\n if (!isElementVNode(nextVNode)) {\n return element;\n }\n\n if (\n isElementVNode(previousVNode) &&\n element.tagName?.toLowerCase() === Object.keys(nextVNode)[0].toLowerCase()\n ) {\n patchElement(element, previousVNode, nextVNode);\n return element;\n }\n\n const replacement = createElement(nextVNode, element.ownerDocument ?? document, namespaceOf(element.parentNode ?? element));\n element.parentNode?.replaceChild(replacement, element);\n return replacement;\n}\n", "/**\n * Clean hydrate() API for Coherent.js\n *\n * Integrates event delegation, state serialization, and mismatch detection\n * into a simple function: hydrate(component, container, options)\n *\n * @module @coherent.js/client/hydrate\n */\n\nimport { eventDelegation, handlerRegistry } from './events/index.js';\nimport { extractState, detectMismatch, reportMismatches } from './hydration/index.js';\nimport { isElementVNode, readElement, pairElementChildren } from './hydration/vnode.js';\nimport { patchRoot } from './hydration/patch.js';\n\n/**\n * Live hydrations by container, so hydrating a container again replaces the\n * previous hydration instead of stacking a second set of handlers on it.\n * @type {WeakMap<Element, {unmount: Function}>}\n */\nconst hydratedContainers = new WeakMap();\n\n/**\n * Hydrate a server-rendered component\n *\n * Hydrating a container that is already hydrated unmounts the previous\n * hydration first.\n *\n * @param {Function} component - Component function that returns virtual DOM\n * @param {HTMLElement} container - DOM element containing server-rendered HTML\n * @param {Object} [options] - Hydration options\n * @param {Object} [options.initialState] - Initial state to override extracted state\n * @param {boolean} [options.detectMismatch] - Compare the server DOM with the\n * component's output. Defaults to on when `strict` or `onMismatch` is given\n * or `process.env.NODE_ENV` is `'development'`, off otherwise\n * @param {boolean} [options.strict=false] - Throw on mismatch instead of warning\n * @param {Function} [options.onMismatch] - Custom mismatch handler\n * @param {Object} [options.props] - Additional props to pass to component\n * @returns {Object} Control object with unmount(), rerender(), getState(), setState()\n */\nexport function hydrate(component, container, options = {}) {\n // Validate inputs\n if (typeof component !== 'function') {\n throw new Error(\n `hydrate() requires a component function, received: ${typeof component}`\n );\n }\n\n if (!container || typeof container.getAttribute !== 'function') {\n throw new Error(\n `hydrate() requires a valid DOM element as container, received: ${\n container === null ? 'null' : typeof container\n }`\n );\n }\n\n // One hydration per container: drop the previous one's handlers\n hydratedContainers.get(container)?.unmount();\n\n // Initialize event delegation (idempotent)\n eventDelegation.initialize();\n\n // Extract options with defaults\n const {\n initialState: providedState,\n strict = false,\n onMismatch,\n props: additionalProps = {},\n } = options;\n\n // Mismatch detection walks the whole DOM: only when asked for, implied by\n // `strict` or `onMismatch`, or in development\n const shouldDetectMismatch = options.detectMismatch ??\n (strict || typeof onMismatch === 'function' || isDevelopment());\n\n // Extract state from DOM data-state attribute, or use provided initial state\n let state = providedState ?? extractState(container) ?? {};\n let mounted = true;\n let root = container;\n\n // Handler ids and the attributes pointing at them, from the latest render\n let registeredHandlerIds = new Set();\n let boundAttributes = [];\n\n const currentProps = () => ({ ...additionalProps, ...state });\n\n // Component reference handed to event handlers (event.state, event.setState, ...)\n const componentRef = {\n component,\n get state() {\n return state;\n },\n get props() {\n return currentProps();\n },\n getState: () => state,\n setState: (newState) => {\n if (!mounted) {\n return;\n }\n if (typeof newState === 'function') {\n state = { ...state, ...newState(state) };\n } else {\n state = { ...state, ...newState };\n }\n // Re-render on state change\n doRerender();\n },\n };\n\n // Generate virtual DOM from component\n let virtualDOM = renderComponent(component, currentProps());\n\n // Detect mismatches if enabled\n if (shouldDetectMismatch) {\n const mismatches = detectMismatch(container, virtualDOM);\n\n if (mismatches.length > 0) {\n if (onMismatch) {\n onMismatch(mismatches);\n } else {\n reportMismatches(mismatches, {\n componentName: component.name || 'Anonymous',\n strict,\n });\n }\n }\n }\n\n // Walk virtual DOM and register event handlers\n registerEventHandlers(root, virtualDOM, componentRef, registeredHandlerIds, boundAttributes);\n\n /**\n * Re-render the component with current state\n */\n function doRerender() {\n if (!mounted) {\n return;\n }\n\n const previousVirtualDOM = virtualDOM;\n virtualDOM = renderComponent(component, currentProps());\n\n // Update the DOM to match the new virtual DOM\n const previousRoot = root;\n root = patchRoot(root, previousVirtualDOM, virtualDOM);\n if (root !== previousRoot) {\n hydratedContainers.delete(previousRoot);\n hydratedContainers.set(root, controller);\n root.setAttribute('data-coherent-hydrated', 'true');\n }\n\n // Swap handlers: register the new render's, then drop the previous ones\n const previousIds = registeredHandlerIds;\n const previousAttributes = boundAttributes;\n registeredHandlerIds = new Set();\n boundAttributes = [];\n registerEventHandlers(root, virtualDOM, componentRef, registeredHandlerIds, boundAttributes);\n releaseHandlers(previousIds, previousAttributes);\n }\n\n /**\n * Unmount the component and clean up. Terminal: later setState() and\n * rerender() calls do nothing.\n */\n function unmount() {\n if (!mounted) {\n return;\n }\n mounted = false;\n\n releaseHandlers(registeredHandlerIds, boundAttributes);\n registeredHandlerIds = new Set();\n boundAttributes = [];\n\n if (hydratedContainers.get(root) === controller) {\n hydratedContainers.delete(root);\n }\n\n // Clear container's hydration marker\n root.removeAttribute('data-coherent-hydrated');\n }\n\n /**\n * Force re-render with optional new props\n * @param {Object} [newProps] - New props to merge\n */\n function rerender(newProps) {\n if (!mounted) {\n return;\n }\n if (newProps) {\n Object.assign(additionalProps, newProps);\n }\n doRerender();\n }\n\n /**\n * Get current state\n * @returns {Object} Current state\n */\n function getState() {\n return { ...state };\n }\n\n /**\n * Set state and trigger re-render\n * @param {Object|Function} newState - New state or updater function\n */\n function setState(newState) {\n componentRef.setState(newState);\n }\n\n // Return control object\n const controller = {\n unmount,\n rerender,\n getState,\n setState,\n };\n\n // Mark container as hydrated\n container.setAttribute('data-coherent-hydrated', 'true');\n hydratedContainers.set(container, controller);\n\n return controller;\n}\n\n/**\n * Whether the app runs in development. `process.env.NODE_ENV` is read at\n * runtime \u2014 this package's build leaves it for the app's bundler to replace \u2014\n * and counts as production when there is no `process` at all.\n * @private\n */\nfunction isDevelopment() {\n try {\n // eslint-disable-next-line no-restricted-globals -- replaced by the app's bundler; guarded for browsers without one\n return process.env.NODE_ENV === 'development';\n } catch {\n return false;\n }\n}\n\n/**\n * Call a component and resolve returned function components, as core does\n * @private\n */\nfunction renderComponent(component, props) {\n let vNode = component(props);\n for (let guard = 0; typeof vNode === 'function' && vNode.length === 0 && guard < 100; guard++) {\n vNode = vNode();\n }\n return vNode;\n}\n\n/**\n * Unregister handler ids and remove the data-coherent-* attributes that still\n * point at them\n * @private\n */\nfunction releaseHandlers(handlerIds, attributes) {\n for (const handlerId of handlerIds) {\n handlerRegistry.unregister(handlerId);\n }\n for (const { element, name, handlerId } of attributes) {\n if (element.getAttribute(name) === handlerId) {\n element.removeAttribute(name);\n }\n }\n}\n\n/** Prop names whose lower-cased suffix is not the DOM event type. */\nconst EVENT_TYPE_ALIASES = {\n doubleclick: 'dblclick',\n};\n\n/**\n * DOM event type for an `on*` prop: onClick -> click, onDoubleClick -> dblclick\n * @private\n */\nfunction toEventType(propName) {\n const type = propName.slice(2).toLowerCase();\n return EVENT_TYPE_ALIASES[type] ?? type;\n}\n\n/**\n * Walk virtual DOM tree and register event handlers\n * @private\n */\nfunction registerEventHandlers(domElement, vNode, componentRef, handlerIds, boundAttributes) {\n if (!domElement || !isElementVNode(vNode)) {\n return;\n }\n\n const { tagName, props } = readElement(vNode);\n\n // Look for event handler props (on* functions)\n const eventProps = Object.keys(props).filter(\n (key) => key.startsWith('on') && typeof props[key] === 'function'\n );\n\n for (const eventProp of eventProps) {\n const eventType = toEventType(eventProp); // onClick -> click\n const handler = props[eventProp];\n\n // Delegate this event type even if it is not one of the defaults\n eventDelegation.listen(eventType);\n\n // Generate unique handler ID\n const handlerId = `${tagName}-${eventType}-${Math.random().toString(36).slice(2, 9)}`;\n\n // Register handler\n handlerRegistry.register(handlerId, handler, componentRef);\n handlerIds.add(handlerId);\n\n // Set data attribute on DOM element for delegation\n const attrName = `data-coherent-${eventType}`;\n if (domElement.setAttribute) {\n domElement.setAttribute(attrName, handlerId);\n boundAttributes.push({ element: domElement, name: attrName, handlerId });\n }\n }\n\n // Pair element children the way the server rendered them: null, booleans,\n // nested arrays and text never shift which element a child binds to.\n for (const [childVNode, childElement] of pairElementChildren(tagName, props, domElement)) {\n registerEventHandlers(childElement, childVNode, componentRef, handlerIds, boundAttributes);\n }\n}\n\nexport default hydrate;\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,eAAe,OAAO;AACpC,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAGhD,QAAM,eAAe,CAAC;AACtB,MAAI,kBAAkB;AAEtB,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,eAAe,KAAK,GAAG;AACzB,mBAAa,GAAG,IAAI;AACpB,wBAAkB;AAAA,IACpB;AAAA,EAEF;AAEA,MAAI,CAAC,gBAAiB,QAAO;AAE7B,MAAI;AACF,UAAM,OAAO,KAAK,UAAU,YAAY;AAExC,WAAO,KAAK,mBAAmB,IAAI,CAAC;AAAA,EACtC,SAAS,GAAG;AACV,YAAQ,KAAK,4CAA4C,CAAC;AAC1D,WAAO;AAAA,EACT;AACF;AAQO,SAAS,iBAAiB,SAAS;AACxC,MAAI,CAAC,WAAW,OAAO,YAAY,SAAU,QAAO;AAEpD,MAAI;AACF,UAAM,OAAO,mBAAmB,KAAK,OAAO,CAAC;AAC7C,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,SAA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