@estjs/template 0.0.15-beta.13 → 0.0.15-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/scope.ts","../src/constants.ts","../src/key.ts","../src/utils/node.ts","../src/utils/dom.ts","../src/patch.ts","../src/binding.ts","../src/lifecycle.ts","../src/component.ts","../src/renderer.ts","../src/provide.ts","../src/events.ts","../src/utils/props.ts","../src/hydration/shared.ts","../src/hydration/hydration.ts","../src/operations/class.ts","../src/operations/styles.ts","../src/operations/attr.ts","../src/operations/event.ts","../src/components/Fragment.ts","../src/components/Portal.ts","../src/components/Suspense.ts","../src/components/createResource.ts","../src/components/For.ts"],"names":["_a","error","isFalsy","isString","warn","isNumber","isSymbol","isHTMLElement","isPrimitive","isNull","isObject","isArray","beforeNode","isTextNode","j","isHtmlInputElement","isHtmlSelectElement","isHtmlTextAreaElement","effect","isFunction","coerceArray","template","shallowReactive","isSignal","isComputed","hasChanged","isPromise","startsWith","document","isBrowser","normalizeClassName","camelCase","capitalize","isSpecialBooleanAttr","isBooleanAttr","includeBooleanAttr","isUndefined","children","signal","memoEffect","untrack","batchFragment"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAI,WAAA,GAA4B,IAAA;AAGhC,IAAI,OAAA,GAAU,CAAA;AAMP,SAAS,cAAA,GAA+B;AAC7C,EAAA,OAAO,WAAA;AACT;AAMO,SAAS,eAAe,KAAA,EAA2B;AACxD,EAAA,WAAA,GAAc,KAAA;AAChB;AASO,SAAS,WAAA,CAAY,SAAuB,WAAA,EAAoB;AACrE,EAAA,MAAM,KAAA,GAAe;AAAA,IACnB,IAAI,EAAE,OAAA;AAAA,IACN,MAAA;AAAA,IACA,QAAA,EAAU,IAAA;AAAA;AAAA,IACV,QAAA,EAAU,IAAA;AAAA;AAAA,IACV,OAAA,EAAS,IAAA;AAAA;AAAA,IACT,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AAA,CAAO,YAAA,CAAa,MAAM,MAAM,CAAA;AAAA,IAClC;AAEA,IAAA,OAAA,GAAU,UAAA;AAAA,EACZ;AAEA,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,MAAA,WAAA,CAAY,KAAK,CAAA;AAAA,IACnB;AACA,IAAA,IAAI,YAAA,IAAgB,aAAa,UAAA,EAAY;AAC3C,MAAA,YAAA,CAAa,UAAA,CAAW,YAAY,YAAY,CAAA;AAAA,IAClD;AACA,IAAA,IAAI,OAAO,UAAA,EAAY;AACrB,MAAA,MAAA,CAAO,UAAA,CAAW,YAAY,MAAM,CAAA;AAAA,IACtC;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,QAAA;AACT;AAEA,GAAA,CAAI,aAAa,CAAA,GAAI,IAAA","file":"template.dev.cjs.js","sourcesContent":["import { error } from '@estjs/shared';\nimport type { InjectionKey } from './provide';\n\n/**\n * Scope represents an execution context in the component tree.\n * It manages provides, cleanup functions, and lifecycle hooks.\n */\nexport interface Scope {\n /** Unique identifier for debugging */\n readonly id: number;\n\n /** Parent scope in the hierarchy */\n parent: Scope | null;\n\n /** Child scopes (lazy initialized) */\n children: Set<Scope> | null;\n\n /** Provided values (lazy initialized) */\n provides: Map<InjectionKey<unknown> | string | number | symbol, unknown> | null;\n\n /** Cleanup functions (lazy initialized) */\n cleanup: Set<() => void> | null;\n\n /** Mount lifecycle hooks (lazy initialized) */\n onMount: Set<() => void | Promise<void>> | null;\n\n /** Update lifecycle hooks (lazy initialized) */\n onUpdate: Set<() => void | Promise<void>> | null;\n\n /** Destroy lifecycle hooks (lazy initialized) */\n onDestroy: Set<() => void | Promise<void>> | null;\n\n /** Whether the scope has been mounted */\n isMounted: boolean;\n\n /** Whether the scope has been destroyed */\n isDestroyed: boolean;\n}\n\n/** Currently active scope */\nlet activeScope: Scope | null = null;\n\n/** Scope ID counter for unique identification */\nlet scopeId = 0;\n\n/**\n * Get the currently active scope.\n * @returns The active scope or null if none is active\n */\nexport function getActiveScope(): Scope | null {\n return activeScope;\n}\n\n/**\n * Set the active scope (internal use).\n * @param scope - The scope to set as active\n */\nexport function setActiveScope(scope: Scope | null): void {\n activeScope = scope;\n}\n\n/**\n * Create a new scope with optional parent.\n * If no parent is provided, uses the current active scope as parent.\n *\n * @param parent - Optional parent scope (defaults to active scope)\n * @returns A new scope instance\n */\nexport function createScope(parent: Scope | null = activeScope): Scope {\n const scope: Scope = {\n id: ++scopeId,\n parent,\n children: null, // Lazy initialized\n provides: null, // Lazy initialized\n cleanup: null, // Lazy initialized\n onMount: null, // Lazy initialized\n onUpdate: null, // Lazy initialized\n onDestroy: null, // Lazy initialized\n isMounted: false,\n isDestroyed: false,\n };\n\n // Establish parent-child relationship\n if (parent) {\n if (!parent.children) {\n parent.children = new Set();\n }\n parent.children.add(scope);\n }\n\n return scope;\n}\n\n/**\n * Run a function within a scope, ensuring proper cleanup.\n * The previous active scope is restored even if the function throws.\n *\n * @param scope - The scope to run within\n * @param fn - The function to execute\n * @returns The return value of the function\n */\nexport function runWithScope<T>(scope: Scope, fn: () => T): T {\n const prevScope = activeScope;\n activeScope = scope;\n\n try {\n return fn();\n } finally {\n // Restore previous scope directly\n activeScope = prevScope;\n }\n}\n\n/**\n * Dispose a scope and all its children.\n * Children are disposed first (depth-first), then the scope itself.\n *\n * @param scope - The scope to dispose\n */\nexport function disposeScope(scope: Scope): void {\n // Idempotent: already destroyed\n if (!scope || scope.isDestroyed) {\n return;\n }\n\n // Dispose children first (depth-first)\n // Iterate directly without copying to avoid allocation\n if (scope.children) {\n // Use while loop since children will remove themselves during dispose\n while (scope.children.size > 0) {\n const child = scope.children.values().next().value;\n if (child) {\n disposeScope(child);\n }\n }\n }\n\n // Execute destroy lifecycle hooks\n if (scope.onDestroy) {\n for (const hook of scope.onDestroy) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in destroy hook:`, error_);\n }\n }\n }\n scope.onDestroy.clear();\n }\n\n // Execute cleanup functions\n if (scope.cleanup) {\n for (const fn of scope.cleanup) {\n try {\n fn();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in cleanup:`, error_);\n }\n }\n }\n scope.cleanup.clear();\n }\n\n // Remove from parent's children\n if (scope.parent?.children) {\n scope.parent.children.delete(scope);\n }\n\n // Clear all internal collections\n scope.children?.clear();\n scope.provides?.clear();\n scope.onMount?.clear();\n scope.onUpdate?.clear();\n\n // reset active with parent scope\n setActiveScope(scope.parent);\n\n // Break parent reference to prevent memory leaks\n scope.parent = null;\n\n // Mark as destroyed\n scope.isDestroyed = true;\n}\n\n/**\n * Register a cleanup function in the current scope.\n * The function will be called when the scope is disposed.\n *\n * @param fn - The cleanup function\n */\nexport function onCleanup(fn: () => void): void {\n const scope = activeScope;\n\n if (!scope) {\n if (__DEV__) {\n error('onCleanup() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize cleanup set\n if (!scope.cleanup) {\n scope.cleanup = new Set();\n }\n\n scope.cleanup.add(fn);\n}\n","/**\n * event prefix, used to distinguish event handler properties\n */\nexport const EVENT_PREFIX = 'on';\n\n/**\n * update prefix, used to identify update callback properties\n */\nexport const UPDATE_PREFIX = 'update';\n\n/**\n * children property name\n */\nexport const CHILDREN_PROP = 'children';\n/**\n * Key name for the Spread attribute\n */\nexport const SPREAD_NAME = '_$spread$';\n\n/**\n * used to get the DOM element reference\n */\nexport const REF_KEY = 'ref';\n/**\n * Component key property name\n */\nexport const KEY_PROP = 'key' as const;\n\n/**\n * SVG namespace constant\n */\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\n/**\n * XML namespace for xlink attributes\n */\nexport const XLINK_NAMESPACE = 'http://www.w3.org/2000/xlink';\n\n/**\n * xmlns namespace for SVG elements\n */\nexport const XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/';\n\n/**\n * Defines various states of components for state management and debugging\n */\nexport enum COMPONENT_STATE {\n /** Initial state */\n INITIAL,\n /** Mounting */\n MOUNTING,\n /** MOUNTED */\n MOUNTED,\n /** Updating */\n UPDATING,\n /** Destroying */\n DESTROYING,\n /** destroy */\n DESTROYED,\n}\n\nexport const NORMAL_COMPONENT = Symbol(__DEV__ ? 'Normal Component' : '');\nexport const FRAGMENT_COMPONENT = Symbol(__DEV__ ? 'Fragment Component' : '');\nexport const PORTAL_COMPONENT = Symbol(__DEV__ ? 'Portal Component' : '');\nexport const SUSPENSE_COMPONENT = Symbol(__DEV__ ? 'Suspense Component' : '');\nexport const FOR_COMPONENT = Symbol(__DEV__ ? 'For Component' : '');\n","import { error, isFalsy, isHTMLElement, isNumber, isString, isSymbol, warn } from '@estjs/shared';\nimport { isComponent } from './component';\nimport type { AnyNode } from './types';\n\n/** Maximum allowed key length before truncation */\nconst MAX_KEY_LENGTH = 1000;\n\nexport type NodeKey = string | number | symbol;\n\n/** Cache for component type key prefixes */\nconst componentKeyPrefixCache = new WeakMap<Function, string>();\n\n/**\n * Generates a stable key prefix for a component type.\n *\n * @param type - The component function\n * @returns The generated key prefix\n */\nexport function getComponentKey(type: Function): string {\n let prefix = componentKeyPrefixCache.get(type);\n if (!prefix) {\n const name = type.name || 'anonymous';\n const hash = simpleHash(type.toString()).toString(36);\n prefix = `${name}_${hash}`;\n componentKeyPrefixCache.set(type, prefix);\n }\n return prefix;\n}\n\n/**\n * DJB2 hash variant - fast string hashing.\n * Limited to first 100 chars for performance.\n *\n * @param str - The input string\n * @returns The hash code (always positive)\n */\nfunction simpleHash(str: string): number {\n let hash = 0;\n const len = str.length < 100 ? str.length : 100;\n for (let i = 0; i < len; i++) {\n hash = Math.trunc((hash << 5) - hash + str.charCodeAt(i));\n }\n return hash < 0 ? -hash : hash;\n}\n\n/** Counter for generating unique IDs for local symbols */\nlet symbolIdCounter = 0;\n\n/**\n * Normalize any key value to a string.\n *\n * @param key - The key value to normalize\n * @returns Normalized string key or undefined for null/undefined\n */\nexport function normalizeKey(key: any): string | undefined {\n if (isFalsy(key)) {\n return undefined;\n }\n\n if (isString(key)) {\n if (key.length <= MAX_KEY_LENGTH) {\n return key;\n }\n if (__DEV__) {\n warn(\n `[Key System] Key length exceeds ${MAX_KEY_LENGTH} characters. ` +\n 'Consider using a shorter identifier.',\n );\n }\n return `${key.slice(0, MAX_KEY_LENGTH - 10)}_${simpleHash(key).toString(36)}`;\n }\n\n if (isNumber(key)) {\n if (__DEV__) {\n if (key !== key) {\n warn('[Key System] NaN cannot be used as a key');\n return undefined;\n }\n if (!Number.isFinite(key)) {\n warn('[Key System] Infinity cannot be used as a key');\n return undefined;\n }\n }\n return String(key);\n }\n\n // Symbol path\n if (isSymbol(key)) {\n const globalKey = Symbol.keyFor(key);\n if (globalKey) {\n return `_s.${globalKey}`;\n }\n const desc = key.description;\n return desc ? `_s.${desc}` : `${symbolIdCounter++}`;\n }\n\n return String(key);\n}\n\n/**\n * Check if two nodes have the same type for reconciliation.\n *\n * @param a - First node\n * @param b - Second node\n * @returns True if nodes are the same type\n */\nexport function isSameNodeType(a: AnyNode, b: AnyNode): boolean {\n const aIsComponent = isComponent(a);\n const bIsComponent = isComponent(b);\n\n // Both components - compare component function\n if (aIsComponent && bIsComponent) {\n return a.component === b.component;\n }\n\n // Both DOM nodes - compare nodeType and tagName\n const aNode = a as Node;\n const bNode = b as Node;\n\n return (\n aNode.nodeType === bNode.nodeType &&\n (aNode.nodeType !== Node.ELEMENT_NODE ||\n (aNode as Element).tagName === (bNode as Element).tagName)\n );\n}\n\n/** Symbol for storing keys on DOM nodes */\nconst NODE_KEY_SYMBOL = Symbol('essor.key');\n\n/**\n * Set a key on a DOM node using Symbol property.\n * Symbol properties are ~40% faster than WeakMap access.\n *\n * @param node - The node to set key on\n * @param key - The key value (will be normalized)\n */\nexport function setNodeKey(node: AnyNode, key: NodeKey | undefined): void {\n // Skip components - they manage their own keys\n if (isComponent(node)) {\n return;\n }\n\n // Validate node\n if (!node || (node as Node).nodeType === Node.DOCUMENT_NODE) {\n if (__DEV__) {\n warn('[Key System] Cannot set key on invalid node');\n }\n return;\n }\n\n const normalizedKey = normalizeKey(key);\n if (isFalsy(normalizedKey)) {\n delete node[NODE_KEY_SYMBOL];\n } else {\n node[NODE_KEY_SYMBOL] = normalizedKey;\n }\n}\n\n/**\n * Get the key from a node or component.\n *\n * @param node - The node to get key from\n * @returns The key string or undefined\n */\nexport function getNodeKey(node: AnyNode): string | undefined {\n if (!node) return undefined;\n return isComponent(node) ? node.key : node[NODE_KEY_SYMBOL];\n}\n\n/**\n * Get node's key or return an index-based fallback.\n * Fallback keys start with '.' to distinguish from user keys.\n *\n * @param node - The node to get key from\n * @param fallbackIndex - Index to use if no key exists\n * @returns The key or fallback string\n */\nexport function getKeyOrFallback(node: AnyNode, fallbackIndex: number): string {\n return getNodeKey(node) || `.${fallbackIndex}`;\n}\n\n/**\n * Validate that child keys are unique (Development only).\n * Logs errors for duplicate keys to help debugging.\n *\n * @param children - Array of child nodes\n * @param parent - Optional parent node for error context\n */\nexport function validateKeys(children: AnyNode[], parent?: Node): void {\n if (!__DEV__) return;\n\n const keySet = new Set<string>();\n const duplicates: string[] = [];\n const len = children.length;\n\n for (let i = 0; i < len; i++) {\n const key = getKeyOrFallback(children[i], i);\n\n // Skip auto-generated fallback keys (start with '.')\n if (key[0] === '.') continue;\n\n if (keySet.has(key)) {\n duplicates.push(key);\n } else {\n keySet.add(key);\n }\n }\n\n if (duplicates.length > 0) {\n const parentTag = isHTMLElement(parent) ? parent.tagName.toLowerCase() : 'unknown';\n error(\n `Duplicate keys detected in <${parentTag}>: [${duplicates.join(', ')}]\\n` +\n 'Keys must be unique among siblings.',\n );\n }\n}\n","/**\n * Node normalization and comparison utilities\n */\n\nimport {\n isArray,\n isFalsy,\n isHTMLElement,\n isNull,\n isObject,\n isPrimitive,\n isTextNode,\n} from '@estjs/shared';\nimport { isComponent } from '../component';\nimport { getNodeKey } from '../key';\nimport type { AnyNode } from '../types';\n\n/**\n * Normalize node for reconciliation\n * Converts primitives to text nodes\n *\n * @param node - Node to normalize\n * @returns Normalized DOM node\n */\nexport function normalizeNode(node: unknown): Node {\n // Already a Node\n if (isHTMLElement(node)) {\n return node;\n }\n\n // Handle primitives - convert to text nodes\n if (isPrimitive(node)) {\n const textContent = isFalsy(node) ? '' : String(node);\n return document.createTextNode(textContent);\n }\n\n return node as Node;\n}\n\n/**\n * Check if two nodes are the same (for reconciliation)\n * Combines key check and type check\n *\n * @param a - First node\n * @param b - Second node\n * @returns true if nodes are considered the same\n */\nexport function isSameNode(a: AnyNode, b: AnyNode): boolean {\n // Check key equality first (fast path)\n const keyA = getNodeKey(a);\n const keyB = getNodeKey(b);\n\n if (keyA !== keyB) {\n return false;\n }\n\n // Inline type check to avoid function call\n const aIsComponent = isComponent(a);\n const bIsComponent = isComponent(b);\n\n if (aIsComponent && bIsComponent) {\n return a.component === b.component;\n }\n\n if (aIsComponent !== bIsComponent) {\n return false;\n }\n\n if (isPrimitive(a) || isPrimitive(b)) {\n return a === b;\n }\n\n const aNode = a as Node;\n const bNode = b as Node;\n\n if (aNode.nodeType !== bNode.nodeType) {\n return false;\n }\n\n if (aNode.nodeType === Node.ELEMENT_NODE) {\n return (aNode as Element).tagName === (bNode as Element).tagName;\n }\n\n return true;\n}\n\n/**\n * Check if a value is a Text node\n * Re-exported from shared for convenience\n */\nexport function isHtmlTextElement(val: unknown): val is Text {\n return isTextNode(val);\n}\n\n/**\n * Shallow compare two objects or arrays\n * Performs strict equality check on top-level properties\n *\n * @param a - First value to compare\n * @param b - Second value to compare\n * @returns true if values are shallowly equal\n */\nexport function shallowCompare(a: unknown, b: unknown): boolean {\n // Fast path: strict equality\n if (a === b) return true;\n\n // Null/undefined check\n if (isNull(a) || isNull(b)) return false;\n\n // Type guard: both must be objects\n if (!isObject(a) || !isObject(b)) return false;\n\n // Array type consistency check\n if (isArray(a) !== isArray(b)) return false;\n\n // Type guard for record-like objects\n const aRecord = a as Record<string, unknown>;\n const bRecord = b as Record<string, unknown>;\n\n // Fast path: check key count first\n const aKeys = Object.keys(aRecord);\n const bKeys = Object.keys(bRecord);\n if (aKeys.length !== bKeys.length) return false;\n\n // Single pass: check all keys and values\n for (const key of aKeys) {\n if (!(key in bRecord) || aRecord[key] !== bRecord[key]) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * DOM manipulation utilities\n */\n\nimport { isPrimitive } from '@estjs/shared';\nimport { isComponent } from '../component';\nimport type { AnyNode } from '../types';\n\n/**\n * Remove node from its parent\n *\n * @param node - Node to remove\n */\nexport function removeNode(node: AnyNode): void {\n if (!node) return;\n\n if (isComponent(node)) {\n node.destroy();\n return;\n }\n\n const element = node as Element;\n if (element.parentElement) {\n element.remove();\n }\n}\n\n/**\n * Insert child node into parent\n * Handles both component nodes and DOM nodes\n *\n * @param parent - Parent node\n * @param child - Child node to insert\n * @param before - Reference node for insertion position\n */\nexport function insertNode(parent: Node, child: AnyNode, before?: AnyNode): void {\n if (!parent || !child) return;\n\n if (isComponent(child)) {\n const beforeNode = isComponent(before) ? before.firstChild : (before as Node);\n child.mount(parent, beforeNode);\n return;\n }\n\n const beforeNode = isComponent(before) ? before.firstChild : (before as Node);\n\n if (beforeNode) {\n parent.insertBefore(child as Node, beforeNode);\n } else {\n parent.appendChild(child as Node);\n }\n}\n\n/**\n * Replace child node with a new node\n * Handles both component nodes and DOM nodes\n *\n * @param parent - Parent node\n * @param newNode - New node to insert\n * @param oldNode - Old node to be replaced\n */\nexport function replaceNode(parent: Node, newNode: AnyNode, oldNode: AnyNode): void {\n if (!parent || !newNode || !oldNode || newNode === oldNode) return;\n\n const beforeNode: AnyNode | undefined = isComponent(oldNode)\n ? oldNode.beforeNode\n : (oldNode as Node).nextSibling!;\n removeNode(oldNode);\n insertNode(parent, newNode, beforeNode);\n}\n\n/**\n * Get the first DOM node from a node or component\n *\n * @param node - Node or component\n * @returns The first DOM node or undefined\n */\nexport function getFirstDOMNode(node: AnyNode): Node | undefined {\n if (!node) {\n return;\n }\n\n if (isComponent(node)) {\n return node.firstChild;\n }\n\n if (isPrimitive(node)) {\n return undefined;\n }\n\n return node as Node;\n}\n","import { isHTMLElement, isTextNode } from '@estjs/shared';\nimport { isComponent } from './component';\nimport { getNodeKey, setNodeKey } from './key';\nimport { getFirstDOMNode, insertNode, removeNode, replaceNode } from './utils/dom';\nimport { isSameNode } from './utils/node';\n\nimport type { AnyNode } from './types';\n\n/**\n * Transfer key from old node to new node if new node doesn't have one.\n * Skips component nodes as they manage their own keys.\n *\n * @param oldNode - Source node to transfer key from\n * @param newNode - Target node to receive key\n */\nexport function transferKey(oldNode: AnyNode, newNode: AnyNode): void {\n // Components manage their own keys, skip them\n if (isComponent(oldNode) || isComponent(newNode)) {\n return;\n }\n\n const oldKey = getNodeKey(oldNode);\n if (oldKey && !getNodeKey(newNode)) {\n setNodeKey(newNode, oldKey);\n }\n}\n\n/**\n * Patches a single node, updating it if possible or replacing it.\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(a) where a is the number of attributes\n * - Same reference check: O(1)\n * - Element equality check: O(a) for attribute comparison\n * - Attribute patching: O(a) for iterating attributes\n * - Text node update: O(1)\n * - Component update: O(1) for type check, O(n) for component update\n * - Node replacement: O(1) for DOM operation\n *\n * - **Space Complexity**: O(1) - no additional allocations for common cases\n *\n * ## Optimization Strategy\n *\n * 1. **Fast path for same reference**: Returns immediately if nodes are identical\n * 2. **Fast path for equal nodes**: Uses isEqualNode() for structural equality\n * 3. **In-place attribute updates**: Modifies existing DOM nodes when possible\n * 4. **Minimal allocations**: Avoids creating intermediate arrays\n *\n * @param parent - The parent node\n * @param oldNode - The old node\n * @param newNode - The new node\n * @returns The patched node (reused old node or new node)\n */\nexport function patch(parent: Node, oldNode: AnyNode, newNode: AnyNode): AnyNode {\n // Fast path: same reference\n if (newNode === oldNode) {\n return oldNode;\n }\n\n // Cache type checks to avoid repeated function calls\n const oldIsElement = isHTMLElement(oldNode);\n const newIsElement = isHTMLElement(newNode);\n\n // Both are HTML elements - optimize attribute patching\n if (newIsElement && oldIsElement) {\n // Fast path: structurally equal nodes\n if (newNode.isEqualNode(oldNode)) {\n return oldNode;\n }\n\n // Patch attributes if tags are same\n if (oldNode.tagName === newNode.tagName) {\n // Iterate directly without creating intermediate arrays\n const oldAttrs = oldNode.attributes;\n const newAttrs = newNode.attributes;\n\n // Remove old attributes not in new (iterate backwards to handle live collection)\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const attrName = oldAttrs[i].name;\n if (!newNode.hasAttribute(attrName)) {\n oldNode.removeAttribute(attrName);\n }\n }\n\n // Set new/changed attributes\n for (let i = 0, len = newAttrs.length; i < len; i++) {\n const attr = newAttrs[i];\n if (oldNode.getAttribute(attr.name) !== attr.value) {\n oldNode.setAttribute(attr.name, attr.value);\n }\n }\n\n transferKey(oldNode, newNode);\n return oldNode;\n }\n }\n\n // Handle text nodes\n if (isTextNode(oldNode) && isTextNode(newNode)) {\n if (oldNode.textContent !== newNode.textContent) {\n oldNode.textContent = newNode.textContent;\n }\n transferKey(oldNode, newNode);\n return oldNode;\n }\n\n // Handle component instances - cache isComponent results\n const oldIsComponent = isComponent(oldNode);\n const newIsComponent = isComponent(newNode);\n\n if (oldIsComponent && newIsComponent) {\n if (oldNode.component === newNode.component) {\n return newNode.update(oldNode);\n }\n }\n\n // Different types, replace\n replaceNode(parent, newNode, oldNode);\n return newNode;\n}\n\n/**\n * Unified children patching with Map-based diffing and LIS optimization.\n *\n * ## Algorithm Complexity\n *\n * - **Best Case**: O(1) - both arrays empty\n * - **Fast Paths**: O(n) - mount all, unmount all, single child, two children\n * - **General Case**: O(n + m) where n = old children, m = new children\n * - Common prefix/suffix sync: O(min(n, m))\n * - Unknown sequence with LIS: O(n + m + k log k) where k = moved nodes\n *\n * - **Space Complexity**:\n * - Fast paths: O(1)\n * - General case: O(m) for index mapping + O(k) for LIS\n *\n * ## Optimization Strategy\n *\n * 1. **Fast path 0**: Both empty - O(1) immediate return\n * 2. **Fast path 1**: Mount all - O(m) simple insertion loop\n * 3. **Fast path 2**: Unmount all - O(n) simple removal loop\n * 4. **Fast path 3**: Single child - O(1) direct patch or replace\n * 5. **Fast path 4**: Two children - O(1) handles same order and swap\n * 6. **General algorithm**: Full diff with LIS optimization\n *\n * ## When Each Path is Used\n *\n * - **Empty arrays**: Initial render or complete removal\n * - **Mount all**: First render of a list\n * - **Unmount all**: Conditional rendering (v-if becomes false)\n * - **Single child**: Most common case in practice\n * - **Two children**: Common for toggle/swap scenarios\n * - **General**: Complex list updates with reordering\n *\n * @param parent - The parent DOM node\n * @param oldChildren - Array of current children\n * @param newChildren - Array of new children\n * @param anchor - Optional anchor node for insertions\n * @returns Patched array of children\n */\nexport function patchChildren(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n anchor?: Node,\n): AnyNode[] {\n const oldLength = oldChildren.length;\n const newLength = newChildren.length;\n\n // FAST PATH 0: Both empty\n if (oldLength === 0 && newLength === 0) {\n return [];\n }\n\n // FAST PATH 1: Mount all (no old children)\n if (oldLength === 0) {\n for (let i = 0; i < newLength; i++) {\n insertNode(parent, newChildren[i], anchor);\n }\n return newChildren;\n }\n\n // FAST PATH 2: Unmount all (no new children)\n if (newLength === 0) {\n // Remove all children efficiently\n for (let i = 0; i < oldLength; i++) {\n removeNode(oldChildren[i]);\n }\n return [];\n }\n\n // FAST PATH 3: Single child\n if (oldLength === 1 && newLength === 1) {\n const oldNode = oldChildren[0];\n const newNode = newChildren[0];\n if (isSameNode(oldNode, newNode)) {\n patch(parent, oldNode, newNode);\n newChildren[0] = oldNode;\n } else {\n replaceNode(parent, newNode, oldNode);\n }\n return newChildren;\n }\n\n // FAST PATH 4: Two children\n if (oldLength === 2 && newLength === 2) {\n const o0 = oldChildren[0];\n const o1 = oldChildren[1];\n const n0 = newChildren[0];\n const n1 = newChildren[1];\n\n // Same order\n if (isSameNode(o0, n0) && isSameNode(o1, n1)) {\n patch(parent, o0, n0);\n patch(parent, o1, n1);\n newChildren[0] = o0;\n newChildren[1] = o1;\n return newChildren;\n }\n\n // Swapped\n if (isSameNode(o0, n1) && isSameNode(o1, n0)) {\n patch(parent, o0, n1);\n patch(parent, o1, n0);\n // Move o1 before o0\n const dom1 = getFirstDOMNode(o1);\n const dom0 = getFirstDOMNode(o0);\n if (dom1 && dom0 && dom1.parentNode === parent) {\n parent.insertBefore(dom1, dom0);\n }\n newChildren[0] = o1;\n newChildren[1] = o0;\n return newChildren;\n }\n }\n\n // GENERAL ALGORITHM: Map-based diffing with LIS\n return patchKeyedChildren(parent, oldChildren, newChildren, anchor);\n}\n\n/**\n * General-purpose keyed children patching using optimized diff algorithm.\n *\n * ## Algorithm Overview\n *\n * This implements a two-pointer algorithm similar to Vue 3's diff algorithm:\n * 1. **Sync from start**: Match common prefix (same keys in same order)\n * 2. **Sync from end**: Match common suffix (same keys in same order)\n * 3. **Handle remaining**: Mount new, unmount old, or diff unknown sequence\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n + m) where n = old length, m = new length\n * - Prefix sync: O(min(n, m))\n * - Suffix sync: O(min(n, m))\n * - Remaining: O(max(n, m))\n * - Unknown sequence: O(n + m + k log k) where k = moved nodes\n *\n * - **Space Complexity**: O(1) for sync phases, O(m) for unknown sequence\n *\n * ## Why This Algorithm?\n *\n * Real-world list updates often have:\n * - **Common prefix**: Items at the start rarely change\n * - **Common suffix**: Items at the end rarely change\n * - **Small changes**: Only a few items in the middle change\n *\n * By syncing prefix and suffix first, we minimize the \"unknown sequence\"\n * that requires expensive diffing.\n *\n * ## Example\n *\n * ```\n * Old: [A, B, C, D, E]\n * New: [A, B, X, Y, E]\n *\n * Step 1: Sync prefix → A, B matched\n * Step 2: Sync suffix → E matched\n * Step 3: Unknown sequence → [C, D] vs [X, Y]\n * ```\n *\n * @param parent - Parent DOM node\n * @param oldChildren - Old children array\n * @param newChildren - New children array\n * @param anchor - Optional anchor node\n * @returns Patched new children array\n */\nfunction patchKeyedChildren(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n anchor?: Node,\n): AnyNode[] {\n let oldStartIdx = 0;\n let newStartIdx = 0;\n let oldEndIdx = oldChildren.length - 1;\n let newEndIdx = newChildren.length - 1;\n\n let oldStartNode = oldChildren[0];\n let oldEndNode = oldChildren[oldEndIdx];\n let newStartNode = newChildren[0];\n let newEndNode = newChildren[newEndIdx];\n\n // 1. Sync from start - skip common prefix\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n if (!oldStartNode) {\n oldStartNode = oldChildren[++oldStartIdx];\n } else if (!oldEndNode) {\n oldEndNode = oldChildren[--oldEndIdx];\n } else if (isSameNode(oldStartNode, newStartNode)) {\n patch(parent, oldStartNode, newStartNode);\n newChildren[newStartIdx] = oldStartNode;\n oldStartNode = oldChildren[++oldStartIdx];\n newStartNode = newChildren[++newStartIdx];\n } else {\n break;\n }\n }\n\n // 2. Sync from end - skip common suffix\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n if (!oldStartNode) {\n oldStartNode = oldChildren[++oldStartIdx];\n } else if (!oldEndNode) {\n oldEndNode = oldChildren[--oldEndIdx];\n } else if (isSameNode(oldEndNode, newEndNode)) {\n patch(parent, oldEndNode, newEndNode);\n newChildren[newEndIdx] = oldEndNode;\n oldEndNode = oldChildren[--oldEndIdx];\n newEndNode = newChildren[--newEndIdx];\n } else {\n break;\n }\n }\n\n // 3. Common sequence + mount new nodes\n if (oldStartIdx > oldEndIdx) {\n if (newStartIdx <= newEndIdx) {\n // Cache anchor calculation\n const anchorNode =\n newEndIdx + 1 < newChildren.length ? getFirstDOMNode(newChildren[newEndIdx + 1]) : anchor;\n\n for (let i = newStartIdx; i <= newEndIdx; i++) {\n insertNode(parent, newChildren[i], anchorNode);\n }\n }\n }\n // 4. Common sequence + unmount old nodes\n else if (newStartIdx > newEndIdx) {\n for (let i = oldStartIdx; i <= oldEndIdx; i++) {\n const node = oldChildren[i];\n if (node) {\n removeNode(node);\n }\n }\n }\n // 5. Unknown sequence - use optimized LIS algorithm\n else {\n patchUnknownSequence(\n parent,\n oldChildren,\n newChildren,\n oldStartIdx,\n oldEndIdx,\n newStartIdx,\n newEndIdx,\n anchor,\n );\n }\n\n return newChildren;\n}\n\n/**\n * Patch unknown sequence with optimized LIS (Longest Increasing Subsequence).\n * Uses Object literal instead of Map for faster string key lookup.\n *\n * ## Algorithm Overview\n *\n * This is the most complex part of the diff algorithm, handling arbitrary\n * reordering of children. It uses the LIS algorithm to minimize DOM moves.\n *\n * ## Algorithm Steps\n *\n * 1. **Build key map**: Create O(1) lookup for new children by key\n * 2. **Map old to new**: For each old child, find its position in new children\n * 3. **Detect moves**: Track if any nodes moved out of order\n * 4. **Calculate LIS**: Find longest increasing subsequence (nodes that don't need to move)\n * 5. **Apply changes**: Mount new nodes, move nodes not in LIS\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n + m + k log k)\n * - Build key map: O(m)\n * - Map old to new: O(n × m) worst case, O(n) with keys\n * - Calculate LIS: O(k log k) where k = number of moved nodes\n * - Apply changes: O(m)\n *\n * - **Space Complexity**: O(m)\n * - Key map: O(m)\n * - Index map: O(m) using Int32Array\n * - LIS result: O(k) where k ≤ m\n *\n * ## Why LIS?\n *\n * The LIS represents nodes that are already in correct relative order.\n * These nodes don't need to move, minimizing expensive DOM operations.\n *\n * ## Example\n *\n * ```\n * Old: [A, B, C, D, E]\n * New: [E, C, A, D, B]\n *\n * Index mapping: [2, 4, 1, 3, 0]\n * LIS: [1, 3] → C and D are in correct order\n * Result: Only move E, A, B; keep C and D in place\n * ```\n *\n * ## Optimization: Object vs Map\n *\n * Using Object.create(null) for key lookup is ~30% faster than Map\n * for string keys, which is the common case.\n *\n * @param parent - Parent DOM node\n * @param oldChildren - Old children array\n * @param newChildren - New children array\n * @param oldStartIdx - Start index in old children\n * @param oldEndIdx - End index in old children\n * @param newStartIdx - Start index in new children\n * @param newEndIdx - End index in new children\n * @param anchor - Optional anchor node\n */\nfunction patchUnknownSequence(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n oldStartIdx: number,\n oldEndIdx: number,\n newStartIdx: number,\n newEndIdx: number,\n anchor?: Node,\n): void {\n // Cache length calculation\n const newLength = newEndIdx - newStartIdx + 1;\n\n // Use Object literal for faster string key lookup\n let keyToNewIndexMap: Record<string, number> | undefined;\n\n // Build key to index map for new children\n for (let i = newStartIdx; i <= newEndIdx; i++) {\n const key = getNodeKey(newChildren[i]);\n if (key !== undefined) {\n if (!keyToNewIndexMap) {\n keyToNewIndexMap = Object.create(null);\n }\n keyToNewIndexMap![key] = i;\n }\n }\n\n // Use Int32Array for better memory layout and performance\n const newIndexToOldIndexMap = new Int32Array(newLength);\n let moved = false;\n let maxNewIndexSoFar = 0;\n let patched = 0;\n\n // Map old children to new positions\n for (let i = oldStartIdx; i <= oldEndIdx; i++) {\n const oldNode = oldChildren[i];\n if (!oldNode) continue;\n\n // All new nodes have been patched, remove remaining old nodes\n if (patched >= newLength) {\n removeNode(oldNode);\n continue;\n }\n\n let newIndex: number | undefined;\n const oldKey = getNodeKey(oldNode);\n\n // Fast path: keyed lookup using object property access\n if (oldKey !== undefined && keyToNewIndexMap && oldKey in keyToNewIndexMap) {\n newIndex = keyToNewIndexMap[oldKey];\n } else {\n // Fallback: type-based matching for unkeyed nodes\n for (let j = newStartIdx; j <= newEndIdx; j++) {\n if (\n newIndexToOldIndexMap[j - newStartIdx] === 0 &&\n oldKey === undefined &&\n getNodeKey(newChildren[j]) === undefined &&\n isSameNode(oldNode, newChildren[j])\n ) {\n newIndex = j;\n break;\n }\n }\n }\n\n if (newIndex === undefined) {\n // No match found, remove old node\n removeNode(oldNode);\n } else {\n // Record mapping (add 1 to distinguish from 0 which means unmapped)\n newIndexToOldIndexMap[newIndex - newStartIdx] = i + 1;\n\n // Track if nodes have moved (for LIS optimization)\n if (newIndex >= maxNewIndexSoFar) {\n maxNewIndexSoFar = newIndex;\n } else {\n moved = true;\n }\n\n // Patch the matched nodes\n patch(parent, oldNode, newChildren[newIndex]);\n newChildren[newIndex] = oldNode;\n patched++;\n }\n }\n\n // Calculate LIS only if nodes have moved\n const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : [];\n let j = increasingNewIndexSequence.length - 1;\n\n // Cache anchor nodes to avoid repeated getFirstDOMNode calls\n let cachedAnchor: Node | undefined = anchor;\n\n // Loop backwards to ensure correct anchor calculation\n for (let i = newLength - 1; i >= 0; i--) {\n const nextIndex = newStartIdx + i;\n const nextNode = newChildren[nextIndex];\n\n if (newIndexToOldIndexMap[i] === 0) {\n // New node - insert it\n insertNode(parent, nextNode, cachedAnchor);\n // Update cached anchor for next iteration\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n } else if (moved) {\n // Existing node - move if not in LIS\n if (j < 0 || i !== increasingNewIndexSequence[j]) {\n const domNode = getFirstDOMNode(nextNode);\n if (domNode && domNode.parentNode === parent) {\n insertNode(parent, domNode, cachedAnchor);\n }\n // Update cached anchor\n cachedAnchor = domNode || cachedAnchor;\n } else {\n // Node is in LIS, update anchor but don't move\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n j--;\n }\n } else {\n // No moves, just update anchor\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n }\n }\n}\n\n/**\n * Compute the Longest Increasing Subsequence (LIS).\n * Uses patience sorting with binary search for O(n log n) time complexity.\n *\n * ## Algorithm: Patience Sorting\n *\n * This algorithm is based on the patience sorting card game:\n * 1. Maintain an array of \"piles\" (result array)\n * 2. For each element, find the leftmost pile where it can be placed\n * 3. Use binary search to find the correct pile in O(log n)\n * 4. Track predecessors to reconstruct the sequence\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n log n)\n * - Main loop: O(n) iterations\n * - Binary search per iteration: O(log n)\n * - Sequence reconstruction: O(k) where k = LIS length\n *\n * - **Space Complexity**: O(n)\n * - Result array: O(k) where k ≤ n\n * - Predecessor array: O(n) using Int32Array\n *\n * ## Why This Algorithm?\n *\n * The LIS problem has multiple solutions:\n * - **Brute force**: O(2^n) - try all subsequences\n * - **Dynamic programming**: O(n²) - classic DP solution\n * - **Patience sorting**: O(n log n) - optimal solution\n *\n * We use patience sorting because:\n * 1. Optimal time complexity for large lists\n * 2. Simple to implement and understand\n * 3. Works well with the diff algorithm's needs\n *\n * ## Example\n *\n * ```\n * Input: [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]\n * Output: [0, 2, 6, 9, 11, 15] (indices of LIS)\n * LIS: [0, 2, 6, 9, 13, 15] (actual values)\n * ```\n *\n * ## Special Cases\n *\n * - **Empty array**: Returns []\n * - **Single element**: Returns [0] if element !== 0\n * - **All zeros**: Returns [] (zeros mean \"no mapping\" in diff context)\n * - **Strictly decreasing**: Returns [last_non_zero_index]\n *\n * ## Diff Context\n *\n * In the diff algorithm, the input array represents:\n * - Index: Position in new children\n * - Value: Position in old children + 1 (0 means new node)\n *\n * The LIS represents nodes that are already in correct relative order\n * and don't need to be moved.\n *\n * @param arr - Array of indices (0 means no mapping)\n * @returns Array of indices representing the LIS\n */\nexport function getSequence(arr: Int32Array | number[]): number[] {\n const len = arr.length;\n if (len === 0) return [];\n\n // Fast path: single element\n if (len === 1) return arr[0] !== 0 ? [0] : [];\n\n const result: number[] = [];\n const p = new Int32Array(len);\n\n let i: number;\n let j: number;\n let u: number;\n let v: number;\n let c: number;\n\n for (i = 0; i < len; i++) {\n const arrI = arr[i];\n if (arrI !== 0) {\n j = result[result.length - 1];\n\n // Append to result if greater than last element\n if (result.length === 0 || arr[j] < arrI) {\n p[i] = j;\n result.push(i);\n continue;\n }\n\n // Binary search for the correct position\n u = 0;\n v = result.length - 1;\n\n while (u < v) {\n c = (u + v) >> 1;\n if (arr[result[c]] < arrI) {\n u = c + 1;\n } else {\n v = c;\n }\n }\n\n // Update result if smaller value found\n if (arrI < arr[result[u]]) {\n if (u > 0) {\n p[i] = result[u - 1];\n }\n result[u] = i;\n }\n }\n }\n\n // Reconstruct the sequence\n u = result.length;\n v = result[u - 1];\n\n while (u-- > 0) {\n result[u] = v;\n v = p[v];\n }\n\n return result;\n}\n","import {\n coerceArray,\n isFunction,\n isHtmlInputElement,\n isHtmlSelectElement,\n isHtmlTextAreaElement,\n} from '@estjs/shared';\nimport { effect } from '@estjs/signals';\nimport { normalizeNode } from './utils/node';\nimport { removeNode } from './utils/dom';\nimport { patchChildren } from './patch';\nimport { getActiveScope, onCleanup, runWithScope } from './scope';\nimport type { AnyNode } from './types';\n\n/**\n * Add event listener with automatic cleanup on scope destruction\n *\n * @param element - Element to attach listener to\n * @param event - Event name\n * @param handler - Event handler function\n * @param options - Event listener options\n */\nexport function addEventListener(\n element: Element,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions,\n): void {\n element.addEventListener(event, handler, options);\n\n onCleanup(() => {\n element.removeEventListener(event, handler, options);\n });\n}\n\n/**\n * Bind an element to a setter function for two-way data binding\n *\n * @param node - The element to bind\n * @param key - The property key (unused, kept for API compatibility)\n * @param defaultValue - Default value (unused, kept for API compatibility)\n * @param setter - The setter function to call when the element's value changes\n */\nexport function bindElement(\n node: Element,\n key: string,\n defaultValue: unknown,\n setter: (value: unknown) => void,\n): void {\n if (isHtmlInputElement(node)) {\n bindInputElement(node, setter);\n } else if (isHtmlSelectElement(node)) {\n bindSelectElement(node, setter);\n } else if (isHtmlTextAreaElement(node)) {\n addEventListener(node, 'input', () => {\n setter((node as HTMLTextAreaElement).value);\n });\n }\n}\n\n/**\n * Bind input element based on its type\n */\nfunction bindInputElement(node: HTMLInputElement, setter: (value: unknown) => void): void {\n switch (node.type) {\n case 'checkbox':\n addEventListener(node, 'change', () => {\n setter(Boolean(node.checked));\n });\n break;\n\n case 'radio':\n addEventListener(node, 'change', () => {\n setter(node.checked ? node.value : '');\n });\n break;\n\n case 'file':\n addEventListener(node, 'change', () => {\n setter(node.files);\n });\n break;\n\n case 'number':\n case 'range':\n addEventListener(node, 'input', () => {\n setter(node.value || '');\n });\n break;\n\n case 'date':\n case 'datetime-local':\n case 'month':\n case 'time':\n case 'week':\n addEventListener(node, 'change', () => {\n setter(node.value || '');\n });\n break;\n\n default:\n // text, email, password, search, tel, url, etc.\n addEventListener(node, 'input', () => {\n setter(node.value);\n });\n break;\n }\n}\n\n/**\n * Bind select element\n */\nfunction bindSelectElement(node: HTMLSelectElement, setter: (value: unknown) => void): void {\n addEventListener(node, 'change', () => {\n if (node.multiple) {\n const values = Array.from(node.options)\n .filter(option => option.selected)\n .map(option => option.value);\n setter(values);\n } else {\n setter(node.value);\n }\n });\n}\n\n/**\n * Reactive node insertion with binding support\n *\n * @param parent Parent node\n * @param nodeFactory Node factory function or static node\n * @param before Reference node for insertion position\n * @param options Insertion options\n *\n * @example\n * ```typescript\n * insert(container, () => message.value, null);\n * insert(container, staticElement, referenceNode);\n * insert(container, \"Hello World\", null); // Direct string support\n * ```\n */\nexport function insert(parent: Node, nodeFactory: AnyNode, before?: Node) {\n if (!parent) return;\n\n let renderedNodes: AnyNode[] = [];\n const currentScope = getActiveScope();\n // Create effect for reactive updates\n const cleanup = effect(() => {\n const run = () => {\n const rawNodes = isFunction(nodeFactory) ? nodeFactory() : nodeFactory;\n const nodes = coerceArray(rawNodes as unknown)\n .map(item => (isFunction(item) ? item() : item))\n .flatMap(normalizeNode) as AnyNode[];\n\n renderedNodes = patchChildren(parent, renderedNodes, nodes, before) as AnyNode[];\n };\n if (currentScope) {\n runWithScope(currentScope, run);\n } else {\n run();\n }\n });\n\n onCleanup(() => {\n cleanup();\n renderedNodes.forEach(node => removeNode(node));\n renderedNodes.length = 0;\n });\n\n return renderedNodes;\n}\n\n/**\n * Map nodes from template by indexes\n *\n * @param template - Template node to traverse\n * @param indexes - Array of indexes to map\n * @returns Array of mapped nodes\n */\nexport function mapNodes(template: Node, indexes: number[]): Node[] {\n const len = indexes.length;\n const tree = new Array<Node>(len);\n const indexSet = new Set(indexes);\n\n let index = 1;\n let found = 0;\n\n const walk = (node: Node): boolean => {\n if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {\n if (indexSet.has(index)) {\n tree[found++] = node;\n if (found === len) return true;\n }\n index++;\n }\n\n let child = node.firstChild;\n while (child) {\n if (walk(child)) return true;\n child = child.nextSibling;\n }\n\n return false;\n };\n\n walk(template);\n return tree;\n}\n","import { error } from '@estjs/shared';\nimport { type Scope, getActiveScope, runWithScope } from './scope';\n\nexport type LifecycleHook = () => void | Promise<void>;\n\nexport const LIFECYCLE = {\n mount: 'mount',\n destroy: 'destroy',\n update: 'update',\n} as const;\n\nexport type LifecycleType = (typeof LIFECYCLE)[keyof typeof LIFECYCLE];\n\nexport type LifecycleHooks = {\n [key in LifecycleType]: Set<LifecycleHook>;\n};\n\n/**\n * Create a new lifecycle context (deprecated)\n * @deprecated Lifecycle hooks are now managed by Scope\n * @returns A new lifecycle hooks object\n */\nexport function createLifecycleContext(): LifecycleHooks {\n return {\n mount: new Set<LifecycleHook>(),\n destroy: new Set<LifecycleHook>(),\n update: new Set<LifecycleHook>(),\n };\n}\n\n/**\n * Register a lifecycle hook\n * @param type - The type of lifecycle hook to register\n * @param hook - The hook function to register\n */\nexport function registerLifecycleHook(type: LifecycleType, hook: LifecycleHook): void {\n switch (type) {\n case LIFECYCLE.mount:\n registerMountHook(hook);\n break;\n case LIFECYCLE.update:\n registerUpdateHook(hook);\n break;\n case LIFECYCLE.destroy:\n registerDestroyHook(hook);\n break;\n default:\n if (__DEV__) {\n error(`Invalid lifecycle type: ${type}`);\n }\n }\n}\n\n/**\n * Register a mount lifecycle hook.\n * If the scope is already mounted, the hook is executed immediately.\n *\n * @param hook - The mount hook function\n */\nexport function registerMountHook(hook: () => void | Promise<void>): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('onMount() must be called within a scope');\n }\n return;\n }\n\n // If already mounted, execute immediately\n if (scope.isMounted) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in mount hook:`, error_);\n }\n }\n return;\n }\n\n // Lazy initialize mount hooks set\n if (!scope.onMount) {\n scope.onMount = new Set();\n }\n\n scope.onMount.add(hook);\n}\n\n/**\n * Register an update lifecycle hook.\n *\n * @param hook - The update hook function\n */\nexport function registerUpdateHook(hook: () => void | Promise<void>): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('onUpdate() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize update hooks set\n if (!scope.onUpdate) {\n scope.onUpdate = new Set();\n }\n\n scope.onUpdate.add(hook);\n}\n\n/**\n * Register a destroy lifecycle hook.\n *\n * @param hook - The destroy hook function\n */\nexport function registerDestroyHook(hook: () => void | Promise<void>): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('onDestroy() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize destroy hooks set\n if (!scope.onDestroy) {\n scope.onDestroy = new Set();\n }\n\n scope.onDestroy.add(hook);\n}\n\n/**\n * Trigger mount lifecycle hooks for a scope.\n *\n * @param scope - The scope to trigger mount hooks for\n */\nexport function triggerMountHooks(scope: Scope): void {\n if (!scope || scope.isDestroyed || scope.isMounted) {\n return;\n }\n\n scope.isMounted = true;\n\n if (scope.onMount) {\n runWithScope(scope, () => {\n for (const hook of scope.onMount!) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in mount hook:`, error_);\n }\n }\n }\n });\n }\n}\n\n/**\n * Trigger update lifecycle hooks for a scope.\n *\n * @param scope - The scope to trigger update hooks for\n */\nexport function triggerUpdateHooks(scope: Scope): void {\n if (!scope || scope.isDestroyed) {\n return;\n }\n\n if (scope.onUpdate) {\n for (const hook of scope.onUpdate) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in update hook:`, error_);\n }\n }\n }\n }\n}\n\n/**\n * Trigger lifecycle hooks of a specific type for the active scope.\n * @param type - The type of lifecycle hooks to trigger\n */\nexport function triggerLifecycleHook(type: LifecycleType): void | Promise<void> {\n const scope = getActiveScope();\n if (!scope) {\n if (__DEV__) {\n error(`triggerLifecycleHook(${type}) called outside of a scope`);\n }\n return;\n }\n\n switch (type) {\n case LIFECYCLE.mount:\n return triggerMountHooks(scope);\n case LIFECYCLE.update:\n return triggerUpdateHooks(scope);\n case LIFECYCLE.destroy:\n if (scope.onDestroy) {\n for (const hook of scope.onDestroy) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in destroy hook:`, error_);\n }\n }\n }\n }\n break;\n }\n}\n/**\n * Register a mount lifecycle hook.\n * Called after the component is mounted to the DOM.\n *\n * @param hook - The hook function to execute on mount\n */\nexport function onMount(hook: LifecycleHook): void {\n registerMountHook(hook);\n}\n\n/**\n * Register a destroy lifecycle hook.\n * Called before the component is removed from the DOM.\n *\n * @param hook - The hook function to execute on destroy\n */\nexport function onDestroy(hook: LifecycleHook): void {\n registerDestroyHook(hook);\n}\n\n/**\n * Register an update lifecycle hook.\n * Called after the component updates.\n *\n * @param hook - The hook function to execute on update\n */\nexport function onUpdate(hook: LifecycleHook): void {\n registerUpdateHook(hook);\n}\n\n/**\n * Cleanup lifecycle hooks for a context (deprecated)\n * @deprecated Use disposeScope instead\n * @param context - The context to cleanup\n */\nexport function cleanupLifecycle(context?: Scope): void {\n const scope = context || getActiveScope();\n if (!scope) {\n return;\n }\n\n // Clear all lifecycle hooks\n scope.onMount?.clear();\n scope.onDestroy?.clear();\n scope.onUpdate?.clear();\n}\n","import { isComputed, isSignal, shallowReactive } from '@estjs/signals';\nimport {\n coerceArray,\n hasChanged,\n isArray,\n isFunction,\n isHTMLElement,\n isObject,\n isPromise,\n startsWith,\n} from '@estjs/shared';\nimport {\n type Scope,\n createScope,\n disposeScope,\n getActiveScope,\n runWithScope,\n setActiveScope,\n} from './scope';\nimport { COMPONENT_STATE, EVENT_PREFIX, NORMAL_COMPONENT, REF_KEY } from './constants';\nimport { addEventListener, insert } from './binding';\nimport { getComponentKey, normalizeKey } from './key';\nimport { getFirstDOMNode, insertNode, removeNode } from './utils/dom';\nimport { shallowCompare } from './utils/node';\nimport { triggerMountHooks, triggerUpdateHooks } from './lifecycle';\nimport type { AnyNode, ComponentFn, ComponentProps } from './types';\n\nexport class Component<P extends ComponentProps = ComponentProps> {\n // Component rendered nodes (supports arrays and fragments)\n protected renderedNodes: AnyNode[] = [];\n\n // Component scope (unified context management)\n protected scope: Scope | null = null;\n\n // Component parent node\n protected parentNode: Node | undefined = undefined;\n\n // Component before node\n public beforeNode: Node | undefined = undefined;\n\n // Component props (reactive and snapshot)\n private reactiveProps: Record<string, any> = {};\n private _propSnapshots: Record<string, any> = {};\n\n // Component key for reconciliation\n public readonly key: string | undefined;\n\n // Component lifecycle state\n protected state: number = COMPONENT_STATE.INITIAL;\n\n // Parent scope captured at construction time for correct hierarchy\n protected parentScope: Scope | null = null;\n\n // @ts-ignore\n public readonly [NORMAL_COMPONENT] = true;\n\n get isConnected(): boolean {\n return this.state === COMPONENT_STATE.MOUNTED;\n }\n\n get firstChild(): Node | undefined {\n // Get the first meaningful DOM node from rendered nodes\n for (const node of this.renderedNodes) {\n const dom = getFirstDOMNode(node);\n if (dom) return dom;\n }\n return undefined;\n }\n\n constructor(\n public component: ComponentFn<P>,\n public props: P = {} as P,\n ) {\n this.key = props.key ? normalizeKey(props.key) : getComponentKey(component);\n this.reactiveProps = shallowReactive({ ...props }) as P;\n this.parentScope = getActiveScope();\n\n // Initialize snapshots for object/array props to track mutations\n for (const key in props) {\n const val = props[key];\n if (isObject(val)) {\n this._propSnapshots[key] = isArray(val) ? [...val] : { ...val };\n }\n }\n }\n\n mount(parentNode: Node, beforeNode?: Node): AnyNode[] {\n this.parentNode = parentNode;\n this.beforeNode = beforeNode;\n this.state = COMPONENT_STATE.MOUNTING;\n\n // if the component already has rendered nodes, re-insert them\n if (this.renderedNodes.length > 0) {\n for (const node of this.renderedNodes) {\n insertNode(parentNode, node, beforeNode);\n }\n this.state = COMPONENT_STATE.MOUNTED;\n return this.renderedNodes;\n }\n\n const parentScope = this.parentScope ?? getActiveScope();\n this.scope = createScope(parentScope);\n setActiveScope(this.scope);\n let result = this.component(this.reactiveProps as P);\n\n // Unwrap function (render function pattern)\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // Unwrap signals and computed values\n if (isSignal<Element>(result) || isComputed<Element>(result)) {\n result = result.value;\n }\n\n const renderedNodes = insert(parentNode, result, beforeNode) ?? [];\n\n this.renderedNodes = renderedNodes;\n\n // Apply props (events, refs) after renderedNodes is set\n\n this.applyProps(this.props);\n\n // Update state to mounted\n this.state = COMPONENT_STATE.MOUNTED;\n\n // Trigger mount lifecycle hooks\n triggerMountHooks(this.scope);\n\n return this.renderedNodes;\n }\n\n update<T extends ComponentProps>(prevNode: Component<T>): Component<T> {\n // if key is different, mount the component\n if (this.key !== prevNode.key) {\n this.mount(prevNode.parentNode!, prevNode.beforeNode);\n return this as unknown as Component<T>;\n }\n\n // Take previous node's properties and reactive state\n this.parentNode = prevNode.parentNode;\n this.beforeNode = prevNode.beforeNode;\n this.scope = prevNode.scope; // Reuse existing scope\n this.parentScope = prevNode.parentScope;\n this.renderedNodes = prevNode.renderedNodes;\n this.state = prevNode.state;\n this.reactiveProps = prevNode.reactiveProps; // Reuse same reactive object\n this._propSnapshots = prevNode._propSnapshots;\n\n // Update reactive props with shallow comparison for objects\n this._updateReactiveProps(this.props);\n\n // Mount component if not connected\n if (!this.isConnected && this.parentNode) {\n this.mount(this.parentNode, this.beforeNode);\n return this as unknown as Component<T>;\n }\n\n // Apply props and trigger update lifecycle\n if (this.scope) {\n setActiveScope(this.scope);\n this.applyProps(this.props);\n triggerUpdateHooks(this.scope);\n }\n\n return this as unknown as Component<T>;\n }\n\n /**\n * Update reactive props by comparing with current values\n */\n private _updateReactiveProps(props: P): void {\n for (const key in props) {\n if (key === 'key') continue;\n\n const newValue = props[key];\n const oldValue = this.reactiveProps[key];\n\n // Early return: if values are strictly equal, skip processing\n // Note: If we have a snapshot, we might still need to check for mutations (same ref but content changed)\n if (newValue === oldValue && !this._propSnapshots[key]) continue;\n\n // Cache type check to avoid repeated calls\n const isNewValueObject = isObject(newValue);\n\n if (isNewValueObject) {\n // For objects/arrays: compare with snapshot to detect mutations\n const snapshot = this._propSnapshots[key];\n\n // Early return: if snapshot exists and content is the same, skip update\n if (snapshot && shallowCompare(newValue, snapshot)) continue;\n\n // Create new snapshot efficiently\n const newSnapshot = isArray(newValue) ? [...newValue] : { ...newValue };\n this.reactiveProps[key] = newSnapshot;\n this._propSnapshots[key] = newSnapshot;\n } else {\n // For primitives: hasChanged check (handles NaN, +0/-0, etc.)\n if (hasChanged(newValue, oldValue)) {\n this.reactiveProps[key] = newValue;\n // Clean up snapshot if it exists (type may have changed from object to primitive)\n if (this._propSnapshots[key]) {\n delete this._propSnapshots[key];\n }\n }\n }\n }\n }\n\n private unwrapRenderResult(result: any): AnyNode[] {\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // Unwrap signals and computed values\n if (isSignal<AnyNode>(result) || isComputed<AnyNode>(result)) {\n result = result.value;\n }\n if (isComponent(result)) {\n result = result.mount(this.parentNode!, this.beforeNode);\n }\n\n if (isPromise(result)) {\n result = result.then(r => this.unwrapRenderResult(r));\n }\n\n return result;\n }\n\n forceUpdate(): void {\n if (this.state === COMPONENT_STATE.DESTROYED || !this.parentNode || !this.scope) {\n return;\n }\n\n const originalNodes = [...this.renderedNodes];\n\n try {\n runWithScope(this.scope, () => {\n // Re-render and get new nodes\n let result = this.component(this.reactiveProps as P);\n\n // Unwrap function (render function pattern)\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // Unwrap signals and computed values\n if (isSignal<AnyNode>(result) || isComputed<AnyNode>(result)) {\n result = result.value;\n }\n\n const newNodes = coerceArray(result) as AnyNode[];\n\n // Calculate anchor position for insertion\n const anchor = this._getAnchorNode();\n\n // Replace old nodes with new ones\n if (!this.parentNode) return;\n\n // Remove old nodes\n for (const node of this.renderedNodes) {\n removeNode(node);\n }\n\n // Insert new nodes\n for (const node of newNodes) {\n insertNode(this.parentNode, node, anchor);\n }\n\n this.renderedNodes = newNodes;\n });\n\n if (this.scope) {\n triggerUpdateHooks(this.scope);\n }\n } catch (error) {\n // Rollback on error\n this.renderedNodes = originalNodes;\n throw error;\n }\n }\n\n /**\n * Get anchor node for insertion\n */\n private _getAnchorNode(): Node | undefined {\n if (this.beforeNode) return this.beforeNode;\n\n if (this.renderedNodes.length > 0) {\n const lastNode = this.renderedNodes[this.renderedNodes.length - 1];\n const lastDom = getFirstDOMNode(lastNode);\n if (lastDom) {\n return lastDom.nextSibling as Node | undefined;\n }\n }\n\n return undefined;\n }\n\n /**\n * Destroy component\n */\n destroy(): void {\n // Prevent duplicate destruction\n if (this.state === COMPONENT_STATE.DESTROYING || this.state === COMPONENT_STATE.DESTROYED) {\n return;\n }\n\n this.state = COMPONENT_STATE.DESTROYING;\n\n // Remove all rendered nodes\n for (const node of this.renderedNodes) {\n removeNode(node);\n }\n\n const scope = this.scope;\n if (scope) {\n disposeScope(scope);\n this.scope = null;\n }\n // Reset all component properties\n this.renderedNodes = [];\n this.parentNode = undefined;\n this.beforeNode = undefined;\n this.parentScope = null;\n this.reactiveProps = {} as P;\n this.props = {} as P;\n this.state = COMPONENT_STATE.DESTROYED;\n }\n\n applyProps(props: P): void {\n if (!props) return;\n\n const firstElement = this.firstChild;\n\n // Apply event listeners and refs\n for (const [propName, propValue] of Object.entries(props)) {\n if (startsWith(propName, EVENT_PREFIX)) {\n if (!firstElement || !isHTMLElement(firstElement)) return;\n\n const eventName = propName.slice(EVENT_PREFIX.length).toLowerCase();\n addEventListener(firstElement, eventName, propValue as EventListener);\n } else if (propName === REF_KEY && isSignal(propValue)) {\n propValue.value = firstElement;\n }\n }\n\n this.props = props;\n }\n}\n\n/**\n * check if a node is a component\n * @param {unknown} node - the node to check\n * @returns {boolean} true if the node is a component, false otherwise\n */\nexport function isComponent(node: unknown): node is Component {\n return !!node && !!node[NORMAL_COMPONENT];\n}\n\n/**\n * create a component\n * @param {Function} componentFn - the component function\n * @param {ComponentProps} props - the component props\n * @returns {Component} the component\n */\nexport function createComponent<P extends ComponentProps>(\n componentFn: ComponentFn<P>,\n props?: P,\n): Component<P> {\n if (isComponent(componentFn)) {\n return componentFn as unknown as Component<P>;\n }\n return new Component(componentFn, props);\n}\n","import { error, isString } from '@estjs/shared';\nimport { type Component, createComponent, isComponent } from './component';\nimport type { ComponentFn, ComponentProps } from './types';\n\n/**\n * Create a template factory function from HTML string\n *\n * This function creates a reusable template factory that efficiently clones\n * DOM nodes from the provided HTML string. The template is parsed once and\n *\n * @param html - The HTML string to create template from\n * @returns Factory function that returns a cloned node of the template\n * @throws {Error} When template content is empty or invalid\n\n */\nexport function template(html: string) {\n let node: Node | undefined;\n\n const create = (): Node => {\n // Regular HTML template\n const template = document.createElement('template');\n template.innerHTML = html;\n const firstChild = template.content.firstChild;\n if (!firstChild) {\n throw new Error('Invalid template: empty content');\n }\n return firstChild;\n };\n\n // return a factory function: create the template when first called, reuse the cached template when called later\n return () => (node || (node = create())).cloneNode(true);\n}\n\n/**\n * Create and mount an application with the specified component\n *\n * This function initializes an application by mounting a root component\n * to a target DOM element. It handles target validation and cleanup.\n *\n * @param component - The root component function to mount\n * @param target - CSS selector string or DOM element to mount to\n * @returns The mount root component instance, or undefined if target not found\n */\nexport function createApp<P extends ComponentProps = {}>(\n component: ComponentFn<P> | Component<P>,\n target: string | Element,\n) {\n const container = isString(target)\n ? document.querySelector(target as string)\n : (target as Element);\n if (!container) {\n error(`Target element not found: ${target}`);\n return;\n }\n\n const existingContext = container.innerHTML;\n if (existingContext) {\n error(`Target element is not empty, it will be delete: ${target}`);\n container.innerHTML = '';\n }\n const rootComponent: Component<P> = isComponent(component)\n ? (component as Component<P>)\n : createComponent(component as ComponentFn<P>);\n rootComponent.mount(container);\n return rootComponent;\n}\n","import { error } from '@estjs/shared';\nimport { type Scope, getActiveScope } from './scope';\n\n/**\n * InjectionKey is a unique identifier for provided values.\n * Using Symbol ensures type safety and prevents key collisions.\n */\n// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types, unused-imports/no-unused-vars\nexport interface InjectionKey<T> extends Symbol {}\n\n/**\n * Provide a value in the current scope.\n * The value can be injected by this scope or any descendant scope.\n *\n * @param key - The injection key\n * @param value - The value to provide\n */\nexport function provide<T>(key: InjectionKey<T> | string | number, value: T): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('provide() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize provides map\n if (!scope.provides) {\n scope.provides = new Map();\n }\n\n scope.provides.set(key, value);\n}\n\n/**\n * Inject a value from the scope hierarchy.\n * Traverses up the parent chain until finding a matching key.\n *\n * @param key - The injection key\n * @param defaultValue - Default value if key is not found\n * @returns The injected value or default value\n */\nexport function inject<T>(key: InjectionKey<T> | string | number, defaultValue?: T): T {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('inject() must be called within a scope');\n }\n return defaultValue as T;\n }\n\n // Traverse up the hierarchy\n let current: Scope | null = scope;\n while (current) {\n if (current.provides) {\n const value = current.provides.get(key);\n if (value) {\n return value as T;\n }\n }\n current = current.parent;\n }\n\n return defaultValue as T;\n}\n","import { isFunction, isString } from '@estjs/shared';\n\n/**\n * Retarget the event's target property\n * @param event - Event object to retarget\n * @param value - New target value\n */\nfunction reTarget(event: Event, value: EventTarget): void {\n Object.defineProperty(event, 'target', {\n configurable: true,\n value,\n });\n}\n\n/**\n * Handle event on current node\n * @param node - Current node to handle\n * @param event - Event object\n * @param key - Event type key\n * @returns Whether to continue propagation\n */\nfunction handleNodeEvent(node: any, event: Event, key: string): boolean {\n const handler = node[`_$${key}`];\n if (handler && isFunction(handler) && !node.disabled) {\n const data = node[`${key}Data`];\n data ? handler.call(node, data, event) : handler.call(node, event);\n if (event.cancelBubble) return false;\n }\n\n // Handle host element retargeting\n if (\n node.host &&\n !isString(node.host) &&\n !node.host._$host &&\n isFunction(node.contains) &&\n node.contains(event.target)\n ) {\n reTarget(event, node.host);\n }\n return true;\n}\n\n/**\n * Walk up the DOM tree handling events\n * @param startNode - Initial node to start from\n * @param event - Event object\n * @param key - Event type key\n * @returns Final node after walking\n */\nfunction walkUpTree(startNode: any, event: Event, key: string): any {\n let node = startNode;\n while (handleNodeEvent(node, event, key) && (node = node._$host || node.parentNode || node.host));\n return node;\n}\n\n/**\n * Event handler for delegated events\n * @param event - The event object\n */\nfunction eventHandler(event): void {\n let node = event.target;\n const key = `${event.type}`;\n const oriTarget = event.target;\n const oriCurrentTarget = event.currentTarget;\n\n // Simulate currentTarget\n Object.defineProperty(event, 'currentTarget', {\n configurable: true,\n get() {\n return node || document;\n },\n });\n\n if (event.composedPath) {\n const path = event.composedPath();\n reTarget(event, path[0]);\n for (let i = 0; i < path.length - 2; i++) {\n node = path[i];\n if (!handleNodeEvent(node, event, key)) break;\n if (node._$host) {\n node = node._$host;\n // Bubble up from portal mount instead of composedPath\n node = walkUpTree(node, event, key);\n break;\n }\n if (node.parentNode === oriCurrentTarget) {\n break; // Don't bubble above root of event delegation\n }\n }\n } else {\n // Fallback for browsers that don't support composedPath\n node = walkUpTree(node, event, key);\n }\n\n // Mixing portals and shadow dom can lead to a nonstandard target, so reset here\n reTarget(event, oriTarget!);\n}\n\n/**\n * Symbol for storing delegated events on document\n */\nconst $EVENTS = Symbol('_$EVENTS');\n\n/**\n * Set up event delegation for specified event types\n * @param {string[]} eventNames - Array of event names to delegate\n * @param {Document} document - Document to attach events to (defaults to window.document)\n */\nexport function delegateEvents(eventNames: string[], document: Document = window.document): void {\n const docWithEvents = document as Document & { [$EVENTS]?: Set<string> };\n const eventSet = docWithEvents[$EVENTS] || (docWithEvents[$EVENTS] = new Set<string>());\n\n for (const name of eventNames) {\n if (!eventSet.has(name)) {\n eventSet.add(name);\n document.addEventListener(name, eventHandler);\n }\n }\n}\n\n/**\n * Clear all delegated events from document\n * @param {Document} document - Document to clear events from (defaults to window.document)\n */\nexport function clearDelegatedEvents(document: Document = window.document): void {\n const docWithEvents = document as Document & { [$EVENTS]?: Set<string> };\n const eventSet = docWithEvents[$EVENTS];\n if (eventSet) {\n for (const name of eventSet.keys()) {\n document.removeEventListener(name, eventHandler);\n }\n delete docWithEvents[$EVENTS];\n }\n}\n","/**\n * Create a reactive proxy that excludes specified properties\n *\n * @param target - The original reactive object\n * @param keys - List of property names to exclude\n * @returns A reactive proxy with specified properties excluded\n */\nexport function omitProps<T extends object, K extends keyof T>(target: T, keys: K[]): Omit<T, K> {\n const excludeSet = new Set(keys);\n\n return new Proxy(target, {\n // Intercept property reads\n get(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n return Reflect.get(obj, prop);\n },\n\n // Intercept property enumeration (for...in, Object.keys, etc.)\n ownKeys(obj) {\n return Reflect.ownKeys(obj).filter(key => !excludeSet.has(key as K));\n },\n\n // Intercept property descriptor retrieval\n getOwnPropertyDescriptor(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n return Reflect.getOwnPropertyDescriptor(obj, prop);\n },\n\n // Intercept the 'in' operator\n has(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return false;\n }\n return Reflect.has(obj, prop);\n },\n });\n}\n","/** Whether hydration is currently active */\nlet isHydrationActive = false;\n\n/**\n * Start hydration mode\n * Called when beginning client-side hydration of server-rendered content\n */\nexport function startHydration(): void {\n isHydrationActive = true;\n}\n\n/**\n * End hydration mode\n * Called when hydration is complete\n */\nexport function endHydration(): void {\n isHydrationActive = false;\n}\n\n/**\n * Check if hydration is currently active\n * @returns true if hydration is in progress\n */\nexport function isHydrating(): boolean {\n return isHydrationActive;\n}\n\n/** Hydration identifier counter, used to generate unique IDs */\nlet hydrationCounter = 0;\n\n/**\n * Get the hydration key\n * @returns the hydration key string\n */\nexport function getHydrationKey(): string {\n return `${hydrationCounter++}`;\n}\n\n/**\n * Reset the hydration key counter\n */\nexport function resetHydrationKey(): void {\n hydrationCounter = 0;\n}\n","import { error, isBrowser, isString } from '@estjs/shared';\nimport {\n createComponent,\n endHydration,\n startHydration,\n template,\n mapNodes as templateMapNodes,\n} from '../';\nimport { getHydrationKey, resetHydrationKey } from './shared';\nimport type { ComponentFn } from '../';\n/**\n * data-idx regex\n */\nexport const DATA_IDX_REGEX = /^\\d+-\\d+$/;\n/**\n * Get rendered element by hydration key or create from template\n * @param {string} temp - the template string\n * @returns {Function} a function that returns the element\n */\nexport function getRenderedElement(temp: string) {\n return () => {\n // SSR environment check\n if (!isBrowser()) {\n return null;\n }\n\n // Get hydration key\n const key = getHydrationKey();\n\n // Try to find existing element with matching hydration key\n const node = document.querySelector(`[data-hk=\"${key}\"]`);\n\n if (node) {\n return node;\n }\n\n // Create new element from template if not found\n return template(temp)();\n };\n}\n\n/**\n * Maps server-side rendered nodes during hydration\n * @param {HTMLElement} templateEl - The root template element\n * @param {number[]} idx - Array of indices to map\n * @returns {Node[]} Array of mapped nodes\n */\nexport function mapSSRNodes(templateEl: HTMLElement, idx: number[]): Node[] {\n // Check if we're in hydration mode by looking for the data-hk attribute\n const hk = templateEl.dataset.hk;\n\n // If not hydrating, fallback to standard node mapping\n if (!hk) {\n return templateMapNodes(templateEl, idx);\n }\n\n // Collection for all nodes\n const nodesList: Array<{ hk: string; idx: string; node: Node }> = [];\n\n // Find element nodes with data-idx attributes\n const elements = templateEl.querySelectorAll(`[data-idx^=\"${hk}\"]`);\n\n // Process element nodes\n if (elements.length > 0) {\n nodesList.push(\n ...Array.from(elements)\n .filter((item: Element) => {\n const idxAttr = (item as HTMLElement).dataset.idx;\n return idxAttr !== null && DATA_IDX_REGEX.test(idxAttr!);\n })\n .map((item: Element) => {\n const idxAttr = (item as HTMLElement).dataset.idx || '';\n const [hkPart, idxPart] = idxAttr.split('-');\n return {\n hk: hkPart,\n idx: idxPart,\n node: item,\n };\n }),\n );\n }\n\n // Find and process comment nodes\n const commentNodes: Array<{ hk: string; idx: string; node: Node }> = [];\n\n const walkNodes = (node: Node): void => {\n // Check for comment nodes with data-idx pattern\n if (\n node.nodeType === Node.COMMENT_NODE &&\n node.textContent &&\n DATA_IDX_REGEX.test(node.textContent)\n ) {\n const [hkPart, idxPart] = node.textContent.split('-');\n commentNodes.push({\n hk: hkPart,\n idx: idxPart,\n node,\n });\n }\n\n // Recursively process child nodes\n let child = node.firstChild;\n while (child) {\n walkNodes(child);\n child = child.nextSibling;\n }\n };\n\n walkNodes(templateEl);\n nodesList.push(...commentNodes);\n\n // Build final node list with template as first element\n const nodes: Node[] = [templateEl];\n\n // Map indices to corresponding nodes\n idx.forEach(indexValue => {\n const node = nodesList.find(item => item.idx === String(indexValue));\n if (node) {\n nodes.push(node.node);\n }\n });\n\n return nodes;\n}\n\n/**\n * Hydrate a server-rendered component\n * @param {ComponentFn} component - Component function to hydrate\n * @param {HTMLElement | string} container - Container element or selector\n * @returns {any} Component instance or undefined if hydration fails\n */\nexport function hydrate(component: ComponentFn, container: HTMLElement | string): any {\n // Set hydration mode\n startHydration();\n // Reset hydration key counter\n resetHydrationKey();\n\n try {\n // Get container element\n const rootElement = isString(container)\n ? document.querySelector(container as string)\n : container;\n\n if (!rootElement) {\n error('Hydration error: Root element not found');\n return undefined;\n }\n\n // Create and mount component\n const rootComponent = createComponent(component);\n rootComponent.mount(rootElement);\n\n // Exit hydration mode\n endHydration();\n\n return rootComponent;\n } catch (error_) {\n error('Hydration error:', error_);\n // Ensure hydration mode is ended even if an error occurs\n endHydration();\n return undefined;\n }\n}\n","import { normalizeClassName } from '@estjs/shared';\nimport { isHydrating } from '../hydration/shared';\n\n/**\n * Type definition for class values\n * @public\n */\nexport type ClassValue = string | Record<string, boolean> | ClassValue[] | null | undefined;\n\n/**\n * Patches the class attribute of an element\n * Supports silent hydration (skips DOM updates during hydration phase)\n *\n * @param el - The element to patch classes on\n * @param prev - Previous class value for diffing\n * @param next - New class value to apply\n * @param isSVG - Whether the element is an SVG element\n * @public\n */\nexport function patchClass(\n el: Element,\n prev: unknown,\n next: unknown,\n isSVG: boolean = false,\n): void {\n if (prev === next) {\n return;\n }\n if (isHydrating()) {\n return;\n }\n const normalizedNext = normalizeClass(next);\n const normalizedPrev = normalizeClass(prev);\n // Skip DOM update if classes haven't changed\n if (normalizedNext && normalizedPrev === normalizedNext) {\n return;\n }\n\n // Apply classes based on element type\n if (!normalizedNext) {\n el.removeAttribute('class');\n } else if (isSVG) {\n el.setAttribute('class', normalizedNext);\n } else {\n el.className = normalizedNext;\n }\n}\n\n/**\n * Normalizes different class value formats into a single string\n * Re-exports normalizeClassName from shared as normalizeClass for backward compatibility\n *\n * @param value - The class value to normalize\n * @returns A normalized class string\n * @public\n */\nexport function normalizeClass(value: unknown): string {\n return normalizeClassName(value);\n}\n","import { camelCase, capitalize, isArray, isObject, isString } from '@estjs/shared';\nimport { isHydrating } from '../hydration/shared';\n\n/**\n * Symbol for storing CSS variable text in style objects\n * @internal\n */\nexport const CSS_VAR_TEXT: unique symbol = Symbol('CSS_VAR_TEXT');\n\n// Cache regex patterns for better performance\nconst importantRE = /\\s*!important$/;\n\n// Cache browser prefixes for better performance\nconst prefixes = ['Webkit', 'Moz', 'ms'];\nconst prefixCache: Record<string, string> = {};\n\n/**\n * Type definition for style values\n * @public\n */\nexport type Style = string | Record<string, string | string[]> | null | undefined;\n\n/**\n * Patches the style of an element, optimized for different style formats\n * Supports silent hydration (skips DOM updates during hydration phase)\n *\n * @param el - The element to patch styles on\n * @public\n */\nexport function patchStyle(el: HTMLElement, prev: unknown, next: unknown) {\n const style = el.style;\n const isCssString = isString(next);\n if (isHydrating()) {\n return;\n }\n if (next && isCssString) {\n if (prev !== next) {\n style.cssText = next;\n }\n return;\n }\n\n if (!next) {\n if (prev) {\n el.removeAttribute('style');\n }\n return;\n }\n\n // Handle object-based styles\n if (prev && !isString(prev)) {\n // Remove styles that are no longer present\n for (const key in prev) {\n if (!next || next[key as keyof typeof next] == null) {\n setStyle(style, key, '');\n }\n }\n } else if (prev && isString(prev)) {\n // Handle previous string-based styles\n const prevStyles = prev.split(';');\n for (const stylePart of prevStyles) {\n const colonIndex = stylePart.indexOf(':');\n if (colonIndex > 0) {\n const key = stylePart.slice(0, colonIndex).trim();\n if (next && isObject(next) && next[key] == null) {\n setStyle(style, key, '');\n }\n }\n }\n }\n\n // Set new styles\n if (next && !isString(next)) {\n for (const key in next) {\n const value = next[key];\n if ((!prev || isString(prev) || prev[key] !== value) && value != null) {\n setStyle(style, key, value);\n }\n }\n }\n}\n\n/**\n * Sets an individual style property with various optimizations\n *\n * @param style - The style object to modify\n * @param name - The style property name\n * @param val - The style property value\n * @private\n */\nexport function setStyle(style: CSSStyleDeclaration, name: string, val: string | string[]): void {\n // Handle array values (vendor prefixed values)\n if (isArray(val)) {\n for (const element of val) {\n setStyle(style, name, element);\n }\n return;\n }\n\n if (val == null || val === '') {\n val = '';\n }\n\n // Handle CSS custom properties\n if (name.startsWith('--')) {\n style.setProperty(name, val);\n return;\n }\n\n // Handle regular CSS properties with potential prefixing\n const prefixed = autoPrefix(style, name);\n\n // Handle !important\n if (isString(val) && importantRE.test(val)) {\n style.setProperty(camelCase(prefixed), val.replace(importantRE, ''), 'important');\n } else {\n style[prefixed] = val;\n }\n}\n\n/**\n * Adds vendor prefixes to style properties as needed\n *\n * @param style - The style object to check against\n * @param rawName - The raw property name\n * @returns The prefixed property name if needed\n * @private\n */\nfunction autoPrefix(style: CSSStyleDeclaration, rawName: string): string {\n // Check cache first\n const cached = prefixCache[rawName];\n if (cached) {\n return cached;\n }\n\n // Try camelCase version directly\n let name = camelCase(rawName);\n if (name !== 'filter' && name in style) {\n return (prefixCache[rawName] = name);\n }\n\n // Try with vendor prefixes\n name = capitalize(name);\n for (const prefix of prefixes) {\n const prefixed = prefix + name;\n if (prefixed in style) {\n return (prefixCache[rawName] = prefixed);\n }\n }\n\n return rawName;\n}\n","import {\n includeBooleanAttr,\n isBooleanAttr,\n isObject,\n isSpecialBooleanAttr,\n isString,\n isSymbol,\n warn,\n} from '@estjs/shared';\nimport {\n KEY_PROP,\n SPREAD_NAME,\n SVG_NAMESPACE,\n XLINK_NAMESPACE,\n XMLNS_NAMESPACE,\n} from '../constants';\nimport { setNodeKey } from '../key';\nimport { isHydrating } from '../hydration/shared';\n\nexport type AttrValue = string | boolean | number | null | undefined | Record<string, unknown>;\n\nexport function patchAttr(el: Element, key: string, prev: AttrValue, next: AttrValue) {\n if (key === KEY_PROP) {\n if (next == null) {\n setNodeKey(el, undefined);\n } else {\n setNodeKey(el, String(next));\n }\n return;\n }\n if (key === SPREAD_NAME) {\n if (__DEV__) {\n if (!isObject(next)) {\n warn('spread attribute must be an object');\n }\n }\n Object.keys(next as Record<string, unknown>).forEach(k => {\n patchAttr(el, k, prev?.[k], next?.[k]);\n });\n return;\n }\n\n if (isHydrating()) {\n return;\n }\n const elementIsSVG = el?.namespaceURI === SVG_NAMESPACE;\n const isXlink = elementIsSVG && key.startsWith('xlink:');\n const isXmlns = elementIsSVG && key.startsWith('xmlns:');\n\n const isBoolean = isSpecialBooleanAttr(key) || isBooleanAttr(key);\n\n // Early return if values are the same\n if (prev === next) {\n return;\n }\n\n // Compute lowerKey only when needed (after early exits)\n const lowerKey = key.toLowerCase();\n\n // Cache event handler check (faster than regex for common case)\n if (lowerKey.length > 2 && lowerKey.charCodeAt(0) === 111 && lowerKey.charCodeAt(1) === 110) {\n // 'on'\n return;\n }\n\n if (lowerKey === 'innerhtml') {\n return;\n }\n\n if (next == null) {\n if (isXlink) {\n el.removeAttributeNS(XLINK_NAMESPACE, key.slice(6));\n } else if (isXmlns) {\n const localName = key.slice(6);\n el.removeAttributeNS(XMLNS_NAMESPACE, localName);\n } else {\n el.removeAttribute(key);\n }\n return;\n }\n\n if (isXlink) {\n el.setAttributeNS(XLINK_NAMESPACE, key, String(next));\n return;\n }\n\n if (isXmlns) {\n el.setAttributeNS(XMLNS_NAMESPACE, key, String(next));\n return;\n }\n\n if (isBoolean) {\n if (includeBooleanAttr(next)) {\n el.setAttribute(key, '');\n } else {\n el.removeAttribute(key);\n }\n return;\n }\n\n const attrValue = isSymbol(next) ? String(next) : next;\n\n const isUrlAttr = lowerKey === 'href' || lowerKey === 'src' || lowerKey === 'xlink:href';\n if (isUrlAttr && isString(attrValue)) {\n const v = attrValue.trim().toLowerCase();\n if (v.startsWith('javascript:') || v.startsWith('data:')) {\n return;\n }\n }\n\n if (elementIsSVG) {\n el.setAttribute(key, String(attrValue));\n } else {\n if (key in el) {\n try {\n el[key] = attrValue;\n } catch {\n el.setAttribute(key, String(attrValue));\n }\n } else {\n el.setAttribute(key, String(attrValue));\n }\n }\n}\n","/**\n * Extended event options with delegation support\n * @public\n */\nexport interface EventOptions extends AddEventListenerOptions {\n /**\n * CSS selector for event delegation\n * When provided, the event will only trigger if the target matches this selector\n */\n delegate?: string;\n}\n\n/**\n * Event handler cleanup function\n * @public\n */\nexport type EventCleanup = () => void;\n\n/**\n * Adds an event listener to an element with optional delegation\n *\n * @param el - The element to attach the event to\n * @param event - The event name (e.g., 'click', 'input')\n * @param handler - The event handler function\n * @param options - Additional event options including delegation\n * @returns A cleanup function to remove the event listener\n * @public\n */\nexport function addEvent(\n el: Element,\n event: string,\n handler: EventListener,\n options?: EventOptions,\n): EventCleanup {\n if (!options?.delegate) {\n el.addEventListener(event, handler, options);\n return () => el.removeEventListener(event, handler, options);\n }\n\n // Delegation path: use simple wrapper\n const selector = options.delegate;\n const wrappedHandler = (e: Event) => {\n const target = e.target as Element;\n if (target.matches(selector) || target.closest(selector)) {\n handler.call(el, e);\n }\n };\n\n // Clean options object by removing delegate property\n const cleanOptions = { ...options };\n cleanOptions.delegate = undefined;\n\n // Add the event listener with the wrapped handler\n el.addEventListener(event, wrappedHandler, cleanOptions);\n\n // Return cleanup function\n return () => {\n el.removeEventListener(event, wrappedHandler, cleanOptions);\n };\n}\n","import { error } from '@estjs/shared';\nimport { FRAGMENT_COMPONENT } from '../constants';\nimport type { AnyNode, ComponentProps } from '../types';\n\nexport interface FragmentProps extends ComponentProps {\n children?: AnyNode | AnyNode[];\n}\n\n/**\n * Fragment component - renders multiple children without wrapper elements (Client-side only)\n *\n * **Client-side behavior:**\n * - Returns children directly for rendering\n * - Hydration system matches children using hydration keys\n * - The template system handles array children automatically\n *\n * @param props - Component props with children\n * @returns Children directly without wrapper\n *\n * @example\n * ```tsx\n * // Basic usage\n * <Fragment>\n * <div>First</div>\n * <span>Second</span>\n * </Fragment>\n *\n * // Nested fragments\n * <Fragment>\n * <Fragment>\n * <div>Nested 1</div>\n * <div>Nested 2</div>\n * </Fragment>\n * <div>Third</div>\n * </Fragment>\n *\n * // Empty fragment (renders nothing)\n * <Fragment />\n * ```\n */\nexport function Fragment(props?: FragmentProps): AnyNode {\n if (__DEV__) {\n if (!props) {\n error('Fragment component requires props');\n return null;\n }\n }\n\n // Handle empty fragment - return null\n if (!props?.children) {\n error('Fragment component requires children');\n return null;\n }\n\n const { children } = props;\n\n // Client-side rendering: Return children directly\n // The template system will handle them appropriately\n return children as AnyNode;\n}\n\nFragment[FRAGMENT_COMPONENT] = true;\n\n/**\n * Check if a node is a Fragment component\n * @param node - Node to check\n * @returns true if node is a Fragment\n */\nexport function isFragment(node: unknown): boolean {\n return !!node && !!node[FRAGMENT_COMPONENT];\n}\n","import { isArray, isString, warn } from '@estjs/shared';\nimport { insertNode } from '../utils/dom';\nimport { normalizeNode } from '../utils/node';\nimport { onMount } from '../lifecycle';\nimport { onCleanup } from '../scope';\nimport { PORTAL_COMPONENT } from '../constants';\nimport type { AnyNode } from '../types';\n\nexport interface PortalProps {\n children?: AnyNode | AnyNode[];\n target: string | HTMLElement;\n key?: string;\n}\n\n/**\n * Portal component - renders children into a different DOM node\n *\n * @param props - Component props with children and target\n * @returns Comment node as placeholder in parent tree\n *\n * @example\n * ```tsx\n * <Portal target=\"#modal-root\">\n * <div>Modal content</div>\n * </Portal>\n */\nexport function Portal(props: PortalProps): Comment | string {\n // Create placeholder comment for parent tree\n const placeholder = document.createComment('portal');\n placeholder[PORTAL_COMPONENT] = true;\n const children = props.children;\n if (children) {\n const childArray = isArray(children) ? children : [children];\n const nodes: (Node | string)[] = [];\n\n onMount(() => {\n // Get target element\n const targetElement = isString(props.target)\n ? document.querySelector(props.target)\n : props.target;\n\n if (!targetElement) {\n if (__DEV__) {\n warn(`[Portal] Target element not found: ${props.target}`);\n }\n return;\n }\n\n childArray.forEach(child => {\n if (child != null) {\n const normalized = normalizeNode(child);\n if (normalized) {\n insertNode(targetElement as Node, normalized);\n nodes.push(normalized);\n }\n }\n });\n\n onCleanup(() => {\n nodes.forEach(node => {\n if (!isString(node) && node.parentNode === targetElement) {\n targetElement.removeChild(node);\n }\n });\n });\n });\n }\n\n return placeholder;\n}\n\nPortal[PORTAL_COMPONENT] = true;\n\n/**\n * Check if a node is a Portal component\n * @param node - Node to check\n * @returns true if node is a Portal\n */\nexport function isPortal(node: unknown): boolean {\n return !!node && !!node[PORTAL_COMPONENT];\n}\n","import { isArray, isPromise, isUndefined, warn } from '@estjs/shared';\nimport { provide } from '../provide';\nimport { isComponent } from '../component';\nimport { normalizeNode } from '../utils/node';\nimport { onDestroy } from '../lifecycle';\nimport { getActiveScope } from '../scope';\nimport { insertNode } from '../utils/dom';\nimport { SUSPENSE_COMPONENT } from '../constants';\nimport type { AnyNode } from '../types';\n\nexport interface SuspenseProps {\n /** The content to render. Can be a Promise for async loading. */\n children?: AnyNode | AnyNode[] | Promise<AnyNode | AnyNode[]>;\n /** Fallback content to display while children is loading (Promise pending). */\n fallback?: AnyNode;\n /** Optional key for reconciliation. */\n key?: string;\n}\n\n/**\n * Suspense component - handles async content with a fallback UI\n *\n * @param props - Component props with children, fallback, and optional key\n * @returns Placeholder node or fallback content\n *\n * @example\n * ```tsx\n * <Suspense fallback={<div>Loading...</div>}>\n * {asyncContent}\n * </Suspense>\n * ```\n */\nexport const SuspenseContext = Symbol('SuspenseContext');\n\nexport interface SuspenseContextType {\n register: (promise: Promise<any>) => void;\n increment: () => void;\n decrement: () => void;\n}\n\n/**\n * Suspense component - handles async content with a fallback UI\n *\n * @param props - Component props with children, fallback, and optional key\n * @returns Placeholder node or fallback content\n *\n * @example\n * ```tsx\n * <Suspense fallback={<div>Loading...</div>}>\n * {asyncContent}\n * </Suspense>\n * ```\n */\nexport function Suspense(props: SuspenseProps): AnyNode {\n // Check if we're in SSR mode (no document)\n if (isUndefined(document)) {\n // In SSR, return fallback as string if available\n const fallback = props.fallback;\n if (fallback) {\n return String(fallback || '');\n }\n return '';\n }\n\n // Create a container to manage content swapping\n const container = document.createElement('div');\n container.style.display = 'contents'; // Invisible wrapper\n\n // Track if component is still mounted (for async cleanup)\n let isMounted = true;\n let pendingCount = 0;\n let isShowingFallback = false;\n\n let resolvedChildren: AnyNode | AnyNode[] | null = null;\n\n const showFallback = () => {\n if (isShowingFallback) return;\n isShowingFallback = true;\n\n // Clear container\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n if (props.fallback != null) {\n const normalized = normalizeNode(props.fallback);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n };\n\n const showChildren = () => {\n if (!isShowingFallback) return;\n\n // Check if we have something to show\n // If children is a promise, we need resolvedChildren.\n // If children is not a promise, we use it directly.\n const hasContent = resolvedChildren || (props.children != null && !isPromise(props.children));\n\n if (!hasContent) {\n // If we don't have content (e.g. promise rejected), keep fallback\n return;\n }\n\n isShowingFallback = false;\n\n // Clear container (remove fallback)\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n // Simple implementation: Re-render children\n if (resolvedChildren) {\n renderChildren(resolvedChildren);\n } else if (props.children != null && !isPromise(props.children)) {\n renderChildren(props.children);\n }\n };\n\n /**\n * Render children into the container\n */\n const renderChildren = (children: AnyNode | AnyNode[]): void => {\n // Clear existing content\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n if (children == null) return;\n\n const currentScope = getActiveScope();\n const childArray = isArray(children) ? children : [children];\n childArray.forEach(child => {\n if (child != null) {\n // Reparent component to current context to ensure it can access SuspenseContext\n // This is necessary because children are created in the parent scope\n if (isComponent(child)) {\n // @ts-ignore\n child.parentContext = currentScope;\n }\n\n const normalized = normalizeNode(child);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n });\n\n // Fix: If a child suspended during insertion, we might have both fallback and children in the container.\n // We need to ensure that if we are in fallback mode, only fallback is shown.\n if (isShowingFallback) {\n // We are in fallback mode.\n // Clear everything (including the just-inserted children)\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n // Re-insert fallback\n if (props.fallback != null) {\n const normalized = normalizeNode(props.fallback);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n }\n };\n\n // Context for resources to register themselves\n const suspenseContext: SuspenseContextType = {\n register: (promise: Promise<any>) => {\n pendingCount++;\n showFallback();\n\n promise\n .then(() => {\n if (!isMounted) return;\n pendingCount--;\n if (pendingCount === 0) {\n showChildren();\n }\n })\n .catch(error => {\n if (__DEV__) {\n warn('[Suspense] Resource failed:', error);\n }\n if (!isMounted) return;\n pendingCount--;\n // For now, if error happens, we still try to show children (or maybe error boundary later)\n if (pendingCount === 0) {\n showChildren();\n }\n });\n },\n increment: () => {\n pendingCount++;\n showFallback();\n },\n decrement: () => {\n pendingCount--;\n if (pendingCount === 0) {\n showChildren();\n }\n },\n };\n\n provide(SuspenseContext, suspenseContext);\n\n const children = props.children;\n\n // Initial render logic\n if (isPromise(children)) {\n // Async children - show fallback immediately, then resolve\n children\n .then(resolved => {\n resolvedChildren = resolved;\n })\n .catch(() => {\n // Ignore error, handled by register\n });\n suspenseContext.register(children);\n } else if (children != null) {\n // Sync children - render immediately\n // If any child is a resource read, it will call register() synchronously during this render\n renderChildren(children);\n } else {\n // No children - show fallback if available\n showFallback();\n }\n\n onDestroy(() => {\n isMounted = false;\n // Clear container\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n });\n\n return container;\n}\n\nSuspense[SUSPENSE_COMPONENT] = true;\n\n/**\n * Check if a node is a Suspense component\n * @param node - Node to check\n * @returns true if node is a Suspense\n */\nexport function isSuspense(node: unknown): boolean {\n return !!node && !!node[SUSPENSE_COMPONENT];\n}\n","import { type Signal, signal } from '@estjs/signals';\nimport { inject } from '../provide';\nimport { SuspenseContext } from './Suspense';\n\nexport type ResourceState = 'pending' | 'ready' | 'errored';\n\nexport interface Resource<T> {\n (): T | undefined;\n loading: Signal<boolean>;\n error: Signal<Error | null>;\n state: Signal<ResourceState>;\n}\n\nexport interface ResourceActions<T> {\n mutate: (value: T) => void;\n refetch: () => Promise<void>;\n}\n\nexport interface ResourceOptions<T> {\n initialValue?: T;\n}\n\n/**\n * Create a resource for async data fetching\n * Inspired by SolidJS createResource\n *\n * @param fetcher - Function that returns a Promise with the data\n * @param options - Optional configuration\n * @returns Tuple of [resource, actions]\n *\n * @example\n * ```typescript\n * const [data, { refetch, mutate }] = createResource(\n * () => fetch('/api/user').then(r => r.json()),\n * { initialValue: null }\n * );\n *\n * // Access data\n * console.log(data());\n * console.log(data.loading.value);\n * console.log(data.state.value);\n *\n * // Refetch data\n * await refetch();\n *\n * // Update data directly\n * mutate({ name: 'John' });\n * ```\n */\nexport function createResource<T>(\n fetcher: () => Promise<T>,\n options?: ResourceOptions<T>,\n): [Resource<T>, ResourceActions<T>] {\n // Internal state\n const value = signal<T | undefined>(options?.initialValue);\n const loading = signal<boolean>(true);\n const error = signal<Error | null>(null);\n const state = signal<ResourceState>('pending');\n\n let fetchId = 0;\n\n let currentPromise: Promise<void> | null = null;\n\n // Fetch function\n const fetch = async (): Promise<void> => {\n const currentFetchId = ++fetchId;\n loading.value = true;\n state.value = 'pending';\n error.value = null;\n\n try {\n const promise = fetcher();\n currentPromise = promise.then(() => {}).catch(() => {}); // Ensure promise is handled\n const result = await promise;\n\n // Only update if this is still the latest fetch\n if (currentFetchId === fetchId) {\n value.value = result;\n state.value = 'ready';\n loading.value = false;\n }\n } catch (error_) {\n // Only update if this is still the latest fetch\n if (currentFetchId === fetchId) {\n error.value = error_ instanceof Error ? error_ : new Error(String(error_));\n state.value = 'errored';\n loading.value = false;\n }\n }\n };\n\n // Start initial fetch\n fetch();\n\n // Resource accessor function\n const resource = (() => {\n // If we are loading and have a suspense context, register the promise\n if (loading.value && currentPromise) {\n const suspenseContext = inject(SuspenseContext, null);\n if (suspenseContext) {\n // @ts-ignore\n suspenseContext.register(currentPromise);\n }\n }\n return value.value;\n }) as Resource<T>;\n resource.loading = loading;\n resource.error = error;\n resource.state = state;\n\n // Actions\n const actions: ResourceActions<T> = {\n mutate: (newValue: T) => {\n value.value = newValue;\n state.value = 'ready';\n loading.value = false;\n error.value = null;\n },\n refetch: async () => {\n await fetch();\n },\n };\n\n return [resource, actions];\n}\n","import { type Signal, isSignal, memoEffect, untrack } from '@estjs/signals';\nimport {\n type Scope,\n createScope,\n disposeScope,\n getActiveScope,\n onCleanup,\n setActiveScope,\n} from '../scope';\nimport { isComponent } from '../component';\nimport { FOR_COMPONENT } from '../constants';\nimport type { AnyNode } from '../types';\n\nexport interface ForProps<T> {\n each: T[] | Signal<T[]> | (() => T[]);\n children: (item: T, index: number) => AnyNode;\n keyFn?: (item: T) => unknown;\n fallback?: () => AnyNode;\n}\n\ninterface ItemEntry {\n key: unknown;\n node: Node;\n scope: Scope; // Track scope for cleanup\n}\n\n/**\n * Optimized For Component\n * - Uses createDetachedScope to avoid parent.children Set overhead (SolidJS style)\n * - Uses DocumentFragment batching for mass creation\n * - Inlines scope switching for performance\n */\nexport function For<T>(props: ForProps<T>): Node {\n const fragment = document.createDocumentFragment();\n const marker = document.createComment('');\n fragment.appendChild(marker);\n\n let entries: ItemEntry[] = [];\n let fallbackNode: Node | null = null;\n\n const keyFn = props.keyFn;\n const renderFn = props.children;\n\n const getList = (): T[] => {\n const input = props.each;\n if (isSignal(input)) return (input as Signal<T[]>).value ?? [];\n if (typeof input === 'function') return (input as () => T[])() ?? [];\n return (input as T[]) ?? [];\n };\n\n const getKey = (item: T): unknown => (keyFn ? keyFn(item) : item);\n\n /**\n * Render item with detached scope.\n */\n const renderItem = (item: T, index: number, parent: Node, before: Node | null): ItemEntry => {\n const prevScope = getActiveScope();\n\n const scope = createScope(prevScope);\n\n setActiveScope(scope);\n\n let node: AnyNode;\n try {\n const result = renderFn(item, index);\n if (isComponent(result)) {\n result.mount(parent, before as Node); // Cast null to Node is okay for beforeNode? mount expects Node|undefined\n node = result.firstChild ?? document.createComment('empty');\n } else {\n node = result as Node;\n // Insert node manually if not handled by Component.mount\n if (!node.parentNode) {\n if (before) {\n parent.insertBefore(node, before);\n } else {\n parent.appendChild(node);\n }\n }\n }\n } finally {\n setActiveScope(prevScope);\n }\n\n return { key: getKey(item), node: node! as Node, scope };\n };\n\n const disposeItem = (entry: ItemEntry) => {\n disposeScope(entry.scope);\n if (entry.node.parentNode) {\n entry.node.parentNode.removeChild(entry.node);\n }\n };\n\n memoEffect(\n ({ prev }) => {\n const newItems = getList();\n\n if (prev === newItems) return { prev: newItems };\n\n const parent = marker.parentNode;\n\n // Initial mount (parent is null because fragment is not attached yet)\n if (!parent) {\n if (newItems.length === 0) {\n if (props.fallback) {\n const fb = props.fallback();\n if (isComponent(fb)) {\n fb.mount(fragment, marker);\n fallbackNode = fb.firstChild ?? document.createComment('empty');\n } else {\n fallbackNode = fb as Node;\n fragment.insertBefore(fallbackNode, marker);\n }\n }\n return { prev: newItems };\n }\n\n entries = new Array(newItems.length);\n\n for (const [i, newItem] of newItems.entries()) {\n entries[i] = renderItem(newItem, i, fragment, marker);\n }\n return { prev: newItems };\n }\n\n untrack(() => reconcile(parent, newItems));\n return { prev: newItems };\n },\n {\n prev: [] as T[],\n },\n );\n\n function reconcile(parent: Node, newItems: T[]): void {\n const oldLen = entries.length;\n const newLen = newItems.length;\n\n // ===== FAST PATH 1: Clear all =====\n if (newLen === 0) {\n for (let i = 0; i < oldLen; i++) {\n disposeItem(entries[i]);\n }\n entries = [];\n\n if (props.fallback && !fallbackNode) {\n const fb = props.fallback();\n if (isComponent(fb)) {\n fb.mount(parent, marker);\n fallbackNode = fb.firstChild ?? document.createComment('empty');\n } else {\n fallbackNode = fb as Node;\n parent.insertBefore(fallbackNode, marker);\n }\n }\n return;\n }\n\n // ===== FAST PATH 2: Create all (from empty/fallback) =====\n if (oldLen === 0 || fallbackNode) {\n if (fallbackNode) {\n if (fallbackNode.parentNode) fallbackNode.parentNode.removeChild(fallbackNode);\n fallbackNode = null;\n }\n\n entries = new Array(newLen);\n\n // Batch creation in fragment\n const batchFragment = document.createDocumentFragment();\n\n for (let i = 0; i < newLen; i++) {\n // Render to batchFragment, append to end (before=null)\n entries[i] = renderItem(newItems[i], i, batchFragment, null);\n }\n\n parent.insertBefore(batchFragment, marker);\n return;\n }\n\n // ===== Keyed reconciliation =====\n const oldKeyMap = new Map<unknown, ItemEntry[]>();\n for (let i = 0; i < oldLen; i++) {\n const entry = entries[i];\n const list = oldKeyMap.get(entry.key);\n if (list) {\n list.push(entry);\n } else {\n oldKeyMap.set(entry.key, [entry]);\n }\n }\n\n const newEntries: ItemEntry[] = new Array(newLen);\n const toRemove: ItemEntry[] = [];\n\n // Batch new nodes in fragment\n const batchFragment = document.createDocumentFragment();\n\n for (let i = 0; i < newLen; i++) {\n const item = newItems[i];\n const key = getKey(item);\n const oldList = oldKeyMap.get(key);\n\n if (oldList && oldList.length > 0) {\n newEntries[i] = oldList.shift()!;\n } else {\n newEntries[i] = renderItem(item, i, batchFragment, null);\n }\n }\n\n for (const list of oldKeyMap.values()) {\n for (const entry of list) {\n toRemove.push(entry);\n }\n }\n\n for (const entry of toRemove) {\n disposeItem(entry);\n }\n\n // Efficient Reorder\n // If we have new nodes in batchFragment, they are not yet in DOM.\n // Existing nodes are in DOM.\n // We iterate 0..newLen.\n // If node is in batchFragment, we must insert it.\n // If node is in DOM, we check order.\n\n for (let i = 0; i < newLen; i++) {\n const node = newEntries[i].node;\n parent.insertBefore(node, marker);\n }\n\n entries = newEntries;\n }\n\n onCleanup(() => {\n for (const entry of entries) {\n disposeItem(entry);\n }\n if (fallbackNode && fallbackNode.parentNode) {\n fallbackNode.parentNode.removeChild(fallbackNode);\n }\n if (marker.parentNode) {\n marker.parentNode.removeChild(marker);\n }\n });\n\n return fragment;\n}\n\nFor[FOR_COMPONENT] = true;\n\nexport function isFor(node: unknown): boolean {\n return !!node && !!(node as Record<symbol, boolean>)[FOR_COMPONENT];\n}\n"]}
1
+ {"version":3,"sources":["../src/lifecycle.ts","../src/scope.ts","../src/constants.ts","../src/key.ts","../src/utils/node.ts","../src/utils/dom.ts","../src/patch.ts","../src/binding.ts","../src/component.ts","../src/renderer.ts","../src/provide.ts","../src/events.ts","../src/utils/props.ts","../src/hydration/shared.ts","../src/hydration/hydration.ts","../src/operations/class.ts","../src/operations/styles.ts","../src/operations/attr.ts","../src/operations/event.ts","../src/components/Fragment.ts","../src/components/Portal.ts","../src/components/Suspense.ts","../src/components/createResource.ts","../src/components/For.ts"],"names":["scopeId","isPromise","error","_a","isFalsy","isString","warn","isNumber","isSymbol","isHTMLElement","isPrimitive","isNull","isObject","isArray","beforeNode","isTextNode","j","isHtmlInputElement","isHtmlSelectElement","isHtmlTextAreaElement","effect","isFunction","coerceArray","template","shallowReactive","isSignal","isComputed","hasChanged","startsWith","document","isBrowser","normalizeClassName","camelCase","capitalize","isSpecialBooleanAttr","isBooleanAttr","includeBooleanAttr","isUndefined","children","signal","memoEffect","untrack","batchFragment"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,IAAM,SAAA,GAAY;AAAA,EACvB,KAAA,EAAO,OAAA;AAAA,EACP,OAAA,EAAS,SAAA;AAAA,EACT,MAAA,EAAQ;AACV,CAAA;AAmBA,SAAS,kBAAA,CACP,KAAA,EACA,OAAA,EACA,IAAA,EACM;AACN,EAAA,IAAI,QAAA,GAAW,MAAM,OAAO,CAAA;AAC5B,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,QAAA,GAAW,KAAA,CAAM,OAAO,CAAA,GAAI,EAAC;AAAA,EAC/B;AAGA,EAAA,IAAI,CAAC,QAAA,CAAS,QAAA,CAAS,IAAI,CAAA,EAAG;AAC5B,IAAA,QAAA,CAAS,KAAK,IAAI,CA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AAA,CAAa,MAAM,MAAM,CAAA;AAAA,IAClC;AAEA,IAAA,OAAA,GAAU,UAAA;AAAA,EACZ;AAEA,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,MAAA,WAAA,CAAY,KAAK,CAAA;AAAA,IACnB;AACA,IAAA,IAAI,YAAA,IAAgB,aAAa,UAAA,EAAY;AAC3C,MAAA,YAAA,CAAa,UAAA,CAAW,YAAY,YAAY,CAAA;AAAA,IAClD;AACA,IAAA,IAAI,OAAO,UAAA,EAAY;AACrB,MAAA,MAAA,CAAO,UAAA,CAAW,YAAY,MAAM,CAAA;AAAA,IACtC;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,QAAA;AACT;AAEA,GAAA,CAAI,aAAa,CAAA,GAAI,IAAA","file":"template.dev.cjs.js","sourcesContent":["import { error, isPromise } from '@estjs/shared';\nimport { type Scope, getActiveScope, runWithScope } from './scope';\n\n/**\n * Lifecycle hook type: returns void or a Promise that resolves when complete.\n * Hooks can perform cleanup by returning a cleanup function.\n */\nexport type LifecycleHook = () => void | Promise<void>;\n\n/**\n * Lifecycle phases enumeration.\n * - mount: Initial render and component setup\n * - update: Re-render after props or state changes\n * - destroy: Cleanup before scope disposal\n */\nexport const LIFECYCLE = {\n mount: 'mount',\n destroy: 'destroy',\n update: 'update',\n} as const;\n\nexport type LifecycleType = (typeof LIFECYCLE)[keyof typeof LIFECYCLE];\n\n/**\n * Lifecycle hooks registry type.\n * Maps lifecycle phases to arrays of registered hooks.\n */\nexport type LifecycleHooks = {\n [key in LifecycleType]: LifecycleHook[];\n};\n\n/**\n * Register a hook into a scope's lifecycle list.\n * Lazily initializes the hook list if not already present.\n * Prevents duplicate registration of the same hook function.\n *\n * @internal\n */\nfunction registerScopedHook(\n scope: Scope,\n listKey: 'onMount' | 'onUpdate' | 'onDestroy',\n hook: LifecycleHook,\n): void {\n let hookList = scope[listKey];\n if (!hookList) {\n hookList = scope[listKey] = [];\n }\n // Prevent duplicate registration of the same hook function\n // This is important when component function is re-executed in forceUpdate\n if (!hookList.includes(hook)) {\n hookList.push(hook);\n }\n}\n\n/**\n * Execute an array of lifecycle hooks, collecting async results.\n * Errors in individual hooks don't prevent others from executing.\n *\n * @internal\n */\nfunction executeHooks(\n hooks: LifecycleHook[],\n scopeId: number,\n phase: 'mount' | 'update' | 'destroy',\n): void | Promise<void> {\n const len = hooks.length;\n if (len === 0) return;\n\n let pending: Promise<void>[] | undefined;\n\n for (let i = 0; i < len; i++) {\n try {\n const result = hooks[i]();\n if (isPromise(result)) {\n const safePromise = result.catch(error_ => {\n if (__DEV__) {\n error(`Scope(${scopeId}): Async ${phase} hook rejected:`, error_);\n }\n });\n (pending ?? (pending = [])).push(safePromise);\n }\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scopeId}): Error in ${phase} hook:`, error_);\n }\n }\n }\n\n if (!pending) return;\n return Promise.all(pending).then(() => undefined);\n}\n\n/**\n * Register a mount lifecycle hook.\n * Runs after component is mounted and virtual tree is committed.\n * If the scope is already mounted, the hook executes immediately.\n *\n * @throws Error in dev mode if called outside a scope\n * @example\n * ```tsx\n * onMount(() => {\n * console.log('Component mounted');\n * return () => console.log('Cleanup');\n * });\n * ```\n */\nexport function onMount(hook: LifecycleHook): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) error('onMount() must be called within a scope');\n return;\n }\n\n if (scope.isMounted) {\n // Scope already mounted, execute immediately\n try {\n const result = hook();\n if (isPromise(result)) {\n result.catch(error_ => {\n if (__DEV__) error(`Scope(${scope.id}): Async ${LIFECYCLE.mount} hook rejected:`, error_);\n });\n }\n } catch (error_) {\n if (__DEV__) error(`Scope(${scope.id}): Error in ${LIFECYCLE.mount} hook:`, error_);\n }\n return;\n }\n\n registerScopedHook(scope, 'onMount', hook);\n}\n\n/**\n * Register an update lifecycle hook.\n * Runs whenever the component re-renders due to prop or state changes.\n *\n * @throws Error in dev mode if called outside a scope\n * @example\n * ```tsx\n * onUpdate(() => {\n * console.log('Component updated');\n * });\n * ```\n */\nexport function onUpdate(hook: LifecycleHook): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) error('onUpdate() must be called within a scope');\n return;\n }\n\n registerScopedHook(scope, 'onUpdate', hook);\n}\n\n/**\n * Register a destroy lifecycle hook.\n * Runs before scope is disposed and resources are cleaned up.\n * Perfect for resetting external state, unsubscribing from events, etc.\n *\n * @throws Error in dev mode if called outside a scope\n * @example\n * ```tsx\n * onDestroy(() => {\n * unsubscribe();\n * clearTimeout(timerId);\n * });\n * ```\n */\nexport function onDestroy(hook: LifecycleHook): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) error('onDestroy() must be called within a scope');\n return;\n }\n\n registerScopedHook(scope, 'onDestroy', hook);\n}\n\n/**\n * Trigger all mount hooks registered in a scope.\n * Clears the hook list after execution and marks scope as mounted.\n *\n * @internal\n */\nexport function triggerMountHooks(scope: Scope): void | Promise<void> {\n if (scope.isDestroyed || !scope.onMount?.length) {\n scope.isMounted = true;\n return;\n }\n\n const mountHooks = scope.onMount;\n const result = runWithScope(scope, () => executeHooks(mountHooks, scope.id, LIFECYCLE.mount));\n mountHooks.length = 0; // Clear for garbage collection\n scope.isMounted = true;\n return result;\n}\n\n/**\n * Trigger all update hooks registered in a scope.\n * Clears the hook list after execution to prevent re-execution on next update.\n *\n * @internal\n */\nexport function triggerUpdateHooks(scope: Scope): void | Promise<void> {\n if (scope.isDestroyed || !scope.onUpdate?.length) return;\n const updateHooks = scope.onUpdate;\n const result = runWithScope(scope, () => executeHooks(updateHooks, scope.id, 'update'));\n updateHooks.length = 0; // Clear for next update cycle\n return result;\n}\n\n/**\n * Trigger all destroy hooks registered in a scope.\n * Hooks are executed in the scope context before resources are freed.\n *\n * @internal\n */\nexport function triggerDestroyHooks(scope: Scope): void | Promise<void> {\n if (scope.isDestroyed || !scope.onDestroy?.length) return;\n return runWithScope(scope, () => executeHooks(scope.onDestroy!, scope.id, 'destroy'));\n}\n","import { error } from '@estjs/shared';\nimport { triggerDestroyHooks } from './lifecycle';\nimport type { InjectionKey } from './provide';\n\nexport interface Scope {\n /// Unique identifier for debugging and tracking scope lifetime\n readonly id: number;\n\n // Parent scope in the tree\n parent: Scope | null;\n\n // Child scopes created within this scope\n children: Scope[] | null;\n\n // Provided values map for dependency injection\n provides: Map<InjectionKey<unknown> | string | number | symbol, unknown> | null;\n\n // Set of cleanup functions to run on scope disposal\n cleanup: (() => void)[] | null;\n\n // Mount lifecycle hooks - run once after first render\n onMount: (() => void | Promise<void>)[] | null;\n\n // Update lifecycle hooks\n onUpdate: (() => void | Promise<void>)[] | null;\n\n // Destroy lifecycle hooks - run before scope disposal\n onDestroy: (() => void | Promise<void>)[] | null;\n\n // Flag indicating whether the scope has completed its mount phase\n isMounted: boolean;\n\n // Flag indicating whether the scope has been disposed\n isDestroyed: boolean;\n}\n\n// Currently active scope\nlet activeScope: Scope | null = null;\n\n// Scope ID counter for unique identification\nlet scopeId = 0;\n\n/**\n * Get the currently active scope.\n * @returns The active scope or null if none is active\n */\nexport function getActiveScope(): Scope | null {\n return activeScope;\n}\n\n/**\n * Set the active scope (internal use).\n * @param scope - The scope to set as active\n */\nexport function setActiveScope(scope: Scope | null): void {\n activeScope = scope;\n}\n\nexport function createScope(parent: Scope | null = activeScope): Scope {\n const scope: Scope = {\n id: ++scopeId,\n parent,\n children: null,\n provides: null,\n cleanup: null,\n onMount: null,\n onUpdate: null,\n onDestroy: null,\n isMounted: false,\n isDestroyed: false,\n };\n\n // Establish parent-child relationship\n if (parent) {\n if (!parent.children) {\n parent.children = [];\n }\n parent.children.push(scope);\n }\n\n return scope;\n}\n\n/**\n * Run a function within a scope, ensuring proper cleanup.\n * The previous active scope is restored even if the function throws.\n *\n * @param scope - The scope to run within\n * @param fn - The function to execute\n * @returns The return value of the function\n */\nexport function runWithScope<T>(scope: Scope, fn: () => T): T {\n const prevScope = activeScope;\n activeScope = scope;\n\n try {\n return fn();\n } finally {\n // Restore previous scope directly\n activeScope = prevScope;\n }\n}\n\n/**\n * Dispose a scope and recursively dispose all child scopes.\n * Performs the following cleanup in order:\n * 1. Recursively disposes all children (depth-first)\n * 2. Executes destroy lifecycle hooks\n * 3. Executes registered cleanup functions\n * 4. Removes scope from parent's children list\n * 5. Clears all internal collections and resets state\n *\n * Safe to call multiple times (idempotent).\n *\n * @param scope - The scope to dispose\n *\n * @example\n * ```ts\n * const scope = createScope(parent);\n * // ... use scope ...\n * disposeScope(scope); // Cleanup everything\n * ```\n */\nexport function disposeScope(scope: Scope): void {\n // Idempotent: skip if already destroyed\n if (!scope || scope.isDestroyed) {\n return;\n }\n\n const parentScope = scope.parent;\n\n // Recursively dispose children first (depth-first cleanup)\n if (scope.children) {\n for (const child of scope.children) {\n disposeScope(child);\n }\n scope.children.length = 0;\n }\n\n // Execute destroy lifecycle hooks\n if (scope.onDestroy?.length) {\n triggerDestroyHooks(scope);\n scope.onDestroy.length = 0;\n }\n\n // Execute cleanup functions in reverse order\n if (scope.cleanup?.length) {\n for (const fn of scope.cleanup) {\n try {\n fn();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in cleanup:`, error_);\n }\n }\n }\n scope.cleanup.length = 0;\n }\n\n // Step 4: Remove from parent's children array\n if (parentScope?.children) {\n const idx = parentScope.children.indexOf(scope);\n if (idx !== -1) {\n parentScope.children.splice(idx, 1);\n }\n }\n\n // Clear provides map\n scope.provides?.clear();\n\n // Clear mount and update hooks\n if (scope.onMount) scope.onMount.length = 0;\n if (scope.onUpdate) scope.onUpdate.length = 0;\n\n // Clear references to prevent memory leaks\n scope.parent = null;\n scope.isDestroyed = true;\n\n // Restore parent scope context if it was active\n if (activeScope === scope) {\n activeScope = parentScope;\n }\n}\n\n/**\n * Register a cleanup function to be executed when the scope is disposed.\n * Useful for cleaning up timers, subscriptions, event listeners, etc.\n *\n * Cleanup functions are executed in LIFO order (last registered, first executed).\n * Cleanup errors don't prevent other cleanups from running.\n *\n * @param fn - The cleanup function to register\n *\n * @throws Error in dev mode if called outside a scope\n *\n * @example\n * ```ts\n * const timerId = setInterval(() => {}, 1000);\n * onCleanup(() => clearInterval(timerId));\n * ```\n */\nexport function onCleanup(fn: () => void): void {\n const scope = activeScope;\n\n if (!scope) {\n if (__DEV__) {\n error('onCleanup() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize cleanup array\n if (!scope.cleanup) {\n scope.cleanup = [];\n }\n\n scope.cleanup.push(fn);\n}\n","/**\n * event prefix, used to distinguish event handler properties\n */\nexport const EVENT_PREFIX = 'on';\n\n/**\n * update prefix, used to identify update callback properties\n */\nexport const UPDATE_PREFIX = 'update';\n\n/**\n * children property name\n */\nexport const CHILDREN_PROP = 'children';\n/**\n * Key name for the Spread attribute\n */\nexport const SPREAD_NAME = '_$spread$';\n\n/**\n * used to get the DOM element reference\n */\nexport const REF_KEY = 'ref';\n/**\n * Component key property name\n */\nexport const KEY_PROP = 'key' as const;\n\n/**\n * SVG namespace constant\n */\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\n/**\n * XML namespace for xlink attributes\n */\nexport const XLINK_NAMESPACE = 'http://www.w3.org/2000/xlink';\n\n/**\n * xmlns namespace for SVG elements\n */\nexport const XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/';\n\n/**\n * Defines various states of components for state management and debugging\n */\nexport enum COMPONENT_STATE {\n /** Initial state */\n INITIAL,\n /** Mounting */\n MOUNTING,\n /** MOUNTED */\n MOUNTED,\n /** Updating */\n UPDATING,\n /** Destroying */\n DESTROYING,\n /** destroy */\n DESTROYED,\n}\n\nexport const NORMAL_COMPONENT = Symbol(__DEV__ ? 'Normal Component' : '');\nexport const FRAGMENT_COMPONENT = Symbol(__DEV__ ? 'Fragment Component' : '');\nexport const PORTAL_COMPONENT = Symbol(__DEV__ ? 'Portal Component' : '');\nexport const SUSPENSE_COMPONENT = Symbol(__DEV__ ? 'Suspense Component' : '');\nexport const FOR_COMPONENT = Symbol(__DEV__ ? 'For Component' : '');\n","import { error, isFalsy, isHTMLElement, isNumber, isString, isSymbol, warn } from '@estjs/shared';\nimport { isComponent } from './component';\nimport type { AnyNode } from './types';\n\n/** Maximum allowed key length before truncation */\nconst MAX_KEY_LENGTH = 1000;\n\nexport type NodeKey = string | number | symbol;\n\n/** Cache for component type key prefixes */\nconst componentKeyPrefixCache = new WeakMap<Function, string>();\n\n/**\n * Generates a stable key prefix for a component type.\n *\n * @param type - The component function\n * @returns The generated key prefix\n */\nexport function getComponentKey(type: Function): string {\n let prefix = componentKeyPrefixCache.get(type);\n if (!prefix) {\n const name = type.name || 'anonymous';\n const hash = simpleHash(type.toString()).toString(36);\n prefix = `${name}_${hash}`;\n componentKeyPrefixCache.set(type, prefix);\n }\n return prefix;\n}\n\n/**\n * DJB2 hash variant - fast string hashing.\n * Limited to first 100 chars for performance.\n *\n * @param str - The input string\n * @returns The hash code (always positive)\n */\nfunction simpleHash(str: string): number {\n let hash = 0;\n const len = str.length < 100 ? str.length : 100;\n for (let i = 0; i < len; i++) {\n hash = Math.trunc((hash << 5) - hash + str.charCodeAt(i));\n }\n return hash < 0 ? -hash : hash;\n}\n\n/** Counter for generating unique IDs for local symbols */\nlet symbolIdCounter = 0;\n\n/**\n * Normalize any key value to a string.\n *\n * @param key - The key value to normalize\n * @returns Normalized string key or undefined for null/undefined\n */\nexport function normalizeKey(key: any): string | undefined {\n if (isFalsy(key)) {\n return undefined;\n }\n\n if (isString(key)) {\n if (key.length <= MAX_KEY_LENGTH) {\n return key;\n }\n if (__DEV__) {\n warn(\n `[Key System] Key length exceeds ${MAX_KEY_LENGTH} characters. ` +\n 'Consider using a shorter identifier.',\n );\n }\n return `${key.slice(0, MAX_KEY_LENGTH - 10)}_${simpleHash(key).toString(36)}`;\n }\n\n if (isNumber(key)) {\n if (__DEV__) {\n if (key !== key) {\n warn('[Key System] NaN cannot be used as a key');\n return undefined;\n }\n if (!Number.isFinite(key)) {\n warn('[Key System] Infinity cannot be used as a key');\n return undefined;\n }\n }\n return String(key);\n }\n\n // Symbol path\n if (isSymbol(key)) {\n const globalKey = Symbol.keyFor(key);\n if (globalKey) {\n return `_s.${globalKey}`;\n }\n const desc = key.description;\n return desc ? `_s.${desc}` : `${symbolIdCounter++}`;\n }\n\n return String(key);\n}\n\n/**\n * Check if two nodes have the same type for reconciliation.\n *\n * @param a - First node\n * @param b - Second node\n * @returns True if nodes are the same type\n */\nexport function isSameNodeType(a: AnyNode, b: AnyNode): boolean {\n const aIsComponent = isComponent(a);\n const bIsComponent = isComponent(b);\n\n // Both components - compare component function\n if (aIsComponent && bIsComponent) {\n return a.component === b.component;\n }\n\n // Both DOM nodes - compare nodeType and tagName\n const aNode = a as Node;\n const bNode = b as Node;\n\n return (\n aNode.nodeType === bNode.nodeType &&\n (aNode.nodeType !== Node.ELEMENT_NODE ||\n (aNode as Element).tagName === (bNode as Element).tagName)\n );\n}\n\n/** Symbol for storing keys on DOM nodes */\nconst NODE_KEY_SYMBOL = Symbol('essor.key');\n\n/**\n * Set a key on a DOM node using Symbol property.\n * Symbol properties are ~40% faster than WeakMap access.\n *\n * @param node - The node to set key on\n * @param key - The key value (will be normalized)\n */\nexport function setNodeKey(node: AnyNode, key: NodeKey | undefined): void {\n // Skip components - they manage their own keys\n if (isComponent(node)) {\n return;\n }\n\n // Validate node\n if (!node || (node as Node).nodeType === Node.DOCUMENT_NODE) {\n if (__DEV__) {\n warn('[Key System] Cannot set key on invalid node');\n }\n return;\n }\n\n const normalizedKey = normalizeKey(key);\n if (isFalsy(normalizedKey)) {\n delete node[NODE_KEY_SYMBOL];\n } else {\n node[NODE_KEY_SYMBOL] = normalizedKey;\n }\n}\n\n/**\n * Get the key from a node or component.\n *\n * @param node - The node to get key from\n * @returns The key string or undefined\n */\nexport function getNodeKey(node: AnyNode): string | undefined {\n if (!node) return undefined;\n return isComponent(node) ? node.key : node[NODE_KEY_SYMBOL];\n}\n\n/**\n * Get node's key or return an index-based fallback.\n * Fallback keys start with '.' to distinguish from user keys.\n *\n * @param node - The node to get key from\n * @param fallbackIndex - Index to use if no key exists\n * @returns The key or fallback string\n */\nexport function getKeyOrFallback(node: AnyNode, fallbackIndex: number): string {\n return getNodeKey(node) || `.${fallbackIndex}`;\n}\n\n/**\n * Validate that child keys are unique (Development only).\n * Logs errors for duplicate keys to help debugging.\n *\n * @param children - Array of child nodes\n * @param parent - Optional parent node for error context\n */\nexport function validateKeys(children: AnyNode[], parent?: Node): void {\n if (!__DEV__) return;\n\n const keySet = new Set<string>();\n const duplicates: string[] = [];\n const len = children.length;\n\n for (let i = 0; i < len; i++) {\n const key = getKeyOrFallback(children[i], i);\n\n // Skip auto-generated fallback keys (start with '.')\n if (key[0] === '.') continue;\n\n if (keySet.has(key)) {\n duplicates.push(key);\n } else {\n keySet.add(key);\n }\n }\n\n if (duplicates.length > 0) {\n const parentTag = isHTMLElement(parent) ? parent.tagName.toLowerCase() : 'unknown';\n error(\n `Duplicate keys detected in <${parentTag}>: [${duplicates.join(', ')}]\\n` +\n 'Keys must be unique among siblings.',\n );\n }\n}\n","/**\n * Node normalization and comparison utilities\n */\n\nimport {\n isArray,\n isFalsy,\n isHTMLElement,\n isNull,\n isObject,\n isPrimitive,\n isTextNode,\n} from '@estjs/shared';\nimport { isComponent } from '../component';\nimport { getNodeKey } from '../key';\nimport type { AnyNode } from '../types';\n\n/**\n * Normalize node for reconciliation\n * Converts primitives to text nodes\n *\n * @param node - Node to normalize\n * @returns Normalized DOM node\n */\nexport function normalizeNode(node: unknown): Node {\n // Already a Node\n if (isHTMLElement(node)) {\n return node;\n }\n\n // Handle primitives - convert to text nodes\n if (isPrimitive(node)) {\n const textContent = isFalsy(node) ? '' : String(node);\n return document.createTextNode(textContent);\n }\n\n return node as Node;\n}\n\n/**\n * Check if two nodes are the same (for reconciliation)\n * Combines key check and type check\n *\n * @param a - First node\n * @param b - Second node\n * @returns true if nodes are considered the same\n */\nexport function isSameNode(a: AnyNode, b: AnyNode): boolean {\n // Check key equality first (fast path)\n const keyA = getNodeKey(a);\n const keyB = getNodeKey(b);\n\n if (keyA !== keyB) {\n return false;\n }\n\n // Inline type check to avoid function call\n const aIsComponent = isComponent(a);\n const bIsComponent = isComponent(b);\n\n if (aIsComponent && bIsComponent) {\n return a.component === b.component;\n }\n\n if (aIsComponent !== bIsComponent) {\n return false;\n }\n\n if (isPrimitive(a) || isPrimitive(b)) {\n return a === b;\n }\n\n const aNode = a as Node;\n const bNode = b as Node;\n\n if (aNode.nodeType !== bNode.nodeType) {\n return false;\n }\n\n if (aNode.nodeType === Node.ELEMENT_NODE) {\n return (aNode as Element).tagName === (bNode as Element).tagName;\n }\n\n return true;\n}\n\n/**\n * Check if a value is a Text node\n * Re-exported from shared for convenience\n */\nexport function isHtmlTextElement(val: unknown): val is Text {\n return isTextNode(val);\n}\n\n/**\n * Shallow compare two objects or arrays\n * Performs strict equality check on top-level properties\n *\n * @param a - First value to compare\n * @param b - Second value to compare\n * @returns true if values are shallowly equal\n */\nexport function shallowCompare(a: unknown, b: unknown): boolean {\n // Fast path: strict equality\n if (a === b) return true;\n\n // Null/undefined check\n if (isNull(a) || isNull(b)) return false;\n\n // Type guard: both must be objects\n if (!isObject(a) || !isObject(b)) return false;\n\n // Array type consistency check\n if (isArray(a) !== isArray(b)) return false;\n\n // Type guard for record-like objects\n const aRecord = a as Record<string, unknown>;\n const bRecord = b as Record<string, unknown>;\n\n // Fast path: check key count first\n const aKeys = Object.keys(aRecord);\n const bKeys = Object.keys(bRecord);\n if (aKeys.length !== bKeys.length) return false;\n\n // Single pass: check all keys and values\n for (const key of aKeys) {\n if (!(key in bRecord) || aRecord[key] !== bRecord[key]) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * DOM manipulation utilities\n */\n\nimport { isPrimitive } from '@estjs/shared';\nimport { isComponent } from '../component';\nimport type { AnyNode } from '../types';\n\n/**\n * Remove node from its parent\n *\n * @param node - Node to remove\n */\nexport function removeNode(node: AnyNode): void {\n if (!node) return;\n\n if (isComponent(node)) {\n node.destroy();\n return;\n }\n\n const element = node as Element;\n if (element.parentElement) {\n element.remove();\n }\n}\n\n/**\n * Insert child node into parent\n * Handles both component nodes and DOM nodes\n *\n * @param parent - Parent node\n * @param child - Child node to insert\n * @param before - Reference node for insertion position\n */\nexport function insertNode(parent: Node, child: AnyNode, before?: AnyNode): void {\n if (!parent || !child) return;\n\n if (isComponent(child)) {\n const beforeNode = isComponent(before) ? before.firstChild : (before as Node);\n child.mount(parent, beforeNode);\n return;\n }\n\n const beforeNode = isComponent(before) ? before.firstChild : (before as Node);\n\n if (beforeNode) {\n parent.insertBefore(child as Node, beforeNode);\n } else {\n parent.appendChild(child as Node);\n }\n}\n\n/**\n * Replace child node with a new node\n * Handles both component nodes and DOM nodes\n *\n * @param parent - Parent node\n * @param newNode - New node to insert\n * @param oldNode - Old node to be replaced\n */\nexport function replaceNode(parent: Node, newNode: AnyNode, oldNode: AnyNode): void {\n if (!parent || !newNode || !oldNode || newNode === oldNode) return;\n\n const beforeNode: AnyNode | undefined = isComponent(oldNode)\n ? oldNode.beforeNode\n : (oldNode as Node).nextSibling!;\n removeNode(oldNode);\n insertNode(parent, newNode, beforeNode);\n}\n\n/**\n * Get the first DOM node from a node or component\n *\n * @param node - Node or component\n * @returns The first DOM node or undefined\n */\nexport function getFirstDOMNode(node: AnyNode): Node | undefined {\n if (!node) {\n return;\n }\n\n if (isComponent(node)) {\n return node.firstChild;\n }\n\n if (isPrimitive(node)) {\n return undefined;\n }\n\n return node as Node;\n}\n","import { isHTMLElement, isTextNode } from '@estjs/shared';\nimport { isComponent } from './component';\nimport { getNodeKey, setNodeKey } from './key';\nimport { getFirstDOMNode, insertNode, removeNode, replaceNode } from './utils/dom';\nimport { isSameNode } from './utils/node';\n\nimport type { AnyNode } from './types';\n\n/**\n * Transfer key from old node to new node if new node doesn't have one.\n * Skips component nodes as they manage their own keys.\n *\n * @param oldNode - Source node to transfer key from\n * @param newNode - Target node to receive key\n */\nexport function transferKey(oldNode: AnyNode, newNode: AnyNode): void {\n // Components manage their own keys, skip them\n if (isComponent(oldNode) || isComponent(newNode)) {\n return;\n }\n\n const oldKey = getNodeKey(oldNode);\n if (oldKey && !getNodeKey(newNode)) {\n setNodeKey(newNode, oldKey);\n }\n}\n\n/**\n * Patches a single node, updating it if possible or replacing it.\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(a) where a is the number of attributes\n * - Same reference check: O(1)\n * - Element equality check: O(a) for attribute comparison\n * - Attribute patching: O(a) for iterating attributes\n * - Text node update: O(1)\n * - Component update: O(1) for type check, O(n) for component update\n * - Node replacement: O(1) for DOM operation\n *\n * - **Space Complexity**: O(1) - no additional allocations for common cases\n *\n * ## Optimization Strategy\n *\n * 1. **Fast path for same reference**: Returns immediately if nodes are identical\n * 2. **Fast path for equal nodes**: Uses isEqualNode() for structural equality\n * 3. **In-place attribute updates**: Modifies existing DOM nodes when possible\n * 4. **Minimal allocations**: Avoids creating intermediate arrays\n *\n * @param parent - The parent node\n * @param oldNode - The old node\n * @param newNode - The new node\n * @returns The patched node (reused old node or new node)\n */\nexport function patch(parent: Node, oldNode: AnyNode, newNode: AnyNode): AnyNode {\n // Fast path: same reference\n if (newNode === oldNode) {\n return oldNode;\n }\n\n // Cache type checks to avoid repeated function calls\n const oldIsElement = isHTMLElement(oldNode);\n const newIsElement = isHTMLElement(newNode);\n\n // Both are HTML elements - optimize attribute patching\n if (newIsElement && oldIsElement) {\n // Fast path: structurally equal nodes\n if (newNode.isEqualNode(oldNode)) {\n return oldNode;\n }\n\n // Patch attributes if tags are same\n if (oldNode.tagName === newNode.tagName) {\n // Iterate directly without creating intermediate arrays\n const oldAttrs = oldNode.attributes;\n const newAttrs = newNode.attributes;\n\n // Remove old attributes not in new (iterate backwards to handle live collection)\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const attrName = oldAttrs[i].name;\n if (!newNode.hasAttribute(attrName)) {\n oldNode.removeAttribute(attrName);\n }\n }\n\n // Set new/changed attributes\n for (let i = 0, len = newAttrs.length; i < len; i++) {\n const attr = newAttrs[i];\n if (oldNode.getAttribute(attr.name) !== attr.value) {\n oldNode.setAttribute(attr.name, attr.value);\n }\n }\n\n transferKey(oldNode, newNode);\n return oldNode;\n }\n }\n\n // Handle text nodes\n if (isTextNode(oldNode) && isTextNode(newNode)) {\n if (oldNode.textContent !== newNode.textContent) {\n oldNode.textContent = newNode.textContent;\n }\n transferKey(oldNode, newNode);\n return oldNode;\n }\n\n // Handle component instances - cache isComponent results\n const oldIsComponent = isComponent(oldNode);\n const newIsComponent = isComponent(newNode);\n\n if (oldIsComponent && newIsComponent) {\n if (oldNode.component === newNode.component) {\n return newNode.update(oldNode);\n }\n }\n\n // Different types, replace\n replaceNode(parent, newNode, oldNode);\n return newNode;\n}\n\n/**\n * Unified children patching with Map-based diffing and LIS optimization.\n *\n * ## Algorithm Complexity\n *\n * - **Best Case**: O(1) - both arrays empty\n * - **Fast Paths**: O(n) - mount all, unmount all, single child, two children\n * - **General Case**: O(n + m) where n = old children, m = new children\n * - Common prefix/suffix sync: O(min(n, m))\n * - Unknown sequence with LIS: O(n + m + k log k) where k = moved nodes\n *\n * - **Space Complexity**:\n * - Fast paths: O(1)\n * - General case: O(m) for index mapping + O(k) for LIS\n *\n * ## Optimization Strategy\n *\n * 1. **Fast path 0**: Both empty - O(1) immediate return\n * 2. **Fast path 1**: Mount all - O(m) simple insertion loop\n * 3. **Fast path 2**: Unmount all - O(n) simple removal loop\n * 4. **Fast path 3**: Single child - O(1) direct patch or replace\n * 5. **Fast path 4**: Two children - O(1) handles same order and swap\n * 6. **General algorithm**: Full diff with LIS optimization\n *\n * ## When Each Path is Used\n *\n * - **Empty arrays**: Initial render or complete removal\n * - **Mount all**: First render of a list\n * - **Unmount all**: Conditional rendering (v-if becomes false)\n * - **Single child**: Most common case in practice\n * - **Two children**: Common for toggle/swap scenarios\n * - **General**: Complex list updates with reordering\n *\n * @param parent - The parent DOM node\n * @param oldChildren - Array of current children\n * @param newChildren - Array of new children\n * @param anchor - Optional anchor node for insertions\n * @returns Patched array of children\n */\nexport function patchChildren(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n anchor?: Node,\n): AnyNode[] {\n const oldLength = oldChildren.length;\n const newLength = newChildren.length;\n\n // FAST PATH 0: Both empty\n if (oldLength === 0 && newLength === 0) {\n return [];\n }\n\n // FAST PATH 1: Mount all (no old children)\n if (oldLength === 0) {\n for (let i = 0; i < newLength; i++) {\n insertNode(parent, newChildren[i], anchor);\n }\n return newChildren;\n }\n\n // FAST PATH 2: Unmount all (no new children)\n if (newLength === 0) {\n // Remove all children efficiently\n for (let i = 0; i < oldLength; i++) {\n removeNode(oldChildren[i]);\n }\n return [];\n }\n\n // FAST PATH 3: Single child\n if (oldLength === 1 && newLength === 1) {\n const oldNode = oldChildren[0];\n const newNode = newChildren[0];\n if (isSameNode(oldNode, newNode)) {\n patch(parent, oldNode, newNode);\n newChildren[0] = oldNode;\n } else {\n replaceNode(parent, newNode, oldNode);\n }\n return newChildren;\n }\n\n // FAST PATH 4: Two children\n if (oldLength === 2 && newLength === 2) {\n const o0 = oldChildren[0];\n const o1 = oldChildren[1];\n const n0 = newChildren[0];\n const n1 = newChildren[1];\n\n // Same order\n if (isSameNode(o0, n0) && isSameNode(o1, n1)) {\n patch(parent, o0, n0);\n patch(parent, o1, n1);\n newChildren[0] = o0;\n newChildren[1] = o1;\n return newChildren;\n }\n\n // Swapped\n if (isSameNode(o0, n1) && isSameNode(o1, n0)) {\n patch(parent, o0, n1);\n patch(parent, o1, n0);\n // Move o1 before o0\n const dom1 = getFirstDOMNode(o1);\n const dom0 = getFirstDOMNode(o0);\n if (dom1 && dom0 && dom1.parentNode === parent) {\n parent.insertBefore(dom1, dom0);\n }\n newChildren[0] = o1;\n newChildren[1] = o0;\n return newChildren;\n }\n }\n\n // GENERAL ALGORITHM: Map-based diffing with LIS\n return patchKeyedChildren(parent, oldChildren, newChildren, anchor);\n}\n\n/**\n * General-purpose keyed children patching using optimized diff algorithm.\n *\n * ## Algorithm Overview\n *\n * This implements a two-pointer algorithm similar to Vue 3's diff algorithm:\n * 1. **Sync from start**: Match common prefix (same keys in same order)\n * 2. **Sync from end**: Match common suffix (same keys in same order)\n * 3. **Handle remaining**: Mount new, unmount old, or diff unknown sequence\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n + m) where n = old length, m = new length\n * - Prefix sync: O(min(n, m))\n * - Suffix sync: O(min(n, m))\n * - Remaining: O(max(n, m))\n * - Unknown sequence: O(n + m + k log k) where k = moved nodes\n *\n * - **Space Complexity**: O(1) for sync phases, O(m) for unknown sequence\n *\n * ## Why This Algorithm?\n *\n * Real-world list updates often have:\n * - **Common prefix**: Items at the start rarely change\n * - **Common suffix**: Items at the end rarely change\n * - **Small changes**: Only a few items in the middle change\n *\n * By syncing prefix and suffix first, we minimize the \"unknown sequence\"\n * that requires expensive diffing.\n *\n * ## Example\n *\n * ```\n * Old: [A, B, C, D, E]\n * New: [A, B, X, Y, E]\n *\n * Step 1: Sync prefix → A, B matched\n * Step 2: Sync suffix → E matched\n * Step 3: Unknown sequence → [C, D] vs [X, Y]\n * ```\n *\n * @param parent - Parent DOM node\n * @param oldChildren - Old children array\n * @param newChildren - New children array\n * @param anchor - Optional anchor node\n * @returns Patched new children array\n */\nfunction patchKeyedChildren(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n anchor?: Node,\n): AnyNode[] {\n let oldStartIdx = 0;\n let newStartIdx = 0;\n let oldEndIdx = oldChildren.length - 1;\n let newEndIdx = newChildren.length - 1;\n\n let oldStartNode = oldChildren[0];\n let oldEndNode = oldChildren[oldEndIdx];\n let newStartNode = newChildren[0];\n let newEndNode = newChildren[newEndIdx];\n\n // 1. Sync from start - skip common prefix\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n if (!oldStartNode) {\n oldStartNode = oldChildren[++oldStartIdx];\n } else if (!oldEndNode) {\n oldEndNode = oldChildren[--oldEndIdx];\n } else if (isSameNode(oldStartNode, newStartNode)) {\n patch(parent, oldStartNode, newStartNode);\n newChildren[newStartIdx] = oldStartNode;\n oldStartNode = oldChildren[++oldStartIdx];\n newStartNode = newChildren[++newStartIdx];\n } else {\n break;\n }\n }\n\n // 2. Sync from end - skip common suffix\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n if (!oldStartNode) {\n oldStartNode = oldChildren[++oldStartIdx];\n } else if (!oldEndNode) {\n oldEndNode = oldChildren[--oldEndIdx];\n } else if (isSameNode(oldEndNode, newEndNode)) {\n patch(parent, oldEndNode, newEndNode);\n newChildren[newEndIdx] = oldEndNode;\n oldEndNode = oldChildren[--oldEndIdx];\n newEndNode = newChildren[--newEndIdx];\n } else {\n break;\n }\n }\n\n // 3. Common sequence + mount new nodes\n if (oldStartIdx > oldEndIdx) {\n if (newStartIdx <= newEndIdx) {\n // Cache anchor calculation\n const anchorNode =\n newEndIdx + 1 < newChildren.length ? getFirstDOMNode(newChildren[newEndIdx + 1]) : anchor;\n\n for (let i = newStartIdx; i <= newEndIdx; i++) {\n insertNode(parent, newChildren[i], anchorNode);\n }\n }\n }\n // 4. Common sequence + unmount old nodes\n else if (newStartIdx > newEndIdx) {\n for (let i = oldStartIdx; i <= oldEndIdx; i++) {\n const node = oldChildren[i];\n if (node) {\n removeNode(node);\n }\n }\n }\n // 5. Unknown sequence - use optimized LIS algorithm\n else {\n patchUnknownSequence(\n parent,\n oldChildren,\n newChildren,\n oldStartIdx,\n oldEndIdx,\n newStartIdx,\n newEndIdx,\n anchor,\n );\n }\n\n return newChildren;\n}\n\n/**\n * Patch unknown sequence with optimized LIS (Longest Increasing Subsequence).\n * Uses Object literal instead of Map for faster string key lookup.\n *\n * ## Algorithm Overview\n *\n * This is the most complex part of the diff algorithm, handling arbitrary\n * reordering of children. It uses the LIS algorithm to minimize DOM moves.\n *\n * ## Algorithm Steps\n *\n * 1. **Build key map**: Create O(1) lookup for new children by key\n * 2. **Map old to new**: For each old child, find its position in new children\n * 3. **Detect moves**: Track if any nodes moved out of order\n * 4. **Calculate LIS**: Find longest increasing subsequence (nodes that don't need to move)\n * 5. **Apply changes**: Mount new nodes, move nodes not in LIS\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n + m + k log k)\n * - Build key map: O(m)\n * - Map old to new: O(n × m) worst case, O(n) with keys\n * - Calculate LIS: O(k log k) where k = number of moved nodes\n * - Apply changes: O(m)\n *\n * - **Space Complexity**: O(m)\n * - Key map: O(m)\n * - Index map: O(m) using Int32Array\n * - LIS result: O(k) where k ≤ m\n *\n * ## Why LIS?\n *\n * The LIS represents nodes that are already in correct relative order.\n * These nodes don't need to move, minimizing expensive DOM operations.\n *\n * ## Example\n *\n * ```\n * Old: [A, B, C, D, E]\n * New: [E, C, A, D, B]\n *\n * Index mapping: [2, 4, 1, 3, 0]\n * LIS: [1, 3] → C and D are in correct order\n * Result: Only move E, A, B; keep C and D in place\n * ```\n *\n * ## Optimization: Object vs Map\n *\n * Using Object.create(null) for key lookup is ~30% faster than Map\n * for string keys, which is the common case.\n *\n * @param parent - Parent DOM node\n * @param oldChildren - Old children array\n * @param newChildren - New children array\n * @param oldStartIdx - Start index in old children\n * @param oldEndIdx - End index in old children\n * @param newStartIdx - Start index in new children\n * @param newEndIdx - End index in new children\n * @param anchor - Optional anchor node\n */\nfunction patchUnknownSequence(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n oldStartIdx: number,\n oldEndIdx: number,\n newStartIdx: number,\n newEndIdx: number,\n anchor?: Node,\n): void {\n // Cache length calculation\n const newLength = newEndIdx - newStartIdx + 1;\n\n // Use Object literal for faster string key lookup\n let keyToNewIndexMap: Record<string, number> | undefined;\n\n // Build key to index map for new children\n for (let i = newStartIdx; i <= newEndIdx; i++) {\n const key = getNodeKey(newChildren[i]);\n if (key !== undefined) {\n if (!keyToNewIndexMap) {\n keyToNewIndexMap = Object.create(null);\n }\n keyToNewIndexMap![key] = i;\n }\n }\n\n // Use Int32Array for better memory layout and performance\n const newIndexToOldIndexMap = new Int32Array(newLength);\n let moved = false;\n let maxNewIndexSoFar = 0;\n let patched = 0;\n\n // Map old children to new positions\n for (let i = oldStartIdx; i <= oldEndIdx; i++) {\n const oldNode = oldChildren[i];\n if (!oldNode) continue;\n\n // All new nodes have been patched, remove remaining old nodes\n if (patched >= newLength) {\n removeNode(oldNode);\n continue;\n }\n\n let newIndex: number | undefined;\n const oldKey = getNodeKey(oldNode);\n\n // Fast path: keyed lookup using object property access\n if (oldKey !== undefined && keyToNewIndexMap && oldKey in keyToNewIndexMap) {\n newIndex = keyToNewIndexMap[oldKey];\n } else {\n // Fallback: type-based matching for unkeyed nodes\n for (let j = newStartIdx; j <= newEndIdx; j++) {\n if (\n newIndexToOldIndexMap[j - newStartIdx] === 0 &&\n oldKey === undefined &&\n getNodeKey(newChildren[j]) === undefined &&\n isSameNode(oldNode, newChildren[j])\n ) {\n newIndex = j;\n break;\n }\n }\n }\n\n if (newIndex === undefined) {\n // No match found, remove old node\n removeNode(oldNode);\n } else {\n // Record mapping (add 1 to distinguish from 0 which means unmapped)\n newIndexToOldIndexMap[newIndex - newStartIdx] = i + 1;\n\n // Track if nodes have moved (for LIS optimization)\n if (newIndex >= maxNewIndexSoFar) {\n maxNewIndexSoFar = newIndex;\n } else {\n moved = true;\n }\n\n // Patch the matched nodes\n patch(parent, oldNode, newChildren[newIndex]);\n newChildren[newIndex] = oldNode;\n patched++;\n }\n }\n\n // Calculate LIS only if nodes have moved\n const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : [];\n let j = increasingNewIndexSequence.length - 1;\n\n // Cache anchor nodes to avoid repeated getFirstDOMNode calls\n let cachedAnchor: Node | undefined = anchor;\n\n // Loop backwards to ensure correct anchor calculation\n for (let i = newLength - 1; i >= 0; i--) {\n const nextIndex = newStartIdx + i;\n const nextNode = newChildren[nextIndex];\n\n if (newIndexToOldIndexMap[i] === 0) {\n // New node - insert it\n insertNode(parent, nextNode, cachedAnchor);\n // Update cached anchor for next iteration\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n } else if (moved) {\n // Existing node - move if not in LIS\n if (j < 0 || i !== increasingNewIndexSequence[j]) {\n const domNode = getFirstDOMNode(nextNode);\n if (domNode && domNode.parentNode === parent) {\n insertNode(parent, domNode, cachedAnchor);\n }\n // Update cached anchor\n cachedAnchor = domNode || cachedAnchor;\n } else {\n // Node is in LIS, update anchor but don't move\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n j--;\n }\n } else {\n // No moves, just update anchor\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n }\n }\n}\n\n/**\n * Compute the Longest Increasing Subsequence (LIS).\n * Uses patience sorting with binary search for O(n log n) time complexity.\n *\n * ## Algorithm: Patience Sorting\n *\n * This algorithm is based on the patience sorting card game:\n * 1. Maintain an array of \"piles\" (result array)\n * 2. For each element, find the leftmost pile where it can be placed\n * 3. Use binary search to find the correct pile in O(log n)\n * 4. Track predecessors to reconstruct the sequence\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n log n)\n * - Main loop: O(n) iterations\n * - Binary search per iteration: O(log n)\n * - Sequence reconstruction: O(k) where k = LIS length\n *\n * - **Space Complexity**: O(n)\n * - Result array: O(k) where k ≤ n\n * - Predecessor array: O(n) using Int32Array\n *\n * ## Why This Algorithm?\n *\n * The LIS problem has multiple solutions:\n * - **Brute force**: O(2^n) - try all subsequences\n * - **Dynamic programming**: O(n²) - classic DP solution\n * - **Patience sorting**: O(n log n) - optimal solution\n *\n * We use patience sorting because:\n * 1. Optimal time complexity for large lists\n * 2. Simple to implement and understand\n * 3. Works well with the diff algorithm's needs\n *\n * ## Example\n *\n * ```\n * Input: [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]\n * Output: [0, 2, 6, 9, 11, 15] (indices of LIS)\n * LIS: [0, 2, 6, 9, 13, 15] (actual values)\n * ```\n *\n * ## Special Cases\n *\n * - **Empty array**: Returns []\n * - **Single element**: Returns [0] if element !== 0\n * - **All zeros**: Returns [] (zeros mean \"no mapping\" in diff context)\n * - **Strictly decreasing**: Returns [last_non_zero_index]\n *\n * ## Diff Context\n *\n * In the diff algorithm, the input array represents:\n * - Index: Position in new children\n * - Value: Position in old children + 1 (0 means new node)\n *\n * The LIS represents nodes that are already in correct relative order\n * and don't need to be moved.\n *\n * @param arr - Array of indices (0 means no mapping)\n * @returns Array of indices representing the LIS\n */\nexport function getSequence(arr: Int32Array | number[]): number[] {\n const len = arr.length;\n if (len === 0) return [];\n\n // Fast path: single element\n if (len === 1) return arr[0] !== 0 ? [0] : [];\n\n const result: number[] = [];\n const p = new Int32Array(len);\n\n let i: number;\n let j: number;\n let u: number;\n let v: number;\n let c: number;\n\n for (i = 0; i < len; i++) {\n const arrI = arr[i];\n if (arrI !== 0) {\n j = result[result.length - 1];\n\n // Append to result if greater than last element\n if (result.length === 0 || arr[j] < arrI) {\n p[i] = j;\n result.push(i);\n continue;\n }\n\n // Binary search for the correct position\n u = 0;\n v = result.length - 1;\n\n while (u < v) {\n c = (u + v) >> 1;\n if (arr[result[c]] < arrI) {\n u = c + 1;\n } else {\n v = c;\n }\n }\n\n // Update result if smaller value found\n if (arrI < arr[result[u]]) {\n if (u > 0) {\n p[i] = result[u - 1];\n }\n result[u] = i;\n }\n }\n }\n\n // Reconstruct the sequence\n u = result.length;\n v = result[u - 1];\n\n while (u-- > 0) {\n result[u] = v;\n v = p[v];\n }\n\n return result;\n}\n","import {\n coerceArray,\n isFunction,\n isHtmlInputElement,\n isHtmlSelectElement,\n isHtmlTextAreaElement,\n} from '@estjs/shared';\nimport { effect } from '@estjs/signals';\nimport { normalizeNode } from './utils/node';\nimport { removeNode } from './utils/dom';\nimport { patchChildren } from './patch';\nimport { getActiveScope, onCleanup, runWithScope } from './scope';\nimport type { AnyNode } from './types';\n\n/**\n * Add event listener with automatic cleanup on scope destruction\n *\n * @param element - Element to attach listener to\n * @param event - Event name\n * @param handler - Event handler function\n * @param options - Event listener options\n */\nexport function addEventListener(\n element: Element,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions,\n): void {\n element.addEventListener(event, handler, options);\n\n onCleanup(() => {\n element.removeEventListener(event, handler, options);\n });\n}\n\n/**\n * Bind an element to a setter function for two-way data binding\n *\n * @param node - The element to bind\n * @param key - The property key (unused, kept for API compatibility)\n * @param defaultValue - Default value (unused, kept for API compatibility)\n * @param setter - The setter function to call when the element's value changes\n */\nexport function bindElement(\n node: Element,\n key: string,\n defaultValue: unknown,\n setter: (value: unknown) => void,\n): void {\n if (isHtmlInputElement(node)) {\n bindInputElement(node, setter);\n } else if (isHtmlSelectElement(node)) {\n bindSelectElement(node, setter);\n } else if (isHtmlTextAreaElement(node)) {\n addEventListener(node, 'input', () => {\n setter((node as HTMLTextAreaElement).value);\n });\n }\n}\n\n/**\n * Bind input element based on its type\n */\nfunction bindInputElement(node: HTMLInputElement, setter: (value: unknown) => void): void {\n switch (node.type) {\n case 'checkbox':\n addEventListener(node, 'change', () => {\n setter(Boolean(node.checked));\n });\n break;\n\n case 'radio':\n addEventListener(node, 'change', () => {\n setter(node.checked ? node.value : '');\n });\n break;\n\n case 'file':\n addEventListener(node, 'change', () => {\n setter(node.files);\n });\n break;\n\n case 'number':\n case 'range':\n addEventListener(node, 'input', () => {\n setter(node.value || '');\n });\n break;\n\n case 'date':\n case 'datetime-local':\n case 'month':\n case 'time':\n case 'week':\n addEventListener(node, 'change', () => {\n setter(node.value || '');\n });\n break;\n\n default:\n // text, email, password, search, tel, url, etc.\n addEventListener(node, 'input', () => {\n setter(node.value);\n });\n break;\n }\n}\n\n/**\n * Bind select element\n */\nfunction bindSelectElement(node: HTMLSelectElement, setter: (value: unknown) => void): void {\n addEventListener(node, 'change', () => {\n if (node.multiple) {\n const values = Array.from(node.options)\n .filter(option => option.selected)\n .map(option => option.value);\n setter(values);\n } else {\n setter(node.value);\n }\n });\n}\n\n/**\n * Reactive node insertion with binding support\n *\n * @param parent Parent node\n * @param nodeFactory Node factory function or static node\n * @param before Reference node for insertion position\n *\n * @example\n * ```typescript\n * insert(container, () => message.value, null);\n * insert(container, staticElement, referenceNode);\n * insert(container, \"Hello World\", null); // Direct string support\n * ```\n */\nexport function insert(parent: Node, nodeFactory: AnyNode, before?: Node) {\n if (!parent) return;\n\n let renderedNodes: AnyNode[] = [];\n const currentScope = getActiveScope();\n // Create effect for reactive updates\n const cleanup = effect(() => {\n const run = () => {\n const rawNodes = isFunction(nodeFactory) ? nodeFactory() : nodeFactory;\n const nodes = coerceArray(rawNodes as unknown)\n .map(item => (isFunction(item) ? item() : item))\n .flatMap(normalizeNode) as AnyNode[];\n\n renderedNodes = patchChildren(parent, renderedNodes, nodes, before) as AnyNode[];\n };\n if (currentScope) {\n runWithScope(currentScope, run);\n } else {\n run();\n }\n });\n\n onCleanup(() => {\n cleanup();\n renderedNodes.forEach(node => removeNode(node));\n renderedNodes.length = 0;\n });\n\n return renderedNodes;\n}\n\n/**\n * Map nodes from template by indexes\n *\n * @param template - Template node to traverse\n * @param indexes - Array of indexes to map\n * @returns Array of mapped nodes\n */\nexport function mapNodes(template: Node, indexes: number[]): Node[] {\n const len = indexes.length;\n const tree = new Array<Node>(len);\n const indexSet = new Set(indexes);\n\n let index = 1;\n let found = 0;\n\n const walk = (node: Node): boolean => {\n if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {\n if (indexSet.has(index)) {\n tree[found++] = node;\n if (found === len) return true;\n }\n index++;\n }\n\n let child = node.firstChild;\n while (child) {\n if (walk(child)) return true;\n child = child.nextSibling;\n }\n\n return false;\n };\n\n walk(template);\n return tree;\n}\n","import { isComputed, isSignal, shallowReactive } from '@estjs/signals';\nimport {\n coerceArray,\n hasChanged,\n isArray,\n isFunction,\n isHTMLElement,\n isObject,\n isPromise,\n startsWith,\n} from '@estjs/shared';\nimport {\n type Scope,\n createScope,\n disposeScope,\n getActiveScope,\n runWithScope,\n setActiveScope,\n} from './scope';\nimport { COMPONENT_STATE, EVENT_PREFIX, NORMAL_COMPONENT, REF_KEY } from './constants';\nimport { addEventListener, insert } from './binding';\nimport { getComponentKey, normalizeKey } from './key';\nimport { getFirstDOMNode, insertNode, removeNode } from './utils/dom';\nimport { shallowCompare } from './utils/node';\nimport { triggerMountHooks, triggerUpdateHooks } from './lifecycle';\nimport type { AnyNode, ComponentFn, ComponentProps } from './types';\n\nexport class Component<P extends ComponentProps = ComponentProps> {\n // Component rendered nodes (supports arrays and fragments)\n protected renderedNodes: AnyNode[] = [];\n\n // Component scope (unified context management)\n protected scope: Scope | null = null;\n\n // Component parent node\n protected parentNode: Node | undefined = undefined;\n\n // Component before node\n public beforeNode: Node | undefined = undefined;\n\n // Component props (reactive and snapshot)\n private reactiveProps: Record<string, any> = {};\n private _propSnapshots: Record<string, any> = {};\n\n // Component key for reconciliation\n public readonly key: string | undefined;\n\n // Component lifecycle state\n protected state: number = COMPONENT_STATE.INITIAL;\n\n // Parent scope captured at construction time for correct hierarchy\n protected parentScope: Scope | null = null;\n\n // @ts-ignore\n public readonly [NORMAL_COMPONENT] = true;\n\n get isConnected(): boolean {\n return this.state === COMPONENT_STATE.MOUNTED;\n }\n\n get firstChild(): Node | undefined {\n // Get the first meaningful DOM node from rendered nodes\n for (const node of this.renderedNodes) {\n const dom = getFirstDOMNode(node);\n if (dom) return dom;\n }\n return undefined;\n }\n\n constructor(\n public component: ComponentFn<P>,\n public props: P = {} as P,\n ) {\n this.key = props.key ? normalizeKey(props.key) : getComponentKey(component);\n this.reactiveProps = shallowReactive({ ...props }) as P;\n this.parentScope = getActiveScope();\n\n // Initialize snapshots for object/array props to track mutations\n for (const key in props) {\n const val = props[key];\n if (isObject(val)) {\n this._propSnapshots[key] = isArray(val) ? [...val] : { ...val };\n }\n }\n }\n\n mount(parentNode: Node, beforeNode?: Node): AnyNode[] {\n this.parentNode = parentNode;\n this.beforeNode = beforeNode;\n this.state = COMPONENT_STATE.MOUNTING;\n\n // if the component already has rendered nodes, re-insert them\n if (this.renderedNodes.length > 0) {\n for (const node of this.renderedNodes) {\n insertNode(parentNode, node, beforeNode);\n }\n this.state = COMPONENT_STATE.MOUNTED;\n return this.renderedNodes;\n }\n\n const parentScope = this.parentScope ?? getActiveScope();\n this.scope = createScope(parentScope);\n setActiveScope(this.scope);\n let result = this.component(this.reactiveProps as P);\n\n // Unwrap function (render function pattern)\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // Unwrap signals and computed values\n if (isSignal<Element>(result) || isComputed<Element>(result)) {\n result = result.value;\n }\n\n const renderedNodes = insert(parentNode, result, beforeNode) ?? [];\n\n this.renderedNodes = renderedNodes;\n\n // Apply props (events, refs) after renderedNodes is set\n\n this.applyProps(this.props);\n\n // Update state to mounted\n this.state = COMPONENT_STATE.MOUNTED;\n\n // Trigger mount lifecycle hooks\n triggerMountHooks(this.scope);\n\n return this.renderedNodes;\n }\n\n update<T extends ComponentProps>(prevNode: Component<T>): Component<T> {\n // if key is different, mount the component\n if (this.key !== prevNode.key) {\n this.mount(prevNode.parentNode!, prevNode.beforeNode);\n return this as unknown as Component<T>;\n }\n\n // Take previous node's properties and reactive state\n this.parentNode = prevNode.parentNode;\n this.beforeNode = prevNode.beforeNode;\n this.scope = prevNode.scope; // Reuse existing scope\n this.parentScope = prevNode.parentScope;\n this.renderedNodes = prevNode.renderedNodes;\n this.state = prevNode.state;\n this.reactiveProps = prevNode.reactiveProps; // Reuse same reactive object\n this._propSnapshots = prevNode._propSnapshots;\n\n // Update reactive props with shallow comparison for objects\n this._updateReactiveProps(this.props);\n\n // Mount component if not connected\n if (!this.isConnected && this.parentNode) {\n this.mount(this.parentNode, this.beforeNode);\n return this as unknown as Component<T>;\n }\n\n // Apply props and trigger update lifecycle\n if (this.scope) {\n setActiveScope(this.scope);\n this.applyProps(this.props);\n triggerUpdateHooks(this.scope);\n }\n\n return this as unknown as Component<T>;\n }\n\n /**\n * Update reactive props by comparing with current values\n */\n private _updateReactiveProps(props: P): void {\n for (const key in props) {\n if (key === 'key') continue;\n\n const newValue = props[key];\n const oldValue = this.reactiveProps[key];\n\n // Early return: if values are strictly equal, skip processing\n // Note: If we have a snapshot, we might still need to check for mutations (same ref but content changed)\n if (newValue === oldValue && !this._propSnapshots[key]) continue;\n\n // Cache type check to avoid repeated calls\n const isNewValueObject = isObject(newValue);\n\n if (isNewValueObject) {\n // For objects/arrays: compare with snapshot to detect mutations\n const snapshot = this._propSnapshots[key];\n\n // Early return: if snapshot exists and content is the same, skip update\n if (snapshot && shallowCompare(newValue, snapshot)) continue;\n\n // Create new snapshot efficiently\n const newSnapshot = isArray(newValue) ? [...newValue] : { ...newValue };\n this.reactiveProps[key] = newSnapshot;\n this._propSnapshots[key] = newSnapshot;\n } else {\n // For primitives: hasChanged check (handles NaN, +0/-0, etc.)\n if (hasChanged(newValue, oldValue)) {\n this.reactiveProps[key] = newValue;\n // Clean up snapshot if it exists (type may have changed from object to primitive)\n if (this._propSnapshots[key]) {\n delete this._propSnapshots[key];\n }\n }\n }\n }\n }\n\n private unwrapRenderResult(result: any): AnyNode[] {\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // Unwrap signals and computed values\n if (isSignal<AnyNode>(result) || isComputed<AnyNode>(result)) {\n result = result.value;\n }\n if (isComponent(result)) {\n result = result.mount(this.parentNode!, this.beforeNode);\n }\n\n if (isPromise(result)) {\n result = result.then(r => this.unwrapRenderResult(r));\n }\n\n return result;\n }\n\n forceUpdate(): void {\n if (this.state === COMPONENT_STATE.DESTROYED || !this.parentNode || !this.scope) {\n return;\n }\n\n const originalNodes = [...this.renderedNodes];\n\n try {\n runWithScope(this.scope, () => {\n // Re-render and get new nodes\n let result = this.component(this.reactiveProps as P);\n\n // Unwrap function (render function pattern)\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // Unwrap signals and computed values\n if (isSignal<AnyNode>(result) || isComputed<AnyNode>(result)) {\n result = result.value;\n }\n\n const newNodes = coerceArray(result) as AnyNode[];\n\n // Calculate anchor position for insertion\n const anchor = this._getAnchorNode();\n\n // Replace old nodes with new ones\n if (!this.parentNode) return;\n\n // Remove old nodes\n for (const node of this.renderedNodes) {\n removeNode(node);\n }\n\n // Insert new nodes\n for (const node of newNodes) {\n insertNode(this.parentNode, node, anchor);\n }\n\n this.renderedNodes = newNodes;\n });\n\n if (this.scope) {\n triggerUpdateHooks(this.scope);\n }\n } catch (error) {\n // Rollback on error\n this.renderedNodes = originalNodes;\n throw error;\n }\n }\n\n /**\n * Get anchor node for insertion\n */\n private _getAnchorNode(): Node | undefined {\n if (this.beforeNode) return this.beforeNode;\n\n if (this.renderedNodes.length > 0) {\n const lastNode = this.renderedNodes[this.renderedNodes.length - 1];\n const lastDom = getFirstDOMNode(lastNode);\n if (lastDom) {\n return lastDom.nextSibling as Node | undefined;\n }\n }\n\n return undefined;\n }\n\n /**\n * Destroy component\n */\n destroy(): void {\n // Prevent duplicate destruction\n if (this.state === COMPONENT_STATE.DESTROYING || this.state === COMPONENT_STATE.DESTROYED) {\n return;\n }\n\n this.state = COMPONENT_STATE.DESTROYING;\n\n // Remove all rendered nodes\n for (const node of this.renderedNodes) {\n removeNode(node);\n }\n\n const scope = this.scope;\n if (scope) {\n disposeScope(scope);\n this.scope = null;\n }\n // Reset all component properties\n this.renderedNodes = [];\n this.parentNode = undefined;\n this.beforeNode = undefined;\n this.parentScope = null;\n this.reactiveProps = {} as P;\n this.props = {} as P;\n this.state = COMPONENT_STATE.DESTROYED;\n }\n\n applyProps(props: P): void {\n if (!props) return;\n\n const firstElement = this.firstChild;\n\n // Apply event listeners and refs\n for (const [propName, propValue] of Object.entries(props)) {\n if (startsWith(propName, EVENT_PREFIX)) {\n if (!firstElement || !isHTMLElement(firstElement)) return;\n\n const eventName = propName.slice(EVENT_PREFIX.length).toLowerCase();\n addEventListener(firstElement, eventName, propValue as EventListener);\n } else if (propName === REF_KEY && isSignal(propValue)) {\n propValue.value = firstElement;\n }\n }\n\n this.props = props;\n }\n}\n\n/**\n * check if a node is a component\n * @param {unknown} node - the node to check\n * @returns {boolean} true if the node is a component, false otherwise\n */\nexport function isComponent(node: unknown): node is Component {\n return !!node && !!node[NORMAL_COMPONENT];\n}\n\n/**\n * create a component\n * @param {Function} componentFn - the component function\n * @param {ComponentProps} props - the component props\n * @returns {Component} the component\n */\nexport function createComponent<P extends ComponentProps>(\n componentFn: ComponentFn<P>,\n props?: P,\n): Component<P> {\n if (isComponent(componentFn)) {\n return componentFn as unknown as Component<P>;\n }\n return new Component(componentFn, props);\n}\n","import { error, isString } from '@estjs/shared';\nimport { type Component, createComponent, isComponent } from './component';\nimport type { ComponentFn, ComponentProps } from './types';\n\n/**\n * Create a template factory function from HTML string\n *\n * This function creates a reusable template factory that efficiently clones\n * DOM nodes from the provided HTML string. The template is parsed once and\n *\n * @param html - The HTML string to create template from\n * @returns Factory function that returns a cloned node of the template\n * @throws {Error} When template content is empty or invalid\n\n */\nexport function template(html: string) {\n let node: Node | undefined;\n\n const create = (): Node => {\n // Regular HTML template\n const template = document.createElement('template');\n template.innerHTML = html;\n const firstChild = template.content.firstChild;\n if (!firstChild) {\n throw new Error('Invalid template: empty content');\n }\n return firstChild;\n };\n\n // return a factory function: create the template when first called, reuse the cached template when called later\n return () => (node || (node = create())).cloneNode(true);\n}\n\n/**\n * Create and mount an application with the specified component\n *\n * This function initializes an application by mounting a root component\n * to a target DOM element. It handles target validation and cleanup.\n *\n * @param component - The root component function to mount\n * @param target - CSS selector string or DOM element to mount to\n * @returns The mount root component instance, or undefined if target not found\n */\nexport function createApp<P extends ComponentProps = {}>(\n component: ComponentFn<P> | Component<P>,\n target: string | Element,\n) {\n const container = isString(target)\n ? document.querySelector(target as string)\n : (target as Element);\n if (!container) {\n error(`Target element not found: ${target}`);\n return;\n }\n\n const existingContext = container.innerHTML;\n if (existingContext) {\n error(`Target element is not empty, it will be delete: ${target}`);\n container.innerHTML = '';\n }\n const rootComponent: Component<P> = isComponent(component)\n ? (component as Component<P>)\n : createComponent(component as ComponentFn<P>);\n rootComponent.mount(container);\n return rootComponent;\n}\n","import { error } from '@estjs/shared';\nimport { type Scope, getActiveScope } from './scope';\n\n/**\n * InjectionKey is a unique identifier for provided values.\n * Using Symbol ensures type safety and prevents key collisions.\n */\n// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types, unused-imports/no-unused-vars\nexport interface InjectionKey<T> extends Symbol {}\n\n/**\n * Provide a value in the current scope.\n * The value can be injected by this scope or any descendant scope.\n *\n * @param key - The injection key\n * @param value - The value to provide\n */\nexport function provide<T>(key: InjectionKey<T> | string | number, value: T): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('provide() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize provides map\n if (!scope.provides) {\n scope.provides = new Map();\n }\n\n scope.provides.set(key, value);\n}\n\n/**\n * Inject a value from the scope hierarchy.\n * Traverses up the parent chain until finding a matching key.\n *\n * @param key - The injection key\n * @param defaultValue - Default value if key is not found\n * @returns The injected value or default value\n */\nexport function inject<T>(key: InjectionKey<T> | string | number, defaultValue?: T): T {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('inject() must be called within a scope');\n }\n return defaultValue as T;\n }\n\n // Traverse up the hierarchy\n let current: Scope | null = scope;\n while (current) {\n if (current.provides) {\n const value = current.provides.get(key);\n if (value) {\n return value as T;\n }\n }\n current = current.parent;\n }\n\n return defaultValue as T;\n}\n","import { isFunction, isString } from '@estjs/shared';\n\n/**\n * Retarget the event's target property\n * @param event - Event object to retarget\n * @param value - New target value\n */\nfunction reTarget(event: Event, value: EventTarget): void {\n Object.defineProperty(event, 'target', {\n configurable: true,\n value,\n });\n}\n\n/**\n * Handle event on current node\n * @param node - Current node to handle\n * @param event - Event object\n * @param key - Event type key\n * @returns Whether to continue propagation\n */\nfunction handleNodeEvent(node: any, event: Event, key: string): boolean {\n const handler = node[`_$${key}`];\n if (handler && isFunction(handler) && !node.disabled) {\n const data = node[`${key}Data`];\n data ? handler.call(node, data, event) : handler.call(node, event);\n if (event.cancelBubble) return false;\n }\n\n // Handle host element retargeting\n if (\n node.host &&\n !isString(node.host) &&\n !node.host._$host &&\n isFunction(node.contains) &&\n node.contains(event.target)\n ) {\n reTarget(event, node.host);\n }\n return true;\n}\n\n/**\n * Walk up the DOM tree handling events\n * @param startNode - Initial node to start from\n * @param event - Event object\n * @param key - Event type key\n * @returns Final node after walking\n */\nfunction walkUpTree(startNode: any, event: Event, key: string): any {\n let node = startNode;\n while (handleNodeEvent(node, event, key) && (node = node._$host || node.parentNode || node.host));\n return node;\n}\n\n/**\n * Event handler for delegated events\n * @param event - The event object\n */\nfunction eventHandler(event): void {\n let node = event.target;\n const key = `${event.type}`;\n const oriTarget = event.target;\n const oriCurrentTarget = event.currentTarget;\n\n // Simulate currentTarget\n Object.defineProperty(event, 'currentTarget', {\n configurable: true,\n get() {\n return node || document;\n },\n });\n\n if (event.composedPath) {\n const path = event.composedPath();\n reTarget(event, path[0]);\n for (let i = 0; i < path.length - 2; i++) {\n node = path[i];\n if (!handleNodeEvent(node, event, key)) break;\n if (node._$host) {\n node = node._$host;\n // Bubble up from portal mount instead of composedPath\n node = walkUpTree(node, event, key);\n break;\n }\n if (node.parentNode === oriCurrentTarget) {\n break; // Don't bubble above root of event delegation\n }\n }\n } else {\n // Fallback for browsers that don't support composedPath\n node = walkUpTree(node, event, key);\n }\n\n // Mixing portals and shadow dom can lead to a nonstandard target, so reset here\n reTarget(event, oriTarget!);\n}\n\n/**\n * Symbol for storing delegated events on document\n */\nconst $EVENTS = Symbol('_$EVENTS');\n\n/**\n * Set up event delegation for specified event types\n * @param {string[]} eventNames - Array of event names to delegate\n * @param {Document} document - Document to attach events to (defaults to window.document)\n */\nexport function delegateEvents(eventNames: string[], document: Document = window.document): void {\n const docWithEvents = document as Document & { [$EVENTS]?: Set<string> };\n const eventSet = docWithEvents[$EVENTS] || (docWithEvents[$EVENTS] = new Set<string>());\n\n for (const name of eventNames) {\n if (!eventSet.has(name)) {\n eventSet.add(name);\n document.addEventListener(name, eventHandler);\n }\n }\n}\n\n/**\n * Clear all delegated events from document\n * @param {Document} document - Document to clear events from (defaults to window.document)\n */\nexport function clearDelegatedEvents(document: Document = window.document): void {\n const docWithEvents = document as Document & { [$EVENTS]?: Set<string> };\n const eventSet = docWithEvents[$EVENTS];\n if (eventSet) {\n for (const name of eventSet.keys()) {\n document.removeEventListener(name, eventHandler);\n }\n delete docWithEvents[$EVENTS];\n }\n}\n","/**\n * Create a reactive proxy that excludes specified properties\n *\n * @param target - The original reactive object\n * @param keys - List of property names to exclude\n * @returns A reactive proxy with specified properties excluded\n */\nexport function omitProps<T extends object, K extends keyof T>(target: T, keys: K[]): Omit<T, K> {\n const excludeSet = new Set(keys);\n\n return new Proxy(target, {\n // Intercept property reads\n get(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n return Reflect.get(obj, prop);\n },\n\n // Intercept property enumeration (for...in, Object.keys, etc.)\n ownKeys(obj) {\n return Reflect.ownKeys(obj).filter(key => !excludeSet.has(key as K));\n },\n\n // Intercept property descriptor retrieval\n getOwnPropertyDescriptor(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n return Reflect.getOwnPropertyDescriptor(obj, prop);\n },\n\n // Intercept the 'in' operator\n has(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return false;\n }\n return Reflect.has(obj, prop);\n },\n });\n}\n","/** Whether hydration is currently active */\nlet isHydrationActive = false;\n\n/**\n * Start hydration mode\n * Called when beginning client-side hydration of server-rendered content\n */\nexport function startHydration(): void {\n isHydrationActive = true;\n}\n\n/**\n * End hydration mode\n * Called when hydration is complete\n */\nexport function endHydration(): void {\n isHydrationActive = false;\n}\n\n/**\n * Check if hydration is currently active\n * @returns true if hydration is in progress\n */\nexport function isHydrating(): boolean {\n return isHydrationActive;\n}\n\n/** Hydration identifier counter, used to generate unique IDs */\nlet hydrationCounter = 0;\n\n/**\n * Get the hydration key\n * @returns the hydration key string\n */\nexport function getHydrationKey(): string {\n return `${hydrationCounter++}`;\n}\n\n/**\n * Reset the hydration key counter\n */\nexport function resetHydrationKey(): void {\n hydrationCounter = 0;\n}\n","import { error, isBrowser, isString } from '@estjs/shared';\nimport {\n createComponent,\n endHydration,\n startHydration,\n template,\n mapNodes as templateMapNodes,\n} from '../';\nimport { getHydrationKey, resetHydrationKey } from './shared';\nimport type { ComponentFn } from '../';\n/**\n * data-idx regex\n */\nexport const DATA_IDX_REGEX = /^\\d+-\\d+$/;\n/**\n * Get rendered element by hydration key or create from template\n * @param {string} temp - the template string\n * @returns {Function} a function that returns the element\n */\nexport function getRenderedElement(temp: string) {\n return () => {\n // SSR environment check\n if (!isBrowser()) {\n return null;\n }\n\n // Get hydration key\n const key = getHydrationKey();\n\n // Try to find existing element with matching hydration key\n const node = document.querySelector(`[data-hk=\"${key}\"]`);\n\n if (node) {\n return node;\n }\n\n // Create new element from template if not found\n return template(temp)();\n };\n}\n\n/**\n * Maps server-side rendered nodes during hydration\n * @param {HTMLElement} templateEl - The root template element\n * @param {number[]} idx - Array of indices to map\n * @returns {Node[]} Array of mapped nodes\n */\nexport function mapSSRNodes(templateEl: HTMLElement, idx: number[]): Node[] {\n // Check if we're in hydration mode by looking for the data-hk attribute\n const hk = templateEl.dataset.hk;\n\n // If not hydrating, fallback to standard node mapping\n if (!hk) {\n return templateMapNodes(templateEl, idx);\n }\n\n // Collection for all nodes\n const nodesList: Array<{ hk: string; idx: string; node: Node }> = [];\n\n // Find element nodes with data-idx attributes\n const elements = templateEl.querySelectorAll(`[data-idx^=\"${hk}\"]`);\n\n // Process element nodes\n if (elements.length > 0) {\n nodesList.push(\n ...Array.from(elements)\n .filter((item: Element) => {\n const idxAttr = (item as HTMLElement).dataset.idx;\n return idxAttr !== null && DATA_IDX_REGEX.test(idxAttr!);\n })\n .map((item: Element) => {\n const idxAttr = (item as HTMLElement).dataset.idx || '';\n const [hkPart, idxPart] = idxAttr.split('-');\n return {\n hk: hkPart,\n idx: idxPart,\n node: item,\n };\n }),\n );\n }\n\n // Find and process comment nodes\n const commentNodes: Array<{ hk: string; idx: string; node: Node }> = [];\n\n const walkNodes = (node: Node): void => {\n // Check for comment nodes with data-idx pattern\n if (\n node.nodeType === Node.COMMENT_NODE &&\n node.textContent &&\n DATA_IDX_REGEX.test(node.textContent)\n ) {\n const [hkPart, idxPart] = node.textContent.split('-');\n commentNodes.push({\n hk: hkPart,\n idx: idxPart,\n node,\n });\n }\n\n // Recursively process child nodes\n let child = node.firstChild;\n while (child) {\n walkNodes(child);\n child = child.nextSibling;\n }\n };\n\n walkNodes(templateEl);\n nodesList.push(...commentNodes);\n\n // Build final node list with template as first element\n const nodes: Node[] = [templateEl];\n\n // Map indices to corresponding nodes\n idx.forEach(indexValue => {\n const node = nodesList.find(item => item.idx === String(indexValue));\n if (node) {\n nodes.push(node.node);\n }\n });\n\n return nodes;\n}\n\n/**\n * Hydrate a server-rendered component\n * @param {ComponentFn} component - Component function to hydrate\n * @param {HTMLElement | string} container - Container element or selector\n * @returns {any} Component instance or undefined if hydration fails\n */\nexport function hydrate(component: ComponentFn, container: HTMLElement | string): any {\n // Set hydration mode\n startHydration();\n // Reset hydration key counter\n resetHydrationKey();\n\n try {\n // Get container element\n const rootElement = isString(container)\n ? document.querySelector(container as string)\n : container;\n\n if (!rootElement) {\n error('Hydration error: Root element not found');\n return undefined;\n }\n\n // Create and mount component\n const rootComponent = createComponent(component);\n rootComponent.mount(rootElement);\n\n // Exit hydration mode\n endHydration();\n\n return rootComponent;\n } catch (error_) {\n error('Hydration error:', error_);\n // Ensure hydration mode is ended even if an error occurs\n endHydration();\n return undefined;\n }\n}\n","import { normalizeClassName } from '@estjs/shared';\nimport { isHydrating } from '../hydration/shared';\n\n/**\n * Type definition for class values\n * @public\n */\nexport type ClassValue = string | Record<string, boolean> | ClassValue[] | null | undefined;\n\n/**\n * Patches the class attribute of an element\n * Supports silent hydration (skips DOM updates during hydration phase)\n *\n * @param el - The element to patch classes on\n * @param prev - Previous class value for diffing\n * @param next - New class value to apply\n * @param isSVG - Whether the element is an SVG element\n * @public\n */\nexport function patchClass(\n el: Element,\n prev: unknown,\n next: unknown,\n isSVG: boolean = false,\n): void {\n if (prev === next) {\n return;\n }\n if (isHydrating()) {\n return;\n }\n const normalizedNext = normalizeClass(next);\n const normalizedPrev = normalizeClass(prev);\n // Skip DOM update if classes haven't changed\n if (normalizedNext && normalizedPrev === normalizedNext) {\n return;\n }\n\n // Apply classes based on element type\n if (!normalizedNext) {\n el.removeAttribute('class');\n } else if (isSVG) {\n el.setAttribute('class', normalizedNext);\n } else {\n el.className = normalizedNext;\n }\n}\n\n/**\n * Normalizes different class value formats into a single string\n * Re-exports normalizeClassName from shared as normalizeClass for backward compatibility\n *\n * @param value - The class value to normalize\n * @returns A normalized class string\n * @public\n */\nexport function normalizeClass(value: unknown): string {\n return normalizeClassName(value);\n}\n","import { camelCase, capitalize, isArray, isObject, isString } from '@estjs/shared';\nimport { isHydrating } from '../hydration/shared';\n\n/**\n * Symbol for storing CSS variable text in style objects\n * @internal\n */\nexport const CSS_VAR_TEXT: unique symbol = Symbol('CSS_VAR_TEXT');\n\n// Cache regex patterns for better performance\nconst importantRE = /\\s*!important$/;\n\n// Cache browser prefixes for better performance\nconst prefixes = ['Webkit', 'Moz', 'ms'];\nconst prefixCache: Record<string, string> = {};\n\n/**\n * Type definition for style values\n * @public\n */\nexport type Style = string | Record<string, string | string[]> | null | undefined;\n\n/**\n * Patches the style of an element, optimized for different style formats\n * Supports silent hydration (skips DOM updates during hydration phase)\n *\n * @param el - The element to patch styles on\n * @public\n */\nexport function patchStyle(el: HTMLElement, prev: unknown, next: unknown) {\n const style = el.style;\n const isCssString = isString(next);\n if (isHydrating()) {\n return;\n }\n if (next && isCssString) {\n if (prev !== next) {\n style.cssText = next;\n }\n return;\n }\n\n if (!next) {\n if (prev) {\n el.removeAttribute('style');\n }\n return;\n }\n\n // Handle object-based styles\n if (prev && !isString(prev)) {\n // Remove styles that are no longer present\n for (const key in prev) {\n if (!next || next[key as keyof typeof next] == null) {\n setStyle(style, key, '');\n }\n }\n } else if (prev && isString(prev)) {\n // Handle previous string-based styles\n const prevStyles = prev.split(';');\n for (const stylePart of prevStyles) {\n const colonIndex = stylePart.indexOf(':');\n if (colonIndex > 0) {\n const key = stylePart.slice(0, colonIndex).trim();\n if (next && isObject(next) && next[key] == null) {\n setStyle(style, key, '');\n }\n }\n }\n }\n\n // Set new styles\n if (next && !isString(next)) {\n for (const key in next) {\n const value = next[key];\n if ((!prev || isString(prev) || prev[key] !== value) && value != null) {\n setStyle(style, key, value);\n }\n }\n }\n}\n\n/**\n * Sets an individual style property with various optimizations\n *\n * @param style - The style object to modify\n * @param name - The style property name\n * @param val - The style property value\n * @private\n */\nexport function setStyle(style: CSSStyleDeclaration, name: string, val: string | string[]): void {\n // Handle array values (vendor prefixed values)\n if (isArray(val)) {\n for (const element of val) {\n setStyle(style, name, element);\n }\n return;\n }\n\n if (val == null || val === '') {\n val = '';\n }\n\n // Handle CSS custom properties\n if (name.startsWith('--')) {\n style.setProperty(name, val);\n return;\n }\n\n // Handle regular CSS properties with potential prefixing\n const prefixed = autoPrefix(style, name);\n\n // Handle !important\n if (isString(val) && importantRE.test(val)) {\n style.setProperty(camelCase(prefixed), val.replace(importantRE, ''), 'important');\n } else {\n style[prefixed] = val;\n }\n}\n\n/**\n * Adds vendor prefixes to style properties as needed\n *\n * @param style - The style object to check against\n * @param rawName - The raw property name\n * @returns The prefixed property name if needed\n * @private\n */\nfunction autoPrefix(style: CSSStyleDeclaration, rawName: string): string {\n // Check cache first\n const cached = prefixCache[rawName];\n if (cached) {\n return cached;\n }\n\n // Try camelCase version directly\n let name = camelCase(rawName);\n if (name !== 'filter' && name in style) {\n return (prefixCache[rawName] = name);\n }\n\n // Try with vendor prefixes\n name = capitalize(name);\n for (const prefix of prefixes) {\n const prefixed = prefix + name;\n if (prefixed in style) {\n return (prefixCache[rawName] = prefixed);\n }\n }\n\n return rawName;\n}\n","import {\n includeBooleanAttr,\n isBooleanAttr,\n isObject,\n isSpecialBooleanAttr,\n isString,\n isSymbol,\n warn,\n} from '@estjs/shared';\nimport {\n KEY_PROP,\n SPREAD_NAME,\n SVG_NAMESPACE,\n XLINK_NAMESPACE,\n XMLNS_NAMESPACE,\n} from '../constants';\nimport { setNodeKey } from '../key';\nimport { isHydrating } from '../hydration/shared';\n\nexport type AttrValue = string | boolean | number | null | undefined | Record<string, unknown>;\n\nexport function patchAttr(el: Element, key: string, prev: AttrValue, next: AttrValue) {\n if (key === KEY_PROP) {\n if (next == null) {\n setNodeKey(el, undefined);\n } else {\n setNodeKey(el, String(next));\n }\n return;\n }\n if (key === SPREAD_NAME) {\n if (__DEV__) {\n if (!isObject(next)) {\n warn('spread attribute must be an object');\n }\n }\n Object.keys(next as Record<string, unknown>).forEach(k => {\n patchAttr(el, k, prev?.[k], next?.[k]);\n });\n return;\n }\n\n if (isHydrating()) {\n return;\n }\n const elementIsSVG = el?.namespaceURI === SVG_NAMESPACE;\n const isXlink = elementIsSVG && key.startsWith('xlink:');\n const isXmlns = elementIsSVG && key.startsWith('xmlns:');\n\n const isBoolean = isSpecialBooleanAttr(key) || isBooleanAttr(key);\n\n // Early return if values are the same\n if (prev === next) {\n return;\n }\n\n // Compute lowerKey only when needed (after early exits)\n const lowerKey = key.toLowerCase();\n\n // Cache event handler check (faster than regex for common case)\n if (lowerKey.length > 2 && lowerKey.charCodeAt(0) === 111 && lowerKey.charCodeAt(1) === 110) {\n // 'on'\n return;\n }\n\n if (lowerKey === 'innerhtml') {\n return;\n }\n\n if (next == null) {\n if (isXlink) {\n el.removeAttributeNS(XLINK_NAMESPACE, key.slice(6));\n } else if (isXmlns) {\n const localName = key.slice(6);\n el.removeAttributeNS(XMLNS_NAMESPACE, localName);\n } else {\n el.removeAttribute(key);\n }\n return;\n }\n\n if (isXlink) {\n el.setAttributeNS(XLINK_NAMESPACE, key, String(next));\n return;\n }\n\n if (isXmlns) {\n el.setAttributeNS(XMLNS_NAMESPACE, key, String(next));\n return;\n }\n\n if (isBoolean) {\n if (includeBooleanAttr(next)) {\n el.setAttribute(key, '');\n } else {\n el.removeAttribute(key);\n }\n return;\n }\n\n const attrValue = isSymbol(next) ? String(next) : next;\n\n const isUrlAttr = lowerKey === 'href' || lowerKey === 'src' || lowerKey === 'xlink:href';\n if (isUrlAttr && isString(attrValue)) {\n const v = attrValue.trim().toLowerCase();\n if (v.startsWith('javascript:') || v.startsWith('data:')) {\n return;\n }\n }\n\n if (elementIsSVG) {\n el.setAttribute(key, String(attrValue));\n } else {\n if (key in el) {\n try {\n el[key] = attrValue;\n } catch {\n el.setAttribute(key, String(attrValue));\n }\n } else {\n el.setAttribute(key, String(attrValue));\n }\n }\n}\n","/**\n * Extended event options with delegation support\n * @public\n */\nexport interface EventOptions extends AddEventListenerOptions {\n /**\n * CSS selector for event delegation\n * When provided, the event will only trigger if the target matches this selector\n */\n delegate?: string;\n}\n\n/**\n * Event handler cleanup function\n * @public\n */\nexport type EventCleanup = () => void;\n\n/**\n * Adds an event listener to an element with optional delegation\n *\n * @param el - The element to attach the event to\n * @param event - The event name (e.g., 'click', 'input')\n * @param handler - The event handler function\n * @param options - Additional event options including delegation\n * @returns A cleanup function to remove the event listener\n * @public\n */\nexport function addEvent(\n el: Element,\n event: string,\n handler: EventListener,\n options?: EventOptions,\n): EventCleanup {\n if (!options?.delegate) {\n el.addEventListener(event, handler, options);\n return () => el.removeEventListener(event, handler, options);\n }\n\n // Delegation path: use simple wrapper\n const selector = options.delegate;\n const wrappedHandler = (e: Event) => {\n const target = e.target as Element;\n if (target.matches(selector) || target.closest(selector)) {\n handler.call(el, e);\n }\n };\n\n // Clean options object by removing delegate property\n const cleanOptions = { ...options };\n cleanOptions.delegate = undefined;\n\n // Add the event listener with the wrapped handler\n el.addEventListener(event, wrappedHandler, cleanOptions);\n\n // Return cleanup function\n return () => {\n el.removeEventListener(event, wrappedHandler, cleanOptions);\n };\n}\n","import { error } from '@estjs/shared';\nimport { FRAGMENT_COMPONENT } from '../constants';\nimport type { AnyNode, ComponentProps } from '../types';\n\nexport interface FragmentProps extends ComponentProps {\n children?: AnyNode | AnyNode[];\n}\n\n/**\n * Fragment component - renders multiple children without wrapper elements (Client-side only)\n *\n * **Client-side behavior:**\n * - Returns children directly for rendering\n * - Hydration system matches children using hydration keys\n * - The template system handles array children automatically\n *\n * @param props - Component props with children\n * @returns Children directly without wrapper\n *\n * @example\n * ```tsx\n * // Basic usage\n * <Fragment>\n * <div>First</div>\n * <span>Second</span>\n * </Fragment>\n *\n * // Nested fragments\n * <Fragment>\n * <Fragment>\n * <div>Nested 1</div>\n * <div>Nested 2</div>\n * </Fragment>\n * <div>Third</div>\n * </Fragment>\n *\n * // Empty fragment (renders nothing)\n * <Fragment />\n * ```\n */\nexport function Fragment(props?: FragmentProps): AnyNode {\n if (__DEV__) {\n if (!props) {\n error('Fragment component requires props');\n return null;\n }\n }\n\n // Handle empty fragment - return null\n if (!props?.children) {\n error('Fragment component requires children');\n return null;\n }\n\n const { children } = props;\n\n // Client-side rendering: Return children directly\n // The template system will handle them appropriately\n return children as AnyNode;\n}\n\nFragment[FRAGMENT_COMPONENT] = true;\n\n/**\n * Check if a node is a Fragment component\n * @param node - Node to check\n * @returns true if node is a Fragment\n */\nexport function isFragment(node: unknown): boolean {\n return !!node && !!node[FRAGMENT_COMPONENT];\n}\n","import { isArray, isString, warn } from '@estjs/shared';\nimport { insertNode } from '../utils/dom';\nimport { normalizeNode } from '../utils/node';\nimport { onMount } from '../lifecycle';\nimport { onCleanup } from '../scope';\nimport { PORTAL_COMPONENT } from '../constants';\nimport type { AnyNode } from '../types';\n\nexport interface PortalProps {\n children?: AnyNode | AnyNode[];\n target: string | HTMLElement;\n key?: string;\n}\n\n/**\n * Portal component - renders children into a different DOM node\n *\n * @param props - Component props with children and target\n * @returns Comment node as placeholder in parent tree\n *\n * @example\n * ```tsx\n * <Portal target=\"#modal-root\">\n * <div>Modal content</div>\n * </Portal>\n */\nexport function Portal(props: PortalProps): Comment | string {\n // Create placeholder comment for parent tree\n const placeholder = document.createComment('portal');\n placeholder[PORTAL_COMPONENT] = true;\n const children = props.children;\n if (children) {\n const childArray = isArray(children) ? children : [children];\n const nodes: (Node | string)[] = [];\n\n onMount(() => {\n // Get target element\n const targetElement = isString(props.target)\n ? document.querySelector(props.target)\n : props.target;\n\n if (!targetElement) {\n if (__DEV__) {\n warn(`[Portal] Target element not found: ${props.target}`);\n }\n return;\n }\n\n childArray.forEach(child => {\n if (child != null) {\n const normalized = normalizeNode(child);\n if (normalized) {\n insertNode(targetElement as Node, normalized);\n nodes.push(normalized);\n }\n }\n });\n\n onCleanup(() => {\n nodes.forEach(node => {\n if (!isString(node) && node.parentNode === targetElement) {\n targetElement.removeChild(node);\n }\n });\n });\n });\n }\n\n return placeholder;\n}\n\nPortal[PORTAL_COMPONENT] = true;\n\n/**\n * Check if a node is a Portal component\n * @param node - Node to check\n * @returns true if node is a Portal\n */\nexport function isPortal(node: unknown): boolean {\n return !!node && !!node[PORTAL_COMPONENT];\n}\n","import { isArray, isPromise, isUndefined, warn } from '@estjs/shared';\nimport { provide } from '../provide';\nimport { isComponent } from '../component';\nimport { normalizeNode } from '../utils/node';\nimport { onDestroy } from '../lifecycle';\nimport { getActiveScope } from '../scope';\nimport { insertNode } from '../utils/dom';\nimport { SUSPENSE_COMPONENT } from '../constants';\nimport type { AnyNode } from '../types';\n\nexport interface SuspenseProps {\n /** The content to render. Can be a Promise for async loading. */\n children?: AnyNode | AnyNode[] | Promise<AnyNode | AnyNode[]>;\n /** Fallback content to display while children is loading (Promise pending). */\n fallback?: AnyNode;\n /** Optional key for reconciliation. */\n key?: string;\n}\n\n/**\n * Suspense component - handles async content with a fallback UI\n *\n * @param props - Component props with children, fallback, and optional key\n * @returns Placeholder node or fallback content\n *\n * @example\n * ```tsx\n * <Suspense fallback={<div>Loading...</div>}>\n * {asyncContent}\n * </Suspense>\n * ```\n */\nexport const SuspenseContext = Symbol('SuspenseContext');\n\nexport interface SuspenseContextType {\n register: (promise: Promise<any>) => void;\n increment: () => void;\n decrement: () => void;\n}\n\n/**\n * Suspense component - handles async content with a fallback UI\n *\n * @param props - Component props with children, fallback, and optional key\n * @returns Placeholder node or fallback content\n *\n * @example\n * ```tsx\n * <Suspense fallback={<div>Loading...</div>}>\n * {asyncContent}\n * </Suspense>\n * ```\n */\nexport function Suspense(props: SuspenseProps): AnyNode {\n // Check if we're in SSR mode (no document)\n if (isUndefined(document)) {\n // In SSR, return fallback as string if available\n const fallback = props.fallback;\n if (fallback) {\n return String(fallback || '');\n }\n return '';\n }\n\n // Create a container to manage content swapping\n const container = document.createElement('div');\n container.style.display = 'contents'; // Invisible wrapper\n\n // Track if component is still mounted (for async cleanup)\n let isMounted = true;\n let pendingCount = 0;\n let isShowingFallback = false;\n\n let resolvedChildren: AnyNode | AnyNode[] | null = null;\n\n const showFallback = () => {\n if (isShowingFallback) return;\n isShowingFallback = true;\n\n // Clear container\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n if (props.fallback != null) {\n const normalized = normalizeNode(props.fallback);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n };\n\n const showChildren = () => {\n if (!isShowingFallback) return;\n\n // Check if we have something to show\n // If children is a promise, we need resolvedChildren.\n // If children is not a promise, we use it directly.\n const hasContent = resolvedChildren || (props.children != null && !isPromise(props.children));\n\n if (!hasContent) {\n // If we don't have content (e.g. promise rejected), keep fallback\n return;\n }\n\n isShowingFallback = false;\n\n // Clear container (remove fallback)\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n // Simple implementation: Re-render children\n if (resolvedChildren) {\n renderChildren(resolvedChildren);\n } else if (props.children != null && !isPromise(props.children)) {\n renderChildren(props.children);\n }\n };\n\n /**\n * Render children into the container\n */\n const renderChildren = (children: AnyNode | AnyNode[]): void => {\n // Clear existing content\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n if (children == null) return;\n\n const currentScope = getActiveScope();\n const childArray = isArray(children) ? children : [children];\n childArray.forEach(child => {\n if (child != null) {\n // Reparent component to current context to ensure it can access SuspenseContext\n // This is necessary because children are created in the parent scope\n if (isComponent(child)) {\n // @ts-ignore\n child.parentContext = currentScope;\n }\n\n const normalized = normalizeNode(child);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n });\n\n // Fix: If a child suspended during insertion, we might have both fallback and children in the container.\n // We need to ensure that if we are in fallback mode, only fallback is shown.\n if (isShowingFallback) {\n // We are in fallback mode.\n // Clear everything (including the just-inserted children)\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n // Re-insert fallback\n if (props.fallback != null) {\n const normalized = normalizeNode(props.fallback);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n }\n };\n\n // Context for resources to register themselves\n const suspenseContext: SuspenseContextType = {\n register: (promise: Promise<any>) => {\n pendingCount++;\n showFallback();\n\n promise\n .then(() => {\n if (!isMounted) return;\n pendingCount--;\n if (pendingCount === 0) {\n showChildren();\n }\n })\n .catch(error => {\n if (__DEV__) {\n warn('[Suspense] Resource failed:', error);\n }\n if (!isMounted) return;\n pendingCount--;\n // For now, if error happens, we still try to show children (or maybe error boundary later)\n if (pendingCount === 0) {\n showChildren();\n }\n });\n },\n increment: () => {\n pendingCount++;\n showFallback();\n },\n decrement: () => {\n pendingCount--;\n if (pendingCount === 0) {\n showChildren();\n }\n },\n };\n\n provide(SuspenseContext, suspenseContext);\n\n const children = props.children;\n\n // Initial render logic\n if (isPromise(children)) {\n // Async children - show fallback immediately, then resolve\n children\n .then(resolved => {\n resolvedChildren = resolved;\n })\n .catch(() => {\n // Ignore error, handled by register\n });\n suspenseContext.register(children);\n } else if (children != null) {\n // Sync children - render immediately\n // If any child is a resource read, it will call register() synchronously during this render\n renderChildren(children);\n } else {\n // No children - show fallback if available\n showFallback();\n }\n\n onDestroy(() => {\n isMounted = false;\n // Clear container\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n });\n\n return container;\n}\n\nSuspense[SUSPENSE_COMPONENT] = true;\n\n/**\n * Check if a node is a Suspense component\n * @param node - Node to check\n * @returns true if node is a Suspense\n */\nexport function isSuspense(node: unknown): boolean {\n return !!node && !!node[SUSPENSE_COMPONENT];\n}\n","import { type Signal, signal } from '@estjs/signals';\nimport { inject } from '../provide';\nimport { SuspenseContext } from './Suspense';\n\nexport type ResourceState = 'pending' | 'ready' | 'errored';\n\nexport interface Resource<T> {\n (): T | undefined;\n loading: Signal<boolean>;\n error: Signal<Error | null>;\n state: Signal<ResourceState>;\n}\n\nexport interface ResourceActions<T> {\n mutate: (value: T) => void;\n refetch: () => Promise<void>;\n}\n\nexport interface ResourceOptions<T> {\n initialValue?: T;\n}\n\n/**\n * Create a resource for async data fetching\n * Inspired by SolidJS createResource\n *\n * @param fetcher - Function that returns a Promise with the data\n * @param options - Optional configuration\n * @returns Tuple of [resource, actions]\n *\n * @example\n * ```typescript\n * const [data, { refetch, mutate }] = createResource(\n * () => fetch('/api/user').then(r => r.json()),\n * { initialValue: null }\n * );\n *\n * // Access data\n * console.log(data());\n * console.log(data.loading.value);\n * console.log(data.state.value);\n *\n * // Refetch data\n * await refetch();\n *\n * // Update data directly\n * mutate({ name: 'John' });\n * ```\n */\nexport function createResource<T>(\n fetcher: () => Promise<T>,\n options?: ResourceOptions<T>,\n): [Resource<T>, ResourceActions<T>] {\n // Internal state\n const value = signal<T | undefined>(options?.initialValue);\n const loading = signal<boolean>(true);\n const error = signal<Error | null>(null);\n const state = signal<ResourceState>('pending');\n\n let fetchId = 0;\n\n let currentPromise: Promise<void> | null = null;\n\n // Fetch function\n const fetch = async (): Promise<void> => {\n const currentFetchId = ++fetchId;\n loading.value = true;\n state.value = 'pending';\n error.value = null;\n\n try {\n const promise = fetcher();\n currentPromise = promise.then(() => {}).catch(() => {}); // Ensure promise is handled\n const result = await promise;\n\n // Only update if this is still the latest fetch\n if (currentFetchId === fetchId) {\n value.value = result;\n state.value = 'ready';\n loading.value = false;\n }\n } catch (error_) {\n // Only update if this is still the latest fetch\n if (currentFetchId === fetchId) {\n error.value = error_ instanceof Error ? error_ : new Error(String(error_));\n state.value = 'errored';\n loading.value = false;\n }\n }\n };\n\n // Start initial fetch\n fetch();\n\n // Resource accessor function\n const resource = (() => {\n // If we are loading and have a suspense context, register the promise\n if (loading.value && currentPromise) {\n const suspenseContext = inject(SuspenseContext, null);\n if (suspenseContext) {\n // @ts-ignore\n suspenseContext.register(currentPromise);\n }\n }\n return value.value;\n }) as Resource<T>;\n resource.loading = loading;\n resource.error = error;\n resource.state = state;\n\n // Actions\n const actions: ResourceActions<T> = {\n mutate: (newValue: T) => {\n value.value = newValue;\n state.value = 'ready';\n loading.value = false;\n error.value = null;\n },\n refetch: async () => {\n await fetch();\n },\n };\n\n return [resource, actions];\n}\n","import { type Signal, isSignal, memoEffect, untrack } from '@estjs/signals';\nimport {\n type Scope,\n createScope,\n disposeScope,\n getActiveScope,\n onCleanup,\n setActiveScope,\n} from '../scope';\nimport { isComponent } from '../component';\nimport { FOR_COMPONENT } from '../constants';\nimport type { AnyNode } from '../types';\n\nexport interface ForProps<T> {\n each: T[] | Signal<T[]> | (() => T[]);\n children: (item: T, index: number) => AnyNode;\n keyFn?: (item: T) => unknown;\n fallback?: () => AnyNode;\n}\n\ninterface ItemEntry {\n key: unknown;\n node: Node;\n scope: Scope; // Track scope for cleanup\n}\n\n/**\n * Optimized For Component\n * - Uses createDetachedScope to avoid parent.children Set overhead (SolidJS style)\n * - Uses DocumentFragment batching for mass creation\n * - Inlines scope switching for performance\n */\nexport function For<T>(props: ForProps<T>): Node {\n const fragment = document.createDocumentFragment();\n const marker = document.createComment('');\n fragment.appendChild(marker);\n\n let entries: ItemEntry[] = [];\n let fallbackNode: Node | null = null;\n\n const keyFn = props.keyFn;\n const renderFn = props.children;\n\n const getList = (): T[] => {\n const input = props.each;\n if (isSignal(input)) return (input as Signal<T[]>).value ?? [];\n if (typeof input === 'function') return (input as () => T[])() ?? [];\n return (input as T[]) ?? [];\n };\n\n const getKey = (item: T): unknown => (keyFn ? keyFn(item) : item);\n\n /**\n * Render item with detached scope.\n */\n const renderItem = (item: T, index: number, parent: Node, before: Node | null): ItemEntry => {\n const prevScope = getActiveScope();\n\n const scope = createScope(prevScope);\n\n setActiveScope(scope);\n\n let node: AnyNode;\n try {\n const result = renderFn(item, index);\n if (isComponent(result)) {\n result.mount(parent, before as Node); // Cast null to Node is okay for beforeNode? mount expects Node|undefined\n node = result.firstChild ?? document.createComment('empty');\n } else {\n node = result as Node;\n // Insert node manually if not handled by Component.mount\n if (!node.parentNode) {\n if (before) {\n parent.insertBefore(node, before);\n } else {\n parent.appendChild(node);\n }\n }\n }\n } finally {\n setActiveScope(prevScope);\n }\n\n return { key: getKey(item), node: node! as Node, scope };\n };\n\n const disposeItem = (entry: ItemEntry) => {\n disposeScope(entry.scope);\n if (entry.node.parentNode) {\n entry.node.parentNode.removeChild(entry.node);\n }\n };\n\n memoEffect(\n ({ prev }) => {\n const newItems = getList();\n\n if (prev === newItems) return { prev: newItems };\n\n const parent = marker.parentNode;\n\n // Initial mount (parent is null because fragment is not attached yet)\n if (!parent) {\n if (newItems.length === 0) {\n if (props.fallback) {\n const fb = props.fallback();\n if (isComponent(fb)) {\n fb.mount(fragment, marker);\n fallbackNode = fb.firstChild ?? document.createComment('empty');\n } else {\n fallbackNode = fb as Node;\n fragment.insertBefore(fallbackNode, marker);\n }\n }\n return { prev: newItems };\n }\n\n entries = new Array(newItems.length);\n\n for (const [i, newItem] of newItems.entries()) {\n entries[i] = renderItem(newItem, i, fragment, marker);\n }\n return { prev: newItems };\n }\n\n untrack(() => reconcile(parent, newItems));\n return { prev: newItems };\n },\n {\n prev: [] as T[],\n },\n );\n\n function reconcile(parent: Node, newItems: T[]): void {\n const oldLen = entries.length;\n const newLen = newItems.length;\n\n // ===== FAST PATH 1: Clear all =====\n if (newLen === 0) {\n for (let i = 0; i < oldLen; i++) {\n disposeItem(entries[i]);\n }\n entries = [];\n\n if (props.fallback && !fallbackNode) {\n const fb = props.fallback();\n if (isComponent(fb)) {\n fb.mount(parent, marker);\n fallbackNode = fb.firstChild ?? document.createComment('empty');\n } else {\n fallbackNode = fb as Node;\n parent.insertBefore(fallbackNode, marker);\n }\n }\n return;\n }\n\n // ===== FAST PATH 2: Create all (from empty/fallback) =====\n if (oldLen === 0 || fallbackNode) {\n if (fallbackNode) {\n if (fallbackNode.parentNode) fallbackNode.parentNode.removeChild(fallbackNode);\n fallbackNode = null;\n }\n\n entries = new Array(newLen);\n\n // Batch creation in fragment\n const batchFragment = document.createDocumentFragment();\n\n for (let i = 0; i < newLen; i++) {\n // Render to batchFragment, append to end (before=null)\n entries[i] = renderItem(newItems[i], i, batchFragment, null);\n }\n\n parent.insertBefore(batchFragment, marker);\n return;\n }\n\n // ===== Keyed reconciliation =====\n const oldKeyMap = new Map<unknown, ItemEntry[]>();\n for (let i = 0; i < oldLen; i++) {\n const entry = entries[i];\n const list = oldKeyMap.get(entry.key);\n if (list) {\n list.push(entry);\n } else {\n oldKeyMap.set(entry.key, [entry]);\n }\n }\n\n const newEntries: ItemEntry[] = new Array(newLen);\n const toRemove: ItemEntry[] = [];\n\n // Batch new nodes in fragment\n const batchFragment = document.createDocumentFragment();\n\n for (let i = 0; i < newLen; i++) {\n const item = newItems[i];\n const key = getKey(item);\n const oldList = oldKeyMap.get(key);\n\n if (oldList && oldList.length > 0) {\n newEntries[i] = oldList.shift()!;\n } else {\n newEntries[i] = renderItem(item, i, batchFragment, null);\n }\n }\n\n for (const list of oldKeyMap.values()) {\n for (const entry of list) {\n toRemove.push(entry);\n }\n }\n\n for (const entry of toRemove) {\n disposeItem(entry);\n }\n\n // Efficient Reorder\n // If we have new nodes in batchFragment, they are not yet in DOM.\n // Existing nodes are in DOM.\n // We iterate 0..newLen.\n // If node is in batchFragment, we must insert it.\n // If node is in DOM, we check order.\n\n for (let i = 0; i < newLen; i++) {\n const node = newEntries[i].node;\n parent.insertBefore(node, marker);\n }\n\n entries = newEntries;\n }\n\n onCleanup(() => {\n for (const entry of entries) {\n disposeItem(entry);\n }\n if (fallbackNode && fallbackNode.parentNode) {\n fallbackNode.parentNode.removeChild(fallbackNode);\n }\n if (marker.parentNode) {\n marker.parentNode.removeChild(marker);\n }\n });\n\n return fragment;\n}\n\nFor[FOR_COMPONENT] = true;\n\nexport function isFor(node: unknown): boolean {\n return !!node && !!(node as Record<symbol, boolean>)[FOR_COMPONENT];\n}\n"]}