create-prisma-php-app 3.6.23 → 3.6.24
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/src/app/js/index.js +1 -1
- package/package.json +1 -1
package/dist/src/app/js/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,r=new Map,n=new WeakMap,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);function i(e){const t=e.currentTarget;if(t instanceof Element)return t;if(t instanceof Document||t===window)return document.body||document.documentElement||null;const r=e.target;if(r instanceof Element)return r;if(r&&"number"==typeof r.nodeType){const e=r;return e.parentElement||e.ownerDocument?.body||null}const n=e.composedPath?.();if(Array.isArray(n))for(const e of n)if(e instanceof Element)return e;return document.body||document.documentElement||null}function o(e,t){const r=globalThis.pphp??globalThis.PPHP?.instance??null;if(!r||!e)return t();let n=["app"];try{n=r.detectElementHierarchy(e)||["app"]}catch{n=["app"]}const s={eff:r._currentEffectContext,proc:r._currentProcessingHierarchy,evt:r._currentEventTarget};try{return r._currentEffectContext=n.join("."),r._currentProcessingHierarchy=n,r._currentEventTarget=e,t()}finally{r._currentEffectContext=s.eff,r._currentProcessingHierarchy=s.proc,r._currentEventTarget=s.evt}}function a(e,t,r){const s=function(e,t){let r=n.get(e);r||(r=new Map,n.set(e,r));let s=r.get(t);return s||(s=new Map,r.set(t,s)),s}(e,t),a=s.get(r);if(a)return a;let c;if("function"==typeof r){const e=r;c=function(t){return o(i(t),(()=>e.call(this,t)))}}else{const e=r;c={handleEvent:t=>o(i(t),(()=>e.handleEvent(t)))}}return s.set(r,c),c}EventTarget.prototype.addEventListener=function(t,n,i){let o=i;s.has(t)&&(void 0===o?o={passive:!0}:"boolean"==typeof o?o={capture:o,passive:!0}:void 0===o.passive&&(o={...o,passive:!0})),r.has(this)||r.set(this,new Map);const c=r.get(this),l=c.get(t)||new Set;l.add(n),c.set(t,l);const h=a(this,t,n);return e.call(this,t,h,o)},EventTarget.prototype.removeEventListener=function(e,s,i){if(r.has(this)&&r.get(this).has(e)){const t=r.get(this).get(e);t.delete(s),0===t.size&&r.get(this).delete(e)}const o=n.get(this)?.get(e),a=o?.get(s)??s;t.call(this,e,a,i),o?.delete(s)},EventTarget.prototype.removeAllEventListeners=function(e){const s=r.get(this);if(s){if(e){const r=s.get(e);if(!r)return;const i=n.get(this)?.get(e);return r.forEach((r=>{const n=i?.get(r)??r;t.call(this,e,n),i?.delete(r)})),void s.delete(e)}s.forEach(((e,r)=>{const s=n.get(this)?.get(r);e.forEach((e=>{const n=s?.get(e)??e;t.call(this,r,n)}))})),r.delete(this),n.delete(this)}}})(),function(){const e=console.log;console.log=(...t)=>{const r=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,r)}}();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_proxyCache=new WeakMap;_rawProps={};_refs=new Map;_wheelHandlersStashed=!1;_evaluatorCache=new Map;_depsCache=new Map;_dirtyDeps=new Set;_handlerCache=new Map;_handlerProxyCache=new WeakMap;_sharedStateMap=new Set;_processedLoops=new WeakSet;_hydrated=!1;_currentProcessingHierarchy=null;_stateHierarchy=new Map;_inlineModuleFns=new Map;_currentExecutionScope=null;_transitionStyleInjected=!1;_currentEffectContext=null;_currentEventTarget=null;_eventContextStack=[];_currentProcessingElement=null;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _cancelableEvents=new Set(["click","submit","change"]);static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;static _passiveEvents=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),r=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...r].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this._rawProps={},this.props=this.makeReactive({}),this.setupGlobalEventTracking(),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}debugProps(){console.group("%cPPHP Debug Snapshot","font-weight:bold; color:teal"),console.groupCollapsed("📦 Raw props"),console.log(JSON.stringify(this.props,null,2)),console.groupEnd(),console.groupCollapsed("🌐 Shared state (pphp.share)"),0===PPHP._shared.size?console.log("(none)"):console.table(Array.from(PPHP._shared.entries()).map((([e,{getter:t}])=>({key:e,value:this.formatValue(t()),type:typeof t()})))),console.groupEnd(),console.groupCollapsed("🔗 Shared keys declared this run"),0===this._sharedStateMap.size?console.log("(none)"):console.log([...this._sharedStateMap]),console.groupEnd(),console.groupCollapsed("🔖 State hierarchy"),console.table(Array.from(this._stateHierarchy.entries()).map((([e,t])=>({scopedKey:e,originalKey:t.originalKey,level:t.level,value:this.formatValue(this.getNested(this.props,e)),path:t.hierarchy.join(" → ")})))),console.groupEnd(),console.groupCollapsed("⚙️ Reactive internals"),console.log("Bindings total:",this._bindings.length),console.log("Pending bindings:",this._pendingBindings.size),console.log("Effects:",this._effects.size),console.log("Pending effects:",this._pendingEffects.size),console.log("Dirty deps:",Array.from(this._dirtyDeps).join(", ")||"(none)"),console.groupEnd(),console.groupCollapsed("🔗 Refs"),console.table(Array.from(this._refs.entries()).map((([e,t])=>({key:e,count:t.length,selectors:t.map((e=>e.tagName.toLowerCase())).join(", ")})))),console.groupEnd(),console.groupCollapsed("📦 Inline modules"),this._inlineModuleFns.forEach(((e,t)=>{console.log(`${t}:`,[...e.keys()])})),console.groupEnd(),console.log("Hydrated:",this._hydrated),console.groupCollapsed("🔀 Conditionals (pp-if chains)");Array.from(document.querySelectorAll("[pp-if], [pp-elseif], [pp-else]")).forEach(((e,t)=>{const r=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",n=e.getAttribute(`pp-${r}`)??null;let s=null;if(n){const t=n.replace(/^{\s*|\s*}$/g,""),r=this.detectElementHierarchy(e);try{s=!!this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r))}catch{s=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:r,expr:n,visible:!e.hasAttribute("hidden"),result:s})})),console.groupEnd(),console.groupCollapsed("🔁 Loops (pp-for)");const e=Array.from(document.querySelectorAll("template[pp-for]"));if(0===e.length)console.log("(none)");else{const t=e.map(((e,t)=>{const{itemName:r,idxName:n,arrExpr:s}=this.parseForExpression(e);let i=0;const o=e.previousSibling;if(o?.nodeType===Node.COMMENT_NODE&&"pp-for"===o.data){let e=o.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));)i+=1,e=e.nextSibling}return{"#":t,"(expr)":s,item:r||"(default)",idx:n||"(—)",rendered:i}}));console.table(t)}console.groupEnd(),console.groupEnd()}setupGlobalEventTracking(){const e=EventTarget.prototype.addEventListener,t=this;EventTarget.prototype.addEventListener=function(r,n,s){return e.call(this,r,(function(e){return t.trackEventContext&&t.trackEventContext(e),"function"==typeof n?n.call(this,e):n&&"function"==typeof n.handleEvent?n.handleEvent(e):void 0}),s)}}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{try{await Promise.all([this.initRefs(),this.bootstrapDeclarativeState(),this.processInlineModuleScripts(),this._hydrated=!0]),await e(),await this.initializeAllReferencedProps(),await e(),await this.manageAttributeBindings(),await e(),await this.processIfChains(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();const t=250;for(let r=0;r<this._bindings.length;r+=t)this._bindings.slice(r,r+t).forEach((e=>{try{e.update()}catch(e){console.error("Initial binding update error:",e)}})),await e();document.body.removeAttribute("hidden")}catch(e){console.error("Hydration failed:",e),document.body.removeAttribute("hidden")}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}async hydratePortal(e=document.body){await this.initReactiveOn(e,{wire:!0,preserveHierarchy:!0})}getPreservedPortalHierarchy(e){let t=e;for(;t&&t!==document.documentElement;){const e=t.getAttribute("data-pphp-original-hierarchy");if(e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch(e){console.warn("Failed to parse preserved portal hierarchy:",e)}t=t.parentElement}return[]}async initCryptoKey(){const e=document.cookie.split("; ").find((e=>e.startsWith("pphp_function_call_jwt=")))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),r=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:n,exp:s}=JSON.parse(r);if(Date.now()/1e3>s)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(n),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),r=(new TextEncoder).encode(e),n=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,r);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(n)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,r]=e.split(":",2),n=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),s=Uint8Array.from(atob(r),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:n},PPHP._cryptoKey,s);return(new TextDecoder).decode(i)}qsa(e,t){try{if(e)return e.querySelectorAll(t)}catch(e){console.error("qsa() failed:",e)}return document.createDocumentFragment().querySelectorAll(t)}async bootstrapDeclarativeState(e=document.body){this.qsa(e,"[pp-init-state]").forEach((e=>{let t,r=e.getAttribute("pp-init-state").trim();if(!r)return void e.removeAttribute("pp-init-state");try{t=JSON5.parse(r)}catch(e){return void console.error("Bad pp-init-state JSON:",r)}const n=this.detectElementHierarchy(e),s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=n,Object.entries(t).forEach((([e,t])=>{this.state(e,t)})),this._currentProcessingHierarchy=s,e.removeAttribute("pp-init-state")}))}detectComponentHierarchy(e){const t=[];let r=e;for(;r&&r!==document.documentElement;){const e=r.getAttribute("pp-component");e&&t.unshift(e),r=r.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){if(!e)return["app"];const t=this.getPreservedPortalHierarchy(e);if(t.length>0)return t;const r=[];let n=e instanceof Element?e:document.body||null;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&"__shared"!==e&&r.unshift(e),n=n.parentElement}return r.length?r:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const r=this._refs.get(e)??[];if(null!=t){const n=r[t];if(!n)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return n}if(0===r.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===r.length?r[0]:r}processRefsInFragment(e,t){e.querySelectorAll("[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),r=this._refs.get(t)??[];r.push(e),this._refs.set(t,r),e.removeAttribute("pp-ref")}))}effect(e,t){const r=Array.isArray(t),n=r?t:[],s=r&&0===n.length,i=this._currentProcessingHierarchy||(this._currentEffectContext?this._currentEffectContext.split("."):["app"]),o=i.join("."),a=n.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e();for(const[r,n]of PPHP._shared.entries())try{if(n.getter()===t)return Object.defineProperty(e,"__pphp_key",{value:`__shared.${r}`,writable:!1,enumerable:!1}),`__shared.${r}`}catch(e){}const r=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(r){const t=r[1],n=t.split(".")[0];if(PPHP._shared.has(n)){const r=`__shared.${t}`;return Object.defineProperty(e,"__pphp_key",{value:r,writable:!1,enumerable:!1}),r}}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),c=n.filter((e=>"function"==typeof e)),l=new Set(a),h=new Map,d=new Map;for(const e of a)try{const t=this.getResolvedValue(e);h.set(e,t)}catch(t){h.set(e,void 0)}for(const e of c)try{const t=e();d.set(e,t)}catch(t){d.set(e,Symbol("error"))}let p=0,u=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const f=PPHP._effectCleanups,m=()=>{const t=f.get(m);if(t){try{t()}catch(e){console.error("cleanup error:",e)}f.delete(m)}const n=performance.now();if(n-u<16)return void requestAnimationFrame((()=>{performance.now()-u>=16&&m()}));if(u=n,++p>100)throw console.error("PPHP: effect exceeded 100 runs - possible infinite loop"),console.error("Effect function:",e.toString()),console.error("Dependencies:",Array.from(l)),new Error("PPHP: effect ran >100 times — possible loop");if(!s){let e=!1;const t=[];for(const r of a)try{const n=this.getResolvedValue(r),s=h.get(r);this.hasValueChanged(n,s)&&(e=!0,t.push(r),h.set(r,n))}catch(n){e=!0,t.push(r),h.set(r,void 0)}for(const r of c)try{const n=r(),s=d.get(r);this.hasValueChanged(n,s)&&(e=!0,t.push("(function)"),d.set(r,n))}catch(n){d.get(r)!==Symbol("error")&&(e=!0,t.push("(function-error)"),d.set(r,Symbol("error")))}if(r&&(a.length>0||c.length>0)&&!e)return}const i=this._currentEffectContext;this._currentEffectContext=o;try{const t=e();"function"==typeof t&&f.set(m,t),p=0}catch(t){console.error("effect error:",t),console.error("Effect function:",e.toString())}finally{this._currentEffectContext=i}};Object.assign(m,{__deps:l,__static:s,__functionDeps:c,__hierarchy:i,__isEffect:!0});const y=this._currentEffectContext;this._currentEffectContext=o;try{const t=e();"function"==typeof t&&f.set(m,t),p=0}catch(e){console.error("effect error (initial):",e)}finally{this._currentEffectContext=y}const g=r&&this._inlineDepth>0?this._pendingEffects:this._effects;return s?this._effects.add(m):g.add(m),()=>{const e=f.get(m);if(e){try{e()}catch(e){console.error("cleanup error:",e)}f.delete(m)}this._effects.delete(m),this._pendingEffects.delete(m)}}resolveDependencyPath(e,t){const r=e.startsWith("app.")?e.substring(4):e,n=r.split(".")[0];if(PPHP._shared.has(n))return`__shared.${r}`;const s=t.join(".")+"."+e;if(this.hasNested(this.props,s))return s;if(this.hasNested(this.props,e))return e;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?n+"."+e:e;if(this.hasNested(this.props,s))return s}return e}getResolvedValue(e){const t=(e.startsWith("app.")?e.substring(4):e).split("."),r=t[0],n=PPHP._shared.get(r);if(n){if(1===t.length)return n.getter();{const e=n.getter(),r=t.slice(1).join(".");return this.getNested(e,r)}}return this.getNested(this.props,e)}hasValueChanged(e,t){if(e===t)return!1;if(null==e||null==t)return e!==t;if("object"!=typeof e||"object"!=typeof t)return e!==t;try{return JSON.stringify(e)!==JSON.stringify(t)}catch(e){return!0}}resetProps(){this._isNavigating=!1,this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=null,this._responseData=null,Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable&&delete window[e]}})),this._rawProps={},this.clearShare(),this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._handlerProxyCache=new WeakMap,this._processedLoops=new WeakSet,this._depsCache.clear(),this._dirtyDeps.clear(),this._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._currentProcessingElement=null,this._transitionStyleInjected=!1,this._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._currentProcessingHierarchy=null,this._currentExecutionScope=null,this._stateHierarchy.clear(),this._currentEventTarget=null,this._eventContextStack=[],this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1,this._currentEffectContext=null;try{const e=window;Object.getOwnPropertyNames(e).forEach((t=>{if(t.startsWith("__pphp_")||t.startsWith("_temp_"))try{delete e[t]}catch(e){}}))}catch(e){}this.props=this.makeReactive({}),this._hydrated=!1;const e=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT,{acceptNode:e=>"pp-for"===e.data?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let t;for(;t=e.nextNode();){let e=t.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));){const t=e.nextSibling;e.parentNode?.removeChild(e),e=t}t.parentNode?.removeChild(t)}}async initReactiveOn(e=document.body,t={}){const{wire:r=!0,preserveHierarchy:n=!1}=t,s=()=>new Promise((e=>setTimeout(e,0)));n&&e instanceof Element&&this.markPortalChildrenWithHierarchy(e),await Promise.all([this.initRefs(e),this.bootstrapDeclarativeState(e)]),await s(),await this.processInlineModuleScripts(e),await s(),this._hydrated=!0,await s(),await this.initializeAllReferencedProps(e),await s(),await this.manageAttributeBindings(e),await s(),await this.processIfChains(e),await s(),await this.initLoopBindings(e),await s(),r&&(e===document.body||e.isConnected)&&(await this.attachWireFunctionEvents(e),await s());for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await s()}markPortalChildrenWithHierarchy(e){const t=e.getAttribute("data-pphp-original-hierarchy");if(!t)return;const r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);for(;r.nextNode();){const e=r.currentNode;e.hasAttribute("data-pphp-original-hierarchy")||e.setAttribute("data-pphp-original-hierarchy",t)}}async removeAllEventListenersOnNavigation(){document.removeAllEventListeners(),this._refs.forEach((e=>e.forEach((e=>e.removeAllEventListeners?.())))),document.querySelectorAll("*").forEach((e=>e.removeAllEventListeners?.()))}async initLoopBindings(e=document.body){this.qsa(e,"template[pp-for]").forEach((e=>{this._processedLoops.has(e)||(this._processedLoops.add(e),this.registerLoop(e))}))}registerLoop(e){const t=this.parseForExpression(e),{marker:r,parent:n,templateHierarchy:s}=this.setupLoopMarker(e),i=this.initializeLoopState(),o=this.createLoopUpdater(e,t,r,n,s,i),a={dependencies:this.extractComprehensiveLoopDependencies(e,t,s),update:o,__isLoop:!0};this._bindings.push(a)}processIfChainsInFragment(e,t,r,n,s,i){const o=new WeakSet;e.querySelectorAll("[pp-if]").forEach((e=>{if(o.has(e))return;const a=[];let c=e;for(;c;){if(c.hasAttribute("pp-if"))a.push({el:c,expr:c.getAttribute("pp-if")});else if(c.hasAttribute("pp-elseif"))a.push({el:c,expr:c.getAttribute("pp-elseif")});else{if(!c.hasAttribute("pp-else"))break;a.push({el:c,expr:null})}o.add(c),c=c.nextElementSibling}a.forEach((e=>{if(null!==e.expr){const i=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(i,r);const o=this.makeScopedEvaluator(i,r);e.evaluate=()=>{const e={...this._createScopedPropsContext(r),[t.itemName]:n};return t.idxName&&(e[t.idxName]=s),!!o(e)}}}));let l=!1;for(const{el:e,expr:t,evaluate:r}of a)!l&&null!==t&&r()?(e.removeAttribute("hidden"),l=!0):l||null!==t?e.setAttribute("hidden",""):(e.removeAttribute("hidden"),l=!0);const h=new Set;a.forEach((e=>e.deps?.forEach((e=>h.add(e)))));const d=r.join("."),p=d?`${d}.${t.arrExpr}`:t.arrExpr;h.add(p);i.push({dependencies:h,update:()=>{const e=this.makeScopedEvaluator(t.arrExpr,r)(this._createScopedPropsContext(r));if(Array.isArray(e)){const i=this.getItemKey(n,s),o=this.findItemByKey(e,i,n),c=e.findIndex((t=>this.getItemKey(t,e.indexOf(t))===i));if(o&&-1!==c){let e=!1;for(const{el:n,expr:s}of a)if(null!==s){const i=this.makeScopedEvaluator(s.replace(/^{\s*|\s*}$/g,""),r),a={...this._createScopedPropsContext(r),[t.itemName]:o};t.idxName&&(a[t.idxName]=c);const l=!!i(a);!e&&l?(n.removeAttribute("hidden"),e=!0):n.setAttribute("hidden","")}else e?n.setAttribute("hidden",""):(n.removeAttribute("hidden"),e=!0)}}},__isLoop:!0})}))}extractComprehensiveLoopDependencies(e,t,r){const n=new Set,s=t.arrExpr.split(".")[0];let i=null;if(PPHP._shared.has(s)){i=`__shared.${t.arrExpr}`;try{const e=this.getNested(this.props,i);Array.isArray(e)||(i=null)}catch{i=null}}if(!i)for(let e=r.length;e>=0;e--){const n=r.slice(0,e),s=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,s);if(Array.isArray(e)){i=s;break}}catch{}}i||(i=t.arrExpr);const o=i;n.add(o);const a=this.extractItemPropertiesFromTemplate(e,t);for(const e of a){n.add(`${o}.*`),n.add(`${o}.*.${e}`);try{const t=this.getNested(this.props,o);if(Array.isArray(t))for(let r=0;r<t.length;r++)n.add(`${o}.${r}.${e}`)}catch{}}return Array.from(n).some((e=>e.includes("*")))||n.add(`${o}.*`),n}extractItemPropertiesFromTemplate(e,t){const r=new Set,n=new RegExp(`\\b${t.itemName}\\.(\\w+(?:\\.\\w+)*)`,"g"),s=document.createTreeWalker(e.content,NodeFilter.SHOW_ALL,null);for(;s.nextNode();){const e=s.currentNode;let t="";if(e.nodeType===Node.TEXT_NODE)t=e.nodeValue||"";else if(e.nodeType===Node.ELEMENT_NODE){const r=e;for(const e of Array.from(r.attributes))t+=" "+e.value}const i=t.matchAll(n);for(const e of i)r.add(e[1])}return r}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[r,n]=t.split(/\s+in\s+/),[s,i]=r.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:r,arrExpr:n,itemName:s,idxName:i}}setupLoopMarker(e){const t=e.parentNode,r=document.createComment("pp-for"),n=this.detectElementHierarchy(e);return t.insertBefore(r,e),t.removeChild(e),{marker:r,parent:t,templateHierarchy:n}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,r,n,s){const i={...this._createScopedPropsContext(s),[n.itemName]:t};n.idxName&&(i[n.idxName]=r);const o=e.content.cloneNode(!0),a=[],c=this.getItemKey(t,r);return this.processTextNodesInFragment(o,n,s,c,t,r,a),this.processElementBindingsInFragment(o,n,s,c,t,r,a),this.processEventHandlersInFragment(o,n,s,t),this.processRefsInFragment(o,a),this.processIfChainsInFragment(o,n,s,t,r,a),a.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),{nodes:Array.from(o.childNodes),bindings:a}}processTextNodesInFragment(e,t,r,n,s,i,o){const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;a.nextNode();){const e=a.currentNode,c=e.nodeValue||"";if(PPHP._mustacheTest.test(c)){const a=new Set,l=r.join("."),h=l?`${l}.${t.arrExpr}`:t.arrExpr;a.add(h);for(const e of c.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],r).forEach((e=>a.add(e)));const d=this.createTextNodeUpdaterWithItemKey(e,c,t,r,n,s);o.push({dependencies:a,update:d}),this.renderTextNode(e,c,t,r,s,i)}}}createTextNodeUpdaterWithItemKey(e,t,r,n,s,i){const o=this.makeScopedEvaluator(r.arrExpr,n);return()=>{const a=o(this._createScopedPropsContext(n));if(Array.isArray(a)){const o=this.findItemByKey(a,s,i),c=a.findIndex((e=>this.getItemKey(e,a.indexOf(e))===s));if(o&&-1!==c){const s={...this._createScopedPropsContext(n),[r.itemName]:o};r.idxName&&(s[r.idxName]=c);const i=this.renderMustacheText(t,n,s);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,r){for(let r=0;r<e.length;r++){const n=e[r];if(this.getItemKey(n,r)===t)return n}return r&&"object"==typeof r&&r.id?e.find((e=>e&&e.id===r.id)):null}processElementBindingsInFragment(e,t,r,n,s,i,o){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,r,n,s,i,o)}))}processElementBindings(e,t,r,n,s,i,o){const a=new Set,c=new Set;for(const{name:t,value:r}of Array.from(e.attributes))if(PPHP._mustacheTest.test(r)&&!t.startsWith("pp-bind"))a.add(t);else if(t.startsWith("pp-bind-")){const e=t.replace(/^pp-bind-/,"");c.add(e)}for(const{name:c,value:l}of Array.from(e.attributes))if("pp-bind"===c)this.createElementBindingWithItemKey(e,l,"text",t,r,n,s,i,o);else if("pp-bind-expr"===c){const a=this.decodeEntities(l);this.createElementBindingWithItemKey(e,a,"text",t,r,n,s,i,o)}else if(c.startsWith("pp-bind-")){const h=c.replace(/^pp-bind-/,"");if(a.has(h)){if(!this._boolAttrs.has(h))continue;e.removeAttribute(h)}this.createElementBindingWithItemKey(e,l,h,t,r,n,s,i,o)}else PPHP._mustacheTest.test(l)&&this.createElementAttributeTemplateBindingWithItemKey(e,c,l,t,r,n,s,i,o)}createElementAttributeTemplateBindingWithItemKey(e,t,r,n,s,i,o,a,c){const l=new Set,h=s.join("."),d=h?`${h}.${n.arrExpr}`:n.arrExpr;l.add(d);for(const e of r.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],s).forEach((e=>l.add(e)));const p=this.createAttributeTemplateUpdaterWithItemKey(e,t,r,n,s,i,o);c.push({dependencies:l,update:p}),this.renderAttributeTemplate(e,t,r,n,s,o,a)}createAttributeTemplateUpdaterWithItemKey(e,t,r,n,s,i,o){const a=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const c=a(this._createScopedPropsContext(s));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));a&&-1!==l&&this.renderAttributeTemplate(e,t,r,n,s,a,l)}}}renderAttributeTemplate(e,t,r,n,s,i,o){const a={...this._createScopedPropsContext(s),[n.itemName]:i};n.idxName&&(a[n.idxName]=o);const c=r.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeScopedEvaluator(t,s);return this.formatValue(e(a))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==c&&e.setAttribute(t,c)}createElementBindingWithItemKey(e,t,r,n,s,i,o,a,c){const l=new Set,h=s.join("."),d=h?`${h}.${n.arrExpr}`:n.arrExpr;l.add(d),this.extractScopedDependencies(t,s).forEach((e=>l.add(e)));const p=this.createElementBindingUpdaterWithItemKey(e,t,r,n,s,i,o);c.push({dependencies:l,update:p}),this.renderElementBinding(e,t,r,n,s,o,a)}createElementBindingUpdaterWithItemKey(e,t,r,n,s,i,o){const a=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const c=a(this._createScopedPropsContext(s));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));if(a&&-1!==l){const i={...this._createScopedPropsContext(s),[n.itemName]:a};n.idxName&&(i[n.idxName]=l),this.updateElementBinding(e,t,r,s,i)}}}}getItemKey(e,t){if(e&&"object"==typeof e){if("id"in e&&null!=e.id)return`id_${e.id}`;if("key"in e&&null!=e.key)return`key_${e.key}`;if("_id"in e&&null!=e._id)return`_id_${e._id}`;const t=Object.keys(e).filter((t=>(t.toLowerCase().includes("id")||t.toLowerCase().includes("uuid"))&&null!=e[t]&&("string"==typeof e[t]||"number"==typeof e[t])));if(t.length>0){const r=t[0];return`${r}_${e[r]}`}}return`idx_${t}`}renderTextNode(e,t,r,n,s,i){const o={...this._createScopedPropsContext(n),[r.itemName]:s};r.idxName&&(o[r.idxName]=i),e.nodeValue=this.renderMustacheText(t,n,o)}renderMustacheText(e,t,r){return e.replace(PPHP._mustachePattern,((e,n)=>{try{const e=this.makeScopedEvaluator(n,t);return this.formatValue(e(r))}catch{return""}}))}updateElementBinding(e,t,r,n,s){const i=this.makeScopedEvaluator(t,n)(s);if("text"===r){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,r,i)}renderElementBinding(e,t,r,n,s,i,o){const a={...this._createScopedPropsContext(s),[n.itemName]:i};n.idxName&&(a[n.idxName]=o),this.updateElementBinding(e,t,r,s,a)}applyAttributeBinding(e,t,r){if(this._boolAttrs.has(t)){const n=!!r;n!==e.hasAttribute(t)&&(n?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==n&&(e[t]=n)}else{const n=String(r);t in e&&e[t]!==n&&(e[t]=n),e.getAttribute(t)!==n&&e.setAttribute(t,n)}}processEventHandlersInFragment(e,t,r,n){e.querySelectorAll("*").forEach((e=>{const s=this.getItemKey(n,-1);for(const{name:n,value:i}of Array.from(e.attributes)){const o=n.toLowerCase();if(!this._eventHandlers.has(o))continue;let a=i;const c=`globalThis.pphp._getDynamicLoopItem('${s}', '${t.arrExpr}', ${JSON.stringify(r)})`;if(a=a.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),c),t.idxName){const e=`globalThis.pphp._idxOf(${c}, '${t.arrExpr}', ${JSON.stringify(r)})`;a=a.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),e)}e.setAttribute(n,a)}}))}_getDynamicLoopItem(e,t,r){try{const n=this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r));if(!Array.isArray(n))return null;for(let t=0;t<n.length;t++){const r=n[t];if(this.getItemKey(r,t)===e)return r}return null}catch{return null}}_idxOf(e,t,r){try{const n=this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r));if(!Array.isArray(n))return-1;let s=n.findIndex((t=>t===e));if(-1!==s)return s;const i=this.getItemKey(e,-1);return s=n.findIndex(((e,t)=>this.getItemKey(e,t)===i)),s}catch{return-1}}updateItemNodes(e,t,r,n,s,i){if(t===r)return;if("object"==typeof t&&"object"==typeof r&&JSON.stringify(t)===JSON.stringify(r))return;const o={...this._createScopedPropsContext(i),[s.itemName]:r};s.idxName&&(o[s.idxName]=n),this.updateNodesContent(e,i,o),this.updateConditionalNodes(e,i,o)}updateConditionalNodes(e,t,r){e.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){e.querySelectorAll("[pp-if], [pp-elseif], [pp-else]").forEach((e=>{const n=e.getAttribute("pp-if")||e.getAttribute("pp-elseif");if(n){const s=n.replace(/^{\s*|\s*}$/g,"");try{const n=this.makeScopedEvaluator(s,t);!!n(r)?e.removeAttribute("hidden"):e.setAttribute("hidden","")}catch(e){console.error("Error evaluating pp-if condition:",s,e)}}else if(e.hasAttribute("pp-else")){const t=e.previousElementSibling;t&&t.hasAttribute("hidden")?e.removeAttribute("hidden"):e.setAttribute("hidden","")}}))}}))}updateNodesContent(e,t,r){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,r)}))}updateElementContent(e,t,r){const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;n.nextNode();){const e=n.nextNode(),s=e.nodeValue||"",i=this.renderMustacheText(s,t,r);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,r),this.updateElementTemplateAttributes(e,t,r)}))}updateElementTemplateAttributes(e,t,r){for(const{name:n,value:s}of Array.from(e.attributes))if(!n.startsWith("pp-bind")&&PPHP._mustacheTest.test(s)){const i=s.replace(PPHP._mustachePattern,((e,n)=>{try{const e=this.makeScopedEvaluator(n,t);return this.formatValue(e(r))}catch(e){return console.error("PPHP: mustache token error:",n,e),""}}));e.getAttribute(n)!==i&&e.setAttribute(n,i)}}updateElementBindingsContent(e,t,r){for(const{name:n,value:s}of Array.from(e.attributes))if("pp-bind"===n)this.updateElementBinding(e,s,"text",t,r);else if(n.startsWith("pp-bind-")){const i=n.replace(/^pp-bind-/,"");this.updateElementBinding(e,s,i,t,r)}}createLoopUpdater(e,t,r,n,s,i){const o=(()=>{const e=t.arrExpr.split(".")[0];return r=>{if(PPHP._shared.has(e))try{const e=`__shared.${t.arrExpr}`,r=this.getNested(this.props,e);if(Array.isArray(r))return r}catch{}for(let e=s.length;e>=0;e--){const r=s.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,r),n=e(this._createScopedPropsContext(r));if(Array.isArray(n))return n}catch{}}try{const e=this.makeScopedEvaluator(t.arrExpr,s)(r);return Array.isArray(e)?e:[]}catch{return[]}}})();return()=>{this.performLoopUpdate(e,t,r,n,s,i,o)}}captureFocusState(e){const t=document.activeElement,r=t&&e.contains(t),n=r?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:r,focusKey:n,caretPos:r&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const r=t.querySelector(`[key="${e.focusKey}"]`),n=r?.querySelector("input,textarea");if(n&&(n.focus({preventScroll:!0}),null!==e.caretPos&&n instanceof HTMLInputElement)){const t=Math.min(e.caretPos,n.value.length);n.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const r=new Map,n=new Map;e.forEach(((e,t)=>{const n=this.getItemKey(e,t);r.set(n,{item:e,index:t})})),t.forEach(((e,t)=>{const r=this.getItemKey(e,t);n.set(r,{item:e,index:t})}));const s=new Set,i=new Map,o=new Map;for(const[e]of r)n.has(e)||s.add(e);for(const[e,{item:t,index:s}]of n)if(r.has(e)){const n=r.get(e);n.item===t&&n.index===s||o.set(e,{oldItem:n.item,newItem:t,newIndex:s,oldIndex:n.index})}else i.set(e,{item:t,index:s});return{toDelete:s,toInsert:i,toUpdate:o}}applyLoopChanges(e,t,r,n,s,i,o){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,r,i),this.applyLoopInsertions(e.toInsert,t,r,n,s,i,o)}applyLoopUpdates(e,t,r,n){for(const[s,{oldItem:i,newItem:o,newIndex:a}]of e){const e=t.renderedItems.get(s);e&&(this.updateItemNodes(e.nodes,i,o,a,r,n),e.item=o,e.index=a,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,r,n,s,i,o){if(0===e.size)return;const a=Array.from(e.entries()).sort((([,e],[,t])=>e.index-t.index));for(const[e,{item:c,index:l}]of a){if(t.renderedItems.has(e)){console.warn(`Item with key ${e} already exists, skipping insertion`);continue}const{nodes:a,bindings:h}=this.createItemNodes(o,c,l,r,i);let d=n;const p=Array.from(t.renderedItems.entries()).map((([e,t])=>({key:e,...t}))).sort(((e,t)=>e.index-t.index));for(let e=p.length-1;e>=0;e--)if(p[e].index<l){d=p[e].nodes[p[e].nodes.length-1];break}a.forEach((e=>{s.insertBefore(e,d.nextSibling),d=e})),t.renderedItems.set(e,{nodes:a,item:c,index:l,bindings:h})}}performLoopUpdate(e,t,r,n,s,i,o){const a=this.captureFocusState(n);let c,l=[];for(let e=s.length;e>=0;e--){const t=s.slice(0,e);try{c=this._createScopedPropsContext(t);const e=o(c);if(Array.isArray(e)&&e.length>=0){l=e;break}}catch(e){console.error("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(s);const e=o(c);l=Array.isArray(e)?e:[]}if(!Array.isArray(l))return void console.warn("Loop expression did not return an array:",l);const h=this.calculateLoopDiff(i.previousList,l);this.applyLoopChanges(h,i,t,r,n,s,e),i.previousList=[...l],this.restoreFocusState(a,n),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const r of e){const e=t.renderedItems.get(r);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{this.cleanupRefsInNode(e),e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(r))}}cleanupRefsInNode(e){if(e.nodeType===Node.ELEMENT_NODE){[e,...e.querySelectorAll("[data-ref-key]")].forEach((e=>{for(const[t,r]of this._refs.entries()){const n=r.indexOf(e);n>-1&&(r.splice(n,1),0===r.length&&this._refs.delete(t))}}))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),r=this._refs.get(t)??[];r.push(e),this._refs.set(t,r),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){if(this.shouldUnwrapValue(e))return e;const r=this._proxyCache.get(e);if(r)return r;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const n=this,s=new Proxy(e,{get(e,r,s){if("__isReactiveProxy"===r)return!0;const i=Reflect.get(e,r,s);if(null===i||"object"!=typeof i)return i;if(Array.isArray(e)&&"string"==typeof r&&n._mutators.has(r)){let o=n._arrayMethodCache.get(e);if(o||(o=new Map,n._arrayMethodCache.set(e,o)),!o.has(r)){const e=i.bind(s),a=t.join("."),c=function(...t){const r=e(...t);return queueMicrotask((()=>{n._bindings.forEach((e=>{const t=n.getBindingType(e);for(const r of e.dependencies)if(n.dependencyMatches(a,r,t)){n.scheduleBindingUpdate(e);break}}))})),r};o.set(r,c)}return o.get(r)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy&&!n.shouldUnwrapValue(i))return n.makeReactive(i,[...t,r]);if(Array.isArray(e)&&"function"==typeof i){let t=n._arrayMethodCache.get(e);return t||(t=new Map,n._arrayMethodCache.set(e,t)),t.has(r)||t.set(r,i.bind(e)),t.get(r)}return i},set(e,r,s,i){if("__isReactiveProxy"===r)return!0;let o=s;null===s||"object"!=typeof s||s.__isReactiveProxy||n.shouldUnwrapValue(s)||(o=n.makeReactive(s,[...t,r]));const a=e[r],c=Reflect.set(e,r,o,i);if(a===o)return c;const l=[...t,r].join(".");if(n._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&n._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(r))){const e=t.join(".");if(n._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),r=t.split(".")[0];PPHP._shared.has(r)&&n._dirtyDeps.add(`${t}.*`)}o&&"object"==typeof o&&Object.keys(o).forEach((t=>{if(n._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const r=e.substring(4),s=r.split(".")[0];PPHP._shared.has(s)&&n._dirtyDeps.add(`${r}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(n._dirtyDeps.add(`${e}.*.${String(r)}`),e.startsWith("app.")){const t=e.substring(4),s=t.split(".")[0];PPHP._shared.has(s)&&n._dirtyDeps.add(`${t}.*.${String(r)}`)}}return n._bindings.forEach((e=>{const t=n.getBindingType(e);for(const r of e.dependencies){if(n.dependencyMatches(l,r,t)){n.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const s=l.substring(4),i=s.split(".")[0];if(PPHP._shared.has(i)&&n.dependencyMatches(s,r,t)){n.scheduleBindingUpdate(e);break}}}})),n._hydrated&&n.scheduleFlush(),c}});return this._proxyCache.set(e,s),s}shouldUnwrapValue(e){return e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof URLSearchParams||e instanceof URL||e instanceof Promise||e instanceof ArrayBuffer||e instanceof DataView||"object"==typeof e&&null!==e&&e.constructor!==Object&&e.constructor!==Array}getBindingType(e){if(e.__isEffect)return"effect";if(e.__isLoop)return"loop";for(const t of e.dependencies)if(t.includes("*")||t.match(/\.\d+\./)||t.endsWith(".*"))return"loop";for(const t of e.dependencies)try{const e=this.getNested(this.props,t);if(Array.isArray(e))return"loop"}catch{}return"binding"}makeAttrTemplateUpdater(e,t,r,n){let s=this._templateStore.get(e);s||(s=new Map,this._templateStore.set(e,s)),s.has(t)||s.set(t,e.getAttribute(t)||"");const i=n??s.get(t),o=this.detectElementHierarchy(e);return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractScopedDependencies(t,o).forEach((e=>r.add(e)))})),()=>{try{const r=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,o),r=this._createScopedPropsContext(o);return this.formatValue(e(r))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==r&&e.setAttribute(t,r)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}formatValue(e){if(e instanceof Date)return e.toISOString();if("function"==typeof e){if(e.__isReactiveProxy)try{return this.formatValue(e())}catch{}return""}if(e&&"object"==typeof e){if(e.__isReactiveProxy&&"value"in e)try{return this.formatValue(e.value)}catch{return String(e)}if(e.__isReactiveProxy)try{const t={};for(const r in e)if("__isReactiveProxy"!==r&&"__pphp_key"!==r)try{t[r]=e[r]}catch{}return Object.keys(t).length?JSON.stringify(t,null,2):""}catch{return String(e)}try{return JSON.stringify(e,((e,t)=>{if("__isReactiveProxy"!==e&&"__pphp_key"!==e)return t&&"object"==typeof t&&t.__isReactiveProxy?"function"==typeof t&&"value"in t?t.value:"[Reactive Object]":t}),2)}catch{return String(e)}}return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e&&null!==e?(()=>{try{return JSON.stringify(e)}catch{return String(e)}})():String(e))).join(", "):e?.toString()??""}registerBinding(e,t,r="text",n){if(this._assignmentRe.test(t))return;const s=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,s),o=this.makeScopedEvaluator(t,s);if("value"===n||"checked"===n){const t=()=>{try{const t=this._createScopedPropsContext(s),r=o(t),i=this.formatValue(r);let a=!1;if("value"===n){const t=e;"value"in e&&t.value!==i?(t.value=i,a=!0):"value"in e||(e.setAttribute("value",i),a=!0)}else{const t=e,r="true"===i;"checked"in e&&t.checked!==r?(t.checked=r,a=!0):"checked"in e||(e.setAttribute("checked",i),a=!0)}if(!a||!this._hydrated||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const c={};this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);c[t]=t}})),c.value="input",c.checked="change";const l=c[n]||n,h="click"===l?new MouseEvent(l,{bubbles:!0,cancelable:!0}):new Event(l,{bubbles:!0});e.dispatchEvent(h)}catch(e){console.error(`Error evaluating attribute "${n}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(n){const r=n.toLowerCase();if(this._boolAttrs.has(r)){e.removeAttribute(r);const a=()=>{try{const t=this._createScopedPropsContext(s),i=!!o(t);e[n]!==i&&(e[n]=i),i?e.setAttribute(r,""):e.removeAttribute(r)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:a})}const a=e.getAttribute(n)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(a)){const t=this.makeAttrTemplateUpdater(e,n,i,a);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(s),r=o(t),i=this.formatValue(r);n in e&&(e[n]=i),e.setAttribute(n,i)}catch(e){console.error(`Error evaluating attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:c})}const a={text(e,t){e.textContent!==t&&(e.textContent=t)},value(e,t){e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked(e,t){e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr(e,t){e.setAttribute("attr",t)}};this._bindings.push({dependencies:i,update:()=>{try{const t=this._createScopedPropsContext(s),n=o(t),i=this.formatValue(n);a[r](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),r=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let n;try{n=new Function("ctx",r)}catch(t){const r=JSON.stringify(e);n=new Function("ctx",`try { return ${r}; } catch { return ""; }`)}return e=>{try{const t=n(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const r=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(r)?`${r}; return "";`:`return (${r});`}\n }\n } catch (error) {\n return "";\n }\n `;let s;try{s=new Function("ctx",n)}catch(t){console.error("Expression compilation error:",t.message,"Expression:",r);const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const r=this._createScopedPropsContext(t,e),n=s(r);return null==n?"":n}catch(e){return e instanceof Error?console.error("Scoped evaluation error:",e.message,"Expression:",r):console.error("Scoped evaluation error:",e,"Expression:",r),""}}}_createScopedPropsContext(e,t={}){const r=e.join("."),n=this.getNested(this.props,r)||{},s=this,i=(e,t)=>{if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch(r){return console.error(`Failed to unwrap reactive proxy function for ${t}:`,r),e}if(e&&"object"==typeof e&&e.__isReactiveProxy){const n=r?`${r}.${t}`:t;try{const r=n.split(".");let i=s._rawProps;for(const e of r){if(!i||"object"!=typeof i||!(e in i)){i=void 0;break}i=i[e]}if(void 0!==i){if(null===i||"object"!=typeof i)return i;if(Array.isArray(i))return e;try{const t=Object.keys(i);if(t.length>0){const r=t[0];return void 0!==e[r]?e:i}}catch(e){console.warn(`Error testing reactive proxy for ${t}:`,e)}return e}}catch(e){console.warn(`Clean path traversal failed for ${t}:`,e)}if(e&&"object"==typeof e&&"value"in e)return e.value;if("function"==typeof e)try{return e()}catch(e){console.warn(`Failed to call malformed proxy for ${t}:`,e)}return e}return e};return new Proxy(t,{get(t,o,a){if("string"!=typeof o)return Reflect.get(t,o,a);if(o in t){const e=Reflect.get(t,o,a);return i(e,o)}if(PPHP._shared.has(o)){const e=PPHP._shared.get(o);if(e)try{return e.getter()}catch(e){console.warn(`Failed to get shared state for ${o}:`,e)}}const c=s.getScopedFunction(o,e);if(c)return c;const l=r?`${r}.${o}`:o;if(s.hasNested(s.props,l)){const e=s.getNested(s.props,l);return i(e,o)}if(n&&o in n){const e=n[o];return i(e,o)}for(let t=e.length-1;t>=0;t--){const r=e.slice(0,t).join("."),n=s.getScopedFunction(o,e.slice(0,t));if(n)return n;const a=r?s.getNested(s.props,r):s.props;if(a&&o in a){const e=a[o];return i(e,o)}}if(PPHP._shared.has(o)){const e=PPHP._shared.get(o);if(e)try{return e.getter()}catch(e){console.warn(`Failed to get shared state for ${o}:`,e)}}return o in globalThis?globalThis[o]:void 0},set(t,n,i,o){if("string"!=typeof n)return Reflect.set(t,n,i,o);if(n in t)return Reflect.set(t,n,i,o);for(let t=e.length;t>=0;t--){const r=e.slice(0,t).join("."),o=r?`${r}.${n}`:n;if(s.hasNested(s.props,o))return s.setNested(s.props,o,i),s._dirtyDeps.add(o),s.scheduleFlush(),!0}const a=r?`${r}.${n}`:n;return s.setNested(s.props,a,i),s._dirtyDeps.add(a),s.scheduleFlush(),!0},has:(t,i)=>"string"==typeof i&&(i in t||!!s.getScopedFunction(i,e)||s.hasNested(s.props,r?`${r}.${i}`:i)||n&&i in n||PPHP._shared.has(i)||i in globalThis||e.some(((t,r)=>{const n=e.slice(0,r).join("."),o=n?s.getNested(s.props,n):s.props;return o&&i in o}))),ownKeys(t){const i=new Set;Object.keys(t).forEach((e=>i.add(e))),n&&"object"==typeof n&&Object.keys(n).forEach((e=>i.add(e)));const o=r?s.getNested(s.props,r):s.props;o&&"object"==typeof o&&Object.keys(o).forEach((e=>i.add(e)));for(let t=e.length-1;t>=0;t--){const r=e.slice(0,t).join("."),n=r?s.getNested(s.props,r):s.props;n&&"object"==typeof n&&Object.keys(n).forEach((e=>i.add(e)))}return PPHP._shared.forEach(((e,t)=>i.add(t))),Array.from(i)},getOwnPropertyDescriptor(e,t){return"string"!=typeof t?Reflect.getOwnPropertyDescriptor(e,t):this.has(e,t)?{enumerable:!0,configurable:!0,writable:!0}:void 0}})}extractScopedDependencies(e,t){const r=this.extractDependencies(e),n=new Set,s=t.join(".");for(const i of r){if(this._reservedWords.has(i.split(".")[0]))continue;const r=i.split(".")[0];if(new RegExp(`\\b${r}\\s*\\(`).test(e))continue;if(this._sharedStateMap.has(r)){n.add(`__shared.${i}`);continue}const o=s+"."+i;if(this._stateHierarchy.has(o)){n.add(o);continue}if(this.hasNested(this.props,o)){n.add(o);continue}let a=!1;for(let e=t.length-1;e>=0&&!a;e--){const r=t.slice(0,e).join("."),s=r?r+"."+i:i;this._stateHierarchy.has(s)?(n.add(s),a=!0):this.hasNested(this.props,s)&&(n.add(s),a=!0)}if(!a){const e=s+"."+i;n.add(e)}}return n}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const r=this.detectElementHierarchy(e),n=[];let s=e;for(;s;){if(s.hasAttribute("pp-if"))n.push({el:s,expr:s.getAttribute("pp-if")});else if(s.hasAttribute("pp-elseif"))n.push({el:s,expr:s.getAttribute("pp-elseif")});else{if(!s.hasAttribute("pp-else"))break;n.push({el:s,expr:null})}t.add(s),s=s.nextElementSibling}n.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,r);const n=this.makeScopedEvaluator(t,r);e.evaluate=()=>{const e=this._createScopedPropsContext(r);return!!n(e)}}}));const i=new Set;n.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:r,evaluate:s}of n)!e&&null!==r&&s()?(t.removeAttribute("hidden"),e=!0):e||null!==r?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})}))}async manageAttributeBindings(e=document.body){this.qsa(e,"*").forEach((e=>{const t=new Map;Array.from(e.attributes).forEach((e=>{if(e.name.startsWith("pp-bind"))return;const r=this.decodeEntities(e.value);PPHP._mustacheTest.test(r)&&t.set(e.name.toLowerCase(),r)})),["pp-bind","pp-bind-expr"].forEach((t=>{const r=e.getAttribute(t);r&&this.registerBinding(e,r,"text")})),Array.from(e.attributes).forEach((t=>{const r=t.name.toLowerCase(),n=t.value.trim();this._boolAttrs.has(r)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(n)&&(e.removeAttribute(t.name),this.registerBinding(e,n,"text",r))})),Array.from(e.attributes).forEach((r=>{if(!r.name.startsWith("pp-bind-"))return;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(r.name))return;const n=r.name.replace(/^pp-bind-/,"").toLowerCase(),s=this.decodeEntities(r.value).replace(/^{{\s*|\s*}}$/g,""),i="value"===n?"value":"checked"===n?"checked":"text";if(t.has(n)){const o=t.get(n).replace(PPHP._mustachePattern,"").trim(),a=o.length>0?`\`${o} \${${s}}\``:s;e.setAttribute(r.name,a);try{const t=this._createScopedPropsContext(this.detectElementHierarchy(e)),r=this.formatValue(this.makeScopedEvaluator(a,this.detectElementHierarchy(e))(t));e.setAttribute(n,r)}catch{}return this.registerBinding(e,a,i,n),void t.delete(n)}this.registerBinding(e,s,i,n)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const r=this.detectElementHierarchy(e),n=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),s=new Set;n.forEach((e=>this.extractScopedDependencies(e,r).forEach((e=>s.add(e)))));const i=new Set;this._bindings.push({dependencies:s,update:()=>{try{const t={},s=this._createScopedPropsContext(r);n.forEach((e=>Object.assign(t,this.makeScopedEvaluator(e,r)(s)??{}))),i.forEach((r=>{r in t||e.hasAttribute(r)||(e.removeAttribute(r),i.delete(r))})),Object.entries(t).forEach((([t,r])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==r||!1===r)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const n="object"==typeof r?JSON.stringify(r):String(r);e.getAttribute(t)!==n&&e.setAttribute(t,n),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})})),t.forEach(((t,r)=>{this.registerBinding(e,t,"text",r)}))}))}callInlineModule(e,...t){const r=this._currentProcessingHierarchy||["app"],n=this.getScopedFunction(e,r);if(!n)throw new Error(`PPHP: no inline module named "${e}" in scope ${r.join(".")}`);return n(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;if(e.startsWith("set")){const t=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(t)){const e=PPHP._shared.get(t);return e?.setter||null}}for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return s.get(e)}if(e.startsWith("set")){const r=e.charAt(3).toLowerCase()+e.slice(4);for(let e=t.length;e>=0;e--){const n=t.slice(0,e).join("."),s=n?`${n}.${r}`:r;if(this.hasNested(this.props,s))return e=>{this.setNested(this.props,s,e),this._dirtyDeps.add(s),this.scheduleFlush()}}}return null}async processInlineModuleScripts(e=document.body){this._inlineDepth++;try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>!this._processedPhpScripts.has(e)));if(0===t.length)return;const r=t.map((e=>{const t=this.detectComponentHierarchy(e);return{script:e,hierarchy:t,depth:t.length}})).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of r){this._currentProcessingHierarchy=t,this._currentEffectContext=t.join(".");const r=t.join(".");let n=(e.textContent||"").trim();n=this.decodeEntities(n),n=this.stripComments(n),n=this.transformStateDeclarations(n),n=this.transformEffectDependencies(n),n=this.injectScopedVariables(n,t);const s=this.extractSetters(n);if(s.length){n+="\n\n";for(const e of s)n+=`pphp._registerScopedFunction('${r}', '${e}', ${e});\n`}n=this.stateDeclarations(n);const i=[];for(const[,e]of[...n.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...n.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${r}', '${e}', ${e});`);i.length&&(n+="\n\n"+i.join("\n"));const o=new Blob([n],{type:"application/javascript"}),a=URL.createObjectURL(o);try{const e=await import(a);this._inlineModuleFns.has(r)||this._inlineModuleFns.set(r,new Map);const t=this._inlineModuleFns.get(r);for(const[r,n]of Object.entries(e))"function"!=typeof n||t.has(r)||t.set(r,n)}catch(e){console.error("❌ Inline module import failed:",e),console.error("📄 Generated source:",n)}finally{URL.revokeObjectURL(a),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}this._currentProcessingHierarchy=null,this._currentEffectContext=null}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}transformEffectDependencies(e){let t=e,r=0;for(;;){const e=t.indexOf("pphp.effect(",r);if(-1===e)break;let n=1,s=e+12,i=!1,o="",a=-1;for(;s<t.length&&n>0;){const e=t[s],r=s>0?t[s-1]:"";if(i||'"'!==e&&"'"!==e&&"`"!==e){if(i&&e===o&&"\\"!==r)i=!1,o="";else if(!i)if("("===e||"{"===e||"["===e)n++;else if(")"===e||"}"===e||"]"===e){if(n--,0===n&&")"===e)break}else","===e&&1===n&&-1===a&&(a=s)}else i=!0,o=e;s++}if(0===n&&-1!==a){const n=s,i=t.substring(a+1,n).trim().match(/^\[\s*([^\]]*?)\s*\]$/);if(i){const s=i[1].trim();if(s){const e=`[${this.smartSplitDependencies(s).map((e=>{const t=e.trim();return/^['"`]/.test(t)?e:/^[a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test(t)?`'${t}'`:e})).join(", ")}]`,i=t.substring(0,a+1),o=t.substring(n);t=i+" "+e+o,r=i.length+e.length}else r=e+12}else r=e+12}else r=e+12}return t}smartSplitDependencies(e){if(!e.trim())return[];const t=[];let r="",n=0,s=!1,i="";for(let o=0;o<e.length;o++){const a=e[o],c=o>0?e[o-1]:"";if(s||'"'!==a&&"'"!==a&&"`"!==a?s&&a===i&&"\\"!==c&&(s=!1,i=""):(s=!0,i=a),!s)if("([{".includes(a))n++;else if(")]}".includes(a))n--;else if(","===a&&0===n){r.trim()&&t.push(r.trim()),r="";continue}r+=a}return r.trim()&&t.push(r.trim()),t}stateDeclarations(e){const t="pphp.",r=["state","share"];let n=e;for(const e of r){let r=0;for(;-1!==(r=n.indexOf(`${t}${e}(`,r));){const t=r+5+e.length+1,s=n.slice(t).match(/^(['"])([^'" ]+)\1\s*,/);if(s){const[e]=s;r=t+e.length}else{const e=n.slice(t),s=e.indexOf(",");if(-1===s)break;{const i=`'${e.slice(0,s).trim()}', `;n=n.slice(0,t)+i+n.slice(t),r=t+i.length+s}}}}return n}injectScopedVariables(e,t){const r=this.extractVariableReferences(e),n=this.extractDeclaredVariables(e),s=this.extractStateVariables(e),i=new Set([...n,...s]),o=[],a=new Set;for(const e of r)if(!a.has(e)&&!i.has(e)&&this.hasInScopedContext(e,t)){const r=this.findScopedKeyForVariable(e,t);o.push(`\nconst ${e} = (() => {\n const fn = () => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n };\n \n fn.__isReactiveProxy = true;\n fn.__pphp_key = '${r}';\n \n Object.defineProperty(fn, 'value', {\n get() {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n },\n configurable: true\n });\n \n fn.valueOf = function() { return this.value; };\n fn.toString = function() { return String(this.value); };\n \n return fn;\n})();`),a.add(e);const n=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(n,t)&&!i.has(n)&&(o.push(`\nconst ${n} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${n}(...args);\n};`),a.add(n))}return o.length>0?o.join("\n")+"\n\n"+e:e}extractStateVariables(e){const t=new Set,r=/\b(?:const|let|var)\s+\[\s*([^,\]]+)(?:\s*,\s*([^,\]]+))?\s*\]\s*=\s*pphp\.state/g;let n;for(;null!==(n=r.exec(e));){const e=n[1]?.trim(),r=n[2]?.trim();e&&t.add(e),r&&t.add(r)}const s=/pphp\.state\s*\(\s*['"]([^'"]+)['"]/g;for(;null!==(n=s.exec(e));){const e=n[1];if(e){t.add(e);const r=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;t.add(r)}}return t}extractDeclaredVariables(e){const t=new Set;let r=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const n=[/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+\[\s*([^\]]+?)\s*\]/g,/\b(?:const|let|var)\s+\{\s*([^}]+?)\s*\}/g,/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\bexport\s+function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g,/\bexport\s+(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g];for(const e of n){let n;for(;null!==(n=e.exec(r));){const r=n[1]||n[2];if(e.source.includes("\\[")&&!e.source.includes("\\{")){const e=r.split(",").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith("...")?e.substring(3).trim():e));for(const r of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(r)&&t.add(r)}else if(e.source.includes("\\{")&&!e.source.includes("\\[")){const e=r.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{const t=e.indexOf(":");return-1!==t?e.substring(t+1).trim():e.startsWith("...")?e.substring(3).trim():e}));for(const r of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(r)&&t.add(r)}else r&&t.add(r)}}return t}findScopedKeyForVariable(e,t){const r=t.join("."),n=this.getNested(this.props,r)||{};if(n&&e in n)return`${r}.${e}`;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?this.getNested(this.props,n):this.props;if(s&&"object"==typeof s&&e in s)return n?`${n}.${e}`:e}return`${r}.${e}`}extractVariableReferences(e){const t=new Set;let r=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ");const n=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let s;for(;null!==(s=n.exec(r));){const e=s[1],n=s.index;if(this._reservedWords.has(e))continue;const i=r.substring(n+e.length,n+e.length+20);if(/^\s*\(/.test(i))continue;const o=r.substring(Math.max(0,n-50),n);/\b(?:const|let|var|function|class|export)\s+$/.test(o)||(n>0&&"."===r[n-1]||/^\s*:/.test(i)||this.isActualFunctionParameter(r,n,e)||this.isInDestructuringDeclaration(r,n,e)||this.shouldSkipVariableInjection(e,r,n)||t.add(e))}return t}shouldSkipVariableInjection(e,t,r){if(this._reservedWords.has(e))return!0;if(new Set(["window","document","console","navigator","location","history","localStorage","sessionStorage","setTimeout","setInterval","clearTimeout","clearInterval","fetch","XMLHttpRequest","Date","Math","JSON","Object","Array","String","Number","Boolean","RegExp","Error","Promise","Map","Set","WeakMap","WeakSet","Symbol","BigInt","Proxy","Reflect","pphp","globalThis","self","top","parent"]).has(e))return!0;if(e.length<=2&&/^[a-z_$][\w$]*$/.test(e))return!0;if(e.startsWith("_"))return!0;const n=t.substring(r+e.length,r+e.length+20);return r>0&&"."===t[r-1]||(!!/^\s*:/.test(n)||!!this.isInDestructuringPattern(t,r))}isInDestructuringPattern(e,t){let r=Math.max(0,t-50),n=e.substring(r,t+20);return[/(?:const|let|var)\s*\{[^}]*$/,/(?:const|let|var)\s*\[[^\]]*$/].some((e=>e.test(n)))}isActualFunctionParameter(e,t,r){let n=-1,s=-1,i=0;for(let r=t-1;r>=0;r--){const t=e[r];if(")"===t)i++;else if("("===t){if(0===i){n=r;break}i--}}if(-1===n)return!1;i=0;for(let n=t+r.length;n<e.length;n++){const t=e[n];if("("===t)i++;else if(")"===t){if(0===i){s=n;break}i--}}if(-1===s)return!1;const o=e.substring(Math.max(0,n-20),n).trim(),a=e.substring(s+1,Math.min(e.length,s+10)).trim(),c=/\bfunction(?:\s+[a-zA-Z_$]\w*)?\s*$/.test(o),l=a.startsWith("=>");if(c||l){const n=e.substring(t+r.length,s);return!n.includes("=>")&&!n.includes("{")}return!1}isInDestructuringDeclaration(e,t,r){const n=e.substring(Math.max(0,t-100),t);if(n.match(/\b(?:const|let|var)\s+\[\s*[^\]]*$/)){const n=e.substring(t+r.length,Math.min(e.length,t+r.length+100));if(/[^\]]*\]\s*=/.test(n))return!0}if(n.match(/\b(?:const|let|var)\s+\{\s*[^}]*$/)){const n=e.substring(t+r.length,Math.min(e.length,t+r.length+100));if(/[^}]*\}\s*=/.test(n))return!0}return!1}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return!0}const r=t.join("."),n=this.getNested(this.props,r)||{};if(n&&e in n)return!0;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?this.getNested(this.props,n):this.props;if(s&&"object"==typeof s&&e in s)return!0;const i=n?`${n}.${e}`:e;if(this._stateHierarchy.has(i))return!0}return!!PPHP._shared.has(e)}_registerScopedFunction(e,t,r){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...n)=>{const s=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&n.length>0?r(n[0]):r(...n)}finally{this._currentExecutionScope=s}}))}extractSetters(e){const t=[],r=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let n;for(;n=r.exec(e);){const[,e,r,s]=n;"share"===s&&this.markShared(e),this._sharedStateMap.has(e)||t.push(r)}return t}markShared(e){this._sharedStateMap.add(e)}transformStateDeclarations(e){return e=(e=(e=e.replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r,n,s)=>`${t}${r}, ${n}${s}'${r}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r,n)=>`${t}${r}${n}'${r}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r)=>`${t}[${r}] = pphp.state('${r}', `))}stripComments(e){let t="",r=0,n=!1,s=!1;for(;r<e.length;){const i=e[r],o=e[r+1];if(s||"'"!==i&&'"'!==i&&"`"!==i||"\\"===e[r-1])if(n)t+=i,r++;else if(s||"/"!==i||"*"!==o)if(s)"*"===i&&"/"===o?(s=!1,r+=2):r++;else if("/"!==i||"/"!==o)t+=i,r++;else for(;r<e.length&&"\n"!==e[r];)r++;else s=!0,r+=2;else n=!n,t+=i,r++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let r=!1;const n=this.getBindingType(t);for(const s of t.dependencies){for(const t of e)if(this.dependencyMatches(t,s,n)){r=!0;break}if(r)break}if(r)try{t.update()}catch(e){console.error("Binding update error:",e)}})),this._pendingBindings.forEach((e=>{try{e.update()}catch(e){console.error("Pending binding update error:",e)}})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const r=t.__deps||new Set,n=t.__functionDeps||[];if(0===r.size&&0===n.length){try{t()}catch(e){console.error("effect error:",e)}return}const s=[...r].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=n.length>0;if(s||i)try{t()}catch(e){console.error("effect error:",e)}}))}static ARRAY_INTRINSICS=(()=>{const e=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]);return new Set(Object.getOwnPropertyNames(Array.prototype).filter((t=>!e.has(t))))})();static headMatch(e,t){return e===t||e.startsWith(t+".")}dependencyMatches(e,t,r="binding"){const n=e=>{if(e.startsWith("__shared."))return e.slice(9);if(e.startsWith("app.")){const t=e.slice(4),r=t.split(".")[0];if(PPHP._shared.has(r))return t}return e},s=n(e),i=n(t);if(s===i||e===t)return!0;if(e.startsWith("__shared.")&&t.startsWith("__shared.")&&e===t)return!0;if(e.startsWith("__shared.")&&t===e.slice(9))return!0;if(t.startsWith("__shared.")&&e===t.slice(9))return!0;const o=i.split(".");if(o.length>1&&PPHP.ARRAY_INTRINSICS.has(o.at(-1))&&PPHP.headMatch(s,o.slice(0,-1).join(".")))return!0;let a=!1;switch(r){case"effect":a=this.matchEffectDependency(s,i);break;case"loop":PPHP.headMatch(s,i)||PPHP.headMatch(i,s)?a=!0:(i.includes("*")||this.matchesArrayIndexPattern(s,i))&&(a=this.matchLoopDependency(s,i));break;default:PPHP.headMatch(s,i)?a=!0:(i.includes("*")||this.matchesArrayIndexPattern(s,i))&&(a=this.matchBindingDependency(s,i))}return a}matchEffectDependency(e,t){if(e===t)return!0;const r=t.startsWith("__shared."),n=e.startsWith("__shared.");if(r&&n){const r=t.substring(9),n=e.substring(9);if(n.startsWith(r+"."))return!0;if(r.startsWith(n+"."))return!0}if(e.startsWith(t+".")){return!e.substring(t.length+1).includes(".")}return!!t.includes("*")&&this.matchesWildcardPattern(e,t)}matchLoopDependency(e,t){return!(!e.startsWith(t+".")&&!t.startsWith(e+"."))||(!(!this.isArrayPath(t)||!this.isArrayItemPath(e,t))||(t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)))}isArrayPath(e){try{const t=this.getNested(this.props,e);return Array.isArray(t)}catch{return!1}}isArrayItemPath(e,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+($|\\.)`).test(e)}matchBindingDependency(e,t){if(e.startsWith(t+".")){return e.substring(t.length+1).split(".").length<=2}return t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)}matchesWildcardPattern(e,t){const r=e.split("."),n=t.split(".");if(r.length!==n.length)return!1;for(let e=0;e<n.length;e++){const t=n[e],s=r[e];if("*"!==t&&t!==s)return!1}return!0}matchesArrayIndexPattern(e,t){const r=e.split("."),n=t.split(".");if(r.length!==n.length)return!1;for(let e=0;e<n.length;e++){const t=r[e],s=n[e];if(t!==s&&(!/^\d+$/.test(t)||!/^\d+$/.test(s)))return!1}return!0}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}getNested(e,t){const r=t.split(".").reduce(((e,t)=>e?e[t]:void 0),e);return r}setNested(e,t,r){const n=t.split("."),s=n.pop(),i=n.reduce(((e,t)=>e[t]??={}),e);try{const e=t.split("."),n=e.pop();let s=this._rawProps;for(const t of e)s[t]&&"object"==typeof s[t]||(s[t]={}),s=s[t];if(r&&"object"==typeof r&&!Array.isArray(r))try{s[n]=JSON.parse(JSON.stringify(r))}catch(e){s[n]={...r}}else s[n]=r}catch(e){console.warn(`Failed to store raw value for ${t}:`,e)}null!==r&&"object"==typeof r?"function"==typeof r&&r.__isReactiveProxy||r.__isReactiveProxy?i[s]=r:i[s]=this.makeReactive(r,n.concat(s)):i[s]=r}hasNested(e,t){const r=t.split(".");let n=e;for(let e=0;e<r.length;e++){const t=r[e];if(null==n||"object"!=typeof n)return!1;if(!(t in n))return!1;n=n[t]}return!0}share(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.share: key must be a non‑empty string.");if(this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another share key.`);const r=PPHP._shared.get(e);if(r)return[r.getter,r.setter];const n=Array.from(this._stateHierarchy.entries()).filter((([t,r])=>r.originalKey===e));n.length>0&&console.warn(`⚠️ PPHP Share Conflict Warning:\n • Creating shared state "${e}"\n • Found existing local state(s) with same key:\n`+n.map((([e,t])=>` - "${e}" (${t.hierarchy.join(" → ")})`)).join("\n")+`\n • Setter "set${e.charAt(0).toUpperCase()}${e.slice(1)}" will prioritize THIS shared state\n • Consider using different variable names to avoid confusion`),this._sharedStateMap.add(e);const s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=["__shared"];const[i,o]=this.state(e,t);this._currentProcessingHierarchy=s;const a=t=>{const r=i(),n="function"==typeof t?t(r):t;o(n);const s=[e,`__shared.${e}`,`app.${e}`];s.forEach((e=>{this._dirtyDeps.add(e)})),n&&"object"==typeof n&&Object.keys(n).forEach((e=>{s.forEach((t=>{this._dirtyDeps.add(`${t}.${e}`)}))})),this.scheduleFlush()};return PPHP._shared.set(e,{getter:i,setter:a}),[i,a]}getShared(e){let t=!1;const r=function(...r){const s=PPHP._shared.get(e);if(s)return s.getter();const i=[`__shared.${e}`,e,`app.${e}`];for(const e of i)if(n.hasNested(n.props,e)){const t=n.getNested(n.props,e);if(void 0!==t)return t}if(!t){t=!0;const r=(t=1)=>{setTimeout((()=>{const s=PPHP._shared.get(e);if(s){n._dirtyDeps.add(e),n._dirtyDeps.add(`__shared.${e}`);const t=s.getter();t&&"object"==typeof t&&Object.keys(t).forEach((t=>{n._dirtyDeps.add(`${e}.${t}`),n._dirtyDeps.add(`__shared.${e}.${t}`)})),n.scheduleFlush()}else t<10&&r(t+1)}),1===t?10:50)};r()}},n=this;r.set=t=>{let s=PPHP._shared.get(e);if(s)return s.setter(t);const i=r(),o="function"==typeof t?t(i):t;n.hasNested(n.props,"__shared")||n.setNested(n.props,"__shared",{});const a=`__shared.${e}`;n.setNested(n.props,a,o),n._dirtyDeps.add(e),n._dirtyDeps.add(a),n._sharedStateMap.add(e),o&&"object"==typeof o&&n.markNestedPropertiesDirty(e,o),n.scheduleFlush()},Object.defineProperties(r,{__isReactiveProxy:{value:!0,writable:!1,enumerable:!1},__pphp_key:{value:`__shared.${e}`,writable:!1,enumerable:!1},valueOf:{value:()=>r(),enumerable:!1},toString:{value:()=>String(r()),enumerable:!1}});return new Proxy(r,{apply:(e,t,r)=>e.apply(t,r),get(t,r,s){if("set"===r||"__isReactiveProxy"===r||"__pphp_key"===r||"valueOf"===r||"toString"===r)return Reflect.get(t,r,s);if("string"!=typeof r)return Reflect.get(t,r,s);{const s=t();if(s&&"object"==typeof s){let t=s[r];return t&&"object"==typeof t&&!t.__isReactiveProxy&&(t=n.makeReactive(t,["__shared",e,r])),t}}},set(t,r,s){if("set"===r||"__isReactiveProxy"===r||"__pphp_key"===r)return Reflect.set(t,r,s);if("string"==typeof r){const i=t();if(i&&"object"==typeof i)i[r]=s,n._dirtyDeps.add(`${e}.${String(r)}`),n._dirtyDeps.add(`__shared.${e}.${String(r)}`),n.scheduleFlush();else{const e={[r]:s};t.set(e)}return!0}return Reflect.set(t,r,s)},has(e,t){if("set"===t||"__isReactiveProxy"===t)return!0;const r=e();return r&&"object"==typeof r&&t in r}})}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure the build-time injector rewrote your declaration to pphp.state('foo', 0).");if(arguments.length<2&&(t=void 0),this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another state key.`);if(PPHP._shared.has(e)){const r=this._currentProcessingHierarchy||["app"],n=this.generateScopedKey(r,e);console.warn(`⚠️ PPHP State Conflict Warning:\n • Shared state "${e}" already exists\n • Creating local state at "${n}"\n • Setter "set${e.charAt(0).toUpperCase()}${e.slice(1)}" will prioritize SHARED state\n • Consider using different variable names to avoid confusion\n • Current shared value:`,PPHP._shared.get(e)?.getter(),"\n • New local value:",t)}const r=this._currentProcessingHierarchy||["app"],n=this.generateScopedKey(r,e);this._stateHierarchy.set(n,{originalKey:e,hierarchy:[...r],level:r.length}),this.hasNested(this.props,n)||this.setNested(this.props,n,t);const s=()=>this.getNested(this.props,n),i=e=>{const t=s(),r="function"==typeof e?e(t):e;this.setNested(this.props,n,r),this._dirtyDeps.add(n),r&&"object"==typeof r&&this.markNestedPropertiesDirty(n,r),this.scheduleFlush()},o=()=>s();Object.defineProperty(o,"value",{get:()=>s(),set:e=>i(e)}),Object.defineProperties(o,{valueOf:{value:()=>s()},toString:{value:()=>String(s())},__isReactiveProxy:{value:!0,writable:!1}}),Object.defineProperty(o,"__pphp_key",{value:n,writable:!1,enumerable:!1,configurable:!1});const a=s();if(null===a||"object"!=typeof a)return[o,i];const c=this;return[new Proxy(o,{apply:(e,t,r)=>Reflect.apply(e,t,r),get(e,t,r){if("value"===t)return s();if("__pphp_key"===t)return n;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,r);if("string"==typeof t){const r=s();if(r&&"object"==typeof r){const s=Object.prototype.hasOwnProperty.call(r,t),i=t in e&&void 0!==e[t];if(s||!i){let e=r[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...n.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,r);const i=s();return i&&"object"==typeof i?i[t]:void 0},set(e,t,r){if("value"===t)return i(r),!0;if("__isReactiveProxy"===t)return!0;const o=s();return o&&"object"==typeof o&&(o[t]=r,c._dirtyDeps.add(`${n}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in o)return!0;const r=s();return r&&"object"==typeof r&&t in r}}),i]}markNestedPropertiesDirty(e,t,r=new WeakSet){t&&"object"==typeof t&&!r.has(t)&&(r.add(t),Object.keys(t).forEach((n=>{const s=`${e}.${n}`;this._dirtyDeps.add(s),this._sharedStateMap.has(e.split(".")[0])&&this._dirtyDeps.add(`__shared.${s}`);const i=t[n];i&&"object"==typeof i&&!r.has(i)&&this.markNestedPropertiesDirty(s,i,r)})))}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return r=>{const n=e.get(r);if(void 0!==n)return n;const s=r in globalThis||t.some((e=>r in e));return e.set(r,s),s}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let r=e.replace(/\?\./g,".");const n=new Set,s=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=s.exec(r);)(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(r);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const o=e=>{let t="",r=0;for(;r<e.length;)if("`"===e[r])for(r++;r<e.length;)if("\\"===e[r])r+=2;else if("$"===e[r]&&"{"===e[r+1]){r+=2;let n=1,s=r;for(;r<e.length&&n;)"{"===e[r]?n++:"}"===e[r]&&n--,r++;t+=o(e.slice(s,r-1))+" "}else{if("`"===e[r]){r++;break}r++}else t+=e[r++];return t};r=o(r),r=r.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),r=r.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const a=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of r.match(c)??[]){const[r,...s]=t.split(".");if(!n.has(r)&&(0!==s.length||!PPHP._isBuiltIn(r)||!new RegExp(`\\.${r}\\b`).test(e))){if(0===s.length&&new RegExp(`\\b${t}\\s*\\(`).test(e)){if(r in globalThis&&"function"==typeof globalThis[r])continue;if(this.isInlineModuleFunction(r))continue;if(this.looksLikeFunctionName(r))continue}a.add(t)}}return a}isInlineModuleFunction(e){for(const[t,r]of this._inlineModuleFns.entries())if(r.has(e))return!0;if(this._currentProcessingHierarchy){const t=this._currentProcessingHierarchy.join("."),r=this._inlineModuleFns.get(t);if(r&&r.has(e))return!0}return!1}looksLikeFunctionName(e){return[/^[a-z][a-zA-Z0-9]*$/,/^[A-Z][a-zA-Z0-9]*$/,/^[a-z_][a-zA-Z0-9_]*$/,/^handle[A-Z]/,/^on[A-Z]/,/^get[A-Z]/,/^set[A-Z]/,/^is[A-Z]/,/^has[A-Z]/,/^can[A-Z]/,/^should[A-Z]/,/^will[A-Z]/].some((t=>t.test(e)))}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,r=PPHP._mustacheTest,n=this.props,s=new Set;this.qsa(e,"*").forEach((e=>{const n=this.detectElementHierarchy(e);for(const{name:i,value:o}of Array.from(e.attributes))if(o){if(r.test(o))for(const e of o.matchAll(t))this.extractScopedDependencies(e[1],n).forEach((e=>s.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(o,n).forEach((e=>s.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>r.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const r=e.parentElement;if(!r)continue;const n=this.detectElementHierarchy(r);for(const r of e.nodeValue.matchAll(t))this.extractScopedDependencies(r[1],n).forEach((e=>s.add(e)))}const o=Array.from(s).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of o){const t=e.split("."),r=t[t.length-1];if(this._sharedStateMap.has(r)&&!e.startsWith("__shared."))continue;let s=n;for(let e=0;e<t.length;e++){const r=t[e],n=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(r in s)||!n&&(null==s[r]||"object"!=typeof s[r])){const e=this._stateHierarchy.has(i);n&&e||(s[r]=n?void 0:{})}s=s[r]}}}async dispatchEvent(e,t,r={}){try{if(!e||"string"!=typeof e)return!1;const n=e.split(".")[0];if(e.includes(".")&&PPHP._shared.has(n)){const r=PPHP._shared.get(n);if(r){const s=r.getter();let i=JSON.parse(JSON.stringify(s||{}));const o=e.substring(n.length+1).split(".");let a=i;for(let e=0;e<o.length-1;e++)null==a[o[e]]&&(a[o[e]]={}),a=a[o[e]];const c=o[o.length-1],l=a[c],h="function"==typeof t?t(l):t;a[c]=h,r.setter(i);const d=`__shared.${e}`,p=`__shared.${n}`;return this._dirtyDeps.add(d),this._dirtyDeps.add(e),this._dirtyDeps.add(p),this._dirtyDeps.add(n),this._hydrated&&this.scheduleFlush(),d}}if(PPHP._shared.has(e)){const r=PPHP._shared.get(e);if(r){r.setter(t);const n=`__shared.${e}`;return this._dirtyDeps.add(n),this._dirtyDeps.add(e),this._hydrated&&this.scheduleFlush(),n}}let s=null;this._currentEffectContext&&(s=this._currentEffectContext.split(".")),!s&&r.from instanceof Element&&(s=this.detectElementHierarchy(r.from)),!s&&this._currentEventTarget instanceof Element&&(s=this.detectElementHierarchy(this._currentEventTarget)),s||(s=["app"]);const i=r.scope??"current";let o=s;Array.isArray(i)?o=i.length?i:["app"]:"parent"===i?o=s.slice(0,-1).length?s.slice(0,-1):["app"]:"root"===i||"app"===i?o=["app"]:"current"!==i&&(o=i.split("."));const a=this.resolveStatePath(e,o),c=a?.startsWith("app.")?a:e.startsWith("app.")?e:`${o.join(".")}.${e}`,l=this.hasNested(this.props,c)?this.getNested(this.props,c):void 0,h="function"==typeof t?t(l):t;if(this.setNested(this.props,c,h),this._dirtyDeps.add(c),this._dirtyDeps.add(`${c}.*`),c.startsWith("app.")){const e=c.slice(4),t=e.split(".")[0];PPHP._shared?.has(t)&&(this._dirtyDeps.add(e),this._dirtyDeps.add(`${e}.*`))}return this._hydrated&&this.scheduleFlush(),c}catch(e){return console.error("PPHP.dispatchEvent error:",e),!1}}determineCurrentComponentHierarchy(){const e=this.getEventSourceHierarchy();if(e.length>0)return e;if(this._currentEffectContext)return this._currentEffectContext.split(".");if(this._currentProcessingHierarchy)return[...this._currentProcessingHierarchy];if(this._currentExecutionScope){return this._currentExecutionScope.split(".")}const t=this.getCurrentScriptHierarchy();if(t.length>0)return t;const r=this.getActiveElementHierarchy();return r.length>0?r:["app"]}trackEventContext(e){e.currentTarget instanceof Element&&(this._currentEventTarget=e.currentTarget,this._eventContextStack.push(e.currentTarget),e.currentTarget.setAttribute("data-pphp-recent",Date.now().toString()),setTimeout((()=>{e.currentTarget?.removeAttribute?.("data-pphp-recent")}),1e3),setTimeout((()=>{this._eventContextStack.pop(),0===this._eventContextStack.length?this._currentEventTarget=null:this._currentEventTarget=this._eventContextStack[this._eventContextStack.length-1]}),0))}getEventSourceHierarchy(){try{let e=null;if(this._currentEventTarget&&(e=this._currentEventTarget),!e){const t=document.currentScript;t&&(e=t.closest("[pp-component]"))}if(!e){const t=document.activeElement;if(t instanceof Element){const r=t.closest("[pp-component]");r&&(e=r)}}if(!e){const t=document.querySelectorAll("[data-pphp-recent]");if(t.length>0){const r=Array.from(t).pop();r&&(e=r.closest("[pp-component]"))}}if(e)return this.buildComponentHierarchy(e)}catch(e){console.warn("Error in getEventSourceHierarchy:",e)}return[]}getCurrentScriptHierarchy(){try{const e=document.currentScript;if(e){const t=e.closest("[pp-component]");if(t)return this.buildComponentHierarchy(t)}}catch(e){}return[]}getActiveElementHierarchy(){try{const e=document.activeElement;if(e&&e!==document.body){const t=e.closest("[pp-component]");if(t)return this.buildComponentHierarchy(t)}}catch(e){}return[]}buildComponentHierarchy(e){const t=[];let r=e;for(;r;){const e=r.getAttribute("pp-component");e&&t.unshift(e),r=r.parentElement}return["app",...t]}resolveStatePath(e,t){if(PPHP._shared.has(e))return`__shared.${e}`;if(e.includes(".")&&this.hasNested(this.props,e))return e;const r=e.split(".")[0];if(PPHP._shared.has(r)){const t=`__shared.${e}`;if(this.hasNested(this.props,t))return t}for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r+1).join(".")+"."+e;if(this.hasNested(this.props,n))return n}for(const[t,r]of this._stateHierarchy.entries())if(r.originalKey===e||t.endsWith("."+e))return t;return t.length>1?t.join(".")+"."+e:e}getCurrentComponent(e){let t=null;if(e){if(t=document.querySelector(e),!t)return console.warn(`PPHP: Element with selector "${e}" not found`),null}else{if(this._currentEffectContext){const e=this._currentEffectContext.split(".");return e[e.length-1]}if(this._currentProcessingHierarchy&&this._currentProcessingHierarchy.length>0)return this._currentProcessingHierarchy[this._currentProcessingHierarchy.length-1];if(this._currentExecutionScope){const e=this._currentExecutionScope.split(".");return e[e.length-1]}const e=document.currentScript;if(e&&(t=e),!t){const e=this.determineCurrentComponentHierarchy();if(e.length>1)return e[e.length-1]}}if(t)return this.findComponentFromElement(t);const r=this.getFallbackComponent();return r||null}findComponentFromElement(e){const t=e.getAttribute("pp-component");if(t)return t;let r=e.parentElement;for(;r&&r!==document.documentElement;){const e=r.getAttribute("pp-component");if(e)return e;r=r.parentElement}return console.warn("PPHP: No pp-component attribute found for element or its ancestors",e),null}getFallbackComponent(){if(this._currentEventTarget){const e=this.findComponentFromElement(this._currentEventTarget);if(e)return e}const e=document.querySelector("[data-pphp-recent-interaction]");if(e){const t=this.findComponentFromElement(e);if(t)return t}const t=document.activeElement;if(t instanceof Element){const e=this.findComponentFromElement(t);if(e)return e}return null}getCurrentComponentHierarchy(){return this.determineCurrentComponentHierarchy()}async updateDocumentContent(e){const t=this.saveScrollPositions(),r=(new DOMParser).parseFromString(this.sanitizePassiveHandlers(e),"text/html");this.scrubTemplateValueAttributes(r),this.reconcileHead(r),this.resetProps(),await this.removeAllEventListenersOnNavigation(),this.ensurePageTransitionStyles();const n=async()=>{morphdom(document.body,r.body,{childrenOnly:!0}),await this.initReactiveOn(),this.restoreScrollPositions(t)};"startViewTransition"in document?await document.startViewTransition(n).finished:(await this.fadeOutBody(),await n(),await this.fadeInBody()),document.body.removeAttribute("hidden")}ensurePageTransitionStyles(){if(this._transitionStyleInjected)return;const e=document.createElement("style");e.id="pphp-page-transition-style",e.textContent="\n body.pphp-fade-out { opacity: 0; }\n body.pphp-fade-in { opacity: 1; }\n body.pphp-fade-in,\n body.pphp-fade-out { transition: opacity 0.25s ease; }\n ",document.head.appendChild(e),this._transitionStyleInjected=!0}async fadeOutBody(e=document.body){e.classList.add("pphp-fade-out");const t=e.getAnimations()[0];return t&&t.finished?t.finished.then((()=>{})):new Promise((e=>setTimeout(e,250)))}async fadeInBody(e=document.body){e.classList.remove("pphp-fade-out"),e.classList.add("pphp-fade-in");const t=e.getAnimations()[0];t&&t.finished?await t.finished:await new Promise((e=>setTimeout(e,250))),e.classList.remove("pphp-fade-in")}reconcileHead(e){const t="pp-dynamic-script",r="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove())),document.head.querySelectorAll(`[${t}]`).forEach((e=>e.remove())),Array.from(e.head.children).forEach((e=>{switch(e.tagName){case"SCRIPT":if(e.hasAttribute(t)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),t.textContent=e.textContent,document.head.appendChild(t)}break;case"META":{const t=e;if(t.getAttribute("charset")||"viewport"===t.name)break;const r=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,n=t.cloneNode(!0),s=document.head.querySelector(r);s?document.head.replaceChild(n,s):document.head.insertBefore(n,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const t=e.cloneNode(!0),r=document.head.querySelector("title");r?document.head.replaceChild(t,r):document.head.appendChild(t);break}case"LINK":{const t=e;if("icon"===t.rel){const e=t.cloneNode(!0),r=document.head.querySelector('link[rel="icon"]');r?document.head.replaceChild(e,r):document.head.appendChild(e)}else t.hasAttribute(r)&&document.head.appendChild(t.cloneNode(!0));break}}}))}scrubTemplateValueAttributes(e){e.querySelectorAll('input[value*="{{"], textarea[value*="{{"], select[value*="{{"],[checked*="{{"], [selected*="{{"]').forEach((e=>{e.hasAttribute("value")&&e.removeAttribute("value"),e.hasAttribute("checked")&&e.removeAttribute("checked"),e.hasAttribute("selected")&&e.removeAttribute("selected")}))}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const r=this.getElementKey(t);e[r]&&(t.scrollTop=e[r].scrollTop,t.scrollLeft=e[r].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const r=e,n=t;return r.value!==n.value&&(n.value=r.value),n.checked=r.checked,document.activeElement!==r||(null!=r.selectionStart&&(n.selectionStart=r.selectionStart,n.selectionEnd=r.selectionEnd),!1)},TEXTAREA(e,t){const r=e,n=t;return r.value!==n.value&&(n.value=r.value),document.activeElement!==r||(n.selectionStart=r.selectionStart,n.selectionEnd=r.selectionEnd,!1)},SELECT(e,t){const r=e;return t.selectedIndex=r.selectedIndex,document.activeElement!==r},VIDEO(e,t){const r=e,n=t;return n.currentTime=r.currentTime,r.paused?n.pause():n.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,r=e instanceof Document?e.body:e;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const r=new Function("event",t);e.addEventListener("wheel",r,{passive:!0})}})),this._wheelHandlersStashed=!0);const n=this.PRESERVE_HANDLERS;morphdom(t,r,{getNodeKey(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.hasAttribute("pp-sync-script")?`pp-sync-script:${t.getAttribute("pp-sync-script")}`:t.getAttribute("key")||void 0},onBeforeElUpdated(e,t){const r=e.tagName;if("SCRIPT"===r||e.hasAttribute("data-nomorph"))return!1;const s=n[r];return!s||s(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async attachWireFunctionEvents(e=document.body){this.handleHiddenAttribute(),this.handleAnchorTag();const t=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(",");if(!t)return;const r=this.qsa(e,t);for(const e of r)for(const t of this._eventHandlers){const r=e.getAttribute(t);if(!r)continue;const n=this.decodeEntities(r).trim();if(!n){e.removeAttribute(t);continue}const s=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(n))} }`;e.removeAttribute(t);const i=t.slice(2);e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,s)}this.handlePassiveWheelStashes(e instanceof Document?e:document)}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let r=t.value;for(;r.includes("&");){t.innerHTML=r;const e=t.value;if(e===r)break;r=e}return r};unwrapArrowBody=e=>{if(!e.trim())return"";const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{([\s\S]*)\}\s*$/);if(t){let e=t[1].trim();return e&&!e.endsWith(";")&&(e+=";"),e}const r=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(r){let t=e.substring(r[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let n=e.trim();return n&&!n.endsWith(";")&&(n+=";"),n};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,r,n)=>{const s=`${t}->${r}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(s)}, event);`})),t=t.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,r,n)=>{const s=`${t}::${r}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(s)}, event);`}));const{normalized:r,originalParam:n}=this.normalizeToArrow(t),s=this.renameEventParam(r,n);return this.replaceThisReferences(s)}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const r=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(r)?r:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const r=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(r,((e,t,r)=>{const n=r[t-1],s=r[t+e.length];return n&&/[\w$]/.test(n)||s&&/[\w$]/.test(s)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,r){const n=e.getAttribute("pp-debounce"),s=n?this.parseTime(n):0,i=e.getAttribute("pp-before-request")??"",o=e.getAttribute("pp-after-request")??"",a=PPHP._cancelableEvents,c=async n=>{a.has(t)&&n.cancelable&&n.preventDefault();try{i&&await this.invokeHandler(e,i,n),await this.invokeHandler(e,r,n),o&&!o.startsWith("@close")&&await this.invokeHandler(e,o,n)}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!a.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,d=e=>{if(s>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const r=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),s);PPHP._debounceTimers.set(h,r)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),d(e)}),l):e.addEventListener(t,d,l)}debounce(e,t=300,r=!1){let n;return function(...s){const i=this;n&&clearTimeout(n),n=setTimeout((()=>{n=null,r||e.apply(i,s)}),t),r&&!n&&e.apply(i,s)}}async invokeHandler(e,t,r){const n=this._currentProcessingElement;this._currentProcessingElement=e;try{const n=t.trim();let s=this._handlerCache.get(n);s||(s=this.parseHandler(n),this._handlerCache.set(n,s)),await this.executeHandler(s,e,r,n)}catch(r){this.handleInvokeError(r,t,e)}finally{this._currentProcessingElement=n,this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const r=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(r)return{type:"call",name:r[1],args:r[2],isAsync:this.isAsyncFunction(r[1])};const n=t.match(/^(\w+)$/);return n?{type:"simple",name:n[1],isAsync:this.isAsyncFunction(n[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,r="",n=0;for(let s=0;s<e.length-1;s++){const i=e[s],o=e[s+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===r&&"\\"!==e[s-1])t=!1,r="";else if(!t&&("("===i&&n++,")"===i&&n--,"="===i&&">"===o&&n>=0))return!0}else t=!0,r=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let r=e.substring(t+2).trim();return r.startsWith("{")&&r.endsWith("}")&&(r=r.slice(1,-1).trim()),{type:"arrow",body:r,isAsync:e.includes("async")||this.containsAwait(r)}}findArrowIndex(e){let t=!1,r="";for(let n=0;n<e.length-1;n++){const s=e[n],i=e[n+1];if(t||'"'!==s&&"'"!==s&&"`"!==s){if(t&&s===r&&"\\"!==e[n-1])t=!1;else if(!t&&"="===s&&">"===i)return n}else t=!0,r=s}return-1}async executeArrowHandler(e,t,r){const n=this.parseStatements(e.body);let s=!1;for(const e of n)await this.executeSingleStatement(e,t,r)&&(s=!0);s||await this.executeDynamic(e.body,t,r)}async executeComplexHandler(e,t,r){await this.executeDynamic(e.body,t,r)}parseStatements(e){const t=[];let r="",n=0,s=!1,i="";for(let o=0;o<e.length;o++){const a=e[o];s||'"'!==a&&"'"!==a&&"`"!==a?s&&a===i&&"\\"!==e[o-1]&&(s=!1,i=""):(s=!0,i=a),s||("("!==a&&"{"!==a&&"["!==a||n++,")"!==a&&"}"!==a&&"]"!==a||n--,";"!==a||0!==n)?r+=a:r.trim()&&(t.push(r.trim()),r="")}return r.trim()&&t.push(r.trim()),t}async executeInlineModule(e,t,r,n,s){if(t&&t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t);null!==r&&"object"==typeof r?await this.callInlineModule(e,{...r}):await this.callInlineModule(e,r)}else try{const n=this.detectElementHierarchy(r),s=this._createScopedPropsContext(n),i=this.makeScopedEvaluator(t,n)(s);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:r,event:n})}else await this.handleParsedCallback(r,s,n)}async executeSingleStatement(e,t,r){const n=e.trim();if(!n)return!1;const s=n.match(/^\(\s*\)\s*=>\s*(.+)$/);if(s)return this.executeSingleStatement(s[1],t,r);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(n))return await this.executeDynamic(n,t,r),!0;const i=n.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,s]=i,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(e,o);let c=[];if(""!==s.trim())try{c=JSON5.parse(`[${s}]`)}catch{try{const e=this._createScopedPropsContext(o),t=this.getOrCreateProxy(e),n=/\bevent\b/.test(s)?s.replace(/\bevent\b/g,"_evt"):s;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${n} ]; }`)(r,t,e)}catch(e){c=[]}}if(a){const e=this.getScopedFunction(a,o);if(e)return c.length>0?await e(...c):await this.executeInlineModule(a,s,t,r,n),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,n,r),!0}const o=n.match(/^(\w+)$/);if(o){const e=o[1],n=this.detectElementHierarchy(t),s=this.resolveFunctionName(e,n);if(s){if(this.getScopedFunction(s,n))return await this.handleParsedCallback(t,`${s}()`,r),!0}if(s){const e=globalThis[s];if("function"==typeof e)return e.call(globalThis,r),!0}return await this.handleParsedCallback(t,`${e}()`,r),!0}return await this.executeDynamic(n,t,r),!0}async executeCallHandler(e,t,r,n){const{name:s,args:i}=e,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(s,o);if(a){if(this.getScopedFunction(a,o))return void await this.executeInlineModule(a,i||"",t,r,n);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,r)}await this.handleParsedCallback(t,n,r)}resolveFunctionName(e,t){if(e.startsWith("set")){const t=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(t))return e}if(t)for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,r){const{name:n}=e,s=this.detectElementHierarchy(t),i=this.resolveFunctionName(n,s);if(i){if(this.getScopedFunction(i,s))return void await this.handleParsedCallback(t,`${i}()`,r);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,r)}await this.handleParsedCallback(t,`${n}()`,r)}async executeHandler(e,t,r,n){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,r);break;case"call":await this.executeCallHandler(e,t,r,n);break;case"simple":await this.executeSimpleHandler(e,t,r);break;case"complex":await this.executeComplexHandler(e,t,r);break;default:await this.handleParsedCallback(t,n,r)}}async executeGlobalFunction(e,t,r,n){if(t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t)??{};e.call(globalThis,{...r})}else{const s=this.detectElementHierarchy(r),i=this._createScopedPropsContext(s),o=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(r,n,o,i,e)}else e.call(globalThis,n)}async executeDynamic(e,t,r){const n=this.detectElementHierarchy(t),s=this._createScopedPropsContext(n),i=this.getOrCreateProxy(s),o=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await o.call(t,r,i,s)}finally{this.scheduleFlush()}}static AsyncFunction=Object.getPrototypeOf((async()=>{})).constructor;getOrCreateEvaluator(e){let t=this._evaluatorCache.get(e);return t||(t=this.makeSafeEvaluator(e),this._evaluatorCache.set(e,t)),t}getOrCreateProxy(e){let t=this._handlerProxyCache.get(e);return t||(t=this.createHandlerProxy(e),this._handlerProxyCache.set(e,t)),t}createHandlerProxy(e){const t=this._currentProcessingHierarchy||["app"],r={alert:window.alert.bind(window),confirm:window.confirm.bind(window),prompt:window.prompt.bind(window),console:window.console,setTimeout:window.setTimeout.bind(window),setInterval:window.setInterval.bind(window),clearTimeout:window.clearTimeout.bind(window),clearInterval:window.clearInterval.bind(window),fetch:window.fetch.bind(window)};return new Proxy(e,{get:(e,n,s)=>{if("string"==typeof n){if(r.hasOwnProperty(n))return r[n];const i=this.getScopedFunction(n,t);if(i)return i;if(n in e){const t=Reflect.get(e,n,s),r=globalThis[n];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(n)&&typeof t!=typeof r))return t}if(n in globalThis&&!r.hasOwnProperty(n)){const e=globalThis[n];return"function"==typeof e&&/^[a-z]/.test(n)?e.bind(globalThis):e}}return Reflect.get(e,n,s)},set:(e,t,r,n)=>Reflect.set(e,t,r,n),has:(e,t)=>{if("string"==typeof t){const n=this._currentProcessingHierarchy||["app"];return r.hasOwnProperty(t)||!!this.getScopedFunction(t,n)||t in e||t in globalThis}return t in e||t in globalThis}})}isAsyncFunction(e){const t=this._inlineModuleFns.get(e)||globalThis[e];return t&&("AsyncFunction"===t.constructor.name||t.toString().includes("async "))}containsAwait(e){return/\bawait\s+/.test(e)}handleInvokeError(e,t,r){const n=e instanceof Error?e.message:String(e),s=r.tagName+(r.id?`#${r.id}`:"");console.error(`Handler execution failed on ${s}:\nHandler: "${t}"\nError: ${n}`,e),r.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:r},bubbles:!0}))}async handleParsedCallback(e,t,r){const{funcName:n,data:s}=this.parseCallback(e,t);if(!n)return;const i=Array.isArray(n)?n:[n],o=this.detectElementHierarchy(e);let a;for(const e of i){const t=this.resolveLocalFunction(e,o);if(t){a=t;break}}if(a){const t=e.hasAttribute("pp-after-request"),n="@close"===e.getAttribute("pp-after-request");let o={args:Array.isArray(s.args)?s.args:[],element:e,data:s,event:r};if(t&&!n){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};o={...o,...e}}try{return void await a.call(this,o)}catch(e){return void console.error(`❌ Error executing function ${i[0]}:`,e)}}this.shouldCallServer(i[0],o)?(this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(n)?n[0]:n,s)):console.warn(`⚠️ Function ${i[0]} not found and not calling server`)}shouldCallServer(e,t){return!!!this.resolveLocalFunction(e,t)}resolveLocalFunction(e,t){const r=this.getScopedFunction(e,t);if(r)return r;for(const[,t]of this._inlineModuleFns.entries())if(t.has(e))return t.get(e);return"function"==typeof this[e]?this[e]:"function"==typeof window[e]?window[e]:void 0}async handleUndefinedFunction(e,t,r){const n={callback:await this.encryptCallbackName(t),...r},s=this.createFetchOptions(n),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const n=new URL(window.location.href);let o="",a="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(o=await this.fetchFileWithData(n.href,t,l,r),a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(n.href,s);if(o=await e.text(),this.getRedirectUrl(o))return void await this.redirect(this.getRedirectUrl(o)||"");if(a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",d=e.getAttribute("pp-after-request")||"";if((h||d&&c.success)&&this.restoreSuspenseElement(e),h||d){let e="";if(c.success){e=o.replace(a,"")}else e=o;if(this.appendAfterbegin(e),!d&&!c.success)return}if(d&&c.success){this.handleAfterRequest(d,a);const e=o.replace(a,"");return this.appendAfterbegin(e),a}if("@close"===d)return c.success?a:void 0;const p=await this.fetch(n.href,i),u=await p.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(o,u,a,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const r=this.parseJson(e),n=t?this.parseJson(t):null,s=r.targets;Array.isArray(s)&&s.forEach((e=>{const{id:t,...r}=e,s=document.querySelector(t);let i={};if(n){for(const t in r)if(r.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===r[t]&&(i[t]=e.responseKey?n[e.responseKey]:n.response);break;default:i[t]=r[t]}}else i=r;s&&this.updateElementAttributes(s,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,r)=>` data-onwheel-code="${this.decodeEntities(r).replace(/"/g,""")}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{const t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null,t&&(e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t))}))}async handleResponseRedirectOrUpdate(e,t,r,n){const s=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,r,n),o=(new DOMParser).parseFromString(s,"text/html");i&&o.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(o.body.outerHTML)}getUpdatedHTMLContent(e,t,r){const n=document.createElement("div");if(n.id="afterbegin-8D95D",r&&t?.success){const t=e.replace(r,"");n.innerHTML=t}else n.innerHTML=e;return n.innerHTML?n:null}async updateBodyContent(e){try{const t=this.saveScrollPositions();this.saveElementState();const r=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(r),await this.appendCallbackResponse(r),await this.populateDocumentBody(r),await this.removeAllEventListenersOnNavigation(),await this.initReactiveOn(),this.restoreScrollPositions(t),document.body.removeAttribute("hidden")}catch(e){console.error("updateBodyContent failed:",e)}}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const r in t)if(t.hasOwnProperty(r))switch(r){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[r]=this.decodeHTML(t[r]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[r].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[r].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[r]));break;case"removeAttribute":e.removeAttribute(t[r]);break;case"className":e.className=this.decodeHTML(t[r]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[r]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[r]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[r]));break;case"classList.replace":const[n,s]=this.decodeHTML(t[r]).split(",");e.classList.replace(n,s);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[r]);break;case"style":Object.assign(e.style,t[r]);break;case"value":e.value=this.decodeHTML(t[r]);break;case"checked":e.checked=t[r];break;default:e.setAttribute(r,this.decodeHTML(t[r]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let r=document.getElementById(t);r?(r.innerHTML=e,document.body.insertAdjacentElement("afterbegin",r)):(r=document.createElement("div"),r.id=t,r.innerHTML=e,document.body.insertAdjacentElement("afterbegin",r))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const r=(e,t)=>{for(const r in t)t.hasOwnProperty(r)&&("textContent"===r?e.textContent=t[r]:"innerHTML"===r?e.innerHTML=t[r]:"disabled"===r?!0===t[r]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(r,t[r]));for(const r of Array.from(e.attributes))t.hasOwnProperty(r.name)||e.removeAttribute(r.name)},n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const n=this.parseJson(e);r(t,n)}else s(t,e);t.removeAttribute("pp-original-state")}}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?n(e,t):r(e,t)};try{const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const n=this.parseJson(t);r(e,n)}}}const s=new FormData(e),i={};if(s.forEach(((e,t)=>{i[t]=e})),n(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(s.targets){s.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&i(n,r)}));const{targets:t,...n}=s;r(e,n)}else{const{empty:t,...n}=s;r(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,r,n={}){const s=new FormData,i=r.files;if(i)for(let e=0;e<i.length;e++)s.append("file[]",i[e]);s.append("callback",t);for(const e in n)n.hasOwnProperty(e)&&s.append(e,n[e]);const o=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:s});return await o.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const r=(e,t)=>{for(const r in t)if(t.hasOwnProperty(r))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(this.isJsonLike(e)){const r=this.parseJson(e);"disabled"!==r.onsubmit&&this.updateElementAttributes(t,r),r.targets&&r.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&s(n,r)}))}else n(t,e)}},n=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},s=(e,t)=>{e instanceof HTMLFormElement?r(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const n=this.parseJson(t);if(n)if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=n;this.updateElementAttributes(e,o),r(e,s)}else if(n.targets){n.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&s(n,r)}));const{targets:t,...r}=n;this.updateElementAttributes(e,r)}else{if("disabled"===n.empty&&""===e.value)return;const{empty:t,...r}=n;this.updateElementAttributes(e,r)}}else if(t)n(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),n={};t.forEach(((e,t)=>{n[t]=e})),r(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let r=0;r<e.attributes.length;r++){const n=e.attributes[r];t[n.name]=n.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const r=e.id;r&&(t=document.querySelector(`[form="${r}"]`)),r&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,r)=>{e[r]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let r={};const n=e.closest("form");if(n){new FormData(n).forEach(((e,t)=>{const n=this.clean(e);r[t]?r[t]=Array.isArray(r[t])?[...r[t],n]:[r[t],n]:r[t]=n}))}else e instanceof HTMLInputElement?r=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(r[e.name]=e.value);if("args"in r){const e=r.args,t=Array.isArray(e)&&e.every((e=>null==e||""===e));(null==e||""===e||t)&&delete r.args}const s=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(!s)return{funcName:t.trim(),data:r};const i=s[1].trim(),o=s[2].trim();if(""===o)return{funcName:i,data:r};const a=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(o.startsWith("{")&&o.endsWith("}")||o.startsWith("[")&&o.endsWith("]"))if(this.isJsonLike(o))try{const e=this.parseJson(o);Array.isArray(e)?r.args=e:e&&"object"==typeof e&&(r={...r,...e})}catch(e){console.error("Error parsing JSON args:",e),r.rawArgs=o}else try{const e=this.evaluateJavaScriptObject(o);Array.isArray(e)?r.args=e:e&&"object"==typeof e?r={...r,...e}:r.rawArgs=o}catch(e){console.error("Error evaluating JS object args:",e),r.rawArgs=o}else if(/^[\s\d"'[\{]/.test(o))try{const e=new Function(`return [${o}];`)();r.args=Array.isArray(e)?e:[e]}catch{a.test(o)?r.args=o.split(a).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):r.args=[o.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(o)(this.props);r.args=[e]}catch{r.args=o.split(a).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return Array.isArray(r.args)&&(r.args=r.args.filter((e=>!(null==e||""===e))),0===r.args.length&&delete r.args),{funcName:i,data:r}}clean(e){if("string"!=typeof e)return e;let t=e.replace(/"/g,'"').trim();/^"(?:[^"\\]|\\.)*"$/.test(t)&&(t=t.slice(1,-1));try{return JSON.parse(t)}catch{}if(/^-?\d+(\.\d+)?$/.test(t)&&!/^0\d/.test(t)){const e=Number(t);if(!Number.isNaN(e))return e}return t}evaluateJavaScriptObject(e){try{const t=this.getOrCreateProxy(this.props);return new Function("proxy","Date","Math","JSON",`\n with (proxy) {\n return ${e};\n }\n `).call(null,t,Date,Math,JSON)}catch(e){throw console.error("Failed to evaluate JavaScript object:",e),e}}handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const r=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=r?r.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}handleInputAppendParams(e,t){const r=e.getAttribute("pp-append-params"),n=e.getAttribute("pp-append-params-sync");if("true"===r){if("true"===n){const t=e.name||e.id;if(t){const r=new URL(window.location.href),n=new URLSearchParams(r.search);n.has(t)&&(e.value=n.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,r=t.value,n=new URL(window.location.href),s=new URLSearchParams(n.search),i=t.name||t.id;if(i){r?s.set(i,r):s.delete(i);const e=s.toString()?`${n.pathname}?${s.toString()}`:n.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),r=this.handleElementVisibility.bind(this),n=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",r))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",n)))}handleVisibilityElementAttribute(e,t,r){const n=e.getAttribute(t);if(n)if(this.isJsonLike(n)){r(e,this.parseJson(n))}else{const r=this.parseTime(n);if(r>0){const n="pp-visibility"===t?"visibility":"display",s="visibility"===n?"hidden":"none";this.scheduleChange(e,r,n,s)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,r,n,s){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[r]=n,this.scheduleChange(e,i,r,s),o>0&&this.scheduleChange(e,i+o,r,n)):o>0&&this.scheduleChange(e,o,r,n)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,r=t.getAttribute("href"),n=t.getAttribute("target");if(r&&"_blank"!==n&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(r)&&!r.startsWith(window.location.origin))window.location.href=r;else{const e=t.getAttribute("pp-append-params");let n="";if(r.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[i,o]=r.split("#");o&&(s=`#${o}`);new URLSearchParams(i.split("?")[1]).forEach(((e,r)=>{t.set(r,e)})),n=`${e.pathname}?${t.toString()}${s}`}else{const[e,t]=r.split("#");n=`${e}${t?`#${t}`:""}`}history.pushState(null,"",n);const s=r.indexOf("#");if(-1!==s){const e=r.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href),r=await t.text();if(!t.ok)return await this.updateDocumentContent(r),void console.error(`Navigation error: ${t.status} ${t.statusText}`);const n=r.match(this._redirectRegex);if(n&&n[1])return void await this.redirect(n[1]);await this.updateDocumentContent(r)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let r=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${r}']`);if(t)return t;if("/"===r)break;const n=r.lastIndexOf("/");r=n<=0?"/":r.substring(0,n)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:r,fadeOut:n}=this.parseTransition(e);await this.fadeOut(t,n),t.innerHTML=e.innerHTML,this.fadeIn(t,r)}parseTransition(e){let t=250,r=250;const n=e.querySelector("[pp-loading-transition]"),s=n?.getAttribute("pp-loading-transition");if(s){const e=this.parseJson(s);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),r=this.parseTime(e.fadeOut??r)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",s)}return{fadeIn:t,fadeOut:r}}fadeOut(e,t){return new Promise((r=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",r()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&(console.log("Aborting active request..."),this._activeAbortController.abort(),this._activeAbortController=null)}async fetch(e,t,r=!1){let n;return r?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,n=this._activeAbortController):n=new AbortController,fetch(e,{...t,signal:n.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){try{if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}catch{return!1}}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,r,n){setTimeout((()=>{requestAnimationFrame((()=>{e.style[r]=n}))}),t)}async fetchFunction(e,t={},r=!1){let n=null;try{r&&this._activeAbortController&&(console.log("Aborting previous request..."),this._activeAbortController.abort(),this._activeAbortController=null),n=new AbortController,r&&(this._activeAbortController=n);const s={callback:await this.encryptCallbackName(e),...t},i=window.location.href;let o;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const r=s[t];r instanceof File?e.append(t,r):r instanceof FileList?Array.from(r).forEach((r=>e.append(t,r))):e.append(t,r)})),o={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e,signal:n.signal}}else o={signal:n.signal,...this.createFetchOptions(s)};const a=await fetch(i,o);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const c=await a.text();n&&this._activeAbortController===n&&(this._activeAbortController=null);try{return JSON.parse(c)}catch{return c}}catch(e){if(n&&this._activeAbortController===n&&(this._activeAbortController=null),e instanceof Error&&"AbortError"===e.name)return console.log("Request was cancelled"),{cancelled:!0};throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const r=e.length?e:["true"],n=await this.fetch(window.location.href,this.createFetchOptions({pphpSync71163:!0,selectors:r,secondRequestC69CD:!0,...this.getUrlParams()}));let s;if(n.headers.get("content-type")?.includes("application/json")){s=(await n.json()).fragments}else s={[r[0]]:await n.text()};const i=`<body>${Object.values(s).join("")}</body>`,o=(new DOMParser).parseFromString(i,"text/html");await this.initReactiveOn(o,{wire:!1});const a=[];r.forEach((e=>{const t=`[pp-sync="${e}"]`,r=document.querySelectorAll(t),n=o.body.querySelector(t);n&&r.forEach((e=>{morphdom(e,n,{childrenOnly:!0,onBeforeElUpdated:(e,t)=>{const r=e.tagName,n=this.PRESERVE_HANDLERS[r];return!n||n(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0),getNodeKey:e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.getAttribute("key")||t.getAttribute("pp-key")||void 0}}),a.push(e)}))})),this.restoreElementState(),this.restoreScrollPositions(t);for(const e of a)await this.attachWireFunctionEvents(e)}catch(e){console.error("pphp.sync failed:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),r=await t.text();await this.updateBodyContent(r)}copyCode(e,t,r,n,s="img",i=2e3){if(!(e instanceof HTMLElement))return;const o=e.closest(`.${t}`)?.querySelector("pre code"),a=o?.textContent?.trim()||"";a?navigator.clipboard.writeText(a).then((()=>{const t=e.querySelector(s);if(t)for(const[e,r]of Object.entries(n))e in t?t[e]=r:t.setAttribute(e,r);setTimeout((()=>{if(t)for(const[e,n]of Object.entries(r))e in t?t[e]=n:t.setAttribute(e,n)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){const r={...this.state,...e};if(JSON.stringify(r)!==JSON.stringify(this.state)&&(this.state=r,this.listeners.forEach((e=>e(this.state))),this.saveState(),t)){const e=localStorage.getItem(this.STORAGE_KEY);e&&e!==this.lastSyncedState&&(this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e}),this.lastSyncedState=e)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t}),this.lastSyncedState=t}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const r=this.params;r.set(e,t),this.updateURL(r)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const r in e){const n=e[r];null!==n&&t.set(r,n)}this.updateURL(t,!0)}updateURL(e,t=!1){const r=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",r):history.pushState(null,"",r),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
|
|
1
|
+
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,r=new Map,n=new WeakMap,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);function i(e){const t=e.currentTarget;if(t instanceof Element)return t;if(t instanceof Document||t===window)return document.body||document.documentElement||null;const r=e.target;if(r instanceof Element)return r;if(r&&"number"==typeof r.nodeType){const e=r;return e.parentElement||e.ownerDocument?.body||null}const n=e.composedPath?.();if(Array.isArray(n))for(const e of n)if(e instanceof Element)return e;return document.body||document.documentElement||null}function o(e,t){const r=globalThis.pphp??globalThis.PPHP?.instance??null;if(!r||!e)return t();let n=["app"];try{n=r.detectElementHierarchy(e)||["app"]}catch{n=["app"]}const s={eff:r._currentEffectContext,proc:r._currentProcessingHierarchy,evt:r._currentEventTarget};try{return r._currentEffectContext=n.join("."),r._currentProcessingHierarchy=n,r._currentEventTarget=e,t()}finally{r._currentEffectContext=s.eff,r._currentProcessingHierarchy=s.proc,r._currentEventTarget=s.evt}}function a(e,t,r){const s=function(e,t){let r=n.get(e);r||(r=new Map,n.set(e,r));let s=r.get(t);return s||(s=new Map,r.set(t,s)),s}(e,t),a=s.get(r);if(a)return a;let c;if("function"==typeof r){const e=r;c=function(t){return o(i(t),(()=>e.call(this,t)))}}else{const e=r;c={handleEvent:t=>o(i(t),(()=>e.handleEvent(t)))}}return s.set(r,c),c}EventTarget.prototype.addEventListener=function(t,n,i){let o=i;s.has(t)&&(void 0===o?o={passive:!0}:"boolean"==typeof o?o={capture:o,passive:!0}:void 0===o.passive&&(o={...o,passive:!0})),r.has(this)||r.set(this,new Map);const c=r.get(this),l=c.get(t)||new Set;l.add(n),c.set(t,l);const h=a(this,t,n);return e.call(this,t,h,o)},EventTarget.prototype.removeEventListener=function(e,s,i){if(r.has(this)&&r.get(this).has(e)){const t=r.get(this).get(e);t.delete(s),0===t.size&&r.get(this).delete(e)}const o=n.get(this)?.get(e),a=o?.get(s)??s;t.call(this,e,a,i),o?.delete(s)},EventTarget.prototype.removeAllEventListeners=function(e){const s=r.get(this);if(s){if(e){const r=s.get(e);if(!r)return;const i=n.get(this)?.get(e);return r.forEach((r=>{const n=i?.get(r)??r;t.call(this,e,n),i?.delete(r)})),void s.delete(e)}s.forEach(((e,r)=>{const s=n.get(this)?.get(r);e.forEach((e=>{const n=s?.get(e)??e;t.call(this,r,n)}))})),r.delete(this),n.delete(this)}}})(),function(){const e=console.log;console.log=(...t)=>{const r=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,r)}}();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_proxyCache=new WeakMap;_rawProps={};_refs=new Map;_wheelHandlersStashed=!1;_evaluatorCache=new Map;_depsCache=new Map;_dirtyDeps=new Set;_handlerCache=new Map;_handlerProxyCache=new WeakMap;_sharedStateMap=new Set;_processedLoops=new WeakSet;_hydrated=!1;_currentProcessingHierarchy=null;_stateHierarchy=new Map;_inlineModuleFns=new Map;_currentExecutionScope=null;_transitionStyleInjected=!1;_currentEffectContext=null;_currentEventTarget=null;_eventContextStack=[];_currentProcessingElement=null;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _cancelableEvents=new Set(["click","submit","change"]);static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;static _passiveEvents=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),r=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...r].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this._rawProps={},this.props=this.makeReactive({}),this.setupGlobalEventTracking(),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}debugProps(){console.group("%cPPHP Debug Snapshot","font-weight:bold; color:teal"),console.groupCollapsed("📦 Raw props"),console.log(JSON.stringify(this.props,null,2)),console.groupEnd(),console.groupCollapsed("🌐 Shared state (pphp.share)"),0===PPHP._shared.size?console.log("(none)"):console.table(Array.from(PPHP._shared.entries()).map((([e,{getter:t}])=>({key:e,value:this.formatValue(t()),type:typeof t()})))),console.groupEnd(),console.groupCollapsed("🔗 Shared keys declared this run"),0===this._sharedStateMap.size?console.log("(none)"):console.log([...this._sharedStateMap]),console.groupEnd(),console.groupCollapsed("🔖 State hierarchy"),console.table(Array.from(this._stateHierarchy.entries()).map((([e,t])=>({scopedKey:e,originalKey:t.originalKey,level:t.level,value:this.formatValue(this.getNested(this.props,e)),path:t.hierarchy.join(" → ")})))),console.groupEnd(),console.groupCollapsed("⚙️ Reactive internals"),console.log("Bindings total:",this._bindings.length),console.log("Pending bindings:",this._pendingBindings.size),console.log("Effects:",this._effects.size),console.log("Pending effects:",this._pendingEffects.size),console.log("Dirty deps:",Array.from(this._dirtyDeps).join(", ")||"(none)"),console.groupEnd(),console.groupCollapsed("🔗 Refs"),console.table(Array.from(this._refs.entries()).map((([e,t])=>({key:e,count:t.length,selectors:t.map((e=>e.tagName.toLowerCase())).join(", ")})))),console.groupEnd(),console.groupCollapsed("📦 Inline modules"),this._inlineModuleFns.forEach(((e,t)=>{console.log(`${t}:`,[...e.keys()])})),console.groupEnd(),console.log("Hydrated:",this._hydrated),console.groupCollapsed("🔀 Conditionals (pp-if chains)");Array.from(document.querySelectorAll("[pp-if], [pp-elseif], [pp-else]")).forEach(((e,t)=>{const r=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",n=e.getAttribute(`pp-${r}`)??null;let s=null;if(n){const t=n.replace(/^{\s*|\s*}$/g,""),r=this.detectElementHierarchy(e);try{s=!!this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r))}catch{s=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:r,expr:n,visible:!e.hasAttribute("hidden"),result:s})})),console.groupEnd(),console.groupCollapsed("🔁 Loops (pp-for)");const e=Array.from(document.querySelectorAll("template[pp-for]"));if(0===e.length)console.log("(none)");else{const t=e.map(((e,t)=>{const{itemName:r,idxName:n,arrExpr:s}=this.parseForExpression(e);let i=0;const o=e.previousSibling;if(o?.nodeType===Node.COMMENT_NODE&&"pp-for"===o.data){let e=o.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));)i+=1,e=e.nextSibling}return{"#":t,"(expr)":s,item:r||"(default)",idx:n||"(—)",rendered:i}}));console.table(t)}console.groupEnd(),console.groupEnd()}setupGlobalEventTracking(){const e=EventTarget.prototype.addEventListener,t=this;EventTarget.prototype.addEventListener=function(r,n,s){return e.call(this,r,(function(e){return t.trackEventContext&&t.trackEventContext(e),"function"==typeof n?n.call(this,e):n&&"function"==typeof n.handleEvent?n.handleEvent(e):void 0}),s)}}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{try{await Promise.all([this.initRefs(),this.bootstrapDeclarativeState(),this.processInlineModuleScripts(),this._hydrated=!0]),await e(),await this.initializeAllReferencedProps(),await e(),await this.manageAttributeBindings(),await e(),await this.processIfChains(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();const t=250;for(let r=0;r<this._bindings.length;r+=t)this._bindings.slice(r,r+t).forEach((e=>{try{e.update()}catch(e){console.error("Initial binding update error:",e)}})),await e();document.body.removeAttribute("hidden")}catch(e){console.error("Hydration failed:",e),document.body.removeAttribute("hidden")}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}async hydratePortal(e=document.body){await this.initReactiveOn(e,{wire:!0,preserveHierarchy:!0})}getPreservedPortalHierarchy(e){let t=e;for(;t&&t!==document.documentElement;){const e=t.getAttribute("data-pphp-original-hierarchy");if(e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch(e){console.warn("Failed to parse preserved portal hierarchy:",e)}t=t.parentElement}return[]}async initCryptoKey(){const e=document.cookie.split("; ").find((e=>e.startsWith("pphp_function_call_jwt=")))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),r=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:n,exp:s}=JSON.parse(r);if(Date.now()/1e3>s)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(n),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),r=(new TextEncoder).encode(e),n=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,r);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(n)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,r]=e.split(":",2),n=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),s=Uint8Array.from(atob(r),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:n},PPHP._cryptoKey,s);return(new TextDecoder).decode(i)}qsa(e,t){try{if(e)return e.querySelectorAll(t)}catch(e){console.error("qsa() failed:",e)}return document.createDocumentFragment().querySelectorAll(t)}async bootstrapDeclarativeState(e=document.body){this.qsa(e,"[pp-init-state]").forEach((e=>{let t,r=e.getAttribute("pp-init-state").trim();if(!r)return void e.removeAttribute("pp-init-state");try{t=JSON5.parse(r)}catch(e){return void console.error("Bad pp-init-state JSON:",r)}const n=this.detectElementHierarchy(e),s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=n,Object.entries(t).forEach((([e,t])=>{this.state(e,t)})),this._currentProcessingHierarchy=s,e.removeAttribute("pp-init-state")}))}detectComponentHierarchy(e){const t=[];let r=e;for(;r&&r!==document.documentElement;){const e=r.getAttribute("pp-component");e&&t.unshift(e),r=r.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){if(!e)return["app"];const t=this.getPreservedPortalHierarchy(e);if(t.length>0)return t;const r=[];let n=e instanceof Element?e:document.body||null;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&"__shared"!==e&&r.unshift(e),n=n.parentElement}return r.length?r:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const r=this._refs.get(e)??[];if(null!=t){const n=r[t];if(!n)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return n}if(0===r.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===r.length?r[0]:r}processRefsInFragment(e,t){e.querySelectorAll("[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),r=this._refs.get(t)??[];r.push(e),this._refs.set(t,r),e.setAttribute("data-ref-key",t),e.removeAttribute("pp-ref")}))}effect(e,t){const r=Array.isArray(t),n=r?t:[],s=r&&0===n.length,i=this._currentProcessingHierarchy||(this._currentEffectContext?this._currentEffectContext.split("."):["app"]),o=i.join("."),a=n.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e();for(const[r,n]of PPHP._shared.entries())try{if(n.getter()===t)return Object.defineProperty(e,"__pphp_key",{value:`__shared.${r}`,writable:!1,enumerable:!1}),`__shared.${r}`}catch(e){}const r=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(r){const t=r[1],n=t.split(".")[0];if(PPHP._shared.has(n)){const r=`__shared.${t}`;return Object.defineProperty(e,"__pphp_key",{value:r,writable:!1,enumerable:!1}),r}}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),c=n.filter((e=>"function"==typeof e)),l=new Set(a),h=new Map,d=new Map;for(const e of a)try{const t=this.getResolvedValue(e);h.set(e,t)}catch(t){h.set(e,void 0)}for(const e of c)try{const t=e();d.set(e,t)}catch(t){d.set(e,Symbol("error"))}let p=0,u=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const f=PPHP._effectCleanups,m=()=>{const t=f.get(m);if(t){try{t()}catch(e){console.error("cleanup error:",e)}f.delete(m)}const n=performance.now();if(n-u<16)return void requestAnimationFrame((()=>{performance.now()-u>=16&&m()}));if(u=n,++p>100)throw console.error("PPHP: effect exceeded 100 runs - possible infinite loop"),console.error("Effect function:",e.toString()),console.error("Dependencies:",Array.from(l)),new Error("PPHP: effect ran >100 times — possible loop");if(!s){let e=!1;const t=[];for(const r of a)try{const n=this.getResolvedValue(r),s=h.get(r);this.hasValueChanged(n,s)&&(e=!0,t.push(r),h.set(r,n))}catch(n){e=!0,t.push(r),h.set(r,void 0)}for(const r of c)try{const n=r(),s=d.get(r);this.hasValueChanged(n,s)&&(e=!0,t.push("(function)"),d.set(r,n))}catch(n){d.get(r)!==Symbol("error")&&(e=!0,t.push("(function-error)"),d.set(r,Symbol("error")))}if(r&&(a.length>0||c.length>0)&&!e)return}const i=this._currentEffectContext;this._currentEffectContext=o;try{const t=e();"function"==typeof t&&f.set(m,t),p=0}catch(t){console.error("effect error:",t),console.error("Effect function:",e.toString())}finally{this._currentEffectContext=i}};Object.assign(m,{__deps:l,__static:s,__functionDeps:c,__hierarchy:i,__isEffect:!0});const y=this._currentEffectContext;this._currentEffectContext=o;try{const t=e();"function"==typeof t&&f.set(m,t),p=0}catch(e){console.error("effect error (initial):",e)}finally{this._currentEffectContext=y}const g=r&&this._inlineDepth>0?this._pendingEffects:this._effects;return s?this._effects.add(m):g.add(m),()=>{const e=f.get(m);if(e){try{e()}catch(e){console.error("cleanup error:",e)}f.delete(m)}this._effects.delete(m),this._pendingEffects.delete(m)}}resolveDependencyPath(e,t){const r=e.startsWith("app.")?e.substring(4):e,n=r.split(".")[0];if(PPHP._shared.has(n))return`__shared.${r}`;const s=t.join(".")+"."+e;if(this.hasNested(this.props,s))return s;if(this.hasNested(this.props,e))return e;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?n+"."+e:e;if(this.hasNested(this.props,s))return s}return e}getResolvedValue(e){const t=(e.startsWith("app.")?e.substring(4):e).split("."),r=t[0],n=PPHP._shared.get(r);if(n){if(1===t.length)return n.getter();{const e=n.getter(),r=t.slice(1).join(".");return this.getNested(e,r)}}return this.getNested(this.props,e)}hasValueChanged(e,t){if(e===t)return!1;if(null==e||null==t)return e!==t;if("object"!=typeof e||"object"!=typeof t)return e!==t;try{return JSON.stringify(e)!==JSON.stringify(t)}catch(e){return!0}}resetProps(){this._isNavigating=!1,this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=null,this._responseData=null,Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable&&delete window[e]}})),this._rawProps={},this.clearShare(),this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._handlerProxyCache=new WeakMap,this._processedLoops=new WeakSet,this._depsCache.clear(),this._dirtyDeps.clear(),this._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._currentProcessingElement=null,this._transitionStyleInjected=!1,this._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._currentProcessingHierarchy=null,this._currentExecutionScope=null,this._stateHierarchy.clear(),this._currentEventTarget=null,this._eventContextStack=[],this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1,this._currentEffectContext=null;try{const e=window;Object.getOwnPropertyNames(e).forEach((t=>{if(t.startsWith("__pphp_")||t.startsWith("_temp_"))try{delete e[t]}catch(e){}}))}catch(e){}this.props=this.makeReactive({}),this._hydrated=!1;const e=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT,{acceptNode:e=>"pp-for"===e.data?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let t;for(;t=e.nextNode();){let e=t.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));){const t=e.nextSibling;e.parentNode?.removeChild(e),e=t}t.parentNode?.removeChild(t)}}async initReactiveOn(e=document.body,t={}){const{wire:r=!0,preserveHierarchy:n=!1}=t,s=()=>new Promise((e=>setTimeout(e,0)));n&&e instanceof Element&&this.markPortalChildrenWithHierarchy(e),await Promise.all([this.initRefs(e),this.bootstrapDeclarativeState(e)]),await s(),await this.processInlineModuleScripts(e),await s(),this._hydrated=!0,await s(),await this.initializeAllReferencedProps(e),await s(),await this.manageAttributeBindings(e),await s(),await this.processIfChains(e),await s(),await this.initLoopBindings(e),await s(),r&&(e===document.body||e.isConnected)&&(await this.attachWireFunctionEvents(e),await s());for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await s()}markPortalChildrenWithHierarchy(e){const t=e.getAttribute("data-pphp-original-hierarchy");if(!t)return;const r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);for(;r.nextNode();){const e=r.currentNode;e.hasAttribute("data-pphp-original-hierarchy")||e.setAttribute("data-pphp-original-hierarchy",t)}}async removeAllEventListenersOnNavigation(){document.removeAllEventListeners(),this._refs.forEach((e=>e.forEach((e=>e.removeAllEventListeners?.())))),document.querySelectorAll("*").forEach((e=>e.removeAllEventListeners?.()))}async initLoopBindings(e=document.body){this.qsa(e,"template[pp-for]").forEach((e=>{this._processedLoops.has(e)||(this._processedLoops.add(e),this.registerLoop(e))}))}registerLoop(e){const t=this.parseForExpression(e),{marker:r,parent:n,templateHierarchy:s}=this.setupLoopMarker(e),i=this.initializeLoopState(),o=this.createLoopUpdater(e,t,r,n,s,i),a={dependencies:this.extractComprehensiveLoopDependencies(e,t,s),update:o,__isLoop:!0};this._bindings.push(a)}processIfChainsInFragment(e,t,r,n,s,i){const o=new WeakSet;e.querySelectorAll("[pp-if]").forEach((e=>{if(o.has(e))return;const a=[];let c=e;for(;c;){if(c.hasAttribute("pp-if"))a.push({el:c,expr:c.getAttribute("pp-if")});else if(c.hasAttribute("pp-elseif"))a.push({el:c,expr:c.getAttribute("pp-elseif")});else{if(!c.hasAttribute("pp-else"))break;a.push({el:c,expr:null})}o.add(c),c=c.nextElementSibling}a.forEach((e=>{if(null!==e.expr){const i=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(i,r);const o=this.makeScopedEvaluator(i,r);e.evaluate=()=>{const e={...this._createScopedPropsContext(r),[t.itemName]:n};return t.idxName&&(e[t.idxName]=s),!!o(e)}}}));let l=!1;for(const{el:e,expr:t,evaluate:r}of a)!l&&null!==t&&r()?(e.removeAttribute("hidden"),l=!0):l||null!==t?e.setAttribute("hidden",""):(e.removeAttribute("hidden"),l=!0);const h=new Set;a.forEach((e=>e.deps?.forEach((e=>h.add(e)))));const d=r.join("."),p=d?`${d}.${t.arrExpr}`:t.arrExpr;h.add(p);i.push({dependencies:h,update:()=>{const e=this.makeScopedEvaluator(t.arrExpr,r)(this._createScopedPropsContext(r));if(Array.isArray(e)){const i=this.getItemKey(n,s),o=this.findItemByKey(e,i,n),c=e.findIndex((t=>this.getItemKey(t,e.indexOf(t))===i));if(o&&-1!==c){let e=!1;for(const{el:n,expr:s}of a)if(null!==s){const i=this.makeScopedEvaluator(s.replace(/^{\s*|\s*}$/g,""),r),a={...this._createScopedPropsContext(r),[t.itemName]:o};t.idxName&&(a[t.idxName]=c);const l=!!i(a);!e&&l?(n.removeAttribute("hidden"),e=!0):n.setAttribute("hidden","")}else e?n.setAttribute("hidden",""):(n.removeAttribute("hidden"),e=!0)}}},__isLoop:!0})}))}extractComprehensiveLoopDependencies(e,t,r){const n=new Set,s=t.arrExpr.split(".")[0];let i=null;if(PPHP._shared.has(s)){i=`__shared.${t.arrExpr}`;try{const e=this.getNested(this.props,i);Array.isArray(e)||(i=null)}catch{i=null}}if(!i)for(let e=r.length;e>=0;e--){const n=r.slice(0,e),s=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,s);if(Array.isArray(e)){i=s;break}}catch{}}i||(i=t.arrExpr);const o=i;n.add(o);const a=this.extractItemPropertiesFromTemplate(e,t);for(const e of a){n.add(`${o}.*`),n.add(`${o}.*.${e}`);try{const t=this.getNested(this.props,o);if(Array.isArray(t))for(let r=0;r<t.length;r++)n.add(`${o}.${r}.${e}`)}catch{}}return Array.from(n).some((e=>e.includes("*")))||n.add(`${o}.*`),n}extractItemPropertiesFromTemplate(e,t){const r=new Set,n=new RegExp(`\\b${t.itemName}\\.(\\w+(?:\\.\\w+)*)`,"g"),s=document.createTreeWalker(e.content,NodeFilter.SHOW_ALL,null);for(;s.nextNode();){const e=s.currentNode;let t="";if(e.nodeType===Node.TEXT_NODE)t=e.nodeValue||"";else if(e.nodeType===Node.ELEMENT_NODE){const r=e;for(const e of Array.from(r.attributes))t+=" "+e.value}const i=t.matchAll(n);for(const e of i)r.add(e[1])}return r}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[r,n]=t.split(/\s+in\s+/),[s,i]=r.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:r,arrExpr:n,itemName:s,idxName:i}}setupLoopMarker(e){const t=e.parentNode,r=document.createComment("pp-for"),n=this.detectElementHierarchy(e);return t.insertBefore(r,e),t.removeChild(e),{marker:r,parent:t,templateHierarchy:n}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,r,n,s){const i={...this._createScopedPropsContext(s),[n.itemName]:t};n.idxName&&(i[n.idxName]=r);const o=e.content.cloneNode(!0),a=[],c=this.getItemKey(t,r);return this.processTextNodesInFragment(o,n,s,c,t,r,a),this.processElementBindingsInFragment(o,n,s,c,t,r,a),this.processEventHandlersInFragment(o,n,s,t),this.processRefsInFragment(o,a),this.processIfChainsInFragment(o,n,s,t,r,a),a.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),{nodes:Array.from(o.childNodes),bindings:a}}processTextNodesInFragment(e,t,r,n,s,i,o){const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;a.nextNode();){const e=a.currentNode,c=e.nodeValue||"";if(PPHP._mustacheTest.test(c)){const a=new Set,l=r.join("."),h=l?`${l}.${t.arrExpr}`:t.arrExpr;a.add(h);for(const e of c.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],r).forEach((e=>a.add(e)));const d=this.createTextNodeUpdaterWithItemKey(e,c,t,r,n,s);o.push({dependencies:a,update:d}),this.renderTextNode(e,c,t,r,s,i)}}}createTextNodeUpdaterWithItemKey(e,t,r,n,s,i){const o=this.makeScopedEvaluator(r.arrExpr,n);return()=>{const a=o(this._createScopedPropsContext(n));if(Array.isArray(a)){const o=this.findItemByKey(a,s,i),c=a.findIndex((e=>this.getItemKey(e,a.indexOf(e))===s));if(o&&-1!==c){const s={...this._createScopedPropsContext(n),[r.itemName]:o};r.idxName&&(s[r.idxName]=c);const i=this.renderMustacheText(t,n,s);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,r){for(let r=0;r<e.length;r++){const n=e[r];if(this.getItemKey(n,r)===t)return n}return r&&"object"==typeof r&&r.id?e.find((e=>e&&e.id===r.id)):null}processElementBindingsInFragment(e,t,r,n,s,i,o){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,r,n,s,i,o)}))}processElementBindings(e,t,r,n,s,i,o){const a=new Set,c=new Set;for(const{name:t,value:r}of Array.from(e.attributes))if(PPHP._mustacheTest.test(r)&&!t.startsWith("pp-bind"))a.add(t);else if(t.startsWith("pp-bind-")){const e=t.replace(/^pp-bind-/,"");c.add(e)}for(const{name:c,value:l}of Array.from(e.attributes))if("pp-bind"===c)this.createElementBindingWithItemKey(e,l,"text",t,r,n,s,i,o);else if("pp-bind-expr"===c){const a=this.decodeEntities(l);this.createElementBindingWithItemKey(e,a,"text",t,r,n,s,i,o)}else if(c.startsWith("pp-bind-")){const h=c.replace(/^pp-bind-/,"");if(a.has(h)){if(!this._boolAttrs.has(h))continue;e.removeAttribute(h)}this.createElementBindingWithItemKey(e,l,h,t,r,n,s,i,o)}else PPHP._mustacheTest.test(l)&&this.createElementAttributeTemplateBindingWithItemKey(e,c,l,t,r,n,s,i,o)}createElementAttributeTemplateBindingWithItemKey(e,t,r,n,s,i,o,a,c){const l=new Set,h=s.join("."),d=h?`${h}.${n.arrExpr}`:n.arrExpr;l.add(d);for(const e of r.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],s).forEach((e=>l.add(e)));const p=this.createAttributeTemplateUpdaterWithItemKey(e,t,r,n,s,i,o);c.push({dependencies:l,update:p}),this.renderAttributeTemplate(e,t,r,n,s,o,a)}createAttributeTemplateUpdaterWithItemKey(e,t,r,n,s,i,o){const a=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const c=a(this._createScopedPropsContext(s));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));a&&-1!==l&&this.renderAttributeTemplate(e,t,r,n,s,a,l)}}}renderAttributeTemplate(e,t,r,n,s,i,o){const a={...this._createScopedPropsContext(s),[n.itemName]:i};n.idxName&&(a[n.idxName]=o);const c=r.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeScopedEvaluator(t,s);return this.formatValue(e(a))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==c&&e.setAttribute(t,c)}createElementBindingWithItemKey(e,t,r,n,s,i,o,a,c){const l=new Set,h=s.join("."),d=h?`${h}.${n.arrExpr}`:n.arrExpr;l.add(d),this.extractScopedDependencies(t,s).forEach((e=>l.add(e)));const p=this.createElementBindingUpdaterWithItemKey(e,t,r,n,s,i,o);c.push({dependencies:l,update:p}),this.renderElementBinding(e,t,r,n,s,o,a)}createElementBindingUpdaterWithItemKey(e,t,r,n,s,i,o){const a=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const c=a(this._createScopedPropsContext(s));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));if(a&&-1!==l){const i={...this._createScopedPropsContext(s),[n.itemName]:a};n.idxName&&(i[n.idxName]=l),this.updateElementBinding(e,t,r,s,i)}}}}getItemKey(e,t){if(e&&"object"==typeof e){if("id"in e&&null!=e.id)return`id_${e.id}`;if("key"in e&&null!=e.key)return`key_${e.key}`;if("_id"in e&&null!=e._id)return`_id_${e._id}`;const t=Object.keys(e).filter((t=>(t.toLowerCase().includes("id")||t.toLowerCase().includes("uuid"))&&null!=e[t]&&("string"==typeof e[t]||"number"==typeof e[t])));if(t.length>0){const r=t[0];return`${r}_${e[r]}`}}return`idx_${t}`}renderTextNode(e,t,r,n,s,i){const o={...this._createScopedPropsContext(n),[r.itemName]:s};r.idxName&&(o[r.idxName]=i),e.nodeValue=this.renderMustacheText(t,n,o)}renderMustacheText(e,t,r){return e.replace(PPHP._mustachePattern,((e,n)=>{try{const e=this.makeScopedEvaluator(n,t);return this.formatValue(e(r))}catch{return""}}))}updateElementBinding(e,t,r,n,s){const i=this.makeScopedEvaluator(t,n)(s);if("text"===r){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,r,i)}renderElementBinding(e,t,r,n,s,i,o){const a={...this._createScopedPropsContext(s),[n.itemName]:i};n.idxName&&(a[n.idxName]=o),this.updateElementBinding(e,t,r,s,a)}applyAttributeBinding(e,t,r){if(this._boolAttrs.has(t)){const n=!!r;n!==e.hasAttribute(t)&&(n?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==n&&(e[t]=n)}else{const n=String(r);t in e&&e[t]!==n&&(e[t]=n),e.getAttribute(t)!==n&&e.setAttribute(t,n)}}processEventHandlersInFragment(e,t,r,n){e.querySelectorAll("*").forEach((e=>{const s=this.getItemKey(n,-1);for(const{name:n,value:i}of Array.from(e.attributes)){const o=n.toLowerCase();if(!this._eventHandlers.has(o))continue;let a=i;const c=`globalThis.pphp._getDynamicLoopItem('${s}', '${t.arrExpr}', ${JSON.stringify(r)})`;if(a=a.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),c),t.idxName){const e=`globalThis.pphp._idxOf(${c}, '${t.arrExpr}', ${JSON.stringify(r)})`;a=a.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),e)}e.setAttribute(n,a)}}))}_getDynamicLoopItem(e,t,r){try{const n=this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r));if(!Array.isArray(n))return null;for(let t=0;t<n.length;t++){const r=n[t];if(this.getItemKey(r,t)===e)return r}return null}catch{return null}}_idxOf(e,t,r){try{const n=this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r));if(!Array.isArray(n))return-1;let s=n.findIndex((t=>t===e));if(-1!==s)return s;const i=this.getItemKey(e,-1);return s=n.findIndex(((e,t)=>this.getItemKey(e,t)===i)),s}catch{return-1}}updateItemNodes(e,t,r,n,s,i){if(t===r)return;if("object"==typeof t&&"object"==typeof r&&JSON.stringify(t)===JSON.stringify(r))return;const o={...this._createScopedPropsContext(i),[s.itemName]:r};s.idxName&&(o[s.idxName]=n),this.updateNodesContent(e,i,o),this.updateConditionalNodes(e,i,o)}updateConditionalNodes(e,t,r){e.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){e.querySelectorAll("[pp-if], [pp-elseif], [pp-else]").forEach((e=>{const n=e.getAttribute("pp-if")||e.getAttribute("pp-elseif");if(n){const s=n.replace(/^{\s*|\s*}$/g,"");try{const n=this.makeScopedEvaluator(s,t);!!n(r)?e.removeAttribute("hidden"):e.setAttribute("hidden","")}catch(e){console.error("Error evaluating pp-if condition:",s,e)}}else if(e.hasAttribute("pp-else")){const t=e.previousElementSibling;t&&t.hasAttribute("hidden")?e.removeAttribute("hidden"):e.setAttribute("hidden","")}}))}}))}updateNodesContent(e,t,r){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,r)}))}updateElementContent(e,t,r){const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;n.nextNode();){const e=n.nextNode(),s=e.nodeValue||"",i=this.renderMustacheText(s,t,r);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,r),this.updateElementTemplateAttributes(e,t,r)}))}updateElementTemplateAttributes(e,t,r){for(const{name:n,value:s}of Array.from(e.attributes))if(!n.startsWith("pp-bind")&&PPHP._mustacheTest.test(s)){const i=s.replace(PPHP._mustachePattern,((e,n)=>{try{const e=this.makeScopedEvaluator(n,t);return this.formatValue(e(r))}catch(e){return console.error("PPHP: mustache token error:",n,e),""}}));e.getAttribute(n)!==i&&e.setAttribute(n,i)}}updateElementBindingsContent(e,t,r){for(const{name:n,value:s}of Array.from(e.attributes))if("pp-bind"===n)this.updateElementBinding(e,s,"text",t,r);else if(n.startsWith("pp-bind-")){const i=n.replace(/^pp-bind-/,"");this.updateElementBinding(e,s,i,t,r)}}createLoopUpdater(e,t,r,n,s,i){const o=(()=>{const e=t.arrExpr.split(".")[0];return r=>{if(PPHP._shared.has(e))try{const e=`__shared.${t.arrExpr}`,r=this.getNested(this.props,e);if(Array.isArray(r))return r}catch{}for(let e=s.length;e>=0;e--){const r=s.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,r),n=e(this._createScopedPropsContext(r));if(Array.isArray(n))return n}catch{}}try{const e=this.makeScopedEvaluator(t.arrExpr,s)(r);return Array.isArray(e)?e:[]}catch{return[]}}})();return()=>{this.performLoopUpdate(e,t,r,n,s,i,o)}}captureFocusState(e){const t=document.activeElement,r=t&&e.contains(t),n=r?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:r,focusKey:n,caretPos:r&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const r=t.querySelector(`[key="${e.focusKey}"]`),n=r?.querySelector("input,textarea");if(n&&(n.focus({preventScroll:!0}),null!==e.caretPos&&n instanceof HTMLInputElement)){const t=Math.min(e.caretPos,n.value.length);n.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const r=new Map,n=new Map;e.forEach(((e,t)=>{const n=this.getItemKey(e,t);r.set(n,{item:e,index:t})})),t.forEach(((e,t)=>{const r=this.getItemKey(e,t);n.set(r,{item:e,index:t})}));const s=new Set,i=new Map,o=new Map;for(const[e]of r)n.has(e)||s.add(e);for(const[e,{item:t,index:s}]of n)if(r.has(e)){const n=r.get(e);n.item===t&&n.index===s||o.set(e,{oldItem:n.item,newItem:t,newIndex:s,oldIndex:n.index})}else i.set(e,{item:t,index:s});return{toDelete:s,toInsert:i,toUpdate:o}}applyLoopChanges(e,t,r,n,s,i,o){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,r,i),this.applyLoopInsertions(e.toInsert,t,r,n,s,i,o)}applyLoopUpdates(e,t,r,n){for(const[s,{oldItem:i,newItem:o,newIndex:a}]of e){const e=t.renderedItems.get(s);e&&(this.updateItemNodes(e.nodes,i,o,a,r,n),e.item=o,e.index=a,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,r,n,s,i,o){if(0===e.size)return;const a=Array.from(e.entries()).sort((([,e],[,t])=>e.index-t.index));for(const[e,{item:c,index:l}]of a){if(t.renderedItems.has(e)){console.warn(`Item with key ${e} already exists, skipping insertion`);continue}const{nodes:a,bindings:h}=this.createItemNodes(o,c,l,r,i);let d=n;const p=Array.from(t.renderedItems.entries()).map((([e,t])=>({key:e,...t}))).sort(((e,t)=>e.index-t.index));for(let e=p.length-1;e>=0;e--)if(p[e].index<l){d=p[e].nodes[p[e].nodes.length-1];break}a.forEach((e=>{s.insertBefore(e,d.nextSibling),d=e})),t.renderedItems.set(e,{nodes:a,item:c,index:l,bindings:h})}}performLoopUpdate(e,t,r,n,s,i,o){const a=this.captureFocusState(n);let c,l=[];for(let e=s.length;e>=0;e--){const t=s.slice(0,e);try{c=this._createScopedPropsContext(t);const e=o(c);if(Array.isArray(e)&&e.length>=0){l=e;break}}catch(e){console.error("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(s);const e=o(c);l=Array.isArray(e)?e:[]}if(!Array.isArray(l))return void console.warn("Loop expression did not return an array:",l);const h=this.calculateLoopDiff(i.previousList,l);this.applyLoopChanges(h,i,t,r,n,s,e),i.previousList=[...l],this.restoreFocusState(a,n),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const r of e){const e=t.renderedItems.get(r);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{this.cleanupRefsInNode(e),e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(r))}}cleanupRefsInNode(e){if(e.nodeType===Node.ELEMENT_NODE){[e,...e.querySelectorAll("[data-ref-key]")].forEach((e=>{for(const[t,r]of this._refs.entries()){const n=r.indexOf(e);n>-1&&(r.splice(n,1),0===r.length&&this._refs.delete(t))}}))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),r=this._refs.get(t)??[];r.push(e),this._refs.set(t,r),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){if(this.shouldUnwrapValue(e))return e;const r=this._proxyCache.get(e);if(r)return r;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const n=this,s=new Proxy(e,{get(e,r,s){if("__isReactiveProxy"===r)return!0;const i=Reflect.get(e,r,s);if(null===i||"object"!=typeof i)return i;if(Array.isArray(e)&&"string"==typeof r&&n._mutators.has(r)){let o=n._arrayMethodCache.get(e);if(o||(o=new Map,n._arrayMethodCache.set(e,o)),!o.has(r)){const e=i.bind(s),a=t.join("."),c=function(...t){const r=e(...t);return queueMicrotask((()=>{n._bindings.forEach((e=>{const t=n.getBindingType(e);for(const r of e.dependencies)if(n.dependencyMatches(a,r,t)){n.scheduleBindingUpdate(e);break}}))})),r};o.set(r,c)}return o.get(r)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy&&!n.shouldUnwrapValue(i))return n.makeReactive(i,[...t,r]);if(Array.isArray(e)&&"function"==typeof i){let t=n._arrayMethodCache.get(e);return t||(t=new Map,n._arrayMethodCache.set(e,t)),t.has(r)||t.set(r,i.bind(e)),t.get(r)}return i},set(e,r,s,i){if("__isReactiveProxy"===r)return!0;let o=s;null===s||"object"!=typeof s||s.__isReactiveProxy||n.shouldUnwrapValue(s)||(o=n.makeReactive(s,[...t,r]));const a=e[r],c=Reflect.set(e,r,o,i);if(a===o)return c;const l=[...t,r].join(".");if(n._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&n._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(r))){const e=t.join(".");if(n._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),r=t.split(".")[0];PPHP._shared.has(r)&&n._dirtyDeps.add(`${t}.*`)}o&&"object"==typeof o&&Object.keys(o).forEach((t=>{if(n._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const r=e.substring(4),s=r.split(".")[0];PPHP._shared.has(s)&&n._dirtyDeps.add(`${r}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(n._dirtyDeps.add(`${e}.*.${String(r)}`),e.startsWith("app.")){const t=e.substring(4),s=t.split(".")[0];PPHP._shared.has(s)&&n._dirtyDeps.add(`${t}.*.${String(r)}`)}}return n._bindings.forEach((e=>{const t=n.getBindingType(e);for(const r of e.dependencies){if(n.dependencyMatches(l,r,t)){n.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const s=l.substring(4),i=s.split(".")[0];if(PPHP._shared.has(i)&&n.dependencyMatches(s,r,t)){n.scheduleBindingUpdate(e);break}}}})),n._hydrated&&n.scheduleFlush(),c}});return this._proxyCache.set(e,s),s}shouldUnwrapValue(e){return e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof URLSearchParams||e instanceof URL||e instanceof Promise||e instanceof ArrayBuffer||e instanceof DataView||"object"==typeof e&&null!==e&&e.constructor!==Object&&e.constructor!==Array}getBindingType(e){if(e.__isEffect)return"effect";if(e.__isLoop)return"loop";for(const t of e.dependencies)if(t.includes("*")||t.match(/\.\d+\./)||t.endsWith(".*"))return"loop";for(const t of e.dependencies)try{const e=this.getNested(this.props,t);if(Array.isArray(e))return"loop"}catch{}return"binding"}makeAttrTemplateUpdater(e,t,r,n){let s=this._templateStore.get(e);s||(s=new Map,this._templateStore.set(e,s)),s.has(t)||s.set(t,e.getAttribute(t)||"");const i=n??s.get(t),o=this.detectElementHierarchy(e);return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractScopedDependencies(t,o).forEach((e=>r.add(e)))})),()=>{try{const r=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,o),r=this._createScopedPropsContext(o);return this.formatValue(e(r))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==r&&e.setAttribute(t,r)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}formatValue(e){if(e instanceof Date)return e.toISOString();if("function"==typeof e){if(e.__isReactiveProxy)try{return this.formatValue(e())}catch{}return""}if(e&&"object"==typeof e){if(e.__isReactiveProxy&&"value"in e)try{return this.formatValue(e.value)}catch{return String(e)}if(e.__isReactiveProxy)try{const t={};for(const r in e)if("__isReactiveProxy"!==r&&"__pphp_key"!==r)try{t[r]=e[r]}catch{}return Object.keys(t).length?JSON.stringify(t,null,2):""}catch{return String(e)}try{return JSON.stringify(e,((e,t)=>{if("__isReactiveProxy"!==e&&"__pphp_key"!==e)return t&&"object"==typeof t&&t.__isReactiveProxy?"function"==typeof t&&"value"in t?t.value:"[Reactive Object]":t}),2)}catch{return String(e)}}return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e&&null!==e?(()=>{try{return JSON.stringify(e)}catch{return String(e)}})():String(e))).join(", "):e?.toString()??""}registerBinding(e,t,r="text",n){if(this._assignmentRe.test(t))return;const s=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,s),o=this.makeScopedEvaluator(t,s);if("value"===n||"checked"===n){const t=()=>{try{const t=this._createScopedPropsContext(s),r=o(t),i=this.formatValue(r);let a=!1;if("value"===n){const t=e;"value"in e&&t.value!==i?(t.value=i,a=!0):"value"in e||(e.setAttribute("value",i),a=!0)}else{const t=e,r="true"===i;"checked"in e&&t.checked!==r?(t.checked=r,a=!0):"checked"in e||(e.setAttribute("checked",i),a=!0)}if(!a||!this._hydrated||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const c={};this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);c[t]=t}})),c.value="input",c.checked="change";const l=c[n]||n,h="click"===l?new MouseEvent(l,{bubbles:!0,cancelable:!0}):new Event(l,{bubbles:!0});e.dispatchEvent(h)}catch(e){console.error(`Error evaluating attribute "${n}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(n){const r=n.toLowerCase();if(this._boolAttrs.has(r)){e.removeAttribute(r);const a=()=>{try{const t=this._createScopedPropsContext(s),i=!!o(t);e[n]!==i&&(e[n]=i),i?e.setAttribute(r,""):e.removeAttribute(r)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:a})}const a=e.getAttribute(n)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(a)){const t=this.makeAttrTemplateUpdater(e,n,i,a);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(s),r=o(t),i=this.formatValue(r);n in e&&(e[n]=i),e.setAttribute(n,i)}catch(e){console.error(`Error evaluating attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:c})}const a={text(e,t){e.textContent!==t&&(e.textContent=t)},value(e,t){e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked(e,t){e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr(e,t){e.setAttribute("attr",t)}};this._bindings.push({dependencies:i,update:()=>{try{const t=this._createScopedPropsContext(s),n=o(t),i=this.formatValue(n);a[r](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),r=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let n;try{n=new Function("ctx",r)}catch(t){const r=JSON.stringify(e);n=new Function("ctx",`try { return ${r}; } catch { return ""; }`)}return e=>{try{const t=n(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const r=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(r)?`${r}; return "";`:`return (${r});`}\n }\n } catch (error) {\n return "";\n }\n `;let s;try{s=new Function("ctx",n)}catch(t){console.error("Expression compilation error:",t.message,"Expression:",r);const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const r=this._createScopedPropsContext(t,e),n=s(r);return null==n?"":n}catch(e){return e instanceof Error?console.error("Scoped evaluation error:",e.message,"Expression:",r):console.error("Scoped evaluation error:",e,"Expression:",r),""}}}_createScopedPropsContext(e,t={}){const r=e.join("."),n=this.getNested(this.props,r)||{},s=this,i=(e,t)=>{if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch(r){return console.error(`Failed to unwrap reactive proxy function for ${t}:`,r),e}if(e&&"object"==typeof e&&e.__isReactiveProxy){const n=r?`${r}.${t}`:t;try{const r=n.split(".");let i=s._rawProps;for(const e of r){if(!i||"object"!=typeof i||!(e in i)){i=void 0;break}i=i[e]}if(void 0!==i){if(null===i||"object"!=typeof i)return i;if(Array.isArray(i))return e;try{const t=Object.keys(i);if(t.length>0){const r=t[0];return void 0!==e[r]?e:i}}catch(e){console.warn(`Error testing reactive proxy for ${t}:`,e)}return e}}catch(e){console.warn(`Clean path traversal failed for ${t}:`,e)}if(e&&"object"==typeof e&&"value"in e)return e.value;if("function"==typeof e)try{return e()}catch(e){console.warn(`Failed to call malformed proxy for ${t}:`,e)}return e}return e};return new Proxy(t,{get(t,o,a){if("string"!=typeof o)return Reflect.get(t,o,a);if(o in t){const e=Reflect.get(t,o,a);return i(e,o)}if(PPHP._shared.has(o)){const e=PPHP._shared.get(o);if(e)try{return e.getter()}catch(e){console.warn(`Failed to get shared state for ${o}:`,e)}}const c=s.getScopedFunction(o,e);if(c)return c;const l=r?`${r}.${o}`:o;if(s.hasNested(s.props,l)){const e=s.getNested(s.props,l);return i(e,o)}if(n&&o in n){const e=n[o];return i(e,o)}for(let t=e.length-1;t>=0;t--){const r=e.slice(0,t).join("."),n=s.getScopedFunction(o,e.slice(0,t));if(n)return n;const a=r?s.getNested(s.props,r):s.props;if(a&&o in a){const e=a[o];return i(e,o)}}if(PPHP._shared.has(o)){const e=PPHP._shared.get(o);if(e)try{return e.getter()}catch(e){console.warn(`Failed to get shared state for ${o}:`,e)}}return o in globalThis?globalThis[o]:void 0},set(t,n,i,o){if("string"!=typeof n)return Reflect.set(t,n,i,o);if(n in t)return Reflect.set(t,n,i,o);for(let t=e.length;t>=0;t--){const r=e.slice(0,t).join("."),o=r?`${r}.${n}`:n;if(s.hasNested(s.props,o))return s.setNested(s.props,o,i),s._dirtyDeps.add(o),s.scheduleFlush(),!0}const a=r?`${r}.${n}`:n;return s.setNested(s.props,a,i),s._dirtyDeps.add(a),s.scheduleFlush(),!0},has:(t,i)=>"string"==typeof i&&(i in t||!!s.getScopedFunction(i,e)||s.hasNested(s.props,r?`${r}.${i}`:i)||n&&i in n||PPHP._shared.has(i)||i in globalThis||e.some(((t,r)=>{const n=e.slice(0,r).join("."),o=n?s.getNested(s.props,n):s.props;return o&&i in o}))),ownKeys(t){const i=new Set;Object.keys(t).forEach((e=>i.add(e))),n&&"object"==typeof n&&Object.keys(n).forEach((e=>i.add(e)));const o=r?s.getNested(s.props,r):s.props;o&&"object"==typeof o&&Object.keys(o).forEach((e=>i.add(e)));for(let t=e.length-1;t>=0;t--){const r=e.slice(0,t).join("."),n=r?s.getNested(s.props,r):s.props;n&&"object"==typeof n&&Object.keys(n).forEach((e=>i.add(e)))}return PPHP._shared.forEach(((e,t)=>i.add(t))),Array.from(i)},getOwnPropertyDescriptor(e,t){return"string"!=typeof t?Reflect.getOwnPropertyDescriptor(e,t):this.has(e,t)?{enumerable:!0,configurable:!0,writable:!0}:void 0}})}extractScopedDependencies(e,t){const r=this.extractDependencies(e),n=new Set,s=t.join(".");for(const i of r){if(this._reservedWords.has(i.split(".")[0]))continue;const r=i.split(".")[0];if(new RegExp(`\\b${r}\\s*\\(`).test(e))continue;if(this._sharedStateMap.has(r)){n.add(`__shared.${i}`);continue}const o=s+"."+i;if(this._stateHierarchy.has(o)){n.add(o);continue}if(this.hasNested(this.props,o)){n.add(o);continue}let a=!1;for(let e=t.length-1;e>=0&&!a;e--){const r=t.slice(0,e).join("."),s=r?r+"."+i:i;this._stateHierarchy.has(s)?(n.add(s),a=!0):this.hasNested(this.props,s)&&(n.add(s),a=!0)}if(!a){const e=s+"."+i;n.add(e)}}return n}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const r=this.detectElementHierarchy(e),n=[];let s=e;for(;s;){if(s.hasAttribute("pp-if"))n.push({el:s,expr:s.getAttribute("pp-if")});else if(s.hasAttribute("pp-elseif"))n.push({el:s,expr:s.getAttribute("pp-elseif")});else{if(!s.hasAttribute("pp-else"))break;n.push({el:s,expr:null})}t.add(s),s=s.nextElementSibling}n.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,r);const n=this.makeScopedEvaluator(t,r);e.evaluate=()=>{const e=this._createScopedPropsContext(r);return!!n(e)}}}));const i=new Set;n.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:r,evaluate:s}of n)!e&&null!==r&&s()?(t.removeAttribute("hidden"),e=!0):e||null!==r?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})}))}async manageAttributeBindings(e=document.body){this.qsa(e,"*").forEach((e=>{const t=new Map;Array.from(e.attributes).forEach((e=>{if(e.name.startsWith("pp-bind"))return;const r=this.decodeEntities(e.value);PPHP._mustacheTest.test(r)&&t.set(e.name.toLowerCase(),r)})),["pp-bind","pp-bind-expr"].forEach((t=>{const r=e.getAttribute(t);r&&this.registerBinding(e,r,"text")})),Array.from(e.attributes).forEach((t=>{const r=t.name.toLowerCase(),n=t.value.trim();this._boolAttrs.has(r)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(n)&&(e.removeAttribute(t.name),this.registerBinding(e,n,"text",r))})),Array.from(e.attributes).forEach((r=>{if(!r.name.startsWith("pp-bind-"))return;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(r.name))return;const n=r.name.replace(/^pp-bind-/,"").toLowerCase(),s=this.decodeEntities(r.value).replace(/^{{\s*|\s*}}$/g,""),i="value"===n?"value":"checked"===n?"checked":"text";if(t.has(n)){const o=t.get(n).replace(PPHP._mustachePattern,"").trim(),a=o.length>0?`\`${o} \${${s}}\``:s;e.setAttribute(r.name,a);try{const t=this._createScopedPropsContext(this.detectElementHierarchy(e)),r=this.formatValue(this.makeScopedEvaluator(a,this.detectElementHierarchy(e))(t));e.setAttribute(n,r)}catch{}return this.registerBinding(e,a,i,n),void t.delete(n)}this.registerBinding(e,s,i,n)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const r=this.detectElementHierarchy(e),n=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),s=new Set;n.forEach((e=>this.extractScopedDependencies(e,r).forEach((e=>s.add(e)))));const i=new Set;this._bindings.push({dependencies:s,update:()=>{try{const t={},s=this._createScopedPropsContext(r);n.forEach((e=>Object.assign(t,this.makeScopedEvaluator(e,r)(s)??{}))),i.forEach((r=>{r in t||e.hasAttribute(r)||(e.removeAttribute(r),i.delete(r))})),Object.entries(t).forEach((([t,r])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==r||!1===r)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const n="object"==typeof r?JSON.stringify(r):String(r);e.getAttribute(t)!==n&&e.setAttribute(t,n),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})})),t.forEach(((t,r)=>{this.registerBinding(e,t,"text",r)}))}))}callInlineModule(e,...t){const r=this._currentProcessingHierarchy||["app"],n=this.getScopedFunction(e,r);if(!n)throw new Error(`PPHP: no inline module named "${e}" in scope ${r.join(".")}`);return n(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;if(e.startsWith("set")){const t=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(t)){const e=PPHP._shared.get(t);return e?.setter||null}}for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return s.get(e)}if(e.startsWith("set")){const r=e.charAt(3).toLowerCase()+e.slice(4);for(let e=t.length;e>=0;e--){const n=t.slice(0,e).join("."),s=n?`${n}.${r}`:r;if(this.hasNested(this.props,s))return e=>{this.setNested(this.props,s,e),this._dirtyDeps.add(s),this.scheduleFlush()}}}return null}async processInlineModuleScripts(e=document.body){this._inlineDepth++;try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>!this._processedPhpScripts.has(e)));if(0===t.length)return;const r=t.map((e=>{const t=this.detectComponentHierarchy(e);return{script:e,hierarchy:t,depth:t.length}})).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of r){this._currentProcessingHierarchy=t,this._currentEffectContext=t.join(".");const r=t.join(".");let n=(e.textContent||"").trim();n=this.decodeEntities(n),n=this.stripComments(n),n=this.transformStateDeclarations(n),n=this.transformEffectDependencies(n),n=this.injectScopedVariables(n,t);const s=this.extractSetters(n);if(s.length){n+="\n\n";for(const e of s)n+=`pphp._registerScopedFunction('${r}', '${e}', ${e});\n`}n=this.stateDeclarations(n);const i=[];for(const[,e]of[...n.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...n.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${r}', '${e}', ${e});`);i.length&&(n+="\n\n"+i.join("\n"));const o=new Blob([n],{type:"application/javascript"}),a=URL.createObjectURL(o);try{const e=await import(a);this._inlineModuleFns.has(r)||this._inlineModuleFns.set(r,new Map);const t=this._inlineModuleFns.get(r);for(const[r,n]of Object.entries(e))"function"!=typeof n||t.has(r)||t.set(r,n)}catch(e){console.error("❌ Inline module import failed:",e),console.error("📄 Generated source:",n)}finally{URL.revokeObjectURL(a),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}this._currentProcessingHierarchy=null,this._currentEffectContext=null}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}transformEffectDependencies(e){let t=e,r=0;for(;;){const e=t.indexOf("pphp.effect(",r);if(-1===e)break;let n=1,s=e+12,i=!1,o="",a=-1;for(;s<t.length&&n>0;){const e=t[s],r=s>0?t[s-1]:"";if(i||'"'!==e&&"'"!==e&&"`"!==e){if(i&&e===o&&"\\"!==r)i=!1,o="";else if(!i)if("("===e||"{"===e||"["===e)n++;else if(")"===e||"}"===e||"]"===e){if(n--,0===n&&")"===e)break}else","===e&&1===n&&-1===a&&(a=s)}else i=!0,o=e;s++}if(0===n&&-1!==a){const n=s,i=t.substring(a+1,n).trim().match(/^\[\s*([^\]]*?)\s*\]$/);if(i){const s=i[1].trim();if(s){const e=`[${this.smartSplitDependencies(s).map((e=>{const t=e.trim();return/^['"`]/.test(t)?e:/^[a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test(t)?`'${t}'`:e})).join(", ")}]`,i=t.substring(0,a+1),o=t.substring(n);t=i+" "+e+o,r=i.length+e.length}else r=e+12}else r=e+12}else r=e+12}return t}smartSplitDependencies(e){if(!e.trim())return[];const t=[];let r="",n=0,s=!1,i="";for(let o=0;o<e.length;o++){const a=e[o],c=o>0?e[o-1]:"";if(s||'"'!==a&&"'"!==a&&"`"!==a?s&&a===i&&"\\"!==c&&(s=!1,i=""):(s=!0,i=a),!s)if("([{".includes(a))n++;else if(")]}".includes(a))n--;else if(","===a&&0===n){r.trim()&&t.push(r.trim()),r="";continue}r+=a}return r.trim()&&t.push(r.trim()),t}stateDeclarations(e){const t="pphp.",r=["state","share"];let n=e;for(const e of r){let r=0;for(;-1!==(r=n.indexOf(`${t}${e}(`,r));){const t=r+5+e.length+1,s=n.slice(t).match(/^(['"])([^'" ]+)\1\s*,/);if(s){const[e]=s;r=t+e.length}else{const e=n.slice(t),s=e.indexOf(",");if(-1===s)break;{const i=`'${e.slice(0,s).trim()}', `;n=n.slice(0,t)+i+n.slice(t),r=t+i.length+s}}}}return n}injectScopedVariables(e,t){const r=this.extractVariableReferences(e),n=this.extractDeclaredVariables(e),s=this.extractStateVariables(e),i=new Set([...n,...s]),o=[],a=new Set;for(const e of r)if(!a.has(e)&&!i.has(e)&&this.hasInScopedContext(e,t)){const r=this.findScopedKeyForVariable(e,t);o.push(`\nconst ${e} = (() => {\n const fn = () => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n };\n \n fn.__isReactiveProxy = true;\n fn.__pphp_key = '${r}';\n \n Object.defineProperty(fn, 'value', {\n get() {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n },\n configurable: true\n });\n \n fn.valueOf = function() { return this.value; };\n fn.toString = function() { return String(this.value); };\n \n return fn;\n})();`),a.add(e);const n=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(n,t)&&!i.has(n)&&(o.push(`\nconst ${n} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${n}(...args);\n};`),a.add(n))}return o.length>0?o.join("\n")+"\n\n"+e:e}extractStateVariables(e){const t=new Set,r=/\b(?:const|let|var)\s+\[\s*([^,\]]+)(?:\s*,\s*([^,\]]+))?\s*\]\s*=\s*pphp\.state/g;let n;for(;null!==(n=r.exec(e));){const e=n[1]?.trim(),r=n[2]?.trim();e&&t.add(e),r&&t.add(r)}const s=/pphp\.state\s*\(\s*['"]([^'"]+)['"]/g;for(;null!==(n=s.exec(e));){const e=n[1];if(e){t.add(e);const r=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;t.add(r)}}return t}extractDeclaredVariables(e){const t=new Set;let r=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const n=[/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+\[\s*([^\]]+?)\s*\]/g,/\b(?:const|let|var)\s+\{\s*([^}]+?)\s*\}/g,/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\bexport\s+function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g,/\bexport\s+(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g];for(const e of n){let n;for(;null!==(n=e.exec(r));){const r=n[1]||n[2];if(e.source.includes("\\[")&&!e.source.includes("\\{")){const e=r.split(",").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith("...")?e.substring(3).trim():e));for(const r of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(r)&&t.add(r)}else if(e.source.includes("\\{")&&!e.source.includes("\\[")){const e=r.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{const t=e.indexOf(":");return-1!==t?e.substring(t+1).trim():e.startsWith("...")?e.substring(3).trim():e}));for(const r of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(r)&&t.add(r)}else r&&t.add(r)}}return t}findScopedKeyForVariable(e,t){const r=t.join("."),n=this.getNested(this.props,r)||{};if(n&&e in n)return`${r}.${e}`;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?this.getNested(this.props,n):this.props;if(s&&"object"==typeof s&&e in s)return n?`${n}.${e}`:e}return`${r}.${e}`}extractVariableReferences(e){const t=new Set;let r=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ");const n=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let s;for(;null!==(s=n.exec(r));){const e=s[1],n=s.index;if(this._reservedWords.has(e))continue;const i=r.substring(n+e.length,n+e.length+20);if(/^\s*\(/.test(i))continue;const o=r.substring(Math.max(0,n-50),n);/\b(?:const|let|var|function|class|export)\s+$/.test(o)||(n>0&&"."===r[n-1]||/^\s*:/.test(i)||this.isActualFunctionParameter(r,n,e)||this.isInDestructuringDeclaration(r,n,e)||this.shouldSkipVariableInjection(e,r,n)||t.add(e))}return t}shouldSkipVariableInjection(e,t,r){if(this._reservedWords.has(e))return!0;if(new Set(["window","document","console","navigator","location","history","localStorage","sessionStorage","setTimeout","setInterval","clearTimeout","clearInterval","fetch","XMLHttpRequest","Date","Math","JSON","Object","Array","String","Number","Boolean","RegExp","Error","Promise","Map","Set","WeakMap","WeakSet","Symbol","BigInt","Proxy","Reflect","pphp","globalThis","self","top","parent"]).has(e))return!0;if(e.length<=2&&/^[a-z_$][\w$]*$/.test(e))return!0;if(e.startsWith("_"))return!0;const n=t.substring(r+e.length,r+e.length+20);return r>0&&"."===t[r-1]||(!!/^\s*:/.test(n)||!!this.isInDestructuringPattern(t,r))}isInDestructuringPattern(e,t){let r=Math.max(0,t-50),n=e.substring(r,t+20);return[/(?:const|let|var)\s*\{[^}]*$/,/(?:const|let|var)\s*\[[^\]]*$/].some((e=>e.test(n)))}isActualFunctionParameter(e,t,r){let n=-1,s=-1,i=0;for(let r=t-1;r>=0;r--){const t=e[r];if(")"===t)i++;else if("("===t){if(0===i){n=r;break}i--}}if(-1===n)return!1;i=0;for(let n=t+r.length;n<e.length;n++){const t=e[n];if("("===t)i++;else if(")"===t){if(0===i){s=n;break}i--}}if(-1===s)return!1;const o=e.substring(Math.max(0,n-20),n).trim(),a=e.substring(s+1,Math.min(e.length,s+10)).trim(),c=/\bfunction(?:\s+[a-zA-Z_$]\w*)?\s*$/.test(o),l=a.startsWith("=>");if(c||l){const n=e.substring(t+r.length,s);return!n.includes("=>")&&!n.includes("{")}return!1}isInDestructuringDeclaration(e,t,r){const n=e.substring(Math.max(0,t-100),t);if(n.match(/\b(?:const|let|var)\s+\[\s*[^\]]*$/)){const n=e.substring(t+r.length,Math.min(e.length,t+r.length+100));if(/[^\]]*\]\s*=/.test(n))return!0}if(n.match(/\b(?:const|let|var)\s+\{\s*[^}]*$/)){const n=e.substring(t+r.length,Math.min(e.length,t+r.length+100));if(/[^}]*\}\s*=/.test(n))return!0}return!1}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return!0}const r=t.join("."),n=this.getNested(this.props,r)||{};if(n&&e in n)return!0;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?this.getNested(this.props,n):this.props;if(s&&"object"==typeof s&&e in s)return!0;const i=n?`${n}.${e}`:e;if(this._stateHierarchy.has(i))return!0}return!!PPHP._shared.has(e)}_registerScopedFunction(e,t,r){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...n)=>{const s=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&n.length>0?r(n[0]):r(...n)}finally{this._currentExecutionScope=s}}))}extractSetters(e){const t=[],r=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let n;for(;n=r.exec(e);){const[,e,r,s]=n;"share"===s&&this.markShared(e),this._sharedStateMap.has(e)||t.push(r)}return t}markShared(e){this._sharedStateMap.add(e)}transformStateDeclarations(e){return e=(e=(e=e.replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r,n,s)=>`${t}${r}, ${n}${s}'${r}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r,n)=>`${t}${r}${n}'${r}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r)=>`${t}[${r}] = pphp.state('${r}', `))}stripComments(e){let t="",r=0,n=!1,s=!1;for(;r<e.length;){const i=e[r],o=e[r+1];if(s||"'"!==i&&'"'!==i&&"`"!==i||"\\"===e[r-1])if(n)t+=i,r++;else if(s||"/"!==i||"*"!==o)if(s)"*"===i&&"/"===o?(s=!1,r+=2):r++;else if("/"!==i||"/"!==o)t+=i,r++;else for(;r<e.length&&"\n"!==e[r];)r++;else s=!0,r+=2;else n=!n,t+=i,r++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let r=!1;const n=this.getBindingType(t);for(const s of t.dependencies){for(const t of e)if(this.dependencyMatches(t,s,n)){r=!0;break}if(r)break}if(r)try{t.update()}catch(e){console.error("Binding update error:",e)}})),this._pendingBindings.forEach((e=>{try{e.update()}catch(e){console.error("Pending binding update error:",e)}})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const r=t.__deps||new Set,n=t.__functionDeps||[];if(0===r.size&&0===n.length){try{t()}catch(e){console.error("effect error:",e)}return}const s=[...r].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=n.length>0;if(s||i)try{t()}catch(e){console.error("effect error:",e)}}))}static ARRAY_INTRINSICS=(()=>{const e=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]);return new Set(Object.getOwnPropertyNames(Array.prototype).filter((t=>!e.has(t))))})();static headMatch(e,t){return e===t||e.startsWith(t+".")}dependencyMatches(e,t,r="binding"){const n=e=>{if(e.startsWith("__shared."))return e.slice(9);if(e.startsWith("app.")){const t=e.slice(4),r=t.split(".")[0];if(PPHP._shared.has(r))return t}return e},s=n(e),i=n(t);if(s===i||e===t)return!0;if(e.startsWith("__shared.")&&t.startsWith("__shared.")&&e===t)return!0;if(e.startsWith("__shared.")&&t===e.slice(9))return!0;if(t.startsWith("__shared.")&&e===t.slice(9))return!0;const o=i.split(".");if(o.length>1&&PPHP.ARRAY_INTRINSICS.has(o.at(-1))&&PPHP.headMatch(s,o.slice(0,-1).join(".")))return!0;let a=!1;switch(r){case"effect":a=this.matchEffectDependency(s,i);break;case"loop":PPHP.headMatch(s,i)||PPHP.headMatch(i,s)?a=!0:(i.includes("*")||this.matchesArrayIndexPattern(s,i))&&(a=this.matchLoopDependency(s,i));break;default:PPHP.headMatch(s,i)?a=!0:(i.includes("*")||this.matchesArrayIndexPattern(s,i))&&(a=this.matchBindingDependency(s,i))}return a}matchEffectDependency(e,t){if(e===t)return!0;const r=t.startsWith("__shared."),n=e.startsWith("__shared.");if(r&&n){const r=t.substring(9),n=e.substring(9);if(n.startsWith(r+"."))return!0;if(r.startsWith(n+"."))return!0}if(e.startsWith(t+".")){return!e.substring(t.length+1).includes(".")}return!!t.includes("*")&&this.matchesWildcardPattern(e,t)}matchLoopDependency(e,t){return!(!e.startsWith(t+".")&&!t.startsWith(e+"."))||(!(!this.isArrayPath(t)||!this.isArrayItemPath(e,t))||(t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)))}isArrayPath(e){try{const t=this.getNested(this.props,e);return Array.isArray(t)}catch{return!1}}isArrayItemPath(e,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+($|\\.)`).test(e)}matchBindingDependency(e,t){if(e.startsWith(t+".")){return e.substring(t.length+1).split(".").length<=2}return t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)}matchesWildcardPattern(e,t){const r=e.split("."),n=t.split(".");if(r.length!==n.length)return!1;for(let e=0;e<n.length;e++){const t=n[e],s=r[e];if("*"!==t&&t!==s)return!1}return!0}matchesArrayIndexPattern(e,t){const r=e.split("."),n=t.split(".");if(r.length!==n.length)return!1;for(let e=0;e<n.length;e++){const t=r[e],s=n[e];if(t!==s&&(!/^\d+$/.test(t)||!/^\d+$/.test(s)))return!1}return!0}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}getNested(e,t){const r=t.split(".").reduce(((e,t)=>e?e[t]:void 0),e);return r}setNested(e,t,r){const n=t.split("."),s=n.pop(),i=n.reduce(((e,t)=>e[t]??={}),e);try{const e=t.split("."),n=e.pop();let s=this._rawProps;for(const t of e)s[t]&&"object"==typeof s[t]||(s[t]={}),s=s[t];if(r&&"object"==typeof r&&!Array.isArray(r))try{s[n]=JSON.parse(JSON.stringify(r))}catch(e){s[n]={...r}}else s[n]=r}catch(e){console.warn(`Failed to store raw value for ${t}:`,e)}null!==r&&"object"==typeof r?"function"==typeof r&&r.__isReactiveProxy||r.__isReactiveProxy?i[s]=r:i[s]=this.makeReactive(r,n.concat(s)):i[s]=r}hasNested(e,t){const r=t.split(".");let n=e;for(let e=0;e<r.length;e++){const t=r[e];if(null==n||"object"!=typeof n)return!1;if(!(t in n))return!1;n=n[t]}return!0}share(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.share: key must be a non‑empty string.");if(this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another share key.`);const r=PPHP._shared.get(e);if(r)return[r.getter,r.setter];const n=Array.from(this._stateHierarchy.entries()).filter((([t,r])=>r.originalKey===e));n.length>0&&console.warn(`⚠️ PPHP Share Conflict Warning:\n • Creating shared state "${e}"\n • Found existing local state(s) with same key:\n`+n.map((([e,t])=>` - "${e}" (${t.hierarchy.join(" → ")})`)).join("\n")+`\n • Setter "set${e.charAt(0).toUpperCase()}${e.slice(1)}" will prioritize THIS shared state\n • Consider using different variable names to avoid confusion`),this._sharedStateMap.add(e);const s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=["__shared"];const[i,o]=this.state(e,t);this._currentProcessingHierarchy=s;const a=t=>{const r=i(),n="function"==typeof t?t(r):t;o(n);const s=[e,`__shared.${e}`,`app.${e}`];s.forEach((e=>{this._dirtyDeps.add(e)})),n&&"object"==typeof n&&Object.keys(n).forEach((e=>{s.forEach((t=>{this._dirtyDeps.add(`${t}.${e}`)}))})),this.scheduleFlush()};return PPHP._shared.set(e,{getter:i,setter:a}),[i,a]}getShared(e){let t=!1;const r=function(...r){const s=PPHP._shared.get(e);if(s)return s.getter();const i=[`__shared.${e}`,e,`app.${e}`];for(const e of i)if(n.hasNested(n.props,e)){const t=n.getNested(n.props,e);if(void 0!==t)return t}if(!t){t=!0;const r=(t=1)=>{setTimeout((()=>{const s=PPHP._shared.get(e);if(s){n._dirtyDeps.add(e),n._dirtyDeps.add(`__shared.${e}`);const t=s.getter();t&&"object"==typeof t&&Object.keys(t).forEach((t=>{n._dirtyDeps.add(`${e}.${t}`),n._dirtyDeps.add(`__shared.${e}.${t}`)})),n.scheduleFlush()}else t<10&&r(t+1)}),1===t?10:50)};r()}},n=this;r.set=t=>{let s=PPHP._shared.get(e);if(s)return s.setter(t);const i=r(),o="function"==typeof t?t(i):t;n.hasNested(n.props,"__shared")||n.setNested(n.props,"__shared",{});const a=`__shared.${e}`;n.setNested(n.props,a,o),n._dirtyDeps.add(e),n._dirtyDeps.add(a),n._sharedStateMap.add(e),o&&"object"==typeof o&&n.markNestedPropertiesDirty(e,o),n.scheduleFlush()},Object.defineProperties(r,{__isReactiveProxy:{value:!0,writable:!1,enumerable:!1},__pphp_key:{value:`__shared.${e}`,writable:!1,enumerable:!1},valueOf:{value:()=>r(),enumerable:!1},toString:{value:()=>String(r()),enumerable:!1}});return new Proxy(r,{apply:(e,t,r)=>e.apply(t,r),get(t,r,s){if("set"===r||"__isReactiveProxy"===r||"__pphp_key"===r||"valueOf"===r||"toString"===r)return Reflect.get(t,r,s);if("string"!=typeof r)return Reflect.get(t,r,s);{const s=t();if(s&&"object"==typeof s){let t=s[r];return t&&"object"==typeof t&&!t.__isReactiveProxy&&(t=n.makeReactive(t,["__shared",e,r])),t}}},set(t,r,s){if("set"===r||"__isReactiveProxy"===r||"__pphp_key"===r)return Reflect.set(t,r,s);if("string"==typeof r){const i=t();if(i&&"object"==typeof i)i[r]=s,n._dirtyDeps.add(`${e}.${String(r)}`),n._dirtyDeps.add(`__shared.${e}.${String(r)}`),n.scheduleFlush();else{const e={[r]:s};t.set(e)}return!0}return Reflect.set(t,r,s)},has(e,t){if("set"===t||"__isReactiveProxy"===t)return!0;const r=e();return r&&"object"==typeof r&&t in r}})}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure the build-time injector rewrote your declaration to pphp.state('foo', 0).");if(arguments.length<2&&(t=void 0),this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another state key.`);if(PPHP._shared.has(e)){const r=this._currentProcessingHierarchy||["app"],n=this.generateScopedKey(r,e);console.warn(`⚠️ PPHP State Conflict Warning:\n • Shared state "${e}" already exists\n • Creating local state at "${n}"\n • Setter "set${e.charAt(0).toUpperCase()}${e.slice(1)}" will prioritize SHARED state\n • Consider using different variable names to avoid confusion\n • Current shared value:`,PPHP._shared.get(e)?.getter(),"\n • New local value:",t)}const r=this._currentProcessingHierarchy||["app"],n=this.generateScopedKey(r,e);this._stateHierarchy.set(n,{originalKey:e,hierarchy:[...r],level:r.length}),this.hasNested(this.props,n)||this.setNested(this.props,n,t);const s=()=>this.getNested(this.props,n),i=e=>{const t=s(),r="function"==typeof e?e(t):e;this.setNested(this.props,n,r),this._dirtyDeps.add(n),r&&"object"==typeof r&&this.markNestedPropertiesDirty(n,r),this.scheduleFlush()},o=()=>s();Object.defineProperty(o,"value",{get:()=>s(),set:e=>i(e)}),Object.defineProperties(o,{valueOf:{value:()=>s()},toString:{value:()=>String(s())},__isReactiveProxy:{value:!0,writable:!1}}),Object.defineProperty(o,"__pphp_key",{value:n,writable:!1,enumerable:!1,configurable:!1});const a=s();if(null===a||"object"!=typeof a)return[o,i];const c=this;return[new Proxy(o,{apply:(e,t,r)=>Reflect.apply(e,t,r),get(e,t,r){if("value"===t)return s();if("__pphp_key"===t)return n;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,r);if("string"==typeof t){const r=s();if(r&&"object"==typeof r){const s=Object.prototype.hasOwnProperty.call(r,t),i=t in e&&void 0!==e[t];if(s||!i){let e=r[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...n.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,r);const i=s();return i&&"object"==typeof i?i[t]:void 0},set(e,t,r){if("value"===t)return i(r),!0;if("__isReactiveProxy"===t)return!0;const o=s();return o&&"object"==typeof o&&(o[t]=r,c._dirtyDeps.add(`${n}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in o)return!0;const r=s();return r&&"object"==typeof r&&t in r}}),i]}markNestedPropertiesDirty(e,t,r=new WeakSet){t&&"object"==typeof t&&!r.has(t)&&(r.add(t),Object.keys(t).forEach((n=>{const s=`${e}.${n}`;this._dirtyDeps.add(s),this._sharedStateMap.has(e.split(".")[0])&&this._dirtyDeps.add(`__shared.${s}`);const i=t[n];i&&"object"==typeof i&&!r.has(i)&&this.markNestedPropertiesDirty(s,i,r)})))}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return r=>{const n=e.get(r);if(void 0!==n)return n;const s=r in globalThis||t.some((e=>r in e));return e.set(r,s),s}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let r=e.replace(/\?\./g,".");const n=new Set,s=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=s.exec(r);)(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(r);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const o=e=>{let t="",r=0;for(;r<e.length;)if("`"===e[r])for(r++;r<e.length;)if("\\"===e[r])r+=2;else if("$"===e[r]&&"{"===e[r+1]){r+=2;let n=1,s=r;for(;r<e.length&&n;)"{"===e[r]?n++:"}"===e[r]&&n--,r++;t+=o(e.slice(s,r-1))+" "}else{if("`"===e[r]){r++;break}r++}else t+=e[r++];return t};r=o(r),r=r.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),r=r.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const a=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of r.match(c)??[]){const[r,...s]=t.split(".");if(!n.has(r)&&(0!==s.length||!PPHP._isBuiltIn(r)||!new RegExp(`\\.${r}\\b`).test(e))){if(0===s.length&&new RegExp(`\\b${t}\\s*\\(`).test(e)){if(r in globalThis&&"function"==typeof globalThis[r])continue;if(this.isInlineModuleFunction(r))continue;if(this.looksLikeFunctionName(r))continue}a.add(t)}}return a}isInlineModuleFunction(e){for(const[t,r]of this._inlineModuleFns.entries())if(r.has(e))return!0;if(this._currentProcessingHierarchy){const t=this._currentProcessingHierarchy.join("."),r=this._inlineModuleFns.get(t);if(r&&r.has(e))return!0}return!1}looksLikeFunctionName(e){return[/^[a-z][a-zA-Z0-9]*$/,/^[A-Z][a-zA-Z0-9]*$/,/^[a-z_][a-zA-Z0-9_]*$/,/^handle[A-Z]/,/^on[A-Z]/,/^get[A-Z]/,/^set[A-Z]/,/^is[A-Z]/,/^has[A-Z]/,/^can[A-Z]/,/^should[A-Z]/,/^will[A-Z]/].some((t=>t.test(e)))}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,r=PPHP._mustacheTest,n=this.props,s=new Set;this.qsa(e,"*").forEach((e=>{const n=this.detectElementHierarchy(e);for(const{name:i,value:o}of Array.from(e.attributes))if(o){if(r.test(o))for(const e of o.matchAll(t))this.extractScopedDependencies(e[1],n).forEach((e=>s.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(o,n).forEach((e=>s.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>r.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const r=e.parentElement;if(!r)continue;const n=this.detectElementHierarchy(r);for(const r of e.nodeValue.matchAll(t))this.extractScopedDependencies(r[1],n).forEach((e=>s.add(e)))}const o=Array.from(s).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of o){const t=e.split("."),r=t[t.length-1];if(this._sharedStateMap.has(r)&&!e.startsWith("__shared."))continue;let s=n;for(let e=0;e<t.length;e++){const r=t[e],n=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(r in s)||!n&&(null==s[r]||"object"!=typeof s[r])){const e=this._stateHierarchy.has(i);n&&e||(s[r]=n?void 0:{})}s=s[r]}}}async dispatchEvent(e,t,r={}){try{if(!e||"string"!=typeof e)return!1;const n=e.split(".")[0];if(e.includes(".")&&PPHP._shared.has(n)){const r=PPHP._shared.get(n);if(r){const s=r.getter();let i=JSON.parse(JSON.stringify(s||{}));const o=e.substring(n.length+1).split(".");let a=i;for(let e=0;e<o.length-1;e++)null==a[o[e]]&&(a[o[e]]={}),a=a[o[e]];const c=o[o.length-1],l=a[c],h="function"==typeof t?t(l):t;a[c]=h,r.setter(i);const d=`__shared.${e}`,p=`__shared.${n}`;return this._dirtyDeps.add(d),this._dirtyDeps.add(e),this._dirtyDeps.add(p),this._dirtyDeps.add(n),this._hydrated&&this.scheduleFlush(),d}}if(PPHP._shared.has(e)){const r=PPHP._shared.get(e);if(r){r.setter(t);const n=`__shared.${e}`;return this._dirtyDeps.add(n),this._dirtyDeps.add(e),this._hydrated&&this.scheduleFlush(),n}}let s=null;this._currentEffectContext&&(s=this._currentEffectContext.split(".")),!s&&r.from instanceof Element&&(s=this.detectElementHierarchy(r.from)),!s&&this._currentEventTarget instanceof Element&&(s=this.detectElementHierarchy(this._currentEventTarget)),s||(s=["app"]);const i=r.scope??"current";let o=s;Array.isArray(i)?o=i.length?i:["app"]:"parent"===i?o=s.slice(0,-1).length?s.slice(0,-1):["app"]:"root"===i||"app"===i?o=["app"]:"current"!==i&&(o=i.split("."));const a=this.resolveStatePath(e,o),c=a?.startsWith("app.")?a:e.startsWith("app.")?e:`${o.join(".")}.${e}`,l=this.hasNested(this.props,c)?this.getNested(this.props,c):void 0,h="function"==typeof t?t(l):t;if(this.setNested(this.props,c,h),this._dirtyDeps.add(c),this._dirtyDeps.add(`${c}.*`),c.startsWith("app.")){const e=c.slice(4),t=e.split(".")[0];PPHP._shared?.has(t)&&(this._dirtyDeps.add(e),this._dirtyDeps.add(`${e}.*`))}return this._hydrated&&this.scheduleFlush(),c}catch(e){return console.error("PPHP.dispatchEvent error:",e),!1}}determineCurrentComponentHierarchy(){const e=this.getEventSourceHierarchy();if(e.length>0)return e;if(this._currentEffectContext)return this._currentEffectContext.split(".");if(this._currentProcessingHierarchy)return[...this._currentProcessingHierarchy];if(this._currentExecutionScope){return this._currentExecutionScope.split(".")}const t=this.getCurrentScriptHierarchy();if(t.length>0)return t;const r=this.getActiveElementHierarchy();return r.length>0?r:["app"]}trackEventContext(e){e.currentTarget instanceof Element&&(this._currentEventTarget=e.currentTarget,this._eventContextStack.push(e.currentTarget),e.currentTarget.setAttribute("data-pphp-recent",Date.now().toString()),setTimeout((()=>{e.currentTarget?.removeAttribute?.("data-pphp-recent")}),1e3),setTimeout((()=>{this._eventContextStack.pop(),0===this._eventContextStack.length?this._currentEventTarget=null:this._currentEventTarget=this._eventContextStack[this._eventContextStack.length-1]}),0))}getEventSourceHierarchy(){try{let e=null;if(this._currentEventTarget&&(e=this._currentEventTarget),!e){const t=document.currentScript;t&&(e=t.closest("[pp-component]"))}if(!e){const t=document.activeElement;if(t instanceof Element){const r=t.closest("[pp-component]");r&&(e=r)}}if(!e){const t=document.querySelectorAll("[data-pphp-recent]");if(t.length>0){const r=Array.from(t).pop();r&&(e=r.closest("[pp-component]"))}}if(e)return this.buildComponentHierarchy(e)}catch(e){console.warn("Error in getEventSourceHierarchy:",e)}return[]}getCurrentScriptHierarchy(){try{const e=document.currentScript;if(e){const t=e.closest("[pp-component]");if(t)return this.buildComponentHierarchy(t)}}catch(e){}return[]}getActiveElementHierarchy(){try{const e=document.activeElement;if(e&&e!==document.body){const t=e.closest("[pp-component]");if(t)return this.buildComponentHierarchy(t)}}catch(e){}return[]}buildComponentHierarchy(e){const t=[];let r=e;for(;r;){const e=r.getAttribute("pp-component");e&&t.unshift(e),r=r.parentElement}return["app",...t]}resolveStatePath(e,t){if(PPHP._shared.has(e))return`__shared.${e}`;if(e.includes(".")&&this.hasNested(this.props,e))return e;const r=e.split(".")[0];if(PPHP._shared.has(r)){const t=`__shared.${e}`;if(this.hasNested(this.props,t))return t}for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r+1).join(".")+"."+e;if(this.hasNested(this.props,n))return n}for(const[t,r]of this._stateHierarchy.entries())if(r.originalKey===e||t.endsWith("."+e))return t;return t.length>1?t.join(".")+"."+e:e}getCurrentComponent(e){let t=null;if(e){if(t=document.querySelector(e),!t)return console.warn(`PPHP: Element with selector "${e}" not found`),null}else{if(this._currentEffectContext){const e=this._currentEffectContext.split(".");return e[e.length-1]}if(this._currentProcessingHierarchy&&this._currentProcessingHierarchy.length>0)return this._currentProcessingHierarchy[this._currentProcessingHierarchy.length-1];if(this._currentExecutionScope){const e=this._currentExecutionScope.split(".");return e[e.length-1]}const e=document.currentScript;if(e&&(t=e),!t){const e=this.determineCurrentComponentHierarchy();if(e.length>1)return e[e.length-1]}}if(t)return this.findComponentFromElement(t);const r=this.getFallbackComponent();return r||null}findComponentFromElement(e){const t=e.getAttribute("pp-component");if(t)return t;let r=e.parentElement;for(;r&&r!==document.documentElement;){const e=r.getAttribute("pp-component");if(e)return e;r=r.parentElement}return console.warn("PPHP: No pp-component attribute found for element or its ancestors",e),null}getFallbackComponent(){if(this._currentEventTarget){const e=this.findComponentFromElement(this._currentEventTarget);if(e)return e}const e=document.querySelector("[data-pphp-recent-interaction]");if(e){const t=this.findComponentFromElement(e);if(t)return t}const t=document.activeElement;if(t instanceof Element){const e=this.findComponentFromElement(t);if(e)return e}return null}getCurrentComponentHierarchy(){return this.determineCurrentComponentHierarchy()}async updateDocumentContent(e){const t=this.saveScrollPositions(),r=(new DOMParser).parseFromString(this.sanitizePassiveHandlers(e),"text/html");this.scrubTemplateValueAttributes(r),this.reconcileHead(r),this.resetProps(),await this.removeAllEventListenersOnNavigation(),this.ensurePageTransitionStyles();const n=async()=>{morphdom(document.body,r.body,{childrenOnly:!0}),await this.initReactiveOn(),this.restoreScrollPositions(t)};"startViewTransition"in document?await document.startViewTransition(n).finished:(await this.fadeOutBody(),await n(),await this.fadeInBody()),document.body.removeAttribute("hidden")}ensurePageTransitionStyles(){if(this._transitionStyleInjected)return;const e=document.createElement("style");e.id="pphp-page-transition-style",e.textContent="\n body.pphp-fade-out { opacity: 0; }\n body.pphp-fade-in { opacity: 1; }\n body.pphp-fade-in,\n body.pphp-fade-out { transition: opacity 0.25s ease; }\n ",document.head.appendChild(e),this._transitionStyleInjected=!0}async fadeOutBody(e=document.body){e.classList.add("pphp-fade-out");const t=e.getAnimations()[0];return t&&t.finished?t.finished.then((()=>{})):new Promise((e=>setTimeout(e,250)))}async fadeInBody(e=document.body){e.classList.remove("pphp-fade-out"),e.classList.add("pphp-fade-in");const t=e.getAnimations()[0];t&&t.finished?await t.finished:await new Promise((e=>setTimeout(e,250))),e.classList.remove("pphp-fade-in")}reconcileHead(e){const t="pp-dynamic-script",r="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove())),document.head.querySelectorAll(`[${t}]`).forEach((e=>e.remove())),Array.from(e.head.children).forEach((e=>{switch(e.tagName){case"SCRIPT":if(e.hasAttribute(t)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),t.textContent=e.textContent,document.head.appendChild(t)}break;case"META":{const t=e;if(t.getAttribute("charset")||"viewport"===t.name)break;const r=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,n=t.cloneNode(!0),s=document.head.querySelector(r);s?document.head.replaceChild(n,s):document.head.insertBefore(n,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const t=e.cloneNode(!0),r=document.head.querySelector("title");r?document.head.replaceChild(t,r):document.head.appendChild(t);break}case"LINK":{const t=e;if("icon"===t.rel){const e=t.cloneNode(!0),r=document.head.querySelector('link[rel="icon"]');r?document.head.replaceChild(e,r):document.head.appendChild(e)}else t.hasAttribute(r)&&document.head.appendChild(t.cloneNode(!0));break}}}))}scrubTemplateValueAttributes(e){e.querySelectorAll('input[value*="{{"], textarea[value*="{{"], select[value*="{{"],[checked*="{{"], [selected*="{{"]').forEach((e=>{e.hasAttribute("value")&&e.removeAttribute("value"),e.hasAttribute("checked")&&e.removeAttribute("checked"),e.hasAttribute("selected")&&e.removeAttribute("selected")}))}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const r=this.getElementKey(t);e[r]&&(t.scrollTop=e[r].scrollTop,t.scrollLeft=e[r].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const r=e,n=t;return r.value!==n.value&&(n.value=r.value),n.checked=r.checked,document.activeElement!==r||(null!=r.selectionStart&&(n.selectionStart=r.selectionStart,n.selectionEnd=r.selectionEnd),!1)},TEXTAREA(e,t){const r=e,n=t;return r.value!==n.value&&(n.value=r.value),document.activeElement!==r||(n.selectionStart=r.selectionStart,n.selectionEnd=r.selectionEnd,!1)},SELECT(e,t){const r=e;return t.selectedIndex=r.selectedIndex,document.activeElement!==r},VIDEO(e,t){const r=e,n=t;return n.currentTime=r.currentTime,r.paused?n.pause():n.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,r=e instanceof Document?e.body:e;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const r=new Function("event",t);e.addEventListener("wheel",r,{passive:!0})}})),this._wheelHandlersStashed=!0);const n=this.PRESERVE_HANDLERS;morphdom(t,r,{getNodeKey(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.hasAttribute("pp-sync-script")?`pp-sync-script:${t.getAttribute("pp-sync-script")}`:t.getAttribute("key")||void 0},onBeforeElUpdated(e,t){const r=e.tagName;if("SCRIPT"===r||e.hasAttribute("data-nomorph"))return!1;const s=n[r];return!s||s(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async attachWireFunctionEvents(e=document.body){this.handleHiddenAttribute(),this.handleAnchorTag();const t=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(",");if(!t)return;const r=this.qsa(e,t);for(const e of r)for(const t of this._eventHandlers){const r=e.getAttribute(t);if(!r)continue;const n=this.decodeEntities(r).trim();if(!n){e.removeAttribute(t);continue}const s=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(n))} }`;e.removeAttribute(t);const i=t.slice(2);e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,s)}this.handlePassiveWheelStashes(e instanceof Document?e:document)}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let r=t.value;for(;r.includes("&");){t.innerHTML=r;const e=t.value;if(e===r)break;r=e}return r};unwrapArrowBody=e=>{if(!e.trim())return"";const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{([\s\S]*)\}\s*$/);if(t){let e=t[1].trim();return e&&!e.endsWith(";")&&(e+=";"),e}const r=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(r){let t=e.substring(r[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let n=e.trim();return n&&!n.endsWith(";")&&(n+=";"),n};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,r,n)=>{const s=`${t}->${r}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(s)}, event);`})),t=t.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,r,n)=>{const s=`${t}::${r}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(s)}, event);`}));const{normalized:r,originalParam:n}=this.normalizeToArrow(t),s=this.renameEventParam(r,n);return this.replaceThisReferences(s)}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const r=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(r)?r:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const r=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(r,((e,t,r)=>{const n=r[t-1],s=r[t+e.length];return n&&/[\w$]/.test(n)||s&&/[\w$]/.test(s)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,r){const n=e.getAttribute("pp-debounce"),s=n?this.parseTime(n):0,i=e.getAttribute("pp-before-request")??"",o=e.getAttribute("pp-after-request")??"",a=PPHP._cancelableEvents,c=async n=>{a.has(t)&&n.cancelable&&n.preventDefault();try{i&&await this.invokeHandler(e,i,n),await this.invokeHandler(e,r,n),o&&!o.startsWith("@close")&&await this.invokeHandler(e,o,n)}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!a.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,d=e=>{if(s>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const r=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),s);PPHP._debounceTimers.set(h,r)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),d(e)}),l):e.addEventListener(t,d,l)}debounce(e,t=300,r=!1){let n;return function(...s){const i=this;n&&clearTimeout(n),n=setTimeout((()=>{n=null,r||e.apply(i,s)}),t),r&&!n&&e.apply(i,s)}}async invokeHandler(e,t,r){const n=this._currentProcessingElement;this._currentProcessingElement=e;try{const n=t.trim();let s=this._handlerCache.get(n);s||(s=this.parseHandler(n),this._handlerCache.set(n,s)),await this.executeHandler(s,e,r,n)}catch(r){this.handleInvokeError(r,t,e)}finally{this._currentProcessingElement=n,this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const r=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(r)return{type:"call",name:r[1],args:r[2],isAsync:this.isAsyncFunction(r[1])};const n=t.match(/^(\w+)$/);return n?{type:"simple",name:n[1],isAsync:this.isAsyncFunction(n[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,r="",n=0;for(let s=0;s<e.length-1;s++){const i=e[s],o=e[s+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===r&&"\\"!==e[s-1])t=!1,r="";else if(!t&&("("===i&&n++,")"===i&&n--,"="===i&&">"===o&&n>=0))return!0}else t=!0,r=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let r=e.substring(t+2).trim();return r.startsWith("{")&&r.endsWith("}")&&(r=r.slice(1,-1).trim()),{type:"arrow",body:r,isAsync:e.includes("async")||this.containsAwait(r)}}findArrowIndex(e){let t=!1,r="";for(let n=0;n<e.length-1;n++){const s=e[n],i=e[n+1];if(t||'"'!==s&&"'"!==s&&"`"!==s){if(t&&s===r&&"\\"!==e[n-1])t=!1;else if(!t&&"="===s&&">"===i)return n}else t=!0,r=s}return-1}async executeArrowHandler(e,t,r){const n=this.parseStatements(e.body);let s=!1;for(const e of n)await this.executeSingleStatement(e,t,r)&&(s=!0);s||await this.executeDynamic(e.body,t,r)}async executeComplexHandler(e,t,r){await this.executeDynamic(e.body,t,r)}parseStatements(e){const t=[];let r="",n=0,s=!1,i="";for(let o=0;o<e.length;o++){const a=e[o];s||'"'!==a&&"'"!==a&&"`"!==a?s&&a===i&&"\\"!==e[o-1]&&(s=!1,i=""):(s=!0,i=a),s||("("!==a&&"{"!==a&&"["!==a||n++,")"!==a&&"}"!==a&&"]"!==a||n--,";"!==a||0!==n)?r+=a:r.trim()&&(t.push(r.trim()),r="")}return r.trim()&&t.push(r.trim()),t}async executeInlineModule(e,t,r,n,s){if(t&&t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t);null!==r&&"object"==typeof r?await this.callInlineModule(e,{...r}):await this.callInlineModule(e,r)}else try{const n=this.detectElementHierarchy(r),s=this._createScopedPropsContext(n),i=this.makeScopedEvaluator(t,n)(s);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:r,event:n})}else await this.handleParsedCallback(r,s,n)}async executeSingleStatement(e,t,r){const n=e.trim();if(!n)return!1;const s=n.match(/^\(\s*\)\s*=>\s*(.+)$/);if(s)return this.executeSingleStatement(s[1],t,r);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(n))return await this.executeDynamic(n,t,r),!0;const i=n.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,s]=i,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(e,o);let c=[];if(""!==s.trim())try{c=JSON5.parse(`[${s}]`)}catch{try{const e=this._createScopedPropsContext(o),t=this.getOrCreateProxy(e),n=/\bevent\b/.test(s)?s.replace(/\bevent\b/g,"_evt"):s;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${n} ]; }`)(r,t,e)}catch(e){c=[]}}if(a){const e=this.getScopedFunction(a,o);if(e)return c.length>0?await e(...c):await this.executeInlineModule(a,s,t,r,n),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,n,r),!0}const o=n.match(/^(\w+)$/);if(o){const e=o[1],n=this.detectElementHierarchy(t),s=this.resolveFunctionName(e,n);if(s){if(this.getScopedFunction(s,n))return await this.handleParsedCallback(t,`${s}()`,r),!0}if(s){const e=globalThis[s];if("function"==typeof e)return e.call(globalThis,r),!0}return await this.handleParsedCallback(t,`${e}()`,r),!0}return await this.executeDynamic(n,t,r),!0}async executeCallHandler(e,t,r,n){const{name:s,args:i}=e,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(s,o);if(a){if(this.getScopedFunction(a,o))return void await this.executeInlineModule(a,i||"",t,r,n);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,r)}await this.handleParsedCallback(t,n,r)}resolveFunctionName(e,t){if(e.startsWith("set")){const t=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(t))return e}if(t)for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,r){const{name:n}=e,s=this.detectElementHierarchy(t),i=this.resolveFunctionName(n,s);if(i){if(this.getScopedFunction(i,s))return void await this.handleParsedCallback(t,`${i}()`,r);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,r)}await this.handleParsedCallback(t,`${n}()`,r)}async executeHandler(e,t,r,n){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,r);break;case"call":await this.executeCallHandler(e,t,r,n);break;case"simple":await this.executeSimpleHandler(e,t,r);break;case"complex":await this.executeComplexHandler(e,t,r);break;default:await this.handleParsedCallback(t,n,r)}}async executeGlobalFunction(e,t,r,n){if(t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t)??{};e.call(globalThis,{...r})}else{const s=this.detectElementHierarchy(r),i=this._createScopedPropsContext(s),o=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(r,n,o,i,e)}else e.call(globalThis,n)}async executeDynamic(e,t,r){const n=this.detectElementHierarchy(t),s=this._createScopedPropsContext(n),i=this.getOrCreateProxy(s),o=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await o.call(t,r,i,s)}finally{this.scheduleFlush()}}static AsyncFunction=Object.getPrototypeOf((async()=>{})).constructor;getOrCreateEvaluator(e){let t=this._evaluatorCache.get(e);return t||(t=this.makeSafeEvaluator(e),this._evaluatorCache.set(e,t)),t}getOrCreateProxy(e){let t=this._handlerProxyCache.get(e);return t||(t=this.createHandlerProxy(e),this._handlerProxyCache.set(e,t)),t}createHandlerProxy(e){const t=this._currentProcessingHierarchy||["app"],r={alert:window.alert.bind(window),confirm:window.confirm.bind(window),prompt:window.prompt.bind(window),console:window.console,setTimeout:window.setTimeout.bind(window),setInterval:window.setInterval.bind(window),clearTimeout:window.clearTimeout.bind(window),clearInterval:window.clearInterval.bind(window),fetch:window.fetch.bind(window)};return new Proxy(e,{get:(e,n,s)=>{if("string"==typeof n){if(r.hasOwnProperty(n))return r[n];const i=this.getScopedFunction(n,t);if(i)return i;if(n in e){const t=Reflect.get(e,n,s),r=globalThis[n];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(n)&&typeof t!=typeof r))return t}if(n in globalThis&&!r.hasOwnProperty(n)){const e=globalThis[n];return"function"==typeof e&&/^[a-z]/.test(n)?e.bind(globalThis):e}}return Reflect.get(e,n,s)},set:(e,t,r,n)=>Reflect.set(e,t,r,n),has:(e,t)=>{if("string"==typeof t){const n=this._currentProcessingHierarchy||["app"];return r.hasOwnProperty(t)||!!this.getScopedFunction(t,n)||t in e||t in globalThis}return t in e||t in globalThis}})}isAsyncFunction(e){const t=this._inlineModuleFns.get(e)||globalThis[e];return t&&("AsyncFunction"===t.constructor.name||t.toString().includes("async "))}containsAwait(e){return/\bawait\s+/.test(e)}handleInvokeError(e,t,r){const n=e instanceof Error?e.message:String(e),s=r.tagName+(r.id?`#${r.id}`:"");console.error(`Handler execution failed on ${s}:\nHandler: "${t}"\nError: ${n}`,e),r.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:r},bubbles:!0}))}async handleParsedCallback(e,t,r){const{funcName:n,data:s}=this.parseCallback(e,t);if(!n)return;const i=Array.isArray(n)?n:[n],o=this.detectElementHierarchy(e);let a;for(const e of i){const t=this.resolveLocalFunction(e,o);if(t){a=t;break}}if(a){const t=e.hasAttribute("pp-after-request"),n="@close"===e.getAttribute("pp-after-request");let o={args:Array.isArray(s.args)?s.args:[],element:e,data:s,event:r};if(t&&!n){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};o={...o,...e}}try{return void await a.call(this,o)}catch(e){return void console.error(`❌ Error executing function ${i[0]}:`,e)}}this.shouldCallServer(i[0],o)?(this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(n)?n[0]:n,s)):console.warn(`⚠️ Function ${i[0]} not found and not calling server`)}shouldCallServer(e,t){return!!!this.resolveLocalFunction(e,t)}resolveLocalFunction(e,t){const r=this.getScopedFunction(e,t);if(r)return r;for(const[,t]of this._inlineModuleFns.entries())if(t.has(e))return t.get(e);return"function"==typeof this[e]?this[e]:"function"==typeof window[e]?window[e]:void 0}async handleUndefinedFunction(e,t,r){const n={callback:await this.encryptCallbackName(t),...r},s=this.createFetchOptions(n),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const n=new URL(window.location.href);let o="",a="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(o=await this.fetchFileWithData(n.href,t,l,r),a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(n.href,s);if(o=await e.text(),this.getRedirectUrl(o))return void await this.redirect(this.getRedirectUrl(o)||"");if(a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",d=e.getAttribute("pp-after-request")||"";if((h||d&&c.success)&&this.restoreSuspenseElement(e),h||d){let e="";if(c.success){e=o.replace(a,"")}else e=o;if(this.appendAfterbegin(e),!d&&!c.success)return}if(d&&c.success){this.handleAfterRequest(d,a);const e=o.replace(a,"");return this.appendAfterbegin(e),a}if("@close"===d)return c.success?a:void 0;const p=await this.fetch(n.href,i),u=await p.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(o,u,a,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const r=this.parseJson(e),n=t?this.parseJson(t):null,s=r.targets;Array.isArray(s)&&s.forEach((e=>{const{id:t,...r}=e,s=document.querySelector(t);let i={};if(n){for(const t in r)if(r.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===r[t]&&(i[t]=e.responseKey?n[e.responseKey]:n.response);break;default:i[t]=r[t]}}else i=r;s&&this.updateElementAttributes(s,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,r)=>` data-onwheel-code="${this.decodeEntities(r).replace(/"/g,""")}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{const t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null,t&&(e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t))}))}async handleResponseRedirectOrUpdate(e,t,r,n){const s=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,r,n),o=(new DOMParser).parseFromString(s,"text/html");i&&o.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(o.body.outerHTML)}getUpdatedHTMLContent(e,t,r){const n=document.createElement("div");if(n.id="afterbegin-8D95D",r&&t?.success){const t=e.replace(r,"");n.innerHTML=t}else n.innerHTML=e;return n.innerHTML?n:null}async updateBodyContent(e){try{const t=this.saveScrollPositions();this.saveElementState();const r=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(r),await this.appendCallbackResponse(r),await this.populateDocumentBody(r),await this.removeAllEventListenersOnNavigation(),await this.initReactiveOn(),this.restoreScrollPositions(t),document.body.removeAttribute("hidden")}catch(e){console.error("updateBodyContent failed:",e)}}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const r in t)if(t.hasOwnProperty(r))switch(r){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[r]=this.decodeHTML(t[r]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[r].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[r].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[r]));break;case"removeAttribute":e.removeAttribute(t[r]);break;case"className":e.className=this.decodeHTML(t[r]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[r]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[r]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[r]));break;case"classList.replace":const[n,s]=this.decodeHTML(t[r]).split(",");e.classList.replace(n,s);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[r]);break;case"style":Object.assign(e.style,t[r]);break;case"value":e.value=this.decodeHTML(t[r]);break;case"checked":e.checked=t[r];break;default:e.setAttribute(r,this.decodeHTML(t[r]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let r=document.getElementById(t);r?(r.innerHTML=e,document.body.insertAdjacentElement("afterbegin",r)):(r=document.createElement("div"),r.id=t,r.innerHTML=e,document.body.insertAdjacentElement("afterbegin",r))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const r=(e,t)=>{for(const r in t)t.hasOwnProperty(r)&&("textContent"===r?e.textContent=t[r]:"innerHTML"===r?e.innerHTML=t[r]:"disabled"===r?!0===t[r]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(r,t[r]));for(const r of Array.from(e.attributes))t.hasOwnProperty(r.name)||e.removeAttribute(r.name)},n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const n=this.parseJson(e);r(t,n)}else s(t,e);t.removeAttribute("pp-original-state")}}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?n(e,t):r(e,t)};try{const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const n=this.parseJson(t);r(e,n)}}}const s=new FormData(e),i={};if(s.forEach(((e,t)=>{i[t]=e})),n(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(s.targets){s.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&i(n,r)}));const{targets:t,...n}=s;r(e,n)}else{const{empty:t,...n}=s;r(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,r,n={}){const s=new FormData,i=r.files;if(i)for(let e=0;e<i.length;e++)s.append("file[]",i[e]);s.append("callback",t);for(const e in n)n.hasOwnProperty(e)&&s.append(e,n[e]);const o=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:s});return await o.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const r=(e,t)=>{for(const r in t)if(t.hasOwnProperty(r))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(this.isJsonLike(e)){const r=this.parseJson(e);"disabled"!==r.onsubmit&&this.updateElementAttributes(t,r),r.targets&&r.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&s(n,r)}))}else n(t,e)}},n=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},s=(e,t)=>{e instanceof HTMLFormElement?r(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const n=this.parseJson(t);if(n)if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=n;this.updateElementAttributes(e,o),r(e,s)}else if(n.targets){n.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&s(n,r)}));const{targets:t,...r}=n;this.updateElementAttributes(e,r)}else{if("disabled"===n.empty&&""===e.value)return;const{empty:t,...r}=n;this.updateElementAttributes(e,r)}}else if(t)n(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),n={};t.forEach(((e,t)=>{n[t]=e})),r(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let r=0;r<e.attributes.length;r++){const n=e.attributes[r];t[n.name]=n.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const r=e.id;r&&(t=document.querySelector(`[form="${r}"]`)),r&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,r)=>{e[r]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let r={};const n=e.closest("form");if(n){new FormData(n).forEach(((e,t)=>{const n=this.clean(e);r[t]?r[t]=Array.isArray(r[t])?[...r[t],n]:[r[t],n]:r[t]=n}))}else e instanceof HTMLInputElement?r=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(r[e.name]=e.value);if("args"in r){const e=r.args,t=Array.isArray(e)&&e.every((e=>null==e||""===e));(null==e||""===e||t)&&delete r.args}const s=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(!s)return{funcName:t.trim(),data:r};const i=s[1].trim(),o=s[2].trim();if(""===o)return{funcName:i,data:r};const a=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(o.startsWith("{")&&o.endsWith("}")||o.startsWith("[")&&o.endsWith("]"))if(this.isJsonLike(o))try{const e=this.parseJson(o);Array.isArray(e)?r.args=e:e&&"object"==typeof e&&(r={...r,...e})}catch(e){console.error("Error parsing JSON args:",e),r.rawArgs=o}else try{const e=this.evaluateJavaScriptObject(o);Array.isArray(e)?r.args=e:e&&"object"==typeof e?r={...r,...e}:r.rawArgs=o}catch(e){console.error("Error evaluating JS object args:",e),r.rawArgs=o}else if(/^[\s\d"'[\{]/.test(o))try{const e=new Function(`return [${o}];`)();r.args=Array.isArray(e)?e:[e]}catch{a.test(o)?r.args=o.split(a).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):r.args=[o.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(o)(this.props);r.args=[e]}catch{r.args=o.split(a).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return Array.isArray(r.args)&&(r.args=r.args.filter((e=>!(null==e||""===e))),0===r.args.length&&delete r.args),{funcName:i,data:r}}clean(e){if("string"!=typeof e)return e;let t=e.replace(/"/g,'"').trim();/^"(?:[^"\\]|\\.)*"$/.test(t)&&(t=t.slice(1,-1));try{return JSON.parse(t)}catch{}if(/^-?\d+(\.\d+)?$/.test(t)&&!/^0\d/.test(t)){const e=Number(t);if(!Number.isNaN(e))return e}return t}evaluateJavaScriptObject(e){try{const t=this.getOrCreateProxy(this.props);return new Function("proxy","Date","Math","JSON",`\n with (proxy) {\n return ${e};\n }\n `).call(null,t,Date,Math,JSON)}catch(e){throw console.error("Failed to evaluate JavaScript object:",e),e}}handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const r=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=r?r.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}handleInputAppendParams(e,t){const r=e.getAttribute("pp-append-params"),n=e.getAttribute("pp-append-params-sync");if("true"===r){if("true"===n){const t=e.name||e.id;if(t){const r=new URL(window.location.href),n=new URLSearchParams(r.search);n.has(t)&&(e.value=n.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,r=t.value,n=new URL(window.location.href),s=new URLSearchParams(n.search),i=t.name||t.id;if(i){r?s.set(i,r):s.delete(i);const e=s.toString()?`${n.pathname}?${s.toString()}`:n.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),r=this.handleElementVisibility.bind(this),n=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",r))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",n)))}handleVisibilityElementAttribute(e,t,r){const n=e.getAttribute(t);if(n)if(this.isJsonLike(n)){r(e,this.parseJson(n))}else{const r=this.parseTime(n);if(r>0){const n="pp-visibility"===t?"visibility":"display",s="visibility"===n?"hidden":"none";this.scheduleChange(e,r,n,s)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,r,n,s){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[r]=n,this.scheduleChange(e,i,r,s),o>0&&this.scheduleChange(e,i+o,r,n)):o>0&&this.scheduleChange(e,o,r,n)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,r=t.getAttribute("href"),n=t.getAttribute("target");if(r&&"_blank"!==n&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(r)&&!r.startsWith(window.location.origin))window.location.href=r;else{const e=t.getAttribute("pp-append-params");let n="";if(r.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[i,o]=r.split("#");o&&(s=`#${o}`);new URLSearchParams(i.split("?")[1]).forEach(((e,r)=>{t.set(r,e)})),n=`${e.pathname}?${t.toString()}${s}`}else{const[e,t]=r.split("#");n=`${e}${t?`#${t}`:""}`}history.pushState(null,"",n);const s=r.indexOf("#");if(-1!==s){const e=r.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href),r=await t.text();if(!t.ok)return await this.updateDocumentContent(r),void console.error(`Navigation error: ${t.status} ${t.statusText}`);const n=r.match(this._redirectRegex);if(n&&n[1])return void await this.redirect(n[1]);await this.updateDocumentContent(r)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let r=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${r}']`);if(t)return t;if("/"===r)break;const n=r.lastIndexOf("/");r=n<=0?"/":r.substring(0,n)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:r,fadeOut:n}=this.parseTransition(e);await this.fadeOut(t,n),t.innerHTML=e.innerHTML,this.fadeIn(t,r)}parseTransition(e){let t=250,r=250;const n=e.querySelector("[pp-loading-transition]"),s=n?.getAttribute("pp-loading-transition");if(s){const e=this.parseJson(s);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),r=this.parseTime(e.fadeOut??r)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",s)}return{fadeIn:t,fadeOut:r}}fadeOut(e,t){return new Promise((r=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",r()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&(console.log("Aborting active request..."),this._activeAbortController.abort(),this._activeAbortController=null)}async fetch(e,t,r=!1){let n;return r?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,n=this._activeAbortController):n=new AbortController,fetch(e,{...t,signal:n.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){try{if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}catch{return!1}}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,r,n){setTimeout((()=>{requestAnimationFrame((()=>{e.style[r]=n}))}),t)}async fetchFunction(e,t={},r=!1){let n=null;try{r&&this._activeAbortController&&(console.log("Aborting previous request..."),this._activeAbortController.abort(),this._activeAbortController=null),n=new AbortController,r&&(this._activeAbortController=n);const s={callback:await this.encryptCallbackName(e),...t},i=window.location.href;let o;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const r=s[t];r instanceof File?e.append(t,r):r instanceof FileList?Array.from(r).forEach((r=>e.append(t,r))):e.append(t,r)})),o={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e,signal:n.signal}}else o={signal:n.signal,...this.createFetchOptions(s)};const a=await fetch(i,o);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const c=await a.text();n&&this._activeAbortController===n&&(this._activeAbortController=null);try{return JSON.parse(c)}catch{return c}}catch(e){if(n&&this._activeAbortController===n&&(this._activeAbortController=null),e instanceof Error&&"AbortError"===e.name)return console.log("Request was cancelled"),{cancelled:!0};throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const r=e.length?e:["true"],n=await this.fetch(window.location.href,this.createFetchOptions({pphpSync71163:!0,selectors:r,secondRequestC69CD:!0,...this.getUrlParams()}));let s;if(n.headers.get("content-type")?.includes("application/json")){s=(await n.json()).fragments}else s={[r[0]]:await n.text()};const i=`<body>${Object.values(s).join("")}</body>`,o=(new DOMParser).parseFromString(i,"text/html");await this.initReactiveOn(o,{wire:!1});const a=[];r.forEach((e=>{const t=`[pp-sync="${e}"]`,r=document.querySelectorAll(t),n=o.body.querySelector(t);n&&r.forEach((e=>{morphdom(e,n,{childrenOnly:!0,onBeforeElUpdated:(e,t)=>{const r=e.tagName,n=this.PRESERVE_HANDLERS[r];return!n||n(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0),getNodeKey:e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.getAttribute("key")||t.getAttribute("pp-key")||void 0}}),a.push(e)}))})),this.restoreElementState(),this.restoreScrollPositions(t);for(const e of a)await this.attachWireFunctionEvents(e)}catch(e){console.error("pphp.sync failed:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),r=await t.text();await this.updateBodyContent(r)}copyCode(e,t,r,n,s="img",i=2e3){if(!(e instanceof HTMLElement))return;const o=e.closest(`.${t}`)?.querySelector("pre code"),a=o?.textContent?.trim()||"";a?navigator.clipboard.writeText(a).then((()=>{const t=e.querySelector(s);if(t)for(const[e,r]of Object.entries(n))e in t?t[e]=r:t.setAttribute(e,r);setTimeout((()=>{if(t)for(const[e,n]of Object.entries(r))e in t?t[e]=n:t.setAttribute(e,n)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){const r={...this.state,...e};if(JSON.stringify(r)!==JSON.stringify(this.state)&&(this.state=r,this.listeners.forEach((e=>e(this.state))),this.saveState(),t)){const e=localStorage.getItem(this.STORAGE_KEY);e&&e!==this.lastSyncedState&&(this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e}),this.lastSyncedState=e)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t}),this.lastSyncedState=t}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const r=this.params;r.set(e,t),this.updateURL(r)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const r in e){const n=e[r];null!==n&&t.set(r,n)}this.updateURL(t,!0)}updateURL(e,t=!1){const r=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",r):history.pushState(null,"",r),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
|