@estjs/template 0.0.15-beta.1 → 0.0.15-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/template.cjs.js +3 -3
- package/dist/template.cjs.js.map +1 -1
- package/dist/template.d.cts +89 -2285
- package/dist/template.d.ts +89 -2285
- package/dist/template.dev.cjs.js +425 -282
- package/dist/template.dev.esm.js +427 -285
- package/dist/template.esm.js +4 -4
- package/dist/template.esm.js.map +1 -1
- package/package.json +3 -3
- package/types/component.d.ts +0 -21
- package/types/index.d.ts +0 -3
- package/types/jsx.d.ts +0 -2209
- package/types/node.d.ts +0 -15
package/dist/template.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/renderer.ts","../src/context.ts","../src/lifecycle.ts","../src/constants.ts","../src/key.ts","../src/utils.ts","../src/patch.ts","../src/binding.ts","../src/component.ts","../src/provide.ts","../src/events.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/server/shared.ts","../src/server/render.ts","../src/server/attrs.ts","../src/server/hydration.ts"],"names":["activeContext","contextStack","contextId","createContext","parent","context","getActiveContext","pushContextStack","popContextStack","destroyContext","cleanupContext","fn","error_","error","LIFECYCLE","registerLifecycleHook","type","hook","triggerLifecycleHook","hooks","onMount","onDestroy","onUpdate","SVG_NAMESPACE","XLINK_NAMESPACE","XMLNS_NAMESPACE","DATA_IDX_REGEX","MAX_KEY_LENGTH","componentKeyPrefixCache","getComponentKey","prefix","name","hash","simpleHash","str","len","i","symbolIdCounter","normalizeKey","key","isFalsy","isString","isNumber","isSymbol","globalKey","desc","NODE_KEY_SYMBOL","setNodeKey","node","isComponent","normalizedKey","getNodeKey","removeNode","element","_error","insertNode","child","before","beforeNode","replaceNode","newNode","oldNode","getFirstDOMNode","isSameNode","a","b","keyA","keyB","aIsComponent","bIsComponent","aNode","bNode","normalizeNode","isHTMLElement","isPrimitive","textContent","isHtmlInputElement","val","isHtmlSelectElement","isHtmlTextAreaElement","isHtmLTextElement","shallowCompare","transferKey","oldKey","patch","oldIsElement","oldAttrs","newAttrs","attrName","attr","oldIsComponent","newIsComponent","patchChildren","oldChildren","newChildren","anchor","oldLength","newLength","fragment","o0","o1","n0","n1","dom1","dom0","patchKeyedChildren","oldStartIdx","newStartIdx","oldEndIdx","newEndIdx","oldStartNode","oldEndNode","newStartNode","newEndNode","anchorNode","patchUnknownSequence","newChildrenLen","keyToNewIndexMap","newIndexToOldIndexMap","moved","maxNewIndexSoFar","patched","newIndex","j","increasingNewIndexSequence","getSequence","nextIndex","nextNode","nextAnchor","domNode","arr","result","p","u","v","arrI","addEventListener","event","handler","options","bindElement","defaultValue","setter","values","option","insert","nodeFactory","renderedNodes","cleanup","effect","rawNodes","isFunction","nodes","coerceArray","mapNodes","template","indexes","tree","indexSet","index","found","walk","_a","Component","component","props","shallowReactive","__spreadValues","isObject","parentNode","isSignal","isComputed","prevNode","newValue","oldValue","snapshot","newSnapshot","hasChanged","__async","rendered","propName","propValue","startsWith","eventName","createComponent","componentFn","html","create","firstChild","createApp","target","container","rootComponent","provide","value","inject","currentContext","isNil","eventHandler","oriTarget","oriCurrentTarget","reTarget","handleNode","data","walkUpTree","path","$EVENTS","delegateEvents","eventNames","document","docWithEvents","eventSet","patchClass","el","prev","next","isSVG","normalizedNext","normalizeClass","normalizedPrev","isArray","importantRE","prefixes","prefixCache","patchStyle","style","isCssString","setStyle","prevStyles","stylePart","colonIndex","prefixed","autoPrefix","camelCase","rawName","cached","capitalize","patchAttr","elementIsSVG","isXlink","isXmlns","isBoolean","isSpecialBooleanAttr","isBooleanAttr","lowerKey","localName","includeBooleanAttr","attrValue","e","addEvent","selector","wrappedHandler","cleanOptions","Fragment","children","normalized","isFragment","Portal","placeholder","targetElement","isPortal","SuspenseContext","Suspense","isUndefined","fallback","isMounted","pendingCount","isShowingFallback","resolvedChildren","showFallback","showChildren","isPromise","renderChildren","suspenseContext","promise","resolved","isSuspense","createResource","fetcher","signal","loading","state","fetchId","currentPromise","fetch","currentFetchId","resource","hydrationCounter","getHydrationKey","resetHydrationKey","endHydration","convertToString","content","isSvg","item","addAttributes","htmlContent","hydrationId","rootElementRegex","indexAttributeRegex","commentRegex","renderToString","render","templates","hydrationKey","components","createSSGComponent","normalizeStyle","styleValue","normalizedStyleObject","styleItem","normalizedItem","parseStyleString","styleSeparatorRegex","propertyValueSeparatorRegex","styleCommentRegex","cssText","styleObject","parts","styleObjectToString","normalizedPropName","kebabCase","normalizeClassName","classValue","resultClassName","className","setSSGAttr","normalizedStyle","normalizedClassName","getRenderedElement","temp","mapSSRNodes","idx","hk","nodesList","elements","idxAttr","hkPart","idxPart","commentNodes","walkNodes","indexValue","hydrate","rootElement"],"mappings":";;;;;AAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,qBAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,cAAA,CAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,oBAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,IAAA,CAAA,IAAA,CAAA,GAAA,CAAA,CAAA,EAAA,CAAA,CAAA,EAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,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,CAEMwG,CACT,CAUO,SAAS8L,GACdlL,CAAAA,CACA2B,CAAAA,CACA1B,CAAAA,CAAiC,GAC5B,CAIL4H,CAAAA,EAAkB,CAElB,GAAI,CAEF,IAAMsD,CAAAA,CAAc9S,QAAAA,CAASsJ,CAAS,CAAA,CAAI,QAAA,CAAS,cAAcA,CAAS,CAAA,CAAIA,EAE9E,GAAI,CAACwJ,CAAAA,CAAa,CAChB1U,MAAM,yCAAyC,CAAA,CAC/C,MACF,CAGA,IAAMmL,EAAgBR,CAAAA,CAAgBpB,CAAAA,CAAWC,CAAK,CAAA,CACtD,OAAA2B,CAAAA,CAAc,KAAA,CAAMuJ,CAAW,CAAA,CAG/BrD,EAAAA,GAEOlG,CACT,CAAA,MAASpL,CAAAA,CAAQ,CACfC,MAAM,kBAAA,CAAoBD,CAAM,CAEnB,CACb,MACF,CACF","file":"template.esm.js","sourcesContent":["import { error, isString } from '@estjs/shared';\nimport { type ComponentFn, createComponent } from './component';\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 * @example\n * ```typescript\n * const buttonTemplate = template('<button>Click me</button>');\n * const button1 = buttonTemplate(); // Creates first button instance\n * const button2 = buttonTemplate(); // Creates second button instance\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 *\n * @example\n * ```typescript\n * const App = () => template('<div>Hello World</div>')\n * const app = createApp(App, '#root');\n *\n * // Or with DOM element\n * const container = document.getElementById('app');\n * const app = createApp(App, container);\n * ```\n */\nexport function createApp(component: ComponentFn, target: string | Element) {\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\n const rootComponent = createComponent(component);\n rootComponent.mount(container);\n\n return rootComponent;\n}\n","import { error } from '@estjs/shared';\nimport type { InjectionKey } from './provide';\n\n/**\n * context interface\n */\nexport interface Context {\n id: number;\n parent: Context | null;\n provides: Map<InjectionKey<unknown> | number | string | symbol, any>;\n cleanup: Set<() => void>;\n mount: Set<() => void | Promise<void>>;\n update: Set<() => void | Promise<void>>;\n destroy: Set<() => void | Promise<void>>;\n isMount: boolean;\n isDestroy: boolean;\n children: Set<Context>;\n}\n\n// active context\nlet activeContext: Context | null = null;\n// context stack\nconst contextStack: Context[] = [];\nlet contextId = 0;\n\n/**\n * create a new context\n * @param {Context} parent - the parent context\n * @returns {Context} the new context\n */\nexport function createContext(parent: Context | null = null) {\n const context: Context = {\n id: ++contextId,\n parent,\n provides: new Map(),\n cleanup: new Set(),\n mount: new Set(),\n update: new Set(),\n destroy: new Set(),\n isMount: false,\n isDestroy: false,\n children: new Set(),\n };\n\n if (parent) {\n parent.children.add(context);\n }\n\n return context;\n}\n\n/**\n * get the active context\n */\nexport function getActiveContext(): Context | null {\n return activeContext;\n}\n\n/**\n * set the active context\n * @param {Context} context - the context to set as active\n */\nexport function setActiveContext(context: Context | null) {\n activeContext = context;\n}\n\n/**\n * push a context to the stack\n * @param {Context} context - the context to push to the stack\n */\nexport function pushContextStack(context: Context): void {\n if (activeContext) {\n contextStack.push(activeContext);\n }\n activeContext = context;\n}\n\n/**\n * pop a context from the stack\n */\nexport function popContextStack(): void {\n activeContext = contextStack.pop() || null;\n}\nexport function withContext<T>(context: Context, fn: () => T): T {\n pushContextStack(context);\n try {\n return fn();\n } finally {\n popContextStack();\n }\n}\n\n/**\n * find a parent context\n */\nexport function findParentContext(): Context | null {\n // use current active context\n if (activeContext) {\n return activeContext;\n }\n\n // find the first not destroy context from the top of the stack\n for (let i = contextStack.length - 1; i >= 0; i--) {\n const contextItem = contextStack[i];\n if (contextItem && !contextItem.isDestroy) {\n return contextItem;\n }\n }\n\n return null;\n}\n/**\n * destroy a context and all its children\n * @param {Context} context - the context to destroy\n */\nexport function destroyContext(context: Context): void {\n // already destroy\n if (!context || context.isDestroy) {\n return;\n }\n\n // Make a copy of children to avoid modification during iteration\n const childrenToDestroy = Array.from(context.children);\n\n // destroy all children contexts\n childrenToDestroy.forEach(destroyContext);\n\n // cleanup the current context\n cleanupContext(context);\n}\n\n/**\n * cleanup a context\n * @param {Context} context - the context to cleanup\n */\nexport function cleanupContext(context: Context) {\n // already destroy\n if (!context || context.isDestroy) {\n return;\n }\n\n // Clean parent-child relationship to break potential circular references\n if (context.parent) {\n context.parent.children.delete(context);\n context.parent = null;\n }\n\n try {\n // cleanup functions\n context.cleanup.forEach(fn => fn());\n context.cleanup.clear();\n\n // lifecycle\n context.mount.clear();\n context.update.clear();\n context.destroy.clear();\n\n // provides\n context.provides.clear();\n\n // Empty children set\n context.children.clear();\n } catch (error_) {\n error('Error during context cleanup:', error_);\n }\n\n // mark as destroy\n context.isDestroy = true;\n}\n","import { error } from '@estjs/shared';\nimport { type Context, getActiveContext } from './context';\n\nexport type LifecycleHook = () => 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\n * @returns {LifecycleHooks} a new lifecycle context\n */\nexport function createLifecycleContext() {\n return Object.keys(LIFECYCLE).reduce((acc, type) => {\n acc[type] = new Set<LifecycleHook>();\n return acc;\n }, {} as LifecycleHooks);\n}\n\n/**\n * register a lifecycle hook\n * @param {LifecycleType} type - the type of lifecycle hook to register\n * @param {LifecycleHook} hook - the hook to register\n */\nexport function registerLifecycleHook(type: LifecycleType, hook: LifecycleHook) {\n const context = getActiveContext();\n // check if context is active\n if (!context) {\n error(`Cannot register ${type} hook outside component context`);\n return;\n }\n\n // check if type is valid\n if (!LIFECYCLE[type]) {\n error(`Invalid lifecycle type: ${type}`);\n return;\n }\n\n // check if type is mount and context is mount\n if (type === LIFECYCLE.mount && context.isMount) {\n try {\n hook();\n } catch (error_) {\n error(`Error in ${type} hook:`, error_);\n }\n return;\n }\n\n context[type].add(hook);\n}\n\n/**\n * trigger a lifecycle hook\n * @param {LifecycleType} type - the type of lifecycle hook to trigger\n */\nexport function triggerLifecycleHook(type: LifecycleType) {\n const context = getActiveContext();\n // check if context is active\n if (!context) {\n error(`Cannot trigger ${type} hook outside component context`);\n return;\n }\n\n const hooks = context[type];\n if (!hooks?.size) {\n return;\n }\n\n hooks.forEach(hook => {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Error in ${type} lifecycle hook:`, error_);\n }\n }\n });\n}\n\n// on mount\nexport function onMount(hook: LifecycleHook) {\n registerLifecycleHook(LIFECYCLE.mount, hook);\n}\n\n// on destroy\nexport function onDestroy(hook: LifecycleHook) {\n registerLifecycleHook(LIFECYCLE.destroy, hook);\n}\n\n// on update\nexport function onUpdate(hook: LifecycleHook) {\n registerLifecycleHook(LIFECYCLE.update, hook);\n}\n\n/**\n * cleanup lifecycle\n * @param {Context} context - the context to cleanup\n */\nexport function cleanupLifecycle(context?: Context): void {\n const ctx = context || getActiveContext();\n if (!ctx) {\n return;\n }\n\n // clear all lifecycle hooks\n if (ctx.mount) {\n ctx.mount.clear();\n }\n if (ctx.destroy) {\n ctx.destroy.clear();\n }\n if (ctx.update) {\n ctx.update.clear();\n }\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/**\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 * data-idx regex\n */\nexport const DATA_IDX_REGEX = /^\\d+-\\d+$/;\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 enum COMPONENT_TYPE {\n NORMAL = 'normal',\n FRAGMENT = 'fragment',\n PORTAL = 'portal',\n SUSPENSE = 'suspense',\n FOR = 'for',\n}\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 * Optimized with inline type checks for hot path performance.\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 * Used in hot paths - optimized for minimal branching.\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 // Mixed types - never the same\n if (aIsComponent !== bIsComponent) {\n return false;\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 as any)[NODE_KEY_SYMBOL];\n } else {\n (node as any)[NODE_KEY_SYMBOL] = normalizedKey;\n }\n}\n\n/**\n * Get the key from a node or component.\n * Optimized for inline usage in hot paths.\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 as any)[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","import { error, isFalsy, isHTMLElement, isPrimitive } from '@estjs/shared';\nimport { isComponent } from './component';\nimport { getNodeKey } from './key';\nimport type { AnyNode } from './types';\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 // Return undefined if it's an excluded property\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n // Otherwise return the original value (maintaining reactivity)\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\n/**\n * Remove node from its parent\n *\n * @param node Node to remove\n *\n * @example\n * ```typescript\n * removeNode(elementToRemove);\n * ```\n */\nexport function removeNode(node: AnyNode): void {\n if (!node) return;\n\n try {\n if (isComponent(node)) {\n node.destroy();\n } else {\n const element = node as Element;\n if (element.parentElement) {\n element.remove();\n }\n }\n } catch (_error) {\n error('Failed to remove node:', _error);\n }\n}\n\n/**\n * Insert child node\n * Handle insertion of component nodes and DOM nodes\n *\n * @param parent Parent node\n * @param child Child node\n * @param before Reference node for insertion\n */\nexport function insertNode(parent: Node, child: AnyNode, before: AnyNode | null = null): void {\n if (!parent || !child) return;\n\n try {\n const beforeNode = isComponent(before) ? before.firstChild : (before as Node);\n\n if (isComponent(child)) {\n child.mount(parent, beforeNode);\n return;\n }\n\n if (beforeNode) {\n parent.insertBefore(child as Node, beforeNode);\n } else {\n if (__DEV__) {\n if (!child) {\n error('insertNode: child is not a Node', child);\n }\n }\n parent.appendChild(child as Node);\n }\n } catch (_error) {\n error('Failed to insert node:', _error);\n }\n}\n\n/**\n * Replace child node\n * Handle replacement of component nodes and DOM nodes\n *\n * @param parent Parent node\n * @param newNode New node\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 try {\n insertNode(parent, newNode, oldNode as Node);\n removeNode(oldNode);\n } catch (_error) {\n error('Failed to replace node:', _error);\n }\n}\n\n/**\n * Get the first DOM node from a node or component\n */\nexport function getFirstDOMNode(node: AnyNode): Node | null {\n if (!node) {\n return null;\n }\n\n if (isComponent(node)) {\n return node.firstChild;\n }\n\n return node;\n}\n\n/**\n * Check if two nodes are the same (inline for performance)\n * This combines key check and type check\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 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 * Normalize node for reconciliation\n */\nexport function normalizeNode(node: unknown): Node {\n // already a Node\n if (isHTMLElement(node)) {\n return node;\n }\n // Handle primitives with memoization\n if (isPrimitive(node)) {\n const textContent = isFalsy(node) ? '' : String(node);\n\n // Create new text node directly\n return document.createTextNode(textContent);\n }\n\n return node as Node;\n}\nexport function isHtmlInputElement(val: unknown): val is HTMLInputElement {\n return val instanceof HTMLInputElement;\n}\nexport function isHtmlSelectElement(val: unknown): val is HTMLSelectElement {\n return val instanceof HTMLSelectElement;\n}\nexport function isHtmlTextAreaElement(val: unknown): val is HTMLTextAreaElement {\n return val instanceof HTMLTextAreaElement;\n}\n\nexport function isHtmlFormElement(val: unknown): val is HTMLFormElement {\n return val instanceof HTMLFormElement;\n}\n\nexport function isHtmLTextElement(val: unknown): val is Text {\n return val instanceof Text;\n}\n\n/**\n * Shallow compare two objects\n * @param {any} a - The first object to compare\n * @param {any} b - The second object to compare\n * @returns {boolean} - Returns true if the objects are equal, false otherwise\n */\nexport function shallowCompare(a: any, b: any): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n\n for (const key in a) {\n if (a[key] !== b[key]) return false;\n }\n\n for (const key in b) {\n if (!(key in a)) return false;\n }\n\n return true;\n}\n","import { isHTMLElement } from '@estjs/shared';\nimport { isComponent } from './component';\nimport { getNodeKey, setNodeKey } from './key';\nimport {\n getFirstDOMNode,\n insertNode,\n isHtmLTextElement,\n isSameNode,\n removeNode,\n replaceNode,\n} from './utils';\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 * Optimized for common cases with early returns and minimal allocations.\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 (isHtmLTextElement(oldNode) && isHtmLTextElement(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 * @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 // Batch insert using DocumentFragment for better performance\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < newLength; i++) {\n insertNode(fragment, newChildren[i]);\n }\n insertNode(parent, fragment, anchor);\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 * @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 | null,\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 * @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 | null,\n): void {\n // Cache length calculation\n const newLength = newEndIdx - newStartIdx + 1;\n const newChildrenLen = newChildren.length;\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 // 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 const nextAnchor =\n nextIndex + 1 < newChildrenLen ? getFirstDOMNode(newChildren[nextIndex + 1]) : anchor;\n\n if (newIndexToOldIndexMap[i] === 0) {\n // New node - insert it\n insertNode(parent, nextNode, nextAnchor);\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, nextAnchor);\n }\n } else {\n j--;\n }\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 * @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 { coerceArray, isFunction } from '@estjs/shared';\nimport { effect } from '@estjs/signals';\nimport { getActiveContext } from './context';\nimport {\n isHtmlInputElement,\n isHtmlSelectElement,\n isHtmlTextAreaElement,\n normalizeNode,\n removeNode,\n} from './utils';\nimport { patchChildren } from './patch';\nimport type { AnyNode } from './types';\n\n/**\n * Add event listener with automatic cleanup on context destruction\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 const context = getActiveContext();\n if (context) {\n context.cleanup.add(() => {\n element.removeEventListener(event, handler, options);\n });\n }\n}\n\n/**\n * Bind an element to a setter function, allowing the element to update the setter value when its value changes.\n *\n * @param node The element to bind.\n * @param setter The setter function to call when the element's value changes.\n */\nexport function bindElement(node: Element, key, defaultValue, setter: (value: unknown) => void) {\n if (isHtmlInputElement(node)) {\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 } else if (isHtmlSelectElement(node)) {\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 } else if (isHtmlTextAreaElement(node)) {\n addEventListener(node, 'input', () => {\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 interface InsertOptions {\n preserveOnCleanup?: boolean;\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(\n parent: Node,\n nodeFactory: Function | Node | string,\n before?: Node,\n options?: InsertOptions,\n): void {\n if (!parent) return;\n\n const context = getActiveContext();\n if (!context) return;\n\n let renderedNodes: AnyNode[] = [];\n\n // Create effect for reactive updates\n const cleanup = effect(() => {\n const rawNodes = isFunction(nodeFactory) ? nodeFactory() : nodeFactory;\n const nodes = coerceArray(rawNodes).map(normalizeNode) as AnyNode[];\n renderedNodes = patchChildren(parent, renderedNodes, nodes, before) as AnyNode[];\n });\n\n // Register cleanup function\n context.cleanup.add(() => {\n cleanup();\n if (!options?.preserveOnCleanup) {\n renderedNodes.forEach(node => removeNode(node));\n }\n renderedNodes.length = 0;\n });\n}\n/**\n * Map nodes from template by indexes\n */\nexport function mapNodes(template: Node, indexes: number[]): Node[] {\n const len = indexes.length;\n const tree = new Array<Node>(len); // Pre-allocate with exact size\n const indexSet = new Set(indexes); // O(1) lookup\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; // Early exit when all nodes found\n }\n index++;\n }\n\n let child = node.firstChild;\n while (child) {\n if (walk(child)) return true; // Propagate early exit\n child = child.nextSibling;\n }\n\n return false;\n };\n\n walk(template);\n return tree;\n}\n","import { type Computed, type Signal, isComputed, isSignal, shallowReactive } from '@estjs/signals';\nimport { error, hasChanged, isFunction, isHTMLElement, isObject, startsWith } from '@estjs/shared';\nimport {\n type Context,\n createContext,\n destroyContext,\n getActiveContext,\n popContextStack,\n pushContextStack,\n} from './context';\nimport { LIFECYCLE, triggerLifecycleHook } from './lifecycle';\nimport { COMPONENT_STATE, COMPONENT_TYPE, EVENT_PREFIX, REF_KEY } from './constants';\nimport { addEventListener } from './binding';\nimport { getComponentKey, normalizeKey } from './key';\nimport { insertNode, removeNode, replaceNode, shallowCompare } from './utils';\n\n// TODO: support Promise<Node> ?\nexport type ComponentFn = (props?: ComponentProps) => Node | Signal<Node> | Computed<Node>;\nexport type ComponentProps = Record<string, unknown>;\n\nexport class Component {\n // component rendered node\n protected renderedNode: Node | null = null;\n\n // component context\n protected componentContext: Context | null = null;\n\n // component parent node\n protected parentNode: Node | null = null;\n\n // component before node\n protected beforeNode: Node | null = null;\n\n // component props\n private reactiveProps: Record<string, any> = {};\n private _propSnapshots: Record<string, any> = {};\n\n // component key\n public readonly key: string | undefined;\n // component state\n protected state: number = COMPONENT_STATE.INITIAL;\n\n // component context\n protected context: Context | null = null;\n // component parent context\n protected parentContext: Context | null = null;\n\n // component type\n // @ts-ignore\n private [COMPONENT_TYPE.NORMAL] = true;\n\n get isConnected(): boolean {\n return this.state === COMPONENT_STATE.MOUNTED;\n }\n\n get firstChild(): Node | null {\n return this.renderedNode ?? null;\n }\n\n constructor(\n public component: ComponentFn,\n public props: ComponentProps | undefined,\n ) {\n this.key = props?.key ? normalizeKey(props.key) : getComponentKey(component);\n this.reactiveProps = shallowReactive({ ...(this.props || {}) });\n this.parentContext = getActiveContext();\n\n // Init snapshots for object props\n if (this.props) {\n for (const key in this.props) {\n const val = this.props[key];\n if (isObject(val) && val !== null) {\n this._propSnapshots[key] = Array.isArray(val) ? [...val] : { ...val };\n }\n }\n }\n }\n\n mount(parentNode: Node, beforeNode?: Node | null): Node | null | Promise<Node | null> {\n this.parentNode = parentNode;\n this.beforeNode = beforeNode || null;\n this.state = COMPONENT_STATE.MOUNTING;\n\n // if the component is already mount, insert the rendered node\n if (this.renderedNode) {\n insertNode(parentNode, this.renderedNode, beforeNode);\n return this.renderedNode;\n }\n\n // context\n this.componentContext = createContext(this.parentContext);\n pushContextStack(this.componentContext);\n\n // render the component\n let result = this.component(this.reactiveProps);\n\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps) as Node;\n }\n\n // Unwrap signals and computed values\n if (isSignal<Node>(result) || isComputed<Node>(result)) {\n result = result.value;\n }\n\n this.renderedNode = result;\n\n // insert the rendered node\n insertNode(parentNode, this.renderedNode, beforeNode);\n\n // apply props\n this.applyProps(this.props || {});\n\n // update marks\n this.state = COMPONENT_STATE.MOUNTED;\n if (this.componentContext) {\n this.componentContext.isMount = true;\n }\n // trigger mount hook\n triggerLifecycleHook(LIFECYCLE.mount);\n\n return this.renderedNode;\n }\n\n update(prevNode: Component): Component {\n // if key is different, mount the component\n if (this.key !== prevNode.key) {\n this.mount(prevNode.parentNode!, prevNode.beforeNode);\n return this;\n }\n\n // Take previous node's properties and reactive state\n this.parentNode = prevNode.parentNode;\n this.beforeNode = prevNode.beforeNode;\n this.componentContext = prevNode.componentContext;\n this.renderedNode = prevNode.renderedNode;\n this.state = prevNode.state;\n this.reactiveProps = prevNode.reactiveProps; // Reuse same reactive object\n this._propSnapshots = prevNode._propSnapshots;\n\n // Smart update: shallow compare object props to detect mutations\n if (this.props) {\n for (const key in this.props) {\n if (key === 'key') continue;\n const newValue = this.props[key];\n const oldValue = this.reactiveProps[key];\n\n if (isObject(newValue) && newValue !== null) {\n // For objects: compare with snapshot\n const snapshot = this._propSnapshots[key];\n if (!snapshot || !shallowCompare(newValue, snapshot)) {\n // Content changed (or new prop) -> Force update\n const newSnapshot = Array.isArray(newValue)\n ? newValue.slice()\n : Object.assign({}, newValue);\n this.reactiveProps[key] = newSnapshot;\n this._propSnapshots[key] = newSnapshot;\n }\n // If content same -> Do nothing (skip update)\n } else {\n // For primitives: standard check\n if (hasChanged(newValue, oldValue)) {\n this.reactiveProps[key] = newValue;\n // Clear snapshot if it existed (type change)\n if (this._propSnapshots[key]) {\n delete this._propSnapshots[key];\n }\n }\n }\n }\n }\n\n // check if the component is already mount\n if (!this.isConnected && this.parentNode) {\n this.mount(this.parentNode, this.beforeNode);\n }\n\n // if the component is mount and has context, apply new props and trigger update lifecycle\n if (this.componentContext) {\n pushContextStack(this.componentContext);\n this.applyProps(this.props || {});\n triggerLifecycleHook(LIFECYCLE.update);\n popContextStack();\n }\n\n return this;\n }\n async forceUpdate() {\n if (this.state === COMPONENT_STATE.DESTROYED || !this.parentNode || !this.componentContext) {\n return;\n }\n\n // Re-render\n const prevNode = this.renderedNode;\n let newNode: Node | Promise<Node>;\n\n try {\n // Create new context for re-render\n if (this.componentContext) {\n pushContextStack(this.componentContext);\n }\n\n newNode = (this.component as Function)(this.reactiveProps);\n\n if (isFunction(newNode)) {\n newNode = (newNode as Function)(this.reactiveProps) as Node;\n }\n\n // Unwrap signals and computed values\n if (isSignal<Node>(newNode) || isComputed<Node>(newNode)) {\n newNode = newNode.value;\n }\n\n if (prevNode && newNode && prevNode !== newNode) {\n // Replace node\n if (this.parentNode) {\n replaceNode(this.parentNode, newNode as Node, prevNode as Node);\n this.renderedNode = newNode as Node;\n }\n }\n\n // Trigger update lifecycle\n await triggerLifecycleHook(LIFECYCLE.update);\n } catch (_error) {\n error('Force update failed:', _error);\n throw _error;\n } finally {\n if (this.componentContext) {\n popContextStack();\n }\n }\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 const context = this.componentContext;\n if (context) {\n pushContextStack(context);\n\n // Trigger destroyed lifecycle\n triggerLifecycleHook(LIFECYCLE.destroy);\n destroyContext(context);\n this.componentContext = null;\n\n popContextStack();\n }\n\n const rendered = this.renderedNode;\n if (rendered) {\n removeNode(rendered);\n }\n\n // Reset all component properties\n this.renderedNode = null;\n this.parentNode = null;\n this.beforeNode = null;\n this.reactiveProps = {};\n this.props = undefined;\n this.state = COMPONENT_STATE.DESTROYED;\n }\n\n applyProps(props: ComponentProps): void {\n // check if props is defined\n if (!props) {\n return;\n }\n\n // iterate over all properties and apply them\n for (const [propName, propValue] of Object.entries(props)) {\n if (startsWith(propName, EVENT_PREFIX) && this.renderedNode) {\n // event handling: extract the event name after on\n const eventName = propName.slice(2).toLowerCase();\n\n if (isHTMLElement(this.renderedNode)) {\n addEventListener(this.renderedNode, eventName, propValue as EventListener);\n }\n } else if (propName === REF_KEY && isSignal(propValue)) {\n // handle reference: store the DOM reference into the signal value\n propValue.value = this.renderedNode;\n }\n }\n\n // save props reference\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[COMPONENT_TYPE.NORMAL];\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(componentFn: ComponentFn, props?: ComponentProps): Component {\n if (isComponent(componentFn)) {\n return componentFn;\n }\n return new Component(componentFn, props);\n}\n","import { error, isNil } from '@estjs/shared';\nimport { type Context, getActiveContext } from './context';\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 to the context\n * @param {InjectionKey<T>|string|number} key - the key to provide the value to\n * @param {T} value - the value to provide\n */\nexport function provide<T>(key: InjectionKey<T> | string | number, value: T) {\n const context = getActiveContext();\n if (!context) {\n error('provide must be called within a template');\n return;\n }\n\n context.provides.set(key, value);\n}\n\n/**\n * inject a value from the context\n * @param {InjectionKey<T>|string|number} key - the key to inject the value from\n * @param {T} defaultValue - the default value to return if the key is not found\n * @returns {T} the value injected\n */\nexport function inject<T>(key: InjectionKey<T> | string | number, defaultValue?: T): T {\n const context = getActiveContext();\n if (!context) {\n error('inject must be called within a template');\n return defaultValue as T;\n }\n\n // Find value in context hierarchy\n let currentContext: Context | null = context;\n while (currentContext) {\n const value = currentContext.provides.get(key);\n if (!isNil(value)) {\n // Cache the found value\n return value as T;\n }\n currentContext = currentContext.parent;\n }\n\n // Cache default value if not found\n return defaultValue as T;\n}\n","import { isFunction, isString } from '@estjs/shared';\n\n/**\n * Event handler for delegated events\n * @param {Event} e - The event object\n */\nfunction eventHandler(e: Event): void {\n let node = e.target as any;\n const key = `${e.type}`;\n const oriTarget = e.target;\n const oriCurrentTarget = e.currentTarget;\n\n /**\n * Retarget the event's target property\n * @param {EventTarget} value - New target value\n */\n const reTarget = (value: EventTarget) =>\n Object.defineProperty(e, 'target', {\n configurable: true,\n value,\n });\n\n /**\n * Handle event on current node\n * @returns {boolean} Whether to continue propagation\n */\n const handleNode = (): 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, e) : handler.call(node, e);\n if (e.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(e.target)\n ) {\n reTarget(node.host);\n }\n return true;\n };\n\n /**\n * Walk up the DOM tree handling events\n */\n const walkUpTree = (): void => {\n while (handleNode() && (node = node._$host || node.parentNode || node.host));\n };\n\n // simulate currentTarget\n Object.defineProperty(e, 'currentTarget', {\n configurable: true,\n get() {\n return node || document;\n },\n });\n\n if (e.composedPath) {\n const path = e.composedPath();\n reTarget(path[0]);\n for (let i = 0; i < path.length - 2; i++) {\n node = path[i] as any;\n if (!handleNode()) break;\n if (node._$host) {\n node = node._$host;\n // bubble up from portal mount instead of composedPath\n walkUpTree();\n break;\n }\n if (node.parentNode === oriCurrentTarget) {\n break; // don't bubble above root of event delegation\n }\n }\n }\n // fallback for browsers that don't support composedPath\n else walkUpTree();\n // Mixing portals and shadow dom can lead to a nonstandard target, so reset here.\n reTarget(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","import { isArray, isObject } from '@estjs/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\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 *\n * @param value - The class value to normalize\n * @returns A normalized class string\n * @public\n */\nexport function normalizeClass(value: unknown): string {\n if (value == null) {\n return '';\n }\n\n if (typeof value === 'string') {\n return value.trim();\n }\n\n // Handle arrays\n if (isArray(value)) {\n return value.map(normalizeClass).filter(Boolean).join(' ');\n }\n\n // Handle objects (conditional classes)\n if (isObject(value)) {\n const result: string[] = [];\n\n for (const key in value) {\n if (value[key]) {\n result.push(key);\n }\n }\n\n return result.join(' ');\n }\n\n // Convert other types to string\n return String(value).trim();\n}\n","import { camelCase, capitalize, isArray, isObject, isString } from '@estjs/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\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 (typeof val === 'string' && 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 { includeBooleanAttr, isBooleanAttr, isSpecialBooleanAttr, isSymbol } from '@estjs/shared';\nimport { KEY_PROP, REF_KEY, SVG_NAMESPACE, XLINK_NAMESPACE, XMLNS_NAMESPACE } from '../constants';\nimport { setNodeKey } from '../key';\n\nexport type AttrValue = string | boolean | number | null | undefined;\n\nexport function patchAttr(el: Element, key: string, prev: AttrValue, next: AttrValue) {\n if (key === REF_KEY) {\n (prev as any).value = el;\n return;\n }\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\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 if (prev === next) {\n return;\n }\n\n const lowerKey = key.toLowerCase();\n if (/^on[a-z]+/.test(lowerKey)) {\n return;\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 && typeof attrValue === 'string') {\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 as any)[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 { insertNode, normalizeNode } from '../utils';\nimport { COMPONENT_TYPE } from '../constants';\nimport type { AnyNode } from '../types';\n\nexport interface FragmentProps {\n children?: AnyNode | AnyNode[];\n key?: string;\n}\n\n/**\n * Fragment component - renders multiple children without wrapper elements\n *\n * @param props - Component props with children\n * @returns DocumentFragment containing all children\n *\n * @example\n * ```tsx\n * <Fragment>\n * <div>First</div>\n * <span>Second</span>\n * </Fragment>\n * ```\n */\nexport function Fragment(props: FragmentProps): DocumentFragment | string {\n // Check if we're in SSR mode (no document)\n if (typeof document === 'undefined') {\n const children = props.children;\n if (!children) return '';\n const childArray = Array.isArray(children) ? children : [children];\n // In SSR, convert children to string\n return childArray.map(child => String(child || '')).join('');\n }\n\n const fragment = document.createDocumentFragment();\n const children = props.children;\n\n if (children) {\n const childArray = Array.isArray(children) ? children : [children];\n childArray.forEach(child => {\n if (child != null) {\n // Skip null/undefined\n const normalized = normalizeNode(child);\n if (normalized) {\n insertNode(fragment, normalized);\n }\n }\n });\n }\n\n return fragment;\n}\n\nFragment[COMPONENT_TYPE.FRAGMENT] = 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 as any)[COMPONENT_TYPE.FRAGMENT];\n}\n","import { isArray, isString, warn } from '@estjs/shared';\nimport { insertNode, normalizeNode } from '../utils';\nimport { COMPONENT_TYPE } from '../constants';\nimport { onMount } from '../lifecycle';\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 * ```\n */\nexport function Portal(props: PortalProps): Comment | string {\n // Check if we're in SSR mode (no document)\n if (typeof document === 'undefined') {\n const children = props.children;\n if (!children) return '';\n const childArray = isArray(children) ? children : [children];\n // In SSR, convert children to string\n return childArray.map(child => String(child || '')).join('');\n }\n // Create placeholder comment for parent tree\n const placeholder = document.createComment('portal');\n // Mark as portal for isPortal check\n (placeholder as any)[COMPONENT_TYPE.PORTAL] = true;\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 const children = props.children;\n if (children) {\n const childArray = isArray(children) ? children : [children];\n childArray.forEach(child => {\n if (child != null) {\n const normalized = normalizeNode(child);\n if (normalized) {\n insertNode(targetElement, normalized);\n }\n }\n });\n }\n });\n\n return placeholder;\n}\n\nPortal[COMPONENT_TYPE.PORTAL] = 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 as any)[COMPONENT_TYPE.PORTAL];\n}\n","import { isArray, isPromise, isUndefined, warn } from '@estjs/shared';\nimport { provide } from '../provide';\nimport { getActiveContext } from '../context';\nimport { isComponent } from '../component';\nimport { insertNode, normalizeNode } from '../utils';\nimport { COMPONENT_TYPE } from '../constants';\nimport { onDestroy } from '../lifecycle';\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): Node | string {\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 currentContext = getActiveContext();\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 (child as any).parentContext = currentContext;\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[COMPONENT_TYPE.SUSPENSE] = 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 as any)[COMPONENT_TYPE.SUSPENSE];\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 const promise = fetcher();\n currentPromise = promise.then(() => {}); // We need a promise that resolves when data is ready\n\n try {\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) as any;\n if (suspenseContext) {\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 { isArray, isFunction, isNil, isString } from '@estjs/shared';\n\n/** Hydration identifier counter, used to generate unique IDs */\nlet hydrationCounter = 0;\n\n/**\n * get the hydration key\n * @returns {string} the hydration key\n */\nexport function getHydrationKey(): string {\n return `${hydrationCounter++}`;\n}\n\n/**\n * reset the hydration key\n */\nexport function resetHydrationKey(): void {\n hydrationCounter = 0;\n}\n\nlet isHydrationActive = false;\n\n/**\n * start the hydration\n */\nexport function startHydration(): void {\n isHydrationActive = true;\n}\n\n/**\n * end the hydration\n */\nexport function endHydration(): void {\n isHydrationActive = false;\n}\n\n/**\n * check if the hydration is active\n * @returns {boolean} true if the hydration is active, false otherwise\n */\nexport function isHydrating(): boolean {\n return isHydrationActive;\n}\n\n/**\n * convert the content to string\n * @param {unknown} content - the content to convert\n * @param {boolean} isSvg - whether the content is SVG\n * @returns {string} the content as a string\n */\nexport function convertToString(content: unknown, isSvg = false): string {\n // if result is null or undefined, return html\n if (isNil(content)) {\n return '';\n }\n\n // if result is a string, return result\n if (isString(content)) {\n return content;\n }\n\n // if result is an array, return the result of the array\n if (isArray(content)) {\n return content.map(item => convertToString(item, isSvg)).join('');\n }\n\n // if result is a function, return the result of the function\n if (isFunction(content)) {\n return convertToString(content(), isSvg);\n }\n\n // if result is other type, return the result of the string\n return String(content);\n}\n\n/**\n * add attributes to the html content\n * @param {string} htmlContent - the html content\n * @param {string} hydrationId - the hydration id\n * @returns {string} the html content with attributes\n */\nexport function addAttributes(htmlContent: string, hydrationId: string): string {\n // match the root element regex\n const rootElementRegex = /^<([a-z]+)(\\s*)([^>]*)>/i;\n // match the index attribute regex\n const indexAttributeRegex = /data-idx=\"(\\d+)\"/g;\n const commentRegex = /<!--(.*?)-->/g;\n\n // handle the html:\n // 1. add the hydration id to the root element\n // 2. add the hydration id prefix to all the index attributes\n const enhancedHtml = htmlContent\n .replace(rootElementRegex, `<$1$2$3 data-hk=\"${hydrationId}\">`)\n .replaceAll(indexAttributeRegex, `data-idx=\"${hydrationId}-$1\"`)\n .replaceAll(commentRegex, `<!--${hydrationId}-$1-->`);\n\n return enhancedHtml;\n}\n","import { error, isFunction } from '@estjs/shared';\nimport { addAttributes, convertToString, resetHydrationKey } from './shared';\nimport type { ComponentFn, ComponentProps } from '../component';\n\n/**\n *\n * ssg compile\n *\n * component context it will this:\n *\n * function component(props) {\n * // render function props: template, hydrationKey, ...components\n * return render(_tmpl, getHydrationKey(), createSSGComponent(xx, {}));\n * }\n *\n * renderToString(component, props)\n *\n *\n */\n\n/**\n * render the component to string\n * @param {ComponentFn} component - the component to render\n * @param {ComponentProps} props - the props to pass to the component\n * @returns {string} the rendered string\n */\nexport function renderToString(component: ComponentFn, props?: ComponentProps) {\n if (!isFunction(component)) {\n error('Component must be a function');\n return '';\n }\n\n // reset the hydration key\n resetHydrationKey();\n\n // render the component\n const result = component(props);\n\n // convert the result to string\n return convertToString(result);\n}\n\n/**\n * render the component to string\n * @param {string[]} templates - the template to render\n * @param {string} hydrationKey - the hydration key\n * @param {...string[]} components - the components to render\n * @returns {string} the rendered string\n */\nexport function render(templates: string[], hydrationKey: string, ...components: string[]) {\n // rendered content\n let content = '';\n // index\n let index = 0;\n\n /**\n *\n * jsx source code\n * <div>\n * <div>\n * <Component 1/>\n * <Component 2/>\n * </div>\n * <Component 3/>\n * </div>\n *\n * it will compile to:\n *\n *\n * let _tmpl = [\n * '<div><div>',\n * '</div>',\n * '</div>',\n * ]\n *\n * function component(props) {\n * return render(_tmpl, getHydrationKey(), createSSGComponent(Component1, {}), createSSGComponent(Component2, {}), createSSGComponent(Component3, {}));\n * }\n *\n */\n\n // map different templates\n for (const template of templates) {\n content += template;\n // render component\n if (index < components.length) {\n const component = components[index++];\n\n if (component) {\n content += convertToString(component);\n }\n }\n }\n\n //add hydrate key\n const result = addAttributes(content, hydrationKey);\n\n return result;\n}\n\n/**\n * create a ssg component\n * @param {ComponentFn} component - the component to create\n * @param {ComponentProps} props - the props to pass to the component\n * @returns {string} the created component as a string\n */\nexport function createSSGComponent(component: ComponentFn, props: ComponentProps = {}): string {\n if (!isFunction(component)) {\n error('create ssg component: Component is not a function');\n return '';\n }\n\n const result = component(props);\n\n return convertToString(result);\n}\n","import { isComputed, isSignal } from '@estjs/signals';\nimport { isArray, isNumber, isObject, isString, kebabCase } from '@estjs/shared';\n\n/**\n * Normalized style object type\n * Represents the processed style object format\n */\nexport type NormalizedStyle = Record<string, string | number>;\n\n/**\n * Normalize style value\n *\n * Convert style values in various formats (object, string, array) to a unified format\n *\n * @param styleValue Original style value\n * @returns Normalized style object or string\n */\nexport function normalizeStyle(styleValue: unknown): NormalizedStyle | string | undefined {\n // Handle array format styles\n if (isArray(styleValue)) {\n const normalizedStyleObject: NormalizedStyle = {};\n\n // Iterate through each style item in the array and merge\n for (const styleItem of styleValue) {\n const normalizedItem = isString(styleItem)\n ? parseStyleString(styleItem)\n : (normalizeStyle(styleItem) as NormalizedStyle);\n\n if (normalizedItem) {\n for (const key in normalizedItem) {\n normalizedStyleObject[key] = normalizedItem[key];\n }\n }\n }\n\n return normalizedStyleObject;\n }\n // Handle string or object format styles\n if (isString(styleValue) || isObject(styleValue)) {\n return styleValue as any;\n }\n\n // Return undefined for other types\n return undefined;\n}\n\n// Style parsing related regular expressions\n/** Semicolon separator regex, excludes semicolons within parentheses */\nconst styleSeparatorRegex = /;(?![^(]*\\))/g;\n/** Property value separator regex */\nconst propertyValueSeparatorRegex = /:([\\s\\S]+)/;\n/** Style comment regex */\nconst styleCommentRegex = /\\/\\*[\\s\\S]*?\\*\\//g;\n\n/**\n * Parse CSS style string into object format\n *\n * Parsing process:\n * 1. Remove CSS comments\n * 2. Split by semicolons into style items\n * 3. Parse each style item into key-value pairs\n *\n * @param cssText CSS style string\n * @returns Normalized style object\n */\nexport function parseStyleString(cssText: string): NormalizedStyle {\n const styleObject: NormalizedStyle = {};\n\n // Remove comments, split by semicolons, and process each item\n cssText\n .replaceAll(styleCommentRegex, '')\n .split(styleSeparatorRegex)\n .forEach(styleItem => {\n if (styleItem) {\n const parts = styleItem.split(propertyValueSeparatorRegex);\n // Only process valid property-value pairs\n if (parts.length > 1) {\n styleObject[parts[0].trim()] = parts[1].trim();\n }\n }\n });\n\n return styleObject;\n}\n\n/**\n * Convert style object to CSS string\n *\n * Handle different types of style values, and apply CSS variable and kebab-case transformations\n *\n * @param styleValue Style object or string\n * @returns Formatted CSS string\n */\nexport function styleObjectToString(styleValue: NormalizedStyle | string | undefined): string {\n // Check for empty values\n if (!styleValue) {\n return '';\n }\n\n // Return string values directly\n if (isString(styleValue)) {\n return styleValue;\n }\n\n // Convert object to string\n let cssText = '';\n for (const propName in styleValue) {\n const propValue = styleValue[propName];\n\n // Only process valid string or number values\n if (isString(propValue) || isNumber(propValue)) {\n // Keep CSS variables as is, convert other properties to kebab-case\n const normalizedPropName = propName.startsWith('--') ? propName : kebabCase(propName);\n cssText += `${normalizedPropName}:${propValue};`;\n }\n }\n\n return cssText;\n}\n\n/**\n * Normalize class name\n *\n * Process different formats of class name input (string, array, object) and output a unified string\n *\n * @param classValue Original class name value\n * @returns Normalized class name string\n */\nexport function normalizeClassName(classValue: unknown): string {\n let resultClassName = '';\n\n // Handle string class names\n if (isString(classValue)) {\n resultClassName = classValue;\n }\n // Handle array class names\n else if (isArray(classValue)) {\n for (const item of classValue) {\n const normalizedItem = normalizeClassName(item);\n if (normalizedItem) {\n resultClassName += `${normalizedItem} `;\n }\n }\n }\n // Handle object class names (conditional classes)\n else if (isObject(classValue)) {\n for (const className in classValue) {\n // Only add class name when value is truthy\n if (classValue[className]) {\n resultClassName += `${className} `;\n }\n }\n }\n\n return resultClassName.trim();\n}\n\n/**\n * Normalize component properties\n *\n * Special handling for class and style attributes, converting them to normalized format\n *\n * @param props Original component properties\n * @returns Normalized component properties\n */\nexport function normalizeProps(props: Record<string, any> | null): Record<string, any> | null {\n if (!props) {\n return null;\n }\n\n const { class: className, style } = props;\n\n // Normalize class attribute\n if (className && !isString(className)) {\n props.class = normalizeClassName(className);\n }\n\n // Normalize style attribute\n if (style) {\n props.style = normalizeStyle(style);\n }\n\n return props;\n}\n\n/**\n * Generate server-side rendering attribute string\n *\n * Generate HTML-compatible attribute string based on attribute type, handling special cases:\n * - Automatic unwrapping of reactive values\n * - Normalization of special attributes (style/class)\n * - Ignoring event attributes\n * - Special handling for boolean attributes\n *\n * @param attrName Attribute name\n * @param attrValue Attribute value\n * @param hydrationId Hydration ID (for client-side reuse)\n * @returns Formatted HTML attribute string\n */\nexport function setSSGAttr(attrName: string, attrValue: any, hydrationId: string): string {\n // Handle reactive values (signals or computed values)\n if (isSignal(attrValue) || isComputed(attrValue)) {\n return setSSGAttr(attrName, attrValue.value, hydrationId);\n }\n\n // Ignore null, undefined, and false value attributes\n if (!attrValue && attrValue !== 0) {\n return '';\n }\n\n // Special attribute handling: style\n if (attrName === 'style') {\n const normalizedStyle = normalizeStyle(attrValue);\n if (!normalizedStyle) {\n return '';\n }\n\n // Use string styles directly\n if (isString(normalizedStyle)) {\n return ` style=\"${normalizedStyle}\"`;\n }\n\n // Convert object styles to string\n return ` style=\"${styleObjectToString(normalizedStyle)}\"`;\n }\n\n // Special attribute handling: class\n if (attrName === 'class') {\n const normalizedClassName = normalizeClassName(attrValue);\n return normalizedClassName ? ` class=\"${normalizedClassName}\"` : '';\n }\n\n // Ignore event handler attributes (client-side behavior)\n if (attrName.startsWith('on')) {\n return '';\n }\n\n // Special handling for boolean attributes\n if (attrValue === true) {\n return ` ${attrName}`;\n }\n\n // Standard attribute handling\n return ` ${attrName}=\"${attrValue}\"`;\n}\n","/**\n * Server-side node mapping utilities\n */\n\nimport { error, isString } from '@estjs/shared';\nimport { createComponent } from '../component';\nimport { template } from '../renderer';\nimport { mapNodes } from '../binding';\nimport { DATA_IDX_REGEX } from '../constants';\nimport { endHydration, getHydrationKey, resetHydrationKey, startHydration } from './shared';\n\n/**\n * getRenderedElement function - gets an element based on string template\n */\nexport function getRenderedElement(temp: string) {\n return () => {\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 // Return existing node if found, otherwise create new element from template\n return node || template(temp)();\n };\n}\n\n/**\n * Maps server-side rendered nodes during hydration\n * @param {HTMLElement} template - The root template element\n * @param {number[]} idx - Array of indices to map\n * @returns {Node[]} Array of mapped nodes\n */\nexport function mapSSRNodes(template: HTMLElement, idx: number[]): Node[] {\n // Check if we're in hydration mode by looking for the data-hk attribute\n const hk = template.dataset.hk;\n\n // If not hydrating, fallback to standard node mapping\n if (!hk) {\n return mapNodes(template, 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 = template.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 //@ts-ignore\n const idxAttr = item.dataset.idx;\n return idxAttr !== null && DATA_IDX_REGEX.test(idxAttr);\n })\n .map((item: Element) => {\n //@ts-ignore\n const idxAttr = item.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(template);\n nodesList.push(...commentNodes);\n\n // Build final node list with template as first element\n const nodes: Node[] = [template];\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 * Hydrates a server-rendered component\n *\n * @param {Function} component - Component function to hydrate\n * @param {HTMLElement | string} container - Container element or selector\n * @param {Record<string, unknown>} props - Component properties\n * @returns {any} Component instance or undefined if hydration fails\n */\nexport function hydrate(\n component: (props?: any) => any,\n container: HTMLElement | string,\n props: Record<string, unknown> = {},\n): 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) ? document.querySelector(container) : 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, props);\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/renderer.ts","../src/scope.ts","../src/constants.ts","../src/key.ts","../src/utils.ts","../src/patch.ts","../src/binding.ts","../src/lifecycle.ts","../src/component.ts","../src/provide.ts","../src/events.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/server/shared.ts","../src/server/render.ts","../src/server/attrs.ts","../src/server/hydration.ts"],"names":["activeScope","scopeId","scopeStack","getActiveScope","setActiveScope","scope","createScope","parent","runWithScope","fn","prevScope","disposeScope","_a","_b","_c","_d","_e","children","child","hook","error_","onCleanup","SPREAD_NAME","SVG_NAMESPACE","XLINK_NAMESPACE","XMLNS_NAMESPACE","DATA_IDX_REGEX","MAX_KEY_LENGTH","componentKeyPrefixCache","getComponentKey","type","prefix","name","hash","simpleHash","str","len","i","symbolIdCounter","normalizeKey","key","isFalsy","isString","isNumber","isSymbol","globalKey","desc","NODE_KEY_SYMBOL","setNodeKey","node","isComponent","normalizedKey","getNodeKey","omitProps","target","keys","excludeSet","obj","prop","removeNode","element","_error","error","insertNode","before","beforeNode","replaceNode","newNode","oldNode","getFirstDOMNode","isPrimitive","isSameNode","a","b","keyA","keyB","aIsComponent","bIsComponent","aNode","bNode","normalizeNode","isHTMLElement","textContent","isHtmlInputElement","val","isHtmlSelectElement","isHtmlTextAreaElement","isHtmLTextElement","shallowCompare","transferKey","oldKey","patch","oldIsElement","oldAttrs","newAttrs","attrName","attr","oldIsComponent","newIsComponent","patchChildren","oldChildren","newChildren","anchor","oldLength","newLength","o0","o1","n0","n1","dom1","dom0","patchKeyedChildren","oldStartIdx","newStartIdx","oldEndIdx","newEndIdx","oldStartNode","oldEndNode","newStartNode","newEndNode","anchorNode","patchUnknownSequence","newChildrenLen","keyToNewIndexMap","newIndexToOldIndexMap","moved","maxNewIndexSoFar","patched","newIndex","j","increasingNewIndexSequence","getSequence","nextIndex","nextNode","nextAnchor","domNode","arr","result","p","u","v","arrI","addEventListener","event","handler","options","bindElement","defaultValue","setter","values","option","insert","nodeFactory","ownerScope","renderedNodes","cleanup","effect","executeUpdate","rawNodes","isFunction","nodes","coerceArray","item","mapNodes","template","indexes","tree","indexSet","index","found","walk","registerMountHook","registerUpdateHook","registerDestroyHook","triggerMountHooks","triggerUpdateHooks","onMount","onDestroy","onUpdate","Component","component","props","shallowReactive","__spreadValues","dom","parentNode","isSignal","isComputed","prevNode","newValue","oldValue","isObject","__async","originalNodes","newNodes","lastNode","lastDom","firstElement","propName","propValue","startsWith","eventName","createComponent","componentFn","html","create","firstChild","createApp","container","rootComponent","provide","value","inject","current","eventHandler","oriTarget","oriCurrentTarget","reTarget","handleNode","data","walkUpTree","path","$EVENTS","delegateEvents","eventNames","document","docWithEvents","eventSet","patchClass","el","prev","next","isSVG","normalizedNext","normalizeClass","normalizedPrev","isArray","importantRE","prefixes","prefixCache","patchStyle","style","isCssString","setStyle","prevStyles","stylePart","colonIndex","prefixed","autoPrefix","camelCase","rawName","cached","capitalize","patchAttr","k","elementIsSVG","isXlink","isXmlns","isBoolean","isSpecialBooleanAttr","isBooleanAttr","lowerKey","localName","includeBooleanAttr","attrValue","e","addEvent","selector","wrappedHandler","cleanOptions","Fragment","isFragment","Portal","placeholder","childArray","targetElement","normalized","isPortal","SuspenseContext","Suspense","isUndefined","fallback","isMounted","pendingCount","isShowingFallback","resolvedChildren","showFallback","showChildren","isPromise","renderChildren","currentScope","suspenseContext","promise","resolved","isSuspense","createResource","fetcher","signal","loading","state","fetchId","currentPromise","fetch","currentFetchId","resource","hydrationCounter","getHydrationKey","resetHydrationKey","endHydration","convertToString","content","isSvg","isNil","addAttributes","htmlContent","hydrationId","rootElementRegex","indexAttributeRegex","commentRegex","renderToString","render","templates","hydrationKey","components","createSSGComponent","normalizeStyle","styleValue","normalizedStyleObject","styleItem","normalizedItem","parseStyleString","styleSeparatorRegex","propertyValueSeparatorRegex","styleCommentRegex","cssText","styleObject","parts","styleObjectToString","normalizedPropName","kebabCase","normalizeClassName","classValue","resultClassName","className","setSSGAttr","normalizedStyle","normalizedClassName","getRenderedElement","temp","mapSSRNodes","idx","hk","nodesList","elements","idxAttr","hkPart","idxPart","commentNodes","walkNodes","indexValue","hydrate","rootElement"],"mappings":";;;;;AAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,qBAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,cAAA,CAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,oBAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,IAAA,CAAA,IAAA,CAAA,GAAA,CAAA,CAAA,EAAA,CAAA,CAAA,EAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,EAAA,CAAA,IAAA,IAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,C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AA,CAAK,GAAA,GAAQ,OAAOqM,CAAU,CAAC,EAC/DtT,CAAAA,EACF+G,CAAAA,CAAM,IAAA,CAAK/G,CAAAA,CAAK,IAAI,EAExB,CAAC,EAEM+G,CACT,CAUO,SAASwM,EAAAA,CACdpL,CAAAA,CACA4B,CAAAA,CACA3B,CAAAA,CAAiC,EAAC,CAC7B,CAIL8H,CAAAA,GAEA,GAAI,CAEF,IAAMsD,CAAAA,CAAc/T,SAASsK,CAAS,CAAA,CAAI,SAAS,aAAA,CAAcA,CAAS,EAAIA,CAAAA,CAE9E,GAAI,CAACyJ,CAAAA,CAAa,CAChB3S,KAAAA,CAAM,yCAAyC,EAC/C,MACF,CAGA,IAAMmJ,CAAAA,CAAgBP,CAAAA,CAAgBtB,CAAAA,CAAWC,CAAK,EACtD,OAAA4B,CAAAA,CAAc,MAAMwJ,CAAW,CAAA,CAG/BrD,IAAa,CAENnG,CACT,OAAS7L,CAAAA,CAAQ,CACf0C,MAAM,kBAAA,CAAoB1C,CAAM,CAEnB,CACb,MACF,CACF","file":"template.esm.js","sourcesContent":["import { error, isString } from '@estjs/shared';\nimport { createComponent } from './component';\nimport type { ComponentFn } 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 * @example\n * ```typescript\n * const buttonTemplate = template('<button>Click me</button>');\n * const button1 = buttonTemplate(); // Creates first button instance\n * const button2 = buttonTemplate(); // Creates second button instance\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 *\n * @example\n * ```typescript\n * const App = () => template('<div>Hello World</div>')\n * const app = createApp(App, '#root');\n *\n * // Or with DOM element\n * const container = document.getElementById('app');\n * const app = createApp(App, container);\n * ```\n */\nexport function createApp(component: ComponentFn, target: string | Element) {\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\n const rootComponent = createComponent(component);\n rootComponent.mount(container);\n\n return rootComponent;\n}\n","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/** Scope stack for nested execution contexts */\nconst scopeStack: Scope[] = [];\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\n // Push previous scope to stack if it exists\n if (prevScope) {\n scopeStack.push(prevScope);\n }\n\n activeScope = scope;\n\n try {\n return fn();\n } finally {\n // Restore previous scope\n activeScope = scopeStack.length > 0 ? scopeStack.pop()! : 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 if (scope.children) {\n // Copy to avoid modification during iteration\n const children = Array.from(scope.children);\n for (const child of children) {\n disposeScope(child);\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 * data-idx regex\n */\nexport const DATA_IDX_REGEX = /^\\d+-\\d+$/;\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 enum COMPONENT_TYPE {\n NORMAL = 'normal',\n FRAGMENT = 'fragment',\n PORTAL = 'portal',\n SUSPENSE = 'suspense',\n FOR = 'for',\n}\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 * Optimized with inline type checks for hot path performance.\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 * Used in hot paths - optimized for minimal branching.\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 as any)[NODE_KEY_SYMBOL];\n } else {\n (node as any)[NODE_KEY_SYMBOL] = normalizedKey;\n }\n}\n\n/**\n * Get the key from a node or component.\n * Optimized for inline usage in hot paths.\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 as any)[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","import { error, isFalsy, isHTMLElement, isPrimitive } from '@estjs/shared';\nimport { isComponent } from './component';\nimport { getNodeKey } from './key';\nimport type { AnyNode } from './types';\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 // Return undefined if it's an excluded property\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n // Otherwise return the original value (maintaining reactivity)\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\n/**\n * Remove node from its parent\n *\n * @param node Node to remove\n *\n * @example\n * ```typescript\n * removeNode(elementToRemove);\n * ```\n */\nexport function removeNode(node: AnyNode): void {\n if (!node) return;\n\n try {\n if (isComponent(node)) {\n node.destroy();\n } else {\n const element = node as Element;\n if (element.parentElement) {\n element.remove();\n }\n }\n } catch (_error) {\n error('Failed to remove node:', _error);\n }\n}\n\n/**\n * Insert child node\n * Handle insertion of component nodes and DOM nodes\n *\n * @param parent Parent node\n * @param child Child node\n * @param before Reference node for insertion\n */\nexport function insertNode(parent: Node, child: AnyNode, before?: AnyNode): void {\n if (!parent || !child) return;\n\n try {\n const beforeNode = isComponent(before) ? before.firstChild : (before as Node);\n\n if (isComponent(child)) {\n child.mount(parent, beforeNode);\n return;\n }\n\n if (beforeNode) {\n parent.insertBefore(child as Node, beforeNode);\n } else {\n if (__DEV__) {\n if (!child) {\n error('insertNode: child is not a Node', child);\n }\n }\n parent.appendChild(child as Node);\n }\n } catch (_error) {\n error('Failed to insert node:', _error);\n }\n}\n\n/**\n * Replace child node\n * Handle replacement of component nodes and DOM nodes\n *\n * @param parent Parent node\n * @param newNode New node\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 try {\n const beforeNode: AnyNode | undefined = isComponent(oldNode)\n ? oldNode.beforeNode\n : (oldNode as Node).nextSibling!;\n removeNode(oldNode);\n insertNode(parent, newNode, beforeNode);\n } catch (_error) {\n error('Failed to replace node:', _error);\n }\n}\n\n/**\n * Get the first DOM node from a node or component\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\n/**\n * Check if two nodes are the same (inline for performance)\n * This combines key check and type check\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 * Normalize node for reconciliation\n */\nexport function normalizeNode(node: unknown): Node {\n // already a Node\n if (isHTMLElement(node)) {\n return node;\n }\n\n // Handle primitives with memoization\n if (isPrimitive(node)) {\n const textContent = isFalsy(node) ? '' : String(node);\n\n // Create new text node directly\n return document.createTextNode(textContent);\n }\n\n return node as Node;\n}\nexport function isHtmlInputElement(val: unknown): val is HTMLInputElement {\n return val instanceof HTMLInputElement;\n}\nexport function isHtmlSelectElement(val: unknown): val is HTMLSelectElement {\n return val instanceof HTMLSelectElement;\n}\nexport function isHtmlTextAreaElement(val: unknown): val is HTMLTextAreaElement {\n return val instanceof HTMLTextAreaElement;\n}\n\nexport function isHtmlFormElement(val: unknown): val is HTMLFormElement {\n return val instanceof HTMLFormElement;\n}\n\nexport function isHtmLTextElement(val: unknown): val is Text {\n return val instanceof Text;\n}\n\n/**\n * Shallow compare two objects\n * @param {any} a - The first object to compare\n * @param {any} b - The second object to compare\n * @returns {boolean} - Returns true if the objects are equal, false otherwise\n */\nexport function shallowCompare(a: any, b: any): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n\n for (const key in a) {\n if (a[key] !== b[key]) return false;\n }\n\n for (const key in b) {\n if (!(key in a)) return false;\n }\n\n return true;\n}\n","import { isHTMLElement } from '@estjs/shared';\nimport { isComponent } from './component';\nimport { getNodeKey, setNodeKey } from './key';\nimport {\n getFirstDOMNode,\n insertNode,\n isHtmLTextElement,\n isSameNode,\n removeNode,\n replaceNode,\n} from './utils';\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 * Optimized for common cases with early returns and minimal allocations.\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 (isHtmLTextElement(oldNode) && isHtmLTextElement(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 * @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 * @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 * @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 const newChildrenLen = newChildren.length;\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 // 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 const nextAnchor =\n nextIndex + 1 < newChildrenLen ? getFirstDOMNode(newChildren[nextIndex + 1]) : anchor;\n\n if (newIndexToOldIndexMap[i] === 0) {\n // New node - insert it\n insertNode(parent, nextNode, nextAnchor);\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, nextAnchor);\n }\n } else {\n j--;\n }\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 * @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 { coerceArray, isFunction } from '@estjs/shared';\nimport { effect } from '@estjs/signals';\nimport {\n isHtmlInputElement,\n isHtmlSelectElement,\n isHtmlTextAreaElement,\n normalizeNode,\n removeNode,\n} from './utils';\nimport { patchChildren } from './patch';\nimport { type Scope, getActiveScope, onCleanup, runWithScope } from './scope';\nimport type { AnyNode } from './types';\n/**\n * Add event listener with automatic cleanup on scope destruction\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 // Register cleanup in current scope using onCleanup\n onCleanup(() => {\n element.removeEventListener(event, handler, options);\n });\n}\n\n/**\n * Bind an element to a setter function, allowing the element to update the setter value when its value changes.\n *\n * @param node The element to bind.\n * @param setter The setter function to call when the element's value changes.\n */\nexport function bindElement(node: Element, key, defaultValue, setter: (value: unknown) => void) {\n if (isHtmlInputElement(node)) {\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 } else if (isHtmlSelectElement(node)) {\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 } else if (isHtmlTextAreaElement(node)) {\n addEventListener(node, 'input', () => {\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 interface InsertOptions {\n preserveOnCleanup?: boolean;\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(\n parent: Node,\n nodeFactory: (() => Node | AnyNode[]) | Node | string | AnyNode[],\n before?: Node,\n) {\n if (!parent) return;\n // Capture owner scope at call time - this is critical for correct context inheritance\n // When dynamic components are created inside effects, they need to inherit from\n // the scope that was active when insert() was called, not when the effect runs\n const ownerScope: Scope | null = getActiveScope();\n\n let renderedNodes: AnyNode[] = [];\n\n // Track if this is the first run (for hydration)\n // Create effect for reactive updates\n const cleanup = effect(() => {\n const executeUpdate = () => {\n const rawNodes = isFunction(nodeFactory) ? nodeFactory() : nodeFactory;\n const nodes = coerceArray(rawNodes as unknown)\n .map(item => (isFunction(item) ? item() : item))\n .flatMap(i => i)\n .map(normalizeNode) as AnyNode[];\n\n renderedNodes = patchChildren(parent, renderedNodes, nodes, before) as AnyNode[];\n };\n\n // If we have an owner scope, run within it to maintain context hierarchy\n if (ownerScope && !ownerScope.isDestroyed) {\n runWithScope(ownerScope, executeUpdate);\n } else {\n executeUpdate();\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 * Map nodes from template by indexes\n */\nexport function mapNodes(template: Node, indexes: number[]): Node[] {\n const len = indexes.length;\n const tree = new Array<Node>(len); // Pre-allocate with exact size\n const indexSet = new Set(indexes); // O(1) lookup\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; // Early exit when all nodes found\n }\n index++;\n }\n\n let child = node.firstChild;\n while (child) {\n if (walk(child)) return true; // Propagate early exit\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 { coerceArray, isFunction, isHTMLElement, isObject, startsWith } from '@estjs/shared';\nimport { type Scope, createScope, disposeScope, getActiveScope, runWithScope } from './scope';\nimport { COMPONENT_STATE, COMPONENT_TYPE, EVENT_PREFIX, REF_KEY } from './constants';\nimport { addEventListener, insert } from './binding';\nimport { getComponentKey, normalizeKey } from './key';\nimport { getFirstDOMNode, insertNode, removeNode, shallowCompare } from './utils';\nimport { triggerMountHooks, triggerUpdateHooks } from './lifecycle';\nimport type { AnyNode, ComponentFn, ComponentProps } from './types';\n\nexport class Component {\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\n private reactiveProps: Record<string, any> = {};\n\n // component key\n public readonly key: string | undefined;\n // component state\n protected state: number = COMPONENT_STATE.INITIAL;\n\n // parent scope captured at construction time\n protected parentScope: Scope | null = null;\n\n // component type\n // @ts-ignore\n private [COMPONENT_TYPE.NORMAL] = 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 // Skip empty text nodes (anchors or null renders)\n for (const node of this.renderedNodes) {\n const dom = getFirstDOMNode(node);\n if (dom) {\n return dom;\n }\n }\n return undefined;\n }\n\n constructor(\n public component: ComponentFn,\n public props: ComponentProps | undefined,\n ) {\n this.key = props?.key ? normalizeKey(props.key) : getComponentKey(component);\n\n this.reactiveProps = shallowReactive({ ...(this.props || {}) });\n\n // Capture parent scope at construction time for correct hierarchy\n this.parentScope = getActiveScope();\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 // Create scope with correct parent (captured at construction or current active)\n const parent = this.parentScope ?? getActiveScope();\n this.scope = createScope(parent);\n\n // Run component within its scope\n const renderedNodes = runWithScope(this.scope, () => {\n // render the component\n let result = this.component(this.reactiveProps);\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 nodes = insert(parentNode, result as any, beforeNode) ?? [];\n\n return nodes;\n });\n\n this.renderedNodes = renderedNodes;\n\n // apply props (events, refs) - must be after renderedNodes is set\n // so that this.firstChild returns the correct element\n runWithScope(this.scope, () => {\n this.applyProps(this.props || {});\n });\n\n // update marks\n this.state = COMPONENT_STATE.MOUNTED;\n\n // Trigger scope mount hooks (unified lifecycle system)\n if (this.scope) {\n triggerMountHooks(this.scope);\n }\n\n return this.renderedNodes;\n }\n\n update(prevNode: Component): Component {\n // if key is different, mount the component\n if (this.key !== prevNode.key) {\n this.mount(prevNode.parentNode!, prevNode.beforeNode);\n return this;\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\n if (this.props) {\n for (const key in this.props) {\n if (key === 'key') continue;\n\n const newValue = this.props[key];\n const oldValue = this.reactiveProps[key];\n\n // 1. reference same\n if (Object.is(oldValue, newValue)) {\n continue;\n }\n // 2. object shallow compare\n if (isObject(oldValue) && isObject(newValue)) {\n if (shallowCompare(oldValue, newValue)) {\n continue;\n }\n }\n\n // 3. update reactiveProps\n this.reactiveProps[key] = newValue;\n }\n }\n\n // check if the component is already mount\n if (!this.isConnected && this.parentNode) {\n this.mount(this.parentNode, this.beforeNode);\n }\n\n // if the component is mount and has scope, apply new props and trigger update lifecycle\n if (this.scope) {\n runWithScope(this.scope, () => {\n this.applyProps(this.props || {});\n });\n // Trigger scope update hooks (unified lifecycle system)\n triggerUpdateHooks(this.scope);\n }\n\n return this;\n }\n\n async forceUpdate(): Promise<void> {\n await Promise.resolve();\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 the component\n let result = (this.component as Function)(this.reactiveProps);\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 // Normalize to array\n const newNodes = coerceArray(result) as AnyNode[];\n\n // Replace old nodes with new ones (complete re-render)\n if (this.parentNode) {\n let anchor: Node | undefined = this.beforeNode;\n if (!anchor && this.renderedNodes.length > 0) {\n const lastNode = this.renderedNodes[this.renderedNodes.length - 1];\n const lastDom = getFirstDOMNode(lastNode);\n if (lastDom) {\n anchor = lastDom.nextSibling as Node | undefined;\n }\n }\n\n // Remove old rendered nodes\n for (const node of this.renderedNodes) {\n removeNode(node);\n }\n\n // Insert new nodes before anchor\n for (const node of newNodes) {\n insertNode(this.parentNode, node, anchor);\n }\n\n this.renderedNodes = newNodes;\n }\n });\n\n if (this.scope) {\n triggerUpdateHooks(this.scope);\n }\n } catch (error) {\n // Rollback\n this.renderedNodes = originalNodes;\n throw error;\n }\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 const scope = this.scope;\n if (scope) {\n // Dispose scope (handles cleanup, destroy hooks, and children)\n // The disposeScope function triggers destroy hooks internally\n disposeScope(scope);\n this.scope = null;\n }\n\n // Remove all rendered nodes\n for (const node of this.renderedNodes) {\n removeNode(node);\n }\n\n // Reset all component properties\n this.renderedNodes = [];\n this.parentNode = undefined;\n this.beforeNode = undefined;\n this.parentScope = null;\n this.reactiveProps = {};\n this.props = undefined;\n this.state = COMPONENT_STATE.DESTROYED;\n }\n\n applyProps(props: ComponentProps): void {\n // check if props is defined\n if (!props) {\n return;\n }\n\n // Get first element for event handling and refs\n const firstElement = this.firstChild;\n\n // iterate over all properties and apply them\n for (const [propName, propValue] of Object.entries(props)) {\n if (startsWith(propName, EVENT_PREFIX) && firstElement) {\n // event handling: extract the event name after on\n const eventName = propName.slice(2).toLowerCase();\n\n if (isHTMLElement(firstElement)) {\n addEventListener(firstElement, eventName, propValue as EventListener);\n }\n } else if (propName === REF_KEY && isSignal(propValue)) {\n // handle reference: store the DOM reference into the signal value\n propValue.value = firstElement;\n }\n }\n\n // save props reference\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[COMPONENT_TYPE.NORMAL];\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(componentFn: ComponentFn, props?: ComponentProps): Component {\n if (isComponent(componentFn)) {\n return componentFn;\n }\n return new Component(componentFn, props);\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 console.log(scope);\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 console.log(current.provides);\n\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 * Event handler for delegated events\n * @param {Event} e - The event object\n */\nfunction eventHandler(e: Event): void {\n let node = e.target as any;\n const key = `${e.type}`;\n const oriTarget = e.target;\n const oriCurrentTarget = e.currentTarget;\n\n /**\n * Retarget the event's target property\n * @param {EventTarget} value - New target value\n */\n const reTarget = (value: EventTarget) =>\n Object.defineProperty(e, 'target', {\n configurable: true,\n value,\n });\n\n /**\n * Handle event on current node\n * @returns {boolean} Whether to continue propagation\n */\n const handleNode = (): 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, e) : handler.call(node, e);\n if (e.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(e.target)\n ) {\n reTarget(node.host);\n }\n return true;\n };\n\n /**\n * Walk up the DOM tree handling events\n */\n const walkUpTree = (): void => {\n while (handleNode() && (node = node._$host || node.parentNode || node.host));\n };\n\n // simulate currentTarget\n Object.defineProperty(e, 'currentTarget', {\n configurable: true,\n get() {\n return node || document;\n },\n });\n\n if (e.composedPath) {\n const path = e.composedPath();\n reTarget(path[0]);\n for (let i = 0; i < path.length - 2; i++) {\n node = path[i] as any;\n if (!handleNode()) break;\n if (node._$host) {\n node = node._$host;\n // bubble up from portal mount instead of composedPath\n walkUpTree();\n break;\n }\n if (node.parentNode === oriCurrentTarget) {\n break; // don't bubble above root of event delegation\n }\n }\n }\n // fallback for browsers that don't support composedPath\n else walkUpTree();\n // Mixing portals and shadow dom can lead to a nonstandard target, so reset here.\n reTarget(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","import { isArray, isObject } from '@estjs/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\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 *\n * @param value - The class value to normalize\n * @returns A normalized class string\n * @public\n */\nexport function normalizeClass(value: unknown): string {\n if (value == null) {\n return '';\n }\n\n if (typeof value === 'string') {\n return value.trim();\n }\n\n // Handle arrays\n if (isArray(value)) {\n return value.map(normalizeClass).filter(Boolean).join(' ');\n }\n\n // Handle objects (conditional classes)\n if (isObject(value)) {\n const result: string[] = [];\n\n for (const key in value) {\n if (value[key]) {\n result.push(key);\n }\n }\n\n return result.join(' ');\n }\n\n // Convert other types to string\n return String(value).trim();\n}\n","import { camelCase, capitalize, isArray, isObject, isString } from '@estjs/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\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 (typeof val === 'string' && 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 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';\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 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 if (prev === next) {\n return;\n }\n\n const lowerKey = key.toLowerCase();\n if (/^on[a-z]+/.test(lowerKey)) {\n return;\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 && typeof attrValue === 'string') {\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 as any)[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 { COMPONENT_TYPE } 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\n *\n * @param props - Component props with children\n * @returns DocumentFragment containing all children\n *\n * @example\n * ```tsx\n * <Fragment>\n * <div>First</div>\n * <span>Second</span>\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 if (!props.children) {\n error('Fragment component requires children');\n return null;\n }\n }\n\n // TODO:\n // Check if we're in SSR mode (no document)\n // if (typeof document === 'undefined') {\n // const children = props.children;\n // if (!children) return '';\n // const childArray = Array.isArray(children) ? children : [children];\n // // In SSR, convert children to string\n // return childArray.map(child => String(child || '')).join('');\n // }\n\n return props?.children as Element;\n}\n\nFragment[COMPONENT_TYPE.FRAGMENT] = 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 as any)[COMPONENT_TYPE.FRAGMENT];\n}\n","import { isArray, isString, warn } from '@estjs/shared';\nimport { insertNode, normalizeNode } from '../utils';\nimport { COMPONENT_TYPE } from '../constants';\nimport { onMount } from '../lifecycle';\nimport { onCleanup } from '../scope';\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 * ```\n */\nexport function Portal(props: PortalProps): Comment | string {\n // Check if we're in SSR mode (no document)\n if (typeof document === 'undefined') {\n const children = props.children;\n if (!children) return '';\n const childArray = isArray(children) ? children : [children];\n // In SSR, convert children to string\n return childArray.map(child => String(child || '')).join('');\n }\n // Create placeholder comment for parent tree\n const placeholder = document.createComment('portal');\n // Mark as portal for isPortal check\n (placeholder as any)[COMPONENT_TYPE.PORTAL] = true;\n\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, normalized);\n nodes.push(normalized);\n }\n }\n });\n\n onCleanup(() => {\n nodes.forEach(node => {\n if (typeof node !== 'string' && node.parentNode === targetElement) {\n targetElement.removeChild(node);\n }\n });\n });\n });\n }\n\n return placeholder;\n}\n\nPortal[COMPONENT_TYPE.PORTAL] = 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 as any)[COMPONENT_TYPE.PORTAL];\n}\n","import { isArray, isPromise, isUndefined, warn } from '@estjs/shared';\nimport { provide } from '../provide';\nimport { isComponent } from '../component';\nimport { insertNode, normalizeNode } from '../utils';\nimport { COMPONENT_TYPE } from '../constants';\nimport { onDestroy } from '../lifecycle';\nimport { getActiveScope } from '../scope';\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 (child as any).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[COMPONENT_TYPE.SUSPENSE] = 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 as any)[COMPONENT_TYPE.SUSPENSE];\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 const promise = fetcher();\n currentPromise = promise.then(() => {}); // We need a promise that resolves when data is ready\n\n try {\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) as any;\n if (suspenseContext) {\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 { isArray, isFunction, isNil, isString } from '@estjs/shared';\n\n/** Hydration identifier counter, used to generate unique IDs */\nlet hydrationCounter = 0;\n\n/**\n * get the hydration key\n * @returns {string} the hydration key\n */\nexport function getHydrationKey(): string {\n return `${hydrationCounter++}`;\n}\n\n/**\n * reset the hydration key\n */\nexport function resetHydrationKey(): void {\n hydrationCounter = 0;\n}\n\nlet isHydrationActive = false;\n\n/**\n * start the hydration\n */\nexport function startHydration(): void {\n isHydrationActive = true;\n}\n\n/**\n * end the hydration\n */\nexport function endHydration(): void {\n isHydrationActive = false;\n}\n\n/**\n * check if the hydration is active\n * @returns {boolean} true if the hydration is active, false otherwise\n */\nexport function isHydrating(): boolean {\n return isHydrationActive;\n}\n\n/**\n * convert the content to string\n * @param {unknown} content - the content to convert\n * @param {boolean} isSvg - whether the content is SVG\n * @returns {string} the content as a string\n */\nexport function convertToString(content: unknown, isSvg = false): string {\n // if result is null or undefined, return html\n if (isNil(content)) {\n return '';\n }\n\n // if result is a string, return result\n if (isString(content)) {\n return content;\n }\n\n // if result is an array, return the result of the array\n if (isArray(content)) {\n return content.map(item => convertToString(item, isSvg)).join('');\n }\n\n // if result is a function, return the result of the function\n if (isFunction(content)) {\n return convertToString(content(), isSvg);\n }\n\n // if result is other type, return the result of the string\n return String(content);\n}\n\n/**\n * add attributes to the html content\n * @param {string} htmlContent - the html content\n * @param {string} hydrationId - the hydration id\n * @returns {string} the html content with attributes\n */\nexport function addAttributes(htmlContent: string, hydrationId: string): string {\n // match the root element regex\n const rootElementRegex = /^<([a-z]+)(\\s*)([^>]*)>/i;\n // match the index attribute regex\n const indexAttributeRegex = /data-idx=\"(\\d+)\"/g;\n const commentRegex = /<!--(.*?)-->/g;\n\n // handle the html:\n // 1. add the hydration id to the root element\n // 2. add the hydration id prefix to all the index attributes\n const enhancedHtml = htmlContent\n .replace(rootElementRegex, `<$1$2$3 data-hk=\"${hydrationId}\">`)\n .replaceAll(indexAttributeRegex, `data-idx=\"${hydrationId}-$1\"`)\n .replaceAll(commentRegex, `<!--${hydrationId}-$1-->`);\n\n return enhancedHtml;\n}\n","import { error, isFunction } from '@estjs/shared';\nimport { addAttributes, convertToString, resetHydrationKey } from './shared';\nimport type { ComponentFn, ComponentProps } from '../types';\n/**\n *\n * ssg compile\n *\n * component context it will this:\n *\n * function component(props) {\n * // render function props: template, hydrationKey, ...components\n * return render(_tmpl, getHydrationKey(), createSSGComponent(xx, {}));\n * }\n *\n * renderToString(component, props)\n *\n *\n */\n\n/**\n * render the component to string\n * @param {ComponentFn} component - the component to render\n * @param {ComponentProps} props - the props to pass to the component\n * @returns {string} the rendered string\n */\nexport function renderToString(component: ComponentFn, props?: ComponentProps) {\n if (!isFunction(component)) {\n error('Component must be a function');\n return '';\n }\n\n // reset the hydration key\n resetHydrationKey();\n\n // render the component\n const result = component(props);\n\n // convert the result to string\n return convertToString(result);\n}\n\n/**\n * render the component to string\n * @param {string[]} templates - the template to render\n * @param {string} hydrationKey - the hydration key\n * @param {...string[]} components - the components to render\n * @returns {string} the rendered string\n */\nexport function render(templates: string[], hydrationKey: string, ...components: string[]) {\n // rendered content\n let content = '';\n // index\n let index = 0;\n\n /**\n *\n * jsx source code\n * <div>\n * <div>\n * <Component 1/>\n * <Component 2/>\n * </div>\n * <Component 3/>\n * </div>\n *\n * it will compile to:\n *\n *\n * let _tmpl = [\n * '<div><div>',\n * '</div>',\n * '</div>',\n * ]\n *\n * function component(props) {\n * return render(_tmpl, getHydrationKey(), createSSGComponent(Component1, {}), createSSGComponent(Component2, {}), createSSGComponent(Component3, {}));\n * }\n *\n */\n\n // map different templates\n for (const template of templates) {\n content += template;\n // render component\n if (index < components.length) {\n const component = components[index++];\n\n if (component) {\n content += convertToString(component);\n }\n }\n }\n\n //add hydrate key\n const result = addAttributes(content, hydrationKey);\n\n return result;\n}\n\n/**\n * create a ssg component\n * @param {ComponentFn} component - the component to create\n * @param {ComponentProps} props - the props to pass to the component\n * @returns {string} the created component as a string\n */\nexport function createSSGComponent(component: ComponentFn, props: ComponentProps = {}): string {\n if (!isFunction(component)) {\n error('create ssg component: Component is not a function');\n return '';\n }\n\n const result = component(props);\n\n return convertToString(result);\n}\n","import { isComputed, isSignal } from '@estjs/signals';\nimport { isArray, isNumber, isObject, isString, kebabCase } from '@estjs/shared';\n\n/**\n * Normalized style object type\n * Represents the processed style object format\n */\nexport type NormalizedStyle = Record<string, string | number>;\n\n/**\n * Normalize style value\n *\n * Convert style values in various formats (object, string, array) to a unified format\n *\n * @param styleValue Original style value\n * @returns Normalized style object or string\n */\nexport function normalizeStyle(styleValue: unknown): NormalizedStyle | string | undefined {\n // Handle array format styles\n if (isArray(styleValue)) {\n const normalizedStyleObject: NormalizedStyle = {};\n\n // Iterate through each style item in the array and merge\n for (const styleItem of styleValue) {\n const normalizedItem = isString(styleItem)\n ? parseStyleString(styleItem)\n : (normalizeStyle(styleItem) as NormalizedStyle);\n\n if (normalizedItem) {\n for (const key in normalizedItem) {\n normalizedStyleObject[key] = normalizedItem[key];\n }\n }\n }\n\n return normalizedStyleObject;\n }\n // Handle string or object format styles\n if (isString(styleValue) || isObject(styleValue)) {\n return styleValue as any;\n }\n\n // Return undefined for other types\n return undefined;\n}\n\n// Style parsing related regular expressions\n/** Semicolon separator regex, excludes semicolons within parentheses */\nconst styleSeparatorRegex = /;(?![^(]*\\))/g;\n/** Property value separator regex */\nconst propertyValueSeparatorRegex = /:([\\s\\S]+)/;\n/** Style comment regex */\nconst styleCommentRegex = /\\/\\*[\\s\\S]*?\\*\\//g;\n\n/**\n * Parse CSS style string into object format\n *\n * Parsing process:\n * 1. Remove CSS comments\n * 2. Split by semicolons into style items\n * 3. Parse each style item into key-value pairs\n *\n * @param cssText CSS style string\n * @returns Normalized style object\n */\nexport function parseStyleString(cssText: string): NormalizedStyle {\n const styleObject: NormalizedStyle = {};\n\n // Remove comments, split by semicolons, and process each item\n cssText\n .replaceAll(styleCommentRegex, '')\n .split(styleSeparatorRegex)\n .forEach(styleItem => {\n if (styleItem) {\n const parts = styleItem.split(propertyValueSeparatorRegex);\n // Only process valid property-value pairs\n if (parts.length > 1) {\n styleObject[parts[0].trim()] = parts[1].trim();\n }\n }\n });\n\n return styleObject;\n}\n\n/**\n * Convert style object to CSS string\n *\n * Handle different types of style values, and apply CSS variable and kebab-case transformations\n *\n * @param styleValue Style object or string\n * @returns Formatted CSS string\n */\nexport function styleObjectToString(styleValue: NormalizedStyle | string | undefined): string {\n // Check for empty values\n if (!styleValue) {\n return '';\n }\n\n // Return string values directly\n if (isString(styleValue)) {\n return styleValue;\n }\n\n // Convert object to string\n let cssText = '';\n for (const propName in styleValue) {\n const propValue = styleValue[propName];\n\n // Only process valid string or number values\n if (isString(propValue) || isNumber(propValue)) {\n // Keep CSS variables as is, convert other properties to kebab-case\n const normalizedPropName = propName.startsWith('--') ? propName : kebabCase(propName);\n cssText += `${normalizedPropName}:${propValue};`;\n }\n }\n\n return cssText;\n}\n\n/**\n * Normalize class name\n *\n * Process different formats of class name input (string, array, object) and output a unified string\n *\n * @param classValue Original class name value\n * @returns Normalized class name string\n */\nexport function normalizeClassName(classValue: unknown): string {\n let resultClassName = '';\n\n // Handle string class names\n if (isString(classValue)) {\n resultClassName = classValue;\n }\n // Handle array class names\n else if (isArray(classValue)) {\n for (const item of classValue) {\n const normalizedItem = normalizeClassName(item);\n if (normalizedItem) {\n resultClassName += `${normalizedItem} `;\n }\n }\n }\n // Handle object class names (conditional classes)\n else if (isObject(classValue)) {\n for (const className in classValue) {\n // Only add class name when value is truthy\n if (classValue[className]) {\n resultClassName += `${className} `;\n }\n }\n }\n\n return resultClassName.trim();\n}\n\n/**\n * Normalize component properties\n *\n * Special handling for class and style attributes, converting them to normalized format\n *\n * @param props Original component properties\n * @returns Normalized component properties\n */\nexport function normalizeProps(props: Record<string, any> | null): Record<string, any> | null {\n if (!props) {\n return null;\n }\n\n const { class: className, style } = props;\n\n // Normalize class attribute\n if (className && !isString(className)) {\n props.class = normalizeClassName(className);\n }\n\n // Normalize style attribute\n if (style) {\n props.style = normalizeStyle(style);\n }\n\n return props;\n}\n\n/**\n * Generate server-side rendering attribute string\n *\n * Generate HTML-compatible attribute string based on attribute type, handling special cases:\n * - Automatic unwrapping of reactive values\n * - Normalization of special attributes (style/class)\n * - Ignoring event attributes\n * - Special handling for boolean attributes\n *\n * @param attrName Attribute name\n * @param attrValue Attribute value\n * @param hydrationId Hydration ID (for client-side reuse)\n * @returns Formatted HTML attribute string\n */\nexport function setSSGAttr(attrName: string, attrValue: any, hydrationId: string): string {\n // Handle reactive values (signals or computed values)\n if (isSignal(attrValue) || isComputed(attrValue)) {\n return setSSGAttr(attrName, attrValue.value, hydrationId);\n }\n\n // Ignore null, undefined, and false value attributes\n if (!attrValue && attrValue !== 0) {\n return '';\n }\n\n // Special attribute handling: style\n if (attrName === 'style') {\n const normalizedStyle = normalizeStyle(attrValue);\n if (!normalizedStyle) {\n return '';\n }\n\n // Use string styles directly\n if (isString(normalizedStyle)) {\n return ` style=\"${normalizedStyle}\"`;\n }\n\n // Convert object styles to string\n return ` style=\"${styleObjectToString(normalizedStyle)}\"`;\n }\n\n // Special attribute handling: class\n if (attrName === 'class') {\n const normalizedClassName = normalizeClassName(attrValue);\n return normalizedClassName ? ` class=\"${normalizedClassName}\"` : '';\n }\n\n // Ignore event handler attributes (client-side behavior)\n if (attrName.startsWith('on')) {\n return '';\n }\n\n // Special handling for boolean attributes\n if (attrValue === true) {\n return ` ${attrName}`;\n }\n\n // Standard attribute handling\n return ` ${attrName}=\"${attrValue}\"`;\n}\n","/**\n * Server-side node mapping utilities\n */\n\nimport { error, isString } from '@estjs/shared';\nimport { createComponent } from '../component';\nimport { template } from '../renderer';\nimport { mapNodes } from '../binding';\nimport { DATA_IDX_REGEX } from '../constants';\nimport { endHydration, getHydrationKey, resetHydrationKey, startHydration } from './shared';\n\n/**\n * getRenderedElement function - gets an element based on string template\n */\nexport function getRenderedElement(temp: string) {\n return () => {\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 // Return existing node if found, otherwise create new element from template\n return node || template(temp)();\n };\n}\n\n/**\n * Maps server-side rendered nodes during hydration\n * @param {HTMLElement} template - The root template element\n * @param {number[]} idx - Array of indices to map\n * @returns {Node[]} Array of mapped nodes\n */\nexport function mapSSRNodes(template: HTMLElement, idx: number[]): Node[] {\n // Check if we're in hydration mode by looking for the data-hk attribute\n const hk = template.dataset.hk;\n\n // If not hydrating, fallback to standard node mapping\n if (!hk) {\n return mapNodes(template, 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 = template.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 //@ts-ignore\n const idxAttr = item.dataset.idx;\n return idxAttr !== null && DATA_IDX_REGEX.test(idxAttr);\n })\n .map((item: Element) => {\n //@ts-ignore\n const idxAttr = item.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(template);\n nodesList.push(...commentNodes);\n\n // Build final node list with template as first element\n const nodes: Node[] = [template];\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 * Hydrates a server-rendered component\n *\n * @param {Function} component - Component function to hydrate\n * @param {HTMLElement | string} container - Container element or selector\n * @param {Record<string, unknown>} props - Component properties\n * @returns {any} Component instance or undefined if hydration fails\n */\nexport function hydrate(\n component: (props?: any) => any,\n container: HTMLElement | string,\n props: Record<string, unknown> = {},\n): 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) ? document.querySelector(container) : 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, props);\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"]}
|