create-prisma-php-app 3.4.5 → 3.4.7

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.
@@ -26,9 +26,19 @@ class PHPX implements IPHPX
26
26
  */
27
27
  protected array $attributesArray = [];
28
28
 
29
+ /**
30
+ * @var array|null Component hierarchy set during rendering
31
+ */
32
+ protected static ?array $currentHierarchy = null;
33
+
34
+ /**
35
+ * @var string|null Current component ID
36
+ */
37
+ protected static ?string $currentComponentId = null;
38
+
29
39
  /**
30
40
  * Constructor to initialize the component with the given properties.
31
- *
41
+ *
32
42
  * @param array<string, mixed> $props Optional properties to customize the component.
33
43
  */
34
44
  public function __construct(array $props = [])
@@ -37,6 +47,74 @@ class PHPX implements IPHPX
37
47
  $this->children = $props['children'] ?? '';
38
48
  }
39
49
 
50
+ /**
51
+ * Set the component hierarchy and current component ID (called by TemplateCompiler during rendering)
52
+ *
53
+ * @param array $hierarchy The component hierarchy
54
+ * @param string $currentId The current component ID
55
+ */
56
+ public static function setRenderingContext(array $hierarchy, string $currentId): void
57
+ {
58
+ self::$currentHierarchy = $hierarchy;
59
+ self::$currentComponentId = $currentId;
60
+ }
61
+
62
+ /**
63
+ * Get the parent component ID from the current hierarchy.
64
+ *
65
+ * @return string|null The parent component ID, or null if no parent exists
66
+ */
67
+ protected function getParentComponent(): ?string
68
+ {
69
+ $fullHierarchy = $this->getComponentHierarchy();
70
+
71
+ if (count($fullHierarchy) >= 2) {
72
+ return $fullHierarchy[count($fullHierarchy) - 2];
73
+ }
74
+
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * Get the current component ID.
80
+ *
81
+ * @return string|null The current component ID, or null if not in component context
82
+ */
83
+ protected function getCurrentComponent(): ?string
84
+ {
85
+ return self::$currentComponentId;
86
+ }
87
+
88
+ /**
89
+ * Get the full component hierarchy as an array.
90
+ * Useful for building complete hierarchy paths for JavaScript.
91
+ *
92
+ * @return array Array of component IDs from root to current
93
+ */
94
+ protected function getComponentHierarchy(): array
95
+ {
96
+ $hierarchy = self::$currentHierarchy ?? ['app'];
97
+
98
+ if (self::$currentComponentId && !in_array(self::$currentComponentId, $hierarchy)) {
99
+ $hierarchy[] = self::$currentComponentId;
100
+ }
101
+
102
+ return $hierarchy;
103
+ }
104
+
105
+ /**
106
+ * Generate JavaScript code to set the correct component hierarchy for dispatchEvent.
107
+ *
108
+ * @return string JavaScript code to set the hierarchy
109
+ */
110
+ protected function getHierarchyScript(): string
111
+ {
112
+ $hierarchy = $this->getComponentHierarchy();
113
+ $hierarchyJson = json_encode($hierarchy);
114
+
115
+ return "pphp._currentProcessingHierarchy = {$hierarchyJson};";
116
+ }
117
+
40
118
  /**
41
119
  * Combines and returns the CSS classes for the component.
42
120
  *
@@ -413,17 +413,24 @@ class TemplateCompiler
413
413
  $mapping = self::selectComponentMapping($componentName);
414
414
  $instance = self::initializeComponentInstance($mapping, $incomingProps);
415
415
 
416
+ $baseId = 's' . base_convert(sprintf('%u', crc32($mapping['className'])), 10, 36);
417
+ $idx = self::$componentInstanceCounts[$baseId] ?? 0;
418
+ self::$componentInstanceCounts[$baseId] = $idx + 1;
419
+ $sectionId = $idx === 0 ? $baseId : "{$baseId}{$idx}";
420
+
421
+ $originalStack = self::$sectionStack;
422
+ self::$sectionStack[] = $sectionId;
423
+
416
424
  $childHtml = '';
417
425
  foreach ($node->childNodes as $c) {
418
426
  $childHtml .= self::processNode($c);
419
427
  }
420
428
 
429
+ self::$sectionStack = $originalStack;
430
+
421
431
  $instance->children = trim($childHtml);
422
432
 
423
- $baseId = 's' . base_convert(sprintf('%u', crc32($mapping['className'])), 10, 36);
424
- $idx = self::$componentInstanceCounts[$baseId] ?? 0;
425
- self::$componentInstanceCounts[$baseId] = $idx + 1;
426
- $sectionId = $idx === 0 ? $baseId : "{$baseId}{$idx}";
433
+ PHPX::setRenderingContext($originalStack, $sectionId);
427
434
 
428
435
  $html = $instance->render();
429
436
  $html = self::preprocessFragmentSyntax($html);
@@ -1 +1 @@
1
- (()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let a=i;s.has(t)&&(void 0===a?a={passive:!0}:"boolean"==typeof a?a={capture:a,passive:!0}:a&&void 0===a.passive&&(a={...a,passive:!0})),n.has(this)||n.set(this,new Map);const o=n.get(this),c=o.get(t)||new Set;c.add(r),o.set(t,c),e.call(this,t,r,a)},EventTarget.prototype.removeEventListener=function(e,s,r){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t.delete(s),0===t.size&&n.get(this).delete(e)}t.call(this,e,s,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(n.has(this)){if(e){const s=n.get(this).get(e);if(!s)return;return s.forEach((n=>t.call(this,e,n))),void n.get(this).delete(e)}n.get(this).forEach(((e,n)=>{e.forEach((e=>t.call(this,n,e)))})),n.delete(this)}}})(),function(){const e=console.log;console.log=(...t)=>{const n=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,n)}}();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;_currentTemplateHierarchy=null;_inlineModuleFns=new Map;_currentExecutionScope=null;_transitionStyleInjected=!1;_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"))),n=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...n].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.props=this.makeReactive(this._rawProps),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 n=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",s=e.getAttribute(`pp-${n}`)??null;let r=null;if(s){const t=s.replace(/^{\s*|\s*}$/g,""),n=this.detectElementHierarchy(e);try{r=!!this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n))}catch{r=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:n,expr:s,visible:!e.hasAttribute("hidden"),result:r})})),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:n,idxName:s,arrExpr:r}=this.parseForExpression(e);let i=0;const a=e.previousSibling;if(a?.nodeType===Node.COMMENT_NODE&&"pp-for"===a.data){let e=a.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));)i+=1,e=e.nextSibling}return{"#":t,"(expr)":r,item:n||"(default)",idx:s||"(—)",rendered:i}}));console.table(t)}console.groupEnd(),console.groupEnd()}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 n=0;n<this._bindings.length;n+=t)this._bindings.slice(n,n+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 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("."),n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:s,exp:r}=JSON.parse(n);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(s),(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)),n=(new TextEncoder).encode(e),s=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,n);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(s)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,n]=e.split(":",2),s=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),r=Uint8Array.from(atob(n),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:s},PPHP._cryptoKey,r);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,n=e.getAttribute("pp-init-state").trim();if(!n)return void e.removeAttribute("pp-init-state");try{t=JSON5.parse(n)}catch(e){return void console.error("Bad pp-init-state JSON:",n)}const s=this.detectElementHierarchy(e),r=this._currentProcessingHierarchy;this._currentProcessingHierarchy=s,Object.entries(t).forEach((([e,t])=>{this.state(e,t)})),this._currentProcessingHierarchy=r,e.removeAttribute("pp-init-state")}))}detectComponentHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return t.length>0?t:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const n=this._refs.get(e)??[];if(null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const n=Array.isArray(t),s=n?t:[],r=n&&0===s.length,i=this._currentProcessingHierarchy||["app"],a=s.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(t){const e=t[1];return this.resolveDependencyPath(e,i)}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),o=s.filter((e=>"function"==typeof e&&!e.__pphp_key)),c=new Set(a),l=new Map;for(const e of a)try{l.set(e,this.getResolvedValue(e))}catch(t){l.set(e,void 0)}const h=new Map;for(const e of o)try{const t=e();h.set(e,t)}catch(t){h.set(e,Symbol("error"))}let d=0,p=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const u=PPHP._effectCleanups,f=()=>{const t=u.get(f);if(t){try{t()}catch(e){console.error("cleanup error:",e)}u.delete(f)}const s=performance.now();if(s-p<16)requestAnimationFrame((()=>{performance.now()-p>=16&&f()}));else{if(p=s,++d>100)throw console.error("PPHP: effect exceeded 100 runs - possible infinite loop"),console.error("Effect function:",e.toString()),console.error("Dependencies:",Array.from(c)),new Error("PPHP: effect ran >100 times — possible loop");if(!r){let e=!1;const t=[];if(a.length>0)for(const n of a)try{const s=this.getResolvedValue(n),r=l.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push(n),l.set(n,s))}catch(s){e=!0,t.push(n),l.set(n,void 0)}for(const n of o)try{const s=n(),r=h.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push("(function)"),h.set(n,s))}catch(s){h.get(n)!==Symbol("error")&&(e=!0,t.push("(function-error)"),h.set(n,Symbol("error")))}if(n&&(a.length>0||o.length>0)&&!e)return}try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(t){console.error("effect error:",t),console.error("Effect function:",e.toString())}}};Object.assign(f,{__deps:c,__static:r,__functionDeps:o,__hierarchy:i,__isEffect:!0});try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(e){console.error("effect error (initial):",e)}const m=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return r?this._effects.add(f):m.add(f),()=>{const e=u.get(f);if(e){try{e()}catch(e){console.error("cleanup error:",e)}u.delete(f)}this._effects.delete(f),this._pendingEffects.delete(f)}}resolveDependencyPath(e,t){const n=e.startsWith("app.")?e.substring(4):e,s=n.split(".")[0];if(PPHP._shared.has(s))return n;const r=t.join(".")+"."+e;if(this.hasNested(this.props,r))return r;if(this.hasNested(this.props,e))return e;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?s+"."+e:e;if(this.hasNested(this.props,r))return r}return e}getResolvedValue(e){e.split(".")[0];const t=(e.startsWith("app.")?e.substring(4):e).split("."),n=t[0],s=PPHP._shared.get(n);if(s){if(1===t.length)return s.getter();{const e=s.getter(),n=t.slice(1).join(".");return this.getNested(e,n)}}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._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._currentProcessingHierarchy=null,this._currentTemplateHierarchy=null,this._currentExecutionScope=null,this._stateHierarchy.clear(),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;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._rawProps),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){const t=()=>new Promise((e=>setTimeout(e,0)));await Promise.all([this.initRefs(e),this.bootstrapDeclarativeState(e),this.processInlineModuleScripts(e),this._hydrated=!0]),await t(),await this.initializeAllReferencedProps(e),await t(),await this.manageAttributeBindings(e),await t(),await this.processIfChains(e),await t(),await this.initLoopBindings(e),await t();for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await 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:n,parent:s,templateHierarchy:r}=this.setupLoopMarker(e),i=this.initializeLoopState(),a=this.createLoopUpdater(e,t,n,s,r,i),o={dependencies:this.extractComprehensiveLoopDependencies(e,t,r),update:a,__isLoop:!0};this._bindings.push(o)}processIfChainsInFragment(e,t,n,s,r,i){const a=new WeakSet;e.querySelectorAll("[pp-if]").forEach((e=>{if(a.has(e))return;const o=[];let c=e;for(;c;){if(c.hasAttribute("pp-if"))o.push({el:c,expr:c.getAttribute("pp-if")});else if(c.hasAttribute("pp-elseif"))o.push({el:c,expr:c.getAttribute("pp-elseif")});else{if(!c.hasAttribute("pp-else"))break;o.push({el:c,expr:null})}a.add(c),c=c.nextElementSibling}o.forEach((e=>{if(null!==e.expr){const i=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(i,n);const a=this.makeScopedEvaluator(i,n);e.evaluate=()=>{const e={...this._createScopedPropsContext(n),[t.itemName]:s};return t.idxName&&(e[t.idxName]=r),!!a(e)}}}));let l=!1;for(const{el:e,expr:t,evaluate:n}of o)!l&&null!==t&&n()?(e.removeAttribute("hidden"),l=!0):l||null!==t?e.setAttribute("hidden",""):(e.removeAttribute("hidden"),l=!0);const h=new Set;o.forEach((e=>e.deps?.forEach((e=>h.add(e)))));const d=n.join("."),p=d?`${d}.${t.arrExpr}`:t.arrExpr;h.add(p);i.push({dependencies:h,update:()=>{const e=this.makeScopedEvaluator(t.arrExpr,n)(this._createScopedPropsContext(n));if(Array.isArray(e)){const i=this.getItemKey(s,r),a=this.findItemByKey(e,i,s),c=e.findIndex((t=>this.getItemKey(t,e.indexOf(t))===i));if(a&&-1!==c){let e=!1;for(const{el:s,expr:r,evaluate:i}of o)if(null!==r){const i=this.makeScopedEvaluator(r.replace(/^{\s*|\s*}$/g,""),n),o={...this._createScopedPropsContext(n),[t.itemName]:a};t.idxName&&(o[t.idxName]=c);const l=!!i(o);!e&&l?(s.removeAttribute("hidden"),e=!0):s.setAttribute("hidden","")}else e?s.setAttribute("hidden",""):(s.removeAttribute("hidden"),e=!0)}}},__isLoop:!0})}))}extractComprehensiveLoopDependencies(e,t,n){const s=new Set;let r=null;for(let e=n.length;e>=0;e--){const s=n.slice(0,e),i=s.length>0?`${s.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,i);if(Array.isArray(e)){r=i;break}}catch{}}if(!r)try{const e=this.getNested(this.props,t.arrExpr);Array.isArray(e)&&(r=t.arrExpr)}catch{r=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr}const i=r;null!==i&&s.add(i);const a=this.extractItemPropertiesFromTemplate(e,t);for(const e of a)if(s.add(`${i}.*`),s.add(`${i}.*.${e}`),"string"==typeof i){const t=this.getNested(this.props,i);if(Array.isArray(t))for(let n=0;n<t.length;n++)s.add(`${i}.${n}.${e}`)}return Array.from(s).some((e=>e.includes("*")))||s.add(`${i}.*`),s}extractItemPropertiesFromTemplate(e,t){const n=new Set,s=new RegExp(`\\b${t.itemName}\\.(\\w+(?:\\.\\w+)*)`,"g"),r=document.createTreeWalker(e.content,NodeFilter.SHOW_ALL,null);for(;r.nextNode();){const e=r.currentNode;let t="";if(e.nodeType===Node.TEXT_NODE)t=e.nodeValue||"";else if(e.nodeType===Node.ELEMENT_NODE){const n=e;for(const e of Array.from(n.attributes))t+=" "+e.value}const i=t.matchAll(s);for(const e of i)n.add(e[1])}return n}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[n,s]=t.split(/\s+in\s+/),[r,i]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:n,arrExpr:s,itemName:r,idxName:i}}setupLoopMarker(e){const t=e.parentNode,n=document.createComment("pp-for"),s=this.detectElementHierarchy(e);return t.insertBefore(n,e),t.removeChild(e),{marker:n,parent:t,templateHierarchy:s}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,n,s,r){this._currentTemplateHierarchy=r;const i={...this._createScopedPropsContext(r),[s.itemName]:t};s.idxName&&(i[s.idxName]=n);const a=e.content.cloneNode(!0),o=[],c=this.getItemKey(t,n);return this.processTextNodesInFragment(a,s,r,c,t,n,o),this.processElementBindingsInFragment(a,s,r,c,t,n,o),this.processEventHandlersInFragment(a,s,r,t,n),this.processIfChainsInFragment(a,s,r,t,n,o),o.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),this._currentTemplateHierarchy=null,{nodes:Array.from(a.childNodes),bindings:o}}processTextNodesInFragment(e,t,n,s,r,i,a){const o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;o.nextNode();){const e=o.currentNode,c=e.nodeValue||"";if(PPHP._mustacheTest.test(c)){const o=new Set,l=n.join("."),h=l?`${l}.${t.arrExpr}`:t.arrExpr;o.add(h);for(const e of c.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],n).forEach((e=>o.add(e)));const d=this.createTextNodeUpdaterWithItemKey(e,c,t,n,s,r);a.push({dependencies:o,update:d}),this.renderTextNode(e,c,t,n,r,i)}}}createTextNodeUpdaterWithItemKey(e,t,n,s,r,i){const a=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const o=a(this._createScopedPropsContext(s));if(Array.isArray(o)){const a=this.findItemByKey(o,r,i),c=o.findIndex((e=>this.getItemKey(e,o.indexOf(e))===r));if(a&&-1!==c){const r={...this._createScopedPropsContext(s),[n.itemName]:a};n.idxName&&(r[n.idxName]=c);const i=this.renderMustacheText(t,s,r);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,n){for(let n=0;n<e.length;n++){const s=e[n];if(this.getItemKey(s,n)===t)return s}return n&&"object"==typeof n&&n.id?e.find((e=>e&&e.id===n.id)):null}processElementBindingsInFragment(e,t,n,s,r,i,a){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,n,s,r,i,a)}))}processElementBindings(e,t,n,s,r,i,a){const o=new Set,c=new Set;for(const{name:t,value:n}of Array.from(e.attributes))if(PPHP._mustacheTest.test(n)&&!t.startsWith("pp-bind"))o.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,n,s,r,i,a);else if("pp-bind-expr"===c){const o=this.decodeEntities(l);this.createElementBindingWithItemKey(e,o,"text",t,n,s,r,i,a)}else if(c.startsWith("pp-bind-")){const h=c.replace(/^pp-bind-/,"");if(o.has(h)){if(!this._boolAttrs.has(h))continue;e.removeAttribute(h)}this.createElementBindingWithItemKey(e,l,h,t,n,s,r,i,a)}else PPHP._mustacheTest.test(l)&&this.createElementAttributeTemplateBindingWithItemKey(e,c,l,t,n,s,r,i,a)}createElementAttributeTemplateBindingWithItemKey(e,t,n,s,r,i,a,o,c){const l=new Set,h=r.join("."),d=h?`${h}.${s.arrExpr}`:s.arrExpr;l.add(d);for(const e of n.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],r).forEach((e=>l.add(e)));const p=this.createAttributeTemplateUpdaterWithItemKey(e,t,n,s,r,i,a);c.push({dependencies:l,update:p}),this.renderAttributeTemplate(e,t,n,s,r,a,o)}createAttributeTemplateUpdaterWithItemKey(e,t,n,s,r,i,a){const o=this.makeScopedEvaluator(s.arrExpr,r);return()=>{const c=o(this._createScopedPropsContext(r));if(Array.isArray(c)){const o=this.findItemByKey(c,i,a),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));o&&-1!==l&&this.renderAttributeTemplate(e,t,n,s,r,o,l)}}}renderAttributeTemplate(e,t,n,s,r,i,a){const o={...this._createScopedPropsContext(r),[s.itemName]:i};s.idxName&&(o[s.idxName]=a);const c=n.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeScopedEvaluator(t,r);return this.formatValue(e(o))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==c&&e.setAttribute(t,c)}createElementBindingWithItemKey(e,t,n,s,r,i,a,o,c){const l=new Set,h=r.join("."),d=h?`${h}.${s.arrExpr}`:s.arrExpr;l.add(d),this.extractScopedDependencies(t,r).forEach((e=>l.add(e)));const p=this.createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,a);c.push({dependencies:l,update:p}),this.renderElementBinding(e,t,n,s,r,a,o)}createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,a){const o=this.makeScopedEvaluator(s.arrExpr,r);return()=>{const c=o(this._createScopedPropsContext(r));if(Array.isArray(c)){const o=this.findItemByKey(c,i,a),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));if(o&&-1!==l){const i={...this._createScopedPropsContext(r),[s.itemName]:o};s.idxName&&(i[s.idxName]=l),this.updateElementBinding(e,t,n,r,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 n=t[0];return`${n}_${e[n]}`}}return`idx_${t}`}renderTextNode(e,t,n,s,r,i){const a={...this._createScopedPropsContext(s),[n.itemName]:r};n.idxName&&(a[n.idxName]=i),e.nodeValue=this.renderMustacheText(t,s,a)}renderMustacheText(e,t,n){return e.replace(PPHP._mustachePattern,((e,s)=>{try{const e=this.makeScopedEvaluator(s,t);return this.formatValue(e(n))}catch{return""}}))}updateElementBinding(e,t,n,s,r){const i=this.makeScopedEvaluator(t,s)(r);if("text"===n){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,n,i)}renderElementBinding(e,t,n,s,r,i,a){const o={...this._createScopedPropsContext(r),[s.itemName]:i};s.idxName&&(o[s.idxName]=a),this.updateElementBinding(e,t,n,r,o)}applyAttributeBinding(e,t,n){if(this._boolAttrs.has(t)){const s=!!n;s!==e.hasAttribute(t)&&(s?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==s&&(e[t]=s)}else{const s=String(n);t in e&&e[t]!==s&&(e[t]=s),e.getAttribute(t)!==s&&e.setAttribute(t,s)}}processEventHandlersInFragment(e,t,n,s,r){e.querySelectorAll("*").forEach((e=>{for(const{name:r,value:i}of Array.from(e.attributes)){const a=r.toLowerCase();if(!this._eventHandlers.has(a))continue;let o=i;const c=t=>{try{if(t&&"object"==typeof t&&!Array.isArray(t)){const n=`__pphp_data_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;return e[n]=t,`(event.currentTarget.${n} || event.target.${n})`}return JSON.stringify(t)}catch(e){return console.error("Failed to serialize item:",e),"null"}};if(o=o.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),c(s)),t.idxName){const e=`(globalThis.pphp._idxOf(${c(s)}, '${t.arrExpr}', ${JSON.stringify(n)}))`;o=o.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),e)}e.setAttribute(r,o)}}))}_idxOf(e,t,n){try{const s=this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n));if(!Array.isArray(s))return-1;let r=s.findIndex((t=>t===e));if(-1!==r)return r;const i=this.getItemKey(e,-1);return r=s.findIndex(((e,t)=>this.getItemKey(e,t)===i)),r}catch{return-1}}updateItemNodes(e,t,n,s,r,i){if(t===n)return;if("object"==typeof t&&"object"==typeof n&&JSON.stringify(t)===JSON.stringify(n))return;this._currentTemplateHierarchy=i;const a={...this._createScopedPropsContext(i),[r.itemName]:n};r.idxName&&(a[r.idxName]=s),this.updateNodesContent(e,i,a),this.updateConditionalNodes(e,i,a),this._currentTemplateHierarchy=null}updateConditionalNodes(e,t,n){e.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){e.querySelectorAll("[pp-if], [pp-elseif], [pp-else]").forEach((e=>{const s=e.getAttribute("pp-if")||e.getAttribute("pp-elseif");if(s){const r=s.replace(/^{\s*|\s*}$/g,"");try{const s=this.makeScopedEvaluator(r,t);!!s(n)?e.removeAttribute("hidden"):e.setAttribute("hidden","")}catch(e){console.error("Error evaluating pp-if condition:",r,e)}}else if(e.hasAttribute("pp-else")){const t=e.previousElementSibling;t&&t.hasAttribute("hidden")?e.removeAttribute("hidden"):e.setAttribute("hidden","")}}))}}))}updateNodesContent(e,t,n){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,n)}))}updateElementContent(e,t,n){const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;s.nextNode();){const e=s.nextNode(),r=e.nodeValue||"",i=this.renderMustacheText(r,t,n);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,n),this.updateElementTemplateAttributes(e,t,n)}))}updateElementTemplateAttributes(e,t,n){for(const{name:s,value:r}of Array.from(e.attributes))if(!s.startsWith("pp-bind")&&PPHP._mustacheTest.test(r)){const i=r.replace(PPHP._mustachePattern,((e,s)=>{try{const e=this.makeScopedEvaluator(s,t);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",s,e),""}}));e.getAttribute(s)!==i&&e.setAttribute(s,i)}}updateElementBindingsContent(e,t,n){for(const{name:s,value:r}of Array.from(e.attributes))if("pp-bind"===s)this.updateElementBinding(e,r,"text",t,n);else if(s.startsWith("pp-bind-")){const i=s.replace(/^pp-bind-/,"");this.updateElementBinding(e,r,i,t,n)}}createLoopUpdater(e,t,n,s,r,i){let a;for(let e=r.length;e>=0;e--){const n=r.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,n),s=e(this._createScopedPropsContext(n));if(Array.isArray(s)){a=e;break}}catch{}}return a=this.makeScopedEvaluator(t.arrExpr,r),()=>{this.performLoopUpdate(e,t,n,s,r,i,a)}}captureFocusState(e){const t=document.activeElement,n=t&&e.contains(t),s=n?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:n,focusKey:s,caretPos:n&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const n=t.querySelector(`[key="${e.focusKey}"]`),s=n?.querySelector("input,textarea");if(s&&(s.focus({preventScroll:!0}),null!==e.caretPos&&s instanceof HTMLInputElement)){const t=Math.min(e.caretPos,s.value.length);s.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const n=new Map,s=new Map;e.forEach(((e,t)=>{const s=this.getItemKey(e,t);n.set(s,{item:e,index:t})})),t.forEach(((e,t)=>{const n=this.getItemKey(e,t);s.set(n,{item:e,index:t})}));const r=new Set,i=new Map,a=new Map;for(const[e]of n)s.has(e)||r.add(e);for(const[e,{item:t,index:r}]of s)if(n.has(e)){const s=n.get(e);s.item===t&&s.index===r||a.set(e,{oldItem:s.item,newItem:t,newIndex:r,oldIndex:s.index})}else i.set(e,{item:t,index:r});return{toDelete:r,toInsert:i,toUpdate:a}}applyLoopChanges(e,t,n,s,r,i,a){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,n,i),this.applyLoopInsertions(e.toInsert,t,n,s,r,i,a)}applyLoopUpdates(e,t,n,s){for(const[r,{oldItem:i,newItem:a,newIndex:o,oldIndex:c}]of e){const e=t.renderedItems.get(r);e&&(this.updateItemNodes(e.nodes,i,a,o,n,s),e.item=a,e.index=o,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,n,s,r,i,a){if(0===e.size)return;const o=Array.from(e.entries()).sort((([,e],[,t])=>e.index-t.index));for(const[e,{item:c,index:l}]of o){if(t.renderedItems.has(e)){console.warn(`Item with key ${e} already exists, skipping insertion`);continue}const{nodes:o,bindings:h}=this.createItemNodes(a,c,l,n,i);let d=s;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}o.forEach((e=>{r.insertBefore(e,d.nextSibling),d=e})),t.renderedItems.set(e,{nodes:o,item:c,index:l,bindings:h})}}performLoopUpdate(e,t,n,s,r,i,a){const o=this.captureFocusState(s);let c,l=[];for(let e=r.length;e>=0;e--){const t=r.slice(0,e);try{c=this._createScopedPropsContext(t);const e=a(c);if(Array.isArray(e)&&e.length>=0){l=e;break}}catch(e){console.log("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(r);const e=a(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,n,s,r,e),i.previousList=[...l],this.restoreFocusState(o,s),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const n of e){const e=t.renderedItems.get(n);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(n))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),n=this._refs.get(t)??[];n.push(e),this._refs.set(t,n),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 n=this._proxyCache.get(e);if(n)return n;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const s=this,r=new Proxy(e,{get(e,n,r){if("__isReactiveProxy"===n)return!0;const i=Reflect.get(e,n,r);if(Array.isArray(e)&&"string"==typeof n&&s._mutators.has(n)){let a=s._arrayMethodCache.get(e);if(a||(a=new Map,s._arrayMethodCache.set(e,a)),!a.has(n)){const e=i.bind(r),o=t.join("."),c=function(...t){const n=e(...t);return queueMicrotask((()=>{s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies)if(s.dependencyMatches(o,n,t)){s.scheduleBindingUpdate(e);break}}))})),n};a.set(n,c)}return a.get(n)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy)return s.makeReactive(i,[...t,n]);if(Array.isArray(e)&&"function"==typeof i){let t=s._arrayMethodCache.get(e);return t||(t=new Map,s._arrayMethodCache.set(e,t)),t.has(n)||t.set(n,i.bind(e)),t.get(n)}return i},set(e,n,r,i){if("__isReactiveProxy"===n)return!0;let a=r;null===r||"object"!=typeof r||r.__isReactiveProxy||(a=s.makeReactive(r,[...t,n]));const o=e[n],c=Reflect.set(e,n,a,i);if(o===a)return c;const l=[...t,n].join(".");if(s._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&s._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(n))){const e=t.join(".");if(s._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),n=t.split(".")[0];PPHP._shared.has(n)&&s._dirtyDeps.add(`${t}.*`)}a&&"object"==typeof a&&Object.keys(a).forEach((t=>{if(s._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const n=e.substring(4),r=n.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${n}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(s._dirtyDeps.add(`${e}.*.${String(n)}`),e.startsWith("app.")){const t=e.substring(4),r=t.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${t}.*.${String(n)}`)}}return s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies){if(s.dependencyMatches(l,n,t)){s.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const r=l.substring(4),i=r.split(".")[0];if(PPHP._shared.has(i)&&s.dependencyMatches(r,n,t)){s.scheduleBindingUpdate(e);break}}}})),s._hydrated&&s.scheduleFlush(),c}});return this._proxyCache.set(e,r),r}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,n,s){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=s??r.get(t),a=this.detectElementHierarchy(e);return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractScopedDependencies(t,a).forEach((e=>n.add(e)))})),()=>{try{const n=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,a),n=this._createScopedPropsContext(a);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==n&&e.setAttribute(t,n)}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 n in e)if("__isReactiveProxy"!==n&&"__pphp_key"!==n)try{t[n]=e[n]}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,n="text",s){if(this._assignmentRe.test(t))return;const r=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,r),a=this.makeScopedEvaluator(t,r);if("value"===s||"checked"===s){const t=()=>{try{const t=this._createScopedPropsContext(r),n=a(t),i=this.formatValue(n);let o=!1;if("value"===s){const t=e;"value"in e&&t.value!==i?(t.value=i,o=!0):"value"in e||(e.setAttribute("value",i),o=!0)}else{const t=e,n="true"===i;"checked"in e&&t.checked!==n?(t.checked=n,o=!0):"checked"in e||(e.setAttribute("checked",i),o=!0)}if(!o||!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[s]||s,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 "${s}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(s){const n=s.toLowerCase();if(this._boolAttrs.has(n)){e.removeAttribute(n);const o=()=>{try{const t=this._createScopedPropsContext(r),i=!!a(t);e[s]!==i&&(e[s]=i),i?e.setAttribute(n,""):e.removeAttribute(n)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:o})}const o=e.getAttribute(s)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(o)){const t=this.makeAttrTemplateUpdater(e,s,i,o);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(r),n=a(t),i=this.formatValue(n);s in e&&(e[s]=i),e.setAttribute(s,i)}catch(e){console.error(`Error evaluating attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:c})}const o={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(r),s=a(t),i=this.formatValue(s);o[n](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let s;try{s=new Function("ctx",n)}catch(t){const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const t=s(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const n=e.trim(),s=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(n)?`${n}; return "";`:`return (${n});`}\n }\n } catch {\n return "";\n }\n `;let r;try{r=new Function("ctx",s)}catch(t){const n=JSON.stringify(e);r=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return n=>{try{for(let s=t.length;s>=0;s--){const i=t.slice(0,s);try{const t=this._createScopedPropsContext(i,n),s=r(t);if(Array.isArray(s)&&"voucherItems"===e)return s;if(null!=s&&""!==s&&"voucherItems"!==e)return s}catch{}}const s=this._createScopedPropsContext(t,n),i=r(s);return null==i?"":i}catch{return""}}}_createScopedPropsContext(e,t={}){const n=e.join("."),s=this.getNested(this.props,n)||{},r=this;return new Proxy(t,{get(t,n,i){if("string"==typeof n){const e=Reflect.get(t,n,i);if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch{}}if(n in t)return Reflect.get(t,n,i);const a=r.getScopedFunction(n,e);if(a)return a;if(s&&n in s)return s[n];for(let t=e.length-1;t>=0;t--){const s=e.slice(0,t).join("."),i=r.getScopedFunction(n,e.slice(0,t));if(i)return i;const a=s?r.getNested(r.props,s):r.props;if(a&&n in a)return a[n]}return n in globalThis?globalThis[n]:void 0},set(t,s,i,a){if("string"!=typeof s)return Reflect.set(t,s,i,a);if(s in t)return Reflect.set(t,s,i,a);for(let t=e.length;t>=0;t--){const n=e.slice(0,t).join("."),a=n?`${n}.${s}`:s;if(r.hasNested(r.props,a))return r.setNested(r.props,a,i),r._dirtyDeps.add(a),r.scheduleFlush(),!0}const o=n?`${n}.${s}`:s;return r.setNested(r.props,o,i),r._dirtyDeps.add(o),r.scheduleFlush(),!0},has:(t,n)=>"string"==typeof n&&(n in t||!!r.getScopedFunction(n,e)||s&&n in s||n in globalThis||e.some(((t,s)=>{const i=e.slice(0,s).join("."),a=i?r.getNested(r.props,i):r.props;return a&&n in a})))})}extractScopedDependencies(e,t){const n=this.extractDependencies(e),s=new Set,r=t.join(".");for(const e of n){if(this._reservedWords.has(e.split(".")[0]))continue;const n=r+"."+e;if(this._stateHierarchy.has(n)){s.add(n);continue}if(this.hasNested(this.props,n)){s.add(n);continue}let i=!1;for(let n=t.length-1;n>=0&&!i;n--){const r=t.slice(0,n).join("."),a=r?r+"."+e:e;this._stateHierarchy.has(a)?(s.add(a),i=!0):this.hasNested(this.props,a)&&(s.add(a),i=!0)}if(!i){const t=r+"."+e;s.add(t)}}return s}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const n=this.detectElementHierarchy(e),s=[];let r=e;for(;r;){if(r.hasAttribute("pp-if"))s.push({el:r,expr:r.getAttribute("pp-if")});else if(r.hasAttribute("pp-elseif"))s.push({el:r,expr:r.getAttribute("pp-elseif")});else{if(!r.hasAttribute("pp-else"))break;s.push({el:r,expr:null})}t.add(r),r=r.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,n);const s=this.makeScopedEvaluator(t,n);e.evaluate=()=>{const e=this._createScopedPropsContext(n);return!!s(e)}}}));const i=new Set;s.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?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 n=this.decodeEntities(e.value);PPHP._mustacheTest.test(n)&&t.set(e.name.toLowerCase(),n)})),["pp-bind","pp-bind-expr"].forEach((t=>{const n=e.getAttribute(t);n&&this.registerBinding(e,n,"text")})),Array.from(e.attributes).forEach((t=>{const n=t.name.toLowerCase(),s=t.value.trim();this._boolAttrs.has(n)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(s)&&(e.removeAttribute(t.name),this.registerBinding(e,s,"text",n))})),Array.from(e.attributes).forEach((n=>{if(!n.name.startsWith("pp-bind-"))return;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(n.name))return;const s=n.name.replace(/^pp-bind-/,"").toLowerCase(),r=this.decodeEntities(n.value).replace(/^{{\s*|\s*}}$/g,""),i="value"===s?"value":"checked"===s?"checked":"text";if(t.has(s)){const a=t.get(s).replace(PPHP._mustachePattern,"").trim(),o=a.length>0?`\`${a} \${${r}}\``:r;e.setAttribute(n.name,o);try{const t=this._createScopedPropsContext(this.detectElementHierarchy(e)),n=this.formatValue(this.makeScopedEvaluator(o,this.detectElementHierarchy(e))(t));e.setAttribute(s,n)}catch{}return this.registerBinding(e,o,i,s),void t.delete(s)}this.registerBinding(e,r,i,s)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const n=this.detectElementHierarchy(e),s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),r=new Set;s.forEach((e=>this.extractScopedDependencies(e,n).forEach((e=>r.add(e)))));const i=new Set;this._bindings.push({dependencies:r,update:()=>{try{const t={},r=this._createScopedPropsContext(n);s.forEach((e=>Object.assign(t,this.makeScopedEvaluator(e,n)(r)??{}))),i.forEach((n=>{n in t||e.hasAttribute(n)||(e.removeAttribute(n),i.delete(n))})),Object.entries(t).forEach((([t,n])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==n||!1===n)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const s="object"==typeof n?JSON.stringify(n):String(n);e.getAttribute(t)!==s&&e.setAttribute(t,s),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})})),t.forEach(((t,n)=>{this.registerBinding(e,t,"text",n)}))}))}callInlineModule(e,...t){const n=this._currentProcessingHierarchy||["app"],s=this.getScopedFunction(e,n);if(!s)throw new Error(`PPHP: no inline module named "${e}" in scope ${n.join(".")}`);return s(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return r.get(e)}if(e.startsWith("set")){const n=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(n)){const e=PPHP._shared.get(n);return e?.setter||null}for(let e=t.length;e>=0;e--){const s=t.slice(0,e).join("."),r=s?`${s}.${n}`:n;if(this.hasNested(this.props,r))return e=>{this.setNested(this.props,r,e),this._dirtyDeps.add(r),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 n=t.map(((e,t)=>{const n=this.detectComponentHierarchy(e);(e.textContent||"").trim().substring(0,100);return{script:e,hierarchy:n,depth:n.length}})).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of n){this._currentProcessingHierarchy=t;const n=t.join(".");let s=(e.textContent||"").trim();s=this.decodeEntities(s),s=this.stripComments(s),s=this.transformStateDeclarations(s),s=this.injectScopedVariables(s,t);const r=this.extractSetters(s);if(r.length){s+="\n\n";for(const e of r)s+=`pphp._registerScopedFunction('${n}', '${e}', ${e});\n`}s=s=this.stateDeclarations(s);const i=[];for(const[,e]of[...s.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${n}', '${e}', ${e});`);i.length&&(s+="\n\n"+i.join("\n"));const a=new Blob([s],{type:"application/javascript"}),o=URL.createObjectURL(a);try{const e=await import(o);this._inlineModuleFns.has(n)||this._inlineModuleFns.set(n,new Map);const t=this._inlineModuleFns.get(n);for(const[n,s]of Object.entries(e))"function"!=typeof s||t.has(n)||t.set(n,s)}catch(e){console.error("❌ Inline module import failed:",e),console.error("📄 Generated source:",s)}finally{URL.revokeObjectURL(o),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}stateDeclarations(e){const t="pphp.",n=["state","share"];let s=e;for(const e of n){let n=0;for(;-1!==(n=s.indexOf(`${t}${e}(`,n));){const t=n+5+e.length+1,r=s.slice(t).match(/^(['"])([^'" ]+)\1\s*,/);if(r){const[e,s,i]=r;n=t+e.length}else{const e=s.slice(t),r=e.indexOf(",");if(-1===r)break;{const i=`'${e.slice(0,r).trim()}', `;s=s.slice(0,t)+i+s.slice(t),n=t+i.length+r}}}}return s}injectScopedVariables(e,t){const n=this.extractVariableReferences(e),s=this.extractDeclaredVariables(e),r=this.extractStateVariables(e),i=new Set([...s,...r]),a=[],o=new Set;for(const e of n)if(!o.has(e)&&!i.has(e)&&this.hasInScopedContext(e,t)){const n=this.findScopedKeyForVariable(e,t);a.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 = '${n}';\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})();`),o.add(e);const s=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(s,t)&&!i.has(s)&&(a.push(`\nconst ${s} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${s}(...args);\n};`),o.add(s))}return a.length>0?a.join("\n")+"\n\n"+e:e}extractStateVariables(e){const t=new Set,n=/\b(?:const|let|var)\s+\[\s*([^,\]]+)(?:\s*,\s*([^,\]]+))?\s*\]\s*=\s*pphp\.state/g;let s;for(;null!==(s=n.exec(e));){const e=s[1]?.trim(),n=s[2]?.trim();e&&t.add(e),n&&t.add(n)}const r=/pphp\.state\s*\(\s*['"]([^'"]+)['"]/g;for(;null!==(s=r.exec(e));){const e=s[1];if(e){t.add(e);const n=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;t.add(n)}}return t}extractDeclaredVariables(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const s=[/\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,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g,/\bexport\s+(?:function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)|(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*))/g];for(const e of s){let s;for(;null!==(s=e.exec(n));){const n=s[1]||s[2];if(e.source.includes("\\[")&&!e.source.includes("\\{")){const e=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith("...")?e.substring(3).trim():e));for(const n of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)&&t.add(n)}else if(e.source.includes("\\{")&&!e.source.includes("\\[")){const e=n.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 n of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)&&t.add(n)}else n&&t.add(n)}}return t}findScopedKeyForVariable(e,t){const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return`${n}.${e}`;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?this.getNested(this.props,s):this.props;if(r&&"object"==typeof r&&e in r)return s?`${s}.${e}`:e}return`${n}.${e}`}extractVariableReferences(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ");const s=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let r;for(;null!==(r=s.exec(n));){const e=r[1],s=r.index;if(this._reservedWords.has(e))continue;const i=n.substring(Math.max(0,s-50),s),a=n.substring(s+e.length,s+e.length+10);/\b(?:const|let|var|function|class|export)\s+$/.test(i)||(s>0&&"."===n[s-1]||/^\s*:/.test(a)||this.isActualFunctionParameter(n,s,e)||this.isInDestructuringDeclaration(n,s,e)||t.add(e))}return t}isActualFunctionParameter(e,t,n){let s=-1,r=-1,i=0;for(let n=t-1;n>=0;n--){const t=e[n];if(")"===t)i++;else if("("===t){if(0===i){s=n;break}i--}}if(-1===s)return!1;i=0;for(let s=t+n.length;s<e.length;s++){const t=e[s];if("("===t)i++;else if(")"===t){if(0===i){r=s;break}i--}}if(-1===r)return!1;const a=e.substring(Math.max(0,s-20),s).trim(),o=e.substring(r+1,Math.min(e.length,r+10)).trim(),c=/\bfunction(?:\s+[a-zA-Z_$]\w*)?\s*$/.test(a),l=o.startsWith("=>");if(c||l){e.substring(s+1,r);const i=e.substring(t+n.length,r);return!i.includes("=>")&&!i.includes("{")}return!1}isInDestructuringDeclaration(e,t,n){const s=e.substring(Math.max(0,t-100),t);if(s.match(/\b(?:const|let|var)\s+\[\s*[^\]]*$/)){const s=e.substring(t+n.length,Math.min(e.length,t+n.length+100));if(/[^\]]*\]\s*=/.test(s))return!0}if(s.match(/\b(?:const|let|var)\s+\{\s*[^}]*$/)){const s=e.substring(t+n.length,Math.min(e.length,t+n.length+100));if(/[^}]*\}\s*=/.test(s))return!0}return!1}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return!0;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n),r=s.join(".");if(this.getScopedFunction(e,s))return!0;const i=r?this.getNested(this.props,r):this.props;if(i&&"object"==typeof i&&e in i)return!0;const a=r?`${r}.${e}`:e;if(this._stateHierarchy.has(a))return!0}return!1}_registerScopedFunction(e,t,n){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...s)=>{const r=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&s.length>0?n(s[0]):n(...s)}finally{this._currentExecutionScope=r}}))}extractSetters(e){const t=[],n=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let s;for(;s=n.exec(e);){const[,e,n,r]=s;"share"===r&&this.markShared(e),this._sharedStateMap.has(e)||t.push(n)}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,n,s,r)=>`${t}${n}, ${s}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}${n}${s}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}[${n}] = pphp.state('${n}', `))}stripComments(e){let t="",n=0,s=!1,r="",i=!1;for(;n<e.length;){const a=e[n],o=e[n+1];if(i||"'"!==a&&'"'!==a&&"`"!==a||"\\"===e[n-1])if(s)t+=a,n++;else if(i||"/"!==a||"*"!==o)if(i)"*"===a&&"/"===o?(i=!1,n+=2):n++;else if("/"!==a||"/"!==o)t+=a,n++;else for(;n<e.length&&"\n"!==e[n];)n++;else i=!0,n+=2;else s=!s,r=s?a:"",t+=a,n++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let n=!1;const s=this.getBindingType(t);for(const r of t.dependencies){for(const t of e)if(this.dependencyMatches(t,r,s)){n=!0;break}if(n)break}if(n)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 n=t.__deps||new Set,s=t.__functionDeps||[];if(0===n.size&&0===s.length){try{t()}catch(e){console.error("effect error:",e)}return}const r=[...n].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=s.length>0;if(r||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,n="binding"){const s=e=>{if(e.startsWith("app.")){const t=e.slice(4),n=t.split(".")[0];if(PPHP._shared.has(n))return t}return e},r=s(e),i=s(t);if(r===i||e===t)return!0;const a=i.split(".");if(a.length>1&&PPHP.ARRAY_INTRINSICS.has(a.at(-1))&&PPHP.headMatch(r,a.slice(0,-1).join(".")))return!0;switch(n){case"effect":return this.matchEffectDependency(r,i);case"loop":return!(!PPHP.headMatch(r,i)&&!PPHP.headMatch(i,r))||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchLoopDependency(r,i);default:return!!PPHP.headMatch(r,i)||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchBindingDependency(r,i)}}matchEffectDependency(e,t){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 n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if("*"!==t&&t!==r)return!1}return!0}matchesArrayIndexPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=n[e],r=s[e];if(t!==r&&(!/^\d+$/.test(t)||!/^\d+$/.test(r)))return!1}return!0}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,n){const s=t.split("."),r=s.pop(),i=s.reduce(((e,t)=>e[t]??={}),e);null===n||"object"!=typeof n||Array.isArray(n)||n.__isReactiveProxy?i[r]=n:i[r]=this.makeReactive(n,s.concat(r))}hasNested(e,t){const n=t.split(".");let s=e;for(let e=0;e<n.length;e++){const t=n[e];if(null==s||"object"!=typeof s)return!1;if(!(t in s))return!1;s=s[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 n=PPHP._shared.get(e);if(n)return[n.getter,n.setter];const s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=["app"];const[r,i]=this.state(e,t);return this._currentProcessingHierarchy=s,PPHP._shared.set(e,{getter:r,setter:i}),[r,i]}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.`);const n=this._currentProcessingHierarchy||["app"],s=this.generateScopedKey(n,e);this._stateHierarchy.set(s,{originalKey:e,hierarchy:[...n],level:n.length}),this.hasNested(this.props,s)||this.setNested(this.props,s,t);const r=()=>this.getNested(this.props,s),i=e=>{const t=r(),n="function"==typeof e?e(t):e;this.setNested(this.props,s,n),this._dirtyDeps.add(s),n&&"object"==typeof n&&this.markNestedPropertiesDirty(s,n),this.scheduleFlush()},a=()=>r();Object.defineProperty(a,"value",{get:()=>r(),set:e=>i(e)}),Object.defineProperties(a,{valueOf:{value:()=>r()},toString:{value:()=>String(r())},__isReactiveProxy:{value:!0,writable:!1}}),a.__pphp_key=s;const o=r();if(null===o||"object"!=typeof o)return[a,i];const c=this;return[new Proxy(a,{apply:(e,t,n)=>Reflect.apply(e,t,n),get(e,t,n){if("value"===t)return r();if("__pphp_key"===t)return s;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,n);if("string"==typeof t){const n=r();if(n&&"object"==typeof n){const r=Object.prototype.hasOwnProperty.call(n,t),i=t in e&&void 0!==e[t];if(r||!i){let e=n[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...s.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,n);const i=r();return i&&"object"==typeof i?i[t]:void 0},set(e,t,n){if("value"===t)return i(n),!0;if("__isReactiveProxy"===t)return!0;const a=r();return a&&"object"==typeof a&&(a[t]=n,c._dirtyDeps.add(`${s}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in a)return!0;const n=r();return n&&"object"==typeof n&&t in n}}),i]}markNestedPropertiesDirty(e,t,n=new WeakSet){t&&"object"==typeof t&&!n.has(t)&&(n.add(t),Object.keys(t).forEach((s=>{const r=`${e}.${s}`;this._dirtyDeps.add(r);const i=t[s];i&&"object"==typeof i&&!n.has(i)&&this.markNestedPropertiesDirty(r,i,n)})))}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 n=>{const s=e.get(n);if(void 0!==s)return s;const r=n in globalThis||t.some((e=>n in e));return e.set(n,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let n=e.replace(/\?\./g,".");const s=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(n);)(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)));const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(n);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)));const a=e=>{let t="",n=0;for(;n<e.length;)if("`"===e[n])for(n++;n<e.length;)if("\\"===e[n])n+=2;else if("$"===e[n]&&"{"===e[n+1]){n+=2;let s=1,r=n;for(;n<e.length&&s;)"{"===e[n]?s++:"}"===e[n]&&s--,n++;t+=a(e.slice(r,n-1))+" "}else{if("`"===e[n]){n++;break}n++}else t+=e[n++];return t};n=a(n),n=n.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),n=n.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const o=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of n.match(c)??[]){const[n,...r]=t.split(".");s.has(n)||(0===r.length&&PPHP._isBuiltIn(n)&&new RegExp(`\\.${n}\\b`).test(e)||0===r.length&&new RegExp(`\\b${t}\\s*\\(`).test(e)&&n in globalThis&&"function"==typeof globalThis[n]||o.add(t))}return o}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,n=PPHP._mustacheTest,s=this.props,r=new Set;this.qsa(e,"*").forEach((e=>{const s=this.detectElementHierarchy(e);for(const{name:i,value:a}of Array.from(e.attributes))if(a){if(n.test(a))for(const e of a.matchAll(t))this.extractScopedDependencies(e[1],s).forEach((e=>r.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(a,s).forEach((e=>r.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>n.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const n=e.parentElement;if(!n)continue;const s=this.detectElementHierarchy(n);for(const n of e.nodeValue.matchAll(t))this.extractScopedDependencies(n[1],s).forEach((e=>r.add(e)))}const a=Array.from(r).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of a){const t=e.split(".");let n=s;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(s in n)||!r&&(null==n[s]||"object"!=typeof n[s])){const e=this._stateHierarchy.has(i);r&&e||(n[s]=r?void 0:{})}n=n[s]}}}dispatchEvent(e,t){try{if("string"!=typeof e||""===e.trim())return console.error("PPHP.dispatchEvent: target must be a non-empty string"),!1;const n=e.trim(),s=n.match(/^(?:app\.)?(.+)$/);if(s){const[,e]=s,n=e.split(".")[0];if(PPHP._shared.has(n)){const s=PPHP._shared.get(n);if(e===n){const e="function"==typeof t?t(s.getter()):t;s.setter(e)}else{const r=s.getter(),i=e.substring(n.length+1);if(!r||"object"!=typeof r)return console.error(`PPHP.dispatchEvent: Cannot update nested property '${i}' on non-object shared state`),!1;{const e=this.updateNestedValue(r,i,t);s.setter(e)}}return!0}}const r=this._currentProcessingHierarchy||this._currentExecutionScope?.split(".")||["app"],i=this.resolveStatePath(n,r);if(!i)return console.error(`PPHP.dispatchEvent: Could not resolve state path '${n}'`),!1;const a=this.hasNested(this.props,i)?this.getNested(this.props,i):void 0,o="function"==typeof t?t(a):t;if(this.setNested(this.props,i,o),this._dirtyDeps.add(i),o&&"object"==typeof o&&this.markNestedPropertiesDirty(i,o),i.startsWith("app.")){const e=i.substring(4);this._dirtyDeps.add(e)}return this.scheduleFlush(),!0}catch(e){return console.error("PPHP.dispatchEvent: Error updating state",e),!1}}resolveStatePath(e,t){if(this.hasNested(this.props,e))return e;const n=t.join(".")+"."+e;if(this.hasNested(this.props,n))return n;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n),r=s.length>0?s.join(".")+"."+e:e;if(this.hasNested(this.props,r))return r}for(const[t,n]of this._stateHierarchy.entries())if(n.originalKey===e||t.endsWith("."+e))return t;return n}updateNestedValue(e,t,n){const s=t.split("."),r={...e};let i=r;for(let e=0;e<s.length-1;e++){const t=s[e];null==i[t]||"object"!=typeof i[t]?i[t]={}:i[t]={...i[t]},i=i[t]}const a=s[s.length-1],o=i[a];return i[a]="function"==typeof n?n(o):n,r}async updateDocumentContent(e){const t=(new DOMParser).parseFromString(this.sanitizePassiveHandlers(e),"text/html");this.scrubTemplateValueAttributes(t),this.reconcileHead(t),this.resetProps(),await this.removeAllEventListenersOnNavigation(),this.ensurePageTransitionStyles();const n=async()=>{morphdom(document.body,t.body,{childrenOnly:!0}),await this.initReactiveOn(),this.attachWireFunctionEvents()};"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",n="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${n}]`).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 n=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,s=t.cloneNode(!0),r=document.head.querySelector(n);r?document.head.replaceChild(s,r):document.head.insertBefore(s,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const t=e.cloneNode(!0),n=document.head.querySelector("title");n?document.head.replaceChild(t,n):document.head.appendChild(t);break}case"LINK":{const t=e;if("icon"===t.rel){const e=t.cloneNode(!0),n=document.head.querySelector('link[rel="icon"]');n?document.head.replaceChild(e,n):document.head.appendChild(e)}else t.hasAttribute(n)&&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")}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),s.checked=n.checked,document.activeElement!==n||(null!=n.selectionStart&&(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd),!1)},TEXTAREA(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),document.activeElement!==n||(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd,!1)},SELECT(e,t){const n=e;return t.selectedIndex=n.selectedIndex,document.activeElement!==n},VIDEO(e,t){const n=e,s=t;return s.currentTime=n.currentTime,n.paused?s.pause():s.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,n=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 n=new Function("event",t);e.addEventListener("wheel",n,{passive:!0})}})),this._wheelHandlersStashed=!0);const s=this.PRESERVE_HANDLERS;morphdom(t,n,{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 n=e.tagName;if("SCRIPT"===n||e.hasAttribute("data-nomorph"))return!1;const r=s[n];return!r||r(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)}}async attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(","),t=this.qsa(document.body,e);for(const e of t)for(const t of this._eventHandlers){const n=e.getAttribute(t);if(!n)continue;const s=this.decodeEntities(n).trim();if(!s){e.removeAttribute(t);continue}const r=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(s))} }`;e.removeAttribute(t);const i=t.slice(2);e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,r)}return this.handlePassiveWheelStashes(document),Promise.resolve()}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let n=t.value;for(;n.includes("&");){t.innerHTML=n;const e=t.value;if(e===n)break;n=e}return n};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 n=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(n){let t=e.substring(n[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let s=e.trim();return s&&!s.endsWith(";")&&(s+=";"),s};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}->${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`})),t=t.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}::${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`}));const{normalized:n,originalParam:s}=this.normalizeToArrow(t),r=this.renameEventParam(n,s);return this.replaceThisReferences(r)}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 n=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(n)?n:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const n=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(n,((e,t,n)=>{const s=n[t-1],r=n[t+e.length];return s&&/[\w$]/.test(s)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,n){const s=e.getAttribute("pp-debounce"),r=s?this.parseTime(s):0,i=e.getAttribute("pp-before-request")??"",a=e.getAttribute("pp-after-request")??"",o=PPHP._cancelableEvents,c=async s=>{o.has(t)&&s.cancelable&&s.preventDefault();try{i&&await this.invokeHandler(e,i,s),await this.invokeHandler(e,n,s),a&&!a.startsWith("@close")&&await this.invokeHandler(e,a,s)}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!o.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,d=e=>{if(r>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const n=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),r);PPHP._debounceTimers.set(h,n)}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,n=!1){let s;return function(...r){const i=this;s&&clearTimeout(s),s=setTimeout((()=>{s=null,n||e.apply(i,r)}),t),n&&!s&&e.apply(i,r)}}async invokeHandler(e,t,n){try{const s=t.trim();let r=this._handlerCache.get(s);r||(r=this.parseHandler(s),this._handlerCache.set(s,r)),await this.executeHandler(r,e,n,s)}catch(n){this.handleInvokeError(n,t,e)}finally{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 n=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(n)return{type:"call",name:n[1],args:n[2],isAsync:this.isAsyncFunction(n[1])};const s=t.match(/^(\w+)$/);return s?{type:"simple",name:s[1],isAsync:this.isAsyncFunction(s[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,n="",s=0;for(let r=0;r<e.length-1;r++){const i=e[r],a=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===n&&"\\"!==e[r-1])t=!1,n="";else if(!t&&("("===i&&s++,")"===i&&s--,"="===i&&">"===a&&s>=0))return!0}else t=!0,n=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let n=e.substring(t+2).trim();return n.startsWith("{")&&n.endsWith("}")&&(n=n.slice(1,-1).trim()),{type:"arrow",body:n,isAsync:e.includes("async")||this.containsAwait(n)}}findArrowIndex(e){let t=!1,n="";for(let s=0;s<e.length-1;s++){const r=e[s],i=e[s+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===n&&"\\"!==e[s-1])t=!1;else if(!t&&"="===r&&">"===i)return s}else t=!0,n=r}return-1}async executeArrowHandler(e,t,n){const s=this.parseStatements(e.body);let r=!1;for(const e of s)await this.executeSingleStatement(e,t,n)&&(r=!0);r||await this.executeDynamic(e.body,t,n)}async executeComplexHandler(e,t,n){await this.executeDynamic(e.body,t,n)}parseStatements(e){const t=[];let n="",s=0,r=!1,i="";for(let a=0;a<e.length;a++){const o=e[a];r||'"'!==o&&"'"!==o&&"`"!==o?r&&o===i&&"\\"!==e[a-1]&&(r=!1,i=""):(r=!0,i=o),r||("("!==o&&"{"!==o&&"["!==o||s++,")"!==o&&"}"!==o&&"]"!==o||s--,";"!==o||0!==s)?n+=o:n.trim()&&(t.push(n.trim()),n="")}return n.trim()&&t.push(n.trim()),t}async executeInlineModule(e,t,n,s,r){if(t&&t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t);null!==n&&"object"==typeof n?await this.callInlineModule(e,{...n}):await this.callInlineModule(e,n)}else try{const s=this.detectElementHierarchy(n),r=this._createScopedPropsContext(s),i=this.makeScopedEvaluator(t,s)(r);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:n,event:s})}else await this.handleParsedCallback(n,r,s)}async executeSingleStatement(e,t,n){const s=e.trim();if(!s)return!1;const r=s.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return this.executeSingleStatement(r[1],t,n);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(s))return await this.executeDynamic(s,t,n),!0;const i=s.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i,a=this.detectElementHierarchy(t),o=this.resolveFunctionName(e,a);let c=[];if(""!==r.trim())try{c=JSON5.parse(`[${r}]`)}catch{try{const e=this._createScopedPropsContext(a),t=this.getOrCreateProxy(e),s=/\bevent\b/.test(r)?r.replace(/\bevent\b/g,"_evt"):r;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${s} ]; }`)(n,t,e)}catch(e){c=[]}}if(o){const e=this.getScopedFunction(o,a);if(e)return c.length>0?await e(...c):await this.executeInlineModule(o,r,t,n,s),!0}if(o){const e=globalThis[o];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,s,n),!0}const a=s.match(/^(\w+)$/);if(a){const e=a[1],s=this.detectElementHierarchy(t),r=this.resolveFunctionName(e,s);if(r){if(this.getScopedFunction(r,s))return await this.handleParsedCallback(t,`${r}()`,n),!0}if(r){const e=globalThis[r];if("function"==typeof e)return e.call(globalThis,n),!0}return await this.handleParsedCallback(t,`${e}()`,n),!0}return await this.executeDynamic(s,t,n),!0}async executeCallHandler(e,t,n,s){const{name:r,args:i}=e,a=this.detectElementHierarchy(t),o=this.resolveFunctionName(r,a);if(o){if(this.getScopedFunction(o,a))return void await this.executeInlineModule(o,i||"",t,n,s);const e=globalThis[o];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,n)}await this.handleParsedCallback(t,s,n)}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 n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,n){const{name:s}=e,r=this.detectElementHierarchy(t),i=this.resolveFunctionName(s,r);if(i){if(this.getScopedFunction(i,r))return void await this.handleParsedCallback(t,`${i}()`,n);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,n)}await this.handleParsedCallback(t,`${s}()`,n)}async executeHandler(e,t,n,s){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,n);break;case"call":await this.executeCallHandler(e,t,n,s);break;case"simple":await this.executeSimpleHandler(e,t,n);break;case"complex":await this.executeComplexHandler(e,t,n);break;default:await this.handleParsedCallback(t,s,n)}}async executeGlobalFunction(e,t,n,s){if(t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t)??{};e.call(globalThis,{...n})}else{const r=this.detectElementHierarchy(n),i=this._createScopedPropsContext(r),a=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(n,s,a,i,e)}else e.call(globalThis,s)}async executeDynamic(e,t,n){const s=this.detectElementHierarchy(t),r=this._createScopedPropsContext(s),i=this.getOrCreateProxy(r),a=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await a.call(t,n,i,r)}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"],n={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,s,r)=>{if("string"==typeof s){if(n.hasOwnProperty(s))return n[s];const i=this.getScopedFunction(s,t);if(i)return i;if(s in e){const t=Reflect.get(e,s,r),n=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof n))return t}if(s in globalThis&&!n.hasOwnProperty(s)){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,r)},set:(e,t,n,s)=>Reflect.set(e,t,n,s),has:(e,t)=>{if("string"==typeof t){const s=this._currentProcessingHierarchy||["app"];return n.hasOwnProperty(t)||!!this.getScopedFunction(t,s)||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,n){const s=e instanceof Error?e.message:String(e),r=n.tagName+(n.id?`#${n.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${s}`,e),n.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:n},bubbles:!0}))}async handleParsedCallback(e,t,n){const{funcName:s,data:r}=this.parseCallback(e,t);if(!s)return;const i=Array.isArray(s)?s:[s],a=this.detectElementHierarchy(e);let o;for(const e of i){const t=this.getScopedFunction(e,a);if(t){o=t;break}if("function"==typeof this[e]){o=this[e];break}if("function"==typeof window[e]){o=window[e];break}}if(o){const t=e.hasAttribute("pp-after-request"),s="@close"===e.getAttribute("pp-after-request");let i={args:Array.isArray(r.args)?r.args:[],element:e,data:r,event:n};if(t&&!s){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};i={...i,...e}}await o.call(this,i)}else this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(s)?s[0]:s,r)}async handleUndefinedFunction(e,t,n){const s={callback:await this.encryptCallbackName(t),...n},r=this.createFetchOptions(s),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const s=new URL(window.location.href);let a="",o="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(a=await this.fetchFileWithData(s.href,t,l,n),o=this.extractJson(a)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(s.href,r);if(a=await e.text(),this.getRedirectUrl(a))return void await this.redirect(this.getRedirectUrl(a)||"");if(o=this.extractJson(a)||"",o)try{c=this.parseJson(o)}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=a.replace(o,"")}else e=a;if(this.appendAfterbegin(e),!d&&!c.success)return}if(d&&c.success){this.handleAfterRequest(d,o);const e=a.replace(o,"");return this.appendAfterbegin(e),o}if("@close"===d)return c.success?o:void 0;const p=await this.fetch(s.href,i),u=await p.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(a,u,o,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 n=this.parseJson(e),s=t?this.parseJson(t):null,r=n.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);let i={};if(s){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(i[t]=e.responseKey?s[e.responseKey]:s.response);break;default:i[t]=n[t]}}else i=n;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,n)=>` data-onwheel-code="${this.decodeEntities(n).replace(/"/g,"&quot;")}"`)).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,n,s){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,n,s),a=(new DOMParser).parseFromString(r,"text/html");i&&a.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(a.body.outerHTML)}getUpdatedHTMLContent(e,t,n){const s=document.createElement("div");if(s.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");s.innerHTML=t}else s.innerHTML=e;return s.innerHTML?s:null}async updateBodyContent(e){try{this.saveElementState();const t=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(t),await this.appendCallbackResponse(t),await this.populateDocumentBody(t),await this.removeAllEventListenersOnNavigation(),await this.initReactiveOn(),this.attachWireFunctionEvents(),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 n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=this.decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=this.decodeHTML(t[n]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[n]));break;case"classList.replace":const[s,r]=this.decodeHTML(t[n]).split(",");e.classList.replace(s,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=this.decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,this.decodeHTML(t[n]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let n=document.getElementById(t);n?(n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n)):(n=document.createElement("div"),n.id=t,n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const n=(e,t)=>{for(const n in t)t.hasOwnProperty(n)&&("textContent"===n?e.textContent=t[n]:"innerHTML"===n?e.innerHTML=t[n]:"disabled"===n?!0===t[n]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(n,t[n]));for(const n of Array.from(e.attributes))t.hasOwnProperty(n.name)||e.removeAttribute(n.name)},s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))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 s=this.parseJson(e);n(t,s)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?s(e,t):n(e,t)};try{const r=this.parseJson(t);if(r)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 s=this.parseJson(t);n(e,s)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),s(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(r.targets){r.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&i(s,n)}));const{targets:t,...s}=r;n(e,s)}else{const{empty:t,...s}=r;n(e,s)}}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,n,s={}){const r=new FormData,i=n.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in s)s.hasOwnProperty(e)&&r.append(e,s[e]);const a=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await a.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))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 n=this.parseJson(e);"disabled"!==n.onsubmit&&this.updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}))}else s(t,e)}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?n(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),s.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...a}=s;this.updateElementAttributes(e,a),n(e,r)}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}));const{targets:t,...n}=s;this.updateElementAttributes(e,n)}else{if("disabled"===s.empty&&""===e.value)return;const{empty:t,...n}=s;this.updateElementAttributes(e,n)}}else if(t)s(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n(e,s)}}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 n=0;n<e.attributes.length;n++){const s=e.attributes[n];t[s.name]=s.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const n=e.id;n&&(t=document.querySelector(`[form="${n}"]`)),n&&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,n)=>{e[n]=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 n={};const s=e.closest("form");if(s){new FormData(s).forEach(((e,t)=>{const s=this.clean(e);n[t]?n[t]=Array.isArray(n[t])?[...n[t],s]:[n[t],s]:n[t]=s}))}else e instanceof HTMLInputElement?n=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const r=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(r){const e=r[1].trim(),t=r[2].trim(),s=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e&&(n={...n,...e})}catch(e){console.error("Error parsing JSON args:",e),n.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e?n={...n,...e}:n.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),n.rawArgs=t}else if(/^[\s\d"'[\{]/.test(t))try{const e=new Function(`return [${t}];`)();n.args=Array.isArray(e)?e:[e]}catch{s.test(t)?n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):n.args=[t.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(t)(this.props);n.args=[e]}catch{n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:n}}return{funcName:t,data:n}}clean(e){if("string"!=typeof e)return e;let t=e.replace(/&quot;/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 n=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=n?n.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}setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const n=parseInt(t.length,10)||0;e.setSelectionRange(n,n)}}handleInputAppendParams(e,t){const n=e.getAttribute("pp-append-params"),s=e.getAttribute("pp-append-params-sync");if("true"===n){if("true"===s){const t=e.name||e.id;if(t){const n=new URL(window.location.href),s=new URLSearchParams(n.search);s.has(t)&&(e.value=s.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,n=t.value,s=new URL(window.location.href),r=new URLSearchParams(s.search),i=t.name||t.id;if(i){n?r.set(i,n):r.delete(i);const e=r.toString()?`${s.pathname}?${r.toString()}`:s.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),n=this.handleElementVisibility.bind(this),s=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",n))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",s)))}handleVisibilityElementAttribute(e,t,n){const s=e.getAttribute(t);if(s)if(this.isJsonLike(s)){n(e,this.parseJson(s))}else{const n=this.parseTime(s);if(n>0){const s="pp-visibility"===t?"visibility":"display",r="visibility"===s?"hidden":"none";this.scheduleChange(e,n,s,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,n,s,r){const i=t.start?this.parseTime(t.start):0,a=t.end?this.parseTime(t.end):0;i>0?(e.style[n]=s,this.scheduleChange(e,i,n,r),a>0&&this.scheduleChange(e,i+a,n,s)):a>0&&this.scheduleChange(e,a,n,s)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),s=t.getAttribute("target");if(n&&"_blank"!==s&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(n)&&!n.startsWith(window.location.origin))window.location.href=n;else{const e=t.getAttribute("pp-append-params");if(n.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[r,i]=n.split("#");i&&(s=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const a=`${e.pathname}?${t.toString()}${s}`;history.pushState(null,"",a)}else{const[e,t]=n.split("#"),s=`${e}${t?`#${t}`:""}`;history.pushState(null,"",s)}const s=n.indexOf("#");if(-1!==s){const e=n.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),n=await t.text();if(!t.ok)return await this.updateDocumentContent(n),void console.error(`Navigation error: ${t.status} ${t.statusText}`);const s=n.match(this._redirectRegex);if(s&&s[1])return void await this.redirect(s[1]);await this.updateDocumentContent(n)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let n=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;const s=n.lastIndexOf("/");n=s<=0?"/":n.substring(0,s)}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:n,fadeOut:s}=this.parseTransition(e);await this.fadeOut(t,s),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const s=e.querySelector("[pp-loading-transition]"),r=s?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}getElementKey(e){return e.id||e.className||e.tagName}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&&this._activeAbortController.abort()}async fetch(e,t,n=!1){let s;return n?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,s=this._activeAbortController):s=new AbortController,fetch(e,{...t,signal:s.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){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("=>"))}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,n,s){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=s}))}),t)}async fetchFunction(e,t={},n=!1){try{const s={callback:await this.encryptCallbackName(e),...t},r=window.location.href;let i;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 n=s[t];n instanceof File?e.append(t,n):n instanceof FileList?Array.from(n).forEach((n=>e.append(t,n))):e.append(t,n)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(s);const a=await this.fetch(r,i,n);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const o=await a.text();try{return JSON.parse(o)}catch{return o}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{this.saveElementState();const t=e.length?e:["true"],n=e=>`[pp-sync="${e}"]`,s=await this.fetch(window.location.href,this.createFetchOptions({pphpSync71163:!0,selectors:t,secondRequestC69CD:!0,...this.getUrlParams()}));let r;if(s.headers.get("content-type")?.includes("application/json")){r=(await s.json()).fragments}else r={[t[0]]:await s.text()};const i=`<body>${Object.values(r).join("")}</body>`,a=(new DOMParser).parseFromString(i,"text/html");await this.initReactiveOn(a),t.forEach((e=>{const t=n(e),s=document.querySelectorAll(t),r=a.body.querySelector(t);r&&s.forEach((e=>e.innerHTML=r.innerHTML))})),this.restoreElementState(),this.attachWireFunctionEvents()}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),n=await t.text();await this.updateBodyContent(n)}copyCode(e,t,n,s,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const a=e.closest(`.${t}`)?.querySelector("pre code"),o=a?.textContent?.trim()||"";o?navigator.clipboard.writeText(o).then((()=>{const t=e.querySelector(r);if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s)}),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 n={...this.state,...e};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,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 n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const s=e[n];null!==s&&t.set(n,s)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),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,n=new Map,r=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,s,i){let o=i;r.has(t)&&(void 0===o?o={passive:!0}:"boolean"==typeof o?o={capture:o,passive:!0}:o&&void 0===o.passive&&(o={...o,passive:!0})),n.has(this)||n.set(this,new Map);const a=n.get(this),c=a.get(t)||new Set;c.add(s),a.set(t,c),e.call(this,t,s,o)},EventTarget.prototype.removeEventListener=function(e,r,s){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t.delete(r),0===t.size&&n.get(this).delete(e)}t.call(this,e,r,s)},EventTarget.prototype.removeAllEventListeners=function(e){if(n.has(this)){if(e){const r=n.get(this).get(e);if(!r)return;return r.forEach((n=>t.call(this,e,n))),void n.get(this).delete(e)}n.get(this).forEach(((e,n)=>{e.forEach((e=>t.call(this,n,e)))})),n.delete(this)}}})(),function(){const e=console.log;console.log=(...t)=>{const n=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,n)}}();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;_currentTemplateHierarchy=null;_inlineModuleFns=new Map;_currentExecutionScope=null;_transitionStyleInjected=!1;_currentEffectContext=null;_currentEventTarget=null;_eventContextStack=[];_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"))),n=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...n].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.props=this.makeReactive(this._rawProps),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 n=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",r=e.getAttribute(`pp-${n}`)??null;let s=null;if(r){const t=r.replace(/^{\s*|\s*}$/g,""),n=this.detectElementHierarchy(e);try{s=!!this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n))}catch{s=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:n,expr:r,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:n,idxName:r,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:n||"(default)",idx:r||"(—)",rendered:i}}));console.table(t)}console.groupEnd(),console.groupEnd()}setupGlobalEventTracking(){const e=EventTarget.prototype.addEventListener,t=this;EventTarget.prototype.addEventListener=function(n,r,s){return e.call(this,n,(function(e){return t.trackEventContext&&t.trackEventContext(e),"function"==typeof r?r.call(this,e):r&&"function"==typeof r.handleEvent?r.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 n=0;n<this._bindings.length;n+=t)this._bindings.slice(n,n+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 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("."),n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:r,exp:s}=JSON.parse(n);if(Date.now()/1e3>s)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(r),(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)),n=(new TextEncoder).encode(e),r=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,n);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(r)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,n]=e.split(":",2),r=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),s=Uint8Array.from(atob(n),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:r},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,n=e.getAttribute("pp-init-state").trim();if(!n)return void e.removeAttribute("pp-init-state");try{t=JSON5.parse(n)}catch(e){return void console.error("Bad pp-init-state JSON:",n)}const r=this.detectElementHierarchy(e),s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=r,Object.entries(t).forEach((([e,t])=>{this.state(e,t)})),this._currentProcessingHierarchy=s,e.removeAttribute("pp-init-state")}))}detectComponentHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return t.length>0?t:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const n=this._refs.get(e)??[];if(null!=t){const r=n[t];if(!r)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return r}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const n=Array.isArray(t),r=n?t:[],s=n&&0===r.length,i=this._currentProcessingHierarchy||["app"],o=this.getCurrentComponent(),a=r.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(t){const e=t[1];return this.resolveDependencyPath(e,i)}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),c=r.filter((e=>"function"==typeof e&&!e.__pphp_key)),l=new Set(a),h=new Map;for(const e of a)try{h.set(e,this.getResolvedValue(e))}catch(t){h.set(e,void 0)}const d=new Map;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 r=performance.now();if(r-u<16)return void requestAnimationFrame((()=>{performance.now()-u>=16&&m()}));if(u=r,++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=[];if(a.length>0)for(const n of a)try{const r=this.getResolvedValue(n),s=h.get(n);this.hasValueChanged(r,s)&&(e=!0,t.push(n),h.set(n,r))}catch(r){e=!0,t.push(n),h.set(n,void 0)}for(const n of c)try{const r=n(),s=d.get(n);this.hasValueChanged(r,s)&&(e=!0,t.push("(function)"),d.set(n,r))}catch(r){d.get(n)!==Symbol("error")&&(e=!0,t.push("(function-error)"),d.set(n,Symbol("error")))}if(n&&(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=n&&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 n=e.startsWith("app.")?e.substring(4):e,r=n.split(".")[0];if(PPHP._shared.has(r))return n;const s=t.join(".")+"."+e;if(this.hasNested(this.props,s))return s;if(this.hasNested(this.props,e))return e;for(let n=t.length-1;n>=0;n--){const r=t.slice(0,n).join("."),s=r?r+"."+e:e;if(this.hasNested(this.props,s))return s}return e}getResolvedValue(e){e.split(".")[0];const t=(e.startsWith("app.")?e.substring(4):e).split("."),n=t[0],r=PPHP._shared.get(n);if(r){if(1===t.length)return r.getter();{const e=r.getter(),n=t.slice(1).join(".");return this.getNested(e,n)}}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._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._currentProcessingHierarchy=null,this._currentTemplateHierarchy=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;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._rawProps),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){const t=()=>new Promise((e=>setTimeout(e,0)));await Promise.all([this.initRefs(e),this.bootstrapDeclarativeState(e),this.processInlineModuleScripts(e),this._hydrated=!0]),await t(),await this.initializeAllReferencedProps(e),await t(),await this.manageAttributeBindings(e),await t(),await this.processIfChains(e),await t(),await this.initLoopBindings(e),await t();for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await 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:n,parent:r,templateHierarchy:s}=this.setupLoopMarker(e),i=this.initializeLoopState(),o=this.createLoopUpdater(e,t,n,r,s,i),a={dependencies:this.extractComprehensiveLoopDependencies(e,t,s),update:o,__isLoop:!0};this._bindings.push(a)}processIfChainsInFragment(e,t,n,r,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,n);const o=this.makeScopedEvaluator(i,n);e.evaluate=()=>{const e={...this._createScopedPropsContext(n),[t.itemName]:r};return t.idxName&&(e[t.idxName]=s),!!o(e)}}}));let l=!1;for(const{el:e,expr:t,evaluate:n}of a)!l&&null!==t&&n()?(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=n.join("."),p=d?`${d}.${t.arrExpr}`:t.arrExpr;h.add(p);i.push({dependencies:h,update:()=>{const e=this.makeScopedEvaluator(t.arrExpr,n)(this._createScopedPropsContext(n));if(Array.isArray(e)){const i=this.getItemKey(r,s),o=this.findItemByKey(e,i,r),c=e.findIndex((t=>this.getItemKey(t,e.indexOf(t))===i));if(o&&-1!==c){let e=!1;for(const{el:r,expr:s,evaluate:i}of a)if(null!==s){const i=this.makeScopedEvaluator(s.replace(/^{\s*|\s*}$/g,""),n),a={...this._createScopedPropsContext(n),[t.itemName]:o};t.idxName&&(a[t.idxName]=c);const l=!!i(a);!e&&l?(r.removeAttribute("hidden"),e=!0):r.setAttribute("hidden","")}else e?r.setAttribute("hidden",""):(r.removeAttribute("hidden"),e=!0)}}},__isLoop:!0})}))}extractComprehensiveLoopDependencies(e,t,n){const r=new Set;let s=null;for(let e=n.length;e>=0;e--){const r=n.slice(0,e),i=r.length>0?`${r.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,i);if(Array.isArray(e)){s=i;break}}catch{}}if(!s)try{const e=this.getNested(this.props,t.arrExpr);Array.isArray(e)&&(s=t.arrExpr)}catch{s=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr}const i=s;null!==i&&r.add(i);const o=this.extractItemPropertiesFromTemplate(e,t);for(const e of o)if(r.add(`${i}.*`),r.add(`${i}.*.${e}`),"string"==typeof i){const t=this.getNested(this.props,i);if(Array.isArray(t))for(let n=0;n<t.length;n++)r.add(`${i}.${n}.${e}`)}return Array.from(r).some((e=>e.includes("*")))||r.add(`${i}.*`),r}extractItemPropertiesFromTemplate(e,t){const n=new Set,r=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 n=e;for(const e of Array.from(n.attributes))t+=" "+e.value}const i=t.matchAll(r);for(const e of i)n.add(e[1])}return n}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[n,r]=t.split(/\s+in\s+/),[s,i]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:n,arrExpr:r,itemName:s,idxName:i}}setupLoopMarker(e){const t=e.parentNode,n=document.createComment("pp-for"),r=this.detectElementHierarchy(e);return t.insertBefore(n,e),t.removeChild(e),{marker:n,parent:t,templateHierarchy:r}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,n,r,s){this._currentTemplateHierarchy=s;const i={...this._createScopedPropsContext(s),[r.itemName]:t};r.idxName&&(i[r.idxName]=n);const o=e.content.cloneNode(!0),a=[],c=this.getItemKey(t,n);return this.processTextNodesInFragment(o,r,s,c,t,n,a),this.processElementBindingsInFragment(o,r,s,c,t,n,a),this.processEventHandlersInFragment(o,r,s,t,n),this.processIfChainsInFragment(o,r,s,t,n,a),a.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),this._currentTemplateHierarchy=null,{nodes:Array.from(o.childNodes),bindings:a}}processTextNodesInFragment(e,t,n,r,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=n.join("."),h=l?`${l}.${t.arrExpr}`:t.arrExpr;a.add(h);for(const e of c.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],n).forEach((e=>a.add(e)));const d=this.createTextNodeUpdaterWithItemKey(e,c,t,n,r,s);o.push({dependencies:a,update:d}),this.renderTextNode(e,c,t,n,s,i)}}}createTextNodeUpdaterWithItemKey(e,t,n,r,s,i){const o=this.makeScopedEvaluator(n.arrExpr,r);return()=>{const a=o(this._createScopedPropsContext(r));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(r),[n.itemName]:o};n.idxName&&(s[n.idxName]=c);const i=this.renderMustacheText(t,r,s);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,n){for(let n=0;n<e.length;n++){const r=e[n];if(this.getItemKey(r,n)===t)return r}return n&&"object"==typeof n&&n.id?e.find((e=>e&&e.id===n.id)):null}processElementBindingsInFragment(e,t,n,r,s,i,o){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,n,r,s,i,o)}))}processElementBindings(e,t,n,r,s,i,o){const a=new Set,c=new Set;for(const{name:t,value:n}of Array.from(e.attributes))if(PPHP._mustacheTest.test(n)&&!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,n,r,s,i,o);else if("pp-bind-expr"===c){const a=this.decodeEntities(l);this.createElementBindingWithItemKey(e,a,"text",t,n,r,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,n,r,s,i,o)}else PPHP._mustacheTest.test(l)&&this.createElementAttributeTemplateBindingWithItemKey(e,c,l,t,n,r,s,i,o)}createElementAttributeTemplateBindingWithItemKey(e,t,n,r,s,i,o,a,c){const l=new Set,h=s.join("."),d=h?`${h}.${r.arrExpr}`:r.arrExpr;l.add(d);for(const e of n.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],s).forEach((e=>l.add(e)));const p=this.createAttributeTemplateUpdaterWithItemKey(e,t,n,r,s,i,o);c.push({dependencies:l,update:p}),this.renderAttributeTemplate(e,t,n,r,s,o,a)}createAttributeTemplateUpdaterWithItemKey(e,t,n,r,s,i,o){const a=this.makeScopedEvaluator(r.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,n,r,s,a,l)}}}renderAttributeTemplate(e,t,n,r,s,i,o){const a={...this._createScopedPropsContext(s),[r.itemName]:i};r.idxName&&(a[r.idxName]=o);const c=n.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,n,r,s,i,o,a,c){const l=new Set,h=s.join("."),d=h?`${h}.${r.arrExpr}`:r.arrExpr;l.add(d),this.extractScopedDependencies(t,s).forEach((e=>l.add(e)));const p=this.createElementBindingUpdaterWithItemKey(e,t,n,r,s,i,o);c.push({dependencies:l,update:p}),this.renderElementBinding(e,t,n,r,s,o,a)}createElementBindingUpdaterWithItemKey(e,t,n,r,s,i,o){const a=this.makeScopedEvaluator(r.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),[r.itemName]:a};r.idxName&&(i[r.idxName]=l),this.updateElementBinding(e,t,n,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 n=t[0];return`${n}_${e[n]}`}}return`idx_${t}`}renderTextNode(e,t,n,r,s,i){const o={...this._createScopedPropsContext(r),[n.itemName]:s};n.idxName&&(o[n.idxName]=i),e.nodeValue=this.renderMustacheText(t,r,o)}renderMustacheText(e,t,n){return e.replace(PPHP._mustachePattern,((e,r)=>{try{const e=this.makeScopedEvaluator(r,t);return this.formatValue(e(n))}catch{return""}}))}updateElementBinding(e,t,n,r,s){const i=this.makeScopedEvaluator(t,r)(s);if("text"===n){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,n,i)}renderElementBinding(e,t,n,r,s,i,o){const a={...this._createScopedPropsContext(s),[r.itemName]:i};r.idxName&&(a[r.idxName]=o),this.updateElementBinding(e,t,n,s,a)}applyAttributeBinding(e,t,n){if(this._boolAttrs.has(t)){const r=!!n;r!==e.hasAttribute(t)&&(r?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==r&&(e[t]=r)}else{const r=String(n);t in e&&e[t]!==r&&(e[t]=r),e.getAttribute(t)!==r&&e.setAttribute(t,r)}}processEventHandlersInFragment(e,t,n,r,s){e.querySelectorAll("*").forEach((e=>{for(const{name:s,value:i}of Array.from(e.attributes)){const o=s.toLowerCase();if(!this._eventHandlers.has(o))continue;let a=i;const c=t=>{try{if(t&&"object"==typeof t&&!Array.isArray(t)){const n=`__pphp_data_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;return e[n]=t,`(event.currentTarget.${n} || event.target.${n})`}return JSON.stringify(t)}catch(e){return console.error("Failed to serialize item:",e),"null"}};if(a=a.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),c(r)),t.idxName){const e=`(globalThis.pphp._idxOf(${c(r)}, '${t.arrExpr}', ${JSON.stringify(n)}))`;a=a.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),e)}e.setAttribute(s,a)}}))}_idxOf(e,t,n){try{const r=this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n));if(!Array.isArray(r))return-1;let s=r.findIndex((t=>t===e));if(-1!==s)return s;const i=this.getItemKey(e,-1);return s=r.findIndex(((e,t)=>this.getItemKey(e,t)===i)),s}catch{return-1}}updateItemNodes(e,t,n,r,s,i){if(t===n)return;if("object"==typeof t&&"object"==typeof n&&JSON.stringify(t)===JSON.stringify(n))return;this._currentTemplateHierarchy=i;const o={...this._createScopedPropsContext(i),[s.itemName]:n};s.idxName&&(o[s.idxName]=r),this.updateNodesContent(e,i,o),this.updateConditionalNodes(e,i,o),this._currentTemplateHierarchy=null}updateConditionalNodes(e,t,n){e.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){e.querySelectorAll("[pp-if], [pp-elseif], [pp-else]").forEach((e=>{const r=e.getAttribute("pp-if")||e.getAttribute("pp-elseif");if(r){const s=r.replace(/^{\s*|\s*}$/g,"");try{const r=this.makeScopedEvaluator(s,t);!!r(n)?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,n){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,n)}))}updateElementContent(e,t,n){const r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;r.nextNode();){const e=r.nextNode(),s=e.nodeValue||"",i=this.renderMustacheText(s,t,n);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,n),this.updateElementTemplateAttributes(e,t,n)}))}updateElementTemplateAttributes(e,t,n){for(const{name:r,value:s}of Array.from(e.attributes))if(!r.startsWith("pp-bind")&&PPHP._mustacheTest.test(s)){const i=s.replace(PPHP._mustachePattern,((e,r)=>{try{const e=this.makeScopedEvaluator(r,t);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",r,e),""}}));e.getAttribute(r)!==i&&e.setAttribute(r,i)}}updateElementBindingsContent(e,t,n){for(const{name:r,value:s}of Array.from(e.attributes))if("pp-bind"===r)this.updateElementBinding(e,s,"text",t,n);else if(r.startsWith("pp-bind-")){const i=r.replace(/^pp-bind-/,"");this.updateElementBinding(e,s,i,t,n)}}createLoopUpdater(e,t,n,r,s,i){let o;for(let e=s.length;e>=0;e--){const n=s.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,n),r=e(this._createScopedPropsContext(n));if(Array.isArray(r)){o=e;break}}catch{}}return o=this.makeScopedEvaluator(t.arrExpr,s),()=>{this.performLoopUpdate(e,t,n,r,s,i,o)}}captureFocusState(e){const t=document.activeElement,n=t&&e.contains(t),r=n?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:n,focusKey:r,caretPos:n&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const n=t.querySelector(`[key="${e.focusKey}"]`),r=n?.querySelector("input,textarea");if(r&&(r.focus({preventScroll:!0}),null!==e.caretPos&&r instanceof HTMLInputElement)){const t=Math.min(e.caretPos,r.value.length);r.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const n=new Map,r=new Map;e.forEach(((e,t)=>{const r=this.getItemKey(e,t);n.set(r,{item:e,index:t})})),t.forEach(((e,t)=>{const n=this.getItemKey(e,t);r.set(n,{item:e,index:t})}));const s=new Set,i=new Map,o=new Map;for(const[e]of n)r.has(e)||s.add(e);for(const[e,{item:t,index:s}]of r)if(n.has(e)){const r=n.get(e);r.item===t&&r.index===s||o.set(e,{oldItem:r.item,newItem:t,newIndex:s,oldIndex:r.index})}else i.set(e,{item:t,index:s});return{toDelete:s,toInsert:i,toUpdate:o}}applyLoopChanges(e,t,n,r,s,i,o){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,n,i),this.applyLoopInsertions(e.toInsert,t,n,r,s,i,o)}applyLoopUpdates(e,t,n,r){for(const[s,{oldItem:i,newItem:o,newIndex:a,oldIndex:c}]of e){const e=t.renderedItems.get(s);e&&(this.updateItemNodes(e.nodes,i,o,a,n,r),e.item=o,e.index=a,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,n,r,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,n,i);let d=r;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,n,r,s,i,o){const a=this.captureFocusState(r);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.log("🔥 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,n,r,s,e),i.previousList=[...l],this.restoreFocusState(a,r),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const n of e){const e=t.renderedItems.get(n);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(n))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),n=this._refs.get(t)??[];n.push(e),this._refs.set(t,n),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 n=this._proxyCache.get(e);if(n)return n;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const r=this,s=new Proxy(e,{get(e,n,s){if("__isReactiveProxy"===n)return!0;const i=Reflect.get(e,n,s);if(Array.isArray(e)&&"string"==typeof n&&r._mutators.has(n)){let o=r._arrayMethodCache.get(e);if(o||(o=new Map,r._arrayMethodCache.set(e,o)),!o.has(n)){const e=i.bind(s),a=t.join("."),c=function(...t){const n=e(...t);return queueMicrotask((()=>{r._bindings.forEach((e=>{const t=r.getBindingType(e);for(const n of e.dependencies)if(r.dependencyMatches(a,n,t)){r.scheduleBindingUpdate(e);break}}))})),n};o.set(n,c)}return o.get(n)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy)return r.makeReactive(i,[...t,n]);if(Array.isArray(e)&&"function"==typeof i){let t=r._arrayMethodCache.get(e);return t||(t=new Map,r._arrayMethodCache.set(e,t)),t.has(n)||t.set(n,i.bind(e)),t.get(n)}return i},set(e,n,s,i){if("__isReactiveProxy"===n)return!0;let o=s;null===s||"object"!=typeof s||s.__isReactiveProxy||(o=r.makeReactive(s,[...t,n]));const a=e[n],c=Reflect.set(e,n,o,i);if(a===o)return c;const l=[...t,n].join(".");if(r._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&r._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(n))){const e=t.join(".");if(r._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),n=t.split(".")[0];PPHP._shared.has(n)&&r._dirtyDeps.add(`${t}.*`)}o&&"object"==typeof o&&Object.keys(o).forEach((t=>{if(r._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const n=e.substring(4),s=n.split(".")[0];PPHP._shared.has(s)&&r._dirtyDeps.add(`${n}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(r._dirtyDeps.add(`${e}.*.${String(n)}`),e.startsWith("app.")){const t=e.substring(4),s=t.split(".")[0];PPHP._shared.has(s)&&r._dirtyDeps.add(`${t}.*.${String(n)}`)}}return r._bindings.forEach((e=>{const t=r.getBindingType(e);for(const n of e.dependencies){if(r.dependencyMatches(l,n,t)){r.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const s=l.substring(4),i=s.split(".")[0];if(PPHP._shared.has(i)&&r.dependencyMatches(s,n,t)){r.scheduleBindingUpdate(e);break}}}})),r._hydrated&&r.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,n,r){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=r??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=>n.add(e)))})),()=>{try{const n=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,o),n=this._createScopedPropsContext(o);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==n&&e.setAttribute(t,n)}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 n in e)if("__isReactiveProxy"!==n&&"__pphp_key"!==n)try{t[n]=e[n]}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,n="text",r){if(this._assignmentRe.test(t))return;const s=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,s),o=this.makeScopedEvaluator(t,s);if("value"===r||"checked"===r){const t=()=>{try{const t=this._createScopedPropsContext(s),n=o(t),i=this.formatValue(n);let a=!1;if("value"===r){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,n="true"===i;"checked"in e&&t.checked!==n?(t.checked=n,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[r]||r,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 "${r}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(r){const n=r.toLowerCase();if(this._boolAttrs.has(n)){e.removeAttribute(n);const a=()=>{try{const t=this._createScopedPropsContext(s),i=!!o(t);e[r]!==i&&(e[r]=i),i?e.setAttribute(n,""):e.removeAttribute(n)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${r}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:a})}const a=e.getAttribute(r)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(a)){const t=this.makeAttrTemplateUpdater(e,r,i,a);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(s),n=o(t),i=this.formatValue(n);r in e&&(e[r]=i),e.setAttribute(r,i)}catch(e){console.error(`Error evaluating attribute ${r}="${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),r=o(t),i=this.formatValue(r);a[n](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let r;try{r=new Function("ctx",n)}catch(t){const n=JSON.stringify(e);r=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const t=r(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const n=e.trim(),r=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(n)?`${n}; return "";`:`return (${n});`}\n }\n } catch {\n return "";\n }\n `;let s;try{s=new Function("ctx",r)}catch(t){const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return n=>{try{for(let r=t.length;r>=0;r--){const i=t.slice(0,r);try{const t=this._createScopedPropsContext(i,n),r=s(t);if(Array.isArray(r)&&"voucherItems"===e)return r;if(null!=r&&""!==r&&"voucherItems"!==e)return r}catch{}}const r=this._createScopedPropsContext(t,n),i=s(r);return null==i?"":i}catch{return""}}}_createScopedPropsContext(e,t={}){const n=e.join("."),r=this.getNested(this.props,n)||{},s=this;return new Proxy(t,{get(t,n,i){if("string"==typeof n){const e=Reflect.get(t,n,i);if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch{}}if(n in t)return Reflect.get(t,n,i);const o=s.getScopedFunction(n,e);if(o)return o;if(r&&n in r)return r[n];for(let t=e.length-1;t>=0;t--){const r=e.slice(0,t).join("."),i=s.getScopedFunction(n,e.slice(0,t));if(i)return i;const o=r?s.getNested(s.props,r):s.props;if(o&&n in o)return o[n]}return n in globalThis?globalThis[n]:void 0},set(t,r,i,o){if("string"!=typeof r)return Reflect.set(t,r,i,o);if(r in t)return Reflect.set(t,r,i,o);for(let t=e.length;t>=0;t--){const n=e.slice(0,t).join("."),o=n?`${n}.${r}`:r;if(s.hasNested(s.props,o))return s.setNested(s.props,o,i),s._dirtyDeps.add(o),s.scheduleFlush(),!0}const a=n?`${n}.${r}`:r;return s.setNested(s.props,a,i),s._dirtyDeps.add(a),s.scheduleFlush(),!0},has:(t,n)=>"string"==typeof n&&(n in t||!!s.getScopedFunction(n,e)||r&&n in r||n in globalThis||e.some(((t,r)=>{const i=e.slice(0,r).join("."),o=i?s.getNested(s.props,i):s.props;return o&&n in o})))})}extractScopedDependencies(e,t){const n=this.extractDependencies(e),r=new Set,s=t.join(".");for(const e of n){if(this._reservedWords.has(e.split(".")[0]))continue;const n=s+"."+e;if(this._stateHierarchy.has(n)){r.add(n);continue}if(this.hasNested(this.props,n)){r.add(n);continue}let i=!1;for(let n=t.length-1;n>=0&&!i;n--){const s=t.slice(0,n).join("."),o=s?s+"."+e:e;this._stateHierarchy.has(o)?(r.add(o),i=!0):this.hasNested(this.props,o)&&(r.add(o),i=!0)}if(!i){const t=s+"."+e;r.add(t)}}return r}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const n=this.detectElementHierarchy(e),r=[];let s=e;for(;s;){if(s.hasAttribute("pp-if"))r.push({el:s,expr:s.getAttribute("pp-if")});else if(s.hasAttribute("pp-elseif"))r.push({el:s,expr:s.getAttribute("pp-elseif")});else{if(!s.hasAttribute("pp-else"))break;r.push({el:s,expr:null})}t.add(s),s=s.nextElementSibling}r.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,n);const r=this.makeScopedEvaluator(t,n);e.evaluate=()=>{const e=this._createScopedPropsContext(n);return!!r(e)}}}));const i=new Set;r.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:s}of r)!e&&null!==n&&s()?(t.removeAttribute("hidden"),e=!0):e||null!==n?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 n=this.decodeEntities(e.value);PPHP._mustacheTest.test(n)&&t.set(e.name.toLowerCase(),n)})),["pp-bind","pp-bind-expr"].forEach((t=>{const n=e.getAttribute(t);n&&this.registerBinding(e,n,"text")})),Array.from(e.attributes).forEach((t=>{const n=t.name.toLowerCase(),r=t.value.trim();this._boolAttrs.has(n)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(r)&&(e.removeAttribute(t.name),this.registerBinding(e,r,"text",n))})),Array.from(e.attributes).forEach((n=>{if(!n.name.startsWith("pp-bind-"))return;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(n.name))return;const r=n.name.replace(/^pp-bind-/,"").toLowerCase(),s=this.decodeEntities(n.value).replace(/^{{\s*|\s*}}$/g,""),i="value"===r?"value":"checked"===r?"checked":"text";if(t.has(r)){const o=t.get(r).replace(PPHP._mustachePattern,"").trim(),a=o.length>0?`\`${o} \${${s}}\``:s;e.setAttribute(n.name,a);try{const t=this._createScopedPropsContext(this.detectElementHierarchy(e)),n=this.formatValue(this.makeScopedEvaluator(a,this.detectElementHierarchy(e))(t));e.setAttribute(r,n)}catch{}return this.registerBinding(e,a,i,r),void t.delete(r)}this.registerBinding(e,s,i,r)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const n=this.detectElementHierarchy(e),r=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),s=new Set;r.forEach((e=>this.extractScopedDependencies(e,n).forEach((e=>s.add(e)))));const i=new Set;this._bindings.push({dependencies:s,update:()=>{try{const t={},s=this._createScopedPropsContext(n);r.forEach((e=>Object.assign(t,this.makeScopedEvaluator(e,n)(s)??{}))),i.forEach((n=>{n in t||e.hasAttribute(n)||(e.removeAttribute(n),i.delete(n))})),Object.entries(t).forEach((([t,n])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==n||!1===n)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const r="object"==typeof n?JSON.stringify(n):String(n);e.getAttribute(t)!==r&&e.setAttribute(t,r),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})})),t.forEach(((t,n)=>{this.registerBinding(e,t,"text",n)}))}))}callInlineModule(e,...t){const n=this._currentProcessingHierarchy||["app"],r=this.getScopedFunction(e,n);if(!r)throw new Error(`PPHP: no inline module named "${e}" in scope ${n.join(".")}`);return r(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;for(let n=t.length;n>=0;n--){const r=t.slice(0,n).join("."),s=this._inlineModuleFns.get(r);if(s&&s.has(e))return s.get(e)}if(e.startsWith("set")){const n=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(n)){const e=PPHP._shared.get(n);return e?.setter||null}for(let e=t.length;e>=0;e--){const r=t.slice(0,e).join("."),s=r?`${r}.${n}`:n;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 n=t.map(((e,t)=>{const n=this.detectComponentHierarchy(e);(e.textContent||"").trim().substring(0,100);return{script:e,hierarchy:n,depth:n.length}})).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of n){this._currentProcessingHierarchy=t;const n=t.join(".");let r=(e.textContent||"").trim();r=this.decodeEntities(r),r=this.stripComments(r),r=this.transformStateDeclarations(r),r=this.injectScopedVariables(r,t);const s=this.extractSetters(r);if(s.length){r+="\n\n";for(const e of s)r+=`pphp._registerScopedFunction('${n}', '${e}', ${e});\n`}r=r=this.stateDeclarations(r);const i=[];for(const[,e]of[...r.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...r.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${n}', '${e}', ${e});`);i.length&&(r+="\n\n"+i.join("\n"));const o=new Blob([r],{type:"application/javascript"}),a=URL.createObjectURL(o);try{const e=await import(a);this._inlineModuleFns.has(n)||this._inlineModuleFns.set(n,new Map);const t=this._inlineModuleFns.get(n);for(const[n,r]of Object.entries(e))"function"!=typeof r||t.has(n)||t.set(n,r)}catch(e){console.error("❌ Inline module import failed:",e),console.error("📄 Generated source:",r)}finally{URL.revokeObjectURL(a),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}stateDeclarations(e){const t="pphp.",n=["state","share"];let r=e;for(const e of n){let n=0;for(;-1!==(n=r.indexOf(`${t}${e}(`,n));){const t=n+5+e.length+1,s=r.slice(t).match(/^(['"])([^'" ]+)\1\s*,/);if(s){const[e,r,i]=s;n=t+e.length}else{const e=r.slice(t),s=e.indexOf(",");if(-1===s)break;{const i=`'${e.slice(0,s).trim()}', `;r=r.slice(0,t)+i+r.slice(t),n=t+i.length+s}}}}return r}injectScopedVariables(e,t){const n=this.extractVariableReferences(e),r=this.extractDeclaredVariables(e),s=this.extractStateVariables(e),i=new Set([...r,...s]),o=[],a=new Set;for(const e of n)if(!a.has(e)&&!i.has(e)&&this.hasInScopedContext(e,t)){const n=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 = '${n}';\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 r=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(r,t)&&!i.has(r)&&(o.push(`\nconst ${r} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${r}(...args);\n};`),a.add(r))}return o.length>0?o.join("\n")+"\n\n"+e:e}extractStateVariables(e){const t=new Set,n=/\b(?:const|let|var)\s+\[\s*([^,\]]+)(?:\s*,\s*([^,\]]+))?\s*\]\s*=\s*pphp\.state/g;let r;for(;null!==(r=n.exec(e));){const e=r[1]?.trim(),n=r[2]?.trim();e&&t.add(e),n&&t.add(n)}const s=/pphp\.state\s*\(\s*['"]([^'"]+)['"]/g;for(;null!==(r=s.exec(e));){const e=r[1];if(e){t.add(e);const n=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;t.add(n)}}return t}extractDeclaredVariables(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const r=[/\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,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g,/\bexport\s+(?:function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)|(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*))/g];for(const e of r){let r;for(;null!==(r=e.exec(n));){const n=r[1]||r[2];if(e.source.includes("\\[")&&!e.source.includes("\\{")){const e=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith("...")?e.substring(3).trim():e));for(const n of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)&&t.add(n)}else if(e.source.includes("\\{")&&!e.source.includes("\\[")){const e=n.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 n of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)&&t.add(n)}else n&&t.add(n)}}return t}findScopedKeyForVariable(e,t){const n=t.join("."),r=this.getNested(this.props,n)||{};if(r&&e in r)return`${n}.${e}`;for(let n=t.length-1;n>=0;n--){const r=t.slice(0,n).join("."),s=r?this.getNested(this.props,r):this.props;if(s&&"object"==typeof s&&e in s)return r?`${r}.${e}`:e}return`${n}.${e}`}extractVariableReferences(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ");const r=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let s;for(;null!==(s=r.exec(n));){const e=s[1],r=s.index;if(this._reservedWords.has(e))continue;const i=n.substring(Math.max(0,r-50),r),o=n.substring(r+e.length,r+e.length+10);/\b(?:const|let|var|function|class|export)\s+$/.test(i)||(r>0&&"."===n[r-1]||/^\s*:/.test(o)||this.isActualFunctionParameter(n,r,e)||this.isInDestructuringDeclaration(n,r,e)||t.add(e))}return t}isActualFunctionParameter(e,t,n){let r=-1,s=-1,i=0;for(let n=t-1;n>=0;n--){const t=e[n];if(")"===t)i++;else if("("===t){if(0===i){r=n;break}i--}}if(-1===r)return!1;i=0;for(let r=t+n.length;r<e.length;r++){const t=e[r];if("("===t)i++;else if(")"===t){if(0===i){s=r;break}i--}}if(-1===s)return!1;const o=e.substring(Math.max(0,r-20),r).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){e.substring(r+1,s);const i=e.substring(t+n.length,s);return!i.includes("=>")&&!i.includes("{")}return!1}isInDestructuringDeclaration(e,t,n){const r=e.substring(Math.max(0,t-100),t);if(r.match(/\b(?:const|let|var)\s+\[\s*[^\]]*$/)){const r=e.substring(t+n.length,Math.min(e.length,t+n.length+100));if(/[^\]]*\]\s*=/.test(r))return!0}if(r.match(/\b(?:const|let|var)\s+\{\s*[^}]*$/)){const r=e.substring(t+n.length,Math.min(e.length,t+n.length+100));if(/[^}]*\}\s*=/.test(r))return!0}return!1}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;const n=t.join("."),r=this.getNested(this.props,n)||{};if(r&&e in r)return!0;for(let n=t.length-1;n>=0;n--){const r=t.slice(0,n),s=r.join(".");if(this.getScopedFunction(e,r))return!0;const i=s?this.getNested(this.props,s):this.props;if(i&&"object"==typeof i&&e in i)return!0;const o=s?`${s}.${e}`:e;if(this._stateHierarchy.has(o))return!0}return!1}_registerScopedFunction(e,t,n){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...r)=>{const s=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&r.length>0?n(r[0]):n(...r)}finally{this._currentExecutionScope=s}}))}extractSetters(e){const t=[],n=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let r;for(;r=n.exec(e);){const[,e,n,s]=r;"share"===s&&this.markShared(e),this._sharedStateMap.has(e)||t.push(n)}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,n,r,s)=>`${t}${n}, ${r}${s}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,r)=>`${t}${n}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,r)=>`${t}[${n}] = pphp.state('${n}', `))}stripComments(e){let t="",n=0,r=!1,s="",i=!1;for(;n<e.length;){const o=e[n],a=e[n+1];if(i||"'"!==o&&'"'!==o&&"`"!==o||"\\"===e[n-1])if(r)t+=o,n++;else if(i||"/"!==o||"*"!==a)if(i)"*"===o&&"/"===a?(i=!1,n+=2):n++;else if("/"!==o||"/"!==a)t+=o,n++;else for(;n<e.length&&"\n"!==e[n];)n++;else i=!0,n+=2;else r=!r,s=r?o:"",t+=o,n++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let n=!1;const r=this.getBindingType(t);for(const s of t.dependencies){for(const t of e)if(this.dependencyMatches(t,s,r)){n=!0;break}if(n)break}if(n)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 n=t.__deps||new Set,r=t.__functionDeps||[];if(0===n.size&&0===r.length){try{t()}catch(e){console.error("effect error:",e)}return}const s=[...n].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=r.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,n="binding"){const r=e=>{if(e.startsWith("app.")){const t=e.slice(4),n=t.split(".")[0];if(PPHP._shared.has(n))return t}return e},s=r(e),i=r(t);if(s===i||e===t)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;switch(n){case"effect":return this.matchEffectDependency(s,i);case"loop":return!(!PPHP.headMatch(s,i)&&!PPHP.headMatch(i,s))||!(!i.includes("*")&&!this.matchesArrayIndexPattern(s,i))&&this.matchLoopDependency(s,i);default:return!!PPHP.headMatch(s,i)||!(!i.includes("*")&&!this.matchesArrayIndexPattern(s,i))&&this.matchBindingDependency(s,i)}}matchEffectDependency(e,t){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 n=e.split("."),r=t.split(".");if(n.length!==r.length)return!1;for(let e=0;e<r.length;e++){const t=r[e],s=n[e];if("*"!==t&&t!==s)return!1}return!0}matchesArrayIndexPattern(e,t){const n=e.split("."),r=t.split(".");if(n.length!==r.length)return!1;for(let e=0;e<r.length;e++){const t=n[e],s=r[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){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,n){const r=t.split("."),s=r.pop(),i=r.reduce(((e,t)=>e[t]??={}),e);null===n||"object"!=typeof n||Array.isArray(n)||n.__isReactiveProxy?i[s]=n:i[s]=this.makeReactive(n,r.concat(s))}hasNested(e,t){const n=t.split(".");let r=e;for(let e=0;e<n.length;e++){const t=n[e];if(null==r||"object"!=typeof r)return!1;if(!(t in r))return!1;r=r[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 n=PPHP._shared.get(e);if(n)return[n.getter,n.setter];const r=this._currentProcessingHierarchy;this._currentProcessingHierarchy=["app"];const[s,i]=this.state(e,t);return this._currentProcessingHierarchy=r,PPHP._shared.set(e,{getter:s,setter:i}),[s,i]}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.`);const n=this._currentProcessingHierarchy||["app"],r=this.generateScopedKey(n,e);this._stateHierarchy.set(r,{originalKey:e,hierarchy:[...n],level:n.length}),this.hasNested(this.props,r)||this.setNested(this.props,r,t);const s=()=>this.getNested(this.props,r),i=e=>{const t=s(),n="function"==typeof e?e(t):e;this.setNested(this.props,r,n),this._dirtyDeps.add(r),n&&"object"==typeof n&&this.markNestedPropertiesDirty(r,n),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}}),o.__pphp_key=r;const a=s();if(null===a||"object"!=typeof a)return[o,i];const c=this;return[new Proxy(o,{apply:(e,t,n)=>Reflect.apply(e,t,n),get(e,t,n){if("value"===t)return s();if("__pphp_key"===t)return r;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,n);if("string"==typeof t){const n=s();if(n&&"object"==typeof n){const s=Object.prototype.hasOwnProperty.call(n,t),i=t in e&&void 0!==e[t];if(s||!i){let e=n[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...r.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,n);const i=s();return i&&"object"==typeof i?i[t]:void 0},set(e,t,n){if("value"===t)return i(n),!0;if("__isReactiveProxy"===t)return!0;const o=s();return o&&"object"==typeof o&&(o[t]=n,c._dirtyDeps.add(`${r}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in o)return!0;const n=s();return n&&"object"==typeof n&&t in n}}),i]}markNestedPropertiesDirty(e,t,n=new WeakSet){t&&"object"==typeof t&&!n.has(t)&&(n.add(t),Object.keys(t).forEach((r=>{const s=`${e}.${r}`;this._dirtyDeps.add(s);const i=t[r];i&&"object"==typeof i&&!n.has(i)&&this.markNestedPropertiesDirty(s,i,n)})))}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 n=>{const r=e.get(n);if(void 0!==r)return r;const s=n in globalThis||t.some((e=>n in e));return e.set(n,s),s}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let n=e.replace(/\?\./g,".");const r=new Set,s=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=s.exec(n);)(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>r.add(e)));const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(n);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>r.add(e)));const o=e=>{let t="",n=0;for(;n<e.length;)if("`"===e[n])for(n++;n<e.length;)if("\\"===e[n])n+=2;else if("$"===e[n]&&"{"===e[n+1]){n+=2;let r=1,s=n;for(;n<e.length&&r;)"{"===e[n]?r++:"}"===e[n]&&r--,n++;t+=o(e.slice(s,n-1))+" "}else{if("`"===e[n]){n++;break}n++}else t+=e[n++];return t};n=o(n),n=n.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),n=n.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const a=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of n.match(c)??[]){const[n,...s]=t.split(".");r.has(n)||(0===s.length&&PPHP._isBuiltIn(n)&&new RegExp(`\\.${n}\\b`).test(e)||0===s.length&&new RegExp(`\\b${t}\\s*\\(`).test(e)&&n in globalThis&&"function"==typeof globalThis[n]||a.add(t))}return a}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,n=PPHP._mustacheTest,r=this.props,s=new Set;this.qsa(e,"*").forEach((e=>{const r=this.detectElementHierarchy(e);for(const{name:i,value:o}of Array.from(e.attributes))if(o){if(n.test(o))for(const e of o.matchAll(t))this.extractScopedDependencies(e[1],r).forEach((e=>s.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(o,r).forEach((e=>s.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>n.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const n=e.parentElement;if(!n)continue;const r=this.detectElementHierarchy(n);for(const n of e.nodeValue.matchAll(t))this.extractScopedDependencies(n[1],r).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(".");let n=r;for(let e=0;e<t.length;e++){const r=t[e],s=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(r in n)||!s&&(null==n[r]||"object"!=typeof n[r])){const e=this._stateHierarchy.has(i);s&&e||(n[r]=s?void 0:{})}n=n[r]}}}async dispatchEvent(e,t){try{if("string"!=typeof e||""===e.trim())return console.error("PPHP.dispatchEvent: target must be a non-empty string"),!1;const n=e.trim(),r=n.match(/^(?:app\.)?(.+)$/);if(r){const[,e]=r,n=e.split(".")[0];if(PPHP._shared.has(n)){const r=PPHP._shared.get(n);if(e===n){const e="function"==typeof t?t(r.getter()):t;r.setter(e)}else{const s=r.getter(),i=e.substring(n.length+1);if(!s||"object"!=typeof s)return console.error(`PPHP.dispatchEvent: Cannot update nested property '${i}' on non-object shared state`),!1;{const e=this.updateNestedValue(s,i,t);r.setter(e)}}return await this.waitForFlush(),!0}}const s=this.determineCurrentComponentHierarchy(),i=this.resolveStatePath(n,s);if(!i)return console.error(`PPHP.dispatchEvent: Could not resolve state path '${n}' in hierarchy [${s.join(" -> ")}]`),!1;const o=this.hasNested(this.props,i)?this.getNested(this.props,i):void 0,a="function"==typeof t?t(o):t;if(this.setNested(this.props,i,a),this._dirtyDeps.add(i),a&&"object"==typeof a&&this.markNestedPropertiesDirty(i,a),i.startsWith("app.")){const e=i.substring(4);this._dirtyDeps.add(e)}return await this.waitForFlush(),!0}catch(e){return console.error("PPHP.dispatchEvent: Error updating state",e),!1}}determineCurrentComponentHierarchy(){const e=this.getEventSourceHierarchy();if(e.length>0)return e;if(this._currentProcessingHierarchy)return[...this._currentProcessingHierarchy];if(this._currentExecutionScope){return this._currentExecutionScope.split(".")}if(this._currentEffectContext){return this._currentEffectContext.split(".")}const t=this.getCurrentScriptHierarchy();if(t.length>0)return t;const n=this.getActiveElementHierarchy();return n.length>0?n:["app"]}trackEventContext(e){e.currentTarget instanceof Element&&(this._currentEventTarget=e.currentTarget,this._eventContextStack.push(e.currentTarget),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 n=t.closest("[pp-component]");n&&(e=n)}}if(!e){const t=document.querySelector("[data-pphp-recent-interaction]");t&&(e=t)}if(e)return this.buildComponentHierarchy(e)}catch(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=[],n=[];let r=e;for(;r;){const e=r.getAttribute("pp-component");e&&n.unshift(e),r=r.parentElement}return t.push(...n),t}resolveStatePath(e,t){if(e.includes(".")&&this.hasNested(this.props,e))return e;for(let n=t.length-1;n>=0;n--){const r=t.slice(0,n+1).join(".")+"."+e;if(this.hasNested(this.props,r))return r}for(const[t,n]of this._stateHierarchy.entries())if(n.originalKey===e||t.endsWith("."+e))return t;return t.length>1?t.join(".")+"."+e:e}waitForFlush(){return new Promise((e=>{if(this._updateScheduled||0!==this._dirtyDeps.size)if(this._updateScheduled){const t=()=>{this._updateScheduled?requestAnimationFrame(t):e()};requestAnimationFrame(t)}else this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings(),e()}));else e()}))}updateNestedValue(e,t,n){const r=t.split("."),s={...e};let i=s;for(let e=0;e<r.length-1;e++){const t=r[e];null==i[t]||"object"!=typeof i[t]?i[t]={}:i[t]={...i[t]},i=i[t]}const o=r[r.length-1],a=i[o];return i[o]="function"==typeof n?n(a):n,s}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)return this._currentEffectContext;const e=this._currentProcessingHierarchy||this._currentExecutionScope?.split(".")||null;if(e&&e.length>0){return e[e.length-1]}const n=document.currentScript;if(n&&(t=n),!t){const e=this.determineCurrentComponentHierarchy();if(e.length>0)return e.length>1?e[e.length-1]:e[0]}}if(t)return this.findComponentFromElement(t);const n=this.getFallbackComponent();return n||(console.warn("PPHP: Could not determine current component context",{hasEffectContext:!!this._currentEffectContext,processingHierarchy:this._currentProcessingHierarchy,executionScope:this._currentExecutionScope,eventHierarchy:this.determineCurrentComponentHierarchy(),currentScript:!!document.currentScript}),null)}findComponentFromElement(e){const t=e.getAttribute("pp-component");if(t)return t;let n=e.parentElement;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");if(e)return e;n=n.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=(new DOMParser).parseFromString(this.sanitizePassiveHandlers(e),"text/html");this.scrubTemplateValueAttributes(t),this.reconcileHead(t),this.resetProps(),await this.removeAllEventListenersOnNavigation(),this.ensurePageTransitionStyles();const n=async()=>{morphdom(document.body,t.body,{childrenOnly:!0}),await this.initReactiveOn(),this.attachWireFunctionEvents()};"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",n="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${n}]`).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 n=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,r=t.cloneNode(!0),s=document.head.querySelector(n);s?document.head.replaceChild(r,s):document.head.insertBefore(r,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const t=e.cloneNode(!0),n=document.head.querySelector("title");n?document.head.replaceChild(t,n):document.head.appendChild(t);break}case"LINK":{const t=e;if("icon"===t.rel){const e=t.cloneNode(!0),n=document.head.querySelector('link[rel="icon"]');n?document.head.replaceChild(e,n):document.head.appendChild(e)}else t.hasAttribute(n)&&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")}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const n=e,r=t;return n.value!==r.value&&(r.value=n.value),r.checked=n.checked,document.activeElement!==n||(null!=n.selectionStart&&(r.selectionStart=n.selectionStart,r.selectionEnd=n.selectionEnd),!1)},TEXTAREA(e,t){const n=e,r=t;return n.value!==r.value&&(r.value=n.value),document.activeElement!==n||(r.selectionStart=n.selectionStart,r.selectionEnd=n.selectionEnd,!1)},SELECT(e,t){const n=e;return t.selectedIndex=n.selectedIndex,document.activeElement!==n},VIDEO(e,t){const n=e,r=t;return r.currentTime=n.currentTime,n.paused?r.pause():r.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,n=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 n=new Function("event",t);e.addEventListener("wheel",n,{passive:!0})}})),this._wheelHandlersStashed=!0);const r=this.PRESERVE_HANDLERS;morphdom(t,n,{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 n=e.tagName;if("SCRIPT"===n||e.hasAttribute("data-nomorph"))return!1;const s=r[n];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)}}async attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(","),t=this.qsa(document.body,e);for(const e of t)for(const t of this._eventHandlers){const n=e.getAttribute(t);if(!n)continue;const r=this.decodeEntities(n).trim();if(!r){e.removeAttribute(t);continue}const s=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(r))} }`;e.removeAttribute(t);const i=t.slice(2);e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,s)}return this.handlePassiveWheelStashes(document),Promise.resolve()}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let n=t.value;for(;n.includes("&");){t.innerHTML=n;const e=t.value;if(e===n)break;n=e}return n};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 n=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(n){let t=e.substring(n[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let r=e.trim();return r&&!r.endsWith(";")&&(r+=";"),r};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,r)=>{const s=`${t}->${n}(${r.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,n,r)=>{const s=`${t}::${n}(${r.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(s)}, event);`}));const{normalized:n,originalParam:r}=this.normalizeToArrow(t),s=this.renameEventParam(n,r);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 n=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(n)?n:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const n=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(n,((e,t,n)=>{const r=n[t-1],s=n[t+e.length];return r&&/[\w$]/.test(r)||s&&/[\w$]/.test(s)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,n){const r=e.getAttribute("pp-debounce"),s=r?this.parseTime(r):0,i=e.getAttribute("pp-before-request")??"",o=e.getAttribute("pp-after-request")??"",a=PPHP._cancelableEvents,c=async r=>{a.has(t)&&r.cancelable&&r.preventDefault();try{i&&await this.invokeHandler(e,i,r),await this.invokeHandler(e,n,r),o&&!o.startsWith("@close")&&await this.invokeHandler(e,o,r)}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 n=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),s);PPHP._debounceTimers.set(h,n)}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,n=!1){let r;return function(...s){const i=this;r&&clearTimeout(r),r=setTimeout((()=>{r=null,n||e.apply(i,s)}),t),n&&!r&&e.apply(i,s)}}async invokeHandler(e,t,n){try{const r=t.trim();let s=this._handlerCache.get(r);s||(s=this.parseHandler(r),this._handlerCache.set(r,s)),await this.executeHandler(s,e,n,r)}catch(n){this.handleInvokeError(n,t,e)}finally{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 n=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(n)return{type:"call",name:n[1],args:n[2],isAsync:this.isAsyncFunction(n[1])};const r=t.match(/^(\w+)$/);return r?{type:"simple",name:r[1],isAsync:this.isAsyncFunction(r[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,n="",r=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===n&&"\\"!==e[s-1])t=!1,n="";else if(!t&&("("===i&&r++,")"===i&&r--,"="===i&&">"===o&&r>=0))return!0}else t=!0,n=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let n=e.substring(t+2).trim();return n.startsWith("{")&&n.endsWith("}")&&(n=n.slice(1,-1).trim()),{type:"arrow",body:n,isAsync:e.includes("async")||this.containsAwait(n)}}findArrowIndex(e){let t=!1,n="";for(let r=0;r<e.length-1;r++){const s=e[r],i=e[r+1];if(t||'"'!==s&&"'"!==s&&"`"!==s){if(t&&s===n&&"\\"!==e[r-1])t=!1;else if(!t&&"="===s&&">"===i)return r}else t=!0,n=s}return-1}async executeArrowHandler(e,t,n){const r=this.parseStatements(e.body);let s=!1;for(const e of r)await this.executeSingleStatement(e,t,n)&&(s=!0);s||await this.executeDynamic(e.body,t,n)}async executeComplexHandler(e,t,n){await this.executeDynamic(e.body,t,n)}parseStatements(e){const t=[];let n="",r=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||r++,")"!==a&&"}"!==a&&"]"!==a||r--,";"!==a||0!==r)?n+=a:n.trim()&&(t.push(n.trim()),n="")}return n.trim()&&t.push(n.trim()),t}async executeInlineModule(e,t,n,r,s){if(t&&t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t);null!==n&&"object"==typeof n?await this.callInlineModule(e,{...n}):await this.callInlineModule(e,n)}else try{const r=this.detectElementHierarchy(n),s=this._createScopedPropsContext(r),i=this.makeScopedEvaluator(t,r)(s);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:n,event:r})}else await this.handleParsedCallback(n,s,r)}async executeSingleStatement(e,t,n){const r=e.trim();if(!r)return!1;const s=r.match(/^\(\s*\)\s*=>\s*(.+)$/);if(s)return this.executeSingleStatement(s[1],t,n);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(r))return await this.executeDynamic(r,t,n),!0;const i=r.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),r=/\bevent\b/.test(s)?s.replace(/\bevent\b/g,"_evt"):s;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${r} ]; }`)(n,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,n,r),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,r,n),!0}const o=r.match(/^(\w+)$/);if(o){const e=o[1],r=this.detectElementHierarchy(t),s=this.resolveFunctionName(e,r);if(s){if(this.getScopedFunction(s,r))return await this.handleParsedCallback(t,`${s}()`,n),!0}if(s){const e=globalThis[s];if("function"==typeof e)return e.call(globalThis,n),!0}return await this.handleParsedCallback(t,`${e}()`,n),!0}return await this.executeDynamic(r,t,n),!0}async executeCallHandler(e,t,n,r){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,n,r);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,n)}await this.handleParsedCallback(t,r,n)}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 n=t.length;n>=0;n--){const r=t.slice(0,n).join("."),s=this._inlineModuleFns.get(r);if(s&&s.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,n){const{name:r}=e,s=this.detectElementHierarchy(t),i=this.resolveFunctionName(r,s);if(i){if(this.getScopedFunction(i,s))return void await this.handleParsedCallback(t,`${i}()`,n);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,n)}await this.handleParsedCallback(t,`${r}()`,n)}async executeHandler(e,t,n,r){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,n);break;case"call":await this.executeCallHandler(e,t,n,r);break;case"simple":await this.executeSimpleHandler(e,t,n);break;case"complex":await this.executeComplexHandler(e,t,n);break;default:await this.handleParsedCallback(t,r,n)}}async executeGlobalFunction(e,t,n,r){if(t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t)??{};e.call(globalThis,{...n})}else{const s=this.detectElementHierarchy(n),i=this._createScopedPropsContext(s),o=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(n,r,o,i,e)}else e.call(globalThis,r)}async executeDynamic(e,t,n){const r=this.detectElementHierarchy(t),s=this._createScopedPropsContext(r),i=this.getOrCreateProxy(s),o=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await o.call(t,n,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"],n={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,r,s)=>{if("string"==typeof r){if(n.hasOwnProperty(r))return n[r];const i=this.getScopedFunction(r,t);if(i)return i;if(r in e){const t=Reflect.get(e,r,s),n=globalThis[r];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(r)&&typeof t!=typeof n))return t}if(r in globalThis&&!n.hasOwnProperty(r)){const e=globalThis[r];return"function"==typeof e&&/^[a-z]/.test(r)?e.bind(globalThis):e}}return Reflect.get(e,r,s)},set:(e,t,n,r)=>Reflect.set(e,t,n,r),has:(e,t)=>{if("string"==typeof t){const r=this._currentProcessingHierarchy||["app"];return n.hasOwnProperty(t)||!!this.getScopedFunction(t,r)||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,n){const r=e instanceof Error?e.message:String(e),s=n.tagName+(n.id?`#${n.id}`:"");console.error(`Handler execution failed on ${s}:\nHandler: "${t}"\nError: ${r}`,e),n.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:n},bubbles:!0}))}async handleParsedCallback(e,t,n){const{funcName:r,data:s}=this.parseCallback(e,t);if(!r)return;const i=Array.isArray(r)?r:[r],o=this.detectElementHierarchy(e);let a;for(const e of i){const t=this.getScopedFunction(e,o);if(t){a=t;break}if("function"==typeof this[e]){a=this[e];break}if("function"==typeof window[e]){a=window[e];break}}if(a){const t=e.hasAttribute("pp-after-request"),r="@close"===e.getAttribute("pp-after-request");let i={args:Array.isArray(s.args)?s.args:[],element:e,data:s,event:n};if(t&&!r){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};i={...i,...e}}await a.call(this,i)}else this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(r)?r[0]:r,s)}async handleUndefinedFunction(e,t,n){const r={callback:await this.encryptCallbackName(t),...n},s=this.createFetchOptions(r),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const r=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(r.href,t,l,n),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(r.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(r.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 n=this.parseJson(e),r=t?this.parseJson(t):null,s=n.targets;Array.isArray(s)&&s.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);let i={};if(r){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(i[t]=e.responseKey?r[e.responseKey]:r.response);break;default:i[t]=n[t]}}else i=n;s&&this.updateElementAttributes(s,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,n)=>` data-onwheel-code="${this.decodeEntities(n).replace(/"/g,"&quot;")}"`)).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,n,r){const s=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,n,r),o=(new DOMParser).parseFromString(s,"text/html");i&&o.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(o.body.outerHTML)}getUpdatedHTMLContent(e,t,n){const r=document.createElement("div");if(r.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");r.innerHTML=t}else r.innerHTML=e;return r.innerHTML?r:null}async updateBodyContent(e){try{this.saveElementState();const t=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(t),await this.appendCallbackResponse(t),await this.populateDocumentBody(t),await this.removeAllEventListenersOnNavigation(),await this.initReactiveOn(),this.attachWireFunctionEvents(),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 n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=this.decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=this.decodeHTML(t[n]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[n]));break;case"classList.replace":const[r,s]=this.decodeHTML(t[n]).split(",");e.classList.replace(r,s);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=this.decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,this.decodeHTML(t[n]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let n=document.getElementById(t);n?(n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n)):(n=document.createElement("div"),n.id=t,n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const n=(e,t)=>{for(const n in t)t.hasOwnProperty(n)&&("textContent"===n?e.textContent=t[n]:"innerHTML"===n?e.innerHTML=t[n]:"disabled"===n?!0===t[n]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(n,t[n]));for(const n of Array.from(e.attributes))t.hasOwnProperty(n.name)||e.removeAttribute(n.name)},r=(e,t)=>{for(const r in t)if(t.hasOwnProperty(r))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 r=this.parseJson(e);n(t,r)}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?r(e,t):n(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 r=this.parseJson(t);n(e,r)}}}const s=new FormData(e),i={};if(s.forEach(((e,t)=>{i[t]=e})),r(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,...n}=e,r=document.querySelector(t);r&&i(r,n)}));const{targets:t,...r}=s;n(e,r)}else{const{empty:t,...r}=s;n(e,r)}}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,n,r={}){const s=new FormData,i=n.files;if(i)for(let e=0;e<i.length;e++)s.append("file[]",i[e]);s.append("callback",t);for(const e in r)r.hasOwnProperty(e)&&s.append(e,r[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 n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))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 n=this.parseJson(e);"disabled"!==n.onsubmit&&this.updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);r&&s(r,n)}))}else r(t,e)}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},s=(e,t)=>{e instanceof HTMLFormElement?n(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),r.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=r;this.updateElementAttributes(e,o),n(e,s)}else if(r.targets){r.targets.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);r&&s(r,n)}));const{targets:t,...n}=r;this.updateElementAttributes(e,n)}else{if("disabled"===r.empty&&""===e.value)return;const{empty:t,...n}=r;this.updateElementAttributes(e,n)}}else if(t)r(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),n(e,r)}}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 n=0;n<e.attributes.length;n++){const r=e.attributes[n];t[r.name]=r.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const n=e.id;n&&(t=document.querySelector(`[form="${n}"]`)),n&&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,n)=>{e[n]=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 n={};const r=e.closest("form");if(r){new FormData(r).forEach(((e,t)=>{const r=this.clean(e);n[t]?n[t]=Array.isArray(n[t])?[...n[t],r]:[n[t],r]:n[t]=r}))}else e instanceof HTMLInputElement?n=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const s=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(s){const e=s[1].trim(),t=s[2].trim(),r=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e&&(n={...n,...e})}catch(e){console.error("Error parsing JSON args:",e),n.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e?n={...n,...e}:n.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),n.rawArgs=t}else if(/^[\s\d"'[\{]/.test(t))try{const e=new Function(`return [${t}];`)();n.args=Array.isArray(e)?e:[e]}catch{r.test(t)?n.args=t.split(r).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):n.args=[t.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(t)(this.props);n.args=[e]}catch{n.args=t.split(r).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:n}}return{funcName:t,data:n}}clean(e){if("string"!=typeof e)return e;let t=e.replace(/&quot;/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 n=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=n?n.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}setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const n=parseInt(t.length,10)||0;e.setSelectionRange(n,n)}}handleInputAppendParams(e,t){const n=e.getAttribute("pp-append-params"),r=e.getAttribute("pp-append-params-sync");if("true"===n){if("true"===r){const t=e.name||e.id;if(t){const n=new URL(window.location.href),r=new URLSearchParams(n.search);r.has(t)&&(e.value=r.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,n=t.value,r=new URL(window.location.href),s=new URLSearchParams(r.search),i=t.name||t.id;if(i){n?s.set(i,n):s.delete(i);const e=s.toString()?`${r.pathname}?${s.toString()}`:r.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),n=this.handleElementVisibility.bind(this),r=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",n))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",r)))}handleVisibilityElementAttribute(e,t,n){const r=e.getAttribute(t);if(r)if(this.isJsonLike(r)){n(e,this.parseJson(r))}else{const n=this.parseTime(r);if(n>0){const r="pp-visibility"===t?"visibility":"display",s="visibility"===r?"hidden":"none";this.scheduleChange(e,n,r,s)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,n,r,s){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[n]=r,this.scheduleChange(e,i,n,s),o>0&&this.scheduleChange(e,i+o,n,r)):o>0&&this.scheduleChange(e,o,n,r)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),r=t.getAttribute("target");if(n&&"_blank"!==r&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(n)&&!n.startsWith(window.location.origin))window.location.href=n;else{const e=t.getAttribute("pp-append-params");let r="";if(n.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[i,o]=n.split("#");o&&(s=`#${o}`);new URLSearchParams(i.split("?")[1]).forEach(((e,n)=>{t.set(n,e)})),r=`${e.pathname}?${t.toString()}${s}`}else{const[e,t]=n.split("#");r=`${e}${t?`#${t}`:""}`}const s="prev"===(t.getAttribute("pp-loading-from")??"next")?window.location.pathname:new URL(r,window.location.origin).pathname;history.pushState(null,"",r);const i=n.indexOf("#");if(-1!==i){const e=n.slice(i+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation(s);const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation(s)}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(e){try{const t=document.getElementById("loading-file-1B87E");if(t){const n=e??window.location.pathname,r=this.findLoadingElement(t,n);r&&await this.updateContentWithTransition(r)}const n=await this.fetch(window.location.href),r=await n.text();if(!n.ok)return await this.updateDocumentContent(r),void console.error(`Navigation error: ${n.status} ${n.statusText}`);const s=r.match(this._redirectRegex);if(s&&s[1])return void await this.redirect(s[1]);await this.updateDocumentContent(r)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let n=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;const r=n.lastIndexOf("/");n=r<=0?"/":n.substring(0,r)}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:n,fadeOut:r}=this.parseTransition(e);await this.fadeOut(t,r),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const r=e.querySelector("[pp-loading-transition]"),s=r?.getAttribute("pp-loading-transition");if(s){const e=this.parseJson(s);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",s)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),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&&this._activeAbortController.abort()}async fetch(e,t,n=!1){let r;return n?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,r=this._activeAbortController):r=new AbortController,fetch(e,{...t,signal:r.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){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("=>"))}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,n,r){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=r}))}),t)}async fetchFunction(e,t={},n=!1){try{const r={callback:await this.encryptCallbackName(e),...t},s=window.location.href;let i;if(Object.keys(r).some((e=>{const t=r[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(r).forEach((t=>{const n=r[t];n instanceof File?e.append(t,n):n instanceof FileList?Array.from(n).forEach((n=>e.append(t,n))):e.append(t,n)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(r);const o=await this.fetch(s,i,n);if(!o.ok)throw new Error(`Fetch failed with status: ${o.status} ${o.statusText}`);const a=await o.text();try{return JSON.parse(a)}catch{return a}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{this.saveElementState();const t=e.length?e:["true"],n=e=>`[pp-sync="${e}"]`,r=await this.fetch(window.location.href,this.createFetchOptions({pphpSync71163:!0,selectors:t,secondRequestC69CD:!0,...this.getUrlParams()}));let s;if(r.headers.get("content-type")?.includes("application/json")){s=(await r.json()).fragments}else s={[t[0]]:await r.text()};const i=`<body>${Object.values(s).join("")}</body>`,o=(new DOMParser).parseFromString(i,"text/html");await this.initReactiveOn(o),t.forEach((e=>{const t=n(e),r=document.querySelectorAll(t),s=o.body.querySelector(t);s&&r.forEach((e=>e.innerHTML=s.innerHTML))})),this.restoreElementState(),this.attachWireFunctionEvents()}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),n=await t.text();await this.updateBodyContent(n)}copyCode(e,t,n,r,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,n]of Object.entries(r))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,r]of Object.entries(n))e in t?t[e]=r:t.setAttribute(e,r)}),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 n={...this.state,...e};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,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 n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const r=e[n];null!==r&&t.set(n,r)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "3.4.5",
3
+ "version": "3.4.7",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",