UNPKG

juris

Version:

JavaScript Unified Reactive Interface Solution - The First and Only Non-blocking Reactive Platform, Architecturally Optimized for Next Generation Cutting-Edge Cross-Platform Application. Transforms web development through comprehensive object-first archit

1 lines 76.9 kB
"use strict";const jurisLinesOfCode=3796,jurisVersion="0.88.2",jurisMinifiedSize="75.11 kB",isValidPath=e=>"string"==typeof e&&e.trim().length>0&&!e.includes(".."),getPathParts=e=>e.split(".").filter(Boolean),deepEquals=(e,t)=>{if(e===t)return!0;if(null==e||null==t||typeof e!=typeof t)return!1;if("object"==typeof e){if(Array.isArray(e)!==Array.isArray(t))return!1;const n=Object.keys(e),s=Object.keys(t);return n.length===s.length&&n.every((n=>s.includes(n)&&deepEquals(e[n],t[n])))}return!1},createLogger=()=>{const e=[],t=(t,n,s)=>{const r={formatted:`${s?`[${s}] `:""}${t}${n?` ${JSON.stringify(n)}`:""}`,message:t,context:n,category:s,timestamp:Date.now()};return setTimeout((()=>e.forEach((e=>e(r)))),0),r};return{log:{l:t,w:t,e:t,i:t,d:t},sub:t=>e.push(t),unsub:t=>e.splice(e.indexOf(t),1)}},{log:log,logSub:logSub,logUnsub:logUnsub}=createLogger(),createPromisify=()=>{const e=new Set;let t=!1;const n=new Set,s=()=>{0===e.size&&n.size>0&&n.forEach((e=>e()))};return{promisify:n=>{const r=n?.then?n:Promise.resolve(n);return t&&r!==n&&(e.add(r),r.finally((()=>{e.delete(r),setTimeout(s,0)}))),r},startTracking:()=>{t=!0,e.clear()},stopTracking:()=>{t=!1,n.clear()},onAllComplete:t=>(n.add(t),0===e.size&&setTimeout(t,0),()=>n.delete(t))}},{promisify:promisify,startTracking:startTracking,stopTracking:stopTracking,onAllComplete:onAllComplete}=createPromisify();class StateManager{constructor(e={},t=[]){console.info(log.i("StateManager initialized",{initialStateKeys:Object.keys(e),middlewareCount:t.length},"framework")),this.state={...e},this.middleware=[...t],this.subscribers=new Map,this.externalSubscribers=new Map,this.currentTracking=null,this.isUpdating=!1,this.initialState=JSON.parse(JSON.stringify(e)),this.maxUpdateDepth=50,this.updateDepth=0,this.currentlyUpdating=new Set,this.isBatching=!1,this.batchQueue=[],this.batchedPaths=new Set}reset(){console.info(log.i("State reset to initial state",{},"framework")),this.isBatching&&(this.batchQueue=[],this.batchedPaths.clear(),this.isBatching=!1),this.state=JSON.parse(JSON.stringify(this.initialState))}getState(e,t=null,n=!0){if(!isValidPath(e))return t;n&&this.currentTracking?.add(e);const s=getPathParts(e);let r=this.state;for(const e of s){if(void 0===r?.[e])return t;r=r[e]}return r}setState(e,t,n={}){console.debug(log.d("State change initiated",{path:e,hasValue:void 0!==t},"application")),isValidPath(e)&&!this._hasCircularUpdate(e)&&(this.isBatching?this._queueBatchedUpdate(e,t,n):this._setStateImmediate(e,t,n))}executeBatch(e){if(this.isBatching)return e();this.beginBatch();try{const t=e();return t&&"function"==typeof t.then?t.then((e=>(this.endBatch(),e))).catch((e=>{throw this.endBatch(),e})):(this.endBatch(),t)}catch(e){throw this.endBatch(),e}}beginBatch(){console.debug(log.d("Manual batch started",{},"framework")),this.isBatching=!0,this.batchQueue=[],this.batchedPaths.clear()}endBatch(){this.isBatching?(console.debug(log.d("Manual batch ending",{queuedUpdates:this.batchQueue.length},"framework")),this.isBatching=!1,0!==this.batchQueue.length&&this._processBatchedUpdates()):console.warn(log.w("endBatch() called without beginBatch()",{},"framework"))}isBatchingActive(){return this.isBatching}getBatchQueueSize(){return this.batchQueue.length}clearBatch(){this.isBatching&&(console.info(log.i("Clearing current batch",{clearedUpdates:this.batchQueue.length},"framework")),this.batchQueue=[],this.batchedPaths.clear())}_queueBatchedUpdate(e,t,n){this.batchQueue=this.batchQueue.filter((t=>t.path!==e)),this.batchQueue.push({path:e,value:t,context:n,timestamp:Date.now()}),this.batchedPaths.add(e)}_processBatchedUpdates(){const e=[...this.batchQueue];this.batchQueue=[],this.batchedPaths.clear();const t=new Map;e.forEach((e=>t.set(e.path,e)));const n=this.isUpdating;this.isUpdating=!0;const s=[];t.forEach((e=>{const t=this.getState(e.path);let n=e.value;for(const s of this.middleware)try{const r=s({path:e.path,oldValue:t,newValue:n,context:e.context,state:this.state});void 0!==r&&(n=r)}catch(t){console.error(log.e("Middleware error in batch",{path:e.path,error:t.message},"application"))}if(deepEquals(t,n))return;const r=getPathParts(e.path);let i=this.state;for(let e=0;e<r.length-1;e++){const t=r[e];null!=i[t]&&"object"==typeof i[t]||(i[t]={}),i=i[t]}i[r[r.length-1]]=n,s.push({path:e.path,oldValue:t,newValue:n})})),this.isUpdating=n;const r=new Set;s.forEach((({path:e})=>{const t=getPathParts(e);for(let e=1;e<=t.length;e++)r.add(t.slice(0,e).join("."))})),r.forEach((e=>{this.subscribers.has(e)&&this._triggerPathSubscribers(e),this.externalSubscribers.has(e)&&this.externalSubscribers.get(e).forEach((({callback:t,hierarchical:n})=>{try{t(this.getState(e),null,e)}catch(e){console.error(log.e("External subscriber error:",e),"application")}}))}))}_setStateImmediate(e,t,n={}){const s=this.getState(e);let r=t;for(const t of this.middleware)try{const i=t({path:e,oldValue:s,newValue:r,context:n,state:this.state});void 0!==i&&(r=i)}catch(n){console.error(log.e("Middleware error",{path:e,error:n.message,middlewareName:t.name||"anonymous"},"application"))}if(deepEquals(s,r))return void console.debug(log.d("State unchanged, skipping update",{path:e},"framework"));console.debug(log.d("State updated",{path:e,oldValue:typeof s,newValue:typeof r},"application"));const i=getPathParts(e);let o=this.state;for(let e=0;e<i.length-1;e++){const t=i[e];null!=o[t]&&"object"==typeof o[t]||(o[t]={}),o=o[t]}o[i[i.length-1]]=r,this.isUpdating||(this.isUpdating=!0,this.currentlyUpdating||(this.currentlyUpdating=new Set),this.currentlyUpdating.add(e),this._notifySubscribers(e,r,s),this._notifyExternalSubscribers(e,r,s),this.currentlyUpdating.delete(e),this.isUpdating=!1)}subscribe(e,t,n=!0){this.externalSubscribers.has(e)||this.externalSubscribers.set(e,new Set);const s={callback:t,hierarchical:n};return this.externalSubscribers.get(e).add(s),()=>{const t=this.externalSubscribers.get(e);t&&(t.delete(s),0===t.size&&this.externalSubscribers.delete(e))}}subscribeExact(e,t){return this.subscribe(e,t,!1)}subscribeInternal(e,t){return this.subscribers.has(e)||this.subscribers.set(e,new Set),this.subscribers.get(e).add(t),()=>{const n=this.subscribers.get(e);n&&(n.delete(t),0===n.size&&this.subscribers.delete(e))}}_notifySubscribers(e,t,n){this._triggerPathSubscribers(e);const s=getPathParts(e);for(let e=s.length-1;e>0;e--)this._triggerPathSubscribers(s.slice(0,e).join("."));const r=e?e+".":"";new Set([...this.subscribers.keys(),...this.externalSubscribers.keys()]).forEach((t=>{t.startsWith(r)&&t!==e&&this._triggerPathSubscribers(t)}))}_notifyExternalSubscribers(e,t,n){this.externalSubscribers.forEach(((s,r)=>{s.forEach((({callback:s,hierarchical:i})=>{if(i?e===r||e.startsWith(r+"."):e===r)try{s(t,n,e)}catch(e){console.error(log.e("External subscriber error:",e),"application")}}))}))}_triggerPathSubscribers(e){const t=this.subscribers.get(e);t&&t.size>0&&(console.debug(log.d("Triggering subscribers",{path:e,subscriberCount:t.size},"framework")),new Set(t).forEach((e=>{let t;try{t=this.currentTracking;const n=new Set;this.currentTracking=n,e(),this.currentTracking=t,n.forEach((t=>{const n=this.subscribers.get(t);n&&n.has(e)||this.subscribeInternal(t,e)}))}catch(e){console.error(log.e("Subscriber error:",e),"application"),this.currentTracking=t}})))}_hasCircularUpdate(e){return this.currentlyUpdating||(this.currentlyUpdating=new Set),!!this.currentlyUpdating.has(e)&&(console.warn(log.w("Circular dependency detected",{path:e},"framework")),!0)}startTracking(){const e=new Set;return this.currentTracking=e,e}endTracking(){const e=this.currentTracking;return this.currentTracking=null,e||new Set}}class HeadlessManager{constructor(e){console.info(log.i("HeadlessManager initialized",{},"framework")),this.juris=e,this.components=new Map,this.instances=new Map,this.context={},this.initQueue=new Set,this.lifecycleHooks=new Map}register(e,t,n={}){console.info(log.i("Headless component registered",{name:e,hasOptions:Object.keys(n).length>0},"framework")),this.components.set(e,{fn:t,options:n}),n.autoInit&&this.initQueue.add(e)}initialize(e,t={}){console.debug(log.d("Initializing headless component",{name:e,propsKeys:Object.keys(t)},"framework"));const n=this.components.get(e);if(!n)return console.error(log.e("Headless component not found",{name:e},"framework")),null;try{const s=this.juris.createHeadlessContext(),r=n.fn(t,s);return r&&"object"==typeof r?(console.info(log.i("Headless component initialized",{name:e,hasAPI:!!r.api,hasHooks:!!r.hooks},"framework")),this.instances.set(e,r),r.hooks&&this.lifecycleHooks.set(e,r.hooks),r.api&&(this.context[e]=r.api,this.juris.headlessAPIs||(this.juris.headlessAPIs={}),this.juris.headlessAPIs[e]=r.api,this.juris._updateComponentContexts()),r.hooks?.onRegister?.(),r):(console.error(log.e("Invalid headless component instance",{name:e},"framework")),null)}catch(t){return console.error(log.e("Headless component initialization failed",{name:e,error:t.message},"framework")),null}}initializeQueued(){this.initQueue.forEach((e=>{if(!this.instances.has(e)){const t=this.components.get(e);this.initialize(e,t.options||{})}})),this.initQueue.clear()}getInstance(e){return this.instances.get(e)}getAPI(e){return this.context[e]}getAllAPIs(){return{...this.context}}reinitialize(e,t={}){const n=this.instances.get(e);if(n?.hooks?.onUnregister)try{n.hooks.onUnregister()}catch(t){console.error(log.e(`Error in onUnregister for '${e}':`,t),"framework")}return this.context[e]&&delete this.context[e],this.juris.headlessAPIs?.[e]&&delete this.juris.headlessAPIs[e],this.instances.delete(e),this.lifecycleHooks.delete(e),this.initialize(e,t)}cleanup(){console.info(log.i("Cleaning up headless components",{instanceCount:this.instances.size},"framework")),this.instances.forEach(((e,t)=>{if(e.hooks?.onUnregister)try{e.hooks.onUnregister()}catch(e){console.error(log.e(`Error in onUnregister for '${t}':`,e),"framework")}})),this.instances.clear(),this.context={},this.lifecycleHooks.clear(),this.juris.headlessAPIs&&(this.juris.headlessAPIs={})}getStatus(){return{registered:Array.from(this.components.keys()),initialized:Array.from(this.instances.keys()),queued:Array.from(this.initQueue),apis:Object.keys(this.context)}}}class ComponentManager{constructor(e){console.info(log.i("ComponentManager initialized",{},"framework")),this.juris=e,this.components=new Map,this.instances=new WeakMap,this.componentCounters=new Map,this.componentStates=new WeakMap,this.asyncPlaceholders=new WeakMap,this.asyncPropsCache=new Map}register(e,t){console.info(log.i("Component registered",{name:e},"application")),this.components.set(e,t)}create(e,t={}){const n=this.components.get(e);if(!n)return console.error(log.e("Component not found",{name:e},"application")),null;try{if(this._hasAsyncProps(t))return console.debug(log.d("Component has async props",{name:e},"framework")),this._createWithAsyncProps(e,n,t);const{componentId:s,componentStates:r}=this._setupComponent(e);console.debug(log.d("Component setup complete",{name:e,componentId:s,stateCount:r.size},"framework"));const i=n(t,this._createComponentContext(s,r));return i?.then?this._handleAsyncComponent(promisify(i),e,t,r):this._processComponentResult(i,e,t,r)}catch(t){return console.error(log.e("Component creation failed. Did you forgot to use children:?",{name:e,error:t.message},"application")),this._createErrorElement(new Error(t.message+" Did you forgot to use children:[]?"))}}_setupComponent(e){this.componentCounters.has(e)||this.componentCounters.set(e,0);const t=this.componentCounters.get(e)+1;this.componentCounters.set(e,t);return{componentId:`${e}_${t}`,componentStates:new Set}}_createComponentContext(e,t){const n=this.juris.createContext();return n.newState=(n,s)=>{const r=`__local.${e}.${n}`;return this.juris.stateManager.getState(r,Symbol("not-found"))===Symbol("not-found")&&this.juris.stateManager.setState(r,s),t.add(r),[()=>this.juris.stateManager.getState(r,s),e=>this.juris.stateManager.setState(r,e)]},n}_hasAsyncProps(e){return Object.values(e).some((e=>e?.then))}_createWithAsyncProps(e,t,n){console.debug(log.d("Creating component with async props",{name:e},"framework"));const s=document.createElement("div");s.id=e.toLowerCase().replace(/[^a-z0-9]/g,"-");const r=this._createPlaceholder(`Loading ${e}...`,"juris-async-props-loading",s);return this.asyncPlaceholders.set(r,{name:e,props:n,type:"async-props"}),this._resolveAsyncProps(n).then((n=>{try{const s=this._createSyncComponent(e,t,n);s&&r.parentNode&&r.parentNode.replaceChild(s,r),this.asyncPlaceholders.delete(r)}catch(e){this._replaceWithError(r,e)}})).catch((e=>this._replaceWithError(r,e))),r}async _resolveAsyncProps(e){const t=this._generateCacheKey(e),n=this.asyncPropsCache.get(t);if(n&&Date.now()-n.timestamp<5e3)return n.props;const s={};for(const[t,n]of Object.entries(e))if(n?.then)try{s[t]=await n}catch(e){s[t]={__asyncError:e.message}}else s[t]=n;return this.asyncPropsCache.set(t,{props:s,timestamp:Date.now()}),s}_generateCacheKey(e){return JSON.stringify(e,((e,t)=>t?.then?"[Promise]":t))}_createSyncComponent(e,t,n){const{componentId:s,componentStates:r}=this._setupComponent(e),i=t(n,this._createComponentContext(s,r));return i?.then?this._handleAsyncComponent(promisify(i),e,n,r):this._processComponentResult(i,e,n,r)}_handleAsyncComponent(e,t,n,s){console.debug(log.d("Handling async component",{name:t},"framework"));const r=document.createElement("div");r.id=t.toLowerCase().replace(/[^a-z0-9]/g,"-");const i=this._createPlaceholder(`Loading ${t}...`,"juris-async-loading",r);return this.asyncPlaceholders.set(i,{name:t,props:n,componentStates:s}),e.then((e=>{console.debug(log.d("Async component resolved",{name:t},"framework"));try{const r=this._processComponentResult(e,t,n,s);r&&i.parentNode&&i.parentNode.replaceChild(r,i),this.asyncPlaceholders.delete(i)}catch(e){console.error(log.e("Async component failed",{name:t,error:e.message},"application")),this._replaceWithError(i,e)}})).catch((e=>this._replaceWithError(i,e))),i}_processComponentResult(e,t,n,s){if(e&&"object"==typeof e){if(this._hasLifecycleHooks(e))return this._createLifecycleComponent(e,t,n,s);if("function"==typeof e.render&&!this._hasLifecycleHooks(e)){const n=document.createElement("div");n.setAttribute("data-juris-reactive-render",t);const r=()=>{try{const s=e.render();if(s?.then)return n.innerHTML='<div class="juris-loading">Loading...</div>',void promisify(s).then((e=>{n.innerHTML="";const t=this.juris.domRenderer.render(e);t&&n.appendChild(t)})).catch((e=>{console.error(`Async render error for ${t}:`,e),n.innerHTML=`<div class="juris-error">Error: ${e.message}</div>`}));Array.from(n.children).forEach((e=>this.cleanup(e))),n.innerHTML="";const r=this.juris.domRenderer.render(s);r&&n.appendChild(r)}catch(e){console.error(`Error in reactive render for ${t}:`,e),n.innerHTML=`<div class="juris-error">Render Error: ${e.message}</div>`}},i=[];return this.juris.domRenderer._createReactiveUpdate(n,r,i),i.length>0&&this.juris.domRenderer.subscriptions.set(n,{subscriptions:i,eventListeners:[]}),s?.size>0&&this.componentStates.set(n,s),n}const r=Object.keys(e);if(1===r.length&&"string"==typeof r[0]&&r[0].length>0){const n=this.juris.domRenderer.render(e,!1,t);return n&&s.size>0&&this.componentStates.set(n,s),n}}const r=this.juris.domRenderer.render(e);return r&&s.size>0&&this.componentStates.set(r,s),r}_hasLifecycleHooks(e){return e.hooks&&(e.hooks.onMount||e.hooks.onUpdate||e.hooks.onUnmount)||e.onMount||e.onUpdate||e.onUnmount}_handleAsyncRender(e,t,n,s=null){const r=document.createElement("div");r.id=t.toLowerCase().replace(/[^a-z0-9]/g,"-");const i=s?this.juris.domRenderer.render(s):this._createPlaceholder(`Loading ${t}...`,"juris-async-loading",r);return e.then((e=>{try{const t=this.juris.domRenderer.render(e);t&&n.size>0&&this.componentStates.set(t,n),i.parentNode&&i.parentNode.replaceChild(t,i)}catch(e){this._replaceWithError(i,e)}})).catch((e=>this._replaceWithError(i,e))),i}_createLifecycleComponent(e,t,n,s){const r={name:t,props:n,hooks:e.hooks||{},api:e.api||{},render:e.render},i=r.render();if(i?.then)return this._handleAsyncLifecycleRender(promisify(i),r,s);const o=this.juris.domRenderer.render(i);return o&&(this.instances.set(o,r),s?.size>0&&this.componentStates.set(o,s),r.hooks.onMount&&setTimeout((()=>{try{const e=r.hooks.onMount();e?.then&&promisify(e).catch((e=>console.error(log.e(`Async onMount error in ${t}:`,e),"application")))}catch(e){console.error(log.e(`onMount error in ${t}:`,e),"application")}}),0)),o}_handleAsyncLifecycleRender(e,t,n){const s=document.createElement("div");s.id=t.name.toLowerCase().replace(/[^a-z0-9]/g,"-");const r=this._createPlaceholder(`Loading ${t.name}...`,"juris-async-lifecycle",s);return e.then((e=>{try{const s=this.juris.domRenderer.render(e);s&&(this.instances.set(s,t),n?.size>0&&this.componentStates.set(s,n),r.parentNode&&r.parentNode.replaceChild(s,r),t.hooks.onMount&&setTimeout((()=>{try{const e=t.hooks.onMount();e?.then&&promisify(e).catch((e=>console.error(log.e(`Async onMount error in ${t.name}:`,e),"application")))}catch(e){console.error(log.e(`onMount error in ${t.name}:`,e),"application")}}),0))}catch(e){this._replaceWithError(r,e)}})).catch((e=>this._replaceWithError(r,e))),r}updateInstance(e,t){const n=this.instances.get(e);if(!n)return;const s=n.props;deepEquals(s,t)||(this._hasAsyncProps(t)?this._resolveAsyncProps(t).then((t=>{n.props=t,this._performUpdate(n,e,s,t)})).catch((e=>console.error(log.e(`Error updating async props for ${n.name}:`,e),"application"))):(n.props=t,this._performUpdate(n,e,s,t)))}_performUpdate(e,t,n,s){if(e.hooks.onUpdate)try{const t=e.hooks.onUpdate(n,s);t?.then&&promisify(t).catch((t=>console.error(log.e(`Async onUpdate error in ${e.name}:`,t),"application")))}catch(t){console.error(log.e(`onUpdate error in ${e.name}:`,t),"application")}try{const n=e.render(),s=promisify(n);s!==n?s.then((e=>{this.juris.domRenderer.updateElementContent(t,e)})).catch((t=>console.error(log.e(`Async re-render error in ${e.name}:`,t),"application"))):this.juris.domRenderer.updateElementContent(t,n)}catch(t){console.error(log.e(`Re-render error in ${e.name}:`,t),"application")}}cleanup(e){const t=this.instances.get(e);if(t&&console.debug(log.d("Cleaning up component",{name:t.name},"framework")),t?.hooks?.onUnmount)try{const e=t.hooks.onUnmount();e?.then&&promisify(e).catch((e=>console.error(log.e(`Async onUnmount error in ${t.name}:`,e),"application")))}catch(e){console.error(log.e(`onUnmount error in ${t.name}:`,e),"application")}e._reactiveSubscriptions&&(e._reactiveSubscriptions.forEach((e=>{try{e()}catch(e){console.warn("Error cleaning up reactive subscription:",e)}})),e._reactiveSubscriptions=[]);const n=this.componentStates.get(e);n&&(n.forEach((e=>{const t=e.split(".");let n=this.juris.stateManager.state;for(let e=0;e<t.length-1;e++){if(!n[t[e]])return;n=n[t[e]]}delete n[t[t.length-1]]})),this.componentStates.delete(e)),this.asyncPlaceholders.has(e)&&this.asyncPlaceholders.delete(e),this.instances.delete(e)}_createPlaceholder(e,t,n=null){const s=this.juris.domRenderer._getPlaceholderConfig(n),r=document.createElement("div");return r.className=s.className,r.textContent=s.text,s.style&&(r.style.cssText=s.style),r}_createErrorElement(e){const t=document.createElement("div");return t.style.cssText="color: red; border: 1px solid red; padding: 8px; background: #ffe6e6;",t.textContent=`Component Error: ${e.message}`,t}_replaceWithError(e,t){const n=this._createErrorElement(t);e.parentNode&&e.parentNode.replaceChild(n,e),this.asyncPlaceholders.delete(e)}clearAsyncPropsCache(){this.asyncPropsCache.clear()}getAsyncStats(){return{registeredComponents:this.components.size,cachedAsyncProps:this.asyncPropsCache.size}}}class DOMRenderer{constructor(e){console.info(log.i("DOMRenderer initialized",{renderMode:"fine-grained"},"framework")),this.juris=e,this.subscriptions=new WeakMap,this.componentStack=[],this.cssCache=new Map,this.injectedCSS=new Set,this.styleSheet=null,this.camelCaseRegex=/([A-Z])/g,this.eventMap={ondoubleclick:"dblclick",onmousedown:"mousedown",onmouseup:"mouseup",onmouseover:"mouseover",onmouseout:"mouseout",onmousemove:"mousemove",onkeydown:"keydown",onkeyup:"keyup",onkeypress:"keypress",onfocus:"focus",onblur:"blur",onchange:"change",oninput:"input",onsubmit:"submit",onload:"load",onresize:"resize",onscroll:"scroll"},this.BOOLEAN_ATTRS=new Set(["disabled","checked","selected","readonly","multiple","autofocus","autoplay","controls","hidden","loop","open","required","reversed","itemScope"]),this.PRESERVED_ATTRIBUTES=new Set(["viewBox","preserveAspectRatio","textLength","gradientUnits","gradientTransform","spreadMethod","patternUnits","patternContentUnits","patternTransform","clipPath","crossOrigin","xmlns","xmlns:xlink","xlink:href"]),this.SVG_ELEMENTS=new Set(["svg","g","defs","desc","metadata","title","circle","ellipse","line","polygon","polyline","rect","path","text","tspan","textPath","marker","pattern","clipPath","mask","image","switch","foreignObject","linearGradient","radialGradient","stop","animate","animateMotion","animateTransform","set","use","symbol"]),this.KEY_PROPS=["id","className","text"],this.SKIP_ATTRS=new Set(["children","key"]),this.ATTRIBUTES_TO_KEEP=new Set(["id","data-juris-key"]),this.elementCache=new Map,this.recyclePool=new Map,this.renderMode="fine-grained",this.failureCount=0,this.maxFailures=3,this.asyncCache=new Map,this.asyncPlaceholders=new WeakMap,this.placeholderConfigs=new Map,this.defaultPlaceholder={className:"juris-async-loading",style:"padding: 8px; background: #f0f0f0; border: 1px dashed #ccc; opacity: 0.7;",text:"Loading...",children:null},this.tempArray=[],this.tempKeyParts=[],this.TOUCH_CONFIG={moveThreshold:10,timeThreshold:300,touchAction:"manipulation",tapHighlight:"transparent",touchCallout:"none"},this.RECYCLE_POOL_SIZE=100}setRenderMode(e){["fine-grained","batch"].includes(e)?(this.renderMode=e,console.info(log.i("Render mode changed",{mode:e},"framework"))):console.warn(log.w("Invalid render mode",{mode:e},"application"))}getRenderMode(){return this.renderMode}isFineGrained(){return"fine-grained"===this.renderMode}isBatchMode(){return"batch"===this.renderMode}render(e,t=!1,n=null){if("string"==typeof e||"number"==typeof e)return document.createTextNode(String(e));if(!e||"object"!=typeof e)return null;if(Array.isArray(e)){const s=document.createDocumentFragment();for(let r=0;r<e.length;r++){const i=this.render(e[r],t,n);i&&s.appendChild(i)}return s}const s=Object.keys(e)[0],r=e[s]||{};if(!t&&this.componentStack.includes(s))return this._createDeepRecursionErrorElement(s,this.componentStack);if(!t&&this.juris.componentManager.components.has(s)){const e=this.juris.stateManager.currentTracking;this.juris.stateManager.currentTracking=null,this.componentStack.push(s);const t=this.juris.componentManager.create(s,r);return this.componentStack.pop(),this.juris.stateManager.currentTracking=e,t}if(!t&&/^[A-Z]/.test(s))return this._createComponentErrorElement(s);if("string"!=typeof s||0===s.length)return null;let i=r;if(r.style&&!t&&this.cssExtraction){const e=n||s,t=this.extractCSS(e,r.style);t.className&&(i={...r},i.className=this.combineClassNames(r.className,t.className),t.reactiveStyle?i.style=t.reactiveStyle:delete i.style)}const o=n||(r.style?s:null);if(t)return this._createElementStatic(s,i,o);if("fine-grained"===this.renderMode)return this._createElementFineGrained(s,i,o);try{const e=i.key||this._generateKey(s,i),t=this.elementCache.get(e);return t&&this._canReuseElement(t,s,i)?(this._updateElementProperties(t,i),t):this._createElementOptimized(s,i,e,o)}catch(e){return this.failureCount++,this.failureCount>=this.maxFailures&&(this.renderMode="fine-grained"),this._createElementFineGrained(s,i,o)}}_createComponentErrorElement(e){const t=document.createElement("div");return t.style.cssText="color: red; border: 1px solid red; padding: 8px; background: #ffe6e6; font-family: monospace;",t.textContent=`Component "${e}" not registered`,t}_createDeepRecursionErrorElement(e,t){const n=document.createElement("div");n.style.cssText="color: red; border: 1px solid red; padding: 8px; background: #ffe6e6; font-family: monospace;";const s=[...t,e].join(" → ");return n.textContent=`Recursion detected: ${s}`,n}extractCSS(e,t){if(!this.cssExtraction)return{reactiveStyle:t};const{staticStyles:n,reactiveStyles:s}=this.separateStyles(t);if(0===Object.keys(n).length)return{reactiveStyle:Object.keys(s).length?s:null};const r=this.hashStyles(n),i=`${e}-${r}`;if(!this.cssCache.has(i)){const t=`j-${e.replace(/[^a-zA-Z0-9]/g,"")}-${r}`,s=this.generateCSS(t,n);this.cssCache.set(i,{css:s,className:t})}const o=this.cssCache.get(i);return this.injectedCSS.has(i)||(this.injectCSS(o.css),this.injectedCSS.add(i)),{className:o.className,reactiveStyle:Object.keys(s).length?s:null}}separateStyles(e){const t={},n={};for(const[s,r]of Object.entries(e))"function"==typeof r?n[s]=r:t[s]=r;return{staticStyles:t,reactiveStyles:n}}hashStyles(e){const t=Object.entries(e).sort((([e],[t])=>e.localeCompare(t))),n=JSON.stringify(t);let s=0;for(let e=0;e<n.length;e++)s=(s<<5)-s+n.charCodeAt(e)&2147483647;return s.toString(36)}generateCSS(e,t){return`.${e} {\n${Object.entries(t).map((([e,t])=>` ${e.replace(this.camelCaseRegex,"-$1").toLowerCase()}: ${t};`)).join("\n")}\n}`}injectCSS(e){if(!this.styleSheet){const e=document.createElement("style");e.setAttribute("data-juris-extracted",""),document.head.appendChild(e),this.styleSheet=e.sheet}try{this.styleSheet.insertRule(e,this.styleSheet.cssRules.length),console.debug(log.d("CSS injected",{css:e},"framework"))}catch(t){console.warn("CSS injection failed:",t),this.styleSheet.ownerNode.textContent+=e+"\n"}}combineClassNames(...e){return e.filter(Boolean).join(" ")}_createElementStatic(e,t,n=null){const s=this.SVG_ELEMENTS.has(e.toLowerCase())?document.createElementNS("http://www.w3.org/2000/svg",e):document.createElement(e);for(const e in t){if(!t.hasOwnProperty(e))continue;const r=t[e];if("children"===e)this._updateChildrenStatic(s,r,n);else if("text"===e)s.textContent=r;else if("style"===e&&"object"==typeof r)Object.assign(s.style,r);else if(e.startsWith("on")){const t="onclick"===e?"click":e.slice(2).toLowerCase();s.addEventListener(t,r)}else"key"!==e&&this._setStaticAttributeFast(s,e,r)}return s}_setStaticAttributeFast(e,t,n){this.PRESERVED_ATTRIBUTES.has(t)||t.includes("-")||t.includes(":")?e.setAttribute(t,n):"className"===t?e.className=n:"htmlFor"===t?e.setAttribute("for",n):"tabIndex"===t?e.tabIndex=n:t in e&&"function"!=typeof e[t]?e[t]=n:e.setAttribute(t,n)}_updateChildrenStatic(e,t,n=null){if("ignore"===t)return;e.textContent="";const s=document.createDocumentFragment();if(Array.isArray(t)){let e=t,r=!1;t.length>0&&t[0]?.config?.staticMode&&(r=!0,e=t.slice(1));for(let t=0;t<e.length;t++){const i=e[t];let o;o="string"==typeof i||"number"==typeof i?document.createTextNode(String(i)):this.render(i,r,n),o&&s.appendChild(o)}}else if(t){let e;e="string"==typeof t||"number"==typeof t?document.createTextNode(String(t)):this.render(t,!1,n),e&&s.appendChild(e)}s.hasChildNodes()&&e.appendChild(s)}_createElementFineGrained(e,t,n=null){const s=this.SVG_ELEMENTS.has(e.toLowerCase())?document.createElementNS("http://www.w3.org/2000/svg",e):document.createElement(e);this.tempArray.length=0;const r=this.tempArray,i=[];for(const e in t){if(!t.hasOwnProperty(e))continue;const o=t[e];"children"===e?this._handleChildren(s,o,r,n):"text"===e?this._handleText(s,o,r):"style"===e?this._handleStyle(s,o,r):e.startsWith("on")?this._handleEvent(s,e,o,i):"function"==typeof o?this._handleReactiveAttribute(s,e,o,r):this._isPromiseLike(o)?this._handleAsyncProp(s,e,o,r):"key"!==e&&this._setStaticAttribute(s,e,o)}return(r.length>0||i.length>0)&&this.subscriptions.set(s,{subscriptions:[...r],eventListeners:i}),s}_handleChildren(e,t,n){"fine-grained"===this.renderMode?this._handleChildrenFineGrained(e,t,n):this._handleChildrenOptimized(e,t,n)}_handleChildrenFineGrained(e,t,n){if(Array.isArray(t)&&t.length>0&&t[0]?.config?.staticMode)return this._updateChildrenStatic(e,t);"function"==typeof t?this._handleReactiveChildren(e,t,n):this._isPromiseLike(t)?this._handleAsyncChildrenDirect(e,t):this._updateChildren(e,t)}_handleChildrenOptimized(e,t,n){if(Array.isArray(t)&&t.length>0&&t[0]?.config?.staticMode)return this._updateChildrenStatic(e,t);if("function"==typeof t){let s=null,r=[],i=!0;const o=()=>{try{const n=t(e);if(this._isPromiseLike(n))promisify(n).then((t=>{if("ignore"!==t&&!this._childrenEqual(s,t))if(i)try{r=this._reconcileChildren(e,r,t),s=t}catch(n){console.warn(log.w("Reconciliation failed, falling back to safe rendering:",n.message),"framework"),i=!1,this._updateChildren(e,t),s=t}else this._updateChildren(e,t),s=t})).catch((e=>{console.error(log.e("Error in async children function:",e),"framework"),i=!1}));else if("ignore"!==n&&!this._childrenEqual(s,n))if(i)try{r=this._reconcileChildren(e,r,n),s=n}catch(t){console.warn(log.w("Reconciliation failed, falling back to safe rendering:",t.message),"framework"),i=!1,this._updateChildren(e,n),s=n}else this._updateChildren(e,n),s=n}catch(t){console.error(log.e("Error in children function:",t),"application"),i=!1;try{this._updateChildren(e,[])}catch(e){console.error(log.e("Even safe fallback failed:",e),"application")}}};this._createReactiveUpdate(e,o,n);try{const n=t();this._isPromiseLike(n)?promisify(n).then((t=>{r=this._reconcileChildren(e,[],t),s=t})).catch((t=>{console.warn(log.w("Initial async children failed, using safe method:",t.message),"framework"),i=!1,this._updateChildren(e,[])})):(r=this._reconcileChildren(e,[],n),s=n)}catch(n){console.warn(log.w("Initial reconciliation failed, using safe method:",n.message),"framework"),i=!1;const r=t();this._updateChildren(e,r),s=r}}else if(this._isPromiseLike(t))this._handleAsyncChildrenDirect(e,t);else try{this._reconcileChildren(e,[],t)}catch(n){console.warn(log.w("Static reconciliation failed, using safe method:",n.message),"framework"),this._updateChildren(e,t)}}_handleAsyncProp(e,t,n,s){"text"===t?this._handleAsyncTextDirect(e,n):"children"===t?this._handleAsyncChildrenDirect(e,n):"style"===t?this._handleAsyncStyleDirect(e,n):"innerHTML"===t?this._handleAsyncInnerHTMLDirect(e,n):(this._setPlaceholder(e,t),promisify(n).then((n=>{const s=this._getPlaceholderConfig(e);e.classList.remove(s.className),this._setStaticAttribute(e,t,n)})).catch((n=>{console.error(log.e(`Async prop '${t}' failed:`,n),"application"),this._setErrorState(e,t,n.message)})))}_handleAsyncInnerHTMLDirect(e,t){const n=this._getPlaceholderConfig(e);e.innerHTML=`<span class="${n.className}">${n.text}</span>`,promisify(t).then((t=>{e.innerHTML=t})).catch((t=>{console.error(log.e("Async innerHTML failed:",t),"application"),e.innerHTML=`<span class="juris-async-error">Error: ${t.message}</span>`}))}_hasAsyncProps(e){for(const t in e)if(e.hasOwnProperty(t)&&!t.startsWith("on")&&this._isPromiseLike(e[t]))return!0;return!1}_isPromiseLike(e){return e?.then}_getPlaceholderConfig(e){if(e?.id&&this.placeholderConfigs.has(e.id))return this.placeholderConfigs.get(e.id);let t=e?.parentElement;for(;t;){if(t.id&&this.placeholderConfigs.has(t.id))return this.placeholderConfigs.get(t.id);t=t.parentElement}return this.defaultPlaceholder}_setPlaceholder(e,t){const n=this._getPlaceholderConfig(e);({text:()=>{e.textContent=n.text,e.className=n.className,n.style&&(e.style.cssText=n.style)},children:()=>{if(n.children){const t=this.render(n.children);if(t)return void e.appendChild(t)}const t=document.createElement("span");t.textContent=n.text,t.className=n.className,n.style&&(t.style.cssText=n.style),e.appendChild(t)},className:()=>e.classList.add(n.className),style:()=>{n.style&&(e.style.cssText=n.style),e.classList.add(n.className)}}[t]||(()=>{e.setAttribute(t,"loading"),e.classList.add(n.className)}))()}_setErrorState(e,t,n){e.classList.add("juris-async-error"),"text"===t?e.textContent=`Error: ${n}`:"children"===t&&(e.innerHTML=`<span class="juris-async-error">Error: ${n}</span>`)}_childrenEqual(e,t){return e===t||Array.isArray(e)===Array.isArray(t)&&((!Array.isArray(e)||e.length===t.length)&&(deepEquals&&deepEquals(e,t)))}_reconcileChildren(e,t,n){console.debug(log.d("Reconciling children",{parentTag:e.tagName,oldCount:t.length,newCount:Array.isArray(n)?n.length:n?1:0},"framework")),Array.isArray(n)||(n=n?[n]:[]);const s=[],r=document.createDocumentFragment(),i=new Map;for(let e=0;e<t.length;e++){const n=t[e],s=n._jurisKey||`auto-${e}`;i.set(s,n)}const o=new Set;for(let t=0;t<n.length;t++){const a=n[t];if(!a||"object"!=typeof a)continue;const c=Object.keys(a)[0],l=a[c]||{},h=l.key||this._generateKey(c,l),d=i.get(h);if(d&&!o.has(d)&&this._canReuseElement(d,c,l)&&!this._wouldCreateCircularReference(e,d))d.parentNode&&d.parentNode.removeChild(d),this._updateElementProperties(d,l),s.push(d),r.appendChild(d),o.add(d),i.delete(h);else{const t=this.render(a);t&&!this._wouldCreateCircularReference(e,t)&&(t._jurisKey=h,s.push(t),r.appendChild(t))}}i.forEach((e=>{o.has(e)||this._recycleElement(e)}));try{e.textContent="",r.hasChildNodes()&&e.appendChild(r)}catch(t){console.error(log.e("Error in reconcileChildren:",t),"framework"),e.textContent="";for(let t=0;t<s.length;t++){const n=s[t];try{n&&!this._wouldCreateCircularReference(e,n)&&e.appendChild(n)}catch(t){console.error(log.e("Reconciliation failed",{parentTag:e.tagName,error:t.message},"framework"))}}}return s}_wouldCreateCircularReference(e,t){if(!e||!t)return!1;if(e===t)return!0;try{let n=e.parentNode;for(;n;){if(n===t)return!0;n=n.parentNode}if(t.contains&&t.contains(e))return!0;if(t.children)for(let n=0;n<t.children.length;n++)if(this._wouldCreateCircularReference(e,t.children[n]))return!0}catch(e){return console.warn(log.w("Error checking circular reference, assuming unsafe:",e),"application"),!0}return!1}_recycleElement(e){if(!e||!e.tagName)return;const t=e.tagName.toLowerCase();e.parentNode&&e.parentNode.removeChild(e),this.recyclePool.has(t)||this.recyclePool.set(t,[]);const n=this.recyclePool.get(t);n.length<this.RECYCLE_POOL_SIZE&&(this.cleanup(e),this._resetElement(e),n.push(e))}_handleAsyncChildrenDirect(e,t){const n=this._getPlaceholderConfig(e);let s;n.children?s=this.render(n.children):(s=document.createElement("div"),s.className=n.className,s.textContent=n.text,n.style&&(s.style.cssText=n.style)),e.appendChild(s),this.asyncPlaceholders.set(e,{type:"children",placeholder:s}),promisify(t).then((t=>{s.parentNode&&e.removeChild(s),this._updateChildren(e,t),this.asyncPlaceholders.delete(e)})).catch((e=>{console.error(log.e("Async children failed:",e),"application"),s.textContent=`Error loading content: ${e.message}`,s.className="juris-async-error"}))}_handleReactiveChildren(e,t,n){let s=null,r=!1;this._createReactiveUpdate(e,(()=>{try{const n=t(e);this._isPromiseLike(n)?promisify(n).then((t=>{"ignore"===t||r&&deepEquals(t,s)||("string"==typeof t||"number"==typeof t?e.textContent=String(t):this._updateChildren(e,t),s=t,r=!0)})).catch((e=>console.error(log.e("Error in async reactive children:",e),"application"))):"ignore"===n||r&&deepEquals(n,s)||("string"==typeof n||"number"==typeof n?e.textContent=String(n):this._updateChildren(e,n),s=n,r=!0)}catch(e){console.error(log.e("Error in reactive children function:",e),"application")}}),n)}_updateChildren(e,t,n=null){if("ignore"===t)return;e.textContent="";const s=document.createDocumentFragment();if(Array.isArray(t)){let e=t,r=!1;t.length>0&&t[0]?.config?.staticMode&&(r=!0,e=t.slice(1));for(let t=0;t<e.length;t++){const i=e[t];if(null==i)continue;let o;o="string"==typeof i||"number"==typeof i?document.createTextNode(String(i)):this.render(i,r,n),o&&s.appendChild(o)}}else if(t){let e;e="string"==typeof t||"number"==typeof t?document.createTextNode(String(t)):this.render(t,!1,n),e&&s.appendChild(e)}s.hasChildNodes()&&e.appendChild(s)}_handleText(e,t,n){"function"==typeof t?this._handleReactiveText(e,t,n):this._isPromiseLike(t)?this._handleAsyncTextDirect(e,t):e.textContent=t}_handleAsyncTextDirect(e,t){const n=this._getPlaceholderConfig(e);e.textContent=n.text,e.className=n.className,n.style&&(e.style.cssText=n.style),promisify(t).then((t=>{e.textContent=t,e.classList.remove(n.className),n.style&&(e.style.cssText="")})).catch((t=>{console.error(log.e("Async text failed:",t),"application"),e.textContent=`Error: ${t.message}`,e.classList.add("juris-async-error")}))}_handleReactiveText(e,t,n){let s=null,r=!1;this._createReactiveUpdate(e,(()=>{try{const n=t(e);this._isPromiseLike(n)?promisify(n).then((t=>{r&&t===s||(e.textContent=t,s=t,r=!0)})).catch((e=>console.error(log.e("Error in async reactive text:",e),"application"))):r&&n===s||(e.textContent=n,s=n,r=!0)}catch(e){console.error(log.e("Error in reactive text function:",e),"application")}}),n)}_handleStyle(e,t,n){if("function"==typeof t)this._handleReactiveStyle(e,t,n);else if(this._isPromiseLike(t))this._handleAsyncStyleDirect(e,t);else if("object"==typeof t)for(const s in t)if(t.hasOwnProperty(s)){const r=t[s];"function"==typeof r?this._handleReactiveStyleProperty(e,s,r,n):e.style[s]=r}}_handleReactiveStyleProperty(e,t,n,s){let r=null,i=!1;this._createReactiveUpdate(e,(()=>{try{const s=n(e);this._isPromiseLike(s)?promisify(s).then((n=>{i&&n===r||(e.style[t]=n,r=n,i=!0)})).catch((e=>console.error(`Error in async reactive style property '${t}':`,e))):i&&s===r||(e.style[t]=s,r=s,i=!0)}catch(e){console.error(`Error in reactive style property '${t}':`,e)}}),s)}_handleAsyncStyleDirect(e,t){const n=this._getPlaceholderConfig(e);if(e.classList.add(n.className),n.style){const t=n.style.split(";").filter((e=>e.trim()));for(let n=0;n<t.length;n++){const s=t[n],[r,i]=s.split(":").map((e=>e.trim()));r&&i&&(e.style[r]=i)}}promisify(t).then((t=>{if(e.classList.remove(n.className),"object"==typeof t){if(n.style){const t=n.style.split(";").map((e=>e.split(":")[0].trim())).filter((e=>e));for(let n=0;n<t.length;n++)e.style.removeProperty(t[n])}Object.assign(e.style,t)}})).catch((e=>console.error(log.e("Async style failed:",e),"application")))}_handleReactiveStyle(e,t,n){let s=null,r=!1;this._createReactiveUpdate(e,(()=>{try{const n=t(e);this._isPromiseLike(n)?promisify(n).then((t=>{r&&deepEquals(t,s)||"object"==typeof t&&(Object.assign(e.style,t),s={...t},r=!0)})).catch((e=>console.error(log.e("Error in async reactive style:",e),"application"))):r&&deepEquals(n,s)||"object"==typeof n&&(Object.assign(e.style,n),s={...n},r=!0)}catch(e){console.error(log.e("Error in reactive style function:",e),"application")}}),n)}_createElementOptimized(e,t,n){let s=this._getRecycledElement(e);s||(s=this.SVG_ELEMENTS.has(e.toLowerCase())?document.createElementNS("http://www.w3.org/2000/svg",e):document.createElement(e)),n&&(this.elementCache.set(n,s),s._jurisKey=n);const r=[],i=[];return this._processProperties(s,t,r,i),(r.length>0||i.length>0)&&this.subscriptions.set(s,{subscriptions:r,eventListeners:i}),s}_processProperties(e,t,n,s){for(const r in t){if(!t.hasOwnProperty(r)||"key"===r)continue;const i=t[r];switch(r){case"children":this._handleChildren(e,i,n);break;case"text":this._handleText(e,i,n);break;case"innerHTML":"function"==typeof i?this._handleReactiveAttribute(e,r,i,n):e.innerHTML=i;break;case"style":this._handleStyle(e,i,n);break;default:111===r.charCodeAt(0)&&110===r.charCodeAt(1)?this._handleEvent(e,r,i,s):"function"==typeof i?this._handleReactiveAttribute(e,r,i,n):this._setStaticAttribute(e,r,i)}}}_handleEvent(e,t,n,s){if(console.debug(log.d("Event handler attached",{tagName:e.tagName,eventName:t},"framework")),"onclick"===t){const t=this.TOUCH_CONFIG;e.style.touchAction=t.touchAction,e.style.webkitTapHighlightColor=t.tapHighlight,e.style.webkitTouchCallout=t.touchCallout,e.addEventListener("click",n),s.push({eventName:"click",handler:n});let r=0,i=!1,o=0,a=0;const c=e=>{r=Date.now(),i=!1,e.touches?.[0]&&(o=e.touches[0].clientX,a=e.touches[0].clientY)},l=e=>{if(e.touches?.[0]){const n=Math.abs(e.touches[0].clientX-o),s=Math.abs(e.touches[0].clientY-a);(n>t.moveThreshold||s>t.moveThreshold)&&(i=!0)}},h=e=>{const s=Date.now()-r;!i&&s<t.timeThreshold&&(e.preventDefault(),e.stopPropagation(),n(e))};e.addEventListener("touchstart",c,{passive:!0}),e.addEventListener("touchmove",l,{passive:!0}),e.addEventListener("touchend",h,{passive:!1}),s.push({eventName:"touchstart",handler:c},{eventName:"touchmove",handler:l},{eventName:"touchend",handler:h})}else{const r=t.toLowerCase(),i=this.eventMap[r]||r.slice(2);e.addEventListener(i,n),s.push({eventName:i,handler:n})}}_handleReactiveAttribute(e,t,n,s){let r=null,i=!1;this._createReactiveUpdate(e,(()=>{try{const s=n(e);this._isPromiseLike(s)?promisify(s).then((n=>{i&&deepEquals(n,r)||(this._setStaticAttribute(e,t,n),r=n,i=!0)})).catch((e=>console.error(log.e(`Error in async reactive attribute '${t}':`,e),"application"))):i&&deepEquals(s,r)||(this._setStaticAttribute(e,t,s),r=s,i=!0)}catch(e){console.error(log.e(`Error in reactive attribute '${t}':`,e),"application")}}),s)}_setStaticAttribute(e,t,n){if(this.SKIP_ATTRS.has(t))return;if("function"==typeof n)return"value"!==t||"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName&&"SELECT"!==e.tagName?void console.warn(log.w(`Function value for attribute '${t}' should be handled reactively`),"application"):void(e.value=n(e));if(this.BOOLEAN_ATTRS.has(t))return void(n&&"false"!==n?e.setAttribute(t,""):e.removeAttribute(t));if("http://www.w3.org/2000/svg"===e.namespaceURI)return void e.setAttribute(t,n);switch(t){case"htmlFor":return void e.setAttribute("for",n);case"className":return void(e.className=n)}const s=t.charCodeAt(0);this.PRESERVED_ATTRIBUTES.has(t)||100===s&&45===t.charCodeAt(4)||97===s&&45===t.charCodeAt(4)||-1!==t.indexOf("-")||-1!==t.indexOf(":")?e.setAttribute(t,n):t in e&&"function"!=typeof e[t]?e[t]=n:e.setAttribute(t,n)}_createReactiveUpdate(e,t,n){const s=this.juris.stateManager.startTracking(),r=this.juris.stateManager.currentTracking;this.juris.stateManager.currentTracking=s;try{t(e)}catch(e){console.error(log.e("Error capturing dependencies:",e),"application")}finally{this.juris.stateManager.currentTracking=r}const i=Array.from(s);for(let e=0;e<i.length;e++){const s=i[e],r=this.juris.stateManager.subscribeInternal(s,t);n.push(r)}}updateElementContent(e,t){this._updateChildren(e,[t])}setupIndicators(e,t){this.placeholderConfigs.set(e,{...this.defaultPlaceholder,...t})}cleanup(e){console.debug(log.d("Cleaning up element",{tagName:e.tagName,hasSubscriptions:this.subscriptions.has(e)},"framework")),this.juris.componentManager.cleanup(e);const t=this.subscriptions.get(e);if(t){if(t.subscriptions)for(let e=0;e<t.subscriptions.length;e++)try{t.subscriptions[e]()}catch(e){console.warn(log.w("Error during subscription cleanup:",e),"framework")}if(t.eventListeners)for(let n=0;n<t.eventListeners.length;n++){const{eventName:s,handler:r}=t.eventListeners[n];try{e.removeEventListener(s,r)}catch(e){console.warn(log.w("Error during event listener cleanup:",e),"framework")}}this.subscriptions.delete(e)}e._jurisKey&&this.elementCache.delete(e._jurisKey),this.asyncPlaceholders.has(e)&&this.asyncPlaceholders.delete(e);try{const t=e.children;for(let e=0;e<t.length;e++)try{this.cleanup(t[e])}catch(e){console.warn(log.w("Error cleaning up child element:",e),"framework")}}catch(e){console.warn(log.w("Error during children cleanup:",e),"framework")}}_generateKey(e,t){if(t.key)return t.key;let n=e;for(let e=0;e<this.KEY_PROPS.length;e++){const s=this.KEY_PROPS[e];t[s]&&"function"!=typeof t[s]&&(n+=`|${s}:${t[s]}`)}return n+=`|hash:${this._hashProps(t)}`,n}_hashProps(e){const t=JSON.stringify(e,((e,t)=>"function"==typeof t?"[function]":t));let n=0;for(let e=0;e<t.length;e++){n=(n<<5)-n+t.charCodeAt(e),n&=n}return Math.abs(n).toString(36)}_getRecycledElement(e){const t=this.recyclePool.get(e);if(t?.length>0){const e=t.pop();return this._resetElement(e),e}return null}_resetElement(e){e.textContent="",e.className="",e.removeAttribute("style");const t=Array.from(e.attributes);for(let n=0;n<t.length;n++){const s=t[n];this.ATTRIBUTES_TO_KEEP.has(s.name)||e.removeAttribute(s.name)}}_canReuseElement(e,t,n){return e.tagName.toLowerCase()===t.toLowerCase()}_updateElementProperties(e,t){for(const n in t)if(t.hasOwnProperty(n)&&!["key","children","text","style"].includes(n)){const s=t[n];"function"!=typeof s&&this._setStaticAttribute(e,n,s)}}clearAsyncCache(){this.asyncCache.clear()}getAsyncStats(){return{cachedAsyncProps:this.asyncCache.size,cachedCSS:this.cssCache.size,injectedCSS:this.injectedCSS.size}}clearCSSCache(){if(this.cssCache.clear(),this.injectedCSS.clear(),this.styleSheet){try{this.styleSheet.ownerNode.remove()}catch(e){}this.styleSheet=null}}getStats(){return{cssCache:this.cssCache.size,injectedCSS:this.injectedCSS.size,estimatedSubscriptions:2*this.cssCache.size,elementCache:this.elementCache.size,recyclePoolSize:Array.from(this.recyclePool.values()).reduce(((e,t)=>e+t.length),0),renderMode:this.renderMode,failureCount:this.failureCount}}}class TemplateCompiler{parseTemplate(e){const t=e.getAttribute("data-component"),n=e.getAttribute("data-context"),s=e.content,r=s.querySelector("script")?.textContent.trim()||"",i=document.createElement("div");i.appendChild(s.cloneNode(!0)),i.querySelector("script")?.remove();return{name:t,script:r,html:i.innerHTML.trim(),contextConfig:n}}htmlToObject(e){const t=document.createElement("div");return t.innerHTML=e,this.convertElement(t.firstElementChild)}convertElement(e){const t={},n=e.tagName.toLowerCase();t[n]={};for(const s of e.attributes){let e=s.value;if(e.startsWith("{")&&e.endsWith("}")){const r=e.slice(1,-1);t[n][s.name]={__FUNCTION__:r}}else t[n][s.name]=e}const s=Array.from(e.childNodes).map((e=>this.convertNode(e))).filter((e=>null!==e));if(1===s.length){const e=s[0];e&&e.__REACTIVE_CHILDREN__?t[n].children={__FUNCTION__:e.__REACTIVE_CHILDREN__}:e&&e.__REACTIVE_TEXT__?t[n].text={__FUNCTION__:e.__REACTIVE_TEXT__}:"string"==typeof e?t[n].text=e:e&&(t[n].children=[e])}else s.length>0&&(t[n].children=s);return t}convertNode(e){if(e.nodeType===Node.TEXT_NODE){const t=e.textContent.trim();if(!t)return null;const n=t.match(/^\{children:(.+)\}$/s);if(n)return{__REACTIVE_CHILDREN__:n[1]};const s=t.match(/^\{text:(.+)\}$/s);if(s)return{__REACTIVE_TEXT__:s[1]};const r=t.match(/^\{(.+)\}$/s);return r?{__REACTIVE_TEXT__:r[1]}:t}return e.nodeType===Node.ELEMENT_NODE?this.convertElement(e):null}generateContextDestructuring(e){if(!e)return"";return`const { ${e.split(",").map((e=>e.trim())).join(", ")} } = context;`}generateComponent(e){const t=this.objectToString(this.htmlToObject(e.html)),n=this.generateContextDestructuring(e.contextConfig);return`(props, context) => {\n${n?`${n}\n${e.script}`:e.script}\nreturn ${t};\n}`}objectToString(e,t=0){const n=" ".repeat(t);if(e&&e.__FUNCTION__)return e.__FUNCTION__;if("string"==typeof e)return`'${e.replace(/'/g,"\\'")}'`;if("number"==typeof e||"boolean"==typeof e)return String(e);if(Array.isArray(e)){if(0===e.length)return"[]";return"[\n"+e.map((e=>n+" "+this.objectToString(e,t+1))).join(",\n")+"\n"+n+"]"}if("object"==typeof e&&null!==e){const s=Object.keys(e);if(0===s.length)return"{}";return"{\n"+s.map((s=>{const r=this.objectToString(e[s],t+1),i=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s)?s:`'${s}'`;return n+" "+i+": "+r})).join(",\n")+"\n"+n+"}"}return"null"}}class DOMEnhancer{constructor(e){console.info(log.i("DOMEnhancer initialized",{},"framework")),this.juris=e,this.enhancedElements=new WeakSet,this.containerEnhancements=new WeakMap,this.options={debounceMs:5,batchUpdates:!0,observeSubtree:!0,observeChildList:!0,observeNewElements:!0,viewportAware:!1,viewportMargin:"50px"},this.enhancementRegistry=new Map,this.unifiedObserver=null,this.observerRefCount=0,this.pendingEnhancements=new Set,this.enhancementTimer=null,this.intersectionObserver=null,this.viewportElements=new WeakMap}enhance(e,t,n={}){if("undefined"==typeof MutationObserver)return()=>{};const s={...this.options,...n};if(s.viewportAware)return this._enhanceViewportAware(e,t,s);if(e instanceof Element){if(this.enhancedElements.has(e))return()=>{};return"selectors"===this._determineEnhancementType("",t)?this._enhanceContainer(e,t,s):this._enhanceElement(e,t,s),()=>this._cleanupElement(e)}const r=e,i=this._determineEnhancementType(r,t);return console.info(log.i("Enhancement registered",{selector:r,type:i,viewportAware:s.viewportAware,optionKeys:Object.keys(n)},"framework")),this.enhancementRegistry.set(r,{definition:t,config:s,type:i}),this._enhanceExistingElements(r,t,s,i),!1!==s.observeNewElements&&(this._ensureUnifiedObserver(s),this.observerRefCount++),()=>this._unenhance(r)}_enhanceViewportAware(e,t,n){if(console.debug(log.d("Viewport-aware enhancement starting",{selector:"string"==typeof e?e:"element",margin:n.viewportMargin},"framework")),e instanceof Element)return this._setupViewportObserver(n),this._observeElementForViewport(e,t,n),()=>this._cleanupViewportElement(e);const s=e,r=document.querySelectorAll(s);return this._setupViewportObserver(n),r.forEach((e=>{this._observeElementForViewport(e,t,n)})),()=>{r.forEach((e=>this._cleanupViewportElement(e))),this._cleanupViewportObserver()}}_determineEnhancementType(e,t){return this._hasSelectorsCategory(t)?"selectors":"string"==typeof e&&/^#[a-zA-Z][\w-]*$/.test(e)?"id":"simple"}_hasSelectorsCategory(e){if(e?.selectors)return!0;if("function"==typeof e)try{const t=e(this.juris.createContext());return t?.selectors}catch(e){return!1}return!1}_setupViewportObserver(e){this.intersectionObserver||(this.intersectionObserver=new IntersectionObserver((t=>{e.debounceMs>0?this._debouncedProcessViewportChanges(t):this._processViewportChanges(t)}),{root:null,rootMargin:e.viewportMargin,threshold:0}),console.debug(log.d("IntersectionObserver created",{margin:e.viewportMargin},"framework")))}_processViewportChanges(e){e.forEach((e=>{const t=e.target,n=this.viewportElements.get(t);n&&(console.debug(log.d("Viewport visibility changed",{element:t.tagName,isVisible:e.isIntersecting},"framework")),e.isIntersecting?this._enhanceElement(t,n.definition,n.config):(this._cleanupElemen