create-prisma-php-app 3.4.7 → 3.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -136,12 +136,12 @@ export async function installComposerDependencies(baseDir, dependencies) {
|
|
|
136
136
|
const npmPinnedVersions = {
|
|
137
137
|
"@tailwindcss/postcss": "^4.1.11",
|
|
138
138
|
"@types/browser-sync": "^2.29.0",
|
|
139
|
-
"@types/node": "^24.
|
|
139
|
+
"@types/node": "^24.2.1",
|
|
140
140
|
"@types/prompts": "^2.4.9",
|
|
141
141
|
"browser-sync": "^3.0.4",
|
|
142
|
-
chalk: "^5.
|
|
142
|
+
chalk: "^5.5.0",
|
|
143
143
|
"chokidar-cli": "^3.0.0",
|
|
144
|
-
cssnano: "^7.0
|
|
144
|
+
cssnano: "^7.1.0",
|
|
145
145
|
"http-proxy-middleware": "^3.0.5",
|
|
146
146
|
"npm-run-all": "^4.1.5",
|
|
147
147
|
"php-parser": "^3.2.5",
|
|
@@ -150,7 +150,7 @@ const npmPinnedVersions = {
|
|
|
150
150
|
prompts: "^2.4.2",
|
|
151
151
|
tailwindcss: "^4.1.11",
|
|
152
152
|
tsx: "^4.20.3",
|
|
153
|
-
typescript: "^5.
|
|
153
|
+
typescript: "^5.9.2",
|
|
154
154
|
};
|
|
155
155
|
function npmPkg(name) {
|
|
156
156
|
return npmPinnedVersions[name] ? `${name}@${npmPinnedVersions[name]}` : name;
|
|
@@ -577,7 +577,6 @@ async function main() {
|
|
|
577
577
|
projectRootPath: projectPathModified,
|
|
578
578
|
phpEnvironment: "XAMPP",
|
|
579
579
|
phpRootPathExe: "C:\\xampp\\php\\php.exe",
|
|
580
|
-
phpGenerateClassPath: "src/Lib/Prisma/Classes",
|
|
581
580
|
bsTarget: bsConfig.bsTarget,
|
|
582
581
|
bsPathRewrite: bsConfig.bsPathRewrite,
|
|
583
582
|
backendOnly: answer.backendOnly,
|
|
@@ -47,6 +47,73 @@ class PHPX implements IPHPX
|
|
|
47
47
|
$this->children = $props['children'] ?? '';
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Convert a property name to a JavaScript variable path.
|
|
52
|
+
*
|
|
53
|
+
* This method generates a JavaScript variable path for the given property name,
|
|
54
|
+
* based on the current component hierarchy. It is used to access properties in
|
|
55
|
+
* the JavaScript context of the component.
|
|
56
|
+
*
|
|
57
|
+
* @param string $name The property name to convert.
|
|
58
|
+
* @return string The JavaScript variable path for the property.
|
|
59
|
+
*/
|
|
60
|
+
protected function propsAsVar(string $name): string
|
|
61
|
+
{
|
|
62
|
+
if (empty($name)) {
|
|
63
|
+
return '';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
$hierarchy = $this->getComponentHierarchy();
|
|
67
|
+
|
|
68
|
+
if (count($hierarchy) > 1 && end($hierarchy) === self::$currentComponentId) {
|
|
69
|
+
array_pop($hierarchy);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return "pphp.props." . implode('.', $hierarchy) . ".{$name}";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Emit a client-side dispatch call.
|
|
77
|
+
*
|
|
78
|
+
* @param non-empty-string|null $name Reactive key (e.g. "myVar", "voucher.total", or "app.s9ggniz.myVar").
|
|
79
|
+
* @param mixed $value Raw JS inserted verbatim (variable, expression, or pre-JSON-encoded value).
|
|
80
|
+
* @param array{
|
|
81
|
+
* scope?: 'current'|'parent'|'root'|string[]
|
|
82
|
+
* } $options Dispatch options (defaults to ['scope' => 'current']).
|
|
83
|
+
*
|
|
84
|
+
* @return string JavaScript snippet like: pphp.dispatchEvent("myVar", 123, {"scope":"current"});
|
|
85
|
+
*/
|
|
86
|
+
protected function dispatchEvent(?string $name, $value, array $options = []): string
|
|
87
|
+
{
|
|
88
|
+
$name = trim((string) $name);
|
|
89
|
+
if ($name === '') {
|
|
90
|
+
return '';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// normalize options
|
|
94
|
+
$opts = $options;
|
|
95
|
+
if (!array_key_exists('scope', $opts)) {
|
|
96
|
+
$opts['scope'] = 'current';
|
|
97
|
+
} else {
|
|
98
|
+
if (is_string($opts['scope'])) {
|
|
99
|
+
$allowed = ['current', 'parent', 'root'];
|
|
100
|
+
if (!in_array($opts['scope'], $allowed, true)) {
|
|
101
|
+
$opts['scope'] = 'current';
|
|
102
|
+
}
|
|
103
|
+
} elseif (is_array($opts['scope'])) {
|
|
104
|
+
$opts['scope'] = array_values(array_map('strval', $opts['scope']));
|
|
105
|
+
} else {
|
|
106
|
+
$opts['scope'] = 'current';
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// safely encode name/options; value is inserted verbatim
|
|
111
|
+
$jsName = json_encode($name, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
112
|
+
$jsOpts = json_encode($opts, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
113
|
+
|
|
114
|
+
return "pphp.dispatchEvent({$jsName}, {$value}, {$jsOpts});";
|
|
115
|
+
}
|
|
116
|
+
|
|
50
117
|
/**
|
|
51
118
|
* Set the component hierarchy and current component ID (called by TemplateCompiler during rendering)
|
|
52
119
|
*
|
|
@@ -75,16 +142,6 @@ class PHPX implements IPHPX
|
|
|
75
142
|
return null;
|
|
76
143
|
}
|
|
77
144
|
|
|
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
145
|
/**
|
|
89
146
|
* Get the full component hierarchy as an array.
|
|
90
147
|
* Useful for building complete hierarchy paths for JavaScript.
|
|
@@ -93,26 +150,7 @@ class PHPX implements IPHPX
|
|
|
93
150
|
*/
|
|
94
151
|
protected function getComponentHierarchy(): array
|
|
95
152
|
{
|
|
96
|
-
|
|
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};";
|
|
153
|
+
return self::$currentHierarchy ?? ['app'];
|
|
116
154
|
}
|
|
117
155
|
|
|
118
156
|
/**
|
|
@@ -411,7 +411,6 @@ class TemplateCompiler
|
|
|
411
411
|
array $incomingProps
|
|
412
412
|
): string {
|
|
413
413
|
$mapping = self::selectComponentMapping($componentName);
|
|
414
|
-
$instance = self::initializeComponentInstance($mapping, $incomingProps);
|
|
415
414
|
|
|
416
415
|
$baseId = 's' . base_convert(sprintf('%u', crc32($mapping['className'])), 10, 36);
|
|
417
416
|
$idx = self::$componentInstanceCounts[$baseId] ?? 0;
|
|
@@ -421,6 +420,10 @@ class TemplateCompiler
|
|
|
421
420
|
$originalStack = self::$sectionStack;
|
|
422
421
|
self::$sectionStack[] = $sectionId;
|
|
423
422
|
|
|
423
|
+
PHPX::setRenderingContext($originalStack, $sectionId);
|
|
424
|
+
|
|
425
|
+
$instance = self::initializeComponentInstance($mapping, $incomingProps);
|
|
426
|
+
|
|
424
427
|
$childHtml = '';
|
|
425
428
|
foreach ($node->childNodes as $c) {
|
|
426
429
|
$childHtml .= self::processNode($c);
|
package/dist/src/app/js/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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,""")}"`)).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(/"/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();
|
|
1
|
+
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map,r=new WeakMap,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);function i(e){const t=e.currentTarget;if(t instanceof Element)return t;if(t instanceof Document||t===window)return document.body||document.documentElement||null;const n=e.target;if(n instanceof Element)return n;if(n&&"number"==typeof n.nodeType){const e=n;return e.parentElement||e.ownerDocument?.body||null}const r=e.composedPath?.();if(Array.isArray(r))for(const e of r)if(e instanceof Element)return e;return document.body||document.documentElement||null}function o(e,t){const n=globalThis.pphp??globalThis.PPHP?.instance??null;if(!n||!e)return t();let r=["app"];try{r=n.detectElementHierarchy(e)||["app"]}catch{r=["app"]}const s={eff:n._currentEffectContext,proc:n._currentProcessingHierarchy,evt:n._currentEventTarget};try{return n._currentEffectContext=r.join("."),n._currentProcessingHierarchy=r,n._currentEventTarget=e,t()}finally{n._currentEffectContext=s.eff,n._currentProcessingHierarchy=s.proc,n._currentEventTarget=s.evt}}function a(e,t,n){const s=function(e,t){let n=r.get(e);n||(n=new Map,r.set(e,n));let s=n.get(t);return s||(s=new Map,n.set(t,s)),s}(e,t),a=s.get(n);if(a)return a;let c;if("function"==typeof n){const e=n;c=function(t){return o(i(t),(()=>e.call(this,t)))}}else{const e=n;c={handleEvent:t=>o(i(t),(()=>e.handleEvent(t)))}}return s.set(n,c),c}EventTarget.prototype.addEventListener=function(t,r,i){let o=i;s.has(t)&&(void 0===o?o={passive:!0}:"boolean"==typeof o?o={capture:o,passive:!0}:void 0===o.passive&&(o={...o,passive:!0})),n.has(this)||n.set(this,new Map);const c=n.get(this),l=c.get(t)||new Set;l.add(r),c.set(t,l);const h=a(this,t,r);return e.call(this,t,h,o)},EventTarget.prototype.removeEventListener=function(e,s,i){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)}const o=r.get(this)?.get(e),a=o?.get(s)??s;t.call(this,e,a,i),o?.delete(s)},EventTarget.prototype.removeAllEventListeners=function(e){const s=n.get(this);if(s){if(e){const n=s.get(e);if(!n)return;const i=r.get(this)?.get(e);return n.forEach((n=>{const r=i?.get(n)??n;t.call(this,e,r),i?.delete(n)})),void s.delete(e)}s.forEach(((e,n)=>{const s=r.get(this)?.get(n);e.forEach((e=>{const r=s?.get(e)??e;t.call(this,n,r)}))})),n.delete(this),r.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._rawProps={},this.props=this.makeReactive({}),this.setupGlobalEventTracking(),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}debugProps(){console.group("%cPPHP Debug Snapshot","font-weight:bold; color:teal"),console.groupCollapsed("📦 Raw props"),console.log(JSON.stringify(this.props,null,2)),console.groupEnd(),console.groupCollapsed("🌐 Shared state (pphp.share)"),0===PPHP._shared.size?console.log("(none)"):console.table(Array.from(PPHP._shared.entries()).map((([e,{getter:t}])=>({key:e,value:this.formatValue(t()),type:typeof t()})))),console.groupEnd(),console.groupCollapsed("🔗 Shared keys declared this run"),0===this._sharedStateMap.size?console.log("(none)"):console.log([...this._sharedStateMap]),console.groupEnd(),console.groupCollapsed("🔖 State hierarchy"),console.table(Array.from(this._stateHierarchy.entries()).map((([e,t])=>({scopedKey:e,originalKey:t.originalKey,level:t.level,value:this.formatValue(this.getNested(this.props,e)),path:t.hierarchy.join(" → ")})))),console.groupEnd(),console.groupCollapsed("⚙️ Reactive internals"),console.log("Bindings total:",this._bindings.length),console.log("Pending bindings:",this._pendingBindings.size),console.log("Effects:",this._effects.size),console.log("Pending effects:",this._pendingEffects.size),console.log("Dirty deps:",Array.from(this._dirtyDeps).join(", ")||"(none)"),console.groupEnd(),console.groupCollapsed("🔗 Refs"),console.table(Array.from(this._refs.entries()).map((([e,t])=>({key:e,count:t.length,selectors:t.map((e=>e.tagName.toLowerCase())).join(", ")})))),console.groupEnd(),console.groupCollapsed("📦 Inline modules"),this._inlineModuleFns.forEach(((e,t)=>{console.log(`${t}:`,[...e.keys()])})),console.groupEnd(),console.log("Hydrated:",this._hydrated),console.groupCollapsed("🔀 Conditionals (pp-if chains)");Array.from(document.querySelectorAll("[pp-if], [pp-elseif], [pp-else]")).forEach(((e,t)=>{const 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 instanceof Element?e:document.body||null;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return t.length?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=i.join("."),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._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.error("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(s);const e=o(c);l=Array.isArray(e)?e:[]}if(!Array.isArray(l))return void console.warn("Loop expression did not return an array:",l);const h=this.calculateLoopDiff(i.previousList,l);this.applyLoopChanges(h,i,t,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(null===i||"object"!=typeof i)return i;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&&!r.shouldUnwrapValue(i))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||r.shouldUnwrapValue(s)||(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 (error) {\n return "";\n }\n `;let s;try{s=new Function("ctx",r)}catch(t){console.error("Expression compilation error:",t.message,"Expression:",n);const r=JSON.stringify(e);s=new Function("ctx",`try { return ${r}; } catch { return ""; }`)}return e=>{try{const n=this._createScopedPropsContext(t,e),r=s(n);return null==r?"":r}catch(e){return e instanceof Error?console.error("Scoped evaluation error:",e.message,"Expression:",n):console.error("Scoped evaluation error:",e,"Expression:",n),""}}}_createScopedPropsContext(e,t={}){const n=e.join("."),r=this.getNested(this.props,n)||{},s=this,i=(e,t)=>{if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch(n){return console.error(`Failed to unwrap reactive proxy function for ${t}:`,n),e}if(e&&"object"==typeof e&&e.__isReactiveProxy){const r=n?`${n}.${t}`:t;try{const n=r.split(".");let i=s._rawProps;for(const e of n){if(!i||"object"!=typeof i||!(e in i)){i=void 0;break}i=i[e]}if(void 0!==i){if(null===i||"object"!=typeof i)return i;if(Array.isArray(i))return e;try{const t=Object.keys(i);if(t.length>0){const n=t[0];return void 0!==e[n]?e:i}}catch(e){console.warn(`Error testing reactive proxy for ${t}:`,e)}return e}}catch(e){console.warn(`Clean path traversal failed for ${t}:`,e)}if(e&&"object"==typeof e&&"value"in e)return e.value;if("function"==typeof e)try{return e()}catch(e){console.warn(`Failed to call malformed proxy for ${t}:`,e)}return e}return e};return new Proxy(t,{get(t,o,a){if("string"!=typeof o)return Reflect.get(t,o,a);if(o in t){const e=Reflect.get(t,o,a);return i(e,o)}const c=s.getScopedFunction(o,e);if(c)return c;const l=n?`${n}.${o}`:o;if(s.hasNested(s.props,l)){const e=s.getNested(s.props,l);return i(e,o)}if(r&&o in r){const e=r[o];return i(e,o)}for(let t=e.length-1;t>=0;t--){const n=e.slice(0,t).join("."),r=s.getScopedFunction(o,e.slice(0,t));if(r)return r;const a=n?s.getNested(s.props,n):s.props;if(a&&o in a){const e=a[o];return i(e,o)}}if(PPHP._shared.has(o)){const e=PPHP._shared.get(o);if(e)try{return e.getter()}catch(e){console.warn(`Failed to get shared state for ${o}:`,e)}}return o in globalThis?globalThis[o]:void 0},set(t,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,i)=>"string"==typeof i&&(i in t||!!s.getScopedFunction(i,e)||s.hasNested(s.props,n?`${n}.${i}`:i)||r&&i in r||PPHP._shared.has(i)||i in globalThis||e.some(((t,n)=>{const r=e.slice(0,n).join("."),o=r?s.getNested(s.props,r):s.props;return o&&i 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,this._currentEffectContext=t.join(".");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}this._currentProcessingHierarchy=null,this._currentEffectContext=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){const n=t.split(".").reduce(((e,t)=>e?e[t]:void 0),e);return n}setNested(e,t,n){const r=t.split("."),s=r.pop(),i=r.reduce(((e,t)=>e[t]??={}),e);try{const e=t.split("."),r=e.pop();let s=this._rawProps;for(const t of e)s[t]&&"object"==typeof s[t]||(s[t]={}),s=s[t];if(n&&"object"==typeof n&&!Array.isArray(n))try{s[r]=JSON.parse(JSON.stringify(n))}catch(e){s[r]={...n}}else s[r]=n}catch(e){console.warn(`Failed to store raw value for ${t}:`,e)}null!==n&&"object"==typeof n?"function"==typeof n&&n.__isReactiveProxy||n.__isReactiveProxy?i[s]=n:i[s]=this.makeReactive(n,r.concat(s)):i[s]=n}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,n={}){try{if(!e||"string"!=typeof e)return!1;let r=null;this._currentEffectContext&&(r=this._currentEffectContext.split(".")),!r&&n.from instanceof Element&&(r=this.detectElementHierarchy(n.from)),!r&&this._currentEventTarget instanceof Element&&(r=this.detectElementHierarchy(this._currentEventTarget)),r||(r=["app"]);const s=n.scope??"current";let i=r;Array.isArray(s)?i=s.length?s:["app"]:"parent"===s?i=r.slice(0,-1).length?r.slice(0,-1):["app"]:"root"===s||"app"===s?i=["app"]:"current"!==s&&(i=s.split("."));const o=this.resolveStatePath(e,i),a=o?.startsWith("app.")?o:e.startsWith("app.")?e:`${i.join(".")}.${e}`,c=this.hasNested(this.props,a)?this.getNested(this.props,a):void 0,l="function"==typeof t?t(c):t;if(this.setNested(this.props,a,l),this._dirtyDeps.add(a),this._dirtyDeps.add(`${a}.*`),a.startsWith("app.")){const e=a.slice(4),t=e.split(".")[0];PPHP._shared?.has(t)&&(this._dirtyDeps.add(e),this._dirtyDeps.add(`${e}.*`))}return this._hydrated&&this.scheduleFlush(),a}catch(e){return console.error("PPHP.dispatchEvent error:",e),!1}}determineCurrentComponentHierarchy(){const e=this.getEventSourceHierarchy();if(e.length>0)return e;if(this._currentEffectContext)return this._currentEffectContext.split(".");if(this._currentProcessingHierarchy)return[...this._currentProcessingHierarchy];if(this._currentExecutionScope){return this._currentExecutionScope.split(".")}const t=this.getCurrentScriptHierarchy();if(t.length>0)return t;const n=this.getActiveElementHierarchy();return n.length>0?n:["app"]}trackEventContext(e){e.currentTarget instanceof Element&&(this._currentEventTarget=e.currentTarget,this._eventContextStack.push(e.currentTarget),e.currentTarget.setAttribute("data-pphp-recent",Date.now().toString()),setTimeout((()=>{e.currentTarget?.removeAttribute?.("data-pphp-recent")}),1e3),setTimeout((()=>{this._eventContextStack.pop(),0===this._eventContextStack.length?this._currentEventTarget=null:this._currentEventTarget=this._eventContextStack[this._eventContextStack.length-1]}),0))}getEventSourceHierarchy(){try{let e=null;if(this._currentEventTarget&&(e=this._currentEventTarget),!e){const t=document.currentScript;t&&(e=t.closest("[pp-component]"))}if(!e){const t=document.activeElement;if(t instanceof Element){const n=t.closest("[pp-component]");n&&(e=n)}}if(!e){const t=document.querySelectorAll("[data-pphp-recent]");if(t.length>0){const n=Array.from(t).pop();n&&(e=n.closest("[pp-component]"))}}if(e)return this.buildComponentHierarchy(e)}catch(e){console.warn("Error in getEventSourceHierarchy:",e)}return[]}getCurrentScriptHierarchy(){try{const e=document.currentScript;if(e){const t=e.closest("[pp-component]");if(t)return this.buildComponentHierarchy(t)}}catch(e){}return[]}getActiveElementHierarchy(){try{const e=document.activeElement;if(e&&e!==document.body){const t=e.closest("[pp-component]");if(t)return this.buildComponentHierarchy(t)}}catch(e){}return[]}buildComponentHierarchy(e){const t=[];let n=e;for(;n;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return["app",...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}getCurrentComponent(e){let t=null;if(e){if(t=document.querySelector(e),!t)return console.warn(`PPHP: Element with selector "${e}" not found`),null}else{if(this._currentEffectContext){const e=this._currentEffectContext.split(".");return e[e.length-1]}if(this._currentProcessingHierarchy&&this._currentProcessingHierarchy.length>0)return this._currentProcessingHierarchy[this._currentProcessingHierarchy.length-1];if(this._currentExecutionScope){const e=this._currentExecutionScope.split(".");return e[e.length-1]}const e=document.currentScript;if(e&&(t=e),!t){const e=this.determineCurrentComponentHierarchy();if(e.length>1)return e[e.length-1]}}if(t)return this.findComponentFromElement(t);const n=this.getFallbackComponent();return n||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){this.removeLoadingContent();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")}removeLoadingContent(){document.querySelectorAll('[pp-loading-content="true"]').forEach((e=>{e.remove()}))}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,""")}"`)).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(/"/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();
|