create-prisma-php-app 3.0.3 → 3.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/app/js/index.js +1 -1
- package/package.json +1 -1
package/dist/src/app/js/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,s=new Map,n=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let a=i;n.has(t)&&(void 0===a?a={passive:!0}:"boolean"==typeof a?a={capture:a,passive:!0}:a&&void 0===a.passive&&(a={...a,passive:!0})),s.has(this)||s.set(this,new Map);const o=s.get(this),c=o.get(t)||new Set;c.add(r),o.set(t,c),e.call(this,t,r,a)},EventTarget.prototype.removeEventListener=function(e,n,r){if(s.has(this)&&s.get(this).has(e)){const t=s.get(this).get(e);t.delete(n),0===t.size&&s.get(this).delete(e)}t.call(this,e,n,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(!s.has(this))return;const n=s.get(this).get(e);n&&(n.forEach((s=>{t.call(this,e,s)})),s.get(this).delete(e))}})();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_scopedKeys=new Map;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpSections=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_activeSection=null;_inlineModuleFns=new Map;_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 Map;_sectionParentMap=new Map;_sectionRefs=new Map;_processedLoops=new WeakSet;_hydrated=!1;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _lastJWT=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"]);static _bareCallRe=/^[A-Za-z_$]\w*\s*\(.*\)$/;static _autoPrefixes=new Set;constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),s=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...s].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{await Promise.all([this.initRefs(),this.processInlineModuleScripts()]),await e(),await this.initializeAllReferencedProps(),await e(),await this.initBindings(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();for(let t=0;t<this._bindings.length;t+=250)this._bindings.slice(t,t+250).forEach((e=>e.update())),await e();document.body.removeAttribute("hidden"),this._hydrated=!0};"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("."),s=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:n,exp:r}=JSON.parse(s);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(n),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),s=(new TextEncoder).encode(e),n=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,s);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(n)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,s]=e.split(":",2),n=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),r=Uint8Array.from(atob(s),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:n},PPHP._cryptoKey,r);return(new TextDecoder).decode(i)}qsa(e,t){return e.querySelectorAll(t)}getScopeId(e){for(;e;){const t=e.getAttribute("pp-phpx-id");if(t)return t;const s=e.getAttribute("pp-section-id");if(s)return s;e=e.parentElement}return null}getSectionId(e){for(;e;){const t=e.getAttribute("pp-section-id");if(t)return t;e=e.parentElement}return null}getPhpxId(e){for(;e;){const t=e.getAttribute("pp-phpx-id");if(t)return t;e=e.parentElement}return null}getPhpxParentId(e){if(!e)return null;let t=e,s=null;for(;t&&!s;)s=t.getAttribute("pp-phpx-id"),s||(t=t.parentElement);let n=t?.parentElement;for(;n;){const e=n.getAttribute("pp-phpx-id");if(e&&e!==s)return e;n=n.parentElement}return null}ref(e,t){const s=this._activeSection;let n=[];if(s&&(n=this._sectionRefs.get(s)?.get(e)??[]),0===n.length&&(n=this._refs.get(e)??[]),null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const s=this._currentScopeId(),n=Array.isArray(t),r=n?t:[],i=n&&0===r.length,a=r.map((e=>{if("function"==typeof e&&e.__pphp_key)return e.__pphp_key;if("string"!=typeof e)return"";if(e.includes("_"))return e;for(const[t,s]of this._scopedKeys)if(s.has(e))return`${t}_${e}`;if(s){const t=this._sharedStateMap.get(s);if(t?.has(e)){const t=this._sectionParentMap.get(s);return t?`${t}_${e}`:e}}return e})).filter(Boolean),o=new Set(a),c=new Map;for(const e of a){const t=this.getNested(this.props,e);c.set(e,t)}let l=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const h=PPHP._effectCleanups,p=()=>{const t=h.get(p);if(t){try{t()}catch(e){console.error("cleanup error:",e)}h.delete(p)}if(++l>50)throw new Error("PPHP: effect ran >50 times — possible loop");if(!i&&a.length>0){let e=!1;for(const t of a){if(this.getNested(this.props,t)!==c.get(t)){e=!0;break}}if(!e)return;for(const e of a)c.set(e,this.getNested(this.props,e))}try{const t=e();"function"==typeof t&&h.set(p,t)}catch(e){console.error("effect error:",e)}};Object.assign(p,{__deps:o,__sectionId:s??null,__static:i});try{const t=e();"function"==typeof t&&h.set(p,t)}catch(e){console.error("effect error (initial):",e)}for(const e of a)c.set(e,this.getNested(this.props,e));const d=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return i?this._effects.add(p):d.add(p),()=>{const e=h.get(p);if(e){try{e()}catch(e){console.error("cleanup error:",e)}h.delete(p)}this._effects.delete(p),this._pendingEffects.delete(p)}}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._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._sectionParentMap.clear(),this._sectionRefs.clear(),this._processedPhpSections.clear(),this._processedPhpScripts=new WeakSet,this._scopedKeys.clear(),this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._activeSection=null,PPHP._autoPrefixes.clear(),this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),this._sectionRefs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1,this.props=this.makeReactive(this._rawProps),this._hydrated=!1}async initReactiveOn(e=document.body){const t=()=>new Promise((e=>setTimeout(e,0)));await Promise.all([this.initRefs(e),await this.processInlineModuleScripts(e)]),await t(),await this.initializeAllReferencedProps(e),await t(),await this.initBindings(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();e===document.body&&document.body.removeAttribute("hidden"),this._hydrated=!0}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.getScopeId(e),s=e.getAttribute("pp-for").trim(),[n,r]=s.split(/\s+in\s+/),[i,a]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim())),o=t?`${t}_${i}`:i,c=a?t?`${t}_${a}`:a:null,l=t?r.replace(/\b([A-Za-z_$]\w*)\b/g,((e,s,n,r)=>"."===r[n-1]||this._reservedWords.has(s)||s.startsWith(t+"_")||this.hasNested(this.props,s)||this._sharedStateMap.get(t)?.has(s)?e:`${t}_${s}`)):r,h=e.parentNode,p=document.createComment("pp-for");h.insertBefore(p,e),h.removeChild(e);const d=this.makeSafeEvaluator(l),u=e=>t?e.replace(new RegExp(`\\b${i}\\b`,"g"),o).replace(a?new RegExp(`\\b${a}\\b`,"g"):/$^/,c??""):e,f=this.extractDependencies(l),m=l.match(/^\s*([A-Za-z_$]\w*)\s*\(/);if(m){const e=m[1],t=this._inlineModuleFns.get(e);if("function"==typeof t){const e=t.toString();this.extractDependencies(e).forEach((e=>f.add(e.split(".")[0])))}}this._bindings.push({dependencies:f,update:()=>{const t=document.activeElement;let s=null,n=null;if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&h.contains(t)){const e=t.closest("[key]");s=e?.getAttribute("key")??null,n=t.selectionStart}for(let e=p.nextSibling;e&&e.nodeType!==Node.COMMENT_NODE;){const t=e.nextSibling;h.removeChild(e),e=t}const r=this.getOrCreateProxy(this.props),l=d(r);Array.isArray(l)||console.warn("[pp-for] expected an Array but got:",l);if((Array.isArray(l)?l:[]).forEach(((t,s)=>{this.props[o]=t,c&&(this.props[c]=s);const n=e.content.cloneNode(!0),r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);for(let e;e=r.nextNode();)e.nodeValue=(e.nodeValue||"").replace(PPHP._mustachePattern,((e,t)=>{try{const e=u(t);return this.formatValue(this.makeSafeEvaluator(e)(this.props))}catch{return""}}));n.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes)){if("pp-bind"===t){const t=u(s),n=this.makeSafeEvaluator(t)(this.props);e.textContent=this.formatValue(n);continue}if("pp-bind-expr"===t){const t=this.decodeEntities?this.decodeEntities(s):s,n=u(t),r=this.makeSafeEvaluator(n)(this.props);e.textContent=this.formatValue(r);continue}const n=t.match(/^pp-bind-(.+)$/);if(!n)continue;const r=n[1],i=u(s),a=this.makeSafeEvaluator(i)(this.props);if(this._boolAttrs.has(r)){const t=!!a;e[r]=t,t?e.setAttribute(r,""):e.removeAttribute(r)}else r in e?e[r]=a:e.setAttribute(r,String(a))}})),n.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes)){const n=t.match(/^pp-bind-(.+)$/);if(!n)continue;const r=n[1],i=u(s),a=this.makeSafeEvaluator(i)(this.props);if(this._boolAttrs.has(r)){const t=!!a;e[r]=t,t?e.setAttribute(r,""):e.removeAttribute(r)}else r in e?e[r]=a:e.setAttribute(r,String(a))}})),n.querySelectorAll("*").forEach((e=>{Array.from(e.attributes).forEach((n=>{const r=n.name.startsWith("on"),o=n.name.startsWith("pp-inc-on"),c=n.name.startsWith("pp-comp-on");if(!r&&!o&&!c)return;let l=n.value;/\b(?:i|idx)\b/.test(l)&&(l=((e,t)=>e.replace(/\[\s*(?:i|idx)\s*\]/g,`[${t}]`).replace(/(^|[^\w$])(?:i|idx)(?!\w)/g,((e,s)=>s+t)))(l,s));const h=new RegExp(`\\b${i}\\b`,"g");var p;if(l=l.replace(h,(p=t,JSON.stringify(p))),a){const e=new RegExp(`\\b${a}\\b`,"g");l=l.replace(e,String(s))}e.setAttribute(n.name,l)}))})),h.insertBefore(n,p.nextSibling)})),null!==s){const e=h.querySelector(`[key="${s}"]`),t=e?.querySelector("input,textarea");if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.focus({preventScroll:!0}),null!==n)){const e=Math.min(n,t.value.length);t.setSelectionRange(e,e)}}this.attachWireFunctionEvents()}})}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),s=this.getScopeId(e)??"__global__",n=this._sectionRefs.get(s)??new Map,r=n.get(t)??[];r.push(e),n.set(t,r),this._sectionRefs.set(s,n);const i=this._refs.get(t)??[];i.push(e),this._refs.set(t,i),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){const s=this._proxyCache.get(e);if(s)return s;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;const n=this,r=new Proxy(e,{get(e,s,r){const i=Reflect.get(e,s,r);if(Array.isArray(e)&&"string"==typeof s&&n._mutators.has(s)){let a=n._arrayMethodCache.get(e);if(a||(a=new Map,n._arrayMethodCache.set(e,a)),!a.has(s)){const e=i.bind(r),o=t.join("."),c=function(...t){const s=e(...t);return queueMicrotask((()=>{n._bindings.forEach((e=>{e.dependencies.has(o)&&n.scheduleBindingUpdate(e)}))})),s};a.set(s,c)}return a.get(s)}return null!==i&&"object"==typeof i?n.makeReactive(i,[...t,s]):i},set(e,s,r,i){let a=r;null!==r&&"object"==typeof r&&(a=n.makeReactive(r,[...t,s]));const o=e[s],c=Reflect.set(e,s,a,i);if(o===a)return c;const l=[...t,s].join(".");return n._bindings.forEach((e=>{for(const t of e.dependencies)if(l===t||l.startsWith(t+".")||t.startsWith(l+".")){n.scheduleBindingUpdate(e);break}})),c}});return this._proxyCache.set(e,r),r}makeAttrTemplateUpdater(e,t,s,n){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=n??r.get(t),a=this.getScopeId(e),o=e=>a?this.prefixIds(e,a,new Set):e;return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractDependencies(o(t)).forEach((e=>s.add(e)))})),()=>{try{const s=i.replace(this._mustacheRe,((e,t)=>{try{const e=o(t),s=this.makeSafeEvaluator(e);return this.formatValue(s(this.props))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==s&&e.setAttribute(t,s)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}makePrimitiveUpdater(e,t,s){const n={};return this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);n[t]=t}})),n.value="input",n.checked="change",()=>{try{const r=s(this.props),i=this.formatValue(r);let a=!1;if("value"===t){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,s="true"===i;"checked"in e&&t.checked!==s?(t.checked=s,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 o=n[t]||t,c="click"===o?new MouseEvent(o,{bubbles:!0,cancelable:!0}):new Event(o,{bubbles:!0});e.dispatchEvent(c)}catch(e){console.error(`Error evaluating attribute "${t}":`,e)}}}formatValue(e){return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"function"==typeof e?"":"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e?JSON.stringify(e):String(e))).join(", "):e&&"object"==typeof e?Object.keys(e).length?JSON.stringify(e,null,2):"":e?.toString()??""}registerBinding(e,t,s="text",n){if(this._assignmentRe.test(t))return;const r=this.getScopeId(e);let i=t;if(r){const e=this._scopedKeys.get(r)||new Set,s=this._sharedStateMap.get(r)||new Set,n=this._sectionParentMap.get(r);i=t.replace(/\b([A-Za-z_$][\w$]*)\b/g,((t,i,a,o)=>{if("."===o[a-1]||this._reservedWords.has(i))return t;if(s.has(i))return n?`${n}_${i}`:i;if(e.has(i)||this._declaredStateRoots.has(`${r}_${i}`)||this.hasNested(this.props,`${r}_${i}`))return`${r}_${i}`;let c=this._sectionParentMap.get(r)||null;for(;c;){if(this._scopedKeys.get(c)?.has(i)||this.hasNested(this.props,`${c}_${i}`))return`${c}_${i}`;c=this._sectionParentMap.get(c)||null}return t}))}const a=new Set([...this.extractDependencies(i)].map((e=>e.split(".")[0])).filter((e=>e in this.props&&!this._reservedWords.has(e)))),o=this.makeSafeEvaluator(i);if("value"===n||"checked"===n){const t=this.makePrimitiveUpdater(e,n,o);return void this._bindings.push({dependencies:a,update:t})}if(n){const s=n.toLowerCase();if(this._boolAttrs.has(s)){e.removeAttribute(s);const r=()=>{try{const t=!!o(this.props);e[n]!==t&&(e[n]=t),t?e.setAttribute(s,""):e.removeAttribute(s)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:a,update:r})}const c=e.getAttribute(n)??"";if(this._mustacheRe.test(i)||this._mustacheRe.test(c)){const t=this._scopedKeys.get(r??"")||new Set,s=this._sharedStateMap.get(r??"")||new Set,i=this._sectionParentMap.get(r??"")||null,o=c.replace(this._mustacheRe,((e,n)=>`{{ ${n.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,n,a,o)=>{if("."===o[a-1]||this._reservedWords.has(n))return e;if(s.has(n))return i?`${i}_${n}`:n;if(t.has(n)||this._declaredStateRoots.has(`${r}_${n}`)||this.hasNested(this.props,`${r}_${n}`))return`${r}_${n}`;let c=this._sectionParentMap.get(r??"")||null;for(;c;){if(this._scopedKeys.get(c)?.has(n)||this.hasNested(this.props,`${c}_${n}`))return`${c}_${n}`;c=this._sectionParentMap.get(c)||null}return e}))} }}`)),l=this.makeAttrTemplateUpdater(e,n,a,o);return void this._bindings.push({dependencies:a,update:l})}const l=()=>{try{const t=o(this.props),s=this.formatValue(t);n in e&&(e[n]=s),e.setAttribute(n,s)}catch(e){console.error(`Error evaluating attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:a,update:l})}const c={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:a,update:()=>{try{const t=o(this.props),n=this.formatValue(t);c[s](e,n)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),s=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let n;try{n=new Function("ctx",s)}catch(t){const s=JSON.stringify(e);n=new Function("ctx",`try { return ${s}; } catch { return ""; }`)}return e=>{try{const t=n(e);return null==t?"":t}catch{return""}}}async initBindings(e=document.body){this._bindings=[];const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const s=[];let n=e;for(;n;){if(n.hasAttribute("pp-if"))s.push({el:n,expr:n.getAttribute("pp-if")});else if(n.hasAttribute("pp-elseif"))s.push({el:n,expr:n.getAttribute("pp-elseif")});else{if(!n.hasAttribute("pp-else"))break;s.push({el:n,expr:null})}t.add(n),n=n.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractDependencies(t);const s=this.makeSafeEvaluator(t);e.evaluate=()=>!!s(this.props)}}));const r=new Set;s.forEach((e=>e.deps?.forEach((e=>r.add(e)))));this._bindings.push({dependencies:r,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})})),this.qsa(e,"*").forEach((e=>{["pp-bind","pp-bind-expr"].forEach((t=>{const s=e.getAttribute(t);s&&this.registerBinding(e,s,"text")})),Array.from(e.attributes).forEach((t=>{const s=t.name.toLowerCase(),n=t.value.trim();this._boolAttrs.has(s)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(n)&&(e.removeAttribute(t.name),this.registerBinding(e,n,"text",s))})),Array.from(e.attributes).forEach((t=>{if(!t.name.startsWith("pp-bind-"))return;const s=t.name;if("pp-bind"===s||"pp-bind-expr"===s||"pp-bind-spread"===s)return;const n=this.decodeEntities(t.value).replace(/^{{\s*|\s*}}$/g,""),r=s.replace(/^(pp-bind-)+/,""),i="value"===r?"value":"checked"===r?"checked":"text";this.registerBinding(e,n,i,r)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),n=new Set;s.forEach((e=>n.add(e.split(".")[0])));const r=new Set;this._bindings.push({dependencies:n,update:()=>{try{const t={};s.forEach((e=>{const s=this.getNested(this.props,e)??{};Object.assign(t,s)})),r.forEach((s=>{s in t||e.hasAttribute(s)||(e.removeAttribute(s),r.delete(s))})),Object.entries(t).forEach((([t,s])=>{if(!r.has(t)&&e.hasAttribute(t))return;if(null==s||!1===s)return void(r.has(t)&&(e.removeAttribute(t),r.delete(t)));const n="object"==typeof s?JSON.stringify(s):String(s);e.getAttribute(t)!==n&&e.setAttribute(t,n),r.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})}))}))}callInlineModule(e,...t){const s=this._inlineModuleFns.get(e);if(!s)throw new Error(`PPHP: no inline module named "${e}"`);return s(...t)}async processInlineModuleScripts(e=document.body){this._inlineDepth++,this._sharedStateMap.clear(),this._sectionParentMap.clear();try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>{const t=this.getScopeId(e);return t?!this._processedPhpSections.has(t):!this._processedPhpScripts.has(e)}));if(!t.length)return;this.qsa(e,"[pp-section-id]").forEach((e=>{const t=e.getAttribute("pp-section-id"),s=this.findParentSectionId(e);s&&this._sectionParentMap.set(t,s)})),this.qsa(e,"[pp-phpx-id]").forEach((e=>{const t=e.getAttribute("pp-phpx-id"),s=this.findParentSectionId(e);s&&this._sectionParentMap.set(t,s)}));const s=this.sortScriptsByDependency(t),n={};for(const e of s){const t=this.getScopeId(e);if(!t)continue;const s=e.textContent||"";for(const[,e]of[...s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g),...s.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g)])n[e]=t}for(const[e,t]of Object.entries(n))this._scopedKeys.has(t)||this._scopedKeys.set(t,new Set),this._scopedKeys.get(t).add(e);for(const e of s){const t=this.getScopeId(e);let s=(e.textContent||"").trim();if(s=this.decodeEntities(s),s=this.stripComments(s),s=this.transformStateDeclarations(s,t),t){const e=this._sectionParentMap.get(t)??null,n=t+"_",r=e?e+"_":"",i=new Set;if(this._declaredStateRoots.forEach((e=>{e.startsWith(n)?i.add(e.slice(n.length)):r&&e.startsWith(r)?i.add(e.slice(r.length)):e.includes("_")||i.add(e)})),i.size){let e="";for(const a of i){const i=this.hasNested(this.props,n+a)?n+a:this.hasNested(this.props,r+a)?r+a:a,o="set"+a[0].toUpperCase()+a.slice(1),c=`${t}_${a}`,l=`${t}_${o}`;new RegExp(`\\b(?:const|let|var)\\s+\\[?\\s*${a}\\b`).test(s)||(e+=`\n const ${a} = (() => {\n const fn = () => pphp.props.${i};\n fn.__pphp_key = '${i}';\n Object.defineProperty(fn, 'value', {\n get() { return pphp.props.${i}; },\n set(v) { pphp.props.${i} = v; }\n });\n return fn;\n })();\n const ${o} = v => {\n pphp.props.${i} = typeof v === 'function'\n ? v(pphp.props.${i})\n : v;\n };\n pphp._inlineModuleFns.set('${c}', ${a});\n pphp._inlineModuleFns.set('${l}', ${o});`)}s=e+"\n"+s}}const r=this.extractSetters(s,t);if(r.length){s+="\n\n";for(const e of r){s+=`pphp._inlineModuleFns.set('${t?`${t}_${e}`:e}', ${e});\n`}}if(t){const e=this._sectionParentMap.get(t)??null,n=e?e+"_":"";s=s.replace(/(\bpphp\.state\(\s*['"])([^'"]+)(['"])/g,((e,s,r,i)=>r.startsWith(t+"_")||n&&r.startsWith(n)||!r.includes("_")?s+r+i:s+`${t}_${r}`+i))}s=s.replace(/\b([A-Za-z_$]\w*)\s*\(/g,((e,t,s,r)=>{const i=r.slice(Math.max(0,s-20),s);if(/\b(?:function|export\s+function)\s*$/.test(i.trim()))return e;const a=n[t];return a?`${a}_${t}(`:e}));const i=new Blob([s],{type:"application/javascript"}),a=URL.createObjectURL(i),o=PPHP.prototype._currentScopeId;t&&(PPHP.prototype._currentScopeId=()=>t);try{const e=await import(a);for(const[s,n]of Object.entries(e))if("function"==typeof n){const e=t?`${t}_${s}`:s;this._inlineModuleFns.set(e,n)}}catch(e){console.error("Inline module import failed:",e)}finally{PPHP.prototype._currentScopeId=o,URL.revokeObjectURL(a),t?this._processedPhpSections.add(t):this._processedPhpScripts.add(e)}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}stripComments(e){let t="",s=0,n=!1,r="",i=!1;for(;s<e.length;){const a=e[s],o=e[s+1];if(i||"'"!==a&&'"'!==a&&"`"!==a||"\\"===e[s-1])if(n)t+=a,s++;else if(i||"/"!==a||"*"!==o)if(i)"*"===a&&"/"===o?(i=!1,s+=2):s++;else if("/"!==a||"/"!==o)t+=a,s++;else for(;s<e.length&&"\n"!==e[s];)s++;else i=!0,s+=2;else n=!n,r=n?a:"",t+=a,s++}return t}findParentSectionId(e){const t=e.parentElement?.closest("[pp-section-id]");return t?t.getAttribute("pp-section-id"):null}extractSetters(e,t){const s=[],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,i]=r;"share"===i&&this.markShared(t,e),t&&this._sharedStateMap.get(t)?.has(e)||s.push(n)}return s}markShared=(e,t)=>{e&&(this._sharedStateMap.has(e)||this._sharedStateMap.set(e,new Set),this._sharedStateMap.get(e).add(t))};transformStateDeclarations(e,t){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,s,n,r,i)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}${n}, ${r}${i}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,s,n,r)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}${n}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,s,n,r)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}[${n}] = pphp.state('${n}', `))}sortScriptsByDependency(e){const t=new Map;for(const s of e){const e=this.getScopeId(s);t.has(e)||t.set(e,[]),t.get(e).push(s)}const s=[],n=new Set,r=e=>{if(!e)return[];const t=this._sectionParentMap.get(e);if(t)return[t];const s=this._sharedStateMap.get(e);return s&&s.size>0?[t||null]:[]},i=e=>{if(n.has(e))return;for(const t of r(e))i(t);const a=t.get(e)||[];s.push(...a),n.add(e)};i(null);for(const e of t.keys())null!==e&&i(e);return s}flushBindings(){const e=new Set(this._dirtyDeps);this._pendingBindings.forEach((t=>{t.dependencies.forEach((t=>e.add(t))),t.update()})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const s=t.__deps||new Set;if(0===s.size||[...s].some((t=>e.has(t)))){const e=this._activeSection;this._activeSection=t.__sectionId??null;try{t()}catch(e){console.error("effect error:",e)}this._activeSection=e}}))}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}scopeKey(e){const t=this._currentScopeId();if(!t)return e;const s=this._sharedStateMap.get(t);if(s?.has(e)){const s=this._sectionParentMap.get(t);return s?`${s}_${e}`:e}return e.startsWith(`${t}_`)?e:`${t}_${e}`}_currentScopeId(){const e=document.currentScript;return this.getScopeId(e)}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,s){const n=t.split("."),r=n.pop();n.reduce(((e,t)=>e[t]??={}),e)[r]=s}hasNested(e,t){return void 0!==this.getNested(e,t)}share(e,t){const s=PPHP._shared.get(e);if(s)return[s.getter,s.setter];const[n,r]=this.state(e,t);return PPHP._shared.set(e,{getter:n,setter:r}),[n,r]}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure your build-time injector ran and you wrote `const [foo, setFoo] = pphp.state(0)` so it became `pphp.state('foo', 0)`.");arguments.length<2&&(t=void 0);const s=this._currentScopeId(),n=e;if(this._reservedWords.has(n))throw new Error(`'${n}' is reserved – choose another state key.`);const r=this.scopeKey(n);this._declaredStateRoots.add(r),s&&(this._scopedKeys.has(s)||this._scopedKeys.set(s,new Set),this._scopedKeys.get(s).add(n)),this.hasNested(pphp.props,r)||this.setNested(pphp.props,r,t);const i=()=>this.getNested(pphp.props,r),a=e=>{const t=i(),s="function"==typeof e?e(t):e;this.setNested(pphp.props,r,s),this._dirtyDeps.add(r.split(".")[0]),this.scheduleFlush()},o=()=>i();Object.defineProperty(o,"value",{get:()=>i(),set:e=>a(e)}),Object.defineProperties(o,{valueOf:{value:()=>i()},toString:{value:()=>String(i())}}),o.__pphp_key=r;const c=i();if(null===c||"object"!=typeof c)return[o,a];return[new Proxy(o,{apply:(e,t,s)=>Reflect.apply(e,t,s),get(e,t,s){if("value"===t)return i();if(t in e)return Reflect.get(e,t,s);return i()[t]},set(e,t,s){if("value"===t)return a(s),!0;return i()[t]=s,!0},has(e,t){if("value"===t||t in o)return!0;return t in i()}}),a]}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 s=>{const n=e.get(s);if(void 0!==n)return n;const r=s in globalThis||t.some((e=>s in e));return e.set(s,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let s=e.replace(/\?\./g,".");const n=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(s);){(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)))}const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(s);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const a=e=>{let t="",s=0;for(;s<e.length;)if("`"===e[s])for(s++;s<e.length;)if("\\"===e[s])s+=2;else if("$"===e[s]&&"{"===e[s+1]){s+=2;let n=1;const r=s;for(;s<e.length&&n>0;)"{"===e[s]?n++:"}"===e[s]&&n--,s++;const i=e.slice(r,s-1);t+=a(i)+" "}else{if("`"===e[s]){s++;break}s++}else t+=e[s++];return t};s=a(s),s=s.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),s=s.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const o=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of s.match(c)??[]){const[s,...r]=t.split(".");n.has(s)||(0===r.length&&PPHP._isBuiltIn(s)&&new RegExp(`\\.${s}\\b`).test(e)||o.add(t))}return o}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,s=PPHP._mustacheTest,n=this.props,r=new Set,i=(e,t)=>{if(this.hasOwnNested(this.props,t))return t;const s=e.getAttribute("pp-section-id"),n=this.getScopeId(e.parentElement);return s??n?`${s??n}_${t}`:t},a=(()=>{const e=new Set([...Object.getOwnPropertyNames(String.prototype),...Object.getOwnPropertyNames(Array.prototype),...Object.getOwnPropertyNames(Number.prototype),...Object.getOwnPropertyNames(Boolean.prototype),...Object.getOwnPropertyNames(Object.prototype),...Object.getOwnPropertyNames(Date.prototype),...Object.getOwnPropertyNames(RegExp.prototype)]);return t=>e.has(t)})(),o=(e,t)=>{const[s,n,...o]=t.split(".");if(this._reservedWords.has(s))return;if(n&&a(n))return void r.add(i(e,s));const c=i(e,s);r.add(n?`${c}.${[n,...o].join(".")}`:c)};for(const n of this.qsa(e,"*"))for(const{name:e,value:r}of Array.from(n.attributes))if(r){if(s.test(r))for(const e of r.matchAll(t))this.extractDependencies(e[1]).forEach((e=>o(n,e)));"pp-if"!==e&&"pp-elseif"!==e||this.extractDependencies(r).forEach((e=>o(n,e))),e.startsWith("pp-bind")&&this.extractDependencies(r).forEach((e=>o(n,e)))}const c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>s.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let l;for(;l=c.nextNode();){const e=l.parentElement;for(const s of l.nodeValue.matchAll(t))this.extractDependencies(s[1]).forEach((t=>o(e,t)))}const h=Array.from(r).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of h){const t=e.split(".");let s=n;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1,i=t.slice(0,e+1).join(".");n in s&&(r||null!=s[n]&&"object"==typeof s[n])||r&&this._declaredStateRoots.has(i)||(s[n]=r?void 0:{}),s=s[n]}}}hasOwnNested(e,t){const s=t.split(".");let n=e;for(const e of s){if(!n||!Object.prototype.hasOwnProperty.call(n,e))return!1;n=n[e]}return!0}setNestedProperty(e,t,s){const n=t.split(".");let r=e;for(let e=0;e<n.length-1;e++)n[e]in r||(r[n[e]]={}),r=r[n[e]];r[n[n.length-1]]=s}async attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=e=>Array.from(this._eventHandlers).map((t=>`[${e}${t}]`)),t=[...e(""),...e("pp-inc-"),...e("data-pp-child-"),...e("data-pp-parent-")].flat().join(","),s=this.qsa(document.body,t);for(const e of s){const t=this.getSectionId(e),s=this.getPhpxId(e),n=this.getPhpxParentId(e);t&&PPHP._autoPrefixes.add(`${t}_`),s&&PPHP._autoPrefixes.add(`${s}_`),n&&PPHP._autoPrefixes.add(`${n}_`);for(const r of this._eventHandlers){const i=r,a=`pp-inc-${r}`,o=`data-pp-child-${r}`,c=`data-pp-parent-${r}`,l=e.getAttribute(i),h=e.getAttribute(a),p=e.getAttribute(o),d=e.getAttribute(c),u=l?this.decodeEntities(l).trim():"",f=h?this.decodeEntities(h).trim():"",m=p?this.decodeEntities(p).trim():"",g=d?this.decodeEntities(d).trim():"";if(!(u||f||m||g))continue;const y=[];if(u&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(u,null))),f&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(f,t))),m&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(m,s))),g){const e=n||t||null;y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(g,e)))}const b=`(event) => { ${[...new Set(y)].join(" ")} }`;[i,a,o,c].forEach((t=>e.removeAttribute(t)));const _=r.slice(2);e.removeAllEventListeners(_),e instanceof HTMLInputElement&&this.handleInputAppendParams(e,_),this.handleDebounce(e,_,b)}}this.handlePassiveWheelStashes(document)}prefixFunctionCalls(e,t){if(!t)return e;const s=this._scopedKeys.get(t)??new Set,n=e=>s.has(e)||this._declaredStateRoots.has(`${t}_${e}`);return e.replace(/\b([A-Za-z_$][\w$]*)\s*\(/g,((e,s)=>this._reservedWords.has(s)||s.startsWith(`${t}_`)||!n(s)||this.hasNested(this.props,s)||this._inlineModuleFns.has(s)||"function"==typeof globalThis[s]?e:`${t}_${s}(`))}prefixIds(e,t,s=new Set){let n="",r=0,i=(e=this.prefixFunctionCalls(e,t)).length,a=!1,o=!1,c=!1;for(;r<i;){const l=e[r];if("'"!==l||o||c||"\\"===e[r-1])if('"'!==l||a||c||"\\"===e[r-1])if("`"!==l||a||o||"\\"===e[r-1])if(a||o||c)n+=l,r++;else if(/[A-Za-z_$]/.test(l)){let a=r+1;for(;a<i&&/[\w$]/.test(e[a]);)a++;const o=e.slice(r,a),c=e[r-1]??"",l=this._reservedWords.has(o),h="."===c;n+=!(o.startsWith(`${t}_`)||h||l||s.has(o)||this.hasNested(this.props,o))?`${t}_${o}`:o,r=a}else n+=l,r++;else c=!c,n+=l,r++;else o=!o,n+=l,r++;else a=!a,n+=l,r++}return n}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let s=t.value;for(;s.includes("&");){t.innerHTML=s;const e=t.value;if(e===s)break;s=e}return s};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 s=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(s){let t=e.substring(s[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let n=e.trim();return n&&!n.endsWith(";")&&(n+=";"),n};buildHandlerFromRawBody(e,t){let s=e.trim();s=s.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,s,n)=>{const r=`${t}->${s}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`})),s=s.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,s,n)=>{const r=`${t}::${s}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`}));const{normalized:n,originalParam:r}=this.normalizeToArrow(s),i=this.renameEventParam(n,r),a=this.replaceThisReferences(i),o=new Set(["event","pphp"]);return t?this.prefixBareIdentifiers(a,t,o):a}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}isBareCall(e){return!e.includes("=>")&&PPHP._bareCallRe.test(e)&&!/^[A-Za-z_$]\w*_/.test(e)}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const s=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(s)?s:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const s=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(s,((e,t,s)=>{const n=s[t-1],r=s[t+e.length];return n&&/[\w$]/.test(n)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}prefixBareIdentifiers(e,t,s=new Set(["event","pphp"])){const n=e.indexOf("=>");if(-1!==n){const r=e.slice(0,n+2),i=e.slice(n+2);return r+this.prefixIds(i,t,s)}const r=this.prefixIds(e,t,s);return/^[A-Za-z_$].*\)$/.test(r.trim())?`() => ${r}`:`(event) => { ${r}; }`}async handleDebounce(e,t,s){const n=e.getAttribute("pp-debounce"),r=n?this.parseTime(n):0,i=e.getAttribute("pp-before-request")??"",a=e.getAttribute("pp-after-request")??"",o=PPHP._cancelableEvents,c=async n=>{o.has(t)&&n.cancelable&&n.preventDefault();try{const t=this.getScopeId(e);if(i){const s=t?`${t}_${i}`:i;await this.invokeHandler(e,s,n)}if(await this.invokeHandler(e,s,n),a&&!a.startsWith("@close")){const s=t?`${t}_${a}`:a;await this.invokeHandler(e,s,n)}this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!o.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,p=e=>{if(r>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const s=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),r);PPHP._debounceTimers.set(h,s)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),p(e)}),l):e.addEventListener(t,p,l)}debounce(e,t=300,s=!1){let n;return function(...r){const i=this;n&&clearTimeout(n),n=setTimeout((()=>{n=null,s||e.apply(i,r)}),t),s&&!n&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const s=t.getAttribute("pp-autofocus");if(!this.isJsonLike(s))return;const n=this.parseJson(s);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,n),t.type="number"):this.setCursorPosition(t,n))}))}async invokeHandler(e,t,s){this._activeSection=this.getScopeId(e);try{const n=t.trim();let r=this._handlerCache.get(n);r||(r=this.parseHandler(n),this._handlerCache.set(n,r)),await this.executeHandler(r,e,s,n)}catch(s){this.handleInvokeError(s,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 s=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(s)return{type:"call",name:s[1],args:s[2],isAsync:this.isAsyncFunction(s[1])};const n=t.match(/^(\w+)$/);return n?{type:"simple",name:n[1],isAsync:this.isAsyncFunction(n[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,s="",n=0;for(let r=0;r<e.length-1;r++){const i=e[r],a=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===s&&"\\"!==e[r-1])t=!1,s="";else if(!t&&("("===i&&n++,")"===i&&n--,"="===i&&">"===a&&n>=0))return!0}else t=!0,s=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let s=e.substring(t+2).trim();return s.startsWith("{")&&s.endsWith("}")&&(s=s.slice(1,-1).trim()),{type:"arrow",body:s,isAsync:e.includes("async")||this.containsAwait(s)}}findArrowIndex(e){let t=!1,s="";for(let n=0;n<e.length-1;n++){const r=e[n],i=e[n+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===s&&"\\"!==e[n-1])t=!1;else if(!t&&"="===r&&">"===i)return n}else t=!0,s=r}return-1}async executeArrowHandler(e,t,s){const n=this.parseStatements(e.body);let r=!1;for(const e of n)await this.executeSingleStatement(e,t,s)&&(r=!0);r||await this.executeDynamic(e.body,t,s)}async executeComplexHandler(e,t,s){await this.executeDynamic(e.body,t,s)}parseStatements(e){const t=[];let s="",n=0,r=!1,i="";for(let a=0;a<e.length;a++){const o=e[a];r||'"'!==o&&"'"!==o&&"`"!==o?r&&o===i&&"\\"!==e[a-1]&&(r=!1,i=""):(r=!0,i=o),r||("("!==o&&"{"!==o&&"["!==o||n++,")"!==o&&"}"!==o&&"]"!==o||n--,";"!==o||0!==n)?s+=o:s.trim()&&(t.push(s.trim()),s="")}return s.trim()&&t.push(s.trim()),t}async executeInlineModule(e,t,s,n,r){if(t&&t.trim())if(this.isJsonLike(t)){const s=this.parseJson(t);null!==s&&"object"==typeof s?await this.callInlineModule(e,{...s}):await this.callInlineModule(e,s)}else try{const s=this.getOrCreateEvaluator(t)(this.props);await this.callInlineModule(e,s)}catch{await this.callInlineModule(e,{element:s,event:n})}else await this.handleParsedCallback(s,r,n)}async executeSingleStatement(e,t,s){const n=e.trim();if(!n)return!1;const r=n.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return this.executeSingleStatement(r[1],t,s);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(n))return await this.executeDynamic(n,t,s),!0;const i=n.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i,a=this.resolveFunctionName(e);let o=[];if(""!==r.trim())try{o=JSON5.parse(`[${r}]`)}catch{try{const e=this.getOrCreateProxy(this.props),t=/\bevent\b/.test(r)?r.replace(/\bevent\b/g,"_evt"):r;o=new Function("_evt","proxy","props",`with (proxy) { return [ ${t} ]; }`)(s,e,this.props)}catch(e){o=[]}}if(a&&this._inlineModuleFns.has(a)){const e=this._inlineModuleFns.get(a);return o.length>0?await e(...o):await this.executeInlineModule(a,r,t,s,n),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,o),!0}return await this.handleParsedCallback(t,n,s),!0}const a=n.match(/^(\w+)$/);if(a){const e=a[1],n=this.resolveFunctionName(e);if(n&&this._inlineModuleFns.has(n))return await this.handleParsedCallback(t,`${n}()`,s),!0;if(n){const e=globalThis[n];if("function"==typeof e)return e.call(globalThis,s),!0}return await this.handleParsedCallback(t,`${e}()`,s),!0}return await this.executeDynamic(n,t,s),!0}async executeCallHandler(e,t,s,n){const{name:r,args:i}=e,a=this.resolveFunctionName(r);if(a){if(this._inlineModuleFns.has(a))return void await this.executeInlineModule(a,i||"",t,s,n);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,s)}await this.handleParsedCallback(t,n,s)}resolveFunctionName(e){if(this._inlineModuleFns.has(e))return e;if(!e.includes("_")&&"function"==typeof globalThis[e])return e;if(e.includes("_")){const[t,...s]=e.split("_"),n=s.join("_"),r=this._sectionParentMap.get(t);if(r){const e=`${r}_${n}`;if(this._inlineModuleFns.has(e))return e}if(this._inlineModuleFns.has(n))return n;if("function"==typeof globalThis[n])return n}return null}async executeSimpleHandler(e,t,s){const{name:n}=e,r=this.resolveFunctionName(n);if(r){if(this._inlineModuleFns.has(r))return void await this.handleParsedCallback(t,`${r}()`,s);const e=globalThis[r];if("function"==typeof e)return void e.call(globalThis,s)}await this.handleParsedCallback(t,`${n}()`,s)}async executeHandler(e,t,s,n){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,s);break;case"call":await this.executeCallHandler(e,t,s,n);break;case"simple":await this.executeSimpleHandler(e,t,s);break;case"complex":await this.executeComplexHandler(e,t,s);break;default:await this.handleParsedCallback(t,n,s)}}async executeGlobalFunction(e,t,s,n){if(t.trim())if(this.isJsonLike(t)){const s=this.parseJson(t)??{};e.call(globalThis,{...s})}else{const r=this.getOrCreateProxy(this.props);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(s,n,r,this.props,e)}else e.call(globalThis,n)}async executeDynamic(e,t,s){const n=this.getOrCreateProxy(this.props);let r=e;this._activeSection&&(r=this.prefixFunctionCalls(e,this._activeSection));const i=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${r}\n }`);await i.call(t,s,n,this.props)}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._inlineModuleFns;return new Proxy(e,{get(e,s,n){if("string"==typeof s){if(t.has(s))return t.get(s);if(s in e){const t=Reflect.get(e,s,n),r=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof r))return t}if(s in globalThis){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,n)},set:(e,t,s,n)=>Reflect.set(e,t,s,n),has:(e,s)=>"string"==typeof s&&t.has(s)||s in e||s 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,s){const n=e instanceof Error?e.message:String(e),r=s.tagName+(s.id?`#${s.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${n}`,e),s.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:s},bubbles:!0}))}clearHandlerCaches(){this._handlerCache.clear(),this._evaluatorCache.clear()}async handleParsedCallback(e,t,s){const{funcName:n,data:r}=this.parseCallback(e,t);if(!n)return;const i=Array.isArray(n)?n:[n];let a;for(const e of i){const t=this._inlineModuleFns.get(e);if("function"==typeof t){a=t;break}const s=this[e];if("function"==typeof s){a=s;break}const n=window[e];if("function"==typeof n){a=n;break}}if(a){const t=e.hasAttribute("pp-after-request"),n="@close"===e.getAttribute("pp-after-request");let i={args:Array.isArray(r.args)?r.args:[],element:e,data:r,event:s};if(t&&!n){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(n)?n[0]:n,r)}stripAutoPrefix(e){for(const t of PPHP._autoPrefixes)if(e.startsWith(t))return e.slice(t.length);return e}async handleUndefinedFunction(e,t,s){const n=this.stripAutoPrefix(t),r={callback:await this.encryptCallbackName(n),...s},i=this.createFetchOptions(r),a=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const t=new URL(window.location.href);let r="",o="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(r=await this.fetchFileWithData(t.href,n,l,s),o=this.extractJson(r)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(t.href,i);if(r=await e.text(),this.getRedirectUrl(r))return void await this.redirect(this.getRedirectUrl(r)||"");if(o=this.extractJson(r)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",p=e.getAttribute("pp-after-request")||"";if((h||p&&c.success)&&this.restoreSuspenseElement(e),h||p){let e="";if(c.success){e=r.replace(o,"")}else e=r;if(this.appendAfterbegin(e),!p&&!c.success)return}if(p&&c.success){this.handleAfterRequest(p,o);const e=r.replace(o,"");return this.appendAfterbegin(e),o}if("@close"===p)return c.success?o:void 0;const d=await this.fetch(t.href,a),u=await d.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(r,u,o,c)}catch(e){console.error(`Error handling undefined function "${n}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const s=this.parseJson(e),n=t?this.parseJson(t):null,r=s.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...s}=e,r=document.querySelector(t);let i={};if(n){for(const t in s)if(s.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===s[t]&&(i[t]=e.responseKey?n[e.responseKey]:n.response);break;default:i[t]=s[t]}}else i=s;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,s)=>` data-onwheel-code="${this.decodeEntities(s).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=>{let t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null;const s=this.getScopeId(e);if(s){const e=t.indexOf("=>");if(e>=0){const n=t.slice(0,e+2),r=t.slice(e+2);t=n+this.prefixIds(r,s)}else t=this.prefixIds(t,s)}e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t)}))}async handleResponseRedirectOrUpdate(e,t,s,n){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,s,n),a=(new DOMParser).parseFromString(r,"text/html");i&&a.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(a.body.outerHTML)}getUpdatedHTMLContent(e,t,s){const n=document.createElement("div");if(n.id="afterbegin-8D95D",s&&t?.success){const t=e.replace(s,"");n.innerHTML=t}else n.innerHTML=e;return n.innerHTML?n:null}async updateBodyContent(e){const t=this.saveScrollPositions();this.saveElementState();const s=(new DOMParser).parseFromString(e,"text/html");this.resetProps(),await this.initReactiveOn(s.body),await this.appendCallbackResponse(s),this.restoreElementState(),this.restoreScrollPositions(t),await this.rerunInlineScripts(),this.attachWireFunctionEvents()}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)}await this.populateDocumentBody(e)}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 s in t)if(t.hasOwnProperty(s))switch(s){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[s]=this.decodeHTML(t[s]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[s].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[s].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[s]));break;case"removeAttribute":e.removeAttribute(t[s]);break;case"className":e.className=this.decodeHTML(t[s]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[s]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[s]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[s]));break;case"classList.replace":const[n,r]=this.decodeHTML(t[s]).split(",");e.classList.replace(n,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[s]);break;case"style":Object.assign(e.style,t[s]);break;case"value":e.value=this.decodeHTML(t[s]);break;case"checked":e.checked=t[s];break;default:e.setAttribute(s,this.decodeHTML(t[s]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let s=document.getElementById(t);s?(s.innerHTML=e,document.body.insertAdjacentElement("afterbegin",s)):(s=document.createElement("div"),s.id=t,s.innerHTML=e,document.body.insertAdjacentElement("afterbegin",s))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const s=(e,t)=>{for(const s in t)t.hasOwnProperty(s)&&("textContent"===s?e.textContent=t[s]:"innerHTML"===s?e.innerHTML=t[s]:"disabled"===s?!0===t[s]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(s,t[s]));for(const s of Array.from(e.attributes))t.hasOwnProperty(s.name)||e.removeAttribute(s.name)},n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const n=this.parseJson(e);s(t,n)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?n(e,t):s(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const n=this.parseJson(t);s(e,n)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),n(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(r.targets){r.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&i(n,s)}));const{targets:t,...n}=r;s(e,n)}else{const{empty:t,...n}=r;s(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,s,n={}){const r=new FormData,i=s.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in n)n.hasOwnProperty(e)&&r.append(e,n[e]);const a=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await a.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))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 s=this.parseJson(e);"disabled"!==s.onsubmit&&this.updateElementAttributes(t,s),s.targets&&s.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&r(n,s)}))}else n(t,e)}},n=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?s(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const n=this.parseJson(t);if(n)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),n.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...a}=n;this.updateElementAttributes(e,a),s(e,r)}else if(n.targets){n.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&r(n,s)}));const{targets:t,...s}=n;this.updateElementAttributes(e,s)}else{if("disabled"===n.empty&&""===e.value)return;const{empty:t,...s}=n;this.updateElementAttributes(e,s)}}else if(t)n(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),n={};t.forEach(((e,t)=>{n[t]=e})),s(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let s=0;s<e.attributes.length;s++){const n=e.attributes[s];t[n.name]=n.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const s=e.id;s&&(t=document.querySelector(`[form="${s}"]`)),s&&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,s)=>{e[s]=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 s={};const n=e.closest("form");if(n){new FormData(n).forEach(((e,t)=>{s[t]?Array.isArray(s[t])?s[t].push(e):s[t]=[s[t],e]:s[t]=e}))}else e instanceof HTMLInputElement?s=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(s[e.name]=e.value);const r=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(r){const e=r[1].trim(),t=r[2].trim(),n=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?s.args=e:e&&"object"==typeof e&&(s={...s,...e})}catch(e){console.error("Error parsing JSON args:",e),s.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?s.args=e:e&&"object"==typeof e?s={...s,...e}:s.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),s.rawArgs=t}else if(/^[\s\d"'[\{]/.test(t))try{const e=new Function(`return [${t}];`)();s.args=Array.isArray(e)?e:[e]}catch{n.test(t)?s.args=t.split(n).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):s.args=[t.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(t)(this.props);s.args=[e]}catch{s.args=t.split(n).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:s}}return{funcName:t,data:s}}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 s=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=s?s.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 s=parseInt(t.length,10)||0;e.setSelectionRange(s,s)}}handleInputAppendParams(e,t){const s=e.getAttribute("pp-append-params"),n=e.getAttribute("pp-append-params-sync");if("true"===s){if("true"===n){const t=e.name||e.id;if(t){const s=new URL(window.location.href),n=new URLSearchParams(s.search);n.has(t)&&(e.value=n.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,s=t.value,n=new URL(window.location.href),r=new URLSearchParams(n.search),i=t.name||t.id;if(i){s?r.set(i,s):r.delete(i);const e=r.toString()?`${n.pathname}?${r.toString()}`:n.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),s=this.handleElementVisibility.bind(this),n=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",s))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",n)))}handleVisibilityElementAttribute(e,t,s){const n=e.getAttribute(t);if(n)if(this.isJsonLike(n)){s(e,this.parseJson(n))}else{const s=this.parseTime(n);if(s>0){const n="pp-visibility"===t?"visibility":"display",r="visibility"===n?"hidden":"none";this.scheduleChange(e,s,n,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,s,n,r){const i=t.start?this.parseTime(t.start):0,a=t.end?this.parseTime(t.end):0;i>0?(e.style[s]=n,this.scheduleChange(e,i,s,r),a>0&&this.scheduleChange(e,i+a,s,n)):a>0&&this.scheduleChange(e,a,s,n)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,s=t.getAttribute("href"),n=t.getAttribute("target");if(s&&"_blank"!==n&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(s)&&!s.startsWith(window.location.origin))window.location.href=s;else{const e=t.getAttribute("pp-append-params");if(s.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let n="";const[r,i]=s.split("#");i&&(n=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,s)=>{t.set(s,e)}));const a=`${e.pathname}?${t.toString()}${n}`;history.pushState(null,"",a)}else{const[e,t]=s.split("#"),n=`${e}${t?`#${t}`:""}`;history.pushState(null,"",n)}const n=s.indexOf("#");if(-1!==n){const e=s.slice(n+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href);if(!t.ok)return void console.error(`Navigation error: ${t.status} ${t.statusText}`);const s=await t.text(),n=s.match(this._redirectRegex);if(n&&n[1])return void await this.redirect(n[1]);await this.updateDocumentContent(s)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let s=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${s}']`);if(t)return t;if("/"===s)break;const n=s.lastIndexOf("/");s=n<=0?"/":s.substring(0,n)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:s,fadeOut:n}=this.parseTransition(e);await this.fadeOut(t,n),t.innerHTML=e.innerHTML,this.fadeIn(t,s)}parseTransition(e){let t=250,s=250;const n=e.querySelector("[pp-loading-transition]"),r=n?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),s=this.parseTime(e.fadeOut??s)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:s}}fadeOut(e,t){return new Promise((s=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",s()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async updateDocumentContent(e){const t=this.saveScrollPositions(),s=this.sanitizePassiveHandlers(e),n=(new DOMParser).parseFromString(s,"text/html"),r="pp-dynamic-script",i="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove()));document.head.querySelectorAll(`[${i}]`).forEach((e=>e.remove()));document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove()));this.resetProps(),await(async e=>{Array.from(e.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(r)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){if(e.getAttribute("charset")||"viewport"===e.getAttribute("name"))return;const t=e.name,s=e.getAttribute("property"),n=document.head.querySelector(t?`meta[name="${t}"]`:`meta[property="${s}"]`),r=document.head.querySelector("title");n?document.head.replaceChild(e.cloneNode(!0),n):r?.nextSibling?document.head.insertBefore(e.cloneNode(!0),r.nextSibling):document.head.appendChild(e.cloneNode(!0))}else if("TITLE"===t){const t=document.head.querySelector("title");t?document.head.replaceChild(e.cloneNode(!0),t):document.head.appendChild(e.cloneNode(!0))}else if("LINK"===t){const t=t=>{const s=document.head.querySelector('link[rel="icon"]');if(s)document.head.replaceChild(e.cloneNode(!0),s);else{const e=document.createElement("link");e.rel="icon",e.href=t,document.head.appendChild(e)}};if("icon"===e.getAttribute("rel")){t(e.href)}else if(e.hasAttribute(i)){const t=e.cloneNode(!0);document.head.appendChild(t)}}})),await this.initReactiveOn(e.body),await this.populateDocumentBody(e)})(n),this.restoreScrollPositions(t),await this.rerunInlineScripts(),this.attachWireFunctionEvents(),this.handlerAutofocusAttribute()}async rerunInlineScripts(){const e=Array.from(document.querySelectorAll('script[type="text/javascript"]:not([src])')),t=new Map;e.forEach((e=>{const s=(e.textContent||"").trim();if(t.has(s))return void e.remove();t.set(s,e);const n=document.createElement("script");[...e.attributes].forEach((e=>n.setAttribute(e.name,e.value))),n.textContent=e.textContent,e.replaceWith(n)}))}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const s=this.getElementKey(t);e[s]&&(t.scrollTop=e[s].scrollTop,t.scrollLeft=e[s].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const s=e,n=t;return s.value!==n.value&&(n.value=s.value),n.checked=s.checked,document.activeElement!==s||(null!=s.selectionStart&&(n.selectionStart=s.selectionStart,n.selectionEnd=s.selectionEnd),!1)},TEXTAREA(e,t){const s=e,n=t;return s.value!==n.value&&(n.value=s.value),document.activeElement!==s||(n.selectionStart=s.selectionStart,n.selectionEnd=s.selectionEnd,!1)},SELECT(e,t){const s=e;return t.selectedIndex=s.selectedIndex,document.activeElement!==s},VIDEO(e,t){const s=e,n=t;return n.currentTime=s.currentTime,s.paused?n.pause():n.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,s=e.body;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const s=new Function("event",t);e.addEventListener("wheel",s,{passive:!0})}})),this._wheelHandlersStashed=!0);const n=this.PRESERVE_HANDLERS;morphdom(t,s,{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 s=e.tagName;if("SCRIPT"===s||e.hasAttribute("data-nomorph"))return!1;const r=n[s];return!r||r(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async 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,s=!1){let n;return s?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,n=this._activeAbortController):n=new AbortController,fetch(e,{...t,signal:n.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){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,s,n){setTimeout((()=>{requestAnimationFrame((()=>{e.style[s]=n}))}),t)}async fetchFunction(e,t={},s=!1){try{const n={callback:await this.encryptCallbackName(e),...t},r=window.location.href;let i;if(Object.keys(n).some((e=>{const t=n[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(n).forEach((t=>{const s=n[t];s instanceof File?e.append(t,s):s instanceof FileList?Array.from(s).forEach((s=>e.append(t,s))):e.append(t,s)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(n);const a=await this.fetch(r,i,s);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const o=await a.text();try{return JSON.parse(o)}catch{return o}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}processSyncScripts(e){e.forEach((e=>{const t=`script[pp-sync-script="${CSS.escape(e)}"]`,s=document.querySelector(t);if(s){s.remove();const e=document.createElement("script");Array.from(s.attributes).forEach((t=>{e.setAttribute(t.name,t.value)})),s.src?e.src=s.src:e.textContent=s.textContent,e.type=s.type||"module",document.body.appendChild(e)}}))}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const s=e.length>0?e.map((e=>`pp-sync="${e}"`)):['pp-sync="true"'],n=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()}),r=await this.fetch(window.location.href,n),i=await r.text(),a=(new DOMParser).parseFromString(i,"text/html"),o=new Set;s.forEach((e=>{const t=document.querySelectorAll(`[${e}]`),s=a.body.querySelectorAll(`[${e}]`);t.forEach(((e,t)=>{const n=s[t];if(n){if(n.hasAttribute("pp-sync-script")){const e=n.getAttribute("pp-sync-script")||"";e&&o.add(e)}n.querySelectorAll("[pp-sync-script]").forEach((e=>{const t=e.getAttribute("pp-sync-script")||"";t&&o.add(t)})),e.innerHTML=n.innerHTML,this.reRunScripts(e)}}))})),this.processSyncScripts(o),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("Error in pphpSync:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),s=await t.text();await this.updateBodyContent(s)}reRunScripts(e){e.querySelectorAll("script").forEach((e=>{const t=document.createElement("script");Array.from(e.attributes).forEach((e=>{t.setAttribute(e.name,e.value)})),e.hasAttribute("src")||(t.textContent=e.textContent),e.parentNode?.replaceChild(t,e)}))}copyCode(e,t,s,n,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const a=e.closest(`.${t}`)?.querySelector("pre code"),o=a?.textContent?.trim()||"";o?navigator.clipboard.writeText(o).then((()=>{const t=e.querySelector(r);if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s);setTimeout((()=>{if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;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.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){if(this.state={...this.state,...e},this.listeners.forEach((e=>e(this.state))),this.saveState(),t){const e=localStorage.getItem(this.STORAGE_KEY);e&&this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]: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})}}}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 s=this.params;s.set(e,t),this.updateURL(s)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const s in e){const n=e[s];null!==n&&t.set(s,n)}this.updateURL(t,!0)}updateURL(e,t=!1){const s=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",s):history.pushState(null,"",s),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,s=new Map,n=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let a=i;n.has(t)&&(void 0===a?a={passive:!0}:"boolean"==typeof a?a={capture:a,passive:!0}:a&&void 0===a.passive&&(a={...a,passive:!0})),s.has(this)||s.set(this,new Map);const o=s.get(this),c=o.get(t)||new Set;c.add(r),o.set(t,c),e.call(this,t,r,a)},EventTarget.prototype.removeEventListener=function(e,n,r){if(s.has(this)&&s.get(this).has(e)){const t=s.get(this).get(e);t.delete(n),0===t.size&&s.get(this).delete(e)}t.call(this,e,n,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(!s.has(this))return;const n=s.get(this).get(e);n&&(n.forEach((s=>{t.call(this,e,s)})),s.get(this).delete(e))}})();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_scopedKeys=new Map;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpSections=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_activeSection=null;_inlineModuleFns=new Map;_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 Map;_sectionParentMap=new Map;_sectionRefs=new Map;_processedLoops=new WeakSet;_hydrated=!1;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _lastJWT=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"]);static _bareCallRe=/^[A-Za-z_$]\w*\s*\(.*\)$/;static _autoPrefixes=new Set;constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),s=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...s].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{await Promise.all([this.initRefs(),this.processInlineModuleScripts()]),await e(),await this.initializeAllReferencedProps(),await e(),await this.initBindings(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();for(let t=0;t<this._bindings.length;t+=250)this._bindings.slice(t,t+250).forEach((e=>e.update())),await e();document.body.removeAttribute("hidden"),this._hydrated=!0};"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("."),s=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:n,exp:r}=JSON.parse(s);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(n),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),s=(new TextEncoder).encode(e),n=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,s);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(n)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,s]=e.split(":",2),n=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),r=Uint8Array.from(atob(s),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:n},PPHP._cryptoKey,r);return(new TextDecoder).decode(i)}qsa(e,t){return e.querySelectorAll(t)}getScopeId(e){for(;e;){const t=e.getAttribute("pp-phpx-id");if(t)return t;const s=e.getAttribute("pp-section-id");if(s)return s;e=e.parentElement}return null}getSectionId(e){for(;e;){const t=e.getAttribute("pp-section-id");if(t)return t;e=e.parentElement}return null}getPhpxId(e){for(;e;){const t=e.getAttribute("pp-phpx-id");if(t)return t;e=e.parentElement}return null}getPhpxParentId(e){if(!e)return null;let t=e,s=null;for(;t&&!s;)s=t.getAttribute("pp-phpx-id"),s||(t=t.parentElement);let n=t?.parentElement;for(;n;){const e=n.getAttribute("pp-phpx-id");if(e&&e!==s)return e;n=n.parentElement}return null}ref(e,t){const s=this._activeSection;let n=[];if(s&&(n=this._sectionRefs.get(s)?.get(e)??[]),0===n.length&&(n=this._refs.get(e)??[]),null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const s=this._currentScopeId(),n=Array.isArray(t),r=n?t:[],i=n&&0===r.length,a=r.map((e=>{if("function"==typeof e&&e.__pphp_key)return e.__pphp_key;if("string"!=typeof e)return"";if(e.includes("_"))return e;for(const[t,s]of this._scopedKeys)if(s.has(e))return`${t}_${e}`;if(s){const t=this._sharedStateMap.get(s);if(t?.has(e)){const t=this._sectionParentMap.get(s);return t?`${t}_${e}`:e}}return e})).filter(Boolean),o=new Set(a),c=new Map;for(const e of a){const t=this.getNested(this.props,e);c.set(e,t)}let l=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const h=PPHP._effectCleanups,p=()=>{const t=h.get(p);if(t){try{t()}catch(e){console.error("cleanup error:",e)}h.delete(p)}if(++l>50)throw new Error("PPHP: effect ran >50 times — possible loop");if(!i&&a.length>0){let e=!1;for(const t of a){if(this.getNested(this.props,t)!==c.get(t)){e=!0;break}}if(!e)return;for(const e of a)c.set(e,this.getNested(this.props,e))}try{const t=e();"function"==typeof t&&h.set(p,t)}catch(e){console.error("effect error:",e)}};Object.assign(p,{__deps:o,__sectionId:s??null,__static:i});try{const t=e();"function"==typeof t&&h.set(p,t)}catch(e){console.error("effect error (initial):",e)}for(const e of a)c.set(e,this.getNested(this.props,e));const d=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return i?this._effects.add(p):d.add(p),()=>{const e=h.get(p);if(e){try{e()}catch(e){console.error("cleanup error:",e)}h.delete(p)}this._effects.delete(p),this._pendingEffects.delete(p)}}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._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._sectionParentMap.clear(),this._sectionRefs.clear(),this._processedPhpSections.clear(),this._processedPhpScripts=new WeakSet,this._scopedKeys.clear(),this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._activeSection=null,PPHP._autoPrefixes.clear(),this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),this._sectionRefs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1,this.props=this.makeReactive(this._rawProps),this._hydrated=!1}async initReactiveOn(e=document.body){const t=()=>new Promise((e=>setTimeout(e,0)));await Promise.all([this.initRefs(e),await this.processInlineModuleScripts(e)]),await t(),await this.initializeAllReferencedProps(e),await t(),await this.initBindings(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();e===document.body&&document.body.removeAttribute("hidden"),this._hydrated=!0}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.getScopeId(e),s=e.getAttribute("pp-for").trim(),[n,r]=s.split(/\s+in\s+/),[i,a]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim())),o=t?`${t}_${i}`:i,c=a?t?`${t}_${a}`:a:null,l=t?r.replace(/\b([A-Za-z_$]\w*)\b/g,((e,s,n,r)=>"."===r[n-1]||this._reservedWords.has(s)||s.startsWith(t+"_")||this.hasNested(this.props,s)||this._sharedStateMap.get(t)?.has(s)?e:`${t}_${s}`)):r,h=e.parentNode,p=document.createComment("pp-for");h.insertBefore(p,e),h.removeChild(e);const d=this.makeSafeEvaluator(l),u=e=>t?e.replace(new RegExp(`\\b${i}\\b`,"g"),o).replace(a?new RegExp(`\\b${a}\\b`,"g"):/$^/,c??""):e,f=this.extractDependencies(l),m=l.match(/^\s*([A-Za-z_$]\w*)\s*\(/);if(m){const e=m[1],t=this._inlineModuleFns.get(e);if("function"==typeof t){const e=t.toString();this.extractDependencies(e).forEach((e=>f.add(e.split(".")[0])))}}this._bindings.push({dependencies:f,update:()=>{const t=document.activeElement;let s=null,n=null;if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&h.contains(t)){const e=t.closest("[key]");s=e?.getAttribute("key")??null,n=t.selectionStart}for(let e=p.nextSibling;e&&e.nodeType!==Node.COMMENT_NODE;){const t=e.nextSibling;h.removeChild(e),e=t}const r=this.getOrCreateProxy(this.props),l=d(r);Array.isArray(l)||console.warn("[pp-for] expected an Array but got:",l);if((Array.isArray(l)?l:[]).forEach(((t,s)=>{this.props[o]=t,c&&(this.props[c]=s);const n=e.content.cloneNode(!0),r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);for(let e;e=r.nextNode();)e.nodeValue=(e.nodeValue||"").replace(PPHP._mustachePattern,((e,t)=>{try{const e=u(t);return this.formatValue(this.makeSafeEvaluator(e)(this.props))}catch{return""}}));n.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes)){if("pp-bind"===t){const t=u(s),n=this.makeSafeEvaluator(t)(this.props);e.textContent=this.formatValue(n);continue}if("pp-bind-expr"===t){const t=this.decodeEntities?this.decodeEntities(s):s,n=u(t),r=this.makeSafeEvaluator(n)(this.props);e.textContent=this.formatValue(r);continue}const n=t.match(/^pp-bind-(.+)$/);if(!n)continue;const r=n[1],i=u(s),a=this.makeSafeEvaluator(i)(this.props);if(this._boolAttrs.has(r)){const t=!!a;e[r]=t,t?e.setAttribute(r,""):e.removeAttribute(r)}else r in e?e[r]=a:e.setAttribute(r,String(a))}})),n.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes)){const n=t.match(/^pp-bind-(.+)$/);if(!n)continue;const r=n[1],i=u(s),a=this.makeSafeEvaluator(i)(this.props);if(this._boolAttrs.has(r)){const t=!!a;e[r]=t,t?e.setAttribute(r,""):e.removeAttribute(r)}else r in e?e[r]=a:e.setAttribute(r,String(a))}})),n.querySelectorAll("*").forEach((e=>{Array.from(e.attributes).forEach((n=>{const r=n.name.startsWith("on"),o=n.name.startsWith("pp-inc-on"),c=n.name.startsWith("pp-comp-on");if(!r&&!o&&!c)return;let l=n.value;/\b(?:i|idx)\b/.test(l)&&(l=((e,t)=>e.replace(/\[\s*(?:i|idx)\s*\]/g,`[${t}]`).replace(/(^|[^\w$])(?:i|idx)(?!\w)/g,((e,s)=>s+t)))(l,s));const h=new RegExp(`\\b${i}\\b`,"g");var p;if(l=l.replace(h,(p=t,JSON.stringify(p))),a){const e=new RegExp(`\\b${a}\\b`,"g");l=l.replace(e,String(s))}e.setAttribute(n.name,l)}))})),h.insertBefore(n,p.nextSibling)})),null!==s){const e=h.querySelector(`[key="${s}"]`),t=e?.querySelector("input,textarea");if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.focus({preventScroll:!0}),null!==n)){const e=Math.min(n,t.value.length);t.setSelectionRange(e,e)}}this.attachWireFunctionEvents()}})}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),s=this.getScopeId(e)??"__global__",n=this._sectionRefs.get(s)??new Map,r=n.get(t)??[];r.push(e),n.set(t,r),this._sectionRefs.set(s,n);const i=this._refs.get(t)??[];i.push(e),this._refs.set(t,i),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){const s=this._proxyCache.get(e);if(s)return s;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;const n=this,r=new Proxy(e,{get(e,s,r){const i=Reflect.get(e,s,r);if(Array.isArray(e)&&"string"==typeof s&&n._mutators.has(s)){let a=n._arrayMethodCache.get(e);if(a||(a=new Map,n._arrayMethodCache.set(e,a)),!a.has(s)){const e=i.bind(r),o=t.join("."),c=function(...t){const s=e(...t);return queueMicrotask((()=>{n._bindings.forEach((e=>{e.dependencies.has(o)&&n.scheduleBindingUpdate(e)}))})),s};a.set(s,c)}return a.get(s)}return null!==i&&"object"==typeof i?n.makeReactive(i,[...t,s]):i},set(e,s,r,i){let a=r;null!==r&&"object"==typeof r&&(a=n.makeReactive(r,[...t,s]));const o=e[s],c=Reflect.set(e,s,a,i);if(o===a)return c;const l=[...t,s].join(".");return n._bindings.forEach((e=>{for(const t of e.dependencies)if(l===t||l.startsWith(t+".")||t.startsWith(l+".")){n.scheduleBindingUpdate(e);break}})),c}});return this._proxyCache.set(e,r),r}makeAttrTemplateUpdater(e,t,s,n){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=n??r.get(t),a=this.getScopeId(e),o=e=>a?this.prefixIds(e,a,new Set):e;return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractDependencies(o(t)).forEach((e=>s.add(e)))})),()=>{try{const s=i.replace(this._mustacheRe,((e,t)=>{try{const e=o(t),s=this.makeSafeEvaluator(e);return this.formatValue(s(this.props))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==s&&e.setAttribute(t,s)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}makePrimitiveUpdater(e,t,s){const n={};return this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);n[t]=t}})),n.value="input",n.checked="change",()=>{try{const r=s(this.props),i=this.formatValue(r);let a=!1;if("value"===t){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,s="true"===i;"checked"in e&&t.checked!==s?(t.checked=s,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 o=n[t]||t,c="click"===o?new MouseEvent(o,{bubbles:!0,cancelable:!0}):new Event(o,{bubbles:!0});e.dispatchEvent(c)}catch(e){console.error(`Error evaluating attribute "${t}":`,e)}}}formatValue(e){return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"function"==typeof e?"":"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e?JSON.stringify(e):String(e))).join(", "):e&&"object"==typeof e?Object.keys(e).length?JSON.stringify(e,null,2):"":e?.toString()??""}registerBinding(e,t,s="text",n){if(this._assignmentRe.test(t))return;const r=this.getScopeId(e);let i=t;if(r){const e=this._scopedKeys.get(r)||new Set,s=this._sharedStateMap.get(r)||new Set,n=this._sectionParentMap.get(r);i=t.replace(/\b([A-Za-z_$][\w$]*)\b/g,((t,i,a,o)=>{if("."===o[a-1]||this._reservedWords.has(i))return t;if(s.has(i))return n?`${n}_${i}`:i;if(e.has(i)||this._declaredStateRoots.has(`${r}_${i}`)||this.hasNested(this.props,`${r}_${i}`))return`${r}_${i}`;let c=this._sectionParentMap.get(r)||null;for(;c;){if(this._scopedKeys.get(c)?.has(i)||this.hasNested(this.props,`${c}_${i}`))return`${c}_${i}`;c=this._sectionParentMap.get(c)||null}return t}))}const a=new Set([...this.extractDependencies(i)].map((e=>e.split(".")[0])).filter((e=>e in this.props&&!this._reservedWords.has(e)))),o=this.makeSafeEvaluator(i);if("value"===n||"checked"===n){const t=this.makePrimitiveUpdater(e,n,o);return void this._bindings.push({dependencies:a,update:t})}if(n){const s=n.toLowerCase();if(this._boolAttrs.has(s)){e.removeAttribute(s);const r=()=>{try{const t=!!o(this.props);e[n]!==t&&(e[n]=t),t?e.setAttribute(s,""):e.removeAttribute(s)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:a,update:r})}const c=e.getAttribute(n)??"";if(this._mustacheRe.test(i)||this._mustacheRe.test(c)){const t=this._scopedKeys.get(r??"")||new Set,s=this._sharedStateMap.get(r??"")||new Set,i=this._sectionParentMap.get(r??"")||null,o=c.replace(this._mustacheRe,((e,n)=>`{{ ${n.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,n,a,o)=>{if("."===o[a-1]||this._reservedWords.has(n))return e;if(s.has(n))return i?`${i}_${n}`:n;if(t.has(n)||this._declaredStateRoots.has(`${r}_${n}`)||this.hasNested(this.props,`${r}_${n}`))return`${r}_${n}`;let c=this._sectionParentMap.get(r??"")||null;for(;c;){if(this._scopedKeys.get(c)?.has(n)||this.hasNested(this.props,`${c}_${n}`))return`${c}_${n}`;c=this._sectionParentMap.get(c)||null}return e}))} }}`)),l=this.makeAttrTemplateUpdater(e,n,a,o);return void this._bindings.push({dependencies:a,update:l})}const l=()=>{try{const t=o(this.props),s=this.formatValue(t);n in e&&(e[n]=s),e.setAttribute(n,s)}catch(e){console.error(`Error evaluating attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:a,update:l})}const c={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:a,update:()=>{try{const t=o(this.props),n=this.formatValue(t);c[s](e,n)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),s=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let n;try{n=new Function("ctx",s)}catch(t){const s=JSON.stringify(e);n=new Function("ctx",`try { return ${s}; } catch { return ""; }`)}return e=>{try{const t=n(e);return null==t?"":t}catch{return""}}}async initBindings(e=document.body){this._bindings=[];const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const s=[];let n=e;for(;n;){if(n.hasAttribute("pp-if"))s.push({el:n,expr:n.getAttribute("pp-if")});else if(n.hasAttribute("pp-elseif"))s.push({el:n,expr:n.getAttribute("pp-elseif")});else{if(!n.hasAttribute("pp-else"))break;s.push({el:n,expr:null})}t.add(n),n=n.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractDependencies(t);const s=this.makeSafeEvaluator(t);e.evaluate=()=>!!s(this.props)}}));const r=new Set;s.forEach((e=>e.deps?.forEach((e=>r.add(e)))));this._bindings.push({dependencies:r,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})})),this.qsa(e,"*").forEach((e=>{["pp-bind","pp-bind-expr"].forEach((t=>{const s=e.getAttribute(t);s&&this.registerBinding(e,s,"text")})),Array.from(e.attributes).forEach((t=>{const s=t.name.toLowerCase(),n=t.value.trim();this._boolAttrs.has(s)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(n)&&(e.removeAttribute(t.name),this.registerBinding(e,n,"text",s))})),Array.from(e.attributes).forEach((t=>{if(!t.name.startsWith("pp-bind-"))return;const s=t.name;if("pp-bind"===s||"pp-bind-expr"===s||"pp-bind-spread"===s)return;const n=this.decodeEntities(t.value).replace(/^{{\s*|\s*}}$/g,""),r=s.replace(/^(pp-bind-)+/,""),i="value"===r?"value":"checked"===r?"checked":"text";this.registerBinding(e,n,i,r)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),n=new Set;s.forEach((e=>n.add(e.split(".")[0])));const r=new Set;this._bindings.push({dependencies:n,update:()=>{try{const t={};s.forEach((e=>{const s=this.getNested(this.props,e)??{};Object.assign(t,s)})),r.forEach((s=>{s in t||e.hasAttribute(s)||(e.removeAttribute(s),r.delete(s))})),Object.entries(t).forEach((([t,s])=>{if(!r.has(t)&&e.hasAttribute(t))return;if(null==s||!1===s)return void(r.has(t)&&(e.removeAttribute(t),r.delete(t)));const n="object"==typeof s?JSON.stringify(s):String(s);e.getAttribute(t)!==n&&e.setAttribute(t,n),r.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})}))}))}callInlineModule(e,...t){const s=this._inlineModuleFns.get(e);if(!s)throw new Error(`PPHP: no inline module named "${e}"`);return s(...t)}async processInlineModuleScripts(e=document.body){this._inlineDepth++,this._sharedStateMap.clear(),this._sectionParentMap.clear();try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>{const t=this.getScopeId(e);return t?!this._processedPhpSections.has(t):!this._processedPhpScripts.has(e)}));if(!t.length)return;this.qsa(e,"[pp-section-id]").forEach((e=>{const t=e.getAttribute("pp-section-id"),s=this.findParentSectionId(e);s&&this._sectionParentMap.set(t,s)})),this.qsa(e,"[pp-phpx-id]").forEach((e=>{const t=e.getAttribute("pp-phpx-id"),s=this.findParentSectionId(e);s&&this._sectionParentMap.set(t,s)}));const s=this.sortScriptsByDependency(t),n={};for(const e of s){const t=this.getScopeId(e);if(!t)continue;const s=e.textContent||"";for(const[,e]of[...s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g),...s.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g)])n[e]=t}for(const[e,t]of Object.entries(n))this._scopedKeys.has(t)||this._scopedKeys.set(t,new Set),this._scopedKeys.get(t).add(e);for(const e of s){const t=this.getScopeId(e);let s=(e.textContent||"").trim();if(s=this.decodeEntities(s),s=this.stripComments(s),s=this.transformStateDeclarations(s,t),t){const e=this._sectionParentMap.get(t)??null,n=t+"_",r=e?e+"_":"",i=new Set;if(this._declaredStateRoots.forEach((e=>{e.startsWith(n)?i.add(e.slice(n.length)):r&&e.startsWith(r)?i.add(e.slice(r.length)):e.includes("_")||i.add(e)})),i.size){let e="";for(const a of i){const i=this.hasNested(this.props,n+a)?n+a:this.hasNested(this.props,r+a)?r+a:a,o="set"+a[0].toUpperCase()+a.slice(1),c=`${t}_${a}`,l=`${t}_${o}`;new RegExp(`\\b(?:const|let|var)\\s+\\[?\\s*${a}\\b`).test(s)||(e+=`\n const ${a} = (() => {\n const fn = () => pphp.props.${i};\n fn.__pphp_key = '${i}';\n Object.defineProperty(fn, 'value', {\n get() { return pphp.props.${i}; },\n set(v) { pphp.props.${i} = v; }\n });\n return fn;\n })();\n const ${o} = v => {\n pphp.props.${i} = typeof v === 'function'\n ? v(pphp.props.${i})\n : v;\n };\n pphp._inlineModuleFns.set('${c}', ${a});\n pphp._inlineModuleFns.set('${l}', ${o});`)}s=e+"\n"+s}}const r=this.extractSetters(s,t);if(r.length){s+="\n\n";for(const e of r){s+=`pphp._inlineModuleFns.set('${t?`${t}_${e}`:e}', ${e});\n`}}if(t){const e=this._sectionParentMap.get(t)??null,n=e?e+"_":"";s=s.replace(/(\bpphp\.state\(\s*['"])([^'"]+)(['"])/g,((e,s,r,i)=>r.startsWith(t+"_")||n&&r.startsWith(n)||!r.includes("_")?s+r+i:s+`${t}_${r}`+i))}s=s.replace(/\b([A-Za-z_$]\w*)\s*\(/g,((e,t,s,r)=>{const i=r.slice(Math.max(0,s-20),s);if(/\b(?:function|export\s+function)\s*$/.test(i.trim()))return e;const a=n[t];return a?`${a}_${t}(`:e}));const i=new Blob([s],{type:"application/javascript"}),a=URL.createObjectURL(i),o=PPHP.prototype._currentScopeId;t&&(PPHP.prototype._currentScopeId=()=>t);try{const e=await import(a);for(const[s,n]of Object.entries(e))if("function"==typeof n){const e=t?`${t}_${s}`:s;this._inlineModuleFns.set(e,n)}}catch(e){console.error("Inline module import failed:",e)}finally{PPHP.prototype._currentScopeId=o,URL.revokeObjectURL(a),t?this._processedPhpSections.add(t):this._processedPhpScripts.add(e)}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}stripComments(e){let t="",s=0,n=!1,r="",i=!1;for(;s<e.length;){const a=e[s],o=e[s+1];if(i||"'"!==a&&'"'!==a&&"`"!==a||"\\"===e[s-1])if(n)t+=a,s++;else if(i||"/"!==a||"*"!==o)if(i)"*"===a&&"/"===o?(i=!1,s+=2):s++;else if("/"!==a||"/"!==o)t+=a,s++;else for(;s<e.length&&"\n"!==e[s];)s++;else i=!0,s+=2;else n=!n,r=n?a:"",t+=a,s++}return t}findParentSectionId(e){const t=e.parentElement?.closest("[pp-section-id]");return t?t.getAttribute("pp-section-id"):null}extractSetters(e,t){const s=[],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,i]=r;"share"===i&&this.markShared(t,e),t&&this._sharedStateMap.get(t)?.has(e)||s.push(n)}return s}markShared=(e,t)=>{e&&(this._sharedStateMap.has(e)||this._sharedStateMap.set(e,new Set),this._sharedStateMap.get(e).add(t))};transformStateDeclarations(e,t){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,s,n,r,i)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}${n}, ${r}${i}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,s,n,r)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}${n}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,s,n,r)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}[${n}] = pphp.state('${n}', `))}sortScriptsByDependency(e){const t=new Map;for(const s of e){const e=this.getScopeId(s);t.has(e)||t.set(e,[]),t.get(e).push(s)}const s=[],n=new Set,r=e=>{if(!e)return[];const t=this._sectionParentMap.get(e);if(t)return[t];const s=this._sharedStateMap.get(e);return s&&s.size>0?[t||null]:[]},i=e=>{if(n.has(e))return;for(const t of r(e))i(t);const a=t.get(e)||[];s.push(...a),n.add(e)};i(null);for(const e of t.keys())null!==e&&i(e);return s}flushBindings(){const e=new Set(this._dirtyDeps);this._pendingBindings.forEach((t=>{t.dependencies.forEach((t=>e.add(t))),t.update()})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const s=t.__deps||new Set;if(0===s.size||[...s].some((t=>e.has(t)))){const e=this._activeSection;this._activeSection=t.__sectionId??null;try{t()}catch(e){console.error("effect error:",e)}this._activeSection=e}}))}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}scopeKey(e){const t=this._currentScopeId();if(!t)return e;const s=this._sharedStateMap.get(t);if(s?.has(e)){const s=this._sectionParentMap.get(t);return s?`${s}_${e}`:e}return e.startsWith(`${t}_`)?e:`${t}_${e}`}_currentScopeId(){const e=document.currentScript;return this.getScopeId(e)}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,s){const n=t.split("."),r=n.pop();n.reduce(((e,t)=>e[t]??={}),e)[r]=s}hasNested(e,t){return void 0!==this.getNested(e,t)}share(e,t){const s=PPHP._shared.get(e);if(s)return[s.getter,s.setter];const[n,r]=this.state(e,t);return PPHP._shared.set(e,{getter:n,setter:r}),[n,r]}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure your build-time injector ran and you wrote `const [foo, setFoo] = pphp.state(0)` so it became `pphp.state('foo', 0)`.");arguments.length<2&&(t=void 0);const s=this._currentScopeId(),n=e;if(this._reservedWords.has(n))throw new Error(`'${n}' is reserved – choose another state key.`);const r=this.scopeKey(n);this._declaredStateRoots.add(r),s&&(this._scopedKeys.has(s)||this._scopedKeys.set(s,new Set),this._scopedKeys.get(s).add(n)),this.hasNested(pphp.props,r)||this.setNested(pphp.props,r,t);const i=()=>this.getNested(pphp.props,r),a=e=>{const t=i(),s="function"==typeof e?e(t):e;this.setNested(pphp.props,r,s),this._dirtyDeps.add(r.split(".")[0]),this.scheduleFlush()},o=()=>i();Object.defineProperty(o,"value",{get:()=>i(),set:e=>a(e)}),Object.defineProperties(o,{valueOf:{value:()=>i()},toString:{value:()=>String(i())}}),o.__pphp_key=r;const c=i();if(null===c||"object"!=typeof c)return[o,a];return[new Proxy(o,{apply:(e,t,s)=>Reflect.apply(e,t,s),get(e,t,s){if("value"===t)return i();if(t in e)return Reflect.get(e,t,s);return i()[t]},set(e,t,s){if("value"===t)return a(s),!0;return i()[t]=s,!0},has(e,t){if("value"===t||t in o)return!0;return t in i()}}),a]}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 s=>{const n=e.get(s);if(void 0!==n)return n;const r=s in globalThis||t.some((e=>s in e));return e.set(s,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let s=e.replace(/\?\./g,".");const n=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(s);){(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)))}const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(s);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const a=e=>{let t="",s=0;for(;s<e.length;)if("`"===e[s])for(s++;s<e.length;)if("\\"===e[s])s+=2;else if("$"===e[s]&&"{"===e[s+1]){s+=2;let n=1;const r=s;for(;s<e.length&&n>0;)"{"===e[s]?n++:"}"===e[s]&&n--,s++;const i=e.slice(r,s-1);t+=a(i)+" "}else{if("`"===e[s]){s++;break}s++}else t+=e[s++];return t};s=a(s),s=s.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),s=s.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const o=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of s.match(c)??[]){const[s,...r]=t.split(".");n.has(s)||(0===r.length&&PPHP._isBuiltIn(s)&&new RegExp(`\\.${s}\\b`).test(e)||o.add(t))}return o}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,s=PPHP._mustacheTest,n=this.props,r=new Set,i=(e,t)=>{if(this.hasOwnNested(this.props,t))return t;const s=e.getAttribute("pp-section-id"),n=this.getScopeId(e.parentElement);return s??n?`${s??n}_${t}`:t},a=(()=>{const e=new Set([...Object.getOwnPropertyNames(String.prototype),...Object.getOwnPropertyNames(Array.prototype),...Object.getOwnPropertyNames(Number.prototype),...Object.getOwnPropertyNames(Boolean.prototype),...Object.getOwnPropertyNames(Object.prototype),...Object.getOwnPropertyNames(Date.prototype),...Object.getOwnPropertyNames(RegExp.prototype)]);return t=>e.has(t)})(),o=(e,t)=>{const[s,n,...o]=t.split(".");if(this._reservedWords.has(s))return;if(n&&a(n))return void r.add(i(e,s));const c=i(e,s);r.add(n?`${c}.${[n,...o].join(".")}`:c)};for(const n of this.qsa(e,"*"))for(const{name:e,value:r}of Array.from(n.attributes))if(r){if(s.test(r))for(const e of r.matchAll(t))this.extractDependencies(e[1]).forEach((e=>o(n,e)));"pp-if"!==e&&"pp-elseif"!==e||this.extractDependencies(r).forEach((e=>o(n,e))),e.startsWith("pp-bind")&&this.extractDependencies(r).forEach((e=>o(n,e)))}const c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>s.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let l;for(;l=c.nextNode();){const e=l.parentElement;for(const s of l.nodeValue.matchAll(t))this.extractDependencies(s[1]).forEach((t=>o(e,t)))}const h=Array.from(r).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of h){const t=e.split(".");let s=n;for(let e=0;e<t.length;e++){const n=t[e],r=e===t.length-1,i=t.slice(0,e+1).join(".");n in s&&(r||null!=s[n]&&"object"==typeof s[n])||r&&this._declaredStateRoots.has(i)||(s[n]=r?void 0:{}),s=s[n]}}}hasOwnNested(e,t){const s=t.split(".");let n=e;for(const e of s){if(!n||!Object.prototype.hasOwnProperty.call(n,e))return!1;n=n[e]}return!0}setNestedProperty(e,t,s){const n=t.split(".");let r=e;for(let e=0;e<n.length-1;e++)n[e]in r||(r[n[e]]={}),r=r[n[e]];r[n[n.length-1]]=s}async attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=e=>Array.from(this._eventHandlers).map((t=>`[${e}${t}]`)),t=[...e(""),...e("pp-inc-"),...e("data-pp-child-"),...e("data-pp-parent-")].flat().join(","),s=this.qsa(document.body,t);for(const e of s){const t=this.getSectionId(e),s=this.getPhpxId(e),n=this.getPhpxParentId(e);t&&PPHP._autoPrefixes.add(`${t}_`),s&&PPHP._autoPrefixes.add(`${s}_`),n&&PPHP._autoPrefixes.add(`${n}_`);for(const r of this._eventHandlers){const i=r,a=`pp-inc-${r}`,o=`data-pp-child-${r}`,c=`data-pp-parent-${r}`,l=e.getAttribute(i),h=e.getAttribute(a),p=e.getAttribute(o),d=e.getAttribute(c),u=l?this.decodeEntities(l).trim():"",f=h?this.decodeEntities(h).trim():"",m=p?this.decodeEntities(p).trim():"",g=d?this.decodeEntities(d).trim():"";if(!(u||f||m||g))continue;const y=[];if(u&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(u,null))),f&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(f,t))),m&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(m,s))),g){const e=n||t||null;y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(g,e)))}const b=`(event) => { ${[...new Set(y)].join(" ")} }`;[i,a,o,c].forEach((t=>e.removeAttribute(t)));const _=r.slice(2);e.removeAllEventListeners(_),e instanceof HTMLInputElement&&this.handleInputAppendParams(e,_),this.handleDebounce(e,_,b)}}this.handlePassiveWheelStashes(document)}prefixFunctionCalls(e,t){if(!t)return e;const s=this._scopedKeys.get(t)??new Set,n=e=>s.has(e)||this._declaredStateRoots.has(`${t}_${e}`);return e.replace(/\b([A-Za-z_$][\w$]*)\s*\(/g,((e,s)=>this._reservedWords.has(s)||s.startsWith(`${t}_`)||!n(s)||this.hasNested(this.props,s)||this._inlineModuleFns.has(s)||"function"==typeof globalThis[s]?e:`${t}_${s}(`))}prefixIds(e,t,s=new Set){let n="",r=0,i=(e=this.prefixFunctionCalls(e,t)).length,a=!1,o=!1,c=!1;for(;r<i;){const l=e[r];if("'"!==l||o||c||"\\"===e[r-1])if('"'!==l||a||c||"\\"===e[r-1])if("`"!==l||a||o||"\\"===e[r-1])if(a||o||c)n+=l,r++;else if(/[A-Za-z_$]/.test(l)){let a=r+1;for(;a<i&&/[\w$]/.test(e[a]);)a++;const o=e.slice(r,a),c=e[r-1]??"",l=this._reservedWords.has(o),h="."===c;n+=!(o.startsWith(`${t}_`)||h||l||s.has(o)||this.hasNested(this.props,o))?`${t}_${o}`:o,r=a}else n+=l,r++;else c=!c,n+=l,r++;else o=!o,n+=l,r++;else a=!a,n+=l,r++}return n}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let s=t.value;for(;s.includes("&");){t.innerHTML=s;const e=t.value;if(e===s)break;s=e}return s};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 s=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(s){let t=e.substring(s[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let n=e.trim();return n&&!n.endsWith(";")&&(n+=";"),n};buildHandlerFromRawBody(e,t){let s=e.trim();s=s.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,s,n)=>{const r=`${t}->${s}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`})),s=s.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,s,n)=>{const r=`${t}::${s}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`}));const{normalized:n,originalParam:r}=this.normalizeToArrow(s),i=this.renameEventParam(n,r),a=this.replaceThisReferences(i),o=new Set(["event","pphp"]);return t?this.prefixBareIdentifiers(a,t,o):a}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}isBareCall(e){return!e.includes("=>")&&PPHP._bareCallRe.test(e)&&!/^[A-Za-z_$]\w*_/.test(e)}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const s=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(s)?s:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const s=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(s,((e,t,s)=>{const n=s[t-1],r=s[t+e.length];return n&&/[\w$]/.test(n)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}prefixBareIdentifiers(e,t,s=new Set(["event","pphp"])){const n=e.indexOf("=>");if(-1!==n){const r=e.slice(0,n+2),i=e.slice(n+2);return r+this.prefixIds(i,t,s)}const r=this.prefixIds(e,t,s);return/^[A-Za-z_$].*\)$/.test(r.trim())?`() => ${r}`:`(event) => { ${r}; }`}async handleDebounce(e,t,s){const n=e.getAttribute("pp-debounce"),r=n?this.parseTime(n):0,i=e.getAttribute("pp-before-request")??"",a=e.getAttribute("pp-after-request")??"",o=PPHP._cancelableEvents,c=async n=>{o.has(t)&&n.cancelable&&n.preventDefault();try{const t=this.getScopeId(e);if(i){const s=t?`${t}_${i}`:i;await this.invokeHandler(e,s,n)}if(await this.invokeHandler(e,s,n),a&&!a.startsWith("@close")){const s=t?`${t}_${a}`:a;await this.invokeHandler(e,s,n)}this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!o.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,p=e=>{if(r>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const s=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),r);PPHP._debounceTimers.set(h,s)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),p(e)}),l):e.addEventListener(t,p,l)}debounce(e,t=300,s=!1){let n;return function(...r){const i=this;n&&clearTimeout(n),n=setTimeout((()=>{n=null,s||e.apply(i,r)}),t),s&&!n&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const s=t.getAttribute("pp-autofocus");if(!this.isJsonLike(s))return;const n=this.parseJson(s);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,n),t.type="number"):this.setCursorPosition(t,n))}))}async invokeHandler(e,t,s){this._activeSection=this.getScopeId(e);try{const n=t.trim();let r=this._handlerCache.get(n);r||(r=this.parseHandler(n),this._handlerCache.set(n,r)),await this.executeHandler(r,e,s,n)}catch(s){this.handleInvokeError(s,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 s=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(s)return{type:"call",name:s[1],args:s[2],isAsync:this.isAsyncFunction(s[1])};const n=t.match(/^(\w+)$/);return n?{type:"simple",name:n[1],isAsync:this.isAsyncFunction(n[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,s="",n=0;for(let r=0;r<e.length-1;r++){const i=e[r],a=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===s&&"\\"!==e[r-1])t=!1,s="";else if(!t&&("("===i&&n++,")"===i&&n--,"="===i&&">"===a&&n>=0))return!0}else t=!0,s=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let s=e.substring(t+2).trim();return s.startsWith("{")&&s.endsWith("}")&&(s=s.slice(1,-1).trim()),{type:"arrow",body:s,isAsync:e.includes("async")||this.containsAwait(s)}}findArrowIndex(e){let t=!1,s="";for(let n=0;n<e.length-1;n++){const r=e[n],i=e[n+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===s&&"\\"!==e[n-1])t=!1;else if(!t&&"="===r&&">"===i)return n}else t=!0,s=r}return-1}async executeArrowHandler(e,t,s){const n=this.parseStatements(e.body);let r=!1;for(const e of n)await this.executeSingleStatement(e,t,s)&&(r=!0);r||await this.executeDynamic(e.body,t,s)}async executeComplexHandler(e,t,s){await this.executeDynamic(e.body,t,s)}parseStatements(e){const t=[];let s="",n=0,r=!1,i="";for(let a=0;a<e.length;a++){const o=e[a];r||'"'!==o&&"'"!==o&&"`"!==o?r&&o===i&&"\\"!==e[a-1]&&(r=!1,i=""):(r=!0,i=o),r||("("!==o&&"{"!==o&&"["!==o||n++,")"!==o&&"}"!==o&&"]"!==o||n--,";"!==o||0!==n)?s+=o:s.trim()&&(t.push(s.trim()),s="")}return s.trim()&&t.push(s.trim()),t}async executeInlineModule(e,t,s,n,r){if(t&&t.trim())if(this.isJsonLike(t)){const s=this.parseJson(t);null!==s&&"object"==typeof s?await this.callInlineModule(e,{...s}):await this.callInlineModule(e,s)}else try{const s=this.getOrCreateEvaluator(t)(this.props);await this.callInlineModule(e,s)}catch{await this.callInlineModule(e,{element:s,event:n})}else await this.handleParsedCallback(s,r,n)}async executeSingleStatement(e,t,s){const n=e.trim();if(!n)return!1;const r=n.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return this.executeSingleStatement(r[1],t,s);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(n))return await this.executeDynamic(n,t,s),!0;const i=n.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i,a=this.resolveFunctionName(e);let o=[];if(""!==r.trim())try{o=JSON5.parse(`[${r}]`)}catch{try{const e=this.getOrCreateProxy(this.props),t=/\bevent\b/.test(r)?r.replace(/\bevent\b/g,"_evt"):r;o=new Function("_evt","proxy","props",`with (proxy) { return [ ${t} ]; }`)(s,e,this.props)}catch(e){o=[]}}if(a&&this._inlineModuleFns.has(a)){const e=this._inlineModuleFns.get(a);return o.length>0?await e(...o):await this.executeInlineModule(a,r,t,s,n),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,o),!0}return await this.handleParsedCallback(t,n,s),!0}const a=n.match(/^(\w+)$/);if(a){const e=a[1],n=this.resolveFunctionName(e);if(n&&this._inlineModuleFns.has(n))return await this.handleParsedCallback(t,`${n}()`,s),!0;if(n){const e=globalThis[n];if("function"==typeof e)return e.call(globalThis,s),!0}return await this.handleParsedCallback(t,`${e}()`,s),!0}return await this.executeDynamic(n,t,s),!0}async executeCallHandler(e,t,s,n){const{name:r,args:i}=e,a=this.resolveFunctionName(r);if(a){if(this._inlineModuleFns.has(a))return void await this.executeInlineModule(a,i||"",t,s,n);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,s)}await this.handleParsedCallback(t,n,s)}resolveFunctionName(e){if(this._inlineModuleFns.has(e))return e;if(!e.includes("_")&&"function"==typeof globalThis[e])return e;if(e.includes("_")){const[t,...s]=e.split("_"),n=s.join("_"),r=this._sectionParentMap.get(t);if(r){const e=`${r}_${n}`;if(this._inlineModuleFns.has(e))return e}if(this._inlineModuleFns.has(n))return n;if("function"==typeof globalThis[n])return n}return null}async executeSimpleHandler(e,t,s){const{name:n}=e,r=this.resolveFunctionName(n);if(r){if(this._inlineModuleFns.has(r))return void await this.handleParsedCallback(t,`${r}()`,s);const e=globalThis[r];if("function"==typeof e)return void e.call(globalThis,s)}await this.handleParsedCallback(t,`${n}()`,s)}async executeHandler(e,t,s,n){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,s);break;case"call":await this.executeCallHandler(e,t,s,n);break;case"simple":await this.executeSimpleHandler(e,t,s);break;case"complex":await this.executeComplexHandler(e,t,s);break;default:await this.handleParsedCallback(t,n,s)}}async executeGlobalFunction(e,t,s,n){if(t.trim())if(this.isJsonLike(t)){const s=this.parseJson(t)??{};e.call(globalThis,{...s})}else{const r=this.getOrCreateProxy(this.props);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(s,n,r,this.props,e)}else e.call(globalThis,n)}async executeDynamic(e,t,s){const n=this.getOrCreateProxy(this.props);let r=e;this._activeSection&&(r=this.prefixFunctionCalls(e,this._activeSection));const i=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${r}\n }`);await i.call(t,s,n,this.props)}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._inlineModuleFns;return new Proxy(e,{get(e,s,n){if("string"==typeof s){if(t.has(s))return t.get(s);if(s in e){const t=Reflect.get(e,s,n),r=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof r))return t}if(s in globalThis){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,n)},set:(e,t,s,n)=>Reflect.set(e,t,s,n),has:(e,s)=>"string"==typeof s&&t.has(s)||s in e||s 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,s){const n=e instanceof Error?e.message:String(e),r=s.tagName+(s.id?`#${s.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${n}`,e),s.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:s},bubbles:!0}))}clearHandlerCaches(){this._handlerCache.clear(),this._evaluatorCache.clear()}async handleParsedCallback(e,t,s){const{funcName:n,data:r}=this.parseCallback(e,t);if(!n)return;const i=Array.isArray(n)?n:[n];let a;for(const e of i){const t=this._inlineModuleFns.get(e);if("function"==typeof t){a=t;break}const s=this[e];if("function"==typeof s){a=s;break}const n=window[e];if("function"==typeof n){a=n;break}}if(a){const t=e.hasAttribute("pp-after-request"),n="@close"===e.getAttribute("pp-after-request");let i={args:Array.isArray(r.args)?r.args:[],element:e,data:r,event:s};if(t&&!n){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(n)?n[0]:n,r)}stripAutoPrefix(e){for(const t of PPHP._autoPrefixes)if(e.startsWith(t))return e.slice(t.length);return e}async handleUndefinedFunction(e,t,s){const n=this.stripAutoPrefix(t),r={callback:await this.encryptCallbackName(n),...s},i=this.createFetchOptions(r),a=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const t=new URL(window.location.href);let r="",o="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(r=await this.fetchFileWithData(t.href,n,l,s),o=this.extractJson(r)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(t.href,i);if(r=await e.text(),this.getRedirectUrl(r))return void await this.redirect(this.getRedirectUrl(r)||"");if(o=this.extractJson(r)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",p=e.getAttribute("pp-after-request")||"";if((h||p&&c.success)&&this.restoreSuspenseElement(e),h||p){let e="";if(c.success){e=r.replace(o,"")}else e=r;if(this.appendAfterbegin(e),!p&&!c.success)return}if(p&&c.success){this.handleAfterRequest(p,o);const e=r.replace(o,"");return this.appendAfterbegin(e),o}if("@close"===p)return c.success?o:void 0;const d=await this.fetch(t.href,a),u=await d.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(r,u,o,c)}catch(e){console.error(`Error handling undefined function "${n}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const s=this.parseJson(e),n=t?this.parseJson(t):null,r=s.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...s}=e,r=document.querySelector(t);let i={};if(n){for(const t in s)if(s.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===s[t]&&(i[t]=e.responseKey?n[e.responseKey]:n.response);break;default:i[t]=s[t]}}else i=s;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,s)=>` data-onwheel-code="${this.decodeEntities(s).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=>{let t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null;const s=this.getScopeId(e);if(s){const e=t.indexOf("=>");if(e>=0){const n=t.slice(0,e+2),r=t.slice(e+2);t=n+this.prefixIds(r,s)}else t=this.prefixIds(t,s)}e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t)}))}async handleResponseRedirectOrUpdate(e,t,s,n){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,s,n),a=(new DOMParser).parseFromString(r,"text/html");i&&a.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(a.body.outerHTML)}getUpdatedHTMLContent(e,t,s){const n=document.createElement("div");if(n.id="afterbegin-8D95D",s&&t?.success){const t=e.replace(s,"");n.innerHTML=t}else n.innerHTML=e;return n.innerHTML?n:null}async updateBodyContent(e){const t=this.saveScrollPositions();this.saveElementState();const s=(new DOMParser).parseFromString(e,"text/html");await this.appendCallbackResponse(s),this.resetProps(),await this.initReactiveOn(),this.restoreElementState(),this.restoreScrollPositions(t),await this.rerunInlineScripts(),this.attachWireFunctionEvents()}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)}await this.populateDocumentBody(e)}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 s in t)if(t.hasOwnProperty(s))switch(s){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[s]=this.decodeHTML(t[s]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[s].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[s].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[s]));break;case"removeAttribute":e.removeAttribute(t[s]);break;case"className":e.className=this.decodeHTML(t[s]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[s]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[s]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[s]));break;case"classList.replace":const[n,r]=this.decodeHTML(t[s]).split(",");e.classList.replace(n,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[s]);break;case"style":Object.assign(e.style,t[s]);break;case"value":e.value=this.decodeHTML(t[s]);break;case"checked":e.checked=t[s];break;default:e.setAttribute(s,this.decodeHTML(t[s]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let s=document.getElementById(t);s?(s.innerHTML=e,document.body.insertAdjacentElement("afterbegin",s)):(s=document.createElement("div"),s.id=t,s.innerHTML=e,document.body.insertAdjacentElement("afterbegin",s))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const s=(e,t)=>{for(const s in t)t.hasOwnProperty(s)&&("textContent"===s?e.textContent=t[s]:"innerHTML"===s?e.innerHTML=t[s]:"disabled"===s?!0===t[s]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(s,t[s]));for(const s of Array.from(e.attributes))t.hasOwnProperty(s.name)||e.removeAttribute(s.name)},n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const n=this.parseJson(e);s(t,n)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?n(e,t):s(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const n=this.parseJson(t);s(e,n)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),n(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(r.targets){r.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&i(n,s)}));const{targets:t,...n}=r;s(e,n)}else{const{empty:t,...n}=r;s(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,s,n={}){const r=new FormData,i=s.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in n)n.hasOwnProperty(e)&&r.append(e,n[e]);const a=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await a.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))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 s=this.parseJson(e);"disabled"!==s.onsubmit&&this.updateElementAttributes(t,s),s.targets&&s.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&r(n,s)}))}else n(t,e)}},n=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?s(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const n=this.parseJson(t);if(n)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),n.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...a}=n;this.updateElementAttributes(e,a),s(e,r)}else if(n.targets){n.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&r(n,s)}));const{targets:t,...s}=n;this.updateElementAttributes(e,s)}else{if("disabled"===n.empty&&""===e.value)return;const{empty:t,...s}=n;this.updateElementAttributes(e,s)}}else if(t)n(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),n={};t.forEach(((e,t)=>{n[t]=e})),s(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let s=0;s<e.attributes.length;s++){const n=e.attributes[s];t[n.name]=n.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const s=e.id;s&&(t=document.querySelector(`[form="${s}"]`)),s&&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,s)=>{e[s]=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 s={};const n=e.closest("form");if(n){new FormData(n).forEach(((e,t)=>{s[t]?Array.isArray(s[t])?s[t].push(e):s[t]=[s[t],e]:s[t]=e}))}else e instanceof HTMLInputElement?s=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(s[e.name]=e.value);const r=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(r){const e=r[1].trim(),t=r[2].trim(),n=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?s.args=e:e&&"object"==typeof e&&(s={...s,...e})}catch(e){console.error("Error parsing JSON args:",e),s.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?s.args=e:e&&"object"==typeof e?s={...s,...e}:s.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),s.rawArgs=t}else if(/^[\s\d"'[\{]/.test(t))try{const e=new Function(`return [${t}];`)();s.args=Array.isArray(e)?e:[e]}catch{n.test(t)?s.args=t.split(n).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):s.args=[t.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(t)(this.props);s.args=[e]}catch{s.args=t.split(n).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:s}}return{funcName:t,data:s}}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 s=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=s?s.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 s=parseInt(t.length,10)||0;e.setSelectionRange(s,s)}}handleInputAppendParams(e,t){const s=e.getAttribute("pp-append-params"),n=e.getAttribute("pp-append-params-sync");if("true"===s){if("true"===n){const t=e.name||e.id;if(t){const s=new URL(window.location.href),n=new URLSearchParams(s.search);n.has(t)&&(e.value=n.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,s=t.value,n=new URL(window.location.href),r=new URLSearchParams(n.search),i=t.name||t.id;if(i){s?r.set(i,s):r.delete(i);const e=r.toString()?`${n.pathname}?${r.toString()}`:n.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),s=this.handleElementVisibility.bind(this),n=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",s))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",n)))}handleVisibilityElementAttribute(e,t,s){const n=e.getAttribute(t);if(n)if(this.isJsonLike(n)){s(e,this.parseJson(n))}else{const s=this.parseTime(n);if(s>0){const n="pp-visibility"===t?"visibility":"display",r="visibility"===n?"hidden":"none";this.scheduleChange(e,s,n,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,s,n,r){const i=t.start?this.parseTime(t.start):0,a=t.end?this.parseTime(t.end):0;i>0?(e.style[s]=n,this.scheduleChange(e,i,s,r),a>0&&this.scheduleChange(e,i+a,s,n)):a>0&&this.scheduleChange(e,a,s,n)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,s=t.getAttribute("href"),n=t.getAttribute("target");if(s&&"_blank"!==n&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(s)&&!s.startsWith(window.location.origin))window.location.href=s;else{const e=t.getAttribute("pp-append-params");if(s.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let n="";const[r,i]=s.split("#");i&&(n=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,s)=>{t.set(s,e)}));const a=`${e.pathname}?${t.toString()}${n}`;history.pushState(null,"",a)}else{const[e,t]=s.split("#"),n=`${e}${t?`#${t}`:""}`;history.pushState(null,"",n)}const n=s.indexOf("#");if(-1!==n){const e=s.slice(n+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href);if(!t.ok)return void console.error(`Navigation error: ${t.status} ${t.statusText}`);const s=await t.text(),n=s.match(this._redirectRegex);if(n&&n[1])return void await this.redirect(n[1]);await this.updateDocumentContent(s)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let s=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${s}']`);if(t)return t;if("/"===s)break;const n=s.lastIndexOf("/");s=n<=0?"/":s.substring(0,n)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:s,fadeOut:n}=this.parseTransition(e);await this.fadeOut(t,n),t.innerHTML=e.innerHTML,this.fadeIn(t,s)}parseTransition(e){let t=250,s=250;const n=e.querySelector("[pp-loading-transition]"),r=n?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),s=this.parseTime(e.fadeOut??s)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:s}}fadeOut(e,t){return new Promise((s=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",s()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async updateDocumentContent(e){const t=this.saveScrollPositions(),s=this.sanitizePassiveHandlers(e),n=(new DOMParser).parseFromString(s,"text/html"),r="pp-dynamic-script",i="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove()));document.head.querySelectorAll(`[${i}]`).forEach((e=>e.remove()));document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove()));this.resetProps(),await(async e=>{Array.from(e.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(r)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){if(e.getAttribute("charset")||"viewport"===e.getAttribute("name"))return;const t=e.name,s=e.getAttribute("property"),n=document.head.querySelector(t?`meta[name="${t}"]`:`meta[property="${s}"]`),r=document.head.querySelector("title");n?document.head.replaceChild(e.cloneNode(!0),n):r?.nextSibling?document.head.insertBefore(e.cloneNode(!0),r.nextSibling):document.head.appendChild(e.cloneNode(!0))}else if("TITLE"===t){const t=document.head.querySelector("title");t?document.head.replaceChild(e.cloneNode(!0),t):document.head.appendChild(e.cloneNode(!0))}else if("LINK"===t){const t=t=>{const s=document.head.querySelector('link[rel="icon"]');if(s)document.head.replaceChild(e.cloneNode(!0),s);else{const e=document.createElement("link");e.rel="icon",e.href=t,document.head.appendChild(e)}};if("icon"===e.getAttribute("rel")){t(e.href)}else if(e.hasAttribute(i)){const t=e.cloneNode(!0);document.head.appendChild(t)}}})),await this.initReactiveOn(e.body),await this.populateDocumentBody(e)})(n),this.restoreScrollPositions(t),await this.rerunInlineScripts(),this.attachWireFunctionEvents(),this.handlerAutofocusAttribute()}async rerunInlineScripts(){const e=Array.from(document.querySelectorAll('script[type="text/javascript"]:not([src])')),t=new Map;e.forEach((e=>{const s=(e.textContent||"").trim();if(t.has(s))return void e.remove();t.set(s,e);const n=document.createElement("script");[...e.attributes].forEach((e=>n.setAttribute(e.name,e.value))),n.textContent=e.textContent,e.replaceWith(n)}))}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const s=this.getElementKey(t);e[s]&&(t.scrollTop=e[s].scrollTop,t.scrollLeft=e[s].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const s=e,n=t;return s.value!==n.value&&(n.value=s.value),n.checked=s.checked,document.activeElement!==s||(null!=s.selectionStart&&(n.selectionStart=s.selectionStart,n.selectionEnd=s.selectionEnd),!1)},TEXTAREA(e,t){const s=e,n=t;return s.value!==n.value&&(n.value=s.value),document.activeElement!==s||(n.selectionStart=s.selectionStart,n.selectionEnd=s.selectionEnd,!1)},SELECT(e,t){const s=e;return t.selectedIndex=s.selectedIndex,document.activeElement!==s},VIDEO(e,t){const s=e,n=t;return n.currentTime=s.currentTime,s.paused?n.pause():n.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,s=e.body;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const s=new Function("event",t);e.addEventListener("wheel",s,{passive:!0})}})),this._wheelHandlersStashed=!0);const n=this.PRESERVE_HANDLERS;morphdom(t,s,{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 s=e.tagName;if("SCRIPT"===s||e.hasAttribute("data-nomorph"))return!1;const r=n[s];return!r||r(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async 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,s=!1){let n;return s?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,n=this._activeAbortController):n=new AbortController,fetch(e,{...t,signal:n.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){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,s,n){setTimeout((()=>{requestAnimationFrame((()=>{e.style[s]=n}))}),t)}async fetchFunction(e,t={},s=!1){try{const n={callback:await this.encryptCallbackName(e),...t},r=window.location.href;let i;if(Object.keys(n).some((e=>{const t=n[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(n).forEach((t=>{const s=n[t];s instanceof File?e.append(t,s):s instanceof FileList?Array.from(s).forEach((s=>e.append(t,s))):e.append(t,s)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(n);const a=await this.fetch(r,i,s);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const o=await a.text();try{return JSON.parse(o)}catch{return o}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}processSyncScripts(e){e.forEach((e=>{const t=`script[pp-sync-script="${CSS.escape(e)}"]`,s=document.querySelector(t);if(s){s.remove();const e=document.createElement("script");Array.from(s.attributes).forEach((t=>{e.setAttribute(t.name,t.value)})),s.src?e.src=s.src:e.textContent=s.textContent,e.type=s.type||"module",document.body.appendChild(e)}}))}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const s=e.length>0?e.map((e=>`pp-sync="${e}"`)):['pp-sync="true"'],n=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()}),r=await this.fetch(window.location.href,n),i=await r.text(),a=(new DOMParser).parseFromString(i,"text/html"),o=new Set;s.forEach((e=>{const t=document.querySelectorAll(`[${e}]`),s=a.body.querySelectorAll(`[${e}]`);t.forEach(((e,t)=>{const n=s[t];if(n){if(n.hasAttribute("pp-sync-script")){const e=n.getAttribute("pp-sync-script")||"";e&&o.add(e)}n.querySelectorAll("[pp-sync-script]").forEach((e=>{const t=e.getAttribute("pp-sync-script")||"";t&&o.add(t)})),e.innerHTML=n.innerHTML,this.reRunScripts(e)}}))})),this.processSyncScripts(o),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("Error in pphpSync:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),s=await t.text();await this.updateBodyContent(s)}reRunScripts(e){e.querySelectorAll("script").forEach((e=>{const t=document.createElement("script");Array.from(e.attributes).forEach((e=>{t.setAttribute(e.name,e.value)})),e.hasAttribute("src")||(t.textContent=e.textContent),e.parentNode?.replaceChild(t,e)}))}copyCode(e,t,s,n,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const a=e.closest(`.${t}`)?.querySelector("pre code"),o=a?.textContent?.trim()||"";o?navigator.clipboard.writeText(o).then((()=>{const t=e.querySelector(r);if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s);setTimeout((()=>{if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;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.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){if(this.state={...this.state,...e},this.listeners.forEach((e=>e(this.state))),this.saveState(),t){const e=localStorage.getItem(this.STORAGE_KEY);e&&this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]: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})}}}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 s=this.params;s.set(e,t),this.updateURL(s)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const s in e){const n=e[s];null!==n&&t.set(s,n)}this.updateURL(t,!0)}updateURL(e,t=!1){const s=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",s):history.pushState(null,"",s),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();
|