create-caspian-app 1.8.0 → 1.8.2

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.
@@ -1,49 +1 @@
1
- var St=class{deferredEventDepth=0;callbacks=new Set;frameHandle=null;timerHandle=null;shouldDefer(){return this.deferredEventDepth>0}enqueue(e){this.callbacks.add(e),this.scheduleFlushOnNextFrame()}flush(){this.cancelScheduledFlush();let e=Array.from(this.callbacks);this.callbacks.clear(),e.forEach(t=>t())}runWithDeferral(e,t){e&&this.deferredEventDepth++;try{return t()}finally{e&&this.deferredEventDepth--}}scheduleFlushOnNextFrame(){if(this.frameHandle!==null||this.timerHandle!==null)return;let e=()=>{this.frameHandle=null,this.timerHandle=null,this.flush()};if(typeof requestAnimationFrame=="function"){this.frameHandle=requestAnimationFrame(e);return}this.timerHandle=setTimeout(e,0)}cancelScheduledFlush(){this.frameHandle!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.frameHandle),this.frameHandle=null,this.timerHandle!==null&&(clearTimeout(this.timerHandle),this.timerHandle=null)}},Se=new St;var J=[],ze=[],qe=class l{constructor(e,t="unknown",n=Se){this.stateUpdateScheduler=n;this.onStateChange=e,this.componentLabel=t}stateUpdateScheduler;static anonymousIdCounter=0;static MAX_BOUNDARY_CAPTURES=5;boundaryError=null;hasErrorBoundaryHook=!1;boundaryErrorCaptureCount=0;uncaughtErrorHandler=null;hooks=[];currentIndex=0;onStateChange;componentLabel;pendingLayoutEffects=J;pendingEffects=J;currentEffectPhase=null;pendingSynchronousRenderUpdate=!1;pendingSynchronousLayoutUpdate=!1;pendingUpdate=!1;hasScheduledRender=!1;portalRegistrations=[];isRenderWindowOpen=!1;warnedHookOutsideRender=!1;warnedHookAfterDispose=!1;currentHookTypes=ze;committedHookTypes=null;disposed=!1;loadState(e){this.hooks=[...e]}getHooks(){return this.hooks}prepareRender(){this.disposed||(this.currentIndex=0,this.isRenderWindowOpen=!0,this.warnedHookOutsideRender=!1,this.currentHookTypes=ze,this.pendingLayoutEffects=J,this.pendingEffects=J,this.currentEffectPhase=null,this.portalRegistrations=[])}startRenderPhase(){this.disposed||(this.currentEffectPhase="render")}finishRenderPhase(){this.currentEffectPhase==="render"&&(this.currentEffectPhase=null),this.isRenderWindowOpen=!1;let e=this.pendingSynchronousRenderUpdate;return this.pendingSynchronousRenderUpdate=!1,e?!0:(this.validateHookSignature(),!1)}recordHook(e){if(this.currentHookTypes===ze&&(this.currentHookTypes=[]),this.disposed)return this.warnedHookAfterDispose||(this.warnedHookAfterDispose=!0,this.emitDiagnostic(`[PP-WARN] ${e} hook for component "${this.componentLabel}" was called after the component was disposed. Hooks cannot be used after destroy.`)),this.currentIndex++;!this.isRenderWindowOpen&&!this.warnedHookOutsideRender&&(this.warnedHookOutsideRender=!0,this.emitDiagnostic(`[PP-WARN] ${e} hook for component "${this.componentLabel}" was called outside an active render. Hooks must be called while the component script is rendering.`));let t=this.currentIndex++;return this.currentHookTypes[t]=e,t}validateHookSignature(){if(this.committedHookTypes===null){this.committedHookTypes=this.currentHookTypes.length===0?ze:this.currentHookTypes.slice();return}let e=this.committedHookTypes,t=this.currentHookTypes;e.length===t.length&&e.every((r,i)=>r===t[i])||this.emitDiagnostic(`[PP-WARN] Hook order changed for component "${this.componentLabel}". Previous: [${e.join(", ")}]. Current: [${t.join(", ")}]. Hooks must be called in the same order on every render.`)}runLayoutEffects(){if(this.disposed)return this.pendingLayoutEffects=J,!1;let e=this.pendingLayoutEffects;this.pendingLayoutEffects=J,this.currentEffectPhase="layout";try{e.forEach(n=>{this.runEffectCleanup(n.previousCleanup,"layout cleanup")}),e.forEach(n=>{let r=this.runEffectCallback(n.callback,"layout effect");this.hooks[n.hookIndex]={deps:n.deps,cleanup:typeof r=="function"?r:void 0,effectType:"layout"}})}finally{this.currentEffectPhase=null}let t=this.pendingSynchronousLayoutUpdate;return this.pendingSynchronousLayoutUpdate=!1,t}hasPendingEffects(){return this.pendingEffects.length>0}runEffects(){if(this.disposed){this.pendingEffects=J;return}let e=this.pendingEffects;this.pendingEffects=J,this.currentEffectPhase="effect";try{e.forEach(t=>{this.runEffectCleanup(t.previousCleanup,"effect cleanup")}),e.forEach(t=>{let n=this.runEffectCallback(t.callback,"effect");this.hooks[t.hookIndex]={deps:t.deps,cleanup:typeof n=="function"?n:void 0,effectType:"effect"}})}finally{this.currentEffectPhase=null}}runEffectCleanup(e,t){if(e)try{e()}catch(n){if(this.reportUncaughtError(n))return;console.error(`[PP-ERROR] ${t} failed for component "${this.componentLabel}"`,n)}}runEffectCallback(e,t){try{let n=e();if(n&&typeof n=="object"&&"then"in n&&typeof n.then=="function"){console.warn(`[PP-WARN] ${t} for component "${this.componentLabel}" returned a Promise. Effects must return only a cleanup function; run async work inside the effect instead.`);return}return n}catch(n){if(this.reportUncaughtError(n))return;console.error(`[PP-ERROR] ${t} failed for component "${this.componentLabel}"`,n);return}}dispose(){if(this.disposed)return;if(this.disposed=!0,this.pendingLayoutEffects=J,this.pendingEffects=J,this.pendingUpdate=!1,this.hasScheduledRender=!1,this.portalRegistrations=[],this.boundaryError=null,this.uncaughtErrorHandler=null,this.hooks.length===0){this.currentIndex=0;return}let e=t=>{let n=t.cleanup;if(typeof n=="function")try{n()}finally{t.cleanup=void 0}};this.hooks.forEach(t=>{!t||typeof t!="object"||t.effectType==="layout"&&e(t)}),this.hooks.forEach(t=>{!t||typeof t!="object"||t.effectType==="effect"&&e(t)}),this.hooks.forEach(t=>{!t||typeof t!="object"||t.effectType||e(t)}),this.hooks=[],this.currentIndex=0}usePortal(e,t){let n=this.recordHook("portal");this.hooks[n]===void 0&&(this.hooks[n]={sourceParent:null});let r=this.hooks[n];return this.portalRegistrations.push({ref:e,target:t??null,info:r}),r}getPortalRegistrations(){return this.portalRegistrations}useState(e){let t=this.recordHook("state");this.hooks[t]===void 0&&(this.hooks[t]={__state:this.resolveInitialState(e),__setter:this.createStateSetter(t)});let n=this.hooks[t];(typeof n!="object"||n===null||!("__state"in n))&&(this.hooks[t]={__state:n,__setter:this.createStateSetter(t)});let r=this.hooks[t];return[r.__state,r.__setter]}resolveInitialState(e){return typeof e=="function"?e():e}createStateSetter(e){return t=>{let n=this.hooks[e];if(this.disposed||n===void 0)return;let r=typeof t=="function"?t(n.__state):t;Object.is(n.__state,r)||(n.__state=r,this.scheduleUpdate())}}scheduleUpdate(){if(!this.disposed){if(this.currentEffectPhase==="render"){this.pendingSynchronousRenderUpdate=!0;return}if(this.currentEffectPhase==="layout"){this.pendingSynchronousLayoutUpdate=!0;return}this.hasScheduledRender=!0,this.pendingUpdate||(this.pendingUpdate=!0,(this.stateUpdateScheduler.shouldDefer()?t=>this.stateUpdateScheduler.enqueue(t):queueMicrotask)(()=>{if(this.pendingUpdate=!1,this.disposed){this.hasScheduledRender=!1;return}this.hasScheduledRender&&(this.hasScheduledRender=!1,this.onStateChange())}))}}useRef(e=null){let t=this.recordHook("ref");return this.hooks[t]===void 0&&(this.hooks[t]={current:e}),this.hooks[t]}useMemo(e,t){let n=this.recordHook("memo"),r=this.hooks[n],i=this.normalizeDeps("memo",t);if(!r||!i||!r.deps||this.areDepsDifferent(r.deps,i)){let s=e();return this.hooks[n]={value:s,deps:i},s}return r.value}useCallback(e,t){let n=this.recordHook("callback"),r=this.hooks[n],i=this.normalizeDeps("callback",t);return!r||!i||!r.deps||this.areDepsDifferent(r.deps,i)?(this.hooks[n]={callback:e,deps:i},e):r.callback}useReducer(e,t,n){let r=this.recordHook("reducer");if(this.hooks[r]===void 0){let o={state:n?n(t):t,reducer:e,dispatch:null};o.dispatch=s=>{if(this.disposed)return;let a=o.reducer(o.state,s);Object.is(o.state,a)||(o.state=a,this.scheduleUpdate())},this.hooks[r]=o}let i=this.hooks[r];return i.reducer=e,[i.state,i.dispatch]}useEffect(e,t){let n=this.recordHook("effect"),r=this.hooks[n],i=this.normalizeDeps("effect",t);(!r||!i||!r.deps||this.areDepsDifferent(r.deps,i))&&(this.pendingEffects===J&&(this.pendingEffects=[]),this.pendingEffects.push({hookIndex:n,deps:i,callback:e,previousCleanup:typeof r?.cleanup=="function"?r.cleanup:void 0}))}useLayoutEffect(e,t){let n=this.recordHook("layoutEffect"),r=this.hooks[n],i=this.normalizeDeps("layoutEffect",t);(!r||!i||!r.deps||this.areDepsDifferent(r.deps,i))&&(this.pendingLayoutEffects===J&&(this.pendingLayoutEffects=[]),this.pendingLayoutEffects.push({hookIndex:n,deps:i,callback:e,previousCleanup:typeof r?.cleanup=="function"?r.cleanup:void 0}))}useErrorBoundary(){let e=this.recordHook("errorBoundary");return this.hasErrorBoundaryHook=!0,this.hooks[e]===void 0&&(this.hooks[e]={reset:()=>{this.disposed||(this.boundaryErrorCaptureCount=0,this.boundaryError!==null&&(this.boundaryError=null,this.scheduleUpdate()))}}),[this.boundaryError,this.hooks[e].reset]}captureError(e){return this.disposed||!this.hasErrorBoundaryHook?!1:this.boundaryErrorCaptureCount>=l.MAX_BOUNDARY_CAPTURES?(console.error(`[PP-ERROR] Error boundary for component "${this.componentLabel}" absorbed ${l.MAX_BOUNDARY_CAPTURES} errors without being reset and has stopped catching to avoid an infinite render loop. Call reset() to re-arm it.`,e),!1):(this.boundaryErrorCaptureCount++,this.boundaryError=e,this.scheduleUpdate(),!0)}setUncaughtErrorHandler(e){this.uncaughtErrorHandler=e}reportUncaughtError(e){if(!this.uncaughtErrorHandler)return!1;try{return this.uncaughtErrorHandler(e)}catch(t){return console.error(`[PP-ERROR] Error boundary handler for component "${this.componentLabel}" threw.`,t),!1}}useId(){let e=this.recordHook("id");return this.hooks[e]===void 0&&(this.hooks[e]=this.createStableId(e)),this.hooks[e]}createStableId(e){let t=this.componentLabel.replace(/[^a-zA-Z0-9_-]/g,"-");return t.length>0&&this.componentLabel!=="unknown"?`pp-${t}-${e}`:`pp-${l.anonymousIdCounter++}-${e}`}useSyncExternalStore(e,t){let[,n]=this.useState(0),r=this.useRef(null),i=this.useRef(null),o=t();return r.current={value:o},i.current=t,this.useEffect(()=>{let s=()=>{let c=i.current,u=r.current;if(!c||!u)return;let h=c();Object.is(u.value,h)||(r.current={value:h},n(d=>d+1))},a=e(s);return s(),typeof a=="function"?a:void 0},[e]),o}useImperativeHandle(e,t,n){this.useLayoutEffect(()=>{if(!e)return;let r=t();if(typeof e=="function"){let i=e(r);return()=>{if(typeof i=="function"){i();return}e(null)}}return e.current=r,()=>{e.current=null}},n===void 0?void 0:[e,...n])}useTransition(){let[e,t]=this.useState(0),n=this.useCallback(r=>{t(s=>s+1);let i=()=>t(s=>s-1),o;try{o=r()}catch(s){throw i(),s}if(o&&typeof o=="object"&&typeof o.then=="function"){o.then(i,i);return}i()},[]);return[e>0,n]}useDeferredValue(e,t){let[n,r]=this.useState(t!==void 0?t:e);return this.useEffect(()=>{r(e)},[e]),n}useOptimistic(e,t){let[n,r]=this.useState([]),i=this.useRef(null);i.current===null&&(i.current={value:e});let o=n;Object.is(i.current.value,e)||(i.current={value:e},n.length>0&&(o=[],r([])));let s=t??((u,h)=>h),a=o.reduce((u,h)=>s(u,h),e),c=this.useCallback(u=>{r(h=>[...h,u])},[]);return[a,c]}normalizeDeps(e,t){if(t!==void 0){if(Array.isArray(t))return t;this.emitDiagnostic(`[PP-WARN] ${e} dependencies for component "${this.componentLabel}" must be an array or omitted. Received ${this.describeDeps(t)}.`)}}describeDeps(e){return e===null?"null":typeof e=="object"?e.constructor?.name??"object":typeof e}emitDiagnostic(e){console.warn(e)}areDepsDifferent(e,t){return e.length!==t.length?!0:t.some((n,r)=>!Object.is(n,e[r]))}};var j="pp-component",G=Symbol("pp.boundaryDirectProps"),ee=Symbol("pp.boundaryChildDerivation"),Te="[pp-component]";function V(l){return(l instanceof HTMLElement||l instanceof SVGElement)&&l.hasAttribute(j)}function K(l){return l.getAttribute(j)}function Ce(l,e){l.setAttribute(j,e)}function he(l){return l.closest(Te)}function Qt(l){let e=he(l);return e===l&&(e=l.parentElement?he(l.parentElement):null),e}function en(l){return Array.from(l.querySelectorAll(Te)).filter(e=>!(e.parentElement&&he(e.parentElement)))}var tn="pp:",Hn="/pp",Tt="pp-fragment";function nn(l){return l.nodeType===Node.COMMENT_NODE&&l.data.startsWith(tn)}function Nn(l){return l.nodeType===Node.COMMENT_NODE&&l.data.trim()===Hn}var Dn=new Set(["TABLE","THEAD","TBODY","TFOOT","TR","SELECT","OPTGROUP"]);function On(l){let e=0;for(let t=l.nextSibling;t;t=t.nextSibling)if(nn(t))e++;else if(Nn(t)){if(e===0)return t;e--}return null}function rn(l){let e=new Set;for(;;){let t=document.createTreeWalker(l,NodeFilter.SHOW_COMMENT),n=null,r=null;for(let a=t.nextNode();a;a=t.nextNode()){if(!nn(a)||e.has(a))continue;let c=a.parentElement;if(c&&Dn.has(c.tagName)){e.add(a);continue}let u=On(a);if(!u){e.add(a);continue}n=a,r=u;break}if(!n||!r)return;let i=document.createElement(Tt);i.style.display="contents";let o=n.data.slice(tn.length).trim();o&&i.setAttribute(j,o),n.parentNode?.insertBefore(i,n);let s=n.nextSibling;for(;s&&s!==r;){let a=s.nextSibling;i.appendChild(s),s=a}n.remove(),r.remove()}}var je=class{constructor(e){this.host=e}host;getId(){return K(this.host)}setId(e){Ce(this.host,e)}readContent(){return this.host.innerHTML}parentBoundaryElement(){return this.host.parentElement?he(this.host.parentElement):null}};var b=class{static states=new Map;static scopes=new Map;static scopeVersions=new Map;static scopeVersionCounter=0;static topologyVersion=0;static topologyBatchDepth=0;static topologyBatchDirty=!1;static mergedScopeCache=new WeakMap;static instances=new Map;static parents=new Map;static childrenByParent=new Map;static ownedTemplateData=new Map;static contextValues=new Map;static consumerContexts=new Map;static contextConsumers=new Map;static bumpTopologyVersion(){this.topologyBatchDepth>0?this.topologyBatchDirty=!0:this.topologyVersion++}static beginTopologyBatch(){this.topologyBatchDepth++}static endTopologyBatch(){this.topologyBatchDepth>0&&this.topologyBatchDepth--,this.topologyBatchDepth===0&&this.topologyBatchDirty&&(this.topologyBatchDirty=!1,this.topologyVersion++)}static saveState(e,t){e&&this.states.set(e,t)}static getState(e){return this.states.get(e)}static removeState(e){this.states.delete(e)}static saveScope(e,t){this.scopes.set(e,t),this.scopeVersions.set(e,++this.scopeVersionCounter)}static getScope(e){return this.scopes.get(e)}static resolveComponentId(e,t=null){if(!e)return null;if(e!=="app"){if(t){let s=new Set,a=t;for(;a&&!s.has(a);){s.add(a);let c=this.instances.get(a);if((c?.el?.__ppBaseComponentId??(c?.el?K(c.el):null)??null)===e)return a;a=this.parents.get(a)??null}}return e}let n=new Set,r=t,i=null;for(;r&&!n.has(r);){if(n.add(r),r.startsWith("page_"))return r;let s=this.parents.get(r)??null;if(!s){i=r;break}r=s}if(i)return i;for(let[s,a]of this.parents.entries())if(a===null&&this.scopes.has(s))return s;let o=this.scopes.keys().next().value;return typeof o=="string"?o:null}static getLiveResolvedScopeWithAncestors(e,t=null){let n=this.resolveComponentId(e,t);if(!n)return;let r=new Set,i=[],o=n;for(;o&&!r.has(o);){r.add(o);let s=this.scopes.get(o);s&&i.push(s),o=this.parents.get(o)??null}if(i.length!==0)return Object.assign({},...i.reverse())}static getResolvedScopeWithAncestors(e,t=null){let n=this.resolveComponentId(e,t);if(!n)return;let r=this.scopes.get(n);if(r){let u=this.mergedScopeCache.get(r);if(u&&u.topology===this.topologyVersion){let h=!0;for(let d=0;d<u.chainIds.length;d++)if((this.scopeVersions.get(u.chainIds[d])??0)!==u.versions[d]){h=!1;break}if(h)return u.merged}}let i=new Set,o=[],s=[],a=n;for(;a&&!i.has(a);){i.add(a),o.push(a);let u=this.scopes.get(a);u&&s.push(u),a=this.parents.get(a)??null}if(s.length===0)return;let c=Object.assign({},...s.reverse());return r&&this.mergedScopeCache.set(r,{topology:this.topologyVersion,chainIds:o,versions:o.map(u=>this.scopeVersions.get(u)??0),merged:c}),c}static removeScope(e){this.scopes.delete(e),this.scopeVersions.set(e,++this.scopeVersionCounter)}static registerInstance(e,t){let n=this.instances.get(e);n&&n!==t&&n.destroy?.(),this.instances.set(e,t)}static getInstance(e){return this.instances.get(e)}static removeInstance(e){this.instances.delete(e)}static saveParent(e,t){if(!e)return;let n=this.parents.has(e),r=this.parents.get(e);if(n&&r===t)return;if(n){let o=this.childrenByParent.get(r??null);o?.delete(e),o?.size===0&&this.childrenByParent.delete(r??null),this.bumpTopologyVersion()}this.parents.set(e,t);let i=this.childrenByParent.get(t)??new Set;i.add(e),this.childrenByParent.set(t,i)}static getParent(e){return this.parents.get(e)}static removeParent(e){if(!this.parents.has(e))return;let t=this.parents.get(e)??null,n=this.childrenByParent.get(e);n?.size&&Array.from(n).forEach(o=>this.saveParent(o,t));let r=this.childrenByParent.get(t);r?.delete(e),r?.size===0&&this.childrenByParent.delete(t),this.childrenByParent.delete(e),this.parents.delete(e),this.bumpTopologyVersion()}static hasChildren(e){return(this.childrenByParent.get(e)?.size??0)>0}static forEachDescendant(e,t){if(!this.childrenByParent.get(e)?.size)return;let n=new Set,r=i=>{let o=this.childrenByParent.get(i);o&&Array.from(o).forEach(s=>{s!==e&&(n.has(s)||(n.add(s),r(s),t(s)))})};r(e)}static saveContextValues(e,t){let n=this.contextValues.get(e)??new Map,r=new Set;return n.forEach((i,o)=>{t.has(o)||r.add(o)}),t.forEach((i,o)=>{if(!n.has(o)){r.add(o);return}Object.is(n.get(o),i)||r.add(o)}),t.size>0?this.contextValues.set(e,new Map(t)):this.contextValues.delete(e),Array.from(r)}static resolveContext(e,t){let n=e;for(;n;){let r=this.contextValues.get(n);if(r?.has(t))return{providerId:n,value:r.get(t)};n=this.parents.get(n)??null}return{providerId:null,value:t.defaultValue}}static updateContextDependencies(e,t){let n=new Set(t),r=this.consumerContexts.get(e)??new Set;r.forEach(i=>{n.has(i)||this.removeContextConsumer(i,e)}),n.forEach(i=>{r.has(i)||this.addContextConsumer(i,e)}),n.size>0?this.consumerContexts.set(e,n):this.consumerContexts.delete(e)}static getConsumersForContextsInSubtree(e,t){let n=new Set;for(let r of t){let i=this.contextConsumers.get(r);i&&i.forEach(o=>{o!==e&&this.isAncestor(e,o)&&n.add(o)})}return n}static removeContextTracking(e){let t=this.contextValues.get(e),n=t?this.getConsumersForContextsInSubtree(e,t.keys()):null;this.contextValues.delete(e);let r=this.consumerContexts.get(e);return r&&(r.forEach(i=>{this.removeContextConsumer(i,e)}),this.consumerContexts.delete(e)),this.removeParent(e),n}static saveOwnedTemplates(e,t){this.ownedTemplateData.has(e)||this.ownedTemplateData.set(e,t)}static getOwnedTemplates(e){return this.ownedTemplateData.get(e)}static removeOwnedTemplates(e){this.ownedTemplateData.delete(e)}static clear(){this.topologyBatchDepth=0,this.topologyBatchDirty&&(this.topologyBatchDirty=!1,this.topologyVersion++),this.states.clear(),this.scopes.clear(),this.instances.clear(),this.parents.clear(),this.childrenByParent.clear(),this.ownedTemplateData.clear(),this.contextValues.clear(),this.consumerContexts.clear(),this.contextConsumers.clear()}static destroyAll(){let e=Array.from(this.instances.values()),t=new Set;this.beginTopologyBatch();try{for(let n of e)if(!(!n||t.has(n))){t.add(n);try{n.destroy?.()}catch(r){console.warn("[PP-WARN] Failed to destroy component instance",r)}}}finally{this.endTopologyBatch()}}static addContextConsumer(e,t){let n=this.contextConsumers.get(e)??new Set;n.add(t),this.contextConsumers.set(e,n)}static removeContextConsumer(e,t){let n=this.contextConsumers.get(e);n&&(n.delete(t),n.size===0&&this.contextConsumers.delete(e))}static isAncestor(e,t){let n=this.parents.get(t)??null;for(;n;){if(n===e)return!0;n=this.parents.get(n)??null}return!1}};function re(l,e,t,n){!l.has(e)&&l.size>=n&&on(l,1),l.set(e,t)}function Xe(l,e,t=Math.floor(e/2)){l.size<=e||on(l,l.size-t)}function on(l,e){let t=l.keys();for(let n=0;n<e;n++){let r=t.next();if(r.done)return;l.delete(r.value)}}var Vn=new Set(["date","datetime-local","month","time","week"]),Fn=new Set(["text","search","url","tel","password"]),$n=new Set(["email","number","password","search","tel","text","url"]);function ge(l){return Vn.has(l.type)}function Le(l){return l instanceof HTMLTextAreaElement?!0:l instanceof HTMLInputElement&&Fn.has(l.type)}function sn(l){return l instanceof HTMLTextAreaElement?!0:l instanceof HTMLInputElement&&$n.has(l.type)}function Ie(l,e){an(l,l,"__ppValueControlMode","__ppWarnedValueControlModeSwitch",e,"Choose either a controlled value binding or an uncontrolled defaultValue for the lifetime of the element.")}function Ge(l,e){an(l,l,"__ppCheckedControlMode","__ppWarnedCheckedControlModeSwitch",e,"Choose either a controlled checked binding or an uncontrolled defaultChecked for the lifetime of the element.")}function Ye(l,e){Ge(l,"controlled"),l.checked!==e&&(l.checked=e)}function an(l,e,t,n,r,i){let o=e[t];if(!o){e[t]=r;return}o!==r&&(e[n]||(e[n]=!0,console.warn(`[PP-WARN] ${Un(l)} changed from ${o} to ${r}. ${i}`)),e[t]=r)}function Un(l){let e=l.tagName.toLowerCase(),t=l.id?`#${l.id}`:"",n=l.getAttribute("name"),r=!t&&n?`[name="${n}"]`:"";return`${e}${t}${r}`}var ae=new Set(["class","for","while","if","else","return","function","var","let","const","import","export","this","debugger","delete","typeof","void","new","in","instanceof","do","try","catch","finally","switch","case","default","break","continue","yield","await","with","super","enum","extends","implements","interface","package","private","protected","public","static"]);var ie="pp-literal-",ye=new Set(["hidden","disabled","checked","selected","readonly","required","open","autofocus","multiple","ismap","noValidate","defer","async","autoplay","controls","loop","muted","default","reversed","scoped","seamless","sortable","translate","draggable","contenteditable","spellcheck"]);function Be(l){return l.includes("-")?l.replace(/-([a-z])/g,e=>e[1].toUpperCase()):l}function W(l,e){if(l.length<2)return!1;let t=l.charCodeAt(0);if(t!==111&&t!==79)return!1;let n=l.charCodeAt(1);if(n!==110&&n!==78)return!1;let r=l.toLowerCase();return!r.includes("-")&&r in e}var ln=new WeakMap,Kn=/^[A-Za-z_$][\w$]*$/;function Wn(l){return Kn.test(l)&&!ae.has(l)}function _e(l){let e=ln.get(l);if(e)return e;let t=Object.keys(l).filter(Wn),n={keys:t,keySig:t.join("\0")};return ln.set(l,n),n}function He(l){let e=_e(l);return{scope:l,keys:e.keys,keySig:e.keySig,values:Pe(l,e.keys)}}function Pe(l,e){let t=new Array(e.length);for(let n=0;n<e.length;n++)t[n]=l[e[n]];return t}var Ct=new Map,zn=500,Pt=null,Je=null;function qn(l){Je||(Je=document.createElement("template")),Je.innerHTML=l;let e=Array.from(Je.content.childNodes).filter(n=>n.nodeType===Node.TEXT_NODE?(n.textContent??"").trim().length>0:n.nodeType===Node.ELEMENT_NODE);if(e.length!==1)return null;let t=e[0];return!(t instanceof HTMLTemplateElement)||!t.hasAttribute("pp-owner")?null:t.innerHTML}function jn(l){let t=A(l),n=!1;for(;;){let r=qn(t);if(r===null)break;t=r,n=!0}return n?t:null}function wt(l){if(!l.includes("<textarea"))return l;let e=l.includes("pp-owner"),t=document.createElement("template");t.innerHTML=l;let n=!1;return t.content.querySelectorAll("textarea").forEach(r=>{let i=r;if(e){let o=jn(i.value);if(o!==null){i.textContent=o,n=!0;return}}i.value.length>0&&i.value.trim().length===0&&(i.textContent="",n=!0)}),n?t.innerHTML:l}function A(l){if(!l.includes("&"))return l;if(Ct.has(l))return Ct.get(l);Pt||(Pt=document.createElement("textarea"));let e=Pt;e.innerHTML=l;let t=e.value,n=0;for(;t.includes("&")&&n++<10;){e.innerHTML=t;let r=e.value;if(r===t)break;t=r}return re(Ct,l,t,zn),t}var Xn=/&(?:amp;)?(?:lbrace|rbrace|#123|#125|#x7b|#x7d);/i;function Rt(l){return l.includes("&")&&Xn.test(l)}var $="data-pp-fragment-root";function Gn(l,e){let t=0,n=e-1;for(;n>=0&&l[n]==="\\";)t++,n--;return t%2!==0}function we(l,e){if(l[e]!=="{")return-1;let t=0,n=null;for(let r=e;r<l.length;r++){let i=l[r],o=Gn(l,r);if(n){i===n&&!o&&(n=null);continue}if(!o&&(i==='"'||i==="'"||i==="`")){n=i;continue}if(i==="{"&&!o)t++;else if(i==="}"&&!o&&(t--,t===0))return r}return-1}function Ne(l,e){return l.startsWith("{{",e)||l.startsWith("{%",e)||l.startsWith("{#",e)}function kt(l,e){let t=l.startsWith("{{",e)?"}}":l.startsWith("{%",e)?"%}":l.startsWith("{#",e)?"#}":"";if(!t)return-1;let n=l.indexOf(t,e+2);return n===-1?-1:n+t.length}function z(l){let e=0;for(;e<l.length&&/\s/.test(l[e]);)e++;if(l[e]!=="{"||Ne(l,e))return null;let t=we(l,e);if(t===-1)return null;let n=t+1;for(;n<l.length&&/\s/.test(l[n]);)n++;return n!==l.length?null:{expression:l.slice(e+1,t).trim(),start:e,end:t}}function cn(l,e){let t="",n=0;for(;n<l.length;){if(l[n]!=="{"){t+=l[n],n++;continue}if(Ne(l,n)){let o=kt(l,n);if(o===-1){t+=l.slice(n);break}t+=l.slice(n,o),n=o;continue}let r=we(l,n);if(r===-1){t+=l.slice(n);break}let i=l.slice(n+1,r);t+=e(i.trim(),i),n=r+1}return t}function un(l){let e=String(l??"").trim().toLowerCase();switch(e){case"table":return{prefix:`<table ${$}="">`,suffix:"</table>",rootSelector:`table[${$}]`};case"caption":return{prefix:`<table><caption ${$}="">`,suffix:"</caption></table>",rootSelector:`caption[${$}]`};case"thead":case"tbody":case"tfoot":return{prefix:`<table><${e} ${$}="">`,suffix:`</${e}></table>`,rootSelector:`${e}[${$}]`};case"tr":return{prefix:`<table><tbody><tr ${$}="">`,suffix:"</tr></tbody></table>",rootSelector:`tr[${$}]`};case"td":case"th":return{prefix:`<table><tbody><tr><${e} ${$}="">`,suffix:`</${e}></tr></tbody></table>`,rootSelector:`${e}[${$}]`};case"colgroup":return{prefix:`<table><colgroup ${$}="">`,suffix:"</colgroup></table>",rootSelector:`colgroup[${$}]`};case"select":return{prefix:`<select ${$}="">`,suffix:"</select>",rootSelector:`select[${$}]`};case"optgroup":return{prefix:`<select><optgroup ${$}="">`,suffix:"</optgroup></select>",rootSelector:`optgroup[${$}]`};case"option":return{prefix:`<select><option ${$}="">`,suffix:"</option></select>",rootSelector:`option[${$}]`};default:return{prefix:"",suffix:"",rootSelector:null}}}function pn(l){let e=un(l);return{wrap:t=>`${e.prefix}${t}${e.suffix}`,unwrap:t=>{if(!e.prefix&&!e.suffix)return t;let n=t.indexOf($);if(n!==-1&&n<=e.prefix.length+32&&t.endsWith(e.suffix)){let o=t.indexOf(">",n);if(o!==-1){let s=t.length-e.suffix.length;if(o+1<=s)return t.slice(o+1,s)}}let i=document.createElement("template");if(i.innerHTML=t,e.rootSelector){let o=i.content.querySelector(e.rootSelector);if(o)return o.innerHTML}return t}}}function le(l,e){let t=un(e),n=document.createElement("template");if(n.innerHTML=wt(`${t.prefix}${l}${t.suffix}`),!t.rootSelector)return{root:n.content,toHtml:()=>n.innerHTML};let r=n.content.querySelector(t.rootSelector);return r?(r.removeAttribute($),{root:r,toHtml:()=>r.innerHTML}):{root:n.content,toHtml:()=>n.innerHTML}}function xt(l,e){if(l===e)return!0;if(!l||!e||typeof l!="object"||typeof e!="object")return!1;let t=Object.keys(l),n=t.length,r=0;for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&(r++,r>n))return!1;if(r!==n)return!1;for(let i=0;i<n;i++){let o=t[i];if(l[o]!==e[o])return!1}return!0}var Ee=class l{static MAX_HANDLER_CACHE_SIZE=4096;root;getScope;canBindElement;handlerCache=new Map;cachedRootElementCount=null;static LARGE_INPUT_RENDER_DEFER_THRESHOLD=100;constructor(e,t,n){this.root=e,this.getScope=t,this.canBindElement=n}clearCache(){this.handlerCache.clear()}static hasSameDirectBoundHandler(e,t,n,r){if(!W(t,e))return!1;let i=t.slice(2).toLowerCase();return i==="input"&&e instanceof HTMLInputElement&&ge(e)?!1:e[`__pp_bound_${i}`]===l.normalizeHandlerCode(n)&&e[`__pp_event_owner_${i}`]===(r??"")}static normalizeHandlerCode(e){let t=e.trim(),n=t.match(/^\{([\s\S]*)\}$/);return n?n[1].trim():t}static prepareHandler(e){let t=[],n=e.replace(/__pp_loop_read\((['"])(ppv_\d+(?:_\d+)?)\1\)/g,(r,i,o)=>`__pp_loop_read(__PP_EVENT_CAPTURES__[${t.push(o)-1}])`);return{sourceCode:e,compiledCode:n,loopCaptureIds:t}}invalidateElementCountCache(){this.cachedRootElementCount=null}resolveEventOwnerScope(e){let t=K(this.root);return b.getLiveResolvedScopeWithAncestors(e,t)}bindEvents(e){e.forEach(t=>{this.canBindElement(t)&&this.bindElementEvents(t)})}bindElementEvents(e){let t=e.getAttribute("pp-event-owner");t&&e.removeAttribute("pp-event-owner");let n=[];Array.from(e.attributes).forEach(r=>{if(W(r.name,e)){let i=r.name.slice(2).toLowerCase(),o=r.value,s=l.normalizeHandlerCode(o),a=l.prepareHandler(s);n.push(r.name),this.getNativeEventNames(e,i).forEach(u=>{let h=`__pp_bound_${u}`,d=`__pp_event_owner_${u}`;if((e.__ppBoundEventBindings??(e.__ppBoundEventBindings=new Map)).set(u,r.name),e[h]===s&&e[d]===(t??""))return;e[h]=s,e[d]=t??"";let f=e[`__pp_handler_${u}`];f&&e.removeEventListener(u,f);let y=m=>{let g=this.shouldPreserveNativeEdit(e,u),E=g&&this.shouldDeferNativeInputRender(),_=e;if(g&&(_.__ppPreserveNativeSelectionOnNextRender=!0),this.runWithNativeInputRenderPolicy(E,()=>{if(t){let C=this.resolveEventOwnerScope(t);if(C){this.executeHandlerWithScope(a,m,C,e);return}}let v=he(e),S=v===e?Qt(e):v,T=S&&K(S)||null;if(T){let C=this.resolveEventOwnerScope(T);if(C){this.executeHandlerWithScope(a,m,C,e);return}}this.executeHandler(a,m,e)}),g){let v=()=>{_.__ppPreserveNativeSelectionOnNextRender&&delete _.__ppPreserveNativeSelectionOnNextRender};E?(Se.enqueue(v),this.ensureDeferredNativeInputBlurFlush(e)):queueMicrotask(v)}};e[`__pp_handler_${u}`]=y,e.addEventListener(u,y)})}}),n.forEach(r=>{e.removeAttribute(r)})}static unbindRemovedEventHandlers(e,t){let n=e.__ppBoundEventBindings;if(!(!n||n.size===0)){for(let[r,i]of Array.from(n)){if(t.hasAttribute(i))continue;let o=`__pp_handler_${r}`,s=e[o];s&&(e.removeEventListener(r,s),delete e[o]),delete e[`__pp_bound_${r}`],delete e[`__pp_event_owner_${r}`],n.delete(r)}n.size===0&&delete e.__ppBoundEventBindings}}getNativeEventNames(e,t){return t==="input"&&e instanceof HTMLInputElement&&ge(e)?["change","blur"]:[t]}runWithNativeInputRenderPolicy(e,t){Se.runWithDeferral(e,t)}shouldDeferNativeInputRender(){return this.cachedRootElementCount===null&&(this.cachedRootElementCount=this.root.getElementsByTagName("*").length+1),this.cachedRootElementCount>=l.LARGE_INPUT_RENDER_DEFER_THRESHOLD}ensureDeferredNativeInputBlurFlush(e){let t=e;if(t.__ppDeferredNativeInputBlurFlush)return;let n=()=>{delete t.__ppDeferredNativeInputBlurFlush,Se.flush()};t.__ppDeferredNativeInputBlurFlush=n,e.addEventListener("blur",n,{once:!0})}shouldPreserveNativeEdit(e,t){return t!=="input"?!1:sn(e)}executeHandler(e,t,n){let r=K(this.root),i=this.resolveEventOwnerScope(r)||this.getScope();this.executeHandlerWithScope(e,t,i,n)}executeHandlerWithScope(e,t,n,r){let i=_e(n),o=i.keys,s=Pe(n,o);try{let c=this.getCompiledHandler(e.compiledCode,o,i.keySig).call(r??t.currentTarget??null,...s,e.loopCaptureIds,t);typeof c=="function"&&c(t)}catch(a){console.error("[PP-ERROR] Handler failed:",a),console.error("Code:",e.sourceCode)}}getCompiledHandler(e,t,n){let r=e+"|"+n,i=this.handlerCache.get(r);if(!i){let o=[["e","event"],["$event","event"],["target","event?.target"],["currentTarget","event?.currentTarget"],["el","event?.currentTarget"]],s=new Set(t),a="__pp_event_captures";for(;s.has(a);)a+="_";let c=e.replaceAll("__PP_EVENT_CAPTURES__",a),u=o.filter(([d])=>!s.has(d)).map(([d,p])=>`const ${d} = ${p};`).join(`
2
- `),h;try{h=new Function(...t,a,"event",`"use strict";${u} return (${c})`)}catch{h=new Function(...t,a,"event",`"use strict";${u} ${c}`)}return re(this.handlerCache,r,h,l.MAX_HANDLER_CACHE_SIZE),h}return i}};var Yn=/[A-Za-z_$]/,dn=/[A-Za-z0-9_$]/;function Jn(l,e){return l===null?!0:l.kind==="l"?!1:l.kind==="i"?Zn.has(l.value):l.value===")"||l.value==="]"?!1:l.value==="}"?!e:!0}var Zn=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function Qn(l){if(l===null||l.kind==="l")return!1;if(l.kind==="i")return er.has(l.value);let e=l.value;return!(e===")"||e==="]"||e==="}"||e==="=>")}var er=new Set(["return","typeof","in","of","case","do","yield","await","throw","new","delete","void"]);function hn(l){let e=[],t=new Set,n=[],r=[],i=0,o=0,s=l.length,a=null,c=!1,u=(p,f,y)=>{let m={kind:p,value:l.slice(f,y),start:f,end:y,depth:i};return e.push(m),a=m,m},h=p=>{for(o++;o<s;){let f=l[o];if(f==="\\"){o+=2;continue}if(f===p){o++;return}o++}},d=()=>{for(;o<s;){let p=l[o];if(p==="\\"){o+=2;continue}if(p==="`")return o++,"end";if(p==="$"&&l[o+1]==="{")return o+=2,"interp";o++}return"end"};for(;o<s;){let p=l[o];if(p===" "||p===" "||p===`
3
- `||p==="\r"||p==="\f"||p==="\v"){o++;continue}if(p==="/"&&l[o+1]==="/"){let E=l.indexOf(`
4
- `,o);o=E===-1?s:E+1;continue}if(p==="/"&&l[o+1]==="*"){let E=l.indexOf("*/",o+2);o=E===-1?s:E+2;continue}if(p==='"'||p==="'"){let E=o;h(p),u("l",E,o),c=!1;continue}if(p==="`"){let E=o;o++;let _=d();u("l",E,o),c=!1,_==="interp"&&(r.push(i),i++);continue}if(Yn.test(p)){let E=o;for(o++;o<s&&dn.test(l[o]);)o++;u("i",E,o),c=!1;continue}if(p>="0"&&p<="9"||p==="."&&l[o+1]>="0"&&l[o+1]<="9"){let E=o;for(o++;o<s&&/[0-9a-fA-FoOxXbB._ne+-]/.test(l[o])&&!((l[o]==="+"||l[o]==="-")&&!(l[o-1]==="e"||l[o-1]==="E"));)o++;u("l",E,o),c=!1;continue}if(p==="/"&&Jn(a,c)){let E=o;o++;let _=!1;for(;o<s;){let v=l[o];if(v==="\\"){o+=2;continue}if(v==="[")_=!0;else if(v==="]")_=!1;else if(v==="/"&&!_){o++;break}else if(v===`
5
- `)break;o++}for(;o<s&&dn.test(l[o]);)o++;u("l",E,o),c=!1;continue}let f=o,y,m=l.slice(o,o+3),g=l.slice(o,o+2);if(m==="..."||m==="==="||m==="!=="||m==="**="||m==="<<="||m===">>="||m==="&&="||m==="||="||m==="??="?y=m:g==="=>"||g==="=="||g==="!="||g==="<="||g===">="||g==="&&"||g==="||"||g==="??"||g==="?."||g==="++"||g==="--"||g==="+="||g==="-="||g==="*="||g==="/="||g==="%="||g==="&="||g==="|="||g==="^="||g==="**"||g==="<<"||g===">>"?y=g:y=p,o+=y.length,y==="("||y==="["||y==="{"){y==="{"&&Qn(a)&&t.add(e.length),n.push(e.length),u("p",f,o),i++,c=!1;continue}if(y===")"||y==="]"||y==="}"){if(y==="}"&&r.length>0&&r[r.length-1]===i-1&&(n.length===0||e[n[n.length-1]]?.depth<r[r.length-1])){r.pop(),i--;let _=o,v=d();u("l",_-1,o),c=!1,v==="interp"&&(r.push(i),i++);continue}i=Math.max(0,i-1);let E=n.pop();u("p",f,o),c=y==="}"&&E!==void 0&&t.has(E);continue}u("p",f,o),c=!1}return{tokens:e,objectBraces:t}}var tr=new Set(["const","let","var","function","class","if","for","while","do","switch","try","return","break","continue","throw","async","import","export"]),U=class{static expressionCache=new Map;static bindingsCache=new Map;static loopVariableCache=new Map;static MAX_CACHE_SIZE=1e3;static clearCaches(){this.expressionCache.clear(),this.bindingsCache.clear(),this.loopVariableCache.clear()}static extractStateBindings(e){if(this.bindingsCache.has(e))return[...this.bindingsCache.get(e)];let t=new Set;try{new Function(e);let{tokens:r}=hn(e);this.collectTopLevelBindings(r,t)}catch(r){console.error("[PP-ERROR] AstParser Failed",r)}let n=Array.from(t);return Xe(this.bindingsCache,this.MAX_CACHE_SIZE),this.bindingsCache.set(e,n),n}static collectTopLevelBindings(e,t){let n=e.length,r=i=>{let o=e[i];if(!o)return i;if(o.kind==="i")return t.add(o.value),i+1;if(o.kind==="p"&&(o.value==="{"||o.value==="[")){let s=o.depth,a=i+1;for(;a<n;){let c=e[a];if(c.depth===s&&c.kind==="p"&&(c.value==="}"||c.value==="]"))return a+1;if(c.depth!==s+1){a++;continue}if(c.kind==="p"&&c.value===","){a++;continue}if(c.kind==="p"&&c.value==="..."){a=r(a+1),a=this.skipDefault(e,a,s+1);continue}if(o.value==="["){a=r(a),a=this.skipDefault(e,a,s+1);continue}if(c.kind==="i"||c.kind==="l"){let u=e[a+1];u&&u.kind==="p"&&u.value===":"?a=r(a+2):(c.kind==="i"&&t.add(c.value),a++),a=this.skipDefault(e,a,s+1);continue}if(c.kind==="p"&&c.value==="["){let u=a+1;for(;u<n&&e[u].depth>s+1;)u++;u++;let h=e[u];h&&h.kind==="p"&&h.value===":"?a=r(u+1):a=u,a=this.skipDefault(e,a,s+1);continue}a++}return a}return i+1};for(let i=0;i<n;i++){let o=e[i];if(!(o.depth!==0||o.kind!=="i")){if(o.value==="const"||o.value==="let"||o.value==="var"){let s=i+1;for(;s<n;){s=r(s);let a=e[s];a&&a.kind==="p"&&a.value==="="&&(s=this.skipInitializer(e,s+1));let c=e[s];if(c&&c.kind==="p"&&c.value===","){s++;continue}break}i=s-1;continue}if(o.value==="function"||o.value==="class"){let s=e[i+1];s&&s.kind==="i"&&s.depth===0&&t.add(s.value);continue}if(o.value==="async"){let s=e[i+1],a=e[i+2];s&&s.kind==="i"&&s.value==="function"&&a&&a.kind==="i"&&t.add(a.value)}}}}static skipDefault(e,t,n){let r=e[t];if(!r||r.kind!=="p"||r.value!=="=")return t;let i=t+1;for(;i<e.length;){let o=e[i];if(o.depth<n||o.depth===n&&o.kind==="p"&&o.value===",")return i;i++}return i}static skipInitializer(e,t){let n=t,r=e[t-1]?.end??0;for(;n<e.length;){let i=e[n];if(i.depth===0&&i.kind==="p"&&(i.value===","||i.value===";")||i.depth===0&&i.kind==="i"&&tr.has(i.value)&&n>t&&i.start>r)return n;r=i.end,n++}return n}static isValidExpression(e){if(!e.trim())return!1;if(this.expressionCache.has(e))return this.expressionCache.get(e);let t=!1;try{new Function(`return (${e});`),t=!0}catch{t=!1}return Xe(this.expressionCache,this.MAX_CACHE_SIZE),this.expressionCache.set(e,t),t}static analyzeLoopVariableUsage(e,t){let n=e+"|"+t;if(this.loopVariableCache.has(n))return[...this.loopVariableCache.get(n)];let r=[];try{let i=hn(e),{tokens:o}=i;for(let s=0;s<o.length;s++){let a=o[s];if(a.kind!=="i"||a.value!==t||this.isMemberProperty(o,s))continue;let c=this.classifyObjectPosition(i,s);if(c==="key")continue;if(c===null){r.push({start:a.start,end:a.end,isShorthand:!1,isUnwrap:!1});continue}let u=o[s-1],h=o[s+1],d=c==="shorthand"&&u.value==="{"&&h.value==="}";r.push(d?{start:u.start,end:h.end,isShorthand:!0,isUnwrap:!0}:{start:a.start,end:a.end,isShorthand:!0,isUnwrap:!1})}}catch{}return Xe(this.loopVariableCache,this.MAX_CACHE_SIZE),this.loopVariableCache.set(n,[...r]),[...r]}static isMemberProperty(e,t){let n=e[t-1];return n!==void 0&&n.kind==="p"&&(n.value==="."||n.value==="?.")}static classifyObjectPosition(e,t){let{tokens:n,objectBraces:r}=e,i=n[t],o=n[t-1],s=n[t+1];if(!o||o.kind!=="p"||o.value!=="{"&&o.value!==",")return null;let a=-1;for(let u=t-1;u>=0;u--){let h=n[u];if(h.kind==="p"&&h.depth<i.depth){h.value==="{"&&(a=u);break}}return a===-1||!r.has(a)||!(o.value==="{"&&t-1===a||o.value===","&&o.depth===i.depth)?null:s&&s.kind==="p"&&s.value===":"?"key":s&&s.kind==="p"&&(s.value===","||s.value==="}"||s.value==="=")?"shorthand":null}};var De="pp-keep-content",fn=["pp-owner","<pp-context-provider","pp-ref","data-pp-ref"];function mn(l){if(l.length===0)return!1;for(let e=0;e<fn.length;e++)if(l.includes(fn[e]))return!1;return!0}var Ze=class{enabled=!0;committedKeys=new Set;renderKeys=new Set;emitted=0;beginRender(){this.renderKeys.clear(),this.emitted=0}getEmittedCount(){return this.emitted}commit(){let e=this.committedKeys;this.committedKeys=this.renderKeys,e.clear(),this.renderKeys=e}disable(){this.enabled=!1,this.committedKeys.clear(),this.renderKeys.clear()}resolve(e,t,n){return this.renderKeys.add(e),!this.enabled||n===null||!this.committedKeys.has(e)?t:(this.emitted++,n)}};var ce=class{static cache=new Map;static MAX_CACHE_SIZE=2e3;static CONTEXT_PROVIDER_TAG_PATTERN=/<\/?([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\.Provider)\b[^>]*>/gi;static LITERAL_CODE_TAG_PATTERN=/(<code\b[^>]*>)([\s\S]*?)(<\/code\s*>)/gi;static ESCAPED_BRACE_ENTITY_PATTERN=/&(?:amp;)?(lbrace|rbrace|#123|#125|#x7b|#x7d);/gi;static LITERAL_TEXT_LT_ENTITY_PATTERN=/&(?:lt|#0*60|#x0*3c);/i;static INTERNAL_LOOP_NAMES=new Set(["__pp_loop_capture","__pp_loop_read","__pp_loop_rows","__pp_render_value","__pp_raw_html","__pp_escape_html","__pp_attr","__pp_bool_attr","__pp_to_loop_items"]);static SPREAD_BOOLEAN_ATTRS=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"]);static DYNAMIC_BOOLEAN_ATTRIBUTE_PATTERN=new RegExp(`(?<![\\w-])(${Array.from(ye).join("|")})=(["'])\\{`,"g");static escapeTemplateLiteralText(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}static COMMENT_STRIP_RAW_TEXT_TAGS=new Set(["script","style","textarea","title","xmp"]);static COMMENT_STRIP_VERBATIM_TAGS=new Set(["pre","code"]);static isRuntimeCommentMarker(e){let t=e.trim();return t.startsWith("pp:")||t==="/pp"||t.startsWith("pp-")||t.startsWith("__PP_")||t==="invalid-loop"}static stripAuthoredComments(e){if(!e.includes("<!--"))return e;let t="",n=0,r=e.length,i=0;for(;n<r;){let o=e[n];if(o==="<"){if(e.startsWith("<!--",n)){let m,g;if(e.startsWith(">",n+4))m=n+5,g="";else if(e.startsWith("->",n+4))m=n+6,g="";else{let E=e.indexOf("-->",n+4);m=E===-1?r:E+3,g=e.slice(n+4,E===-1?r:E)}(i>0||this.isRuntimeCommentMarker(g))&&(t+=e.slice(n,m)),n=m;continue}let a=e[n+1]==="/",c=n+(a?2:1),u=/^[a-zA-Z][^\s/>]*/.exec(e.slice(c,c+64));if(!u){t+=o,n++;continue}let h=u[0].toLowerCase(),d=c+u[0].length,p=null;for(;d<r;){let m=e[d];if(p)m===p&&(p=null);else if(m==='"'||m==="'")p=m;else if(m===">")break;d++}let f=Math.min(d+1,r);if(t+=e.slice(n,f),n=f,a){this.COMMENT_STRIP_VERBATIM_TAGS.has(h)&&i>0&&i--;continue}if(d<r&&e[d-1]==="/")continue;if(this.COMMENT_STRIP_RAW_TEXT_TAGS.has(h)){let m=new RegExp(`</${h}(?=[\\s/>]|$)`,"gi");m.lastIndex=n;let g=m.exec(e),E=g?g.index:r;t+=e.slice(n,E),n=E;continue}this.COMMENT_STRIP_VERBATIM_TAGS.has(h)&&i++;continue}if(o==="{"&&i===0){if(this.isServerTemplateBlockStart(e,n)){let c=this.findServerTemplateBlockEnd(e,n);if(c!==-1){t+=e.slice(n,c),n=c;continue}}let a=this.findClosingBrace(e,n);if(a!==-1){t+=e.slice(n,a+1),n=a+1;continue}t+=o,n++;continue}let s=n;for(;s<r&&e[s]!=="<"&&e[s]!=="{";)s++;s===n&&(s=n+1),t+=e.slice(n,s),n=s}return t}static SHARED_RENDER_HELPERS=(()=>{let e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/,n=/[&<>"']/g,r=p=>e[p],i=p=>{let f=String(p);return t.test(f)?f.replace(n,r):f},o=p=>({__ppRawHtml:String(p)}),s=p=>(console.warn(`[PP-WARN] Invalid template child of type "${p===null?"null":typeof p}" was omitted. Render a primitive, an array of renderable values, or explicit trusted HTML instead.`,p),""),a=p=>typeof p=="boolean"||p==null?"":p&&typeof p=="object"&&Object.prototype.hasOwnProperty.call(p,"__ppRawHtml")?p.__ppRawHtml:Array.isArray(p)?p.map(a).join(""):typeof p=="object"||typeof p=="function"||typeof p=="symbol"?s(p):i(p);return{__pp_escape_html:i,__pp_raw_html:o,__pp_render_value:a,__pp_attr_text:p=>typeof p=="boolean"||p==null?"":Array.isArray(p)?p.join(""):String(p),__pp_attr:(p,f)=>o(typeof f=="boolean"?p+'="'+i(f)+'"':p+'="'+a(f)+'"'),__pp_bool_attr:(p,f,y)=>typeof f=="boolean"?o(f?p:""):f==null?"":typeof f=="string"||typeof f=="number"||typeof f=="bigint"?f?o(p+'="'+i(f)+'"'):"":o(p+'="{'+y+'}"'),__pp_to_loop_items:p=>{if(Array.isArray(p))return p;if(p==null)return[];try{if(typeof p[Symbol.iterator]=="function")return Array.from(p)}catch(f){return console.warn("[PP-WARN] pp-for iterable could not be consumed:",p,f),[]}return console.warn("[PP-WARN] pp-for collection is not an array or iterable:",p),[]}}})();static SHARED_HELPER_PRELUDE=`const { __pp_escape_html, __pp_raw_html, __pp_render_value, __pp_attr_text, __pp_attr, __pp_bool_attr, __pp_to_loop_items } = __pp_shared;
6
- `;static escapeTemplateLiteralTextPreservingInterpolations(e){let t="",n=0,r=0;for(;n<e.length;){if(e[n]==="$"&&e[n+1]==="{"){let i=this.findClosingBrace(e,n+1);if(i!==-1){t+=this.escapeTemplateLiteralText(e.slice(r,n)),t+=e.slice(n,i+1),n=i+1,r=n;continue}}n++}return t+=this.escapeTemplateLiteralText(e.slice(r)),t}static clearCache(){this.cache.clear()}static maskEscapedBraceEntities(e){let t=new Map,n=0;return{maskedHtml:e.replace(this.ESCAPED_BRACE_ENTITY_PATTERN,(i,o)=>{let s=`__PP_ESCAPED_BRACE_${n++}__`;return t.set(s,A(`&${o};`)),s}),placeholders:t}}static transformSpreadAttributes(e){let t=new Map,n=0;if(!e.includes("pp-spread"))return{html:e,spreadReplacements:t};let r=document.createElement("template");r.innerHTML=e;let i=o=>{if(o.nodeType===Node.ELEMENT_NODE){let s=o;if(Array.from(s.childNodes).forEach(i),s.hasAttribute("pp-spread")){let a=s.getAttribute("pp-spread")||"";s.removeAttribute("pp-spread");let u=z(a)?.expression.trim()??"";if(u.startsWith("...")){let h=A(u.slice(3).trim()),d=`___pp_spread_${n++}___`,p=JSON.stringify(Array.from(this.SPREAD_BOOLEAN_ATTRS)),f=`\${ (() => {
7
- const __obj = ${h};
8
- if (!__obj || typeof __obj !== 'object') return '';
9
- const __booleanAttrs = ${p};
10
- return Object.entries(__obj)
11
- .map(([k, v]) => {
12
- if (v == null) return '';
13
- const __attrName = String(k);
14
- if (!/^[^\\s"'<>/=]+$/.test(__attrName) || /^on/i.test(__attrName)) return '';
15
- if (__booleanAttrs.includes(__attrName.toLowerCase())) {
16
- if (v === false) return '';
17
- if (v === true) return __attrName;
18
- }
19
- const __escapedValue = String(v)
20
- .split('&').join('&amp;')
21
- .split('"').join('&quot;')
22
- .split("'").join('&#39;')
23
- .split('<').join('&lt;')
24
- .split('>').join('&gt;');
25
- return __attrName + '="' + __escapedValue + '"';
26
- })
27
- .filter(Boolean)
28
- .join(' ');
29
- })() }`;t.set(d,f),s.setAttribute(d,"")}}}};return Array.from(r.content.childNodes).forEach(i),{html:r.innerHTML,spreadReplacements:t}}static expandSpreadPlaceholders(e,t){let n=e;return t.forEach((r,i)=>{n=n.split(`${i}=""`).join(r),n=n.split(i).join(r)}),n}static transformRefAttributes(e){if(!e.includes("pp-ref"))return e;let t=document.createElement("template");t.innerHTML=e;let n=document.createTreeWalker(t.content,NodeFilter.SHOW_ELEMENT),r=n.nextNode();for(;r;){let i=r;if(i.hasAttribute("pp-ref")){if(i.hasAttribute("pp-component")&&!i.hasAttribute("pp-ref-owner")){r=n.nextNode();continue}let o=i.getAttribute("pp-ref")||"",s=z(o);if(s){let a=A(s.expression);i.removeAttribute("pp-ref"),i.setAttribute("data-pp-ref",`{ __pp_ref(${a}) }`)}}r=n.nextNode()}return t.innerHTML}static transformContextProviderTags(e){if(!/\.provider\b/i.test(e))return e;let t="",n=0;for(;n<e.length;){let r=e.slice(n).match(/^<([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\.Provider)\b/i);if(!r){t+=e[n],n+=1;continue}let i=r[1],o=this.findOpeningTagEnd(e,n);if(o===-1){t+=e[n],n+=1;continue}let s=e.slice(n+r[0].length,o),a=o+1,c=this.findMatchingContextProviderClose(e,a);if(!c){t+=e[n],n+=1;continue}let u=this.transformContextProviderTags(e.slice(a,c.start)),d=`'${i.replace(/\.Provider$/i,"").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`,p=this.extractContextProviderValueExpression(s);t+=`<pp-context-provider data-pp-context-token="{ __pp_context_token(__pp_context_lookup(${d})) }" data-pp-context-value="{ __pp_context_value(${p}) }">`+u+"</pp-context-provider>",n=c.end}return t}static findOpeningTagEnd(e,t){let n=null,r=0;for(let i=t;i<e.length;i++){let o=e[i],s=this.isEscaped(e,i);if(n){if(o==="{"&&!s){r++;continue}if(o==="}"&&!s&&r>0){r--;continue}o===n&&!s&&r===0&&(n=null);continue}if(!s&&(o==='"'||o==="'")){n=o,r=0;continue}if(o===">")return i}return-1}static findMatchingContextProviderClose(e,t){this.CONTEXT_PROVIDER_TAG_PATTERN.lastIndex=t;let n=1,r;for(;r=this.CONTEXT_PROVIDER_TAG_PATTERN.exec(e);){let i=r[0],o=i.startsWith("</");if(n+=o?-1:1,n===0)return{start:r.index,end:r.index+i.length}}return null}static extractContextProviderValueExpression(e){let t=e.match(/\bvalue\s*=\s*(?:"([\s\S]*?)"|'([\s\S]*?)'|([^\s>]+))/i);if(!t)return"undefined";let n=t[1]??t[2]??t[3]??"",r=A(n.trim()),i=z(r);return i?i.expression:JSON.stringify(n)}static normalizeTextareaValueAttributes(e){if(!e.includes("<textarea")||!e.includes("value="))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("textarea").forEach(n=>{let r=n,i=r.getAttribute("value");i!==null&&(r.textContent=i,r.removeAttribute("value"))}),t.innerHTML}static transformStyleAliasAttributes(e){if(!e.includes("pp-style"))return e;let t=document.createElement("template");t.innerHTML=e;let n=document.createTreeWalker(t.content,NodeFilter.SHOW_ELEMENT),r=n.nextNode();for(;r;){let i=r;if(i.hasAttribute("pp-style")){let o=i.getAttribute("pp-style")??"",s=i.getAttribute("style")??"";i.removeAttribute("pp-style");let a=this.mergeStyleAttributeValues(s,o);a.length>0&&i.setAttribute("style",a)}r=n.nextNode()}return t.innerHTML}static mergeStyleAttributeValues(e,t){let n=e.trim(),r=t.trim().replace(/^;+\s*/,"");return n?r?`${n.endsWith(";")?n:`${n};`} ${r}`:n:r}static transformSelectValueAttributes(e){if(!e.includes("<select")||!e.includes("value="))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("select").forEach(n=>{let r=n,i=r.getAttribute("value");if(i===null)return;let o=z(i);if(!o)return;let s=A(o.expression);r.removeAttribute("value"),r.setAttribute("data-pp-select-value",`{ __pp_select_value(${s}) }`)}),t.innerHTML}static transformInputValueAttributes(e){if(!e.includes("<input")||!e.includes("value="))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("input").forEach(n=>{let r=n,i=r.getAttribute("value");if(i===null)return;let o=z(i);if(!o)return;let s=A(o.expression);r.removeAttribute("value"),r.setAttribute("data-pp-input-value",`{ __pp_input_value(${s}) }`)}),t.innerHTML}static transformCheckedValueAttributes(e){if(!e.includes("<input")||!e.includes("checked="))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("input").forEach(n=>{let r=n,i=r.getAttribute("checked");if(i===null)return;let o=z(i);if(!o)return;let s=A(o.expression);r.removeAttribute("checked"),r.setAttribute("data-pp-checked-value",`{ __pp_checked_value(${s}) }`)}),t.innerHTML}static transformDefaultValueAttributes(e){if(!e.includes("default"))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("input, textarea, select").forEach(n=>{let r=n,i=r.getAttribute("defaultvalue");if(i===null)return;let o=z(i);if(!o)return;let s=A(o.expression);r.removeAttribute("defaultvalue"),r.setAttribute("data-pp-default-value",`{ __pp_default_value(${s}) }`)}),t.innerHTML}static transformDefaultCheckedAttributes(e){if(!e.includes("default"))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("input").forEach(n=>{let r=n,i=r.getAttribute("defaultchecked");if(i===null)return;let o=z(i);if(!o)return;let s=A(o.expression);r.removeAttribute("defaultchecked"),r.setAttribute("data-pp-default-checked",`{ __pp_default_checked(${s}) }`)}),t.innerHTML}static transformComponentBoundaryBindings(e,t={}){if(!e.includes("pp-component=")||!e.includes("{"))return{html:e,boundaryReplacements:new Map};let n=document.createElement("template");n.innerHTML=e;let r=new Map,i=0;return n.content.querySelectorAll("[pp-component]").forEach(o=>{let s=o;Array.from(s.attributes).forEach(a=>{let c=a.name;if(c==="pp-component"||W(c,s))return;let u=z(a.value);if(!u){let E=this.buildMixedBoundaryAttributeCode(c,a.value,t.rewriteExpression);if(E){let _=`___PP_BOUNDARY_ATTR_${i++}___`;r.set(`${c}="${_}"`,E),s.setAttribute(c,_)}return}let h=this.expandEmbeddedBindingsInStringLiterals(A(u.expression)),d=t.rewriteExpression?.(h),p=d?.evalExpression??h,f=(d?.evalExpression??h).replace(/\\/g,"\\\\").replace(/'/g,"\\'"),y=d?.rawExpressionCode??JSON.stringify(f),m=`___PP_BOUNDARY_ATTR_${i++}___`,g=this.isBooleanAttribute(c)?`return __pp_raw_html(__ppAttr ? '${c}' : '');`:`return __pp_raw_html('${c}="' + __pp_escape_html(__ppAttr) + '"');`;r.set(`${c}="${m}"`,`\${__pp_render_value((() => { const __ppAttr = (${p}); if (typeof __ppAttr === 'boolean') { ${g} } if (__ppAttr == null) return ''; if (typeof __ppAttr === 'string' || typeof __ppAttr === 'number' || typeof __ppAttr === 'bigint') { const __ppText = String(__ppAttr); return __pp_raw_html('${c}="' + __pp_escape_html(__ppText) + '"' + (__ppText.indexOf('{') === -1 && __ppText.indexOf('}') === -1 ? '' : ' ${ie}${c}=""')); } return __pp_raw_html('${c}="{' + ${y} + '}"'); })())}`),s.setAttribute(c,m)})}),{html:n.innerHTML,boundaryReplacements:r}}static maskStaticComponentIds(e){if(!e.includes("pp-component="))return{html:e,componentIdPlaceholders:new Map};let t=document.createElement("template");t.innerHTML=e;let n=new Map,r=0;return t.content.querySelectorAll("[pp-component]").forEach(i=>{let o=i.getAttribute("pp-component");if(!o||o.includes("{"))return;let s=`___PP_STATIC_COMPONENT_ID_${r++}___`;n.set(s,o),i.setAttribute("pp-component",s)}),{html:t.innerHTML,componentIdPlaceholders:n}}static buildMixedBoundaryAttributeCode(e,t,n){if(!t.includes("{"))return null;let r=[],i="",o=!1,s=0,a=()=>{i.length!==0&&(r.push(JSON.stringify(i)),i="")};for(;s<t.length;){if(t[s]!=="{"){i+=t[s],s++;continue}if(s>0&&t[s-1]==="$"){i+="{",s++;continue}let u=this.findClosingBrace(t,s);if(u===-1){i+=t[s],s++;continue}let h=this.expandEmbeddedBindingsInStringLiterals(A(t.slice(s+1,u)));if(!U.isValidExpression(h)){i+=t.slice(s,u+1),s=u+1;continue}a();let d=n?.(h).evalExpression??h;r.push(`__pp_attr_text((${d}))`),o=!0,s=u+1}return o?(a(),`\${__pp_render_value((() => { const __ppAttr = '' + (${r.length===1?r[0]:r.join(" + ")}); return __pp_raw_html('${e}="' + __pp_escape_html(__ppAttr) + '"' + (__ppAttr.indexOf('{') === -1 && __ppAttr.indexOf('}') === -1 ? '' : ' ${ie}${e}=""')); })())}`):null}static transformLoopAttributeEmbeddedBindings(e,t){if(!e.includes("{"))return e;let n=document.createElement("template");n.innerHTML=e;let r=!1,i=s=>{Array.from(s.attributes).forEach(a=>{if(W(a.name,s)||!a.value.includes("{"))return;let c=z(a.value);if(!c)return;let u=A(c.expression),h=this.expandEmbeddedBindingsInStringLiterals(u);h!==u&&U.isValidExpression(h)&&(s.setAttribute(a.name,`{${t(h).evalExpression}}`),r=!0)})},o=s=>{Array.from(s.children).forEach(a=>{i(a),a instanceof HTMLTemplateElement?o(a.content):o(a)})};return o(n.content),r?n.innerHTML:e}static expandEmbeddedBindingsInStringLiterals(e){let t="",n=0;for(;n<e.length;){let r=e[n];if(r!=='"'&&r!=="'"){t+=e[n],n++;continue}let i=n;n++;let o="";for(;n<e.length;){let a=e[n];if(o+=a,n++,a===r&&!this.isEscaped(o,o.length-1)){o=o.slice(0,-1);break}}if(!o.includes("{")){t+=e.slice(i,n);continue}let s=this.expandEmbeddedBindingsInStringLiteral(o,r);t+=s??e.slice(i,n)}return t}static expandEmbeddedBindingsInStringLiteral(e,t){let n=[],r=0,i=0,o=s=>{s.length>0&&n.push(`${t}${s}${t}`)};for(;r<e.length;){if(e[r]!=="{"||e[r-1]==="$"||this.isEscaped(e,r)||this.isServerTemplateBlockStart(e,r)){r++;continue}let s=this.findClosingBrace(e,r);if(s===-1){r++;continue}o(e.slice(i,r));let a=e.slice(r+1,s).trim();a&&n.push(this.stringifyEmbeddedBindingExpression(a)),r=s+1,i=r}return n.length===0?null:(o(e.slice(i)),`(${n.length>0?n.join(" + "):`${t}${t}`})`)}static stringifyEmbeddedBindingExpression(e){return`((__ppVal) => { if (typeof __ppVal === 'boolean' || __ppVal == null) return ''; if (Array.isArray(__ppVal)) return __ppVal.map((__ppItem) => __ppItem == null || typeof __ppItem === 'boolean' ? '' : String(__ppItem)).join(''); return String(__ppVal); })(${e})`}static compile(e,t){let n=this.stripAuthoredComments((e||"").replace(/\r\n/g,`
30
- `).replace(/\r/g,`
31
- `)),r=t.join("\0"),i=`${n}${r}`,o=this.cache.get(i);if(o)return this.cache.delete(i),this.cache.set(i,o),o;let s=this.transformContextProviderTags(n),{maskedHtml:a,placeholders:c}=this.maskEscapedBraceEntities(s),u=this.escapeLiteralCodeProcessingInstructionOpeners(a),{maskedHtml:h,placeholders:d}=this.maskLiteralHtmlTextNodes(u),{maskedTemplate:p,placeholders:f,boundaryStubs:y}=this.maskComplexComponents(h),{maskedHtml:m,placeholders:g}=this.maskLiteralElements(p,"style","STYLE"),{maskedHtml:E,placeholders:_}=this.maskLiteralElements(m,"script","SCRIPT"),v=this.transformStyleAliasAttributes(E),S=this.normalizeTextareaValueAttributes(wt(v)),T=t.includes("__pp_input_value")?this.transformInputValueAttributes(S):S,C=t.includes("__pp_checked_value")?this.transformCheckedValueAttributes(T):T,P=this.transformSelectValueAttributes(C),w=this.transformDefaultValueAttributes(P),x=this.transformDefaultCheckedAttributes(w),B=this.transformRefAttributes(x),{html:N,boundaryReplacements:X}=this.transformComponentBoundaryBindings(B),{html:q,spreadReplacements:D}=this.transformSpreadAttributes(N),{html:oe,loopReplacements:bt}=this.processStructuralDirectives(q,R=>{let k=R;return k=this.restorePlaceholders(k,_),k=this.restorePlaceholders(k,g),k=this.restoreComponentPlaceholders(k,f,y,void 0),k=this.restorePlaceholders(k,d),this.restorePlaceholders(k,c)}),M=this.transformNonBooleanAttributeBooleans(this.transformBooleanAttributes(oe));(()=>{let R=!0;for(;R;)R=!1,bt.forEach((k,L)=>{let O=M;M=M.split("${"+L+"}").join("${"+k+"}"),M=M.split(L).join("{ __pp_raw_html("+k+") }"),M!==O&&(R=!0)})})();let F="return `",H=0,te="";for(;H<M.length;){let R=M[H],k=R==="o"||R==="O"?M[H+1]:"";if(k==="n"||k==="N"){let O=M.slice(H,H+20).toLowerCase().match(/^on\w+\s*=\s*(["'])/);if(O){let se=M.slice(H,H+O[0].length),Me=se[se.length-1],ne=H+O[0].length;for(;ne<M.length&&!(M[ne]===Me&&M[ne-1]!=="\\");)ne++;let me=M.slice(H,ne+1);te+=me,H=ne+1;continue}}if(R==="{"){if(this.isServerTemplateBlockStart(M,H)){let O=this.findServerTemplateBlockEnd(M,H);if(O!==-1){te+=M.slice(H,O),H=O;continue}}let L=this.findClosingBrace(M,H);if(L!==-1){let O=M.slice(H+1,L),se=A(O);if(U.isValidExpression(se)){F+=this.escapeTemplateLiteralText(te),te="";let Me=se.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g," ");F+=`\${ (() => {
32
- try {
33
- const __res = (${se});
34
- return __pp_render_value(__res);
35
- } catch(e) {
36
- console.error("[PP-ERROR] Template Expression Failed: \\"${Me}\\"", e);
37
- return '';
38
- }
39
- })() }`,H=L+1;continue}}}te+=R,H++}F+=this.escapeTemplateLiteralText(te),F+="`;",F=this.expandSpreadPlaceholders(F,D),X.size>0&&(F=F.replace(/[^\s"'<>=]+="___PP_BOUNDARY_ATTR_\d+___"/g,R=>X.get(R)??R));let de=this.SHARED_HELPER_PRELUDE+F;try{let R=t.slice(),k=de.includes("__pp_loop_capture(")&&!R.includes("__pp_loop_capture"),L=de.includes("__pp_loop_read(")&&!R.includes("__pp_loop_read"),O=de.includes("__pp_loop_rows(")&&!R.includes("__pp_loop_rows");k&&R.push("__pp_loop_capture"),L&&R.push("__pp_loop_read"),O&&R.push("__pp_loop_rows");let se=R.indexOf("__pp_boundary_html"),Me=new Function("__pp_shared",...R,de),ne=(...me)=>{let Yt=k||L?new Map:null,Bn=0,Ue=k||L||O?me.slice():me;k&&Ue.push(Ke=>{let be=`ppv_${++Bn}`;return Yt.set(be,Ke),be}),L&&Ue.push(Ke=>Yt.get(Ke)),O&&Ue.push((Ke,be,Jt)=>{if(!Jt)return be.join("");let Zt="";for(let We=0;We<be.length;We++)Zt+=Jt(be[We],We);return Zt});let Q=Me(this.SHARED_RENDER_HELPERS,...Ue);return Q=this.restorePlaceholders(Q,_),Q=this.restorePlaceholders(Q,g),Q=this.restoreComponentPlaceholders(Q,f,y,se>=0?me[se]:void 0),Q=this.restorePlaceholders(Q,d),Q=this.restorePlaceholders(Q,c),Q};return ne.__ppRestoreArtifacts=me=>{let Y=me;return Y=this.restorePlaceholders(Y,_),Y=this.restorePlaceholders(Y,g),Y=this.restoreComponentPlaceholders(Y,f,y,void 0),Y=this.restorePlaceholders(Y,d),Y=this.restorePlaceholders(Y,c),Y},re(this.cache,i,ne,this.MAX_CACHE_SIZE),ne}catch(R){return console.error("[PP-ERROR] Compilation Failed",R),()=>"Error in Template"}}static maskLiteralElements(e,t,n){if(!new RegExp(`<${t}[\\s>]`,"i").test(e))return{maskedHtml:e,placeholders:new Map};let r=document.createElement("template");r.innerHTML=e;let i=new Map,o=0;return r.content.querySelectorAll(t).forEach(s=>{let a=`__PP_${n}_${o++}__`;i.set(a,s.outerHTML),s.replaceWith(document.createTextNode(a))}),{maskedHtml:r.innerHTML,placeholders:i}}static maskLiteralHtmlTextNodes(e){if(!e.includes("{")&&!e.includes("}"))return{maskedHtml:e,placeholders:new Map};if(!this.LITERAL_TEXT_LT_ENTITY_PATTERN.test(e))return{maskedHtml:e,placeholders:new Map};let t=document.createElement("template");t.innerHTML=e;let n=new Map,r={value:0},i=document.createTreeWalker(t.content,NodeFilter.SHOW_TEXT),o=[];for(;i.nextNode();)o.push(i.currentNode);return o.forEach(s=>{if(this.isWithinLiteralTextContainer(s))return;let a=s.textContent??"";if(!a.includes("{")&&!a.includes("}"))return;let c=this.splitLiteralHtmlTextSegments(a);if(!c)return;let u="";c.forEach(h=>{u+=h.literalHtml?this.maskLiteralBraces(h.text,n,r):h.text}),s.textContent=u}),{maskedHtml:t.innerHTML,placeholders:n}}static escapeLiteralCodeProcessingInstructionOpeners(e){return e.includes("<?")?e.replace(this.LITERAL_CODE_TAG_PATTERN,(t,n,r,i)=>!r.includes("<?")||this.isPureBindingLiteral(r.trim())?t:`${n}${r.replace(/<\?/g,"&lt;?")}${i}`):e}static isWithinLiteralTextContainer(e){let t=e.parentNode;for(;t;){if(t.nodeType===Node.ELEMENT_NODE){let n=t.tagName.toLowerCase();if(n==="script"||n==="style")return!0}t=t.parentNode}return!1}static splitLiteralHtmlTextSegments(e){if(!e.includes("<")||!e.includes(">"))return null;let t=document.createElement("template");t.innerHTML=e;let n=Array.from(t.content.childNodes).map(r=>({text:r.nodeType===Node.TEXT_NODE?r.textContent??"":this.serializeNodeHtml(r),literalHtml:r.nodeType!==Node.TEXT_NODE}));return n.some(r=>r.literalHtml)?n:null}static serializeNodeHtml(e){let t=document.createElement("template");return t.content.appendChild(e.cloneNode(!0)),t.innerHTML}static maskLiteralBraces(e,t,n){let r="";for(let i of e){if(i==="{"||i==="}"){let o=`__PP_LITERAL_HTML_BRACE_${n.value++}__`;t.set(o,i),r+=o;continue}r+=i}return r}static isPureBindingLiteral(e){return z(e)!==null}static restoreComponentPlaceholders(e,t,n,r){if(t.size===0)return e;let i="",o=0;for(;o<e.length;){let s=e.indexOf("__PP_CHILD_",o);if(s===-1)break;let a=e.indexOf("__",s+11);if(a===-1)break;let c=e.slice(s,a+2),u=t.get(c);if(u===void 0){i+=e.slice(o,a+2),o=a+2;continue}let h=r?r(c,u,n.get(c)??null):u;i+=e.slice(o,s),i+=h.includes("__PP_CHILD_")?this.restoreComponentPlaceholders(h,t,n,r):h,o=a+2}return o===0?e:i+e.slice(o)}static restorePlaceholders(e,t){let n=e;return t.forEach((r,i)=>{n.includes(i)&&(n=n.split(i).join(r))}),n}static transformBooleanAttributes(e){let t="",n=0,r=0,i=this.DYNAMIC_BOOLEAN_ATTRIBUTE_PATTERN;for(i.lastIndex=0;r<e.length;){i.lastIndex=r;let o=i.exec(e);if(!o)break;let s=o[1],a=o[2],c=o.index,u=c+o[0].length-1;if(s==="checked"&&this.isAttributeOnComponentBoundary(e,c)||this.isServerTemplateBlockStart(e,u)){r=c+1;continue}let h=this.findClosingBrace(e,u);if(h===-1||e[h+1]!==a){r=c+1;continue}let d=e.slice(u+1,h),p=A(d),f=p.replace(/\\/g,"\\\\").replace(/'/g,"\\'");t+=e.slice(n,c),t+=`{ __pp_bool_attr('${s}', (${p}), '${f}') }`,n=h+2,r=n}return n===0?e:t+e.slice(n)}static DYNAMIC_ATTRIBUTE_CANDIDATE_PATTERN=/([^\s"'<>/=]+)\s*=\s*(["'])\{/y;static transformNonBooleanAttributeBooleans(e){let t=this.DYNAMIC_ATTRIBUTE_CANDIDATE_PATTERN,n="",r=0,i=0;for(;i<e.length;){let o=this.findNextAttributeCandidate(e,i);if(o===-1)break;t.lastIndex=o;let s=t.exec(e);if(!s){i=o+1;continue}let a=s[1],c=s[2];if(this.isAttributePosition(e,o)&&!this.isBooleanAttribute(a)&&a!=="pp-component"&&!/^on\w+$/i.test(a)){let u=o+s[0].length-1;if(!this.isServerTemplateBlockStart(e,u)){let h=this.findClosingBrace(e,u);if(h!==-1&&e[h+1]===c){let d=e.slice(u+1,h),p=A(d);if(U.isValidExpression(p)){n+=e.slice(r,o),n+=`{ __pp_attr('${a}', (${p})) }`,r=h+2,i=r;continue}}}}i=o+1}return r===0?e:n+e.slice(r)}static findNextAttributeCandidate(e,t){let n=t;for(;n<e.length;){let r=e.indexOf("{",n);if(r<=0)return-1;let i=e[r-1];if(i!=='"'&&i!=="'"){n=r+1;continue}let o=r-2;for(;o>=0&&/\s/.test(e[o]);)o--;if(o<0||e[o]!=="="){n=r+1;continue}for(o--;o>=0&&/\s/.test(e[o]);)o--;let s=o;for(;o>=0&&!/[\s"'<>/=]/.test(e[o]);)o--;if(s===o){n=r+1;continue}let a=o+1;if(a<t){n=r+1;continue}return a}return-1}static isBooleanAttribute(e){return ye.has(e.toLowerCase())}static isAttributePosition(e,t){let n=e.lastIndexOf("<",t);return n===-1||e.lastIndexOf(">",t)>=n?!1:t>n&&/\s/.test(e[t-1]??"")}static isAttributeOnComponentBoundary(e,t){let n=e.lastIndexOf("<",t);if(n===-1||e.lastIndexOf(">",t)>n)return!1;let i=this.findOpeningTagEnd(e,n);if(i===-1||t>i)return!1;let o=e.slice(n,n+2);if(o==="</"||o==="<!"||o==="<?")return!1;let s=e.slice(n,i+1);return/\spp-component(?:\s|=|>)/i.test(s)}static captureLoopVariablesInEventHandlers(e,t,n,r=!1,i=[]){let o="",s=0;for(;s<e.length;){let c=e.slice(s,s+40).toLowerCase().match(/^on\w+\s*=\s*(["'])/);if(c){let u=c[0].length,h=e.slice(s,s+u),d=h[h.length-1],p=s+u,f=p;for(;f<e.length&&!(e[f]===d&&e[f-1]!=="\\");)f++;let y=h.slice(0,-2).trim(),m=e.slice(p,f);m=this.rewriteLoopEventHandlerCode(m,t,n,r,i),o+=`${y}=${d}${m}${d}`,s=f+1;continue}o+=e[s],s++}return o}static rewriteLoopEventHandlerCode(e,t,n,r,i=[]){let o=z(e),a=A(o?o.expression:e);i.forEach(u=>{a=this.applyLoopEventCaptureRewrites(a,u)});let c={iterator:t,collectionName:"",indexVar:n,userDefinedIndex:r};return a=this.applyLoopEventCaptureRewrites(a,c),[...i,c].forEach(u=>{let h=this.getLoopIndexToken(u.indexVar);a=a.split(h).join(`\${${u.indexVar}}`)}),o?`{${a}}`:a}static applyLoopEventCaptureRewrites(e,t){let n=this.getLoopIndexToken(t.indexVar),r=e;return t.userDefinedIndex&&(r=this.replaceLoopIdentifierUsages(r,t.indexVar,n)),this.replaceLoopIdentifierUsages(r,t.iterator,`__pp_loop_read('\${__pp_loop_capture(${t.iterator})}')`)}static getLoopIndexToken(e){return`__PP_LOOP_IDX_${e}__`}static replaceLoopIdentifierUsages(e,t,n){let r=U.analyzeLoopVariableUsage(e,t).slice().sort((o,s)=>s.start-o.start);if(r.length===0)return e;let i=e;return r.forEach(o=>{let s=o.isShorthand?this.buildShorthandReplacement(t,n,o.isUnwrap):n;i=i.slice(0,o.start)+s+i.slice(o.end)}),i}static buildShorthandReplacement(e,t,n){return n?`{ ${e}: ${t} }`:`${e}: ${t}`}static createLoopBoundaryBindingRewrite(){return e=>({evalExpression:e,rawExpressionCode:`("__pp_loop_read('" + __pp_loop_capture(__ppAttr) + "')")`})}static isIdentifier(e){return/^[A-Za-z_$][\w$]*$/.test(e)&&!ae.has(e)&&!this.INTERNAL_LOOP_NAMES.has(e)}static stripBalancedParens(e){let t=e.trim();return!t.startsWith("(")||this.findMatchingToken(t,0,"(",")")!==t.length-1?null:t.slice(1,-1).trim()}static parseLoopDirective(e){let t=this.findTopLevelInSeparator(e);if(t===-1)return null;let n=e.slice(0,t).trim(),r=e.slice(t+2).trim();if(!n||!r)return null;let i=this.stripBalancedParens(n);if(i!==null){let o=this.findTopLevelToken(i,",");if(o===-1)return null;let s=i.slice(0,o).trim(),a=i.slice(o+1).trim();return!s||!a?null:{iterator:s,indexVar:a,collection:r}}return{iterator:n,indexVar:null,collection:r}}static findTopLevelInSeparator(e){let t={parenDepth:0,bracketDepth:0,braceDepth:0,quote:null};for(let n=0;n<e.length;n++){let r=e[n];if(!this.advanceScannerState(t,e,n)&&t.parenDepth===0&&t.bracketDepth===0&&t.braceDepth===0&&r==="i"&&e[n+1]==="n"&&/\s/.test(e[n-1]??"")&&/\s/.test(e[n+2]??""))return n}return-1}static findTopLevelToken(e,t){let n={parenDepth:0,bracketDepth:0,braceDepth:0,quote:null};for(let r=0;r<e.length;r++)if(!this.advanceScannerState(n,e,r)&&n.parenDepth===0&&n.bracketDepth===0&&n.braceDepth===0&&e[r]===t)return r;return-1}static findMatchingToken(e,t,n,r){let i=0,o=null;for(let s=t;s<e.length;s++){let a=e[s],c=this.isEscaped(e,s);if(o){a===o&&!c&&(o=null);continue}if(!c&&(a==='"'||a==="'"||a==="`")){o=a;continue}if(a===n&&!c)i++;else if(a===r&&!c&&(i--,i===0))return s}return-1}static advanceScannerState(e,t,n){let r=t[n],i=this.isEscaped(t,n);return e.quote?(r===e.quote&&!i&&(e.quote=null),!0):!i&&(r==='"'||r==="'"||r==="`")?(e.quote=r,!0):(i||(r==="("?e.parenDepth++:r===")"?e.parenDepth--:r==="["?e.bracketDepth++:r==="]"?e.bracketDepth--:r==="{"?e.braceDepth++:r==="}"&&e.braceDepth--),!1)}static isEscaped(e,t){let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n++,r--;return n%2!==0}static compileLoopRowPlan(e,t){let n=null;for(let s=e.firstChild;s;s=s.nextSibling)if(s.nodeType===Node.ELEMENT_NODE){if(n)return null;n=s}if(!n)return null;let r=this.buildElementPlan(n,!0);if(r===null||r.keyIndex===-1)return null;let i=n.hasAttribute("pp-component"),o={key:r.keyIndex,slots:r.slots,size:r.exprs.length};return r.hasBoundary&&(o.hasBoundary=1),i&&(o.rootBoundary=1),(!r.hasBoundary||i)&&(o.prototypeHtml=n.outerHTML,o.contextTag=t),{exprs:r.exprs,descriptor:o}}static serializeRowPlanDescriptor(e){let t=JSON.stringify(e),n=e.prototypeHtml;if(!n||!n.includes("{")&&!n.includes("}"))return t;let r=JSON.stringify(n),i=r.replace(/\{/g,"\\u007b").replace(/\}/g,"\\u007d");return t.replace(r,i)}static buildElementPlan(e,t){let n=[],r=[],i=-1,o=d=>{let p=this.expandEmbeddedBindingsInStringLiterals(d);return U.isValidExpression(p)?(n.push(p),n.length-1):null},s=d=>{let p=[],f=0,y=0;for(;f<d.length;){if(d[f]!=="{"){f++;continue}if(f>0&&d[f-1]==="$"){f++;continue}if(Ne(d,f))return null;let m=we(d,f);if(m===-1){f++;continue}let g=A(d.slice(f+1,m)),E=o(g);if(E===null){f=m+1;continue}f>y&&p.push(d.slice(y,f)),p.push(E),f=m+1,y=f}return y<d.length&&p.push(d.slice(y)),p},a=!1,c=(d,p)=>{a=!0;let f=d.getAttributeNames();for(let m=0;m<f.length;m++){let g=f[m],E=g.toLowerCase();if(E==="pp-component")continue;if(E==="pp-ref"||E==="pp-ref-owner"||E==="pp-owner")return!1;let _=d.getAttribute(g)??"";if(!_.includes("{"))continue;if(E.startsWith("on"))return!1;let v=z(_);if(!v)return!1;let S=o(A(v.expression));if(S===null)return!1;if(p.length===0&&E==="key"){i=S;continue}r.push({kind:"battr",p,name:E,v:S})}let y=[d];for(;y.length>0;){let m=y.pop();for(let g=m.firstChild;g;g=g.nextSibling){if(g.nodeType===Node.TEXT_NODE){if(g.data.includes("{"))return!1;continue}if(g.nodeType===Node.COMMENT_NODE)return!1;if(g.nodeType!==Node.ELEMENT_NODE)continue;let E=g,_=E.tagName.toLowerCase();if(_==="template"||_==="pp-context-provider")return!1;let v=E.getAttributeNames();for(let S=0;S<v.length;S++){let T=v[S].toLowerCase();if(T==="pp-owner"||T==="pp-ref"||T==="pp-ref-owner"||T==="data-pp-ref"||(E.getAttribute(v[S])??"").includes("{"))return!1}y.push(E)}}return!0},u=(d,p)=>{let f=d.tagName.toLowerCase();if(d.hasAttribute("pp-component"))return c(d,p);if(f==="template"||f==="script"||f==="style"||f==="slot"||f==="input"||f==="textarea"||f==="select"||f==="pp-context-provider"||f.includes("."))return!1;let y=d.getAttributeNames();for(let _=0;_<y.length;_++){let v=y[_],S=v.toLowerCase();if(S.startsWith("on")||S.startsWith("pp-")||S.startsWith("data-pp-")||S==="defaultvalue"||S==="defaultchecked")return!1;let T=d.getAttribute(v)??"";if(T.includes("__PP_"))return!1;if(!T.includes("{"))continue;let C=z(T),P=p.length===0&&S==="key";if(C){let B=o(A(C.expression));if(B===null)continue;if(P){if(!t)return!1;i=B;continue}r.push({kind:"attr",p,name:v,bool:ye.has(S),v:B});continue}if(P||ye.has(S))return!1;let w=s(T);if(w===null)return!1;w.some(B=>typeof B=="number")&&r.push({kind:"attrParts",p,name:v,parts:w})}let m=!1,g="",E=!1;for(let _=d.firstChild;_;_=_.nextSibling){if(_.nodeType===Node.ELEMENT_NODE){m=!0;continue}if(_.nodeType===Node.COMMENT_NODE)return!1;_.nodeType===Node.TEXT_NODE&&(g+=_.data,E=!0)}if(E&&g.includes("__PP_"))return!1;if(E&&g.includes("{"))if(m){let _=s(g);if(_&&_.some(v=>typeof v=="number"))return!1}else{let _=s(g);if(_===null)return!1;_.some(v=>typeof v=="number")&&r.push({kind:"text",p,parts:_})}if(m){let _=0;for(let v=d.firstElementChild;v;v=v.nextElementSibling){if(!u(v,[...p,_]))return!1;_++}}return!0},h;try{h=u(e,[])}catch{return null}return h?{exprs:n,slots:r,keyIndex:i,hasBoundary:a}:null}static compileComponentBodyPlan(e){let t=e;if(t.length===0||t.length>8192||/<(?:script|style|template|slot|input|textarea|select|pre|code|xmp|title|svg|math|iframe|frame|object|embed)\b|\bpp-|\.provider|<!--|&(?:amp;)?(?:lbrace|rbrace|#0*123|#0*125|#x0*7b|#x0*7d|lt|#0*60|#x0*3c);|__PP_|\$\{/i.test(t))return null;let n=document.createElement("template");n.innerHTML=t;let r=null;for(let o=n.content.firstChild;o;o=o.nextSibling){if(o.nodeType===Node.ELEMENT_NODE){if(r!==null)return null;r=o;continue}if(!(o.nodeType===Node.TEXT_NODE&&o.data.trim()===""))return null}if(r===null)return null;let i;try{i=this.buildElementPlan(r,!1)}catch{return null}return i===null||i.hasBoundary||i.slots.length>30?null:{exprs:i.exprs,descriptor:{rootTag:r.tagName,slots:i.slots,size:i.exprs.length}}}static isBoundaryRowBodySafe(e){let t=(n,r)=>{for(let i=n.firstChild;i;i=i.nextSibling){if(i.nodeType===Node.COMMENT_NODE){if(!r)return!1;continue}if(i.nodeType===Node.TEXT_NODE){if(!r&&i.data.includes("__PP_"))return!1;continue}if(i.nodeType!==Node.ELEMENT_NODE)continue;let o=i,s=o.tagName.toLowerCase();if(s==="template"||o.hasAttribute("pp-ref-owner")||!r&&(s==="input"||s==="textarea"||s==="select"||s==="slot"||s==="pp-context-provider"||o.hasAttribute("pp-ref")||o.hasAttribute("data-pp-ref")))return!1;let a=r||o.hasAttribute("pp-component");if(!t(o,a))return!1}return!0};return t(e,!1)}static processStructuralDirectives(e,t){if(!e.includes("pp-for"))return{html:e,loopReplacements:new Map};let n=document.createElement("template");n.innerHTML=e;let r=new Map,i=0,o=0,s=(a,c=[])=>{let u=Array.from(a.childNodes);for(let h of u){if(h.nodeType!==Node.ELEMENT_NODE)continue;let d=h,p=d.tagName==="TEMPLATE",f=d.tagName==="template"&&d.localName==="template";if(p||f){let y=d,m=y.getAttribute("pp-for")||"",g=null;if(y.hasAttribute("pp-for")){let _=this.parseLoopDirective(m),v,S,T,C=!1;if(_)v=_.iterator,T=_.collection,S=_.indexVar??`__pp_idx_${o++}`,C=_.indexVar!==null;else{console.warn(`[PP-WARN] Invalid pp-for directive skipped: "${m}"`),y.replaceWith(document.createComment("invalid-loop"));continue}if(!this.isIdentifier(v)||C&&!this.isIdentifier(S)||C&&v===S){console.warn(`[PP-WARN] pp-for currently expects identifier loop variables: "${m}"`),y.replaceWith(document.createComment("invalid-loop"));continue}if(!U.isValidExpression(T)){console.warn(`[PP-WARN] Invalid pp-for collection expression skipped: "${T}"`),y.replaceWith(document.createComment("invalid-loop"));continue}g={iterator:v,collectionName:T,indexVar:S,userDefinedIndex:C}}let E=y.content??y;if(s(E,g?[...c,g]:c),g){let{iterator:_,collectionName:v,indexVar:S,userDefinedIndex:T}=g,C=c.length===0?this.compileLoopRowPlan(E,y.parentElement?.tagName.toLowerCase()):null;C?.descriptor.prototypeHtml&&(C.descriptor.prototypeHtml=t(C.descriptor.prototypeHtml));let P=y.innerHTML,{html:w,componentIdPlaceholders:x}=this.maskStaticComponentIds(P);P=w,P=this.transformContextProviderTags(P),P=this.transformRefAttributes(P),P=this.transformStyleAliasAttributes(P);let B=this.createLoopBoundaryBindingRewrite(),{html:N,boundaryReplacements:X}=this.transformComponentBoundaryBindings(P,{rewriteExpression:B});P=N,P=this.captureLoopVariablesInEventHandlers(P,_,S,T,c),P=this.transformLoopAttributeEmbeddedBindings(P,B),P=P.replace(/___PP_LOOP_\d+___/g,k=>"${"+k+"}"),P=P.replace(/\r/g,""),P=this.transformNonBooleanAttributeBooleans(this.transformBooleanAttributes(P)),P=this.transformInterpolations(P),P=this.escapeTemplateLiteralTextPreservingInterpolations(P),X.size>0&&(P=P.replace(/[^\s"'<>=]+="___PP_BOUNDARY_ATTR_\d+___"/g,k=>X.get(k)??k)),x.forEach((k,L)=>{P=P.split(L).join(k)});let q=`(${_}, ${S})`,D=`__pp_collection_${i}`,oe=`__pp_items_${i}`,M=c.length>0||!this.loopBodyRendersSingleRoot(E)?-1:i,fe=M>=0&&C!==null&&(C.descriptor.hasBoundary===1||!P.includes("__pp_loop_capture")&&!P.includes("__PP_")&&!P.includes("pp-component"))?C:null,F=M>=0&&P.includes("pp-component")&&this.isBoundaryRowBodySafe(E)?1:0,H=fe?`, (${_}, ${S}, __pp_out, __pp_base) => { `+fe.exprs.map((k,L)=>`__pp_out[__pp_base + ${L}] = (${k});`).join(" ")+" return __pp_out; }, "+this.serializeRowPlanDescriptor(fe.descriptor):F!==0?", undefined, undefined":"",te=F!==0?`, ${F}`:"",de=`(() => { const ${D} = (${v}); const ${oe} = __pp_to_loop_items(${D}); return __pp_loop_rows(${M}, ${oe}, ${q} => \`${P}\`${H}${te}); })()`,R=`___PP_LOOP_${i++}___`;r.set(R,de),y.replaceWith(document.createTextNode(R));continue}continue}s(d,c)}};return s(n.content),{html:n.innerHTML,loopReplacements:r}}static loopBodyRendersSingleRoot(e){let t=0;for(let n=e.firstChild;n;n=n.nextSibling){if(n.nodeType===Node.ELEMENT_NODE){if(++t>1)return!1;continue}if(!(n.nodeType===Node.TEXT_NODE&&(n.textContent??"").trim()===""))return!1}return t===1}static transformInterpolations(e){let t="",n=0;for(;n<e.length;){if(e[n]==="o"||e[n]==="O"){let i=e.slice(n,n+20).toLowerCase().match(/^on\w+\s*=\s*(["'])/);if(i){let o=e.slice(n,n+i[0].length),s=o[o.length-1],a=n+i[0].length;for(;a<e.length&&!(e[a]===s&&e[a-1]!=="\\");)a++;t+=e.slice(n,a+1),n=a+1;continue}}if(e[n]==="{"){if(n>0&&e[n-1]==="$"){t+="{",n++;continue}if(this.isServerTemplateBlockStart(e,n)){let i=this.findServerTemplateBlockEnd(e,n);if(i!==-1){t+=e.slice(n,i),n=i;continue}}let r=this.findClosingBrace(e,n);if(r!==-1){let i=e.slice(n+1,r),o=A(i);if(U.isValidExpression(o)){t+="${__pp_render_value("+o+")}",n=r+1;continue}}}t+=e[n],n++}return t}static maskComplexComponents(e){if(!e.includes("pp-component=")||!e.includes("<script")&&!e.includes("pp-owner"))return{maskedTemplate:e,placeholders:new Map,boundaryStubs:new Map};let t=document.createElement("template");t.innerHTML=e;let n=new Map,r=new Map,i=0,o=d=>d.replace(/&/g,"&amp;").replace(/"/g,"&quot;"),s=d=>d.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),a=(d,p)=>{if(!d.includes("{"))return d;let f="",y=0;for(;y<d.length;){let m=d[y];if(m==="{"&&d[y-1]!=="$"){let g=we(d,y);if(g!==-1){let E=`__PP_CHILD_${i++}__`;n.set(E,p(d.slice(y,g+1))),f+=E,y=g+1;continue}}f+=m,y++}return f},c=d=>{Array.from(d.attributes).forEach(p=>{p.value.includes("{")&&d.setAttribute(p.name,a(p.value,o))})},u=(d,p)=>{for(let f=d.firstChild,y=null;f;f=y){if(y=f.nextSibling,f.nodeType===Node.TEXT_NODE){if(!p){let E=f.textContent??"";E.includes("{")&&(f.textContent=a(E,s))}continue}if(f.nodeType!==Node.ELEMENT_NODE)continue;let m=f;if(m.tagName.toLowerCase()==="script"){let E=`__PP_CHILD_${i++}__`;n.set(E,m.outerHTML),m.replaceWith(document.createTextNode(E));continue}if(m instanceof HTMLTemplateElement&&m.hasAttribute("pp-owner")){u(m.content,!0);continue}if(m.hasAttribute("pp-component")){p||c(m);let E=Array.from(m.querySelectorAll("script")).some(S=>S.closest("[pp-component]")===m),_=Array.from(m.querySelectorAll("template[pp-owner]")).some(S=>S.closest("[pp-component]")===m);u(m,p&&!E&&!_);continue}p||c(m),u(m instanceof HTMLTemplateElement?m.content:m,p)}},h=(d,p=!1)=>{if(d instanceof Element){if(d.hasAttribute("pp-component")){let y=!!d.querySelector("script");if(y||!!d.querySelector("template[pp-owner]")){if(p)y&&u(d,!1);else if(d.hasAttribute("pp-ref-owner")&&d.hasAttribute("pp-ref")){let g=d.getAttribute("pp-ref");c(d),g!==null&&d.setAttribute("pp-ref",g),u(d,!1)}else{let g=`__PP_CHILD_${i++}__`;n.set(g,d.outerHTML);let E=this.buildBoundaryStub(d);E!==null&&r.set(g,E),d.replaceWith(document.createTextNode(g))}return}}if(d instanceof HTMLTemplateElement){h(d.content,!0);return}}let f=d.firstElementChild;for(;f;){let y=f.nextElementSibling;h(f,p),f=y}};return h(t.content),{maskedTemplate:t.innerHTML,placeholders:n,boundaryStubs:r}}static buildBoundaryStub(e){if(!mn(e.innerHTML))return null;let t=e.cloneNode(!1);t.setAttribute(De,"");let n=t.outerHTML;return n.endsWith(`</${e.tagName.toLowerCase()}>`)?n:null}static findClosingBrace(e,t){return we(e,t)}static isServerTemplateBlockStart(e,t){return Ne(e,t)}static findServerTemplateBlockEnd(e,t){return kt(e,t)}};var At="data-pp-script-source";function Oe(l){l.querySelectorAll("script:not([type])").forEach(e=>{let t=e;t.hasAttribute(At)||(t.setAttribute(At,t.textContent??""),t.textContent="")})}function Mt(l){return l.getAttribute(At)??l.textContent??""}var Qe=class{constructor(e){this.componentId=e}componentId;bindingSeq=0;activeBindings=new Map;hasActiveBindings(){return this.activeBindings.size>0}ensureBindingId(e,t){let n=t==="captured"?"__ppCapturedRefBindingId":"__ppPlainRefBindingId";return e[n]||(e[n]=`pprefbind_${this.componentId}_${t}_${++this.bindingSeq}`),e[n]}commit(e){let t=new Map;for(let[n,r]of this.activeBindings.entries()){let i=e.get(n);if(!i){this.detachValue(r,"[PP-WARN] Ref cleanup failed");continue}r.value!==i.value||r.element!==i.element?this.detachValue(r,"[PP-WARN] Ref cleanup failed"):t.set(n,r)}for(let[n,r]of e.entries()){let i=this.activeBindings.get(n);if(i&&i.value===r.value&&i.element===r.element)continue;let o=this.attachValue(r.value,r.element,"[PP-WARN] Ref attachment failed");t.set(n,{...r,cleanup:o})}this.activeBindings=t}clearAll(){for(let e of this.activeBindings.values())this.detachValue(e,"[PP-WARN] Ref cleanup failed");this.activeBindings.clear()}attachValue(e,t,n){let r=this.updateValue(e,t,n);return typeof r=="function"?r:void 0}detachValue(e,t){if(e.cleanup){try{e.cleanup()}catch(n){console.warn(t,n)}return}this.updateValue(e.value,null,t)}updateValue(e,t,n){try{if(typeof e=="function")return e(t);e&&typeof e=="object"&&"current"in e&&(e.current=t)}catch(r){console.warn(n,r)}}};var et=class{constructor(e){this.componentId=e}componentId;trackedPortals=new Map;get size(){return this.trackedPortals.size}has(e){return this.trackedPortals.has(e)}getPlaceholderText(e){return this.trackedPortals.get(e)?.placeholder.data||`pp-portal:${this.componentId}`}apply(e){let t=new Set,n=!1;for(let r of e){let i=r.ref.current;if(!i)continue;let o=r.target??document.body;t.add(i);let s=this.trackedPortals.get(i);if(s?.placeholder.parentNode){s.target!==o&&(o.appendChild(i),s.target=o,n=!0);continue}r.info.sourceParent===null&&i.parentNode instanceof Element&&(r.info.sourceParent=i.parentNode);let a=document.createComment(`pp-portal:${this.componentId}`);i.parentNode&&i.parentNode.insertBefore(a,i),o.appendChild(i),this.trackedPortals.set(i,{element:i,placeholder:a,target:o}),n=!0}for(let[r,i]of this.trackedPortals)t.has(r)||(i.placeholder.parentNode?(i.placeholder.parentNode.insertBefore(r,i.placeholder),i.placeholder.remove()):r.parentNode&&r.remove(),this.trackedPortals.delete(r),n=!0);return n}replaceElement(e,t){let n=this.trackedPortals.get(e);n&&(this.trackedPortals.delete(e),this.trackedPortals.set(t,{...n,element:t}))}contains(e){for(let[t]of this.trackedPortals)if(t===e||t.contains(e))return!0;return!1}elements(){return Array.from(this.trackedPortals.keys())}destroyAll(){for(let[,e]of this.trackedPortals)e.element.parentNode&&e.element.remove(),e.placeholder.parentNode&&e.placeholder.remove();this.trackedPortals.clear()}};var tt=class{registeredResetForms=new Set;applyControlledSelectValue(e,t){if(e.multiple){let r=new Set(this.normalizeControlledSelectValues(t));for(let i=0;i<e.options.length;i++){let o=e.options[i],s=r.has(o.value);o.selected!==s&&(o.selected=s)}return}let n=t==null?"":String(t);e.value!==n&&(e.value=n)}applyControlledInputValue(e,t){let n=t==null?"":String(t);if(this.shouldDeferFocusedDateLikeInputValue(e,n)){this.deferFocusedControlledInputValue(e,t);return}this.shouldDeferActiveNativeTextInputValue(e,n)||e.value!==n&&(e.value=n)}bindControlledSelectValues(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(!(r instanceof HTMLSelectElement))continue;let i=this.resolveControlledSelectCaptureId(r,t);i&&(Ie(r,"controlled"),this.applyControlledSelectValue(r,t.get(i)))}}bindControlledInputValues(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(!(r instanceof HTMLInputElement))continue;let i=this.resolveControlledInputValue(r,t);i.hasValue&&(Ie(r,"controlled"),this.applyControlledInputValue(r,i.value))}}bindControlledCheckedValues(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(!(r instanceof HTMLInputElement))continue;let i=this.resolveControlledCheckedValue(r,t);if(!i.hasValue)continue;Ge(r,"controlled");let o=!!i.value;r.checked!==o&&(r.checked=o)}}applyUncontrolledDefaultValue(e,t){if(e instanceof HTMLSelectElement){this.applyUncontrolledDefaultSelectValue(e,t);return}let n=t==null?"":String(t);Ie(e,"uncontrolled"),e.defaultValue!==n&&(e.defaultValue=n),e.value!==n&&(e.value=n),e.__ppHasUncontrolledDefaultValue=!0}applyUncontrolledDefaultChecked(e,t){let n=this.normalizeDefaultCheckedValue(t);Ge(e,"uncontrolled"),e.defaultChecked!==n&&(e.defaultChecked=n),e.checked!==n&&(e.checked=n),e.__ppHasUncontrolledDefaultChecked=!0}restoreUncontrolledSelectState(e){let t=Array.from(e.options);if(e.multiple){t.forEach(r=>{r.selected=r.defaultSelected});return}let n=t.find(r=>r.defaultSelected);if(n){e.value=n.value;return}t.length>0&&(e.selectedIndex=0)}isUncontrolledResetManagedElement(e){let t=e;return t.__ppHasUncontrolledDefaultValue||t.__ppHasUncontrolledDefaultChecked?!0:e instanceof HTMLSelectElement?Array.from(e.options).some(n=>n.defaultSelected):!1}syncUncontrolledFormResets(e,t,n){let r=new Set;for(let i=0;i<t.length;i++){let o=t[i];if(!o.__ppHasUncontrolledDefaultValue&&!o.__ppHasUncontrolledDefaultChecked&&!(o instanceof HTMLSelectElement))continue;let s=o.closest("form");s instanceof HTMLFormElement&&this.isUncontrolledResetManagedElement(o)&&(r.add(s),this.registerResetHandler(s,e,()=>{this.restoreUncontrolledFormDefaults(s,n())}))}for(let i of this.registeredResetForms)r.has(i)||this.unregisterResetHandler(i,e);this.registeredResetForms=r}clearResetHandlers(e){for(let t of this.registeredResetForms)this.unregisterResetHandler(t,e);this.registeredResetForms.clear()}restoreUncontrolledFormDefaults(e,t){for(let n=0;n<t.length;n++){let r=t[n],i=r;if(r.closest("form")===e){if(r instanceof HTMLSelectElement){this.restoreUncontrolledSelectState(r);continue}(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement)&&i.__ppHasUncontrolledDefaultValue&&(r.value=r.defaultValue),r instanceof HTMLInputElement&&i.__ppHasUncontrolledDefaultChecked&&(r.checked=r.defaultChecked)}}}resolveDefaultValueBinding(e,t){let n=e.getAttribute("data-pp-default-value");if(n){if(e.removeAttribute("data-pp-default-value"),e.__ppDefaultValueCaptureId=n,t.has(n))return t.get(n)}else if(e.__ppDefaultValueCaptureId){if(t.has(e.__ppDefaultValueCaptureId))return t.get(e.__ppDefaultValueCaptureId);delete e.__ppDefaultValueCaptureId}if("__ppResolvedDefaultValue"in e)return e.__ppResolvedDefaultValue;if(e.hasAttribute("defaultvalue"))return e.getAttribute("defaultvalue")}resolveDefaultCheckedBinding(e,t){let n=e.getAttribute("data-pp-default-checked");if(n){if(e.removeAttribute("data-pp-default-checked"),e.__ppDefaultCheckedCaptureId=n,t.has(n))return t.get(n)}else if(e.__ppDefaultCheckedCaptureId){if(t.has(e.__ppDefaultCheckedCaptureId))return t.get(e.__ppDefaultCheckedCaptureId);delete e.__ppDefaultCheckedCaptureId}if("__ppResolvedDefaultChecked"in e)return e.__ppResolvedDefaultChecked;if(e.hasAttribute("defaultchecked"))return e.getAttribute("defaultchecked")}materializeNestedBoundaryFormDefaults(e,t){let n=e,r=e.getAttribute("data-pp-input-value")??n.__ppInputValueCaptureId;if(r&&t.inputValueStore.has(r)){let c=t.inputValueStore.get(r);if(e.removeAttribute("data-pp-input-value"),n.__ppInputValueCaptureId=r,n.__ppResolvedInputValue=c,e instanceof HTMLInputElement)this.applyControlledInputValue(e,c);else if(e instanceof HTMLSelectElement)this.applyControlledSelectValue(e,c);else if(e instanceof HTMLTextAreaElement){let u=c==null?"":String(c);e.value!==u&&(e.value=u)}}let i=e.getAttribute("data-pp-default-value");if(i&&t.defaultValueStore.has(i)&&(e.removeAttribute("data-pp-default-value"),e.__ppResolvedDefaultValue=t.defaultValueStore.get(i)),!(e instanceof HTMLInputElement))return;let o=e,s=e.getAttribute("data-pp-checked-value")??o.__ppCheckedValueCaptureId;if(s&&t.checkedValueStore.has(s)){let c=t.checkedValueStore.get(s);e.removeAttribute("data-pp-checked-value"),o.__ppCheckedValueCaptureId=s;let u=!!c;e.checked!==u&&(e.checked=u)}let a=e.getAttribute("data-pp-default-checked");a&&t.defaultCheckedStore.has(a)&&(e.removeAttribute("data-pp-default-checked"),e.__ppResolvedDefaultChecked=t.defaultCheckedStore.get(a))}normalizeControlledSelectValues(e){return e==null?[]:Array.isArray(e)?e.filter(t=>t!=null).map(t=>String(t)):[String(e)]}applyUncontrolledDefaultSelectValue(e,t){Ie(e,"uncontrolled");let n=this.normalizeControlledSelectValues(t),r=e.multiple?new Set(n):new Set(n.length>0?[n[0]]:[]);for(let i=0;i<e.options.length;i++){let o=e.options[i],s=o,a=r.has(o.value);o.defaultSelected!==a&&(o.defaultSelected=a),o.selected!==a&&(o.selected=a),a?s.__ppHasUncontrolledDefaultSelected=!0:delete s.__ppHasUncontrolledDefaultSelected}if(!e.multiple){let i=n.length>0?n[0]:"";e.value!==i&&(e.value=i)}}resolveControlledSelectCaptureId(e,t){let n=e.getAttribute("data-pp-select-value"),r=null;return n?(e.removeAttribute("data-pp-select-value"),e.__ppSelectValueCaptureId=n,r=n):e.__ppSelectValueCaptureId&&t.has(e.__ppSelectValueCaptureId)?r=e.__ppSelectValueCaptureId:e.__ppSelectValueCaptureId&&delete e.__ppSelectValueCaptureId,r}resolveControlledInputValue(e,t){let n=e.getAttribute("data-pp-input-value"),r,i=!1;return n?(e.removeAttribute("data-pp-input-value"),e.__ppInputValueCaptureId=n,t.has(n)&&(r=t.get(n),i=!0)):e.__ppInputValueCaptureId&&t.has(e.__ppInputValueCaptureId)?(r=t.get(e.__ppInputValueCaptureId),i=!0):"__ppResolvedInputValue"in e?(r=e.__ppResolvedInputValue,i=!0):e.__ppInputValueCaptureId&&delete e.__ppInputValueCaptureId,{hasValue:i,value:r}}resolveControlledCheckedValue(e,t){let n=e.getAttribute("data-pp-checked-value"),r,i=!1;if(n)e.removeAttribute("data-pp-checked-value"),e.__ppCheckedValueCaptureId=n,t.has(n)&&(r=t.get(n),i=r!=null);else{let o=e.__ppCheckedValueCaptureId;o&&t.has(o)?(r=t.get(o),i=r!=null):o&&delete e.__ppCheckedValueCaptureId}return{hasValue:i,value:r}}registerResetHandler(e,t,n){let r=e;r.__ppResetCallbacks||(r.__ppResetCallbacks=new Map),r.__ppResetCallbacks.set(t,n),!r.__ppOriginalReset&&(r.__ppOriginalReset=e.reset,e.reset=function(){r.__ppOriginalReset?.call(this),r.__ppResetCallbacks?.forEach((o,s)=>{if(!b.getInstance(s)&&s!==t){r.__ppResetCallbacks?.delete(s);return}o()})})}unregisterResetHandler(e,t){let n=e;n.__ppResetCallbacks?.delete(t),!(n.__ppResetCallbacks&&n.__ppResetCallbacks.size>0)&&(n.__ppOriginalReset&&(e.reset=n.__ppOriginalReset,delete n.__ppOriginalReset),delete n.__ppResetCallbacks)}normalizeDefaultCheckedValue(e){if(typeof e=="string"){let t=e.trim().toLowerCase();if(t===""||t==="true")return!0;if(t==="false"||t==="0"||t==="off"||t==="no")return!1}return!!e}shouldDeferFocusedDateLikeInputValue(e,t){return document.activeElement!==e||!ge(e)?!1:e.value!==t}shouldDeferActiveNativeTextInputValue(e,t){return document.activeElement!==e||!e.__ppPreserveNativeSelectionOnNextRender?!1:Le(e)&&e.value!==t}deferFocusedControlledInputValue(e,t){if(e.__ppDeferredControlledValue=t,e.__ppDeferredControlledBlurHandler)return;let n=()=>{let r=e.__ppDeferredControlledValue;if(delete e.__ppDeferredControlledValue,delete e.__ppDeferredControlledBlurHandler,!e.isConnected)return;let i=r==null?"":String(r);e.value!==i&&(e.value=i)};e.__ppDeferredControlledBlurHandler=n,e.addEventListener("blur",n,{once:!0})}};var nt=class{constructor(e,t,n,r,i){this.componentId=e;this.getParentId=t;this.isCurrentInstance=n;this.isRendering=r;this.forceUpdate=i}componentId;getParentId;isCurrentInstance;isRendering;forceUpdate;pendingProvidedContexts=new Map;pendingContextTokens=new Set;activeProviderBoundaryIds=new Set;refreshPending=!1;warnedContextOutsideRender=!1;prepareRender(){this.pendingProvidedContexts=new Map,this.pendingContextTokens=new Set}consume(e){return!this.isRendering()&&!this.warnedContextOutsideRender&&(this.warnedContextOutsideRender=!0,console.warn(`[PP-WARN] pp.context(...) should be called while component "${this.componentId}" is rendering. Move context reads to the component script body and pass values to event handlers through closure state.`)),this.pendingContextTokens.add(e),b.resolveContext(this.getParentId(),e).value}provide(e,t){this.pendingProvidedContexts.set(e,t)}commitRenderContexts(){let e=b.saveContextValues(this.componentId,this.pendingProvidedContexts);return b.updateContextDependencies(this.componentId,this.pendingContextTokens),e.length>0?b.getConsumersForContextsInSubtree(this.componentId,e):null}syncProviderBoundary(e,t,n,r){b.saveParent(e,t);let i=b.saveContextValues(e,new Map([[n,r]]));return i.length>0?b.getConsumersForContextsInSubtree(e,i):new Set}replaceActiveProviderBoundaries(e){let t=new Set;return this.activeProviderBoundaryIds.forEach(n=>{if(e.has(n))return;b.removeContextTracking(n)?.forEach(i=>t.add(i))}),this.activeProviderBoundaryIds=e,t}requestRefresh(){this.refreshPending||(this.refreshPending=!0,queueMicrotask(()=>{if(this.refreshPending=!1,!!this.isCurrentInstance()){if(this.isRendering()){this.requestRefresh();return}this.forceUpdate()}}))}refreshConsumers(e){for(let t of e)b.getInstance(t)?.requestContextRefresh?.()}destroy(){return this.activeProviderBoundaryIds.forEach(e=>{b.removeContextTracking(e)}),this.activeProviderBoundaryIds.clear(),b.removeContextTracking(this.componentId)}};var rt=class{constructor(e,t){this.getRoot=e;this.containsPortalElement=t}getRoot;containsPortalElement;save(e){let t=document.activeElement;if(!t)return null;let r=this.getRoot().contains(t),i=!r&&this.containsPortalElement(t);if(!r&&!i)return null;let s=e.indexOf(t);if(s===-1)return null;let a=this.getTextSelectionState(t);return{element:t,index:s,selectionStart:a.selectionStart,selectionEnd:a.selectionEnd}}restore(e,t){if(!e)return;let n=e.element,r=this.getRoot(),o=!!n&&n.isConnected&&(r.contains(n)||this.containsPortalElement(n))?n:t[e.index];if(!o)return;let s=o===document.activeElement,a=o;if(!(s&&o instanceof HTMLInputElement&&ge(o))&&(s||o.focus(),e.selectionStart!==null&&e.selectionEnd!==null&&Le(o))){if(s&&a.__ppPreserveNativeSelectionOnNextRender){delete a.__ppPreserveNativeSelectionOnNextRender;return}if(s&&o.selectionStart===e.selectionStart&&o.selectionEnd===e.selectionEnd)return;try{o.setSelectionRange(e.selectionStart,e.selectionEnd)}catch(c){console.warn("Could not restore cursor position",c)}}}getTextSelectionState(e){if(!Le(e))return{selectionStart:null,selectionEnd:null};try{return{selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}catch{return{selectionStart:null,selectionEnd:null}}}};var Dt="pp-keep",Ve="pp-keep-run",Lt="pp-loop-build",It=3,gn=/^[A-Za-z0-9_.:-]+$/,nr=/^\s*<([a-zA-Z][^\s/>]*)(?=[\s/>])[^>]*?\skey="([^"]*)"/,Bt=["pp-component","pp-owner","<pp-context-provider","<!--pp:","__PP_COMPONENT_","__PP_SCRIPT_","__PP_STYLE_"],rr=/<(?:input|textarea|select)\b|pp-ref/i,it="\0pp-patched",ir=0;function or(l){let e=[],t=(n,r)=>{let i=0;for(let o=n.firstElementChild;o;o=o.nextElementSibling){let s=[...r,i];o.tagName.toLowerCase()==="script"&&!o.hasAttribute("type")?e.push(s):t(o,s),i++}};return t(l,[]),e}function sr(l,e){let t=l;for(let n=0;n<e.length&&t!==null;n++){let r=t.firstElementChild;for(let i=e[n];i>0&&r!==null;i--)r=r.nextElementSibling;t=r}return t}var ue=new Map,_n=!0;function En(l){_n=l,l||ue.clear()}function vn(l,e,t){let n=ue.get(l);if(n===void 0||e.handedOver||!t||e.latestScope===null)return;let r=e.el;if(r.isConnected||r.parentNode!==null)return;let i=r.getAttribute("key");i===null||!n.index.has(i)||n.rows.has(i)||r[G]!==void 0&&n.rows.set(i,{record:e,state:t})}var ot=1;function ar(l,e){for(let t=0;t<Bt.length;t++)if(!(e&&Bt[t]==="pp-component")&&l.includes(Bt[t]))return!1;return!0}function st(l){return l.includes("<")||l.includes("&")?l.replace(/&/g,"&amp;").replace(/</g,"&lt;"):l}function yn(l){return l.includes("&")?A(l):l}function Re(l){return l!==null&&(typeof l=="object"||typeof l=="function"||typeof l=="symbol")}function Ht(l){if(l.slots.length>30)return null;let e=new Array(l.size).fill(0),t=0,n=[];return l.slots.forEach((r,i)=>{let o=1<<i;if(r.kind==="attr"){e[r.v]|=o;return}if(r.kind==="battr"){e[r.v]|=o,t|=o,n.push(r.v);return}for(let s of r.parts)typeof s=="number"&&(e[s]|=o)}),{key:l.key,slots:l.slots,size:l.size,slotBitsByValue:e,boundarySlotMask:t,boundaryValueIndices:n}}function Nt(l){return typeof l=="boolean"||l==null?"":String(l)}function ve(l,e,t,n,r=0){let i=e.slots.length;for(let o=0;o<i;o++){if((n&1<<o)===0)continue;let s=e.slots[o],a=l,c=s.p;for(let p=0;p<c.length&&a;p++)a=a.children[c[p]]??null;if(!a)return!1;if(s.kind==="battr"){let p=t[r+s.v],y=a[G];y&&(y[s.name]=p),typeof p=="boolean"?p?a.setAttribute(s.name,""):a.removeAttribute(s.name):p==null?a.removeAttribute(s.name):a.setAttribute(s.name,String(p));continue}if(s.kind==="attr"){let p=t[r+s.v];s.bool?(typeof p=="boolean"?p?a.setAttribute(s.name,""):a.removeAttribute(s.name):p==null||!p?a.removeAttribute(s.name):a.setAttribute(s.name,String(p)),s.name==="checked"&&a instanceof HTMLInputElement&&Ye(a,!!p)):a.setAttribute(s.name,typeof p=="boolean"?String(p):p==null?"":String(p));continue}if(s.kind==="attrParts"){let p=s.parts,f="";for(let y=0;y<p.length;y++){let m=p[y];f+=typeof m=="number"?Nt(t[r+m]):m}a.setAttribute(s.name,f);continue}let u=s.parts,h;if(u.length===1){let p=u[0];h=typeof p=="number"?Nt(t[r+p]):p}else{h="";for(let p=0;p<u.length;p++){let f=u[p];h+=typeof f=="number"?Nt(t[r+f]):f}}let d=a.firstChild;d!==null&&d.nodeType===Node.TEXT_NODE&&d.nextSibling===null&&h!==""?d.data=h:a.textContent=h}return!0}var at=class{loops=new Map;enabled=!0;patchingEnabled=!0;valuePatchSink=null;directBuildingEnabled=!0;pendingDirectBuilds=null;directChildDerivations=null;directPrototypes=null;preparedDirectMarkers=null;pendingReviveRegistrations=null;directScriptsToReactivate=null;emitted=0;pendingPatchGroups=null;structuralBoundaryChange=!1;setValuePatchSink(e){this.valuePatchSink=e}disable(){this.enabled=!1,this.loops.clear(),this.pendingPatchGroups=null,this.dropParkedGenerations()}disablePatching(){this.patchingEnabled=!1,this.pendingPatchGroups=null}disableDirectBuilding(){this.directBuildingEnabled=!1,this.pendingDirectBuilds=null,this.preparedDirectMarkers=null,this.directScriptsToReactivate=null,this.directChildDerivations=null,this.directPrototypes=null,this.dropParkedGenerations(),this.loops.clear()}clear(){this.loops.clear(),this.pendingPatchGroups=null,this.directChildDerivations=null,this.directPrototypes=null,this.dropParkedGenerations()}dropParkedGenerations(){if(this.pendingReviveRegistrations=null,ue.size!==0)for(let[e,t]of ue)t.owner===this&&ue.delete(e)}beginRender(){this.emitted=0,this.pendingPatchGroups=null,this.structuralBoundaryChange=!1,this.pendingDirectBuilds=null,this.preparedDirectMarkers=null,this.directScriptsToReactivate=null,this.pendingReviveRegistrations=null}prepareDirectBuilds(e){let t=this.pendingDirectBuilds;if(t===null||t.size===0)return!0;let n=new Map;for(let r of t.values()){let i=e.querySelectorAll(`[${Lt}="${r.loopId}"]`);if(i.length!==1)return!1;let o=i[0],s=Ot(o),a=o.parentElement;if(s===null||s.length!==r.keys.length||r.nodes.length!==r.keys.length||a===null||a.namespaceURI!=="http://www.w3.org/1999/xhtml"||o.tagName.toLowerCase()!==r.tag)return!1;for(let c=0;c<r.keys.length;c++){let u=r.nodes[c];if(s[c]!==r.keys[c]||u.parentNode!==null||u.tagName.toLowerCase()!==r.tag||u.getAttribute("key")!==r.keys[c])return!1}n.set(r.loopId,r.nodes)}return this.pendingDirectBuilds=null,this.preparedDirectMarkers=n,!0}hasPendingDirectBuilds(){return this.pendingDirectBuilds!==null&&this.pendingDirectBuilds.size>0}takeDirectBuild(e){let t=this.preparedDirectMarkers;if(t===null)return null;let n=e.getAttribute(Lt);if(n===null)return null;let r=Number(n);if(!Number.isSafeInteger(r))return null;let i=t.get(r)??null;if(i!==null){t.delete(r);let o=this.pendingReviveRegistrations?.get(r);if(o!==void 0){this.pendingReviveRegistrations.delete(r);for(let s=0;s<o.length;s++){let{record:a,state:c}=o[s];b.registerInstance(a.id,a),b.saveParent(a.id,a.parentId),b.saveState(a.id,c),b.saveScope(a.id,a.latestScope)}}}return i}finishDirectBuilds(){let e=this.preparedDirectMarkers,t=e===null||e.size===0;this.preparedDirectMarkers=null;let n=this.directScriptsToReactivate;if(this.directScriptsToReactivate=null,n)for(let r=0;r<n.length;r++)n[r].removeAttribute("type");return t}takeStructuralBoundaryChange(){let e=this.structuralBoundaryChange;return this.structuralBoundaryChange=!1,e}getEmittedCount(){return this.emitted}takePendingPatches(){let e=this.pendingPatchGroups;return this.pendingPatchGroups=null,e}commitPatches(e){for(let t of e)for(let n of t.patches)n.entry.html=n.html}render(e,t,n,r,i,o=0){if(e<0){if(!n)return t.join("");let s="";for(let a=0;a<t.length;a++)s+=n(t[a],a);return s}if(t.length===0)return(o&ot)!==0&&this.loops.has(e)&&(this.structuralBoundaryChange=!0,this.tryParkClosingLoop(e)),this.loops.delete(e),"";if(n){if(i&&r&&this.enabled&&this.directBuildingEnabled&&(!i.hasBoundary||i.rootBoundary===1&&(o&ot)!==0)&&!this.loops.has(e)){let a=this.tryDirectBuild(e,t,r,i,o);if(a!==null)return a}if(i&&r&&this.enabled&&this.patchingEnabled&&this.valuePatchSink!==null){let a=this.loops.get(e);if(a&&a.values!==null&&a.valueKeys!==null&&a.keyRawValues!==null&&a.entries.length===t.length&&!a.hasDuplicates&&a.allReusable){let c=this.tryValueLane(e,a,t,r,i);if(c!==null)return c}}let s=new Array(t.length);for(let a=0;a<t.length;a++)s[a]=n(t[a],a);return this.renderRows(e,s,!0,i&&r?{items:t,valuesFn:r,plan:i}:null,o)}return this.renderRows(e,t,!1,null,0)}tryParkClosingLoop(e){if(!_n||!this.enabled||!this.directBuildingEnabled)return;let t=this.loops.get(e),n=this.directChildDerivations?.get(e),r=this.directPrototypes?.get(e);if(n===void 0||r===void 0||t.plan===null||t.values===null||t.valueKeys===null||t.keyRawValues===null||t.hasDuplicates)return;let i=t.valueKeys,o=new Map;for(let s=0;s<i.length;s++)o.set(i[s],s);ue.set(n,{owner:this,prototypeHtml:r.html,contextTag:r.contextTag,index:o,values:t.values,size:t.plan.size,rows:new Map})}takeParkedGeneration(e){if(ue.size===0)return null;let t=this.directChildDerivations?.get(e);if(t===void 0)return null;let n=ue.get(t);return n===void 0?null:(ue.delete(t),n.owner===this?n:null)}tryReviveRow(e,t,n,r,i,o){let s=e.rows.get(t);if(s===void 0)return null;e.rows.delete(t);let a=s.record,c=a.el,u=e.index.get(t),h=c[G];if(a.latestScope===null||u===void 0||h===void 0||c.isConnected||c.parentNode!==null||c.getAttribute("key")!==t||b.getInstance(a.id)!==void 0||b.getState(a.id)!==void 0)return null;let d=0,p=u*e.size;for(let f=0;f<e.size;f++)Object.is(r[i+f],e.values[p+f])||(d|=o.slotBitsByValue[f]);return d!==0&&!ve(c,o,r,d,i)?null:(Object.is(h.key,n)||(h.key=n),s)}tryDirectBuild(e,t,n,r,i){let o=t.length;if(o<It||!r.prototypeHtml)return null;let s=this.directPrototypes?.get(e),a,c;if(s!==void 0&&s.html===r.prototypeHtml&&s.contextTag===r.contextTag)a=s.prepared,c=s.prototype;else{let w=Ht(r);if(w===null)return null;let x=le(r.prototypeHtml,r.contextTag),B=null;for(let N=x.root.firstChild;N;N=N.nextSibling){if(N.nodeType===Node.ELEMENT_NODE){if(B!==null)return null;B=N;continue}if(!(N.nodeType===Node.TEXT_NODE&&N.data.trim()===""))return null}if(B===null)return null;a=w,c=B,(this.directPrototypes??=new Map).set(e,{html:r.prototypeHtml,contextTag:r.contextTag,prototype:c,prepared:a,scriptPaths:r.rootBoundary===1?or(B):[]})}let u=r.rootBoundary===1?this.directPrototypes.get(e).scriptPaths:null,h=a.slots.length===0?0:(1<<a.slots.length)-1,d=new Array(o*a.size),p=new Array(o),f=new Array(o),y=new Array(o),m=new Set,g=null;if(r.rootBoundary===1){let w=!0;for(let x=0;x<a.slots.length;x++)if(a.slots[x].p.length!==0){w=!1;break}if(w){let x=this.directChildDerivations??=new Map;g=x.get(e)??null,g===null&&(g={childHtml:null,hasScript:!1,mintKey:++ir,propsSchema:null,blueprint:null,scriptPath:null,stringlessMounted:!1,flyweight:null},x.set(e,g))}}let E=null;if(r.rootBoundary===1){let w=this.takeParkedGeneration(e);w!==null&&w.rows.size!==0&&w.prototypeHtml===r.prototypeHtml&&w.contextTag===r.contextTag&&w.size===a.size&&(E=w)}let _=null;try{for(let w=0;w<o;w++){let x=w*a.size;if(n(t[w],w,d,x)!==d)return null;for(let D=0;D<a.size;D++)if(Re(d[x+D]))return null;let N=d[x+a.key];if(Re(N))return null;let X=N==null?"":String(N);if(!X||!gn.test(X)||m.has(X))return null;m.add(X);let q=null;if(E!==null){let D=this.tryReviveRow(E,X,N,d,x,a);D!==null&&(q=D.record.el,(_??=[]).push(D))}if(q===null){if(q=c.cloneNode(!0),r.rootBoundary===1){let D=Object.create(null);D.key=N,q[G]=D,g!==null&&(q[ee]=g)}if(!ve(q,a,d,h,x))return null;if(q.setAttribute("key",X),u!==null)for(let D=0;D<u.length;D++){let oe=sr(q,u[D]);if(oe===null)return null;oe.setAttribute("type","application/pp"),(this.directScriptsToReactivate??=[]).push(oe)}}p[w]=X,f[w]=N,y[w]=q}}catch{return null}let v=c.tagName.toLowerCase(),S=new Array(o),T=new Map;for(let w=0;w<o;w++){let x={html:it,key:p[w],tag:v,reusable:!0,simpleKey:!0,patchSafe:!0};S[w]=x,T.set(p[w],x)}let C=p.join(","),P=`<${v} ${Ve}="${C}" key="${p[0]}" ${Lt}="${e}"></${v}>`;return this.loops.set(e,{entries:S,byKey:T,hasDuplicates:!1,allReusable:!0,keepEmission:P,values:d,valueKeys:p.slice(),keyRawValues:f,plan:a}),r.rootBoundary===1&&(i&ot)!==0&&(this.structuralBoundaryChange=!0),(this.pendingDirectBuilds??=new Map).set(e,{loopId:e,tag:v,keys:p,nodes:y}),_!==null&&(this.pendingReviveRegistrations??=new Map).set(e,_),P}tryValueLane(e,t,n,r,i){let o=t.plan??=Ht(i);if(o===null)return null;let s=n.length,a=t.values,c=t.valueKeys,u=t.keyRawValues,h=o.size,d=new Array(s*h),p=o.slotBitsByValue,f=o.boundaryValueIndices,y=o.boundarySlotMask,m=this.valuePatchSink,g;for(let E=0;E<s;E++){let _=E*h;if(r(n[E],E,d,_)!==d)return null;let v=d[_+o.key],S=!1;if(!Object.is(v,u[E])){if(Re(v)||String(v)!==c[E])return null;S=i.rootBoundary===1,u[E]=v}let T=0;for(let C=0;C<f.length;C++)if(Re(d[_+f[C]]))return null;for(let C=0;C<h;C++){let P=d[_+C];if(!Object.is(P,a[_+C])){if(Re(P)||(p[C]&y)!==0&&typeof P=="string"&&(P.includes("{")||P.includes("}")))return null;T|=p[C]}}if(T!==0||S){let C=c[E];if(g===void 0&&(g=m.begin(e,C,y!==0||S)),g===null)return this.abandonValuePatching(m);let P=g.index.get(C);if(P===void 0||P.parentNode!==g.container)return this.abandonValuePatching(m);if(T!==0&&!ve(P,o,d,T,_))return this.abandonValuePatching(m);let w=!1;if(S){let x=P[G];x&&(x.key=v,w=!0)}((T&y)!==0||w)&&m.onBoundaryRowPatched(P),(T!==0||w)&&this.poisonEntryAt(t,E)}}return t.values=d,this.emitted+=s,t.keepEmission??=this.buildKeepEmission(t.entries)}abandonValuePatching(e){return e.reportPatchAbandoned(),this.disablePatching(),null}poisonEntryAt(e,t){let n=e.entries[t];if(n.html===it)return;let r={...n,html:it};e.entries[t]=r,r.key!==null&&e.byKey.set(r.key,r)}buildKeepEmission(e){let t=e.length,n="",r=0;for(;r<t;){let i=e[r],o=r;for(;o<t&&e[o].simpleKey;)o++;if(o-r>=It){let s=e[r].key;for(let a=r+1;a<o;a++)s+=","+e[a].key;n+=`<${i.tag} ${Ve}="${s}" key="${st(i.key)}"></${i.tag}>`,r=o;continue}n+=`<${i.tag} ${Dt} key="${st(i.key)}"></${i.tag}>`,r++}return n}renderRows(e,t,n,r,i){let o=(i&ot)!==0,s=this.loops.get(e),a=s?.entries,c=s?.byKey,u=t.length,h=new Array(u),d=new Array(u),p=a===void 0||a.length!==u,f=!0;for(let v=0;v<u;v++){let S=t[v],T=a!==void 0?a[v]:void 0;if(T!==void 0&&T.html===S){h[v]=T,d[v]=!0,T.reusable||(f=!1);continue}let C=nr.exec(S),P=C!==null&&C[2].length>0?C[2]:null,w;if(P!==null&&c!==void 0){let x=c.get(P);x!==void 0&&x.html===S&&(w=x)}if(w===void 0){let x=P!==null&&ar(S,o);w={html:S,key:P,tag:C!==null?C[1]:"",reusable:x,simpleKey:P!==null&&gn.test(P),patchSafe:x&&!rr.test(S)},d[v]=!1}else d[v]=!0;w.reusable||(f=!1),h[v]=w,(T===void 0||T.key!==P)&&(p=!0)}o&&p&&a!==void 0&&(this.structuralBoundaryChange=!0);let y;if(!p&&s!==void 0)y=s.hasDuplicates;else{let v=new Set;y=!1;for(let S=0;S<u;S++){let T=h[S].key;if(T!==null){if(v.has(T)){y=!0;break}v.add(T)}}}if(y)return this.loops.delete(e),t.join("");let m;if(p||c===void 0){m=new Map;for(let v=0;v<u;v++){let S=h[v].key;S!==null&&m.set(S,h[v])}}else{m=c;for(let v=0;v<u;v++){let S=h[v];S!==a[v]&&S.key!==null&&m.set(S.key,S)}}let g={entries:h,byKey:m,hasDuplicates:y,allReusable:f,keepEmission:!p&&s!==void 0?s.keepEmission:null,values:null,valueKeys:null,keyRawValues:null,plan:s?.plan??null};if(n&&this.enabled&&this.patchingEnabled&&s!==void 0&&!p&&f&&u>0){let v=null,S=!0;for(let T=0;T<u;T++)if(!d[T]){if(!h[T].patchSafe){S=!1;break}(v??=[]).push({key:yn(h[T].key),html:t[T],entry:h[T]})}if(S){if(v!==null){for(let T of v)T.entry.html=it;(this.pendingPatchGroups??=[]).push({loopId:e,patches:v})}return this.seedValueLane(g,r),this.loops.set(e,g),this.emitted+=u,g.keepEmission??=this.buildKeepEmission(h)}}let E="",_=0;for(;_<u;){let v=h[_];if(!this.enabled||!d[_]||!v.reusable){E+=t[_],_++;continue}let S=_;for(;S<u&&d[S]&&h[S].reusable&&h[S].simpleKey;)S++;if(S-_>=It){let T=h[_].key;for(let C=_+1;C<S;C++)T+=","+h[C].key;E+=`<${v.tag} ${Ve}="${T}" key="${st(v.key)}"></${v.tag}>`,this.emitted+=S-_,_=S;continue}this.emitted++,E+=`<${v.tag} ${Dt} key="${st(v.key)}"></${v.tag}>`,_++}return this.loops.set(e,g),E}seedValueLane(e,t){if(t===null||!e.allReusable)return;let n=e.plan??=Ht(t.plan);if(n===null)return;let{items:r,valuesFn:i}=t,o=r.length,s=new Array(o*n.size),a=new Array(o),c=new Array(o);for(let u=0;u<o;u++){let h=u*n.size;if(i(r[u],u,s,h)!==s)return;for(let p=0;p<n.boundaryValueIndices.length;p++)if(Re(s[h+n.boundaryValueIndices[p]]))return;c[u]=s[h+n.key];let d=e.entries[u].key;if(d===null)return;a[u]=yn(d)}e.values=s,e.valueKeys=a,e.keyRawValues=c}};function lt(l){if(l.nodeType!==Node.ELEMENT_NODE)return!1;let e=l;return e.hasAttribute(Dt)||e.hasAttribute(Ve)}function Ot(l){if(l.nodeType!==Node.ELEMENT_NODE)return null;let e=l.getAttribute(Ve);return e===null?null:e.split(",")}var ct=class{constructor(e){this.options=e}options;morphPatchedRow(e,t,n){return t.tagName!==n.tagName?(e.replaceChild(n,t),this.options.collectEventElements(n),n):(this.morphCompatibleElement(e,t,n),t)}morphChildren(e,t){if(t.firstChild===null){if(e.firstChild===null)return;delete e.__ppLoopKeyIndex;let o=e.firstChild;for(;o!==null;){let s=o.nextSibling;e.removeChild(o),o=s}return}if(this.hasKeyedDirectChildren(e)||this.hasKeyedDirectChildren(t)){this.morphKeyedChildren(e,t);return}let n=this.options.canSkipEqualSubtrees?.()??!1,r=e.firstChild,i=t.firstChild;for(;r||i;){let o=r?.nextSibling??null,s=i?.nextSibling??null;if(!i){r&&e.removeChild(r),r=o;continue}if(!r){e.appendChild(i),i.nodeType===Node.ELEMENT_NODE&&this.options.collectEventElements(i),i=s;continue}if(r.nodeType!==i.nodeType){e.replaceChild(i,r),i.nodeType===Node.ELEMENT_NODE&&this.options.collectEventElements(i),r=o,i=s;continue}if(r.nodeType===Node.TEXT_NODE){r.textContent!==i.textContent&&(r.textContent=i.textContent),r=o,i=s;continue}r.nodeType===Node.ELEMENT_NODE&&(r.firstElementChild!==null&&r.isEqualNode(i)?n||this.options.collectEventElements(r):this.morphCompatibleElement(e,r,i)),r=o,i=s}}morphCompatibleElement(e,t,n){if(t.tagName!==n.tagName){e.replaceChild(n,t),this.options.collectEventElements(n);return}if(V(t)&&t!==this.options.root){let o=n.hasAttribute(De);if(o&&n.removeAttribute(De),t.firstChild===null&&n.firstChild!==null&&this.options.shouldForceChildRefresh?.()){e.replaceChild(n,t),this.options.collectEventElements(n);return}if(!o&&n.firstChild!==null&&this.options.ownsBoundaryContent?.(t,n)){t.replaceChildren(...Array.from(n.childNodes)),this.options.syncAttributes(t,n),this.options.collectEventElements(t);return}if(!this.options.syncNestedBoundaryAttributes(t,n)){e.replaceChild(n,t),this.options.collectEventElements(n);return}o&&t.firstChild!==null&&this.options.onBoundaryKeepResolved?.(),this.options.hasEventAttributes(t)&&this.options.collectEventElements(t);return}if(this.options.syncAttributes(t,n),this.options.hasEventAttributes(t)&&this.options.collectEventElements(t),t instanceof HTMLTextAreaElement)return;let r=t.firstChild,i=n.firstChild;if(r?.nodeType===Node.TEXT_NODE&&i?.nodeType===Node.TEXT_NODE&&r.nextSibling===null&&i.nextSibling===null){r.nodeValue!==i.nodeValue&&(r.nodeValue=i.nodeValue);return}this.morphChildren(t,n)}hasKeyedDirectChildren(e){let t=e.firstElementChild;for(;t;){if(this.getElementKey(t)!==null)return!0;t=t.nextElementSibling}return!1}getNodeKey(e){return e.nodeType!==Node.ELEMENT_NODE?null:this.getElementKey(e)}getElementKey(e){let t=e.getAttribute("key");return t&&t.length>0?t:null}readLeafText(e){if(e.nodeType===Node.TEXT_NODE||e.nodeType===Node.COMMENT_NODE)return e.nodeValue;let t=e.firstChild;return t===null?"":t.nodeType===Node.TEXT_NODE&&t.nextSibling===null?t.nodeValue:e.textContent}areKeyedNodesCompatible(e,t){return e.nodeType!==t.nodeType?!1:e.nodeType!==Node.ELEMENT_NODE?!0:e.tagName===t.tagName}areNodesCompatible(e,t){if(e.nodeType!==t.nodeType)return!1;if(e.nodeType!==Node.ELEMENT_NODE)return!0;let n=e,r=t;if(n.tagName!==r.tagName)return!1;let i=this.getNodeKey(e),o=this.getNodeKey(t);return i!==null||o!==null?i!==null&&i===o:!0}morphKeyedChildren(e,t){e.__ppLoopKeyIndex=void 0;let n=[],r=[];for(let m=e.firstChild;m;m=m.nextSibling)n.push(m),r.push(this.getNodeKey(m));let i=[],o=[],s=null,a=null;for(let m=t.firstChild;m;m=m.nextSibling){let g=this.getNodeKey(m);i.push(m),o.push(g),g!==null&&(s===null&&(s=new Set),s.has(g)?(a??=new Set).add(g):s.add(g))}let c=new Map,u=new Set,h=new Map;a!==null&&console.warn(`[PP-WARN] Duplicate key values detected: ${Array.from(a).join(", ")}`);let d=m=>{u.add(m);let g=this.getUnkeyedNodeSignature(m),E=h.get(g);E?E.push(m):h.set(g,[m])},p=m=>{let g=this.getUnkeyedNodeSignature(m),E=h.get(g);for(;E&&E.length>0;){let _=E.shift();if(u.delete(_),this.areNodesCompatible(_,m))return E.length===0&&h.delete(g),_}h.delete(g)};for(let m=0;m<n.length;m++){let g=n[m],E=r[m];if(E===null){d(g);continue}let _=c.get(E);_?_.push(g):c.set(E,[g])}let f=e.firstChild,y=this.options.hasKeepPlaceholders?.()??!1;for(let m=0;m<i.length;m++){let g=i[m],E=o[m],_;if(g.nodeType===Node.ELEMENT_NODE){let T=this.options.takeDirectBuild?.(g);if(T){let C=document.createDocumentFragment();for(let w=0;w<T.length;w++)C.appendChild(T[w]);let P=T[T.length-1];e.insertBefore(C,f),f=P.nextSibling;continue}}if(y){let T=Ot(g);if(T!==null){for(let C=0;C<T.length;C++){let P=c.get(T[C]),w=P&&P.length>0?P.shift():void 0;if(!w||lt(w)){w&&d(w);continue}w!==f&&e.insertBefore(w,f),f=w.nextSibling,this.options.onKeepResolved?.()}continue}}if(y&&E!==null&&lt(g)){let T=c.get(E),C=T&&T.length>0?T.shift():void 0;if(!C||lt(C)){C&&d(C);continue}C!==f&&e.insertBefore(C,f),f=C.nextSibling,this.options.onKeepResolved?.();continue}if(E!==null){let T=c.get(E);for(;T&&T.length>0;){let C=T.shift();if(this.areKeyedNodesCompatible(C,g)){_=C;break}d(C)}}else _=p(g);_?_!==f&&e.insertBefore(_,f):(e.insertBefore(g,f),g.nodeType===Node.ELEMENT_NODE&&this.options.collectEventElements(g),_=g);let v=_.nodeType!==Node.ELEMENT_NODE||!_.firstElementChild&&!this.options.hasEventAttributes(_),S=v&&this.readLeafText(_)===this.readLeafText(g);(!v||!S||!_.isEqualNode(g))&&this.morphNode(_,g),f=_.nextSibling}u.forEach(m=>{m.parentNode===e&&e.removeChild(m)}),c.forEach(m=>{m.forEach(g=>{g.parentNode===e&&e.removeChild(g)})})}getUnkeyedNodeSignature(e){return e.nodeType!==Node.ELEMENT_NODE?`node:${e.nodeType}`:`element:${e.tagName}`}morphNode(e,t){if(e.nodeType!==t.nodeType){let o=e.parentNode;if(!o)return;o.replaceChild(t,e),t.nodeType===Node.ELEMENT_NODE&&this.options.collectEventElements(t);return}if(e.nodeType===Node.TEXT_NODE){e.textContent!==t.textContent&&(e.textContent=t.textContent);return}if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e,r=t,i=n.parentNode;i&&this.morphCompatibleElement(i,n,r)}};var ke=class l{constructor(e){this.componentId=e}componentId;static ownedRenderCache=new WeakMap;static ownerScopeViews=new WeakMap;static MAX_OWNED_EXPANSION_DEPTH=32;static MAX_OWNED_PLACEHOLDER_LENGTH=220;static HOST_HELPER_NAMES=new Set(["__pp_input_value","__pp_select_value","__pp_checked_value","__pp_default_value","__pp_default_checked"]);ownerScopeRecords=[];haveOwnerScopeIdentitiesChanged(){for(let e of this.ownerScopeRecords)if((b.getResolvedScopeWithAncestors(e.ownerId,e.relativeTo)??null)!==e.scope)return!0;return!1}extractOwnedTemplates(e,t){let n=new Map,r=e.querySelectorAll("template[pp-owner]"),i=0;return r.forEach(o=>{if(t){let h=o.getAttribute("pp-owner");h&&t(h)}if((o.parentElement?he(o.parentElement):null)!==e)return;let a=o.getAttribute("pp-owner");if(!a)return;o.content.querySelectorAll("script:not([type])").forEach(h=>{h.parentElement?.closest(Te)||h.remove()});let u=`__PP_OWNED_${this.componentId}_${i++}__`;n.set(u,{ownerId:a,content:o.innerHTML,contextTag:o.parentElement?.tagName.toLowerCase()??null}),o.replaceWith(document.createComment(u))}),n}resolveOwnedChildren(e,t){return this.ownerScopeRecords.length=0,e.includes("__PP_OWNED_")?(t.forEach(n=>{let r=this.resolveOwnedTemplateOwner(n.ownerId);this.ownerScopeRecords.push({ownerId:n.ownerId,relativeTo:this.componentId,scope:r?r.scope:null})}),this.expandOwnedPlaceholders(e,t,0)):e}expandOwnedPlaceholders(e,t,n){if(!e.includes("__PP_OWNED_"))return e;if(n>=l.MAX_OWNED_EXPANSION_DEPTH)return console.warn(`[PP-WARN] Owned template expansion exceeded ${l.MAX_OWNED_EXPANSION_DEPTH} levels for component "${this.componentId}". A slot's content may reference its own placeholder.`),e;let r="__PP_OWNED_",i="",o=0,s=!1,a=0,c;for(;(c=e.indexOf(r,a))!==-1;){let u=Math.min(e.length,c+l.MAX_OWNED_PLACEHOLDER_LENGTH),h=-1,d=null,p=null;for(let E=e.indexOf("__",c+r.length);E!==-1&&E+2<=u;E=e.indexOf("__",E+1)){let _=E+2,v=e.slice(c,_),S=/_(\d+)__$/.exec(v);if(!S||S.index<r.length)continue;let T=t.get(v);if(T){h=_,d=T,p=null;continue}let C=v.slice(r.length,S.index);if(!C)continue;let P=b.getOwnedTemplates(C)?.get(v);P&&(h=_,d=P,p=C)}if(d===null){a=c+r.length;continue}let f=p===null?this.resolveOwnedTemplateOwner(d.ownerId):this.resolveOwnedTemplateOwner(d.ownerId,p);p!==null&&this.ownerScopeRecords.push({ownerId:d.ownerId,relativeTo:p,scope:f?f.scope:null});let y=f?this.renderOwnedContent(d,f.ownerId,f.scope):d.content,m=c,g=h;m>=4&&e.startsWith("<!--",m-4)&&e.startsWith("-->",g)&&(m-=4,g+=3),i+=e.slice(o,m),i+=this.expandOwnedPlaceholders(y,t,n+1),o=g,a=g,s=!0}return s?i+e.slice(o):e}maskNestedOwnedTemplates(e,t){if(!e.includes("pp-owner"))return{content:e,placeholders:new Map};let n=new Map,r=le(e,t),i=0,o=r.root.querySelectorAll(`${Te} > template[pp-owner]`);for(let s of Array.from(o)){let a=`__PP_NESTED_TPL_${i++}__`;n.set(a,s.outerHTML),s.replaceWith(document.createComment(a))}return{content:r.toHtml(),placeholders:n}}materializeTemplateComponentBoundaries(e){l.materializeTemplateComponentBoundaries(e)}static materializeTemplateComponentBoundaries(e){let t=[];e instanceof HTMLTemplateElement&&e.hasAttribute(j)&&t.push(e),e.querySelectorAll(`template${Te}`).forEach(n=>t.push(n)),t.forEach(n=>{let r=n.content.cloneNode(!0);Oe(r);let i=r.firstElementChild;if(!i){n.replaceWith(document.createComment("pp-empty-template-component"));return}let o=n.getAttribute(j),s=i.getAttribute(j);if(o!==null&&s!==null&&s!==o){let a=document.createElement(Tt);a.style.display="contents",Array.from(n.attributes).forEach(c=>{c.name!=="pp-owner"&&a.setAttribute(c.name,c.value)}),a.appendChild(r),n.replaceWith(a);return}Array.from(n.attributes).forEach(a=>{a.name!=="pp-owner"&&i.setAttribute(a.name,a.value)}),n.replaceWith(r)})}static restoreNestedTemplatePlaceholders(e,t){if(t.size===0||!e.includes("__PP_NESTED_TPL_"))return e;let n=/<!--(__PP_NESTED_TPL_\d+__)-->|(__PP_NESTED_TPL_\d+__)/g;return e.replace(n,(r,i,o)=>{let s=t.get(i??o);return s!==void 0?s:r})}renderOwnedContent(e,t,n){let r=l.ownerScopeViews.get(n);if(!r){let d=_e(n).keys.filter(p=>p!=="__pp_boundary_html"&&p!=="__pp_loop_rows");r={keys:d,keysSig:d.join(" ")},l.ownerScopeViews.set(n,r)}let i=b.getScope(this.componentId),o=r.keys,s=new Array(o.length);for(let d=0;d<o.length;d++){let p=o[d],f=i&&l.HOST_HELPER_NAMES.has(p)?i[p]:void 0;s[d]=typeof f=="function"?f:n[p]}let a=r.keysSig,c=l.ownedRenderCache.get(e);if(!c||c.keysSig!==a){let d=this.maskNestedOwnedTemplates(e.content,e.contextTag),p=pn(e.contextTag);c={keysSig:a,compiledFn:ce.compile(p.wrap(d.content),o),nestedPlaceholders:d.placeholders,wrapper:p},l.ownedRenderCache.set(e,c)}let u=l.restoreNestedTemplatePlaceholders(c.wrapper.unwrap(c.compiledFn(...s)),c.nestedPlaceholders);if(c.markedIn===u&&c.markedOwnerId===t&&c.markedOut!==void 0)return c.markedOut;let h=this.markOwnedBindings(u,t,e.contextTag);return c.markedIn=u,c.markedOwnerId=t,c.markedOut=h,h}resolveOwnedTemplateOwner(e,t=this.componentId){let n=b.resolveComponentId(e,t);if(!n)return null;let r=b.getResolvedScopeWithAncestors(e,t);return r?{ownerId:n,scope:r}:null}markOwnedBindings(e,t,n=null){if(!e.includes("data-pp-ref")&&!/[\s/]on[a-zA-Z]+\s*=/.test(e))return e;let r=le(e,n),o=[...r.root instanceof DocumentFragment?Array.from(r.root.children):[r.root]].reverse();for(;o.length>0;){let s=o.pop();if(Array.from(s.attributes).some(c=>W(c.name,s))&&s.setAttribute("pp-event-owner",t),s.hasAttribute("data-pp-ref")&&s.setAttribute("pp-ref-owner",t),!V(s))for(let c=s.lastElementChild;c;c=c.previousElementSibling)o.push(c)}return r.toHtml()}};var ut=class{constructor(e,t){this.componentId=e;this.getCachedFunction=t}componentId;getCachedFunction;interpolationCache=null;scopeEvalCache=null;propEvalCache=null;interpolateAttrString(e,t,n){let r=n??He(t),i=r.keys,o=r.values,s=r.keySig;return cn(e,(a,c)=>{let u=A(a);if(!U.isValidExpression(u))return`{${c}}`;try{let d=this.getCachedFunction(this.interpolationCache??=new Map,u,i,s,300)(...o);return typeof d=="boolean"||d==null?"":Array.isArray(d)?d.join(""):String(d)}catch(h){return console.warn(`[PP-WARN] Failed attribute interpolation for {${u}}`,h),""}})}applyBoundaryBindings(e,t,n,r){for(let i in t){if(r?.(i))continue;let o=t[i],s=this.resolveBoundaryAttributeValue(i,o,n);if(s===null){e.hasAttribute(i)&&e.removeAttribute(i);continue}e.getAttribute(i)!==s&&e.setAttribute(i,s)}}resolveBoundaryAttributeValue(e,t,n){let r=z(t);if(!r)return this.interpolateAttrString(t,n.scope,n);let i=A(r.expression);if(!U.isValidExpression(i))return t;let o;try{o=this.getCachedFunction(this.scopeEvalCache??=new Map,i,n.keys,n.keySig,300)(...n.values)}catch(a){return console.error(`[PP-ERROR] Failed to eval "${i}"`,a),t}let s=typeof o;if(ye.has(e.toLowerCase())){if(s==="boolean")return o?"":null;if(!o&&(s==="string"||s==="number"||s==="bigint"))return null}return o==null?null:s==="string"||s==="number"||s==="boolean"||s==="bigint"?String(o):t}computePropsFromAttributes(e,t,n){let r=n;if(!r&&t){let f=b.getResolvedScopeWithAncestors(t,this.componentId);f&&(r=He(f))}let i=r?.scope,o=r?.keys??[],s=r?.values??[],a=e.__ppRawBindings,c=e.__ppLiteralAttrs,u=e[G],h=e.getAttributeNames();if(a)for(let f in a)h.includes(f)||h.push(f);if(u)for(let f in u)h.includes(f)||h.push(f);let d=r?.keySig??"",p={};for(let f=0;f<h.length;f++){let y=h[f];if(W(y,e)||y==="pp-component"||y.startsWith(ie))continue;let g=Be(y);if(ae.has(g))continue;if(u&&Object.prototype.hasOwnProperty.call(u,y)){p[g]=u[y];continue}let E=a?.[y],_=E!==void 0?E:e.getAttribute(y)??void 0;if(_!==void 0){if(_===""){p[g]=!0;continue}if(i&&!c?.has(y)){let v=z(_);if(v){let S=A(v.expression);if(U.isValidExpression(S)){p[g]=this.evalPropExpression(S,o,d,s);continue}}if(_.includes("{")){p[g]=this.interpolateAttrString(_,i);continue}}p[g]=_}}return p}evalPropExpression(e,t,n,r){try{return this.getCachedFunction(this.propEvalCache??=new Map,e,t,n,200)(...r)}catch(i){console.warn(`[PP-WARN] Failed to evaluate prop expression "{${e}}" for component "${this.componentId}"`,i);return}}};function dt(l){let e=l.getAttributeNames();for(let t=0;t<e.length;t++)if(W(e[t],l))return!0;return!1}var pt=class{constructor(e,t,n,r){this.getRoot=e;this.getPortalElements=t;this.refCaptureIdsByElement=n;this.refExprsByElement=r}getRoot;getPortalElements;refCaptureIdsByElement;refExprsByElement;cache=null;invalidate(){this.cache=null}getCache(){if(this.cache)return this.cache;let e=this.getRoot(),t=[],n=[],r=[],i=null,o=[],s=(a,c)=>{if(c){o.push(a);return}for(let u=a.lastElementChild;u;u=u.previousElementSibling)o.push(u)};s(e,!0);for(let a of this.getPortalElements())i??=new Set,s(a,!0);for(;o.length>0;){let a=o.pop();if(i){if(i.has(a))continue;i.add(a)}let c=a,u=a!==e&&V(a);if((a.hasAttribute("data-pp-ref")||a.hasAttribute("pp-ref")||this.refCaptureIdsByElement.has(c)||this.refExprsByElement.has(c))&&r.push(c),!u&&(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement)&&n.push(c),u){t.push(c);continue}for(let h=a.lastElementChild;h;h=h.previousElementSibling)o.push(h)}return this.cache={childBoundaries:t,managedInputs:n,refElements:r},this.cache}collectManagedInputs(){return this.getCache().managedInputs}collectEventElements(e,t){let n=this.getRoot();if(dt(e)&&t.add(e),!(e!==n&&V(e)))for(let r=e.firstElementChild;r;r=r.nextElementSibling)this.collectEventElements(r,t)}isManagedEventElement(e){if(this.isElementOwnedByTree(e,this.getRoot()))return!0;for(let t of this.getPortalElements())if(this.isElementOwnedByTree(e,t))return!0;return!1}isElementOwnedByTree(e,t){if(e===t)return!0;if(!t.contains(e))return!1;let n=e,r=!0;for(;n&&n!==t;){if(!r&&V(n))return!1;n=n.parentElement,r=!1}return n===t}};function lr(l){for(let e in l)return!0;return!1}var cr=Object.freeze({});function ur(l,e){let t=0;for(let r in l)if(t++,l[r]!==e[r])return!1;let n=0;for(let r in e)if(n++,n>t)return!1;return t===n}var ht=class{constructor(e){this.options=e}options;boundaryOccurrencesByBaseId=new Map;parentScopesByBoundaryId=new Map;materializeFormsThisPass=!0;bootstrap(){this.boundaryOccurrencesByBaseId.clear(),this.parentScopesByBoundaryId.clear(),this.materializeFormsThisPass=this.options.hasFormDefaultState();let e=new Set,t=new Set,n=new Set,r=(o,s)=>{for(let a=o.firstElementChild;a;a=a.nextElementSibling){let c=a;if(V(c)){let h=this.bootstrapComponentBoundary(c,s);h&&e.add(h);continue}let u=this.syncContextProviderBoundary(c,s,t,n);r(c,u??s)}};r(this.options.getRoot(),this.options.componentId);for(let o of this.options.getPortalElements())r(o,this.options.componentId);this.options.getContextManager().replaceActiveProviderBoundaries(t).forEach(o=>n.add(o)),n.size>0&&this.options.refreshContextConsumers(n),this.destroyDisconnectedDescendants(e)}refreshPatchedBoundaries(e){this.boundaryOccurrencesByBaseId.clear(),this.parentScopesByBoundaryId.clear(),this.materializeFormsThisPass=this.options.hasFormDefaultState();for(let t of e){if(V(t)){this.bootstrapComponentBoundary(t,this.options.componentId);continue}this.traversePatchedRow(t)}}traversePatchedRow(e){for(let t=e.firstElementChild;t;t=t.nextElementSibling){if(V(t)){this.bootstrapComponentBoundary(t,this.options.componentId);continue}this.traversePatchedRow(t)}}syncNestedBoundaryAttributes(e,t){let n=K(t),r=this.getBoundaryBaseId(e);if(!n||r&&n!==r)return!1;let i=e,o=t[G];o?i[G]=o:delete i[G];let s=this.collectRawBindings(t),a=s.bindings;i.__ppLiteralAttrs=s.literalAttrs;let c=i.__ppRawBindings,u=c!==void 0&&ur(c,a);return this.options.syncAttributes(e,t,!1,!0,u?a:void 0),i.__ppRawBindings=u?c:a,i.__ppRuntimeComponentId&&K(e)!==i.__ppRuntimeComponentId&&Ce(e,i.__ppRuntimeComponentId),this.refreshNestedOwnedChildren(e,t),!0}refreshNestedOwnedChildren(e,t){let r=e.__ppRuntimeComponentId??K(e);if(!r)return;b.getInstance(r)?.refreshOwnedChildrenFromElement?.(t)}getBoundaryScopeSignature(e,t){let n=[],r=e;for(;r;){let i=r.getAttribute("key");i&&i.length>0?n.unshift(`k:${i}`):n.unshift(`i:${this.getElementIndexWithinParent(r)}`);let o=r.parentElement;if(!o||V(o))break;r=o}return`${t}|${n.join("/")}`}getElementIndexWithinParent(e){let t=e.parentElement;if(!t)return 0;let n=t.children;for(let r=0;r<n.length;r++)if(n[r]===e)return r;return 0}hashScope(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33^e.charCodeAt(n);return(t>>>0).toString(36)}getBoundaryBaseId(e){let t=e,n=K(e);return!t.__ppBaseComponentId&&n&&(t.__ppBaseComponentId=n),t.__ppBaseComponentId??n}ensureBoundaryIdentity(e,t){let n=e,r=K(e)||"",i=0;if(r&&(i=(this.boundaryOccurrencesByBaseId.get(r)??0)+1,this.boundaryOccurrencesByBaseId.set(r,i)),n.__ppRuntimeComponentId)return r!==n.__ppRuntimeComponentId&&Ce(e,n.__ppRuntimeComponentId),n.__ppBaseComponentId||(n.__ppBaseComponentId=r||n.__ppRuntimeComponentId),n.__ppRuntimeComponentId;if(!r)return"";r.includes("{")&&!n.__ppWarnedDynamicComponentId&&(n.__ppWarnedDynamicComponentId=!0,console.warn(`[PP-WARN] Dynamic pp-component values are not supported. Component boundary ids are static; received "${r}". Use a stable pp-component id and pass dynamic values through props instead.`)),n.__ppBaseComponentId=r;let o,s=e[ee],a=s!==void 0?e.getAttribute("key"):null;s!==void 0&&a?o=`${r}__ppd${s.mintKey.toString(36)}x${a}`:i===1?o=r:o=`${r}__pp${this.hashScope(this.getBoundaryScopeSignature(e,t))}`;let c=b.getInstance(o);if(c&&c.el&&c.el!==e)if(!c.el.isConnected)c.destroy?.();else{let u=this.createUniqueCollisionId(o,i,e);return n.__ppRuntimeComponentId=u,Ce(e,u),u}return c===void 0&&b.getState(o)===void 0&&(n.__ppFreshIdentity=!0),n.__ppRuntimeComponentId=o,r!==o&&Ce(e,o),o}createUniqueCollisionId(e,t,n){let r=Math.max(t,1);for(;;){let i=r===1?`${e}_1`:`${e}_${r.toString(36)}`,o=b.getInstance(i);if(!o||!o.el||o.el===n)return i;if(!o.el.isConnected)return o.destroy?.(),i;r+=1}}bootstrapComponentBoundary(e,t){let n=e,r=this.ensureBoundaryIdentity(e,t);if(!r)return null;if(!n.__ppRawBindings){let u=e[ee];if(u!==void 0&&u.propsSchema!==null)n.__ppRawBindings=cr;else{let h=this.collectRawBindings(e);n.__ppRawBindings=h.bindings,n.__ppLiteralAttrs=h.literalAttrs}}let i=n.__ppRawBindings,o=lr(i),s=n.__ppFreshIdentity===!0,a=s?void 0:b.getInstance(r),c=o||!a?this.getParentScopeBundle(t):void 0;if(o){let u=this.options.isEffectManagedSurfaceElement(e);this.options.applyBoundaryBindings(e,i,c,u?h=>this.options.shouldSkipEffectManagedAttr(h):void 0)}if(this.materializeFormsThisPass&&this.options.materializeFormDefaults(e),a?.refreshPropsFromParent){let u=a.parentId!==t;if(a.parentId=t,b.saveParent(r,t),a.el!==e){let h=a.el;!n.__ppRawBindings&&h.__ppRawBindings&&(n.__ppRawBindings=h.__ppRawBindings),a.el=e}return a.refreshPropsFromParent(u||(this.options.shouldForceChildRefresh?.()??!1),this.getBoundaryBaseId(e)===t?void 0:c,!o),r}if(s||!b.getState(r)){n.__ppRuntimeParentId=t;try{this.options.createComponent(e,c)}finally{delete n.__ppRuntimeParentId,s&&delete n.__ppFreshIdentity}}else s&&delete n.__ppFreshIdentity;return r}getParentScopeBundle(e){let t=this.parentScopesByBoundaryId.get(e);if(t)return t;let n=b.getResolvedScopeWithAncestors(e,this.options.componentId)??this.options.getLatestScope(),r=He(n);return this.parentScopesByBoundaryId.set(e,r),r}collectRawBindings(e){let t={},n=e[G],r=e.getAttributeNames(),i,o;for(let s=0;s<r.length;s++){let a=r[s];if(a===j)continue;if(a.charCodeAt(0)===112&&a.startsWith(ie)){(i??=new Set).add(a.slice(ie.length)),(o??=[]).push(a);continue}if(n&&Object.prototype.hasOwnProperty.call(n,a))continue;let c=e.getAttribute(a);c!==null&&c.includes("{")&&!W(a,e)&&(t[a]=c)}if(i){for(let s of i)delete t[s];for(let s of o)e.removeAttribute(s)}return{bindings:t,literalAttrs:i}}destroyDisconnectedDescendants(e){if(b.hasChildren(this.options.componentId)){b.beginTopologyBatch();try{b.forEachDescendant(this.options.componentId,t=>{if(e.has(t))return;let n=b.getInstance(t);!n?.el||n.el.isConnected||n.destroy?.()})}finally{b.endTopologyBatch()}}}syncContextProviderBoundary(e,t,n,r){if(e.tagName.toLowerCase()!=="pp-context-provider")return null;let i=this.resolveContextProviderBoundary(e);return i?(n.add(i.boundaryId),this.options.getContextManager().syncProviderBoundary(i.boundaryId,t,i.context,i.value).forEach(s=>r.add(s)),i.boundaryId):null}resolveContextProviderBoundary(e){let t=e,n=e.getAttribute("data-pp-context-token")??t.__ppContextTokenCaptureId??null,r=e.getAttribute("data-pp-context-value")??t.__ppContextValueCaptureId??null;if(!n||!r)return null;t.__ppContextTokenCaptureId=n,t.__ppContextValueCaptureId=r,e.removeAttribute("data-pp-context-token"),e.removeAttribute("data-pp-context-value");let i=this.options.getContextTokenStore().get(n);return i?{boundaryId:this.ensureContextProviderBoundaryId(t),context:i,value:this.options.getContextValueStore().get(r)}:null}ensureContextProviderBoundaryId(e){return e.__ppContextBoundaryId||(e.__ppContextBoundaryId=`ppctx_${this.options.componentId}_${Math.random().toString(36).slice(2,10)}`),e.__ppContextBoundaryId}};var Vt=new Set(["data-state","data-open","style","aria-hidden","aria-checked","hidden","inert"]),bn=new Set(["alert-dialog-content","alert-dialog-overlay","alert-dialog-portal","checkbox","dialog-content","dialog-overlay","dialog-portal","popover-content","sheet-content","sheet-overlay","sheet-portal","tooltip-content"]),ft=class{constructor(e,t){this.refCaptureIdsByElement=e;this.refExprsByElement=t}refCaptureIdsByElement;refExprsByElement;isEffectManagedAttr(e){return Vt.has(e)}isEffectManagedSurfaceElement(e,t){let n=e.getAttribute("data-slot");if(n&&bn.has(n))return!0;let r=t?.getAttribute("data-slot");return r?bn.has(r):!1}syncAttributes(e,t,n=!1,r=!1,i){let o=e.__ppBoundEventBindings;if(e.attributes.length===0&&t.attributes.length===0&&(!o||o.size===0)&&!(e instanceof HTMLTextAreaElement))return;let s=n||this.isEffectManagedSurfaceElement(e,t),a=e,c=e.getAttributeNames();for(let d=c.length-1;d>=0;d--){let p=c[d];if(!(r&&p===j)&&!(i!==void 0&&p in i)&&!t.hasAttribute(p)){if(s&&Vt.has(p)||p==="value"&&e instanceof HTMLInputElement&&a.__ppHasUncontrolledDefaultValue||p==="checked"&&e instanceof HTMLInputElement&&a.__ppHasUncontrolledDefaultChecked||p==="selected"&&e instanceof HTMLOptionElement&&a.__ppHasUncontrolledDefaultSelected)continue;e.removeAttribute(p),p==="checked"&&e instanceof HTMLInputElement&&e.checked&&(e.checked=!1),p==="data-pp-ref"&&this.refCaptureIdsByElement.delete(e),p==="pp-ref"&&this.refExprsByElement.delete(e)}}Ee.unbindRemovedEventHandlers(e,t);let u=t.getAttributeNames(),h=t.getAttribute("pp-event-owner");for(let d=0;d<u.length;d++){let p=u[d];if(s&&Vt.has(p)||r&&p===j||i!==void 0&&p in i)continue;let f=t.getAttribute(p)??"";Ee.hasSameDirectBoundHandler(e,p,f,h)||(e.getAttribute(p)!==f&&e.setAttribute(p,f),p==="checked"&&e instanceof HTMLInputElement&&Ye(e,!0),p==="value"&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&e.value!=f&&(e.value=f))}if(e.hasAttribute("pp-event-owner")&&!e.getAttributeNames().some(d=>W(d,e))&&e.removeAttribute("pp-event-owner"),e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement&&!a.__ppHasUncontrolledDefaultValue){let d=t.getAttribute("value"),p=d??t.value,f=d??t.defaultValue;e.defaultValue!==f&&(a.__ppTextareaValueFollowsTemplate=!0),a.__ppTextareaValueFollowsTemplate&&(e.value!==p&&(e.value=p),e.defaultValue!==f&&(e.defaultValue=f))}}};var pr=Symbol.for("pp.context"),Ft=null;function dr(l){if(!l||typeof l!="object"||!("value"in l))throw new Error("Context.Provider expects an object like { value, children? }.");return l}function Fe(l){let e=Ft;return Ft=l,e}function Sn(l){let e={$$typeof:pr,defaultValue:l,Provider:t=>{let n=dr(t),r=Ft;if(!r)throw new Error("Context.Provider() can only be used while a component is rendering.");return r(e,n.value),n.children??null}};return e}var hr=["script","compile","template","domDiff","bindEvents","bindRefs","bootstrapNested","portals","restoreFocus","layoutEffects","effects","ctor","ctorSerialize","ctorProps","ctorPipeline","destroy","total"];function mt(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Kt=new Map,fr=0,I=new Map,$t=new Set,mr=new Map,gr=l=>Kt.get(l),$e=[],Ut=[],gt=" pp-stringless-mount",yr=Object.freeze({managedInputTags:!1,refMarkers:!1,contextProviders:!1,nestedBoundaries:!1,ownerMarkers:!1});function _r(l){if(l.includes("\\u")||/\barguments\b/.test(l)||/\beval\b/.test(l)||/\bthis\b/.test(l))return!1;let e=l.replace(/\bpp\s*\.\s*props\b/g,"");return!/\bpp\b/.test(e)}var Tn=new Map,Er=400,zt=1,qt=2,jt=4,Cn=zt|qt|jt,vr=/<(?:input|textarea|select)\b|defaultvalue|defaultchecked|data-pp-(?:input|select|checked|default)/i,br=/\.provider|pp-context/i;function Sr(l,e){if(e||l.includes("pp-owner"))return Cn;let t=0;return l.includes("pp-ref")&&(t|=zt),vr.test(l)&&(t|=qt),br.test(l)&&(t|=jt),t}function Tr(l){let{rootTag:e,slots:t,size:n}=l.descriptor,r=new Array(n).fill(0),i=0;return t.forEach((o,s)=>{let a=1<<s;if(i|=a,o.kind==="attr"||o.kind==="battr"){r[o.v]|=a;return}for(let c of o.parts)typeof c=="number"&&(r[c]|=a)}),{rootTag:e,size:n,fullMask:i,slotBitsByValue:r,exprs:l.exprs,applyPlan:{key:0,slots:t,size:n,slotBitsByValue:r,boundarySlotMask:0,boundaryValueIndices:[]}}}var Z=class l{static MAX_SYNC_RERENDERS=25;static MAX_RENDER_FUNCTION_CACHE_SIZE=500;static renderFunctionCache=new Map;el;boundary;id;rawTemplate="";renderFunction;renderPipelineInitialized=!1;templateFn=null;pipelineBlueprint=null;hooksSystem=null;_eventManager=null;latestScope;__ppRefStore=I;__ppRefSeq=0;__ppRefCaptureIdsByElement=new WeakMap;__ppRefExprsByElement=new WeakMap;_refBindingManager=null;__ppInputValueStore=I;__ppInputValueSeq=0;__ppSelectValueStore=I;__ppSelectValueSeq=0;__ppCheckedValueStore=I;__ppCheckedValueSeq=0;__ppContextTokenStore=I;__ppContextTokenSeq=0;__ppContextValueStore=I;__ppContextValueSeq=0;__ppDefaultValueStore=I;__ppDefaultValueSeq=0;__ppDefaultCheckedStore=I;__ppDefaultCheckedSeq=0;__ppLoopValueIds=$t;__ppLoopOwnerKey=0;__ppLoopValueSeq=0;_formControlManager=null;passiveEffectsVersion=0;isRendering=!1;props;ownedChildren=mr;lastRenderedHtml="";renderCount=0;freshStateId=!1;_portalManager=null;parentId=null;initialChildrenHtml="";subtreeHadOwnedTemplate=!1;pendingEventElements=null;_traversalManager=null;_contextManager=null;_focusManager=null;_domMorpher=null;_ownedTemplateManager=null;_propBindingManager=null;_nestedBoundaryManager=null;_attributeSyncManager=null;_lastRawScopeKeySig="";_lastSortedKeys=[];_lastHtmlProbes;_lastSortedScopeKeySig="";_cachedHooksAPI=null;_cachedRuntimeAPI=null;_provisionDispatcher=null;_refEvalFnCache=null;hadNestedRuntimeStructures=!1;loopRowCache=null;loopKeepResolved=0;usesLoops=!1;captureNeeds=Cn;propsOnlyRuntime=!1;bodyPlan=null;bodyPlanValues=null;bodyPlanValuesFn=null;bodyPlanDisabled=!1;liveOwnScriptEl=null;boundaryContentCache=null;boundaryKeepResolved=0;forceChildBoundaryRefresh=!1;morphingFromCommittedRender=!1;__ppLoopRowsFn=null;_loopContainers=null;_patchedBoundaryRows=null;__ppBoundaryHtmlFn=null;static perfEnabled=!1;static perfStats=new Map;constructor(e,t){let n=l.perfEnabled?mt():0;this.el=e,this.boundary=new je(e),this.id=this.boundary.getId()||"",this.id||(this.id="anon_"+Math.random().toString(36).substring(2,9),this.boundary.setId(this.id)),b.registerInstance(this.id,this),this.syncParentId();let r=e[ee];r!==void 0&&delete e[ee];let i=r!==void 0?r.childHtml:null,o=e.__ppFreshIdentity===!0;o&&(delete e.__ppFreshIdentity,this.freshStateId=!0);let s=this.startPerfTimer(),a=null;i!==null&&r.propsSchema!==null&&(a=Xt(r.propsSchema,e)),this.props=a??this.computePropsFromAttributes(t),this.endPerfTimer("ctorProps",s);let c=this.startPerfTimer(),u=i!==null?i:this.boundary.readContent();this.endPerfTimer("ctorSerialize",c);let h=!1;i===null&&u.includes("pp-owner")&&(this.ownedChildren=this.ownedTemplateManager.extractOwnedTemplates(this.el,f=>{(f===this.id||b.resolveComponentId(f,this.id)===this.id)&&(h=!0),this.subtreeHadOwnedTemplate=!0}),this.ownedChildren.size>0&&(u=this.boundary.readContent())),o||b.removeOwnedTemplates(this.id),this.ownedChildren.size>0&&b.saveOwnedTemplates(this.id,this.ownedChildren),this.initialChildrenHtml=u,this.props.children=this.initialChildrenHtml,r!==void 0&&i===null&&this.ownedChildren.size===0&&!this.subtreeHadOwnedTemplate&&(r.childHtml=u,r.hasScript=u.includes("<script"),r.propsSchema=this.recordDirectPropsSchema());let d=i!==null?r.hasScript:u.includes("<script"),p=null;if(d&&(i!==null&&(p=Pn(this.el,r.scriptPath)),p??=this.findOwnScript(this.el)),this.liveOwnScriptEl=p,i===null&&this.canReuseStaticInitialMarkup(p,h))this.reuseStaticInitialMarkup(u);else{let f=this.startPerfTimer();this.initializeRenderPipeline(p,i!==null?r.blueprint:null),this.endPerfTimer("ctorPipeline",f),r!==void 0&&r.childHtml!==null&&(r.blueprint===null&&this.pipelineBlueprint!==null&&(r.blueprint=this.pipelineBlueprint),r.scriptPath===null&&p!==null&&(r.scriptPath=this.deriveScriptPath(p))),this.render(),r!==void 0&&i===null&&r.childHtml!==null&&(r.stringlessMounted=this.lastRenderedHtml===gt)}l.perfEnabled&&this.recordPerfPhase("ctor",mt()-n)}ensureHooksSystem(){let e=this.hooksSystem;if(e!==null)return e;e=new qe(()=>{this.isRendering||this.render()},this.id),e.setUncaughtErrorHandler(n=>this.deliverErrorToBoundary(n));let t=this.freshStateId?void 0:b.getState(this.id);return t&&e.loadState(t),this.hooksSystem=e,e}get eventManager(){return this._eventManager??=new Ee(this.el,()=>this.latestScope,e=>this.traversalManager.isManagedEventElement(e))}get refBindingManager(){return this._refBindingManager??=new Qe(this.id)}get formControlManager(){return this._formControlManager??=new tt}get portalManager(){return this._portalManager??=new et(this.id)}get attributeSyncManager(){return this._attributeSyncManager??=new ft(this.__ppRefCaptureIdsByElement,this.__ppRefExprsByElement)}get traversalManager(){return this._traversalManager??=new pt(()=>this.el,()=>this.portalManager.elements(),this.__ppRefCaptureIdsByElement,this.__ppRefExprsByElement)}get contextManager(){return this._contextManager??=new nt(this.id,()=>this.parentId,()=>b.getInstance(this.id)===this,()=>this.isRendering,()=>this.forceUpdate())}get ownedTemplateManager(){return this._ownedTemplateManager??=new ke(this.id)}get propBindingManager(){return this._propBindingManager??=new ut(this.id,(e,t,n,r,i)=>this.getCachedFunction(e,t,n,r,i))}get nestedBoundaryManager(){return this._nestedBoundaryManager??=new ht({componentId:this.id,getRoot:()=>this.el,getPortalElements:()=>this.portalManager.elements(),getLatestScope:()=>this.latestScope,getContextTokenStore:()=>this.__ppContextTokenStore,getContextValueStore:()=>this.__ppContextValueStore,getContextManager:()=>this.contextManager,isEffectManagedSurfaceElement:e=>this.isEffectManagedSurfaceElement(e),shouldSkipEffectManagedAttr:e=>this.attributeSyncManager.isEffectManagedAttr(e),syncAttributes:(e,t,n,r,i)=>this.syncAttributes(e,t,n,r,i),applyBoundaryBindings:(e,t,n,r)=>this.applyBoundaryBindings(e,t,n,r),materializeFormDefaults:e=>this.materializeNestedBoundaryFormDefaults(e),hasFormDefaultState:()=>this._formControlManager!==null||this.__ppInputValueStore.size>0||this.__ppCheckedValueStore.size>0||this.__ppDefaultValueStore.size>0||this.__ppDefaultCheckedStore.size>0,createComponent:(e,t)=>Rr(e,t),refreshContextConsumers:e=>this.refreshContextConsumers(e),shouldForceChildRefresh:()=>this.forceChildBoundaryRefresh})}get focusManager(){return this._focusManager??=new rt(()=>this.el,e=>this.portalManager.contains(e))}get domMorpher(){return this._domMorpher??=new ct({root:this.el,collectEventElements:e=>this.collectEventElements(e),hasEventAttributes:e=>this.hasEventAttributes(e),syncAttributes:(e,t)=>this.syncAttributes(e,t),syncNestedBoundaryAttributes:(e,t)=>this.nestedBoundaryManager.syncNestedBoundaryAttributes(e,t),onKeepResolved:()=>{this.loopKeepResolved++},onBoundaryKeepResolved:()=>{this.boundaryKeepResolved++},hasKeepPlaceholders:()=>(this.loopRowCache?.getEmittedCount()??0)>0,takeDirectBuild:e=>this.loopRowCache?.takeDirectBuild(e)??null,shouldForceChildRefresh:()=>this.forceChildBoundaryRefresh,canSkipEqualSubtrees:()=>this.morphingFromCommittedRender,ownsBoundaryContent:(e,t)=>this.ownsBoundaryContent(e,t)})}initializeRenderPipeline(e=null,t=null){if(this.renderPipelineInitialized)return;let n=this.ownedChildren.size===0&&!this.subtreeHadOwnedTemplate?this.initialChildrenHtml:null;if(n!==null){let s=t??Tn.get(n);if(s){this.rawTemplate=s.rawTemplate,this.renderFunction=s.renderFunction,this.pipelineBlueprint=s,this.captureNeeds=s.captureNeeds,this.propsOnlyRuntime=s.propsOnlyRuntime,this.bodyPlan=s.bodyPlan,this.installLoopMachinery(s.usesLoops,s.hasBoundaryCall),this.renderPipelineInitialized=!0;return}}let r="",i=!1;if(!/<script\b|<textarea\b/i.test(this.initialChildrenHtml))this.rawTemplate=this.initialChildrenHtml;else{let s=this.spliceOwnScriptFromInitialHtml(e);if(s)r=s.scriptContent,i=!0,this.rawTemplate=s.template;else{let a=le(this.initialChildrenHtml,this.el.tagName.toLowerCase()),c=this.findOwnScript(a.root)??this.findOwnedSlotScript(a.root);r=c?Mt(c):"",i=c!==null,c&&c.remove(),this.rawTemplate=a.toHtml()}}!i&&this.parentCompiledOurContent()&&(this.rawTemplate=this.neutralizeScriptlessTemplate(this.rawTemplate)),this.installLoopMachinery(this.rawTemplate.includes("pp-for"),this.rawTemplate.includes("pp-component=")),this.captureNeeds=Sr(this.rawTemplate,this.ownedChildren.size>0||this.subtreeHadOwnedTemplate),this.propsOnlyRuntime=_r(r);let o=ce.compileComponentBodyPlan(this.rawTemplate);if(this.bodyPlan=o?Tr(o):null,this.renderFunction=this.createRenderFunction(r),this.renderPipelineInitialized=!0,n!==null){let s={rawTemplate:this.rawTemplate,scriptContent:r,usesLoops:this.usesLoops,hasBoundaryCall:this.__ppBoundaryHtmlFn!==null,captureNeeds:this.captureNeeds,propsOnlyRuntime:this.propsOnlyRuntime,bodyPlan:this.bodyPlan,renderFunction:this.renderFunction,templateFns:new Map,bodyValuesFns:new Map,scopeShape:null};re(Tn,n,s,Er),this.pipelineBlueprint=s}}installLoopMachinery(e,t){if(this.usesLoops=e,e){let n=new at;this.loopRowCache=n,n.setValuePatchSink(this.createLoopValuePatchSink()),this.__ppLoopRowsFn=(r,i,o,s,a,c)=>n.render(r,i,o,s,a,c)}if(t){let n=new Ze;this.boundaryContentCache=n,this.__ppBoundaryHtmlFn=(r,i,o)=>n.resolve(r,i,o)}}syncParentId(){let e=this.el.__ppRuntimeParentId;if(e!==void 0)this.parentId=e;else{let t=this.boundary.parentBoundaryElement();this.parentId=t?K(t):null}b.saveParent(this.id,this.parentId)}static setPerfEnabled(e){this.perfEnabled=e,En(!e)}static getPerfEnabled(){return this.perfEnabled}static resetPerfStats(){this.perfStats.clear()}static getPerfStats(){return Object.fromEntries(this.perfStats.entries())}static createEmptyPerfEntry(){let e={};return hr.forEach(t=>{e[t]={count:0,totalMs:0,maxMs:0}}),{renderCount:0,phases:e}}recordPerfPhase(e,t){if(!l.perfEnabled)return;let n=l.perfStats.get(this.id);n||(n=l.createEmptyPerfEntry(),l.perfStats.set(this.id,n));let r=n.phases[e];r.count++,r.totalMs+=t,r.maxMs=Math.max(r.maxMs,t)}startPerfTimer(){return l.perfEnabled?mt():0}endPerfTimer(e,t){l.perfEnabled&&this.recordPerfPhase(e,mt()-t)}spliceOwnScriptFromInitialHtml(e){if(/<textarea\b/i.test(this.initialChildrenHtml))return null;let t=e??this.findOwnScript(this.el);if(!t)return null;let n=t.outerHTML,r=this.initialChildrenHtml.indexOf(n);return r===-1||this.initialChildrenHtml.indexOf(n,r+n.length)!==-1?null:{template:this.initialChildrenHtml.slice(0,r)+this.initialChildrenHtml.slice(r+n.length),scriptContent:Mt(t)}}findOwnScript(e){for(let t=e.firstElementChild;t;t=t.nextElementSibling){if(t.tagName.toLowerCase()==="script"&&!t.hasAttribute("type"))return t;if(V(t))continue;let n=this.findOwnScript(t);if(n)return n}return null}canReuseStaticInitialMarkup(e,t){if(e||this.ownedChildren.size>0||t)return!1;let n=[this.el];for(;n.length>0;){let r=n.pop();if(r instanceof Text){if(/[{}]/.test(r.data)||Rt(r.data))return!1;continue}if(!(r instanceof Element)||r!==this.el&&V(r))continue;let o=r.tagName.toLowerCase();if(o==="script"||o==="template"||o==="slot"||o==="pp-context-provider"||o.endsWith(".provider")||o==="input"||o==="textarea"||o==="select")return!1;for(let s of r.getAttributeNames()){let a=s.toLowerCase(),c=r.getAttribute(s)??"";if(a!==j&&(/[{}]/.test(c)||Rt(c)||a.startsWith("on")||a.startsWith("pp-")||a.startsWith("data-pp-")||a==="key"))return!1}for(let s=r.lastChild;s;s=s.previousSibling)n.push(s)}return!0}reuseStaticInitialMarkup(e){this.latestScope={},b.saveState(this.id,this.hooksSystem?.getHooks()??(this.freshStateId?void 0:b.getState(this.id))??$e),this.freshStateId=!1,b.saveScope(this.id,this.latestScope),this.lastRenderedHtml=e;let t=this.subtreeHasComponentBoundary();this.hadNestedRuntimeStructures=t,t&&this.bootstrapNestedComponents()}subtreeHasComponentBoundary(){let e=[];for(let t=this.el.lastElementChild;t;t=t.previousElementSibling)e.push(t);for(;e.length>0;){let t=e.pop();if(V(t))return!0;for(let n=t.lastElementChild;n;n=n.previousElementSibling)e.push(n)}return!1}ownsBoundaryContent(e,t){if(this.morphingFromCommittedRender)return!1;let n=e.innerHTML;return n.includes("{")?n!==t.innerHTML:!1}parentCompiledOurContent(){return this.subtreeHadOwnedTemplate?!1:!/<script\b/i.test(this.initialChildrenHtml)}neutralizeScriptlessTemplate(e){return e.includes("{")?e.split("{").join("&#123;").split("}").join("&#125;"):e}findOwnedSlotScript(e){let t=Array.from(e.querySelectorAll("template[pp-owner]")).filter(n=>{let r=n.getAttribute("pp-owner");return r===this.id||b.resolveComponentId(r,this.id)===this.id});for(let n of t){let r=n.content;if(!r)continue;let i=this.findOwnScript(r);if(i)return i}return null}applyBoundaryBindings(e,t,n,r){this.propBindingManager.applyBoundaryBindings(e,t,n,r)}computePropsFromAttributes(e,t=!1){return this.propBindingManager.computePropsFromAttributes(this.el,t?null:this.parentId,e)}recordDirectPropsSchema(){let e=this.el,t=e,n=t.__ppRawBindings;if(n===void 0)return null;for(let s in n)return null;if(t.__ppLiteralAttrs!==void 0&&t.__ppLiteralAttrs.size>0)return null;let r=t[G];if(r===void 0)return null;let i=[],o=e.getAttributeNames();for(let s=0;s<o.length;s++){let a=o[s];if(a===j)continue;if(a.startsWith(ie))return null;if(W(a,e))continue;let c=Be(a);if(!ae.has(c)){if(Object.prototype.hasOwnProperty.call(r,a)){i.push({name:a,camel:c,direct:!0});continue}i.push({name:a,camel:c,direct:!1,staticValue:this.props[c]})}}for(let s in r){if(o.includes(s))continue;let a=Be(s);ae.has(a)||i.push({name:s,camel:a,direct:!0})}return i}deriveScriptPath(e){let t=[],n=e;for(;n!==this.el;){let r=n.parentElement;if(r===null)return null;let i=0;for(let o=r.firstElementChild;o!==null&&o!==n;o=o.nextElementSibling)i++;t.unshift(i),n=r}return t}refreshPropsFromParent(e=!1,t,n=!1){let r=this.computePropsFromAttributes(t,n);if(r.children=this.initialChildrenHtml,!e&&xt(this.props,r)&&(this.ownedChildren.size===0||!this.ownedTemplateManager.haveOwnerScopeIdentitiesChanged())){this.hadNestedRuntimeStructures&&this.bootstrapNestedComponents();return}this.props=r,this.isRendering||this.render()}refreshOwnedChildrenFromElement(e){if(this.ownedChildren.size===0)return!1;let t=e.cloneNode(!0),n=this.ownedTemplateManager.extractOwnedTemplates(t);if(n.size===0)return!1;let r=!1;return n.forEach((i,o)=>{let s=this.ownedChildren.get(o);(!s||s.content!==i.content||s.ownerId!==i.ownerId)&&(r=!0)}),r?(this.ownedChildren=n,b.saveOwnedTemplates(this.id,n),this.forceUpdate(),!0):!1}getCachedFunction(e,t,n,r,i){let o=t+"|"+r,s=e.get(o);return s||(s=new Function(...n,`"use strict"; return (${t});`),re(e,o,s,i)),s}createRenderFunction(e){let t=l.renderFunctionCache.get(e);if(t)return t;let n=U.extractStateBindings(e),r=new Function("pp",`
40
- "use strict";
41
- ${e}
42
- return { ${n.join(", ")} };
43
- `);return re(l.renderFunctionCache,e,r,l.MAX_RENDER_FUNCTION_CACHE_SIZE),r}resolveCapturedRefValue(e,t){if(this.__ppRefStore.has(e))return this.__ppRefStore.get(e);if(!t||t===this.id)return;let n=b.getInstance(t);if(!(!n||!n.__ppRefStore.has(e)))return n.__ppRefStore.get(e)}resolvePlainRefValue(e,t,n,r){let i=this.latestScope[e];if(typeof i=="function"||i&&typeof i=="object"&&"current"in i)return i;try{return this.getCachedFunction(this._refEvalFnCache??=new Map,e,t,r,200)(...n)}catch{return}}__ppRefCaptureFn=null;__ppSelectValueCaptureFn=null;__ppCheckedValueCaptureFn=null;__ppInputValueCaptureFn=null;__ppContextTokenCaptureFn=null;__ppContextValueCaptureFn=null;createRefCaptureFunction(){return this.__ppRefStore!==I&&this.__ppRefStore.clear(),this.__ppRefSeq=0,this.__ppRefCaptureFn??=e=>{let t=`ppref_${this.id}_${++this.__ppRefSeq}`;return this.__ppRefStore===I&&(this.__ppRefStore=new Map),this.__ppRefStore.set(t,e),t}}createSelectValueCaptureFunction(){return this.__ppSelectValueStore!==I&&this.__ppSelectValueStore.clear(),this.__ppSelectValueSeq=0,this.__ppSelectValueCaptureFn??=e=>{let t=`ppselect_${this.id}_${++this.__ppSelectValueSeq}`;return this.__ppSelectValueStore===I&&(this.__ppSelectValueStore=new Map),this.__ppSelectValueStore.set(t,e),t}}createCheckedValueCaptureFunction(){return this.__ppCheckedValueStore!==I&&this.__ppCheckedValueStore.clear(),this.__ppCheckedValueSeq=0,this.__ppCheckedValueCaptureFn??=e=>{let t=`ppchecked_${this.id}_${++this.__ppCheckedValueSeq}`;return this.__ppCheckedValueStore===I&&(this.__ppCheckedValueStore=new Map),this.__ppCheckedValueStore.set(t,e),t}}createInputValueCaptureFunction(){return this.__ppInputValueStore!==I&&this.__ppInputValueStore.clear(),this.__ppInputValueSeq=0,this.__ppInputValueCaptureFn??=e=>{let t=`ppinput_${this.id}_${++this.__ppInputValueSeq}`;return this.__ppInputValueStore===I&&(this.__ppInputValueStore=new Map),this.__ppInputValueStore.set(t,e),t}}createContextTokenCaptureFunction(){return this.__ppContextTokenStore!==I&&this.__ppContextTokenStore.clear(),this.__ppContextTokenSeq=0,this.__ppContextTokenCaptureFn??=e=>{let t=`ppcontexttoken_${this.id}_${++this.__ppContextTokenSeq}`;return this.__ppContextTokenStore===I&&(this.__ppContextTokenStore=new Map),this.__ppContextTokenStore.set(t,e),t}}createContextValueCaptureFunction(){return this.__ppContextValueStore!==I&&this.__ppContextValueStore.clear(),this.__ppContextValueSeq=0,this.__ppContextValueCaptureFn??=e=>{let t=`ppcontextvalue_${this.id}_${++this.__ppContextValueSeq}`;return this.__ppContextValueStore===I&&(this.__ppContextValueStore=new Map),this.__ppContextValueStore.set(t,e),t}}__ppContextLookupFn=null;createContextLookupFunction(){if(this.__ppContextLookupFn)return this.__ppContextLookupFn;let e=(t,n)=>{if(t==null)return;if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let r=Object.keys(Object(t)).find(i=>i.toLowerCase()===n.toLowerCase());return r?t[r]:void 0};return this.__ppContextLookupFn=t=>{let n=String(t).split(".").map(s=>s.trim()).filter(Boolean);if(n.length===0)return;let[r,...i]=n,o;r.toLowerCase()==="globalthis"?o=globalThis:r.toLowerCase()==="window"?o=typeof window<"u"?window:globalThis:(o=e(this.latestScope,r),o===void 0&&(o=e(globalThis,r)));for(let s of i)o=e(o,s);return o},this.__ppContextLookupFn}__ppDefaultValueCaptureFn=null;__ppDefaultCheckedCaptureFn=null;createDefaultValueCaptureFunction(){return this.__ppDefaultValueStore!==I&&this.__ppDefaultValueStore.clear(),this.__ppDefaultValueSeq=0,this.__ppDefaultValueCaptureFn??=e=>{let t=`ppdefaultvalue_${this.id}_${++this.__ppDefaultValueSeq}`;return this.__ppDefaultValueStore===I&&(this.__ppDefaultValueStore=new Map),this.__ppDefaultValueStore.set(t,e),t}}createDefaultCheckedCaptureFunction(){return this.__ppDefaultCheckedStore!==I&&this.__ppDefaultCheckedStore.clear(),this.__ppDefaultCheckedSeq=0,this.__ppDefaultCheckedCaptureFn??=e=>{let t=`ppdefaultchecked_${this.id}_${++this.__ppDefaultCheckedSeq}`;return this.__ppDefaultCheckedStore===I&&(this.__ppDefaultCheckedStore=new Map),this.__ppDefaultCheckedStore.set(t,e),t}}__ppLoopCaptureFn=null;clearLoopValues(){this.__ppLoopValueIds===$t||this.__ppLoopValueIds.size===0||(this.__ppLoopValueIds.forEach(e=>Kt.delete(e)),this.__ppLoopValueIds.clear())}createLoopCaptureFunction(){return this.clearLoopValues(),this.__ppLoopValueSeq=0,this.__ppLoopCaptureFn??=e=>{this.__ppLoopValueIds===$t&&(this.__ppLoopValueIds=new Set),this.__ppLoopOwnerKey===0&&(this.__ppLoopOwnerKey=++fr);let t=`ppv_${this.__ppLoopOwnerKey}_${++this.__ppLoopValueSeq}`;return Kt.set(t,e),this.__ppLoopValueIds.add(t),t}}consumeContext(e){return this.contextManager.consume(e)}registerProvidedContext(e,t){this.contextManager.provide(e,t)}requestContextRefresh(){this.contextManager.requestRefresh()}refreshContextConsumers(e){this.contextManager.refreshConsumers(e)}makeHooksAPI(){if(this._cachedHooksAPI)this._cachedHooksAPI.props=this.props;else if(this.propsOnlyRuntime)this._cachedHooksAPI={props:this.props};else{let e=this.ensureHooksSystem();this._cachedHooksAPI={state:t=>e.useState(t),effect:(t,n)=>e.useEffect(t,n),layoutEffect:(t,n)=>e.useLayoutEffect(t,n),ref:(t=null)=>e.useRef(t),memo:(t,n)=>e.useMemo(t,n),callback:(t,n)=>e.useCallback(t,n),reducer:(t,n,r)=>r?e.useReducer(t,n,r):e.useReducer(t,n),context:t=>this.consumeContext(t),portal:(t,n)=>e.usePortal(t,n),id:()=>e.useId(),errorBoundary:()=>e.useErrorBoundary(),syncExternalStore:(t,n)=>e.useSyncExternalStore(t,n),imperativeHandle:(t,n,r)=>e.useImperativeHandle(t,n,r),transition:()=>e.useTransition(),deferredValue:(t,n)=>e.useDeferredValue(t,n),optimistic:(t,n)=>e.useOptimistic(t,n),props:this.props}}return this._cachedHooksAPI}makeRuntimeAPI(e){if(this.propsOnlyRuntime)return this._cachedRuntimeAPI=e,e;if(!this._cachedRuntimeAPI){let t=globalThis.pp;return this._cachedRuntimeAPI=t?.createComponentRuntime?.(e)??e,this._cachedRuntimeAPI}return this._cachedRuntimeAPI.props=e.props,this._cachedRuntimeAPI}syncTrackedPortals(e){if((this._portalManager?.size??0)===0)return;let t=this.hooksSystem?.getPortalRegistrations()??Ut;if(t.length===0)return;let n=new Map,r=new Map;e.querySelectorAll("*").forEach(c=>{let u=c,h=u.getAttribute("data-pp-ref");if(h){let p=n.get(h);p?p.push(u):n.set(h,[u])}let d=u.getAttribute("pp-ref");if(d){let p=r.get(d);p?p.push(u):r.set(d,[u])}});let i=new Map;for(let[c,u]of this.__ppRefStore.entries()){if(!u||typeof u!="object"||!("current"in u))continue;let h=u,d=i.get(h);d?d.push(c):i.set(h,[c])}let o=new Map;for(let[c,u]of Object.entries(this.latestScope)){if(!u||typeof u!="object"||!("current"in u))continue;let h=u,d=o.get(h);d?d.push(c):o.set(h,[c])}let s=(c,u)=>{for(let h of u){let d=c.get(h);if(!d||d.length===0)continue;let p=d.shift()??null;if(d.length===0&&c.delete(h),p)return p}return null},a=[];for(let c of t){let u=c.ref.current;if(!u||!this.portalManager.has(u))continue;let h=i.get(c.ref)??[],d=s(n,h);if(!d){let p=o.get(c.ref)??[];d=s(r,p)}d&&a.push({liveElement:u,sourceElement:d,placeholderText:this.portalManager.getPlaceholderText(u)})}a.length!==0&&(a.forEach(({sourceElement:c,placeholderText:u})=>{c.replaceWith(document.createComment(u))}),a.forEach(({liveElement:c,sourceElement:u})=>{this.morphTrackedPortalRoot(c,u)}))}morphTrackedPortalRoot(e,t){if(e.tagName!==t.tagName){let n=e.parentNode;if(!n)return;let r=t.cloneNode(!0);n.replaceChild(r,e),this.collectEventElements(r),this.portalManager.replaceElement(e,r);return}this.syncAttributes(e,t,!0),this.hasEventAttributes(e)&&(this.pendingEventElements??=new Set).add(e),this.domMorpher.morphChildren(e,t)}applyPortals(){let e=this.hooksSystem?.getPortalRegistrations()??Ut;this.portalManager.apply(e)&&this.invalidateTraversalCache()}render(e=0){if(e>l.MAX_SYNC_RERENDERS){console.warn(`[PP-WARN] Synchronous rerender limit exceeded for component "${this.id}". Check for state updates during render or layout effects.`);return}if(this.initializeRenderPipeline(),this.isRendering)return;this.isRendering=!0,this.renderCount++;let t=this.startPerfTimer();if(l.perfEnabled){let n=l.perfStats.get(this.id);n||(n=l.createEmptyPerfEntry(),l.perfStats.set(this.id,n)),n.renderCount++}try{this._contextManager?.prepareRender();let n=this.propsOnlyRuntime?this.hooksSystem:this.ensureHooksSystem();n?.prepareRender();let r=this.makeHooksAPI(),i=this.makeRuntimeAPI(r),o=this.startPerfTimer();n?.startRenderPhase();let s,a=!1,c=yt;if(c!==null)yt=null,s=c.scope,c.provisions?.forEach((R,k)=>this.registerProvidedContext(k,R)),a=n?.finishRenderPhase()??!1;else{let R=Fe(this._provisionDispatcher??=(k,L)=>this.registerProvidedContext(k,L));try{s=this.renderFunction(i)}finally{Fe(R),a=n?.finishRenderPhase()??!1}}if(this.endPerfTimer("script",o),a){this.isRendering=!1,this.render(e+1);return}b.saveState(this.id,n!==null?n.getHooks():this.freshStateId?$e:b.getState(this.id)??$e),this.freshStateId=!1,this.latestScope=s;let u=this.captureNeeds;(u&zt)!==0&&(this.latestScope.__pp_ref=this.createRefCaptureFunction()),(u&qt)!==0&&(this.latestScope.__pp_input_value=this.createInputValueCaptureFunction(),this.latestScope.__pp_select_value=this.createSelectValueCaptureFunction(),this.latestScope.__pp_checked_value=this.createCheckedValueCaptureFunction(),this.latestScope.__pp_default_value=this.createDefaultValueCaptureFunction(),this.latestScope.__pp_default_checked=this.createDefaultCheckedCaptureFunction()),(u&jt)!==0&&(this.latestScope.__pp_context_token=this.createContextTokenCaptureFunction(),this.latestScope.__pp_context_value=this.createContextValueCaptureFunction(),this.latestScope.__pp_context_lookup=this.createContextLookupFunction()),this.usesLoops&&(this.latestScope.__pp_loop_capture=this.createLoopCaptureFunction(),this.latestScope.__pp_loop_read=gr,this.latestScope.__pp_loop_rows=this.__ppLoopRowsFn),this.__ppBoundaryHtmlFn&&(this.latestScope.__pp_boundary_html=this.__ppBoundaryHtmlFn),b.saveScope(this.id,this.latestScope);let h=this.pipelineBlueprint,d=u===0&&!this.usesLoops&&this.__ppBoundaryHtmlFn===null&&h!==null,p,f,y=d?h.scopeShape:null;if(y!==null)p=y.sortedKeys,f=y.sortedKeySig;else{let R=_e(this.latestScope),k=R.keys,L=R.keySig;L===this._lastRawScopeKeySig?(p=this._lastSortedKeys,f=this._lastSortedScopeKeySig):(p=k.length>1?[...k].sort():k.slice(),f=p.join("\0"),this._lastRawScopeKeySig=L,this._lastSortedKeys=p,this._lastSortedScopeKeySig=f),d&&(h.scopeShape={sortedKeys:p,sortedKeySig:f})}let m=Pe(this.latestScope,p);if(!this.templateFn){let R=this.startPerfTimer(),k=h?.templateFns.get(f);k?this.templateFn=k:(this.templateFn=ce.compile(this.rawTemplate,p),h?.templateFns.set(f,this.templateFn)),this.endPerfTimer("compile",R)}this.loopRowCache?.beginRender(),this.loopKeepResolved=0,this._patchedBoundaryRows=null,this.boundaryContentCache?.beginRender(),this.boundaryKeepResolved=0;let g=this.startPerfTimer(),E=!1,_;this.canAttemptStringlessMount()&&(E=this.tryBodyPlanCommit(p,m,f)),E?_=gt:(_=this.templateFn(...m),(this._ownedTemplateManager!==null||_.includes("__PP_OWNED_"))&&(_=this.ownedTemplateManager.resolveOwnedChildren(_,this.ownedChildren))),this.endPerfTimer("template",g);let v=n?.getPortalRegistrations()??Ut,S=this.lastRenderedHtml!==_,T=this.loopRowCache?.takePendingPatches()??null,C=this._patchedBoundaryRows;this._patchedBoundaryRows=null;let P=this.loopRowCache?.takeStructuralBoundaryChange()??!1,w=this._lastHtmlProbes;(S||!w)&&(w=_===gt?yr:{managedInputTags:/<(?:input|textarea|select)\b/i.test(_),refMarkers:_.includes("pp-ref"),contextProviders:_.includes("<pp-context-provider"),nestedBoundaries:_.includes("pp-component="),ownerMarkers:_.includes("pp-owner")},this._lastHtmlProbes=w);let B=this.el instanceof HTMLInputElement||this.el instanceof HTMLTextAreaElement||this.el instanceof HTMLSelectElement||w.managedInputTags,N=this.el.hasAttribute("pp-ref")||this.el.hasAttribute("data-pp-ref")||w.refMarkers||(this._refBindingManager?.hasActiveBindings()??!1),X=w.contextProviders,q=w.nestedBoundaries||X||v.length>0,D=this.ownedChildren.size>0||w.ownerMarkers;if(!S&&T===null&&!P&&!B&&!D&&!X&&!(q&&this.getTraversalCache().childBoundaries.some(R=>{let k=R.__ppRawBindings;return!!k&&Object.keys(k).length>0}))){if(C!==null){let O=this.startPerfTimer();this.nestedBoundaryManager.refreshPatchedBoundaries(C),this.endPerfTimer("bootstrapNested",O)}if(N){let O=this.startPerfTimer();this.bindRefs(p,m,f),this.endPerfTimer("bindRefs",O)}let R=this._contextManager?.commitRenderContexts()??null;if(v.length>0||(this._portalManager?.size??0)>0){let O=this.startPerfTimer();this.applyPortals(),this.endPerfTimer("portals",O)}let k=this.startPerfTimer(),L=n?.runLayoutEffects()??!1;if(this.endPerfTimer("layoutEffects",k),L){this.isRendering=!1,this.render(e+1);return}this.schedulePassiveEffects(),this.boundaryContentCache?.commit(),R?.size&&this.refreshContextConsumers(R);return}let M=B?this.collectManagedInputs():[],fe=B||this._focusManager!==null?this.focusManager.save(M):null;if(S){let R=this.startPerfTimer();if(!E&&!this.tryBodyPlanCommit(p,m,f)&&!this.applyDomDiff(_)){console.warn(`[PP-WARN] Direct loop row construction was abandoned for component "${this.id}" because its parsed marker did not match the planned rows. Rendering through the string pipeline.`),this.loopRowCache?.disableDirectBuilding(),this.lastRenderedHtml="",this.isRendering=!1,this.render(e+1);return}this.endPerfTimer("domDiff",R),this.lastRenderedHtml=_;let k=this.loopRowCache?.getEmittedCount()??0;if(k>0&&this.loopKeepResolved!==k){console.warn(`[PP-WARN] Loop row reuse was abandoned for component "${this.id}" because a reused row was no longer mounted. Rendering without row reuse.`),this.loopRowCache?.disable(),this.lastRenderedHtml="",this.isRendering=!1,this.render(e+1);return}let L=this.boundaryContentCache?.getEmittedCount()??0;if(L>0&&this.boundaryKeepResolved!==L){console.warn(`[PP-WARN] Nested boundary content reuse was abandoned for component "${this.id}" because a reused boundary was no longer mounted. Rendering without boundary reuse.`),this.boundaryContentCache?.disable(),this.forceChildBoundaryRefresh=!0,this.lastRenderedHtml="",this.isRendering=!1,this.render(e+1);return}}if(T!==null){let R=this.startPerfTimer(),k=this.applyLoopPatches(T);if(this.endPerfTimer("domDiff",R),!k){console.warn(`[PP-WARN] Loop row patching was abandoned for component "${this.id}" because a patched row was no longer mounted. Rendering without row patching.`),this.loopRowCache?.disablePatching(),this.lastRenderedHtml="",this.isRendering=!1,this.render(e+1);return}this.loopRowCache?.commitPatches(T),this.invalidateTraversalCache()}if(C!==null){let R=this.startPerfTimer();this.nestedBoundaryManager.refreshPatchedBoundaries(C),this.endPerfTimer("bootstrapNested",R)}if(this.boundaryContentCache?.commit(),this.hasEventAttributes(this.el)&&(this.pendingEventElements??=new Set).add(this.el),(this.pendingEventElements?.size??0)>0){let R=this.pendingEventElements;this.pendingEventElements=null;let k=this.startPerfTimer();this.eventManager.bindEvents(R),this.endPerfTimer("bindEvents",k)}if(N){let R=this.startPerfTimer();this.bindRefs(p,m,f),this.endPerfTimer("bindRefs",R)}let F=S&&B?this.collectManagedInputs():M,H=this._contextManager?.commitRenderContexts()??null;if(q||this.hadNestedRuntimeStructures||P){let R=this.startPerfTimer();this.bootstrapNestedComponents(),this.endPerfTimer("bootstrapNested",R)}if(this.hadNestedRuntimeStructures=q,v.length>0||(this._portalManager?.size??0)>0){let R=this.startPerfTimer();this.applyPortals(),this.endPerfTimer("portals",R)}if((B||this._formControlManager!==null)&&(this.bindControlledInputValues(F),this.bindUncontrolledInputDefaults(F),this.bindUncontrolledFormResets(F),this.bindControlledSelectValues(F),this.bindControlledCheckedValues(F)),fe!==null){let R=this.startPerfTimer();this.focusManager.restore(fe,F),this.endPerfTimer("restoreFocus",R)}let te=this.startPerfTimer(),de=n?.runLayoutEffects()??!1;if(this.endPerfTimer("layoutEffects",te),de){this.isRendering=!1,this.render(e+1);return}this.schedulePassiveEffects(),H?.size&&this.refreshContextConsumers(H)}catch(n){this.deliverErrorToBoundary(n)||console.error("[PP-ERROR] Render Cycle Failed",n)}finally{this.endPerfTimer("total",t),this.isRendering=!1}}deliverErrorToBoundary(e){return this.hooksSystem?.captureError(e)?!0:wn(this.id,e)}captureComponentError(e){return this.hooksSystem?.captureError(e)??!1}schedulePassiveEffects(){if(!this.hooksSystem?.hasPendingEffects())return;let e=++this.passiveEffectsVersion;queueMicrotask(()=>{if(this.passiveEffectsVersion!==e||b.getInstance(this.id)!==this)return;let t=this.startPerfTimer();this.hooksSystem?.runEffects(),this.endPerfTimer("effects",t)})}applyDomDiff(e){if(this.morphingFromCommittedRender=this.lastRenderedHtml!=="",this.lastRenderedHtml===""&&this.liveOwnScriptEl?.parentNode){let i=this.liveOwnScriptEl,o=i.previousSibling,s=i.nextSibling;i.remove(),o?.nodeType===Node.TEXT_NODE&&s?.nodeType===Node.TEXT_NODE&&(o.nodeValue=(o.nodeValue??"")+(s.nodeValue??""),s.parentNode?.removeChild(s)),this.liveOwnScriptEl=null}if(typeof SVGElement<"u"&&this.el instanceof SVGElement){let s=new DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${e}</svg>`,"image/svg+xml").documentElement,a=document.createDocumentFragment();return Array.from(s.childNodes).forEach(c=>{a.appendChild(document.importNode(c,!0))}),this.domMorpher.morphChildren(this.el,a),this.invalidateTraversalCache(),!0}let r=le(e,this.el.tagName.toLowerCase()).root;return this.loopRowCache!==null&&!this.loopRowCache.prepareDirectBuilds(r)?!1:(e.includes("<template")&&e.includes("pp-component")&&this.ownedTemplateManager.materializeTemplateComponentBoundaries(r),e.includes("<script")&&Oe(r),this.syncTrackedPortals(r),this.domMorpher.morphChildren(this.el,r),this.invalidateTraversalCache(),this.loopRowCache?.finishDirectBuilds()??!0)}canAttemptStringlessMount(){return this.lastRenderedHtml===""&&this.bodyPlan!==null&&!this.bodyPlanDisabled&&this.captureNeeds===0&&!this.usesLoops&&this.__ppBoundaryHtmlFn===null&&this.ownedChildren.size===0&&this._ownedTemplateManager===null}tryBodyPlanCommit(e,t,n){let r=this.bodyPlan;if(r===null||this.bodyPlanDisabled||!(this.el instanceof HTMLElement))return!1;let i=this.bodyPlanValuesFn;if(i===null){let h=this.pipelineBlueprint;if(i=h?.bodyValuesFns.get(n)??null,i===null){try{i=new Function(...e,`"use strict"; return [${r.exprs.join(", ")}];`)}catch{return this.bodyPlanDisabled=!0,!1}h?.bodyValuesFns.set(n,i)}this.bodyPlanValuesFn=i}let o;try{o=i(...t)}catch{return this.bodyPlanValues=null,!1}for(let h=0;h<r.size;h++){let d=o[h];if(d!==null&&(typeof d=="object"||typeof d=="function"||typeof d=="symbol"))return this.bodyPlanValues=null,!1}let s=this.lastRenderedHtml==="";s&&this.liveOwnScriptEl!==null&&(this.liveOwnScriptEl.remove(),this.liveOwnScriptEl=null);let a=this.el.firstElementChild;if(a===null||a.tagName!==r.rootTag||a.nextElementSibling!==null)return this.bodyPlanValues=null,!1;let c=this.bodyPlanValues,u;if(c===null||s)u=r.fullMask;else{u=0;let h=r.slotBitsByValue;for(let d=0;d<r.size;d++)Object.is(o[d],c[d])||(u|=h[d]);if(u===0)return this.lastRenderedHtml===gt?!0:(this.bodyPlanDisabled=!0,this.bodyPlanValues=null,!1)}return u!==0&&!ve(a,r.applyPlan,o,u)?(this.bodyPlanValues=null,!1):(this.bodyPlanValues=o,!0)}applyLoopPatches(e){this.morphingFromCommittedRender=!0;let t=null;for(let n of e){let r=n.patches.some(h=>h.html.includes("pp-component")),i=this.resolveLoopContainer(n.loopId,n.patches[0].key,r);if(!i)return!1;let o=this.ensureLoopKeyIndex(i),s="";for(let h of n.patches)s+=h.html;if(s.includes("__PP_")){let h=this.templateFn?.__ppRestoreArtifacts;if(!h)return!1;s=h(s)}let a=le(s,i.tagName.toLowerCase());s.includes("<script")&&Oe(a.root);let c=[];for(let h=a.root.firstElementChild;h;h=h.nextElementSibling)c.push(h);if(c.length!==n.patches.length)return!1;let u=n.patches;for(let h=0;h<u.length;h++){let d=u[h],p=o.get(d.key);if(!p||p.parentNode!==i)return!1;let f=this.domMorpher.morphPatchedRow(i,p,c[h]);if(f!==p){if(V(f)||f.querySelector(`[${j}]`)!==null)return!1;o.set(d.key,f)}else d.html.includes("pp-component")&&(t??=[]).push(p)}}return t!==null&&this.nestedBoundaryManager.refreshPatchedBoundaries(t),!0}ensureLoopKeyIndex(e){let t=e,n=t.__ppLoopKeyIndex;if(!n){n=new Map;for(let r=e.firstElementChild;r;r=r.nextElementSibling){let i=r.getAttribute("key");i!==null&&i.length>0&&!n.has(i)&&n.set(i,r)}t.__ppLoopKeyIndex=n}return n}createLoopValuePatchSink(){return{begin:(e,t,n)=>{let r=this.resolveLoopContainer(e,t,n);return r?{container:r,index:this.ensureLoopKeyIndex(r)}:null},onBoundaryRowPatched:e=>{(this._patchedBoundaryRows??=[]).push(e)},reportPatchAbandoned:()=>{console.warn(`[PP-WARN] Loop row patching was abandoned for component "${this.id}" because a patched row was no longer mounted. Rendering without row patching.`)}}}loopSearchRoots(){let e=this._portalManager?.elements();if(!e||e.length===0)return[this.el];let t=[this.el];for(let n of e)this.el.contains(n)||t.push(n);return t}ownsSurfaceElement(e){return this.el.contains(e)||(this._portalManager?.contains(e)??!1)}resolveLoopContainer(e,t,n){let r=this._loopContainers?.get(e);if(r&&r.el.isConnected&&this.ownsSurfaceElement(r.el))return n&&!r.providerFree?null:r.el;try{let o=`[key="${t.replace(/["\\]/g,"\\$&")}"]`,s=this.loopSearchRoots(),a=null,c=!0;for(let h of s){let d=h.querySelectorAll(o);for(let p=0;p<d.length;p++){let f=d[p],y=f.parentElement,m=!1,g=!1;for(;y&&y!==h;){if(V(y)){m=!0;break}y.tagName.toLowerCase()==="pp-context-provider"&&(g=!0),y=y.parentElement}if(!(m||y!==h)){if(a!==null)return null;a=f,c=!g}}}let u=a===null?null:a.parentElement;return!u||u.namespaceURI!=="http://www.w3.org/1999/xhtml"||((this._loopContainers??=new Map).set(e,{el:u,providerFree:c}),n&&!c)?null:u}catch{return null}}isEffectManagedSurfaceElement(e,t){return this.attributeSyncManager.isEffectManagedSurfaceElement(e,t)}collectEventElements(e){this.traversalManager.collectEventElements(e,this.pendingEventElements??=new Set)}hasEventAttributes(e){return dt(e)}invalidateTraversalCache(){this._traversalManager?.invalidate(),this._eventManager?.invalidateElementCountCache()}getTraversalCache(){return this.traversalManager.getCache()}collectManagedInputs(){return this.traversalManager.collectManagedInputs()}resolveForwardedComponentRefTarget(e){if(e.getAttribute("pp-ref-forward")!=="true")return e;let t=e,n=new Set;for(;!n.has(t);){if(n.add(t),!(t.getAttribute("style")||"").toLowerCase().replace(/\s+/g,"").includes("display:contents"))return t;let i=Array.from(t.children).filter(o=>o instanceof HTMLElement&&V(o));if(i.length!==1)return console.error(`[PP-ERROR] Cannot forward pp-ref through component "${K(t)||"unknown"}": expected exactly one child component root, found ${i.length}. Render one x-* root or consume ppRef explicitly in the component.`),e;t=i[0]}return console.error(`[PP-ERROR] Cannot forward pp-ref through component "${K(e)||"unknown"}": detected a component-root cycle.`),e}syncAttributes(e,t,n=!1,r=!1,i){this.attributeSyncManager.syncAttributes(e,t,n,r,i)}bindRefs(e,t,n){let r=this.getTraversalCache(),i=new Map;for(let o=0;o<r.refElements.length;o++){let s=r.refElements[o],a=s,c=s!==this.el&&V(s),u=s.getAttribute("data-pp-ref"),h=s.getAttribute("pp-ref-owner"),d=null;if(u)this.__ppRefStore.has(u)?(s.removeAttribute("data-pp-ref"),this.__ppRefCaptureIdsByElement.set(s,u),d=u):c||(s.removeAttribute("data-pp-ref"),this.__ppRefCaptureIdsByElement.set(s,u),d=u);else{let m=this.__ppRefCaptureIdsByElement.get(s);m&&(this.__ppRefStore.has(m)||this.resolveCapturedRefValue(m,h)!==void 0?d=m:this.__ppRefCaptureIdsByElement.delete(s))}if(d){let m=this.resolveCapturedRefValue(d,h);if(typeof m=="function"||m&&typeof m=="object"&&"current"in m){let g=this.refBindingManager.ensureBindingId(a,"captured");i.set(g,{element:this.resolveForwardedComponentRefTarget(s),value:m})}else u&&d.startsWith(`ppref_${this.id}_`)&&console.warn(`[PP-WARN] Missing captured ref for id="${d}"`)}let p=s.getAttribute("pp-ref"),f=p||this.__ppRefExprsByElement.get(s)||null;if(!f)continue;let y=this.resolvePlainRefValue(f,e,t,n);if(typeof y=="function"||y&&typeof y=="object"&&"current"in y){p&&s.removeAttribute("pp-ref"),this.__ppRefExprsByElement.set(s,f);let m=this.refBindingManager.ensureBindingId(a,"plain");i.set(m,{element:this.resolveForwardedComponentRefTarget(s),value:y});continue}p&&c||(p&&(s.removeAttribute("pp-ref"),this.__ppRefExprsByElement.set(s,f)),Object.prototype.hasOwnProperty.call(this.latestScope,f)||console.warn(`[PP-WARN] Could not resolve pp-ref="${f}"`))}this.refBindingManager.commit(i)}bindControlledSelectValues(e){this.formControlManager.bindControlledSelectValues(e,this.__ppSelectValueStore)}bindControlledCheckedValues(e){this.formControlManager.bindControlledCheckedValues(e,this.__ppCheckedValueStore)}bindControlledInputValues(e){this.formControlManager.bindControlledInputValues(e,this.__ppInputValueStore)}bindUncontrolledInputDefaults(e){for(let t=0;t<e.length;t++){let n=e[t];if(!n.__ppManagedInputMounted){let i=this.formControlManager.resolveDefaultValueBinding(n,this.__ppDefaultValueStore);if(i!==void 0&&this.formControlManager.applyUncontrolledDefaultValue(n,i),n instanceof HTMLInputElement){let o=this.formControlManager.resolveDefaultCheckedBinding(n,this.__ppDefaultCheckedStore);o!==void 0&&this.formControlManager.applyUncontrolledDefaultChecked(n,o)}}else this.formControlManager.resolveDefaultValueBinding(n,this.__ppDefaultValueStore),n instanceof HTMLInputElement&&this.formControlManager.resolveDefaultCheckedBinding(n,this.__ppDefaultCheckedStore);n.__ppManagedInputMounted=!0}}bindUncontrolledFormResets(e){this.formControlManager.syncUncontrolledFormResets(this.id,e,()=>this.collectManagedInputs())}bootstrapNestedComponents(){try{this.nestedBoundaryManager.bootstrap()}finally{this.forceChildBoundaryRefresh=!1}}materializeNestedBoundaryFormDefaults(e){this._formControlManager===null&&this.__ppInputValueStore.size===0&&this.__ppCheckedValueStore.size===0&&this.__ppDefaultValueStore.size===0&&this.__ppDefaultCheckedStore.size===0||this.formControlManager.materializeNestedBoundaryFormDefaults(e,{inputValueStore:this.__ppInputValueStore,checkedValueStore:this.__ppCheckedValueStore,defaultValueStore:this.__ppDefaultValueStore,defaultCheckedStore:this.__ppDefaultCheckedStore})}forceUpdate(){this.lastRenderedHtml="",this.render()}destroyNestedComponents(){if(b.hasChildren(this.id)){b.beginTopologyBatch();try{b.forEachDescendant(this.id,e=>{let t=b.getInstance(e);t&&t!==this&&t.destroy?.()})}finally{b.endTopologyBatch()}}}destroy(){let e=this.startPerfTimer();this.destroyNestedComponents(),this._formControlManager?.clearResetHandlers(this.id),this.hooksSystem?.dispose(),this._refBindingManager?.clearAll(),this.clearLoopValues(),this.loopRowCache?.clear(),this._portalManager?.destroyAll();let t=this._contextManager?this._contextManager.destroy():b.removeContextTracking(this.id);this._eventManager?.clearCache(),b.removeState(this.id),b.removeScope(this.id),b.removeOwnedTemplates(this.id),b.removeInstance(this.id),l.perfEnabled?this.endPerfTimer("destroy",e):l.perfStats.delete(this.id),t&&this._contextManager?.refreshConsumers(t)}},yt=null,xe=null,Cr=(l,e)=>{(xe??=new Map).set(l,e)};function Xt(l,e){let t=e[G];if(t===void 0)return null;let n={};for(let r=0;r<l.length;r++){let i=l[r];n[i.camel]=i.direct?t[i.name]:i.staticValue}return n}function Pn(l,e){if(e===null)return null;let t=l;for(let n=0;n<e.length&&t!==null;n++){let r=t.firstElementChild;for(let i=e[n];i>0&&r!==null;i--)r=r.nextElementSibling;t=r}return t===null||t.tagName.toLowerCase()!=="script"||t.hasAttribute("type")?null:t}function wn(l,e){let t=new Set([l]),n=b.getParent(l);for(;n&&!t.has(n);){if(t.add(n),b.getInstance(n)?.captureComponentError?.(e))return!0;n=b.getParent(n)??null}return!1}function Pr(l,e){let t=e.blueprint;if(!e.stringlessMounted||t===null||!t.propsOnlyRuntime||t.captureNeeds!==0||t.usesLoops||t.hasBoundaryCall||t.bodyPlan===null||t.scopeShape===null||e.propsSchema===null||e.scriptPath===null&&e.hasScript||dt(l)||l instanceof HTMLInputElement||l instanceof HTMLTextAreaElement||l instanceof HTMLSelectElement||l.hasAttribute("pp-ref")||l.hasAttribute("data-pp-ref"))return!1;let n=t.scopeShape,r=t.bodyPlan,i=t.bodyValuesFns.get(n.sortedKeySig)??null;if(i===null){try{i=new Function(...n.sortedKeys,`"use strict"; return [${r.exprs.join(", ")}];`)}catch{return!1}t.bodyValuesFns.set(n.sortedKeySig,i)}return{derivation:e,blueprint:t,schema:e.propsSchema,childrenHtml:e.childHtml,scriptPath:e.scriptPath,scopeKeys:n.sortedKeys,plan:r,valuesFn:i,renderFunction:t.renderFunction}}function Rn(l,e,t,n,r,i){l[ee]=e.derivation,i&&(l.__ppFreshIdentity=!0),t!==null&&(yt={scope:t,provisions:n});try{new Z(l,r)}finally{yt=null}return!0}function kn(l,e,t){let n=Fe(Cr);try{return l.renderFunction({props:e})}catch(r){return xe=null,wn(t,r)||console.error("[PP-ERROR] Render Cycle Failed",r),null}finally{Fe(n)}}function xn(l,e){let t;try{t=l.valuesFn(...Pe(e,l.scopeKeys))}catch{return null}for(let n=0;n<l.plan.size;n++){let r=t[n];if(r!==null&&(typeof r=="object"||typeof r=="function"||typeof r=="symbol"))return null}return t}function An(l,e){let t=l.firstElementChild;return t!==null&&t.tagName===e.rootTag&&t.nextElementSibling===null?t:null}function wr(l,e,t){let n=Xt(e.schema,l);if(n===null)return!1;n.children=e.childrenHtml;let r=l;delete l[ee];let i=r.__ppFreshIdentity===!0;i&&delete r.__ppFreshIdentity;let o=r.__ppRuntimeComponentId??K(l)??"",s=new Wt(l,o,r.__ppRuntimeParentId??null,n,e);b.registerInstance(o,s),b.saveParent(o,s.parentId);let a=kn(e,n,o);if(a===null)return!0;let c=xe,u=null;if(c===null){if(u=xn(e,a),u!==null&&e.scriptPath!==null){let h=Pn(l,e.scriptPath);h!==null?h.remove():u=null}if(u!==null){let h=An(l,e.plan);(h===null||!ve(h,e.plan.applyPlan,u,e.plan.fullMask))&&(u=null)}}else xe=null;return u===null?(s.handedOver=!0,Rn(l,e,a,c,t,i)):(b.saveState(o,i?$e:b.getState(o)??$e),s.latestScope=a,b.saveScope(o,a),s.bodyPlanValues=u,!0)}function Rr(l,e){let t=l[ee];if(t!==void 0&&t.childHtml!==null&&!Z.getPerfEnabled()){let n=t.flyweight;if(n===null&&(n=Pr(l,t),t.flyweight=n),n!==!1&&wr(l,n,e))return}new Z(l,e)}var Wt=class{constructor(e,t,n,r,i){this.el=e;this.id=t;this.parentId=n;this.props=r;this.shape=i;this.pipelineBlueprint=i.blueprint}el;id;parentId;props;shape;latestScope=null;bodyPlanValues=null;renderCount=1;handedOver=!1;pipelineBlueprint;captureComponentError(){return!1}refreshPropsFromParent(e=!1,t){let n=this.shape,r=Xt(n.schema,this.el);if(r===null){this.materialize(null,null,t);return}if(r.children=n.childrenHtml,!e&&xt(this.props,r))return;this.props=r,this.renderCount++;let i=kn(n,r,this.id);if(i===null)return;let o=xe,s=null;if(o===null?s=xn(n,i):xe=null,s!==null){let a=n.plan,c=An(this.el,a);if(c!==null){let u=this.bodyPlanValues,h;if(e||u===null)h=a.fullMask;else{h=0;let d=a.slotBitsByValue;for(let p=0;p<a.size;p++)Object.is(s[p],u[p])||(h|=d[p])}if(h===0||ve(c,a.applyPlan,s,h)){this.bodyPlanValues=s,this.latestScope=i,b.saveScope(this.id,i);return}}}this.materialize(i,o,t)}materialize(e,t,n){this.handedOver=!0,Rn(this.el,this.shape,e,t,n,!1)}destroy(){b.getInstance(this.id)===this&&(vn(this.shape.derivation,this,b.getState(this.id)),b.removeContextTracking(this.id),b.removeState(this.id),b.removeScope(this.id),b.removeInstance(this.id))}};function Mn(l,e,t=typeof window<"u"?window:globalThis,n=!0,r={}){let{cache:i=!1,configurable:o=!1,resetOnNull:s=!1}=r,a=!1,c,u=()=>{if(i&&a)return c;let h=e,d=h!==null&&(typeof h=="function"||typeof h=="object")&&"getInstance"in h&&typeof h.getInstance=="function"?h.getInstance():e;return i&&(c=d,a=!0),d};if(Object.defineProperty(t,l,{get(){return u()},set(h){if(s&&h===null){a=!1;return}console.warn(`[${l}] Cannot override global ${l}; ignoring.`,h)},configurable:o,enumerable:!0}),n)try{t[l]}catch(h){console.error(`Failed to initialize ${l}:`,h)}}function Ae(l){if(!l)return null;try{let e=new URL(l,window.location.href);return e.origin!==window.location.origin?(console.warn("Ignoring cross-origin redirect target from server response:",l),null):e.pathname+e.search+e.hash}catch(e){return console.warn("Ignoring invalid redirect target from server response:",l,e),null}}function _t(l){let e=l.headers.get("X-PP-Redirect"),t=Ae(e);if(t)return t;let n=l.headers.get("Location"),r=l.status;return n&&r>=300&&r<400?Ae(n):null}var pe=class extends Error{status;errors;requestId;body;constructor(e,t,n=null){super(e),this.name="RpcError",this.status=t,this.body=n,this.requestId=n&&typeof n.requestId=="string"?n.requestId:null,this.errors=n&&typeof n.errors=="object"&&n.errors!==null&&!Array.isArray(n.errors)?n.errors:{}}},Et=class{constructor(e){this.redirect=e}redirect;activeAbortController=null;async call(e,t={},n=!1){let r=null,i=typeof n=="boolean"?{abortPrevious:n}:n;try{i.abortPrevious&&this.activeAbortController&&(this.activeAbortController.abort(),this.activeAbortController=null),r=new AbortController,i.abortPrevious&&(this.activeAbortController=r);let o=this.resolveUrl(i.url),s=this.resolveCredentials(o,i.credentials),c={"X-CSRF-Token":await this.ensureCsrfToken(o,s,i.csrfUrl),"X-PP-RPC":"true","X-PulsePoint-Wire":"true","X-PP-Function":e,"X-Requested-With":"XMLHttpRequest",Accept:"application/json, text/event-stream"},u=Object.values(t).some(y=>y instanceof File||y instanceof FileList&&y.length>0),h;if(u){let y=this.createFormData(t);if(i.onUploadProgress){let m=await this.uploadWithProgress({url:o.toString(),headers:c,body:y,controller:r,credentials:s,options:i});return this.clearActiveController(r),m}h={method:"POST",headers:c,body:y,credentials:s,signal:r.signal}}else h={method:"POST",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(t),credentials:s,signal:r.signal};let d=await fetch(o.toString(),h);await this.assertSuccessfulResponse(d);let p=_t(d);if(p)return await this.redirect(p),this.clearActiveController(r),{redirected:!0,to:p};if((d.headers.get("Content-Type")||"").includes("text/event-stream")&&d.body){i.onStream||console.warn("RPC returned a stream, but no onStream handler provided.");try{await this.handleStream(d.body,i)}finally{this.clearActiveController(r)}return}return this.clearActiveController(r),await d.json()}catch(o){if(this.clearActiveController(r),o instanceof Error&&o.name==="AbortError")return console.log("Request was cancelled"),{cancelled:!0};if(i.onStreamError){i.onStreamError(o);return}throw console.error("RPC error:",o),o}}getCsrfToken(){let e=window.location.port?[`pp_csrf_${window.location.port}`,"pp_csrf"]:["pp_csrf"];for(let t of e){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=document.cookie.match(new RegExp(`(?:^|;\\s*)${n}=([^;]*)`));if(r)return decodeURIComponent(r[1])}return""}resolveUrl(e){let t=window.location.pathname.replace(/\/+$/,"")||"/";return new URL(e??t,window.location.origin)}resolveCredentials(e,t){return t||(e.origin===window.location.origin?"same-origin":"include")}async ensureCsrfToken(e,t,n){let r=this.getCsrfToken();if(r!==""||t==="omit")return r;let i=new URL(n??e.toString(),window.location.origin);return await fetch(i.toString(),{method:"GET",credentials:t,cache:"no-store",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/html, application/json, */*"}}),r=this.getCsrfToken(),r}createFormData(e){let t=new FormData,n=[];for(let[r,i]of Object.entries(e))i instanceof File?n.push([r,i]):i instanceof FileList?Array.from(i).forEach(o=>n.push([r,o])):i!=null&&t.append(r,typeof i=="object"?JSON.stringify(i):String(i));for(let[r,i]of n)t.append(r,i);return t}async assertSuccessfulResponse(e){if(e.ok)return;let t=await e.json().catch(()=>null);throw e.status===401?new pe("Authentication required",401,t):e.status===403?new pe("Permission denied",403,t):!t&&e.status===415?new pe("Server rejected data format (415).",415,null):new pe(t?.error||`Request failed: ${e.status} ${e.statusText}`,e.status,t)}clearActiveController(e){this.activeAbortController===e&&(this.activeAbortController=null)}uploadWithProgress(e){let{url:t,headers:n,body:r,controller:i,credentials:o,options:s}=e;return new Promise((a,c)=>{let u=new XMLHttpRequest;u.open("POST",t,!0),u.withCredentials=o==="include";for(let[d,p]of Object.entries(n))u.setRequestHeader(d,p);let h=()=>{try{u.abort()}catch{}};i.signal.addEventListener("abort",h,{once:!0}),u.upload&&s.onUploadProgress&&(u.upload.onprogress=d=>{let p=d.lengthComputable?d.total:null,f=d.lengthComputable&&d.total>0?Math.min(100,Math.max(0,d.loaded/d.total*100)):null;s.onUploadProgress?.({loaded:d.loaded,total:p,percent:f})}),u.onerror=()=>{i.signal.removeEventListener("abort",h),c(new Error("Network error (XHR upload)."))},u.onload=async()=>{if(i.signal.removeEventListener("abort",h),u.status<200||u.status>=300){let y=null;try{y=JSON.parse(u.responseText||"null")}catch{}if(u.status===401)return c(new pe("Authentication required",401,y));if(u.status===403)return c(new pe("Permission denied",403,y));let m=y?.error||y?.message||`Request failed: ${u.status} ${u.statusText}`;return c(new pe(m,u.status,y))}let d=Ae(u.getResponseHeader("X-PP-Redirect")||(u.status>=300&&u.status<400?u.getResponseHeader("Location"):null));if(d)try{return await this.redirect(d),s.onUploadComplete?.(),a({redirected:!0,to:d})}catch(y){return c(y)}let p=u.responseText??"",f=p;try{f=JSON.parse(p)}catch{}s.onUploadComplete?.(),a(f)};try{u.send(r)}catch(d){i.signal.removeEventListener("abort",h),c(d)}})}async handleStream(e,t){let n=e.getReader(),r=new TextDecoder,i="";try{for(;;){let{done:o,value:s}=await n.read();if(o){t.onStreamComplete?.();break}i+=r.decode(s,{stream:!0});let a=i.split(`
44
- `);i=a.pop()||"";for(let c of a){if(c.trim()===""||!c.startsWith("data: "))continue;let u=c.slice(6),h=u;try{(u==="true"||u==="false"||u==="null"||!isNaN(Number(u))||u.startsWith("{")||u.startsWith("[")||u.startsWith('"'))&&(h=JSON.parse(u))}catch{}t.onStream?.(h)}}}catch(o){if(t.onStreamError)t.onStreamError(o);else throw o}finally{n.releaseLock()}}};var kr="/__pulsepoint/ws";function xr(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length===1&&typeof l.error=="string"?l.error:null}var vt=class{active=new Set;connect(e,t={},n={}){let r=new URL(n.url??kr,window.location.origin);r.searchParams.set("name",e),r.protocol=r.protocol==="https:"?"wss:":"ws:";let i=new WebSocket(r.toString());this.active.add(i);let o=[],s=!1,a=!1;return i.onopen=()=>{i.send(JSON.stringify(t??{})),s=!0;for(let c of o.splice(0))i.send(c);n.onOpen?.()},i.onmessage=c=>{if(typeof c.data!="string")return;let u=c.data;try{u=JSON.parse(c.data)}catch{}let h=xr(u);if(h!==null){a=!0,n.onError?.(new Error(h));return}n.onMessage?.(u)},i.onerror=()=>{!s&&!a&&(a=!0,n.onError?.(new Error(`Socket "${e}" could not connect. The server refuses unknown names, cross-origin pages, and \u2014 for auth sockets \u2014 missing sessions before the connection opens.`)))},i.onclose=c=>{this.active.delete(i),n.onClose?.({code:c.code,reason:c.reason,wasClean:c.wasClean})},{send:c=>{if(i.readyState===WebSocket.CLOSING||i.readyState===WebSocket.CLOSED)return!1;let u=JSON.stringify(c);if(!s)return o.push(u),!0;try{return i.send(u),!0}catch{return!1}},close:(c,u)=>{try{i.close(c??1e3,u)}catch{}},get readyState(){return i.readyState}}}};var Ar="opacity 0.18s ease-out",Ln=15e3,In={bootstrap:()=>{ke.materializeTemplateComponentBoundaries(document.body),rn(document.body),en(document).forEach(l=>{new Z(l)})}},Gt=class l{static instance=null;rpcClient=new Et(e=>this.redirect(e));socketClient=new vt;navigationEnabled=!1;boundHandleLinkClick=null;boundHandlePopState=null;boundHandleTrackedScroll=null;isNavigating=!1;pendingHistoryStateSaveTimer=null;lastHistoryStateSaveAt=0;pendingProgrammaticScrollPersistenceTimer=null;RESET_SCROLL_ATTR="pp-reset-scroll";HISTORY_SCROLL_STATE_KEY="__ppScrollPositions";TRACKED_SCROLL_PERSISTENCE_INTERVAL_MS=150;PROGRAMMATIC_SCROLL_SETTLE_MS=120;mounted=!1;suppressTrackedScrollPersistence=!1;pendingRevealFrame=null;pendingTransitionUnlockFrame=null;hydrationBodySnapshot=null;previousHistoryScrollRestoration=null;trackedScrollElements=new Set;didInitialScrollDiscovery=!1;SCROLL_KEY_ATTR="pp-scroll-key";static PUBLIC_METHODS=["createContext","mount","redirect","rpc","socket","enablePerf","disablePerf","getPerfStats","resetPerfStats"];constructor(){}mount(){this.mounted||(this.mounted=!0,this.disableTransitions(),this.hideBodyForHydration(!0),In.bootstrap(),this.scheduleHydrationReveal(),this.enableSPANavigation())}boundPublicApi=null;createComponentRuntime(e){if(this.boundPublicApi===null){let t={};for(let n of l.PUBLIC_METHODS){let r=this[n];typeof r=="function"?t[n]=r.bind(this):r!==void 0&&(t[n]=r)}this.boundPublicApi=t}return Object.assign({},this.boundPublicApi,e)}createContext(e){return Sn(e)}enablePerf(){Z.setPerfEnabled(!0)}disablePerf(){Z.setPerfEnabled(!1)}getPerfStats(){return Z.getPerfStats()}resetPerfStats(){Z.resetPerfStats()}disableTransitions(){if(document.getElementById("pp-disable-transitions"))return;let e=document.createElement("style");e.id="pp-disable-transitions",e.textContent=`
45
- *, *::before, *::after {
46
- transition: none !important;
47
- animation: none !important;
48
- }
49
- `,document.head.insertBefore(e,document.head.firstChild)}enableTransitions(){let e=document.getElementById("pp-disable-transitions");e&&e.remove()}requestFrame(e){return typeof requestAnimationFrame=="function"?requestAnimationFrame(e):window.setTimeout(()=>e(performance.now()),16)}cancelFrame(e){if(typeof cancelAnimationFrame=="function"){cancelAnimationFrame(e);return}window.clearTimeout(e)}cancelScheduledHydrationReveal(){this.pendingRevealFrame!==null&&(this.cancelFrame(this.pendingRevealFrame),this.pendingRevealFrame=null),this.pendingTransitionUnlockFrame!==null&&(this.cancelFrame(this.pendingTransitionUnlockFrame),this.pendingTransitionUnlockFrame=null)}cancelPendingProgrammaticScrollPersistence(){this.pendingProgrammaticScrollPersistenceTimer!==null&&(window.clearTimeout(this.pendingProgrammaticScrollPersistenceTimer),this.pendingProgrammaticScrollPersistenceTimer=null)}beginProgrammaticScrollPersistencePause(){this.suppressTrackedScrollPersistence=!0,this.cancelPendingHistoryStateSave(),this.cancelPendingProgrammaticScrollPersistence()}scheduleProgrammaticScrollPersistence(){this.suppressTrackedScrollPersistence&&(this.cancelPendingProgrammaticScrollPersistence(),this.pendingProgrammaticScrollPersistenceTimer=window.setTimeout(()=>{this.pendingProgrammaticScrollPersistenceTimer=null,this.suppressTrackedScrollPersistence=!1,this.persistCurrentHistoryScrollState()},this.PROGRAMMATIC_SCROLL_SETTLE_MS))}scrollElementIntoView(e){this.beginProgrammaticScrollPersistencePause(),e.scrollIntoView({behavior:"smooth"}),this.scheduleProgrammaticScrollPersistence()}normalizeHydrationBodySnapshotStyle(e){if(e===null)return null;let t=document.createElement("div");t.setAttribute("style",e),t.style.opacity==="0"&&t.style.removeProperty("opacity"),t.style.pointerEvents==="none"&&t.style.removeProperty("pointer-events"),t.style.userSelect==="none"&&t.style.removeProperty("user-select"),t.style.transition.replace(/\s+/g," ").trim().toLowerCase()===Ar&&t.style.removeProperty("transition");let n=t.getAttribute("style")?.trim()??"";return n===""?null:n}hideBodyForHydration(e=!1){if(!this.hydrationBodySnapshot){let t=document.body.getAttribute("style");this.hydrationBodySnapshot={style:e?this.normalizeHydrationBodySnapshotStyle(t):t,hadAriaBusy:document.body.hasAttribute("aria-busy"),ariaBusy:document.body.getAttribute("aria-busy"),hadInert:document.body.hasAttribute("inert"),inert:document.body.getAttribute("inert")}}document.body.style.opacity="0",document.body.style.pointerEvents="none",document.body.style.userSelect="none",document.body.setAttribute("aria-busy","true"),document.body.setAttribute("inert","")}scheduleHydrationReveal(e){this.cancelScheduledHydrationReveal(),this.pendingRevealFrame=this.requestFrame(()=>{this.pendingRevealFrame=null,this.restoreBodyAccessibility(),e?.(),this.pendingTransitionUnlockFrame=this.requestFrame(()=>{this.pendingTransitionUnlockFrame=null,this.enableTransitions()})})}restoreBodyAccessibility(){let e=this.hydrationBodySnapshot;if(!e){document.body.style.removeProperty("transition"),document.body.style.removeProperty("opacity"),document.body.style.removeProperty("pointer-events"),document.body.style.removeProperty("user-select"),document.body.removeAttribute("inert"),document.body.removeAttribute("aria-busy");return}e.style===null?document.body.removeAttribute("style"):document.body.setAttribute("style",e.style),e.hadInert?document.body.setAttribute("inert",e.inert??""):document.body.removeAttribute("inert"),e.hadAriaBusy?document.body.setAttribute("aria-busy",e.ariaBusy??""):document.body.removeAttribute("aria-busy"),this.hydrationBodySnapshot=null}static getInstance(){if(!this.instance){this.instance=new l;try{localStorage.getItem("pp-perf")==="1"&&Z.setPerfEnabled(!0)}catch{}}return this.instance}enableSPANavigation(){this.navigationEnabled||(this.navigationEnabled=!0,this.boundHandleLinkClick=this.handleLinkClick.bind(this),this.boundHandlePopState=this.handlePopState.bind(this),this.boundHandleTrackedScroll=this.handleTrackedScroll.bind(this),"scrollRestoration"in history&&(this.previousHistoryScrollRestoration=history.scrollRestoration,history.scrollRestoration="manual"),document.addEventListener("click",this.boundHandleLinkClick),window.addEventListener("popstate",this.boundHandlePopState),document.addEventListener("scroll",this.boundHandleTrackedScroll,!0),window.addEventListener("scroll",this.boundHandleTrackedScroll,{passive:!0}),this.registerInitiallyScrolledElements(),this.persistCurrentHistoryScrollState())}handleLinkClick(e){if(!this.navigationEnabled)return;let t=this.getNavigationTarget(e.target);if(!t)return;let n=t.closest("a");if(!(!n||!n.href))try{let r=new URL(n.href),i=r.origin!==window.location.origin,o=r.pathname===window.location.pathname&&r.search===window.location.search,s=n.getAttribute("pp-spa")==="false";if(i||n.target==="_blank"||n.hasAttribute("download")||s||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;if(e.preventDefault(),o){let a=r.hash;if(a){e.preventDefault(),this.persistCurrentHistoryScrollState(),history.pushState(this.buildHistoryState(),"",r.pathname+r.search+a);let c=document.querySelector(a);c&&this.scrollElementIntoView(c);return}}this.navigateTo(r.pathname+r.search+r.hash)}catch(r){console.error("Link click navigation error:",r)}}getNavigationTarget(e){return e instanceof Element?e:e instanceof Node?e.parentElement:null}handleTrackedScroll(e){if(!this.navigationEnabled||this.isNavigating)return;if(e.target instanceof HTMLElement&&this.trackedScrollElements.add(e.target),this.suppressTrackedScrollPersistence){this.scheduleProgrammaticScrollPersistence();return}let n=Date.now()-this.lastHistoryStateSaveAt;if(n>=this.TRACKED_SCROLL_PERSISTENCE_INTERVAL_MS){this.cancelPendingHistoryStateSave(),this.persistCurrentHistoryScrollState();return}this.pendingHistoryStateSaveTimer===null&&(this.pendingHistoryStateSaveTimer=window.setTimeout(()=>{this.pendingHistoryStateSaveTimer=null,this.persistCurrentHistoryScrollState()},this.TRACKED_SCROLL_PERSISTENCE_INTERVAL_MS-n))}async handlePopState(e){let t=this.getCurrentUrl(),n=this.getScrollPositionsFromHistoryState(e.state);await this.navigateTo(t,!1,n)}async navigateTo(e,t=!0,n=null){this.cancelPendingHistoryStateSave(),this.cancelPendingProgrammaticScrollPersistence(),this.suppressTrackedScrollPersistence=!1,this.isNavigating=!0;try{this.dispatchNavigationEvent("start",e),await this.showLoadingTransition();let r=await this.fetchPageContent(e);if("hardReload"in r){window.location.href=r.hardReload;return}if("redirect"in r){await this.navigateTo(r.redirect,t,n);return}let i=r,o=t?this.saveScrollPositions():null;this.updateBrowserHistory(e,t,o);let s=this.getResetScrollConfig(i);await this.updatePageContent(i),this.resetGlobalCaches(),In.bootstrap(),await this.handleScrollRestoration(t?o:n,s,t?"push":"history"),await this.handleNavigationCompletion(),this.dispatchNavigationEvent("complete",e)}catch(r){this.handleNavigationError(e,r)}finally{this.isNavigating=!1}}resetGlobalCaches(){b.clear(),U.clearCaches(),ce.clearCache()}getResetScrollConfig(e){if(e.body.getAttribute(this.RESET_SCROLL_ATTR)==="true")return{mode:"global",resetElementKeys:new Set,resetWindow:!1};let n=e.querySelectorAll(`[${this.RESET_SCROLL_ATTR}]`),r=new Set,i=!1;if(n.length>0)for(let o of Array.from(n))o.getAttribute(this.RESET_SCROLL_ATTR)==="true"&&(r.add(this.getElementKey(o)),i=!0);return{mode:"none",resetElementKeys:r,resetWindow:i}}handleScrollRestoration(e,t,n){let r=()=>{if(t.mode==="global"){window.scrollTo(0,0),document.documentElement.scrollTop=0,document.documentElement.scrollLeft=0,this.getTrackedScrollElements().forEach(s=>{(s.scrollTop||s.scrollLeft)&&(s.scrollTop=0,s.scrollLeft=0)});return}if(!(n==="history"&&!t.resetWindow&&!!e?.window))window.scrollTo(0,0),document.documentElement.scrollTop=0,document.documentElement.scrollLeft=0;else{let s=e?.window;s&&window.scrollTo(s.scrollLeft,s.scrollTop)}new Set([...Object.keys(e??{}).filter(s=>s!=="window"),...t.resetElementKeys]).forEach(s=>{let a=this.findScrollElementByKey(s);if(!a)return;this.trackedScrollElements.add(a);let c=e?.[s];t.resetElementKeys.has(s)?(a.scrollTop=0,a.scrollLeft=0):c&&(a.scrollTop=c.scrollTop,a.scrollLeft=c.scrollLeft)}),document.querySelectorAll(`[${this.RESET_SCROLL_ATTR}="true"]`).forEach(s=>{s.scrollTop=0,s.scrollLeft=0,this.trackedScrollElements.add(s)})};return r(),new Promise(i=>{requestAnimationFrame(()=>{r(),requestAnimationFrame(()=>{r(),i()})})})}saveScrollPositions(){let e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return this.didInitialScrollDiscovery||this.registerInitiallyScrolledElements(),this.getTrackedScrollElements().forEach(t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})}),e}getElementKey(e){return e.getAttribute(this.SCROLL_KEY_ATTR)||e.id||e.className||e.tagName}registerInitiallyScrolledElements(){this.didInitialScrollDiscovery=!0,document.querySelectorAll("*").forEach(e=>{(e.scrollTop||e.scrollLeft||e.hasAttribute(this.SCROLL_KEY_ATTR)||e.hasAttribute(this.RESET_SCROLL_ATTR))&&this.trackedScrollElements.add(e)})}getTrackedScrollElements(){let e=[];return this.trackedScrollElements.forEach(t=>{if(!t.isConnected){this.trackedScrollElements.delete(t);return}e.push(t)}),document.querySelectorAll(`[${this.SCROLL_KEY_ATTR}], [${this.RESET_SCROLL_ATTR}]`).forEach(t=>{this.trackedScrollElements.has(t)||(this.trackedScrollElements.add(t),e.push(t))}),e}findScrollElementByKey(e){for(let i of this.getTrackedScrollElements())if(this.getElementKey(i)===e)return i;let t=document.getElementById(e);if(t)return t;let n=document.getElementsByClassName(e)[0];if(n instanceof HTMLElement)return n;let r=document.getElementsByTagName(e)[0];return r instanceof HTMLElement?r:null}cancelPendingHistoryStateSave(){this.pendingHistoryStateSaveTimer!==null&&(window.clearTimeout(this.pendingHistoryStateSaveTimer),this.pendingHistoryStateSaveTimer=null)}buildHistoryState(e){let t=history.state,n=t&&typeof t=="object"&&!Array.isArray(t)?{...t}:{};return e?n[this.HISTORY_SCROLL_STATE_KEY]=e:delete n[this.HISTORY_SCROLL_STATE_KEY],n}getScrollPositionsFromHistoryState(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e[this.HISTORY_SCROLL_STATE_KEY];return!t||typeof t!="object"||Array.isArray(t)?null:t}persistCurrentHistoryScrollState(e=this.saveScrollPositions()){this.lastHistoryStateSaveAt=Date.now(),history.replaceState(this.buildHistoryState(e),"",this.getCurrentUrl())}getCurrentUrl(){return window.location.pathname+window.location.search+window.location.hash}teardownCurrentPageComponents(){b.destroyAll()}dispatchNavigationEvent(e,t,n){let r=`pp:navigation:${e}`,i=n?{url:t,error:n}:{url:t};document.dispatchEvent(new CustomEvent(r,{detail:i}))}async showLoadingTransition(){let e=document.getElementById("loading-file-1B87E");if(e){let n=this.findLoadingElement(e,window.location.pathname);if(n){await this.updateContentWithTransition(n);return}}let t=document.querySelector("[pp-loading-content='true']")||document.body;t&&!("startViewTransition"in document)&&await this.fadeOut(t,250)}async fetchPageContent(e){let t=new URL(e,window.location.origin).hash,n=new AbortController,r=window.setTimeout(()=>{n.abort()},Ln),i;try{i=await fetch(e,{signal:n.signal,headers:{"X-Requested-With":"XMLHttpRequest","X-PP-Navigation":"true","X-PulsePoint-Wire":"true",Accept:"text/html"}})}catch(p){throw p instanceof Error&&p.name==="AbortError"?new Error(`Navigation timed out after ${Math.round(Ln/1e3)}s: ${e}`):p}finally{window.clearTimeout(r)}if(!i.ok)throw new Error(`Navigation failed: ${i.status} ${i.statusText}`);let o=i.headers.get("X-PP-Root-Layout"),s=document.querySelector('meta[name="pp-root-layout"]'),a=s?s.getAttribute("content"):null;if(o&&a&&o!==a)return{hardReload:e};if(i.redirected){let p=Ae(i.url);if(!p)return{hardReload:e};let f=new URL(p,window.location.origin);if(t&&f.searchParams.has("next")){let y=f.searchParams.get("next");y&&!y.includes("#")&&f.searchParams.set("next",y+t)}return{redirect:f.pathname+f.search+f.hash}}let c=_t(i);if(c)return{redirect:c};let u=await i.text();return new DOMParser().parseFromString(u,"text/html")}updateBrowserHistory(e,t,n=null){t&&(this.persistCurrentHistoryScrollState(n??void 0),history.pushState(this.buildHistoryState(),"",e))}async updatePageContent(e){e.title&&(document.title=e.title),this.syncManagedHead(e);let t=e.body;this.syncBodyAttributes(t),this.teardownCurrentPageComponents(),document.body.innerHTML=t.innerHTML}syncManagedHead(e){let t="[data-pp-meta]";document.head.querySelectorAll(t).forEach(n=>n.parentNode?.removeChild(n)),e.head&&e.head.querySelectorAll(t).forEach(n=>{document.head.appendChild(document.importNode(n,!0))})}syncBodyAttributes(e){e&&(Array.from(document.body.attributes).forEach(t=>{t.name!=="style"&&document.body.removeAttribute(t.name)}),Array.from(e.attributes).forEach(t=>{t.name!=="style"&&document.body.setAttribute(t.name,t.value)}))}async handleNavigationCompletion(){let e=window.location.hash;if(!e)return;let t=document.querySelector(e);t&&this.scrollElementIntoView(t)}handleNavigationError(e,t){console.error("Navigation error:",t),this.restoreBodyAccessibility(),this.enableTransitions(),this.dispatchNavigationEvent("error",e,t),window.location.href=e}findLoadingElement(e,t){let n=t;for(;;){let r=e.querySelector(`div[pp-loading-url='${n}']`);if(r)return r;if(n==="/")break;let i=n.lastIndexOf("/");i<=0?n="/":n=n.substring(0,i)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){let t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;let{fadeIn:n,fadeOut:r}=this.parseTransition(e);await this.fadeOut(t,r),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250,i=e.querySelector("[pp-loading-transition]")?.getAttribute("pp-loading-transition");if(i){let o=JSON.parse(i);o&&typeof o=="object"?(t=this.parseTime(o.fadeIn??t),n=this.parseTime(o.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON -> default values (250 ms) will be used. String:",i)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise(n=>{e.style.transition=`opacity ${t}ms ease-out`,setTimeout(()=>{e.style.transition="",n()},t)})}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,setTimeout(()=>{e.style.transition=""},t)}parseTime(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)(ms|s|m)?$/);if(t){let n=parseInt(t[1],10),r=t[2];return r==="s"?n*1e3:r==="m"?n*60*1e3:n}return 0}async redirect(e){if(e)try{let t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:this.navigationEnabled?await this.navigateTo(t.pathname+t.search+t.hash):window.location.href=e}catch(t){console.error("Redirect error:",t)}}async rpc(e,t={},n=!1){return this.rpcClient.call(e,t,n)}socket(e,t={},n={}){return this.socketClient.connect(e,t,n)}};Mn("pp",{getInstance:()=>Gt.getInstance()},typeof window<"u"?window:globalThis,!0,{cache:!0,configurable:!0,resetOnNull:!0});export{In as ComponentInit,Gt as PPUtilities};
1
+ var e=new class{deferredEventDepth=0;callbacks=new Set;frameHandle=null;timerHandle=null;shouldDefer(){return this.deferredEventDepth>0}enqueue(e){this.callbacks.add(e),this.scheduleFlushOnNextFrame()}flush(){this.cancelScheduledFlush();let e=Array.from(this.callbacks);this.callbacks.clear(),e.forEach(e=>e())}runWithDeferral(e,t){e&&this.deferredEventDepth++;try{return t()}finally{e&&this.deferredEventDepth--}}scheduleFlushOnNextFrame(){if(null!==this.frameHandle||null!==this.timerHandle)return;let e=()=>{this.frameHandle=null,this.timerHandle=null,this.flush()};"function"!=typeof requestAnimationFrame?this.timerHandle=setTimeout(e,0):this.frameHandle=requestAnimationFrame(e)}cancelScheduledFlush(){null!==this.frameHandle&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(this.frameHandle),this.frameHandle=null,null!==this.timerHandle&&(clearTimeout(this.timerHandle),this.timerHandle=null)}},t=[],n=[],r=class r{stateUpdateScheduler;static anonymousIdCounter=0;static MAX_BOUNDARY_CAPTURES=5;boundaryError=null;hasErrorBoundaryHook=!1;boundaryErrorCaptureCount=0;uncaughtErrorHandler=null;hooks=[];currentIndex=0;onStateChange;componentLabel;pendingLayoutEffects=t;pendingEffects=t;currentEffectPhase=null;pendingSynchronousRenderUpdate=!1;pendingSynchronousLayoutUpdate=!1;pendingUpdate=!1;hasScheduledRender=!1;portalRegistrations=[];isRenderWindowOpen=!1;warnedHookOutsideRender=!1;warnedHookAfterDispose=!1;currentHookTypes=n;committedHookTypes=null;disposed=!1;constructor(t,n="unknown",r=e){this.stateUpdateScheduler=r,this.onStateChange=t,this.componentLabel=n}loadState(e){this.hooks=[...e]}getHooks(){return this.hooks}prepareRender(){this.disposed||(this.currentIndex=0,this.isRenderWindowOpen=!0,this.warnedHookOutsideRender=!1,this.currentHookTypes=n,this.pendingLayoutEffects=t,this.pendingEffects=t,this.currentEffectPhase=null,this.portalRegistrations=[])}startRenderPhase(){this.disposed||(this.currentEffectPhase="render")}finishRenderPhase(){"render"===this.currentEffectPhase&&(this.currentEffectPhase=null),this.isRenderWindowOpen=!1;let e=this.pendingSynchronousRenderUpdate;return this.pendingSynchronousRenderUpdate=!1,!!e||(this.validateHookSignature(),!1)}recordHook(e){if(this.currentHookTypes===n&&(this.currentHookTypes=[]),this.disposed)return this.warnedHookAfterDispose||(this.warnedHookAfterDispose=!0,this.emitDiagnostic(`[PP-WARN] ${e} hook for component "${this.componentLabel}" was called after the component was disposed. Hooks cannot be used after destroy.`)),this.currentIndex++;!this.isRenderWindowOpen&&!this.warnedHookOutsideRender&&(this.warnedHookOutsideRender=!0,this.emitDiagnostic(`[PP-WARN] ${e} hook for component "${this.componentLabel}" was called outside an active render. Hooks must be called while the component script is rendering.`));let t=this.currentIndex++;return this.currentHookTypes[t]=e,t}validateHookSignature(){if(null===this.committedHookTypes)return void(this.committedHookTypes=0===this.currentHookTypes.length?n:this.currentHookTypes.slice());let e=this.committedHookTypes,t=this.currentHookTypes;e.length===t.length&&e.every((e,n)=>e===t[n])||this.emitDiagnostic(`[PP-WARN] Hook order changed for component "${this.componentLabel}". Previous: [${e.join(", ")}]. Current: [${t.join(", ")}]. Hooks must be called in the same order on every render.`)}runLayoutEffects(){if(this.disposed)return this.pendingLayoutEffects=t,!1;let e=this.pendingLayoutEffects;this.pendingLayoutEffects=t,this.currentEffectPhase="layout";try{e.forEach(e=>{this.runEffectCleanup(e.previousCleanup,"layout cleanup")}),e.forEach(e=>{let t=this.runEffectCallback(e.callback,"layout effect");this.hooks[e.hookIndex]={deps:e.deps,cleanup:"function"==typeof t?t:void 0,effectType:"layout"}})}finally{this.currentEffectPhase=null}let n=this.pendingSynchronousLayoutUpdate;return this.pendingSynchronousLayoutUpdate=!1,n}hasPendingEffects(){return this.pendingEffects.length>0}runEffects(){if(this.disposed)return void(this.pendingEffects=t);let e=this.pendingEffects;this.pendingEffects=t,this.currentEffectPhase="effect";try{e.forEach(e=>{this.runEffectCleanup(e.previousCleanup,"effect cleanup")}),e.forEach(e=>{let t=this.runEffectCallback(e.callback,"effect");this.hooks[e.hookIndex]={deps:e.deps,cleanup:"function"==typeof t?t:void 0,effectType:"effect"}})}finally{this.currentEffectPhase=null}}runEffectCleanup(e,t){if(e)try{e()}catch(e){if(this.reportUncaughtError(e))return;console.error(`[PP-ERROR] ${t} failed for component "${this.componentLabel}"`,e)}}runEffectCallback(e,t){try{let n=e();return n&&"object"==typeof n&&"then"in n&&"function"==typeof n.then?void console.warn(`[PP-WARN] ${t} for component "${this.componentLabel}" returned a Promise. Effects must return only a cleanup function; run async work inside the effect instead.`):n}catch(e){if(this.reportUncaughtError(e))return;return void console.error(`[PP-ERROR] ${t} failed for component "${this.componentLabel}"`,e)}}dispose(){if(this.disposed)return;if(this.disposed=!0,this.pendingLayoutEffects=t,this.pendingEffects=t,this.pendingUpdate=!1,this.hasScheduledRender=!1,this.portalRegistrations=[],this.boundaryError=null,this.uncaughtErrorHandler=null,0===this.hooks.length)return void(this.currentIndex=0);let e=e=>{let t=e.cleanup;if("function"==typeof t)try{t()}finally{e.cleanup=void 0}};this.hooks.forEach(t=>{!t||"object"!=typeof t||"layout"===t.effectType&&e(t)}),this.hooks.forEach(t=>{!t||"object"!=typeof t||"effect"===t.effectType&&e(t)}),this.hooks.forEach(t=>{!t||"object"!=typeof t||t.effectType||e(t)}),this.hooks=[],this.currentIndex=0}usePortal(e,t){let n=this.recordHook("portal");void 0===this.hooks[n]&&(this.hooks[n]={sourceParent:null});let r=this.hooks[n];return this.portalRegistrations.push({ref:e,target:t??null,info:r}),r}getPortalRegistrations(){return this.portalRegistrations}useState(e){let t=this.recordHook("state");void 0===this.hooks[t]&&(this.hooks[t]={__state:this.resolveInitialState(e),__setter:this.createStateSetter(t)});let n=this.hooks[t];("object"!=typeof n||!n||!("__state"in n))&&(this.hooks[t]={__state:n,__setter:this.createStateSetter(t)});let r=this.hooks[t];return[r.__state,r.__setter]}resolveInitialState(e){return"function"==typeof e?e():e}createStateSetter(e){return t=>{let n=this.hooks[e];if(this.disposed||void 0===n)return;let r="function"==typeof t?t(n.__state):t;Object.is(n.__state,r)||(n.__state=r,this.scheduleUpdate())}}scheduleUpdate(){if(!this.disposed){if("render"===this.currentEffectPhase)return void(this.pendingSynchronousRenderUpdate=!0);if("layout"===this.currentEffectPhase)return void(this.pendingSynchronousLayoutUpdate=!0);this.hasScheduledRender=!0,this.pendingUpdate||(this.pendingUpdate=!0,(this.stateUpdateScheduler.shouldDefer()?e=>this.stateUpdateScheduler.enqueue(e):queueMicrotask)(()=>{this.pendingUpdate=!1,this.disposed?this.hasScheduledRender=!1:this.hasScheduledRender&&(this.hasScheduledRender=!1,this.onStateChange())}))}}useRef(e=null){let t=this.recordHook("ref");return void 0===this.hooks[t]&&(this.hooks[t]={current:e}),this.hooks[t]}useMemo(e,t){let n=this.recordHook("memo"),r=this.hooks[n],i=this.normalizeDeps("memo",t);if(!r||!i||!r.deps||this.areDepsDifferent(r.deps,i)){let t=e();return this.hooks[n]={value:t,deps:i},t}return r.value}useCallback(e,t){let n=this.recordHook("callback"),r=this.hooks[n],i=this.normalizeDeps("callback",t);return r&&i&&r.deps&&!this.areDepsDifferent(r.deps,i)?r.callback:(this.hooks[n]={callback:e,deps:i},e)}useReducer(e,t,n){let r=this.recordHook("reducer");if(void 0===this.hooks[r]){let i={state:n?n(t):t,reducer:e,dispatch:null};i.dispatch=e=>{if(this.disposed)return;let t=i.reducer(i.state,e);Object.is(i.state,t)||(i.state=t,this.scheduleUpdate())},this.hooks[r]=i}let i=this.hooks[r];return i.reducer=e,[i.state,i.dispatch]}useEffect(e,n){let r=this.recordHook("effect"),i=this.hooks[r],l=this.normalizeDeps("effect",n);(!i||!l||!i.deps||this.areDepsDifferent(i.deps,l))&&(this.pendingEffects===t&&(this.pendingEffects=[]),this.pendingEffects.push({hookIndex:r,deps:l,callback:e,previousCleanup:"function"==typeof i?.cleanup?i.cleanup:void 0}))}useLayoutEffect(e,n){let r=this.recordHook("layoutEffect"),i=this.hooks[r],l=this.normalizeDeps("layoutEffect",n);(!i||!l||!i.deps||this.areDepsDifferent(i.deps,l))&&(this.pendingLayoutEffects===t&&(this.pendingLayoutEffects=[]),this.pendingLayoutEffects.push({hookIndex:r,deps:l,callback:e,previousCleanup:"function"==typeof i?.cleanup?i.cleanup:void 0}))}useErrorBoundary(){let e=this.recordHook("errorBoundary");return this.hasErrorBoundaryHook=!0,void 0===this.hooks[e]&&(this.hooks[e]={reset:()=>{this.disposed||(this.boundaryErrorCaptureCount=0,null!==this.boundaryError&&(this.boundaryError=null,this.scheduleUpdate()))}}),[this.boundaryError,this.hooks[e].reset]}captureError(e){return!(this.disposed||!this.hasErrorBoundaryHook)&&(this.boundaryErrorCaptureCount>=r.MAX_BOUNDARY_CAPTURES?(console.error(`[PP-ERROR] Error boundary for component "${this.componentLabel}" absorbed ${r.MAX_BOUNDARY_CAPTURES} errors without being reset and has stopped catching to avoid an infinite render loop. Call reset() to re-arm it.`,e),!1):(this.boundaryErrorCaptureCount++,this.boundaryError=e,this.scheduleUpdate(),!0))}setUncaughtErrorHandler(e){this.uncaughtErrorHandler=e}reportUncaughtError(e){if(!this.uncaughtErrorHandler)return!1;try{return this.uncaughtErrorHandler(e)}catch(e){return console.error(`[PP-ERROR] Error boundary handler for component "${this.componentLabel}" threw.`,e),!1}}useId(){let e=this.recordHook("id");return void 0===this.hooks[e]&&(this.hooks[e]=this.createStableId(e)),this.hooks[e]}createStableId(e){let t=this.componentLabel.replace(/[^a-zA-Z0-9_-]/g,"-");return t.length>0&&"unknown"!==this.componentLabel?`pp-${t}-${e}`:`pp-${r.anonymousIdCounter++}-${e}`}useSyncExternalStore(e,t){let[,n]=this.useState(0),r=this.useRef(null),i=this.useRef(null),l=t();return r.current={value:l},i.current=t,this.useEffect(()=>{let t=()=>{let e=i.current,t=r.current;if(!e||!t)return;let l=e();Object.is(t.value,l)||(r.current={value:l},n(e=>e+1))},l=e(t);return t(),"function"==typeof l?l:void 0},[e]),l}useImperativeHandle(e,t,n){this.useLayoutEffect(()=>{if(!e)return;let n=t();if("function"==typeof e){let t=e(n);return()=>{"function"!=typeof t?e(null):t()}}return e.current=n,()=>{e.current=null}},void 0===n?void 0:[e,...n])}useTransition(){let[e,t]=this.useState(0),n=this.useCallback(e=>{t(e=>e+1);let n,r=()=>t(e=>e-1);try{n=e()}catch(e){throw r(),e}n&&"object"==typeof n&&"function"==typeof n.then?n.then(r,r):r()},[]);return[e>0,n]}useDeferredValue(e,t){let[n,r]=this.useState(void 0===t?e:t);return this.useEffect(()=>{r(e)},[e]),n}useOptimistic(e,t){let[n,r]=this.useState([]),i=this.useRef(null);null===i.current&&(i.current={value:e});let l=n;Object.is(i.current.value,e)||(i.current={value:e},n.length>0&&(l=[],r([])));let o=t??((e,t)=>t);return[l.reduce((e,t)=>o(e,t),e),this.useCallback(e=>{r(t=>[...t,e])},[])]}normalizeDeps(e,t){if(void 0!==t){if(Array.isArray(t))return t;this.emitDiagnostic(`[PP-WARN] ${e} dependencies for component "${this.componentLabel}" must be an array or omitted. Received ${this.describeDeps(t)}.`)}}describeDeps(e){return null===e?"null":"object"==typeof e?e.constructor?.name??"object":typeof e}emitDiagnostic(e){console.warn(e)}areDepsDifferent(e,t){return e.length!==t.length||t.some((t,n)=>!Object.is(t,e[n]))}},i="pp-component",a=Symbol("pp.boundaryDirectProps"),o=Symbol("pp.boundaryChildDerivation"),s="[pp-component]";function c(e){return(e instanceof HTMLElement||e instanceof SVGElement)&&e.hasAttribute("pp-component")}function l(e){return e.getAttribute(i)}function u(e,t){e.setAttribute(i,t)}function d(e){return e.closest(s)}function f(e){let t=d(e);return t===e&&(t=e.parentElement?d(e.parentElement):null),t}function p(e){return Array.from(e.querySelectorAll(s)).filter(e=>!(e.parentElement&&d(e.parentElement)))}var m="pp-fragment";function h(e){return e.nodeType===Node.COMMENT_NODE&&e.data.startsWith("pp:")}function g(e){return e.nodeType===Node.COMMENT_NODE&&"/pp"===e.data.trim()}var _=new Set(["TABLE","THEAD","TBODY","TFOOT","TR","SELECT","OPTGROUP"]);function v(e){let t=0;for(let n=e.nextSibling;n;n=n.nextSibling)if(h(n))t++;else if(g(n)){if(0===t)return n;t--}return null}function y(e){let t=new Set;for(;;){let n=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),r=null,l=null;for(let e=n.nextNode();e;e=n.nextNode()){if(!h(e)||t.has(e))continue;let n=e.parentElement;if(n&&_.has(n.tagName)){t.add(e);continue}let i=v(e);if(i){r=e,l=i;break}t.add(e)}if(!r||!l)return;let o=document.createElement(m);o.style.display="contents";let s=r.data.slice(3).trim();s&&o.setAttribute(i,s),r.parentNode?.insertBefore(o,r);let a=r.nextSibling;for(;a&&a!==l;){let e=a.nextSibling;o.appendChild(a),a=e}r.remove(),l.remove()}}var b=class{host;constructor(e){this.host=e}getId(){return l(this.host)}setId(e){u(this.host,e)}readContent(){return this.host.innerHTML}parentBoundaryElement(){return this.host.parentElement?d(this.host.parentElement):null}},x=class{static states=new Map;static scopes=new Map;static scopeVersions=new Map;static scopeVersionCounter=0;static topologyVersion=0;static topologyBatchDepth=0;static topologyBatchDirty=!1;static mergedScopeCache=new WeakMap;static instances=new Map;static parents=new Map;static childrenByParent=new Map;static ownedTemplateData=new Map;static contextValues=new Map;static consumerContexts=new Map;static contextConsumers=new Map;static bumpTopologyVersion(){this.topologyBatchDepth>0?this.topologyBatchDirty=!0:this.topologyVersion++}static beginTopologyBatch(){this.topologyBatchDepth++}static endTopologyBatch(){this.topologyBatchDepth>0&&this.topologyBatchDepth--,0===this.topologyBatchDepth&&this.topologyBatchDirty&&(this.topologyBatchDirty=!1,this.topologyVersion++)}static saveState(e,t){e&&this.states.set(e,t)}static getState(e){return this.states.get(e)}static removeState(e){this.states.delete(e)}static saveScope(e,t){this.scopes.set(e,t),this.scopeVersions.set(e,++this.scopeVersionCounter)}static getScope(e){return this.scopes.get(e)}static resolveComponentId(e,t=null){if(!e)return null;if("app"!==e){if(t){let n=new Set,r=t;for(;r&&!n.has(r);){n.add(r);let t=this.instances.get(r);if((t?.el?.__ppBaseComponentId??(t?.el?l(t.el):null)??null)===e)return r;r=this.parents.get(r)??null}}return e}let n=new Set,r=t,i=null;for(;r&&!n.has(r);){if(n.add(r),r.startsWith("page_"))return r;let e=this.parents.get(r)??null;if(!e){i=r;break}r=e}if(i)return i;for(let[e,t]of this.parents.entries())if(null===t&&this.scopes.has(e))return e;let o=this.scopes.keys().next().value;return"string"==typeof o?o:null}static getLiveResolvedScopeWithAncestors(e,t=null){let n=this.resolveComponentId(e,t);if(!n)return;let r=new Set,i=[],l=n;for(;l&&!r.has(l);){r.add(l);let e=this.scopes.get(l);e&&i.push(e),l=this.parents.get(l)??null}return 0!==i.length?Object.assign({},...i.reverse()):void 0}static getResolvedScopeWithAncestors(e,t=null){let n=this.resolveComponentId(e,t);if(!n)return;let r=this.scopes.get(n);if(r){let e=this.mergedScopeCache.get(r);if(e&&e.topology===this.topologyVersion){let t=!0;for(let n=0;n<e.chainIds.length;n++)if((this.scopeVersions.get(e.chainIds[n])??0)!==e.versions[n]){t=!1;break}if(t)return e.merged}}let i=new Set,l=[],o=[],s=n;for(;s&&!i.has(s);){i.add(s),l.push(s);let e=this.scopes.get(s);e&&o.push(e),s=this.parents.get(s)??null}if(0===o.length)return;let a=Object.assign({},...o.reverse());return r&&this.mergedScopeCache.set(r,{topology:this.topologyVersion,chainIds:l,versions:l.map(e=>this.scopeVersions.get(e)??0),merged:a}),a}static removeScope(e){this.scopes.delete(e),this.scopeVersions.set(e,++this.scopeVersionCounter)}static registerInstance(e,t){let n=this.instances.get(e);n&&n!==t&&n.destroy?.(),this.instances.set(e,t)}static getInstance(e){return this.instances.get(e)}static removeInstance(e){this.instances.delete(e)}static saveParent(e,t){if(!e)return;let n=this.parents.has(e),r=this.parents.get(e);if(n&&r===t)return;if(n){let t=this.childrenByParent.get(r??null);t?.delete(e),0===t?.size&&this.childrenByParent.delete(r??null),this.bumpTopologyVersion()}this.parents.set(e,t);let i=this.childrenByParent.get(t)??new Set;i.add(e),this.childrenByParent.set(t,i)}static getParent(e){return this.parents.get(e)}static removeParent(e){if(!this.parents.has(e))return;let t=this.parents.get(e)??null,n=this.childrenByParent.get(e);n?.size&&Array.from(n).forEach(e=>this.saveParent(e,t));let r=this.childrenByParent.get(t);r?.delete(e),0===r?.size&&this.childrenByParent.delete(t),this.childrenByParent.delete(e),this.parents.delete(e),this.bumpTopologyVersion()}static hasChildren(e){return(this.childrenByParent.get(e)?.size??0)>0}static forEachDescendant(e,t){if(!this.childrenByParent.get(e)?.size)return;let n=new Set,r=i=>{let l=this.childrenByParent.get(i);l&&Array.from(l).forEach(i=>{i!==e&&(n.has(i)||(n.add(i),r(i),t(i)))})};r(e)}static saveContextValues(e,t){let n=this.contextValues.get(e)??new Map,r=new Set;return n.forEach((e,n)=>{t.has(n)||r.add(n)}),t.forEach((e,t)=>{n.has(t)&&Object.is(n.get(t),e)||r.add(t)}),t.size>0?this.contextValues.set(e,new Map(t)):this.contextValues.delete(e),Array.from(r)}static resolveContext(e,t){let n=e;for(;n;){let e=this.contextValues.get(n);if(e?.has(t))return{providerId:n,value:e.get(t)};n=this.parents.get(n)??null}return{providerId:null,value:t.defaultValue}}static updateContextDependencies(e,t){let n=new Set(t),r=this.consumerContexts.get(e)??new Set;r.forEach(t=>{n.has(t)||this.removeContextConsumer(t,e)}),n.forEach(t=>{r.has(t)||this.addContextConsumer(t,e)}),n.size>0?this.consumerContexts.set(e,n):this.consumerContexts.delete(e)}static getConsumersForContextsInSubtree(e,t){let n=new Set;for(let r of t){let t=this.contextConsumers.get(r);t&&t.forEach(t=>{t!==e&&this.isAncestor(e,t)&&n.add(t)})}return n}static removeContextTracking(e){let t=this.contextValues.get(e),n=t?this.getConsumersForContextsInSubtree(e,t.keys()):null;this.contextValues.delete(e);let r=this.consumerContexts.get(e);return r&&(r.forEach(t=>{this.removeContextConsumer(t,e)}),this.consumerContexts.delete(e)),this.removeParent(e),n}static saveOwnedTemplates(e,t){this.ownedTemplateData.has(e)||this.ownedTemplateData.set(e,t)}static getOwnedTemplates(e){return this.ownedTemplateData.get(e)}static removeOwnedTemplates(e){this.ownedTemplateData.delete(e)}static clear(){this.topologyBatchDepth=0,this.topologyBatchDirty&&(this.topologyBatchDirty=!1,this.topologyVersion++),this.states.clear(),this.scopes.clear(),this.instances.clear(),this.parents.clear(),this.childrenByParent.clear(),this.ownedTemplateData.clear(),this.contextValues.clear(),this.consumerContexts.clear(),this.contextConsumers.clear()}static destroyAll(){let e=Array.from(this.instances.values()),t=new Set;this.beginTopologyBatch();try{for(let n of e)if(n&&!t.has(n)){t.add(n);try{n.destroy?.()}catch(e){console.warn("[PP-WARN] Failed to destroy component instance",e)}}}finally{this.endTopologyBatch()}}static addContextConsumer(e,t){let n=this.contextConsumers.get(e)??new Set;n.add(t),this.contextConsumers.set(e,n)}static removeContextConsumer(e,t){let n=this.contextConsumers.get(e);n&&(n.delete(t),0===n.size&&this.contextConsumers.delete(e))}static isAncestor(e,t){let n=this.parents.get(t)??null;for(;n;){if(n===e)return!0;n=this.parents.get(n)??null}return!1}};function S(e,t,n,r){!e.has(t)&&e.size>=r&&w(e,1),e.set(t,n)}function C(e,t,n=Math.floor(t/2)){e.size<=t||w(e,e.size-n)}function w(e,t){let n=e.keys();for(let r=0;r<t;r++){let t=n.next();if(t.done)return;e.delete(t.value)}}var T=new Set(["date","datetime-local","month","time","week"]),E=new Set(["text","search","url","tel","password"]),D=new Set(["email","number","password","search","tel","text","url"]);function O(e){return T.has(e.type)}function k(e){return e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement&&E.has(e.type)}function A(e){return e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement&&D.has(e.type)}function j(e,t){P(e,e,"__ppValueControlMode","__ppWarnedValueControlModeSwitch",t,"Choose either a controlled value binding or an uncontrolled defaultValue for the lifetime of the element.")}function M(e,t){P(e,e,"__ppCheckedControlMode","__ppWarnedCheckedControlModeSwitch",t,"Choose either a controlled checked binding or an uncontrolled defaultChecked for the lifetime of the element.")}function N(e,t){M(e,"controlled"),e.checked!==t&&(e.checked=t)}function P(e,t,n,r,i,l){let o=t[n];o?o!==i&&(t[r]||(t[r]=!0,console.warn(`[PP-WARN] ${F(e)} changed from ${o} to ${i}. ${l}`)),t[n]=i):t[n]=i}function F(e){let t=e.tagName.toLowerCase(),n=e.id?`#${e.id}`:"",r=e.getAttribute("name");return`${t}${n}${!n&&r?`[name="${r}"]`:""}`}var I=new Set("class.for.while.if.else.return.function.var.let.const.import.export.this.debugger.delete.typeof.void.new.in.instanceof.do.try.catch.finally.switch.case.default.break.continue.yield.await.with.super.enum.extends.implements.interface.package.private.protected.public.static".split(".")),L="pp-literal-",R=new Set("hidden.disabled.checked.selected.readonly.required.open.autofocus.multiple.ismap.noValidate.defer.async.autoplay.controls.loop.muted.default.reversed.scoped.seamless.sortable.translate.draggable.contenteditable.spellcheck".split("."));function ee(e){return e.includes("-")?e.replace(/-([a-z])/g,e=>e[1].toUpperCase()):e}function z(e,t){if(e.length<2)return!1;let n=e.charCodeAt(0);if(111!==n&&79!==n)return!1;let r=e.charCodeAt(1);if(110!==r&&78!==r)return!1;let i=e.toLowerCase();return!i.includes("-")&&i in t}var te=new WeakMap,ne=/^[A-Za-z_$][\w$]*$/;function re(e){return ne.test(e)&&!I.has(e)}function ie(e){let t=te.get(e);if(t)return t;let n=Object.keys(e).filter(re),r={keys:n,keySig:n.join("\0")};return te.set(e,r),r}function ae(e){let t=ie(e);return{scope:e,keys:t.keys,keySig:t.keySig,values:oe(e,t.keys)}}function oe(e,t){let n=Array(t.length);for(let r=0;r<t.length;r++)n[r]=e[t[r]];return n}var se=new Map,ce=500,le=null,ue=null;function de(e){ue||=document.createElement("template"),ue.innerHTML=e;let t=Array.from(ue.content.childNodes).filter(e=>e.nodeType===Node.TEXT_NODE?(e.textContent??"").trim().length>0:e.nodeType===Node.ELEMENT_NODE);if(1!==t.length)return null;let n=t[0];return n instanceof HTMLTemplateElement&&n.hasAttribute("pp-owner")?n.innerHTML:null}function fe(e){let t=B(e),n=!1;for(;;){let e=de(t);if(null===e)break;t=e,n=!0}return n?t:null}function pe(e){if(!e.includes("<textarea"))return e;let t=e.includes("pp-owner"),n=document.createElement("template");n.innerHTML=e;let r=!1;return n.content.querySelectorAll("textarea").forEach(e=>{let n=e;if(t){let e=fe(n.value);if(null!==e)return n.textContent=e,void(r=!0)}n.value.length>0&&0===n.value.trim().length&&(n.textContent="",r=!0)}),r?n.innerHTML:e}function B(e){if(!e.includes("&"))return e;if(se.has(e))return se.get(e);le||=document.createElement("textarea");let t=le;t.innerHTML=e;let n=t.value,r=0;for(;n.includes("&")&&r++<10;){t.innerHTML=n;let e=t.value;if(e===n)break;n=e}return S(se,e,n,ce),n}var me=/&(?:amp;)?(?:lbrace|rbrace|#123|#125|#x7b|#x7d);/i;function he(e){return e.includes("&")&&me.test(e)}var V="data-pp-fragment-root";function ge(e,t){let n=0,r=t-1;for(;r>=0&&"\\"===e[r];)n++,r--;return n%2!=0}function H(e,t){if("{"!==e[t])return-1;let n=0,r=null;for(let i=t;i<e.length;i++){let t=e[i],l=ge(e,i);if(r)t===r&&!l&&(r=null);else if(l||'"'!==t&&"'"!==t&&"`"!==t)if("{"!==t||l){if("}"===t&&!l&&(n--,0===n))return i}else n++;else r=t}return-1}function _e(e,t){return e.startsWith("{{",t)||e.startsWith("{%",t)||e.startsWith("{#",t)}function ve(e,t){let n=e.startsWith("{{",t)?"}}":e.startsWith("{%",t)?"%}":e.startsWith("{#",t)?"#}":"";if(!n)return-1;let r=e.indexOf(n,t+2);return-1===r?-1:r+n.length}function U(e){let t=0;for(;t<e.length&&/\s/.test(e[t]);)t++;if("{"!==e[t]||_e(e,t))return null;let n=H(e,t);if(-1===n)return null;let r=n+1;for(;r<e.length&&/\s/.test(e[r]);)r++;return r===e.length?{expression:e.slice(t+1,n).trim(),start:t,end:n}:null}function ye(e,t){let n="",r=0;for(;r<e.length;){if("{"!==e[r]){n+=e[r],r++;continue}if(_e(e,r)){let t=ve(e,r);if(-1===t){n+=e.slice(r);break}n+=e.slice(r,t),r=t;continue}let i=H(e,r);if(-1===i){n+=e.slice(r);break}let l=e.slice(r+1,i);n+=t(l.trim(),l),r=i+1}return n}function be(e){let t=String(e??"").trim().toLowerCase();switch(t){case"table":return{prefix:`<table ${V}="">`,suffix:"</table>",rootSelector:`table[${V}]`};case"caption":return{prefix:`<table><caption ${V}="">`,suffix:"</caption></table>",rootSelector:`caption[${V}]`};case"thead":case"tbody":case"tfoot":return{prefix:`<table><${t} ${V}="">`,suffix:`</${t}></table>`,rootSelector:`${t}[${V}]`};case"tr":return{prefix:`<table><tbody><tr ${V}="">`,suffix:"</tr></tbody></table>",rootSelector:`tr[${V}]`};case"td":case"th":return{prefix:`<table><tbody><tr><${t} ${V}="">`,suffix:`</${t}></tr></tbody></table>`,rootSelector:`${t}[${V}]`};case"colgroup":return{prefix:`<table><colgroup ${V}="">`,suffix:"</colgroup></table>",rootSelector:`colgroup[${V}]`};case"select":return{prefix:`<select ${V}="">`,suffix:"</select>",rootSelector:`select[${V}]`};case"optgroup":return{prefix:`<select><optgroup ${V}="">`,suffix:"</optgroup></select>",rootSelector:`optgroup[${V}]`};case"option":return{prefix:`<select><option ${V}="">`,suffix:"</option></select>",rootSelector:`option[${V}]`};default:return{prefix:"",suffix:"",rootSelector:null}}}function xe(e){let t=be(e);return{wrap:e=>`${t.prefix}${e}${t.suffix}`,unwrap:e=>{if(!t.prefix&&!t.suffix)return e;let n=e.indexOf(V);if(-1!==n&&n<=t.prefix.length+32&&e.endsWith(t.suffix)){let r=e.indexOf(">",n);if(-1!==r){let n=e.length-t.suffix.length;if(r+1<=n)return e.slice(r+1,n)}}let r=document.createElement("template");if(r.innerHTML=e,t.rootSelector){let e=r.content.querySelector(t.rootSelector);if(e)return e.innerHTML}return e}}}function W(e,t){let n=be(t),r=document.createElement("template");if(r.innerHTML=pe(`${n.prefix}${e}${n.suffix}`),!n.rootSelector)return{root:r.content,toHtml:()=>r.innerHTML};let i=r.content.querySelector(n.rootSelector);return i?(i.removeAttribute(V),{root:i,toHtml:()=>i.innerHTML}):{root:r.content,toHtml:()=>r.innerHTML}}function Se(e,t){if(e===t)return!0;if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;let n=Object.keys(e),r=n.length,i=0;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&(i++,i>r))return!1;if(i!==r)return!1;for(let i=0;i<r;i++){let r=n[i];if(e[r]!==t[r])return!1}return!0}var Ce=class t{static MAX_HANDLER_CACHE_SIZE=4096;root;getScope;canBindElement;handlerCache=new Map;cachedRootElementCount=null;static LARGE_INPUT_RENDER_DEFER_THRESHOLD=100;constructor(e,t,n){this.root=e,this.getScope=t,this.canBindElement=n}clearCache(){this.handlerCache.clear()}static hasSameDirectBoundHandler(e,n,r,i){if(!z(n,e))return!1;let l=n.slice(2).toLowerCase();return!("input"===l&&e instanceof HTMLInputElement&&O(e))&&(e[`__pp_bound_${l}`]===t.normalizeHandlerCode(r)&&e[`__pp_event_owner_${l}`]===(i??""))}static normalizeHandlerCode(e){let t=e.trim(),n=t.match(/^\{([\s\S]*)\}$/);return n?n[1].trim():t}static prepareHandler(e){let t=[];return{sourceCode:e,compiledCode:e.replace(/__pp_loop_read\((['"])(ppv_\d+(?:_\d+)?)\1\)/g,(e,n,r)=>`__pp_loop_read(__PP_EVENT_CAPTURES__[${t.push(r)-1}])`),loopCaptureIds:t}}invalidateElementCountCache(){this.cachedRootElementCount=null}resolveEventOwnerScope(e){let t=l(this.root);return x.getLiveResolvedScopeWithAncestors(e,t)}bindEvents(e){e.forEach(e=>{this.canBindElement(e)&&this.bindElementEvents(e)})}bindElementEvents(n){let r=n.getAttribute("pp-event-owner");r&&n.removeAttribute("pp-event-owner");let i=[];Array.from(n.attributes).forEach(o=>{if(z(o.name,n)){let s=o.name.slice(2).toLowerCase(),a=o.value,u=t.normalizeHandlerCode(a),p=t.prepareHandler(u);i.push(o.name),this.getNativeEventNames(n,s).forEach(t=>{let i=`__pp_bound_${t}`,s=`__pp_event_owner_${t}`;if((n.__ppBoundEventBindings??=new Map).set(t,o.name),n[i]===u&&n[s]===(r??""))return;n[i]=u,n[s]=r??"";let a=n[`__pp_handler_${t}`];a&&n.removeEventListener(t,a);let c=i=>{let o=this.shouldPreserveNativeEdit(n,t),s=o&&this.shouldDeferNativeInputRender(),a=n;if(o&&(a.__ppPreserveNativeSelectionOnNextRender=!0),this.runWithNativeInputRenderPolicy(s,()=>{if(r){let e=this.resolveEventOwnerScope(r);if(e)return void this.executeHandlerWithScope(p,i,e,n)}let e=d(n),t=e===n?f(n):e,o=t&&l(t)||null;if(o){let e=this.resolveEventOwnerScope(o);if(e)return void this.executeHandlerWithScope(p,i,e,n)}this.executeHandler(p,i,n)}),o){let t=()=>{a.__ppPreserveNativeSelectionOnNextRender&&delete a.__ppPreserveNativeSelectionOnNextRender};s?(e.enqueue(t),this.ensureDeferredNativeInputBlurFlush(n)):queueMicrotask(t)}};n[`__pp_handler_${t}`]=c,n.addEventListener(t,c)})}}),i.forEach(e=>{n.removeAttribute(e)})}static unbindRemovedEventHandlers(e,t){let n=e.__ppBoundEventBindings;if(n&&0!==n.size){for(let[r,i]of Array.from(n)){if(t.hasAttribute(i))continue;let l=`__pp_handler_${r}`,o=e[l];o&&(e.removeEventListener(r,o),delete e[l]),delete e[`__pp_bound_${r}`],delete e[`__pp_event_owner_${r}`],n.delete(r)}0===n.size&&delete e.__ppBoundEventBindings}}getNativeEventNames(e,t){return"input"===t&&e instanceof HTMLInputElement&&O(e)?["change","blur"]:[t]}runWithNativeInputRenderPolicy(t,n){e.runWithDeferral(t,n)}shouldDeferNativeInputRender(){return null===this.cachedRootElementCount&&(this.cachedRootElementCount=this.root.getElementsByTagName("*").length+1),this.cachedRootElementCount>=t.LARGE_INPUT_RENDER_DEFER_THRESHOLD}ensureDeferredNativeInputBlurFlush(t){let n=t;if(n.__ppDeferredNativeInputBlurFlush)return;let r=()=>{delete n.__ppDeferredNativeInputBlurFlush,e.flush()};n.__ppDeferredNativeInputBlurFlush=r,t.addEventListener("blur",r,{once:!0})}shouldPreserveNativeEdit(e,t){return"input"===t&&A(e)}executeHandler(e,t,n){let r=l(this.root),i=this.resolveEventOwnerScope(r)||this.getScope();this.executeHandlerWithScope(e,t,i,n)}executeHandlerWithScope(e,t,n,r){let i=ie(n),l=i.keys,o=oe(n,l);try{let n=this.getCompiledHandler(e.compiledCode,l,i.keySig).call(r??t.currentTarget??null,...o,e.loopCaptureIds,t);"function"==typeof n&&n(t)}catch(t){console.error("[PP-ERROR] Handler failed:",t),console.error("Code:",e.sourceCode)}}getCompiledHandler(e,n,r){let i=e+"|"+r,l=this.handlerCache.get(i);if(!l){let r=[["e","event"],["$event","event"],["target","event?.target"],["currentTarget","event?.currentTarget"],["el","event?.currentTarget"]],l=new Set(n),o="__pp_event_captures";for(;l.has(o);)o+="_";let s,a=e.replaceAll("__PP_EVENT_CAPTURES__",o),u=r.filter(([e])=>!l.has(e)).map(([e,t])=>`const ${e} = ${t};`).join("\n");try{s=Function(...n,o,"event",`"use strict";${u} return (${a})`)}catch{s=Function(...n,o,"event",`"use strict";${u} ${a}`)}return S(this.handlerCache,i,s,t.MAX_HANDLER_CACHE_SIZE),s}return l}},we=/[A-Za-z_$]/,Te=/[A-Za-z0-9_$]/;function Ee(e,t){return null===e||"l"!==e.kind&&("i"===e.kind?De.has(e.value):")"!==e.value&&"]"!==e.value&&("}"!==e.value||!t))}var De=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]);function Oe(e){if(null===e||"l"===e.kind)return!1;if("i"===e.kind)return ke.has(e.value);let t=e.value;return!(")"===t||"]"===t||"}"===t||"=>"===t)}var ke=new Set(["return","typeof","in","of","case","do","yield","await","throw","new","delete","void"]);function Ae(e){let t=[],n=new Set,r=[],i=[],l=0,o=0,s=e.length,a=null,u=!1,p=(n,r,i)=>{let o={kind:n,value:e.slice(r,i),start:r,end:i,depth:l};return t.push(o),a=o,o},d=t=>{for(o++;o<s;){let n=e[o];if("\\"!==n){if(n===t)return void o++;o++}else o+=2}},c=()=>{for(;o<s;){let t=e[o];if("\\"!==t){if("`"===t)return o++,"end";if("$"===t&&"{"===e[o+1])return o+=2,"interp";o++}else o+=2}return"end"};for(;o<s;){let h=e[o];if(" "===h||"\t"===h||"\n"===h||"\r"===h||"\f"===h||"\v"===h){o++;continue}if("/"===h&&"/"===e[o+1]){let t=e.indexOf("\n",o);o=-1===t?s:t+1;continue}if("/"===h&&"*"===e[o+1]){let t=e.indexOf("*/",o+2);o=-1===t?s:t+2;continue}if('"'===h||"'"===h){let e=o;d(h),p("l",e,o),u=!1;continue}if("`"===h){let e=o;o++;let t=c();p("l",e,o),u=!1,"interp"===t&&(i.push(l),l++);continue}if(we.test(h)){let t=o;for(o++;o<s&&Te.test(e[o]);)o++;p("i",t,o),u=!1;continue}if(h>="0"&&h<="9"||"."===h&&e[o+1]>="0"&&e[o+1]<="9"){let t=o;for(o++;o<s&&/[0-9a-fA-FoOxXbB._ne+-]/.test(e[o])&&("+"!==e[o]&&"-"!==e[o]||"e"===e[o-1]||"E"===e[o-1]);)o++;p("l",t,o),u=!1;continue}if("/"===h&&Ee(a,u)){let t=o;o++;let n=!1;for(;o<s;){let t=e[o];if("\\"!==t){if("["===t)n=!0;else if("]"===t)n=!1;else{if("/"===t&&!n){o++;break}if("\n"===t)break}o++}else o+=2}for(;o<s&&Te.test(e[o]);)o++;p("l",t,o),u=!1;continue}let f,m=o,_=e.slice(o,o+3),g=e.slice(o,o+2);if(f="..."===_||"==="===_||"!=="===_||"**="===_||"<<="===_||">>="===_||"&&="===_||"||="===_||"??="===_?_:"=>"===g||"=="===g||"!="===g||"<="===g||">="===g||"&&"===g||"||"===g||"??"===g||"?."===g||"++"===g||"--"===g||"+="===g||"-="===g||"*="===g||"/="===g||"%="===g||"&="===g||"|="===g||"^="===g||"**"===g||"<<"===g||">>"===g?g:h,o+=f.length,"("!==f&&"["!==f&&"{"!==f){if(")"===f||"]"===f||"}"===f){if("}"===f&&i.length>0&&i[i.length-1]===l-1&&(0===r.length||t[r[r.length-1]]?.depth<i[i.length-1])){i.pop(),l--;let e=o,t=c();p("l",e-1,o),u=!1,"interp"===t&&(i.push(l),l++);continue}l=Math.max(0,l-1);let e=r.pop();p("p",m,o),u="}"===f&&void 0!==e&&n.has(e);continue}p("p",m,o),u=!1}else"{"===f&&Oe(a)&&n.add(t.length),r.push(t.length),p("p",m,o),l++,u=!1}return{tokens:t,objectBraces:n}}var je=new Set(["const","let","var","function","class","if","for","while","do","switch","try","return","break","continue","throw","async","import","export"]),G=class{static expressionCache=new Map;static bindingsCache=new Map;static loopVariableCache=new Map;static MAX_CACHE_SIZE=1e3;static clearCaches(){this.expressionCache.clear(),this.bindingsCache.clear(),this.loopVariableCache.clear()}static extractStateBindings(e){if(this.bindingsCache.has(e))return[...this.bindingsCache.get(e)];let t=new Set;try{Function(e);let{tokens:n}=Ae(e);this.collectTopLevelBindings(n,t)}catch(e){console.error("[PP-ERROR] AstParser Failed",e)}let n=Array.from(t);return C(this.bindingsCache,this.MAX_CACHE_SIZE),this.bindingsCache.set(e,n),n}static collectTopLevelBindings(e,t){let n=e.length,r=i=>{let l=e[i];if(!l)return i;if("i"===l.kind)return t.add(l.value),i+1;if("p"===l.kind&&("{"===l.value||"["===l.value)){let o=l.depth,s=i+1;for(;s<n;){let i=e[s];if(i.depth===o&&"p"===i.kind&&("}"===i.value||"]"===i.value))return s+1;if(i.depth===o+1)if("p"!==i.kind||","!==i.value)if("p"!==i.kind||"..."!==i.value)if("["!==l.value){if("i"===i.kind||"l"===i.kind){let n=e[s+1];n&&"p"===n.kind&&":"===n.value?s=r(s+2):("i"===i.kind&&t.add(i.value),s++),s=this.skipDefault(e,s,o+1);continue}if("p"===i.kind&&"["===i.value){let t=s+1;for(;t<n&&e[t].depth>o+1;)t++;t++;let i=e[t];s=i&&"p"===i.kind&&":"===i.value?r(t+1):t,s=this.skipDefault(e,s,o+1);continue}s++}else s=r(s),s=this.skipDefault(e,s,o+1);else s=r(s+1),s=this.skipDefault(e,s,o+1);else s++;else s++}return s}return i+1};for(let i=0;i<n;i++){let l=e[i];if(0===l.depth&&"i"===l.kind){if("const"===l.value||"let"===l.value||"var"===l.value){let t=i+1;for(;t<n;){t=r(t);let n=e[t];n&&"p"===n.kind&&"="===n.value&&(t=this.skipInitializer(e,t+1));let i=e[t];if(!i||"p"!==i.kind||","!==i.value)break;t++}i=t-1;continue}if("function"===l.value||"class"===l.value){let n=e[i+1];n&&"i"===n.kind&&0===n.depth&&t.add(n.value);continue}if("async"===l.value){let n=e[i+1],r=e[i+2];n&&"i"===n.kind&&"function"===n.value&&r&&"i"===r.kind&&t.add(r.value)}}}}static skipDefault(e,t,n){let r=e[t];if(!r||"p"!==r.kind||"="!==r.value)return t;let i=t+1;for(;i<e.length;){let t=e[i];if(t.depth<n||t.depth===n&&"p"===t.kind&&","===t.value)return i;i++}return i}static skipInitializer(e,t){let n=t,r=e[t-1]?.end??0;for(;n<e.length;){let i=e[n];if(0===i.depth&&"p"===i.kind&&(","===i.value||";"===i.value)||0===i.depth&&"i"===i.kind&&je.has(i.value)&&n>t&&i.start>r)return n;r=i.end,n++}return n}static isValidExpression(e){if(!e.trim())return!1;if(this.expressionCache.has(e))return this.expressionCache.get(e);let t=!1;try{Function(`return (${e});`),t=!0}catch{t=!1}return C(this.expressionCache,this.MAX_CACHE_SIZE),this.expressionCache.set(e,t),t}static analyzeLoopVariableUsage(e,t){let n=e+"|"+t;if(this.loopVariableCache.has(n))return[...this.loopVariableCache.get(n)];let r=[];try{let n=Ae(e),{tokens:i}=n;for(let e=0;e<i.length;e++){let l=i[e];if("i"!==l.kind||l.value!==t||this.isMemberProperty(i,e))continue;let o=this.classifyObjectPosition(n,e);if("key"===o)continue;if(null===o){r.push({start:l.start,end:l.end,isShorthand:!1,isUnwrap:!1});continue}let s=i[e-1],a=i[e+1],u="shorthand"===o&&"{"===s.value&&"}"===a.value;r.push(u?{start:s.start,end:a.end,isShorthand:!0,isUnwrap:!0}:{start:l.start,end:l.end,isShorthand:!0,isUnwrap:!1})}}catch{}return C(this.loopVariableCache,this.MAX_CACHE_SIZE),this.loopVariableCache.set(n,[...r]),[...r]}static isMemberProperty(e,t){let n=e[t-1];return void 0!==n&&"p"===n.kind&&("."===n.value||"?."===n.value)}static classifyObjectPosition(e,t){let{tokens:n,objectBraces:r}=e,i=n[t],l=n[t-1],o=n[t+1];if(!l||"p"!==l.kind||"{"!==l.value&&","!==l.value)return null;let s=-1;for(let e=t-1;e>=0;e--){let t=n[e];if("p"===t.kind&&t.depth<i.depth){"{"===t.value&&(s=e);break}}return-1!==s&&r.has(s)&&("{"===l.value&&t-1===s||","===l.value&&l.depth===i.depth)?o&&"p"===o.kind&&":"===o.value?"key":!o||"p"!==o.kind||","!==o.value&&"}"!==o.value&&"="!==o.value?null:"shorthand":null}},Me="pp-keep-content",Ne=["pp-owner","<pp-context-provider","pp-ref","data-pp-ref"];function Pe(e){if(0===e.length)return!1;for(let t=0;t<Ne.length;t++)if(e.includes(Ne[t]))return!1;return!0}var Fe=class{enabled=!0;committedKeys=new Set;renderKeys=new Set;emitted=0;beginRender(){this.renderKeys.clear(),this.emitted=0}getEmittedCount(){return this.emitted}commit(){let e=this.committedKeys;this.committedKeys=this.renderKeys,e.clear(),this.renderKeys=e}disable(){this.enabled=!1,this.committedKeys.clear(),this.renderKeys.clear()}resolve(e,t,n){return this.renderKeys.add(e),this.enabled&&null!==n&&this.committedKeys.has(e)?(this.emitted++,n):t}},Ie=class{static cache=new Map;static MAX_CACHE_SIZE=2e3;static CONTEXT_PROVIDER_TAG_PATTERN=/<\/?([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\.Provider)\b[^>]*>/gi;static LITERAL_CODE_TAG_PATTERN=/(<code\b[^>]*>)([\s\S]*?)(<\/code\s*>)/gi;static ESCAPED_BRACE_ENTITY_PATTERN=/&(?:amp;)?(lbrace|rbrace|#123|#125|#x7b|#x7d);/gi;static LITERAL_TEXT_LT_ENTITY_PATTERN=/&(?:lt|#0*60|#x0*3c);/i;static INTERNAL_LOOP_NAMES=new Set(["__pp_loop_capture","__pp_loop_read","__pp_loop_rows","__pp_render_value","__pp_raw_html","__pp_escape_html","__pp_attr","__pp_bool_attr","__pp_to_loop_items"]);static SPREAD_BOOLEAN_ATTRS=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"]);static DYNAMIC_BOOLEAN_ATTRIBUTE_PATTERN=RegExp(`(?<![\\w-])(${Array.from(R).join("|")})=(["'])\\{`,"g");static escapeTemplateLiteralText(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}static COMMENT_STRIP_RAW_TEXT_TAGS=new Set(["script","style","textarea","title","xmp"]);static COMMENT_STRIP_VERBATIM_TAGS=new Set(["pre","code"]);static isRuntimeCommentMarker(e){let t=e.trim();return t.startsWith("pp:")||"/pp"===t||t.startsWith("pp-")||t.startsWith("__PP_")||"invalid-loop"===t}static stripAuthoredComments(e){if(!e.includes("\x3c!--"))return e;let t="",n=0,r=e.length,i=0;for(;n<r;){let l=e[n];if("<"===l){if(e.startsWith("\x3c!--",n)){let l,o;if(e.startsWith(">",n+4))l=n+5,o="";else if(e.startsWith("->",n+4))l=n+6,o="";else{let t=e.indexOf("--\x3e",n+4);l=-1===t?r:t+3,o=e.slice(n+4,-1===t?r:t)}(i>0||this.isRuntimeCommentMarker(o))&&(t+=e.slice(n,l)),n=l;continue}let o="/"===e[n+1],s=n+(o?2:1),a=/^[a-zA-Z][^\s/>]*/.exec(e.slice(s,s+64));if(!a){t+=l,n++;continue}let u=a[0].toLowerCase(),p=s+a[0].length,d=null;for(;p<r;){let t=e[p];if(d)t===d&&(d=null);else if('"'===t||"'"===t)d=t;else if(">"===t)break;p++}let c=Math.min(p+1,r);if(t+=e.slice(n,c),n=c,o){this.COMMENT_STRIP_VERBATIM_TAGS.has(u)&&i>0&&i--;continue}if(p<r&&"/"===e[p-1])continue;if(this.COMMENT_STRIP_RAW_TEXT_TAGS.has(u)){let i=RegExp(`</${u}(?=[\\s/>]|$)`,"gi");i.lastIndex=n;let l=i.exec(e),o=l?l.index:r;t+=e.slice(n,o),n=o;continue}this.COMMENT_STRIP_VERBATIM_TAGS.has(u)&&i++;continue}if("{"===l&&0===i){if(this.isServerTemplateBlockStart(e,n)){let r=this.findServerTemplateBlockEnd(e,n);if(-1!==r){t+=e.slice(n,r),n=r;continue}}let r=this.findClosingBrace(e,n);if(-1!==r){t+=e.slice(n,r+1),n=r+1;continue}t+=l,n++;continue}let o=n;for(;o<r&&"<"!==e[o]&&"{"!==e[o];)o++;o===n&&(o=n+1),t+=e.slice(n,o),n=o}return t}static SHARED_RENDER_HELPERS=(()=>{let e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},t=/[&<>"']/,n=/[&<>"']/g,r=t=>e[t],i=e=>{let i=String(e);return t.test(i)?i.replace(n,r):i},l=e=>({__ppRawHtml:String(e)}),o=e=>"boolean"==typeof e||null==e?"":e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"__ppRawHtml")?e.__ppRawHtml:Array.isArray(e)?e.map(o).join(""):"object"==typeof e||"function"==typeof e||"symbol"==typeof e?(e=>(console.warn(`[PP-WARN] Invalid template child of type "${null===e?"null":typeof e}" was omitted. Render a primitive, an array of renderable values, or explicit trusted HTML instead.`,e),""))(e):i(e);return{__pp_escape_html:i,__pp_raw_html:l,__pp_render_value:o,__pp_attr_text:e=>"boolean"==typeof e||null==e?"":Array.isArray(e)?e.join(""):String(e),__pp_attr:(e,t)=>l("boolean"==typeof t?e+'="'+i(t)+'"':e+'="'+o(t)+'"'),__pp_bool_attr:(e,t,n)=>"boolean"==typeof t?l(t?e:""):null==t?"":"string"==typeof t||"number"==typeof t||"bigint"==typeof t?t?l(e+'="'+i(t)+'"'):"":l(e+'="{'+n+'}"'),__pp_to_loop_items:e=>{if(Array.isArray(e))return e;if(null==e)return[];try{if("function"==typeof e[Symbol.iterator])return Array.from(e)}catch(t){return console.warn("[PP-WARN] pp-for iterable could not be consumed:",e,t),[]}return console.warn("[PP-WARN] pp-for collection is not an array or iterable:",e),[]}}})();static SHARED_HELPER_PRELUDE="const { __pp_escape_html, __pp_raw_html, __pp_render_value, __pp_attr_text, __pp_attr, __pp_bool_attr, __pp_to_loop_items } = __pp_shared;\n";static escapeTemplateLiteralTextPreservingInterpolations(e){let t="",n=0,r=0;for(;n<e.length;){if("$"===e[n]&&"{"===e[n+1]){let i=this.findClosingBrace(e,n+1);if(-1!==i){t+=this.escapeTemplateLiteralText(e.slice(r,n)),t+=e.slice(n,i+1),n=i+1,r=n;continue}}n++}return t+=this.escapeTemplateLiteralText(e.slice(r)),t}static clearCache(){this.cache.clear()}static maskEscapedBraceEntities(e){let t=new Map,n=0;return{maskedHtml:e.replace(this.ESCAPED_BRACE_ENTITY_PATTERN,(e,r)=>{let i=`__PP_ESCAPED_BRACE_${n++}__`;return t.set(i,B(`&${r};`)),i}),placeholders:t}}static transformSpreadAttributes(e){let t=new Map,n=0;if(!e.includes("pp-spread"))return{html:e,spreadReplacements:t};let r=document.createElement("template");r.innerHTML=e;let i=e=>{if(e.nodeType===Node.ELEMENT_NODE){let r=e;if(Array.from(r.childNodes).forEach(i),r.hasAttribute("pp-spread")){let e=r.getAttribute("pp-spread")||"";r.removeAttribute("pp-spread");let i=U(e)?.expression.trim()??"";if(i.startsWith("...")){let e=B(i.slice(3).trim()),l=`___pp_spread_${n++}___`,o=`\${ (() => {\n const __obj = ${e};\n if (!__obj || typeof __obj !== 'object') return '';\n const __booleanAttrs = ${JSON.stringify(Array.from(this.SPREAD_BOOLEAN_ATTRS))};\n return Object.entries(__obj)\n .map(([k, v]) => {\n if (v == null) return '';\n const __attrName = String(k);\n if (!/^[^\\s"'<>/=]+$/.test(__attrName) || /^on/i.test(__attrName)) return '';\n if (__booleanAttrs.includes(__attrName.toLowerCase())) {\n if (v === false) return '';\n if (v === true) return __attrName;\n }\n const __escapedValue = String(v)\n .split('&').join('&amp;')\n .split('"').join('&quot;')\n .split("'").join('&#39;')\n .split('<').join('&lt;')\n .split('>').join('&gt;');\n return __attrName + '="' + __escapedValue + '"';\n })\n .filter(Boolean)\n .join(' ');\n })() }`;t.set(l,o),r.setAttribute(l,"")}}}};return Array.from(r.content.childNodes).forEach(i),{html:r.innerHTML,spreadReplacements:t}}static expandSpreadPlaceholders(e,t){let n=e;return t.forEach((e,t)=>{n=n.split(`${t}=""`).join(e),n=n.split(t).join(e)}),n}static transformRefAttributes(e){if(!e.includes("pp-ref"))return e;let t=document.createElement("template");t.innerHTML=e;let n=document.createTreeWalker(t.content,NodeFilter.SHOW_ELEMENT),r=n.nextNode();for(;r;){let e=r;if(e.hasAttribute("pp-ref")){if(e.hasAttribute("pp-component")&&!e.hasAttribute("pp-ref-owner")){r=n.nextNode();continue}let t=U(e.getAttribute("pp-ref")||"");if(t){let n=B(t.expression);e.removeAttribute("pp-ref"),e.setAttribute("data-pp-ref",`{ __pp_ref(${n}) }`)}}r=n.nextNode()}return t.innerHTML}static transformContextProviderTags(e){if(!/\.provider\b/i.test(e))return e;let t="",n=0;for(;n<e.length;){let r=e.slice(n).match(/^<([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\.Provider)\b/i);if(!r){t+=e[n],n+=1;continue}let i=r[1],l=this.findOpeningTagEnd(e,n);if(-1===l){t+=e[n],n+=1;continue}let o=e.slice(n+r[0].length,l),s=l+1,a=this.findMatchingContextProviderClose(e,s);if(!a){t+=e[n],n+=1;continue}let u=this.transformContextProviderTags(e.slice(s,a.start));t+=`<pp-context-provider data-pp-context-token="{ __pp_context_token(__pp_context_lookup(${`'${i.replace(/\.Provider$/i,"").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`})) }" data-pp-context-value="{ __pp_context_value(${this.extractContextProviderValueExpression(o)}) }">`+u+"</pp-context-provider>",n=a.end}return t}static findOpeningTagEnd(e,t){let n=null,r=0;for(let i=t;i<e.length;i++){let t=e[i],l=this.isEscaped(e,i);if(n){if("{"===t&&!l){r++;continue}if("}"===t&&!l&&r>0){r--;continue}t===n&&!l&&0===r&&(n=null)}else if(l||'"'!==t&&"'"!==t){if(">"===t)return i}else n=t,r=0}return-1}static findMatchingContextProviderClose(e,t){this.CONTEXT_PROVIDER_TAG_PATTERN.lastIndex=t;let n,r=1;for(;n=this.CONTEXT_PROVIDER_TAG_PATTERN.exec(e);){let e=n[0];if(r+=e.startsWith("</")?-1:1,0===r)return{start:n.index,end:n.index+e.length}}return null}static extractContextProviderValueExpression(e){let t=e.match(/\bvalue\s*=\s*(?:"([\s\S]*?)"|'([\s\S]*?)'|([^\s>]+))/i);if(!t)return"undefined";let n=t[1]??t[2]??t[3]??"",r=U(B(n.trim()));return r?r.expression:JSON.stringify(n)}static normalizeTextareaValueAttributes(e){if(!e.includes("<textarea")||!e.includes("value="))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("textarea").forEach(e=>{let t=e,n=t.getAttribute("value");null!==n&&(t.textContent=n,t.removeAttribute("value"))}),t.innerHTML}static transformStyleAliasAttributes(e){if(!e.includes("pp-style"))return e;let t=document.createElement("template");t.innerHTML=e;let n=document.createTreeWalker(t.content,NodeFilter.SHOW_ELEMENT),r=n.nextNode();for(;r;){let e=r;if(e.hasAttribute("pp-style")){let t=e.getAttribute("pp-style")??"",n=e.getAttribute("style")??"";e.removeAttribute("pp-style");let r=this.mergeStyleAttributeValues(n,t);r.length>0&&e.setAttribute("style",r)}r=n.nextNode()}return t.innerHTML}static mergeStyleAttributeValues(e,t){let n=e.trim(),r=t.trim().replace(/^;+\s*/,"");return n?r?`${n.endsWith(";")?n:`${n};`} ${r}`:n:r}static transformSelectValueAttributes(e){if(!e.includes("<select")||!e.includes("value="))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("select").forEach(e=>{let t=e,n=t.getAttribute("value");if(null===n)return;let r=U(n);if(!r)return;let i=B(r.expression);t.removeAttribute("value"),t.setAttribute("data-pp-select-value",`{ __pp_select_value(${i}) }`)}),t.innerHTML}static transformInputValueAttributes(e){if(!e.includes("<input")||!e.includes("value="))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("input").forEach(e=>{let t=e,n=t.getAttribute("value");if(null===n)return;let r=U(n);if(!r)return;let i=B(r.expression);t.removeAttribute("value"),t.setAttribute("data-pp-input-value",`{ __pp_input_value(${i}) }`)}),t.innerHTML}static transformCheckedValueAttributes(e){if(!e.includes("<input")||!e.includes("checked="))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("input").forEach(e=>{let t=e,n=t.getAttribute("checked");if(null===n)return;let r=U(n);if(!r)return;let i=B(r.expression);t.removeAttribute("checked"),t.setAttribute("data-pp-checked-value",`{ __pp_checked_value(${i}) }`)}),t.innerHTML}static transformDefaultValueAttributes(e){if(!e.includes("default"))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("input, textarea, select").forEach(e=>{let t=e,n=t.getAttribute("defaultvalue");if(null===n)return;let r=U(n);if(!r)return;let i=B(r.expression);t.removeAttribute("defaultvalue"),t.setAttribute("data-pp-default-value",`{ __pp_default_value(${i}) }`)}),t.innerHTML}static transformDefaultCheckedAttributes(e){if(!e.includes("default"))return e;let t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("input").forEach(e=>{let t=e,n=t.getAttribute("defaultchecked");if(null===n)return;let r=U(n);if(!r)return;let i=B(r.expression);t.removeAttribute("defaultchecked"),t.setAttribute("data-pp-default-checked",`{ __pp_default_checked(${i}) }`)}),t.innerHTML}static transformComponentBoundaryBindings(e,t={}){if(!e.includes("pp-component=")||!e.includes("{"))return{html:e,boundaryReplacements:new Map};let n=document.createElement("template");n.innerHTML=e;let r=new Map,i=0;return n.content.querySelectorAll("[pp-component]").forEach(e=>{let n=e;Array.from(n.attributes).forEach(e=>{let l=e.name;if("pp-component"===l||z(l,n))return;let o=U(e.value);if(!o){let o=this.buildMixedBoundaryAttributeCode(l,e.value,t.rewriteExpression);if(o){let e=`___PP_BOUNDARY_ATTR_${i++}___`;r.set(`${l}="${e}"`,o),n.setAttribute(l,e)}return}let s=this.expandEmbeddedBindingsInStringLiterals(B(o.expression)),a=t.rewriteExpression?.(s),u=a?.evalExpression??s,p=(a?.evalExpression??s).replace(/\\/g,"\\\\").replace(/'/g,"\\'"),d=a?.rawExpressionCode??JSON.stringify(p),c=`___PP_BOUNDARY_ATTR_${i++}___`,h=this.isBooleanAttribute(l)?`return __pp_raw_html(__ppAttr ? '${l}' : '');`:`return __pp_raw_html('${l}="' + __pp_escape_html(__ppAttr) + '"');`;r.set(`${l}="${c}"`,`\${__pp_render_value((() => { const __ppAttr = (${u}); if (typeof __ppAttr === 'boolean') { ${h} } if (__ppAttr == null) return ''; if (typeof __ppAttr === 'string' || typeof __ppAttr === 'number' || typeof __ppAttr === 'bigint') { const __ppText = String(__ppAttr); return __pp_raw_html('${l}="' + __pp_escape_html(__ppText) + '"' + (__ppText.indexOf('{') === -1 && __ppText.indexOf('}') === -1 ? '' : ' ${L}${l}=""')); } return __pp_raw_html('${l}="{' + ${d} + '}"'); })())}`),n.setAttribute(l,c)})}),{html:n.innerHTML,boundaryReplacements:r}}static maskStaticComponentIds(e){if(!e.includes("pp-component="))return{html:e,componentIdPlaceholders:new Map};let t=document.createElement("template");t.innerHTML=e;let n=new Map,r=0;return t.content.querySelectorAll("[pp-component]").forEach(e=>{let t=e.getAttribute("pp-component");if(!t||t.includes("{"))return;let i=`___PP_STATIC_COMPONENT_ID_${r++}___`;n.set(i,t),e.setAttribute("pp-component",i)}),{html:t.innerHTML,componentIdPlaceholders:n}}static buildMixedBoundaryAttributeCode(e,t,n){if(!t.includes("{"))return null;let r=[],i="",l=!1,o=0,s=()=>{0!==i.length&&(r.push(JSON.stringify(i)),i="")};for(;o<t.length;){if("{"!==t[o]){i+=t[o],o++;continue}if(o>0&&"$"===t[o-1]){i+="{",o++;continue}let e=this.findClosingBrace(t,o);if(-1===e){i+=t[o],o++;continue}let a=this.expandEmbeddedBindingsInStringLiterals(B(t.slice(o+1,e)));if(!G.isValidExpression(a)){i+=t.slice(o,e+1),o=e+1;continue}s();let u=n?.(a).evalExpression??a;r.push(`__pp_attr_text((${u}))`),l=!0,o=e+1}return l?(s(),`\${__pp_render_value((() => { const __ppAttr = '' + (${1===r.length?r[0]:r.join(" + ")}); return __pp_raw_html('${e}="' + __pp_escape_html(__ppAttr) + '"' + (__ppAttr.indexOf('{') === -1 && __ppAttr.indexOf('}') === -1 ? '' : ' ${L}${e}=""')); })())}`):null}static transformLoopAttributeEmbeddedBindings(e,t){if(!e.includes("{"))return e;let n=document.createElement("template");n.innerHTML=e;let r=!1,i=e=>{Array.from(e.attributes).forEach(n=>{if(z(n.name,e)||!n.value.includes("{"))return;let i=U(n.value);if(!i)return;let l=B(i.expression),o=this.expandEmbeddedBindingsInStringLiterals(l);o!==l&&G.isValidExpression(o)&&(e.setAttribute(n.name,`{${t(o).evalExpression}}`),r=!0)})},l=e=>{Array.from(e.children).forEach(e=>{i(e),e instanceof HTMLTemplateElement?l(e.content):l(e)})};return l(n.content),r?n.innerHTML:e}static expandEmbeddedBindingsInStringLiterals(e){let t="",n=0;for(;n<e.length;){let r=e[n];if('"'!==r&&"'"!==r){t+=e[n],n++;continue}let i=n;n++;let l="";for(;n<e.length;){let t=e[n];if(l+=t,n++,t===r&&!this.isEscaped(l,l.length-1)){l=l.slice(0,-1);break}}l.includes("{")?t+=this.expandEmbeddedBindingsInStringLiteral(l,r)??e.slice(i,n):t+=e.slice(i,n)}return t}static expandEmbeddedBindingsInStringLiteral(e,t){let n=[],r=0,i=0,l=e=>{e.length>0&&n.push(`${t}${e}${t}`)};for(;r<e.length;){if("{"!==e[r]||"$"===e[r-1]||this.isEscaped(e,r)||this.isServerTemplateBlockStart(e,r)){r++;continue}let t=this.findClosingBrace(e,r);if(-1===t){r++;continue}l(e.slice(i,r));let o=e.slice(r+1,t).trim();o&&n.push(this.stringifyEmbeddedBindingExpression(o)),r=t+1,i=r}return 0===n.length?null:(l(e.slice(i)),`(${n.length>0?n.join(" + "):`${t}${t}`})`)}static stringifyEmbeddedBindingExpression(e){return`((__ppVal) => { if (typeof __ppVal === 'boolean' || __ppVal == null) return ''; if (Array.isArray(__ppVal)) return __ppVal.map((__ppItem) => __ppItem == null || typeof __ppItem === 'boolean' ? '' : String(__ppItem)).join(''); return String(__ppVal); })(${e})`}static compile(e,t){let n=this.stripAuthoredComments((e||"").replace(/\r\n/g,"\n").replace(/\r/g,"\n")),r=`${n}${t.join("\0")}`,i=this.cache.get(r);if(i)return this.cache.delete(r),this.cache.set(r,i),i;let l=this.transformContextProviderTags(n),{maskedHtml:o,placeholders:s}=this.maskEscapedBraceEntities(l),a=this.escapeLiteralCodeProcessingInstructionOpeners(o),{maskedHtml:u,placeholders:p}=this.maskLiteralHtmlTextNodes(a),{maskedTemplate:d,placeholders:c,boundaryStubs:h}=this.maskComplexComponents(u),{maskedHtml:f,placeholders:m}=this.maskLiteralElements(d,"style","STYLE"),{maskedHtml:_,placeholders:g}=this.maskLiteralElements(f,"script","SCRIPT"),y=this.transformStyleAliasAttributes(_),E=this.normalizeTextareaValueAttributes(pe(y)),v=t.includes("__pp_input_value")?this.transformInputValueAttributes(E):E,b=t.includes("__pp_checked_value")?this.transformCheckedValueAttributes(v):v,C=this.transformSelectValueAttributes(b),T=this.transformDefaultValueAttributes(C),w=this.transformDefaultCheckedAttributes(T),P=this.transformRefAttributes(w),{html:k,boundaryReplacements:R}=this.transformComponentBoundaryBindings(P),{html:A,spreadReplacements:x}=this.transformSpreadAttributes(k),{html:I,loopReplacements:M}=this.processStructuralDirectives(A,e=>{let t=e;return t=this.restorePlaceholders(t,g),t=this.restorePlaceholders(t,m),t=this.restoreComponentPlaceholders(t,c,h,void 0),t=this.restorePlaceholders(t,p),this.restorePlaceholders(t,s)}),N=this.transformNonBooleanAttributeBooleans(this.transformBooleanAttributes(I));(()=>{let e=!0;for(;e;)e=!1,M.forEach((t,n)=>{let r=N;N=N.split("${"+n+"}").join("${"+t+"}"),N=N.split(n).join("{ __pp_raw_html("+t+") }"),N!==r&&(e=!0)})})();let L="return `",H=0,D="";for(;H<N.length;){let e=N[H],t="o"===e||"O"===e?N[H+1]:"";if("n"===t||"N"===t){let e=N.slice(H,H+20).toLowerCase().match(/^on\w+\s*=\s*(["'])/);if(e){let t=N.slice(H,H+e[0].length),n=t[t.length-1],r=H+e[0].length;for(;r<N.length&&(N[r]!==n||"\\"===N[r-1]);)r++;D+=N.slice(H,r+1),H=r+1;continue}}if("{"===e){if(this.isServerTemplateBlockStart(N,H)){let e=this.findServerTemplateBlockEnd(N,H);if(-1!==e){D+=N.slice(H,e),H=e;continue}}let e=this.findClosingBrace(N,H);if(-1!==e){let t=B(N.slice(H+1,e));if(G.isValidExpression(t)){L+=this.escapeTemplateLiteralText(D),D="";let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g," ");L+=`\${ (() => {\n try {\n const __res = (${t});\n return __pp_render_value(__res);\n } catch(e) {\n console.error("[PP-ERROR] Template Expression Failed: \\"${n}\\"", e);\n return '';\n }\n })() }`,H=e+1;continue}}}D+=e,H++}L+=this.escapeTemplateLiteralText(D),L+="`;",L=this.expandSpreadPlaceholders(L,x),R.size>0&&(L=L.replace(/[^\s"'<>=]+="___PP_BOUNDARY_ATTR_\d+___"/g,e=>R.get(e)??e));let O=this.SHARED_HELPER_PRELUDE+L;try{let e=t.slice(),n=O.includes("__pp_loop_capture(")&&!e.includes("__pp_loop_capture"),i=O.includes("__pp_loop_read(")&&!e.includes("__pp_loop_read"),l=O.includes("__pp_loop_rows(")&&!e.includes("__pp_loop_rows");n&&e.push("__pp_loop_capture"),i&&e.push("__pp_loop_read"),l&&e.push("__pp_loop_rows");let o=e.indexOf("__pp_boundary_html"),a=Function("__pp_shared",...e,O),u=(...e)=>{let t=n||i?new Map:null,r=0,u=n||i||l?e.slice():e;n&&u.push(e=>{let n="ppv_"+ ++r;return t.set(n,e),n}),i&&u.push(e=>t.get(e)),l&&u.push((e,t,n)=>{if(!n)return t.join("");let r="";for(let e=0;e<t.length;e++)r+=n(t[e],e);return r});let d=a(this.SHARED_RENDER_HELPERS,...u);return d=this.restorePlaceholders(d,g),d=this.restorePlaceholders(d,m),d=this.restoreComponentPlaceholders(d,c,h,o>=0?e[o]:void 0),d=this.restorePlaceholders(d,p),d=this.restorePlaceholders(d,s),d};return u.__ppRestoreArtifacts=e=>{let t=e;return t=this.restorePlaceholders(t,g),t=this.restorePlaceholders(t,m),t=this.restoreComponentPlaceholders(t,c,h,void 0),t=this.restorePlaceholders(t,p),t=this.restorePlaceholders(t,s),t},S(this.cache,r,u,this.MAX_CACHE_SIZE),u}catch(e){return console.error("[PP-ERROR] Compilation Failed",e),()=>"Error in Template"}}static maskLiteralElements(e,t,n){if(!RegExp(`<${t}[\\s>]`,"i").test(e))return{maskedHtml:e,placeholders:new Map};let r=document.createElement("template");r.innerHTML=e;let i=new Map,l=0;return r.content.querySelectorAll(t).forEach(e=>{let t=`__PP_${n}_${l++}__`;i.set(t,e.outerHTML),e.replaceWith(document.createTextNode(t))}),{maskedHtml:r.innerHTML,placeholders:i}}static maskLiteralHtmlTextNodes(e){if(!e.includes("{")&&!e.includes("}")||!this.LITERAL_TEXT_LT_ENTITY_PATTERN.test(e))return{maskedHtml:e,placeholders:new Map};let t=document.createElement("template");t.innerHTML=e;let n=new Map,r={value:0},i=document.createTreeWalker(t.content,NodeFilter.SHOW_TEXT),l=[];for(;i.nextNode();)l.push(i.currentNode);return l.forEach(e=>{if(this.isWithinLiteralTextContainer(e))return;let t=e.textContent??"";if(!t.includes("{")&&!t.includes("}"))return;let i=this.splitLiteralHtmlTextSegments(t);if(!i)return;let l="";i.forEach(e=>{l+=e.literalHtml?this.maskLiteralBraces(e.text,n,r):e.text}),e.textContent=l}),{maskedHtml:t.innerHTML,placeholders:n}}static escapeLiteralCodeProcessingInstructionOpeners(e){return e.includes("<?")?e.replace(this.LITERAL_CODE_TAG_PATTERN,(e,t,n,r)=>!n.includes("<?")||this.isPureBindingLiteral(n.trim())?e:`${t}${n.replace(/<\?/g,"&lt;?")}${r}`):e}static isWithinLiteralTextContainer(e){let t=e.parentNode;for(;t;){if(t.nodeType===Node.ELEMENT_NODE){let e=t.tagName.toLowerCase();if("script"===e||"style"===e)return!0}t=t.parentNode}return!1}static splitLiteralHtmlTextSegments(e){if(!e.includes("<")||!e.includes(">"))return null;let t=document.createElement("template");t.innerHTML=e;let n=Array.from(t.content.childNodes).map(e=>({text:e.nodeType===Node.TEXT_NODE?e.textContent??"":this.serializeNodeHtml(e),literalHtml:e.nodeType!==Node.TEXT_NODE}));return n.some(e=>e.literalHtml)?n:null}static serializeNodeHtml(e){let t=document.createElement("template");return t.content.appendChild(e.cloneNode(!0)),t.innerHTML}static maskLiteralBraces(e,t,n){let r="";for(let i of e){if("{"===i||"}"===i){let e=`__PP_LITERAL_HTML_BRACE_${n.value++}__`;t.set(e,i),r+=e;continue}r+=i}return r}static isPureBindingLiteral(e){return null!==U(e)}static restoreComponentPlaceholders(e,t,n,r){if(0===t.size)return e;let i="",l=0;for(;l<e.length;){let o=e.indexOf("__PP_CHILD_",l);if(-1===o)break;let s=e.indexOf("__",o+11);if(-1===s)break;let a=e.slice(o,s+2),u=t.get(a);if(void 0===u){i+=e.slice(l,s+2),l=s+2;continue}let p=r?r(a,u,n.get(a)??null):u;i+=e.slice(l,o),i+=p.includes("__PP_CHILD_")?this.restoreComponentPlaceholders(p,t,n,r):p,l=s+2}return 0===l?e:i+e.slice(l)}static restorePlaceholders(e,t){let n=e;return t.forEach((e,t)=>{n.includes(t)&&(n=n.split(t).join(e))}),n}static transformBooleanAttributes(e){let t="",n=0,r=0,i=this.DYNAMIC_BOOLEAN_ATTRIBUTE_PATTERN;for(i.lastIndex=0;r<e.length;){i.lastIndex=r;let l=i.exec(e);if(!l)break;let o=l[1],s=l[2],a=l.index,u=a+l[0].length-1;if("checked"===o&&this.isAttributeOnComponentBoundary(e,a)||this.isServerTemplateBlockStart(e,u)){r=a+1;continue}let p=this.findClosingBrace(e,u);if(-1===p||e[p+1]!==s){r=a+1;continue}let d=B(e.slice(u+1,p)),c=d.replace(/\\/g,"\\\\").replace(/'/g,"\\'");t+=e.slice(n,a),t+=`{ __pp_bool_attr('${o}', (${d}), '${c}') }`,n=p+2,r=n}return 0===n?e:t+e.slice(n)}static DYNAMIC_ATTRIBUTE_CANDIDATE_PATTERN=/([^\s"'<>/=]+)\s*=\s*(["'])\{/y;static transformNonBooleanAttributeBooleans(e){let t=this.DYNAMIC_ATTRIBUTE_CANDIDATE_PATTERN,n="",r=0,i=0;for(;i<e.length;){let l=this.findNextAttributeCandidate(e,i);if(-1===l)break;t.lastIndex=l;let o=t.exec(e);if(!o){i=l+1;continue}let s=o[1],a=o[2];if(this.isAttributePosition(e,l)&&!this.isBooleanAttribute(s)&&"pp-component"!==s&&!/^on\w+$/i.test(s)){let t=l+o[0].length-1;if(!this.isServerTemplateBlockStart(e,t)){let o=this.findClosingBrace(e,t);if(-1!==o&&e[o+1]===a){let a=B(e.slice(t+1,o));if(G.isValidExpression(a)){n+=e.slice(r,l),n+=`{ __pp_attr('${s}', (${a})) }`,r=o+2,i=r;continue}}}}i=l+1}return 0===r?e:n+e.slice(r)}static findNextAttributeCandidate(e,t){let n=t;for(;n<e.length;){let r=e.indexOf("{",n);if(r<=0)return-1;let i=e[r-1];if('"'!==i&&"'"!==i){n=r+1;continue}let l=r-2;for(;l>=0&&/\s/.test(e[l]);)l--;if(l<0||"="!==e[l]){n=r+1;continue}for(l--;l>=0&&/\s/.test(e[l]);)l--;let o=l;for(;l>=0&&!/[\s"'<>/=]/.test(e[l]);)l--;if(o===l){n=r+1;continue}let s=l+1;if(!(s<t))return s;n=r+1}return-1}static isBooleanAttribute(e){return R.has(e.toLowerCase())}static isAttributePosition(e,t){let n=e.lastIndexOf("<",t);return!(-1===n||e.lastIndexOf(">",t)>=n)&&(t>n&&/\s/.test(e[t-1]??""))}static isAttributeOnComponentBoundary(e,t){let n=e.lastIndexOf("<",t);if(-1===n||e.lastIndexOf(">",t)>n)return!1;let r=this.findOpeningTagEnd(e,n);if(-1===r||t>r)return!1;let i=e.slice(n,n+2);if("</"===i||"<!"===i||"<?"===i)return!1;let l=e.slice(n,r+1);return/\spp-component(?:\s|=|>)/i.test(l)}static captureLoopVariablesInEventHandlers(e,t,n,r=!1,i=[]){let l="",o=0;for(;o<e.length;){let s=e.slice(o,o+40).toLowerCase().match(/^on\w+\s*=\s*(["'])/);if(s){let a=s[0].length,u=e.slice(o,o+a),p=u[u.length-1],d=o+a,c=d;for(;c<e.length&&(e[c]!==p||"\\"===e[c-1]);)c++;let h=u.slice(0,-2).trim(),f=e.slice(d,c);f=this.rewriteLoopEventHandlerCode(f,t,n,r,i),l+=`${h}=${p}${f}${p}`,o=c+1;continue}l+=e[o],o++}return l}static rewriteLoopEventHandlerCode(e,t,n,r,i=[]){let l=U(e),o=B(l?l.expression:e);i.forEach(e=>{o=this.applyLoopEventCaptureRewrites(o,e)});let s={iterator:t,collectionName:"",indexVar:n,userDefinedIndex:r};return o=this.applyLoopEventCaptureRewrites(o,s),[...i,s].forEach(e=>{let t=this.getLoopIndexToken(e.indexVar);o=o.split(t).join(`\${${e.indexVar}}`)}),l?`{${o}}`:o}static applyLoopEventCaptureRewrites(e,t){let n=this.getLoopIndexToken(t.indexVar),r=e;return t.userDefinedIndex&&(r=this.replaceLoopIdentifierUsages(r,t.indexVar,n)),this.replaceLoopIdentifierUsages(r,t.iterator,`__pp_loop_read('\${__pp_loop_capture(${t.iterator})}')`)}static getLoopIndexToken(e){return`__PP_LOOP_IDX_${e}__`}static replaceLoopIdentifierUsages(e,t,n){let r=G.analyzeLoopVariableUsage(e,t).slice().sort((e,t)=>t.start-e.start);if(0===r.length)return e;let i=e;return r.forEach(e=>{let r=e.isShorthand?this.buildShorthandReplacement(t,n,e.isUnwrap):n;i=i.slice(0,e.start)+r+i.slice(e.end)}),i}static buildShorthandReplacement(e,t,n){return n?`{ ${e}: ${t} }`:`${e}: ${t}`}static createLoopBoundaryBindingRewrite(){return e=>({evalExpression:e,rawExpressionCode:'("__pp_loop_read(\'" + __pp_loop_capture(__ppAttr) + "\')")'})}static isIdentifier(e){return/^[A-Za-z_$][\w$]*$/.test(e)&&!I.has(e)&&!this.INTERNAL_LOOP_NAMES.has(e)}static stripBalancedParens(e){let t=e.trim();return t.startsWith("(")&&this.findMatchingToken(t,0,"(",")")===t.length-1?t.slice(1,-1).trim():null}static parseLoopDirective(e){let t=this.findTopLevelInSeparator(e);if(-1===t)return null;let n=e.slice(0,t).trim(),r=e.slice(t+2).trim();if(!n||!r)return null;let i=this.stripBalancedParens(n);if(null!==i){let e=this.findTopLevelToken(i,",");if(-1===e)return null;let t=i.slice(0,e).trim(),n=i.slice(e+1).trim();return t&&n?{iterator:t,indexVar:n,collection:r}:null}return{iterator:n,indexVar:null,collection:r}}static findTopLevelInSeparator(e){let t={parenDepth:0,bracketDepth:0,braceDepth:0,quote:null};for(let n=0;n<e.length;n++){let r=e[n];if(!this.advanceScannerState(t,e,n)&&0===t.parenDepth&&0===t.bracketDepth&&0===t.braceDepth&&"i"===r&&"n"===e[n+1]&&/\s/.test(e[n-1]??"")&&/\s/.test(e[n+2]??""))return n}return-1}static findTopLevelToken(e,t){let n={parenDepth:0,bracketDepth:0,braceDepth:0,quote:null};for(let r=0;r<e.length;r++)if(!this.advanceScannerState(n,e,r)&&0===n.parenDepth&&0===n.bracketDepth&&0===n.braceDepth&&e[r]===t)return r;return-1}static findMatchingToken(e,t,n,r){let i=0,l=null;for(let o=t;o<e.length;o++){let t=e[o],s=this.isEscaped(e,o);if(l)t===l&&!s&&(l=null);else if(s||'"'!==t&&"'"!==t&&"`"!==t)if(t!==n||s){if(t===r&&!s&&(i--,0===i))return o}else i++;else l=t}return-1}static advanceScannerState(e,t,n){let r=t[n],i=this.isEscaped(t,n);return e.quote?(r===e.quote&&!i&&(e.quote=null),!0):i||'"'!==r&&"'"!==r&&"`"!==r?(i||("("===r?e.parenDepth++:")"===r?e.parenDepth--:"["===r?e.bracketDepth++:"]"===r?e.bracketDepth--:"{"===r?e.braceDepth++:"}"===r&&e.braceDepth--),!1):(e.quote=r,!0)}static isEscaped(e,t){let n=0,r=t-1;for(;r>=0&&"\\"===e[r];)n++,r--;return n%2!=0}static compileLoopRowPlan(e,t){let n=null;for(let t=e.firstChild;t;t=t.nextSibling)if(t.nodeType===Node.ELEMENT_NODE){if(n)return null;n=t}if(!n)return null;let r=this.buildElementPlan(n,!0);if(null===r||-1===r.keyIndex)return null;let i=n.hasAttribute("pp-component"),l={key:r.keyIndex,slots:r.slots,size:r.exprs.length};return r.hasBoundary&&(l.hasBoundary=1),i&&(l.rootBoundary=1),(!r.hasBoundary||i)&&(l.prototypeHtml=n.outerHTML,l.contextTag=t),{exprs:r.exprs,descriptor:l}}static serializeRowPlanDescriptor(e){let t=JSON.stringify(e),n=e.prototypeHtml;if(!n||!n.includes("{")&&!n.includes("}"))return t;let r=JSON.stringify(n),i=r.replace(/\{/g,"\\u007b").replace(/\}/g,"\\u007d");return t.replace(r,i)}static buildElementPlan(e,t){let n,r=[],i=[],l=-1,o=e=>{let t=this.expandEmbeddedBindingsInStringLiterals(e);return G.isValidExpression(t)?(r.push(t),r.length-1):null},s=e=>{let t=[],n=0,r=0;for(;n<e.length;){if("{"!==e[n]){n++;continue}if(n>0&&"$"===e[n-1]){n++;continue}if(_e(e,n))return null;let i=H(e,n);if(-1===i){n++;continue}let l=o(B(e.slice(n+1,i)));null!==l?(n>r&&t.push(e.slice(r,n)),t.push(l),n=i+1,r=n):n=i+1}return r<e.length&&t.push(e.slice(r)),t},a=!1,u=(e,t)=>{a=!0;let n=e.getAttributeNames();for(let r=0;r<n.length;r++){let s=n[r],a=s.toLowerCase();if("pp-component"===a)continue;if("pp-ref"===a||"pp-ref-owner"===a||"pp-owner"===a)return!1;let u=e.getAttribute(s)??"";if(!u.includes("{"))continue;if(a.startsWith("on"))return!1;let p=U(u);if(!p)return!1;let d=o(B(p.expression));if(null===d)return!1;0!==t.length||"key"!==a?i.push({kind:"battr",p:t,name:a,v:d}):l=d}let r=[e];for(;r.length>0;){for(let e=r.pop().firstChild;e;e=e.nextSibling){if(e.nodeType===Node.TEXT_NODE){if(e.data.includes("{"))return!1;continue}if(e.nodeType===Node.COMMENT_NODE)return!1;if(e.nodeType!==Node.ELEMENT_NODE)continue;let t=e,n=t.tagName.toLowerCase();if("template"===n||"pp-context-provider"===n)return!1;let i=t.getAttributeNames();for(let e=0;e<i.length;e++){let n=i[e].toLowerCase();if("pp-owner"===n||"pp-ref"===n||"pp-ref-owner"===n||"data-pp-ref"===n||(t.getAttribute(i[e])??"").includes("{"))return!1}r.push(t)}}return!0},p=(e,n)=>{let r=e.tagName.toLowerCase();if(e.hasAttribute("pp-component"))return u(e,n);if("template"===r||"script"===r||"style"===r||"slot"===r||"input"===r||"textarea"===r||"select"===r||"pp-context-provider"===r||r.includes("."))return!1;let a=e.getAttributeNames();for(let r=0;r<a.length;r++){let u=a[r],p=u.toLowerCase();if(p.startsWith("on")||p.startsWith("pp-")||p.startsWith("data-pp-")||"defaultvalue"===p||"defaultchecked"===p)return!1;let d=e.getAttribute(u)??"";if(d.includes("__PP_"))return!1;if(!d.includes("{"))continue;let c=U(d),h=0===n.length&&"key"===p;if(c){let e=o(B(c.expression));if(null===e)continue;if(h){if(!t)return!1;l=e;continue}i.push({kind:"attr",p:n,name:u,bool:R.has(p),v:e});continue}if(h||R.has(p))return!1;let f=s(d);if(null===f)return!1;f.some(e=>"number"==typeof e)&&i.push({kind:"attrParts",p:n,name:u,parts:f})}let d=!1,c="",h=!1;for(let t=e.firstChild;t;t=t.nextSibling)if(t.nodeType!==Node.ELEMENT_NODE){if(t.nodeType===Node.COMMENT_NODE)return!1;t.nodeType===Node.TEXT_NODE&&(c+=t.data,h=!0)}else d=!0;if(h&&c.includes("__PP_"))return!1;if(h&&c.includes("{"))if(d){let e=s(c);if(e&&e.some(e=>"number"==typeof e))return!1}else{let e=s(c);if(null===e)return!1;e.some(e=>"number"==typeof e)&&i.push({kind:"text",p:n,parts:e})}if(d){let t=0;for(let r=e.firstElementChild;r;r=r.nextElementSibling){if(!p(r,[...n,t]))return!1;t++}}return!0};try{n=p(e,[])}catch{return null}return n?{exprs:r,slots:i,keyIndex:l,hasBoundary:a}:null}static compileComponentBodyPlan(e){let t=e;if(0===t.length||t.length>8192||/<(?:script|style|template|slot|input|textarea|select|pre|code|xmp|title|svg|math|iframe|frame|object|embed)\b|\bpp-|\.provider|<!--|&(?:amp;)?(?:lbrace|rbrace|#0*123|#0*125|#x0*7b|#x0*7d|lt|#0*60|#x0*3c);|__PP_|\$\{/i.test(t))return null;let n=document.createElement("template");n.innerHTML=t;let r,i=null;for(let e=n.content.firstChild;e;e=e.nextSibling)if(e.nodeType!==Node.ELEMENT_NODE){if(e.nodeType!==Node.TEXT_NODE||""!==e.data.trim())return null}else{if(null!==i)return null;i=e}if(null===i)return null;try{r=this.buildElementPlan(i,!1)}catch{return null}return null===r||r.hasBoundary||r.slots.length>30?null:{exprs:r.exprs,descriptor:{rootTag:i.tagName,slots:r.slots,size:r.exprs.length}}}static isBoundaryRowBodySafe(e){let t=(e,n)=>{for(let r=e.firstChild;r;r=r.nextSibling){if(r.nodeType===Node.COMMENT_NODE){if(!n)return!1;continue}if(r.nodeType===Node.TEXT_NODE){if(!n&&r.data.includes("__PP_"))return!1;continue}if(r.nodeType!==Node.ELEMENT_NODE)continue;let e=r,i=e.tagName.toLowerCase();if("template"===i||e.hasAttribute("pp-ref-owner")||!n&&("input"===i||"textarea"===i||"select"===i||"slot"===i||"pp-context-provider"===i||e.hasAttribute("pp-ref")||e.hasAttribute("data-pp-ref"))||!t(e,n||e.hasAttribute("pp-component")))return!1}return!0};return t(e,!1)}static processStructuralDirectives(e,t){if(!e.includes("pp-for"))return{html:e,loopReplacements:new Map};let n=document.createElement("template");n.innerHTML=e;let r=new Map,i=0,l=0,o=(e,n=[])=>{let s=Array.from(e.childNodes);for(let e of s){if(e.nodeType!==Node.ELEMENT_NODE)continue;let s=e,a="TEMPLATE"===s.tagName,u="template"===s.tagName&&"template"===s.localName;if(a||u){let e=s,a=e.getAttribute("pp-for")||"",u=null;if(e.hasAttribute("pp-for")){let t,n,r,i=this.parseLoopDirective(a),o=!1;if(!i){console.warn(`[PP-WARN] Invalid pp-for directive skipped: "${a}"`),e.replaceWith(document.createComment("invalid-loop"));continue}if(t=i.iterator,r=i.collection,n=i.indexVar??"__pp_idx_"+l++,o=null!==i.indexVar,!this.isIdentifier(t)||o&&!this.isIdentifier(n)||o&&t===n){console.warn(`[PP-WARN] pp-for currently expects identifier loop variables: "${a}"`),e.replaceWith(document.createComment("invalid-loop"));continue}if(!G.isValidExpression(r)){console.warn(`[PP-WARN] Invalid pp-for collection expression skipped: "${r}"`),e.replaceWith(document.createComment("invalid-loop"));continue}u={iterator:t,collectionName:r,indexVar:n,userDefinedIndex:o}}let p=e.content??e;if(o(p,u?[...n,u]:n),u){let{iterator:l,collectionName:o,indexVar:s,userDefinedIndex:a}=u,d=0===n.length?this.compileLoopRowPlan(p,e.parentElement?.tagName.toLowerCase()):null;d?.descriptor.prototypeHtml&&(d.descriptor.prototypeHtml=t(d.descriptor.prototypeHtml));let c=e.innerHTML,{html:h,componentIdPlaceholders:f}=this.maskStaticComponentIds(c);c=h,c=this.transformContextProviderTags(c),c=this.transformRefAttributes(c),c=this.transformStyleAliasAttributes(c);let m=this.createLoopBoundaryBindingRewrite(),{html:_,boundaryReplacements:g}=this.transformComponentBoundaryBindings(c,{rewriteExpression:m});c=_,c=this.captureLoopVariablesInEventHandlers(c,l,s,a,n),c=this.transformLoopAttributeEmbeddedBindings(c,m),c=c.replace(/___PP_LOOP_\d+___/g,e=>"${"+e+"}"),c=c.replace(/\r/g,""),c=this.transformNonBooleanAttributeBooleans(this.transformBooleanAttributes(c)),c=this.transformInterpolations(c),c=this.escapeTemplateLiteralTextPreservingInterpolations(c),g.size>0&&(c=c.replace(/[^\s"'<>=]+="___PP_BOUNDARY_ATTR_\d+___"/g,e=>g.get(e)??e)),f.forEach((e,t)=>{c=c.split(t).join(e)});let y=`(${l}, ${s})`,E=`__pp_collection_${i}`,v=`__pp_items_${i}`,S=n.length>0||!this.loopBodyRendersSingleRoot(p)?-1:i,b=S>=0&&null!==d&&(1===d.descriptor.hasBoundary||!c.includes("__pp_loop_capture")&&!c.includes("__PP_")&&!c.includes("pp-component"))?d:null,C=S>=0&&c.includes("pp-component")&&this.isBoundaryRowBodySafe(p)?1:0,T=b?`, (${l}, ${s}, __pp_out, __pp_base) => { `+b.exprs.map((e,t)=>`__pp_out[__pp_base + ${t}] = (${e});`).join(" ")+" return __pp_out; }, "+this.serializeRowPlanDescriptor(b.descriptor):0===C?"":", undefined, undefined",w=`(() => { const ${E} = (${o}); const ${v} = __pp_to_loop_items(${E}); return __pp_loop_rows(${S}, ${v}, ${y} => \`${c}\`${T}${0===C?"":`, ${C}`}); })()`,P=`___PP_LOOP_${i++}___`;r.set(P,w),e.replaceWith(document.createTextNode(P));continue}continue}o(s,n)}};return o(n.content),{html:n.innerHTML,loopReplacements:r}}static loopBodyRendersSingleRoot(e){let t=0;for(let n=e.firstChild;n;n=n.nextSibling)if(n.nodeType!==Node.ELEMENT_NODE){if(n.nodeType!==Node.TEXT_NODE||""!==(n.textContent??"").trim())return!1}else if(++t>1)return!1;return 1===t}static transformInterpolations(e){let t="",n=0;for(;n<e.length;){if("o"===e[n]||"O"===e[n]){let r=e.slice(n,n+20).toLowerCase().match(/^on\w+\s*=\s*(["'])/);if(r){let i=e.slice(n,n+r[0].length),l=i[i.length-1],o=n+r[0].length;for(;o<e.length&&(e[o]!==l||"\\"===e[o-1]);)o++;t+=e.slice(n,o+1),n=o+1;continue}}if("{"===e[n]){if(n>0&&"$"===e[n-1]){t+="{",n++;continue}if(this.isServerTemplateBlockStart(e,n)){let r=this.findServerTemplateBlockEnd(e,n);if(-1!==r){t+=e.slice(n,r),n=r;continue}}let r=this.findClosingBrace(e,n);if(-1!==r){let i=B(e.slice(n+1,r));if(G.isValidExpression(i)){t+="${__pp_render_value("+i+")}",n=r+1;continue}}}t+=e[n],n++}return t}static maskComplexComponents(e){if(!e.includes("pp-component=")||!e.includes("<script")&&!e.includes("pp-owner"))return{maskedTemplate:e,placeholders:new Map,boundaryStubs:new Map};let t=document.createElement("template");t.innerHTML=e;let n=new Map,r=new Map,i=0,l=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;"),o=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),s=(e,t)=>{if(!e.includes("{"))return e;let r="",l=0;for(;l<e.length;){let o=e[l];if("{"===o&&"$"!==e[l-1]){let o=H(e,l);if(-1!==o){let s=`__PP_CHILD_${i++}__`;n.set(s,t(e.slice(l,o+1))),r+=s,l=o+1;continue}}r+=o,l++}return r},a=e=>{Array.from(e.attributes).forEach(t=>{t.value.includes("{")&&e.setAttribute(t.name,s(t.value,l))})},u=(e,t)=>{for(let r=e.firstChild,l=null;r;r=l){if(l=r.nextSibling,r.nodeType===Node.TEXT_NODE){if(!t){let e=r.textContent??"";e.includes("{")&&(r.textContent=s(e,o))}continue}if(r.nodeType!==Node.ELEMENT_NODE)continue;let e=r;if("script"===e.tagName.toLowerCase()){let t=`__PP_CHILD_${i++}__`;n.set(t,e.outerHTML),e.replaceWith(document.createTextNode(t));continue}if(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-owner"))u(e.content,!0);else{if(e.hasAttribute("pp-component")){t||a(e);let n=Array.from(e.querySelectorAll("script")).some(t=>t.closest("[pp-component]")===e),r=Array.from(e.querySelectorAll("template[pp-owner]")).some(t=>t.closest("[pp-component]")===e);u(e,t&&!n&&!r);continue}t||a(e),u(e instanceof HTMLTemplateElement?e.content:e,t)}}},p=(e,t=!1)=>{if(e instanceof Element){if(e.hasAttribute("pp-component")){let l=!!e.querySelector("script");if(l||e.querySelector("template[pp-owner]")){if(t)l&&u(e,!1);else if(e.hasAttribute("pp-ref-owner")&&e.hasAttribute("pp-ref")){let t=e.getAttribute("pp-ref");a(e),null!==t&&e.setAttribute("pp-ref",t),u(e,!1)}else{let t=`__PP_CHILD_${i++}__`;n.set(t,e.outerHTML);let l=this.buildBoundaryStub(e);null!==l&&r.set(t,l),e.replaceWith(document.createTextNode(t))}return}}if(e instanceof HTMLTemplateElement)return void p(e.content,!0)}let l=e.firstElementChild;for(;l;){let e=l.nextElementSibling;p(l,t),l=e}};return p(t.content),{maskedTemplate:t.innerHTML,placeholders:n,boundaryStubs:r}}static buildBoundaryStub(e){if(!Pe(e.innerHTML))return null;let t=e.cloneNode(!1);t.setAttribute(Me,"");let n=t.outerHTML;return n.endsWith(`</${e.tagName.toLowerCase()}>`)?n:null}static findClosingBrace(e,t){return H(e,t)}static isServerTemplateBlockStart(e,t){return _e(e,t)}static findServerTemplateBlockEnd(e,t){return ve(e,t)}},Le="data-pp-script-source";function Re(e){e.querySelectorAll("script:not([type])").forEach(e=>{let t=e;t.hasAttribute(Le)||(t.setAttribute(Le,t.textContent??""),t.textContent="")})}function ze(e){return e.getAttribute(Le)??e.textContent??""}var Be=class{componentId;bindingSeq=0;activeBindings=new Map;constructor(e){this.componentId=e}hasActiveBindings(){return this.activeBindings.size>0}ensureBindingId(e,t){let n="captured"===t?"__ppCapturedRefBindingId":"__ppPlainRefBindingId";return e[n]||(e[n]=`pprefbind_${this.componentId}_${t}_${++this.bindingSeq}`),e[n]}commit(e){let t=new Map;for(let[n,r]of this.activeBindings.entries()){let i=e.get(n);i?r.value!==i.value||r.element!==i.element?this.detachValue(r,"[PP-WARN] Ref cleanup failed"):t.set(n,r):this.detachValue(r,"[PP-WARN] Ref cleanup failed")}for(let[n,r]of e.entries()){let e=this.activeBindings.get(n);if(e&&e.value===r.value&&e.element===r.element)continue;let i=this.attachValue(r.value,r.element,"[PP-WARN] Ref attachment failed");t.set(n,{...r,cleanup:i})}this.activeBindings=t}clearAll(){for(let e of this.activeBindings.values())this.detachValue(e,"[PP-WARN] Ref cleanup failed");this.activeBindings.clear()}attachValue(e,t,n){let r=this.updateValue(e,t,n);return"function"==typeof r?r:void 0}detachValue(e,t){if(e.cleanup)try{e.cleanup()}catch(e){console.warn(t,e)}else this.updateValue(e.value,null,t)}updateValue(e,t,n){try{if("function"==typeof e)return e(t);e&&"object"==typeof e&&"current"in e&&(e.current=t)}catch(e){console.warn(n,e)}}},Ve=class{componentId;trackedPortals=new Map;constructor(e){this.componentId=e}get size(){return this.trackedPortals.size}has(e){return this.trackedPortals.has(e)}getPlaceholderText(e){return this.trackedPortals.get(e)?.placeholder.data||`pp-portal:${this.componentId}`}apply(e){let t=new Set,n=!1;for(let r of e){let e=r.ref.current;if(!e)continue;let i=r.target??document.body;t.add(e);let l=this.trackedPortals.get(e);if(l?.placeholder.parentNode){l.target!==i&&(i.appendChild(e),l.target=i,n=!0);continue}null===r.info.sourceParent&&e.parentNode instanceof Element&&(r.info.sourceParent=e.parentNode);let o=document.createComment(`pp-portal:${this.componentId}`);e.parentNode&&e.parentNode.insertBefore(o,e),i.appendChild(e),this.trackedPortals.set(e,{element:e,placeholder:o,target:i}),n=!0}for(let[e,r]of this.trackedPortals)t.has(e)||(r.placeholder.parentNode?(r.placeholder.parentNode.insertBefore(e,r.placeholder),r.placeholder.remove()):e.parentNode&&e.remove(),this.trackedPortals.delete(e),n=!0);return n}replaceElement(e,t){let n=this.trackedPortals.get(e);n&&(this.trackedPortals.delete(e),this.trackedPortals.set(t,{...n,element:t}))}contains(e){for(let[t]of this.trackedPortals)if(t===e||t.contains(e))return!0;return!1}elements(){return Array.from(this.trackedPortals.keys())}destroyAll(){for(let[,e]of this.trackedPortals)e.element.parentNode&&e.element.remove(),e.placeholder.parentNode&&e.placeholder.remove();this.trackedPortals.clear()}},He=class{registeredResetForms=new Set;applyControlledSelectValue(e,t){if(e.multiple){let n=new Set(this.normalizeControlledSelectValues(t));for(let t=0;t<e.options.length;t++){let r=e.options[t],i=n.has(r.value);r.selected!==i&&(r.selected=i)}return}let n=null==t?"":String(t);e.value!==n&&(e.value=n)}applyControlledInputValue(e,t){let n=null==t?"":String(t);this.shouldDeferFocusedDateLikeInputValue(e,n)?this.deferFocusedControlledInputValue(e,t):this.shouldDeferActiveNativeTextInputValue(e,n)||e.value!==n&&(e.value=n)}bindControlledSelectValues(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(!(r instanceof HTMLSelectElement))continue;let i=this.resolveControlledSelectCaptureId(r,t);i&&(j(r,"controlled"),this.applyControlledSelectValue(r,t.get(i)))}}bindControlledInputValues(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(!(r instanceof HTMLInputElement))continue;let i=this.resolveControlledInputValue(r,t);i.hasValue&&(j(r,"controlled"),this.applyControlledInputValue(r,i.value))}}bindControlledCheckedValues(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(!(r instanceof HTMLInputElement))continue;let i=this.resolveControlledCheckedValue(r,t);if(!i.hasValue)continue;M(r,"controlled");let l=!!i.value;r.checked!==l&&(r.checked=l)}}applyUncontrolledDefaultValue(e,t){if(e instanceof HTMLSelectElement)return void this.applyUncontrolledDefaultSelectValue(e,t);let n=null==t?"":String(t);j(e,"uncontrolled"),e.defaultValue!==n&&(e.defaultValue=n),e.value!==n&&(e.value=n),e.__ppHasUncontrolledDefaultValue=!0}applyUncontrolledDefaultChecked(e,t){let n=this.normalizeDefaultCheckedValue(t);M(e,"uncontrolled"),e.defaultChecked!==n&&(e.defaultChecked=n),e.checked!==n&&(e.checked=n),e.__ppHasUncontrolledDefaultChecked=!0}restoreUncontrolledSelectState(e){let t=Array.from(e.options);if(e.multiple)return void t.forEach(e=>{e.selected=e.defaultSelected});let n=t.find(e=>e.defaultSelected);n?e.value=n.value:t.length>0&&(e.selectedIndex=0)}isUncontrolledResetManagedElement(e){let t=e;return!(!t.__ppHasUncontrolledDefaultValue&&!t.__ppHasUncontrolledDefaultChecked)||e instanceof HTMLSelectElement&&Array.from(e.options).some(e=>e.defaultSelected)}syncUncontrolledFormResets(e,t,n){let r=new Set;for(let i=0;i<t.length;i++){let l=t[i];if(!(l.__ppHasUncontrolledDefaultValue||l.__ppHasUncontrolledDefaultChecked||l instanceof HTMLSelectElement))continue;let o=l.closest("form");o instanceof HTMLFormElement&&this.isUncontrolledResetManagedElement(l)&&(r.add(o),this.registerResetHandler(o,e,()=>{this.restoreUncontrolledFormDefaults(o,n())}))}for(let t of this.registeredResetForms)r.has(t)||this.unregisterResetHandler(t,e);this.registeredResetForms=r}clearResetHandlers(e){for(let t of this.registeredResetForms)this.unregisterResetHandler(t,e);this.registeredResetForms.clear()}restoreUncontrolledFormDefaults(e,t){for(let n=0;n<t.length;n++){let r=t[n],i=r;if(r.closest("form")===e){if(r instanceof HTMLSelectElement){this.restoreUncontrolledSelectState(r);continue}(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement)&&i.__ppHasUncontrolledDefaultValue&&(r.value=r.defaultValue),r instanceof HTMLInputElement&&i.__ppHasUncontrolledDefaultChecked&&(r.checked=r.defaultChecked)}}}resolveDefaultValueBinding(e,t){let n=e.getAttribute("data-pp-default-value");if(n){if(e.removeAttribute("data-pp-default-value"),e.__ppDefaultValueCaptureId=n,t.has(n))return t.get(n)}else if(e.__ppDefaultValueCaptureId){if(t.has(e.__ppDefaultValueCaptureId))return t.get(e.__ppDefaultValueCaptureId);delete e.__ppDefaultValueCaptureId}return"__ppResolvedDefaultValue"in e?e.__ppResolvedDefaultValue:e.hasAttribute("defaultvalue")?e.getAttribute("defaultvalue"):void 0}resolveDefaultCheckedBinding(e,t){let n=e.getAttribute("data-pp-default-checked");if(n){if(e.removeAttribute("data-pp-default-checked"),e.__ppDefaultCheckedCaptureId=n,t.has(n))return t.get(n)}else if(e.__ppDefaultCheckedCaptureId){if(t.has(e.__ppDefaultCheckedCaptureId))return t.get(e.__ppDefaultCheckedCaptureId);delete e.__ppDefaultCheckedCaptureId}return"__ppResolvedDefaultChecked"in e?e.__ppResolvedDefaultChecked:e.hasAttribute("defaultchecked")?e.getAttribute("defaultchecked"):void 0}materializeNestedBoundaryFormDefaults(e,t){let n=e,r=e.getAttribute("data-pp-input-value")??n.__ppInputValueCaptureId;if(r&&t.inputValueStore.has(r)){let i=t.inputValueStore.get(r);if(e.removeAttribute("data-pp-input-value"),n.__ppInputValueCaptureId=r,n.__ppResolvedInputValue=i,e instanceof HTMLInputElement)this.applyControlledInputValue(e,i);else if(e instanceof HTMLSelectElement)this.applyControlledSelectValue(e,i);else if(e instanceof HTMLTextAreaElement){let t=null==i?"":String(i);e.value!==t&&(e.value=t)}}let i=e.getAttribute("data-pp-default-value");if(i&&t.defaultValueStore.has(i)&&(e.removeAttribute("data-pp-default-value"),e.__ppResolvedDefaultValue=t.defaultValueStore.get(i)),!(e instanceof HTMLInputElement))return;let l=e,o=e.getAttribute("data-pp-checked-value")??l.__ppCheckedValueCaptureId;if(o&&t.checkedValueStore.has(o)){let n=t.checkedValueStore.get(o);e.removeAttribute("data-pp-checked-value"),l.__ppCheckedValueCaptureId=o;let r=!!n;e.checked!==r&&(e.checked=r)}let s=e.getAttribute("data-pp-default-checked");s&&t.defaultCheckedStore.has(s)&&(e.removeAttribute("data-pp-default-checked"),e.__ppResolvedDefaultChecked=t.defaultCheckedStore.get(s))}normalizeControlledSelectValues(e){return null==e?[]:Array.isArray(e)?e.filter(e=>null!=e).map(e=>String(e)):[String(e)]}applyUncontrolledDefaultSelectValue(e,t){j(e,"uncontrolled");let n=this.normalizeControlledSelectValues(t),r=e.multiple?new Set(n):new Set(n.length>0?[n[0]]:[]);for(let t=0;t<e.options.length;t++){let n=e.options[t],i=n,l=r.has(n.value);n.defaultSelected!==l&&(n.defaultSelected=l),n.selected!==l&&(n.selected=l),l?i.__ppHasUncontrolledDefaultSelected=!0:delete i.__ppHasUncontrolledDefaultSelected}if(!e.multiple){let t=n.length>0?n[0]:"";e.value!==t&&(e.value=t)}}resolveControlledSelectCaptureId(e,t){let n=e.getAttribute("data-pp-select-value"),r=null;return n?(e.removeAttribute("data-pp-select-value"),e.__ppSelectValueCaptureId=n,r=n):e.__ppSelectValueCaptureId&&t.has(e.__ppSelectValueCaptureId)?r=e.__ppSelectValueCaptureId:e.__ppSelectValueCaptureId&&delete e.__ppSelectValueCaptureId,r}resolveControlledInputValue(e,t){let n,r=e.getAttribute("data-pp-input-value"),i=!1;return r?(e.removeAttribute("data-pp-input-value"),e.__ppInputValueCaptureId=r,t.has(r)&&(n=t.get(r),i=!0)):e.__ppInputValueCaptureId&&t.has(e.__ppInputValueCaptureId)?(n=t.get(e.__ppInputValueCaptureId),i=!0):"__ppResolvedInputValue"in e?(n=e.__ppResolvedInputValue,i=!0):e.__ppInputValueCaptureId&&delete e.__ppInputValueCaptureId,{hasValue:i,value:n}}resolveControlledCheckedValue(e,t){let n,r=e.getAttribute("data-pp-checked-value"),i=!1;if(r)e.removeAttribute("data-pp-checked-value"),e.__ppCheckedValueCaptureId=r,t.has(r)&&(n=t.get(r),i=null!=n);else{let r=e.__ppCheckedValueCaptureId;r&&t.has(r)?(n=t.get(r),i=null!=n):r&&delete e.__ppCheckedValueCaptureId}return{hasValue:i,value:n}}registerResetHandler(e,t,n){let r=e;r.__ppResetCallbacks||=new Map,r.__ppResetCallbacks.set(t,n),!r.__ppOriginalReset&&(r.__ppOriginalReset=e.reset,e.reset=function(){r.__ppOriginalReset?.call(this),r.__ppResetCallbacks?.forEach((e,n)=>{x.getInstance(n)||n===t?e():r.__ppResetCallbacks?.delete(n)})})}unregisterResetHandler(e,t){let n=e;n.__ppResetCallbacks?.delete(t),!(n.__ppResetCallbacks&&n.__ppResetCallbacks.size>0)&&(n.__ppOriginalReset&&(e.reset=n.__ppOriginalReset,delete n.__ppOriginalReset),delete n.__ppResetCallbacks)}normalizeDefaultCheckedValue(e){if("string"==typeof e){let t=e.trim().toLowerCase();if(""===t||"true"===t)return!0;if("false"===t||"0"===t||"off"===t||"no"===t)return!1}return!!e}shouldDeferFocusedDateLikeInputValue(e,t){return!(document.activeElement!==e||!O(e))&&e.value!==t}shouldDeferActiveNativeTextInputValue(e,t){return!(document.activeElement!==e||!e.__ppPreserveNativeSelectionOnNextRender)&&(k(e)&&e.value!==t)}deferFocusedControlledInputValue(e,t){if(e.__ppDeferredControlledValue=t,e.__ppDeferredControlledBlurHandler)return;let n=()=>{let t=e.__ppDeferredControlledValue;if(delete e.__ppDeferredControlledValue,delete e.__ppDeferredControlledBlurHandler,!e.isConnected)return;let n=null==t?"":String(t);e.value!==n&&(e.value=n)};e.__ppDeferredControlledBlurHandler=n,e.addEventListener("blur",n,{once:!0})}},Ue=class{componentId;getParentId;isCurrentInstance;isRendering;forceUpdate;pendingProvidedContexts=new Map;pendingContextTokens=new Set;activeProviderBoundaryIds=new Set;refreshPending=!1;warnedContextOutsideRender=!1;constructor(e,t,n,r,i){this.componentId=e,this.getParentId=t,this.isCurrentInstance=n,this.isRendering=r,this.forceUpdate=i}prepareRender(){this.pendingProvidedContexts=new Map,this.pendingContextTokens=new Set}consume(e){return!this.isRendering()&&!this.warnedContextOutsideRender&&(this.warnedContextOutsideRender=!0,console.warn(`[PP-WARN] pp.context(...) should be called while component "${this.componentId}" is rendering. Move context reads to the component script body and pass values to event handlers through closure state.`)),this.pendingContextTokens.add(e),x.resolveContext(this.getParentId(),e).value}provide(e,t){this.pendingProvidedContexts.set(e,t)}commitRenderContexts(){let e=x.saveContextValues(this.componentId,this.pendingProvidedContexts);return x.updateContextDependencies(this.componentId,this.pendingContextTokens),e.length>0?x.getConsumersForContextsInSubtree(this.componentId,e):null}syncProviderBoundary(e,t,n,r){x.saveParent(e,t);let i=x.saveContextValues(e,new Map([[n,r]]));return i.length>0?x.getConsumersForContextsInSubtree(e,i):new Set}replaceActiveProviderBoundaries(e){let t=new Set;return this.activeProviderBoundaryIds.forEach(n=>{e.has(n)||x.removeContextTracking(n)?.forEach(e=>t.add(e))}),this.activeProviderBoundaryIds=e,t}requestRefresh(){this.refreshPending||(this.refreshPending=!0,queueMicrotask(()=>{if(this.refreshPending=!1,this.isCurrentInstance()){if(this.isRendering())return void this.requestRefresh();this.forceUpdate()}}))}refreshConsumers(e){for(let t of e)x.getInstance(t)?.requestContextRefresh?.()}destroy(){return this.activeProviderBoundaryIds.forEach(e=>{x.removeContextTracking(e)}),this.activeProviderBoundaryIds.clear(),x.removeContextTracking(this.componentId)}},We=class{getRoot;containsPortalElement;constructor(e,t){this.getRoot=e,this.containsPortalElement=t}save(e){let t=document.activeElement;if(!t)return null;let n=this.getRoot().contains(t),r=!n&&this.containsPortalElement(t);if(!n&&!r)return null;let i=e.indexOf(t);if(-1===i)return null;let l=this.getTextSelectionState(t);return{element:t,index:i,selectionStart:l.selectionStart,selectionEnd:l.selectionEnd}}restore(e,t){if(!e)return;let n=e.element,r=this.getRoot(),i=n&&n.isConnected&&(r.contains(n)||this.containsPortalElement(n))?n:t[e.index];if(!i)return;let l=i===document.activeElement,o=i;if(!(l&&i instanceof HTMLInputElement&&O(i))&&(l||i.focus(),null!==e.selectionStart&&null!==e.selectionEnd&&k(i))){if(l&&o.__ppPreserveNativeSelectionOnNextRender)return void delete o.__ppPreserveNativeSelectionOnNextRender;if(l&&i.selectionStart===e.selectionStart&&i.selectionEnd===e.selectionEnd)return;try{i.setSelectionRange(e.selectionStart,e.selectionEnd)}catch(e){console.warn("Could not restore cursor position",e)}}}getTextSelectionState(e){if(!k(e))return{selectionStart:null,selectionEnd:null};try{return{selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}catch{return{selectionStart:null,selectionEnd:null}}}},Ge="pp-keep",Ke="pp-keep-run",qe="pp-loop-build",Je=3,Ye=/^[A-Za-z0-9_.:-]+$/,Xe=/^\s*<([a-zA-Z][^\s/>]*)(?=[\s/>])[^>]*?\skey="([^"]*)"/,Ze=["pp-component","pp-owner","<pp-context-provider","\x3c!--pp:","__PP_COMPONENT_","__PP_SCRIPT_","__PP_STYLE_"],Qe=/<(?:input|textarea|select)\b|pp-ref/i,$e="\0pp-patched",et=0;function tt(e){let t=[],n=(e,r)=>{let i=0;for(let l=e.firstElementChild;l;l=l.nextElementSibling){let e=[...r,i];"script"!==l.tagName.toLowerCase()||l.hasAttribute("type")?n(l,e):t.push(e),i++}};return n(e,[]),t}function nt(e,t){let n=e;for(let e=0;e<t.length&&null!==n;e++){let r=n.firstElementChild;for(let n=t[e];n>0&&null!==r;n--)r=r.nextElementSibling;n=r}return n}var K=new Map,rt=!0;function it(e){rt=e,e||K.clear()}function at(e,t,n){let r=K.get(e);if(void 0===r||t.handedOver||!n||null===t.latestScope)return;let i=t.el;if(i.isConnected||null!==i.parentNode)return;let l=i.getAttribute("key");null===l||!r.index.has(l)||r.rows.has(l)||void 0!==i[a]&&r.rows.set(l,{record:t,state:n})}function ot(e,t){for(let n=0;n<Ze.length;n++)if((!t||"pp-component"!==Ze[n])&&e.includes(Ze[n]))return!1;return!0}function st(e){return e.includes("<")||e.includes("&")?e.replace(/&/g,"&amp;").replace(/</g,"&lt;"):e}function ct(e){return e.includes("&")?B(e):e}function q(e){return null!==e&&("object"==typeof e||"function"==typeof e||"symbol"==typeof e)}function lt(e){if(e.slots.length>30)return null;let t=Array(e.size).fill(0),n=0,r=[];return e.slots.forEach((e,i)=>{let l=1<<i;if("attr"!==e.kind){if("battr"===e.kind)return t[e.v]|=l,n|=l,void r.push(e.v);for(let n of e.parts)"number"==typeof n&&(t[n]|=l)}else t[e.v]|=l}),{key:e.key,slots:e.slots,size:e.size,slotBitsByValue:t,boundarySlotMask:n,boundaryValueIndices:r}}function ut(e){return"boolean"==typeof e||null==e?"":String(e)}function J(e,t,n,r,i=0){let l=t.slots.length;for(let o=0;o<l;o++){if(!(r&1<<o))continue;let l=t.slots[o],s=e,u=l.p;for(let e=0;e<u.length&&s;e++)s=s.children[u[e]]??null;if(!s)return!1;if("battr"===l.kind){let e=n[i+l.v],t=s[a];t&&(t[l.name]=e),"boolean"==typeof e?e?s.setAttribute(l.name,""):s.removeAttribute(l.name):null==e?s.removeAttribute(l.name):s.setAttribute(l.name,String(e));continue}if("attr"===l.kind){let e=n[i+l.v];l.bool?("boolean"==typeof e?e?s.setAttribute(l.name,""):s.removeAttribute(l.name):null!=e&&e?s.setAttribute(l.name,String(e)):s.removeAttribute(l.name),"checked"===l.name&&s instanceof HTMLInputElement&&N(s,!!e)):s.setAttribute(l.name,"boolean"==typeof e?String(e):null==e?"":String(e));continue}if("attrParts"===l.kind){let e=l.parts,t="";for(let r=0;r<e.length;r++){let l=e[r];t+="number"==typeof l?ut(n[i+l]):l}s.setAttribute(l.name,t);continue}let p,d=l.parts;if(1===d.length){let e=d[0];p="number"==typeof e?ut(n[i+e]):e}else{p="";for(let e=0;e<d.length;e++){let t=d[e];p+="number"==typeof t?ut(n[i+t]):t}}let c=s.firstChild;null!==c&&c.nodeType===Node.TEXT_NODE&&null===c.nextSibling&&""!==p?c.data=p:s.textContent=p}return!0}var dt=class{loops=new Map;enabled=!0;patchingEnabled=!0;valuePatchSink=null;directBuildingEnabled=!0;pendingDirectBuilds=null;directChildDerivations=null;directPrototypes=null;preparedDirectMarkers=null;pendingReviveRegistrations=null;directScriptsToReactivate=null;emitted=0;pendingPatchGroups=null;structuralBoundaryChange=!1;setValuePatchSink(e){this.valuePatchSink=e}disable(){this.enabled=!1,this.loops.clear(),this.pendingPatchGroups=null,this.dropParkedGenerations()}disablePatching(){this.patchingEnabled=!1,this.pendingPatchGroups=null}disableDirectBuilding(){this.directBuildingEnabled=!1,this.pendingDirectBuilds=null,this.preparedDirectMarkers=null,this.directScriptsToReactivate=null,this.directChildDerivations=null,this.directPrototypes=null,this.dropParkedGenerations(),this.loops.clear()}clear(){this.loops.clear(),this.pendingPatchGroups=null,this.directChildDerivations=null,this.directPrototypes=null,this.dropParkedGenerations()}dropParkedGenerations(){if(this.pendingReviveRegistrations=null,0!==K.size)for(let[e,t]of K)t.owner===this&&K.delete(e)}beginRender(){this.emitted=0,this.pendingPatchGroups=null,this.structuralBoundaryChange=!1,this.pendingDirectBuilds=null,this.preparedDirectMarkers=null,this.directScriptsToReactivate=null,this.pendingReviveRegistrations=null}prepareDirectBuilds(e){let t=this.pendingDirectBuilds;if(null===t||0===t.size)return!0;let n=new Map;for(let r of t.values()){let t=e.querySelectorAll(`[${qe}="${r.loopId}"]`);if(1!==t.length)return!1;let i=t[0],l=pt(i),o=i.parentElement;if(null===l||l.length!==r.keys.length||r.nodes.length!==r.keys.length||null===o||"http://www.w3.org/1999/xhtml"!==o.namespaceURI||i.tagName.toLowerCase()!==r.tag)return!1;for(let e=0;e<r.keys.length;e++){let t=r.nodes[e];if(l[e]!==r.keys[e]||null!==t.parentNode||t.tagName.toLowerCase()!==r.tag||t.getAttribute("key")!==r.keys[e])return!1}n.set(r.loopId,r.nodes)}return this.pendingDirectBuilds=null,this.preparedDirectMarkers=n,!0}hasPendingDirectBuilds(){return null!==this.pendingDirectBuilds&&this.pendingDirectBuilds.size>0}takeDirectBuild(e){let t=this.preparedDirectMarkers;if(null===t)return null;let n=e.getAttribute(qe);if(null===n)return null;let r=Number(n);if(!Number.isSafeInteger(r))return null;let i=t.get(r)??null;if(null!==i){t.delete(r);let e=this.pendingReviveRegistrations?.get(r);if(void 0!==e){this.pendingReviveRegistrations.delete(r);for(let t=0;t<e.length;t++){let{record:n,state:r}=e[t];x.registerInstance(n.id,n),x.saveParent(n.id,n.parentId),x.saveState(n.id,r),x.saveScope(n.id,n.latestScope)}}}return i}finishDirectBuilds(){let e=this.preparedDirectMarkers,t=null===e||0===e.size;this.preparedDirectMarkers=null;let n=this.directScriptsToReactivate;if(this.directScriptsToReactivate=null,n)for(let e=0;e<n.length;e++)n[e].removeAttribute("type");return t}takeStructuralBoundaryChange(){let e=this.structuralBoundaryChange;return this.structuralBoundaryChange=!1,e}getEmittedCount(){return this.emitted}takePendingPatches(){let e=this.pendingPatchGroups;return this.pendingPatchGroups=null,e}commitPatches(e){for(let t of e)for(let e of t.patches)e.entry.html=e.html}render(e,t,n,r,i,l=0){if(e<0){if(!n)return t.join("");let e="";for(let r=0;r<t.length;r++)e+=n(t[r],r);return e}if(0===t.length)return 1&l&&this.loops.has(e)&&(this.structuralBoundaryChange=!0,this.tryParkClosingLoop(e)),this.loops.delete(e),"";if(n){if(i&&r&&this.enabled&&this.directBuildingEnabled&&(!i.hasBoundary||1===i.rootBoundary&&1&l)&&!this.loops.has(e)){let n=this.tryDirectBuild(e,t,r,i,l);if(null!==n)return n}if(i&&r&&this.enabled&&this.patchingEnabled&&null!==this.valuePatchSink){let n=this.loops.get(e);if(n&&null!==n.values&&null!==n.valueKeys&&null!==n.keyRawValues&&n.entries.length===t.length&&!n.hasDuplicates&&n.allReusable){let l=this.tryValueLane(e,n,t,r,i);if(null!==l)return l}}let o=Array(t.length);for(let e=0;e<t.length;e++)o[e]=n(t[e],e);return this.renderRows(e,o,!0,i&&r?{items:t,valuesFn:r,plan:i}:null,l)}return this.renderRows(e,t,!1,null,0)}tryParkClosingLoop(e){if(!rt||!this.enabled||!this.directBuildingEnabled)return;let t=this.loops.get(e),n=this.directChildDerivations?.get(e),r=this.directPrototypes?.get(e);if(void 0===n||void 0===r||null===t.plan||null===t.values||null===t.valueKeys||null===t.keyRawValues||t.hasDuplicates)return;let i=t.valueKeys,l=new Map;for(let e=0;e<i.length;e++)l.set(i[e],e);K.set(n,{owner:this,prototypeHtml:r.html,contextTag:r.contextTag,index:l,values:t.values,size:t.plan.size,rows:new Map})}takeParkedGeneration(e){if(0===K.size)return null;let t=this.directChildDerivations?.get(e);if(void 0===t)return null;let n=K.get(t);return void 0===n?null:(K.delete(t),n.owner===this?n:null)}tryReviveRow(e,t,n,r,i,l){let o=e.rows.get(t);if(void 0===o)return null;e.rows.delete(t);let s=o.record,u=s.el,p=e.index.get(t),d=u[a];if(null===s.latestScope||void 0===p||void 0===d||u.isConnected||null!==u.parentNode||u.getAttribute("key")!==t||void 0!==x.getInstance(s.id)||void 0!==x.getState(s.id))return null;let c=0,h=p*e.size;for(let t=0;t<e.size;t++)Object.is(r[i+t],e.values[h+t])||(c|=l.slotBitsByValue[t]);return 0===c||J(u,l,r,c,i)?(Object.is(d.key,n)||(d.key=n),o):null}tryDirectBuild(e,t,n,r,i){let l=t.length;if(l<Je||!r.prototypeHtml)return null;let s,u,p=this.directPrototypes?.get(e);if(void 0!==p&&p.html===r.prototypeHtml&&p.contextTag===r.contextTag)s=p.prepared,u=p.prototype;else{let t=lt(r);if(null===t)return null;let n=null;for(let e=W(r.prototypeHtml,r.contextTag).root.firstChild;e;e=e.nextSibling)if(e.nodeType!==Node.ELEMENT_NODE){if(e.nodeType!==Node.TEXT_NODE||""!==e.data.trim())return null}else{if(null!==n)return null;n=e}if(null===n)return null;s=t,u=n,(this.directPrototypes??=new Map).set(e,{html:r.prototypeHtml,contextTag:r.contextTag,prototype:u,prepared:s,scriptPaths:1===r.rootBoundary?tt(n):[]})}let d=1===r.rootBoundary?this.directPrototypes.get(e).scriptPaths:null,c=0===s.slots.length?0:(1<<s.slots.length)-1,h=Array(l*s.size),f=Array(l),m=Array(l),_=Array(l),g=new Set,y=null;if(1===r.rootBoundary){let t=!0;for(let e=0;e<s.slots.length;e++)if(0!==s.slots[e].p.length){t=!1;break}if(t){let t=this.directChildDerivations??=new Map;y=t.get(e)??null,null===y&&(y={childHtml:null,hasScript:!1,mintKey:++et,propsSchema:null,blueprint:null,scriptPath:null,stringlessMounted:!1,flyweight:null},t.set(e,y))}}let E=null;if(1===r.rootBoundary){let t=this.takeParkedGeneration(e);null!==t&&0!==t.rows.size&&t.prototypeHtml===r.prototypeHtml&&t.contextTag===r.contextTag&&t.size===s.size&&(E=t)}let v=null;try{for(let e=0;e<l;e++){let i=e*s.size;if(n(t[e],e,h,i)!==h)return null;for(let e=0;e<s.size;e++)if(q(h[i+e]))return null;let l=h[i+s.key];if(q(l))return null;let p=null==l?"":String(l);if(!p||!Ye.test(p)||g.has(p))return null;g.add(p);let S=null;if(null!==E){let e=this.tryReviveRow(E,p,l,h,i,s);null!==e&&(S=e.record.el,(v??=[]).push(e))}if(null===S){if(S=u.cloneNode(!0),1===r.rootBoundary){let e=Object.create(null);e.key=l,S[a]=e,null!==y&&(S[o]=y)}if(!J(S,s,h,c,i))return null;if(S.setAttribute("key",p),null!==d)for(let e=0;e<d.length;e++){let t=nt(S,d[e]);if(null===t)return null;t.setAttribute("type","application/pp"),(this.directScriptsToReactivate??=[]).push(t)}}f[e]=p,m[e]=l,_[e]=S}}catch{return null}let S=u.tagName.toLowerCase(),b=Array(l),C=new Map;for(let e=0;e<l;e++){let t={html:$e,key:f[e],tag:S,reusable:!0,simpleKey:!0,patchSafe:!0};b[e]=t,C.set(f[e],t)}let T=`<${S} ${Ke}="${f.join(",")}" key="${f[0]}" ${qe}="${e}"></${S}>`;return this.loops.set(e,{entries:b,byKey:C,hasDuplicates:!1,allReusable:!0,keepEmission:T,values:h,valueKeys:f.slice(),keyRawValues:m,plan:s}),1===r.rootBoundary&&1&i&&(this.structuralBoundaryChange=!0),(this.pendingDirectBuilds??=new Map).set(e,{loopId:e,tag:S,keys:f,nodes:_}),null!==v&&(this.pendingReviveRegistrations??=new Map).set(e,v),T}tryValueLane(e,t,n,r,i){let l=t.plan??=lt(i);if(null===l)return null;let o,s=n.length,u=t.values,p=t.valueKeys,d=t.keyRawValues,c=l.size,h=Array(s*c),f=l.slotBitsByValue,m=l.boundaryValueIndices,_=l.boundarySlotMask,g=this.valuePatchSink;for(let y=0;y<s;y++){let s=y*c;if(r(n[y],y,h,s)!==h)return null;let E=h[s+l.key],v=!1;if(!Object.is(E,d[y])){if(q(E)||String(E)!==p[y])return null;v=1===i.rootBoundary,d[y]=E}let S=0;for(let e=0;e<m.length;e++)if(q(h[s+m[e]]))return null;for(let e=0;e<c;e++){let t=h[s+e];if(!Object.is(t,u[s+e])){if(q(t)||0!==(f[e]&_)&&"string"==typeof t&&(t.includes("{")||t.includes("}")))return null;S|=f[e]}}if(0!==S||v){let n=p[y];if(void 0===o&&(o=g.begin(e,n,0!==_||v)),null===o)return this.abandonValuePatching(g);let r=o.index.get(n);if(void 0===r||r.parentNode!==o.container||0!==S&&!J(r,l,h,S,s))return this.abandonValuePatching(g);let i=!1;if(v){let e=r[a];e&&(e.key=E,i=!0)}(0!==(S&_)||i)&&g.onBoundaryRowPatched(r),(0!==S||i)&&this.poisonEntryAt(t,y)}}return t.values=h,this.emitted+=s,t.keepEmission??=this.buildKeepEmission(t.entries)}abandonValuePatching(e){return e.reportPatchAbandoned(),this.disablePatching(),null}poisonEntryAt(e,t){let n=e.entries[t];if(n.html===$e)return;let r={...n,html:$e};e.entries[t]=r,null!==r.key&&e.byKey.set(r.key,r)}buildKeepEmission(e){let t=e.length,n="",r=0;for(;r<t;){let i=e[r],l=r;for(;l<t&&e[l].simpleKey;)l++;if(l-r>=Je){let t=e[r].key;for(let n=r+1;n<l;n++)t+=","+e[n].key;n+=`<${i.tag} ${Ke}="${t}" key="${st(i.key)}"></${i.tag}>`,r=l;continue}n+=`<${i.tag} ${Ge} key="${st(i.key)}"></${i.tag}>`,r++}return n}renderRows(e,t,n,r,i){let l,o,s=!!(1&i),a=this.loops.get(e),u=a?.entries,p=a?.byKey,d=t.length,c=Array(d),h=Array(d),f=void 0===u||u.length!==d,m=!0;for(let e=0;e<d;e++){let n=t[e],r=void 0===u?void 0:u[e];if(void 0!==r&&r.html===n){c[e]=r,h[e]=!0,r.reusable||(m=!1);continue}let i,l=Xe.exec(n),o=null!==l&&l[2].length>0?l[2]:null;if(null!==o&&void 0!==p){let e=p.get(o);void 0!==e&&e.html===n&&(i=e)}if(void 0===i){let t=null!==o&&ot(n,s);i={html:n,key:o,tag:null===l?"":l[1],reusable:t,simpleKey:null!==o&&Ye.test(o),patchSafe:t&&!Qe.test(n)},h[e]=!1}else h[e]=!0;i.reusable||(m=!1),c[e]=i,(void 0===r||r.key!==o)&&(f=!0)}if(s&&f&&void 0!==u&&(this.structuralBoundaryChange=!0),f||void 0===a){let e=new Set;l=!1;for(let t=0;t<d;t++){let n=c[t].key;if(null!==n){if(e.has(n)){l=!0;break}e.add(n)}}}else l=a.hasDuplicates;if(l)return this.loops.delete(e),t.join("");if(f||void 0===p){o=new Map;for(let e=0;e<d;e++){let t=c[e].key;null!==t&&o.set(t,c[e])}}else{o=p;for(let e=0;e<d;e++){let t=c[e];t!==u[e]&&null!==t.key&&o.set(t.key,t)}}let _={entries:c,byKey:o,hasDuplicates:l,allReusable:m,keepEmission:f||void 0===a?null:a.keepEmission,values:null,valueKeys:null,keyRawValues:null,plan:a?.plan??null};if(n&&this.enabled&&this.patchingEnabled&&void 0!==a&&!f&&m&&d>0){let n=null,i=!0;for(let e=0;e<d;e++)if(!h[e]){if(!c[e].patchSafe){i=!1;break}(n??=[]).push({key:ct(c[e].key),html:t[e],entry:c[e]})}if(i){if(null!==n){for(let e of n)e.entry.html=$e;(this.pendingPatchGroups??=[]).push({loopId:e,patches:n})}return this.seedValueLane(_,r),this.loops.set(e,_),this.emitted+=d,_.keepEmission??=this.buildKeepEmission(c)}}let g="",y=0;for(;y<d;){let e=c[y];if(!this.enabled||!h[y]||!e.reusable){g+=t[y],y++;continue}let n=y;for(;n<d&&h[n]&&c[n].reusable&&c[n].simpleKey;)n++;if(n-y>=Je){let t=c[y].key;for(let e=y+1;e<n;e++)t+=","+c[e].key;g+=`<${e.tag} ${Ke}="${t}" key="${st(e.key)}"></${e.tag}>`,this.emitted+=n-y,y=n;continue}this.emitted++,g+=`<${e.tag} ${Ge} key="${st(e.key)}"></${e.tag}>`,y++}return this.loops.set(e,_),g}seedValueLane(e,t){if(null===t||!e.allReusable)return;let n=e.plan??=lt(t.plan);if(null===n)return;let{items:r,valuesFn:i}=t,l=r.length,o=Array(l*n.size),s=Array(l),a=Array(l);for(let t=0;t<l;t++){let l=t*n.size;if(i(r[t],t,o,l)!==o)return;for(let e=0;e<n.boundaryValueIndices.length;e++)if(q(o[l+n.boundaryValueIndices[e]]))return;a[t]=o[l+n.key];let u=e.entries[t].key;if(null===u)return;s[t]=ct(u)}e.values=o,e.valueKeys=s,e.keyRawValues=a}};function ft(e){if(e.nodeType!==Node.ELEMENT_NODE)return!1;let t=e;return t.hasAttribute("pp-keep")||t.hasAttribute("pp-keep-run")}function pt(e){if(e.nodeType!==Node.ELEMENT_NODE)return null;let t=e.getAttribute(Ke);return null===t?null:t.split(",")}var mt=class{options;constructor(e){this.options=e}morphPatchedRow(e,t,n){return t.tagName===n.tagName?(this.morphCompatibleElement(e,t,n),t):(e.replaceChild(n,t),this.options.collectEventElements(n),n)}morphChildren(e,t){if(null===t.firstChild){if(null===e.firstChild)return;delete e.__ppLoopKeyIndex;let t=e.firstChild;for(;null!==t;){let n=t.nextSibling;e.removeChild(t),t=n}return}if(this.hasKeyedDirectChildren(e)||this.hasKeyedDirectChildren(t))return void this.morphKeyedChildren(e,t);let n=this.options.canSkipEqualSubtrees?.()??!1,r=e.firstChild,i=t.firstChild;for(;r||i;){let t=r?.nextSibling??null,l=i?.nextSibling??null;i?r?r.nodeType===i.nodeType?r.nodeType!==Node.TEXT_NODE?(r.nodeType===Node.ELEMENT_NODE&&(null!==r.firstElementChild&&r.isEqualNode(i)?n||this.options.collectEventElements(r):this.morphCompatibleElement(e,r,i)),r=t,i=l):(r.textContent!==i.textContent&&(r.textContent=i.textContent),r=t,i=l):(e.replaceChild(i,r),i.nodeType===Node.ELEMENT_NODE&&this.options.collectEventElements(i),r=t,i=l):(e.appendChild(i),i.nodeType===Node.ELEMENT_NODE&&this.options.collectEventElements(i),i=l):(r&&e.removeChild(r),r=t)}}morphCompatibleElement(e,t,n){if(t.tagName!==n.tagName)return e.replaceChild(n,t),void this.options.collectEventElements(n);if(c(t)&&t!==this.options.root){let r=n.hasAttribute(Me);return r&&n.removeAttribute(Me),null===t.firstChild&&null!==n.firstChild&&this.options.shouldForceChildRefresh?.()?(e.replaceChild(n,t),void this.options.collectEventElements(n)):!r&&null!==n.firstChild&&this.options.ownsBoundaryContent?.(t,n)?(t.replaceChildren(...Array.from(n.childNodes)),this.options.syncAttributes(t,n),void this.options.collectEventElements(t)):this.options.syncNestedBoundaryAttributes(t,n)?(r&&null!==t.firstChild&&this.options.onBoundaryKeepResolved?.(),void(this.options.hasEventAttributes(t)&&this.options.collectEventElements(t))):(e.replaceChild(n,t),void this.options.collectEventElements(n))}if(this.options.syncAttributes(t,n),this.options.hasEventAttributes(t)&&this.options.collectEventElements(t),t instanceof HTMLTextAreaElement)return;let r=t.firstChild,i=n.firstChild;r?.nodeType!==Node.TEXT_NODE||i?.nodeType!==Node.TEXT_NODE||null!==r.nextSibling||null!==i.nextSibling?this.morphChildren(t,n):r.nodeValue!==i.nodeValue&&(r.nodeValue=i.nodeValue)}hasKeyedDirectChildren(e){let t=e.firstElementChild;for(;t;){if(null!==this.getElementKey(t))return!0;t=t.nextElementSibling}return!1}getNodeKey(e){return e.nodeType===Node.ELEMENT_NODE?this.getElementKey(e):null}getElementKey(e){let t=e.getAttribute("key");return t&&t.length>0?t:null}readLeafText(e){if(e.nodeType===Node.TEXT_NODE||e.nodeType===Node.COMMENT_NODE)return e.nodeValue;let t=e.firstChild;return null===t?"":t.nodeType===Node.TEXT_NODE&&null===t.nextSibling?t.nodeValue:e.textContent}areKeyedNodesCompatible(e,t){return e.nodeType===t.nodeType&&(e.nodeType!==Node.ELEMENT_NODE||e.tagName===t.tagName)}areNodesCompatible(e,t){if(e.nodeType!==t.nodeType)return!1;if(e.nodeType!==Node.ELEMENT_NODE)return!0;let n=t;if(e.tagName!==n.tagName)return!1;let r=this.getNodeKey(e),i=this.getNodeKey(t);return null===r&&null===i||null!==r&&r===i}morphKeyedChildren(e,t){e.__ppLoopKeyIndex=void 0;let n=[],r=[];for(let t=e.firstChild;t;t=t.nextSibling)n.push(t),r.push(this.getNodeKey(t));let i=[],l=[],o=null,s=null;for(let e=t.firstChild;e;e=e.nextSibling){let t=this.getNodeKey(e);i.push(e),l.push(t),null!==t&&(null===o&&(o=new Set),o.has(t)?(s??=new Set).add(t):o.add(t))}let a=new Map,u=new Set,p=new Map;null!==s&&console.warn(`[PP-WARN] Duplicate key values detected: ${Array.from(s).join(", ")}`);let d=e=>{u.add(e);let t=this.getUnkeyedNodeSignature(e),n=p.get(t);n?n.push(e):p.set(t,[e])},c=e=>{let t=this.getUnkeyedNodeSignature(e),n=p.get(t);for(;n&&n.length>0;){let r=n.shift();if(u.delete(r),this.areNodesCompatible(r,e))return 0===n.length&&p.delete(t),r}p.delete(t)};for(let e=0;e<n.length;e++){let t=n[e],i=r[e];if(null===i){d(t);continue}let l=a.get(i);l?l.push(t):a.set(i,[t])}let h=e.firstChild,f=this.options.hasKeepPlaceholders?.()??!1;for(let t=0;t<i.length;t++){let n,r=i[t],o=l[t];if(r.nodeType===Node.ELEMENT_NODE){let t=this.options.takeDirectBuild?.(r);if(t){let n=document.createDocumentFragment();for(let e=0;e<t.length;e++)n.appendChild(t[e]);let r=t[t.length-1];e.insertBefore(n,h),h=r.nextSibling;continue}}if(f){let t=pt(r);if(null!==t){for(let n=0;n<t.length;n++){let r=a.get(t[n]),i=r&&r.length>0?r.shift():void 0;i&&!ft(i)?(i!==h&&e.insertBefore(i,h),h=i.nextSibling,this.options.onKeepResolved?.()):i&&d(i)}continue}}if(f&&null!==o&&ft(r)){let t=a.get(o),n=t&&t.length>0?t.shift():void 0;if(!n||ft(n)){n&&d(n);continue}n!==h&&e.insertBefore(n,h),h=n.nextSibling,this.options.onKeepResolved?.();continue}if(null!==o){let e=a.get(o);for(;e&&e.length>0;){let t=e.shift();if(this.areKeyedNodesCompatible(t,r)){n=t;break}d(t)}}else n=c(r);n?n!==h&&e.insertBefore(n,h):(e.insertBefore(r,h),r.nodeType===Node.ELEMENT_NODE&&this.options.collectEventElements(r),n=r);let s=n.nodeType!==Node.ELEMENT_NODE||!n.firstElementChild&&!this.options.hasEventAttributes(n),u=s&&this.readLeafText(n)===this.readLeafText(r);(!s||!u||!n.isEqualNode(r))&&this.morphNode(n,r),h=n.nextSibling}u.forEach(t=>{t.parentNode===e&&e.removeChild(t)}),a.forEach(t=>{t.forEach(t=>{t.parentNode===e&&e.removeChild(t)})})}getUnkeyedNodeSignature(e){return e.nodeType===Node.ELEMENT_NODE?`element:${e.tagName}`:`node:${e.nodeType}`}morphNode(e,t){if(e.nodeType!==t.nodeType){let n=e.parentNode;if(!n)return;return n.replaceChild(t,e),void(t.nodeType===Node.ELEMENT_NODE&&this.options.collectEventElements(t))}if(e.nodeType===Node.TEXT_NODE)return void(e.textContent!==t.textContent&&(e.textContent=t.textContent));if(e.nodeType!==Node.ELEMENT_NODE)return;let n=e,r=t,i=n.parentNode;i&&this.morphCompatibleElement(i,n,r)}},ht=class e{componentId;static ownedRenderCache=new WeakMap;static ownerScopeViews=new WeakMap;static MAX_OWNED_EXPANSION_DEPTH=32;static MAX_OWNED_PLACEHOLDER_LENGTH=220;static HOST_HELPER_NAMES=new Set(["__pp_input_value","__pp_select_value","__pp_checked_value","__pp_default_value","__pp_default_checked"]);ownerScopeRecords=[];constructor(e){this.componentId=e}haveOwnerScopeIdentitiesChanged(){for(let e of this.ownerScopeRecords)if((x.getResolvedScopeWithAncestors(e.ownerId,e.relativeTo)??null)!==e.scope)return!0;return!1}extractOwnedTemplates(e,t){let n=new Map,r=e.querySelectorAll("template[pp-owner]"),i=0;return r.forEach(r=>{if(t){let e=r.getAttribute("pp-owner");e&&t(e)}if((r.parentElement?d(r.parentElement):null)!==e)return;let l=r.getAttribute("pp-owner");if(!l)return;r.content.querySelectorAll("script:not([type])").forEach(e=>{e.parentElement?.closest("[pp-component]")||e.remove()});let o=`__PP_OWNED_${this.componentId}_${i++}__`;n.set(o,{ownerId:l,content:r.innerHTML,contextTag:r.parentElement?.tagName.toLowerCase()??null}),r.replaceWith(document.createComment(o))}),n}resolveOwnedChildren(e,t){return this.ownerScopeRecords.length=0,e.includes("__PP_OWNED_")?(t.forEach(e=>{let t=this.resolveOwnedTemplateOwner(e.ownerId);this.ownerScopeRecords.push({ownerId:e.ownerId,relativeTo:this.componentId,scope:t?t.scope:null})}),this.expandOwnedPlaceholders(e,t,0)):e}expandOwnedPlaceholders(t,n,r){if(!t.includes("__PP_OWNED_"))return t;if(r>=e.MAX_OWNED_EXPANSION_DEPTH)return console.warn(`[PP-WARN] Owned template expansion exceeded ${e.MAX_OWNED_EXPANSION_DEPTH} levels for component "${this.componentId}". A slot's content may reference its own placeholder.`),t;let i,l="",o=0,s=!1,a=0;for(;-1!==(i=t.indexOf("__PP_OWNED_",a));){let u=Math.min(t.length,i+e.MAX_OWNED_PLACEHOLDER_LENGTH),p=-1,d=null,c=null;for(let e=t.indexOf("__",i+11);-1!==e&&e+2<=u;e=t.indexOf("__",e+1)){let r=e+2,l=t.slice(i,r),o=/_(\d+)__$/.exec(l);if(!o||o.index<11)continue;let s=n.get(l);if(s){p=r,d=s,c=null;continue}let a=l.slice(11,o.index);if(!a)continue;let u=x.getOwnedTemplates(a)?.get(l);u&&(p=r,d=u,c=a)}if(null===d){a=i+11;continue}let h=null===c?this.resolveOwnedTemplateOwner(d.ownerId):this.resolveOwnedTemplateOwner(d.ownerId,c);null!==c&&this.ownerScopeRecords.push({ownerId:d.ownerId,relativeTo:c,scope:h?h.scope:null});let f=h?this.renderOwnedContent(d,h.ownerId,h.scope):d.content,m=i,_=p;m>=4&&t.startsWith("\x3c!--",m-4)&&t.startsWith("--\x3e",_)&&(m-=4,_+=3),l+=t.slice(o,m),l+=this.expandOwnedPlaceholders(f,n,r+1),o=_,a=_,s=!0}return s?l+t.slice(o):t}maskNestedOwnedTemplates(e,t){if(!e.includes("pp-owner"))return{content:e,placeholders:new Map};let n=new Map,r=W(e,t),i=0,l=r.root.querySelectorAll(`${s} > template[pp-owner]`);for(let e of Array.from(l)){let t=`__PP_NESTED_TPL_${i++}__`;n.set(t,e.outerHTML),e.replaceWith(document.createComment(t))}return{content:r.toHtml(),placeholders:n}}materializeTemplateComponentBoundaries(t){e.materializeTemplateComponentBoundaries(t)}static materializeTemplateComponentBoundaries(e){let t=[];e instanceof HTMLTemplateElement&&e.hasAttribute("pp-component")&&t.push(e),e.querySelectorAll(`template${s}`).forEach(e=>t.push(e)),t.forEach(e=>{let t=e.content.cloneNode(!0);Re(t);let n=t.firstElementChild;if(!n)return void e.replaceWith(document.createComment("pp-empty-template-component"));let r=e.getAttribute(i),l=n.getAttribute(i);if(null!==r&&null!==l&&l!==r){let n=document.createElement(m);return n.style.display="contents",Array.from(e.attributes).forEach(e=>{"pp-owner"!==e.name&&n.setAttribute(e.name,e.value)}),n.appendChild(t),void e.replaceWith(n)}Array.from(e.attributes).forEach(e=>{"pp-owner"!==e.name&&n.setAttribute(e.name,e.value)}),e.replaceWith(t)})}static restoreNestedTemplatePlaceholders(e,t){return 0!==t.size&&e.includes("__PP_NESTED_TPL_")?e.replace(/<!--(__PP_NESTED_TPL_\d+__)-->|(__PP_NESTED_TPL_\d+__)/g,(e,n,r)=>{let i=t.get(n??r);return void 0===i?e:i}):e}renderOwnedContent(t,n,r){let i=e.ownerScopeViews.get(r);if(!i){let t=ie(r).keys.filter(e=>"__pp_boundary_html"!==e&&"__pp_loop_rows"!==e);i={keys:t,keysSig:t.join(" ")},e.ownerScopeViews.set(r,i)}let l=x.getScope(this.componentId),o=i.keys,s=Array(o.length);for(let t=0;t<o.length;t++){let n=o[t],i=l&&e.HOST_HELPER_NAMES.has(n)?l[n]:void 0;s[t]="function"==typeof i?i:r[n]}let a=i.keysSig,u=e.ownedRenderCache.get(t);if(!u||u.keysSig!==a){let n=this.maskNestedOwnedTemplates(t.content,t.contextTag),r=xe(t.contextTag);u={keysSig:a,compiledFn:Ie.compile(r.wrap(n.content),o),nestedPlaceholders:n.placeholders,wrapper:r},e.ownedRenderCache.set(t,u)}let p=e.restoreNestedTemplatePlaceholders(u.wrapper.unwrap(u.compiledFn(...s)),u.nestedPlaceholders);if(u.markedIn===p&&u.markedOwnerId===n&&void 0!==u.markedOut)return u.markedOut;let d=this.markOwnedBindings(p,n,t.contextTag);return u.markedIn=p,u.markedOwnerId=n,u.markedOut=d,d}resolveOwnedTemplateOwner(e,t=this.componentId){let n=x.resolveComponentId(e,t);if(!n)return null;let r=x.getResolvedScopeWithAncestors(e,t);return r?{ownerId:n,scope:r}:null}markOwnedBindings(e,t,n=null){if(!e.includes("data-pp-ref")&&!/[\s/]on[a-zA-Z]+\s*=/.test(e))return e;let r=W(e,n),i=[...r.root instanceof DocumentFragment?Array.from(r.root.children):[r.root]].reverse();for(;i.length>0;){let e=i.pop();if(Array.from(e.attributes).some(t=>z(t.name,e))&&e.setAttribute("pp-event-owner",t),e.hasAttribute("data-pp-ref")&&e.setAttribute("pp-ref-owner",t),!c(e))for(let t=e.lastElementChild;t;t=t.previousElementSibling)i.push(t)}return r.toHtml()}},gt=class{componentId;getCachedFunction;interpolationCache=null;scopeEvalCache=null;propEvalCache=null;constructor(e,t){this.componentId=e,this.getCachedFunction=t}interpolateAttrString(e,t,n){let r=n??ae(t),i=r.keys,l=r.values,o=r.keySig;return ye(e,(e,t)=>{let n=B(e);if(!G.isValidExpression(n))return`{${t}}`;try{let e=this.getCachedFunction(this.interpolationCache??=new Map,n,i,o,300)(...l);return"boolean"==typeof e||null==e?"":Array.isArray(e)?e.join(""):String(e)}catch(e){return console.warn(`[PP-WARN] Failed attribute interpolation for {${n}}`,e),""}})}applyBoundaryBindings(e,t,n,r){for(let i in t){if(r?.(i))continue;let l=t[i],o=this.resolveBoundaryAttributeValue(i,l,n);null!==o?e.getAttribute(i)!==o&&e.setAttribute(i,o):e.hasAttribute(i)&&e.removeAttribute(i)}}resolveBoundaryAttributeValue(e,t,n){let r=U(t);if(!r)return this.interpolateAttrString(t,n.scope,n);let i,l=B(r.expression);if(!G.isValidExpression(l))return t;try{i=this.getCachedFunction(this.scopeEvalCache??=new Map,l,n.keys,n.keySig,300)(...n.values)}catch(e){return console.error(`[PP-ERROR] Failed to eval "${l}"`,e),t}let o=typeof i;if(R.has(e.toLowerCase())){if("boolean"===o)return i?"":null;if(!i&&("string"===o||"number"===o||"bigint"===o))return null}return null==i?null:"string"===o||"number"===o||"boolean"===o||"bigint"===o?String(i):t}computePropsFromAttributes(e,t,n){let r=n;if(!r&&t){let e=x.getResolvedScopeWithAncestors(t,this.componentId);e&&(r=ae(e))}let i=r?.scope,l=r?.keys??[],o=r?.values??[],s=e.__ppRawBindings,u=e.__ppLiteralAttrs,p=e[a],d=e.getAttributeNames();if(s)for(let e in s)d.includes(e)||d.push(e);if(p)for(let e in p)d.includes(e)||d.push(e);let c=r?.keySig??"",h={};for(let t=0;t<d.length;t++){let n=d[t];if(z(n,e)||"pp-component"===n||n.startsWith("pp-literal-"))continue;let r=ee(n);if(I.has(r))continue;if(p&&Object.prototype.hasOwnProperty.call(p,n)){h[r]=p[n];continue}let a=s?.[n],f=void 0===a?e.getAttribute(n)??void 0:a;if(void 0!==f){if(""===f){h[r]=!0;continue}if(i&&!u?.has(n)){let e=U(f);if(e){let t=B(e.expression);if(G.isValidExpression(t)){h[r]=this.evalPropExpression(t,l,c,o);continue}}if(f.includes("{")){h[r]=this.interpolateAttrString(f,i);continue}}h[r]=f}}return h}evalPropExpression(e,t,n,r){try{return this.getCachedFunction(this.propEvalCache??=new Map,e,t,n,200)(...r)}catch(t){return void console.warn(`[PP-WARN] Failed to evaluate prop expression "{${e}}" for component "${this.componentId}"`,t)}}};function _t(e){let t=e.getAttributeNames();for(let n=0;n<t.length;n++)if(z(t[n],e))return!0;return!1}var vt=class{getRoot;getPortalElements;refCaptureIdsByElement;refExprsByElement;cache=null;constructor(e,t,n,r){this.getRoot=e,this.getPortalElements=t,this.refCaptureIdsByElement=n,this.refExprsByElement=r}invalidate(){this.cache=null}getCache(){if(this.cache)return this.cache;let e=this.getRoot(),t=[],n=[],r=[],i=null,l=[],o=(e,t)=>{if(t)l.push(e);else for(let t=e.lastElementChild;t;t=t.previousElementSibling)l.push(t)};o(e,!0);for(let e of this.getPortalElements())i??=new Set,o(e,!0);for(;l.length>0;){let o=l.pop();if(i){if(i.has(o))continue;i.add(o)}let s=o,a=o!==e&&c(o);if((o.hasAttribute("data-pp-ref")||o.hasAttribute("pp-ref")||this.refCaptureIdsByElement.has(s)||this.refExprsByElement.has(s))&&r.push(s),!a&&(o instanceof HTMLInputElement||o instanceof HTMLTextAreaElement||o instanceof HTMLSelectElement)&&n.push(s),a)t.push(s);else for(let e=o.lastElementChild;e;e=e.previousElementSibling)l.push(e)}return this.cache={childBoundaries:t,managedInputs:n,refElements:r},this.cache}collectManagedInputs(){return this.getCache().managedInputs}collectEventElements(e,t){let n=this.getRoot();if(_t(e)&&t.add(e),e===n||!c(e))for(let n=e.firstElementChild;n;n=n.nextElementSibling)this.collectEventElements(n,t)}isManagedEventElement(e){if(this.isElementOwnedByTree(e,this.getRoot()))return!0;for(let t of this.getPortalElements())if(this.isElementOwnedByTree(e,t))return!0;return!1}isElementOwnedByTree(e,t){if(e===t)return!0;if(!t.contains(e))return!1;let n=e,r=!0;for(;n&&n!==t;){if(!r&&c(n))return!1;n=n.parentElement,r=!1}return n===t}};function yt(e){for(let t in e)return!0;return!1}var bt=Object.freeze({});function xt(e,t){let n=0;for(let r in e)if(n++,e[r]!==t[r])return!1;let r=0;for(let e in t)if(r++,r>n)return!1;return n===r}var St=class{options;boundaryOccurrencesByBaseId=new Map;parentScopesByBoundaryId=new Map;materializeFormsThisPass=!0;constructor(e){this.options=e}bootstrap(){this.boundaryOccurrencesByBaseId.clear(),this.parentScopesByBoundaryId.clear(),this.materializeFormsThisPass=this.options.hasFormDefaultState();let e=new Set,t=new Set,n=new Set,r=(i,l)=>{for(let o=i.firstElementChild;o;o=o.nextElementSibling){let i=o;if(c(i)){let t=this.bootstrapComponentBoundary(i,l);t&&e.add(t);continue}r(i,this.syncContextProviderBoundary(i,l,t,n)??l)}};r(this.options.getRoot(),this.options.componentId);for(let e of this.options.getPortalElements())r(e,this.options.componentId);this.options.getContextManager().replaceActiveProviderBoundaries(t).forEach(e=>n.add(e)),n.size>0&&this.options.refreshContextConsumers(n),this.destroyDisconnectedDescendants(e)}refreshPatchedBoundaries(e){this.boundaryOccurrencesByBaseId.clear(),this.parentScopesByBoundaryId.clear(),this.materializeFormsThisPass=this.options.hasFormDefaultState();for(let t of e)c(t)?this.bootstrapComponentBoundary(t,this.options.componentId):this.traversePatchedRow(t)}traversePatchedRow(e){for(let t=e.firstElementChild;t;t=t.nextElementSibling)c(t)?this.bootstrapComponentBoundary(t,this.options.componentId):this.traversePatchedRow(t)}syncNestedBoundaryAttributes(e,t){let n=l(t),r=this.getBoundaryBaseId(e);if(!n||r&&n!==r)return!1;let i=e,o=t[a];o?i[a]=o:delete i[a];let s=this.collectRawBindings(t),p=s.bindings;i.__ppLiteralAttrs=s.literalAttrs;let d=i.__ppRawBindings,c=void 0!==d&&xt(d,p);return this.options.syncAttributes(e,t,!1,!0,c?p:void 0),i.__ppRawBindings=c?d:p,i.__ppRuntimeComponentId&&l(e)!==i.__ppRuntimeComponentId&&u(e,i.__ppRuntimeComponentId),this.refreshNestedOwnedChildren(e,t),!0}refreshNestedOwnedChildren(e,t){let n=e.__ppRuntimeComponentId??l(e);n&&x.getInstance(n)?.refreshOwnedChildrenFromElement?.(t)}getBoundaryScopeSignature(e,t){let n=[],r=e;for(;r;){let e=r.getAttribute("key");e&&e.length>0?n.unshift(`k:${e}`):n.unshift(`i:${this.getElementIndexWithinParent(r)}`);let t=r.parentElement;if(!t||c(t))break;r=t}return`${t}|${n.join("/")}`}getElementIndexWithinParent(e){let t=e.parentElement;if(!t)return 0;let n=t.children;for(let t=0;t<n.length;t++)if(n[t]===e)return t;return 0}hashScope(e){let t=5381;for(let n=0;n<e.length;n++)t=33*t^e.charCodeAt(n);return(t>>>0).toString(36)}getBoundaryBaseId(e){let t=e,n=l(e);return!t.__ppBaseComponentId&&n&&(t.__ppBaseComponentId=n),t.__ppBaseComponentId??n}ensureBoundaryIdentity(e,t){let n=e,r=l(e)||"",i=0;if(r&&(i=(this.boundaryOccurrencesByBaseId.get(r)??0)+1,this.boundaryOccurrencesByBaseId.set(r,i)),n.__ppRuntimeComponentId)return r!==n.__ppRuntimeComponentId&&u(e,n.__ppRuntimeComponentId),n.__ppBaseComponentId||=r||n.__ppRuntimeComponentId,n.__ppRuntimeComponentId;if(!r)return"";r.includes("{")&&!n.__ppWarnedDynamicComponentId&&(n.__ppWarnedDynamicComponentId=!0,console.warn(`[PP-WARN] Dynamic pp-component values are not supported. Component boundary ids are static; received "${r}". Use a stable pp-component id and pass dynamic values through props instead.`)),n.__ppBaseComponentId=r;let s,a=e[o],p=void 0===a?null:e.getAttribute("key");s=void 0!==a&&p?`${r}__ppd${a.mintKey.toString(36)}x${p}`:1===i?r:`${r}__pp${this.hashScope(this.getBoundaryScopeSignature(e,t))}`;let d=x.getInstance(s);if(d&&d.el&&d.el!==e){if(d.el.isConnected){let t=this.createUniqueCollisionId(s,i,e);return n.__ppRuntimeComponentId=t,u(e,t),t}d.destroy?.()}return void 0===d&&void 0===x.getState(s)&&(n.__ppFreshIdentity=!0),n.__ppRuntimeComponentId=s,r!==s&&u(e,s),s}createUniqueCollisionId(e,t,n){let r=Math.max(t,1);for(;;){let t=1===r?`${e}_1`:`${e}_${r.toString(36)}`,i=x.getInstance(t);if(!i||!i.el||i.el===n)return t;if(!i.el.isConnected)return i.destroy?.(),t;r+=1}}bootstrapComponentBoundary(e,t){let n=e,r=this.ensureBoundaryIdentity(e,t);if(!r)return null;if(!n.__ppRawBindings){let t=e[o];if(void 0!==t&&null!==t.propsSchema)n.__ppRawBindings=bt;else{let t=this.collectRawBindings(e);n.__ppRawBindings=t.bindings,n.__ppLiteralAttrs=t.literalAttrs}}let i=n.__ppRawBindings,l=yt(i),s=!0===n.__ppFreshIdentity,a=s?void 0:x.getInstance(r),u=l||!a?this.getParentScopeBundle(t):void 0;if(l){let t=this.options.isEffectManagedSurfaceElement(e);this.options.applyBoundaryBindings(e,i,u,t?e=>this.options.shouldSkipEffectManagedAttr(e):void 0)}if(this.materializeFormsThisPass&&this.options.materializeFormDefaults(e),a?.refreshPropsFromParent){let i=a.parentId!==t;if(a.parentId=t,x.saveParent(r,t),a.el!==e){let t=a.el;!n.__ppRawBindings&&t.__ppRawBindings&&(n.__ppRawBindings=t.__ppRawBindings),a.el=e}return a.refreshPropsFromParent(i||(this.options.shouldForceChildRefresh?.()??!1),this.getBoundaryBaseId(e)===t?void 0:u,!l),r}if(s||!x.getState(r)){n.__ppRuntimeParentId=t;try{this.options.createComponent(e,u)}finally{delete n.__ppRuntimeParentId,s&&delete n.__ppFreshIdentity}}else s&&delete n.__ppFreshIdentity;return r}getParentScopeBundle(e){let t=this.parentScopesByBoundaryId.get(e);if(t)return t;let n=ae(x.getResolvedScopeWithAncestors(e,this.options.componentId)??this.options.getLatestScope());return this.parentScopesByBoundaryId.set(e,n),n}collectRawBindings(e){let t,n,r={},i=e[a],l=e.getAttributeNames();for(let o=0;o<l.length;o++){let s=l[o];if("pp-component"===s)continue;if(112===s.charCodeAt(0)&&s.startsWith("pp-literal-")){(t??=new Set).add(s.slice(L.length)),(n??=[]).push(s);continue}if(i&&Object.prototype.hasOwnProperty.call(i,s))continue;let a=e.getAttribute(s);null!==a&&a.includes("{")&&!z(s,e)&&(r[s]=a)}if(t){for(let e of t)delete r[e];for(let t of n)e.removeAttribute(t)}return{bindings:r,literalAttrs:t}}destroyDisconnectedDescendants(e){if(x.hasChildren(this.options.componentId)){x.beginTopologyBatch();try{x.forEachDescendant(this.options.componentId,t=>{if(e.has(t))return;let n=x.getInstance(t);!n?.el||n.el.isConnected||n.destroy?.()})}finally{x.endTopologyBatch()}}}syncContextProviderBoundary(e,t,n,r){if("pp-context-provider"!==e.tagName.toLowerCase())return null;let i=this.resolveContextProviderBoundary(e);return i?(n.add(i.boundaryId),this.options.getContextManager().syncProviderBoundary(i.boundaryId,t,i.context,i.value).forEach(e=>r.add(e)),i.boundaryId):null}resolveContextProviderBoundary(e){let t=e,n=e.getAttribute("data-pp-context-token")??t.__ppContextTokenCaptureId??null,r=e.getAttribute("data-pp-context-value")??t.__ppContextValueCaptureId??null;if(!n||!r)return null;t.__ppContextTokenCaptureId=n,t.__ppContextValueCaptureId=r,e.removeAttribute("data-pp-context-token"),e.removeAttribute("data-pp-context-value");let i=this.options.getContextTokenStore().get(n);return i?{boundaryId:this.ensureContextProviderBoundaryId(t),context:i,value:this.options.getContextValueStore().get(r)}:null}ensureContextProviderBoundaryId(e){return e.__ppContextBoundaryId||=`ppctx_${this.options.componentId}_${Math.random().toString(36).slice(2,10)}`,e.__ppContextBoundaryId}},Ct=new Set(["data-state","data-open","style","aria-hidden","aria-checked","hidden","inert"]),wt=new Set(["alert-dialog-content","alert-dialog-overlay","alert-dialog-portal","checkbox","dialog-content","dialog-overlay","dialog-portal","popover-content","sheet-content","sheet-overlay","sheet-portal","tooltip-content"]),Tt=class{refCaptureIdsByElement;refExprsByElement;constructor(e,t){this.refCaptureIdsByElement=e,this.refExprsByElement=t}isEffectManagedAttr(e){return Ct.has(e)}isEffectManagedSurfaceElement(e,t){let n=e.getAttribute("data-slot");if(n&&wt.has(n))return!0;let r=t?.getAttribute("data-slot");return!!r&&wt.has(r)}syncAttributes(e,t,n=!1,r=!1,i){let l=e.__ppBoundEventBindings;if(!(0!==e.attributes.length||0!==t.attributes.length||l&&0!==l.size||e instanceof HTMLTextAreaElement))return;let o=n||this.isEffectManagedSurfaceElement(e,t),s=e,a=e.getAttributeNames();for(let n=a.length-1;n>=0;n--){let l=a[n];if(!(r&&"pp-component"===l||void 0!==i&&l in i||t.hasAttribute(l))){if(o&&Ct.has(l)||"value"===l&&e instanceof HTMLInputElement&&s.__ppHasUncontrolledDefaultValue||"checked"===l&&e instanceof HTMLInputElement&&s.__ppHasUncontrolledDefaultChecked||"selected"===l&&e instanceof HTMLOptionElement&&s.__ppHasUncontrolledDefaultSelected)continue;e.removeAttribute(l),"checked"===l&&e instanceof HTMLInputElement&&e.checked&&(e.checked=!1),"data-pp-ref"===l&&this.refCaptureIdsByElement.delete(e),"pp-ref"===l&&this.refExprsByElement.delete(e)}}Ce.unbindRemovedEventHandlers(e,t);let u=t.getAttributeNames(),p=t.getAttribute("pp-event-owner");for(let n=0;n<u.length;n++){let l=u[n];if(o&&Ct.has(l)||r&&"pp-component"===l||void 0!==i&&l in i)continue;let s=t.getAttribute(l)??"";Ce.hasSameDirectBoundHandler(e,l,s,p)||(e.getAttribute(l)!==s&&e.setAttribute(l,s),"checked"===l&&e instanceof HTMLInputElement&&N(e,!0),"value"===l&&(e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&e.value!=s&&(e.value=s))}if(e.hasAttribute("pp-event-owner")&&!e.getAttributeNames().some(t=>z(t,e))&&e.removeAttribute("pp-event-owner"),e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement&&!s.__ppHasUncontrolledDefaultValue){let n=t.getAttribute("value"),r=n??t.value,i=n??t.defaultValue;e.defaultValue!==i&&(s.__ppTextareaValueFollowsTemplate=!0),s.__ppTextareaValueFollowsTemplate&&(e.value!==r&&(e.value=r),e.defaultValue!==i&&(e.defaultValue=i))}}},Et=Symbol.for("pp.context"),Dt=null;function Ot(e){if(!e||"object"!=typeof e||!("value"in e))throw Error("Context.Provider expects an object like { value, children? }.");return e}function kt(e){let t=Dt;return Dt=e,t}function At(e){let t={$$typeof:Et,defaultValue:e,Provider:e=>{let n=Ot(e),r=Dt;if(!r)throw Error("Context.Provider() can only be used while a component is rendering.");return r(t,n.value),n.children??null}};return t}var jt=["script","compile","template","domDiff","bindEvents","bindRefs","bootstrapNested","portals","restoreFocus","layoutEffects","effects","ctor","ctorSerialize","ctorProps","ctorPipeline","destroy","total"];function Mt(){return typeof performance<"u"&&"function"==typeof performance.now?performance.now():Date.now()}var Nt=new Map,Pt=0,Y=new Map,Ft=new Set,It=new Map,Lt=e=>Nt.get(e),X=[],Rt=[],zt=" pp-stringless-mount",Bt=Object.freeze({managedInputTags:!1,refMarkers:!1,contextProviders:!1,nestedBoundaries:!1,ownerMarkers:!1});function Vt(e){if(e.includes("\\u")||/\barguments\b/.test(e)||/\beval\b/.test(e)||/\bthis\b/.test(e))return!1;let t=e.replace(/\bpp\s*\.\s*props\b/g,"");return!/\bpp\b/.test(t)}var Ht=new Map,Ut=400,Wt=1,Gt=2,Kt=4,qt=7,Jt=/<(?:input|textarea|select)\b|defaultvalue|defaultchecked|data-pp-(?:input|select|checked|default)/i,Yt=/\.provider|pp-context/i;function Xt(e,t){if(t||e.includes("pp-owner"))return qt;let n=0;return e.includes("pp-ref")&&(n|=Wt),Jt.test(e)&&(n|=Gt),Yt.test(e)&&(n|=Kt),n}function Zt(e){let{rootTag:t,slots:n,size:r}=e.descriptor,i=Array(r).fill(0),l=0;return n.forEach((e,t)=>{let n=1<<t;if(l|=n,"attr"!==e.kind&&"battr"!==e.kind)for(let t of e.parts)"number"==typeof t&&(i[t]|=n);else i[e.v]|=n}),{rootTag:t,size:r,fullMask:l,slotBitsByValue:i,exprs:e.exprs,applyPlan:{key:0,slots:n,size:r,slotBitsByValue:i,boundarySlotMask:0,boundaryValueIndices:[]}}}var Z=class e{static MAX_SYNC_RERENDERS=25;static MAX_RENDER_FUNCTION_CACHE_SIZE=500;static renderFunctionCache=new Map;el;boundary;id;rawTemplate="";renderFunction;renderPipelineInitialized=!1;templateFn=null;pipelineBlueprint=null;hooksSystem=null;_eventManager=null;latestScope;__ppRefStore=Y;__ppRefSeq=0;__ppRefCaptureIdsByElement=new WeakMap;__ppRefExprsByElement=new WeakMap;_refBindingManager=null;__ppInputValueStore=Y;__ppInputValueSeq=0;__ppSelectValueStore=Y;__ppSelectValueSeq=0;__ppCheckedValueStore=Y;__ppCheckedValueSeq=0;__ppContextTokenStore=Y;__ppContextTokenSeq=0;__ppContextValueStore=Y;__ppContextValueSeq=0;__ppDefaultValueStore=Y;__ppDefaultValueSeq=0;__ppDefaultCheckedStore=Y;__ppDefaultCheckedSeq=0;__ppLoopValueIds=Ft;__ppLoopOwnerKey=0;__ppLoopValueSeq=0;_formControlManager=null;passiveEffectsVersion=0;isRendering=!1;props;ownedChildren=It;lastRenderedHtml="";renderCount=0;freshStateId=!1;_portalManager=null;parentId=null;initialChildrenHtml="";subtreeHadOwnedTemplate=!1;pendingEventElements=null;_traversalManager=null;_contextManager=null;_focusManager=null;_domMorpher=null;_ownedTemplateManager=null;_propBindingManager=null;_nestedBoundaryManager=null;_attributeSyncManager=null;_lastRawScopeKeySig="";_lastSortedKeys=[];_lastHtmlProbes;_lastSortedScopeKeySig="";_cachedHooksAPI=null;_cachedRuntimeAPI=null;_provisionDispatcher=null;_refEvalFnCache=null;hadNestedRuntimeStructures=!1;loopRowCache=null;loopKeepResolved=0;usesLoops=!1;captureNeeds=qt;propsOnlyRuntime=!1;bodyPlan=null;bodyPlanValues=null;bodyPlanValuesFn=null;bodyPlanDisabled=!1;liveOwnScriptEl=null;boundaryContentCache=null;boundaryKeepResolved=0;forceChildBoundaryRefresh=!1;morphingFromCommittedRender=!1;__ppLoopRowsFn=null;_loopContainers=null;_patchedBoundaryRows=null;__ppBoundaryHtmlFn=null;static perfEnabled=!1;static perfStats=new Map;constructor(t,n){let r=e.perfEnabled?Mt():0;this.el=t,this.boundary=new b(t),this.id=this.boundary.getId()||"",this.id||(this.id="anon_"+Math.random().toString(36).substring(2,9),this.boundary.setId(this.id)),x.registerInstance(this.id,this),this.syncParentId();let i=t[o];void 0!==i&&delete t[o];let l=void 0===i?null:i.childHtml,s=!0===t.__ppFreshIdentity;s&&(delete t.__ppFreshIdentity,this.freshStateId=!0);let a=this.startPerfTimer(),u=null;null!==l&&null!==i.propsSchema&&(u=en(i.propsSchema,t)),this.props=u??this.computePropsFromAttributes(n),this.endPerfTimer("ctorProps",a);let p=this.startPerfTimer(),d=null===l?this.boundary.readContent():l;this.endPerfTimer("ctorSerialize",p);let c=!1;null===l&&d.includes("pp-owner")&&(this.ownedChildren=this.ownedTemplateManager.extractOwnedTemplates(this.el,e=>{(e===this.id||x.resolveComponentId(e,this.id)===this.id)&&(c=!0),this.subtreeHadOwnedTemplate=!0}),this.ownedChildren.size>0&&(d=this.boundary.readContent())),s||x.removeOwnedTemplates(this.id),this.ownedChildren.size>0&&x.saveOwnedTemplates(this.id,this.ownedChildren),this.initialChildrenHtml=d,this.props.children=this.initialChildrenHtml,void 0!==i&&null===l&&0===this.ownedChildren.size&&!this.subtreeHadOwnedTemplate&&(i.childHtml=d,i.hasScript=d.includes("<script"),i.propsSchema=this.recordDirectPropsSchema());let h=null;if((null===l?d.includes("<script"):i.hasScript)&&(null!==l&&(h=tn(this.el,i.scriptPath)),h??=this.findOwnScript(this.el)),this.liveOwnScriptEl=h,null===l&&this.canReuseStaticInitialMarkup(h,c))this.reuseStaticInitialMarkup(d);else{let e=this.startPerfTimer();this.initializeRenderPipeline(h,null===l?null:i.blueprint),this.endPerfTimer("ctorPipeline",e),void 0!==i&&null!==i.childHtml&&(null===i.blueprint&&null!==this.pipelineBlueprint&&(i.blueprint=this.pipelineBlueprint),null===i.scriptPath&&null!==h&&(i.scriptPath=this.deriveScriptPath(h))),this.render(),void 0!==i&&null===l&&null!==i.childHtml&&(i.stringlessMounted=this.lastRenderedHtml===zt)}e.perfEnabled&&this.recordPerfPhase("ctor",Mt()-r)}ensureHooksSystem(){let e=this.hooksSystem;if(null!==e)return e;e=new r(()=>{this.isRendering||this.render()},this.id),e.setUncaughtErrorHandler(e=>this.deliverErrorToBoundary(e));let t=this.freshStateId?void 0:x.getState(this.id);return t&&e.loadState(t),this.hooksSystem=e,e}get eventManager(){return this._eventManager??=new Ce(this.el,()=>this.latestScope,e=>this.traversalManager.isManagedEventElement(e))}get refBindingManager(){return this._refBindingManager??=new Be(this.id)}get formControlManager(){return this._formControlManager??=new He}get portalManager(){return this._portalManager??=new Ve(this.id)}get attributeSyncManager(){return this._attributeSyncManager??=new Tt(this.__ppRefCaptureIdsByElement,this.__ppRefExprsByElement)}get traversalManager(){return this._traversalManager??=new vt(()=>this.el,()=>this.portalManager.elements(),this.__ppRefCaptureIdsByElement,this.__ppRefExprsByElement)}get contextManager(){return this._contextManager??=new Ue(this.id,()=>this.parentId,()=>x.getInstance(this.id)===this,()=>this.isRendering,()=>this.forceUpdate())}get ownedTemplateManager(){return this._ownedTemplateManager??=new ht(this.id)}get propBindingManager(){return this._propBindingManager??=new gt(this.id,(e,t,n,r,i)=>this.getCachedFunction(e,t,n,r,i))}get nestedBoundaryManager(){return this._nestedBoundaryManager??=new St({componentId:this.id,getRoot:()=>this.el,getPortalElements:()=>this.portalManager.elements(),getLatestScope:()=>this.latestScope,getContextTokenStore:()=>this.__ppContextTokenStore,getContextValueStore:()=>this.__ppContextValueStore,getContextManager:()=>this.contextManager,isEffectManagedSurfaceElement:e=>this.isEffectManagedSurfaceElement(e),shouldSkipEffectManagedAttr:e=>this.attributeSyncManager.isEffectManagedAttr(e),syncAttributes:(e,t,n,r,i)=>this.syncAttributes(e,t,n,r,i),applyBoundaryBindings:(e,t,n,r)=>this.applyBoundaryBindings(e,t,n,r),materializeFormDefaults:e=>this.materializeNestedBoundaryFormDefaults(e),hasFormDefaultState:()=>null!==this._formControlManager||this.__ppInputValueStore.size>0||this.__ppCheckedValueStore.size>0||this.__ppDefaultValueStore.size>0||this.__ppDefaultCheckedStore.size>0,createComponent:(e,t)=>un(e,t),refreshContextConsumers:e=>this.refreshContextConsumers(e),shouldForceChildRefresh:()=>this.forceChildBoundaryRefresh})}get focusManager(){return this._focusManager??=new We(()=>this.el,e=>this.portalManager.contains(e))}get domMorpher(){return this._domMorpher??=new mt({root:this.el,collectEventElements:e=>this.collectEventElements(e),hasEventAttributes:e=>this.hasEventAttributes(e),syncAttributes:(e,t)=>this.syncAttributes(e,t),syncNestedBoundaryAttributes:(e,t)=>this.nestedBoundaryManager.syncNestedBoundaryAttributes(e,t),onKeepResolved:()=>{this.loopKeepResolved++},onBoundaryKeepResolved:()=>{this.boundaryKeepResolved++},hasKeepPlaceholders:()=>(this.loopRowCache?.getEmittedCount()??0)>0,takeDirectBuild:e=>this.loopRowCache?.takeDirectBuild(e)??null,shouldForceChildRefresh:()=>this.forceChildBoundaryRefresh,canSkipEqualSubtrees:()=>this.morphingFromCommittedRender,ownsBoundaryContent:(e,t)=>this.ownsBoundaryContent(e,t)})}initializeRenderPipeline(e=null,t=null){if(this.renderPipelineInitialized)return;let n=0!==this.ownedChildren.size||this.subtreeHadOwnedTemplate?null:this.initialChildrenHtml;if(null!==n){let e=t??Ht.get(n);if(e)return this.rawTemplate=e.rawTemplate,this.renderFunction=e.renderFunction,this.pipelineBlueprint=e,this.captureNeeds=e.captureNeeds,this.propsOnlyRuntime=e.propsOnlyRuntime,this.bodyPlan=e.bodyPlan,this.installLoopMachinery(e.usesLoops,e.hasBoundaryCall),void(this.renderPipelineInitialized=!0)}let r="",i=!1;if(/<script\b|<textarea\b/i.test(this.initialChildrenHtml)){let t=this.spliceOwnScriptFromInitialHtml(e);if(t)r=t.scriptContent,i=!0,this.rawTemplate=t.template;else{let e=W(this.initialChildrenHtml,this.el.tagName.toLowerCase()),t=this.findOwnScript(e.root)??this.findOwnedSlotScript(e.root);r=t?ze(t):"",i=null!==t,t&&t.remove(),this.rawTemplate=e.toHtml()}}else this.rawTemplate=this.initialChildrenHtml;!i&&this.parentCompiledOurContent()&&(this.rawTemplate=this.neutralizeScriptlessTemplate(this.rawTemplate)),this.installLoopMachinery(this.rawTemplate.includes("pp-for"),this.rawTemplate.includes("pp-component=")),this.captureNeeds=Xt(this.rawTemplate,this.ownedChildren.size>0||this.subtreeHadOwnedTemplate),this.propsOnlyRuntime=Vt(r);let l=Ie.compileComponentBodyPlan(this.rawTemplate);if(this.bodyPlan=l?Zt(l):null,this.renderFunction=this.createRenderFunction(r),this.renderPipelineInitialized=!0,null!==n){let e={rawTemplate:this.rawTemplate,scriptContent:r,usesLoops:this.usesLoops,hasBoundaryCall:null!==this.__ppBoundaryHtmlFn,captureNeeds:this.captureNeeds,propsOnlyRuntime:this.propsOnlyRuntime,bodyPlan:this.bodyPlan,renderFunction:this.renderFunction,templateFns:new Map,bodyValuesFns:new Map,scopeShape:null};S(Ht,n,e,Ut),this.pipelineBlueprint=e}}installLoopMachinery(e,t){if(this.usesLoops=e,e){let e=new dt;this.loopRowCache=e,e.setValuePatchSink(this.createLoopValuePatchSink()),this.__ppLoopRowsFn=(t,n,r,i,l,o)=>e.render(t,n,r,i,l,o)}if(t){let e=new Fe;this.boundaryContentCache=e,this.__ppBoundaryHtmlFn=(t,n,r)=>e.resolve(t,n,r)}}syncParentId(){let e=this.el.__ppRuntimeParentId;if(void 0!==e)this.parentId=e;else{let e=this.boundary.parentBoundaryElement();this.parentId=e?l(e):null}x.saveParent(this.id,this.parentId)}static setPerfEnabled(e){this.perfEnabled=e,it(!e)}static getPerfEnabled(){return this.perfEnabled}static resetPerfStats(){this.perfStats.clear()}static getPerfStats(){return Object.fromEntries(this.perfStats.entries())}static createEmptyPerfEntry(){let e={};return jt.forEach(t=>{e[t]={count:0,totalMs:0,maxMs:0}}),{renderCount:0,phases:e}}recordPerfPhase(t,n){if(!e.perfEnabled)return;let r=e.perfStats.get(this.id);r||(r=e.createEmptyPerfEntry(),e.perfStats.set(this.id,r));let i=r.phases[t];i.count++,i.totalMs+=n,i.maxMs=Math.max(i.maxMs,n)}startPerfTimer(){return e.perfEnabled?Mt():0}endPerfTimer(t,n){e.perfEnabled&&this.recordPerfPhase(t,Mt()-n)}spliceOwnScriptFromInitialHtml(e){if(/<textarea\b/i.test(this.initialChildrenHtml))return null;let t=e??this.findOwnScript(this.el);if(!t)return null;let n=t.outerHTML,r=this.initialChildrenHtml.indexOf(n);return-1===r||-1!==this.initialChildrenHtml.indexOf(n,r+n.length)?null:{template:this.initialChildrenHtml.slice(0,r)+this.initialChildrenHtml.slice(r+n.length),scriptContent:ze(t)}}findOwnScript(e){for(let t=e.firstElementChild;t;t=t.nextElementSibling){if("script"===t.tagName.toLowerCase()&&!t.hasAttribute("type"))return t;if(c(t))continue;let e=this.findOwnScript(t);if(e)return e}return null}canReuseStaticInitialMarkup(e,t){if(e||this.ownedChildren.size>0||t)return!1;let n=[this.el];for(;n.length>0;){let e=n.pop();if(e instanceof Text){if(/[{}]/.test(e.data)||he(e.data))return!1;continue}if(!(e instanceof Element)||e!==this.el&&c(e))continue;let t=e.tagName.toLowerCase();if("script"===t||"template"===t||"slot"===t||"pp-context-provider"===t||t.endsWith(".provider")||"input"===t||"textarea"===t||"select"===t)return!1;for(let t of e.getAttributeNames()){let n=t.toLowerCase(),r=e.getAttribute(t)??"";if("pp-component"!==n&&(/[{}]/.test(r)||he(r)||n.startsWith("on")||n.startsWith("pp-")||n.startsWith("data-pp-")||"key"===n))return!1}for(let t=e.lastChild;t;t=t.previousSibling)n.push(t)}return!0}reuseStaticInitialMarkup(e){this.latestScope={},x.saveState(this.id,this.hooksSystem?.getHooks()??(this.freshStateId?void 0:x.getState(this.id))??X),this.freshStateId=!1,x.saveScope(this.id,this.latestScope),this.lastRenderedHtml=e;let t=this.subtreeHasComponentBoundary();this.hadNestedRuntimeStructures=t,t&&this.bootstrapNestedComponents()}subtreeHasComponentBoundary(){let e=[];for(let t=this.el.lastElementChild;t;t=t.previousElementSibling)e.push(t);for(;e.length>0;){let t=e.pop();if(c(t))return!0;for(let n=t.lastElementChild;n;n=n.previousElementSibling)e.push(n)}return!1}ownsBoundaryContent(e,t){if(this.morphingFromCommittedRender)return!1;let n=e.innerHTML;return!!n.includes("{")&&n!==t.innerHTML}parentCompiledOurContent(){return!this.subtreeHadOwnedTemplate&&!/<script\b/i.test(this.initialChildrenHtml)}neutralizeScriptlessTemplate(e){return e.includes("{")?e.split("{").join("&#123;").split("}").join("&#125;"):e}findOwnedSlotScript(e){let t=Array.from(e.querySelectorAll("template[pp-owner]")).filter(e=>{let t=e.getAttribute("pp-owner");return t===this.id||x.resolveComponentId(t,this.id)===this.id});for(let e of t){let t=e.content;if(!t)continue;let n=this.findOwnScript(t);if(n)return n}return null}applyBoundaryBindings(e,t,n,r){this.propBindingManager.applyBoundaryBindings(e,t,n,r)}computePropsFromAttributes(e,t=!1){return this.propBindingManager.computePropsFromAttributes(this.el,t?null:this.parentId,e)}recordDirectPropsSchema(){let e=this.el,t=e,n=t.__ppRawBindings;if(void 0===n)return null;for(let e in n)return null;if(void 0!==t.__ppLiteralAttrs&&t.__ppLiteralAttrs.size>0)return null;let r=t[a];if(void 0===r)return null;let i=[],l=e.getAttributeNames();for(let t=0;t<l.length;t++){let n=l[t];if("pp-component"===n)continue;if(n.startsWith("pp-literal-"))return null;if(z(n,e))continue;let o=ee(n);if(!I.has(o)){if(Object.prototype.hasOwnProperty.call(r,n)){i.push({name:n,camel:o,direct:!0});continue}i.push({name:n,camel:o,direct:!1,staticValue:this.props[o]})}}for(let e in r){if(l.includes(e))continue;let t=ee(e);I.has(t)||i.push({name:e,camel:t,direct:!0})}return i}deriveScriptPath(e){let t=[],n=e;for(;n!==this.el;){let e=n.parentElement;if(null===e)return null;let r=0;for(let t=e.firstElementChild;null!==t&&t!==n;t=t.nextElementSibling)r++;t.unshift(r),n=e}return t}refreshPropsFromParent(e=!1,t,n=!1){let r=this.computePropsFromAttributes(t,n);r.children=this.initialChildrenHtml,e||!Se(this.props,r)||0!==this.ownedChildren.size&&this.ownedTemplateManager.haveOwnerScopeIdentitiesChanged()?(this.props=r,this.isRendering||this.render()):this.hadNestedRuntimeStructures&&this.bootstrapNestedComponents()}refreshOwnedChildrenFromElement(e){if(0===this.ownedChildren.size)return!1;let t=e.cloneNode(!0),n=this.ownedTemplateManager.extractOwnedTemplates(t);if(0===n.size)return!1;let r=!1;return n.forEach((e,t)=>{let n=this.ownedChildren.get(t);(!n||n.content!==e.content||n.ownerId!==e.ownerId)&&(r=!0)}),!!r&&(this.ownedChildren=n,x.saveOwnedTemplates(this.id,n),this.forceUpdate(),!0)}getCachedFunction(e,t,n,r,i){let l=t+"|"+r,o=e.get(l);return o||(o=Function(...n,`"use strict"; return (${t});`),S(e,l,o,i)),o}createRenderFunction(t){let n=e.renderFunctionCache.get(t);if(n)return n;let r=G.extractStateBindings(t),i=Function("pp",`\n "use strict";\n ${t}\n return { ${r.join(", ")} };\n `);return S(e.renderFunctionCache,t,i,e.MAX_RENDER_FUNCTION_CACHE_SIZE),i}resolveCapturedRefValue(e,t){if(this.__ppRefStore.has(e))return this.__ppRefStore.get(e);if(!t||t===this.id)return;let n=x.getInstance(t);return n&&n.__ppRefStore.has(e)?n.__ppRefStore.get(e):void 0}resolvePlainRefValue(e,t,n,r){let i=this.latestScope[e];if("function"==typeof i||i&&"object"==typeof i&&"current"in i)return i;try{return this.getCachedFunction(this._refEvalFnCache??=new Map,e,t,r,200)(...n)}catch{return}}__ppRefCaptureFn=null;__ppSelectValueCaptureFn=null;__ppCheckedValueCaptureFn=null;__ppInputValueCaptureFn=null;__ppContextTokenCaptureFn=null;__ppContextValueCaptureFn=null;createRefCaptureFunction(){return this.__ppRefStore!==Y&&this.__ppRefStore.clear(),this.__ppRefSeq=0,this.__ppRefCaptureFn??=e=>{let t=`ppref_${this.id}_${++this.__ppRefSeq}`;return this.__ppRefStore===Y&&(this.__ppRefStore=new Map),this.__ppRefStore.set(t,e),t}}createSelectValueCaptureFunction(){return this.__ppSelectValueStore!==Y&&this.__ppSelectValueStore.clear(),this.__ppSelectValueSeq=0,this.__ppSelectValueCaptureFn??=e=>{let t=`ppselect_${this.id}_${++this.__ppSelectValueSeq}`;return this.__ppSelectValueStore===Y&&(this.__ppSelectValueStore=new Map),this.__ppSelectValueStore.set(t,e),t}}createCheckedValueCaptureFunction(){return this.__ppCheckedValueStore!==Y&&this.__ppCheckedValueStore.clear(),this.__ppCheckedValueSeq=0,this.__ppCheckedValueCaptureFn??=e=>{let t=`ppchecked_${this.id}_${++this.__ppCheckedValueSeq}`;return this.__ppCheckedValueStore===Y&&(this.__ppCheckedValueStore=new Map),this.__ppCheckedValueStore.set(t,e),t}}createInputValueCaptureFunction(){return this.__ppInputValueStore!==Y&&this.__ppInputValueStore.clear(),this.__ppInputValueSeq=0,this.__ppInputValueCaptureFn??=e=>{let t=`ppinput_${this.id}_${++this.__ppInputValueSeq}`;return this.__ppInputValueStore===Y&&(this.__ppInputValueStore=new Map),this.__ppInputValueStore.set(t,e),t}}createContextTokenCaptureFunction(){return this.__ppContextTokenStore!==Y&&this.__ppContextTokenStore.clear(),this.__ppContextTokenSeq=0,this.__ppContextTokenCaptureFn??=e=>{let t=`ppcontexttoken_${this.id}_${++this.__ppContextTokenSeq}`;return this.__ppContextTokenStore===Y&&(this.__ppContextTokenStore=new Map),this.__ppContextTokenStore.set(t,e),t}}createContextValueCaptureFunction(){return this.__ppContextValueStore!==Y&&this.__ppContextValueStore.clear(),this.__ppContextValueSeq=0,this.__ppContextValueCaptureFn??=e=>{let t=`ppcontextvalue_${this.id}_${++this.__ppContextValueSeq}`;return this.__ppContextValueStore===Y&&(this.__ppContextValueStore=new Map),this.__ppContextValueStore.set(t,e),t}}__ppContextLookupFn=null;createContextLookupFunction(){if(this.__ppContextLookupFn)return this.__ppContextLookupFn;let e=(e,t)=>{if(null==e)return;if(Object.prototype.hasOwnProperty.call(e,t))return e[t];let n=Object.keys(Object(e)).find(e=>e.toLowerCase()===t.toLowerCase());return n?e[n]:void 0};return this.__ppContextLookupFn=t=>{let n=String(t).split(".").map(e=>e.trim()).filter(Boolean);if(0===n.length)return;let r,[i,...l]=n;"globalthis"===i.toLowerCase()?r=globalThis:"window"===i.toLowerCase()?r=typeof window<"u"?window:globalThis:(r=e(this.latestScope,i),void 0===r&&(r=e(globalThis,i)));for(let t of l)r=e(r,t);return r},this.__ppContextLookupFn}__ppDefaultValueCaptureFn=null;__ppDefaultCheckedCaptureFn=null;createDefaultValueCaptureFunction(){return this.__ppDefaultValueStore!==Y&&this.__ppDefaultValueStore.clear(),this.__ppDefaultValueSeq=0,this.__ppDefaultValueCaptureFn??=e=>{let t=`ppdefaultvalue_${this.id}_${++this.__ppDefaultValueSeq}`;return this.__ppDefaultValueStore===Y&&(this.__ppDefaultValueStore=new Map),this.__ppDefaultValueStore.set(t,e),t}}createDefaultCheckedCaptureFunction(){return this.__ppDefaultCheckedStore!==Y&&this.__ppDefaultCheckedStore.clear(),this.__ppDefaultCheckedSeq=0,this.__ppDefaultCheckedCaptureFn??=e=>{let t=`ppdefaultchecked_${this.id}_${++this.__ppDefaultCheckedSeq}`;return this.__ppDefaultCheckedStore===Y&&(this.__ppDefaultCheckedStore=new Map),this.__ppDefaultCheckedStore.set(t,e),t}}__ppLoopCaptureFn=null;clearLoopValues(){this.__ppLoopValueIds===Ft||0===this.__ppLoopValueIds.size||(this.__ppLoopValueIds.forEach(e=>Nt.delete(e)),this.__ppLoopValueIds.clear())}createLoopCaptureFunction(){return this.clearLoopValues(),this.__ppLoopValueSeq=0,this.__ppLoopCaptureFn??=e=>{this.__ppLoopValueIds===Ft&&(this.__ppLoopValueIds=new Set),0===this.__ppLoopOwnerKey&&(this.__ppLoopOwnerKey=++Pt);let t=`ppv_${this.__ppLoopOwnerKey}_${++this.__ppLoopValueSeq}`;return Nt.set(t,e),this.__ppLoopValueIds.add(t),t}}consumeContext(e){return this.contextManager.consume(e)}registerProvidedContext(e,t){this.contextManager.provide(e,t)}requestContextRefresh(){this.contextManager.requestRefresh()}refreshContextConsumers(e){this.contextManager.refreshConsumers(e)}makeHooksAPI(){if(this._cachedHooksAPI)this._cachedHooksAPI.props=this.props;else if(this.propsOnlyRuntime)this._cachedHooksAPI={props:this.props};else{let e=this.ensureHooksSystem();this._cachedHooksAPI={state:t=>e.useState(t),effect:(t,n)=>e.useEffect(t,n),layoutEffect:(t,n)=>e.useLayoutEffect(t,n),ref:(t=null)=>e.useRef(t),memo:(t,n)=>e.useMemo(t,n),callback:(t,n)=>e.useCallback(t,n),reducer:(t,n,r)=>r?e.useReducer(t,n,r):e.useReducer(t,n),context:e=>this.consumeContext(e),portal:(t,n)=>e.usePortal(t,n),id:()=>e.useId(),errorBoundary:()=>e.useErrorBoundary(),syncExternalStore:(t,n)=>e.useSyncExternalStore(t,n),imperativeHandle:(t,n,r)=>e.useImperativeHandle(t,n,r),transition:()=>e.useTransition(),deferredValue:(t,n)=>e.useDeferredValue(t,n),optimistic:(t,n)=>e.useOptimistic(t,n),props:this.props}}return this._cachedHooksAPI}makeRuntimeAPI(e){if(this.propsOnlyRuntime)return this._cachedRuntimeAPI=e,e;if(!this._cachedRuntimeAPI){let t=globalThis.pp;return this._cachedRuntimeAPI=t?.createComponentRuntime?.(e)??e,this._cachedRuntimeAPI}return this._cachedRuntimeAPI.props=e.props,this._cachedRuntimeAPI}syncTrackedPortals(e){if(0===(this._portalManager?.size??0))return;let t=this.hooksSystem?.getPortalRegistrations()??Rt;if(0===t.length)return;let n=new Map,r=new Map;e.querySelectorAll("*").forEach(e=>{let t=e,i=t.getAttribute("data-pp-ref");if(i){let e=n.get(i);e?e.push(t):n.set(i,[t])}let l=t.getAttribute("pp-ref");if(l){let e=r.get(l);e?e.push(t):r.set(l,[t])}});let i=new Map;for(let[e,t]of this.__ppRefStore.entries()){if(!t||"object"!=typeof t||!("current"in t))continue;let n=t,r=i.get(n);r?r.push(e):i.set(n,[e])}let l=new Map;for(let[e,t]of Object.entries(this.latestScope)){if(!t||"object"!=typeof t||!("current"in t))continue;let n=t,r=l.get(n);r?r.push(e):l.set(n,[e])}let o=(e,t)=>{for(let n of t){let t=e.get(n);if(!t||0===t.length)continue;let r=t.shift()??null;if(0===t.length&&e.delete(n),r)return r}return null},s=[];for(let e of t){let t=e.ref.current;if(!t||!this.portalManager.has(t))continue;let a=o(n,i.get(e.ref)??[]);a||=o(r,l.get(e.ref)??[]),a&&s.push({liveElement:t,sourceElement:a,placeholderText:this.portalManager.getPlaceholderText(t)})}0!==s.length&&(s.forEach(({sourceElement:e,placeholderText:t})=>{e.replaceWith(document.createComment(t))}),s.forEach(({liveElement:e,sourceElement:t})=>{this.morphTrackedPortalRoot(e,t)}))}morphTrackedPortalRoot(e,t){if(e.tagName!==t.tagName){let n=e.parentNode;if(!n)return;let r=t.cloneNode(!0);return n.replaceChild(r,e),this.collectEventElements(r),void this.portalManager.replaceElement(e,r)}this.syncAttributes(e,t,!0),this.hasEventAttributes(e)&&(this.pendingEventElements??=new Set).add(e),this.domMorpher.morphChildren(e,t)}applyPortals(){let e=this.hooksSystem?.getPortalRegistrations()??Rt;this.portalManager.apply(e)&&this.invalidateTraversalCache()}render(t=0){if(t>e.MAX_SYNC_RERENDERS)return void console.warn(`[PP-WARN] Synchronous rerender limit exceeded for component "${this.id}". Check for state updates during render or layout effects.`);if(this.initializeRenderPipeline(),this.isRendering)return;this.isRendering=!0,this.renderCount++;let n=this.startPerfTimer();if(e.perfEnabled){let t=e.perfStats.get(this.id);t||(t=e.createEmptyPerfEntry(),e.perfStats.set(this.id,t)),t.renderCount++}try{this._contextManager?.prepareRender();let e=this.propsOnlyRuntime?this.hooksSystem:this.ensureHooksSystem();e?.prepareRender();let n=this.makeHooksAPI(),r=this.makeRuntimeAPI(n),i=this.startPerfTimer();e?.startRenderPhase();let l,o=!1,s=Qt;if(null!==s)Qt=null,l=s.scope,s.provisions?.forEach((e,t)=>this.registerProvidedContext(t,e)),o=e?.finishRenderPhase()??!1;else{let t=kt(this._provisionDispatcher??=(e,t)=>this.registerProvidedContext(e,t));try{l=this.renderFunction(r)}finally{kt(t),o=e?.finishRenderPhase()??!1}}if(this.endPerfTimer("script",i),o)return this.isRendering=!1,void this.render(t+1);x.saveState(this.id,null===e?this.freshStateId?X:x.getState(this.id)??X:e.getHooks()),this.freshStateId=!1,this.latestScope=l;let a=this.captureNeeds;0!==(a&Wt)&&(this.latestScope.__pp_ref=this.createRefCaptureFunction()),0!==(a&Gt)&&(this.latestScope.__pp_input_value=this.createInputValueCaptureFunction(),this.latestScope.__pp_select_value=this.createSelectValueCaptureFunction(),this.latestScope.__pp_checked_value=this.createCheckedValueCaptureFunction(),this.latestScope.__pp_default_value=this.createDefaultValueCaptureFunction(),this.latestScope.__pp_default_checked=this.createDefaultCheckedCaptureFunction()),0!==(a&Kt)&&(this.latestScope.__pp_context_token=this.createContextTokenCaptureFunction(),this.latestScope.__pp_context_value=this.createContextValueCaptureFunction(),this.latestScope.__pp_context_lookup=this.createContextLookupFunction()),this.usesLoops&&(this.latestScope.__pp_loop_capture=this.createLoopCaptureFunction(),this.latestScope.__pp_loop_read=Lt,this.latestScope.__pp_loop_rows=this.__ppLoopRowsFn),this.__ppBoundaryHtmlFn&&(this.latestScope.__pp_boundary_html=this.__ppBoundaryHtmlFn),x.saveScope(this.id,this.latestScope);let u,p,d=this.pipelineBlueprint,c=0===a&&!this.usesLoops&&null===this.__ppBoundaryHtmlFn&&null!==d,h=c?d.scopeShape:null;if(null!==h)u=h.sortedKeys,p=h.sortedKeySig;else{let e=ie(this.latestScope),t=e.keys,n=e.keySig;n===this._lastRawScopeKeySig?(u=this._lastSortedKeys,p=this._lastSortedScopeKeySig):(u=t.length>1?[...t].sort():t.slice(),p=u.join("\0"),this._lastRawScopeKeySig=n,this._lastSortedKeys=u,this._lastSortedScopeKeySig=p),c&&(d.scopeShape={sortedKeys:u,sortedKeySig:p})}let f=oe(this.latestScope,u);if(!this.templateFn){let e=this.startPerfTimer(),t=d?.templateFns.get(p);t?this.templateFn=t:(this.templateFn=Ie.compile(this.rawTemplate,u),d?.templateFns.set(p,this.templateFn)),this.endPerfTimer("compile",e)}this.loopRowCache?.beginRender(),this.loopKeepResolved=0,this._patchedBoundaryRows=null,this.boundaryContentCache?.beginRender(),this.boundaryKeepResolved=0;let m,_=this.startPerfTimer(),g=!1;this.canAttemptStringlessMount()&&(g=this.tryBodyPlanCommit(u,f,p)),g?m=zt:(m=this.templateFn(...f),(null!==this._ownedTemplateManager||m.includes("__PP_OWNED_"))&&(m=this.ownedTemplateManager.resolveOwnedChildren(m,this.ownedChildren))),this.endPerfTimer("template",_);let y=e?.getPortalRegistrations()??Rt,E=this.lastRenderedHtml!==m,v=this.loopRowCache?.takePendingPatches()??null,S=this._patchedBoundaryRows;this._patchedBoundaryRows=null;let b=this.loopRowCache?.takeStructuralBoundaryChange()??!1,C=this._lastHtmlProbes;(E||!C)&&(C=m===zt?Bt:{managedInputTags:/<(?:input|textarea|select)\b/i.test(m),refMarkers:m.includes("pp-ref"),contextProviders:m.includes("<pp-context-provider"),nestedBoundaries:m.includes("pp-component="),ownerMarkers:m.includes("pp-owner")},this._lastHtmlProbes=C);let T=this.el instanceof HTMLInputElement||this.el instanceof HTMLTextAreaElement||this.el instanceof HTMLSelectElement||C.managedInputTags,w=this.el.hasAttribute("pp-ref")||this.el.hasAttribute("data-pp-ref")||C.refMarkers||(this._refBindingManager?.hasActiveBindings()??!1),P=C.contextProviders,k=C.nestedBoundaries||P||y.length>0,R=this.ownedChildren.size>0||C.ownerMarkers;if(!(E||null!==v||b||T||R||P||k&&this.getTraversalCache().childBoundaries.some(e=>{let t=e.__ppRawBindings;return!!t&&Object.keys(t).length>0}))){if(null!==S){let e=this.startPerfTimer();this.nestedBoundaryManager.refreshPatchedBoundaries(S),this.endPerfTimer("bootstrapNested",e)}if(w){let e=this.startPerfTimer();this.bindRefs(u,f,p),this.endPerfTimer("bindRefs",e)}let n=this._contextManager?.commitRenderContexts()??null;if(y.length>0||(this._portalManager?.size??0)>0){let e=this.startPerfTimer();this.applyPortals(),this.endPerfTimer("portals",e)}let r=this.startPerfTimer(),i=e?.runLayoutEffects()??!1;return this.endPerfTimer("layoutEffects",r),i?(this.isRendering=!1,void this.render(t+1)):(this.schedulePassiveEffects(),this.boundaryContentCache?.commit(),void(n?.size&&this.refreshContextConsumers(n)))}let A=T?this.collectManagedInputs():[],I=T||null!==this._focusManager?this.focusManager.save(A):null;if(E){let e=this.startPerfTimer();if(!g&&!this.tryBodyPlanCommit(u,f,p)&&!this.applyDomDiff(m))return console.warn(`[PP-WARN] Direct loop row construction was abandoned for component "${this.id}" because its parsed marker did not match the planned rows. Rendering through the string pipeline.`),this.loopRowCache?.disableDirectBuilding(),this.lastRenderedHtml="",this.isRendering=!1,void this.render(t+1);this.endPerfTimer("domDiff",e),this.lastRenderedHtml=m;let n=this.loopRowCache?.getEmittedCount()??0;if(n>0&&this.loopKeepResolved!==n)return console.warn(`[PP-WARN] Loop row reuse was abandoned for component "${this.id}" because a reused row was no longer mounted. Rendering without row reuse.`),this.loopRowCache?.disable(),this.lastRenderedHtml="",this.isRendering=!1,void this.render(t+1);let r=this.boundaryContentCache?.getEmittedCount()??0;if(r>0&&this.boundaryKeepResolved!==r)return console.warn(`[PP-WARN] Nested boundary content reuse was abandoned for component "${this.id}" because a reused boundary was no longer mounted. Rendering without boundary reuse.`),this.boundaryContentCache?.disable(),this.forceChildBoundaryRefresh=!0,this.lastRenderedHtml="",this.isRendering=!1,void this.render(t+1)}if(null!==v){let e=this.startPerfTimer(),n=this.applyLoopPatches(v);if(this.endPerfTimer("domDiff",e),!n)return console.warn(`[PP-WARN] Loop row patching was abandoned for component "${this.id}" because a patched row was no longer mounted. Rendering without row patching.`),this.loopRowCache?.disablePatching(),this.lastRenderedHtml="",this.isRendering=!1,void this.render(t+1);this.loopRowCache?.commitPatches(v),this.invalidateTraversalCache()}if(null!==S){let e=this.startPerfTimer();this.nestedBoundaryManager.refreshPatchedBoundaries(S),this.endPerfTimer("bootstrapNested",e)}if(this.boundaryContentCache?.commit(),this.hasEventAttributes(this.el)&&(this.pendingEventElements??=new Set).add(this.el),(this.pendingEventElements?.size??0)>0){let e=this.pendingEventElements;this.pendingEventElements=null;let t=this.startPerfTimer();this.eventManager.bindEvents(e),this.endPerfTimer("bindEvents",t)}if(w){let e=this.startPerfTimer();this.bindRefs(u,f,p),this.endPerfTimer("bindRefs",e)}let M=E&&T?this.collectManagedInputs():A,N=this._contextManager?.commitRenderContexts()??null;if(k||this.hadNestedRuntimeStructures||b){let e=this.startPerfTimer();this.bootstrapNestedComponents(),this.endPerfTimer("bootstrapNested",e)}if(this.hadNestedRuntimeStructures=k,y.length>0||(this._portalManager?.size??0)>0){let e=this.startPerfTimer();this.applyPortals(),this.endPerfTimer("portals",e)}if((T||null!==this._formControlManager)&&(this.bindControlledInputValues(M),this.bindUncontrolledInputDefaults(M),this.bindUncontrolledFormResets(M),this.bindControlledSelectValues(M),this.bindControlledCheckedValues(M)),null!==I){let e=this.startPerfTimer();this.focusManager.restore(I,M),this.endPerfTimer("restoreFocus",e)}let L=this.startPerfTimer(),B=e?.runLayoutEffects()??!1;if(this.endPerfTimer("layoutEffects",L),B)return this.isRendering=!1,void this.render(t+1);this.schedulePassiveEffects(),N?.size&&this.refreshContextConsumers(N)}catch(e){this.deliverErrorToBoundary(e)||console.error("[PP-ERROR] Render Cycle Failed",e)}finally{this.endPerfTimer("total",n),this.isRendering=!1}}deliverErrorToBoundary(e){return!!this.hooksSystem?.captureError(e)||nn(this.id,e)}captureComponentError(e){return this.hooksSystem?.captureError(e)??!1}schedulePassiveEffects(){if(!this.hooksSystem?.hasPendingEffects())return;let e=++this.passiveEffectsVersion;queueMicrotask(()=>{if(this.passiveEffectsVersion!==e||x.getInstance(this.id)!==this)return;let t=this.startPerfTimer();this.hooksSystem?.runEffects(),this.endPerfTimer("effects",t)})}applyDomDiff(e){if(this.morphingFromCommittedRender=""!==this.lastRenderedHtml,""===this.lastRenderedHtml&&this.liveOwnScriptEl?.parentNode){let e=this.liveOwnScriptEl,t=e.previousSibling,n=e.nextSibling;e.remove(),t?.nodeType===Node.TEXT_NODE&&n?.nodeType===Node.TEXT_NODE&&(t.nodeValue=(t.nodeValue??"")+(n.nodeValue??""),n.parentNode?.removeChild(n)),this.liveOwnScriptEl=null}if(typeof SVGElement<"u"&&this.el instanceof SVGElement){let t=(new DOMParser).parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${e}</svg>`,"image/svg+xml").documentElement,n=document.createDocumentFragment();return Array.from(t.childNodes).forEach(e=>{n.appendChild(document.importNode(e,!0))}),this.domMorpher.morphChildren(this.el,n),this.invalidateTraversalCache(),!0}let t=W(e,this.el.tagName.toLowerCase()).root;return!(null!==this.loopRowCache&&!this.loopRowCache.prepareDirectBuilds(t))&&(e.includes("<template")&&e.includes("pp-component")&&this.ownedTemplateManager.materializeTemplateComponentBoundaries(t),e.includes("<script")&&Re(t),this.syncTrackedPortals(t),this.domMorpher.morphChildren(this.el,t),this.invalidateTraversalCache(),this.loopRowCache?.finishDirectBuilds()??!0)}canAttemptStringlessMount(){return""===this.lastRenderedHtml&&null!==this.bodyPlan&&!this.bodyPlanDisabled&&0===this.captureNeeds&&!this.usesLoops&&null===this.__ppBoundaryHtmlFn&&0===this.ownedChildren.size&&null===this._ownedTemplateManager}tryBodyPlanCommit(e,t,n){let r=this.bodyPlan;if(null===r||this.bodyPlanDisabled||!(this.el instanceof HTMLElement))return!1;let i,l=this.bodyPlanValuesFn;if(null===l){let t=this.pipelineBlueprint;if(l=t?.bodyValuesFns.get(n)??null,null===l){try{l=Function(...e,`"use strict"; return [${r.exprs.join(", ")}];`)}catch{return this.bodyPlanDisabled=!0,!1}t?.bodyValuesFns.set(n,l)}this.bodyPlanValuesFn=l}try{i=l(...t)}catch{return this.bodyPlanValues=null,!1}for(let e=0;e<r.size;e++){let t=i[e];if(null!==t&&("object"==typeof t||"function"==typeof t||"symbol"==typeof t))return this.bodyPlanValues=null,!1}let o=""===this.lastRenderedHtml;o&&null!==this.liveOwnScriptEl&&(this.liveOwnScriptEl.remove(),this.liveOwnScriptEl=null);let s=this.el.firstElementChild;if(null===s||s.tagName!==r.rootTag||null!==s.nextElementSibling)return this.bodyPlanValues=null,!1;let a,u=this.bodyPlanValues;if(null===u||o)a=r.fullMask;else{a=0;let e=r.slotBitsByValue;for(let t=0;t<r.size;t++)Object.is(i[t],u[t])||(a|=e[t]);if(0===a)return this.lastRenderedHtml===zt||(this.bodyPlanDisabled=!0,this.bodyPlanValues=null,!1)}return 0===a||J(s,r.applyPlan,i,a)?(this.bodyPlanValues=i,!0):(this.bodyPlanValues=null,!1)}applyLoopPatches(e){this.morphingFromCommittedRender=!0;let t=null;for(let n of e){let e=n.patches.some(e=>e.html.includes("pp-component")),r=this.resolveLoopContainer(n.loopId,n.patches[0].key,e);if(!r)return!1;let i=this.ensureLoopKeyIndex(r),l="";for(let e of n.patches)l+=e.html;if(l.includes("__PP_")){let e=this.templateFn?.__ppRestoreArtifacts;if(!e)return!1;l=e(l)}let o=W(l,r.tagName.toLowerCase());l.includes("<script")&&Re(o.root);let s=[];for(let e=o.root.firstElementChild;e;e=e.nextElementSibling)s.push(e);if(s.length!==n.patches.length)return!1;let a=n.patches;for(let e=0;e<a.length;e++){let n=a[e],l=i.get(n.key);if(!l||l.parentNode!==r)return!1;let o=this.domMorpher.morphPatchedRow(r,l,s[e]);if(o!==l){if(c(o)||null!==o.querySelector("[pp-component]"))return!1;i.set(n.key,o)}else n.html.includes("pp-component")&&(t??=[]).push(l)}}return null!==t&&this.nestedBoundaryManager.refreshPatchedBoundaries(t),!0}ensureLoopKeyIndex(e){let t=e,n=t.__ppLoopKeyIndex;if(!n){n=new Map;for(let t=e.firstElementChild;t;t=t.nextElementSibling){let e=t.getAttribute("key");null!==e&&e.length>0&&!n.has(e)&&n.set(e,t)}t.__ppLoopKeyIndex=n}return n}createLoopValuePatchSink(){return{begin:(e,t,n)=>{let r=this.resolveLoopContainer(e,t,n);return r?{container:r,index:this.ensureLoopKeyIndex(r)}:null},onBoundaryRowPatched:e=>{(this._patchedBoundaryRows??=[]).push(e)},reportPatchAbandoned:()=>{console.warn(`[PP-WARN] Loop row patching was abandoned for component "${this.id}" because a patched row was no longer mounted. Rendering without row patching.`)}}}loopSearchRoots(){let e=this._portalManager?.elements();if(!e||0===e.length)return[this.el];let t=[this.el];for(let n of e)this.el.contains(n)||t.push(n);return t}ownsSurfaceElement(e){return this.el.contains(e)||(this._portalManager?.contains(e)??!1)}resolveLoopContainer(e,t,n){let r=this._loopContainers?.get(e);if(r&&r.el.isConnected&&this.ownsSurfaceElement(r.el))return n&&!r.providerFree?null:r.el;try{let r=`[key="${t.replace(/["\\]/g,"\\$&")}"]`,i=this.loopSearchRoots(),l=null,o=!0;for(let e of i){let t=e.querySelectorAll(r);for(let n=0;n<t.length;n++){let r=t[n],i=r.parentElement,s=!1,a=!1;for(;i&&i!==e;){if(c(i)){s=!0;break}"pp-context-provider"===i.tagName.toLowerCase()&&(a=!0),i=i.parentElement}if(!s&&i===e){if(null!==l)return null;l=r,o=!a}}}let s=null===l?null:l.parentElement;return s&&"http://www.w3.org/1999/xhtml"===s.namespaceURI&&((this._loopContainers??=new Map).set(e,{el:s,providerFree:o}),!n||o)?s:null}catch{return null}}isEffectManagedSurfaceElement(e,t){return this.attributeSyncManager.isEffectManagedSurfaceElement(e,t)}collectEventElements(e){this.traversalManager.collectEventElements(e,this.pendingEventElements??=new Set)}hasEventAttributes(e){return _t(e)}invalidateTraversalCache(){this._traversalManager?.invalidate(),this._eventManager?.invalidateElementCountCache()}getTraversalCache(){return this.traversalManager.getCache()}collectManagedInputs(){return this.traversalManager.collectManagedInputs()}resolveForwardedComponentRefTarget(e){if("true"!==e.getAttribute("pp-ref-forward"))return e;let t=e,n=new Set;for(;!n.has(t);){if(n.add(t),!(t.getAttribute("style")||"").toLowerCase().replace(/\s+/g,"").includes("display:contents"))return t;let r=Array.from(t.children).filter(e=>e instanceof HTMLElement&&c(e));if(1!==r.length)return console.error(`[PP-ERROR] Cannot forward pp-ref through component "${l(t)||"unknown"}": expected exactly one child component root, found ${r.length}. Render one x-* root or consume ppRef explicitly in the component.`),e;t=r[0]}return console.error(`[PP-ERROR] Cannot forward pp-ref through component "${l(e)||"unknown"}": detected a component-root cycle.`),e}syncAttributes(e,t,n=!1,r=!1,i){this.attributeSyncManager.syncAttributes(e,t,n,r,i)}bindRefs(e,t,n){let r=this.getTraversalCache(),i=new Map;for(let l=0;l<r.refElements.length;l++){let o=r.refElements[l],s=o,a=o!==this.el&&c(o),u=o.getAttribute("data-pp-ref"),p=o.getAttribute("pp-ref-owner"),d=null;if(u)this.__ppRefStore.has(u)?(o.removeAttribute("data-pp-ref"),this.__ppRefCaptureIdsByElement.set(o,u),d=u):a||(o.removeAttribute("data-pp-ref"),this.__ppRefCaptureIdsByElement.set(o,u),d=u);else{let e=this.__ppRefCaptureIdsByElement.get(o);e&&(this.__ppRefStore.has(e)||void 0!==this.resolveCapturedRefValue(e,p)?d=e:this.__ppRefCaptureIdsByElement.delete(o))}if(d){let e=this.resolveCapturedRefValue(d,p);if("function"==typeof e||e&&"object"==typeof e&&"current"in e){let t=this.refBindingManager.ensureBindingId(s,"captured");i.set(t,{element:this.resolveForwardedComponentRefTarget(o),value:e})}else u&&d.startsWith(`ppref_${this.id}_`)&&console.warn(`[PP-WARN] Missing captured ref for id="${d}"`)}let h=o.getAttribute("pp-ref"),f=h||this.__ppRefExprsByElement.get(o)||null;if(!f)continue;let m=this.resolvePlainRefValue(f,e,t,n);if("function"==typeof m||m&&"object"==typeof m&&"current"in m){h&&o.removeAttribute("pp-ref"),this.__ppRefExprsByElement.set(o,f);let e=this.refBindingManager.ensureBindingId(s,"plain");i.set(e,{element:this.resolveForwardedComponentRefTarget(o),value:m});continue}h&&a||(h&&(o.removeAttribute("pp-ref"),this.__ppRefExprsByElement.set(o,f)),Object.prototype.hasOwnProperty.call(this.latestScope,f)||console.warn(`[PP-WARN] Could not resolve pp-ref="${f}"`))}this.refBindingManager.commit(i)}bindControlledSelectValues(e){this.formControlManager.bindControlledSelectValues(e,this.__ppSelectValueStore)}bindControlledCheckedValues(e){this.formControlManager.bindControlledCheckedValues(e,this.__ppCheckedValueStore)}bindControlledInputValues(e){this.formControlManager.bindControlledInputValues(e,this.__ppInputValueStore)}bindUncontrolledInputDefaults(e){for(let t=0;t<e.length;t++){let n=e[t];if(n.__ppManagedInputMounted)this.formControlManager.resolveDefaultValueBinding(n,this.__ppDefaultValueStore),n instanceof HTMLInputElement&&this.formControlManager.resolveDefaultCheckedBinding(n,this.__ppDefaultCheckedStore);else{let e=this.formControlManager.resolveDefaultValueBinding(n,this.__ppDefaultValueStore);if(void 0!==e&&this.formControlManager.applyUncontrolledDefaultValue(n,e),n instanceof HTMLInputElement){let e=this.formControlManager.resolveDefaultCheckedBinding(n,this.__ppDefaultCheckedStore);void 0!==e&&this.formControlManager.applyUncontrolledDefaultChecked(n,e)}}n.__ppManagedInputMounted=!0}}bindUncontrolledFormResets(e){this.formControlManager.syncUncontrolledFormResets(this.id,e,()=>this.collectManagedInputs())}bootstrapNestedComponents(){try{this.nestedBoundaryManager.bootstrap()}finally{this.forceChildBoundaryRefresh=!1}}materializeNestedBoundaryFormDefaults(e){null===this._formControlManager&&0===this.__ppInputValueStore.size&&0===this.__ppCheckedValueStore.size&&0===this.__ppDefaultValueStore.size&&0===this.__ppDefaultCheckedStore.size||this.formControlManager.materializeNestedBoundaryFormDefaults(e,{inputValueStore:this.__ppInputValueStore,checkedValueStore:this.__ppCheckedValueStore,defaultValueStore:this.__ppDefaultValueStore,defaultCheckedStore:this.__ppDefaultCheckedStore})}forceUpdate(){this.lastRenderedHtml="",this.render()}destroyNestedComponents(){if(x.hasChildren(this.id)){x.beginTopologyBatch();try{x.forEachDescendant(this.id,e=>{let t=x.getInstance(e);t&&t!==this&&t.destroy?.()})}finally{x.endTopologyBatch()}}}destroy(){let t=this.startPerfTimer();this.destroyNestedComponents(),this._formControlManager?.clearResetHandlers(this.id),this.hooksSystem?.dispose(),this._refBindingManager?.clearAll(),this.clearLoopValues(),this.loopRowCache?.clear(),this._portalManager?.destroyAll();let n=this._contextManager?this._contextManager.destroy():x.removeContextTracking(this.id);this._eventManager?.clearCache(),x.removeState(this.id),x.removeScope(this.id),x.removeOwnedTemplates(this.id),x.removeInstance(this.id),e.perfEnabled?this.endPerfTimer("destroy",t):e.perfStats.delete(this.id),n&&this._contextManager?.refreshConsumers(n)}},Qt=null,Q=null,$t=(e,t)=>{(Q??=new Map).set(e,t)};function en(e,t){let n=t[a];if(void 0===n)return null;let r={};for(let t=0;t<e.length;t++){let i=e[t];r[i.camel]=i.direct?n[i.name]:i.staticValue}return r}function tn(e,t){if(null===t)return null;let n=e;for(let e=0;e<t.length&&null!==n;e++){let r=n.firstElementChild;for(let n=t[e];n>0&&null!==r;n--)r=r.nextElementSibling;n=r}return null===n||"script"!==n.tagName.toLowerCase()||n.hasAttribute("type")?null:n}function nn(e,t){let n=new Set([e]),r=x.getParent(e);for(;r&&!n.has(r);){if(n.add(r),x.getInstance(r)?.captureComponentError?.(t))return!0;r=x.getParent(r)??null}return!1}function rn(e,t){let n=t.blueprint;if(!t.stringlessMounted||null===n||!n.propsOnlyRuntime||0!==n.captureNeeds||n.usesLoops||n.hasBoundaryCall||null===n.bodyPlan||null===n.scopeShape||null===t.propsSchema||null===t.scriptPath&&t.hasScript||_t(e)||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.hasAttribute("pp-ref")||e.hasAttribute("data-pp-ref"))return!1;let r=n.scopeShape,i=n.bodyPlan,l=n.bodyValuesFns.get(r.sortedKeySig)??null;if(null===l){try{l=Function(...r.sortedKeys,`"use strict"; return [${i.exprs.join(", ")}];`)}catch{return!1}n.bodyValuesFns.set(r.sortedKeySig,l)}return{derivation:t,blueprint:n,schema:t.propsSchema,childrenHtml:t.childHtml,scriptPath:t.scriptPath,scopeKeys:r.sortedKeys,plan:i,valuesFn:l,renderFunction:n.renderFunction}}function an(e,t,n,r,i,l){e[o]=t.derivation,l&&(e.__ppFreshIdentity=!0),null!==n&&(Qt={scope:n,provisions:r});try{new Z(e,i)}finally{Qt=null}return!0}function on(e,t,n){let r=kt($t);try{return e.renderFunction({props:t})}catch(e){return Q=null,nn(n,e)||console.error("[PP-ERROR] Render Cycle Failed",e),null}finally{kt(r)}}function sn(e,t){let n;try{n=e.valuesFn(...oe(t,e.scopeKeys))}catch{return null}for(let t=0;t<e.plan.size;t++){let e=n[t];if(null!==e&&("object"==typeof e||"function"==typeof e||"symbol"==typeof e))return null}return n}function cn(e,t){let n=e.firstElementChild;return null!==n&&n.tagName===t.rootTag&&null===n.nextElementSibling?n:null}function ln(e,t,n){let r=en(t.schema,e);if(null===r)return!1;r.children=t.childrenHtml;let i=e;delete e[o];let s=!0===i.__ppFreshIdentity;s&&delete i.__ppFreshIdentity;let a=i.__ppRuntimeComponentId??l(e)??"",u=new dn(e,a,i.__ppRuntimeParentId??null,r,t);x.registerInstance(a,u),x.saveParent(a,u.parentId);let p=on(t,r,a);if(null===p)return!0;let d=Q,c=null;if(null===d){if(c=sn(t,p),null!==c&&null!==t.scriptPath){let n=tn(e,t.scriptPath);null===n?c=null:n.remove()}if(null!==c){let n=cn(e,t.plan);(null===n||!J(n,t.plan.applyPlan,c,t.plan.fullMask))&&(c=null)}}else Q=null;return null===c?(u.handedOver=!0,an(e,t,p,d,n,s)):(x.saveState(a,s?X:x.getState(a)??X),u.latestScope=p,x.saveScope(a,p),u.bodyPlanValues=c,!0)}function un(e,t){let n=e[o];if(void 0!==n&&null!==n.childHtml&&!Z.getPerfEnabled()){let r=n.flyweight;if(null===r&&(r=rn(e,n),n.flyweight=r),!1!==r&&ln(e,r,t))return}new Z(e,t)}var dn=class{el;id;parentId;props;shape;latestScope=null;bodyPlanValues=null;renderCount=1;handedOver=!1;pipelineBlueprint;constructor(e,t,n,r,i){this.el=e,this.id=t,this.parentId=n,this.props=r,this.shape=i,this.pipelineBlueprint=i.blueprint}captureComponentError(){return!1}refreshPropsFromParent(e=!1,t){let n=this.shape,r=en(n.schema,this.el);if(null===r)return void this.materialize(null,null,t);if(r.children=n.childrenHtml,!e&&Se(this.props,r))return;this.props=r,this.renderCount++;let i=on(n,r,this.id);if(null===i)return;let l=Q,o=null;if(null===l?o=sn(n,i):Q=null,null!==o){let t=n.plan,r=cn(this.el,t);if(null!==r){let n,l=this.bodyPlanValues;if(e||null===l)n=t.fullMask;else{n=0;let e=t.slotBitsByValue;for(let r=0;r<t.size;r++)Object.is(o[r],l[r])||(n|=e[r])}if(0===n||J(r,t.applyPlan,o,n))return this.bodyPlanValues=o,this.latestScope=i,void x.saveScope(this.id,i)}}this.materialize(i,l,t)}materialize(e,t,n){this.handedOver=!0,an(this.el,this.shape,e,t,n,!1)}destroy(){x.getInstance(this.id)===this&&(at(this.shape.derivation,this,x.getState(this.id)),x.removeContextTracking(this.id),x.removeState(this.id),x.removeScope(this.id),x.removeInstance(this.id))}};function fn(e,t,n=(typeof window<"u"?window:globalThis),r=!0,i={}){let l,{cache:o=!1,configurable:s=!1,resetOnNull:a=!1}=i,u=!1;if(Object.defineProperty(n,e,{get:()=>(()=>{if(o&&u)return l;let e=t,n=null===e||"function"!=typeof e&&"object"!=typeof e||!("getInstance"in e)||"function"!=typeof e.getInstance?t:e.getInstance();return o&&(l=n,u=!0),n})(),set(t){a&&null===t?u=!1:console.warn(`[${e}] Cannot override global ${e}; ignoring.`,t)},configurable:s,enumerable:!0}),r)try{n[e]}catch(t){console.error(`Failed to initialize ${e}:`,t)}}function pn(e){if(!e)return null;try{let t=new URL(e,window.location.href);return t.origin===window.location.origin?t.pathname+t.search+t.hash:(console.warn("Ignoring cross-origin redirect target from server response:",e),null)}catch(t){return console.warn("Ignoring invalid redirect target from server response:",e,t),null}}function mn(e){let t=pn(e.headers.get("X-PP-Redirect"));if(t)return t;let n=e.headers.get("Location"),r=e.status;return n&&r>=300&&r<400?pn(n):null}var $=class extends Error{status;errors;requestId;body;constructor(e,t,n=null){super(e),this.name="RpcError",this.status=t,this.body=n,this.requestId=n&&"string"==typeof n.requestId?n.requestId:null,this.errors=n&&"object"==typeof n.errors&&null!==n.errors&&!Array.isArray(n.errors)?n.errors:{}}},hn=class{redirect;activeAbortController=null;constructor(e){this.redirect=e}async call(e,t={},n=!1){let r=null,i="boolean"==typeof n?{abortPrevious:n}:n;try{i.abortPrevious&&this.activeAbortController&&(this.activeAbortController.abort(),this.activeAbortController=null),r=new AbortController,i.abortPrevious&&(this.activeAbortController=r);let n,l=this.resolveUrl(i.url),o=this.resolveCredentials(l,i.credentials),s={"X-CSRF-Token":await this.ensureCsrfToken(l,o,i.csrfUrl),"X-PP-RPC":"true","X-PulsePoint-Wire":"true","X-PP-Function":e,"X-Requested-With":"XMLHttpRequest",Accept:"application/json, text/event-stream"},a=Object.values(t).some(e=>e instanceof File||e instanceof FileList&&e.length>0);if(a){let e=this.createFormData(t);if(i.onUploadProgress){let t=await this.uploadWithProgress({url:l.toString(),headers:s,body:e,controller:r,credentials:o,options:i});return this.clearActiveController(r),t}n={method:"POST",headers:s,body:e,credentials:o,signal:r.signal}}else n={method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify(t),credentials:o,signal:r.signal};let u=await fetch(l.toString(),n);await this.assertSuccessfulResponse(u);let p=mn(u);if(p)return await this.redirect(p),this.clearActiveController(r),{redirected:!0,to:p};if((u.headers.get("Content-Type")||"").includes("text/event-stream")&&u.body){i.onStream||console.warn("RPC returned a stream, but no onStream handler provided.");try{await this.handleStream(u.body,i)}finally{this.clearActiveController(r)}return}return this.clearActiveController(r),await u.json()}catch(e){if(this.clearActiveController(r),e instanceof Error&&"AbortError"===e.name)return console.log("Request was cancelled"),{cancelled:!0};if(i.onStreamError)return void i.onStreamError(e);throw console.error("RPC error:",e),e}}getCsrfToken(){let e=window.location.port?[`pp_csrf_${window.location.port}`,"pp_csrf"]:["pp_csrf"];for(let t of e){let e=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(RegExp(`(?:^|;\\s*)${e}=([^;]*)`));if(n)return decodeURIComponent(n[1])}return""}resolveUrl(e){let t=window.location.pathname.replace(/\/+$/,"")||"/";return new URL(e??t,window.location.origin)}resolveCredentials(e,t){return t||(e.origin===window.location.origin?"same-origin":"include")}async ensureCsrfToken(e,t,n){let r=this.getCsrfToken();if(""!==r||"omit"===t)return r;let i=new URL(n??e.toString(),window.location.origin);return await fetch(i.toString(),{method:"GET",credentials:t,cache:"no-store",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/html, application/json, */*"}}),r=this.getCsrfToken(),r}createFormData(e){let t=new FormData,n=[];for(let[r,i]of Object.entries(e))i instanceof File?n.push([r,i]):i instanceof FileList?Array.from(i).forEach(e=>n.push([r,e])):null!=i&&t.append(r,"object"==typeof i?JSON.stringify(i):String(i));for(let[e,r]of n)t.append(e,r);return t}async assertSuccessfulResponse(e){if(e.ok)return;let t=await e.json().catch(()=>null);throw 401===e.status?new $("Authentication required",401,t):403===e.status?new $("Permission denied",403,t):t||415!==e.status?new $(t?.error||`Request failed: ${e.status} ${e.statusText}`,e.status,t):new $("Server rejected data format (415).",415,null)}clearActiveController(e){this.activeAbortController===e&&(this.activeAbortController=null)}uploadWithProgress(e){let{url:t,headers:n,body:r,controller:i,credentials:l,options:o}=e;return new Promise((e,s)=>{let a=new XMLHttpRequest;a.open("POST",t,!0),a.withCredentials="include"===l;for(let[e,t]of Object.entries(n))a.setRequestHeader(e,t);let u=()=>{try{a.abort()}catch{}};i.signal.addEventListener("abort",u,{once:!0}),a.upload&&o.onUploadProgress&&(a.upload.onprogress=e=>{let t=e.lengthComputable?e.total:null,n=e.lengthComputable&&e.total>0?Math.min(100,Math.max(0,e.loaded/e.total*100)):null;o.onUploadProgress?.({loaded:e.loaded,total:t,percent:n})}),a.onerror=()=>{i.signal.removeEventListener("abort",u),s(Error("Network error (XHR upload)."))},a.onload=async()=>{if(i.signal.removeEventListener("abort",u),a.status<200||a.status>=300){let e=null;try{e=JSON.parse(a.responseText||"null")}catch{}return 401===a.status?s(new $("Authentication required",401,e)):403===a.status?s(new $("Permission denied",403,e)):s(new $(e?.error||e?.message||`Request failed: ${a.status} ${a.statusText}`,a.status,e))}let t=pn(a.getResponseHeader("X-PP-Redirect")||(a.status>=300&&a.status<400?a.getResponseHeader("Location"):null));if(t)try{return await this.redirect(t),o.onUploadComplete?.(),e({redirected:!0,to:t})}catch(e){return s(e)}let n=a.responseText??"",r=n;try{r=JSON.parse(n)}catch{}o.onUploadComplete?.(),e(r)};try{a.send(r)}catch(e){i.signal.removeEventListener("abort",u),s(e)}})}async handleStream(e,t){let n=e.getReader(),r=new TextDecoder,i="";try{for(;;){let{done:e,value:l}=await n.read();if(e){t.onStreamComplete?.();break}i+=r.decode(l,{stream:!0});let o=i.split("\n");i=o.pop()||"";for(let e of o){if(""===e.trim()||!e.startsWith("data: "))continue;let n=e.slice(6),r=n;try{("true"===n||"false"===n||"null"===n||!isNaN(Number(n))||n.startsWith("{")||n.startsWith("[")||n.startsWith('"'))&&(r=JSON.parse(n))}catch{}t.onStream?.(r)}}}catch(e){if(!t.onStreamError)throw e;t.onStreamError(e)}finally{n.releaseLock()}}},gn="/__pulsepoint/ws";function _n(e){return"object"==typeof e&&e&&!Array.isArray(e)&&1===Object.keys(e).length&&"string"==typeof e.error?e.error:null}var vn=class{active=new Set;connect(e,t={},n={}){let r=new URL(n.url??gn,window.location.origin);r.searchParams.set("name",e),r.protocol="https:"===r.protocol?"wss:":"ws:";let i=new WebSocket(r.toString());this.active.add(i);let l=[],o=!1,s=!1;return i.onopen=()=>{i.send(JSON.stringify(t??{})),o=!0;for(let e of l.splice(0))i.send(e);n.onOpen?.()},i.onmessage=e=>{if("string"!=typeof e.data)return;let t=e.data;try{t=JSON.parse(e.data)}catch{}let r=_n(t);if(null!==r)return s=!0,void n.onError?.(Error(r));n.onMessage?.(t)},i.onerror=()=>{!o&&!s&&(s=!0,n.onError?.(Error(`Socket "${e}" could not connect. The server refuses unknown names, cross-origin pages, and — for auth sockets — missing sessions before the connection opens.`)))},i.onclose=e=>{this.active.delete(i),n.onClose?.({code:e.code,reason:e.reason,wasClean:e.wasClean})},{send:e=>{if(i.readyState===WebSocket.CLOSING||i.readyState===WebSocket.CLOSED)return!1;let t=JSON.stringify(e);if(!o)return l.push(t),!0;try{return i.send(t),!0}catch{return!1}},close:(e,t)=>{try{i.close(e??1e3,t)}catch{}},get readyState(){return i.readyState}}}},yn="opacity 0.18s ease-out",bn=15e3,xn={bootstrap:()=>{ht.materializeTemplateComponentBoundaries(document.body),y(document.body),p(document).forEach(e=>{new Z(e)})}},Sn=class e{static instance=null;rpcClient=new hn(e=>this.redirect(e));socketClient=new vn;navigationEnabled=!1;boundHandleLinkClick=null;boundHandlePopState=null;boundHandleTrackedScroll=null;isNavigating=!1;pendingHistoryStateSaveTimer=null;lastHistoryStateSaveAt=0;pendingProgrammaticScrollPersistenceTimer=null;RESET_SCROLL_ATTR="pp-reset-scroll";HISTORY_SCROLL_STATE_KEY="__ppScrollPositions";TRACKED_SCROLL_PERSISTENCE_INTERVAL_MS=150;PROGRAMMATIC_SCROLL_SETTLE_MS=120;mounted=!1;suppressTrackedScrollPersistence=!1;pendingRevealFrame=null;pendingTransitionUnlockFrame=null;hydrationBodySnapshot=null;previousHistoryScrollRestoration=null;trackedScrollElements=new Set;didInitialScrollDiscovery=!1;SCROLL_KEY_ATTR="pp-scroll-key";static PUBLIC_METHODS=["createContext","mount","redirect","rpc","socket","enablePerf","disablePerf","getPerfStats","resetPerfStats"];constructor(){}mount(){this.mounted||(this.mounted=!0,this.disableTransitions(),this.hideBodyForHydration(!0),xn.bootstrap(),this.scheduleHydrationReveal(),this.enableSPANavigation())}boundPublicApi=null;createComponentRuntime(t){if(null===this.boundPublicApi){let t={};for(let n of e.PUBLIC_METHODS){let e=this[n];"function"==typeof e?t[n]=e.bind(this):void 0!==e&&(t[n]=e)}this.boundPublicApi=t}return Object.assign({},this.boundPublicApi,t)}createContext(e){return At(e)}enablePerf(){Z.setPerfEnabled(!0)}disablePerf(){Z.setPerfEnabled(!1)}getPerfStats(){return Z.getPerfStats()}resetPerfStats(){Z.resetPerfStats()}disableTransitions(){if(document.getElementById("pp-disable-transitions"))return;let e=document.createElement("style");e.id="pp-disable-transitions",e.textContent="\n *, *::before, *::after {\n transition: none !important;\n animation: none !important;\n }\n ",document.head.insertBefore(e,document.head.firstChild)}enableTransitions(){let e=document.getElementById("pp-disable-transitions");e&&e.remove()}requestFrame(e){return"function"==typeof requestAnimationFrame?requestAnimationFrame(e):window.setTimeout(()=>e(performance.now()),16)}cancelFrame(e){"function"!=typeof cancelAnimationFrame?window.clearTimeout(e):cancelAnimationFrame(e)}cancelScheduledHydrationReveal(){null!==this.pendingRevealFrame&&(this.cancelFrame(this.pendingRevealFrame),this.pendingRevealFrame=null),null!==this.pendingTransitionUnlockFrame&&(this.cancelFrame(this.pendingTransitionUnlockFrame),this.pendingTransitionUnlockFrame=null)}cancelPendingProgrammaticScrollPersistence(){null!==this.pendingProgrammaticScrollPersistenceTimer&&(window.clearTimeout(this.pendingProgrammaticScrollPersistenceTimer),this.pendingProgrammaticScrollPersistenceTimer=null)}beginProgrammaticScrollPersistencePause(){this.suppressTrackedScrollPersistence=!0,this.cancelPendingHistoryStateSave(),this.cancelPendingProgrammaticScrollPersistence()}scheduleProgrammaticScrollPersistence(){this.suppressTrackedScrollPersistence&&(this.cancelPendingProgrammaticScrollPersistence(),this.pendingProgrammaticScrollPersistenceTimer=window.setTimeout(()=>{this.pendingProgrammaticScrollPersistenceTimer=null,this.suppressTrackedScrollPersistence=!1,this.persistCurrentHistoryScrollState()},this.PROGRAMMATIC_SCROLL_SETTLE_MS))}scrollElementIntoView(e){this.beginProgrammaticScrollPersistencePause(),e.scrollIntoView({behavior:"smooth"}),this.scheduleProgrammaticScrollPersistence()}normalizeHydrationBodySnapshotStyle(e){if(null===e)return null;let t=document.createElement("div");t.setAttribute("style",e),"0"===t.style.opacity&&t.style.removeProperty("opacity"),"none"===t.style.pointerEvents&&t.style.removeProperty("pointer-events"),"none"===t.style.userSelect&&t.style.removeProperty("user-select"),t.style.transition.replace(/\s+/g," ").trim().toLowerCase()===yn&&t.style.removeProperty("transition");let n=t.getAttribute("style")?.trim()??"";return""===n?null:n}hideBodyForHydration(e=!1){if(!this.hydrationBodySnapshot){let t=document.body.getAttribute("style");this.hydrationBodySnapshot={style:e?this.normalizeHydrationBodySnapshotStyle(t):t,hadAriaBusy:document.body.hasAttribute("aria-busy"),ariaBusy:document.body.getAttribute("aria-busy"),hadInert:document.body.hasAttribute("inert"),inert:document.body.getAttribute("inert")}}document.body.style.opacity="0",document.body.style.pointerEvents="none",document.body.style.userSelect="none",document.body.setAttribute("aria-busy","true"),document.body.setAttribute("inert","")}scheduleHydrationReveal(e){this.cancelScheduledHydrationReveal(),this.pendingRevealFrame=this.requestFrame(()=>{this.pendingRevealFrame=null,this.restoreBodyAccessibility(),e?.(),this.pendingTransitionUnlockFrame=this.requestFrame(()=>{this.pendingTransitionUnlockFrame=null,this.enableTransitions()})})}restoreBodyAccessibility(){let e=this.hydrationBodySnapshot;if(!e)return document.body.style.removeProperty("transition"),document.body.style.removeProperty("opacity"),document.body.style.removeProperty("pointer-events"),document.body.style.removeProperty("user-select"),document.body.removeAttribute("inert"),void document.body.removeAttribute("aria-busy");null===e.style?document.body.removeAttribute("style"):document.body.setAttribute("style",e.style),e.hadInert?document.body.setAttribute("inert",e.inert??""):document.body.removeAttribute("inert"),e.hadAriaBusy?document.body.setAttribute("aria-busy",e.ariaBusy??""):document.body.removeAttribute("aria-busy"),this.hydrationBodySnapshot=null}static getInstance(){if(!this.instance){this.instance=new e;try{"1"===localStorage.getItem("pp-perf")&&Z.setPerfEnabled(!0)}catch{}}return this.instance}enableSPANavigation(){this.navigationEnabled||(this.navigationEnabled=!0,this.boundHandleLinkClick=this.handleLinkClick.bind(this),this.boundHandlePopState=this.handlePopState.bind(this),this.boundHandleTrackedScroll=this.handleTrackedScroll.bind(this),"scrollRestoration"in history&&(this.previousHistoryScrollRestoration=history.scrollRestoration,history.scrollRestoration="manual"),document.addEventListener("click",this.boundHandleLinkClick),window.addEventListener("popstate",this.boundHandlePopState),document.addEventListener("scroll",this.boundHandleTrackedScroll,!0),window.addEventListener("scroll",this.boundHandleTrackedScroll,{passive:!0}),this.registerInitiallyScrolledElements(),this.persistCurrentHistoryScrollState())}handleLinkClick(e){if(!this.navigationEnabled)return;let t=this.getNavigationTarget(e.target);if(!t)return;let n=t.closest("a");if(n&&n.href)try{let t=new URL(n.href),r=t.origin!==window.location.origin,i=t.pathname===window.location.pathname&&t.search===window.location.search,l="false"===n.getAttribute("pp-spa");if(r||"_blank"===n.target||n.hasAttribute("download")||l||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;if(e.preventDefault(),i){let n=t.hash;if(n){e.preventDefault(),this.persistCurrentHistoryScrollState(),history.pushState(this.buildHistoryState(),"",t.pathname+t.search+n);let r=document.querySelector(n);return void(r&&this.scrollElementIntoView(r))}}this.navigateTo(t.pathname+t.search+t.hash)}catch(e){console.error("Link click navigation error:",e)}}getNavigationTarget(e){return e instanceof Element?e:e instanceof Node?e.parentElement:null}handleTrackedScroll(e){if(!this.navigationEnabled||this.isNavigating)return;if(e.target instanceof HTMLElement&&this.trackedScrollElements.add(e.target),this.suppressTrackedScrollPersistence)return void this.scheduleProgrammaticScrollPersistence();let t=Date.now()-this.lastHistoryStateSaveAt;if(t>=this.TRACKED_SCROLL_PERSISTENCE_INTERVAL_MS)return this.cancelPendingHistoryStateSave(),void this.persistCurrentHistoryScrollState();null===this.pendingHistoryStateSaveTimer&&(this.pendingHistoryStateSaveTimer=window.setTimeout(()=>{this.pendingHistoryStateSaveTimer=null,this.persistCurrentHistoryScrollState()},this.TRACKED_SCROLL_PERSISTENCE_INTERVAL_MS-t))}async handlePopState(e){let t=this.getCurrentUrl(),n=this.getScrollPositionsFromHistoryState(e.state);await this.navigateTo(t,!1,n)}async navigateTo(e,t=!0,n=null){this.cancelPendingHistoryStateSave(),this.cancelPendingProgrammaticScrollPersistence(),this.suppressTrackedScrollPersistence=!1,this.isNavigating=!0;try{this.dispatchNavigationEvent("start",e),await this.showLoadingTransition();let r=await this.fetchPageContent(e);if("hardReload"in r)return void(window.location.href=r.hardReload);if("redirect"in r)return void await this.navigateTo(r.redirect,t,n);let i=r,l=t?this.saveScrollPositions():null;this.updateBrowserHistory(e,t,l);let o=this.getResetScrollConfig(i);await this.updatePageContent(i),this.resetGlobalCaches(),xn.bootstrap(),await this.handleScrollRestoration(t?l:n,o,t?"push":"history"),await this.handleNavigationCompletion(),this.dispatchNavigationEvent("complete",e)}catch(t){this.handleNavigationError(e,t)}finally{this.isNavigating=!1}}resetGlobalCaches(){x.clear(),G.clearCaches(),Ie.clearCache()}getResetScrollConfig(e){if("true"===e.body.getAttribute(this.RESET_SCROLL_ATTR))return{mode:"global",resetElementKeys:new Set,resetWindow:!1};let t=e.querySelectorAll(`[${this.RESET_SCROLL_ATTR}]`),n=new Set,r=!1;if(t.length>0)for(let e of Array.from(t))"true"===e.getAttribute(this.RESET_SCROLL_ATTR)&&(n.add(this.getElementKey(e)),r=!0);return{mode:"none",resetElementKeys:n,resetWindow:r}}handleScrollRestoration(e,t,n){let r=()=>{if("global"===t.mode)return window.scrollTo(0,0),document.documentElement.scrollTop=0,document.documentElement.scrollLeft=0,void this.getTrackedScrollElements().forEach(e=>{(e.scrollTop||e.scrollLeft)&&(e.scrollTop=0,e.scrollLeft=0)});if("history"!==n||t.resetWindow||!e?.window)window.scrollTo(0,0),document.documentElement.scrollTop=0,document.documentElement.scrollLeft=0;else{let t=e?.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop)}new Set([...Object.keys(e??{}).filter(e=>"window"!==e),...t.resetElementKeys]).forEach(n=>{let r=this.findScrollElementByKey(n);if(!r)return;this.trackedScrollElements.add(r);let i=e?.[n];t.resetElementKeys.has(n)?(r.scrollTop=0,r.scrollLeft=0):i&&(r.scrollTop=i.scrollTop,r.scrollLeft=i.scrollLeft)}),document.querySelectorAll(`[${this.RESET_SCROLL_ATTR}="true"]`).forEach(e=>{e.scrollTop=0,e.scrollLeft=0,this.trackedScrollElements.add(e)})};return r(),new Promise(e=>{requestAnimationFrame(()=>{r(),requestAnimationFrame(()=>{r(),e()})})})}saveScrollPositions(){let e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return this.didInitialScrollDiscovery||this.registerInitiallyScrolledElements(),this.getTrackedScrollElements().forEach(t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})}),e}getElementKey(e){return e.getAttribute(this.SCROLL_KEY_ATTR)||e.id||e.className||e.tagName}registerInitiallyScrolledElements(){this.didInitialScrollDiscovery=!0,document.querySelectorAll("*").forEach(e=>{(e.scrollTop||e.scrollLeft||e.hasAttribute(this.SCROLL_KEY_ATTR)||e.hasAttribute(this.RESET_SCROLL_ATTR))&&this.trackedScrollElements.add(e)})}getTrackedScrollElements(){let e=[];return this.trackedScrollElements.forEach(t=>{t.isConnected?e.push(t):this.trackedScrollElements.delete(t)}),document.querySelectorAll(`[${this.SCROLL_KEY_ATTR}], [${this.RESET_SCROLL_ATTR}]`).forEach(t=>{this.trackedScrollElements.has(t)||(this.trackedScrollElements.add(t),e.push(t))}),e}findScrollElementByKey(e){for(let t of this.getTrackedScrollElements())if(this.getElementKey(t)===e)return t;let t=document.getElementById(e);if(t)return t;let n=document.getElementsByClassName(e)[0];if(n instanceof HTMLElement)return n;let r=document.getElementsByTagName(e)[0];return r instanceof HTMLElement?r:null}cancelPendingHistoryStateSave(){null!==this.pendingHistoryStateSaveTimer&&(window.clearTimeout(this.pendingHistoryStateSaveTimer),this.pendingHistoryStateSaveTimer=null)}buildHistoryState(e){let t=history.state,n=t&&"object"==typeof t&&!Array.isArray(t)?{...t}:{};return e?n[this.HISTORY_SCROLL_STATE_KEY]=e:delete n[this.HISTORY_SCROLL_STATE_KEY],n}getScrollPositionsFromHistoryState(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e[this.HISTORY_SCROLL_STATE_KEY];return!t||"object"!=typeof t||Array.isArray(t)?null:t}persistCurrentHistoryScrollState(e=this.saveScrollPositions()){this.lastHistoryStateSaveAt=Date.now(),history.replaceState(this.buildHistoryState(e),"",this.getCurrentUrl())}getCurrentUrl(){return window.location.pathname+window.location.search+window.location.hash}teardownCurrentPageComponents(){x.destroyAll()}dispatchNavigationEvent(e,t,n){let r=`pp:navigation:${e}`,i=n?{url:t,error:n}:{url:t};document.dispatchEvent(new CustomEvent(r,{detail:i}))}async showLoadingTransition(){let e=document.getElementById("loading-file-1B87E");if(e){let t=this.findLoadingElement(e,window.location.pathname);if(t)return void await this.updateContentWithTransition(t)}let t=document.querySelector("[pp-loading-content='true']")||document.body;t&&!("startViewTransition"in document)&&await this.fadeOut(t,250)}async fetchPageContent(e){let t,n=new URL(e,window.location.origin).hash,r=new AbortController,i=window.setTimeout(()=>{r.abort()},bn);try{t=await fetch(e,{signal:r.signal,headers:{"X-Requested-With":"XMLHttpRequest","X-PP-Navigation":"true","X-PulsePoint-Wire":"true",Accept:"text/html"}})}catch(n){throw n instanceof Error&&"AbortError"===n.name?Error(`Navigation timed out after ${Math.round(bn/1e3)}s: ${e}`):n}finally{window.clearTimeout(i)}if(!t.ok)throw Error(`Navigation failed: ${t.status} ${t.statusText}`);let l=t.headers.get("X-PP-Root-Layout"),o=document.querySelector('meta[name="pp-root-layout"]'),s=o?o.getAttribute("content"):null;if(l&&s&&l!==s)return{hardReload:e};if(t.redirected){let r=pn(t.url);if(!r)return{hardReload:e};let i=new URL(r,window.location.origin);if(n&&i.searchParams.has("next")){let e=i.searchParams.get("next");e&&!e.includes("#")&&i.searchParams.set("next",e+n)}return{redirect:i.pathname+i.search+i.hash}}let a=mn(t);if(a)return{redirect:a};let u=await t.text();return(new DOMParser).parseFromString(u,"text/html")}updateBrowserHistory(e,t,n=null){t&&(this.persistCurrentHistoryScrollState(n??void 0),history.pushState(this.buildHistoryState(),"",e))}async updatePageContent(e){e.title&&(document.title=e.title),this.syncManagedHead(e);let t=e.body;this.syncBodyAttributes(t),this.teardownCurrentPageComponents(),document.body.innerHTML=t.innerHTML}syncManagedHead(e){let t="[data-pp-meta]";document.head.querySelectorAll(t).forEach(e=>e.parentNode?.removeChild(e)),e.head&&e.head.querySelectorAll(t).forEach(e=>{document.head.appendChild(document.importNode(e,!0))})}syncBodyAttributes(e){e&&(Array.from(document.body.attributes).forEach(e=>{"style"!==e.name&&document.body.removeAttribute(e.name)}),Array.from(e.attributes).forEach(e=>{"style"!==e.name&&document.body.setAttribute(e.name,e.value)}))}async handleNavigationCompletion(){let e=window.location.hash;if(!e)return;let t=document.querySelector(e);t&&this.scrollElementIntoView(t)}handleNavigationError(e,t){console.error("Navigation error:",t),this.restoreBodyAccessibility(),this.enableTransitions(),this.dispatchNavigationEvent("error",e,t),window.location.href=e}findLoadingElement(e,t){let n=t;for(;;){let t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;let r=n.lastIndexOf("/");n=r<=0?"/":n.substring(0,r)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){let t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;let{fadeIn:n,fadeOut:r}=this.parseTransition(e);await this.fadeOut(t,r),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250,r=e.querySelector("[pp-loading-transition]")?.getAttribute("pp-loading-transition");if(r){let e=JSON.parse(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON -> default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise(n=>{e.style.transition=`opacity ${t}ms ease-out`,setTimeout(()=>{e.style.transition="",n()},t)})}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,setTimeout(()=>{e.style.transition=""},t)}parseTime(e){if("number"==typeof e)return e;let t=e.match(/^(\d+)(ms|s|m)?$/);if(t){let e=parseInt(t[1],10),n=t[2];return"s"===n?1e3*e:"m"===n?60*e*1e3:e}return 0}async redirect(e){if(e)try{let t=new URL(e,window.location.origin);t.origin===window.location.origin&&this.navigationEnabled?await this.navigateTo(t.pathname+t.search+t.hash):window.location.href=e}catch(e){console.error("Redirect error:",e)}}async rpc(e,t={},n=!1){return this.rpcClient.call(e,t,n)}socket(e,t={},n={}){return this.socketClient.connect(e,t,n)}};fn("pp",{getInstance:()=>Sn.getInstance()},typeof window<"u"?window:globalThis,!0,{cache:!0,configurable:!0,resetOnNull:!0});export{xn as ComponentInit,Sn as PPUtilities};