wcstack 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/package.json +1 -1
package/dist/auto.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n,s=Symbol.for("wcstack.binder"),r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");const a=".",l="*",c=128,u=128,d="#",h="|",f="prevent",p="stop",m="ro",g="init",y="sync",b="else",w="...",v="on",_="eventToken",$="command",S="class",x="attr",P="style",N={};for(let t=0;t<c;t++)N[`$${t+1}`]=t;const k=Object.freeze(N),I="$connectedCallback",A="$disconnectedCallback",E="$updatedCallback",C="$errorCallback",T="$stateReadyCallback",M="$bindables",O="$commands",L="$commandTokens",R="$command",j="$eventTokens",D="$on",W="$streams",z="$watch",B="$scan",F="$recursion",H="**",q="$listKeys",U="$streamStatus",G="$streamError",V="data-wc-definition",K=/\{\{\s*(.+?)\s*\}\}/g,J=new Set(["SCRIPT","STYLE"]);function Q(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&J.has(t.parentElement.tagName)||X(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),Q(e.content)}else Q(t.content)}function X(t){const e=t.data;if(K.lastIndex=0,!K.test(e))return;K.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=K.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}function Y(t){throw new Error(`[@wcstack/state] ${t}`)}const Z=new Map;let tt=0;function et(t){let e=Z.get(t);return void 0!==e||(-1!==t.indexOf(H)&&Y(`[wcs/recursion-unsupported] "${t}" uses "${H}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`),e=Object.freeze(new nt(t)),Z.set(t,e)),e}class nt{id=++tt;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:et(e),n=t.split("."),o=[],s=[],r=[],i={},a=[],c=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===l&&(r.push(h),i[h]=p,a.push(e(h)),c.push(f),u.push(e(f)),d.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=u,this.wildcardParentPathInfoSet=new Set(u),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}}function ot(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function st(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=ot(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const rt=" Validate statically: npx @wcstack/lint <file>.",it=new Set(["if","elseif","else","for"]),at={not:()=>t=>!t},lt={input:new Map,output:new Map},ct={input:new Map,output:new Map},ut=new Map;function dt(t,e,n){const o=lt[t],s=ct[t];for(const t of Object.keys(e)){o.set(t,e[t]);const r=n?.[t];void 0===r?s.delete(t):s.set(t,r)}ut.clear()}function ht(t,e,n,o=e){const s=`${t}${JSON.stringify(o)}:${n}`,r=ut.get(s);if(void 0!==r)return r;const i=lt[n].get(t)??at[t];void 0===i&&Y(`[wcs/filter-unknown] filter not found: ${t}.${st(t,function(t){return[...new Set([...Object.keys(at),...lt[t].keys()])]}(n))}${rt}`);const a=ct[n].get(t);void 0!==a&&(e.length<a[0]||e.length>a[1])&&Y(e.length<a[0]?`[wcs/filter-arity] filter "${t}" requires at least ${a[0]} argument(s) (${e.length} given).${rt}`:`[wcs/filter-arity] filter "${t}" accepts at most ${a[1]} argument(s) (${e.length} given).${rt}`);const l=i(e,o);return ut.set(s,l),l}function ft(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const pt=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function mt(t,e){return e?t:"true"===t||"false"!==t&&("null"===t?null:pt.test(t)?Number(t):t)}function gt(t){const e=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const t=ft(o,i,a);e.push(t),n.push(mt(t,r)),o="",r=!1,i=-1,a=-1};for(let e=0;e<t.length;e++){const n=t[e];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&Y(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${t})". Close the quote.${rt}`);const c=ft(o,i,a);return(c||r)&&(e.push(c),n.push(mt(c,r))),{args:e,literals:n}}function yt(t,e){return t.map(e=>{const n=e.indexOf("("),o=e.lastIndexOf(")");-1!==n&&-1===o&&Y(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==o&&-1===n&&Y(`Invalid filter format: missing opening parenthesis in "${e}"`);const s=(-1===n?e:e.substring(0,n)).trim();return 0===s.length&&Y(`[wcs/binding-syntax] an empty filter in "${t.join("|")}" — remove the extra "|" or name the filter.${rt}`),-1===n?{filterName:s,args:[],literals:[]}:{filterName:s,...gt(e.substring(n+1,o))}})}const bt=t=>t.trim(),wt=t=>"'"===t||'"'===t;function vt(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(null!==n)s===n&&(n=null);else if(wt(s))n=s;else if(s===e)return o}return-1}function _t(t,e){const n=[];let o=null,s=0;for(let r=0;r<t.length;r++){const i=t[r];null!==o?i===o&&(o=null):wt(i)?o=i:i===e&&(n.push(t.slice(s,r)),s=r+1)}return n.push(t.slice(s)),n}const $t=new Map;function St(t){const e=vt(t,h);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),$t.has(s)?r=$t.get(s):(o=_t(s,h).map(bt),r=yt(o),$t.set(s,r))):n=t.trim();const i=n.split(d).map(bt);i.length>2&&Y(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${d}" — write "${i[0]}${d}${i.slice(1).join(",")}".${rt}`);const[l,c]=i,u=l.split(a).map(bt);return{propName:l,propSegments:u,propModifiers:c?c.split(",").map(bt):[],inFilters:r}}const xt=new Map;function Pt(t){const e=vt(t,h);let n="",o=[],s="",r=[];return-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),xt.has(s)?r=xt.get(s):(o=_t(s,h).map(bt),r=yt(o),xt.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&Y(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`),{statePathName:n,statePathInfo:et(n),outFilters:r}}const Nt=new Set([b,"if","elseif","for",w]);function kt(t){const[...e]=function(t){return _t(t,";")}(t).map(bt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&Y(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim(),s=n.split(d)[0].split(h)[0].trim();if(s!==n&&Nt.has(s)&&Y(`[wcs/binding-syntax] "${t}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${rt}`),n===b){o.length>0&&Y(`[wcs/binding-syntax] "${t}": "else" takes no value — write "else:".${rt}`);const e=et("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===w){const e=Pt(o);return e.outFilters.length>0&&Y(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&Y(`Invalid spread binding "${t}": spread target path is required.`),{propName:w,propSegments:[w],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...Pt(o),bindingType:n};if("radio"===s||"checkbox"===s){const t=Pt(o);return{...St(n),...t,bindingType:s}}{const t=Pt(o),e=St(n);return e.propSegments[0]===_||e.propSegments[0].startsWith(v)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>it.has(t.bindingType))&&Y(`[wcs/template-syntax] Invalid bindText: "${t}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${rt}`),n}const It=new WeakMap,At=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Et=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Ct(t){const e=It.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Et.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return At.has(r)?(It.set(t,s[2]),s[2]):null}function Tt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...Pt(t),bindingType:"text"}}const Mt=new WeakMap,Ot=new WeakSet;let Lt=0;async function Rt(t){const e=function(t){let e,n=Mt.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++Lt,promise:o,resolve:e},Mt.set(t,n),Ot.has(t)&&n.resolve(),n}(t);await e.promise}function jt(t){const e=Mt.get(t);void 0===e?Ot.add(t):e.resolve()}const Dt=new WeakMap;function Wt(t){const e=Dt.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{Dt.set(t,n)}}function zt(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function Bt(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return zt(e);if(void 0!==n)return zt(n)}return zt(globalThis.customElements)}function Ft(t,e){t.upgrade?.(e)}function Ht(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=Vt(s.properties,qt);if(null===r)return null;const i=void 0===s.inputs?new Map:Vt(s.inputs,Ut);if(null===i)return null;const a=void 0===s.commands?new Map:Vt(s.commands,Gt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function qt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function Ut(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function Gt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function Vt(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function Kt(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:et(n),inFilters:[],outFilters:[],bindingType:"prop"}}function Jt(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function Qt(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&Y("Spread binding requires an element node.");const e=t,o=Wt(e);null===o&&Y(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=Bt(e);if(null===a&&Y(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||Y(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Ft(a,e);const l=Ht(e);null===l&&Y(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=Kt(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=Kt(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=Jt(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=Jt(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function Xt(t,e){let n=t;for(let t=0;t<e.length;t++){let o=e[t];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function Yt(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o];n.push({filterName:s.filterName,args:s.args,filterFn:ht(s.filterName,s.args,e,s.literals??s.args)})}return n}const Zt=new WeakMap;function te(t){return Zt.get(t)||null}function ee(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function ne(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!ee(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function oe(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function se(t){const e=[],n=ne(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Ct(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&oe(t,n)||e.push(t)}return e}const re=new WeakSet;function ie(t,e,n,o){const s=Qt(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Wt(t):null;return null===n&&Y("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}re.add(t);const r=function(t,e){const n=[];for(const o of e){const e=Yt(o.inFilters,"input"),s=Yt(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:t});else{const r=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:r})}}return n}(t,function(t,e){return void 0===e?t:t.map(t=>null!=t.uuid?t:e(t))}(s,o));return function(t,e){Zt.set(t,e)}(t,r),jt(t),{bindings:r,deferred:null}}function ae(t,e){const n=se(t),o=[],s=[];for(const t of n){if(re.has(t))continue;const n=ie(t,ra(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function le(t){re.add(t)}function ce(t){const{node:e,parseResults:n,transform:o}=t;return function(t){re.delete(t)}(e),ie(e,n,{allowDeferred:!1},o).bindings}const ue=new WeakMap;let de=null;function he(t){let e=t;for(;e;){const t=ue.get(e);if(t)return t;let n=e.parentNode;null===n&&null!==de&&e instanceof ShadowRoot&&(n=de(e)),e=n}return null}function fe(t,e){null!==e?ue.set(t,e):ue.delete(t)}let pe=null;const me=new WeakMap;function ge(t){return me.get(t)??[]}function ye(t,e){me.set(t,e)}function be(t){return me.has(t)}const we=new WeakMap;let ve=null,_e=0;function $e(t){return we.get(t)??[]}function Se(t,e){null===ve?we.set(t,e):ve.set(t,e)}function xe(){_e++,null===ve&&(ve=new Map)}function Pe(){if(0!==_e&&(_e--,!(_e>0||null===ve))){for(const[t,e]of ve)we.set(t,e);ve=null}}function Ne(t){return(ve?.has(t)??!1)||we.has(t)}const ke=Symbol("$$setLoopContext"),Ie=Symbol("$$getByAddress"),Ae=Symbol("$$hasByAddress"),Ee=Symbol("$$setByAddress"),Ce=Symbol("$$connectedCallback"),Te=Symbol("$$disconnectedCallback"),Me=Symbol("$$updatedCallback"),Oe=Symbol("$$errorCallback"),Le=new WeakMap,Re=new WeakMap;class je{absolutePathInfo;listIndex;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}}function De(t,e){if(null===e){let e=Re.get(t);return void 0!==e||(e=new je(t,null),Re.set(t,e)),e}{let n=Le.get(e);void 0===n&&(n=new WeakMap,Le.set(e,n));let o=n.get(t);return void 0!==o||(o=new je(t,e),n.set(t,o)),o}}const We=new WeakMap;function ze(t,e){let n=We.get(t);void 0===n&&(n=new Map,We.set(t,n));let o=n.get(e);return void 0===o&&(o=Object.freeze(new Be(t,e)),n.set(e,o)),o}class Be{pathInfo;stateElement;constructor(t,e){this.pathInfo=e,this.stateElement=t}}function Fe(t,e){return De(ze(t,e.pathInfo),e.listIndex)}function He(t,e,n){return De(ze(t,e),n)}const qe=new WeakMap;function Ue(t,e){null===e?qe.delete(t):qe.set(t,e)}function Ge(t){return qe.get(t)||null}const Ve=new Map;function Ke(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=Ve.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Ve.set(s,r)),r}function Je(t,e,n){return e<0||e>=n?null:t.at(e-n)}function Qe(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const Xe=new WeakMap;function Ye(t){const e=he(t.node);if(null===e)return null;let n=Xe.get(e);if(void 0===n)n=new WeakMap,Xe.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Ke(e.pathInfo,t.statePathInfo);return n>0&&(o=Je(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const Ze=new WeakMap;function tn(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Ge(n);null===e?Y(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function en(t,e){let n=null;if(n=Ze.get(t)||null,null!==n)return n;const o=tn(t,e),s=Ye(t),r=Xi(o);return null===r&&Y("No state tree found on this root for binding."),n=He(r,t.statePathInfo,s),Ze.set(t,n),n}function nn(t){Ze.delete(t)}const on=new WeakMap;function sn(t,e){const n=on.get(t);void 0===n?on.set(t,e):n instanceof Set?n.add(e):n!==e&&on.set(t,new Set([n,e])),null!==pe&&pe({type:"state:binding-added",absoluteAddress:t,binding:e})}function rn(t,e){const n=on.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&on.delete(t),null!==pe&&pe({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const an=new WeakMap;function ln(t){const e=on.get(t);return void 0!==e?e:null!==t.listIndex?an.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const cn=new WeakMap,un=new WeakMap;class dn{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=hn(t,e)}}function hn(t,e){if(null===e){let e=un.get(t);return void 0!==e||(e=new dn(t,null),un.set(t,e)),e}{let n=cn.get(e);void 0===n&&(n=new WeakMap,cn.set(e,n));let o=n.get(t);return void 0!==o||(o=new dn(t,e),n.set(t,o)),o}}const fn=new WeakMap;function pn(t){let e=null;if(e=fn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=Ye(t);null===n&&Y(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=hn(t.statePathInfo,n)}else e=hn(t.statePathInfo,null);return fn.set(t,e),e}function mn(t){fn.delete(t)}function gn(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const yn=new Map,bn=gn();function wn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function vn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}function _n(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function $n(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)_n(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class Sn{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)e.push(n(...t));return e}}class xn extends Sn{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==pe&&pe({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const Pn=new WeakMap;function Nn(t,e){let n=Pn.get(t);void 0===n&&(n=new Map,Pn.set(t,n));let o=n.get(e);return void 0===o&&(o=new xn(e,t),n.set(e,o)),o}const kn=new WeakMap;class In extends Sn{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==pe&&pe({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function An(t){return t instanceof In}const En=new Map,Cn=gn();function Tn(t){const e=t.propModifiers.filter(t=>t===f||t===p).sort().join(",");return`${t.statePathName}::${e}`}function Mn(t){if(!t.propName.startsWith(v))return!1;const e=Tn(t);let n=En.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(f)&&o.preventDefault(),e.includes(p)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=Xi(r);null===i&&Y("No state tree found on this root for event handler.");const a=he(s),l=t.startsWith(R+".");i.createStateAsync("writable",async e=>{const c=e[ke](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const t=i.addressHooks;if(t){const e=t.handlerScope;for(let t=0;t<e.length;t++)c=e[t](i,s,r,a,c)}}const u=null!==a?Qe(a.listIndex,c):[];if(l){const s=e[Ie](hn(n,null));return An(s)||Y(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...u)}const d=e[t];return"function"!=typeof d&&Y(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});$n(c,`"${t}"`)})})(t.statePathName,t.propModifiers,t.statePathInfo),En.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),Cn.add(e,t),!0}function On(t){if(!t.propName.startsWith(v))return!1;const e=Tn(t),n=En.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);return t.node.removeEventListener(o,n),0!==Cn.countOf(e)&&(Cn.remove(e,t)&&En.delete(e),!0)}const Ln=new Map,Rn=gn();function jn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Dn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}const Wn=new Set(["radio","checkbox"]),zn=new Set(["value","valueAsNumber","valueAsDate"]);function Bn(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(Wn.has(t)&&"checked"===e)return!0;if(zn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Wt(n);if(null!==s){const t=Bt(n)?.get(s);void 0===t&&Y(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Ht(n);if(o?.knownProperties.has(e))return!0}return!1}let Fn=1,Hn=1,qn=1;const Un=new WeakMap;function Gn(t,e,n){let o=Un.get(t);void 0===o&&(o=new Map,Un.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=Fn++,o.set(s,r)),r}function Vn(t,e){return"to-element"===e?2*t:2*t+1}const Kn=new Set;function Jn(t){return{transactionId:Hn++,originBindingId:t,visitedEdges:Kn,hop:0}}function Qn(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let Xn=null;function Yn(){return Xn}function Zn(t,e){const n=Xn;Xn=t;try{return e()}finally{Xn=n}}const to=[];let eo=!1;const no=new Map,oo=gn(),so=new WeakMap,ro=t=>t.detail,io=new WeakMap;function ao(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function lo(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Wt(t.node);if(null!==n){const o=Bt(t.node)?.get(n);void 0===o&&Y(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Ht(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}function co(t){if(null!==Wt(t.node)){const e=Ht(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??ro}return null}function uo(t){if(null===Wt(t.node))return!1;const e=Ht(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const ho=new WeakSet;function fo(t){ho.add(t)}function po(t){return!!ho.has(t)&&(ho.delete(t),!0)}const mo=new WeakMap;function go(t,e){const n=mo.get(t);return!(void 0===n||n<e||(n===e?mo.delete(t):mo.set(t,n-e),0))}const yo=new WeakSet;function bo(t){yo.add(t)}function wo(t){return!!yo.has(t)&&(yo.delete(t),!0)}let vo=0;function _o(){vo--}function $o(){return vo>0}class So{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const xo=new WeakMap;function Po(t){let e=xo.get(t);return void 0===e&&(e=new So(t),xo.set(t,e)),e}function No(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==g&&s!==y&&Y(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&Y(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function ko(t){return t.propModifiers.some(t=>t.includes("="))}const Io=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),Ao=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Eo(t,e){return"state"===t&&"call"===e?Io:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Co(t){if(!o.enableDirectionalInitialSync)return ko(t)&&Y("init=/sync= modifiers require enableDirectionalInitialSync."),Io;const e=null===(n=No(t,g))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:Y(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":Y(`Invalid sync modifier value "${t}".`)}(No(t,y));if("event"===t.bindingType)return null!==e&&"none"!==e&&Y("Event bindings only allow init=none."),"call"===s?Ao:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===$)return Eo("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&Y(`Binding type "${t.bindingType}" does not support init=${e}.`),Eo(e??"state",s);const r=Ht(t.node);if(null===r)return Eo(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||Y(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||Y(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||Y(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let To=0,Mo=0;const Oo=["active","disposed","failed"],Lo=new WeakMap,Ro=new WeakMap,jo=new WeakMap,Do=new WeakMap,Wo=new WeakMap;function zo(t,e){const n=Wo.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Wo.set(t,new Set([n,e]))):Wo.set(t,e)}function Bo(t){return Wo.has(t)}function Fo(t,e){const n=Wo.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Ho(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Ho(n,e)}function qo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class Uo{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.removedNodes;if(0===r.length||!go(s.target,r.length))for(let t=0;t<r.length;t++)e.push(r[t]);const i=s.addedNodes;for(let t=0;t<i.length;t++)n.push(i[t])}const o=[];for(const t of e)po(t)||Ho(t,t=>{Fo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)wo(t)&&!$o()||Ho(t,t=>{Fo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&Di(o)}}const Go=new WeakMap;function Vo(t){let e=Go.get(t);return void 0===e&&(e=new Uo(t),Go.set(t,e)),e}function Ko(t){const e=t.inFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|"),n=t.outFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function Jo(t,e,n){const o=Xi(tn(t,n));null===o&&Y("No state tree found on this root for binding.");const s=ze(o,t.statePathInfo);return function(t,e,n){let o=an.get(t);void 0===o&&(o=new WeakMap,an.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==pe&&pe({type:"state:binding-added",absoluteAddress:De(t,e),binding:n})}(s,e,t),s}function Qo(t,e){const n=en(t,e);return sn(n,t),n}function Xo(t,e,n,o){null!==e?rn(e,t):function(t,e,n){const o=an.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==pe&&pe({type:"state:binding-removed",absoluteAddress:De(t,e),binding:n}))}(n,o,t),mn(t),nn(t)}function Yo(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class Zo{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=this.rowOf(t),i=null===o?-1:o.bindings.indexOf(t);if(null!==o&&0===o.phases[i]){const e=o;this.observe(t.replaceNode),s.registerAddress&&null===e.addresses[i]&&null===e.patternPathInfos[i]&&(e.registered=!0,this.registerRowSlot(e,i));continue}const a=Ro.get(t);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(t,s,n),r.push(t)):(this.observe(a.anchor),s.registerAddress&&null===a.address&&null===a.patternListIndex&&(a.options.registerAddress=!0,this.registerAddress(a)),"active"===a.phase&&this.settleInitialRecord(a),this.settleConnectedSnapshot(a))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(qo(e)&&Vo(e),null===this.rowPlan)for(const n of t){const t=Ro.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return ko(t)&&Co(t),!0;const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0){if(!e.registered)return!0;if(2===e.phases[n])return!1;const t=e.plan.slots[n];return 1&e.flags[n]?"state"===t.authority||!t.policy.outputOnly:(e.flags[n]|=1,"state"===t.authority)}}const n=Ro.get(t);return void 0===n||n.session!==this||!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority))}getRecord(t){const e=this.rowOf(t),n=null===e?-1:e.bindings.indexOf(t);if(null!==e&&n>=0)return{id:64*e.id+n,info:t,generation:e.generation,phase:Oo[e.phases[n]],teardowns:null};const o=Ro.get(t);return o?.session===this?o:null}addTeardown(t,e){const n=Ro.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(Yo(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=Bt(t);null===s&&Y(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),zo(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Po(s).wait(e,()=>{if(a())try{Ft(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0)return void this.disposeRowSlot(e,n)}const n=Ro.get(t);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(t){for(let e=0;e<t.length;e++)this.disposeBinding(t[e]);if(!(this.rows.size>0))for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}destroyRow(t){const e=t.length>0?this.rowOf(t[0]):null;null!==e?(this.destroyRowRecord(e),this.rows.delete(e)):this.destroyRecords()}destroyRowRecord(t){for(let e=0;e<t.bindings.length;e++){const n=t.addresses[e];null!==n&&(rn(n,t.bindings[e]),t.addresses[e]=null),t.phases[e]=1}}dispose(){for(const t of Array.from(this.rows))for(let e=0;e<t.bindings.length;e++)this.disposeRowSlot(t,e);for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.rows)this.destroyRowRecord(t);this.rows.clear();for(const t of this.records)null!==t.address&&(rn(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.rows)for(let n=0;n<e.bindings.length;n++)0===e.phases[n]&&t(e.bindings[n].node);for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];for(const e of this.rows)for(let n=0;n<e.bindings.length;n++){if(0!==e.phases[n])continue;if(null===e.addresses[n]&&null===e.patternPathInfos[n])continue;const o=e.bindings[n];this.unregisterRowSlot(e,n),this.registerRowSlot(e,n),this.shouldApplyState(o)&&t.push(o)}for(const e of this.records){if("active"!==e.phase)continue;const n=e.info;if(null===e.address&&null===e.patternListIndex)continue;const o="for"===n.bindingType?en(n):null;if(Xo(n,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null,this.registerAddress(e),null!==o){const t=en(n);t!==o&&be(o)&&ye(t,ge(o)),t!==o&&Ne(o)&&Se(t,$e(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return qo(e)?e:null}(t);null!==e&&Vo(e)}handleMutations(t,e,n){for(const n of e)Ho(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Ho(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&Di(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Ro.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=Do.get(e);void 0===t&&(t=Ko(e),Do.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;zo(n,this);const o=this.knownMapFor(n);let s=Do.get(t);void 0===s&&(s=Ko(t),Do.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n=t.slots,o=e.length,s={id:++To,session:this,generation:++Mo,plan:t,bindings:e,registered:!1,phases:new Array(o).fill(0),flags:new Array(o).fill(0),addresses:new Array(o).fill(null),patternPathInfos:new Array(o).fill(null),patternListIndexes:new Array(o).fill(null)};this.rows.add(s);for(let t=0;t<o;t++){const o=e[t],r=o.replaceNode;if(zo(r,this),this.addKnownRowBinding(r,o,t),Lo.set(o,s),n[t].isEvent){try{Mn(o)}catch(e){throw s.phases[t]=2,e}s.flags[t]|=2}}}activatePlanRows(t,e,n){const o=e.length>0?this.rowOf(e[0]):null;if(null===o||o.bindings!==e){for(const t of e)this.initialize([t],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=t.slots;let r=!1;for(let t=0;t<e.length;t++)if(0===o.phases[t])null===o.addresses[t]&&null===o.patternPathInfos[t]&&this.registerRowSlot(o,t,n);else{if(r||(o.generation=++Mo,r=!0,this.rows.add(o)),o.phases[t]=0,o.flags[t]=0,s[t].isEvent){try{Mn(e[t])}catch(e){throw o.phases[t]=2,this.runRowSlotTeardowns(o,t),e}o.flags[t]|=2}this.registerRowSlot(o,t,n)}}rowOf(t){const e=Lo.get(t);return void 0!==e&&e.session===this?e:null}registerRowSlot(t,e,n){if(null!==t.addresses[e]||null!==t.patternPathInfos[e])return;const o=t.bindings[e],s=Ye(o);null!==s?(t.patternPathInfos[e]=Jo(o,s,n),t.patternListIndexes[e]=s):t.addresses[e]=Qo(o,n)}unregisterRowSlot(t,e){const n=t.addresses[e],o=t.patternPathInfos[e];null===n&&null===o||(Xo(t.bindings[e],n,o,t.patternListIndexes[e]),t.addresses[e]=null,t.patternPathInfos[e]=null,t.patternListIndexes[e]=null)}disposeRowSlot(t,e){if(1!==t.phases[e]){t.phases[e]=1,this.runRowSlotTeardowns(t,e);for(let e=0;e<t.phases.length;e++)if(0===t.phases[e])return;this.rows.delete(t)}}runRowSlotTeardowns(t,e){try{this.unregisterRowSlot(t,e)}catch{}if(2&t.flags[e]){t.flags[e]&=-3;try{On(t.bindings[e])}catch{}}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++To,info:t,generation:++Mo,phase:"discovered",teardowns:null,session:this,anchor:t.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Ro.set(t,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;Mn(e)?t.eventAttached=!0:e.propSegments[0]!==_?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=Dn(t),s=jn(t,o);let r=Ln.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const t of n)s=t.filterFn(s);const r=Xi(o.getRootNode());null===r&&Y("No state tree found on this root for two-way binding.");const i=he(o);r.createState("writable",t=>{t[ke](i,()=>{t[e]=s})})},Ln.set(s,r)),t.node.addEventListener(o,r),Rn.add(s,t),!0}var e,n;return!1}(e)&&Yo(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=Dn(t),n=jn(t,e),o=Ln.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Rn.countOf(n)&&(Rn.remove(n,t)&&Ln.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=vn(t),s=wn(t,o);let r=yn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const t of n)r=t.filterFn(r);const i=Xi(o.getRootNode());null===i&&Y("No state tree found on this root for two-way binding.");const a=he(o);i.createState("writable",t=>{t[ke](a,()=>{let n=t[e];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(t[e]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(t[e]=n.toSpliced(o,1))}else t[e]=s?[r]:[]})})},yn.set(s,r)),t.node.addEventListener(o,r),bn.add(s,t),!0}var e,n;return!1}(e)&&Yo(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=vn(t),n=wn(t,e),o=yn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==bn.countOf(n)&&(bn.remove(n,t)&&yn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&Bn(e.node,e.propName)&&-1===e.propModifiers.indexOf(m)){const n=function(t,e,n){let o=so.get(t);void 0===o&&(o=new Map,so.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&so.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});Yo(t,n)}!function(t){const e=Wt(t.node);if(null!==e){const n=Bt(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&Y(`CustomElementRegistry is unavailable for <${e}>.`))}if(Bn(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const e=lo(t),n=co(t),s=uo(t),r=ao(t,e,null!==n,s);let i=no.get(r);void 0===i&&(i=((t,e,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==ro||r||function(t,e,n){const o=t[e];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${e} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,e)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${e}" key while element.${e} is ${typeof o}`),null===s)return;let r=io.get(t);void 0===r&&(r=new Set,io.set(t,r)),r.has(e)||(r.add(e),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${t.tagName.toLowerCase()}> "${e}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${e}, or (e) => e.target.${e}) on that wcBindable property.`))}(a,t,l);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const t of n)c=t.filterFn(c);const u=so.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(o.enablePropagationContext){const n=Gn(a,t,e),s=function(t,e){for(let n=to.length-1;n>=0;n--){const o=to[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==pe&&pe({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Vn(n,"to-state"),node:a,member:t}));const r=Vn(n,"to-state"),i=Yn();if(null!==i&&i.visitedEdges.has(r))return void(null!==pe&&pe({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=Qn(i??Jn(n),r)}const h=Xi(a.getRootNode());null===h&&Y("No state tree found on this root for two-way binding.");const f=he(a),p=()=>{r&&(eo=!0);try{h.createState("writable",t=>{t[ke](f,()=>{t[e]=c})})}finally{r&&(eo=!1)}};null!==d?Zn(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),no.set(r,i)),t.node.addEventListener(e,i),oo.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==_)return!1;const e=t.node,n=Wt(e),o=Bt(e);if(null!==n&&void 0===o?.get(n))return null===o&&Y(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(kn.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||Y('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Wt(t)?null:Ht(t)}(e);null===r&&Y(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&Y(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${st(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,c=t.propModifiers,u=t=>{c.includes(f)&&t.preventDefault(),c.includes(p)&&t.stopPropagation();const n=Xi(e.getRootNode());null===n&&Y("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||Y(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${st(l,n.eventTokenNames)}${rt}`);const o=he(e);n.createStateAsync("writable",async e=>{$n(e[ke](o,()=>{const s=null!==o?Qe(o.listIndex,o.pathInfo.wildcardCount):[];return Nn(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,u),kn.set(t,{eventName:a,handler:u}),!0})(e)&&Yo(t,()=>function(t){if(t.propSegments[0]!==_)return!1;const e=kn.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),kn.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Wt(t.info.node);if(null===n)return void e();const o=Bt(t.info.node);if(null===o&&Y(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=Po(o).wait(n,()=>{if(this.isAlive(t,s))try{Ft(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});Yo(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Co(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=Xi(t.replaceNode.getRootNode());null===e&&Y("No state tree found on this root for binding.");const n=pn(t);let o=!1;return e.createState("readonly",t=>{o=t[Ae](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void vo++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,_o()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=Xi(t.node.getRootNode());null===o&&Y("No state tree found on this root for initial binding sync.");const s=he(t.node);o.createState("writable",e=>{e[ke](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=Ye(n);if(null!==o?(t.patternPathInfo=Jo(n,o,e),t.patternListIndex=o):t.address=Qo(n,e),!t.options.registerPathInfo)return;const s=Xi(n.replaceNode.getRootNode());null===s&&Y("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Ro.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,_o());const e=t.info;if(null!==t.address||null!==t.patternListIndex)try{Xo(e,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=Wt(t.node);if(null!==e){const n=Bt(t.node),o=n?.get(e);if(void 0===o)return}if(Bn(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const e=lo(t),n=ao(t,e,null!==co(t),uo(t)),o=no.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),oo.remove(n,t)&&no.delete(n)}}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{On(e)}catch{}}}}function ts(t){let e=jo.get(t);return void 0===e&&(e=new Zo(t),jo.set(t,e)),e}function es(t){return Ro.get(t)?.session??Lo.get(t)?.session??null}let ns=null;function os(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const ss=Object.freeze([]),rs=new WeakMap,is=new WeakMap;function as(t){return is.get(t)??[]}function ls(t,e){is.set(t,e)}const cs=new WeakMap;function us(t){return cs.get(t)??[]}function ds(t,e){cs.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let hs=0;function fs(){return`u${(hs++).toString(36)}`}let ps=0,ms=0;const gs=Symbol("wcs.listIndex.noValue");class ys{uuid=fs();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=gs,this._index=e,this._version=ps,this._chainGeneration=ms}get index(){return this._index}set index(t){this._index=t,this._version=++ps,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(t){this._value=t}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=ps),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===ms||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=ms),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++ps,ms++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function bs(t,e,n=t){return new ys(t,e,n)}function ws(t,e){t.reparent(e)}function vs(t){return t.homeParentListIndex}function _s(t,e){t.value=e}function $s(t,e){const n=t.value;return n!==gs&&n===e.value}const Ss=new WeakMap,xs=new WeakSet;function Ps(t){return xs.has(t)}function Ns(t){const e=Ss.get(t);return void 0===e?null:e}function ks(t,e){const n=Ss.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o){const t=function(t,e){const n=vs(t),o=t.parentListIndex;return null===n||n===o||xs.has(n)?function(t,e,n){return null!==t&&null!==n&&n!==e&&!!xs.has(t)&&!xs.has(n)&&n.position===t.position&&$s(n,t)}(n,o,e)||function(t,e){return t!==e&&null!==t&&null!==e&&t.position===e.position&&xs.has(t)&&!xs.has(e)}(o,e)?e:null:n}(o,e);if(null!==t)for(const e of n)ws(e,t)}return n}function Is(t,e){null!==e?Ss.set(t,e):Ss.delete(t)}const As=new WeakMap;function Es(t,e){null===e?As.delete(t):As.set(t,e)}function Cs(t){const e=As.get(t);e&&(e.dirty=!0)}const Ts=Symbol.for("wcstack.transition-runner");function Ms(t){const e=globalThis[Ts];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}function Os(t,e,n){const o=Ms(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const Ls=[],Rs=[];function js(t){Rs.includes(t)||Rs.push(t)}function Ds(t,e=0){const n=Ls.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Ls.push(o):Ls.splice(n,0,o)}function Ws(t){queueMicrotask(()=>{throw t})}const zs=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){for(let e=0;e<Rs.length;e++)Rs[e](t);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(t){const e=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(t),e&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){xe(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(t,e)})}hasQueuedPath(t,e){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===t&&n.absoluteAddress.absolutePathInfo.pathInfo.path===e)}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t,n=[]){const o=new Map,s=new Set;for(let e=0;e<t.length;e++){const n=t[e],r=o.get(n.absoluteAddress);null!==pe&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&pe({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let t=0;t<n.length;t++){const e=n[t];o.has(e)||o.set(e,null)}const r=[],i=new Map;o.forEach((t,e)=>{if(null!==t&&t.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,transactionId:t.transactionId,hop:t.hop,maxHops:32}),void(null!==pe&&pe({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop}));const n=ln(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(r.push(e),null!==t&&i.set(e,t));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==t&&i.set(n,t))});try{const t=()=>{i.size>0?Di(r,i):Di(r)};if(e()||0===r.length)t();else{const e=Os("state",t);void 0!==e&&e.catch(Ws)}}finally{Pe(),function(t){for(const e of Ls.slice())e.listener(t)}(s)}}};function Bs(){return zs}const Fs=new WeakMap,Hs=new WeakMap,qs=new WeakMap,Us=new WeakMap;let Gs=!1;const Vs=new WeakMap,Ks=new WeakMap,Js=new WeakMap,Qs=[];function Xs(t,e){const n=Ys(t);if(n.recorded.has(e))return;n.recorded.add(e);const o=et(e).cumulativePaths;if(o.length<2)return;let s=Js.get(t);void 0===s&&Js.set(t,s=new Map);for(let t=0;t<o.length-1;t++){let n=s.get(o[t]);void 0===n&&s.set(o[t],n=new Set),n.add(e)}}function Ys(t){let e=Fs.get(t);return void 0===e&&Fs.set(t,e={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),e}function Zs(t,e,n){let o=t.get(e);void 0===o&&t.set(e,o=new Set),o.add(n)}function tr(t,e,n){const o=t.get(e);o.delete(n),0===o.size&&t.delete(e)}function er(t,e,n,o){const s=function(t,e){let n=t.byPath.get(e);return void 0===n&&t.byPath.set(e,n=new Map),n}(t,e);let r=Hs.get(o);if(void 0===r&&Hs.set(o,r=new Map),r.has(e)){const t=r.get(e);return Object.is(t,n)||(tr(s,t,o),r.set(e,n),Zs(s,n,o)),!1}return r.set(e,n),Zs(s,n,o),!0}function nr(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function or(t,e,n,o,s,r){t.lastValue.set(e,n),s&&(null!==o.listIndex&&nr(qs,o.listIndex,r),null!==r.levelListIndex&&nr(Us,r.levelListIndex,r))}function sr(t,e,n,o,s){Gs=!0;const r=Ys(t);Xs(t,e),or(r,e,s,o,er(r,e,n,o),{stateElement:t,path:e,absAddress:o,levelListIndex:null})}function rr(t,e){Ys(t).tracked.add(e)}function ir(t,e,n){if("number"!=typeof e)return;const o=t.indexes[e];if(void 0!==o)for(const e of t.getters)n.push(Fe(t.stateElement,hn(e,o)))}function ar(t,e){if(void 0!==t)for(const n of t)e.push(n)}function lr(t,e,n,o,s){const r=Fs.get(t),i=r?.byPath.get(e),a=Vs.get(t)?.get(e);if(void 0===r||void 0===i&&void 0===a)return Qs;const l=r.lastValue.has(e),c=r.lastValue.get(e);r.lastValue.set(e,s);const u=[],d=!n||!Object.is(o,s),h=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&ar(i.get(o),u),h&&ar(i.get(c),u),d&&ar(i.get(s),u)),void 0!==a)for(const t of a)n&&ir(t,o,u),h&&ir(t,c,u),d&&ir(t,s,u);return u}function cr(t,e){let n=t;for(const t of e){if("object"!=typeof n||null===n)return;n=n[t]}return n}function ur(t,e,n){const o=Fs.get(t).byPath.get(e);if(void 0!==o)for(const t of o.values())ar(t,n);const s=Vs.get(t)?.get(e);if(void 0!==s)for(const t of s)for(let e=0;e<t.indexes.length;e++)ir(t,e,n)}function dr(t){const e=Us.get(t.levelListIndex),n=e.indexOf(t);e.splice(n,1)}function hr(t){if(!Gs)return;const e=qs.get(t);if(void 0!==e){qs.delete(t);for(const t of e){const{stateElement:e,path:n,absAddress:o}=t,s=Hs.get(o),r=s.get(n);s.delete(n),tr(Fs.get(e).byPath.get(n),r,o),null!==t.levelListIndex&&dr(t)}}}function fr(t,e,n){if(!Gs)return;const o=Us.get(t);if(void 0!==o)for(const{stateElement:t,path:s,absAddress:r}of o){const o=Fs.get(t),i=o.byPath.get(s);tr(i,e,r),Zs(i,n,r),Hs.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,e)||Object.is(a,n))&&(Cs(r),Bs().enqueueAbsoluteAddress(r,null))}}const pr=new WeakMap,mr=Object.freeze([]),gr=new Set;function yr(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:mr,s=Array.isArray(n)&&n.length>0?n:mr,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:mr,o=Array.isArray(e)&&e.length>0?e:mr;let s=pr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=ks(o,t)||[],a=i.length>0?vs(i[0]):t;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:gr,deleteIndexSet:new Set(i),addIndexSet:gr};let e=ks(s,t);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=bs(t,n,a);e.push(o)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:gr,deleteIndexSet:gr,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:gr,deleteIndexSet:gr,addIndexSet:gr};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],u=n.get(l),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=bs(t,o,a);e.push(n),c.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:c}}finally{void 0!==l&&(function(t,e,n){let o=pr.get(t);o||(o=new WeakMap,pr.set(t,o)),o.set(e,n)}(o,s,l),Is(s,l.newIndexes))}}(t,e,n);!function(t,e){for(let n=0;n<t.length;n++){if(t[n].index!==n){const e=t[n].index;t[n].index=n,fr(t[n],e,n)}_s(t[n],e[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:mr),function(t){for(const e of t)xs.add(e)}(o.deleteIndexSet);for(const t of o.deleteIndexSet)hr(t);return function(t){for(const e of t)xs.delete(e)}(o.newIndexes),function(t,e){if(!Gs||t===e)return;const n=Ks.get(t);if(void 0===n)return;Ks.delete(t);const o=Ks.get(e);Ks.set(e,void 0===o?n:o.concat(n));for(const o of n){o.indexes=e;const n=Ys(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=t[n],r=e[n];if(s!==r)for(const t of[s,r])if(void 0!==t&&!Ps(t))for(const e of o.getters){const n=Fe(o.stateElement,hn(e,t));Cs(n),Bs().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}const br=new WeakSet,wr=new WeakMap;function vr(t){return wr.get(t)??null}function _r(t,e){wr.set(t,e)}const $r=new WeakMap;function Sr(t){return $r.get(t)??[]}function xr(t,e){$r.set(t,e)}function Pr(t,e){const n=Sr(t);for(const t of n)fe(t,e)}const Nr=new WeakMap,kr=new WeakMap;function Ir(t,e){for(let n=0;n<t.length;n++)if(e.has(t[n]))return!0;return!1}function Ar(t,e,n){Pr(t,e);const o=as(t),s=vr(t);if(null!==s&&(s.activate(o,n.rootNode),null!==e&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(t){return Nr.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=kr.get(t);void 0===o&&kr.set(t,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=e.map((e,o)=>{const s=t.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=e.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const t of a){if("*"===t)return null;c+="."+t,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(t,e,o.pathInfo.path),i=s.stateElement.getterPaths;let a,l=!1;for(let t=0;t<e.length;t++){const c=e[t];if(!n.shouldApplyState(c))continue;const u=r[t];if(null===u||Ir(u.prefixes,i)){Ri(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[Ie](o),l=!0);const d=u.tail;let h=a;for(let t=0;t<d.length;t++){if(null==h){h=void 0;break}h=h[d[t]]}Li(c,s,h)}}(r,o,s,e,n)}for(const t of o)null===s&&sn(en(t),t),(null===s||s.shouldApplyState(t))&&Ri(t,n)}function Er(t){if(!t.mounted)return;const e=as(t),n=vr(t);for(let t=0;t<e.length;t++){const o=e[t];null!==n?n.disposeBinding(o):rn(en(o),o)}!function(t){const e=Sr(t);for(let t=0;t<e.length;t++)fe(e[t],null)}(t)}const Cr=new WeakMap,Tr=Object.freeze(new Set);function Mr(t,e){const n=Cr.get(t);n?n.add(e):Cr.set(t,new Set([e]))}function Or(t){const e=Cr.get(t);return void 0!==e?e:Tr}function Lr(t,e){const n=Cr.get(t);n&&(n.delete(e),0===n.size&&Cr.delete(t))}function Rr(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o];n.push({filterName:s.filterName,args:s.args,filterFn:ht(s.filterName,s.args,e,s.literals??s.args)})}return n}function jr(t){return{...t,inFilters:Rr(t.inFilters,"input"),outFilters:Rr(t.outFilters,"output")}}const Dr=new Set(["if","elseif","else","for"]);class Wr{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e;const n=[];for(let e=t.firstChild;null!==e;e=e.nextSibling)n.push(e);this._childNodeArray=n,this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(t){const e=this._childNodeArray;for(let n=0;n<e.length;n++){const o=e[n];bo(o),t.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){bo(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=vr(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRow(as(this));const e=this._childNodeArray;for(let t=0;t<e.length;t++){const n=e[t];null!==n.parentNode&&(fo(n),n.parentNode.removeChild(n))}const n=as(this);for(let t=0;t<n.length;t++){const e=n[t];Dr.has(e.bindingType)&&Or(e.node).forEach(t=>{t.tryDestroy()||t.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const t=vr(this);null!==t&&(t.isRowSession?t.disposeBindings(as(this)):t.dispose())}this._teardownBindings()}_teardownBindings(){const t=as(this);for(let e=0;e<t.length;e++){const n=t[e];Dr.has(n.bindingType)&&Or(n.node).forEach(t=>{t.unmount()}),mn(n),nn(n)}}unmount(){{const t=vr(this);null!==t&&(t.isRowSession?t.disposeBindings(as(this)):t.dispose())}for(const t of this._childNodeArray)null!==t.parentNode&&(fo(t),t.parentNode.removeChild(t));const t=as(this);for(let e=0;e<t.length;e++){const n=t[e];Dr.has(n.bindingType)&&Or(n.node).forEach(t=>{t.unmount()}),mn(n),nn(n)}this._mounted=!1}}function zr(t){const e=document.createDocumentFragment(),n=new Wr(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function Br(t){void 0!==t.uuid&&null!==t.uuid||Y("BindingInfo.uuid is null.");const n=sa(t.uuid);n||Y(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=Xt(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===$||s===_)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Wt(r))return null;if("prop"===o&&Bn(r,t.propName))return null;const i=jr(t);let a;try{a=Co({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:e,template:i,isEvent:"event"===o,isIndexBinding:t.statePathName in k,policy:a,authority:a.authority})}}return{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=Xt(o,s[t].nodePath);null===e&&Y(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),le(e),jt(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e,n){let o=zi.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new Zo,zi.set(n,o)),o.initializeRow(t,e),o}(n,a,t.node),u=new Wr(o);return _r(u,c),ls(u,a),function(t,e){Nr.set(t,e)}(u,n),ds(u,l),xr(u,r),Mr(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=Xt(t,s.nodePath);if(null===e&&Y(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),re.has(e))continue;const r=ie(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new Zo;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new Wr(i,s);_r(l,a.bindingSession),ls(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in k&&c.push(t);return ds(l,c),xr(l,a.nodes),Mr(t.node,l),l}const Fr=new WeakSet,Hr=Symbol.for("wcstack.state.view-transition-naming");function qr(){const t=Ms("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Ur(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||Fr.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[Hr]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(Fr.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const Gr=new WeakMap,Vr=new WeakMap,Kr=new WeakMap,Jr=new WeakMap;function Qr(t,e,n){!function(t,e,n){let o=Vr.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Vr.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function Xr(t,e){Gr.set(t,e)}function Yr(t){return t.nodeType===Node.ELEMENT_NODE||(t.nodeType===Node.TEXT_NODE?""!==(t.textContent?.trim()??""):t.nodeType===Node.COMMENT_NODE&&t.data.startsWith("@@wcs-"))}function Zr(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const ti=new Set(["if","elseif","else","for"]);function ei(t,e){for(const n of as(t))if(e.appliedBindingSet.delete(n),ti.has(n.bindingType))for(const t of Or(n.node))ei(t,e)}function ni(t){for(const e of as(t)){if(!ti.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of Or(e.node))ni(n),t&&n.mounted&&(Er(n),n.unmount(),Lr(e.node,n))}}function oi(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function si(t,n,s){const r=Boolean(s);let i;const a=Or(t.node);i=0===a.size?Br(t):a.values().next().value;const l=e(),c=t.uuid??"",u=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${oi(t)}`),Er(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${oi(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);Ar(i,he(t.node),n);const e=qr();null!==e&&Ur(i,"branch",e)}}const ri=new WeakMap;function ii(t){return ri.get(t)??[]}const ai=new Set,li=Symbol.for("wcstack.trustedTypes.policy");function ci(){const t=globalThis[li];return null===t||"object"!=typeof t?null:t}let ui,di=!1;const hi={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}},fi=new Set(["textContent","innerText","innerHTML"]);function pi(t,n,s){if(void 0===s&&1===t.propSegments.length&&fi.has(t.propSegments[0])&&(s=""),void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0],u=r[c];if(u!==s){null!==ns&&null!==u&&"object"==typeof u&&null!==s&&"object"==typeof s&&null!==Wt(r)&&ns.rememberOverwrittenObject(r,c,u);const e="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let t=!1;try{r[c]=e?function(t){if("string"!=typeof t)return t;const e=ci(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(di)return;if(!function(){if(void 0!==ui)return ui;if(!("trustedTypes"in globalThis))return ui=!1,ui;try{document.createElement("div").innerHTML="<i></i>",ui=!1}catch{ui=!0}return ui}())return;di=!0;const n="function"==typeof ci()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${e}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:t,property:e})}(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=Wt(t);if(null===n)return null;const o=Bt(t)?.get(n);if(void 0===o)return null;const s=Ht(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&Bn(r,c)){const e=Gn(r,c,t.statePathName),o=Vn(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??Yn()??Jn(e);if(a.visitedEdges.has(o))null!==pe&&pe({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=Qn(a,o);Zn(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:qn++,writtenValue:n};to.push({receipt:i,node:t});try{return r()}finally{to.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=hi[c];t?t(r,s):(function(t,e,n){let o=ri.get(t);o||(o=[],ri.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,s),a=r,ai.add(a))}return}var a,l;const c=i[0];let u=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==u)return;u=u[e]}const d=i[i.length-1],h=u[d];if(h!==s){if(Object.isFrozen(u))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:s}));null!==ns&&2===i.length&&"object"==typeof u&&null!==u&&null!==Wt(r)&&(d in u?ns.rememberOverwrittenValue(r,c,d,u[d]):ns.recordInjectedKey(r,c,d));try{u[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:s,error:t})}}}const mi=new WeakSet;function gi(t,e,n){}function yi(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function bi(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),s=e.length>0?e+a:"";for(const t of n){if(s.length>0&&!t.startsWith(s))continue;const e=t.slice(s.length);e.length>0&&-1===e.indexOf(a)&&o.push(e)}return o}const wi={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},vi={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function _i(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${rt}`}function $i(t,e){return`[wcs/recursion-anchor] "${t}" does not match the declared recursion anchor "${e}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function Si(t,e){return`$setAll("${t}") ${e}`}function xi(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${rt}`}const Pi=new WeakSet;function Ni(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const ki=Object.freeze({[S]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&Y("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[x]:function(t,e,n){const o=t.node,s=t.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[P]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[$]:function(t,e,n){An(n)||Y("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=rs.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||Y('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Wt(t);if(null===e)return null;const n=Bt(t)?.get(e);return void 0===n&&Y(`Custom element <${e}> is not defined for command binding.`),Ht(t)}(r);null===a&&Y(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||Y(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${st(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),rs.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void rs.delete(t);const o=n[i];return"function"!=typeof o&&Y(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),rs.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Ii={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!mi.has(t.replaceNode)){mi.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,r=Ye(t),i=en(t),a=ge(i),c=a.length>0&&!Vr.has(t.node)?[]:a,u=yr(r,c,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let d=Vr.get(t.node);const h=void 0!==d?function(t,e,n){if(o=e,!br.has(o))return null;var o;let s=null;for(let e=0;e<n.newIndexes.length;e++){const o=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?t.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}(d,c,u):null,f=Array.isArray(c)&&c.length===u.deleteIndexSet.size&&u.deleteIndexSet.size>0;if(f&&null===h&&null!==t.node.parentNode){let e=Jr.get(t.node);if(void 0===e){const n=Gr.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(Yr(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(Yr(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n),Jr.set(t.node,e)}if(e){const e=t.node.parentNode;!function(t,e){mo.set(t,(mo.get(t)??0)+e)}(e,e.childNodes.length),e.textContent="",e.appendChild(t.node)}}let p=f?1e3-function(t){return Kr.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==d){const e=d;u.deleteIndexSet.forEach(n=>{const o=e.get(n);void 0!==o&&(null!==h&&h.reused.has(o)?(Er(o),ni(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Lr(t.node,o):(Er(o),o.unmount(),function(t,e){let n=Kr.get(t.node);void 0===n&&(n=[],Kr.set(t.node,n)),n.length<1e3?n.push(e):Lr(t.node,e)}(t,o),p-=1),f||e.delete(n))}),f&&(Vr.delete(t.node),d=void 0)}let m=t.node;const g=et(s.path+"."+l),y=n.stateElement.loopContextStack,b=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const t of i)a.add(n[t]);return a}(u);let w=null;u.newIndexes.length==u.addIndexSet.size&&u.newIndexes.length>0&&m.isConnected&&null===h&&(w=document.createDocumentFragment(),Ue(w,n.rootNode));const v=e(),_=qr(),$=t.uuid??"",S=Kr.get(t.node);for(const e of u.newIndexes){let o;if(u.addIndexSet.has(e)){const r=hn(g,e);if(y.createLoopContext(r,r=>{if(o=h?.byAddedIndex.get(e)??(void 0!==S?S.pop():void 0),void 0===o?o=Br(t):ei(o,n),null!==w)v&&w.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`)),o.appendTo(w),v&&w.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const t=document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`);m.parentNode.insertBefore(t,m.nextSibling),m=t}o.mountAfter(m)}if(v){const t=document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`),n=o.lastNode??m;n.parentNode.insertBefore(t,n.nextSibling)}}Ar(o,r,n),null!==_&&Ur(o,"row",_)}),void 0===o&&Y(`Content not found for ListIndex: ${e.index} at path "${s.path}"`),null!==h&&h.reused.has(o)){const t=n.stateElement.addressHooks;if(t){const e=t.rowReused;for(let t=0;t<e.length;t++)e[t](n.stateElement,o)}}}else{if(o=void 0!==d?d.get(e)??null:null,u.changeIndexSet.has(e)){const t=us(o);for(const e of t)Ri(e,n)}null===o&&Y(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==b&&b.has(e)&&Zr(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),t){const t=o,s=hn(g,e);y.createLoopContext(s,e=>{Ar(t,e,n)})}}m=o.lastNode||m,void 0===d&&(d=new WeakMap,Vr.set(t.node,d)),d.set(e,o)}Gr.set(t.node,m),null!==w&&(t.node.parentNode.insertBefore(w,t.node.nextSibling),Ue(w,null))},if:si,else:si,elseif:si,radio:function(t,e,n){const o=t.node,s=os(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=os(o.value,t.inFilters),r=Array.isArray(n)?n:ss;o.checked=r.includes(s)}},Ai=new WeakMap,Ei=new WeakMap,Ci=new WeakMap;function Ti(){}function Mi(t){const e=ns;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return gi;if(e.isDeclared(n,o))return Ti}return pi}function Oi(t,e){Li(t,e,function(t,e){const n=pn(e);if(n.pathInfo.path in k){const t=he(e.node);return null===t&&Y(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&Y("ListIndex not found for loopContext:");const n=k[e];void 0===n&&Y(`Invalid index name: ${e}`);const o=Je(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&Y(xi(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Ie](n)}(e.state,t))}function Li(t,e,n){const o=os(n,t.outFilters);if(!0===Ei.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=Ai.get(t);if(void 0===s){if(Ai.has(t))return s=Mi(t),s===gi&&Ai.set(t,s),void s(t,e,o);if(s=Ii[t.bindingType],void 0===s){const e=t.propSegments[0];s=ki[e],Ai.set(t,s),void 0===s&&(Wt(t.replaceNode)?(s=Mi(t),s===gi&&Ai.set(t,s)):(s=pi,Ai.set(t,s)))}if(s===pi&&"SELECT"===t.node.tagName){const n=t.propSegments[0];if("value"===n||"selectedIndex"===n)return e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement}),void Ei.set(t,!0)}s(t,e,o)}else s(t,e,o)}function Ri(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=en(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=es(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Ci.get(t)){const e=Wt(t.replaceNode);if(e&&void 0===Bt(t.replaceNode)?.get(e))return void function(t,e){if(Pi.has(t))return;Pi.add(t);const n=()=>{Pi.delete(t);const e=es(t);(null===e||e.shouldApplyState(t))&&Di([t])},o=n=>{Pi.delete(t),Ni(e,n)},s=es(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Pi.delete(t),r()})||(Pi.delete(t),r()))}const r=Bt(t.replaceNode);if(null===r)return Pi.delete(t),void Ni(e,new Error("CustomElementRegistry is unavailable."));Po(r).wait(e,()=>{t.replaceNode.isConnected?n():Pi.delete(t)},o)}(t,e);Ci.set(t,!0)}if(!0===e.sameRootVerified)return void Oi(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Ge(o),null===o&&Y("Root node for fragment not found for binding.")),o!==e.rootNode){const n=Xi(o);null===n&&Y("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};Oi(t,r)})}else Oi(t,e)}function ji(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==pe&&pe({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function Di(t,e,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<t.length;){let n=t[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=Ge(u),null===u&&Y("Root node for fragment not found for binding."));const d=Xi(u);null===d&&Y("No state tree found on this root for binding."),d.createState("readonly",o=>{const h={rootNode:u,stateElement:d,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Ri(n,h)}catch(t){ji(n,t,d,c)}s++;const e=t[s];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{pi(t,{propagationContextByBinding:e},n)}catch(e){ji(t,e,o??null,c)}for(const[t,e]of i.entries())ye(t,e),Se(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[Me](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[Oe](n,o)}catch(t){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:t,original:n,node:o.node})}})}function Wi(t,e,n){const[o,s,r]=ae(t,n),i=ts(t);for(const t of o)fe(t,e);Di(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=ce(o);0!==t.length&&(fe(o.node,e),Di(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const zi=new WeakMap;async function Bi(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=Bt(t);null===s&&Y(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(ee(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function Fi(t){if(t===document)await Bi(document),Q(document),_a(document,document),Wi(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await Rt(e.host),await Bi(e),Q(e),_a(e,e),Wi(e,null)}}const Hi={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function qi(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${Hi[t]??t}" before the state is defined.`}let Ui=null;function Gi(t){return null===Ui&&Y(qi("ssr",t)),Ui}const Vi=new WeakMap,Ki=new WeakMap,Ji=new Set,Qi=[];function Xi(t){return Vi.get(t)??null}function Yi(t){return Ki.get(t)??Promise.resolve()}const Zi=new WeakSet;function ta(t){Zi.add(t)}function ea(t,n){const s=Vi.get(t);if(null===n){if(void 0===s)return;Vi.delete(t),Ji.delete(s),null!==pe&&pe({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{o&&await Gi('the "enable-ssr" attribute').hydrate(t)||await Fi(t),ta(t),ka(),e()}catch(t){n(t)}})});Ki.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await Fi(t),ta(t),ka(),e()}catch(t){n(t)}})});Ki.set(t,e)}}void 0!==s&&Y('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Vi.set(t,n),Ji.add(n);for(let e=0;e<Qi.length;e++)Qi[e](t,n);null!==pe&&pe({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}const na=new Map;function oa(t,e,n){if(null===n)na.delete(t);else{na.set(t,n);const o=Xi(e);null===o&&Y("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function sa(t){return na.get(t)||null}function ra(t){if(t.nodeType===Node.ELEMENT_NODE)return kt(t.getAttribute(o.bindAttributeName)||"");if(t.nodeType===Node.COMMENT_NODE){const e=Ct(t);null===e&&Y("Comment node binding text not found.");const n=sa(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Tt(e),s=null):s=e,[{...o,uuid:s}]}return[]}let ia;function aa(){return ia??={filterName:"not",args:[]}}const la=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function ca(t,e){const n=e+a+l,o=t.indexOf("|");let s,r;if(-1!==o?(s=t.slice(0,o).trim(),r=t.slice(o)):(s=t.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return t;s=n+a+s.slice(1)}return r.length>0?s+r:s}function ua(t,e){const n=la.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+ca(s,e)+r}function da(t,e){const n=t.split(";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=n.indexOf(":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=ca(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function ha(t,e){return da(t,e)}function fa(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=ua(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=da(r,e);t!==r&&o.setAttribute(n,t)}}}function pa(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}function ma(t){const e=[],n=se(t);for(const t of n){const n=ra(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:pa(o),parseBindTextResults:n})}return e}function ga(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const ya=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),ba=aa();function wa(t,e){const n=e.outFilters;return{...e,outFilters:[...n,ba],bindingType:t}}function va(t,e,n,o,s,r=!0){ga(e),"string"==typeof o&&fa(e,o),_a(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:ma(e)};return void 0!==s&&function(t,e,n){for(const o of t)for(let t=0;t<o.parseBindTextResults.length;t++){const s=o.parseBindTextResults[t];null==s.uuid&&(o.parseBindTextResults[t]=e(s,n))}}(i.nodeInfos,s,o),i}function _a(t,e,n,s){const r=o.commentElsePrefix,i=ne(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],u=[];for(;a.nextNode();){const t=a.currentNode;u.push(t)}for(const e of u){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=ha(i,n));let a=kt(i)[0];const u=ya.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=fs();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&Y("'else' binding found without preceding 'if' or 'elseif' binding."),a=wa("else",l.parseBindTextResult),p=va(t,h,a,m,s,!1),oa(f,t,p);const n=c.at(-1),o=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:pa(o),parseBindTextResults:ra(o)})):e.replaceWith(o)}else if("elseif"===d){null===l&&Y("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=va(t,h,a,m,s),oa(f,t,p);const n=document.createComment(`@@${u}:${f}`),o=fs(),i={fragment:document.createDocumentFragment(),parseBindTextResult:wa("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:pa(n),parseBindTextResults:ra(n)}),oa(o,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:pa(g),parseBindTextResults:ra(g)})):e.replaceWith(g)}else{p=va(t,h,a,m,s),oa(f,t,p);const n=document.createComment(`@@${u}:${f}`);e.replaceWith(n)}"if"===d?(c.length=0,l=p):"elseif"===d?l=p:"else"===d&&(l=null,c.length=0)}}const $a=()=>`[${o.bindAttributeName}]`;function Sa(t){if(Bo(t))return!0;if(!xa(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector($a());return null!==e&&Bo(e)}function xa(t){return 1===t.nodeType}function Pa(t){if(Sa(t))return;Q(t),_a(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Wi(e&&s?n:t,null)}const Na=[];function ka(){const t=Na.splice(0,Na.length);for(const e of t)Pa(e);!function(){const t=function(){const t=globalThis[s];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[r];return void 0===e&&(e=[],t[r]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[i];return void 0===e&&(e=new WeakSet,t[i]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const Ia={protocol:"wcs-binder",version:1,bind:function(t){var e;xa(t)&&!Sa(t)&&(e=t.getRootNode(),Zi.has(e)?Pa(t):Na.push(t))}},Aa="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ea=0;async function Ca(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++Ea}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${Aa}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${Aa}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function Ta(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){Y(`Failed to load script file: ${t}`)}}class Ma{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&Y("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=u&&Y("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&Y("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&Y("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&Y(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const Oa=new WeakMap;function La(t,e){let n=Oa.get(t);void 0===n&&(n=new Map,Oa.set(t,n));let o=n.get(e);return void 0===o&&(o=new In(e,t),n.set(e,o)),o}const Ra=new WeakMap;function ja(t){const e=Ra.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return La(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:La(t,n)}},set(){Y("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){Y("$command namespace is read-only; deleting from it is not allowed.")}});return Ra.set(t,n),n}const Da=Symbol("wcs.notHandled"),Wa=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],za=new Map;function Ba(t,e){za.set(t,e)}const Fa=new Map;let Ha=[],qa=[];function Ua(t,e){Fa.set(t,e),Ha=Array.from(Fa.values()).sort((t,e)=>t.order-e.order),qa=Ha.slice().reverse()}function Ga(t,e){for(let n=0;n<Ha.length;n++)Ha[n].activate?.(t,e)}function Va(t){"readonly"===t.mutability&&Y("This state is readonly.")}const Ka=new Map;class Ja{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=et(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function Qa(t){let e;return Ka.get(t)??(Ka.set(t,e=new Ja(t)),e)}function Xa(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:Je(n.listIndex,o,n.pathInfo.wildcardCount)}function Ya(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=Ke(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?Je(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?Je(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}function Za(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function tl(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](t,e,n,o,s);if(a!==Da)return a}}return Da}function el(t,e,n,o,s){if(e.pathInfo.segments[0]===R)return function(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}(ja(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){if(null===e.parentAddress){const r=tl(s,e,null,n,o);if(r!==Da)return r;Y(function(t,e,n){return`[${wi.binding}] Path "${t}" does not exist on the state tree.${st(t,bi(e,"",n))}${rt}`}(e.pathInfo.path,t,s.getterPaths))}const r=nl(t,e.parentAddress,n,o);if(null==r)return;const i=e.pathInfo.segments[e.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==l&&!(i in Object(r))){const t=tl(s,e,Object(r),n,o);if(t!==Da)return t}if(i===l){const t=e.listIndex?.index??Y(xi(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(r,t)}return Reflect.get(r,i)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}function nl(t,e,n,o){Ya(o,e),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,e.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const t=r.read;for(let r=0;r<t.length;r++){const i=t[r](s,e,n,o);if(i!==Da)return i}}return Za(s,e)?function(t,e,n,o,s){const r=Fe(s,e),i=function(t){return As.get(t)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=el(t,e,n,o,s);return Es(r,{value:l,dirty:!1,generation:a}),l}(t,e,n,o,s):el(t,e,n,o,s)}function ol(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,u,d)=>{const h=o[s]??null;if(null===h)return void d.push(u);const f=hn(h,r),p=Fe(n.stateElement,f),m=$e(p),g=nl(t,f,e,n),y=yr(r,m,g).newIndexes,b=l[c]??null;if(i.set(p,g),null===b)for(let t=0;t<y.length;t++){const e=y[t];a(o,s+1,e,l,c+1,u.concat(e.index),d)}else{const t=y[b]??Y(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,u.concat(t.index),d):d.push(u.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Se(t,Array.isArray(e)?e:[]);return l}function sl(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=ks(nl(t,hn(a,r),e,n),r);null==l&&Y(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??Y(`ListIndex not found at index ${c} of ${a.path}`)}return r}function rl(t,e,n,o){"object"==typeof t&&null!==t||Y(`${q} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&Y(`${q} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function il(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&Y(`${q} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function al(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];rl(a,n,o,i);const l=il(a,e,n,o,i);r.has(l)&&Y(`${q} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function ll(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function cl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const r=nl(t,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=e.pathInfo.lastSegment;if(i===l){const t=e.listIndex?.index;return"number"==typeof t&&t in r}return i in r}const ul=new WeakMap;function dl(t,e){null===e?ul.delete(t):ul.set(t,e)}function hl(t,e,n){const s=hn(et(t.wildcardParentPaths[e]),n),r=Fe(t.stateElement,s),i=$e(r),a=t.stateProxy[Ie](s),l=yr(s.listIndex,i,a);t.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(l,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)hl(t,e+1,n)}const fl=[];function pl(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:fl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:fl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const ml=[];function gl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return ml;let s=null;const r=e+a;for(const t of o){if(t!==e&&!t.startsWith(r))continue;const o=et(t);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??ml}function yl(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const r of s){const s=et(r);if(t.listPathSet.has(o)&&s.lastSegment===l){const i=t.stateProxy[Ie](e),a=Fe(t.stateElement,e),l=$e(a),c=yr(e.listIndex,l,i);t.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const u=pl(t,o,0,0,c);for(const e of u.fullRows){const o=hn(s,e);t.result.add(o),n.push(o)}if(null!==u.movedRows){const e=gl(t,r,s);if(null===e)for(const e of u.movedRows){const o=hn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of u.movedRows)for(const s of e){const e=hn(s,o);t.result.add(e),n.push(e)}}}else{const o=hn(s,e.listIndex);t.result.add(o),n.push(o)}}const r=t.dynamicMap.get(o);if(r)for(const o of r){const s=et(o),r=[];if(s.wildcardCount>0){const n=Ke(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&Y(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=Je(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};hl(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&Y(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=Je(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=hn(s,e);t.result.add(o),n.push(o)}}}function bl(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&Y(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),d={ranks:u,stateElement:t,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,yl(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(d,e,a);for(const[t,e]of d.observedListValueByAbsAddress)Se(t,e);return Array.from(d.result)}function wl(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](t,e,n,o,s)}}function vl(t,e,n){const o=t.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function _l(t,e,n){const o=t.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function $l(t,e,n,s,r,i){const a=function(t,e){return!0===Fs.get(t)?.byPath.has(e)||!0===Vs.get(t)?.has(e)}(t,e),c=function(t,e){return!0===Js.get(t)?.has(e)}(t,e);if(!a&&!c)return;const u=Bs(),d=o.enablePropagationContext?Yn()??null:null,h=t=>{Cs(t),u.enqueueAbsoluteAddress(t,d)};a&&lr(t,e,n,s,r).forEach(h),c&&function(t,e,n,o){const s=et(e).segments.length,r=[];for(const i of Js.get(t).get(e)){const e=et(i).segments.slice(s);if(e.includes(l))ur(t,i,r);else for(const s of lr(t,i,!0,cr(n,e),cr(o,e)))r.push(s)}return r}(t,e,n?s:i(),r).forEach(h)}function Sl(t,e,n,s,r,i,a="diff"){const l=o.enablePropagationContext?Yn()??Jn(-1):null,c=Bs();c.enqueueAbsoluteAddress(e,l),i&&Cs(e),bl(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=Fe(s.stateElement,e);Cs(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function xl(t,e,n,o,s){s&&(t.getterPaths.has(e)?Cs(n):Es(n,{value:o,dirty:!1,generation:t.stateGeneration}))}function Pl(t,e,n,o,s,r,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const i=nl(t,n,s,r),a=e.pathInfo.segments[e.pathInfo.segments.length-1];if(a===l){const t=e.listIndex?.index??Y(xi(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(i,t,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);r.pushAddress(e),r.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{Sl(e,n,s,r,i,a)}}function Nl(t,e,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(e.pathInfo.path);if(void 0!==i){const r=nl(t,e,o,s),c=function(t,e,n,o){const s=al(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=al(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,i,r,n);if(null!==c)return function(t,e,n,o,s,r){const i=e.pathInfo.path,c=e.listIndex;null===Ns(o)&&yr(c,null,o);const u=yr(c,o,n.list),d=kl(t,e,n.list,s,r,i),h=et(i+a+l);for(const e of n.matched){const n=ll(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const i of n)void 0!==o?Nl(t,hn(et(h.path+a+i.field),o),i.value,s,r):e.oldRow[i.field]=i.value}return d}(t,e,c,r,o,s)}}return kl(t,e,n,o,s,null)}function kl(t,e,n,s,r,i){const c=r.stateElement,u=e.pathInfo.path,d=c.addressHooks;if(d){const t=d.write;for(let o=0;o<t.length;o++){const i=t[o](c,e,n,s,r);if(i!==Da)return i}}const h=!!eo&&(eo=!1,!0);if(!(u in t)&&null!==e.parentAddress&&!c.elementPaths.has(u)){const a=nl(t,e.parentAddress,s,r);if("object"==typeof a&&null!==a){const t=e.pathInfo.lastSegment,f=t===l?e.listIndex?.index:t;let p,m=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==f&&f in a,e=void 0!==f?a[f]:void 0;if(t&&Object.is(e,n))return!0;p=e,m=!0}$l(c,u,m,p,n,()=>a[f]);const g=Za(c,e),y=Fe(c,e);null!==pe&&pe({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:m}),wl(c,u,y,p,m);let b=!1;try{if(void 0===f&&Y(xi(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),d&&0!==d.writeMissing.length&&t!==l&&!(f in a)){const t=d.writeMissing;for(let o=0;o<t.length;o++){b=!0;const i=t[o](c,e,a,f,n,s,r);if(i!==Da)return i;b=!1}}return Reflect.set(a,f,n)}finally{Sl(e,y,s,r,i,g),b?Cs(y):xl(c,u,y,n,g),vl(c,e.pathInfo,{value:n})}}}let f,p=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=nl(t,e,s,r);if(cl(t,e,s,r)&&Object.is(o,n))return!0;f=o,p=!0}$l(c,u,p,f,n,()=>nl(t,e,s,r));const m=c.elementPaths.has(e.pathInfo.path),g=Za(c,e),y=Fe(c,e);null!==pe&&pe({type:"state:write",absoluteAddress:y,value:n,oldValue:f,hasOldValue:p}),wl(c,u,y,f,p);try{return m?function(t,e,n,o,s,r,i,c){const u=e.parentAddress??Y(`address.parentAddress is undefined path: ${e.pathInfo.path}`),d=nl(t,u,s,r)??[];let h=(f=d,ul.get(f)??null);var f;if(null===h){const t=Ns(d)??[];h={value:[...d],listIndexes:[...t]},dl(d,h)}try{return Pl(t,e,n,o,s,r,i,c)}finally{const n=h.value.indexOf(o),i=nl(t,u,s,r)??[],c=Array.isArray(i)?Ns(i)??[]:[],f=e.listIndex.index,p=-1!==n?h.listIndexes[n]:bs(u.listIndex,-1);if(c[f]=p,new Set(i).size===h.value.length){for(let t=0;t<c.length;t++)c[t].index=t;dl(d,null),function(t,e,n,o,s,r){const i=r.stateElement,c=Bs(),u=Fe(i,t);ge(u)===n&&(Is(e.value,e.listIndexes),ye(u,e.value),function(t){br.add(t)}(e.value)),c.enqueueRenderOnlyAddress(u);const d=new Map;e.listIndexes.forEach((t,e)=>d.set(t,e));const h=et(t.pathInfo.path+a+l);for(let t=0;t<o.length;t++){const n=o[t],a=d.get(n);if(a===t)continue;const l=hn(h,n),u=Fe(i,l);if(void 0===a){const n=He(i,h,e.listIndexes[t]??null);_l(i,u,n),Sl(l,u,s,r,null,Za(i,l),"full");continue}bl(i,l,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",t=>{const e=Fe(i,t);Cs(e),c.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}}(u,h,i,c,s,r)}}}(t,e,y,n,s,r,i,g):Pl(t,e,y,n,s,r,i,g)}finally{m||xl(c,u,y,n,g),vl(c,e.pathInfo,{value:n})}}function Il(t,e,n,o){return(e,s,...r)=>{const i=et(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&Y(_i("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=hn(i,sl(t,n,o,i,s));if(0===r.length)return nl(t,a,n,o);Va(o),Nl(t,a,r[0],n,o)}}function Al(t,e,n,o){const s=Il(t,0,n,o);return(e,r)=>{const i=et(e);if(void 0===r||Array.isArray(r)||Y(`$getAll("${e}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&Y(_i("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=Xa(o,i.wildcardPaths[t]);if(e){r=Qe(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&Y(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(e,t.pathInfo.path)),r=[]}}const a=ol(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}function El(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return Xa(o,s.wildcardPaths.at(-1)??Y(`lastWildcardPath is null: ${e.pathInfo.path}`))??Y(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??Y(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=ks(nl(t,hn(i,s),n,o),s)??Y(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??Y(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??Y(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":Y(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function Cl(t,e,n,o){return(e,s,r,i)=>{Va(o);const a=et(e);Array.isArray(s)||Y(Si(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&Y(_i("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&Y(Si(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&Y(Si(e,"requires an array as the value when { spread: true } is set."));const u=ol(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&Y(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,u.length,r.length));const d=[];for(let e=0;e<u.length;e++){const s=sl(t,n,o,a,u[e]);d.push(hn(a,s))}let h=0;for(let e=0;e<d.length;e++){const s=d[e];let i;i=c?r(nl(t,s,n,o),...u[e]):l?r[e]:r,void 0!==i&&(Nl(t,s,i,n,o),h++)}return h}}function Tl(t,e){const n=t.getterPaths;if(0===n.size)return!1;for(const t of et(e).cumulativePaths)if(n.has(t))return!0;return!1}const Ml=/^\$\d+$/,Ol=`${U}${a}`,Ll=`${G}${a}`,Rl=new WeakMap;class jl{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=Xi(t);null===n&&Y("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&Y("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&Y(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),Y(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const n=this._addressStack[e];if(n){if(t.has(n))return!0;t.add(n)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&Y(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return function(t,e,n,o){const s=k[e];if(void 0===s&&"string"==typeof e&&36===e.charCodeAt(0)&&Ml.test(e)&&Y(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&Y(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&Y(`ListIndex not found: ${e.toString()}`);let i=s;const a=t.pathInfo,l=o.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let n=0;n<e.length;n++)i+=e[n](o,t)}const c=Je(r,i,a.wildcardCount);return c?.index??Y(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,e,n,t);if(i!==Da)return i}}if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>Al(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>Cl(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=Qa(e),i=El(t,r,n,o),a=hn(r.pathInfo,i),l=Fe(s,a),c=Bs();c.enqueueAbsoluteAddress(l),bl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Fe(s,t);Cs(e),c.enqueueAbsoluteAddress(e)});const u=s.addressHooks;if(u){const t=u.written;for(let e=0;e<t.length;e++)t[e](s,a.pathInfo)}}}(t,0,n,o)(e);case"$resolve":return(e,s,...r)=>Il(t,0,n,o)(e,s,...r);case"$trackDependency":return t=>function(t,e,n,o){return t=>{-1!==t.indexOf(H)&&Y(`[wcs/recursion-unsupported] $trackDependency("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&Y(`No active state reference to track dependency for path "${t}".`);const e=o.lastAddressStack?.pathInfo??Y("Internal error: lastAddressStack is null"),n=o.stateElement;o.stateElement.getterPaths.has(e.path)&&e.path!==t&&n.addDynamicDependency(t,e.path)}}(0,0,0,o)(t);case"$eq":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Tl(o.stateElement,t))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&rr(o.stateElement,t),Object.is(n[t],e);let r;o.beginUntrack();try{r=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&sr(o.stateElement,t,e,Fe(o.stateElement,s),r),Object.is(r,e)};case"$eqPath":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Tl(o.stateElement,t);let i,a=r?n[t]:void 0;o.beginUntrack();try{r||(a=n[t]),i=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?rr(o.stateElement,t):sr(o.stateElement,t,i,Fe(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(t,e=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||Y(`$eqIndex("${t}") needs a list row scope.`);const r=Je(s.listIndex,e-1,s.pathInfo.wildcardCount);if(null===r&&Y(`$eqIndex("${t}", ${e}): no list index at that level.`),Tl(o.stateElement,t))return o.stateElement.getterPaths.has(s.pathInfo.path)&&rr(o.stateElement,t),Object.is(n[t],r.index);const i=e===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[t],i&&(l=n[s.pathInfo.wildcardParentPaths[e-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const e=i?Ns(l):null;null!==e?function(t,e,n,o,s){Gs=!0,Ys(t).lastValue.set(e,s),Xs(t,e);let r=Vs.get(t);void 0===r&&Vs.set(t,r=new Map);let i=r.get(e);void 0===i&&r.set(e,i=new Set);let a,l=Ks.get(o);void 0===l?Ks.set(o,l=[]):a=l.find(n=>n.stateElement===t&&n.path===e),void 0===a&&(a={stateElement:t,path:e,indexes:o,getters:new Set},l.push(a),i.add(a)),a.getters.add(n)}(o.stateElement,t,s.pathInfo,e,a):function(t,e,n,o,s){Gs=!0;const r=Ys(t);Xs(t,e),or(r,e,s,o,er(r,e,n.index,o),{stateElement:t,path:e,absAddress:o,levelListIndex:n})}(o.stateElement,t,r,Fe(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case R:return ja(o.stateElement)}if(!e.startsWith(Ol)&&!e.startsWith(Ll))return}const r=Qa(e),i=El(t,r,n,o),a=hn(r.pathInfo,i);return nl(t,a,n,o)}if("symbol"==typeof e){const s=function(t){let e=Rl.get(t);return void 0===e&&(e=new Map,Rl.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case ke:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&Y("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case Ie:i=e=>nl(t,e,n,o);break;case Ae:i=e=>cl(t,e,n,o);break;case Ee:i=(e,s)=>Nl(t,e,s,n,o);break;case Ce:i=()=>async function(t,e,n){const o=Reflect.get(t,I);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Te:i=()=>function(t,e,n){const o=Reflect.get(t,A);"function"==typeof o&&o.call(n)}(t,0,n);break;case Me:i=e=>function(t,e,n,o){const s=Reflect.get(t,E);let r;if("function"==typeof s){const t=new Set,i={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,s=e.path;if(-1===s.indexOf("#")&&(t.add(s),e.wildcardCount>0)){const t=Qe(n.listIndex,e.wildcardCount),o=i[s];void 0===o?i[s]=[t]:o.push(t)}}r=s.call(n,Array.from(t),i)}const i=o.stateElement?.addressHooks;if(i){const t=i.updated;for(let s=0;s<t.length;s++)t[s](o.stateElement,e,n)}return r}(t,e,n,o);break;case Oe:i=(e,o)=>function(t,e,n,o){const s=Reflect.get(t,C);"function"==typeof s&&s.call(o,e,n)}(t,e,o,n);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}(t,e,n,this)}set(t,e,n,o){return Va(this),function(t,e,n,o,s){if("string"==typeof e){const r=Qa(e),i=El(t,r,o,s);return Nl(t,hn(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}}const Dl=Promise.resolve(),Wl=new Map;let zl=[];function Bl(t,e){Wl.set(t,e),zl=Array.from(Wl.values()).sort((t,e)=>t.order-e.order)}function Fl(t,e){return Y(qi(t,e))}const Hl="undefined"==typeof HTMLElement?class{}:HTMLElement;function ql(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}let Ul=null;const Gl=new Set(["for","if","elseif","else"]);class Vl extends Hl{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return Yi(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Ma}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&Y(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){const e=this.__state,n=function(){const t=new Map;return{get:e=>t.get(e),set(e,n){t.set(e,n)}}}();n.set("previousState",e),function(t,e,n){for(let o=0;o<Ha.length;o++)Ha[o].validateEarly?.(t,e,n)}(this,t,n);const o=function(t){const e=new Set,n=t[L];if(void 0===n)return e;Array.isArray(n)||Y(`${L} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Y(`${L} entries must be non-empty strings.`),t===R&&Y(`${L} entry "${t}" conflicts with the reserved namespace name "${R}".`),e.has(t)&&Y(`${L} entry "${t}" is duplicated.`),e.add(t);return e}(t),s=function(t){const e=new Set,n=t[j];if(void 0===n)return e;Array.isArray(n)||Y(`${j} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Y(`${j} entries must be non-empty strings.`),e.has(t)&&Y(`${j} entry "${t}" is duplicated.`),e.add(t);return e}(t),r=function(t){const e=t[q];if(void 0===e)return null;"object"==typeof e&&null!==e||Y(`${q} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&Y(`${q} entry path must be a non-empty string.`);const e=t.split(a);e.some(t=>0===t.length)&&Y(`${q} entry "${t}" must not contain empty path segments.`),e[e.length-1]===l&&Y(`${q} entry "${t}" must be the list path itself, not the element path (drop the trailing "${a}${l}").`),-1!==t.indexOf(H)&&Y(`[wcs/recursion-unsupported] ${q} entry "${t}" uses "${H}", which ${q} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${a}${l}${a}children").`),"function"!=typeof o?("string"!=typeof o&&Y(`${q} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&Y(`${q} entry "${t}" key field name must be a non-empty string.`),(o.includes(a)||o.includes(l))&&Y(`${q} entry "${t}" key field name "${o}" must be a flat property name ("${a}" / "${l}" are not allowed).`),o in Object.prototype&&Y(`${q} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t);n.set("eventTokenNames",s),function(t,e,n){for(let o=0;o<Ha.length;o++)Ha[o].validate?.(t,e,n)}(this,t,n),function(t,e,n){for(let o=0;o<Ha.length;o++)Ha[o].preCommit?.(t,e,n)}(this,t,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=t,void 0!==e&&Ul?.reset(this),this._hasUpdatedCallback=E in t,this._hasErrorCallback=C in t,Pn.delete(this),function(t,e,n){for(let o=0;o<Ha.length;o++)Ha[o].applyEarly?.(t,e,n)}(this,t,n),function(t,e,n){const o=e[D];if(void 0!==o){"object"==typeof o&&null!==o||Y(`${D} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||Y(`${D} entry "${e}" is not declared in $eventTokens.${st(e,n)}`),"function"!=typeof s&&Y(`${D} entry "${e}" must be a function.`),Nn(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const i=function(t){const e=new Set,n=new Set,o=ql(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of i.getterPaths)this._getterPaths.add(t);for(const t of i.setterPaths)this._setterPaths.add(t);!function(t,e,n){for(let o=0;o<Ha.length;o++)Ha[o].apply?.(t,e,n)}(this,t,n),this._listKeys=r,this._rebuildPathInfo(),function(t,e,n){for(let o=0;o<Ha.length;o++)Ha[o].register?.(t,e,n)}(this,t,n),Ga(this,null),this._resolveLoading?.()}attributeChangedCallback(t,e,n){this._initialized&&e!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===e?"absent":`"${e}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?Gi('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){Y("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await Ca(t,o.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||Y(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await Ta(t);Y(`Unsupported src file type: ${t}`)}}catch(t){Y(`Failed to initialize state: ${t}`)}}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}return await this._loadingPromise,null!==this._rootNode&&(ea(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),Y(t)}_failInitializeLoudly(t,e=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),e&&null!==this._rootNode&&null===Xi(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),Ki.set(t,n)}(this._rootNode,t),function(t,e,n){for(let o=0;o<zl.length;o++)zl[o].initializeFailed?.(t,e,n)}(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{I in t&&await t[Ce]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{A in t&&t[Te]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(t){for(let e=0;e<zl.length;e++)if(!0===zl[e].reconnecting?.(t))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||Xi(this._rootNode)===this||ea(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const e=function(t){for(let e=0;e<zl.length;e++){const n=zl[e].connecting?.(t);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const n=this.parentNode;if(n instanceof ShadowRoot&&n.host.hasAttribute(V))try{Fl("dcc",`a <${o.tagNames.state}> inside a [${V}] host`)}catch(t){this._failInitializeLoudly(t)}if(this.hasAttribute("mount"))try{Fl("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}let s=!1;try{const t=function(t){for(let e=0;e<zl.length;e++){const n=zl[e].preparing?.(t);if(null!=n)return n}return null}(this);null===t&&this.hasAttribute("bind-component")&&Fl("scopes",'the "bind-component" attribute'),s=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(s)return;let r=!1;try{r=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!r)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!e()||t!==this._connectGeneration||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await Gi('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Ga(this,t),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!function(t){for(let e=0;e<zl.length;e++)if(!0===zl[e].disconnecting?.(t))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(t,e){for(let n=0;n<zl.length;n++)zl[n].initializeFailureCleared?.(t,e)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{ea(this.rootNode,null),Ra.delete(this),function(t){for(let e=0;e<qa.length;e++)qa[e].deactivate?.(t)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource()}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e,this.attachAddressHooks("watch",z)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&Y(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return yi(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&Y("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const n=function(t,e){const n=za.get(t);return void 0===n&&Y(qi(t,`"${e}"`)),n}(t,e);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(t,e){for(let n=0;n<Wa.length;n++){const o=Wa[n],s=e[o];if(void 0===s)continue;const r=t[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",M)}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(t);void 0===o?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:o.bound||"binding"===n})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+l)),!this._pathSet.has(t)){const e=et(t);if(this._pathSet.add(t),Ul?.check(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=et(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,n){try{const o=function(t,e,n){const o=new jl(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&Y(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);!function(t){for(let e=0;e<zl.length;e++)zl[e].replacingState?.(t)}(this),(this._hasGraftedVolumes||this._hasMounts)&&Y("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const e=this.__state;this._state=t;const n=function(t){const e=new Set;for(const n of t)if(void 0!==n)for(const[t,o]of Object.entries(ql(n)))t.startsWith("$")||t.includes(l)||"function"==typeof o.value||e.add(t);return e}([e,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){!function(t,n,o){const s=new Map;for(const t of o){const e=et(t);if(null===e.lastWildcardPath)continue;const n=s.get(e.lastWildcardPath);void 0===n?s.set(e.lastWildcardPath,[e]):n.push(e)}const r=[],i=new Set,a=e=>{const n=Fe(t,e);if(i.has(n))return;i.add(n);const o=ln(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==e.listIndex){const t=s.get(e.pathInfo.path);if(void 0!==t)for(const n of t)a(hn(n,e.listIndex))}};xe();try{if(t.createState("readonly",e=>{for(const o of n){const n=hn(et(o),null);a(n);try{bl(t,n,t.staticDependency,t.dynamicDependency,t.listPaths,e,"new",a)}catch{}}}),0===r.length)return;const o=function(t){const e=[],n=[];for(const o of t)Gl.has(o.bindingType)?e.push(o):n.push(o);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(n)}(r),s=()=>{Di(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=Os("state",s);void 0!==i&&i.catch(Ws)}finally{Pe()}}(this,t,this._pathRegistrations.keys())}}const Kl=[];function Jl(t,e){const r=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(t);var i;r&&((i=r).tagNames&&Object.assign(n.tagNames,i.tagNames),"string"==typeof i.bindAttributeName&&(n.bindAttributeName=i.bindAttributeName),"string"==typeof i.commentTextPrefix&&(n.commentTextPrefix=i.commentTextPrefix),"string"==typeof i.commentForPrefix&&(n.commentForPrefix=i.commentForPrefix),"string"==typeof i.commentIfPrefix&&(n.commentIfPrefix=i.commentIfPrefix),"string"==typeof i.commentElseIfPrefix&&(n.commentElseIfPrefix=i.commentElseIfPrefix),"string"==typeof i.commentElsePrefix&&(n.commentElsePrefix=i.commentElsePrefix),"string"==typeof i.locale&&(n.locale=i.locale),"boolean"==typeof i.debug&&(n.debug=i.debug),"boolean"==typeof i.enableMustache&&(n.enableMustache=i.enableMustache),"boolean"==typeof i.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=i.enableDirectionalInitialSync),"boolean"==typeof i.enablePropagationContext&&(n.enablePropagationContext=i.enablePropagationContext),"boolean"==typeof i.enableContractAnalyzer&&(n.enableContractAnalyzer=i.enableContractAnalyzer),"boolean"==typeof i.sameValueGuard&&(n.sameValueGuard=i.sameValueGuard)),function(t=customElements){for(let e=0;e<Kl.length;e++)Kl[e](t);t.get(o.tagNames.state)||t.define(o.tagNames.state,Vl)}(e),function(){const t=globalThis;void 0===t[s]&&(t[s]=Ia)}()}let Ql=0;const Xl=["$watch","$streams","$scan","$listKeys","$updatedCallback","$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],Yl=new Set;function Zl(t,e){const n=t.stateObject[e];if("function"==typeof n)try{const o=t.component[t.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function tc(t){const e=t.indexOf(a);return-1===e?t:t.slice(0,e)}function ec(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function nc(t,e){for(const n of t.entries)if(ec(e,n.innerSegments)){const t=e.slice(n.innerSegments.length);return 0===t.length?n.outerPathInfo.path:n.outerPathInfo.path+a+t.join(a)}return null}function oc(t,e){return t.markerBasePath+a+e}function sc(t,e,n,o){let s=t.accessorBySuffixByMarkerParent.get(e);void 0===s&&(s=new Map,t.accessorBySuffixByMarkerParent.set(e,s));const r=e+a+n;s.set(n,{accessorName:o,indexShift:et(r).wildcardCount-et(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(r),t.addedGetterPaths.add(r))}function rc(t,e){return!t.injectedKeys.has(e)&&!t.mappedKeys.has(e)&&("function"==typeof t.stateObject[e]&&!t.getterKeys.has(e)||Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function ic(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(a)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${tc(e)}: path") or declare the key on the component state.`}const ac=/^\$(\d+)$/;function lc(t,e){const n=e[0];if("$"===n||"#"===n)return null;if(t.getterKeys.has(e)||t.setterKeys.has(e))return null;const o=tc(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||rc(t,o))return null;const s=function(t,e){for(const n of t.entries)if(ec(e,n.innerSegments))return n;return null}(t,e.split(a));return null!==s&&s.readonly?s:null}function cc(t,e){const n=lc(t,e);if(null!==n){const o=0===n.innerSegments.length?"":a+n.innerSegments.join(a);Y(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${m}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${m} from the mount.`)}return uc(t,e)}function uc(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(a);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===l){o=t;break}if(-1===o)return sc(t,t.markerBasePath,e,e),oc(t,e);if(rc(t,n[0]))return sc(t,t.markerBasePath,e,e),oc(t,e);const s=n.slice(0,o+1),r=n.slice(o+1),i=nc(t,s);null===i&&Y(ic(t,e)),0===r.length&&Y(`Wildcard-terminal accessor "${e}" on mounted <${t.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const c=i+a+t.marker;return sc(t,c,r.join(a),e),c+a+r.join(a)}(t,e);const o=tc(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return oc(t,e);if(rc(t,o))return oc(t,e);const s=nc(t,e.split(a));if(null!==s)return s;Y(ic(t,e))}function dc(t,e,n,o,s){if(void 0===o)return;const r=et(n).wildcardCount-et(e).wildcardCount;return 0===r?o:(s.length<r&&Y(`Cannot resolve "${e}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const hc=new WeakMap,fc=new WeakMap,pc=new WeakMap,mc=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)}),gc=new WeakMap;function yc(t){return gc.get(t)??null}let bc=!1;function wc(t){const e=pc.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}function vc(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=pc.get(t);if(void 0===o)return null;const s=e.indexOf(a,n),r=-1===s?e.slice(n):e.slice(n,s),i=o.get(r);if(void 0===i)return null;const l=i.deref();return void 0===l?(o.delete(r),null):l}const _c="3.0.0",$c=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Sc(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const xc="__WCSTACK_DEVTOOLS_HOOK__";const Pc=t=>{null!==pe&&pe({type:"state:update-batch",addresses:t})};function Nc(t){const e=null!==pe;!function(t){pe=t}(t);const n=null!==t;n&&!e?Ds(Pc,0):!n&&e&&function(t){const e=Ls.findIndex(e=>e.listener===t);-1!==e&&Ls.splice(e,1)}(Pc)}function kc(t){return{rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function Ic(t){return Xi(t)??Y("devtools: no state tree on this root")}let Ac=null;function Ec(){if(e())return;if(null!==Ac)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:_c,getStateElements(){const t=[];for(const e of Ji)t.push(kc(e));return t},overlays:t=>wc(Ic(t)).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join("."),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]})),keyedSubscriptions:t=>function(t){const e=function(t){const e=Fs.get(t);return void 0===e?null:{byPath:e.byPath,lastValue:e.lastValue,tracked:e.tracked,watchers:Vs.get(t)}}(t);if(null===e)return[];const n=new Set([...e.byPath.keys(),...e.tracked]);if(void 0!==e.watchers)for(const t of e.watchers.keys())n.add(t);const o=[];for(const t of[...n].sort()){const n=e.byPath.get(t);let s=0;if(void 0!==n)for(const t of n.values())s+=t.size;o.push({path:t,tracked:e.tracked.has(t),rows:s,keys:n?.size??0,lists:e.watchers?.get(t)?.size??0,lastValue:e.lastValue.get(t)})}return o}(Ic(t)),keys(t){const e=Ic(t),n=[];return e.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}n.push(e)}}),n},read(t,e,n){let o;return Ic(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){Ic(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=[...t.inFilters,...t.outFilters].map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=sa(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Sc(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=Qt(e,kt(n));for(const o of t)r(Sc(e,o,"attribute",n))}catch{}continue}const e=$c.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=sa(s);if(null===a){if(n===o.commentTextPrefix)try{r(Sc(t,Tt(s),"comment",s))}catch{}}else r(Sc(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:Nc};Ac=t,function(){const t=globalThis,e=t[xc];if(void 0!==e)return 2!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 2. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:2,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[xc]=n,n}().register(t)}const Cc={name:"devtools",install(){Ec()}},Tc=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Mc=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])}),Oc=new WeakMap,Lc=new WeakMap,Rc=new WeakSet,jc=new WeakMap;function Dc(t,e,n,o){console.warn(`[@wcstack/state] [${wi[n]}] ${vi[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${st(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${rt}`),null!==pe&&pe({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const Wc={check:function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=t.addressHooks;if(s){const e=s.suppressPathDiagnostic;for(let o=0;o<e.length;o++)if(e[o](t,n))return}const r=et(n).segments;if("binding"===o&&r.length<2)return;if(function(t,e){let n=Oc.get(t);return void 0===n&&(n=new Set,Oc.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const i=function(t,e,n){if(void 0!==yi(t,e))return Mc;const o=et(e).segments;let s=t,r="";for(let e=0;e<o.length;e++){const i=o[e],c=r;if(r=0===e?i:r+a+i,e>0&&e<o.length-1&&void 0!==yi(t,r))return Tc;if(Object(s)!==s)return Tc;if(i===l){if(!Array.isArray(s)||0===s.length)return Tc;s=s[0];continue}const u=yi(s,i);if(void 0===u)return{existence:"missing",missingSegment:i,candidates:bi(s,c,n)};if("function"==typeof u.get)return e===o.length-1?Mc:Tc;s=u.value}return Mc}(e,n,t.getterPaths);"missing"===i.existence&&(function(t,e){return!0===jc.get(t)?.has(e)}(t,n)||("binding"!==o?Dc(0,n,o,i):function(t,e,n){let o=Lc.get(t);void 0===o&&(o=new Map,Lc.set(t,o)),o.set(e,n),Rc.has(t)||(Rc.add(t),setTimeout(()=>function(t){Rc.delete(t);const e=Lc.get(t);if(void 0!==e){Lc.delete(t);for(const[t,n]of e)Dc(0,t,"binding",n)}}(t),0))}(t,n,i)))},reset:function(t){Oc.delete(t),Lc.delete(t)},markExported:function(t,e){let n=jc.get(t);void 0===n&&(n=new Set,jc.set(t,n)),n.add(e),Lc.get(t)?.delete(e)}};let zc=!1;const Bc={name:"diagnostics",install(){zc||(zc=!0,Ul=Wc)}};function Fc(t){Y(`filter ${t} requires at least one option`)}function Hc(t){Y(`filter ${t} requires a number as option`)}function qc(t){Y(`filter ${t} requires a number value`)}function Uc(t){Y(`filter ${t} requires a date value`)}function Gc(t){return!(!t||isNaN(Number(t)))}const Vc={eq:(t,e)=>{const n=t?.[0]??Fc("eq"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?(Gc(n)||Hc("eq"),t===Number(n)):"string"==typeof t?t===n:t===o},ne:(t,e)=>{const n=t?.[0]??Fc("ne"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?(Gc(n)||Hc("ne"),t!==Number(n)):"string"==typeof t?t!==n:t!==o},not:t=>t=>("boolean"!=typeof t&&Y("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??Fc("lt");return Gc(e)||Hc("lt"),t=>("number"!=typeof t&&qc("lt"),t<Number(e))},le:t=>{const e=t?.[0]??Fc("le");return Gc(e)||Hc("le"),t=>("number"!=typeof t&&qc("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??Fc("gt");return Gc(e)||Hc("gt"),t=>("number"!=typeof t&&qc("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??Fc("ge");return Gc(e)||Hc("ge"),t=>("number"!=typeof t&&qc("ge"),t>=Number(e))},inc:t=>{const e=t?.[0]??Fc("inc");return Gc(e)||Hc("inc"),t=>("number"!=typeof t&&qc("inc"),t+Number(e))},dec:t=>{const e=t?.[0]??Fc("dec");return Gc(e)||Hc("dec"),t=>("number"!=typeof t&&qc("dec"),t-Number(e))},mul:t=>{const e=t?.[0]??Fc("mul");return Gc(e)||Hc("mul"),t=>("number"!=typeof t&&qc("mul"),t*Number(e))},div:t=>{const e=t?.[0]??Fc("div");return Gc(e)||Hc("div"),t=>("number"!=typeof t&&qc("div"),t/Number(e))},mod:t=>{const e=t?.[0]??Fc("mod");return Gc(e)||Hc("mod"),t=>("number"!=typeof t&&qc("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&qc("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??Fc("clamp");Gc(e)||Hc("clamp");const n=t?.[1]??Fc("clamp");Gc(n)||Hc("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&qc("clamp"),Math.min(Math.max(t,o),s))},fix:t=>{const e=t?.[0]??"0";return Gc(e)||Hc("fix"),t=>("number"!=typeof t&&qc("fix"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&qc("locale"),t.toLocaleString(e??o.locale))},uc:t=>t=>String(t).toUpperCase(),lc:t=>t=>String(t).toLowerCase(),cap:t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)},trim:t=>t=>String(t).trim(),slice:t=>{const e=[],n=t?.[0]??Fc("slice");Gc(n)||Hc("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(Gc(o)||Hc("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??Fc("substr");Gc(e)||Hc("substr");const n=t?.[1]??Fc("substr");return Gc(n)||Hc("substr"),t=>String(t).substr(Number(e),Number(n))},pad:t=>{const e=t?.[0]??Fc("pad");Gc(e)||Hc("pad");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},rep:t=>{const e=t?.[0]??Fc("rep");return Gc(e)||Hc("rep"),t=>String(t).repeat(Number(e))},rev:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??Fc("truncate");Gc(e)||Hc("truncate");const n=Number(e),o=t?.[1]??"…";return t=>{const e=String(t);return e.length<=n?e:e.slice(0,n)+o}},join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||Y("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=t?.[0]??"0";return Gc(e)||Hc("round"),t=>{"number"!=typeof t&&qc("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return Gc(e)||Hc("floor"),t=>{"number"!=typeof t&&qc("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return Gc(e)||Hc("ceil"),t=>{"number"!=typeof t&&qc("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return Gc(e)||Hc("percent"),t=>("number"!=typeof t&&qc("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??Fc("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||Uc("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||Uc("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||Uc("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||Uc("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||Uc("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!t,truthy:t=>t=>!!t,defaults:(t,e)=>{const n=t?.[0]??Fc("defaults"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t||o},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),null:t=>t=>""===t?null:t},Kc={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],inc:[0,1],dec:[0,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],fix:[0,1],locale:[0,1],uc:[0,0],lc:[0,0],cap:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],pad:[1,2],rep:[1,1],rev:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],boolean:[0,0],number:[0,0],string:[0,0],null:[0,0]},Jc=Vc,Qc=Vc;let Xc=!1;const Yc={name:"formats",install(){Xc||(Xc=!0,dt("input",Qc,Kc),dt("output",Jc,Kc))}};function Zc(t){return-1!==t.indexOf(H)}function tu(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+a;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(Zc(o))return null;const s=o.slice(1).split(a);return s[0]===l||s.some(t=>0===t.length)?null:o}function eu(t){return 0===t.length?t:a+su(t.slice(1))}function nu(t,e,n){const o=a+t.repeat,s=e.length<=n.length?e:n,r=e.length<=n.length?n:e;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let t=0;t<i.length;t+=o.length)if(!i.startsWith(o,t))return!1;return!0}function ou(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(a,o-1))if(nu(t,e,n.slice(0,o)))return!0;return!1}function su(t){const e=t.split(a);for(let t=0;t<e.length;t++)e[t]===l||Number.isNaN(Number(e[t]))||(e[t]=l);return e.join(a)}function ru(t,e){const n=t.repeat.split(a),o=a+t.repeat;let s=e;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===a+t.repeatList+a+"length")return!0;for(let t=1;t<n.length;t++)if(s===a+n.slice(0,t).join(a))return!0;return!1}function iu(t,e,n){n<0&&Y(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=a+t.repeat;const s=o+e;let r=0;for(const t of s.split(a))t===l&&r++;return r>c&&Y(`[wcs/recursion-depth-exceeded] Recursion on "${t.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function au(t,e){return iu(t,"",e)}function lu(t,e,n){if(!n.startsWith(t.anchor))return null;if(e.length>0&&!n.endsWith(e))return null;if(n.length<t.anchor.length+e.length)return null;const o=n.slice(t.anchor.length,n.length-e.length);if(0===o.length)return 0;const s=a+t.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function cu(t,e,n){const o=t.recursionRegistry,s=tu(o.spec,n);null===s&&Y($i(n,o.spec.recursiveAnchor));const r=function(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=e.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(t,e){const n=t.spec;if(!e.startsWith(n.anchor))return null;const o=a+n.repeat;let s=0,r=n.anchor.length;for(;e.startsWith(o,r);)r+=o.length,s++;return r!==e.length&&46!==e.charCodeAt(r)?null:s}(e,n.pathInfo.path)}(e,o);return null===r&&Y(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function uu(t,e,n,o,s){const r=o.spec,i=[],l=new Map,c=[],u=r.repeatList,d=r.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void i.push(hn(t,n));const s=m(o[e],n,null).rows;for(let n=0;n<s.length;n++)p(t,e+1,s[n])};function m(o,s,i){const a=hn(o,s),c=Fe(n.stateElement,a),d=nl(t,a,e,n),f=null===i?null:((t,e,n)=>{if(!Array.isArray(e)||0===e.length)return null;const o=e;return h.has(o)&&Y(`[wcs/recursion-cycle] "${t}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&Y(`[wcs/recursion-shared-list] "${t}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${u}" array.`),o})(o.path,d,i),p=yr(s,$e(c),d);return l.set(c,Array.isArray(d)?d:[]),null!==f&&null!==i&&i.add(f),{rows:p.newIndexes,tracked:f}}const g=(t,e,n)=>{const{rows:r,tracked:l}=m(e,n,f);if(0===r.length)return;const d=(t=>{const e=c[t];if(void 0!==e)return e;const n=o.concretePathAt(s,t),r=0===s.length?n:o.concretePathAt("",t),i={nodePath:r,concretePathInfo:et(n),childListPathInfo:et(r+a+u)};return c[t]=i,i})(t),y=l;h.add(y);const b=d.concretePathInfo.wildcardCount===t+1;for(let e=0;e<r.length;e++){const n=r[e];b?i.push(hn(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,et(d),null);for(const[t,e]of l)Se(t,e);return i}const du={write(t,e){if(!0!==t.hasRecursion)return Da;const n=t.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);return null!==n&&Y(`[wcs/recursion-readonly] "${e.pathInfo.path}" writes into the recursive getter "${n}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),Da},get(t,e,n,o){if(!0!==t.stateElement.hasRecursion)return Da;if("$getAll"===e)return(e,s)=>{if(Zc(e)){if(void 0!==s)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=tu(r.spec,o);null===i&&Y($i(o,r.spec.recursiveAnchor)),Array.isArray(s)||Y(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&Y(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=uu(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(nl(t,a[o],e,n));return l}(o,n,t,e,s);e=cu(t.stateElement,t,e)}return Al(o,0,n,t)(e,s)};if("$setAll"===e)return(e,s,r,i)=>Zc(e)?function(t,e,n,o,s,r,i){Va(n);const a=n.stateElement.recursionRegistry,l=tu(a.spec,o);null===l&&Y($i(o,a.spec.recursiveAnchor));const c=eu(l);Array.isArray(s)||Y(Si(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&Y(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&Y(Si(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&Y(Si(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(t,e,n){ru(t,n)&&Y(`[wcs/recursion-structural-write] "${e}" writes the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const u=a.conflictingRecursiveGetter(c);null!==u&&Y(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${u}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const d=uu(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(Nl(t,d[o],r,e,n),h++);return h}(o,n,t,e,s,r,i):Cl(o,0,n,t)(e,s,r,i);if(36!==e.charCodeAt(0)&&Zc(e)){const s=Qa(cu(t.stateElement,t,e)),r=El(o,s,n,t);return nl(o,hn(s.pathInfo,r),n,t)}return Da}};let hu=!1;function fu(t,e){"string"==typeof e&&0!==e.length||Y(`[wcs/recursion-declaration-invalid] ${F} ${t} must be a non-empty string.`);const n=e.split(a);n.some(t=>0===t.length)&&Y(`[wcs/recursion-declaration-invalid] ${F} ${t} "${e}" must not contain empty path segments.`),n.length<2&&Y(`[wcs/recursion-declaration-invalid] ${F} ${t} "${e}" must name a list element: a property path ending with "${a}${l}" (for example "nodes${a}${l}").`),n[n.length-1]!==l&&Y(`[wcs/recursion-declaration-invalid] ${F} ${t} "${e}" must end with "${a}${l}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&Y(`[wcs/recursion-declaration-invalid] ${F} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&Y(`[wcs/recursion-declaration-invalid] ${F} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===l&&Y(`[wcs/recursion-declaration-invalid] ${F} ${t} "${e}" must have exactly one "${l}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===H&&Y(`[wcs/recursion-declaration-invalid] ${F} ${t} "${e}" must not contain "${H}" — the declaration is what gives "${H}" its meaning.`),isNaN(Number(n[o]))||Y(`[wcs/recursion-declaration-invalid] ${F} ${t} "${e}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const pu=new WeakSet;function mu(t){return"function"==typeof t.get&&pu.has(t.get)}const gu="[wcs/recursion-declaration-invalid]";class yu{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(t,e){this.spec=t;const n=ql(e);for(const[e,o]of Object.entries(n)){if(!Zc(e))continue;"function"==typeof o.set&&Y(`${gu} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&Y(`${gu} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=tu(t,e);null===n&&Y($i(e,t.recursiveAnchor)),0===n.length&&Y(`${gu} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${a}total"), not the node.`),ru(t,eu(n))&&Y(`${gu} "${e}" names the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${t.recursiveAnchor}${a}total").`),this._definitions.set(e,{recursivePath:e,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(t){for(const[e,n]of Object.entries(t)){if(Zc(e)||mu(n))continue;const t=this._matchExpansion(e);null!==t&&Y(`${gu} "${e}" is already defined on the state, so the recursive getter "${t}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const t=Array.from(this._definitions.values());for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)nu(this.spec,t[e].suffix,t[n].suffix)&&Y(`${gu} "${t[e].recursivePath}" and "${t[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(t){for(const e of this._definitions.values())if(ou(this.spec,e.suffix,t))return e.recursivePath;return null}recursiveGetterOwningPath(t){const e=this._ownerByPathInfo.get(t);if(void 0!==e)return e;const n=this.recursiveGetterOwning(t.path);return this._ownerByPathInfo.set(t,n),n}recursiveGetterOwning(t){const e=this._accessors.get(t);if(void 0!==e)return e.recursivePath;const n=su(t),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let t=n.lastIndexOf(a);null===s&&t>this.spec.anchor.length;t=n.lastIndexOf(a,t-1))s=this._matchExpansion(n.slice(0,t))}return this._ownerByPath.set(n,s),s}_matchExpansion(t){for(const e of this._definitions.values())if(null!==lu(this.spec,e.suffix,t))return e.recursivePath;return null}materializeForPathInfo(t,e){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(e);if(void 0!==n)return n;const o=this.materializeFor(t,e.path);return this._accessorByPathInfo.set(e,o),o}materializeFor(t,e){const n=this._accessors.get(e);if(void 0!==n)return n;if(!e.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const t of this._definitions.values()){const n=lu(this.spec,t.suffix,e);null!==n&&(null!==o&&Y(`"${e}" matches both "${o.recursivePath}" and "${t.recursivePath}".`),o=t,s=n)}return null===o?null:this._define(t,o,s,e)}_define(t,e,n,o){const s=t.findStateDescriptor(o);void 0===s||mu(s)||Y(`"${o}" is already defined on the state, so the recursive getter "${e.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:e.recursivePath,depth:n}),i=e.get,a=function(){return i.call(this)};var l;return l=a,pu.add(l),t.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(t,n),this._accessors.set(o,r),r}_registerListPaths(t,e){for(const n of function(t,e){const n=[];n.push(t.anchorList);for(let o=0;o<e;o++)n.push(au(t,o)+a+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){const n=new Set(this._accessors.keys());return function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&mu(n)&&delete e[t]}for(const e of[t.staticDependency,t.dynamicDependency]){for(const t of n)e.delete(t);for(const[t,o]of e){let s=null;for(let t=0;t<o.length;t++)n.has(o[t])?s??=o.slice(0,t):s?.push(o[t]);null!==s&&(0===s.length?e.delete(t):e.set(t,s))}}!function(t,e,n){for(const o of n){const n=et(o),s=n.wildcardParentPathInfos,r=(e,o,i)=>{if(i===s.length)return void Es(He(t,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=e;for(const t of s[i].segments.slice(a))l=l?.[t];if(!Array.isArray(l))return;const c=Ns(l);if(null===c)return;const u=Math.min(c.length,l.length);for(let t=0;t<u;t++)r(l[t],c[t],i+1)};r(e,null,0)}}(t,e,n)}}(t,e,n),n}concretePathAt(t,e){let n=this._concreteBySuffix.get(t);void 0===n&&(n=[],this._concreteBySuffix.set(t,n));let o=n[e];return void 0===o&&(o=iu(this.spec,t,e),n[e]=o),o}accessorFor(t){return this._accessors.get(t)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const bu="recursionSpec",wu="recursionRegistry",vu={order:5,validateEarly(t,e,n){const o=function(t){const e=t[F];if(void 0===e)return null;"object"==typeof e&&null!==e||Y(`[wcs/recursion-declaration-invalid] ${F} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(e);0===n.length&&Y(`[wcs/recursion-declaration-invalid] ${F} must declare exactly one anchor; it is empty.`),n.length>1&&Y(`[wcs/recursion-declaration-invalid] ${F} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];fu("anchor",o),"string"!=typeof s&&Y(`[wcs/recursion-declaration-invalid] ${F} entry "${o}" must map to the repeating sub-path as a string (for example "children${a}${l}").`),fu("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(a)),i=s.slice(0,s.lastIndexOf(a)),c=r+a+H;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:c,anchorList:r,repeatList:i})}(e);n.set(bu,o),n.set(wu,null===o?null:new yu(o,e))},preCommit(t,e,n){const o=t.recursionRegistry;if(null!==o)for(const e of o.forgetGenerated(t,n.get("previousState")))t.addGeneratedPath?.(e);const s=n.get(wu)??null;t.setRecursionRegistry?.(s),null!==s&&t.attachAddressHooks?.("recursion",F)},apply(t,e,n){const o=n.get(bu)??null;null!==o&&t.addListPath(o.anchorList)}};let _u=!1;const $u={name:"recursion",install(){_u||(_u=!0,hu||(hu=!0,Ba("recursion",du)),Ua("recursion",vu))}},Su={written:function(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let xu=!1;function Pu(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function Nu(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function ku(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function Iu(t){return t.startsWith("$")}function Au(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function Eu(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||Y(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||Y(`${e} entries must be non-empty strings.`),t.startsWith("$")&&Y(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&Y(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function Cu(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||Y(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=Bt(t);null!==r&&"function"==typeof r.define||Y(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&Y(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const t of Array.from(e.childNodes))i.content.appendChild(a.importNode(t,!0));const l=e.mode,{bindables:c,commands:u,streamBackedBindables:d}=function(t){const e=Eu(t,M)??[],n=Eu(t,O)??[],o=ql(t),s=function(t){const e=t[W];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}Y(`${M} entry "${t}" is not declared on the state.${st(t,Au(o,"value"))}`)}"function"==typeof e.value&&Y(`${M} entry "${t}" is a method. Declare it in ${O} instead.`)}for(const t of n){const e=o[t];void 0===e&&Y(`${O} entry "${t}" is not declared on the state.${st(t,Au(o,"method"))}`),"function"!=typeof e.value&&Y(`${O} entry "${t}" is not a method. Declare it in ${M} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||u.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(V))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=Bt(this._shadow);return null!==t&&Ft(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(m.bindableEventMap).length>0){const e=t.querySelector(p);e?(xu||(xu=!0,Ba("dcc",Su)),e.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${M} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=ql(n);for(const[t,e]of Object.entries(g)){if(Iu(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=ku(t,o)}else n.get=Pu(t),n.set=Nu(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:Pu(t),set:Nu(t)});r.define(s,m)}const Tu={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(V)?async function(t,e,n){const o=t;try{o.hasAttribute("bind-component")&&Y(`"bind-component" cannot be used inside a [${V}] host. DCC state comes from the template, not from a component property.`);const s=await async function(t,e){try{if(t.hasAttribute("src")){const e=t.getAttribute("src");if(e.endsWith(".js"))return await Ta(e);Y(`DCC: Unsupported src type: ${e}`)}const n=t.querySelector('script[type="module"]');if(n)return await Ca(n,e.tagName.toLowerCase());Y(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}catch(t){Y(`DCC: Failed to load state: ${t}`)}}(o,e);Cu(e,n,s),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}(t,e.host,e):null}};let Mu=!1;const Ou=new WeakMap;function Lu(t,e,n){let o=Ou.get(t);void 0===o&&(o=new Map,Ou.set(t,o));null!=o.get(e)&&Y(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function Ru(t,e){if(null===t)return!1;const n=Ou.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+a)||t.startsWith(e+a))return!0;return!1}const ju=new WeakMap;function Du(t,e){return new Proxy({},{get(n,o){if("string"==typeof o&&"then"!==o){if("$"===o[0]){if("$postUpdate"===o)return n=>{e.$postUpdate(t+a+n)};if("$getAll"===o||"$setAll"===o||"$resolve"===o){const n=o;return(o,...s)=>e[n](t+a+o,...s)}return e[o]}return e[t+a+o]}},set:(n,o,s)=>("string"!=typeof o||(e[t+a+o]=s),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Wu=new WeakMap,zu=[],Bu=new WeakMap,Fu=new WeakSet;function Hu(t){console.error(`[@wcstack/state] volume "${t.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),t.onGrafted(null)}let qu=null;const Uu=new WeakMap,Gu=new Set;function Vu(t,e,n,o){let s=Uu.get(t);if(void 0===s){if(!o)return null;s=new Map,Uu.set(t,s)}let r=s.get(e);if(void 0===r){if(!o)return null;r=new Map,s.set(e,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function Ku(t,e){if(!t.component.isConnected)return!1;const n=he(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function Ju(t,e,n,o){const s=Vu(t,e,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&Ku(n,e)?n:null}(r,o);if(null!==t)return{record:t,entry:r.entry}}let i=null,l=null;for(const t of s.holders){const r=t.ref.deref();void 0!==r?Ku(r,o)&&(null!==l&&Y(`[wcs/mount-export-ambiguous] "${e}${a}${n}" is exported by two mounted components on the same instance: <${l.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=t,l=r):s.holders.delete(t)}return null===i||null===l?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:l,entry:i.entry})}function Qu(t){const e=t.parentStateElement,n=he(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[ke](n,()=>{t.$postUpdate(o.exportedPath)})})}const Xu=new WeakMap;class Yu{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,s,r){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return hn(et(this.markerParentPath+a+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(uc(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,s,...r)=>{const i=r.length>0?cc(t,e):uc(t,e),a=dc(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a="$setAll"===s?cc(t,e):uc(t,e),l=dc(0,e,a,r,n);return o[s](a,l,...i)}}return this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return Ya(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[uc(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||Y(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(t,e)?(t[e]=n,!0):(this.receiver[cc(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return uc(this.record,e),!0}catch{return!1}}}function Zu(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=Xu.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},Xu.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(i,new Yu(t,s,e.listIndex,r,n,o))}function td(t,e){const n=function(t){return hc.get(t)??null}(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&Y(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&ts(e).dispose(),function(t,e){bc||(bc=!0,de=t=>hc.has(t)?t.host:null),hc.set(t,e),gc.set(e,t);let n=pc.get(e.parentStateElement);void 0===n&&(n=new Map,pc.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=fc.get(e.component);void 0===o&&(o=new Map,fc.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&mc.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}(e,t),e instanceof ShadowRoot&&function(t,e){const n=Vi.get(t);if(void 0!==n){if(n===e)return;Y("A state tree is already registered on this root.")}Vi.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const s=ac.exec(e.statePathName);if(null!==s){const r=function(t,e){return void 0===e?t.delta:et(uc(t,e)).wildcardCount-et(e).wildcardCount}(t,n);o=0===r?e.statePathName:`$${Number(s[1])+r}`}else if(o=uc(t,e.statePathName),"for"===e.bindingType){const n=et(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+a+l,n)}const r=e.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(m)&&null!==lc(t,e.statePathName);return o!==e.statePathName||i?{...e,statePathName:o,statePathInfo:et(o),...i?{propModifiers:[...r,m]}:{}}:e}(t,e,n);Q(e);const o=he(t.component);_a(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),Wi(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=uc(t,n)}catch{continue}const o=e.indexOf(a+t.marker);if(-1===o)continue;const s=e.slice(0,o+1+t.marker.length),r=e.slice(s.length+1),i=e.slice(0,o)+a+r,l=et(i);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:e,exportedPath:i};t.exports.set(i,c),Vu(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,i),Ul?.markExported(t.parentStateElement,i)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=he(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const s=`${n}|${o.exportedPath}`;if(Gu.has(s))continue;const r=et(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[ke](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(Gu.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(t),Qu(t),o=e,s=Promise.resolve(),Ki.set(o,s),s.then(()=>ta(o),()=>{})}function ed(t,e){const n=ts(e),o=he(t.component);n.forEachActiveBindingNode(t=>fe(t,o)),Di(n.rebindAddresses()),Qu(t)}function nd(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const od={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const s=vc(t,e.pathInfo.path);if(null!==s)return Zu(s,e,n,o)}return Da},readMissing(t,e,n,o,s){if(null===n){if(Ru(t.rootNode??null,e.pathInfo.path))return;return Da}if(!0===t.hasMounts){const n=Ju(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s){const r=Zu(t,hn(et(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(n.record,n.entry,e.listIndex,o,s)}return Da},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=ju.get(t);if(void 0===n||0===n.size)return null;const o=e+a;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&Y(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return Da},writeMissing(t,e,n,o,s,r,i){if(!0===t.hasMounts){const n=Ju(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s,r){const i=Zu(t,hn(et(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(n.record,n.entry,e.listIndex,s,r,i)}return Da},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=vc(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(a,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const s=-1===o?e:e.slice(0,o),r=-1===o?"":e.slice(o+1),i=t.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:t.delta}(t,o)}return 0},handlerScope(t,e,n,o,s){if(!0!==t.hasMounts)return s;const r=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=hc.get(n);if(void 0!==t)return t;n=n.parentNode}return hc.get(e)??null}(e,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(t,e,n){const o=function(t){return Wu.get(t)??zu}(t);for(const s of o){const o=s.mountPath+a,r=new Set,i={};for(const n of e){if(n.absolutePathInfo.stateElement!==t)continue;const e=n.absolutePathInfo.pathInfo.path;if(e!==s.mountPath&&!e.startsWith(o))continue;if(-1!==e.indexOf("#"))continue;const a=e===s.mountPath?"":e.slice(o.length);if(""===a)continue;r.add(a);const l=n.absolutePathInfo.pathInfo.wildcardCount;if(l>0&&null!==n.listIndex){const t=Qe(n.listIndex,l);(i[a]??=[]).push(t)}}if(r.size>0)try{s.callback.call(Du(s.mountPath,n),Array.from(r),i)}catch(t){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>Ru(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(function(t){const e=pc.get(t);return void 0!==e&&e.size>0}(e))for(const n of wc(e)){if(!nd(n.component,t))continue;const e=yc(n);null!==e&&ed(n,e)}}(e,t)}};let sd=!1;const rd=new WeakMap;function id(t){let e=rd.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},rd.set(t,e)),e}function ad(t,e){null!==e.slotRootNode&&(function(t,e,n){const o=Ou.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function ld(t,e,n){if(e.slotRootNode===n)return!0;const s=e.mountPath;try{Lu(n,s,t)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return Xi(n)?.markHasVolume?.(),e.slotRootNode=n,!0}const cd={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=id(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{Lu(n,e.mountPath,t),Xi(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,Dl}return async function(t,e){const n=t,s=t.connectedRootNode,r=n.getAttribute("mount");try{!function(t){0===t.length&&Y('"mount" requires a non-empty tree path.');const e=et(t);for(const n of e.segments)0===n.length&&Y(`"mount" path "${t}" has an empty segment.`),n===l&&Y(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&Y(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),n.hasAttribute("bind-component")&&Y('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),Lu(s,r,t),Xi(s)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=s}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===Xi(s)&&function(t,e){const n=()=>{if(null!==Xi(t))return;const n=t.querySelectorAll(o.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=t.ownerDocument??t;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const i=n=>{e.graftInfo=n,t.markInitialized(),null===n&&ad(t,e),t.settleInitialization()};let a;try{a=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void i(null)}const c=t.connectedRootNode??null;null!==c&&ld(t,e,c)?function(t,e,n,o,s,r){const i={mountPath:n,volumeState:o,onGrafted:s,acquireSlot:r};null===e?(uf(),function(t,e){if(Fu.has(t))return void Hu(e);let n=Bu.get(t);void 0===n&&(n=[],Bu.set(t,n)),n.push(e)}(t,i)):lf(e,i)}(c,Xi(c),r,a,i,()=>ld(t,e,c)):i(null)}(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=id(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&Xi(n)===e.graftInfo.rootStateElement&&rf(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==rd.get(t)?.initializing)return;const e=t.getAttribute("mount");Y(`Cannot replace the state of <${o.tagNames.state} mount="${e}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){Fu.add(t);const e=Bu.get(t);if(void 0!==e){Bu.delete(t);for(const t of e)Hu(t)}}(e)},initializeFailureCleared(t,e){!function(t){Fu.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=id(t);return null!==e.graftInfo&&rf(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,ad(t,e)),t.clearConnectedRootNode(),!0}};let ud=!1;const dd=new WeakMap;function hd(t,e){let n=dd.get(t);n||(n=new Set,dd.set(t,n)),n.add(e)}const fd=new WeakMap,pd=new WeakMap,md=new WeakMap,gd=new WeakMap,yd={isComplete:function(t,e){return!0===dd.get(t)?.has(e)},isDeclared:function(t,e){return!0===fd.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=pd.get(t);o||(o=new Map,pd.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=md.get(t);o||(o=new Map,md.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)},rememberOverwrittenValue:function(t,e,n,o){let s=gd.get(t);s||(s=new Map,gd.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}};const bd=new WeakMap;class wd{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=bd.get(t);return n?n.get(e)??null:null}(t,e)??Y("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const vd=t=>()=>t;function _d(t,e,n,o){!function(t,e,n){let o=bd.get(t);o||(o=new Map,bd.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(function(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}(o));const s=function(t,e){const n=new wd(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:vd(s),enumerable:!0,configurable:!0}),hd(e,n),$d(e,n)}function $d(t,e){if(T in t){const n=t[T];"function"==typeof n?n.call(t,e).catch(t=>{Y(`Error in ${T}: ${t instanceof Error?t.message:String(t)}`)}):Y(`${T} is not a function.`)}}const Sd=new Set;function xd(t,e){Sd.has(t)||(Sd.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Pd(t){const e=t.rootEntry,n=he(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[ke](n,()=>{o=t[e.outerPathInfo.path]})}),o}const Nd=new WeakMap;function kd(t,e){t.landInitialization(),Y(e)}async function Id(t,e){const n=t;if(n.hasAttribute("bind-component")){const i=n.parentNode,l=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,c=l?Wt(l):null;null!==l&&null!==c||Y(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||l.hasAttribute(o.bindAttributeName)||kd(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const u=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&u.push('<script type="module">'),u.length>0&&Y(`"bind-component" cannot be combined with ${u.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(t,e){let n=fd.get(t);n||(n=new Set,fd.set(t,n)),n.add(e)}(l,d);const h=Bt(l);null===h&&Y(`CustomElementRegistry is unavailable for <${c}>.`),await h.whenDefined(c.toLowerCase()),l.hasAttribute(o.bindAttributeName)&&await Rt(l),d in l||Y(`Component does not have property "${d}" for state binding.`);let f=l[d];"object"==typeof f&&null!==f||Y(`Component property "${d}" is not an object for state binding.`);const p=function(t,e){const n=pd.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(l,d);if(void 0!==p&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=te(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(l,d)&&(l[d]=p,f=p),e.boundComponent=l,e.boundComponentStateProp=d,t.setBoundComponent(l,d),i instanceof ShadowRoot||(te(l)??[]).some(t=>t.propSegments[0]===d)||kd(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${d}: path").`),l.hasAttribute(o.bindAttributeName)){const o=(te(l)??[]).filter(t=>t.propSegments[0]===d);if(o.length>0){const u=Xi(l.getRootNode())??kd(t,`No state tree found on this root for mount host <${c}>.`);let h=(s=l,r=d,fc.get(s)?.get(r)??null);const p=null!==h;if(null===h&&(function(t,e,n){const o=gd.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;gd.get(t).delete(e)}}(l,d,f),h=function(t,e,n,o,s,r=new Set){0===n.length&&Y(`Cannot build a mount record without host bindings for "${e}".`);const i=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(a);l.has(n)&&Y("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(m)};i.push(o),0===e.length&&(c=o)}i.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++Ql,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(s),p=new Set;for(const t of i)t.innerSegments.length>0&&p.add(t.innerSegments[0]);const g={};for(const t of Object.keys(s))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof s[t]&&(r.has(t)||p.has(t)||(g[t]=s[t]));return{id:u,marker:d,component:t,stateProp:e,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?d:c.outerPathInfo.path+a+d,stateObject:s,getterKeys:h,setterKeys:f,injectedKeys:r,mappedKeys:p,privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(l,d,o,u,f,function(t,e){return md.get(t)?.get(e)}(l,d)),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp;let s,r=!1;for(const i of e){if(null===t.rootEntry)continue;if(r||(s=Pd(t),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const e=t.rootEntry.outerPathInfo.path;xd(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${e}.${i}" (${o}: ${e}). Remove the default to read the tree, or rename it to keep it private.`)}}(h)),e.mountRecord=h,n.parentNode!==i)return;try{td(h,i instanceof ShadowRoot?i:l)}catch(e){throw t.landInitialization(),e}if(!p){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=he(t.component);let s;return e[ke](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(t,e,n){const o=t.parentStateElement,s=(t,e)=>{let s;return o.createState(t,t=>{s=n(t,()=>e(t))}),s};return"$postUpdate"===e?e=>s("readonly",n=>n.$postUpdate(uc(t,e))):(n,o,...r)=>{const i="$setAll"===e||"$resolve"===e&&r.length>0,a=i?cc(t,n):uc(t,n),l=he(t.component)?.listIndex.indexes??[],c=dc(0,n,a,"$resolve"===e?o??[]:o,l);return s(i?"writable":"readonly",t=>t[e](a,c,...r))}}(t,s,n);let r;return e.createState("readonly",e=>{r=n(e,()=>e["$"===s[0]?s:uc(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:cc(t,s)]=r})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return uc(t,n),!0}catch{return!1}}})}(h);Object.defineProperty(l,d,{get:()=>t,enumerable:!0,configurable:!0}),hd(l,d)}return $d(l,d),function(t){const e=Xl.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(H)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;Yl.has(n)||(Yl.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(h),void Zl(h,"$connectedCallback")}}_d(t,e.boundComponent,e.boundComponentStateProp,f)}var s,r}const Ad={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=Nd.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Nd.set(t,e)),e}(t);return Id(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=Nd.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&ed(n,o)}),Zl(n,"$connectedCallback"),!0},disconnecting(t){const e=Nd.get(t);return void 0!==e&&null!==e.mountRecord&&(Zl(e.mountRecord,"$disconnectedCallback"),Qu(e.mountRecord),t.clearConnectedRootNode(),!0)}};let Ed=!1;const Cd=new WeakMap,Td=new Set,Md=new Set;function Od(t){return t.byFromPath.size>0||t.byResetPath.size>0}function Ld(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function Rd(t){return Cd.get(t)}function jd(t){Dd(t),Cd.delete(t)}function Dd(t){Td.delete(t),Md.delete(t)}const Wd=new WeakMap,zd=new WeakMap,Bd=new Set,Fd=new Map;function Hd(t){return Wd.get(t)??Fd}const qd=new Map;function Ud(t){return zd.get(t)??qd}function Gd(t){0===t.length&&Y(`[wcs/watch-declaration-invalid] ${z} entry name must be a non-empty state path.`),t.startsWith("$")&&Y(`[wcs/watch-declaration-invalid] ${z} entry "${t}" must not start with "$" (reserved namespace).${rt}`),t.includes("@")&&Y(`[wcs/watch-declaration-invalid] ${z} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${rt}`),t in Object.prototype&&Y(`[wcs/watch-declaration-invalid] ${z} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=et(t);for(const n of e.segments)0===n.length&&Y(`[wcs/watch-declaration-invalid] ${z} entry "${t}" has an empty path segment.${rt}`);return e.wildcardCount>c&&Y(`[wcs/watch-declaration-invalid] ${z} entry "${t}" exceeds the maximum wildcard depth (128).`),e}let Vd=0,Kd=0;function Jd(t){Vd=t+1}function Qd(){Vd=0}function Xd(){Vd>Kd&&(Kd=Vd)}const Yd=new WeakMap;function Zd(t,e,n){let o=Yd.get(t);void 0===o&&(o=new Map,Yd.set(t,o)),o.set(e,n)}const th=new Map;function eh(t,e){th.has(t)||th.set(t,e)}function nh(t){return th.get(t)}const oh={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||eh(n,o)},swapped(t,e,n){var o;o=n,th.has(o)&&eh(e,nh(n))}};function sh(t){for(let e=t;null!==e;e=e.parentListIndex)if(Ps(e))return!0;return!1}function rh(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[Ie](hn(e.wildcardParentPathInfos[i],r)),l=Ns(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=Je(o,i,e.wildcardCount);if(l!==c&&!$s(l,c)){if(Ps(c))return"gone";s="replaced"}r=l}return s}function ih(t,e,n){const o=new Map;for(const s of n){const n=rh(t,e,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),t=>t.row)}const ah=new Set;function lh(t){ah.delete(t)}const ch=Symbol("wcs-stream-last-notified-uncertain"),uh=new WeakMap;function dh(t,e){const n=uh.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function hh(t,e){const n=uh.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:ch,error:Object.is(o.error,null)?null:ch})}const fh=new WeakMap;function ph(t){return fh.get(t)??new Map}function mh(t){lh(t);const e=fh.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,hh(t,n.name)}const gh=new WeakSet;let yh=0;function bh(t){return Rd(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function wh(t){if(0===Md.size)return;if(e=t.absolutePathInfo.stateElement,!Md.has(e))return;var e;const n=bh(t);if(void 0!==n)for(const t of n)vh(t)}function vh(t){gh.has(t)||(gh.add(t),yh++)}function _h(t){return!!gh.delete(t)&&(yh--,!0)}const $h=/^(?:0|[1-9]\d*)$/;function Sh(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function xh(t){if("object"!=typeof t||null===t||Object.isFrozen(t))return null;const e=Object.getPrototypeOf(t);return Array.isArray(t)?e===Array.prototype&&Reflect.ownKeys(t).every(e=>"length"===e||"string"==typeof e&&$h.test(e)&&Sh(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&Sh(t,e))?null:"object"}function Ph(t,e){const n=xh(t);if(null===n)return t;const o=t,s=e.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(t.length):null===Object.getPrototypeOf(t)?Object.create(null):{},e.set(o,r);for(const t of Object.keys(o))r[t]=Ph(o[t],e);return r}function Nh(t){return Ph(t,new Map)}function kh(t,e,n){if(Object.is(t,e))return!0;const o=xh(e);if(null===o||"object"!=typeof t||null===t)return!1;const s=t,r=e;if("array"===o){if(!Array.isArray(t)||t.length!==e.length)return!1}else if(Array.isArray(t)||Object.keys(s).length!==Object.keys(r).length)return!1;if(xh(t)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let e=0;e<t.length;e++)if(!kh(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&kh(s[t],r[t],n))}function Ih(t,e){return kh(t,e,new Map)}const Ah=new WeakMap;function Eh(t,e){if("function"!=typeof e)return;const n=Ah.get(e);void 0===n?Ah.set(e,new Set([t])):n.add(t)}const Ch={"read-source":t=>`${B} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-output":t=>`${B} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${B} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${B} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${B} could not write the output "${t}".`},Th={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Mh(t,e,n){null!==pe&&pe({type:"state:watch-error",phase:e,path:`${B}.${t}`,error:n})}function Oh(t,e,n){console.error(`[@wcstack/state] ${Ch[n](t)}`,e),Mh(t,Th[n],e)}function Lh(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function Rh(t,e){e.then(void 0,()=>{}),Oh(t,new TypeError(`${B} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const jh=new WeakSet,Dh=Object.freeze([]);function Wh(t,e,n){let o=t.get(n);return void 0===o&&(o={stateElement:e,entry:n,rows:[],reset:!1},t.set(n,o)),o}function zh(t,e){let n=0;for(;n<t.indexes.length-1&&t.indexes[n]===e.indexes[n];)n++;return t.indexes[n]-e.indexes[n]}function Bh(t,e){return e.has(t.stateElement)&&!0===Rd(t.stateElement)?.entries.has(t.entry)}function Fh(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>Hh(n,t))||_h(e)}function Hh(t,e){return Bs().hasQueuedPath(t,e)}function qh(t,e){!function(t,e,n){if(0!==yh)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=bh(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||_h(e)}}(t,e,Hh)}function Uh(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function Gh(t,e,n){if(!Bh(t,n))return Fh(t),null;const{stateElement:o,entry:s}=t;if(t.reset)return{group:t,next:s.initial};const r=s.source;if(function(t,e){for(const n of e.pathInfo.cumulativePaths)if(t.getterPaths.has(n))return!0;return!1}(o,r))return function(t,e,n){if(jh.has(t))return;jh.add(t);const o=`[wcs/scan-source-computed] ${B} entry "${e}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),Mh(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=ph(t).get(e);if(void 0===o)return!1;for(const t of o.depAddresses)if(n.has(t))return!0;return!1}(o,r.pathInfo.segments[0],e))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",e=>{const n=e[s.name],o=0===r.pathInfo.wildcardCount?t.rows:ih(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(zh)){let n;try{n=Uh(e,r,t)}catch(t){Oh(s.name,t,"read-source");continue}const o=a(l,n,nh(t.absAddress),...t.indexes);if(Lh(o))return void Rh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){Oh(s.name,t,i.failure)}return i.plan}function Vh(t,e){const{group:n}=t;if(!Bh(n,e))return void Fh(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||_h(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!Ih(o,s.initial):!Object.is(o,t.next)){const o=n.reset?Nh(s.initial):t.next;e[s.name]=o,Eh(s.name,o)}})}catch(t){Oh(s.name,t,"write")}}function Kh(t){of(),(0!==Hd(t).size||0!==Ud(t).size||function(t){const e=Cd.get(t);return void 0!==e&&Od(e)}(t))&&(function(t){Bd.add(t),function(t){const e=Cd.get(t);void 0!==e&&(Od(e)&&Td.add(t),function(t){return t.eventResetByPath.size>0}(e)&&Md.add(t))}(t)}(t),function(t){const e=[];for(const n of Hd(t).values())Jh(t,n)&&e.push(n);for(const n of Ud(t).values())for(const o of n)Jh(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{Zd(t,He(t,o.pathInfo,null),n[o.path])}catch(e){Xh(t,o.path,"prime",e)}})}(t))}function Jh(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const Qh={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function Xh(t,e,n,o){console.error(`[@wcstack/state] $watch ${Qh[n]} "${e}" threw.`,o),null!==pe&&pe({type:"state:watch-error",phase:n,path:e,error:o})}function Yh(t){const e=Bd;try{if(0===e.size)return void qh(t,e);const n=function(){const t=Kd;return Kd=0,t}();if(n>32){qh(t,null);const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==pe&&pe({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}!function(t,e,n){if(0!==t.length){Jd(n);try{for(const n of t)Vh(n,e)}finally{Qd()}}}(function(t,e,n){if(qh(t,e),0===Td.size)return Dh;const o=new Map;for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=Rd(t);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let e=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;e=Qe(n.listIndex,r.wildcardCount)}for(const s of i)Wh(o,t,s).rows.push({absAddress:n,indexes:e})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const e of a)Wh(o,t,e).reset=!0}if(0===o.size)return Dh;const s=Array.from(o.values()).sort((t,e)=>t.entry.order-e.entry.order),r=[];Jd(n);try{for(const n of s){const o=Gh(n,t,e);null!==o&&r.push(o)}}finally{Qd()}return r}(t,e,n),e,n),function(t,e,n){const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=Hd(t).get(s),i=Ud(t).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const e of a){let s=[];if(e.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=Qe(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(tf);const s=function(t){let e=null;for(let n=0;n<t.length;n++){const o=t[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=t[n-1];(sh(o.absAddress.listIndex)||s?.entry===o.entry&&Zh(s.indexes,o.indexes))&&(e??=new Set).add(o.entry)}if(null===e)return t;const n=new Set;for(const o of e){const e=t.filter(t=>t.entry===o),s=e[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(ih(t,o.pathInfo,e));for(const t of e)s.has(t)||n.add(t)})}catch(t){Xh(0,o.path,"evaluate",t);for(const t of e)n.add(t)}}return t.filter(t=>!n.has(t))}(o);Jd(n);try{for(const t of s){if(!e.has(t.stateElement))continue;const n=Hd(t.stateElement).get(t.entry.path)===t.entry,o=!0===Ud(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&ef(t)}}finally{Qd()}}(t,e,n)}finally{th.clear()}}function Zh(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function tf(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function ef(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=Jh(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void Xh(0,n.path,"evaluate",t)}const a=r?function(t,e){return Yd.get(t)?.get(e)}(e,o):nh(o);r&&Zd(e,o,i),null!==pe&&pe({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){Xh(0,n.path,"handler",t)}}let nf=!1;function of(){nf||(nf=!0,Ba("watch",oh),Ua("watch",sf),Ds(Yh,10),js(Xd))}const sf={order:10,register(t,e){var n;n=t,Bd.delete(n),Dd(n),Wd.delete(n),function(t){Yd.delete(t)}(t);const o=function(t,e){const n=e[z];if(void 0===n)return null;"object"==typeof n&&null!==n||Y(`[wcs/watch-declaration-invalid] ${z} must be an object mapping state paths to handler functions.${rt}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&Y(`[wcs/watch-declaration-invalid] ${z} entry "${e}" must be a function.${rt}`);const n=Gd(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){Wd.set(t,e)}(t,o),s.size>0?s:null}(t,e);t.setWatchPaths?.(o),null===o&&null==t.scanPaths||t.attachAddressHooks?.("watch",null!==o?z:B)},activate(t,n){e()||null==t.connectedRootNode||(null===n?!0===t.initialized:n===t.connectGeneration)&&Kh(t)},deactivate(t){var e;e=t,Bd.delete(e),Dd(e)}};function rf(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(Du(t.mountPath,o));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function af(t,e,n){!function(t,e,n){const o=n[z];if(void 0!==o){"object"==typeof o&&null!==o||Y(`${z} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(o))"function"!=typeof e&&Y(`${z} entry "${t}" must be a function.`),Gd(t)}const s=n[q];if(void 0!==s){"object"==typeof s&&null!==s||Y(`${q} must be an object mapping list paths to key specs.`);for(const[n,o]of Object.entries(s))(0===n.length||"string"!=typeof o&&"function"!=typeof o)&&Y(`${q} entry "${n}" must map a list path to a field name or a key function.`),t.listKeys?.has(e+a+n)&&Y(`${q} entry "${e+a+n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}void 0!==n.$streams&&Y(`Volume "${e}" declares $streams, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&Y(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[F]&&Y(`Volume "${e}" declares ${F}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys(ql(n)))-1!==t.indexOf(H)&&Y(`Volume "${e}" declares "${t}", which uses "${H}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n);const{data:o,accessors:s}=function(t){const e={},n=new Map;for(const[o,s]of Object.entries(Object.getOwnPropertyDescriptors(t)))o.startsWith("$")||("function"!=typeof s.get&&"function"!=typeof s.set?"function"!=typeof s.value&&(e[o]=s.value):n.set(o,s));return{data:e,accessors:n}}(n),r=et(e),i=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===r.segments.length&&e in t){if(i)return;Y(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<r.segments.length-1;e++){const o=r.segments[e],s=""===n?o in t:void 0!==t[n+a+o];n=""===n?o:n+a+o,s||(t[n]={})}if(r.segments.length>1&&void 0!==t[e]){if(i)return;Y(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=o}),function(t,e){let n=ju.get(t);void 0===n&&(n=new Set,ju.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,o]of s){const s=e+a+n,r=o.get,i=o.set,l={enumerable:!1,configurable:!0};"function"==typeof r&&(l.get=function(){return r.call(Du(e,this))}),"function"==typeof i&&(l.set=function(t){i.call(Du(e,this),t)}),t.defineTreeAccessor(s,l)}!function(t,e,n){const o=n[z];if(void 0!==o){const n=[],s=new Set;let r=0;for(const[i,l]of Object.entries(o)){const o=e+a+i,c=function(t,n,...o){l.call(Du(e,this),t,n,...o)};n.push({path:o,pathInfo:et(o),handler:c,order:1e6+r++}),s.add(o),t.setPathInfo(o,"prop","watch")}n.length>0&&(function(t,e){let n=zd.get(t);void 0===n&&(n=new Map,zd.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}(t,n),t.addVolumeWatchPaths?.(s),Kh(t))}const s=n[q];if(void 0!==s){const n=new Map;for(const[t,o]of Object.entries(s))n.set(e+a+t,o);t.mergeVolumeListKeys?.(n)}const r=n[E];"function"==typeof r&&(function(t,e){let n=Wu.get(t);void 0===n&&(n=[],Wu.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,callback:r}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}(t,e,n);const l=n.$connectedCallback;return"function"==typeof l&&t.createState("writable",t=>{let n;try{n=l.call(Du(e,t))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n}}function lf(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=af(t,e.mountPath,e.volumeState)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}let cf=!1;function uf(){var t;cf||(cf=!0,sd||(sd=!0,Ba("scopes",od)),ud||(ud=!0,Bl("scopes",cd)),Ed||(Ed=!0,Bl("bindComponent",Ad),ns=yd),qu=lf,t=df,Qi.includes(t)||Qi.push(t))}function df(t,e){(function(t){const e=Ou.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){Fu.delete(t);const n=Bu.get(t);if(void 0===n||0===n.length||null===qu)return;Bu.delete(t);const o=qu;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const hf={name:"scopes",install(){uf(),Mu||(Mu=!0,Bl("dcc",Tu))}},ff=/^@@wcs-(?:for|if|elseif|else):[^-]/,pf=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,mf=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,gf=/^@@wcs-text-start:(.+)$/;function yf(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class bf extends Hl{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=_c.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=o.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(e,t);if(void 0!==o&&"function"==typeof o.get)continue;const s=e[t];"function"!=typeof s&&(n[t]=s)}return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=yf(JSON.stringify(e)),t.appendChild(n);const s=Array.from(na.keys());for(const e of s){const n=sa(e);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",e);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),t.appendChild(s)}const r=Array.from(ai);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=ii(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const t of o)i[t.propName]=t.value;e[s]=i}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=yf(JSON.stringify(e)),t.appendChild(n)}}ai.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(pf.test(t.data)||mf.test(t.data))&&n.push(t)}for(const t of n)t.remove()}static removeStructuralComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;ff.test(t.data)&&n.push(t)}for(const t of n)t.remove()}static restoreTextBindings(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode,o=gf.exec(t.data);o&&n.push({comment:t,path:o[1]})}for(const{comment:t,path:e}of n){const n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}const r=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const t=r.currentNode;pf.test(t.data)&&i.push(t)}for(const t of i){const e=pf.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}bf.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(ff.test(t.data)){const e=t.data.split(":")[1];l.push({comment:t,uuid:e})}}for(const{comment:t,uuid:e}of l){const n=s.get(e);if(n){const e=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&e.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)e.content.appendChild(r);else for(const t of Array.from(n.childNodes))e.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(e,t)}}const c=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of c)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const wf={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of s){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",_c),bf.buildContent(o,bf.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}},vf=new Set(["for","if","elseif","else"]);function _f(t){const e=new Zo;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i]=ae(s),a=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:e}}function $f(t,e,n){for(const o of e)"event"===o.bindingType||vf.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in k||et(o.statePathName).wildcardCount>n||t.push(o)}function Sf(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const t=i.currentNode;if(t.data===r)return t}return null}function xf(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=kt(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,aa()],bindingType:"else"}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;ga(a),"string"==typeof l&&fa(a,l),_a(n,a,l),oa(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:ma(a)})}}const Pf={hydrate:async function(t){await Bi(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${_c}". Falling back to full render.`),bf.cleanupDom(t),!1}for(const n of e)xf(t,n);const n=function(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const t of o){const n=pf.exec(t.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let u=t.nextSibling;const d=`@@wcs-${o}-end:${s}`;for(;u&&(u.nodeType!==Node.COMMENT_NODE||u.data!==d);)c.push(u),u=u.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body),s=function(t,e){const n=new Map,o=[];for(const s of e){if(0===s.nodes.length)continue;const e=zr(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=_f(s.nodes);_r(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");ls(e,r),xr(e,i);const c=[];for(const t of r)t.statePathName in k&&c.push(t);if(ds(e,c),"for"===s.type&&null!==s.index){const i=Sf(t,"for",s.uuid);if(i){const t=bs(null,s.index);Qr(i,t,e),Xr(i,s.nodes[s.nodes.length-1]),Mr(i,e);const c=et(s.path+"."+l);Pr(e,hn(c,t)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),$f(o,r,c.wildcardCount);let u=n.get(s.uuid);u||(u=[],n.set(s.uuid,u)),u.push(t)}}else{const n=Sf(t,s.type,s.uuid);n&&(Mr(n,e),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),$f(o,r,0))}}for(const[e,o]of n){const n=Sf(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=sa(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=Xi(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&Is(e,o)})}return o}(document.body,n);bf.removeBlockBoundaryComments(document.body);const r=[];for(const t of e)t.parentNode&&(r.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());bf.restoreTextBindings(document.body);const[i,a]=ae(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(fe(t,null),e.setAttribute("data-wcs-completed",""))}else fe(t,null);const c=[],u=[],d=ts(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(vf.has(t.bindingType))u.push(t);else{if(t.statePathName.includes(l))continue;c.push(t)}for(const t of u)if("for"===t.bindingType){const e=en(t),n=Xi(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&(ye(e,o),Se(e,o))})}Di([...c,...s]);for(const{el:t,parent:e,next:n}of r)e.insertBefore(t,n);const h=t.querySelectorAll(o.tagNames.ssr);for(const e of h){const n=e.hydrateProps;for(const[e,o]of Object.entries(n)){const n=t.querySelector(`[data-wcs-ssr-id="${e}"]`);if(n)for(const[t,e]of Object.entries(o))n[t]=e}}const f=t.querySelectorAll("[data-wcs-completed]");for(const t of f)t.removeAttribute("data-wcs-completed");return!0},loadState(t){const e=t.parentNode;if(!e)return null;const n=bf.find(e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(t){await Yi(t.rootNode);const e=bf.extractStateData(t),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",_c),bf.buildContent(n,e),t.parentNode?.insertBefore(n,t)}};let Nf=!1;const kf={name:"ssr",install(){!function(){var e;Nf||(Nf=!0,Ui=Pf,e=t=>{t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,bf)},Kl.includes(e)||Kl.push(e),function(){const e=globalThis;void 0===e[t]&&(e[t]=wf)}())}()}},If="[wcs/scan-declaration-invalid]",Af=Object.freeze([]);function Ef(t){return`${B} entry "${t}"`}function Cf(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function Tf(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${l}${l}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${rt}`}function Mf(t,e,n){0===n.length&&Y(`${If} ${t} "${e}" must be a non-empty state path.${rt}`),n.startsWith("$")&&Y(`${If} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${rt}`),n.includes("@")&&Y(`${If} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${rt}`),n in Object.prototype&&Y(`${If} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${rt}`);const o=et(n);for(const s of o.segments)0===s.length&&Y(`${If} ${t} ${e} "${n}" has an empty path segment.${rt}`);return o.wildcardCount>c&&Y(`${If} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function Of(t,e,n,o){const s=Ef(t);0===t.length&&Y(`${If} ${B} entry name must be a non-empty string.${rt}`),(t.includes(a)||t.includes(l))&&Y(`${If} ${s} must be a flat property name ("${a}" and "${l}" are not allowed). The output is a property the runtime owns.${rt}`),t.startsWith("$")&&Y(`${If} ${s} must not start with "$" (reserved namespace).${rt}`),t in Object.prototype&&Y(`${If} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${rt}`),e.has(t)&&Y(`${If} ${s} conflicts with a getter declared on the state.${rt}`),n.has(t)&&Y(`${If} ${s} conflicts with a setter declared on the state.${rt}`),o.has(t)&&Y(`${If} ${s} conflicts with the ${W} entry of the same name — each output has exactly one owner.${rt}`)}function Lf(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!function(t,e){return"function"==typeof e&&!0===Ah.get(e)?.has(t)}(t,o)&&Y(`${If} ${Ef(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${rt}`)}function Rf(t,e,n,o,s,r){const i=Ef(t),l=void 0!==e.from,c=void 0!==e.on;if(l===c&&Y(`${If} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${rt}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||Y(`${If} ${i} "on" must be a non-empty event-token name.${rt}`),n.has(t)||Y(`${If} ${i} on "${t}" is not declared in ${j}.${st(t,n)}${rt}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&Y(`${If} ${i} "from" must be a state path string.${rt}`);const d=Mf(i,"from",u),h=Cf(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&Y(Tf(i,"from",u,h));const f=Cf(d,s);return null!==f&&Y(function(t,e,n){return`${If} ${t} from "${e}" ${n===e?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${rt}`}(i,u,f)),(u===t||u.startsWith(t+a))&&Y(`${If} ${i} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${rt}`),{kind:"path",path:u,pathInfo:d}}function jf(t,e,n,o){if(void 0===e)return Af;const s=Ef(t);Array.isArray(e)||Y(`${If} ${s} "resetOn" must be an array of state paths.${rt}`);const r=[];for(const t of e){"string"!=typeof t&&Y(`${If} ${s} "resetOn" must contain only state path strings.${rt}`);const e=Mf(s,"resetOn",t);e.wildcardCount>0&&Y(`${If} ${s} resetOn "${t}" must not contain "${l}" — a reset returns the whole output to "initial".${rt}`);const i=Cf(e,o);null!==i&&Y(Tf(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&Y(`${If} ${s} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${rt}`),"path"===n.kind&&t.startsWith(n.path+a)&&Y(`${If} ${s} resetOn "${t}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${rt}`),r.push(t)}return r}function Df(t){const e=t.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[t.name];i="threw";const a=function(t){return gh.has(t)}(t),l=a&&!Ih(n,t.initial)?Nh(t.initial):n,c=e(l,o,...s);if(Lh(c))return void Rh(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,Eh(t.name,c)),a&&_h(t)}catch(e){Oh(t.name,e,i)}}}const Wf="scanEntries",zf={order:8,validate(t,e,n){const o=function(t,e,n=null){const o=t[B];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&Y(`${If} ${B} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${rt}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(ql(t)))"function"==typeof n.get?s.add(e):"function"==typeof n.set&&i.add(e),"function"==typeof n.set&&r.add(e),"function"==typeof n.value&&a.set(e,n.value);const l=function(t){const e=t[W];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];let u=0;for(const[t,d]of Object.entries(o)){Of(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&Y(`${If} ${Ef(t)} must be an object ({ from | on, initial, fold, resetOn? }).${rt}`);const o=d;Lf(t,a,o);const h=Rf(t,o,e,s,i,n);"initial"in o||Y(`${If} ${Ef(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${rt}`),"function"!=typeof o.fold&&Y(`${If} ${Ef(t)} fold must be a function.${rt}`);const f=jf(t,o.resetOn,h,s);c.push({name:t,source:h,fold:o.fold,initial:o.initial,resetOn:f,order:u++})}return function(t){const e=new Set(t.map(t=>t.name)),n=new Map;for(const o of t){for(const t of o.resetOn){const n=et(t).segments[0];e.has(n)&&Y(`${If} ${Ef(o.name)} resetOn "${t}" reads the ${B} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${rt}`)}if("path"===o.source.kind){const t=o.source.pathInfo.segments[0];e.has(t)&&n.set(o.name,t)}}for(const t of n.keys()){const o=[t];let s=n.get(t);for(;void 0!==s&&o.length<=e.size;)s===t&&Y(`${If} ${B} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${rt}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}(e,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Wf,o)},applyEarly(t,e,n){const o=n.get(Wf)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=Nh(n.initial);t[n.name]=e,Eh(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&Nn(t,n.source.tokenName).subscribe(Df(n))}(t,o))},register(t,e,n){const o=n.get(Wf)??null,s=function(t){const e=new Map,n=Rd(t);if(void 0!==n)for(const t of n.entries)_h(t)&&e.set(t.name,t.resetOn);return jd(t),e}(t);t.setScanPaths?.(null===o?null:function(t,e,n){const o=function(t,e){jd(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&Ld(n,t.source.path,t);for(const e of t.resetOn)Ld(o,e,t),"event"===t.source.kind&&Ld(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return Cd.set(t,r),r}(t,e);for(const o of e){const e=n.get(o.name);"event"===o.source.kind&&void 0!==e&&o.resetOn.some(n=>e.includes(n)&&Bs().hasQueuedPath(t,n))&&vh(o)}const s=new Set;for(const e of o.byFromPath.keys())s.add(e),t.setPathInfo(e,"prop","scan");for(const e of o.byResetPath.keys())t.setPathInfo(e,"prop","scan");return s.size>0?s:null}(t,o,s))}};let Bf=!1;const Ff=Object.freeze([]),Hf=Object.freeze([]);function qf(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??Ff,i=t.dynamicDependency.get(n)??Ff,a=e.byFromPath.get(n)??Hf;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const Uf=(t,e)=>e,Gf=new Set;const Vf=new WeakMap,Kf=new WeakMap;function Jf(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=ph(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&ph(t).has(n),ownKeys:()=>Array.from(ph(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=ph(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){Y(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){Y(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function Qf(t){const e=Vf.get(t);if(void 0!==e)return e;const n=Jf(t,U,t=>t.status);return Vf.set(t,n),n}function Xf(t){const e=Kf.get(t);if(void 0!==e)return e;const n=Jf(t,G,t=>t.error);return Kf.set(t,n),n}function Yf(t){Vf.delete(t),Kf.delete(t)}let Zf=null;function tp(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}const ep={read(t,e){!function(t,e){null!==Zf&&Zf.add(Fe(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===U?tp(Qf(t),e.pathInfo.segments):n===G?tp(Xf(t),e.pathInfo.segments):Da},get:(t,e)=>e===U?Qf(t.stateElement):e===G?Xf(t.stateElement):Da};function np(t){cp();const e=ph(t);if(0!==e.size){!function(t){ah.add(t)}(t);for(const n of e.values())op(t,n)}}function op(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=Zf,s=new Set;let r;Zf=s;try{t.createState("readonly",t=>{r=n(t)})}finally{Zf=o}r instanceof Promise&&Y(`${W} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${U}${a}${e.name}`,l=`${G}${a}${e.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==i&&o.path!==l||Y(`${W} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&Y(`${W} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=s,r}(t,e);!function(t,e){const n=Rd(t);if(void 0!==n&&0!==e.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==e.name)continue;const s=qf(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&Y(`[wcs/scan-feedback-loop] ${W} entry "${e.name}" args read "${n}", which is derived from the ${B} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,e),t.createState("writable",t=>{t[e.name]=e.definition.initial}),sp(t,e,"active",null);const s=e.definition,r={fold(n){t.createState("writable",t=>{t[e.name]=s.fold(t[e.name],n)})},done(){sp(t,e,"done",null)},fail(o){sp(t,e,"error",o),n.abort()}};!async function(t,e,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",i)}}(s.source,o,n.signal,r)}function sp(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return uh.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(function(t,e,n,o){let s=uh.get(t);void 0===s&&(s=new Map,uh.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${U}${a}${e.name}`),i&&t.$postUpdate(`${G}${a}${e.name}`)}))}function rp(t){const e=ah;if(0===e.size)return;const n=[];for(const o of e)for(const e of ph(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&ph(t).get(o.name)===o)try{op(t,o)}catch(n){o.controller?.abort(),e.has(t)&&ph(t).get(o.name)===o&&sp(t,o,"error",n)}}let ip=!1;const ap=new WeakMap,lp={order:20,apply(t,e){var n;Yf(t),mh(n=t),lh(n),fh.delete(n),function(t,e){const n=e[W];if(void 0===n)return void dh(t,Gf);"object"==typeof n&&null!==n||Y(`${W} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&Y(`${W} entry name must be a non-empty string.`),s.includes(a)&&Y(`${W} entry "${s}" must be a flat property name ("${a}" is not allowed).`),s.includes(l)&&Y(`${W} entry "${s}" must be a flat property name ("${l}" is not allowed).`),s.startsWith("$")&&Y(`${W} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&Y(`${W} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(s)&&Y(`${W} entry "${s}" conflicts with a getter declared on the state.`),t.setterPaths.has(s)&&Y(`${W} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||Y(`${W} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&Y(`${W} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&Y(`${W} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&Y(`${W} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&Y(`${W} entry "${s}" args must be a function.`);const c={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??Uf,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in e||(e[s]=c.definition.initial),o.set(s,c)}!function(t,e){fh.set(t,e)}(t,o),dh(t,new Set(o.keys()))}(t,e),void 0!==e[W]&&t.attachAddressHooks?.("streams",W)},activate(t,n){if(!e()&&null!=t.connectedRootNode){if(null===n){if(!0!==t.initialized)return;return np(t),void ap.set(t,t.connectGeneration??0)}n===t.connectGeneration&&ap.get(t)!==n&&np(t)}},deactivate(t){mh(t),Yf(t)}};function cp(){ip||(ip=!0,Ba("streams",ep),Ua("streams",lp),Ds(rp,20))}const up=[Yc,{name:"temporal",install(){of(),Bf||(Bf=!0,Ua("scan",zf),js(wh)),cp()}},$u,hf,kf,Cc,Bc];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(up),void Jl(void 0,void 0));const dp={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},hp=!1,fp=[".html"];function pp(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function mp(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let gp=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const yp={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function bp(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function wp(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}const vp={static:2,param:1,"catch-all":0};let _p=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&mp(`${dp.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&mp(`${dp.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=vp[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(yp).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||mp(`${dp.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath,o=await this._guardHandler(e,n,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:bp(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new gp("Navigation cancelled by guard.",o);if(!o)throw new gp("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new gp("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},$p=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=pp();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new _p(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||mp(`${dp.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):mp(`${dp.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&mp(`${dp.route} with fallback attribute must be a direct child of ${dp.router}.`),t.fallbackRoute&&mp(`${dp.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const Sp=Symbol.for("wcstack.trustedTypes.policy"),xp=Symbol.for("wcstack.trustedTypes.internal"),Pp="wcstack";function Np(){const t=globalThis[Sp];return null===t||"object"!=typeof t?null:t}let kp=!1;function Ip(t){const e=function(){const t=globalThis,e=t[xp];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Pp,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof Np()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Pp}". Allow it in the CSP (\`trusted-types ${Pp};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[xp]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Np(),s=o?.createHTML;return"function"==typeof s?(kp||(kp=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Pp}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Pp};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Ap=new Map;let Ep=class extends HTMLElement{_uuid=pp();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||mp(`${dp.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Ap.set(t,n),n}catch(e){mp(`${dp.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${dp.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Ap.has(t)?n.innerHTML=Ip(Ap.get(t)||""):n.innerHTML=Ip(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Ip(t):console.warn(`${dp.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&hp}get name(){return this.getAttribute("name")||""}},Cp=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||mp(`${dp.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&hp}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Tp=new Set(["props","states","attr",""]);function Mp(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function Op(t,e){t.hasAttribute("data-bind")||mp(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Tp.has(n)||mp(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&Mp(t,e,o)}).catch(()=>{mp(`Failed to define custom element: ${s}`)}):Mp(t,e,o)}let Lp=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||mp(`${dp.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${dp.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{Op(e,t)}),e.hasAttribute("data-bind")&&Op(e,t))}};function Rp(){return document.createElement(dp.layoutOutlet)}const jp="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Dp(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){mp(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${jp}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${jp}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function Wp(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function zp(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===dp.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),Wp(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===dp.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Dp(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===dp.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=Rp();o.layout=n,i=o,a=e}}const c=await zp(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function Bp(t){const e=new Map;return await zp(t,t.template.content,[],e)}function Fp(t){return!1!==t.checkVisibility?.()}function Hp(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",n=yp[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)Hp(s,e,n,o)}function qp(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)Hp(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let Up=null,Gp=null;function Vp(){const t=fp;return 0===t.length?null:(Up===t&&Gp||(Up=t,Gp=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),Gp)}function Kp(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=Vp();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function Jp(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function Qp(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=Vp();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function Xp(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function Yp(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{Op(e,t.typedParams)}),n.hasAttribute("data-bind")&&Op(n,t.typedParams),n.querySelectorAll(dp.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===dp.layoutOutlet&&n.assignParams(t.typedParams)}}function Zp(t,e){Yp(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const tm=Symbol.for("wcstack.transition-runner");const em=Symbol.for("wcstack.binder");function nm(){const t=globalThis[em];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const om=Symbol.for("wcstack.binder.pending"),sm=Symbol.for("wcstack.binder.taken");function rm(){const t=globalThis;let e=t[sm];return void 0===e&&(e=new WeakSet,t[sm]=e),e}function im(t){const e=nm();return null===e?(function(){const t=globalThis;let e=t[om];return void 0===e&&(e=[],t[om]=e),e}().push(t),!1):(rm().add(t),e.bind(t),!0)}const am=new WeakSet,lm="data-wcs";function cm(t,e,n){!am.has(t)&&function(t){return t.hasAttribute(lm)||null!==t.querySelector(`[${lm}]`)}(t)&&(am.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==nm()||(o=t,rm().has(o))||console.warn(`[@wcstack/router] ${e} contains ${lm} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function um(t){for(const e of t.childNodeArray)1===e.nodeType&&(im(e)||cm(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.'))}async function dm(t,e){try{let t=null;for(const n of e.routes){const o=await n.guardCheck(e);o&&(t=null===t?o:Object.assign({},t,o))}e.data=t}catch(e){if(e instanceof gp)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function hm(t,e,n,o,s=""){const r=Jp(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:s,path:r}),!0;let i=qp(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:mp(`${dp.router} No route matched for path: ${r}`)),i.lastPath=o,i.search=s;const a=e.lastRoutes,l=await async function(t,e,n){if(!await dm(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||Xp(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=Zp(o,e),n.length>0&&!s.has(o)&&um(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[tm];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",data:i.data??null,search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(Fp(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(Fp(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(t,i),!0)}function fm(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function pm(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function mm(t){return"?"===t?"":t}function gm(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function ym(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const bm="data-wcs-ssr",wm="data-wcs-ssr-link",vm="@@wcs-route-ph:",_m="@@wcs-route-start:",$m="@@wcs-route-end:",Sm=Object.freeze({});class xm extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Sm;_typedParams=Sm;_searchParams=Sm;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return Kp(t)}_normalizeBasename(t){return Qp(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(dp.outlet))return t;const e=document.createElement(dp.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||mp(`${dp.router} has no outlet.`),this._outlet}get template(){return this._template||mp(`${dp.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=bp(t.search),s=t.data??null,r=this._data!==s,i=!wp(this._params,e),a=this._routeName!==t.routeName,l=!wp(this._searchParams,o),c=this._path!==t.path;r&&(this._data=s),i&&(this._params=e,this._typedParams=n),a&&(this._routeName=t.routeName),l&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,r&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${dp.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${dp.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=pm(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+mm(n.search)+n.hash,r=fm();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(Jp(t,this._basename));await hm(this,this.outlet,t,this._path,mm(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(Jp(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await hm(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${dp.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await hm(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=ym();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||mp(`${dp.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||mp(`${dp.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await Bp(this),r=!t&&this._outlet.hasAttribute(bm);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&mp(`${dp.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(bm);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await hm(this,this.outlet,i,this._path,window.location.search||""),(r||null!==nm())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(dp.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(vm)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(_m)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith($m)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=Jp(t,this._basename);let d=qp(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of d.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(_m)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===dp.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(bm);for(const t of d.routes)Yp(t,d);return this.outlet.lastRoutes=d.routes,!await dm(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(t){const e=Jp(t,this._basename),n=qp(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&mp(`${dp.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await hm(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${vm}${t.absolutePath}`}),this.outlet.setAttribute(bm,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${_m}${t.absolutePath}`),s=document.createComment(`${$m}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&im(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!gm(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),ym()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=fm();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(fm()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Pm=["title","rel","target","download","hreflang","lang","dir"];class Nm extends HTMLElement{static get observedAttributes(){return["to",...Pm]}_childNodeArray=[];_uuid=pp();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(dp.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(dp.router);if(n)return this._router=n;mp(`${dp.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return Kp(t)}_joinInternalPath(t,e){const n=Qp(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=pm(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+mm(o)+s}else try{t.href=new URL(e).toString()}catch{mp(`[${dp.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){ym()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(wm)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(wm),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||Pm.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,ym())return this._updateActiveState(),void n.setAttribute(wm,"");fm()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!fm()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){fm()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Pm.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=pm(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const km=[],Im=new Map;let Am=!1;const Em=new WeakMap;class Cm extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Am||(this._captureInitialHead(),Am=!0),km.push(this),this._reapplyHead()}disconnectedCallback(){const t=km.indexOf(this);-1!==t&&km.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||mp("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Em.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Em.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Im.has(t)||Im.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of km)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Im.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=km.length-1;e>=0;e--){const o=km[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Im.has(n)&&(t=Im.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),im(t)||cm(t,`<${t.tagName.toLowerCase()}> inside <${dp.head}>`,`<${dp.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(dp.layout)||t.define(dp.layout,Ep),t.get(dp.layoutOutlet)||t.define(dp.layoutOutlet,Lp),t.get(dp.outlet)||t.define(dp.outlet,Cp),t.get(dp.route)||t.define(dp.route,$p),t.get(dp.router)||t.define(dp.router,xm),t.get(dp.link)||t.define(dp.link,Nm),t.get(dp.head)||t.define(dp.head,Cm)}(void 0);const Tm="data-fetchtarget",Mm={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Om=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function Lm(t,e){return e.every(e=>"available"===t.availability.get(e))}const Rm=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let jm=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new Om("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return Lm(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),u=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",d=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:u,userActivation:d},epoch:e.epoch??0,lastError:e.lastError}}(Rm,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!Lm(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:u="auto",timeout:d=0}=e;let h=null;d>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},d));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===u)s=await n.blob();else if("arrayBuffer"===u)s=await n.arrayBuffer();else if("text"===u)s=await n.text();else if("json"===u)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,d)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},Dm=!1;function Wm(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Tm}]`);if(!n)return;const o=n.getAttribute(Tm);if(!o)return;const s=customElements.get(Mm.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function zm(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}const Bm=Symbol.for("wcstack.trustedTypes.policy");function Fm(){const t=globalThis[Bm];return null===t||"object"!=typeof t?null:t}let Hm,qm=!1;let Um=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...jm.wcBindable,properties:[...jm.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new jm(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(Mm.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(Mm.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&function(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=Fm(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==Hm)return Hm;if(!("trustedTypes"in globalThis))return Hm=!1,Hm;try{document.createElement("div").innerHTML="<i></i>",Hm=!1}catch{Hm=!0}return Hm}())return void function(){if(qm)return;qm=!0;const t="function"==typeof Fm()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}(t,s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!zm(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Dm||(Dm=!0,document.addEventListener("click",Wm)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class Gm extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class Vm extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let Km=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof Um&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(Mm.fetch)||t.define(Mm.fetch,Um),t.get(Mm.fetchHeader)||t.define(Mm.fetchHeader,Gm),t.get(Mm.fetchBody)||t.define(Mm.fetchBody,Vm),t.get(Mm.infiniteScroll)||t.define(Mm.infiniteScroll,Km)}(void 0);const Jm="data-storagetarget",Qm={storage:"wcs-storage"},Xm="wcs-storage:value-changed",Ym="wcs-storage:loading-changed",Zm="wcs-storage:error",tg="wcs-storage:error-info-changed",eg="wcs-storage:trigger-changed";let ng=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:Xm,semantics:"state",getter:t=>t.detail},{name:"loading",event:Ym,semantics:"state"},{name:"error",event:Zm,semantics:"state"},{name:"errorInfo",event:tg,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(Ym,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(Zm,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(tg,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(Xm,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},og=!1;function sg(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Jm}]`);if(!n)return;const o=n.getAttribute(Jm);if(!o)return;const s=customElements.get(Qm.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function rg(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let ig=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...ng.wcBindable,properties:[...ng.wcBindable.properties,{name:"trigger",event:eg,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new ng(this),this._internals=this._initInternals(),this._wireStates({[Ym]:t=>({loading:!0===t}),[Zm]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(eg,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!rg(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",og||(og=!0,document.addEventListener("click",sg)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(Qm.storage)||t.define(Qm.storage,ig)}(void 0);const ag="*",lg="vanilla",cg={scanImportmap:!0,loaders:{[lg]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[ag]:lg},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function ug(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function dg(t,e,n){let o;if(null===e||e===ag||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===ag)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[ag],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const hg=new Set,fg=new Map;let pg=new WeakMap;function mg(t){if(t===globalThis.customElements)return fg;let e=pg.get(t);return void 0===e&&(e=new Map,pg.set(t,e)),e}const gg=new Map;async function yg(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of gg)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){hg.has(e)||(console.error(`Failed to eager load component '${e}':`,t),hg.add(e))}}function bg(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function wg(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&gg.set(t,e)});const vg=new WeakSet,_g=new WeakSet;async function $g(t,e,n){t.shadowRoot&&(vg.has(t)||await async function(t,e,n){vg.add(t),await Ng(t.shadowRoot,e,n)}(t,e,n))}async function Sg(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=mg(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=dg("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),hg.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function xg(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=wg(t);void 0===o.get(s.name)?(_g.has(t)||(_g.add(t),o.whenDefined(s.name).then(async()=>{await $g(t,e,n)})),a.has(s.name)||hg.has(s.name)||(a.add(s.name),i.push(s))):await $g(t,e,n)}let l=0;for(const t of i)await Sg(t,e,n,o),l++;return l}async function Pg(t,e,n,o){for(;await xg(t,e,n,o)>0;);}async function Ng(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return bg(e)}return bg(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Pg(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await Pg(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class kg extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),kg._instance)throw new Error(`${cg.tagNames.autoloader} can only be instantiated once.`);kg._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=ug(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=dg(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(yg(s,o,r))}await Promise.all(n)}(n,cg.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await Ng(document,cg,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,kg._instance===this&&(kg._instance=null)}}!function(t=customElements){t.get(cg.tagNames.autoloader)||t.define(cg.tagNames.autoloader,kg)}(void 0);
|
|
1
|
+
const t=Symbol.for("wcstack.ssr.snapshotBuilder");function e(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const n={bindAttributeName:"data-wcs",commentTextPrefix:"wcs-text",commentForPrefix:"wcs-for",commentIfPrefix:"wcs-if",commentElseIfPrefix:"wcs-elseif",commentElsePrefix:"wcs-else",tagNames:{state:"wcs-state",ssr:"wcs-ssr"},locale:"en",debug:!1,enableMustache:!0,enableDirectionalInitialSync:!0,enablePropagationContext:!0,enableContractAnalyzer:!1,sameValueGuard:!0},o=n,s=Symbol.for("wcstack.binder"),r=Symbol.for("wcstack.binder.pending"),i=Symbol.for("wcstack.binder.taken");const a=".",l="*",c=128,u=128,d="#",h="|",f="prevent",p="stop",m="ro",g="init",y="sync",b="else",w="...",v="on",_="eventToken",$="state",S="command",x="class",P="attr",N="style",k={};for(let t=0;t<c;t++)k[`$${t+1}`]=t;const I=Object.freeze(k),A="$connectedCallback",E="$disconnectedCallback",C="$renderedCallback",T="$errorCallback",M="$stateReadyCallback",O="$bindables",L="$commands",R="$commandTokens",j="$command",W="$eventTokens",D="$on",z="$stream",B="$watch",F="$scan",H="$recursion",q="**",U="$listKeys",G="$streamStatus",V="$streamError",K="data-wc-definition",J=/\{\{\s*(.+?)\s*\}\}/g,Q=new Set(["SCRIPT","STYLE"]);function X(t){if(!o.enableMustache)return;!function(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),n=[];for(;e.nextNode();)n.push(e.currentNode);for(const t of n)t.parentElement&&Q.has(t.parentElement.tagName)||Y(t)}(t);const e=Array.from(t.querySelectorAll("template"));for(const t of e)if("http://www.w3.org/2000/svg"===t.namespaceURI){const e=document.createElement("template"),n=Array.from(t.childNodes);for(let t=0;t<n.length;t++){const o=n[t];e.content.appendChild(o)}for(const n of t.attributes)e.setAttribute(n.name,n.value);t.replaceWith(e),X(e.content)}else X(t.content)}function Y(t){const e=t.data;if(J.lastIndex=0,!J.test(e))return;J.lastIndex=0;const n=document.createDocumentFragment();let o,s=0;for(;null!==(o=J.exec(e));){o.index>s&&n.appendChild(document.createTextNode(e.slice(s,o.index)));const t=o[1];n.appendChild(document.createComment(`@@: ${t}`)),s=o.index+o[0].length}s<e.length&&n.appendChild(document.createTextNode(e.slice(s))),t.parentNode.replaceChild(n,t)}function Z(t){throw new Error(`[@wcstack/state] ${t}`)}const tt=new Map;let et=0;function nt(t){let e=tt.get(t);return void 0!==e||(-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] "${t}" uses "${q}", which is not accepted here. It is only meaningful in a $recursion declaration, in a recursive getter key, and in the path argument of $getAll / $setAll — and only when the state declares a $recursion anchor.`),e=Object.freeze(new ot(t)),tt.set(t,e)),e}class ot{id=++et;path;segments;lastSegment;cumulativePaths;cumulativePathSet;cumulativePathInfos;cumulativePathInfoSet;parentPath;wildcardPaths;wildcardPathSet;indexByWildcardPath;wildcardPathInfos;wildcardPathInfoSet;wildcardParentPaths;wildcardParentPathSet;wildcardParentPathInfos;wildcardParentPathInfoSet;wildcardPositions;lastWildcardPath;lastWildcardInfo;wildcardCount;parentPathInfo;constructor(t){const e=e=>t===e?this:nt(e),n=t.split("."),o=[],s=[],r=[],i={},a=[],c=[],u=[],d=[];let h="",f="",p=0;for(let t=0;t<n.length;t++)h+=n[t],n[t]===l&&(r.push(h),i[h]=p,a.push(e(h)),c.push(f),u.push(e(f)),d.push(t),p++),o.push(h),s.push(e(h)),f=h,h+=".";const m=r.length>0?r[r.length-1]:null,g=o.length>1?o[o.length-2]:null;this.path=t,this.segments=n,this.lastSegment=n[n.length-1],this.cumulativePaths=o,this.cumulativePathSet=new Set(o),this.cumulativePathInfos=s,this.cumulativePathInfoSet=new Set(s),this.wildcardPaths=r,this.wildcardPathSet=new Set(r),this.indexByWildcardPath=i,this.wildcardPathInfos=a,this.wildcardPathInfoSet=new Set(a),this.wildcardParentPaths=c,this.wildcardParentPathSet=new Set(c),this.wildcardParentPathInfos=u,this.wildcardParentPathInfoSet=new Set(u),this.wildcardPositions=d,this.lastWildcardPath=m,this.lastWildcardInfo=m?e(m):null,this.parentPath=g,this.parentPathInfo=g?e(g):null,this.wildcardCount=p}}function st(t,e,n){if(Math.abs(t.length-e.length)>n)return n+1;const o=new Array(e.length+1),s=new Array(e.length+1);for(let t=0;t<=e.length;t++)o[t]=t;for(let n=1;n<=t.length;n++){s[0]=n;for(let r=1;r<=e.length;r++){const i=t[n-1]===e[r-1]?0:1;s[r]=Math.min(o[r]+1,s[r-1]+1,o[r-1]+i)}for(let t=0;t<=e.length;t++)o[t]=s[t]}return o[e.length]}function rt(t,e){if(0===t.length)return"";const n=t.toLowerCase();let o=null,s=3;for(const t of e){const e=st(n,t.toLowerCase(),2);e<s&&(o=t,s=e)}return null!==o?` Did you mean "${o}"?`:""}const it=" Validate statically: npx @wcstack/lint <file>.",at=new Set(["if","elseif","else","for"]),lt={not:()=>t=>!t},ct={input:new Map,output:new Map},ut={input:new Map,output:new Map},dt={input:new Map,output:new Map},ht=new Map;function ft(t,e,n,o){const s=ct[t],r=ut[t];for(const t of Object.keys(e)){s.set(t,e[t]);const o=n?.[t];void 0===o?r.delete(t):r.set(t,o)}for(const e of Object.keys(o??{}))dt[t].set(e,o[e]);ht.clear()}function pt(t,e,n,o=e){const s=`${t}${JSON.stringify(o)}:${n}`,r=ht.get(s);if(void 0!==r)return r;const i=dt[n].get(t)??t,a=ct[n].get(i)??lt[i];void 0===a&&Z(`[wcs/filter-unknown] filter not found: ${t}.${rt(t,function(t){return[...new Set([...Object.keys(lt),...ct[t].keys()])]}(n))}${it}`);const l=ut[n].get(i);void 0!==l&&(e.length<l[0]||e.length>l[1])&&Z(e.length<l[0]?`[wcs/filter-arity] filter "${t}" requires at least ${l[0]} argument(s) (${e.length} given).${it}`:`[wcs/filter-arity] filter "${t}" accepts at most ${l[1]} argument(s) (${e.length} given).${it}`);const c=a(e,o);return ht.set(s,c),c}function mt(t,e,n){const o=-1===e?t.length:e;let s=0;for(;s<o&&/\s/.test(t[s]);)s++;const r=-1===n?0:n;let i=t.length;for(;i>r&&/\s/.test(t[i-1]);)i--;return t.slice(s,i)}const gt=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function yt(t,e){return e?t:"true"===t||"false"!==t&&("null"===t?null:gt.test(t)?Number(t):t)}function bt(t){const e=[],n=[];let o="",s=null,r=!1,i=-1,a=-1;const l=()=>{const t=mt(o,i,a);e.push(t),n.push(yt(t,r)),o="",r=!1,i=-1,a=-1};for(let e=0;e<t.length;e++){const n=t[e];s?n===s?s=null:(-1===i&&(i=o.length),o+=n,a=o.length):'"'===n||"'"===n?(s=n,r=!0):","===n?l():o+=n}null!==s&&Z(`[wcs/binding-syntax] unterminated ${s} quote in the filter arguments "(${t})". Close the quote.${it}`);const c=mt(o,i,a);return(c||r)&&(e.push(c),n.push(yt(c,r))),{args:e,literals:n}}function wt(t,e){return t.map(e=>{const n=e.indexOf("("),o=e.lastIndexOf(")");-1!==n&&-1===o&&Z(`Invalid filter format: missing closing parenthesis in "${e}"`),-1!==o&&-1===n&&Z(`Invalid filter format: missing opening parenthesis in "${e}"`);const s=(-1===n?e:e.substring(0,n)).trim();return 0===s.length&&Z(`[wcs/binding-syntax] an empty filter in "${t.join("|")}" — remove the extra "|" or name the filter.${it}`),-1===n?{filterName:s,args:[],literals:[]}:{filterName:s,...bt(e.substring(n+1,o))}})}const vt=t=>t.trim(),_t=t=>"'"===t||'"'===t;function $t(t,e){let n=null;for(let o=0;o<t.length;o++){const s=t[o];if(null!==n)s===n&&(n=null);else if(_t(s))n=s;else if(s===e)return o}return-1}function St(t,e){const n=[];let o=null,s=0;for(let r=0;r<t.length;r++){const i=t[r];null!==o?i===o&&(o=null):_t(i)?o=i:i===e&&(n.push(t.slice(s,r)),s=r+1)}return n.push(t.slice(s)),n}const xt=new Map;function Pt(t){const e=$t(t,h);let n="",o=[],s="",r=[];-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),xt.has(s)?r=xt.get(s):(o=St(s,h).map(vt),r=wt(o),xt.set(s,r))):n=t.trim();const i=n.split(d).map(vt);i.length>2&&Z(`[wcs/binding-syntax] "${n}": a binding takes one modifier list after a single "${d}" — write "${i[0]}${d}${i.slice(1).join(",")}".${it}`);const[l,c]=i,u=l.split(a).map(vt);return{propName:l,propSegments:u,propModifiers:c?c.split(",").map(vt):[],inFilters:r}}const Nt=new Map;function kt(t){const e=$t(t,h);let n="",o=[],s="",r=[];return-1!==e?(n=t.slice(0,e).trim(),s=t.slice(e+1).trim(),Nt.has(s)?r=Nt.get(s):(o=St(s,h).map(vt),r=wt(o),Nt.set(s,r))):n=t.trim(),-1!==n.indexOf("@")&&Z(`"${n}": the "@name" selector was removed in v2 — there is a single state tree. Mount the named state onto the tree (<wcs-state mount="...">) and read it by its path prefix instead.`),{statePathName:n,statePathInfo:nt(n),outFilters:r}}const It=new Set([b,"if","elseif","for",w]),At=new Set([x,P,N,S,_]);function Et(t){const[...e]=function(t){return St(t,";")}(t).map(vt).filter(t=>t.length>0),n=e.map(t=>{const e=t.indexOf(":");-1===e&&Z(`Invalid bindText: "${t}". Missing ':' separator between propPart and statePart.`);const n=t.slice(0,e).trim(),o=t.slice(e+1).trim(),s=n.split(d)[0].split(h)[0].trim();if(s!==n&&It.has(s)&&Z(`[wcs/binding-syntax] "${t}": "${s}" takes no modifiers or filters on its left side — write "${s}:".${it}`),n===b){o.length>0&&Z(`[wcs/binding-syntax] "${t}": "else" takes no value — write "else:".${it}`);const e=nt("#else");return{propName:b,propSegments:[b],propModifiers:[],statePathName:"#else",statePathInfo:e,inFilters:[],outFilters:[],bindingType:"else"}}if(n===w){const e=kt(o);return e.outFilters.length>0&&Z(`Invalid spread binding "${t}": filters are not allowed on spread targets.`),0===e.statePathName.length&&Z(`Invalid spread binding "${t}": spread target path is required.`),{propName:w,propSegments:[w],propModifiers:[],inFilters:[],...e,bindingType:"spread"}}if("if"===n||"elseif"===n||"for"===n)return{propName:n,propSegments:[n],propModifiers:[],inFilters:[],...kt(o),bindingType:n};if("radio"===s||"checkbox"===s){const t=kt(o);return{...Pt(n),...t,bindingType:s}}{const t=kt(o),e=Pt(n);if(""===e.propSegments[0]&&e.propSegments.length>1){const o=e.propSegments.slice(1);return(o.includes("")||At.has(o[0]))&&Z(`[wcs/binding-syntax] "${n}": a leading "." binds an element property by name — write a non-empty property that is not a namespace (${[...At].join(", ")}).${it}`),{...e,propName:o.join(a),propSegments:o,...t,bindingType:"prop"}}return e.propSegments[0]===_||e.propSegments[0].startsWith(v)?{...e,...t,bindingType:"event"}:{...e,...t,bindingType:"prop"}}});return n.length>1&&n.some(t=>at.has(t.bindingType))&&Z(`[wcs/template-syntax] Invalid bindText: "${t}". 'if', 'elseif', 'else', and 'for' bindings must be single binding. Put the structural binding alone in its own data-wcs (e.g. <template data-wcs="for: items">).${it}`),n}const Ct=new WeakMap,Tt=new Set([o.commentTextPrefix,o.commentForPrefix,o.commentIfPrefix,o.commentElseIfPrefix,o.commentElsePrefix]),Mt=new RegExp("^\\s*@@\\s*(.*?)\\s*:\\s*(.+?)\\s*$");function Ot(t){const e=Ct.get(t);if("string"==typeof e)return e;if(t.nodeType!==Node.COMMENT_NODE)return null;const n=t.data.trim(),s=Mt.exec(n);if(null===s)return null;const r=s[1]||o.commentTextPrefix;return Tt.has(r)?(Ct.set(t,s[2]),s[2]):null}function Lt(t){return{propName:"textContent",propSegments:["textContent"],propModifiers:[],inFilters:[],...kt(t),bindingType:"text"}}const Rt=new WeakMap,jt=new WeakSet;let Wt=0;async function Dt(t){const e=function(t){let e,n=Rt.get(t)||null;if(null!==n)return n;const o=new Promise(t=>{e=t});return n={id:++Wt,promise:o,resolve:e},Rt.set(t,n),jt.has(t)&&n.resolve(),n}(t);await e.promise}function zt(t){const e=Rt.get(t);void 0===e?jt.add(t):e.resolve()}const Bt=new WeakMap;function Ft(t){const e=Bt.get(t);if(void 0!==e)return e;let n=null;try{if(t.nodeType!==Node.ELEMENT_NODE)return n;const e=t,o=e.tagName.toLowerCase();if(o.includes("-"))return n=o;if(e.hasAttribute("is")){const t=e.getAttribute("is");if(t.includes("-"))return n=t}return n}finally{Bt.set(t,n)}}function Ht(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined?null:e}function qt(t=null){if(null!=t){const{customElementRegistry:e,customElements:n}=t;if(null===e)return null;if(void 0!==e)return Ht(e);if(void 0!==n)return Ht(n)}return Ht(globalThis.customElements)}function Ut(t,e){t.upgrade?.(e)}function Gt(t){try{if(null===t||"object"!=typeof t&&"function"!=typeof t)return null;const e=t,n=e.addEventListener,o=e.removeEventListener,s=e.constructor?.wcBindable;if("function"!=typeof n||"function"!=typeof o)return null;if("wc-bindable"!==s?.protocol)return null;if(!Number.isInteger(s.version)||s.version<1)return null;const r=Qt(s.properties,Vt);if(null===r)return null;const i=void 0===s.inputs?new Map:Qt(s.inputs,Kt);if(null===i)return null;const a=void 0===s.commands?new Map:Qt(s.commands,Jt);return null===a?null:{target:t,liveDeclaration:s,knownProperties:r,declaredInputs:i,declaredCommands:a}}catch{return null}}function Vt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&"string"==typeof e.event&&0!==e.event.length&&(void 0===e.getter||"function"==typeof e.getter)}function Kt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.attribute||"string"==typeof e.attribute)}function Jt(t){if("object"!=typeof t||null===t)return!1;const e=t;return"string"==typeof e.name&&0!==e.name.length&&(void 0===e.async||"boolean"==typeof e.async)}function Qt(t,e){if(!Array.isArray(t))return null;const n=new Map;for(const o of t){if(!e(o)||n.has(o.name))return null;n.set(o.name,o)}return n}function Xt(t,e){const n="."===e?`.${t}`:`${e}.${t}`;return{propName:t,propSegments:[t],propModifiers:[],statePathName:n,statePathInfo:nt(n),inFilters:[],outFilters:[],bindingType:"prop"}}function Yt(t){switch(t.bindingType){case"prop":case"event":case"radio":case"checkbox":return`${t.bindingType}::${t.propName}`;default:return null}}function Zt(t,e,n={}){const s=n.allowDeferred??!0;if(!e.some(t=>"spread"===t.bindingType))return e;const r=[],i=new WeakSet;for(const n of e){if("spread"!==n.bindingType){r.push(n);continue}t.nodeType!==Node.ELEMENT_NODE&&Z("Spread binding requires an element node.");const e=t,o=Ft(e);null===o&&Z(`Spread binding "${n.statePathName}" requires a custom element with wcBindable, but <${e.tagName.toLowerCase()}> is not a custom element.`);const a=qt(e);if(null===a&&Z(`CustomElementRegistry is unavailable for <${o}>.`),void 0===a.get(o)){s||Z(`Spread binding "${n.statePathName}" requires <${o}> to be registered. Define the custom element before initializing this binding.`),r.push(n);continue}Ut(a,e);const l=Gt(e);null===l&&Z(`Spread binding "${n.statePathName}" requires <${o}> to expose a valid wcBindable declaration.`);const c=n.statePathName,u=new Set;for(const t of l.knownProperties.keys()){if(u.has(t))continue;u.add(t);const e=Xt(t,c);i.add(e),r.push(e)}for(const t of l.declaredInputs.keys()){if(u.has(t))continue;u.add(t);const e=Xt(t,c);i.add(e),r.push(e)}}const a=new Map;for(let t=0;t<r.length;t++){const e=Yt(r[t]);null!==e&&a.set(e,t)}const l=[];for(let e=0;e<r.length;e++){const n=Yt(r[e]);if(null!==n){if(a.get(n)===e)l.push(r[e]);else if(o.debug&&i.has(r[e])){const o=r[a.get(n)],s=t.nodeType===Node.ELEMENT_NODE?`<${t.tagName.toLowerCase()}>`:"node";console.debug(`[@wcstack/state] spread: prop "${r[e].propName}" of ${s} overridden by explicit binding (statePath: "${o.statePathName}").`)}}else l.push(r[e])}return l}function te(t,e){let n=t;for(let t=0;t<e.length;t++){let o=e[t];for(n=n.firstChild;null!==n&&o>0;)n=n.nextSibling,o--;if(null===n)break}return n}function ee(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o];n.push({filterName:s.filterName,args:s.args,filterFn:pt(s.filterName,s.args,e,s.literals??s.args)})}return n}const ne=new WeakMap;function oe(t){return ne.get(t)||null}function se(t){if(!t.hasAttribute("bind-component"))return!1;const e=t.parentNode;return e instanceof Element&&e.hasAttribute(o.bindAttributeName)}function re(t){const e=[],n=t.querySelectorAll(`${o.tagNames.state}[bind-component]`);for(const o of n){if(!se(o))continue;const n=o.parentNode;n!==t&&e.push(n)}return e}function ie(t,e){for(let n=0;n<e.length;n++){const o=e[n];if(o!==t&&o.contains(t))return!0}return!1}function ae(t){const e=[],n=re(t),s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT,{acceptNode:t=>t.nodeType===Node.ELEMENT_NODE?t.hasAttribute(o.bindAttributeName)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP:null!==Ot(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;s.nextNode();){const t=s.currentNode;n.length>0&&ie(t,n)||e.push(t)}return e}const le=new WeakSet;function ce(t,e,n,o){const s=Zt(t,e,{allowDeferred:n.allowDeferred});if(s.some(t=>"spread"===t.bindingType)){const n=t.nodeType===Node.ELEMENT_NODE?Ft(t):null;return null===n&&Z("Spread binding deferred but element is not a custom element."),{bindings:[],deferred:{node:t,tagName:n,parseResults:e,transform:o}}}le.add(t);const r=function(t,e){const n=[];for(const o of e){const e=ee(o.inFilters,"input"),s=ee(o.outFilters,"output");if("text"!==o.bindingType)n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:t});else{const r=t.nodeType===Node.TEXT_NODE?t:document.createTextNode("");n.push({...o,inFilters:e,outFilters:s,node:t,replaceNode:r})}}return n}(t,function(t,e){return void 0===e?t:t.map(t=>null!=t.uuid?t:e(t))}(s,o));return function(t,e){ne.set(t,e)}(t,r),zt(t),{bindings:r,deferred:null}}function ue(t,e){const n=ae(t),o=[],s=[];for(const t of n){if(le.has(t))continue;const n=ce(t,la(t),{allowDeferred:!0},e);null===n.deferred?o.push(...n.bindings):s.push(n.deferred)}return[n,o,s]}function de(t){le.add(t)}function he(t){const{node:e,parseResults:n,transform:o}=t;return function(t){le.delete(t)}(e),ce(e,n,{allowDeferred:!1},o).bindings}const fe=new WeakMap;let pe=null;function me(t){let e=t;for(;e;){const t=fe.get(e);if(t)return t;let n=e.parentNode;null===n&&null!==pe&&e instanceof ShadowRoot&&(n=pe(e)),e=n}return null}function ge(t,e){null!==e?fe.set(t,e):fe.delete(t)}let ye=null;const be=new WeakMap;function we(t){return be.get(t)??[]}function ve(t,e){be.set(t,e)}function _e(t){return be.has(t)}const $e=new WeakMap;let Se=null,xe=0;function Pe(t){return $e.get(t)??[]}function Ne(t,e){null===Se?$e.set(t,e):Se.set(t,e)}function ke(){xe++,null===Se&&(Se=new Map)}function Ie(){if(0!==xe&&(xe--,!(xe>0||null===Se))){for(const[t,e]of Se)$e.set(t,e);Se=null}}function Ae(t){return(Se?.has(t)??!1)||$e.has(t)}const Ee=Symbol("$$setLoopContext"),Ce=Symbol("$$getByAddress"),Te=Symbol("$$hasByAddress"),Me=Symbol("$$setByAddress"),Oe=Symbol("$$connectedCallback"),Le=Symbol("$$disconnectedCallback"),Re=Symbol("$$updatedCallback"),je=Symbol("$$errorCallback"),We=new WeakMap,De=new WeakMap;class ze{absolutePathInfo;listIndex;constructor(t,e){this.absolutePathInfo=t,this.listIndex=e}}function Be(t,e){if(null===e){let e=De.get(t);return void 0!==e||(e=new ze(t,null),De.set(t,e)),e}{let n=We.get(e);void 0===n&&(n=new WeakMap,We.set(e,n));let o=n.get(t);return void 0!==o||(o=new ze(t,e),n.set(t,o)),o}}const Fe=new WeakMap;function He(t,e){let n=Fe.get(t);void 0===n&&(n=new Map,Fe.set(t,n));let o=n.get(e);return void 0===o&&(o=Object.freeze(new qe(t,e)),n.set(e,o)),o}class qe{pathInfo;stateElement;constructor(t,e){this.pathInfo=e,this.stateElement=t}}function Ue(t,e){return Be(He(t,e.pathInfo),e.listIndex)}function Ge(t,e,n){return Be(He(t,e),n)}const Ve=new WeakMap;function Ke(t,e){null===e?Ve.delete(t):Ve.set(t,e)}function Je(t){return Ve.get(t)||null}const Qe=new Map;function Xe(t,e){let n,o;if(0===t.wildcardCount||0===e.wildcardCount)return 0;if(1===t.wildcardCount&&e.wildcardCount>0&&e.wildcardPathSet.has(t.path))return 1;t.id<e.id?(n=t,o=e):(n=e,o=t);const s=`${n.path}\t${o.path}`;let r=Qe.get(s);return void 0!==r||(r=n.wildcardPathSet.intersection(o.wildcardPathSet).size,Qe.set(s,r)),r}function Ye(t,e,n){return e<0||e>=n?null:t.at(e-n)}function Ze(t,e){const n=t.indexes??[];return n.length===e?n:n.slice(n.length-e)}const tn=new WeakMap;function en(t){const e=me(t.node);if(null===e)return null;let n=tn.get(e);if(void 0===n)n=new WeakMap,tn.set(e,n);else{const e=n.get(t);if(void 0!==e)return e}let o=null;try{const n=Xe(e.pathInfo,t.statePathInfo);return n>0&&(o=Ye(e.listIndex,n-1,e.pathInfo.wildcardCount)),o}finally{n.set(t,o)}}const nn=new WeakMap;function on(t,e){if(null!=e)return e;let n=t.replaceNode.getRootNode();if(!1===t.replaceNode.isConnected){const e=Je(n);null===e?Z(`Cannot get absolute state address for disconnected binding: ${t.bindingType} ${t.statePathName} on ${t.node.nodeName}`):n=e}return n}function sn(t,e){let n=null;if(n=nn.get(t)||null,null!==n)return n;const o=on(t,e),s=en(t),r=ta(o);return null===r&&Z("No state tree found on this root for binding."),n=Ge(r,t.statePathInfo,s),nn.set(t,n),n}function rn(t){nn.delete(t)}const an=new WeakMap;function ln(t,e){const n=an.get(t);void 0===n?an.set(t,e):n instanceof Set?n.add(e):n!==e&&an.set(t,new Set([n,e])),null!==ye&&ye({type:"state:binding-added",absoluteAddress:t,binding:e})}function cn(t,e){const n=an.get(t);void 0!==n&&(n instanceof Set?n.delete(e):n===e&&an.delete(t),null!==ye&&ye({type:"state:binding-removed",absoluteAddress:t,binding:e}))}const un=new WeakMap;function dn(t){const e=an.get(t);return void 0!==e?e:null!==t.listIndex?un.get(t.absolutePathInfo)?.get(t.listIndex):void 0}const hn=new WeakMap,fn=new WeakMap;class pn{pathInfo;listIndex;_parentAddress;constructor(t,e){this.pathInfo=t,this.listIndex=e}get parentAddress(){if(void 0!==this._parentAddress)return this._parentAddress;const t=this.pathInfo.parentPathInfo;if(null===t)return null;let e=null;return e=this.pathInfo.segments[this.pathInfo.segments.length-1]===l?this.listIndex?.parentListIndex??null:this.listIndex,this._parentAddress=mn(t,e)}}function mn(t,e){if(null===e){let e=fn.get(t);return void 0!==e||(e=new pn(t,null),fn.set(t,e)),e}{let n=hn.get(e);void 0===n&&(n=new WeakMap,hn.set(e,n));let o=n.get(t);return void 0!==o||(o=new pn(t,e),n.set(t,o)),o}}const gn=new WeakMap;function yn(t){let e=null;if(e=gn.get(t)||null,null!==e)return e;if(t.statePathInfo.wildcardCount>0){const n=en(t);null===n&&Z(`Cannot resolve state address for binding with wildcard statePathName "${t.statePathName}" because list index is null.`),e=mn(t.statePathInfo,n)}else e=mn(t.statePathInfo,null);return gn.set(t,e),e}function bn(t){gn.delete(t)}function wn(){const t=new Map,e=new Map;return{add(n,o){let s=t.get(n);return void 0===s&&(s=new WeakSet,t.set(n,s)),!s.has(o)&&(s.add(o),e.set(n,(e.get(n)??0)+1),!0)},remove(n,o){const s=t.get(n);if(void 0===s||!s.has(o))return!1;s.delete(o);const r=(e.get(n)??1)-1;return r<=0?(t.delete(n),e.delete(n),!0):(e.set(n,r),!1)},has:(e,n)=>t.get(e)?.has(n)??!1,countOf:t=>e.get(t)??0,get keyCount(){return e.size},clear(){t.clear(),e.clear()}}}const vn=new Map,_n=wn();function $n(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Sn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}function xn(t){return("object"==typeof t||"function"==typeof t)&&null!==t&&"function"==typeof t.then}function Pn(t,e){const n=Array.isArray(t)?t:[t];for(const t of n)xn(t)&&Promise.resolve(t).catch(t=>{console.error(`[wcstack/state] ${e} rejected.`,t)})}class Nn{_name;_subscribers=new Set;constructor(t){this._name=t}get name(){return this._name}get size(){return this._subscribers.size}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}unsubscribe(t){return this._subscribers.delete(t)}emit(...t){const e=[];for(const n of this._subscribers)e.push(n(...t));return e}}class kn extends Nn{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==ye&&ye({type:"state:token-emit",kind:"event",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}const In=new WeakMap;function An(t,e){let n=In.get(t);void 0===n&&(n=new Map,In.set(t,n));let o=n.get(e);return void 0===o&&(o=new kn(e,t),n.set(e,o)),o}const En=new WeakMap;class Cn extends Nn{_stateElement;constructor(t,e){super(t),this._stateElement=e}emit(...t){return null!==ye&&ye({type:"state:token-emit",kind:"command",tokenName:this.name,args:t,subscriberCount:this.size,stateElement:this._stateElement}),super.emit(...t)}}function Tn(t){return t instanceof Cn}const Mn=new Map,On=wn();function Ln(t){const e=t.propModifiers.filter(t=>t===f||t===p).sort().join(",");return`${t.statePathName}::${e}`}function Rn(t){if(!t.propName.startsWith(v))return!1;const e=Ln(t);let n=Mn.get(e);void 0===n&&(n=((t,e,n)=>o=>{e.includes(f)&&o.preventDefault(),e.includes(p)&&o.stopPropagation();const s=o.target,r=s.getRootNode(),i=ta(r);null===i&&Z("No state tree found on this root for event handler.");const a=me(s),l=t.startsWith(j+".");i.createStateAsync("writable",async e=>{const c=e[Ee](a,()=>{let c=null!==a?a.pathInfo.wildcardCount:0;if(null!==a){const t=i.addressHooks;if(t){const e=t.handlerScope;for(let t=0;t<e.length;t++)c=e[t](i,s,r,a,c)}}const u=null!==a?Ze(a.listIndex,c):[];if(l){const s=e[Ce](mn(n,null));return Tn(s)||Z(`Event binding "${t}" did not resolve to a CommandToken. Declare the name in $commandTokens and reference it as $command.<name>.`),s.emit(o,...u)}const d=e[t];return"function"!=typeof d&&Z(`Handler "${t}" is not a function on the state tree.`),Reflect.apply(d,e,[o,...u])});Pn(c,`"${t}"`)})})(t.statePathName,t.propModifiers,t.statePathInfo),Mn.set(e,n));const o=t.propName.slice(2);return t.node.addEventListener(o,n),On.add(e,t),!0}function jn(t){if(!t.propName.startsWith(v))return!1;const e=Ln(t),n=Mn.get(e);if(void 0===n)return!1;const o=t.propName.slice(2);return t.node.removeEventListener(o,n),0!==On.countOf(e)&&(On.remove(e,t)&&Mn.delete(e),!0)}const Wn=new Map,Dn=wn();function zn(t,e){const n=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.statePathName}::${e}::${n}`}function Bn(t){let e="input";for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}const Fn=new Set(["radio","checkbox"]),Hn=new Set(["value","valueAsNumber","valueAsDate"]);function qn(t,e){if(t.nodeType!==Node.ELEMENT_NODE)return!1;const n=t,o=n.tagName.toLowerCase();if("input"===o){const t=(n.getAttribute("type")||"text").toLowerCase();if("button"===t)return!1;if(Fn.has(t)&&"checked"===e)return!0;if(Hn.has(e))return!0}if("select"===o&&"value"===e)return!0;if("textarea"===o&&"value"===e)return!0;const s=Ft(n);if(null!==s){const t=qt(n)?.get(s);void 0===t&&Z(`Custom element <${s}> is not defined. Cannot determine if property "${e}" is suitable for two-way binding.`);const o=Gt(n);if(o?.knownProperties.has(e))return!0}return!1}let Un=1,Gn=1,Vn=1;const Kn=new WeakMap;function Jn(t,e,n){let o=Kn.get(t);void 0===o&&(o=new Map,Kn.set(t,o));const s=function(t,e){return`${e}::${t}`}(e,n);let r=o.get(s);return void 0===r&&(r=Un++,o.set(s,r)),r}function Qn(t,e){return"to-element"===e?2*t:2*t+1}const Xn=new Set;function Yn(t){return{transactionId:Gn++,originBindingId:t,visitedEdges:Xn,hop:0}}function Zn(t,e){const n=new Set(t.visitedEdges);return n.add(e),{transactionId:t.transactionId,originBindingId:t.originBindingId,visitedEdges:n,hop:t.hop+1}}let to=null;function eo(){return to}function no(t,e){const n=to;to=t;try{return e()}finally{to=n}}const oo=[];let so=!1;const ro=new Map,io=wn(),ao=new WeakMap,lo=t=>t.detail,co=new WeakMap;function uo(t,e,n,o){const s=t.inFilters.map(t=>t.filterName+"("+t.args.join(",")+")").join("|");return`${t.propName}::${t.statePathName}::${e}::${s}::${n?"g":"n"}::${o?"o":"s"}`}function ho(t){let e="select"===t.node.tagName.toLowerCase()?"change":"input";const n=Ft(t.node);if(null!==n){const o=qt(t.node)?.get(n);void 0===o&&Z(`Custom element <${n}> is not defined. Cannot determine event name for two-way binding.`);const s=Gt(t.node)?.knownProperties.get(t.propName);s&&(e=s.event)}for(const n of t.propModifiers)n.startsWith(v)&&(e=n.slice(2));return e}function fo(t){if(null!==Ft(t.node)){const e=Gt(t.node)?.knownProperties.get(t.propName);if(e)return e.getter??lo}return null}function po(t){if(null===Ft(t.node))return!1;const e=Gt(t.node)?.knownProperties.get(t.propName);return"event"===e?.semantics}const mo=new WeakSet;function go(t){mo.add(t)}function yo(t){return!!mo.has(t)&&(mo.delete(t),!0)}const bo=new WeakMap;function wo(t,e){const n=bo.get(t);return!(void 0===n||n<e||(n===e?bo.delete(t):bo.set(t,n-e),0))}const vo=new WeakSet;function _o(t){vo.add(t)}function $o(t){return!!vo.has(t)&&(vo.delete(t),!0)}let So=0;function xo(){So--}function Po(){return So>0}class No{registry;entries=new Map;constructor(t){this.registry=t}wait(t,e,n=()=>{}){const o=t.toLowerCase();let s=this.entries.get(o);void 0===s&&(s={waiters:new Set},this.entries.set(o,s),this.registry.whenDefined(o).then(()=>this.settle(o,null),t=>this.settle(o,t)));const r={active:!0,resolve:e,reject:n};return s.waiters.add(r),()=>{r.active&&(r.active=!1,s?.waiters.delete(r))}}pendingCount(t){return this.entries.get(t.toLowerCase())?.waiters.size??0}settle(t,e){const n=this.entries.get(t);if(void 0===n)return;this.entries.delete(t);const o=Array.from(n.waiters);n.waiters.clear();for(const t of o)t.active&&(t.active=!1,null===e?t.resolve():t.reject(e))}}const ko=new WeakMap;function Io(t){let e=ko.get(t);return void 0===e&&(e=new No(t),ko.set(t,e)),e}function Ao(t,e){let n=null;for(const o of t.propModifiers){const t=o.indexOf("=");if(t<0)continue;const s=o.slice(0,t).trim(),r=o.slice(t+1).trim();s!==g&&s!==y&&Z(`Unknown binding modifier "${s}" in "${o}".`),s===e&&(null!==n&&Z(`Binding modifier "${e}" may only be specified once.`),n=r)}return n}function Eo(t){return t.propModifiers.some(t=>t.includes("="))}const Co=Object.freeze({authority:"state",syncOn:"call",observable:!1,outputOnly:!1}),To=Object.freeze({authority:"none",syncOn:"call",observable:!1,outputOnly:!1});function Mo(t,e){return"state"===t&&"call"===e?Co:{authority:t,syncOn:e,observable:!1,outputOnly:!1}}function Oo(t){if(!o.enableDirectionalInitialSync)return Eo(t)&&Z("init=/sync= modifiers require enableDirectionalInitialSync."),Co;const e=null===(n=Ao(t,g))?null:"state"===n||"element"===n||"auto"===n||"none"===n?n:Z(`Invalid init modifier value "${n}".`);var n;const s=function(t){return null===t||"call"===t?"call":"connect"===t?"connect":Z(`Invalid sync modifier value "${t}".`)}(Ao(t,y));if("event"===t.bindingType)return null!==e&&"none"!==e&&Z("Event bindings only allow init=none."),"call"===s?To:{authority:"none",syncOn:s,observable:!1,outputOnly:!1};if(t.propSegments[0]===S)return Mo("state",s);if("prop"!==t.bindingType)return null!==e&&"state"!==e&&"none"!==e&&Z(`Binding type "${t.bindingType}" does not support init=${e}.`),Mo(e??"state",s);const r=Gt(t.node);if(null===r)return Mo(e??"state",s);const i=r.knownProperties.has(t.propName),a=r.declaredInputs.has(t.propName);i||a||Z(`Property "${t.propName}" is not declared by wcBindable.`);const l=e??(i&&!a?"element":"state");return(i&&a?new Set(["state","element","auto","none"]):i?new Set(["element","none"]):new Set(["state","none"])).has(l)||Z(`init=${l} is incompatible with wcBindable member "${t.propName}".`),"connect"!==s||i||Z(`sync=connect requires observable property "${t.propName}".`),{authority:l,syncOn:s,observable:i,outputOnly:i&&!a}}let Lo=0,Ro=0;const jo=["active","disposed","failed"],Wo=new WeakMap,Do=new WeakMap,zo=new WeakMap,Bo=new WeakMap,Fo=new WeakMap;function Ho(t,e){const n=Fo.get(t);void 0!==n?n!==e&&(n instanceof Set?n.add(e):Fo.set(t,new Set([n,e]))):Fo.set(t,e)}function qo(t){return Fo.has(t)}function Uo(t,e){const n=Fo.get(t);if(void 0!==n)if(n instanceof Set)for(const t of Array.from(n))e(t);else e(n)}function Go(t,e){if(e(t),null!==t.firstChild)for(const n of Array.from(t.childNodes))Go(n,e)}function Vo(t){if("object"!=typeof t||null===t)return!1;const e=t;return 9===e.nodeType||11===e.nodeType&&"host"in e}class Ko{root;observer;constructor(t){this.root=t;const e=globalThis.MutationObserver;this.observer="function"==typeof e?new e(t=>this.handleMutations(t)):null,this.observer?.observe(t,{childList:!0,subtree:!0})}handleMutations(t){const e=[],n=[];for(let o=0;o<t.length;o++){const s=t[o],r=s.removedNodes;if(0===r.length||!wo(s.target,r.length))for(let t=0;t<r.length;t++)e.push(r[t]);const i=s.addedNodes;for(let t=0;t<i.length;t++)n.push(i[t])}const o=[];for(const t of e)yo(t)||Go(t,t=>{Uo(t,e=>{this.root.contains(t)||e.handleRemovedNode(t)})});for(const t of n)$o(t)&&!Po()||Go(t,t=>{Uo(t,e=>{this.root.contains(t)&&e.handleAddedNode(t,o)})});o.length>0&&Bi(o)}}const Jo=new WeakMap;function Qo(t){let e=Jo.get(t);return void 0===e&&(e=new Ko(t),Jo.set(t,e)),e}function Xo(t){const e=t.inFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|"),n=t.outFilters.map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.bindingType,t.propName,t.propModifiers.join(","),t.statePathName,e,n,t.uuid??""].join("\0")}function Yo(t,e,n){const o=ta(on(t,n));null===o&&Z("No state tree found on this root for binding.");const s=He(o,t.statePathInfo);return function(t,e,n){let o=un.get(t);void 0===o&&(o=new WeakMap,un.set(t,o));const s=o.get(e);void 0===s?o.set(e,n):s instanceof Set?s.add(n):s!==n&&o.set(e,new Set([s,n])),null!==ye&&ye({type:"state:binding-added",absoluteAddress:Be(t,e),binding:n})}(s,e,t),s}function Zo(t,e){const n=sn(t,e);return ln(n,t),n}function ts(t,e,n,o){null!==e?cn(e,t):function(t,e,n){const o=un.get(t);if(void 0===o)return;const s=o.get(e);void 0!==s&&(s instanceof Set?s.delete(n):s===n&&o.delete(e),null!==ye&&ye({type:"state:binding-removed",absoluteAddress:Be(t,e),binding:n}))}(n,o,t),bn(t),rn(t)}function es(t,e){null===t.teardowns&&(t.teardowns=new Set),t.teardowns.add(e)}class ns{records=new Set;rowPlan=null;rows=new Set;knownBindingsByNode=new WeakMap;optionsByBinding=new WeakMap;deferredByNode=new WeakMap;deferred=new Set;constructor(t=null){null!==t&&this.observe(t)}initialize(t,e={},n){const o=e.registerAddress??!0,s={registerAddress:o,registerPathInfo:e.registerPathInfo??o,applyOnReconnect:e.applyOnReconnect??!0},r=[];for(const e of t){const t=this.remember(e,s),o=this.rowOf(t),i=null===o?-1:o.bindings.indexOf(t);if(null!==o&&0===o.phases[i]){const e=o;this.observe(t.replaceNode),s.registerAddress&&null===e.addresses[i]&&null===e.patternPathInfos[i]&&(e.registered=!0,this.registerRowSlot(e,i));continue}const a=Do.get(t);void 0===a||"disposed"===a.phase||"failed"===a.phase?(this.start(t,s,n),r.push(t)):(this.observe(a.anchor),s.registerAddress&&null===a.address&&null===a.patternListIndex&&(a.options.registerAddress=!0,this.registerAddress(a)),"active"===a.phase&&this.settleInitialRecord(a),this.settleConnectedSnapshot(a))}return r.filter(t=>this.shouldApplyState(t))}activate(t,e){if(Vo(e)&&Qo(e),null===this.rowPlan)for(const n of t){const t=Do.get(n);if(void 0!==t&&t.session===this&&"disposed"!==t.phase&&"failed"!==t.phase){null===t.address&&null===t.patternListIndex&&(t.options.registerAddress=!0,this.registerAddress(t,e)),"active"===t.phase&&this.settleInitialRecord(t),this.settleConnectedSnapshot(t);continue}const o=this.optionsByBinding.get(n);void 0!==o?(o.registerAddress=!0,this.start(n,o,e)):this.initialize([n],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1})}else this.activatePlanRows(this.rowPlan,t,e)}shouldApplyState(t){if(!o.enableDirectionalInitialSync)return Eo(t)&&Oo(t),!0;const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0){if(!e.registered)return!0;if(2===e.phases[n])return!1;const t=e.plan.slots[n];return 1&e.flags[n]?"state"===t.authority||!t.policy.outputOnly:(e.flags[n]|=1,"state"===t.authority)}}const n=Do.get(t);return void 0===n||n.session!==this||!n.options.registerAddress||"waiting-definition"===n.phase||"failed"!==n.phase&&("active"===n.phase&&this.settleInitialRecord(n),n.initialApplyDone?"state"===n.resolvedAuthority||!n.outputOnlyMember&&!n.observationPending:(n.initialApplyDone=!0,"state"===n.resolvedAuthority))}getRecord(t){const e=this.rowOf(t),n=null===e?-1:e.bindings.indexOf(t);if(null!==e&&n>=0)return{id:64*e.id+n,info:t,generation:e.generation,phase:jo[e.phases[n]],teardowns:null};const o=Do.get(t);return o?.session===this?o:null}addTeardown(t,e){const n=Do.get(t);return!(void 0===n||!this.isAlive(n,n.generation)||(es(n,e),0))}deferUntilDefined(t,e,n,o=()=>{}){const s=qt(t);null===s&&Z(`CustomElementRegistry is unavailable for <${e}>.`),this.observe(t),Ho(t,this);const r={node:t,active:!0,cancel:null};let i=this.deferredByNode.get(t);void 0===i&&(i=new Set,this.deferredByNode.set(t,i)),i.add(r),this.deferred.add(r);const a=()=>!!r.active&&(r.active=!1,i?.delete(r),this.deferred.delete(r),!0);return r.cancel=Io(s).wait(e,()=>{if(a())try{Ut(s,t),n()}catch(t){o(t)}},t=>{a()&&o(t)}),()=>{a()&&r.cancel?.()}}disposeBinding(t){const e=this.rowOf(t);if(null!==e){const n=e.bindings.indexOf(t);if(n>=0)return void this.disposeRowSlot(e,n)}const n=Do.get(t);void 0!==n&&n.session===this&&this.disposeRecord(n)}get isRowSession(){return null!==this.rowPlan}get currentRowPlan(){return this.rowPlan}disposeBindings(t){for(let e=0;e<t.length;e++)this.disposeBinding(t[e]);if(!(this.rows.size>0))for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}destroyRow(t){const e=t.length>0?this.rowOf(t[0]):null;null!==e?(this.destroyRowRecord(e),this.rows.delete(e)):this.destroyRecords()}destroyRowRecord(t){for(let e=0;e<t.bindings.length;e++){const n=t.addresses[e];null!==n&&(cn(n,t.bindings[e]),t.addresses[e]=null),t.phases[e]=1}}dispose(){for(const t of Array.from(this.rows))for(let e=0;e<t.bindings.length;e++)this.disposeRowSlot(t,e);for(const t of Array.from(this.records))this.disposeRecord(t);for(const t of Array.from(this.deferred))t.active=!1,t.cancel?.(),this.deferred.delete(t),this.deferredByNode.get(t.node)?.delete(t)}canWholesaleDestroy(){if(this.deferred.size>0)return!1;if(0===this.records.size)return!0;for(const t of this.records)if(t.pendingDefinitions>0||t.observationPending)return!1;return!0}destroyRecords(){for(const t of this.rows)this.destroyRowRecord(t);this.rows.clear();for(const t of this.records)null!==t.address&&(cn(t.address,t.info),t.address=null),t.phase="disposed",t.teardowns=null;this.records.clear()}forEachActiveBindingNode(t){for(const e of this.rows)for(let n=0;n<e.bindings.length;n++)0===e.phases[n]&&t(e.bindings[n].node);for(const e of this.records)"active"===e.phase&&t(e.info.node)}rebindAddresses(){const t=[];for(const e of this.rows)for(let n=0;n<e.bindings.length;n++){if(0!==e.phases[n])continue;if(null===e.addresses[n]&&null===e.patternPathInfos[n])continue;const o=e.bindings[n];this.unregisterRowSlot(e,n),this.registerRowSlot(e,n),this.shouldApplyState(o)&&t.push(o)}for(const e of this.records){if("active"!==e.phase)continue;const n=e.info;if(null===e.address&&null===e.patternListIndex)continue;const o="for"===n.bindingType?sn(n):null;if(ts(n,e.address,e.patternPathInfo,e.patternListIndex),e.address=null,e.patternPathInfo=null,e.patternListIndex=null,this.registerAddress(e),null!==o){const t=sn(n);t!==o&&_e(o)&&ve(t,we(o)),t!==o&&Ae(o)&&Ne(t,Pe(o))}this.shouldApplyState(n)&&t.push(n)}return t}observe(t){const e=function(t){const e=t.getRootNode();return Vo(e)?e:null}(t);null!==e&&Qo(e)}handleMutations(t,e,n){for(const n of e)Go(n,e=>{t.contains(e)||this.handleRemovedNode(e)});const o=[];for(const e of n)Go(e,e=>{t.contains(e)&&this.handleAddedNode(e,o)});o.length>0&&Bi(o)}handleRemovedNode(t){const e=this.knownBindingsByNode.get(t);if(void 0!==e)if(e instanceof Map)for(const t of e.values())this.disposeBinding(t);else this.disposeBinding(e);const n=this.deferredByNode.get(t);if(void 0!==n)for(const t of Array.from(n))t.active=!1,t.cancel?.(),n.delete(t),this.deferred.delete(t)}handleAddedNode(t,e){const n=this.knownBindingsByNode.get(t);if(void 0===n)return;const o=n instanceof Map?n.values():[n];for(const t of o){const n=Do.get(t);if("active"===n?.phase){this.settleConnectedSnapshot(n);continue}if("disposed"!==n?.phase)continue;const o=this.optionsByBinding.get(t);if(void 0!==o)try{this.start(t,o),o.applyOnReconnect&&this.shouldApplyState(t)&&e.push(t)}catch{}}}knownMapFor(t){const e=this.knownBindingsByNode.get(t);if(e instanceof Map)return e;const n=new Map;if(void 0!==e){let t=Bo.get(e);void 0===t&&(t=Xo(e),Bo.set(e,t)),n.set(t,e)}return this.knownBindingsByNode.set(t,n),n}remember(t,e){const n=t.replaceNode;Ho(n,this);const o=this.knownMapFor(n);let s=Bo.get(t);void 0===s&&(s=Xo(t),Bo.set(t,s));const r=o.get(s);if(void 0!==r){const t=this.optionsByBinding.get(r);return void 0!==t&&(t.registerAddress||=e.registerAddress,t.registerPathInfo||=e.registerPathInfo,t.applyOnReconnect||=e.applyOnReconnect),r}return o.set(s,t),this.optionsByBinding.set(t,{...e}),t}initializeRow(t,e){this.rowPlan=t;const n=t.slots,o=e.length,s={id:++Lo,session:this,generation:++Ro,plan:t,bindings:e,registered:!1,phases:new Array(o).fill(0),flags:new Array(o).fill(0),addresses:new Array(o).fill(null),patternPathInfos:new Array(o).fill(null),patternListIndexes:new Array(o).fill(null)};this.rows.add(s);for(let t=0;t<o;t++){const o=e[t],r=o.replaceNode;if(Ho(r,this),this.addKnownRowBinding(r,o,t),Wo.set(o,s),n[t].isEvent){try{Rn(o)}catch(e){throw s.phases[t]=2,e}s.flags[t]|=2}}}activatePlanRows(t,e,n){const o=e.length>0?this.rowOf(e[0]):null;if(null===o||o.bindings!==e){for(const t of e)this.initialize([t],{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1});return}o.registered=!0;const s=t.slots;let r=!1;for(let t=0;t<e.length;t++)if(0===o.phases[t])null===o.addresses[t]&&null===o.patternPathInfos[t]&&this.registerRowSlot(o,t,n);else{if(r||(o.generation=++Ro,r=!0,this.rows.add(o)),o.phases[t]=0,o.flags[t]=0,s[t].isEvent){try{Rn(e[t])}catch(e){throw o.phases[t]=2,this.runRowSlotTeardowns(o,t),e}o.flags[t]|=2}this.registerRowSlot(o,t,n)}}rowOf(t){const e=Wo.get(t);return void 0!==e&&e.session===this?e:null}registerRowSlot(t,e,n){if(null!==t.addresses[e]||null!==t.patternPathInfos[e])return;const o=t.bindings[e],s=en(o);null!==s?(t.patternPathInfos[e]=Yo(o,s,n),t.patternListIndexes[e]=s):t.addresses[e]=Zo(o,n)}unregisterRowSlot(t,e){const n=t.addresses[e],o=t.patternPathInfos[e];null===n&&null===o||(ts(t.bindings[e],n,o,t.patternListIndexes[e]),t.addresses[e]=null,t.patternPathInfos[e]=null,t.patternListIndexes[e]=null)}disposeRowSlot(t,e){if(1!==t.phases[e]){t.phases[e]=1,this.runRowSlotTeardowns(t,e);for(let e=0;e<t.phases.length;e++)if(0===t.phases[e])return;this.rows.delete(t)}}runRowSlotTeardowns(t,e){try{this.unregisterRowSlot(t,e)}catch{}if(2&t.flags[e]){t.flags[e]&=-3;try{jn(t.bindings[e])}catch{}}}addKnownRowBinding(t,e,n){const o=this.knownBindingsByNode.get(t);if(void 0===o)return void this.knownBindingsByNode.set(t,e);if(o instanceof Map)return void o.set("@plan:"+n,e);const s=new Map;s.set("@plan:first",o),s.set("@plan:"+n,e),this.knownBindingsByNode.set(t,s)}start(t,e,n){!function(t){const e=t.node,n=t.replaceNode;e!==n&&null!==e.parentNode&&e.parentNode.replaceChild(n,e)}(t);const o=this.optionsByBinding.get(t)??{...e},s={id:++Lo,info:t,generation:++Ro,phase:"discovered",teardowns:null,session:this,anchor:t.replaceNode,options:o,address:null,patternPathInfo:null,patternListIndex:null,pendingDefinitions:0,initialPolicy:null,resolvedAuthority:null,initialSettled:!1,initialApplyDone:!1,outputOnlyMember:!1,observationPending:!1,eventSequence:0,hasProducerValue:!1,producerValue:void 0,eventAttached:!1,twowayAttached:!1};Do.set(t,s),this.records.add(s),void 0===n&&this.observe(s.anchor);try{s.phase="attaching",this.attachListeners(s),s.options.registerAddress&&this.registerAddress(s,n),0===s.pendingDefinitions&&(s.phase="active")}catch(t){throw s.phase="failed",this.runTeardowns(s),this.records.delete(s),t}}attachListeners(t){const e=t.info;Rn(e)?t.eventAttached=!0:e.propSegments[0]!==_?(function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=Bn(t),s=zn(t,o);let r=Wn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("radio"!==o.type)return void console.warn("[@wcstack/state] event.target is not a radio input element.");if(!1===o.checked)return;let s=o.value;for(const t of n)s=t.filterFn(s);const r=ta(o.getRootNode());null===r&&Z("No state tree found on this root for two-way binding.");const i=me(o);r.createState("writable",t=>{t[Ee](i,()=>{t[e]=s})})},Wn.set(s,r)),t.node.addEventListener(o,r),Dn.add(s,t),!0}var e,n;return!1}(e)&&es(t,()=>function(t){if("radio"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=Bn(t),n=zn(t,e),o=Wn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==Dn.countOf(n)&&(Dn.remove(n,t)&&Wn.delete(n),!0))}return!1}(e)),function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const o=Sn(t),s=$n(t,o);let r=vn.get(s);return void 0===r&&(e=t.statePathName,n=t.inFilters,r=t=>{const o=t.target;if(null===o)return void console.warn("[@wcstack/state] event.target is null.");if("checkbox"!==o.type)return void console.warn("[@wcstack/state] event.target is not a checkbox input element.");const s=o.checked;let r=o.value;for(const t of n)r=t.filterFn(r);const i=ta(o.getRootNode());null===i&&Z("No state tree found on this root for two-way binding.");const a=me(o);i.createState("writable",t=>{t[Ee](a,()=>{let n=t[e];if(Array.isArray(n))if(s)-1===n.indexOf(r)&&(t[e]=n.concat(r));else{const o=n.indexOf(r);-1!==o&&(t[e]=n.toSpliced(o,1))}else t[e]=s?[r]:[]})})},vn.set(s,r)),t.node.addEventListener(o,r),_n.add(s,t),!0}var e,n;return!1}(e)&&es(t,()=>function(t){if("checkbox"===t.bindingType&&-1===t.propModifiers.indexOf(m)){const e=Sn(t),n=$n(t,e),o=vn.get(n);return void 0!==o&&(t.node.removeEventListener(e,o),0!==_n.countOf(n)&&(_n.remove(n,t)&&vn.delete(n),!0))}return!1}(e)),this.attachAfterDefinition(t,()=>{if(o.enableDirectionalInitialSync&&qn(e.node,e.propName)&&-1===e.propModifiers.indexOf(m)){const n=function(t,e,n){let o=ao.get(t);void 0===o&&(o=new Map,ao.set(t,o));let s=o.get(e);return void 0===s&&(s=new Set,o.set(e,s)),s.add(n),()=>{s?.delete(n),0===s?.size&&o?.delete(e),0===o?.size&&ao.delete(t)}}(e.node,e.propName,e=>{this.isAlive(t,t.generation)&&(t.eventSequence+=1,t.hasProducerValue=!0,t.producerValue=e)});es(t,n)}!function(t){const e=Ft(t.node);if(null!==e){const n=qt(t.node),o=n?.get(e);if(void 0===o)return void(null===n&&Z(`CustomElementRegistry is unavailable for <${e}>.`))}if(qn(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const e=ho(t),n=fo(t),s=po(t),r=uo(t,e,null!==n,s);let i=ro.get(r);void 0===i&&(i=((t,e,n,s,r)=>i=>{const a=i.target;if(null===a)return void console.warn("[@wcstack/state] event.target is null.");let l;if(null!==s)l=s(i),s!==lo||r||function(t,e,n){const o=t[e];let s=null;if(void 0===n?void 0!==o&&(s=`the event carried no detail (undefined) while element.${e} is ${typeof o}`):null===n||"object"!=typeof n||!Object.prototype.hasOwnProperty.call(n,e)||null!==o&&"object"==typeof o||(s=`the event's detail is an object with a "${e}" key while element.${e} is ${typeof o}`),null===s)return;let r=co.get(t);void 0===r&&(r=new Set,co.set(t,r)),r.has(e)||(r.add(e),console.warn(`[@wcstack/state] [wcs/default-getter-mismatch] <${t.tagName.toLowerCase()}> "${e}": ${s}. With no getter, state receives e.detail as-is. Dispatch the value itself as detail, or declare getter (e.g. (e) => e.detail.${e}, or (e) => e.target.${e}) on that wcBindable property.`))}(a,t,l);else{if(!(t in a))return void console.warn(`[@wcstack/state] Property "${t}" does not exist on target element.`);l=a[t]}let c=l;for(const t of n)c=t.filterFn(c);const u=ao.get(a)?.get(t);if(void 0!==u)for(const t of u)t(c);let d=null;if(o.enablePropagationContext){const n=Jn(a,t,e),s=function(t,e){for(let n=oo.length-1;n>=0;n--){const o=oo[n];if(o.node===t&&o.receipt.member===e)return o.receipt}return null}(a,t);if(null!==s&&Object.is(s.writtenValue,l))return o.debug&&console.debug("[@wcstack/state] propagation: write confirmation suppressed echo.",{node:a,propName:t,statePathName:e,transactionId:s.transactionId,coveredBySameValueGuard:o.sameValueGuard&&(null===c||"object"!=typeof c)}),void(null!==ye&&ye({type:"propagation:suppressed",reason:"confirmation",transactionId:s.transactionId,edgeId:Qn(n,"to-state"),node:a,member:t}));const r=Qn(n,"to-state"),i=eo();if(null!==i&&i.visitedEdges.has(r))return void(null!==ye&&ye({type:"propagation:suppressed",reason:"visited-edge",transactionId:i.transactionId,edgeId:r,node:a,member:t}));d=Zn(i??Yn(n),r)}const h=ta(a.getRootNode());null===h&&Z("No state tree found on this root for two-way binding.");const f=me(a),p=()=>{r&&(so=!0);try{h.createState("writable",t=>{t[Ee](f,()=>{t[e]=c})})}finally{r&&(so=!1)}};null!==d?no(d,p):p()})(t.propName,t.statePathName,t.inFilters,n,s),ro.set(r,i)),t.node.addEventListener(e,i),io.add(r,t)}}(e),t.twowayAttached=!0})):this.attachAfterDefinition(t,()=>{(function(t){if(t.propSegments[0]!==_)return!1;const e=t.node,n=Ft(e),o=qt(e);if(null!==n&&void 0===o?.get(n))return null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),!0;if(En.has(t))return!0;const s=t.propSegments[1];"string"==typeof s&&0!==s.length||Z('eventToken binding requires a property name (e.g., "eventToken.error").');const r=function(t){return null===Ft(t)?null:Gt(t)}(e);null===r&&Z(`eventToken binding requires a wc-bindable custom element. <${e.tagName.toLowerCase()}> is not wc-bindable.`);const i=r.knownProperties.get(s);void 0===i&&Z(`Property "${s}" is not declared in wcBindable.properties of <${e.tagName.toLowerCase()}>.${rt(s,r.knownProperties.keys())}`);const a=i.event,l=t.statePathName,c=t.propModifiers,u=t=>{c.includes(f)&&t.preventDefault(),c.includes(p)&&t.stopPropagation();const n=ta(e.getRootNode());null===n&&Z("No state tree found on this root for eventToken handler."),n.eventTokenNames.has(l)||Z(`[wcs/token-undeclared] eventToken "${l}" is not declared in $eventTokens.${rt(l,n.eventTokenNames)}${it}`);const o=me(e);n.createStateAsync("writable",async e=>{Pn(e[Ee](o,()=>{const s=null!==o?Ze(o.listIndex,o.pathInfo.wildcardCount):[];return An(n,l).emit(e,t,...s)}),`$on."${l}"`)})};return e.addEventListener(a,u),En.set(t,{eventName:a,handler:u}),!0})(e)&&es(t,()=>function(t){if(t.propSegments[0]!==_)return!1;const e=En.get(t);return void 0!==e&&(t.node.removeEventListener(e.eventName,e.handler),En.delete(t),!0)}(e))})}attachAfterDefinition(t,e){const n=Ft(t.info.node);if(null===n)return void e();const o=qt(t.info.node);if(null===o&&Z(`CustomElementRegistry is unavailable for <${n}>.`),void 0!==o.get(n))return void e();t.phase="waiting-definition",t.pendingDefinitions+=1;const s=t.generation,r=Io(o).wait(n,()=>{if(this.isAlive(t,s))try{Ut(o,t.info.node),e(),t.pendingDefinitions-=1,0===t.pendingDefinitions&&(t.phase="active",this.settleInitialRecord(t))}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}},()=>{this.isAlive(t,s)&&(t.phase="failed",this.runTeardowns(t),this.records.delete(t))});es(t,r)}settleInitialRecord(t){if(o.enableDirectionalInitialSync&&!t.initialSettled&&t.options.registerAddress){t.phase="synchronizing";try{const e=Oo(t.info),n=function(t,e){return"auto"!==e?e:function(t){const e=ta(t.replaceNode.getRootNode());null===e&&Z("No state tree found on this root for binding.");const n=yn(t);let o=!1;return e.createState("readonly",t=>{o=t[Te](n)}),o}(t)?"state":"element"}(t.info,e.authority);if(t.initialPolicy=e,t.resolvedAuthority=n,t.initialSettled=!0,t.outputOnlyMember=e.outputOnly,t.phase="active",!e.observable)return;if("connect"===e.syncOn&&t.info.node instanceof HTMLElement&&!t.info.node.isConnected)return t.observationPending=!0,void So++;this.readProducerSnapshot(t,"call"===e.syncOn)}catch(e){throw t.phase="failed",this.runTeardowns(t),this.records.delete(t),e}}}readProducerSnapshot(t,e){if(!this.isAlive(t,t.generation))return;const n=t.info.node,o=t.info.propName;if(!(o in n))return;const s=t.eventSequence,r=n[o];t.observationPending&&(t.observationPending=!1,xo()),e&&t.eventSequence!==s||(t.hasProducerValue=!0,t.producerValue=r,"element"===t.resolvedAuthority&&function(t,e){let n=e;for(const e of t.inFilters)n=e.filterFn(n);const o=ta(t.node.getRootNode());null===o&&Z("No state tree found on this root for initial binding sync.");const s=me(t.node);o.createState("writable",e=>{e[Ee](s,()=>{e[t.statePathName]=n})})}(t.info,r))}settleConnectedSnapshot(t){if(o.enableDirectionalInitialSync&&t.observationPending&&t.info.node instanceof HTMLElement&&t.info.node.isConnected)try{this.readProducerSnapshot(t,!1)}catch{t.phase="failed",this.runTeardowns(t),this.records.delete(t)}}registerAddress(t,e){if(null!==t.address||null!==t.patternListIndex)return;const n=t.info,o=en(n);if(null!==o?(t.patternPathInfo=Yo(n,o,e),t.patternListIndex=o):t.address=Zo(n,e),!t.options.registerPathInfo)return;const s=ta(n.replaceNode.getRootNode());null===s&&Z("No state tree found on this root for binding."),"event"!==n.bindingType&&s.setPathInfo(n.statePathName,n.bindingType)}isAlive(t,e){return t.generation===e&&Do.get(t.info)===t&&"disposed"!==t.phase&&"failed"!==t.phase}disposeRecord(t){"disposed"!==t.phase&&(t.phase="disposed",this.runTeardowns(t),this.records.delete(t))}runTeardowns(t){t.observationPending&&(t.observationPending=!1,xo());const e=t.info;if(null!==t.address||null!==t.patternListIndex)try{ts(e,t.address,t.patternPathInfo,t.patternListIndex),t.address=null,t.patternPathInfo=null,t.patternListIndex=null}catch{}if(t.twowayAttached){t.twowayAttached=!1;try{!function(t){const e=Ft(t.node);if(null!==e){const n=qt(t.node),o=n?.get(e);if(void 0===o)return}if(qn(t.node,t.propName)&&-1===t.propModifiers.indexOf(m)){const e=ho(t),n=uo(t,e,null!==fo(t),po(t)),o=ro.get(n);if(void 0===o)return;t.node.removeEventListener(e,o),io.remove(n,t)&&ro.delete(n)}}(e)}catch{}}if(null!==t.teardowns){const e=Array.from(t.teardowns).reverse();t.teardowns=null;for(const t of e)try{t()}catch{}}if(t.eventAttached){t.eventAttached=!1;try{jn(e)}catch{}}}}function os(t){let e=zo.get(t);return void 0===e&&(e=new ns(t),zo.set(t,e)),e}function ss(t){return Do.get(t)?.session??Wo.get(t)?.session??null}let rs=null;function is(t,e){let n=t;for(const t of e)n=t.filterFn(n);return n}const as=Object.freeze([]),ls=new WeakMap,cs=new WeakMap;function us(t){return cs.get(t)??[]}function ds(t,e){cs.set(t,e)}const hs=new WeakMap;function fs(t){return hs.get(t)??[]}function ps(t,e){hs.set(t,e)}Set.prototype.difference||(Set.prototype.difference=function(t){const e=new Set(this);for(const n of t)e.delete(n);return e}),Set.prototype.intersection||(Set.prototype.intersection=function(t){const e=new Set;for(const n of t)this.has(n)&&e.add(n);return e});let ms=0;function gs(){return`u${(ms++).toString(36)}`}let ys=0,bs=0;const ws=Symbol("wcs.listIndex.noValue");class vs{uuid=gs();parentListIndex;position;length;_index;_version;_indexes;_listIndexes;_chainGeneration;_homeParentListIndex;_value;constructor(t,e,n){this.parentListIndex=t,this.position=t?t.position+1:0,this.length=this.position+1,this._homeParentListIndex=n,this._value=ws,this._index=e,this._version=ys,this._chainGeneration=bs}get index(){return this._index}set index(t){this._index=t,this._version=++ys,this.indexes[this.position]=t}get version(){return this._version}get homeParentListIndex(){return this._homeParentListIndex}get value(){return this._value}set value(t){this._value=t}get dirty(){return null!==this.parentListIndex&&(this.parentListIndex.dirty||this.parentListIndex.version>this._version)}get indexes(){return null===this.parentListIndex?void 0===this._indexes&&(this._indexes=[this._index]):(void 0===this._indexes||this.dirty)&&(this._indexes=[...this.parentListIndex.indexes,this._index],this._version=ys),this._indexes}get listIndexes(){return null===this.parentListIndex?void 0===this._listIndexes&&(this._listIndexes=[new WeakRef(this)]):void 0!==this._listIndexes&&this._chainGeneration===bs||(this._listIndexes=[...this.parentListIndex.listIndexes,new WeakRef(this)],this._chainGeneration=bs),this._listIndexes}get varName(){return`$${this.position+1}`}reparent(t){this.parentListIndex=t,this._indexes=void 0,this._listIndexes=void 0,this._version=++ys,bs++}at(t){return t>=0?this.listIndexes[t]?.deref()||null:this.listIndexes[this.listIndexes.length+t]?.deref()||null}}function _s(t,e,n=t){return new vs(t,e,n)}function $s(t,e){t.reparent(e)}function Ss(t){return t.homeParentListIndex}function xs(t,e){t.value=e}function Ps(t,e){const n=t.value;return n!==ws&&n===e.value}const Ns=new WeakMap,ks=new WeakSet;function Is(t){return ks.has(t)}function As(t){const e=Ns.get(t);return void 0===e?null:e}function Es(t,e){const n=Ns.get(t);if(void 0===n)return null;const o=n[0];if(void 0!==o){const t=function(t,e){const n=Ss(t),o=t.parentListIndex;return null===n||n===o||ks.has(n)?function(t,e,n){return null!==t&&null!==n&&n!==e&&!!ks.has(t)&&!ks.has(n)&&n.position===t.position&&Ps(n,t)}(n,o,e)||function(t,e){return t!==e&&null!==t&&null!==e&&t.position===e.position&&ks.has(t)&&!ks.has(e)}(o,e)?e:null:n}(o,e);if(null!==t)for(const e of n)$s(e,t)}return n}function Cs(t,e){null!==e?Ns.set(t,e):Ns.delete(t)}const Ts=new WeakMap;function Ms(t,e){null===e?Ts.delete(t):Ts.set(t,e)}function Os(t){const e=Ts.get(t);e&&(e.dirty=!0)}const Ls=Symbol.for("wcstack.transition-runner");function Rs(t){const e=globalThis[Ls];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}function js(t,e,n){const o=Rs(t);if(null!==o)return o.run(e,{source:t,types:n});e()}const Ws=[],Ds=[];function zs(t){Ds.includes(t)||Ds.push(t)}function Bs(t,e=0){const n=Ws.findIndex(t=>t.priority>e),o={listener:t,priority:e};-1===n?Ws.push(o):Ws.splice(n,0,o)}function Fs(t){queueMicrotask(()=>{throw t})}const Hs=new class{_queueUpdateRecords=[];_queueRenderOnlyAddresses=[];constructor(){}enqueueAbsoluteAddress(t,e=null){for(let e=0;e<Ds.length;e++)Ds[e](t);const n=this._isQueueEmpty();this._queueUpdateRecords.push({absoluteAddress:t,context:e}),n&&this._scheduleDrain()}enqueueRenderOnlyAddress(t){const e=this._isQueueEmpty();this._queueRenderOnlyAddresses.push(t),e&&this._scheduleDrain()}_isQueueEmpty(){return 0===this._queueUpdateRecords.length&&0===this._queueRenderOnlyAddresses.length}_scheduleDrain(){ke(),queueMicrotask(()=>{const t=this._queueUpdateRecords,e=this._queueRenderOnlyAddresses;this._queueUpdateRecords=[],this._queueRenderOnlyAddresses=[],this._applyChange(t,e)})}hasQueuedPath(t,e){return this._queueUpdateRecords.some(n=>n.absoluteAddress.absolutePathInfo.stateElement===t&&n.absoluteAddress.absolutePathInfo.pathInfo.path===e)}testApplyChange(t,e){this._applyChange(t.map((t,n)=>({absoluteAddress:t,context:e?.[n]??null})))}_applyChange(t,n=[]){const o=new Map,s=new Set;for(let e=0;e<t.length;e++){const n=t[e],r=o.get(n.absoluteAddress);null!==ye&&null!=r&&null!==n.context&&r.transactionId!==n.context.transactionId&&ye({type:"propagation:coalesced",absoluteAddress:n.absoluteAddress,droppedTransactionId:r.transactionId,winnerTransactionId:n.context.transactionId}),o.set(n.absoluteAddress,n.context),s.add(n.absoluteAddress)}for(let t=0;t<n.length;t++){const e=n[t];o.has(e)||o.set(e,null)}const r=[],i=new Map;o.forEach((t,e)=>{if(null!==t&&t.hop>=32)return console.error("[@wcstack/state] propagation hop limit exceeded; update record quarantined.",{path:e.absolutePathInfo.pathInfo.path,transactionId:t.transactionId,hop:t.hop,maxHops:32}),void(null!==ye&&ye({type:"propagation:hop-limit",absoluteAddress:e,transactionId:t.transactionId,hop:t.hop}));const n=dn(e);if(void 0!==n)if(n instanceof Set)for(const e of n)!1!==e.replaceNode.isConnected&&(r.push(e),null!==t&&i.set(e,t));else!1!==n.replaceNode.isConnected&&(r.push(n),null!==t&&i.set(n,t))});try{const t=()=>{i.size>0?Bi(r,i):Bi(r)};if(e()||0===r.length)t();else{const e=js("state",t);void 0!==e&&e.catch(Fs)}}finally{Ie(),function(t){for(const e of Ws.slice())e.listener(t)}(s)}}};function qs(){return Hs}const Us=new WeakMap,Gs=new WeakMap,Vs=new WeakMap,Ks=new WeakMap;let Js=!1;const Qs=new WeakMap,Xs=new WeakMap,Ys=new WeakMap,Zs=[];function tr(t,e){const n=er(t);if(n.recorded.has(e))return;n.recorded.add(e);const o=nt(e).cumulativePaths;if(o.length<2)return;let s=Ys.get(t);void 0===s&&Ys.set(t,s=new Map);for(let t=0;t<o.length-1;t++){let n=s.get(o[t]);void 0===n&&s.set(o[t],n=new Set),n.add(e)}}function er(t){let e=Us.get(t);return void 0===e&&Us.set(t,e={byPath:new Map,lastValue:new Map,recorded:new Set,tracked:new Set}),e}function nr(t,e,n){let o=t.get(e);void 0===o&&t.set(e,o=new Set),o.add(n)}function or(t,e,n){const o=t.get(e);o.delete(n),0===o.size&&t.delete(e)}function sr(t,e,n,o){const s=function(t,e){let n=t.byPath.get(e);return void 0===n&&t.byPath.set(e,n=new Map),n}(t,e);let r=Gs.get(o);if(void 0===r&&Gs.set(o,r=new Map),r.has(e)){const t=r.get(e);return Object.is(t,n)||(or(s,t,o),r.set(e,n),nr(s,n,o)),!1}return r.set(e,n),nr(s,n,o),!0}function rr(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function ir(t,e,n,o,s,r){t.lastValue.set(e,n),s&&(null!==o.listIndex&&rr(Vs,o.listIndex,r),null!==r.levelListIndex&&rr(Ks,r.levelListIndex,r))}function ar(t,e,n,o,s){Js=!0;const r=er(t);tr(t,e),ir(r,e,s,o,sr(r,e,n,o),{stateElement:t,path:e,absAddress:o,levelListIndex:null})}function lr(t,e){er(t).tracked.add(e)}function cr(t,e,n){if("number"!=typeof e)return;const o=t.indexes[e];if(void 0!==o)for(const e of t.getters)n.push(Ue(t.stateElement,mn(e,o)))}function ur(t,e){if(void 0!==t)for(const n of t)e.push(n)}function dr(t,e,n,o,s){const r=Us.get(t),i=r?.byPath.get(e),a=Qs.get(t)?.get(e);if(void 0===r||void 0===i&&void 0===a)return Zs;const l=r.lastValue.has(e),c=r.lastValue.get(e);r.lastValue.set(e,s);const u=[],d=!n||!Object.is(o,s),h=l&&(!n||!Object.is(c,o))&&!Object.is(c,s);if(void 0!==i&&(n&&ur(i.get(o),u),h&&ur(i.get(c),u),d&&ur(i.get(s),u)),void 0!==a)for(const t of a)n&&cr(t,o,u),h&&cr(t,c,u),d&&cr(t,s,u);return u}function hr(t,e){let n=t;for(const t of e){if("object"!=typeof n||null===n)return;n=n[t]}return n}function fr(t,e,n){const o=Us.get(t).byPath.get(e);if(void 0!==o)for(const t of o.values())ur(t,n);const s=Qs.get(t)?.get(e);if(void 0!==s)for(const t of s)for(let e=0;e<t.indexes.length;e++)cr(t,e,n)}function pr(t){const e=Ks.get(t.levelListIndex),n=e.indexOf(t);e.splice(n,1)}function mr(t){if(!Js)return;const e=Vs.get(t);if(void 0!==e){Vs.delete(t);for(const t of e){const{stateElement:e,path:n,absAddress:o}=t,s=Gs.get(o),r=s.get(n);s.delete(n),or(Us.get(e).byPath.get(n),r,o),null!==t.levelListIndex&&pr(t)}}}function gr(t,e,n){if(!Js)return;const o=Ks.get(t);if(void 0!==o)for(const{stateElement:t,path:s,absAddress:r}of o){const o=Us.get(t),i=o.byPath.get(s);or(i,e,r),nr(i,n,r),Gs.get(r).set(s,n);const a=o.lastValue.get(s);(Object.is(a,e)||Object.is(a,n))&&(Os(r),qs().enqueueAbsoluteAddress(r,null))}}const yr=new WeakMap,br=Object.freeze([]),wr=new Set;function vr(t,e,n){const o=function(t,e,n){const o=Array.isArray(e)&&e.length>0?e:br,s=Array.isArray(n)&&n.length>0?n:br,r=function(t,e){const n=Array.isArray(t)&&t.length>0?t:br,o=Array.isArray(e)&&e.length>0?e:br;let s=yr.get(n);return s&&s.get(o)||null}(o,s);if(r)return r;const i=Es(o,t)||[],a=i.length>0?Ss(i[0]):t;let l;try{if(0===s.length)return l={oldIndexes:i,newIndexes:[],changeIndexSet:wr,deleteIndexSet:new Set(i),addIndexSet:wr};let e=Es(s,t);if(0===o.length){if(null===e){e=[];for(let n=0;n<s.length;n++){const o=_s(t,n,a);e.push(o)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:wr,deleteIndexSet:wr,addIndexSet:new Set(e)}}if(function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(o,s))return l={oldIndexes:i,newIndexes:i,changeIndexSet:wr,deleteIndexSet:wr,addIndexSet:wr};if(null!==e)return function(t,e){const n=new Set(e),o=new Set(t),s=new Set,r=n.difference(o),i=o.difference(n),a=new Map;for(let e=0;e<t.length;e++)a.set(t[e],e);for(let t=0;t<e.length;t++){const n=e[t];r.has(n)||a.get(n)!==t&&s.add(n)}return{oldIndexes:t,newIndexes:e,changeIndexSet:s,deleteIndexSet:i,addIndexSet:r}}(i,e);e=[];const n=new Map;for(let t=0;t<o.length;t++){const e=o[t];let s=n.get(e);s||(s=[],n.set(e,s)),s.push(t)}const r=new Set,c=new Set;for(let o=0;o<s.length;o++){const l=s[o],u=n.get(l),d=u&&u.length>0?u.shift():void 0;if(void 0===d){const n=_s(t,o,a);e.push(n),c.add(n)}else{const t=i[d];d!==o&&r.add(t),e.push(t)}}return l={oldIndexes:i,newIndexes:e,changeIndexSet:r,deleteIndexSet:new Set(i).difference(new Set(e)),addIndexSet:c}}finally{void 0!==l&&(function(t,e,n){let o=yr.get(t);o||(o=new WeakMap,yr.set(t,o)),o.set(e,n)}(o,s,l),Cs(s,l.newIndexes))}}(t,e,n);!function(t,e){for(let n=0;n<t.length;n++){if(t[n].index!==n){const e=t[n].index;t[n].index=n,gr(t[n],e,n)}xs(t[n],e[n])}}(o.newIndexes,Array.isArray(n)&&n.length>0?n:br),function(t){for(const e of t)ks.add(e)}(o.deleteIndexSet);for(const t of o.deleteIndexSet)mr(t);return function(t){for(const e of t)ks.delete(e)}(o.newIndexes),function(t,e){if(!Js||t===e)return;const n=Xs.get(t);if(void 0===n)return;Xs.delete(t);const o=Xs.get(e);Xs.set(e,void 0===o?n:o.concat(n));for(const o of n){o.indexes=e;const n=er(o.stateElement).lastValue.get(o.path);if("number"!=typeof n)continue;const s=t[n],r=e[n];if(s!==r)for(const t of[s,r])if(void 0!==t&&!Is(t))for(const e of o.getters){const n=Ue(o.stateElement,mn(e,t));Os(n),qs().enqueueAbsoluteAddress(n,null)}}}(o.oldIndexes,o.newIndexes),o}const _r=new WeakSet,$r=new WeakMap;function Sr(t){return $r.get(t)??null}function xr(t,e){$r.set(t,e)}const Pr=new WeakMap;function Nr(t){return Pr.get(t)??[]}function kr(t,e){Pr.set(t,e)}function Ir(t,e){const n=Nr(t);for(const t of n)ge(t,e)}const Ar=new WeakMap,Er=new WeakMap;function Cr(t,e){for(let n=0;n<t.length;n++)if(e.has(t[n]))return!0;return!1}function Tr(t,e,n){Ir(t,e);const o=us(t),s=Sr(t);if(null!==s&&(s.activate(o,n.rootNode),null!==e&&!1===n.stateElement.hasUpdatedCallback&&!0!==n.stateElement.hasRecursion)){const r=function(t){return Ar.get(t)??null}(t);if(null!==r)return void function(t,e,n,o,s){const r=function(t,e,n){let o=Er.get(t);void 0===o&&Er.set(t,o=new Map);const s=o.get(n);if(void 0!==s)return s;const r=n+".",i=e.map((e,o)=>{const s=t.slots[o];if(s.isEvent||s.isIndexBinding)return null;const i=e.statePathInfo.path;if(!i.startsWith(r))return null;const a=i.slice(r.length).split("."),l=[];let c=n;for(const t of a){if("*"===t)return null;c+="."+t,l.push(c)}return{tail:a,prefixes:l}});return o.set(n,i),i}(t,e,o.pathInfo.path),i=s.stateElement.getterPaths;let a,l=!1;for(let t=0;t<e.length;t++){const c=e[t];if(!n.shouldApplyState(c))continue;const u=r[t];if(null===u||Cr(u.prefixes,i)){Di(c,s);continue}if(s.appliedBindingSet.has(c))continue;s.appliedBindingSet.add(c),l||(a=s.state[Ce](o),l=!0);const d=u.tail;let h=a;for(let t=0;t<d.length;t++){if(null==h){h=void 0;break}h=h[d[t]]}Wi(c,s,h)}}(r,o,s,e,n)}for(const t of o)null===s&&ln(sn(t),t),(null===s||s.shouldApplyState(t))&&Di(t,n)}function Mr(t){if(!t.mounted)return;const e=us(t),n=Sr(t);for(let t=0;t<e.length;t++){const o=e[t];null!==n?n.disposeBinding(o):cn(sn(o),o)}!function(t){const e=Nr(t);for(let t=0;t<e.length;t++)ge(e[t],null)}(t)}const Or=new WeakMap,Lr=Object.freeze(new Set);function Rr(t,e){const n=Or.get(t);n?n.add(e):Or.set(t,new Set([e]))}function jr(t){const e=Or.get(t);return void 0!==e?e:Lr}function Wr(t,e){const n=Or.get(t);n&&(n.delete(e),0===n.size&&Or.delete(t))}function Dr(t,e){if(0===t.length)return t;const n=[];for(let o=0;o<t.length;o++){const s=t[o];n.push({filterName:s.filterName,args:s.args,filterFn:pt(s.filterName,s.args,e,s.literals??s.args)})}return n}function zr(t){return{...t,inFilters:Dr(t.inFilters,"input"),outFilters:Dr(t.outFilters,"output")}}const Br=new Set(["if","elseif","else","for"]);class Fr{_content;_childNodeArray=[];_firstNode=null;_lastNode=null;_mounted=!1;_ranged=!1;constructor(t,e=!1){this._content=t,this._ranged=e;const n=[];for(let e=t.firstChild;null!==e;e=e.nextSibling)n.push(e);this._childNodeArray=n,this._firstNode=this._childNodeArray.length>0?this._childNodeArray[0]:null,this._lastNode=this._childNodeArray.length>0?this._childNodeArray[this._childNodeArray.length-1]:null}get firstNode(){return this._firstNode}get lastNode(){return this._lastNode}get mounted(){return this._mounted}appendTo(t){const e=this._childNodeArray;for(let n=0;n<e.length;n++){const o=e[n];_o(o),t.appendChild(o)}this._mounted=!0}_movableNodes(){if(!this._ranged||!this._mounted)return this._childNodeArray;const t=this._firstNode,e=this._lastNode;if(null===t||null===e||null===t.parentNode)return this._childNodeArray;const n=[];for(let o=t;null!==o;o=o.nextSibling)if(n.push(o),o===e)return n;return this._childNodeArray}mountAfter(t){const e=t.parentNode;if(e){let n=t;for(const t of this._movableNodes()){if(n.nextSibling!==t){_o(t);const o=e;t.parentNode===e&&"function"==typeof o.moveBefore?o.moveBefore(t,n.nextSibling):e.insertBefore(t,n.nextSibling)}n=t}}this._mounted=!0}tryDestroy(){const t=Sr(this);if(null===t||!t.canWholesaleDestroy())return!1;t.destroyRow(us(this));const e=this._childNodeArray;for(let t=0;t<e.length;t++){const n=e[t];null!==n.parentNode&&(go(n),n.parentNode.removeChild(n))}const n=us(this);for(let t=0;t<n.length;t++){const e=n[t];Br.has(e.bindingType)&&jr(e.node).forEach(t=>{t.tryDestroy()||t.unmount()})}return this._mounted=!1,!0}unmountInPlace(){{const t=Sr(this);null!==t&&(t.isRowSession?t.disposeBindings(us(this)):t.dispose())}this._teardownBindings()}_teardownBindings(){const t=us(this);for(let e=0;e<t.length;e++){const n=t[e];Br.has(n.bindingType)&&jr(n.node).forEach(t=>{t.unmount()}),bn(n),rn(n)}}unmount(){{const t=Sr(this);null!==t&&(t.isRowSession?t.disposeBindings(us(this)):t.dispose())}for(const t of this._childNodeArray)null!==t.parentNode&&(go(t),t.parentNode.removeChild(t));const t=us(this);for(let e=0;e<t.length;e++){const n=t[e];Br.has(n.bindingType)&&jr(n.node).forEach(t=>{t.unmount()}),bn(n),rn(n)}this._mounted=!1}}function Hr(t){const e=document.createDocumentFragment(),n=new Fr(e);return n._childNodeArray=t,n._firstNode=t.length>0?t[0]:null,n._lastNode=t.length>0?t[t.length-1]:null,n._mounted=!0,n}function qr(t){void 0!==t.uuid&&null!==t.uuid||Z("BindingInfo.uuid is null.");const n=aa(t.uuid);n||Z(`Fragment with UUID "${t.uuid}" not found.`);const s=!e()&&function(t){let e=t.topLevelStructural;return void 0===e&&(e=t.topLevelStructural=function(t){const e=new RegExp(`^@@(?:${o.commentForPrefix}|${o.commentIfPrefix}|${o.commentElseIfPrefix}|${o.commentElsePrefix}):`);for(let n=t.firstChild;null!==n;n=n.nextSibling)if(n.nodeType===Node.COMMENT_NODE&&e.test(n.data))return!0;return!1}(t.fragment)),e}(n);let r=n.rowPlan;if((void 0===r||null!==r&&r.directional!==o.enableDirectionalInitialSync)&&(r=n.rowPlan=function(t){const e=o.enableDirectionalInitialSync,n=[],s=t.nodeInfos;for(let e=0;e<s.length;e++){const o=s[e],r=te(t.fragment,o.nodePath);if(null===r)return null;for(const t of o.parseBindTextResults){const o=t.bindingType;if("text"!==o&&"prop"!==o&&"event"!==o)return null;const s=t.propSegments[0];if(s===S||s===_)return null;if("text"===o){if(r.nodeType!==Node.TEXT_NODE)return null}else if(null!==Ft(r))return null;if("prop"===o&&qn(r,t.propName))return null;const i=zr(t);let a;try{a=Oo({...i,node:r,replaceNode:r})}catch{return null}if(a.observable||"auto"===a.authority)return null;n.push({nodeIndex:e,template:i,isEvent:"event"===o,isIndexBinding:t.statePathName in I,policy:a,authority:a.authority})}}return{directional:e,slots:n}}(n)),null!==r)return function(t,e,n){const o=document.importNode(e.fragment,!0),s=e.nodeInfos,r=new Array(s.length);for(let t=0;t<s.length;t++){const e=te(o,s[t].nodePath);null===e&&Z(`Node not found by path [${s[t].nodePath.join(", ")}] in fragment.`),de(e),zt(e),r[t]=e}const i=n.slots,a=new Array(i.length),l=[];for(let t=0;t<i.length;t++){const e=i[t],n=r[e.nodeIndex],o={...e.template,node:n,replaceNode:n};a[t]=o,e.isIndexBinding&&l.push(o)}const c=function(t,e,n){let o=Hi.get(n);return void 0!==o&&o.currentRowPlan===t||(o=new ns,Hi.set(n,o)),o.initializeRow(t,e),o}(n,a,t.node),u=new Fr(o);return xr(u,c),ds(u,a),function(t,e){Ar.set(t,e)}(u,n),ps(u,l),kr(u,r),Rr(t.node,u),u}(t,n,r);const i=document.importNode(n.fragment,!0),a=function(t,e){const[n,o]=function(t,e){const n=[],o=[];for(const s of e){const e=te(t,s.nodePath);if(null===e&&Z(`Node not found by path [${s.nodePath.join(", ")}] in fragment.`),le.has(e))continue;const r=ce(e,s.parseBindTextResults,{allowDeferred:!1});o.push(...r.bindings),n.push(e)}return[n,o]}(t,e),s=new ns;return{nodes:n,bindingInfos:s.initialize(o,{registerAddress:!1,applyOnReconnect:!1},null),bindingSession:s}}(i,n.nodeInfos);s&&function(t,e){t.appendChild(document.createComment(`wcs-row-end:${e}`))}(i,t.uuid);const l=new Fr(i,s);xr(l,a.bindingSession),ds(l,a.bindingInfos);const c=[];for(const t of a.bindingInfos)t.statePathName in I&&c.push(t);return ps(l,c),kr(l,a.nodes),Rr(t.node,l),l}const Ur=new WeakSet,Gr=Symbol.for("wcstack.state.view-transition-naming");function Vr(){const t=Rs("state");return null===t||"auto"!==t.naming?null:{limit:t.namingLimit}}function Kr(t,e,n){const o=function(t){const e=t.firstNode;if(null===e)return null;const n=t.lastNode;for(let t=e;null!==t;t=t.nextSibling){if(t.nodeType===Node.ELEMENT_NODE)return t;if(t===n)break}return null}(t);if(null===o||Ur.has(o))return;const s=o.style;if(void 0===s)return;const r=function(){const t=globalThis;return t[Gr]??={counter:0,assigned:0,warned:!1}}();r.assigned>=n.limit?r.warned||(r.warned=!0,console.warn(`[@wcstack/state] auto view-transition-name limit (${n.limit}) reached; further elements are left unnamed. Raise naming-limit on <wcs-view-transition>, or switch to naming="manual" and name only what should morph.`)):(Ur.add(o),r.assigned+=1,r.counter+=1,s.setProperty("view-transition-name",`wcs-${e}-${r.counter}`),s.setProperty("view-transition-class",`wcs-${e}`))}const Jr=new WeakMap,Qr=new WeakMap,Xr=new WeakMap,Yr=new WeakMap;function Zr(t,e,n){!function(t,e,n){let o=Qr.get(t);if(void 0===o){if(null===n)return;o=new WeakMap,Qr.set(t,o)}null===n?o.delete(e):o.set(e,n)}(t,e,n)}function ti(t,e){Jr.set(t,e)}function ei(t){return t.nodeType===Node.ELEMENT_NODE||(t.nodeType===Node.TEXT_NODE?""!==(t.textContent?.trim()??""):t.nodeType===Node.COMMENT_NODE&&t.data.startsWith("@@wcs-"))}function ni(t,e){if(null===e)return!1;if(t.nextSibling===e)return!0;const n=t.compareDocumentPosition(e);return 0!==(n&Node.DOCUMENT_POSITION_FOLLOWING)&&0===(n&Node.DOCUMENT_POSITION_DISCONNECTED)}const oi=new Set(["if","elseif","else","for"]);function si(t,e){for(const n of us(t))if(e.appliedBindingSet.delete(n),oi.has(n.bindingType))for(const t of jr(n.node))si(t,e)}function ri(t){for(const e of us(t)){if(!oi.has(e.bindingType))continue;const t="for"===e.bindingType;for(const n of jr(e.node))ri(n),t&&n.mounted&&(Mr(n),n.unmount(),Wr(e.node,n))}}function ii(t){return`${t.bindingType} ${t.statePathName} ${t.outFilters.map(t=>t.filterName).join("|")} ${t.node.isConnected?"(connected)":"(disconnected)"}`}function ai(t,n,s){const r=Boolean(s);let i;const a=jr(t.node);i=0===a.size?qr(t):a.values().next().value;const l=e(),c=t.uuid??"",u=t.bindingType;if(r||(o.debug&&console.log(`unmount if content : ${ii(t)}`),Mr(i),i.unmount()),r){if(o.debug&&console.log(`mount if content : ${ii(t)}`),l){const e=document.createComment(`@@wcs-${u}-start:${c}:${t.statePathName}`);t.node.parentNode.insertBefore(e,t.node.nextSibling),i.mountAfter(e);const n=document.createComment(`@@wcs-${u}-end:${c}:${t.statePathName}`),o=i.lastNode??e;o.parentNode.insertBefore(n,o.nextSibling)}else i.mountAfter(t.node);Tr(i,me(t.node),n);const e=Vr();null!==e&&Kr(i,"branch",e)}}const li=new WeakMap;function ci(t){return li.get(t)??[]}const ui=new Set,di=Symbol.for("wcstack.trustedTypes.policy");function hi(){const t=globalThis[di];return null===t||"object"!=typeof t?null:t}let fi,pi=!1;const mi={value(t,e){"TEXTAREA"===t.tagName?t.textContent=String(e??""):t.setAttribute("value",String(e??""))},checked(t,e){e?t.setAttribute("checked",""):t.removeAttribute("checked")},selected(t,e){e?t.setAttribute("selected",""):t.removeAttribute("selected")},disabled(t,e){e?t.setAttribute("disabled",""):t.removeAttribute("disabled")},selectedIndex(t,e){const n=t.querySelectorAll("option"),o=Number(e);for(let t=0;t<n.length;t++)t===o?n[t].setAttribute("selected",""):n[t].removeAttribute("selected")}},gi=new Set(["textContent","innerText","innerHTML"]);function yi(t,n,s){if(void 0===s&&1===t.propSegments.length&&gi.has(t.propSegments[0])&&(s=""),void 0===s)return void(o.debug&&console.debug("Skipped property write: state value is undefined.",{element:t.node,propSegments:t.propSegments,statePathName:t.statePathName}));const r=t.node,i=t.propSegments;if(1===i.length){const c=i[0],u=r[c];if(u!==s){null!==rs&&null!==u&&"object"==typeof u&&null!==s&&"object"==typeof s&&null!==Ft(r)&&rs.rememberOverwrittenObject(r,c,u);const e="innerHTML"===(l=c)||"outerHTML"===l||"srcdoc"===l,i=()=>{let t=!1;try{r[c]=e?function(t){if("string"!=typeof t)return t;const e=hi(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(s):s,t=!0}catch(t){e&&function(t,e){if(pi)return;if(!function(){if(void 0!==fi)return fi;if(!("trustedTypes"in globalThis))return fi=!1,fi;try{document.createElement("div").innerHTML="<i></i>",fi=!1}catch{fi=!0}return fi}())return;pi=!0;const n="function"==typeof hi()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/state deliberately does not pass state values through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/state] Writing to "${e}" was blocked by Trusted Types (require-trusted-types-for 'script'). ${n}\nInstall a sanitizing policy before the first binding is applied:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr bind the value as text instead of HTML. See docs/csp.md section 7.`,{element:t,property:e})}(r,c),o.debug&&console.warn(`Failed to set property '${c}' on element.`,{element:r,newValue:s,error:t})}if(t){const t=function(t,e){const n=Ft(t);if(null===n)return null;const o=qt(t)?.get(n);if(void 0===o)return null;const s=Gt(t)?.declaredInputs.get(e);return"string"==typeof s?.attribute&&s.attribute.length>0?s.attribute:null}(r,c);if(null!==t)try{!function(t,e,n){if(null==n)return void t.removeAttribute(e);let o;if("object"==typeof n)try{o=JSON.stringify(n)}catch{o=String(n)}else o=String(n);t.setAttribute(e,o)}(r,t,s)}catch(e){o.debug&&console.warn(`Failed to mirror attribute '${t}' on element.`,{element:r,newValue:s,error:e})}}};if(o.enablePropagationContext&&qn(r,c)){const e=Jn(r,c,t.statePathName),o=Qn(e,"to-element"),a=n?.propagationContextByBinding?.get(t)??eo()??Yn(e);if(a.visitedEdges.has(o))null!==ye&&ye({type:"propagation:suppressed",reason:"visited-edge",transactionId:a.transactionId,edgeId:o,node:r,member:c});else{const t=Zn(a,o);no(t,()=>function(t,e,n,o,s,r){const i={bindingId:o,bindingGeneration:0,member:e,transactionId:s,synchronousScopeId:Vn++,writtenValue:n};oo.push({receipt:i,node:t});try{return r()}finally{oo.pop()}}(r,c,s,e,t.transactionId,i))}}else i()}if(e()){const t=mi[c];t?t(r,s):(function(t,e,n){let o=li.get(t);o||(o=[],li.set(t,o));const s=o.find(t=>t.propName===e);s?s.value=n:o.push({propName:e,value:n})}(r,c,s),a=r,ui.add(a))}return}var a,l;const c=i[0];let u=r[c];for(let t=1;t<i.length-1;t++){const e=i[t];if(null==u)return;u=u[e]}const d=i[i.length-1],h=u[d];if(h!==s){if(Object.isFrozen(u))return void(o.debug&&console.warn("Attempting to set property on frozen object.",{element:r,propSegments:i,oldValue:h,newValue:s}));null!==rs&&2===i.length&&"object"==typeof u&&null!==u&&null!==Ft(r)&&(d in u?rs.rememberOverwrittenValue(r,c,d,u[d]):rs.recordInjectedKey(r,c,d));try{u[d]=s}catch(t){o.debug&&console.warn("Failed to set property on sub-object.",{element:r,propSegments:i,oldValue:h,newValue:s,error:t})}}}const bi=new WeakSet;function wi(t,e,n){}function vi(t,e){let n=t;for(;null!==n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return t;n=Object.getPrototypeOf(n)}}function _i(t,e,n){const o=function(t){const e=[];let n=t;for(;null!==n&&n!==Object.prototype;){for(const t of Object.getOwnPropertyNames(n))e.push(t);n=Object.getPrototypeOf(n)}return e}(t),s=e.length>0?e+a:"";for(const t of n){if(s.length>0&&!t.startsWith(s))continue;const e=t.slice(s.length);e.length>0&&-1===e.indexOf(a)&&o.push(e)}return o}const $i={binding:"wcs/binding-path-missing",watch:"wcs/watch-path-missing",scan:"wcs/scan-path-missing"},Si={binding:"Bound path",watch:"$watch path",scan:"$scan path"};function xi(t,e,n,o){return`[wcs/index-arity] ${t}("${e}") requires ${"$resolve"===t?`exactly ${n}`:`at most ${n}`} index(es) ("*" appears ${n} time(s) in the path) but got ${o}.${it}`}function Pi(t,e){return`[wcs/recursion-anchor] "${t}" does not match the declared recursion anchor "${e}". This version supports exactly one anchor per state, and "**" must be followed by a well-formed suffix (no second "**", no empty segment, no bare "*" right after "**").`}function Ni(t,e){return`$setAll("${t}") ${e}`}function ki(t,e,n){return`[wcs/wildcard-rank] ${t} needs ${e} enclosing loop level(s) but the current scope provides ${n}. Wrap it in that many "for" templates, or use $resolve(path, indexes) to name the row explicitly.${it}`}const Ii=new WeakSet;function Ai(t,e){console.error(`[@wcstack/state] deferred apply failed for <${t}>.`,e)}const Ei=Object.freeze({[x]:function(t,e,n){const o=t.node,s=t.propSegments[1];"boolean"!=typeof n&&Z("Invalid value for class application: expected boolean, got "+typeof n),o.classList.toggle(s,n)},[P]:function(t,e,n){const o=t.node,s=t.propSegments[1];null!=n?o.getAttribute(s)!==n&&o.setAttribute(s,n):o.hasAttribute(s)&&o.removeAttribute(s)},[N]:function(t,e,n){const o=t.propSegments[1],s=t.node.style;null==n&&(n=""),s[o]!==n&&(s[o]=n)},[S]:function(t,e,n){Tn(n)||Z("command binding requires a CommandToken value (use $command.<tokenName> with a name declared in $commandTokens).");const o=n,s=ls.get(t);if(s&&s.token===o)return;const r=t.node,i=t.propSegments[1];"string"==typeof i&&0!==i.length||Z('command binding requires a method name (e.g., "command.fetch").');const a=function(t){const e=Ft(t);if(null===e)return null;const n=qt(t)?.get(e);return void 0===n&&Z(`Custom element <${e}> is not defined for command binding.`),Gt(t)}(r);null===a&&Z(`command binding requires a wc-bindable custom element. <${r.tagName.toLowerCase()}> is not wc-bindable.`),a.declaredCommands.has(i)||Z(`Command "${i}" is not declared in wcBindable.commands of <${r.tagName.toLowerCase()}>.${rt(i,a.declaredCommands.keys())}`),s&&(s.unsubscribe(),ls.delete(t));const l=new WeakRef(r);let c=null;c=o.subscribe((...e)=>{const n=l.deref();if(!n||!n.isConnected)return c?.(),void ls.delete(t);const o=n[i];return"function"!=typeof o&&Z(`Method "${i}" is not a function on <${n.tagName.toLowerCase()}>.`),Reflect.apply(o,n,e)}),ls.set(t,{token:o,unsubscribe:c,elementRef:l})}}),Ci={text:function(t,n,o){const s=null==o?"":String(o);if(t.replaceNode.nodeValue!==s&&(t.replaceNode.nodeValue=s),e()&&!bi.has(t.replaceNode)){bi.add(t.replaceNode);const e=t.replaceNode.parentNode;if(e){const n=t.statePathName,o=document.createComment(`@@wcs-text-start:${n}`),s=document.createComment(`@@wcs-text-end:${n}`);e.insertBefore(o,t.replaceNode),e.insertBefore(s,t.replaceNode.nextSibling)}}},for:function(t,n,o){const s=t.statePathInfo,r=en(t),i=sn(t),a=we(i),c=a.length>0&&!Qr.has(t.node)?[]:a,u=vr(r,c,o);n.newListValueByAbsAddress.set(i,Array.isArray(o)?o:[]);let d=Qr.get(t.node);const h=void 0!==d?function(t,e,n){if(o=e,!_r.has(o))return null;var o;let s=null;for(let e=0;e<n.newIndexes.length;e++){const o=n.newIndexes[e],r=n.oldIndexes[e],i=n.addIndexSet.has(o)&&n.deleteIndexSet.has(r)?t.get(r):void 0;void 0!==i&&(s??={byAddedIndex:new Map,reused:new Set},s.byAddedIndex.set(o,i),s.reused.add(i))}return s}(d,c,u):null,f=Array.isArray(c)&&c.length===u.deleteIndexSet.size&&u.deleteIndexSet.size>0;if(f&&null===h&&null!==t.node.parentNode){let e=Yr.get(t.node);if(void 0===e){const n=Jr.get(t.node)||t.node;e=function(t,e){let n=t.previousSibling,o=e.nextSibling,s=!0;for(;null!==n;){if(ei(n)){s=!1;break}n=n.previousSibling}for(;null!==o;){if(ei(o)){s=!1;break}o=o.nextSibling}return s}(t.node,n),Yr.set(t.node,e)}if(e){const e=t.node.parentNode;!function(t,e){bo.set(t,(bo.get(t)??0)+e)}(e,e.childNodes.length),e.textContent="",e.appendChild(t.node)}}let p=f?1e3-function(t){return Xr.get(t.node)||[]}(t).length:Number.POSITIVE_INFINITY;if(void 0!==d){const e=d;u.deleteIndexSet.forEach(n=>{const o=e.get(n);void 0!==o&&(null!==h&&h.reused.has(o)?(Mr(o),ri(o),o.unmountInPlace()):p<=0&&o.tryDestroy()?Wr(t.node,o):(Mr(o),o.unmount(),function(t,e){let n=Xr.get(t.node);void 0===n&&(n=[],Xr.set(t.node,n)),n.length<1e3?n.push(e):Wr(t.node,e)}(t,o),p-=1),f||e.delete(n))}),f&&(Qr.delete(t.node),d=void 0)}let m=t.node;const g=nt(s.path+"."+l),y=n.stateElement.loopContextStack,b=function(t){if(0===t.changeIndexSet.size||t.addIndexSet.size===t.newIndexes.length)return null;const e=new Map;for(let n=0;n<t.oldIndexes.length;n++)e.set(t.oldIndexes[n],n);const n=[],o=[];let s=-1,r=!0;for(const i of t.newIndexes){if(t.addIndexSet.has(i))continue;const a=e.get(i);if(void 0===a)return null;a<s&&(r=!1),s=a,n.push(i),o.push(a)}if(r)return null;const i=function(t){const e=t.length,n=[],o=new Array(e).fill(-1);for(let s=0;s<e;s++){const e=t[s];let r=0,i=n.length;for(;r<i;){const o=r+i>>1;t[n[o]]<e?r=o+1:i=o}r>0&&(o[s]=n[r-1]),n[r]=s}const s=[];let r=n.length>0?n[n.length-1]:-1;for(;r>=0;)s.push(r),r=o[r];return s.reverse(),s}(o),a=new Set;for(const t of i)a.add(n[t]);return a}(u);let w=null;u.newIndexes.length==u.addIndexSet.size&&u.newIndexes.length>0&&m.isConnected&&null===h&&(w=document.createDocumentFragment(),Ke(w,n.rootNode));const v=e(),_=Vr(),$=t.uuid??"",S=Xr.get(t.node);for(const e of u.newIndexes){let o;if(u.addIndexSet.has(e)){const r=mn(g,e);if(y.createLoopContext(r,r=>{if(o=h?.byAddedIndex.get(e)??(void 0!==S?S.pop():void 0),void 0===o?o=qr(t):si(o,n),null!==w)v&&w.appendChild(document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`)),o.appendTo(w),v&&w.appendChild(document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`));else{if(m.nextSibling!==o.firstNode){if(v){const t=document.createComment(`@@wcs-for-start:${$}:${s.path}:${e.index}`);m.parentNode.insertBefore(t,m.nextSibling),m=t}o.mountAfter(m)}if(v){const t=document.createComment(`@@wcs-for-end:${$}:${s.path}:${e.index}`),n=o.lastNode??m;n.parentNode.insertBefore(t,n.nextSibling)}}Tr(o,r,n),null!==_&&Kr(o,"row",_)}),void 0===o&&Z(`Content not found for ListIndex: ${e.index} at path "${s.path}"`),null!==h&&h.reused.has(o)){const t=n.stateElement.addressHooks;if(t){const e=t.rowReused;for(let t=0;t<e.length;t++)e[t](n.stateElement,o)}}}else{if(o=void 0!==d?d.get(e)??null:null,u.changeIndexSet.has(e)){const t=fs(o);for(const e of t)Di(e,n)}null===o&&Z(`Content not found for ListIndex: ${e.index} at path "${s.path}"`);const t=!o.mounted;if(null!==b&&b.has(e)&&ni(m,o.firstNode)||m.nextSibling===o.firstNode||o.mountAfter(m),t){const t=o,s=mn(g,e);y.createLoopContext(s,e=>{Tr(t,e,n)})}}m=o.lastNode||m,void 0===d&&(d=new WeakMap,Qr.set(t.node,d)),d.set(e,o)}Jr.set(t.node,m),null!==w&&(t.node.parentNode.insertBefore(w,t.node.nextSibling),Ke(w,null))},if:ai,else:ai,elseif:ai,radio:function(t,e,n){const o=t.node,s=is(o.value,t.inFilters);o.checked=n===s},checkbox:function(t,e,n){const o=t.node,s=is(o.value,t.inFilters),r=Array.isArray(n)?n:as;o.checked=r.includes(s)}},Ti=new WeakMap,Mi=new WeakMap,Oi=new WeakMap;function Li(){}function Ri(t){const e=rs;if(null!==e){const n=t.replaceNode,o=t.propSegments[0];if(e.isComplete(n,o))return wi;if(e.isDeclared(n,o))return Li}return yi}function ji(t,e){Wi(t,e,function(t,e){const n=yn(e);if(n.pathInfo.path in I){const t=me(e.node);return null===t&&Z(`ListIndex not found for binding: ${e.statePathName}`),function(t,e){null===t.listIndex&&Z("ListIndex not found for loopContext:");const n=I[e];void 0===n&&Z(`Invalid index name: ${e}`);const o=Ye(t.listIndex,n,t.pathInfo.wildcardCount);return null===o&&Z(ki(`"${e}"`,n+1,t.pathInfo.wildcardCount)),o.index}(t,n.pathInfo.path)}return t[Ce](n)}(e.state,t))}function Wi(t,e,n){const o=is(n,t.outFilters);if(!0===Mi.get(t))return void e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement});let s=Ti.get(t);if(void 0===s){if(Ti.has(t))return s=Ri(t),s===wi&&Ti.set(t,s),void s(t,e,o);if(s=Ci[t.bindingType],void 0===s){const e=t.propSegments[0];s=Ei[e],Ti.set(t,s),void 0===s&&(Ft(t.replaceNode)?(s=Ri(t),s===wi&&Ti.set(t,s)):(s=yi,Ti.set(t,s)))}if(s===yi&&"SELECT"===t.node.tagName){const n=t.propSegments[0];if("value"===n||"selectedIndex"===n)return e.deferredSelectBindings.push({binding:t,value:o,stateElement:e.stateElement}),void Mi.set(t,!0)}s(t,e,o)}else s(t,e,o)}function Di(t,e){if(e.appliedBindingSet.has(t))return;if(e.appliedBindingSet.add(t),!1!==e.stateElement.hasUpdatedCallback){const n=sn(t);e.updatedAbsAddressSetByStateElement.has(e.stateElement)?e.updatedAbsAddressSetByStateElement.get(e.stateElement).add(n):e.updatedAbsAddressSetByStateElement.set(e.stateElement,new Set([n]))}const n=ss(t);if(null!==n&&!n.shouldApplyState(t))return;if("event"===t.bindingType)return;if(!0!==Oi.get(t)){const e=Ft(t.replaceNode);if(e&&void 0===qt(t.replaceNode)?.get(e))return void function(t,e){if(Ii.has(t))return;Ii.add(t);const n=()=>{Ii.delete(t);const e=ss(t);(null===e||e.shouldApplyState(t))&&Bi([t])},o=n=>{Ii.delete(t),Ai(e,n)},s=ss(t);if(null!==s){const r=s.deferUntilDefined(t.replaceNode,e,n,o);return void(s.addTeardown(t,()=>{Ii.delete(t),r()})||(Ii.delete(t),r()))}const r=qt(t.replaceNode);if(null===r)return Ii.delete(t),void Ai(e,new Error("CustomElementRegistry is unavailable."));Io(r).wait(e,()=>{t.replaceNode.isConnected?n():Ii.delete(t)},o)}(t,e);Oi.set(t,!0)}if(!0===e.sameRootVerified)return void ji(t,e);let o=t.replaceNode.getRootNode();if(o instanceof DocumentFragment&&!(o instanceof ShadowRoot)&&(o=Je(o),null===o&&Z("Root node for fragment not found for binding.")),o!==e.rootNode){const n=ta(o);null===n&&Z("No state tree found on this root for binding."),n.createState("readonly",s=>{const r={rootNode:o,stateElement:n,state:s,appliedBindingSet:e.appliedBindingSet,newListValueByAbsAddress:e.newListValueByAbsAddress,updatedAbsAddressSetByStateElement:e.updatedAbsAddressSetByStateElement,deferredSelectBindings:e.deferredSelectBindings};ji(t,r)})}else ji(t,e)}function zi(t,e,n,o){if(null!==n&&!0===n.hasErrorCallback){const s={path:t.statePathName,bindingType:t.bindingType,node:t.node},r=o.get(n);void 0===r?o.set(n,[{error:e,info:s}]):r.push({error:e,info:s})}else console.error(`[@wcstack/state] binding "${t.bindingType}: ${t.statePathName}" failed to apply; the rest of this batch continues.`,{node:t.node,error:e});null!==ye&&ye({type:"state:binding-apply-error",path:t.statePathName,bindingType:t.bindingType,error:e})}function Bi(t,e,n){let s=0;const r=new Set,i=new Map,a=new Map,l=[],c=new Map;for(;s<t.length;){let n=t[s];if(!1===n.replaceNode.isConnected){o.debug&&console.log(`applyChangeFromBindings: skip disconnected binding: ${n.bindingType} ${n.statePathName} on ${n.node.nodeName}`,n),s++;continue}let u=n.replaceNode.getRootNode();u instanceof DocumentFragment&&!(u instanceof ShadowRoot)&&(u=Je(u),null===u&&Z("Root node for fragment not found for binding."));const d=ta(u);null===d&&Z("No state tree found on this root for binding."),d.createState("readonly",o=>{const h={rootNode:u,stateElement:d,state:o,appliedBindingSet:r,newListValueByAbsAddress:i,updatedAbsAddressSetByStateElement:a,deferredSelectBindings:l,sameRootVerified:!0,propagationContextByBinding:e};for(;;){try{Di(n,h)}catch(t){zi(n,t,d,c)}s++;const e=t[s];if(!e)break;if(e.replaceNode.getRootNode()!==h.rootNode)break;n=e}})}for(const{binding:t,value:n,stateElement:o}of l)try{yi(t,{propagationContextByBinding:e},n)}catch(e){zi(t,e,o??null,c)}for(const[t,e]of i.entries())ve(t,e),Ne(t,e);if(!1!==n?.updatedCallback)for(const[t,e]of a.entries())t.createState("writable",t=>{t[Re](Array.from(e))});for(const[t,e]of c.entries())t.createState("writable",t=>{for(const{error:n,info:o}of e)try{t[je](n,o)}catch(t){console.error(`[@wcstack/state] $errorCallback threw while handling the failure of binding "${o.bindingType}: ${o.path}".`,{error:t,original:n,node:o.node})}})}function Fi(t,e,n){const[o,s,r]=ue(t,n),i=os(t);for(const t of o)ge(t,e);Bi(i.initialize(s)),function(t,e,n){for(const o of t)n.deferUntilDefined(o.node,o.tagName,()=>{const t=he(o);0!==t.length&&(ge(o.node,e),Bi(n.initialize(t)))},t=>{console.error(`[@wcstack/state] deferred spread failed for <${o.tagName}>.`,t)})}(r,e,i)}const Hi=new WeakMap;async function qi(t){const e=t.querySelectorAll(o.tagNames.state),n=[],s=qt(t);null===s&&Z(`CustomElementRegistry is unavailable for <${o.tagNames.state}>.`),await s.whenDefined(o.tagNames.state);for(const t of e){if(se(t))continue;const e=t;n.push(e.initializePromise)}await Promise.all(n)}async function Ui(t){if(t===document)await qi(document),X(document),xa(document,document),Fi(document.body,null);else{const e=t;e.host.hasAttribute(o.bindAttributeName)&&await Dt(e.host),await qi(e),X(e),xa(e,e),Fi(e,null)}}const Gi={watch:"temporal",scan:"temporal",stream:"temporal",scopes:"scopes",dcc:"scopes",bindComponent:"scopes",recursion:"recursion",ssr:"ssr",devtools:"devtools"};function Vi(t,e){return`[wcs/feature-not-installed] ${e} needs the "${t}" feature: install it with installFeatures([...]) from "@wcstack/state/features/${Gi[t]??t}" before the state is defined.`}let Ki=null;function Ji(t){return null===Ki&&Z(Vi("ssr",t)),Ki}const Qi=new WeakMap,Xi=new WeakMap,Yi=new Set,Zi=[];function ta(t){return Qi.get(t)??null}function ea(t){return Xi.get(t)??Promise.resolve()}const na=new WeakSet;function oa(t){na.add(t)}function sa(t,n){const s=Qi.get(t);if(null===n){if(void 0===s)return;Qi.delete(t),Yi.delete(s),null!==ye&&ye({type:"state:element-unregistered",rootNode:t,element:s}),o.debug&&console.debug("State element unregistered")}else{if(s===n)return;if(void 0===s){const o=!e()&&n.hasAttribute?.("enable-ssr");if("HTMLDocument"===t.constructor.name||"Document"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{o&&await Ji('the "enable-ssr" attribute').hydrate(t)||await Ui(t),oa(t),Ea(),e()}catch(t){n(t)}})});Xi.set(t,e)}else if("ShadowRoot"===t.constructor.name){const e=new Promise((e,n)=>{queueMicrotask(async()=>{try{await Ui(t),oa(t),Ea(),e()}catch(t){n(t)}})});Xi.set(t,e)}}void 0!==s&&Z('A state tree is already registered on this root — one <wcs-state> per root in v2. This second element stays unregistered: it keeps the state it loaded and its declarations stay live, but nothing binds to it and disconnecting it runs no cleanup — remove it. Mount additional states onto the tree instead: <wcs-state mount="...">.'),Qi.set(t,n),Yi.add(n);for(let e=0;e<Zi.length;e++)Zi[e](t,n);null!==ye&&ye({type:"state:element-registered",rootNode:t,element:n}),o.debug&&console.debug("State element registered",n)}}const ra=new Map;function ia(t,e,n){if(null===n)ra.delete(t);else{ra.set(t,n);const o=ta(e);null===o&&Z("No state tree found on this root for fragment info.");const s=n.parseBindTextResult;o.setPathInfo(s.statePathName,s.bindingType);for(const t of n.nodeInfos)for(const e of t.parseBindTextResults)o.setPathInfo(e.statePathName,e.bindingType)}}function aa(t){return ra.get(t)||null}function la(t){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=Et(e.getAttribute(o.bindAttributeName)||"");return e.localName===o.tagNames.state&&e.hasAttribute("mount")?n.filter(t=>t.propSegments[0]!==$):n}if(t.nodeType===Node.COMMENT_NODE){const e=Ot(t);null===e&&Z("Comment node binding text not found.");const n=aa(e);let o=n?.parseBindTextResult??null,s=null;return null===o?(o=Lt(e),s=null):s=e,[{...o,uuid:s}]}return[]}let ca;function ua(){return ca??={filterName:"not",args:[]}}const da=/^(\s*@@\s*(?:.*?)\s*:\s*)(.+?)(\s*)$/;function ha(t,e){const n=e+a+l,o=t.indexOf("|");let s,r;if(-1!==o?(s=t.slice(0,o).trim(),r=t.slice(o)):(s=t.trim(),r=""),"."===s)s=n;else{if(!s.startsWith("."))return t;s=n+a+s.slice(1)}return r.length>0?s+r:s}function fa(t,e){const n=da.exec(t);if(null===n)return t;const o=n[1],s=n[2],r=n[3];return o+ha(s,e)+r}function pa(t,e){const n=t.split(";");let o=!1;const s=n.map(t=>{const n=t.trim();if(0===n.length)return t;const s=n.indexOf(":");if(-1===s)return t;const r=n.slice(0,s).trim(),i=n.slice(s+1).trim(),a=ha(i,e);return a!==i?(o=!0,`${r}: ${a}`):t});return o?s.join(";"):t}function ma(t,e){return pa(t,e)}function ga(t,e){const n=o.bindAttributeName,s=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);for(;s.nextNode();){const t=s.currentNode;if(t.nodeType===Node.COMMENT_NODE){const n=t;n.data=fa(n.data,e);continue}const o=t;if(o instanceof HTMLTemplateElement)continue;const r=o.getAttribute(n);if(null!==r){const t=pa(r,e);t!==r&&o.setAttribute(n,t)}}}function ya(t){let e=t;const n=[];for(;null!==e.parentNode;){const t=Array.from(e.parentNode.childNodes).indexOf(e);n.unshift(t),e=e.parentNode}return n}function ba(t){const e=[],n=ae(t);for(const t of n){const n=la(t);let o=t;if(t.nodeType===Node.COMMENT_NODE&&1===n.length&&"text"===n[0].bindingType&&null!==t.parentNode){const e=document.createTextNode("");t.parentNode.replaceChild(e,t),o=e}e.push({nodePath:ya(o),parseBindTextResults:n})}return e}function wa(t){const e=Array.from(t.childNodes);for(const n of e)n.nodeType===Node.TEXT_NODE&&""===(n.textContent||"").trim()&&t.removeChild(n)}const va=new Map([["for",o.commentForPrefix],["if",o.commentIfPrefix],["elseif",o.commentElseIfPrefix],["else",o.commentElsePrefix]]),_a=ua();function $a(t,e){const n=e.outFilters;return{...e,outFilters:[...n,_a],bindingType:t}}function Sa(t,e,n,o,s,r=!0){wa(e),"string"==typeof o&&ga(e,o),xa(t,e,o,s);const i={fragment:e,parseBindTextResult:void 0!==s&&r?s(n,o):n,nodeInfos:ba(e)};return void 0!==s&&function(t,e,n){for(const o of t)for(let t=0;t<o.parseBindTextResults.length;t++){const s=o.parseBindTextResults[t];null==s.uuid&&(o.parseBindTextResults[t]=e(s,n))}}(i.nodeInfos,s,o),i}function xa(t,e,n,s){const r=o.commentElsePrefix,i=re(e),a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode(t){const e=t;return i.length>0&&-1!==i.indexOf(e)?NodeFilter.FILTER_REJECT:"template"===e.tagName.toLowerCase()&&(e.getAttribute(o.bindAttributeName)||"").length>0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let l=null;const c=[],u=[];for(;a.nextNode();){const t=a.currentNode;u.push(t)}for(const e of u){let i=e.getAttribute(o.bindAttributeName)||"";"string"==typeof n&&(i=ma(i,n));let a=Et(i)[0];const u=va.get(a.bindingType);if(void 0===u)continue;const d=a.bindingType,h=e.content,f=gs();let p=null;const m="for"===d?a.statePathName:n;if("else"===d){null===l&&Z("'else' binding found without preceding 'if' or 'elseif' binding."),a=$a("else",l.parseBindTextResult),p=Sa(t,h,a,m,s,!1),ia(f,t,p);const n=c.at(-1),o=document.createComment(`@@${u}:${f}`);void 0!==n?(e.remove(),n.fragment.appendChild(o),n.nodeInfos.push({nodePath:ya(o),parseBindTextResults:la(o)})):e.replaceWith(o)}else if("elseif"===d){null===l&&Z("'elseif' binding found without preceding 'if' or 'elseif' binding."),p=Sa(t,h,a,m,s),ia(f,t,p);const n=document.createComment(`@@${u}:${f}`),o=gs(),i={fragment:document.createDocumentFragment(),parseBindTextResult:$a("else",l.parseBindTextResult),nodeInfos:[]};i.fragment.appendChild(n),i.nodeInfos.push({nodePath:ya(n),parseBindTextResults:la(n)}),ia(o,t,i);const d=c.at(-1);c.push(i);const g=document.createComment(`@@${r}:${o}`);void 0!==d?(e.remove(),d.fragment.appendChild(g),d.nodeInfos.push({nodePath:ya(g),parseBindTextResults:la(g)})):e.replaceWith(g)}else{p=Sa(t,h,a,m,s),ia(f,t,p);const n=document.createComment(`@@${u}:${f}`);e.replaceWith(n)}"if"===d?(c.length=0,l=p):"elseif"===d?l=p:"else"===d&&(l=null,c.length=0)}}const Pa=()=>`[${o.bindAttributeName}]`;function Na(t){if(qo(t))return!0;if(!ka(t))return!1;if(t.hasAttribute(o.bindAttributeName))return!1;const e=t.querySelector(Pa());return null!==e&&qo(e)}function ka(t){return 1===t.nodeType}function Ia(t){if(Na(t))return;X(t),xa(t.getRootNode(),t);const e=t.hasAttribute(o.bindAttributeName),n=t.parentNode,s=null!==n&&(1===n.nodeType||9===n.nodeType||11===n.nodeType);Fi(e&&s?n:t,null)}const Aa=[];function Ea(){const t=Aa.splice(0,Aa.length);for(const e of t)Ia(e);!function(){const t=function(){const t=globalThis[s];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}();if(null===t)return;const e=function(){const t=globalThis;let e=t[r];return void 0===e&&(e=[],t[r]=e),e}();if(0===e.length)return;const n=e.splice(0,e.length),o=function(){const t=globalThis;let e=t[i];return void 0===e&&(e=new WeakSet,t[i]=e),e}();for(const e of n)o.add(e),t.bind(e)}()}const Ca={protocol:"wcs-binder",version:1,bind:function(t){var e;ka(t)&&!Na(t)&&(e=t.getRootNode(),na.has(e)?Ia(t):Aa.push(t))}},Ta="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";let Ma=0;async function Oa(t,e){let n=null;const o=`\n//# sourceURL=${e}#${++Ma}\n`;let s=!1;const r=t=>{t.effectiveDirective.startsWith("script-src")&&(s=!0)};document.addEventListener("securitypolicyviolation",r);try{if("function"==typeof URL.createObjectURL){const e=new Blob([t.text+o],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}finally{URL.revokeObjectURL(s)}}else{const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(t.text+o)));n=await(import(`data:application/javascript;base64,${e}`))}}catch(t){throw new Error(function(t,e,n){const o=e?.message??String(e);return n?`The inline <script> of state "${t}" was blocked by Content-Security-Policy. Inline state is evaluated through a blob: URL, so script-src must allow blob:. Prefer moving the state into an external file and loading it with src="./state.js", which requires no extra CSP directive. See ${Ta}`:`Failed to evaluate the inline <script> of state "${t}": ${o}. If this page sets a Content-Security-Policy, see ${Ta}`}(e,t,s),{cause:t})}finally{document.removeEventListener("securitypolicyviolation",r)}return n&&"object"==typeof n.default?n.default:{}}async function La(t){try{const e=await(import(function(t){return new URL(t,document.baseURI).href}(t)));return e.default||{}}catch(t){Z(`Failed to load script file: ${t}`)}}class Ra{_loopContextStack=Array(u).fill(void 0);_length=0;createLoopContext(t,e){null===t.listIndex&&Z("Cannot create loop context for a state address that does not have a list index.");const n=t;this._length>=u&&Z("Exceeded maximum loop context stack depth of 128. Possible infinite loop.");const o=this._loopContextStack[this._length-1];if(void 0!==o){o.pathInfo.wildcardCount+1!==n.pathInfo.wildcardCount&&Z("Cannot push loop context for a list whose wildcard count is not exactly one more than the current active loop context.");const t=n.pathInfo.wildcardPathInfos[n.pathInfo.wildcardPathInfos.length-2];o.pathInfo!==t&&Z("Cannot push loop context for a list whose parent wildcard path info does not match the current active loop context.")}else n.listIndex.length!==n.pathInfo.wildcardCount&&Z(`Cannot push loop context when there is no active loop context: the list index chain (length ${n.listIndex.length}) does not cover the wildcard path (wildcard count ${n.pathInfo.wildcardCount}).`);let s;this._loopContextStack[this._length]=n,this._length++;try{s=e(n)}finally{s instanceof Promise?s.finally(()=>{this._length--,this._loopContextStack[this._length]=void 0}):(this._length--,this._loopContextStack[this._length]=void 0)}return s}}const ja={$updatedCallback:C,$streams:z},Wa=new WeakSet;function Da(t,e){let n=t;for(;null!==n&&!Object.prototype.hasOwnProperty.call(n,e);)n=Object.getPrototypeOf(n);return n}function za(t){if(!Wa.has(t)){for(const e of Object.keys(ja)){if(!(e in t))continue;const n=ja[e];n in t&&Z(`[wcs/declaration-alias] The state declares both "${e}" and "${n}". "${e}" is the old name of "${n}" (it works through 3.x) — keep "${n}".`);const o=Da(t,e),s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,n,{...s,configurable:!0}),o===t&&delete t[e]}Wa.add(t)}}const Ba=new WeakMap;function Fa(t,e){let n=Ba.get(t);void 0===n&&(n=new Map,Ba.set(t,n));let o=n.get(e);return void 0===o&&(o=new Cn(e,t),n.set(e,o)),o}const Ha=new WeakMap;function qa(t){const e=Ha.get(t);if(void 0!==e)return e;const n=new Proxy(Object.create(null),{get(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return Fa(t,n)},has:(e,n)=>"string"==typeof n&&t.commandTokenNames.has(n),ownKeys:()=>Array.from(t.commandTokenNames),getOwnPropertyDescriptor(e,n){if("string"==typeof n&&t.commandTokenNames.has(n))return{configurable:!0,enumerable:!0,value:Fa(t,n)}},set(){Z("$command namespace is read-only; assigning to it is not allowed.")},deleteProperty(){Z("$command namespace is read-only; deleting from it is not allowed.")}});return Ha.set(t,n),n}const Ua=Symbol("wcs.notHandled"),Ga=["read","readMissing","write","writeMissing","writeObserve","written","swapped","get","indexShift","handlerScope","updated","suppressPathDiagnostic","rowReused"],Va=new Map;function Ka(t,e){Va.set(t,e)}const Ja=new Map;let Qa=[],Xa=[];function Ya(t,e){Ja.set(t,e),Qa=Array.from(Ja.values()).sort((t,e)=>t.order-e.order),Xa=Qa.slice().reverse()}function Za(t,e){for(let n=0;n<Qa.length;n++)Qa[n].activate?.(t,e)}function tl(t){"readonly"===t.mutability&&Z("This state is readonly.")}const el=new Map;class nl{path;segments;wildcardCount;wildcardType;wildcardIndexes;pathInfo;constructor(t){const e=t.split("."),n=e.slice();let o=0,s=0,r=0,i="none";const a=[];for(let t=0;t<e.length;t++){const i=e[t];if("*"===i)n[t]="*",a.push(null),o++,r++;else{const e=Number(i);Number.isNaN(e)||(n[t]="*",a.push(e),s++,r++)}}const l=nt(n.join("."));(o>0||s>0)&&(i=o===r?"context":s===r?"all":"partial"),this.path=t,this.segments=e,this.wildcardCount=r,this.wildcardType=i,this.wildcardIndexes=a,this.pathInfo=l}}function ol(t){let e;return el.get(t)??(el.set(t,e=new nl(t)),e)}function sl(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=n.pathInfo.indexByWildcardPath[e];return void 0===o||null===n.listIndex?null:Ye(n.listIndex,o,n.pathInfo.wildcardCount)}function rl(t,e){if(!t.untracking&&t.addressStackLength>0){const n=t.lastAddressStack,o=n?.pathInfo??null,s=t.stateElement;if(null!==o&&s.getterPaths.has(o.path)&&o.path!==e.pathInfo.path&&(s.addDynamicDependency(e.pathInfo.path,o.path),e.pathInfo.wildcardCount>0&&o.wildcardCount>0)){const t=Xe(e.pathInfo,o);if(t>0){let r=!1;const i=e.listIndex??null,a=n.listIndex??null;for(let n=0;n<t;n++)if((null!==i?Ye(i,n,e.pathInfo.wildcardCount):null)!==(null!==a?Ye(a,n,o.wildcardCount):null)){r=!0;break}if(r)for(let n=0;n<t;n++)s.addCrossRowListPath?.(e.pathInfo.wildcardParentPaths[n])}}}}function il(t,e){return(!0!==t.hasMounts||35!==e.pathInfo.lastSegment.charCodeAt(0))&&(e.pathInfo.wildcardCount>0||t.getterPaths.has(e.pathInfo.path))}function al(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.readMissing;for(let r=0;r<i.length;r++){const a=i[r](t,e,n,o,s);if(a!==Ua)return a}}return Ua}function ll(t,e,n,o,s){if(e.pathInfo.segments[0]===j)return function(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}(qa(s),e.pathInfo.segments);if(!(e.pathInfo.path in t)){if(null===e.parentAddress){const r=al(s,e,null,n,o);if(r!==Ua)return r;Z(function(t,e,n){return`[${$i.binding}] Path "${t}" does not exist on the state tree.${rt(t,_i(e,"",n))}${it}`}(e.pathInfo.path,t,s.getterPaths))}const r=cl(t,e.parentAddress,n,o);if(null==r)return;const i=e.pathInfo.segments[e.pathInfo.segments.length-1],a=s.addressHooks;if(a&&0!==a.readMissing.length&&i!==l&&!(i in Object(r))){const t=al(s,e,Object(r),n,o);if(t!==Ua)return t}if(i===l){const t=e.listIndex?.index??Z(ki(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.get(r,t)}return Reflect.get(r,i)}if(!s.getterPaths.has(e.pathInfo.path))return Reflect.get(t,e.pathInfo.path);o.pushAddress(e);try{return Reflect.get(t,e.pathInfo.path,n)}finally{o.popAddress()}}function cl(t,e,n,o){rl(o,e),!0===o.stateElement.hasRecursion&&o.stateElement.recursionRegistry.materializeForPathInfo(o.stateElement,e.pathInfo);const s=o.stateElement,r=s.addressHooks;if(r){const t=r.read;for(let r=0;r<t.length;r++){const i=t[r](s,e,n,o);if(i!==Ua)return i}}return il(s,e)?function(t,e,n,o,s){const r=Ue(s,e),i=function(t){return Ts.get(t)??null}(r),a=s.stateGeneration;if(null!==i&&!1===i.dirty&&i.generation===a)return i.value;const l=ll(t,e,n,o,s);return Ms(r,{value:l,dirty:!1,generation:a}),l}(t,e,n,o,s):ll(t,e,n,o,s)}function ul(t,e,n,o,s,r){const i=new Map,a=(o,s,r,l,c,u,d)=>{const h=o[s]??null;if(null===h)return void d.push(u);const f=mn(h,r),p=Ue(n.stateElement,f),m=Pe(p),g=cl(t,f,e,n),y=vr(r,m,g).newIndexes,b=l[c]??null;if(i.set(p,g),null===b)for(let t=0;t<y.length;t++){const e=y[t];a(o,s+1,e,l,c+1,u.concat(e.index),d)}else{const t=y[b]??Z(`ListIndex not found at index ${b} of ${h.path}`);s+1<o.length?a(o,s+1,t,l,c+1,u.concat(t.index),d):d.push(u.concat(t.index))}},l=[];if(a(o.wildcardParentPathInfos,0,null,s,0,[],l),r.commitDiffBaseline)for(const[t,e]of i.entries())Ne(t,Array.isArray(e)?e:[]);return l}function dl(t,e,n,o,s){let r=null;for(let i=0;i<o.wildcardParentPathInfos.length;i++){const a=o.wildcardParentPathInfos[i],l=Es(cl(t,mn(a,r),e,n),r);null==l&&Z(`ListIndexes not found: ${a.path}`);const c=s[i];r=l[c]??Z(`ListIndex not found at index ${c} of ${a.path}`)}return r}function hl(t,e,n,o){"object"==typeof t&&null!==t||Z(`${U} list "${e}": ${n} row at index ${o} must be a plain object (got ${null===t?"null":typeof t}).`);const s=Object.getPrototypeOf(t);s!==Object.prototype&&null!==s&&Z(`${U} list "${e}": ${n} row at index ${o} must be a plain object (class instances and exotic objects cannot be value-expanded).`)}function fl(t,e,n,o,s){const r="function"==typeof e?e(t):t[e];return null==r&&Z(`${U} list "${n}": ${o} row at index ${s} has no key (${"function"==typeof e?"key function":`field "${e}"`} returned ${String(r)}).`),r}function pl(t,e,n,o){const s=new Array(t.length),r=new Set;for(let i=0;i<t.length;i++){const a=t[i];hl(a,n,o,i);const l=fl(a,e,n,o,i);r.has(l)&&Z(`${U} list "${n}": duplicate key ${JSON.stringify(l)} in ${o} list.`),r.add(l),s[i]=l}return s}function ml(t,e){const n=[];for(const o of Object.keys(e))Object.is(t[o],e[o])||n.push({field:o,value:e[o]});for(const o of Object.keys(t))Object.hasOwn(e,o)||null==t[o]||n.push({field:o,value:null});return n}function gl(t,e,n,o){if(e.pathInfo.path in t)return!0;const s=e.parentAddress;if(null===s)return!1;const r=cl(t,s,n,o);if(null===r||"object"!=typeof r&&"function"!=typeof r)return!1;const i=e.pathInfo.lastSegment;if(i===l){const t=e.listIndex?.index;return"number"==typeof t&&t in r}return i in r}const yl=new WeakMap;function bl(t,e){null===e?yl.delete(t):yl.set(t,e)}function wl(t,e,n){const s=mn(nt(t.wildcardParentPaths[e]),n),r=Ue(t.stateElement,s),i=Pe(r),a=t.stateProxy[Ce](s),l=vr(s.listIndex,i,a);t.observedListValueByAbsAddress.set(r,Array.isArray(a)?a:[]);const c=function(t,e){switch(e){case"old":return t.oldIndexes;case"new":return t.newIndexes;case"add":return t.addIndexSet;case"change":return t.changeIndexSet;case"delete":return t.deleteIndexSet;default:return o.debug&&console.log(`Invalid search type: ${e}`),[]}}(l,t.searchType);if(e===t.wildcardPaths.length-1)t.targetListIndexes.push(...c);else for(const n of c)wl(t,e+1,n)}const vl=[];function _l(t,e,n,o,s){return"full"===t.listExpansion||t.stateElement.crossRowListPaths?.has(e)?{fullRows:s.newIndexes,movedRows:null}:0===s.addIndexSet.size&&0===s.changeIndexSet.size?0===s.deleteIndexSet.size?t.keyedMergePath===e?{fullRows:vl,movedRows:null}:{fullRows:s.newIndexes,movedRows:null}:{fullRows:vl,movedRows:null}:{fullRows:s.addIndexSet,movedRows:s.changeIndexSet}}const $l=[];function Sl(t,e,n){const o=t.stateElement.indexDependentGetterPaths;if(!o||0===o.size)return $l;let s=null;const r=e+a;for(const t of o){if(t!==e&&!t.startsWith(r))continue;const o=nt(t);if(o.wildcardCount!==n.wildcardCount)return null;(s??=[]).push(o)}return s??$l}function xl(t,e,n){const o=e.pathInfo.path,s=t.staticMap.get(o);if(s)for(const r of s){const s=nt(r);if(t.listPathSet.has(o)&&s.lastSegment===l){const i=t.stateProxy[Ce](e),a=Ue(t.stateElement,e),l=Pe(a),c=vr(e.listIndex,l,i);t.observedListValueByAbsAddress.set(a,Array.isArray(i)?i:[]);const u=_l(t,o,0,0,c);for(const e of u.fullRows){const o=mn(s,e);t.result.add(o),n.push(o)}if(null!==u.movedRows){const e=Sl(t,r,s);if(null===e)for(const e of u.movedRows){const o=mn(s,e);t.result.add(o),n.push(o)}else if(e.length>0)for(const o of u.movedRows)for(const s of e){const e=mn(s,o);t.result.add(e),n.push(e)}}}else{const o=mn(s,e.listIndex);t.result.add(o),n.push(o)}}const r=t.dynamicMap.get(o);if(r)for(const o of r){const s=nt(o),r=[];if(s.wildcardCount>0){const n=Xe(e.pathInfo,s);if(s.wildcardCount-n>=1){let o;n>0?(null===e.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`),o=Ye(e.listIndex,n-1,e.pathInfo.wildcardCount)):o=null;const i={stateElement:t.stateElement,observedListValueByAbsAddress:t.observedListValueByAbsAddress,targetListIndexes:[],wildcardPaths:s.wildcardPaths,wildcardParentPaths:s.wildcardParentPaths,stateProxy:t.stateProxy,searchType:t.searchType};wl(i,n,o),r.push(...i.targetListIndexes)}else{null===e.listIndex&&Z(`Cannot expand dynamic dependency with wildcard for non-list address: ${e.pathInfo.path}`);const t=Ye(e.listIndex,n-1,e.pathInfo.wildcardCount);r.push(t)}}else r.push(null);for(const e of r){const o=mn(s,e);t.result.add(o),n.push(o)}}}function Pl(t,e,n,o,s,r,i,a,l){const c=e.pathInfo.path;if(!n.has(c)&&!o.has(c))return a(e),[];const u=function(t,e,n){const o=new Map,s=new Map,r=[t];for(s.set(t,0);r.length>0;){const t=r.pop();if(o.has(t))continue;const i=e.get(t),a=n.get(t);let l;l=void 0===i?a??[]:void 0===a?i:i.concat(a),o.set(t,l);for(let t=0;t<l.length;t++){const e=l[t];s.set(e,(s.get(e)??0)+1),o.has(e)||r.push(e)}}const i=new Map,a=new Set,l=[];for(const[t,e]of s)0===e&&(i.set(t,0),a.add(t),l.push(t));for(let t=0;t<l.length;t++){const e=l[t],n=i.get(e)+1;n>1e3&&Z(`Maximum dependency depth of 1000 exceeded. Possible circular dependency detected at path: ${e}`);const r=o.get(e);for(let t=0;t<r.length;t++){const e=r[t];n>(i.get(e)??-1)&&i.set(e,n);const o=s.get(e)-1;s.set(e,o),0===o&&(a.add(e),l.push(e))}}if(a.size!==o.size){let t=-1;for(const e of a){const n=i.get(e);n>t&&(t=n)}const e=t+1;for(const t of o.keys())a.has(t)||i.set(t,e)}return i}(c,n,o),d={ranks:u,stateElement:t,observedListValueByAbsAddress:new Map,staticMap:n,dynamicMap:o,result:new Set,listPathSet:s,visited:new Set,stateProxy:r,searchType:i,listExpansion:l?.listExpansion??"full",keyedMergePath:l?.keyedMergePath??null};!function(t,e,n){const o=[],s=t.ranks,r=(t,e)=>{let n=s.get(t.pathInfo.path)??e;n<e&&(n=e),(o[n]??=[]).push(t)};r(e,0);const i=[];for(let e=0;e<o.length;e++){const s=o[e];if(void 0!==s)for(let o=0;o<s.length;o++){const a=s[o];if(!t.visited.has(a)){t.visited.add(a),n(a),i.length=0,xl(t,a,i);for(let t=0;t<i.length;t++)r(i[t],e+1)}}}}(d,e,a);for(const[t,e]of d.observedListValueByAbsAddress)Ne(t,e);return Array.from(d.result)}function Nl(t,e,n,o,s){const r=t.addressHooks;if(r){const i=r.writeObserve;for(let r=0;r<i.length;r++)i[r](t,e,n,o,s)}}function kl(t,e,n){const o=t.addressHooks;if(o){const s=o.written;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function Il(t,e,n){const o=t.addressHooks;if(o){const s=o.swapped;for(let o=0;o<s.length;o++)s[o](t,e,n)}}function Al(t,e,n,s,r,i){const a=function(t,e){return!0===Us.get(t)?.byPath.has(e)||!0===Qs.get(t)?.has(e)}(t,e),c=function(t,e){return!0===Ys.get(t)?.has(e)}(t,e);if(!a&&!c)return;const u=qs(),d=o.enablePropagationContext?eo()??null:null,h=t=>{Os(t),u.enqueueAbsoluteAddress(t,d)};a&&dr(t,e,n,s,r).forEach(h),c&&function(t,e,n,o){const s=nt(e).segments.length,r=[];for(const i of Ys.get(t).get(e)){const e=nt(i).segments.slice(s);if(e.includes(l))fr(t,i,r);else for(const s of dr(t,i,!0,hr(n,e),hr(o,e)))r.push(s)}return r}(t,e,n?s:i(),r).forEach(h)}function El(t,e,n,s,r,i,a="diff"){const l=o.enablePropagationContext?eo()??Yn(-1):null,c=qs();c.enqueueAbsoluteAddress(e,l),i&&Os(e),Pl(s.stateElement,t,s.stateElement.staticDependency,s.stateElement.dynamicDependency,s.stateElement.listPaths,n,"new",e=>{if(e===t)return;const n=Ue(s.stateElement,e);Os(n),c.enqueueAbsoluteAddress(n,l)},{listExpansion:a,keyedMergePath:r})}function Cl(t,e,n,o,s){s&&(t.getterPaths.has(e)?Os(n):Ms(n,{value:o,dirty:!1,generation:t.stateGeneration}))}function Tl(t,e,n,o,s,r,i,a){try{if(!(e.pathInfo.path in t)){const n=e.parentAddress;if(null===n)return Reflect.set(t,e.pathInfo.path,o);const i=cl(t,n,s,r),a=e.pathInfo.segments[e.pathInfo.segments.length-1];if(a===l){const t=e.listIndex?.index??Z(ki(`path "${e.pathInfo.path}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0));return Reflect.set(i,t,o)}return Reflect.set(i,a,o)}if(!r.stateElement.setterPaths.has(e.pathInfo.path))return Reflect.set(t,e.pathInfo.path,o);r.pushAddress(e),r.beginUntrack();try{return Reflect.set(t,e.pathInfo.path,o,s)}finally{r.endUntrack(),r.popAddress()}}finally{El(e,n,s,r,i,a)}}function Ml(t,e,n,o,s){const r=s.stateElement.listKeys;if(null!=r&&Array.isArray(n)){const i=r.get(e.pathInfo.path);if(void 0!==i){const r=cl(t,e,o,s),c=function(t,e,n,o){const s=pl(o,e,t,"new");if(!Array.isArray(n)||0===n.length||0===o.length)return null;const r=n,i=pl(r,e,t,"current"),a=new Map;for(let t=0;t<r.length;t++)a.set(i[t],r[t]);const l=new Array(o.length),c=[];for(let t=0;t<o.length;t++){const e=o[t],n=a.get(s[t]);void 0!==n&&n!==e?(l[t]=n,c.push({position:t,oldRow:n,newRow:e})):l[t]=e}return c.length>0?{list:l,matched:c}:null}(e.pathInfo.path,i,r,n);if(null!==c)return function(t,e,n,o,s,r){const i=e.pathInfo.path,c=e.listIndex;null===As(o)&&vr(c,null,o);const u=vr(c,o,n.list),d=Ol(t,e,n.list,s,r,i),h=nt(i+a+l);for(const e of n.matched){const n=ml(e.oldRow,e.newRow);if(0===n.length)continue;const o=u.newIndexes[e.position];for(const i of n)void 0!==o?Ml(t,mn(nt(h.path+a+i.field),o),i.value,s,r):e.oldRow[i.field]=i.value}return d}(t,e,c,r,o,s)}}return Ol(t,e,n,o,s,null)}function Ol(t,e,n,s,r,i){const c=r.stateElement,u=e.pathInfo.path,d=c.addressHooks;if(d){const t=d.write;for(let o=0;o<t.length;o++){const i=t[o](c,e,n,s,r);if(i!==Ua)return i}}const h=!!so&&(so=!1,!0);if(!(u in t)&&null!==e.parentAddress&&!c.elementPaths.has(u)){const a=cl(t,e.parentAddress,s,r);if("object"==typeof a&&null!==a){const t=e.pathInfo.lastSegment,f=t===l?e.listIndex?.index:t;let p,m=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const t=void 0!==f&&f in a,e=void 0!==f?a[f]:void 0;if(t&&Object.is(e,n))return!0;p=e,m=!0}Al(c,u,m,p,n,()=>a[f]);const g=il(c,e),y=Ue(c,e);null!==ye&&ye({type:"state:write",absoluteAddress:y,value:n,oldValue:p,hasOldValue:m}),Nl(c,u,y,p,m);let b=!1;try{if(void 0===f&&Z(ki(`path "${u}"`,e.pathInfo.wildcardCount,e.listIndex?.length??0)),d&&0!==d.writeMissing.length&&t!==l&&!(f in a)){const t=d.writeMissing;for(let o=0;o<t.length;o++){b=!0;const i=t[o](c,e,a,f,n,s,r);if(i!==Ua)return i;b=!1}}return Reflect.set(a,f,n)}finally{El(e,y,s,r,i,g),b?Os(y):Cl(c,u,y,n,g),kl(c,e.pathInfo,{value:n})}}}let f,p=!1;if(!h&&o.sameValueGuard&&(null===n||"object"!=typeof n)){const o=cl(t,e,s,r);if(gl(t,e,s,r)&&Object.is(o,n))return!0;f=o,p=!0}Al(c,u,p,f,n,()=>cl(t,e,s,r));const m=c.elementPaths.has(e.pathInfo.path),g=il(c,e),y=Ue(c,e);null!==ye&&ye({type:"state:write",absoluteAddress:y,value:n,oldValue:f,hasOldValue:p}),Nl(c,u,y,f,p);try{return m?function(t,e,n,o,s,r,i,c){const u=e.parentAddress??Z(`address.parentAddress is undefined path: ${e.pathInfo.path}`),d=cl(t,u,s,r)??[];let h=(f=d,yl.get(f)??null);var f;if(null===h){const t=As(d)??[];h={value:[...d],listIndexes:[...t]},bl(d,h)}try{return Tl(t,e,n,o,s,r,i,c)}finally{const n=h.value.indexOf(o),i=cl(t,u,s,r)??[],c=Array.isArray(i)?As(i)??[]:[],f=e.listIndex.index,p=-1!==n?h.listIndexes[n]:_s(u.listIndex,-1);if(c[f]=p,new Set(i).size===h.value.length){for(let t=0;t<c.length;t++)c[t].index=t;bl(d,null),function(t,e,n,o,s,r){const i=r.stateElement,c=qs(),u=Ue(i,t);we(u)===n&&(Cs(e.value,e.listIndexes),ve(u,e.value),function(t){_r.add(t)}(e.value)),c.enqueueRenderOnlyAddress(u);const d=new Map;e.listIndexes.forEach((t,e)=>d.set(t,e));const h=nt(t.pathInfo.path+a+l);for(let t=0;t<o.length;t++){const n=o[t],a=d.get(n);if(a===t)continue;const l=mn(h,n),u=Ue(i,l);if(void 0===a){const n=Ge(i,h,e.listIndexes[t]??null);Il(i,u,n),El(l,u,s,r,null,il(i,l),"full");continue}Pl(i,l,i.staticDependency,i.dynamicDependency,i.listPaths,s,"new",t=>{const e=Ue(i,t);Os(e),c.enqueueRenderOnlyAddress(e)},{listExpansion:"diff"})}}(u,h,i,c,s,r)}}}(t,e,y,n,s,r,i,g):Tl(t,e,y,n,s,r,i,g)}finally{m||Cl(c,u,y,n,g),kl(c,e.pathInfo,{value:n})}}function Ll(t,e,n,o){return(e,s,...r)=>{const i=nt(e);if(o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}s.length!==i.wildcardParentPathInfos.length&&Z(xi("$resolve",e,i.wildcardParentPathInfos.length,s.length));const a=mn(i,dl(t,n,o,i,s));if(0===r.length)return cl(t,a,n,o);tl(o),Ml(t,a,r[0],n,o)}}function Rl(t,e,n,o){const s=Ll(t,0,n,o);return(e,r)=>{const i=nt(e);if(void 0===r||Array.isArray(r)||Z(`$getAll("${e}") requires the indexes to be an array when given (omit them for the loop context, or pass [] to expand every level) — got `+(null===r?"null":typeof r)+"."),o.addressStackLength>0){const t=o.lastAddressStack?.pathInfo??null,e=o.stateElement;null!==t&&t.path!==i.path&&e.getterPaths.has(t.path)&&e.addDynamicDependency(i.path,t.path)}if(void 0!==r&&r.length>i.wildcardParentPathInfos.length&&Z(xi("$getAll",e,i.wildcardParentPathInfos.length,r.length)),void 0===r){for(let t=i.wildcardPaths.length-1;t>=0;t--){const e=sl(o,i.wildcardPaths[t]);if(e){r=Ze(e,e.length);break}}if(void 0===r){const t=o.addressStackLength>0?o.lastAddressStack:null,n=t?.listIndex??null;i.wildcardCount>0&&null!==t&&null!==n&&n.length>0&&Z(function(t,e){return`$getAll("${t}") was called without indexes inside the loop context of "${e}", but the path shares no wildcard level with that context, so the context indexes ($1..$n) do not apply. Pass indexes explicitly ([] expands every level).`}(e,t.pathInfo.path)),r=[]}}const a=ul(t,n,o,i,r,{commitDiffBaseline:!0}),l=[];for(let t=0;t<a.length;t++)l.push(s(i.path,a[t]));return l}}function jl(t,e,n,o){const s=e.pathInfo;switch(e.wildcardType){case"none":return null;case"context":return sl(o,s.wildcardPaths.at(-1)??Z(`lastWildcardPath is null: ${e.pathInfo.path}`))??Z(`ListIndex not found: ${e.pathInfo.path}`);case"all":{let s=null;for(let r=0;r<e.pathInfo.wildcardCount;r++){const i=e.pathInfo.wildcardParentPathInfos[r]??Z(`wildcardParentPathInfo is null: ${e.pathInfo.path}`),a=Es(cl(t,mn(i,s),n,o),s)??Z(`ListIndex not found: ${i.path}`),l=e.wildcardIndexes[r]??Z(`wildcardIndex is null: ${e.pathInfo.path}`);s=a[l]??Z(`ListIndex not found at index ${l} of ${i.path}`)}return s}case"partial":Z(`Partial wildcard type is not supported yet: ${e.pathInfo.path}`)}}function Wl(t,e,n,o){return(e,s,r,i)=>{tl(o);const a=nt(e);Array.isArray(s)||Z(Ni(e,"requires an explicit indexes array (pass [] to expand every level).")),s.length>a.wildcardParentPathInfos.length&&Z(xi("$setAll",e,a.wildcardParentPathInfos.length,s.length));const l=!0===i?.spread,c="function"==typeof r;l&&c&&Z(Ni(e,"cannot combine { spread: true } with a mapper function.")),l&&!Array.isArray(r)&&Z(Ni(e,"requires an array as the value when { spread: true } is set."));const u=ul(t,n,o,a,s,{commitDiffBaseline:!1});l&&r.length!==u.length&&Z(function(t,e,n){return`$setAll("${t}", …, { spread: true }) requires the values array to have exactly one entry per matched address (matched ${e}) but got ${n}. Did the list change between $getAll and $setAll?`}(e,u.length,r.length));const d=[];for(let e=0;e<u.length;e++){const s=dl(t,n,o,a,u[e]);d.push(mn(a,s))}let h=0;for(let e=0;e<d.length;e++){const s=d[e];let i;i=c?r(cl(t,s,n,o),...u[e]):l?r[e]:r,void 0!==i&&(Ml(t,s,i,n,o),h++)}return h}}function Dl(t,e){const n=t.getterPaths;if(0===n.size)return!1;for(const t of nt(e).cumulativePaths)if(n.has(t))return!0;return!1}const zl=/^\$\d+$/,Bl=`${G}${a}`,Fl=`${V}${a}`,Hl=new WeakMap;class ql{_stateElement;_addressStack=Array(u).fill(void 0);_addressStackIndex=-1;_loopContext;_mutability;_untrackDepth=0;constructor(t,e){const n=ta(t);null===n&&Z("StateHandler: no state tree found on this root."),this._stateElement=n,this._mutability=e}get stateElement(){return this._stateElement}get mutability(){return this._mutability}get lastAddressStack(){let t;return this._addressStackIndex>=0&&(t=this._addressStack[this._addressStackIndex]),void 0===t&&Z("Last address stack is undefined."),t}get addressStackLength(){return this._addressStackIndex+1}get loopContext(){return this._loopContext}pushAddress(t){this._addressStackIndex+1>=u&&(this._hasRepeatedAddress()&&Z(`[wcs/getter-cycle] Exceeded maximum address stack depth of 128. Possible circular dependency between path getters: ${this._describeAddressCycle()}`),Z(`[wcs/getter-depth-exceeded] Exceeded maximum address stack depth of 128 with no address visited twice — the data is simply nested deeper than the engine evaluates in one pass. Deepest path first: ${this._describeAddressCycle()}`)),this._addressStackIndex++,this._addressStack[this._addressStackIndex]=t}_hasRepeatedAddress(){const t=new Set;for(let e=0;e<=this._addressStackIndex;e++){const n=this._addressStack[e];if(n){if(t.has(n))return!0;t.add(n)}}return!1}_tailAddressPaths(){const t=[];for(let e=this._addressStackIndex;e>=0&&t.length<8;e--){const n=this._addressStack[e];n&&t.push(n.pathInfo.path)}return t}_describeAddressCycle(){const t=this._tailAddressPaths();return`${Array.from(new Set(t)).reverse().join(" -> ")} -> ...`}popAddress(){if(this._addressStackIndex<0)return null;const t=this._addressStack[this._addressStackIndex];return void 0===t&&Z(`Address stack at index ${this._addressStackIndex} is undefined.`),this._addressStack[this._addressStackIndex]=void 0,this._addressStackIndex--,t}setLoopContext(t){this._loopContext=t}clearLoopContext(){this._loopContext=void 0}get untracking(){return this._untrackDepth>0}beginUntrack(){this._untrackDepth++}endUntrack(){this._untrackDepth--}get(t,e,n){return function(t,e,n,o){const s=I[e];if(void 0===s&&"string"==typeof e&&36===e.charCodeAt(0)&&zl.test(e)&&Z(`[wcs/index-param-range] "${e}" is not a valid list index parameter: they run from $1 to $128, with no leading zeros.`),void 0!==s){0===o.addressStackLength&&Z(`No active state reference to get list index for "${e.toString()}".`);const t=o.lastAddressStack,n=t?.pathInfo;n&&!o.untracking&&o.stateElement?.getterPaths.has(n.path)&&o.stateElement.addIndexDependentGetterPath?.(n.path);const r=t?.listIndex;null==r&&Z(`ListIndex not found: ${e.toString()}`);let i=s;const a=t.pathInfo,l=o.stateElement?.addressHooks;if(l){const e=l.indexShift;for(let n=0;n<e.length;n++)i+=e[n](o,t)}const c=Ye(r,i,a.wildcardCount);return c?.index??Z(`ListIndex not found: ${e.toString()}`)}if("string"==typeof e){const s=o.stateElement?.addressHooks;if(s){const r=s.get;for(let s=0;s<r.length;s++){const i=r[s](o,e,n,t);if(i!==Ua)return i}}if("$"===e[0]){switch(e){case"$stateElement":return o.stateElement;case"$getAll":return(e,s)=>Rl(t,0,n,o)(e,s);case"$setAll":return(e,s,r,i)=>Wl(t,0,n,o)(e,s,r,i);case"$postUpdate":return e=>function(t,e,n,o){const s=o.stateElement;return e=>{const r=ol(e),i=jl(t,r,n,o),a=mn(r.pathInfo,i),l=Ue(s,a),c=qs();c.enqueueAbsoluteAddress(l),Pl(o.stateElement,a,o.stateElement.staticDependency,o.stateElement.dynamicDependency,o.stateElement.listPaths,n,"new",t=>{const e=Ue(s,t);Os(e),c.enqueueAbsoluteAddress(e)});const u=s.addressHooks;if(u){const t=u.written;for(let e=0;e<t.length;e++)t[e](s,a.pathInfo)}}}(t,0,n,o)(e);case"$resolve":return(e,s,...r)=>Ll(t,0,n,o)(e,s,...r);case"$dependOn":case"$trackDependency":return t=>function(t,e,n,o){return t=>{-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] ${String(e)}("${t}") cannot take "**" — a dependency is registered against a concrete path (a fixed number of "*"). Track the concrete depth, or read the path through this[...] / $getAll inside the getter so the dependency is recorded automatically.`),0===o.addressStackLength&&Z(`No active state reference to track dependency for path "${t}".`);const n=o.lastAddressStack?.pathInfo??Z("Internal error: lastAddressStack is null"),s=o.stateElement;o.stateElement.getterPaths.has(n.path)&&n.path!==t&&s.addDynamicDependency(t,n.path)}}(0,e,0,o)(t);case"$eq":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;if(Dl(o.stateElement,t))return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&lr(o.stateElement,t),Object.is(n[t],e);let r;o.beginUntrack();try{r=n[t]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&ar(o.stateElement,t,e,Ue(o.stateElement,s),r),Object.is(r,e)};case"$eqPath":return(t,e)=>{const s=o.addressStackLength>0?o.lastAddressStack:null,r=Dl(o.stateElement,t);let i,a=r?n[t]:void 0;o.beginUntrack();try{r||(a=n[t]),i=n[e]}finally{o.endUntrack()}return null!==s&&o.stateElement.getterPaths.has(s.pathInfo.path)&&(r?lr(o.stateElement,t):ar(o.stateElement,t,i,Ue(o.stateElement,s),a)),Object.is(a,i)};case"$eqIndex":return(t,e=1)=>{const s=o.addressStackLength>0?o.lastAddressStack:null;null!==s&&null!==s.listIndex||Z(`$eqIndex("${t}") needs a list row scope.`);const r=Ye(s.listIndex,e-1,s.pathInfo.wildcardCount);if(null===r&&Z(`$eqIndex("${t}", ${e}): no list index at that level.`),Dl(o.stateElement,t))return o.stateElement.getterPaths.has(s.pathInfo.path)&&lr(o.stateElement,t),Object.is(n[t],r.index);const i=e===s.pathInfo.wildcardCount;let a,l;o.beginUntrack();try{a=n[t],i&&(l=n[s.pathInfo.wildcardParentPaths[e-1]])}finally{o.endUntrack()}if(o.stateElement.getterPaths.has(s.pathInfo.path)){const e=i?As(l):null;null!==e?function(t,e,n,o,s){Js=!0,er(t).lastValue.set(e,s),tr(t,e);let r=Qs.get(t);void 0===r&&Qs.set(t,r=new Map);let i=r.get(e);void 0===i&&r.set(e,i=new Set);let a,l=Xs.get(o);void 0===l?Xs.set(o,l=[]):a=l.find(n=>n.stateElement===t&&n.path===e),void 0===a&&(a={stateElement:t,path:e,indexes:o,getters:new Set},l.push(a),i.add(a)),a.getters.add(n)}(o.stateElement,t,s.pathInfo,e,a):function(t,e,n,o,s){Js=!0;const r=er(t);tr(t,e),ir(r,e,s,o,sr(r,e,n.index,o),{stateElement:t,path:e,absAddress:o,levelListIndex:n})}(o.stateElement,t,r,Ue(o.stateElement,s),a)}return Object.is(a,r.index)};case"$untracked":case"$untrackDependency":return t=>function(t,e,n,o){return t=>{o.beginUntrack();try{return t()}finally{o.endUntrack()}}}(0,0,0,o)(t);case j:return qa(o.stateElement)}if(!e.startsWith(Bl)&&!e.startsWith(Fl))return}const r=ol(e),i=jl(t,r,n,o),a=mn(r.pathInfo,i);return cl(t,a,n,o)}if("symbol"==typeof e){const s=function(t){let e=Hl.get(t);return void 0===e&&(e=new Map,Hl.set(t,e)),e}(o),r=s.get(e);if(void 0!==r)return r;let i;switch(e){case Ee:i=(t,e=()=>{})=>function(t,e,n){void 0!==t.loopContext&&Z("already in loop context"),t.setLoopContext(e);try{t.pushAddress(e);try{return n()}finally{t.popAddress()}}finally{t.clearLoopContext()}}(o,t,e);break;case Ce:i=e=>cl(t,e,n,o);break;case Te:i=e=>gl(t,e,n,o);break;case Me:i=(e,s)=>Ml(t,e,s,n,o);break;case Oe:i=()=>async function(t,e,n){const o=Reflect.get(t,A);"function"==typeof o&&await o.call(n)}(t,0,n);break;case Le:i=()=>function(t,e,n){const o=Reflect.get(t,E);"function"==typeof o&&o.call(n)}(t,0,n);break;case Re:i=e=>function(t,e,n,o){const s=Reflect.get(t,C);let r;if("function"==typeof s){const t=new Set,i={};for(const n of e){if(n.absolutePathInfo.stateElement!==o.stateElement)continue;const e=n.absolutePathInfo.pathInfo,s=e.path;if(-1===s.indexOf("#")&&(t.add(s),e.wildcardCount>0)){const t=Ze(n.listIndex,e.wildcardCount),o=i[s];void 0===o?i[s]=[t]:o.push(t)}}r=s.call(n,Array.from(t),i)}const i=o.stateElement?.addressHooks;if(i){const t=i.updated;for(let s=0;s<t.length;s++)t[s](o.stateElement,e,n)}return r}(t,e,n,o);break;case je:i=(e,o)=>function(t,e,n,o){const s=Reflect.get(t,T);"function"==typeof s&&s.call(o,e,n)}(t,e,o,n);break;default:return Reflect.get(t,e,n)}return s.set(e,i),i}}(t,e,n,this)}set(t,e,n,o){return tl(this),function(t,e,n,o,s){if("string"==typeof e){const r=ol(e),i=jl(t,r,o,s);return Ml(t,mn(r.pathInfo,i),n,o,s)}return Reflect.set(t,e,n,o)}(t,e,n,o,this)}has(t,e){return Reflect.has(t,e)}}const Ul=Promise.resolve(),Gl=new Map;let Vl=[];function Kl(t,e){Gl.set(t,e),Vl=Array.from(Gl.values()).sort((t,e)=>t.order-e.order)}function Jl(t,e){return Z(Vi(t,e))}const Ql="undefined"==typeof HTMLElement?class{}:HTMLElement;function Xl(t){const e=[];let n=t;for(;n&&n!==Object.prototype;)e.push(n),n=Object.getPrototypeOf(n);const o={};for(let t=e.length-1;t>=0;t--)Object.assign(o,Object.getOwnPropertyDescriptors(e[t]));return o}let Yl=null;const Zl=new Set(["for","if","elseif","else"]);class tc extends Ql{static hasConnectedCallbackPromise=!0;static getBindingsReady(t){return ea(t)}static get observedAttributes(){return["mount"]}__state;_hasUpdatedCallback=!1;_hasErrorCallback=!1;_hydratedFromSsr=!1;_crossRowListPaths=new Set;_indexDependentGetterPaths=new Set;_initialized=!1;_initializeFailed=!1;_initializationLanded=!1;_initializePromise;_resolveInitialize=null;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;_loadingPromise;_resolveLoading=null;_setStatePromise=null;_resolveSetState=null;_listPaths=new Set;_listKeys=null;_recursionRegistry=null;_elementPaths=new Set;_getterPaths=new Set;_setterPaths=new Set;_loopContextStack=function(){return new Ra}();_dynamicDependency=new Map;_staticDependency=new Map;_pathSet=new Set;_stateGeneration=0;_pathRegistrations=new Map;_pendingReapplyPaths=null;_generatedPaths=new Set;_watchPaths=null;_scanPaths=null;_version=0;_rootNode=null;_boundComponent=null;_boundComponentStateProp=null;_hasMounts=!1;_hasGraftedVolumes=!1;_addressHooks=null;_bindableEventMap={};_commandTokenNames=new Set;_eventTokenNames=new Set;_treeless=!1;_connectGeneration=0;constructor(){super(),this._initializePromise=new Promise(t=>{this._resolveInitialize=t}),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._loadingPromise=new Promise(t=>{this._resolveLoading=t}),this._setStatePromise=new Promise(t=>{this._resolveSetState=t})}get _state(){return void 0===this.__state&&Z(`${o.tagNames.state} _state is not initialized yet.`),this.__state}set _state(t){za(t);const e=this.__state,n=function(){const t=new Map;return{get:e=>t.get(e),set(e,n){t.set(e,n)}}}();n.set("previousState",e),function(t,e,n){for(let o=0;o<Qa.length;o++)Qa[o].validateEarly?.(t,e,n)}(this,t,n);const o=function(t){const e=new Set,n=t[R];if(void 0===n)return e;Array.isArray(n)||Z(`${R} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Z(`${R} entries must be non-empty strings.`),t===j&&Z(`${R} entry "${t}" conflicts with the reserved namespace name "${j}".`),e.has(t)&&Z(`${R} entry "${t}" is duplicated.`),e.add(t);return e}(t),s=function(t){const e=new Set,n=t[W];if(void 0===n)return e;Array.isArray(n)||Z(`${W} must be an array of strings.`);for(const t of n)"string"==typeof t&&0!==t.length||Z(`${W} entries must be non-empty strings.`),e.has(t)&&Z(`${W} entry "${t}" is duplicated.`),e.add(t);return e}(t),r=function(t){const e=t[U];if(void 0===e)return null;"object"==typeof e&&null!==e||Z(`${U} must be an object mapping list paths to key specs.`);const n=new Map;for(const[t,o]of Object.entries(e)){0===t.length&&Z(`${U} entry path must be a non-empty string.`);const e=t.split(a);e.some(t=>0===t.length)&&Z(`${U} entry "${t}" must not contain empty path segments.`),e[e.length-1]===l&&Z(`${U} entry "${t}" must be the list path itself, not the element path (drop the trailing "${a}${l}").`),-1!==t.indexOf(q)&&Z(`[wcs/recursion-unsupported] ${U} entry "${t}" uses "${q}", which ${U} does not interpret — a keyed list is one concrete list path. Declare the key per depth instead (for example "nodes${a}${l}${a}children").`),"function"!=typeof o?("string"!=typeof o&&Z(`${U} entry "${t}" key spec must be a field name (string) or a function.`),0===o.length&&Z(`${U} entry "${t}" key field name must be a non-empty string.`),(o.includes(a)||o.includes(l))&&Z(`${U} entry "${t}" key field name "${o}" must be a flat property name ("${a}" / "${l}" are not allowed).`),o in Object.prototype&&Z(`${U} entry "${t}" key field name "${o}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),n.set(t,o)):n.set(t,o)}return n.size>0?n:null}(t);n.set("eventTokenNames",s),function(t,e,n){for(let o=0;o<Qa.length;o++)Qa[o].validate?.(t,e,n)}(this,t,n),function(t,e,n){for(let o=0;o<Qa.length;o++)Qa[o].preCommit?.(t,e,n)}(this,t,n),this._commandTokenNames=o,this._eventTokenNames=s,this._stateGeneration++,this.__state=t,void 0!==e&&Yl?.reset(this),this._hasUpdatedCallback=C in t,this._hasErrorCallback=T in t,In.delete(this),function(t,e,n){for(let o=0;o<Qa.length;o++)Qa[o].applyEarly?.(t,e,n)}(this,t,n),function(t,e,n){const o=e[D];if(void 0!==o){"object"==typeof o&&null!==o||Z(`${D} must be an object mapping event-token names to handler functions.`);for(const[e,s]of Object.entries(o))n.has(e)||Z(`${D} entry "${e}" is not declared in $eventTokens.${rt(e,n)}`),"function"!=typeof s&&Z(`${D} entry "${e}" must be a function.`),An(t,e).subscribe(s)}}(this,t,this._eventTokenNames),this._listPaths.clear(),this._elementPaths.clear(),this._getterPaths.clear(),this._setterPaths.clear(),this._pathSet.clear();const i=function(t){const e=new Set,n=new Set,o=Xl(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterPaths:e,setterPaths:n}}(t);for(const t of i.getterPaths)this._getterPaths.add(t);for(const t of i.setterPaths)this._setterPaths.add(t);!function(t,e,n){for(let o=0;o<Qa.length;o++)Qa[o].apply?.(t,e,n)}(this,t,n),this._listKeys=r,this._rebuildPathInfo(),function(t,e,n){for(let o=0;o<Qa.length;o++)Qa[o].register?.(t,e,n)}(this,t,n),Za(this,null),this._resolveLoading?.()}attributeChangedCallback(t,e,n){this._initialized&&e!==n&&console.warn(`[@wcstack/state] Changing the "mount" attribute after initialization is not supported and is ignored (was ${null===e?"absent":`"${e}"`}, now ${null===n?"absent":`"${n}"`}). Remove this <${o.tagNames.state}> element and create a new one with the desired mount path instead.`)}_loadFromSsrElement(){return this.hasAttribute("enable-ssr")?Ji('the "enable-ssr" attribute').loadState(this):null}async _loadStateFromSource(){try{if(this.hasAttribute("state"))return function(t){const e=document.getElementById(t);if(e&&"application/json"===e.type)try{return JSON.parse(e.textContent||"{}")}catch(t){Z("Failed to parse JSON from script element:"+t)}return{}}(this.getAttribute("state"));if(!this.hasAttribute("src")){if(this.hasAttribute("json")){const t=this.getAttribute("json");return JSON.parse(t)}{const t=this.querySelector('script[type="module"]');if(t)return await Oa(t,o.tagNames.state);{const t=setTimeout(()=>{console.warn(`[@wcstack/state] Warning: No state source found for <${o.tagNames.state}> element.`)},6e4),e=await this._setStatePromise;return clearTimeout(t),e}}}{const t=this.getAttribute("src");if(t&&t.endsWith(".json"))return await async function(t){try{const e=await fetch(t);return e.ok||Z(`Failed to fetch JSON file: ${e.statusText}`),await e.json()}catch(t){return console.error("Failed to load JSON file:",t),{}}}(t);if(t&&t.endsWith(".js"))return await La(t);Z(`Unsupported src file type: ${t}`)}}catch(t){Z(`Failed to initialize state: ${t}`)}}async _initialize(){const t=e()?null:this._loadFromSsrElement();if(null!==t&&(this._hydratedFromSsr=!0),this._state=await this._loadStateFromSource(),null!==t&&this.__state)for(const[e,n]of Object.entries(t)){if(e in this.__state){const t=Object.getOwnPropertyDescriptor(this.__state,e);if(t&&(t.get||t.set))continue;if("function"==typeof this.__state[e])continue}this.__state[e]=n}return await this._loadingPromise,null!==this._rootNode&&(sa(this._rootNode,this),!0)}_failInitialization(t){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.(),Z(t)}_failInitializeLoudly(t,e=!0){if(this._initializationLanded)throw t;throw this._initializeFailed=!0,console.error(`[@wcstack/state] <${o.tagNames.state}> failed to initialize.`,t),this._resolveInitialize?.(),this._resolveLoading?.(),this._connectedCallbackPromise.catch(()=>{}),this._rejectConnectedCallback?.(t),e&&null!==this._rootNode&&null===ta(this._rootNode)&&(function(t,e){const n=Promise.reject(e);n.catch(()=>{}),Xi.set(t,n)}(this._rootNode,t),function(t,e,n){for(let o=0;o<Vl.length;o++)Vl[o].initializeFailed?.(t,e,n)}(this,this._rootNode,t)),t}async _callStateConnectedCallback(){await this.createStateAsync("writable",async t=>{A in t&&await t[Oe]()})}_callStateDisconnectedCallback(){this.createState("writable",t=>{E in t&&t[Le]()})}async connectedCallback(){this._rootNode=this.getRootNode();const t=++this._connectGeneration;if(this._initializationLanded=!1,this._initialized){if(function(t){for(let e=0;e<Vl.length;e++)if(!0===Vl[e].reconnecting?.(t))return!0;return!1}(this))return void this._resolveConnectedCallback?.();this._treeless||ta(this._rootNode)===this||sa(this._rootNode,this)}else{this.hasAttribute("name")&&this._failInitialization(this.hasAttribute("mount")?'"mount" replaces "name" — a volume has no name of its own. Remove the name attribute.':`The "name" attribute was removed in v2 — there is a single state tree per root. Mount this state onto the tree instead: <wcs-state mount="${this.getAttribute("name")}" ...> and read it as "${this.getAttribute("name")}.<path>".`);const e=function(t){for(let e=0;e<Vl.length;e++){const n=Vl[e].connecting?.(t);if(null!=n)return n}return null}(this);if(null!==e)return void await e;const n=this.parentNode;if(n instanceof ShadowRoot&&n.host.hasAttribute(K))try{Jl("dcc",`a <${o.tagNames.state}> inside a [${K}] host`)}catch(t){this._failInitializeLoudly(t)}if(this.hasAttribute("mount"))try{Jl("scopes",'the "mount" attribute')}catch(t){this._failInitializeLoudly(t,!1)}let s=!1;try{const t=function(t){for(let e=0;e<Vl.length;e++){const n=Vl[e].preparing?.(t);if(null!=n)return n}return null}(this);null===t&&this.hasAttribute("bind-component")&&Jl("scopes",'the "bind-component" attribute'),s=await(t??!1)}catch(t){this._failInitializeLoudly(t)}if(s)return;let r=!1;try{r=await this._initialize()}catch(t){this._failInitializeLoudly(t)}if(!r)return;this._initialized=!0,this._resolveInitialize?.()}if(null!==this._pendingReapplyPaths){const t=this._pendingReapplyPaths;this._pendingReapplyPaths=null,this._reapplyBindings(t)}if(this.hasAttribute("enable-ssr")&&!e()||t!==this._connectGeneration||await this._callStateConnectedCallback(),e()&&this.hasAttribute("enable-ssr")&&!function(){const t=document.documentElement;return!!t&&"orchestrated"===t.getAttribute("data-wcs-server")}())try{await Ji('the "enable-ssr" attribute').emitSnapshot(this)}catch(t){throw this._rejectConnectedCallback?.(t),t}Za(this,t),this._resolveConnectedCallback?.()}disconnectedCallback(){if(!function(t){for(let e=0;e<Vl.length;e++)if(!0===Vl[e].disconnecting?.(t))return!0;return!1}(this)&&null!==this._rootNode){if(!this._initialized)return this._initializeFailed&&function(t,e){for(let n=0;n<Vl.length;n++)Vl[n].initializeFailureCleared?.(t,e)}(this,this._rootNode),void(this._rootNode=null);try{this._callStateDisconnectedCallback()}finally{sa(this.rootNode,null),Ha.delete(this),function(t){for(let e=0;e<Xa.length;e++)Xa[e].deactivate?.(t)}(this),this._rootNode=null}}}get initialized(){return this._initialized}get connectedRootNode(){return this._rootNode}clearConnectedRootNode(){this._rootNode=null}markInitialized(){this._initialized=!0}settleInitialization(){this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}loadStateFromSource(){return this._loadStateFromSource().then(t=>(za(t),t))}markTreeless(){this._treeless=!0}failInitializeLoudly(t){return this._failInitializeLoudly(t)}get connectGeneration(){return this._connectGeneration}setWatchPaths(t){this._watchPaths=t}setScanPaths(t){this._scanPaths=t}landInitialization(){this._initializationLanded=!0,this._resolveInitialize?.(),this._resolveLoading?.(),this._resolveConnectedCallback?.()}setRecursionRegistry(t){this._recursionRegistry=t}addGeneratedPath(t){this._generatedPaths.add(t)}setBoundComponent(t,e){this._boundComponent=t,this._boundComponentStateProp=e}get initializePromise(){return this._initializePromise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get listPaths(){return this._listPaths}get listKeys(){return this._listKeys}get hasRecursion(){return null!==this._recursionRegistry}get recursionRegistry(){return this._recursionRegistry}get watchPaths(){return this._watchPaths}get scanPaths(){return this._scanPaths}get elementPaths(){return this._elementPaths}addVolumeWatchPaths(t){if(0===t.size)return;const e=new Set(this._watchPaths??[]);for(const n of t)e.add(n);this._watchPaths=e,this.attachAddressHooks("watch",B)}mergeVolumeListKeys(t){if(0===t.size)return;const e=new Map(this._listKeys??[]);for(const[n,o]of t)e.has(n)&&Z(`$listKeys entry "${n}" is declared by both the root and a volume (or two volumes). Keep exactly one.`),e.set(n,o);this._listKeys=e}enableUpdatedCallback(){this._hasUpdatedCallback=!0}get hydratedFromSsr(){return this._hydratedFromSsr}addListPath(t){this._listPaths.add(t)}findStateDescriptor(t){return vi(this._state,t)}defineTreeAccessor(t,e){Object.defineProperty(this._state,t,e),"function"==typeof e.get&&this._getterPaths.add(t),"function"==typeof e.set&&this._setterPaths.add(t),this.setPathInfo(t,"prop","internal")}get getterPaths(){return this._getterPaths}get setterPaths(){return this._setterPaths}get loopContextStack(){return this._loopContextStack}get dynamicDependency(){return this._dynamicDependency}get staticDependency(){return this._staticDependency}get version(){return this._version}get stateGeneration(){return this._stateGeneration}get rootNode(){return null===this._rootNode&&Z("State rootNode is not available."),this._rootNode}get boundComponentStateProp(){return this._boundComponentStateProp}get hasMounts(){return this._hasMounts}markHasMounts(){this._hasMounts=!0,this._attachScopeHooks("bind-component")}get hasGraftedVolumes(){return this._hasGraftedVolumes}get addressHooks(){return this._addressHooks}attachAddressHooks(t,e){const n=function(t,e){const n=Va.get(t);return void 0===n&&Z(Vi(t,`"${e}"`)),n}(t,e);null===this._addressHooks&&(this._addressHooks={read:[],readMissing:[],write:[],writeMissing:[],writeObserve:[],written:[],swapped:[],get:[],indexShift:[],handlerScope:[],updated:[],suppressPathDiagnostic:[],rowReused:[]}),function(t,e){for(let n=0;n<Ga.length;n++){const o=Ga[n],s=e[o];if(void 0===s)continue;const r=t[o];r.includes(s)||r.push(s)}}(this._addressHooks,n)}markHasGraftedVolumes(){this._hasGraftedVolumes=!0,this._attachScopeHooks("mount")}markHasVolume(){this._attachScopeHooks("mount")}_attachScopeHooks(t){this.attachAddressHooks("scopes",t)}get bindableEventMap(){return this._bindableEventMap}get commandTokenNames(){return this._commandTokenNames}get eventTokenNames(){return this._eventTokenNames}setBindableEventMap(t){this._bindableEventMap=t,this.attachAddressHooks("dcc",O)}_addDependency(t,e,n){const o=t.get(e);return void 0===o?(t.set(e,[n]),!0):!o.includes(n)&&(o.push(n),!0)}addDynamicDependency(t,e){return this._addDependency(this._dynamicDependency,t,e)}addStaticDependency(t,e){return this._addDependency(this._staticDependency,t,e)}setPathInfo(t,e,n="binding"){if("internal"!==n){const o=this._pathRegistrations.get(t);void 0===o?this._pathRegistrations.set(t,{bindingType:e,bound:"binding"===n}):"for"!==o.bindingType&&this._pathRegistrations.set(t,{bindingType:e,bound:o.bound||"binding"===n})}if("for"===e&&(this._listPaths.add(t),this._elementPaths.add(t+"."+l)),!this._pathSet.has(t)){const e=nt(t);if(this._pathSet.add(t),Yl?.check(this,this.__state,t,n),null!==e.parentPath){let t=e;for(;null!==t.parentPath&&this.addStaticDependency(t.parentPath,t.path);)t=nt(t.parentPath)}}}_rebuildPathInfo(){for(const[t,e]of Array.from(this._pathRegistrations))e.bound&&!this._generatedPaths.has(t)&&this.setPathInfo(t,e.bindingType)}_createState(t,e,n){try{const o=function(t,e,n){const o=new ql(t,n);return new Proxy(e,o)}(t,this._state,e);return n(o)}finally{}}async createStateAsync(t,e){return await this._createState(this.rootNode,t,e)}createState(t,e){this._createState(this.rootNode,t,e)}nextVersion(){return this._version++,this._version}get hasUpdatedCallback(){return this._hasUpdatedCallback}get hasErrorCallback(){return this._hasErrorCallback}get crossRowListPaths(){return this._crossRowListPaths}addCrossRowListPath(t){this._crossRowListPaths.add(t)}get indexDependentGetterPaths(){return this._indexDependentGetterPaths}addIndexDependentGetterPath(t){this._indexDependentGetterPaths.add(t)}setInitialState(t){if(!this._initialized)return this._initializeFailed&&Z(`<${o.tagNames.state}> failed to initialize (the diagnostic was reported when it connected), so its state cannot be replaced. Remove this element and create a new one with the corrected state.`),void this._resolveSetState?.(t);!function(t){for(let e=0;e<Vl.length;e++)Vl[e].replacingState?.(t)}(this),(this._hasGraftedVolumes||this._hasMounts)&&Z("Cannot replace the whole state of a tree that has grafted volumes or mounted components: re-setting would silently drop grafted data, tree accessors and mount ledgers (D22). Write the changed paths instead.");const e=this.__state;this._state=t;const n=function(t){const e=new Set;for(const n of t)if(void 0!==n)for(const[t,o]of Object.entries(Xl(n)))t.startsWith("$")||t.includes(l)||"function"==typeof o.value||e.add(t);return e}([e,t]);null!==this._rootNode?this._reapplyBindings(n):this._pendingReapplyPaths=new Set([...this._pendingReapplyPaths??[],...n])}_reapplyBindings(t){!function(t,n,o){const s=new Map;for(const t of o){const e=nt(t);if(null===e.lastWildcardPath)continue;const n=s.get(e.lastWildcardPath);void 0===n?s.set(e.lastWildcardPath,[e]):n.push(e)}const r=[],i=new Set,a=e=>{const n=Ue(t,e);if(i.has(n))return;i.add(n);const o=dn(n);if(o instanceof Set?r.push(...o):void 0!==o&&r.push(o),null!==e.listIndex){const t=s.get(e.pathInfo.path);if(void 0!==t)for(const n of t)a(mn(n,e.listIndex))}};ke();try{if(t.createState("readonly",e=>{for(const o of n){const n=mn(nt(o),null);a(n);try{Pl(t,n,t.staticDependency,t.dynamicDependency,t.listPaths,e,"new",a)}catch{}}}),0===r.length)return;const o=function(t){const e=[],n=[];for(const o of t)Zl.has(o.bindingType)?e.push(o):n.push(o);return e.sort((t,e)=>0!==(t.replaceNode.compareDocumentPosition(e.replaceNode)&Node.DOCUMENT_POSITION_FOLLOWING)?-1:1),e.concat(n)}(r),s=()=>{Bi(o,void 0,{updatedCallback:!1})};if(e())return void s();const i=js("state",s);void 0!==i&&i.catch(Fs)}finally{Ie()}}(this,t,this._pathRegistrations.keys())}}const ec=[];function nc(t,e){const r=function(t){const e=function(){const t=document.documentElement?.lang;if(t)try{return Intl.getCanonicalLocales(t),t}catch{return void console.warn(`[@wcstack/state] <html lang="${t}"> is not a valid BCP-47 language tag. Falling back to the default locale for filters.`)}}();return void 0===e?t:{...t,locale:e}}(t);var i;r&&((i=r).tagNames&&Object.assign(n.tagNames,i.tagNames),"string"==typeof i.bindAttributeName&&(n.bindAttributeName=i.bindAttributeName),"string"==typeof i.commentTextPrefix&&(n.commentTextPrefix=i.commentTextPrefix),"string"==typeof i.commentForPrefix&&(n.commentForPrefix=i.commentForPrefix),"string"==typeof i.commentIfPrefix&&(n.commentIfPrefix=i.commentIfPrefix),"string"==typeof i.commentElseIfPrefix&&(n.commentElseIfPrefix=i.commentElseIfPrefix),"string"==typeof i.commentElsePrefix&&(n.commentElsePrefix=i.commentElsePrefix),"string"==typeof i.locale&&(n.locale=i.locale),"boolean"==typeof i.debug&&(n.debug=i.debug),"boolean"==typeof i.enableMustache&&(n.enableMustache=i.enableMustache),"boolean"==typeof i.enableDirectionalInitialSync&&(n.enableDirectionalInitialSync=i.enableDirectionalInitialSync),"boolean"==typeof i.enablePropagationContext&&(n.enablePropagationContext=i.enablePropagationContext),"boolean"==typeof i.enableContractAnalyzer&&(n.enableContractAnalyzer=i.enableContractAnalyzer),"boolean"==typeof i.sameValueGuard&&(n.sameValueGuard=i.sameValueGuard)),function(t=customElements){for(let e=0;e<ec.length;e++)ec[e](t);t.get(o.tagNames.state)||t.define(o.tagNames.state,tc)}(e),function(){const t=globalThis;void 0===t[s]&&(t[s]=Ca)}()}function oc(t,e){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function sc(t,e){for(const n of t)if(oc(e,n.innerSegments))return n;return null}function rc(t,e){const n=e.slice(t.innerSegments.length);return 0===n.length?t.outerPathInfo.path:t.outerPathInfo.path+a+n.join(a)}let ic=0;const ac=["$watch",z,"$scan","$listKeys",C,"$commandTokens","$eventTokens","$on","$recursion","$errorCallback"],lc=new Set;function cc(t,e){const n=t.stateObject[e];if("function"==typeof n)try{const o=t.component[t.stateProp],s=n.call(o);s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)})}catch(n){console.error(`[@wcstack/state] mounted <${t.component.tagName.toLowerCase()}> ${e} failed.`,n)}}function uc(t){const e=t.indexOf(a);return-1===e?t:t.slice(0,e)}function dc(t,e){const n=sc(t.entries,e);return null===n?null:rc(n,e)}function hc(t,e){return t.markerBasePath+a+e}function fc(t,e,n,o){let s=t.accessorBySuffixByMarkerParent.get(e);void 0===s&&(s=new Map,t.accessorBySuffixByMarkerParent.set(e,s));const r=e+a+n;s.set(n,{accessorName:o,indexShift:nt(r).wildcardCount-nt(o).wildcardCount}),t.getterKeys.has(o)&&(t.parentStateElement.getterPaths?.add(r),t.addedGetterPaths.add(r))}function pc(t,e){return!t.injectedKeys.has(e)&&!t.mappedKeys.has(e)&&("function"==typeof t.stateObject[e]&&!t.getterKeys.has(e)||Object.prototype.hasOwnProperty.call(t.stateObject,e)&&!t.getterKeys.has(e)&&!t.setterKeys.has(e))}function mc(t,e){return`Path "${e}" in <${t.component.tagName.toLowerCase()}> does not resolve: it is not an own key of the component state and no mount entry covers it (mounted prefixes: ${t.entries.filter(t=>t.innerSegments.length>0).map(t=>t.innerSegments.join(a)).join(", ")}). Mount it from the host ("${t.stateProp}: path" / "${t.stateProp}.${uc(e)}: path") or declare the key on the component state.`}const gc=/^\$(\d+)$/;function yc(t,e){const n=e[0];if("$"===n||"#"===n)return null;if(t.getterKeys.has(e)||t.setterKeys.has(e))return null;const o=uc(e);if(t.getterKeys.has(o)||t.setterKeys.has(o)||pc(t,o))return null;const s=function(t,e){return sc(t.entries,e)}(t,e.split(a));return null!==s&&s.readonly?s:null}function bc(t,e){const n=yc(t,e);if(null!==n){const o=0===n.innerSegments.length?"":a+n.innerSegments.join(a);Z(`[wcs/mount-readonly] <${t.component.tagName.toLowerCase()}> cannot write "${e}": it is mounted read-only ("${t.stateProp}${o}#${m}: ${n.outerPathInfo.path}"). Write it on the host, or drop #${m} from the mount.`)}return wc(t,e)}function wc(t,e){const n=e[0];if("$"===n||"#"===n)return e;if(t.getterKeys.has(e)||t.setterKeys.has(e))return function(t,e){const n=e.split(a);let o=-1;for(let t=n.length-1;t>=0;t--)if(n[t]===l){o=t;break}if(-1===o)return fc(t,t.markerBasePath,e,e),hc(t,e);if(pc(t,n[0]))return fc(t,t.markerBasePath,e,e),hc(t,e);const s=n.slice(0,o+1),r=n.slice(o+1),i=dc(t,s);null===i&&Z(mc(t,e)),0===r.length&&Z(`Wildcard-terminal accessor "${e}" on mounted <${t.component.tagName.toLowerCase()}> is not supported: it translates to a marker-terminal path where the mount overlay would shadow the accessor. Declare the row value as a getter on the host tree, or back it with a component-own array (a private key makes the whole path private).`);const c=i+a+t.marker;return fc(t,c,r.join(a),e),c+a+r.join(a)}(t,e);const o=uc(e);if(t.getterKeys.has(o)||t.setterKeys.has(o))return hc(t,e);if(pc(t,o))return hc(t,e);const s=dc(t,e.split(a));if(null!==s)return s;Z(mc(t,e))}function vc(t,e,n,o,s){if(void 0===o)return;const r=nt(n).wildcardCount-nt(e).wildcardCount;return 0===r?o:(s.length<r&&Z(`Cannot resolve "${e}" from this mount: the mounted prefix has ${r} wildcard(s) but the host context provides only ${s.length} index(es).`),[...s.slice(0,r),...o])}const _c=new WeakMap,$c=new WeakMap,Sc=new WeakMap,xc=new FinalizationRegistry(function(t){const e=t.byMarker.get(t.marker);if(void 0!==e&&void 0===e.deref()&&t.byMarker.delete(t.marker),void 0!==t.getterPaths)for(const e of t.addedGetterPaths)t.getterPaths.delete(e)}),Pc=new WeakMap;function Nc(t){return Pc.get(t)??null}let kc=!1;function Ic(t){const e=Sc.get(t);if(void 0===e)return[];const n=[];for(const t of e.values()){const e=t.deref();void 0!==e&&n.push(e)}return n}function Ac(t,e){const n=e.lastIndexOf("#");if(-1===n)return null;const o=Sc.get(t);if(void 0===o)return null;const s=e.indexOf(a,n),r=-1===s?e.slice(n):e.slice(n,s),i=o.get(r);if(void 0===i)return null;const l=i.deref();return void 0===l?(o.delete(r),null):l}const Ec="3.2.0",Cc=/^\s*@@\s*(.*?)\s*:\s*(.+?)\s*$/;function Tc(t,e,n,o){return{node:t,propName:e.propName,statePathName:e.statePathName,bindingType:e.bindingType,inFilters:e.inFilters,outFilters:e.outFilters,origin:n,raw:o}}const Mc="__WCSTACK_DEVTOOLS_HOOK__";const Oc=t=>{null!==ye&&ye({type:"state:update-batch",addresses:t})};function Lc(t){const e=null!==ye;!function(t){ye=t}(t);const n=null!==t;n&&!e?Bs(Oc,0):!n&&e&&function(t){const e=Ws.findIndex(e=>e.listener===t);-1!==e&&Ws.splice(e,1)}(Oc)}function Rc(t){return{rootNode:t.rootNode,element:t,paths:{list:t.listPaths,element:t.elementPaths,getter:t.getterPaths,setter:t.setterPaths},commandTokenNames:t.commandTokenNames,eventTokenNames:t.eventTokenNames,staticDependency:t.staticDependency,dynamicDependency:t.dynamicDependency,watchPaths:t.watchPaths??null,keyedListPaths:void 0===t.listKeys||null===t.listKeys?null:new Set(t.listKeys.keys())}}function jc(t){return ta(t)??Z("devtools: no state tree on this root")}let Wc=null;function Dc(){if(e())return;if(null!==Wc)return;const t={id:"state:"+Math.random().toString(36).slice(2,10),kind:"state",packageVersion:Ec,getStateElements(){const t=[];for(const e of Yi)t.push(Rc(e));return t},overlays:t=>Ic(jc(t)).map(t=>({marker:t.marker,componentTag:t.component.tagName.toLowerCase(),stateProp:t.stateProp,mountTable:t.entries.map(t=>({inner:t.innerSegments.join("."),outer:t.outerPathInfo.path})),delta:t.delta,privateKeys:Object.keys(t.privateSnapshot),getterKeys:[...t.getterKeys],exports:[...t.exports.keys()]})),keyedSubscriptions:t=>function(t){const e=function(t){const e=Us.get(t);return void 0===e?null:{byPath:e.byPath,lastValue:e.lastValue,tracked:e.tracked,watchers:Qs.get(t)}}(t);if(null===e)return[];const n=new Set([...e.byPath.keys(),...e.tracked]);if(void 0!==e.watchers)for(const t of e.watchers.keys())n.add(t);const o=[];for(const t of[...n].sort()){const n=e.byPath.get(t);let s=0;if(void 0!==n)for(const t of n.values())s+=t.size;o.push({path:t,tracked:e.tracked.has(t),rows:s,keys:n?.size??0,lists:e.watchers?.get(t)?.size??0,lastValue:e.lastValue.get(t)})}return o}(jc(t)),keys(t){const e=jc(t),n=[];return e.createState("readonly",t=>{for(const e of Object.keys(t))if(!e.includes("*")&&!e.startsWith("$")){try{if("function"==typeof t[e])continue}catch{}n.push(e)}}),n},read(t,e,n){let o;return jc(t).createState("readonly",t=>{o=t.$resolve(e,n??[])}),o},write(t,e,n,o){jc(t).createState("writable",t=>{void 0!==o&&o.length>0?t.$resolve(e,o,n):t[e]=n})},getDeclaredBindings:t=>function(t){const e=[],n=new Set,s=new Set,r=t=>{const o=function(t){const e=[...t.inFilters,...t.outFilters].map(t=>`${t.filterName}(${t.args.join(",")})`).join("|");return[t.statePathName,t.propName,t.bindingType,e].join("\0")}(t);n.has(o)||(n.add(o),e.push(t))},i=t=>{if(s.has(t))return;s.add(t);const e=aa(t);if(null!==e)for(const t of e.nodeInfos)for(const e of t.parseBindTextResults)r(Tc(null,e,"fragment","")),null!=e.uuid&&i(e.uuid)},a=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);for(let t=a.nextNode();null!==t;t=a.nextNode()){if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.getAttribute(o.bindAttributeName);if(null===n||0===n.length)continue;try{const t=Zt(e,Et(n));for(const o of t)r(Tc(e,o,"attribute",n))}catch{}continue}const e=Cc.exec(t.data.trim());if(null===e)continue;const n=e[1]||o.commentTextPrefix,s=e[2],a=aa(s);if(null===a){if(n===o.commentTextPrefix)try{r(Tc(t,Lt(s),"comment",s))}catch{}}else r(Tc(t,a.parseBindTextResult,"comment",s)),i(s)}return e}(t),_setSink:Lc};Wc=t,function(){const t=globalThis,e=t[Mc];if(void 0!==e)return 2!==e.version&&console.warn(`[wcstack/state] devtools hook registry version mismatch: found ${e.version}, expected 2. Keeping the existing registry (first-wins).`),e;const n=function(){const t=new Map,e=new Set,n=t=>{if(0===e.size)return void t._setSink(null);const n=t.id;t._setSink(t=>{for(const o of e)o.onEvent?.(n,t)})};return{version:2,sources:t,register(o){if(!t.has(o.id)){t.set(o.id,o),n(o);for(const t of e)t.onSourceRegistered?.(o)}},unregister(n){const o=t.get(n);if(void 0!==o){o._setSink(null),t.delete(n);for(const t of e)t.onSourceUnregistered?.(n)}},addListener(o){e.add(o);for(const e of t.values())n(e),o.onSourceRegistered?.(e);return()=>{if(e.delete(o))for(const e of t.values())n(e)}}}}();return t[Mc]=n,n}().register(t)}const zc={name:"devtools",install(){Dc()}},Bc=Object.freeze({existence:"unknown",missingSegment:"",candidates:Object.freeze([])}),Fc=Object.freeze({existence:"exists",missingSegment:"",candidates:Object.freeze([])}),Hc=new WeakMap,qc=new WeakMap,Uc=new WeakSet,Gc=new WeakMap;function Vc(t,e,n,o){console.warn(`[@wcstack/state] [${$i[n]}] ${Si[n]} "${e}" does not resolve on the state tree: "${o.missingSegment}" is not declared.${rt(o.missingSegment,o.candidates)} Updates to this path will be silently dropped.${it}`),null!==ye&&ye({type:"state:path-unresolved",source:n,path:e,missingSegment:o.missingSegment})}const Kc={check:function(t,e,n,o){if("internal"===o||void 0===e)return;if(n.startsWith("$"))return;if(-1!==n.indexOf("#"))return;const s=t.addressHooks;if(s){const e=s.suppressPathDiagnostic;for(let o=0;o<e.length;o++)if(e[o](t,n))return}const r=nt(n).segments;if("binding"===o&&r.length<2)return;if(function(t,e){let n=Hc.get(t);return void 0===n&&(n=new Set,Hc.set(t,n)),!!n.has(e)||(n.add(e),!1)}(t,n))return;if(!0===t.hasRecursion&&null!==t.recursionRegistry.recursiveGetterOwning(n))return;const i=function(t,e,n){if(void 0!==vi(t,e))return Fc;const o=nt(e).segments;let s=t,r="";for(let e=0;e<o.length;e++){const i=o[e],c=r;if(r=0===e?i:r+a+i,e>0&&e<o.length-1&&void 0!==vi(t,r))return Bc;if(Object(s)!==s)return Bc;if(i===l){if(!Array.isArray(s)||0===s.length)return Bc;s=s[0];continue}const u=vi(s,i);if(void 0===u)return{existence:"missing",missingSegment:i,candidates:_i(s,c,n)};if("function"==typeof u.get)return e===o.length-1?Fc:Bc;s=u.value}return Fc}(e,n,t.getterPaths);"missing"===i.existence&&(function(t,e){return!0===Gc.get(t)?.has(e)}(t,n)||("binding"!==o?Vc(0,n,o,i):function(t,e,n){let o=qc.get(t);void 0===o&&(o=new Map,qc.set(t,o)),o.set(e,n),Uc.has(t)||(Uc.add(t),setTimeout(()=>function(t){Uc.delete(t);const e=qc.get(t);if(void 0!==e){qc.delete(t);for(const[t,n]of e)Vc(0,t,"binding",n)}}(t),0))}(t,n,i)))},reset:function(t){Hc.delete(t),qc.delete(t)},markExported:function(t,e){let n=Gc.get(t);void 0===n&&(n=new Set,Gc.set(t,n)),n.add(e),qc.get(t)?.delete(e)}};let Jc=!1;const Qc={name:"diagnostics",install(){Jc||(Jc=!0,Yl=Kc)}};function Xc(t){Z(`filter ${t} requires at least one option`)}function Yc(t){Z(`filter ${t} requires a number as option`)}function Zc(t){Z(`filter ${t} requires a number value`)}function tu(t){Z(`filter ${t} requires a date value`)}const eu={inc:"add",dec:"sub",fix:"toFixed",uc:"upper",lc:"lower",cap:"capitalize",rep:"repeat",rev:"reverse",pad:"padStart",null:"nullIfEmpty"};function nu(t){return!(!t||isNaN(Number(t)))}const ou={eq:(t,e)=>{const n=t?.[0]??Xc("eq"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?(nu(n)||Yc("eq"),t===Number(n)):"string"==typeof t?t===n:t===o},ne:(t,e)=>{const n=t?.[0]??Xc("ne"),o=void 0!==e&&e.length>0?e[0]:n;return t=>"number"==typeof t?(nu(n)||Yc("ne"),t!==Number(n)):"string"==typeof t?t!==n:t!==o},not:t=>t=>("boolean"!=typeof t&&Z("filter not requires a boolean value"),!t),lt:t=>{const e=t?.[0]??Xc("lt");return nu(e)||Yc("lt"),t=>("number"!=typeof t&&Zc("lt"),t<Number(e))},le:t=>{const e=t?.[0]??Xc("le");return nu(e)||Yc("le"),t=>("number"!=typeof t&&Zc("le"),t<=Number(e))},gt:t=>{const e=t?.[0]??Xc("gt");return nu(e)||Yc("gt"),t=>("number"!=typeof t&&Zc("gt"),t>Number(e))},ge:t=>{const e=t?.[0]??Xc("ge");return nu(e)||Yc("ge"),t=>("number"!=typeof t&&Zc("ge"),t>=Number(e))},add:t=>{const e=t?.[0]??Xc("add");return nu(e)||Yc("add"),t=>("number"!=typeof t&&Zc("add"),t+Number(e))},sub:t=>{const e=t?.[0]??Xc("sub");return nu(e)||Yc("sub"),t=>("number"!=typeof t&&Zc("sub"),t-Number(e))},mul:t=>{const e=t?.[0]??Xc("mul");return nu(e)||Yc("mul"),t=>("number"!=typeof t&&Zc("mul"),t*Number(e))},div:t=>{const e=t?.[0]??Xc("div");return nu(e)||Yc("div"),t=>("number"!=typeof t&&Zc("div"),t/Number(e))},mod:t=>{const e=t?.[0]??Xc("mod");return nu(e)||Yc("mod"),t=>("number"!=typeof t&&Zc("mod"),t%Number(e))},abs:t=>t=>("number"!=typeof t&&Zc("abs"),Math.abs(t)),clamp:t=>{const e=t?.[0]??Xc("clamp");nu(e)||Yc("clamp");const n=t?.[1]??Xc("clamp");nu(n)||Yc("clamp");const o=Number(e),s=Number(n);return t=>("number"!=typeof t&&Zc("clamp"),Math.min(Math.max(t,o),s))},toFixed:t=>{const e=t?.[0]??"0";return nu(e)||Yc("toFixed"),t=>("number"!=typeof t&&Zc("toFixed"),t.toFixed(Number(e)))},locale:t=>{const e=t?.[0];return t=>("number"!=typeof t&&Zc("locale"),t.toLocaleString(e??o.locale))},upper:t=>t=>String(t).toUpperCase(),lower:t=>t=>String(t).toLowerCase(),capitalize:t=>t=>{const e=String(t);return 0===e.length?e:1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)},trim:t=>t=>String(t).trim(),slice:t=>{const e=[],n=t?.[0]??Xc("slice");nu(n)||Yc("slice"),e.push(Number(n));const o=t?.[1];return void 0!==o&&(nu(o)||Yc("slice"),e.push(Number(o))),t=>String(t).slice(...e)},substr:t=>{const e=t?.[0]??Xc("substr");nu(e)||Yc("substr");const n=t?.[1]??Xc("substr");return nu(n)||Yc("substr"),t=>String(t).substr(Number(e),Number(n))},padStart:t=>{const e=t?.[0]??Xc("padStart");nu(e)||Yc("padStart");const n=t?.[1]??"0";return t=>String(t).padStart(Number(e),n)},padEnd:t=>{const e=t?.[0]??Xc("padEnd");nu(e)||Yc("padEnd");const n=t?.[1]??" ";return t=>String(t).padEnd(Number(e),n)},repeat:t=>{const e=t?.[0]??Xc("repeat");return nu(e)||Yc("repeat"),t=>String(t).repeat(Number(e))},reverse:t=>t=>String(t).split("").reverse().join(""),truncate:t=>{const e=t?.[0]??Xc("truncate");nu(e)||Yc("truncate");const n=Number(e),o=t?.[1]??"…";return t=>{const e=String(t);return e.length<=n?e:e.slice(0,n)+o}},join:t=>{const e=t?.[0]??", ";return t=>(Array.isArray(t)||Z("filter join requires an array value"),t.join(e))},int:t=>t=>parseInt(String(t),10),float:t=>t=>parseFloat(String(t)),round:t=>{const e=t?.[0]??"0";return nu(e)||Yc("round"),t=>{"number"!=typeof t&&Zc("round");const n=Math.pow(10,Number(e));return Math.round(t*n)/n}},floor:t=>{const e=t?.[0]??"0";return nu(e)||Yc("floor"),t=>{"number"!=typeof t&&Zc("floor");const n=Math.pow(10,Number(e));return Math.floor(t*n)/n}},ceil:t=>{const e=t?.[0]??"0";return nu(e)||Yc("ceil"),t=>{"number"!=typeof t&&Zc("ceil");const n=Math.pow(10,Number(e));return Math.ceil(t*n)/n}},percent:t=>{const e=t?.[0]??"0";return nu(e)||Yc("percent"),t=>("number"!=typeof t&&Zc("percent"),`${(100*t).toFixed(Number(e))}%`)},unit:t=>{const e=t?.[0]??Xc("unit");return t=>null==t?t:String(t)+e},date:t=>{const e=t?.[0];return t=>(t instanceof Date||tu("date"),t.toLocaleDateString(e??o.locale))},time:t=>{const e=t?.[0];return t=>(t instanceof Date||tu("time"),t.toLocaleTimeString(e??o.locale))},datetime:t=>{const e=t?.[0];return t=>(t instanceof Date||tu("datetime"),t.toLocaleString(e??o.locale))},ymd:t=>{const e=t?.[0]??"-";return t=>{t instanceof Date||tu("ymd");const n=t.getFullYear().toString(),o=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},hms:t=>{const e=t?.[0]??":";return t=>{t instanceof Date||tu("hms");const n=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${n}${e}${o}${e}${s}`}},falsy:t=>t=>!t,truthy:t=>t=>!!t,defaults:(t,e)=>{const n=t?.[0]??Xc("defaults"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t||o},coalesce:(t,e)=>{const n=t?.[0]??Xc("coalesce"),o=void 0!==e&&e.length>0?e[0]:n;return t=>t??o},boolean:t=>t=>Boolean(t),number:t=>t=>Number(t),string:t=>t=>String(t),nullIfEmpty:t=>t=>""===t?null:t},su={eq:[1,1],not:[0,0],ne:[1,1],lt:[1,1],le:[1,1],gt:[1,1],ge:[1,1],add:[1,1],sub:[1,1],mul:[1,1],div:[1,1],mod:[1,1],abs:[0,0],clamp:[2,2],toFixed:[0,1],locale:[0,1],upper:[0,0],lower:[0,0],capitalize:[0,0],trim:[0,0],slice:[1,2],substr:[1,2],padStart:[1,2],padEnd:[1,2],repeat:[1,1],reverse:[0,0],truncate:[1,2],join:[0,1],int:[0,0],float:[0,0],round:[0,1],floor:[0,1],ceil:[0,1],percent:[0,1],unit:[1,1],date:[0,0],time:[0,0],datetime:[0,0],ymd:[0,1],hms:[0,1],falsy:[0,0],truthy:[0,0],defaults:[1,1],coalesce:[1,1],boolean:[0,0],number:[0,0],string:[0,0],nullIfEmpty:[0,0]},ru=ou,iu=ou;let au=!1;const lu={name:"formats",install(){au||(au=!0,ft("input",iu,su,eu),ft("output",ru,su,eu))}};function cu(t){return-1!==t.indexOf(q)}function uu(t,e){if(e===t.recursiveAnchor)return"";const n=t.recursiveAnchor+a;if(!e.startsWith(n))return null;const o=e.slice(t.recursiveAnchor.length);if(cu(o))return null;const s=o.slice(1).split(a);return s[0]===l||s.some(t=>0===t.length)?null:o}function du(t){return 0===t.length?t:a+pu(t.slice(1))}function hu(t,e,n){const o=a+t.repeat,s=e.length<=n.length?e:n,r=e.length<=n.length?n:e;if(!r.endsWith(s))return!1;const i=r.slice(0,r.length-s.length);if(0===i.length)return!0;if(i.length%o.length!==0)return!1;for(let t=0;t<i.length;t+=o.length)if(!i.startsWith(o,t))return!1;return!0}function fu(t,e,n){for(let o=n.length;o>0;o=n.lastIndexOf(a,o-1))if(hu(t,e,n.slice(0,o)))return!0;return!1}function pu(t){const e=t.split(a);for(let t=0;t<e.length;t++)e[t]===l||Number.isNaN(Number(e[t]))||(e[t]=l);return e.join(a)}function mu(t,e){const n=t.repeat.split(a),o=a+t.repeat;let s=e;for(;s.startsWith(o);)s=s.slice(o.length);if(0===s.length||s===a+t.repeatList+a+"length")return!0;for(let t=1;t<n.length;t++)if(s===a+n.slice(0,t).join(a))return!0;return!1}function gu(t,e,n){n<0&&Z(`Recursion depth must not be negative (got ${n}).`);let o=t.anchor;for(let e=0;e<n;e++)o+=a+t.repeat;const s=o+e;let r=0;for(const t of s.split(a))t===l&&r++;return r>c&&Z(`[wcs/recursion-depth-exceeded] Recursion on "${t.anchor}" reached depth ${n} ("${s}"), which needs ${r} wildcard levels — the limit is 128. Either the data nests deeper than the engine can address, or the tree contains a cycle.`),s}function yu(t,e){return gu(t,"",e)}function bu(t,e,n){if(!n.startsWith(t.anchor))return null;if(e.length>0&&!n.endsWith(e))return null;if(n.length<t.anchor.length+e.length)return null;const o=n.slice(t.anchor.length,n.length-e.length);if(0===o.length)return 0;const s=a+t.repeat;let r=0,i=0;for(;i<o.length;){if(!o.startsWith(s,i))return null;i+=s.length,r++}return r}function wu(t,e,n){const o=t.recursionRegistry,s=uu(o.spec,n);null===s&&Z(Pi(n,o.spec.recursiveAnchor));const r=function(t,e){if(0===t.addressStackLength)return null;const n=t.lastAddressStack;if(null===n)return null;const o=e.accessorFor(n.pathInfo.path);return null!==o?o.depth:function(t,e){const n=t.spec;if(!e.startsWith(n.anchor))return null;const o=a+n.repeat;let s=0,r=n.anchor.length;for(;e.startsWith(o,r);)r+=o.length,s++;return r!==e.length&&46!==e.charCodeAt(r)?null:s}(e,n.pathInfo.path)}(e,o);return null===r&&Z(`[wcs/recursion-context] "${n}" uses "**", which is bound to the depth of the recursive getter being evaluated, and there is no recursion context here. Read it from inside a recursive getter or a row getter under "${o.spec.anchor}", or name a concrete depth (for example "${o.spec.anchor}${n.slice(o.spec.recursiveAnchor.length)}"). The depth comes from the innermost frame only: a plain getter reached from a recursive getter has no row of its own, so read "**" in the recursive getter and pass the value on.`),o.concretePathAt(s,r)}function vu(t,e,n,o,s){const r=o.spec,i=[],l=new Map,c=[],u=r.repeatList,d=r.anchorList,h=new Set,f=new Set,p=(t,e,n)=>{const o=t.wildcardParentPathInfos;if(e>=o.length)return void i.push(mn(t,n));const s=m(o[e],n,null).rows;for(let n=0;n<s.length;n++)p(t,e+1,s[n])};function m(o,s,i){const a=mn(o,s),c=Ue(n.stateElement,a),d=cl(t,a,e,n),f=null===i?null:((t,e,n)=>{if(!Array.isArray(e)||0===e.length)return null;const o=e;return h.has(o)&&Z(`[wcs/recursion-cycle] "${t}" is reachable from itself: the recursion on "${r.anchor}" walked into a list that one of its own ancestors already owns. The data contains a cycle, which this version does not support.`),n.has(o)&&Z(`[wcs/recursion-shared-list] "${t}" is the same array instance as a list reached from another node. The recursion on "${r.anchor}" needs a tree: give each node its own "${u}" array.`),o})(o.path,d,i),p=vr(s,Pe(c),d);return l.set(c,Array.isArray(d)?d:[]),null!==f&&null!==i&&i.add(f),{rows:p.newIndexes,tracked:f}}const g=(t,e,n)=>{const{rows:r,tracked:l}=m(e,n,f);if(0===r.length)return;const d=(t=>{const e=c[t];if(void 0!==e)return e;const n=o.concretePathAt(s,t),r=0===s.length?n:o.concretePathAt("",t),i={nodePath:r,concretePathInfo:nt(n),childListPathInfo:nt(r+a+u)};return c[t]=i,i})(t),y=l;h.add(y);const b=d.concretePathInfo.wildcardCount===t+1;for(let e=0;e<r.length;e++){const n=r[e];b?i.push(mn(d.concretePathInfo,n)):p(d.concretePathInfo,t+1,n),g(t+1,d.childListPathInfo,n)}h.delete(y)};g(0,nt(d),null);for(const[t,e]of l)Ne(t,e);return i}const _u={write(t,e){if(!0!==t.hasRecursion)return Ua;const n=t.recursionRegistry.recursiveGetterOwningPath(e.pathInfo);return null!==n&&Z(`[wcs/recursion-readonly] "${e.pathInfo.path}" writes into the recursive getter "${n}" (this path is that getter at one depth, or a path inside the value it derives), which has no setter. Write the values it derives from instead.`),Ua},get(t,e,n,o){if(!0!==t.stateElement.hasRecursion)return Ua;if("$getAll"===e)return(e,s)=>{if(cu(e)){if(void 0!==s)return function(t,e,n,o,s){const r=n.stateElement.recursionRegistry,i=uu(r.spec,o);null===i&&Z(Pi(o,r.spec.recursiveAnchor)),Array.isArray(s)||Z(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes either no indexes (to read the depth of the recursive getter being evaluated) or [] (to walk every depth) — got ${null===s?"null":typeof s}.`),s.length>0&&Z(`[wcs/recursion-getall-form] $getAll("${o}", indexes) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Omit the indexes to read the depth of the recursive getter being evaluated, or pass [] to walk every depth.`);const a=vu(t,e,n,r,i),l=[];for(let o=0;o<a.length;o++)l.push(cl(t,a[o],e,n));return l}(o,n,t,e,s);e=wu(t.stateElement,t,e)}return Rl(o,0,n,t)(e,s)};if("$setAll"===e)return(e,s,r,i)=>cu(e)?function(t,e,n,o,s,r,i){tl(n);const a=n.stateElement.recursionRegistry,l=uu(a.spec,o);null===l&&Z(Pi(o,a.spec.recursiveAnchor));const c=du(l);Array.isArray(s)||Z(Ni(o,'with "**" requires an explicit empty indexes array ([]) — the write API takes no context.')),s.length>0&&Z(`[wcs/recursion-setall-form] $setAll("${o}", indexes, …) with "**" takes no partial prefix: a prefix cannot say which depth it applies to. Pass [] to broadcast to every depth.`),"function"==typeof r&&Z(Ni(o,'with "**" does not take a mapper yet — the index tuple has a different length at each depth.')),!0===i?.spread&&Z(Ni(o,'with "**" does not take { spread: true } — handing a flat array to a tree needs the author to know the walk order, which is not a usable contract.')),function(t,e,n){mu(t,n)&&Z(`[wcs/recursion-structural-write] "${e}" writes the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). This version broadcasts to leaf properties only — replacing a node would invalidate the child addresses already resolved for this write.`)}(a.spec,o,c);const u=a.conflictingRecursiveGetter(c);null!==u&&Z(`[wcs/recursion-readonly] "${o}" writes into the recursive getter "${u}", which has no setter — the two name the same family of concrete paths (or this path points inside the value that getter derives). Write the values it derives from instead.`);const d=vu(t,e,n,a,l);let h=0;for(let o=0;o<d.length;o++)void 0!==r&&(Ml(t,d[o],r,e,n),h++);return h}(o,n,t,e,s,r,i):Wl(o,0,n,t)(e,s,r,i);if(36!==e.charCodeAt(0)&&cu(e)){const s=ol(wu(t.stateElement,t,e)),r=jl(o,s,n,t);return cl(o,mn(s.pathInfo,r),n,t)}return Ua}};let $u=!1;function Su(t,e){"string"==typeof e&&0!==e.length||Z(`[wcs/recursion-declaration-invalid] ${H} ${t} must be a non-empty string.`);const n=e.split(a);n.some(t=>0===t.length)&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain empty path segments.`),n.length<2&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must name a list element: a property path ending with "${a}${l}" (for example "nodes${a}${l}").`),n[n.length-1]!==l&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must end with "${a}${l}" — it names the element of the list, not the list itself.`),36===n[0].charCodeAt(0)&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not start with "$" — that namespace is reserved.`),-1!==e.indexOf("#")&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain "#" — that segment is reserved for mounts.`);for(let o=0;o<n.length-1;o++)n[o]===l&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must have exactly one "${l}", at the end. Wildcards in the middle are not supported in this version.`),n[o]===q&&Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain "${q}" — the declaration is what gives "${q}" its meaning.`),isNaN(Number(n[o]))||Z(`[wcs/recursion-declaration-invalid] ${H} ${t} "${e}" must not contain an index segment ("${n[o]}") — the recursion is declared over the shape of the tree, not over one row.`)}const xu=new WeakSet;function Pu(t){return"function"==typeof t.get&&xu.has(t.get)}const Nu="[wcs/recursion-declaration-invalid]";class ku{spec;_definitions=new Map;_accessors=new Map;_ownerByPath=new Map;_ownerByPathInfo=new WeakMap;_accessorByPathInfo=new WeakMap;_concreteBySuffix=new Map;_registeredListPaths=new Set;constructor(t,e){this.spec=t;const n=Xl(e);for(const[e,o]of Object.entries(n)){if(!cu(e))continue;"function"==typeof o.set&&Z(`${Nu} Recursive setters are not supported in this version: "${e}". Declare a plain path setter, or write through the concrete path.`),"function"!=typeof o.get&&Z(`${Nu} "${e}" contains "**" but is not a getter. The recursion wildcard only names a family of computed paths.`);const n=uu(t,e);null===n&&Z(Pi(e,t.recursiveAnchor)),0===n.length&&Z(`${Nu} "${e}" names the recursive node itself. "**" names a computed path under a node (for example "${t.recursiveAnchor}${a}total"), not the node.`),mu(t,du(n))&&Z(`${Nu} "${e}" names the recursion structure itself (a node, its "${t.repeatList}" list or that list's length, or an object on the way to that list). A recursive getter would hide the real child list at every depth — "**" names a computed leaf under a node (for example "${t.recursiveAnchor}${a}total").`),this._definitions.set(e,{recursivePath:e,suffix:n,get:o.get})}this._assertNoColliding(),this._assertNoConcreteCollision(n)}_assertNoConcreteCollision(t){for(const[e,n]of Object.entries(t)){if(cu(e)||Pu(n))continue;const t=this._matchExpansion(e);null!==t&&Z(`${Nu} "${e}" is already defined on the state, so the recursive getter "${t}" cannot expand to it. Rename one of them.`)}}_assertNoColliding(){const t=Array.from(this._definitions.values());for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++)hu(this.spec,t[e].suffix,t[n].suffix)&&Z(`${Nu} "${t[e].recursivePath}" and "${t[n].recursivePath}" expand to the same concrete path at different depths (they differ by whole repetitions of "${this.spec.repeat}"). Rename one of them.`)}get hasDefinitions(){return this._definitions.size>0}conflictingRecursiveGetter(t){for(const e of this._definitions.values())if(fu(this.spec,e.suffix,t))return e.recursivePath;return null}recursiveGetterOwningPath(t){const e=this._ownerByPathInfo.get(t);if(void 0!==e)return e;const n=this.recursiveGetterOwning(t.path);return this._ownerByPathInfo.set(t,n),n}recursiveGetterOwning(t){const e=this._accessors.get(t);if(void 0!==e)return e.recursivePath;const n=pu(t),o=this._ownerByPath.get(n);if(void 0!==o)return o;let s=null;if(n.startsWith(this.spec.anchor)){s=this._matchExpansion(n);for(let t=n.lastIndexOf(a);null===s&&t>this.spec.anchor.length;t=n.lastIndexOf(a,t-1))s=this._matchExpansion(n.slice(0,t))}return this._ownerByPath.set(n,s),s}_matchExpansion(t){for(const e of this._definitions.values())if(null!==bu(this.spec,e.suffix,t))return e.recursivePath;return null}materializeForPathInfo(t,e){if(0===this._definitions.size)return null;const n=this._accessorByPathInfo.get(e);if(void 0!==n)return n;const o=this.materializeFor(t,e.path);return this._accessorByPathInfo.set(e,o),o}materializeFor(t,e){const n=this._accessors.get(e);if(void 0!==n)return n;if(!e.startsWith(this.spec.anchor))return null;let o=null,s=0;for(const t of this._definitions.values()){const n=bu(this.spec,t.suffix,e);null!==n&&(null!==o&&Z(`"${e}" matches both "${o.recursivePath}" and "${t.recursivePath}".`),o=t,s=n)}return null===o?null:this._define(t,o,s,e)}_define(t,e,n,o){const s=t.findStateDescriptor(o);void 0===s||Pu(s)||Z(`"${o}" is already defined on the state, so the recursive getter "${e.recursivePath}" cannot expand to it. Rename one of them.`);const r=Object.freeze({recursivePath:e.recursivePath,depth:n}),i=e.get,a=function(){return i.call(this)};var l;return l=a,xu.add(l),t.defineTreeAccessor(o,{get:a,enumerable:!1,configurable:!0}),this._registerListPaths(t,n),this._accessors.set(o,r),r}_registerListPaths(t,e){for(const n of function(t,e){const n=[];n.push(t.anchorList);for(let o=0;o<e;o++)n.push(yu(t,o)+a+t.repeatList);return n}(this.spec,e))this._registeredListPaths.has(n)||(this._registeredListPaths.add(n),t.addListPath(n))}forgetGenerated(t,e){const n=new Set(this._accessors.keys());return function(t,e,n){if(0!==n.size){for(const t of n){const n=Object.getOwnPropertyDescriptor(e,t);void 0!==n&&Pu(n)&&delete e[t]}for(const e of[t.staticDependency,t.dynamicDependency]){for(const t of n)e.delete(t);for(const[t,o]of e){let s=null;for(let t=0;t<o.length;t++)n.has(o[t])?s??=o.slice(0,t):s?.push(o[t]);null!==s&&(0===s.length?e.delete(t):e.set(t,s))}}!function(t,e,n){for(const o of n){const n=nt(o),s=n.wildcardParentPathInfos,r=(e,o,i)=>{if(i===s.length)return void Ms(Ge(t,n,o),null);const a=0===i?0:s[i-1].segments.length+1;let l=e;for(const t of s[i].segments.slice(a))l=l?.[t];if(!Array.isArray(l))return;const c=As(l);if(null===c)return;const u=Math.min(c.length,l.length);for(let t=0;t<u;t++)r(l[t],c[t],i+1)};r(e,null,0)}}(t,e,n)}}(t,e,n),n}concretePathAt(t,e){let n=this._concreteBySuffix.get(t);void 0===n&&(n=[],this._concreteBySuffix.set(t,n));let o=n[e];return void 0===o&&(o=gu(this.spec,t,e),n[e]=o),o}accessorFor(t){return this._accessors.get(t)??null}get materializedPaths(){return new Set(this._accessors.keys())}}const Iu="recursionSpec",Au="recursionRegistry",Eu={order:5,validateEarly(t,e,n){const o=function(t){const e=t[H];if(void 0===e)return null;"object"==typeof e&&null!==e||Z(`[wcs/recursion-declaration-invalid] ${H} must be an object mapping one anchor path to its repeating sub-path (for example { "nodes.*": "children.*" }).`);const n=Object.entries(e);0===n.length&&Z(`[wcs/recursion-declaration-invalid] ${H} must declare exactly one anchor; it is empty.`),n.length>1&&Z(`[wcs/recursion-declaration-invalid] ${H} declares ${n.length} anchors (${n.map(([t])=>`"${t}"`).join(", ")}). This version supports exactly one self-recursive anchor per state.`);const[o,s]=n[0];Su("anchor",o),"string"!=typeof s&&Z(`[wcs/recursion-declaration-invalid] ${H} entry "${o}" must map to the repeating sub-path as a string (for example "children${a}${l}").`),Su("repeating sub-path",s);const r=o.slice(0,o.lastIndexOf(a)),i=s.slice(0,s.lastIndexOf(a)),c=r+a+q;return Object.freeze({anchor:o,repeat:s,recursiveAnchor:c,anchorList:r,repeatList:i})}(e);n.set(Iu,o),n.set(Au,null===o?null:new ku(o,e))},preCommit(t,e,n){const o=t.recursionRegistry;if(null!==o)for(const e of o.forgetGenerated(t,n.get("previousState")))t.addGeneratedPath?.(e);const s=n.get(Au)??null;t.setRecursionRegistry?.(s),null!==s&&t.attachAddressHooks?.("recursion",H)},apply(t,e,n){const o=n.get(Iu)??null;null!==o&&t.addListPath(o.anchorList)}};let Cu=!1;const Tu={name:"recursion",install(){Cu||(Cu=!0,$u||($u=!0,Ka("recursion",_u)),Ya("recursion",Eu))}},Mu={written:function(t,e,n){const o=t.bindableEventMap,s=o[e.path],r="string"==typeof s,i=r?s:e.segments.length>1?o[e.segments[0]]:void 0;if("string"!=typeof i)return;const a=t.rootNode;a instanceof ShadowRoot&&a.host.dispatchEvent(new CustomEvent(i,{detail:r&&void 0!==n?n.value:void 0,bubbles:!0}))}};let Ou=!1;function Lu(t){return function(){const e=this.stateElement;if(!e)return;if(!0!==e.initialized)return;let n;try{e.createState("readonly",e=>{n=e[t]})}catch(e){return void console.warn(`[@wcstack/state] DCC getter "${t}" failed:`,e)}return n}}function Ru(t){return function(e){const n=this.stateElement;n&&(!0!==n.initialized?n.initializePromise.then(()=>{n.createState("writable",n=>{n[t]=e})}):n.createState("writable",n=>{n[t]=e}))}}function ju(t,e){return e?function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createStateAsync("writable",async n=>{o=await n[t](...e)}).then(()=>o)})}:function(...e){const n=this.stateElement;if(n)return n.initializePromise.then(()=>{let o;return n.createState("writable",n=>{o=n[t](...e)}),o})}}function Wu(t){return t.startsWith("$")}function Du(t,e){return Object.keys(t).filter(n=>{if(n.startsWith("$")||"constructor"===n)return!1;const o="function"==typeof t[n].value;return"method"===e?o:!o})}function zu(t,e){const n=t[e];if(void 0===n)return null;Array.isArray(n)||Z(`${e} must be an array of strings.`);const o=[],s=new Set;for(const t of n)"string"==typeof t&&0!==t.length||Z(`${e} entries must be non-empty strings.`),t.startsWith("$")&&Z(`${e} entry "${t}" must not start with "$" (internal properties are not exposed on the component).`),s.has(t)&&Z(`${e} entry "${t}" is duplicated.`),s.add(t),o.push(t);return o}function Bu(t,e,n){const s=t.tagName.toLowerCase();s.includes("-")||Z(`DCC: "${s}" is not a valid custom element name (must contain a hyphen).`);const r=qt(t);null!==r&&"function"==typeof r.define||Z(`DCC: CustomElementRegistry is unavailable for "${s}".`),r.get(s)&&Z(`DCC: "${s}" is already registered. A custom element name can only be defined once.`);const i=document.createElement("template"),a=i.content.ownerDocument;for(const t of Array.from(e.childNodes))i.content.appendChild(a.importNode(t,!0));const l=e.mode,{bindables:c,commands:u,streamBackedBindables:d}=function(t){za(t);const e=zu(t,O)??[],n=zu(t,L)??[],o=Xl(t),s=function(t){const e=t[z];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),r=[];for(const t of e){const e=o[t];if(void 0===e){if(s.has(t)){r.push(t);continue}Z(`${O} entry "${t}" is not declared on the state.${rt(t,Du(o,"value"))}`)}"function"==typeof e.value&&Z(`${O} entry "${t}" is a method. Declare it in ${L} instead.`)}for(const t of n){const e=o[t];void 0===e&&Z(`${L} entry "${t}" is not declared on the state.${rt(t,Du(o,"method"))}`),"function"!=typeof e.value&&Z(`${L} entry "${t}" is not a method. Declare it in ${O} instead.`)}return{bindables:e,commands:n,streamBackedBindables:r}}(n),h=c.length>0||u.length>0?function(t,e,n=[]){const o={protocol:"wc-bindable",version:1,properties:e.map(e=>({name:e,event:`${t}:${e}-changed`,getter:t=>t.target[e]})),inputs:e.map(t=>({name:t}))};if(0===n.length)return o;const s=n.map(t=>({name:t,async:!0}));return{...o,commands:s}}(s,c,u):null,f=c.length>0?function(t,e){const n={};for(const o of e)n[o]=`${t}:${o}-changed`;return n}(s,c):{},p=o.tagNames.state,m=class extends HTMLElement{static template=i;static shadowRootMode=l;static wcBindable=h;static bindableEventMap=f;_shadow=null;_ensureShadow(){if(null!==this._shadow)return this._shadow;if(this.hasAttribute(K))return null;this._shadow=this.attachShadow({mode:m.shadowRootMode}),this._shadow.appendChild(m.template.content.cloneNode(!0));const t=qt(this._shadow);return null!==t&&Ut(t,this._shadow),this._shadow}connectedCallback(){const t=this._ensureShadow();if(null!==t&&Object.keys(m.bindableEventMap).length>0){const e=t.querySelector(p);e?(Ou||(Ou=!0,Ka("dcc",Mu)),e.setBindableEventMap(m.bindableEventMap)):console.warn(`[@wcstack/state] DCC: "${s}" declares ${O} but its template has no <${o.tagNames.state}>. Change events will not be dispatched.`)}}get stateElement(){return this._ensureShadow()?.querySelector(p)??null}},g=Xl(n);for(const[t,e]of Object.entries(g)){if(Wu(t))continue;const n={configurable:!0,enumerable:!0};if("function"==typeof e.value){const o="AsyncFunction"===e.value.constructor?.name;n.value=ju(t,o)}else n.get=Lu(t),n.set=Ru(t);Object.defineProperty(m.prototype,t,n)}for(const t of d)Object.defineProperty(m.prototype,t,{configurable:!0,enumerable:!0,get:Lu(t),set:Ru(t)});r.define(s,m)}const Fu={order:10,connecting(t){const e=t.parentNode;return e instanceof ShadowRoot&&e.host.hasAttribute(K)?async function(t,e,n){const o=t;try{o.hasAttribute("bind-component")&&Z(`"bind-component" cannot be used inside a [${K}] host. DCC state comes from the template, not from a component property.`);const s=await async function(t,e){try{if(t.hasAttribute("src")){const e=t.getAttribute("src");if(e.endsWith(".js"))return await La(e);Z(`DCC: Unsupported src type: ${e}`)}const n=t.querySelector('script[type="module"]');if(n)return await Oa(n,e.tagName.toLowerCase());Z(`DCC: No state source found for "${e.tagName.toLowerCase()}".`)}catch(t){Z(`DCC: Failed to load state: ${t}`)}}(o,e);Bu(e,n,s),t.markTreeless(),t.markInitialized(),t.clearConnectedRootNode(),t.settleInitialization()}catch(e){t.failInitializeLoudly(e)}}(t,e.host,e):null}};let Hu=!1;const qu=new WeakMap;function Uu(t,e,n){let o=qu.get(t);void 0===o&&(o=new Map,qu.set(t,o));null!=o.get(e)&&Z(`Volume slot "${e}" is already mounted on this tree.`),o.set(e,n)}function Gu(t,e){if(null===t)return!1;const n=qu.get(t);if(void 0===n||0===n.size)return!1;for(const t of n.keys())if(e===t||e.startsWith(t+a)||t.startsWith(e+a))return!0;return!1}const Vu=new WeakMap,Ku=[];function Ju(t,e,n,o){if(e.length>0){const s=n.split(a),r=sc(e,s);if(null!==r)return o&&r.readonly&&Z(`[wcs/mount-readonly] volume "${t}" cannot write "${n}": it is injected read-only ("${$}.${r.innerSegments.join(a)}#${m}: ${r.outerPathInfo.path}"). Write "${r.outerPathInfo.path}" on the root, or drop #${m} from the injection.`),rc(r,s)}return t+a+n}function Qu(t,e,n){for(const t of e){const e=t.outerPathInfo.path;if(n===e)return t.innerSegments.join(a);if(n.startsWith(e+a))return t.innerSegments.join(a)+n.slice(e.length)}return n===t?"":n.startsWith(t+a)?n.slice(t.length+1):null}function Xu(t,e,n=Ku){return new Proxy({},{get(o,s){if("string"==typeof s&&"then"!==s){if("$"===s[0]){if("$postUpdate"===s||"$getAll"===s){const o=s;return(s,...r)=>e[o](Ju(t,n,s,!1),...r)}return"$setAll"===s?(o,...s)=>e.$setAll(Ju(t,n,o,!0),...s):"$resolve"===s?(o,...s)=>e.$resolve(Ju(t,n,o,s.length>1),...s):e[s]}return e[Ju(t,n,s,!1)]}},set:(o,s,r)=>("string"!=typeof s||(e[Ju(t,n,s,!0)]=r),!0),has:(t,e)=>"string"==typeof e&&"$"!==e[0]&&"#"!==e[0]})}const Yu=new WeakMap,Zu=[],td=new WeakMap,ed=new WeakSet;function nd(t){console.error(`[@wcstack/state] volume "${t.mountPath}" was not grafted — the root state element on this root node failed to initialize (its own diagnostic is reported separately). The volume is not at fault: fix the root <wcs-state>.`),t.onGrafted(null)}let od=null;const sd=new WeakMap,rd=new Set;function id(t,e,n,o){let s=sd.get(t);if(void 0===s){if(!o)return null;s=new Map,sd.set(t,s)}let r=s.get(e);if(void 0===r){if(!o)return null;r=new Map,s.set(e,r)}let i=r.get(n);if(void 0===i){if(!o)return null;i={holders:new Set,byListIndex:new WeakMap,noIndex:null},r.set(n,i)}return i}function ad(t,e){if(!t.component.isConnected)return!1;const n=me(t.component)?.listIndex??null;if(null===e)return null===n;let o=n;for(;null!==o;){if(o===e)return!0;o=o.parentListIndex}return!1}function ld(t,e,n,o){const s=id(t,e,n,!1);if(null===s)return null;const r=null===o?s.noIndex:s.byListIndex.get(o)??null;if(null!==r){const t=function(t,e){const n=t.ref.deref();return void 0!==n&&ad(n,e)?n:null}(r,o);if(null!==t)return{record:t,entry:r.entry}}let i=null,l=null;for(const t of s.holders){const r=t.ref.deref();void 0!==r?ad(r,o)&&(null!==l&&Z(`[wcs/mount-export-ambiguous] "${e}${a}${n}" is exported by two mounted components on the same instance: <${l.component.tagName.toLowerCase()}> and <${r.component.tagName.toLowerCase()}>. Mount only one of them there, or rename one accessor. See docs/state-overlay-export-design.md X4.`),i=t,l=r):s.holders.delete(t)}return null===i||null===l?null:(null===o?s.noIndex=i:s.byListIndex.set(o,i),{record:l,entry:i.entry})}function cd(t){const e=t.parentStateElement,n=me(t.component);if(!(!1===e.isConnected||t.delta>0&&null===n))for(const o of t.exports.values())e.createState("readonly",t=>{t[Ee](n,()=>{t.$postUpdate(o.exportedPath)})})}const ud=new WeakMap;class dd{record;markerParentPath;listIndex;isBase;receiver;handler;constructor(t,e,n,o,s,r){this.record=t,this.markerParentPath=e,this.listIndex=n,this.isBase=o,this.receiver=s,this.handler=r}accessorNameFor(t){return this.record.accessorBySuffixByMarkerParent.get(this.markerParentPath)?.get(t)?.accessorName}accessorAddress(t){return mn(nt(this.markerParentPath+a+t),this.listIndex)}get(t,e,n){if("string"!=typeof e)return Reflect.get(t,e);if("then"===e)return;if("$"===e[0]){if("$postUpdate"===e)return t=>{this.receiver.$postUpdate(wc(this.record,t))};if("$getAll"===e||"$setAll"===e||"$resolve"===e){const t=this.record,n=this.listIndex?.indexes??[],o=this.receiver;if("$resolve"===e)return(e,s,...r)=>{const i=r.length>0?bc(t,e):wc(t,e),a=vc(0,e,i,s??[],n);return o.$resolve(i,a,...r)};const s=e;return(e,r,...i)=>{const a="$setAll"===s?bc(t,e):wc(t,e),l=vc(0,e,a,r,n);return o[s](a,l,...i)}}return this.receiver[e]}const o=this.accessorNameFor(e);if(void 0!==o){this.handler.pushAddress(this.accessorAddress(e));try{return Reflect.get(this.record.stateObject,o,n)}finally{this.handler.popAddress()}}if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return rl(this.handler,this.accessorAddress(e)),t[e];const o=this.record.stateObject[e];if("function"==typeof o)return o.bind(n)}return this.receiver[wc(this.record,e)]}set(t,e,n,o){if("string"!=typeof e)return Reflect.set(t,e,n);const s=this.accessorNameFor(e);if(void 0!==s){this.record.setterKeys.has(s)||Z(`Cannot write to "${s}" on mounted <${this.record.component.tagName.toLowerCase()}>: the accessor has no setter. Add a setter or write to the underlying state paths instead.`),this.handler.pushAddress(this.accessorAddress(e)),this.handler.beginUntrack();try{return Reflect.set(this.record.stateObject,s,n,o)}finally{this.handler.endUntrack(),this.handler.popAddress()}}return this.isBase&&Object.prototype.hasOwnProperty.call(t,e)?(t[e]=n,!0):(this.receiver[bc(this.record,e)]=n,!0)}has(t,e){if("string"!=typeof e)return Reflect.has(t,e);if("$"===e[0]||"#"===e[0])return!1;if(void 0!==this.accessorNameFor(e))return!0;if(this.isBase){if(Object.prototype.hasOwnProperty.call(t,e))return!0;if("function"==typeof this.record.stateObject[e])return!0}try{return wc(this.record,e),!0}catch{return!1}}}function hd(t,e,n,o){const s=e.pathInfo.path,r=s===t.markerBasePath,i=r?function(t,e){let n=ud.get(t);if(void 0===n&&(n={byListIndex:new WeakMap,noIndex:null},ud.set(t,n)),null===e)return n.noIndex??={...t.privateSnapshot};let o=n.byListIndex.get(e);return void 0===o&&(o={...t.privateSnapshot},n.byListIndex.set(e,o)),o}(t,e.listIndex):{};return new Proxy(i,new dd(t,s,e.listIndex,r,n,o))}function fd(t,e){const n=function(t){return _c.get(t)??null}(e);var o,s;null!==n&&n.stateProp!==t.stateProp&&Z(`A mount scope is already initialized on this component for "${n.stateProp}" — one <wcs-state bind-component> per component (v2). Merge the "${t.stateProp}" wiring into "${n.stateProp}" or split the component.`),null!==n&&os(e).dispose(),function(t,e){kc||(kc=!0,pe=t=>_c.has(t)?t.host:null),_c.set(t,e),Pc.set(e,t);let n=Sc.get(e.parentStateElement);void 0===n&&(n=new Map,Sc.set(e.parentStateElement,n)),n.set(e.marker,new WeakRef(e));let o=$c.get(e.component);void 0===o&&(o=new Map,$c.set(e.component,o));const s=o.get(e.stateProp)!==e;o.set(e.stateProp,e),s&&xc.register(e,{byMarker:n,marker:e.marker,getterPaths:e.parentStateElement.getterPaths,addedGetterPaths:e.addedGetterPaths}),e.parentStateElement.markHasMounts?.()}(e,t),e instanceof ShadowRoot&&function(t,e){const n=Qi.get(t);if(void 0!==n){if(n===e)return;Z("A state tree is already registered on this root.")}Qi.set(t,e)}(e,t.parentStateElement),function(t,e){const n=(e,n)=>function(t,e,n){let o;const s=gc.exec(e.statePathName);if(null!==s){const r=function(t,e){return void 0===e?t.delta:nt(wc(t,e)).wildcardCount-nt(e).wildcardCount}(t,n);o=0===r?e.statePathName:`$${Number(s[1])+r}`}else if(o=wc(t,e.statePathName),"for"===e.bindingType){const n=nt(o).wildcardCount-e.statePathInfo.wildcardCount;t.indexShiftByLoopElementPath.set(o+a+l,n)}const r=e.propModifiers,i=null===s&&Array.isArray(r)&&!r.includes(m)&&null!==yc(t,e.statePathName);return o!==e.statePathName||i?{...e,statePathName:o,statePathInfo:nt(o),...i?{propModifiers:[...r,m]}:{}}:e}(t,e,n);X(e);const o=me(t.component);xa(e instanceof ShadowRoot?e:e.getRootNode(),e,void 0,n),Fi(e,o,n)}(t,e),function(t){if(t.exports.size>0||null===t.rootEntry)return;const e=new Set([...t.getterKeys,...t.setterKeys]);for(const n of e){let e;try{e=wc(t,n)}catch{continue}const o=e.indexOf(a+t.marker);if(-1===o)continue;const s=e.slice(0,o+1+t.marker.length),r=e.slice(s.length+1),i=e.slice(0,o)+a+r,l=nt(i);if(l.wildcardCount!==t.delta)continue;const c={markerTerminalPath:s,suffix:r,markerPath:e,exportedPath:i};t.exports.set(i,c),id(t.parentStateElement,l.parentPath,l.lastSegment,!0).holders.add({ref:new WeakRef(t),entry:c}),t.parentStateElement.addDynamicDependency(e,i),Yl?.markExported(t.parentStateElement,i)}t.parentStateElement.markHasMounts?.()}(t),function(t){const e=me(t.component);if(t.delta>0&&null===e)return;const n=t.component.tagName.toLowerCase();for(const o of t.exports.values()){const s=`${n}|${o.exportedPath}`;if(rd.has(s))continue;const r=nt(o.exportedPath);let i;t.parentStateElement.createState("readonly",t=>{t[Ee](e,()=>{i=t[r.parentPath]})}),null!=i&&r.lastSegment in Object(i)&&(rd.add(s),console.warn(`[@wcstack/state] [wcs/mount-export-shadowed] <${n}>.${t.stateProp}.${o.suffix} is exported at "${o.exportedPath}" but the tree already has that key, so readers outside the component get the tree value. Remove the tree key or rename the accessor. See docs/state-overlay-export-design.md X1.`))}}(t),cd(t),o=e,s=Promise.resolve(),Xi.set(o,s),s.then(()=>oa(o),()=>{})}function pd(t,e){const n=os(e),o=me(t.component);n.forEachActiveBindingNode(t=>ge(t,o)),Bi(n.rebindAddresses()),cd(t)}function md(t,e){for(let n=e.firstNode;null!==n;n=n.nextSibling){if(n===t||n.contains(t))return!0;if(n===e.lastNode)break}return!1}const gd={read(t,e,n,o){if(!0===t.hasMounts&&35===e.pathInfo.lastSegment.charCodeAt(0)){const s=Ac(t,e.pathInfo.path);if(null!==s)return hd(s,e,n,o)}return Ua},readMissing(t,e,n,o,s){if(null===n){if(Gu(t.rootNode??null,e.pathInfo.path))return;return Ua}if(!0===t.hasMounts){const n=ld(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s){const r=hd(t,mn(nt(e.markerTerminalPath),n),o,s);return Reflect.get(r,e.suffix)}(n.record,n.entry,e.listIndex,o,s)}return Ua},write(t,e){if(!0===t.hasGraftedVolumes){const n=e.pathInfo.path,o=function(t,e){const n=Vu.get(t);if(void 0===n||0===n.size)return null;const o=e+a;for(const t of n)if(t.startsWith(o))return t;return null}(t,n);null!==o&&Z(`Cannot replace "${n}" wholesale: a volume is mounted at "${o}" under it (D22). Replacing an ancestor of a mount point silently discards the grafted data while its accessors remain. Write "${o}" itself, or individual fields inside "${n}", instead.`)}return Ua},writeMissing(t,e,n,o,s,r,i){if(!0===t.hasMounts){const n=ld(t,e.parentAddress.pathInfo.path,e.pathInfo.lastSegment,e.listIndex);if(null!==n)return function(t,e,n,o,s,r){const i=hd(t,mn(nt(e.markerTerminalPath),n),s,r);return Reflect.set(i,e.suffix,o)}(n.record,n.entry,e.listIndex,s,r,i)}return Ua},indexShift(t,e){const n=t.stateElement,o=e.pathInfo.path;if(!0===n.hasMounts&&-1!==o.indexOf("#")){const t=Ac(n,o);if(null!==t)return function(t,e){const n=e.lastIndexOf("#");if(-1===n)return t.delta;const o=e.indexOf(a,n);if((-1===o?e.slice(n):e.slice(n,o))!==t.marker)return t.delta;const s=-1===o?e:e.slice(0,o),r=-1===o?"":e.slice(o+1),i=t.accessorBySuffixByMarkerParent.get(s)?.get(r);return void 0!==i?i.indexShift:t.delta}(t,o)}return 0},handlerScope(t,e,n,o,s){if(!0!==t.hasMounts)return s;const r=function(t,e){let n=t;for(;null!==n&&n!==e;){const t=_c.get(n);if(void 0!==t)return t;n=n.parentNode}return _c.get(e)??null}(e,n);if(null===r)return s;const i=r.indexShiftByLoopElementPath.get(o.pathInfo.path);return void 0!==i?s-i:0},updated(t,e,n){const o=function(t){return Yu.get(t)??Zu}(t);for(const s of o){const o=new Set,r={};for(const n of e){if(n.absolutePathInfo.stateElement!==t)continue;const e=n.absolutePathInfo.pathInfo.path;if(-1!==e.indexOf("#"))continue;const i=Qu(s.mountPath,s.injections,e);if(null===i||""===i)continue;o.add(i);const a=n.absolutePathInfo.pathInfo.wildcardCount;if(a>0&&null!==n.listIndex){const t=Ze(n.listIndex,a);(r[i]??=[]).push(t)}}if(o.size>0)try{s.callback.call(Xu(s.mountPath,n,s.injections),Array.from(o),r)}catch(t){console.error(`[@wcstack/state] volume "${s.mountPath}" $updatedCallback threw.`,t)}}},suppressPathDiagnostic:(t,e)=>Gu(!1===t.isConnected?null:t.rootNode??null,e),rowReused(t,e){!function(t,e){if(function(t){const e=Sc.get(t);return void 0!==e&&e.size>0}(e))for(const n of Ic(e)){if(!md(n.component,t))continue;const e=Nc(n);null!==e&&pd(n,e)}}(e,t)}};let yd=!1;const bd=new WeakMap;function wd(t){let e=bd.get(t);return void 0===e&&(e={graftInfo:null,initializing:!1,mountPath:null,slotRootNode:null,detachedFrom:null},bd.set(t,e)),e}function vd(t,e){null!==e.slotRootNode&&(function(t,e,n){const o=qu.get(t);o?.get(e)===n&&o.set(e,null)}(e.slotRootNode,e.mountPath,t),e.slotRootNode=null)}function _d(t,e,n){if(e.slotRootNode===n)return!0;const s=e.mountPath;try{Uu(n,s,t)}catch{return console.error(`[@wcstack/state] <${o.tagNames.state} mount="${s}"> will not graft: another volume already holds the "${s}" slot on this root. Keep one volume per mount path.`),!1}return ta(n)?.markHasVolume?.(),e.slotRootNode=n,!0}const $d={order:20,connecting(t){if(!t.hasAttribute("mount"))return null;const e=wd(t);if(e.initializing){const n=t.connectedRootNode;if(null!=n&&e.detachedFrom===n)try{Uu(n,e.mountPath,t),ta(n)?.markHasVolume?.(),e.slotRootNode=n}catch{}return e.detachedFrom=null,Ul}return async function(t,e){const n=t,s=t.connectedRootNode,r=n.getAttribute("mount");let i;try{!function(t){0===t.length&&Z('"mount" requires a non-empty tree path.');const e=nt(t);for(const n of e.segments)0===n.length&&Z(`"mount" path "${t}" has an empty segment.`),n===l&&Z(`"mount" path "${t}" must be static (wildcards are not allowed).`),(n.includes("$")||n.includes("#")||n.includes("@"))&&Z(`"mount" path "${t}" must not use reserved characters ($, #, @).`)}(r),i=function(t,e){const n=[],s=new Set;for(const r of Et(t)){if(r.propSegments[0]!==$)continue;const t=r.propSegments.slice(1),i=r.statePathInfo,a=t=>Z(`[wcs/mount-path-invalid] <${o.tagNames.state} mount="${e}"> "${r.propName}: ${r.statePathName}": ${t}`);1===t.length&&t[0]&&t[0]!==l&&"$"!==t[0][0]&&"#"!==t[0][0]||a(`inject one key at a time ("${$}.<key>: path"); change "mount" to move the whole volume.`),(i.wildcardCount>0||"$"===i.path[0]||"#"===i.path[0])&&a("the injected path must be a static path on the root tree (a volume has no loop context)."),(r.inFilters.length>0||r.outFilters.length>0)&&a("an injection takes no filters."),r.propModifiers.some(t=>t!==m)&&a(`an injection accepts only #${m}.`),s.has(t[0])&&a(`"${t[0]}" is injected twice.`),s.add(t[0]),n.push({innerSegments:t,outerPathInfo:i,readonly:r.propModifiers.includes(m)})}return n}(n.getAttribute(o.bindAttributeName)??"",r),n.hasAttribute("bind-component")&&Z('"mount" cannot be combined with "bind-component".'),n.hasAttribute("enable-ssr")&&console.warn(`[@wcstack/state] <${o.tagNames.state} mount="${r}"> ignores "enable-ssr" — snapshots are per root tree (the root state element aggregates volume data).`),Uu(s,r,t),ta(s)?.markHasVolume?.(),e.mountPath=r,e.slotRootNode=s}catch(e){throw t.settleInitialization(),e}e.initializing=!0,null===ta(s)&&function(t,e){const n=()=>{if(null!==ta(t))return;const n=t.querySelectorAll(o.tagNames.state);for(const t of n)if(!t.hasAttribute("mount")&&!t.hasAttribute("bind-component"))return;console.error(`[@wcstack/state] <${o.tagNames.state} mount="${e}"> has no root state tree to graft onto (D11). A volume mounts onto the root tree — add a root <${o.tagNames.state}> to this root node (an empty <${o.tagNames.state}></${o.tagNames.state}> is enough). If the root is added dynamically later, the graft will still complete and this report can be ignored.`)},s=t.ownerDocument??t;"loading"===s.readyState?s.addEventListener("DOMContentLoaded",()=>queueMicrotask(n),{once:!0}):setTimeout(n,0)}(s,r);const a=n=>{e.graftInfo=n,t.markInitialized(),null===n&&vd(t,e),t.settleInitialization()};let c;try{c=await t.loadStateFromSource()}catch(t){return console.error(`[@wcstack/state] volume "${r}" failed to load.`,t),void a(null)}const u=t.connectedRootNode??null;null!==u&&_d(t,e,u)?function(t,e,n,o,s,r,i=[]){const a={mountPath:n,volumeState:o,injections:i,onGrafted:s,acquireSlot:r};null===e?(Sf(),function(t,e){if(ed.has(t))return void nd(e);let n=td.get(t);void 0===n&&(n=[],td.set(t,n)),n.push(e)}(t,a)):_f(e,a)}(u,ta(u),r,c,a,()=>_d(t,e,u),i):a(null)}(t,e)},reconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=wd(t),n=t.connectedRootNode??null;return null!==e.graftInfo&&null!==n&&ta(n)===e.graftInfo.rootStateElement&&wf(e.graftInfo,"$connectedCallback"),!0},replacingState(t){if(!0!==bd.get(t)?.initializing)return;const e=t.getAttribute("mount");Z(`Cannot replace the state of <${o.tagNames.state} mount="${e}"> after it has loaded: a volume's data is copied into the root tree when it grafts, so a new state would never reach the page. Write the paths under "${e}" on the root state instead.`)},initializeFailed(t,e){!function(t){ed.add(t);const e=td.get(t);if(void 0!==e){td.delete(t);for(const t of e)nd(t)}}(e)},initializeFailureCleared(t,e){!function(t){ed.delete(t)}(e)},disconnecting(t){if(!t.hasAttribute("mount"))return!1;const e=wd(t);return null!==e.graftInfo&&wf(e.graftInfo,"$disconnectedCallback"),!0!==t.initialized&&(e.detachedFrom=e.slotRootNode,vd(t,e)),t.clearConnectedRootNode(),!0}};let Sd=!1;const xd=new WeakMap;function Pd(t,e){let n=xd.get(t);n||(n=new Set,xd.set(t,n)),n.add(e)}const Nd=new WeakMap,kd=new WeakMap,Id=new WeakMap,Ad=new WeakMap,Ed={isComplete:function(t,e){return!0===xd.get(t)?.has(e)},isDeclared:function(t,e){return!0===Nd.get(t)?.has(e)},rememberOverwrittenObject:function(t,e,n){let o=kd.get(t);o||(o=new Map,kd.set(t,o)),o.has(e)||o.set(e,n)},recordInjectedKey:function(t,e,n){let o=Id.get(t);o||(o=new Map,Id.set(t,o));let s=o.get(e);s||(s=new Set,o.set(e,s)),s.add(n)},rememberOverwrittenValue:function(t,e,n,o){let s=Ad.get(t);s||(s=new Map,Ad.set(t,s));let r=s.get(e);r||(r=new Map,s.set(e,r)),r.has(n)||r.set(n,o)}};const Cd=new WeakMap;class Td{_innerStateElement;constructor(t,e){this._innerStateElement=function(t,e){const n=Cd.get(t);return n?n.get(e)??null:null}(t,e)??Z("State element not found for web component.")}get(t,e,n){if("string"==typeof e){let t;return this._innerStateElement.createState("readonly",n=>{t=n[e]}),t}return Reflect.get(t,e,n)}set(t,e,n,o){return"string"==typeof e?(this._innerStateElement.createState("writable",t=>{t[e]=n}),!0):Reflect.set(t,e,n,o)}}const Md=t=>()=>t;function Od(t,e,n,o){!function(t,e,n){let o=Cd.get(t);o||(o=new Map,Cd.set(t,o)),o.set(e,n)}(e,n,t),t.setInitialState(function(t){return function(t){const e=Object.getPrototypeOf(t),n=Object.create(e),o=Object.getOwnPropertyDescriptors(t);for(const t in o){const e=o[t];!1===e.writable&&(e.writable=!0)}return Object.defineProperties(n,o),n}(t)}(o));const s=function(t,e){const n=new Td(t,e);return new Proxy({},n)}(e,n);Object.defineProperty(e,n,{get:Md(s),enumerable:!0,configurable:!0}),Pd(e,n),Ld(e,n)}function Ld(t,e){if(M in t){const n=t[M];"function"==typeof n?n.call(t,e).catch(t=>{Z(`Error in ${M}: ${t instanceof Error?t.message:String(t)}`)}):Z(`${M} is not a function.`)}}const Rd=new Set;function jd(t,e){Rd.has(t)||(Rd.add(t),console.warn(`[@wcstack/state] [wcs/mount-own-key-shadow] ${e} See docs/state-mount-design.md §4-3.`))}function Wd(t){const e=t.rootEntry,n=me(t.component);if(e.outerPathInfo.wildcardCount>0&&null===n)return;let o;return t.parentStateElement.createState("readonly",t=>{t[Ee](n,()=>{o=t[e.outerPathInfo.path]})}),o}const Dd=new WeakMap;function zd(t,e){t.landInitialization(),Z(e)}async function Bd(t,e){const n=t;if(n.hasAttribute("bind-component")){const i=n.parentNode,l=i instanceof ShadowRoot?i.host:i instanceof Element?i:null,c=l?Ft(l):null;null!==l&&null!==c||Z(`"bind-component" requires <${o.tagNames.state}> to be a direct child of a custom element.`),i instanceof ShadowRoot||l.hasAttribute(o.bindAttributeName)||zd(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${n.getAttribute("bind-component")}: path").`);const u=["state","src","json"].filter(t=>n.hasAttribute(t));null!==n.querySelector('script[type="module"]')&&u.push('<script type="module">'),u.length>0&&Z(`"bind-component" cannot be combined with ${u.join(", ")}. The component's "${n.getAttribute("bind-component")}" property is the only state source.`);const d=n.getAttribute("bind-component");!function(t,e){let n=Nd.get(t);n||(n=new Set,Nd.set(t,n)),n.add(e)}(l,d);const h=qt(l);null===h&&Z(`CustomElementRegistry is unavailable for <${c}>.`),await h.whenDefined(c.toLowerCase()),l.hasAttribute(o.bindAttributeName)&&await Dt(l),d in l||Z(`Component does not have property "${d}" for state binding.`);let f=l[d];"object"==typeof f&&null!==f||Z(`Component property "${d}" is not an object for state binding.`);const p=function(t,e){const n=kd.get(t);if(!n)return;const o=n.get(e);return n.delete(e),o}(l,d);if(void 0!==p&&function(t,e){if(!t.hasAttribute(o.bindAttributeName))return!1;const n=oe(t);if(null===n)return!1;for(const t of n)if(1===t.propSegments.length&&t.propSegments[0]===e)return!0;return!1}(l,d)&&(l[d]=p,f=p),e.boundComponent=l,e.boundComponentStateProp=d,t.setBoundComponent(l,d),i instanceof ShadowRoot||(oe(l)??[]).some(t=>t.propSegments[0]===d)||zd(t,`A plain (unwired) Light DOM "bind-component" is not supported. Attach a shadow root to <${c}>, or mount it from the host (data-wcs="${d}: path").`),l.hasAttribute(o.bindAttributeName)){const o=(oe(l)??[]).filter(t=>t.propSegments[0]===d);if(o.length>0){const u=ta(l.getRootNode())??zd(t,`No state tree found on this root for mount host <${c}>.`);let h=(s=l,r=d,$c.get(s)?.get(r)??null);const p=null!==h;if(null===h&&(function(t,e,n){const o=Ad.get(t)?.get(e);if(void 0!==o){for(const[t,e]of o)n[t]=e;Ad.get(t).delete(e)}}(l,d,f),h=function(t,e,n,o,s,r=new Set){0===n.length&&Z(`Cannot build a mount record without host bindings for "${e}".`),za(s);const i=[],l=new Set;let c=null;for(const t of n){const e=t.propSegments.slice(1),n=e.join(a);l.has(n)&&Z("Duplicate mapping rule for web component."),l.add(n);const o={innerSegments:e,outerPathInfo:t.statePathInfo,readonly:!0===t.propModifiers?.includes(m)};i.push(o),0===e.length&&(c=o)}i.sort((t,e)=>e.innerSegments.length-t.innerSegments.length);const u=++ic,d=`#m${u}`,{getterKeys:h,setterKeys:f}=function(t){const e=new Set,n=new Set,o=Object.getOwnPropertyDescriptors(t);for(const[t,s]of Object.entries(o))"function"==typeof s.get&&e.add(t),"function"==typeof s.set&&n.add(t);return{getterKeys:e,setterKeys:n}}(s),p=new Set;for(const t of i)t.innerSegments.length>0&&p.add(t.innerSegments[0]);const g={};for(const t of Object.keys(s))t.startsWith("$")||h.has(t)||f.has(t)||"function"!=typeof s[t]&&(r.has(t)||p.has(t)||(g[t]=s[t]));return{id:u,marker:d,component:t,stateProp:e,parentStateElement:o,entries:i,rootEntry:c,delta:null===c?0:c.outerPathInfo.wildcardCount,markerBasePath:null===c?d:c.outerPathInfo.path+a+d,stateObject:s,getterKeys:h,setterKeys:f,injectedKeys:r,mappedKeys:p,privateSnapshot:g,accessorBySuffixByMarkerParent:new Map,indexShiftByLoopElementPath:new Map,addedGetterPaths:new Set,exports:new Map}}(l,d,o,u,f,function(t,e){return Id.get(t)?.get(e)}(l,d)),function(t){const e=Object.keys(t.privateSnapshot);if(0===e.length)return;const n=t.component.tagName.toLowerCase(),o=t.stateProp;let s,r=!1;for(const i of e){if(null===t.rootEntry)continue;if(r||(s=Wd(t),r=!0),"object"!=typeof s||null===s||!(i in s))continue;const e=t.rootEntry.outerPathInfo.path;jd(`${n}|${o}|${i}|root`,`<${n}>.${o}.${i} is private and hides the mounted tree key "${e}.${i}" (${o}: ${e}). Remove the default to read the tree, or rename it to keep it private.`)}}(h)),e.mountRecord=h,n.parentNode!==i)return;try{fd(h,i instanceof ShadowRoot?i:l)}catch(e){throw t.landInitialization(),e}if(!p){const t=function(t){const e=t.parentStateElement,n=(e,n)=>{const o=me(t.component);let s;return e[Ee](o,()=>{s=n()}),s};return new Proxy({},{get(o,s){if("string"!=typeof s||"then"===s)return;if("$getAll"===s||"$setAll"===s||"$resolve"===s||"$postUpdate"===s)return function(t,e,n){const o=t.parentStateElement,s=(t,e)=>{let s;return o.createState(t,t=>{s=n(t,()=>e(t))}),s};return"$postUpdate"===e?e=>s("readonly",n=>n.$postUpdate(wc(t,e))):(n,o,...r)=>{const i="$setAll"===e||"$resolve"===e&&r.length>0,a=i?bc(t,n):wc(t,n),l=me(t.component)?.listIndex.indexes??[],c=vc(0,n,a,"$resolve"===e?o??[]:o,l);return s(i?"writable":"readonly",t=>t[e](a,c,...r))}}(t,s,n);let r;return e.createState("readonly",e=>{r=n(e,()=>e["$"===s[0]?s:wc(t,s)])}),r},set:(o,s,r)=>("string"!=typeof s||e.createState("writable",e=>{n(e,()=>{e["$"===s[0]?s:bc(t,s)]=r})}),!0),has(e,n){if("string"!=typeof n||"$"===n[0]||"#"===n[0])return!1;if(Object.prototype.hasOwnProperty.call(t.stateObject,n))return!0;try{return wc(t,n),!0}catch{return!1}}})}(h);Object.defineProperty(l,d,{get:()=>t,enumerable:!0,configurable:!0}),Pd(l,d)}return Ld(l,d),function(t){const e=ac.filter(e=>void 0!==t.stateObject[e]);for(const n of t.getterKeys)-1!==n.indexOf(q)&&e.push(`"${n}"`);if(0===e.length)return;const n=`${t.component.tagName.toLowerCase()}|${t.stateProp}`;lc.has(n)||(lc.add(n),console.warn(`[@wcstack/state] [wcs/mount-dollar-declaration] <${n.split("|")[0]}>.${t.stateProp} declares ${e.join(", ")}, which mounted components do not run. Declare them on the root state instead (a volume <wcs-state mount="..."> can host $watch / $listKeys / $updatedCallback; $recursion and "**" getters expand against the root tree). See docs/state-mount-design.md §4-6.`))}(h),void cc(h,"$connectedCallback")}}Od(t,e.boundComponent,e.boundComponentStateProp,f)}var s,r}const Fd={order:30,preparing(t){if(!t.hasAttribute("bind-component"))return null;const e=function(t){let e=Dd.get(t);return void 0===e&&(e={boundComponent:null,boundComponentStateProp:null,mountRecord:null},Dd.set(t,e)),e}(t);return Bd(t,e).then(()=>null!==e.mountRecord&&(t.markInitialized(),t.settleInitialization(),!0))},reconnecting(t){const e=Dd.get(t);if(void 0===e||null===e.mountRecord)return!1;const n=e.mountRecord,o=t.parentNode;return queueMicrotask(()=>{null!=t.connectedRootNode&&pd(n,o)}),cc(n,"$connectedCallback"),!0},disconnecting(t){const e=Dd.get(t);return void 0!==e&&null!==e.mountRecord&&(cc(e.mountRecord,"$disconnectedCallback"),cd(e.mountRecord),t.clearConnectedRootNode(),!0)}};let Hd=!1;const qd=new WeakMap,Ud=new Set,Gd=new Set;function Vd(t){return t.byFromPath.size>0||t.byResetPath.size>0}function Kd(t,e,n){const o=t.get(e);void 0===o?t.set(e,[n]):o.push(n)}function Jd(t){return qd.get(t)}function Qd(t){Xd(t),qd.delete(t)}function Xd(t){Ud.delete(t),Gd.delete(t)}const Yd=new WeakMap,Zd=new WeakMap,th=new Set,eh=new Map;function nh(t){return Yd.get(t)??eh}const oh=new Map;function sh(t){return Zd.get(t)??oh}function rh(t){0===t.length&&Z(`[wcs/watch-declaration-invalid] ${B} entry name must be a non-empty state path.`),t.startsWith("$")&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not start with "$" (reserved namespace).${it}`),t.includes("@")&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not contain "@" — the name selector was removed in v2; watch only paths of the state tree.${it}`),t in Object.prototype&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`);const e=nt(t);for(const n of e.segments)0===n.length&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" has an empty path segment.${it}`);return e.wildcardCount>c&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${t}" exceeds the maximum wildcard depth (128).`),e}let ih=0,ah=0;function lh(t){ih=t+1}function ch(){ih=0}function uh(){ih>ah&&(ah=ih)}const dh=new WeakMap;function hh(t,e,n){let o=dh.get(t);void 0===o&&(o=new Map,dh.set(t,o)),o.set(e,n)}const fh=new Map;function ph(t,e){fh.has(t)||fh.set(t,e)}function mh(t){return fh.get(t)}const gh={writeObserve(t,e,n,o,s){if(!s)return;const r=t.watchPaths,i=t.scanPaths;!0!==r?.has(e)&&!0!==i?.has(e)||ph(n,o)},swapped(t,e,n){var o;o=n,fh.has(o)&&ph(e,mh(n))}};function yh(t){for(let e=t;null!==e;e=e.parentListIndex)if(Is(e))return!0;return!1}function bh(t,e,n){const o=n.absAddress.listIndex;let s="current",r=null;for(let i=0;i<e.wildcardCount;i++){const a=t[Ce](mn(e.wildcardParentPathInfos[i],r)),l=As(a)?.[n.indexes[i]];if(void 0===l)return"gone";const c=Ye(o,i,e.wildcardCount);if(l!==c&&!Ps(l,c)){if(Is(c))return"gone";s="replaced"}r=l}return s}function wh(t,e,n){const o=new Map;for(const s of n){const n=bh(t,e,s);if("gone"===n)continue;const r="current"===n?1:0,i=s.indexes.join(","),a=o.get(i);(void 0===a||r>a.rank)&&o.set(i,{row:s,rank:r})}return Array.from(o.values(),t=>t.row)}const vh=new Set;function _h(t){vh.delete(t)}const $h=Symbol("wcs-stream-last-notified-uncertain"),Sh=new WeakMap;function xh(t,e){const n=Sh.get(t);if(void 0!==n)for(const t of n.keys())e.has(t)||n.delete(t)}function Ph(t,e){const n=Sh.get(t);if(void 0===n)return;const o=n.get(e);void 0!==o&&n.set(e,{status:"idle"===o.status?o.status:$h,error:Object.is(o.error,null)?null:$h})}const Nh=new WeakMap;function kh(t){return Nh.get(t)??new Map}function Ih(t){_h(t);const e=Nh.get(t);if(void 0!==e)for(const n of e.values())n.controller?.abort(),n.controller=null,n.status="idle",n.error=null,Ph(t,n.name)}const Ah=new WeakSet;let Eh=0;function Ch(t){return Jd(t.absolutePathInfo.stateElement)?.eventResetByPath.get(t.absolutePathInfo.pathInfo.path)}function Th(t){if(0===Gd.size)return;if(e=t.absolutePathInfo.stateElement,!Gd.has(e))return;var e;const n=Ch(t);if(void 0!==n)for(const t of n)Mh(t)}function Mh(t){Ah.has(t)||(Ah.add(t),Eh++)}function Oh(t){return!!Ah.delete(t)&&(Eh--,!0)}const Lh=/^(?:0|[1-9]\d*)$/;function Rh(t,e){const n=Object.getOwnPropertyDescriptor(t,e);return!0===n.enumerable&&"value"in n}function jh(t){if("object"!=typeof t||null===t||Object.isFrozen(t))return null;const e=Object.getPrototypeOf(t);return Array.isArray(t)?e===Array.prototype&&Reflect.ownKeys(t).every(e=>"length"===e||"string"==typeof e&&Lh.test(e)&&Rh(t,e))?"array":null:e!==Object.prototype&&null!==e||!Reflect.ownKeys(t).every(e=>"string"==typeof e&&Rh(t,e))?null:"object"}function Wh(t,e){const n=jh(t);if(null===n)return t;const o=t,s=e.get(o);if(void 0!==s)return s;let r;r="array"===n?new Array(t.length):null===Object.getPrototypeOf(t)?Object.create(null):{},e.set(o,r);for(const t of Object.keys(o))r[t]=Wh(o[t],e);return r}function Dh(t){return Wh(t,new Map)}function zh(t,e,n){if(Object.is(t,e))return!0;const o=jh(e);if(null===o||"object"!=typeof t||null===t)return!1;const s=t,r=e;if("array"===o){if(!Array.isArray(t)||t.length!==e.length)return!1}else if(Array.isArray(t)||Object.keys(s).length!==Object.keys(r).length)return!1;if(jh(t)!==o)return!1;let i=n.get(s);if(void 0===i)i=new Set,n.set(s,i);else if(i.has(r))return!0;if(i.add(r),"array"===o){for(let e=0;e<t.length;e++)if(!zh(s[e],r[e],n))return!1;return!0}return Object.keys(r).every(t=>Object.prototype.hasOwnProperty.call(s,t)&&zh(s[t],r[t],n))}function Bh(t,e){return zh(t,e,new Map)}const Fh=new WeakMap;function Hh(t,e){if("function"!=typeof e)return;const n=Fh.get(e);void 0===n?Fh.set(e,new Set([t])):n.add(t)}const qh={"read-source":t=>`${F} could not read a "from" value for "${t}". That landing was not folded; the other landings of the batch still were.`,"read-output":t=>`${F} could not read the output "${t}". Nothing was folded or written.`,threw:t=>`${F} fold for "${t}" threw. The output was not written.`,"returned-promise":t=>`${F} fold for "${t}" returned a Promise. fold must be synchronous and return the next value; the output was not written.`,write:t=>`${F} could not write the output "${t}".`},Uh={"read-source":"evaluate","read-output":"evaluate",threw:"fold","returned-promise":"fold",write:"write"};function Gh(t,e,n){null!==ye&&ye({type:"state:watch-error",phase:e,path:`${F}.${t}`,error:n})}function Vh(t,e,n){console.error(`[@wcstack/state] ${qh[n](t)}`,e),Gh(t,Uh[n],e)}function Kh(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function Jh(t,e){e.then(void 0,()=>{}),Vh(t,new TypeError(`${F} fold for "${t}" returned a Promise. fold must be synchronous and return the next value.`),"returned-promise")}const Qh=new WeakSet,Xh=Object.freeze([]);function Yh(t,e,n){let o=t.get(n);return void 0===o&&(o={stateElement:e,entry:n,rows:[],reset:!1},t.set(n,o)),o}function Zh(t,e){let n=0;for(;n<t.indexes.length-1&&t.indexes[n]===e.indexes[n];)n++;return t.indexes[n]-e.indexes[n]}function tf(t,e){return e.has(t.stateElement)&&!0===Jd(t.stateElement)?.entries.has(t.entry)}function ef(t){const{entry:e,stateElement:n}=t;"event"!==e.source.kind||e.resetOn.some(t=>nf(n,t))||Oh(e)}function nf(t,e){return qs().hasQueuedPath(t,e)}function of(t,e){!function(t,e,n){if(0!==Eh)for(const o of t){const t=o.absolutePathInfo.stateElement;if(!0===e?.has(t))continue;const s=Ch(o);if(void 0!==s)for(const e of s)e.resetOn.some(e=>n(t,e))||Oh(e)}}(t,e,nf)}function sf(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n.indexes)}function rf(t,e,n){if(!tf(t,n))return ef(t),null;const{stateElement:o,entry:s}=t;if(t.reset)return{group:t,next:s.initial};const r=s.source;if(function(t,e){for(const n of e.pathInfo.cumulativePaths)if(t.getterPaths.has(n))return!0;return!1}(o,r))return function(t,e,n){if(Qh.has(t))return;Qh.add(t);const o=`[wcs/scan-source-computed] ${F} entry "${e}" from "${n}" is now backed by a getter (registered after the declaration, e.g. by a volume). A getter re-evaluates whenever its inputs change, so this scan stopped folding. Fold the plain value the getter reads instead.`;console.error(`[@wcstack/state] ${o}`),Gh(e,"fold",new Error(o))}(s,s.name,r.path),null;if(function(t,e,n){const o=kh(t).get(e);if(void 0===o)return!1;for(const t of o.depAddresses)if(n.has(t))return!0;return!1}(o,r.pathInfo.segments[0],e))return null;const i={plan:null,failure:"read-output"};try{o.createState("readonly",e=>{const n=e[s.name],o=0===r.pathInfo.wildcardCount?t.rows:wh(e,r.pathInfo,t.rows);i.failure="threw";const a=s.fold;let l=n;for(const t of o.sort(Zh)){let n;try{n=sf(e,r,t)}catch(t){Vh(s.name,t,"read-source");continue}const o=a(l,n,mh(t.absAddress),...t.indexes);if(Kh(o))return void Jh(s.name,o);l=o}Object.is(l,n)||(i.plan={group:t,next:l})})}catch(t){Vh(s.name,t,i.failure)}return i.plan}function af(t,e){const{group:n}=t;if(!tf(n,e))return void ef(n);const{stateElement:o,entry:s}=n;if(!n.reset||"event"!==s.source.kind||Oh(s))try{o.createState("writable",e=>{const o=e[s.name];if(n.reset?!Bh(o,s.initial):!Object.is(o,t.next)){const o=n.reset?Dh(s.initial):t.next;e[s.name]=o,Hh(s.name,o)}})}catch(t){Vh(s.name,t,"write")}}function lf(t){yf(),(0!==nh(t).size||0!==sh(t).size||function(t){const e=qd.get(t);return void 0!==e&&Vd(e)}(t))&&(function(t){th.add(t),function(t){const e=qd.get(t);void 0!==e&&(Vd(e)&&Ud.add(t),function(t){return t.eventResetByPath.size>0}(e)&&Gd.add(t))}(t)}(t),function(t){const e=[];for(const n of nh(t).values())cf(t,n)&&e.push(n);for(const n of sh(t).values())for(const o of n)cf(t,o)&&e.push(o);0!==e.length&&t.createState("readonly",n=>{for(const o of e)try{hh(t,Ge(t,o.pathInfo,null),n[o.path])}catch(e){df(t,o.path,"prime",e)}})}(t))}function cf(t,e){return 0===e.pathInfo.wildcardCount&&t.getterPaths.has(e.path)}const uf={prime:"initial evaluation of",evaluate:"evaluation of",handler:"handler for"};function df(t,e,n,o){console.error(`[@wcstack/state] $watch ${uf[n]} "${e}" threw.`,o),null!==ye&&ye({type:"state:watch-error",phase:n,path:e,error:o})}function hf(t){const e=th;try{if(0===e.size)return void of(t,e);const n=function(){const t=ah;return ah=0,t}();if(n>32){of(t,null);const e=Array.from(t,t=>t.absolutePathInfo.pathInfo.path);return console.error("[@wcstack/state] $watch chain depth limit exceeded; $scan folds and $watch handlers for this batch were skipped.",{maxDepth:32,paths:e}),void(null!==ye&&ye({type:"state:watch-chain-limit",maxDepth:32,paths:e}))}!function(t,e,n){if(0!==t.length){lh(n);try{for(const n of t)af(n,e)}finally{ch()}}}(function(t,e,n){if(of(t,e),0===Ud.size)return Xh;const o=new Map;for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=Jd(t);if(void 0===s)continue;const r=n.absolutePathInfo.pathInfo,i=s.byFromPath.get(r.path);if(void 0!==i){let e=[];if(r.wildcardCount>0){if(null===n.listIndex)continue;e=Ze(n.listIndex,r.wildcardCount)}for(const s of i)Yh(o,t,s).rows.push({absAddress:n,indexes:e})}const a=s.byResetPath.get(r.path);if(void 0!==a)for(const e of a)Yh(o,t,e).reset=!0}if(0===o.size)return Xh;const s=Array.from(o.values()).sort((t,e)=>t.entry.order-e.entry.order),r=[];lh(n);try{for(const n of s){const o=rf(n,t,e);null!==o&&r.push(o)}}finally{ch()}return r}(t,e,n),e,n),function(t,e,n){const o=[];for(const n of t){const t=n.absolutePathInfo.stateElement;if(!e.has(t))continue;const s=n.absolutePathInfo.pathInfo.path,r=nh(t).get(s),i=sh(t).get(s);if(void 0===r&&void 0===i)continue;const a=void 0===r?[]:[r];void 0!==i&&a.push(...i);for(const e of a){let s=[];if(e.pathInfo.wildcardCount>0){if(null===n.listIndex)continue;s=Ze(n.listIndex,e.pathInfo.wildcardCount)}o.push({stateElement:t,entry:e,absAddress:n,indexes:s})}}if(0===o.length)return;o.sort(pf);const s=function(t){let e=null;for(let n=0;n<t.length;n++){const o=t[n];if(0===o.entry.pathInfo.wildcardCount)continue;const s=t[n-1];(yh(o.absAddress.listIndex)||s?.entry===o.entry&&ff(s.indexes,o.indexes))&&(e??=new Set).add(o.entry)}if(null===e)return t;const n=new Set;for(const o of e){const e=t.filter(t=>t.entry===o),s=e[0].stateElement;try{s.createState("readonly",t=>{const s=new Set(wh(t,o.pathInfo,e));for(const t of e)s.has(t)||n.add(t)})}catch(t){df(0,o.path,"evaluate",t);for(const t of e)n.add(t)}}return t.filter(t=>!n.has(t))}(o);lh(n);try{for(const t of s){if(!e.has(t.stateElement))continue;const n=nh(t.stateElement).get(t.entry.path)===t.entry,o=!0===sh(t.stateElement).get(t.entry.path)?.includes(t.entry);(n||o)&&mf(t)}}finally{ch()}}(t,e,n)}finally{fh.clear()}}function ff(t,e){for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function pf(t,e){if(t.entry.order!==e.entry.order)return t.entry.order-e.entry.order;const n=Math.min(t.indexes.length,e.indexes.length);for(let o=0;o<n;o++)if(t.indexes[o]!==e.indexes[o])return t.indexes[o]-e.indexes[o];return t.indexes.length-e.indexes.length}function mf(t){const{stateElement:e,entry:n,absAddress:o,indexes:s}=t,r=cf(e,n);try{e.createState("writable",t=>{let i;try{i=function(t,e,n){return 0===e.pathInfo.wildcardCount?t[e.path]:t.$resolve(e.path,n)}(t,n,s)}catch(t){return void df(0,n.path,"evaluate",t)}const a=r?function(t,e){return dh.get(t)?.get(e)}(e,o):mh(o);r&&hh(e,o,i),null!==ye&&ye({type:"state:watch-fired",path:n.path,stateElement:e}),n.handler.call(t,i,a,...s)})}catch(t){df(0,n.path,"handler",t)}}let gf=!1;function yf(){gf||(gf=!0,Ka("watch",gh),Ya("watch",bf),Bs(hf,10),zs(uh))}const bf={order:10,register(t,e){var n;n=t,th.delete(n),Xd(n),Yd.delete(n),function(t){dh.delete(t)}(t);const o=function(t,e){const n=e[B];if(void 0===n)return null;"object"==typeof n&&null!==n||Z(`[wcs/watch-declaration-invalid] ${B} must be an object mapping state paths to handler functions.${it}`);const o=new Map,s=new Set;let r=0;for(const[e,i]of Object.entries(n)){"function"!=typeof i&&Z(`[wcs/watch-declaration-invalid] ${B} entry "${e}" must be a function.${it}`);const n=rh(e);o.set(e,{path:e,pathInfo:n,handler:i,order:r++}),s.add(e),t.setPathInfo(e,"prop","watch")}return function(t,e){Yd.set(t,e)}(t,o),s.size>0?s:null}(t,e);t.setWatchPaths?.(o),null===o&&null==t.scanPaths||t.attachAddressHooks?.("watch",null!==o?B:F)},activate(t,n){e()||null==t.connectedRootNode||(null===n?!0===t.initialized:n===t.connectGeneration)&&lf(t)},deactivate(t){var e;e=t,th.delete(e),Xd(e)}};function wf(t,e){const n=t.volumeState[e];"function"==typeof n&&t.rootStateElement.createState("writable",o=>{const s=n.call(Xu(t.mountPath,o,t.injections));s instanceof Promise&&s.catch(n=>{console.error(`[@wcstack/state] volume "${t.mountPath}" ${e} failed.`,n)})})}function vf(t,e,n,o=[]){za(n),function(t,e,n,o){for(const t of o){const o=t.innerSegments[0],s=Object.getOwnPropertyDescriptor(n,o);void 0===s||"function"!=typeof s.get&&"function"!=typeof s.set&&"function"!=typeof s.value||Z(`Volume "${e}" declares "${o}" as an accessor or a method and also injects it ("${$}.${o}: ${t.outerPathInfo.path}"). Rename one of them.`)}const s=n[B];if(void 0!==s){"object"==typeof s&&null!==s||Z(`${B} must be an object mapping state paths to handler functions.`);for(const[t,e]of Object.entries(s))"function"!=typeof e&&Z(`${B} entry "${t}" must be a function.`),rh(t)}const r=n[U];if(void 0!==r){"object"==typeof r&&null!==r||Z(`${U} must be an object mapping list paths to key specs.`);for(const[n,s]of Object.entries(r)){(0===n.length||"string"!=typeof s&&"function"!=typeof s)&&Z(`${U} entry "${n}" must map a list path to a field name or a key function.`);const r=Ju(e,o,n,!1);t.listKeys?.has(r)&&Z(`${U} entry "${r}" is declared by both the root and a volume (or two volumes). Keep exactly one.`)}}void 0!==n[z]&&Z(`Volume "${e}" declares ${z}, which volumes do not support yet. Declare the stream on the root state.`),void 0!==n.$scan&&Z(`Volume "${e}" declares $scan, which volumes do not support yet. Declare the scan on the root state.`),void 0!==n[H]&&Z(`Volume "${e}" declares ${H}, which volumes do not support yet. Declare the recursion anchor on the root state — the anchor path is resolved against the root tree.`);for(const t of Object.keys(Xl(n)))-1!==t.indexOf(q)&&Z(`Volume "${e}" declares "${t}", which uses "${q}". Volumes do not support recursive getters yet — declare them on the root state.`)}(t,e,n,o);const{data:s,accessors:r}=function(t,e){const n={},o=new Map;for(const[s,r]of Object.entries(Object.getOwnPropertyDescriptors(t)))s.startsWith("$")||e.has(s)||("function"!=typeof r.get&&"function"!=typeof r.set?"function"!=typeof r.value&&(n[s]=r.value):o.set(s,r));return{data:n,accessors:o}}(n,new Set(o.map(t=>t.innerSegments[0]))),i=nt(e),l=!0===t.hydratedFromSsr;t.createState("writable",t=>{if(1===i.segments.length&&e in t){if(l)return;Z(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}let n="";for(let e=0;e<i.segments.length-1;e++){const o=i.segments[e],s=""===n?o in t:void 0!==t[n+a+o];n=""===n?o:n+a+o,s||(t[n]={})}if(i.segments.length>1&&void 0!==t[e]){if(l)return;Z(`Volume mount "${e}" collides with an existing key on the root tree. Remove the root key or mount the volume elsewhere.`)}t[e]=s}),function(t,e){let n=Vu.get(t);void 0===n&&(n=new Set,Vu.set(t,n)),n.add(e)}(t,e),t.markHasGraftedVolumes?.();for(const[n,s]of r){const r=e+a+n,i=s.get,l=s.set,c={enumerable:!1,configurable:!0};"function"==typeof i&&(c.get=function(){return i.call(Xu(e,this,o))}),"function"==typeof l&&(c.set=function(t){l.call(Xu(e,this,o),t)}),t.defineTreeAccessor(r,c)}!function(t,e,n,o){const s=n[B];if(void 0!==s){const n=[],r=new Set;let i=0;for(const[a,l]of Object.entries(s)){const s=Ju(e,o,a,!1),c=function(t,n,...s){l.call(Xu(e,this,o),t,n,...s)};n.push({path:s,pathInfo:nt(s),handler:c,order:1e6+i++}),r.add(s),t.setPathInfo(s,"prop","watch")}n.length>0&&(function(t,e){let n=Zd.get(t);void 0===n&&(n=new Map,Zd.set(t,n));for(const t of e){const e=n.get(t.path);void 0===e?n.set(t.path,[t]):e.push(t)}}(t,n),t.addVolumeWatchPaths?.(r),lf(t))}const r=n[U];if(void 0!==r){const n=new Map;for(const[t,s]of Object.entries(r))n.set(Ju(e,o,t,!1),s);t.mergeVolumeListKeys?.(n)}const i=n[C];"function"==typeof i&&(function(t,e){let n=Yu.get(t);void 0===n&&(n=[],Yu.set(t,n)),n.push(e),t.markHasVolume?.()}(t,{mountPath:e,injections:o,callback:i}),t.enableUpdatedCallback?.());for(const t of["$commandTokens","$eventTokens","$on","$errorCallback"])void 0!==n[t]&&console.warn(`[@wcstack/state] volume "${e}" declares ${t}, which volumes do not support. Declare it on the root state instead.`)}(t,e,n,o);const c=n.$connectedCallback;return"function"==typeof c&&t.createState("writable",t=>{let n;try{n=c.call(Xu(e,t,o))}catch(t){return void console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)}n instanceof Promise&&n.catch(t=>{console.error(`[@wcstack/state] volume "${e}" $connectedCallback failed.`,t)})}),{rootStateElement:t,mountPath:e,volumeState:n,injections:o}}function _f(t,e){if(!e.acquireSlot())return void e.onGrafted(null);let n=null;try{n=vf(t,e.mountPath,e.volumeState,e.injections)}catch(t){console.error(`[@wcstack/state] volume "${e.mountPath}" failed to graft.`,t)}finally{e.onGrafted(n)}}let $f=!1;function Sf(){var t;$f||($f=!0,yd||(yd=!0,Ka("scopes",gd)),Sd||(Sd=!0,Kl("scopes",$d)),Hd||(Hd=!0,Kl("bindComponent",Fd),rs=Ed),od=_f,t=xf,Zi.includes(t)||Zi.push(t))}function xf(t,e){(function(t){const e=qu.get(t);return void 0!==e&&e.size>0})(t)&&e.markHasVolume?.(),function(t,e){ed.delete(t);const n=td.get(t);if(void 0===n||0===n.length||null===od)return;td.delete(t);const o=od;queueMicrotask(()=>{for(const t of n)o(e,t)})}(t,e)}const Pf={name:"scopes",install(){Sf(),Hu||(Hu=!0,Kl("dcc",Fu))}},Nf=/^@@wcs-(?:for|if|elseif|else):[^-]/,kf=/^@@wcs-(for|if|elseif|else)-start:(.+)$/,If=/^@@wcs-(for|if|elseif|else)-end:(.+)$/,Af=/^@@wcs-text-start:(.+)$/;function Ef(t){return t.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}class Cf extends Ql{_stateData=null;_templates=null;_hydrateProps=null;get version(){return this.getAttribute("version")||""}get stateData(){return null===this._stateData&&(this._stateData=this._loadStateData()),this._stateData}get templates(){return null===this._templates&&(this._templates=this._loadTemplates()),this._templates}get hydrateProps(){return null===this._hydrateProps&&(this._hydrateProps=this._loadHydrateProps()),this._hydrateProps}getTemplate(t){return this.templates.get(t)??null}verifyVersion(){const t=this.version;if(!t)return!0;const e=t.split("."),n=Ec.split(".");return e[0]===n[0]&&e[1]===n[1]}setStateData(t){this._stateData=t}setHydrateProps(t){this._hydrateProps=t}_loadStateData(){const t=this.querySelector('script[type="application/json"]:not([data-wcs-ssr-props])');if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}_loadTemplates(){const t=new Map,e=this.querySelectorAll("template[id]");for(const n of e){const e=n.getAttribute("id");e&&t.set(e,n)}return t}_loadHydrateProps(){const t=this.querySelector("script[data-wcs-ssr-props]");if(!t)return{};try{return JSON.parse(t.textContent||"{}")}catch{return{}}}static find(t){const e=o.tagNames.ssr,n=t instanceof Element?t:t instanceof Document?t.documentElement:null;return n?n.querySelector(e):null}static extractStateData(t){const e=t.__state;if(!e||"object"!=typeof e)return{};const n={};for(const t of Object.keys(e)){if(t.startsWith("$"))continue;const o=Object.getOwnPropertyDescriptor(e,t);if(void 0!==o&&"function"==typeof o.get)continue;const s=e[t];"function"!=typeof s&&(n[t]=s)}return n}static buildContent(t,e){const n=document.createElement("script");n.setAttribute("type","application/json"),n.textContent=Ef(JSON.stringify(e)),t.appendChild(n);const s=Array.from(ra.keys());for(const e of s){const n=aa(e);if(!n)continue;const s=document.createElement("template");s.setAttribute("id",e);const r=n.parseBindTextResult,i="else"===r.bindingType?"else:":`${r.bindingType}: ${r.statePathName}`;s.setAttribute(o.bindAttributeName,i);const a=n.fragment.cloneNode(!0);s.content.appendChild(a),t.appendChild(s)}const r=Array.from(ui);if(r.length>0){const e={};for(let t=0;t<r.length;t++){const n=r[t],o=ci(n);if(0===o.length)continue;const s=`wcs-ssr-${t}`;n.setAttribute("data-wcs-ssr-id",s);const i={};for(const t of o)i[t.propName]=t.value;e[s]=i}if(Object.keys(e).length>0){const n=document.createElement("script");n.setAttribute("type","application/json"),n.setAttribute("data-wcs-ssr-props",""),n.textContent=Ef(JSON.stringify(e)),t.appendChild(n)}}ui.clear()}static removeBlockBoundaryComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;(kf.test(t.data)||If.test(t.data))&&n.push(t)}for(const t of n)t.remove()}static removeStructuralComments(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode;Nf.test(t.data)&&n.push(t)}for(const t of n)t.remove()}static restoreTextBindings(t){const e=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),n=[];for(;e.nextNode();){const t=e.currentNode,o=Af.exec(t.data);o&&n.push({comment:t,path:o[1]})}for(const{comment:t,path:e}of n){const n=document.createComment(`@@: ${e}`);t.parentNode.insertBefore(n,t);let o=t.nextSibling;t.remove();const s=`@@wcs-text-end:${e}`;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===s){o.parentNode.removeChild(o);break}o.parentNode.removeChild(o),o=t}}}static cleanupDom(t){const e=document.body,n=t.querySelectorAll(o.tagNames.ssr),s=new Map;for(const t of n){const e=t.querySelectorAll("template[id]");for(const t of e){const e=t.getAttribute("id");e&&s.set(e,t)}}const r=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),i=[];for(;r.nextNode();){const t=r.currentNode;kf.test(t.data)&&i.push(t)}for(const t of i){const e=kf.exec(t.data),n=`@@wcs-${e[1]}-end:${e[2]}`;let o=t.nextSibling;for(;o;){const t=o.nextSibling;if(o.nodeType===Node.COMMENT_NODE&&o.data===n){o.remove();break}o.remove(),o=t}t.remove()}Cf.restoreTextBindings(e);const a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT),l=[];for(;a.nextNode();){const t=a.currentNode;if(Nf.test(t.data)){const e=t.data.split(":")[1];l.push({comment:t,uuid:e})}}for(const{comment:t,uuid:e}of l){const n=s.get(e);if(n){const e=document.createElement("template"),s=n.getAttribute(o.bindAttributeName);s&&e.setAttribute(o.bindAttributeName,s);const r=document.importNode(n.content,!0);if(r.childNodes.length>0)e.content.appendChild(r);else for(const t of Array.from(n.childNodes))e.content.appendChild(document.importNode(t,!0));t.parentNode.replaceChild(e,t)}}const c=t.querySelectorAll("[data-wcs-ssr-id]");for(const t of c)t.removeAttribute("data-wcs-ssr-id");for(const t of n)t.remove()}}const Tf={protocol:"wcs-ssr-snapshot",version:1,build:function(t){const e=o.tagNames.state,n=o.tagNames.ssr,s=t.querySelectorAll(`${e}[enable-ssr]:not([mount]):not([bind-component])`);for(const t of s){const e=t.previousElementSibling;if(null!==e&&e.tagName.toLowerCase()===n)continue;const o=document.createElement(n);o.setAttribute("version",Ec),Cf.buildContent(o,Cf.extractStateData(t)),t.parentNode?.insertBefore(o,t)}}},Mf=new Set(["for","if","elseif","else"]);function Of(t){const e=new ns;if(0===t.length)return{bindingInfos:[],subscriberNodes:[],bindingSession:e};const n=t[0].parentNode,o=t[t.length-1].nextSibling,s=document.createElement("div");for(const e of t)s.appendChild(e);const[r,i]=ue(s),a=e.initialize(i,{registerAddress:!1,applyOnReconnect:!1});if(n)for(;s.firstChild;)n.insertBefore(s.firstChild,o);return{bindingInfos:a,subscriberNodes:r,bindingSession:e}}function Lf(t,e,n){for(const o of e)"event"===o.bindingType||Mf.has(o.bindingType)||o.node.nodeType===Node.COMMENT_NODE||o.statePathName in I||nt(o.statePathName).wildcardCount>n||t.push(o)}function Rf(t,e,n){const s={for:o.commentForPrefix,if:o.commentIfPrefix,elseif:o.commentElseIfPrefix,else:o.commentElsePrefix}[e];if(!s)return null;const r=`@@${s}:${n}`,i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT);for(;i.nextNode();){const t=i.currentNode;if(t.data===r)return t}return null}function jf(t,e){const n=t;let s=null;for(const[t,r]of e.templates){let e=Et(r.getAttribute(o.bindAttributeName)||"")[0];const i=e.bindingType;"else"===i&&s&&(e={...s,outFilters:[...s.outFilters,ua()],bindingType:"else"}),"if"===i||"elseif"===i?s=e:"else"===i&&(s=null);const a=document.importNode(r.content,!0),l="for"===i?e.statePathName:void 0;wa(a),"string"==typeof l&&ga(a,l),xa(n,a,l),ia(t,n,{fragment:a,parseBindTextResult:e,nodeInfos:ba(a)})}}const Wf={hydrate:async function(t){await qi(t);const e=t.querySelectorAll(o.tagNames.ssr);for(const n of e){const e=n;if(!e.verifyVersion())return console.warn(`[@wcstack/state] SSR version mismatch: server="${e.version}", client="${Ec}". Falling back to full render.`),Cf.cleanupDom(t),!1}for(const n of e)jf(t,n);const n=function(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),o=[];for(;n.nextNode();)o.push(n.currentNode);for(const t of o){const n=kf.exec(t.data);if(!n)continue;const o=n[1],s=n[2],r=s.split(":");let i,a,l=null;"for"===o?(i=r[0],a=r[1],l=parseInt(r[2],10)):(i=r[0],a=r.slice(1).join(":"));const c=[];let u=t.nextSibling;const d=`@@wcs-${o}-end:${s}`;for(;u&&(u.nodeType!==Node.COMMENT_NODE||u.data!==d);)c.push(u),u=u.nextSibling;e.push({type:o,uuid:i,path:a,index:l,nodes:c})}return e}(document.body),s=function(t,e){const n=new Map,o=[];for(const s of e){if(0===s.nodes.length)continue;const e=Hr(s.nodes),{bindingInfos:r,subscriberNodes:i,bindingSession:a}=Of(s.nodes);xr(e,a);for(const t of i)t.nodeType===Node.ELEMENT_NODE&&t.setAttribute("data-wcs-completed","");ds(e,r),kr(e,i);const c=[];for(const t of r)t.statePathName in I&&c.push(t);if(ps(e,c),"for"===s.type&&null!==s.index){const i=Rf(t,"for",s.uuid);if(i){const t=_s(null,s.index);Zr(i,t,e),ti(i,s.nodes[s.nodes.length-1]),Rr(i,e);const c=nt(s.path+"."+l);Ir(e,mn(c,t)),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Lf(o,r,c.wildcardCount);let u=n.get(s.uuid);u||(u=[],n.set(s.uuid,u)),u.push(t)}}else{const n=Rf(t,s.type,s.uuid);n&&(Rr(n,e),a.initialize(r,{registerAddress:!0,registerPathInfo:!1,applyOnReconnect:!1}),Lf(o,r,0))}}for(const[e,o]of n){const n=Rf(t,"for",e);if(!n)continue;const s=n.getRootNode(),r=aa(e);if(!r)continue;const i=r.parseBindTextResult.statePathName,a=ta(s);a&&a.createState("readonly",t=>{const e=t[i];Array.isArray(e)&&Cs(e,o)})}return o}(document.body,n);Cf.removeBlockBoundaryComments(document.body);const r=[];for(const t of e)t.parentNode&&(r.push({el:t,parent:t.parentNode,next:t.nextSibling}),t.remove());Cf.restoreTextBindings(document.body);const[i,a]=ue(document.body);for(const t of i)if(t.nodeType===Node.ELEMENT_NODE){const e=t;e.hasAttribute("data-wcs-completed")||(ge(t,null),e.setAttribute("data-wcs-completed",""))}else ge(t,null);const c=[],u=[],d=os(document.body).initialize(a);for(const t of d)if("event"!==t.bindingType)if(Mf.has(t.bindingType))u.push(t);else{if(t.statePathName.includes(l))continue;c.push(t)}for(const t of u)if("for"===t.bindingType){const e=sn(t),n=ta(t.replaceNode.getRootNode());n&&n.createState("readonly",n=>{const o=n[t.statePathName];Array.isArray(o)&&(ve(e,o),Ne(e,o))})}Bi([...c,...s]);for(const{el:t,parent:e,next:n}of r)e.insertBefore(t,n);const h=t.querySelectorAll(o.tagNames.ssr);for(const e of h){const n=e.hydrateProps;for(const[e,o]of Object.entries(n)){const n=t.querySelector(`[data-wcs-ssr-id="${e}"]`);if(n)for(const[t,e]of Object.entries(o))n[t]=e}}const f=t.querySelectorAll("[data-wcs-completed]");for(const t of f)t.removeAttribute("data-wcs-completed");return!0},loadState(t){const e=t.parentNode;if(!e)return null;const n=Cf.find(e);if(!n)return null;const o=n.stateData;return Object.keys(o).length>0?o:null},async emitSnapshot(t){await ea(t.rootNode);const e=Cf.extractStateData(t),n=document.createElement(o.tagNames.ssr);n.setAttribute("version",Ec),Cf.buildContent(n,e),t.parentNode?.insertBefore(n,t)}};let Df=!1;const zf={name:"ssr",install(){!function(){var e;Df||(Df=!0,Ki=Wf,e=t=>{t.get(o.tagNames.ssr)||t.define(o.tagNames.ssr,Cf)},ec.includes(e)||ec.push(e),function(){const e=globalThis;void 0===e[t]&&(e[t]=Tf)}())}()}},Bf="[wcs/scan-declaration-invalid]",Ff=Object.freeze([]);function Hf(t){return`${F} entry "${t}"`}function qf(t,e){for(const n of t.cumulativePaths)if(e.has(n))return n;return null}function Uf(t,e,n,o){return`[wcs/scan-source-computed] ${t} ${e} "${n}" ${o===n?"is a getter":o.includes(`${l}${l}`)?`is computed by the recursive getter "${o}"`:`is under the getter "${o}"`}. A getter re-evaluates whenever its inputs change, so folding it would count re-evaluations, not events. Fold the plain value the getter reads, or use "on" with an event token.${it}`}function Gf(t,e,n){0===n.length&&Z(`${Bf} ${t} "${e}" must be a non-empty state path.${it}`),n.startsWith("$")&&Z(`${Bf} ${t} ${e} "${n}" must not start with "$" (reserved namespace).${it}`),n.includes("@")&&Z(`${Bf} ${t} ${e} "${n}" must not contain "@" — there is a single state tree per root.${it}`),n in Object.prototype&&Z(`${Bf} ${t} ${e} "${n}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${it}`);const o=nt(n);for(const s of o.segments)0===s.length&&Z(`${Bf} ${t} ${e} "${n}" has an empty path segment.${it}`);return o.wildcardCount>c&&Z(`${Bf} ${t} ${e} "${n}" exceeds the maximum wildcard depth (128).`),o}function Vf(t,e,n,o){const s=Hf(t);0===t.length&&Z(`${Bf} ${F} entry name must be a non-empty string.${it}`),(t.includes(a)||t.includes(l))&&Z(`${Bf} ${s} must be a flat property name ("${a}" and "${l}" are not allowed). The output is a property the runtime owns.${it}`),t.startsWith("$")&&Z(`${Bf} ${s} must not start with "$" (reserved namespace).${it}`),t in Object.prototype&&Z(`${Bf} ${s} must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").${it}`),e.has(t)&&Z(`${Bf} ${s} conflicts with a getter declared on the state.${it}`),n.has(t)&&Z(`${Bf} ${s} conflicts with a setter declared on the state.${it}`),o.has(t)&&Z(`${Bf} ${s} conflicts with the ${z} entry of the same name — each output has exactly one owner.${it}`)}function Kf(t,e,n){const o=e.get(t);e.has(t)&&o!==n.initial&&!function(t,e){return"function"==typeof e&&!0===Fh.get(e)?.has(t)}(t,o)&&Z(`${Bf} ${Hf(t)} conflicts with a method (a function-valued property) declared on the state. The output is a property the runtime owns.${it}`)}function Jf(t,e,n,o,s,r){const i=Hf(t),l=void 0!==e.from,c=void 0!==e.on;if(l===c&&Z(`${Bf} ${i} must declare exactly one of "from" (a state path) or "on" (an event-token name).${it}`),c){const t=e.on;return"string"==typeof t&&0!==t.length||Z(`${Bf} ${i} "on" must be a non-empty event-token name.${it}`),n.has(t)||Z(`${Bf} ${i} on "${t}" is not declared in ${W}.${rt(t,n)}${it}`),{kind:"event",tokenName:t}}const u=e.from;"string"!=typeof u&&Z(`${Bf} ${i} "from" must be a state path string.${it}`);const d=Gf(i,"from",u),h=qf(d,o)??r?.recursiveGetterOwning(u)??null;null!==h&&Z(Uf(i,"from",u,h));const f=qf(d,s);return null!==f&&Z(function(t,e,n){return`${Bf} ${t} from "${e}" ${n===e?"is a setter without a getter":`is under the setter without a getter "${n}"`}, so it always reads undefined and every fold would receive undefined. Fold the plain value the setter writes, or use "on" with an event token.${it}`}(i,u,f)),(u===t||u.startsWith(t+a))&&Z(`${Bf} ${i} from "${u}" reads the entry's own output — the scan would fold its own writes forever.${it}`),{kind:"path",path:u,pathInfo:d}}function Qf(t,e,n,o){if(void 0===e)return Ff;const s=Hf(t);Array.isArray(e)||Z(`${Bf} ${s} "resetOn" must be an array of state paths.${it}`);const r=[];for(const t of e){"string"!=typeof t&&Z(`${Bf} ${s} "resetOn" must contain only state path strings.${it}`);const e=Gf(s,"resetOn",t);e.wildcardCount>0&&Z(`${Bf} ${s} resetOn "${t}" must not contain "${l}" — a reset returns the whole output to "initial".${it}`);const i=qf(e,o);null!==i&&Z(Uf(s,"resetOn",t,i)),"path"===n.kind&&t===n.path&&Z(`${Bf} ${s} resetOn "${t}" is the entry's own "from" — every change would reset instead of fold.${it}`),"path"===n.kind&&t.startsWith(n.path+a)&&Z(`${Bf} ${s} resetOn "${t}" sits under the entry's own "from" "${n.path}" — every write of "from" also lands it, so the reset would win every time and nothing would fold.${it}`),r.push(t)}return r}function Xf(t){const e=t.fold;return(n,o,...s)=>{const r=n;let i="read-output";try{const n=r[t.name];i="threw";const a=function(t){return Ah.has(t)}(t),l=a&&!Bh(n,t.initial)?Dh(t.initial):n,c=e(l,o,...s);if(Kh(c))return void Jh(t.name,c);Object.is(c,n)||(i="write",r[t.name]=c,Hh(t.name,c)),a&&Oh(t)}catch(e){Vh(t.name,e,i)}}}const Yf="scanEntries",Zf={order:8,validate(t,e,n){const o=function(t,e,n=null){const o=t[F];if(void 0===o)return null;("object"!=typeof o||null===o||Array.isArray(o))&&Z(`${Bf} ${F} must be an object mapping output names to scan definitions ({ from | on, initial, fold, resetOn? }).${it}`);const s=new Set,r=new Set,i=new Set,a=new Map;for(const[e,n]of Object.entries(Xl(t)))"function"==typeof n.get?s.add(e):"function"==typeof n.set&&i.add(e),"function"==typeof n.set&&r.add(e),"function"==typeof n.value&&a.set(e,n.value);const l=function(t){za(t);const e=t[z];return"object"!=typeof e||null===e?new Set:new Set(Object.keys(e))}(t),c=[];let u=0;for(const[t,d]of Object.entries(o)){Vf(t,s,r,l),("object"!=typeof d||null===d||Array.isArray(d))&&Z(`${Bf} ${Hf(t)} must be an object ({ from | on, initial, fold, resetOn? }).${it}`);const o=d;Kf(t,a,o);const h=Jf(t,o,e,s,i,n);"initial"in o||Z(`${Bf} ${Hf(t)} requires "initial" — the seed of the accumulator and the value "resetOn" returns to.${it}`),"function"!=typeof o.fold&&Z(`${Bf} ${Hf(t)} fold must be a function.${it}`);const f=Qf(t,o.resetOn,h,s);c.push({name:t,source:h,fold:o.fold,initial:o.initial,resetOn:f,order:u++})}return function(t){const e=new Set(t.map(t=>t.name)),n=new Map;for(const o of t){for(const t of o.resetOn){const n=nt(t).segments[0];e.has(n)&&Z(`${Bf} ${Hf(o.name)} resetOn "${t}" reads the ${F} output "${n}" — a reset driven by an accumulator is a feedback loop. Reset on the plain inputs instead.${it}`)}if("path"===o.source.kind){const t=o.source.pathInfo.segments[0];e.has(t)&&n.set(o.name,t)}}for(const t of n.keys()){const o=[t];let s=n.get(t);for(;void 0!==s&&o.length<=e.size;)s===t&&Z(`${Bf} ${F} entries ${[...o,t].map(t=>`"${t}"`).join(" → ")} feed each other through "from" — each fold would re-trigger the next forever.${it}`),o.push(s),s=n.get(s)}}(c),c.length>0?c:null}(e,n.get("eventTokenNames")??new Set,n.get("recursionRegistry")??null);n.set(Yf,o)},applyEarly(t,e,n){const o=n.get(Yf)??null;null!==o&&(function(t,e){for(const n of e)if(!(n.name in t)){const e=Dh(n.initial);t[n.name]=e,Hh(n.name,e)}}(e,o),function(t,e){for(const n of e)"event"===n.source.kind&&An(t,n.source.tokenName).subscribe(Xf(n))}(t,o))},register(t,e,n){const o=n.get(Yf)??null,s=function(t){const e=new Map,n=Jd(t);if(void 0!==n)for(const t of n.entries)Oh(t)&&e.set(t.name,t.resetOn);return Qd(t),e}(t);t.setScanPaths?.(null===o?null:function(t,e,n){const o=function(t,e){Qd(t);const n=new Map,o=new Map,s=new Map;for(const t of e){"path"===t.source.kind&&Kd(n,t.source.path,t);for(const e of t.resetOn)Kd(o,e,t),"event"===t.source.kind&&Kd(s,e,t)}const r={entries:new Set(e),byFromPath:n,byResetPath:o,eventResetByPath:s};return qd.set(t,r),r}(t,e);for(const o of e){const e=n.get(o.name);"event"===o.source.kind&&void 0!==e&&o.resetOn.some(n=>e.includes(n)&&qs().hasQueuedPath(t,n))&&Mh(o)}const s=new Set;for(const e of o.byFromPath.keys())s.add(e),t.setPathInfo(e,"prop","scan");for(const e of o.byResetPath.keys())t.setPathInfo(e,"prop","scan");return s.size>0?s:null}(t,o,s))}};let tp=!1;const ep=Object.freeze([]),np=Object.freeze([]);function op(t,e,n){const o=new Set([n]),s=[n];for(;s.length>0;){const n=s.pop(),r=t.staticDependency.get(n)??ep,i=t.dynamicDependency.get(n)??ep,a=e.byFromPath.get(n)??np;for(const t of[...r,...i,...a.map(t=>t.name)])o.has(t)||(o.add(t),s.push(t))}return o}const sp=(t,e)=>e,rp=new Set;const ip=new WeakMap,ap=new WeakMap;function lp(t,e,n){return new Proxy(Object.create(null),{get(e,o){if("string"!=typeof o)return;const s=kh(t).get(o);return void 0!==s?n(s):void 0},has:(e,n)=>"string"==typeof n&&kh(t).has(n),ownKeys:()=>Array.from(kh(t).keys()),getOwnPropertyDescriptor(e,o){if("string"!=typeof o)return;const s=kh(t).get(o);return void 0!==s?{configurable:!0,enumerable:!0,value:n(s)}:void 0},set(){Z(`${e} namespace is read-only; assigning to it is not allowed.`)},deleteProperty(){Z(`${e} namespace is read-only; deleting from it is not allowed.`)}})}function cp(t){const e=ip.get(t);if(void 0!==e)return e;const n=lp(t,G,t=>t.status);return ip.set(t,n),n}function up(t){const e=ap.get(t);if(void 0!==e)return e;const n=lp(t,V,t=>t.error);return ap.set(t,n),n}function dp(t){ip.delete(t),ap.delete(t)}let hp=null;function fp(t,e){let n=t;for(let t=1;t<e.length;t++){if(Object(n)!==n)return;n=Reflect.get(n,e[t])}return n}const pp={read(t,e){!function(t,e){null!==hp&&hp.add(Ue(t,e))}(t,e);const n=e.pathInfo.segments[0];return n===G?fp(cp(t),e.pathInfo.segments):n===V?fp(up(t),e.pathInfo.segments):Ua},get:(t,e)=>e===G?cp(t.stateElement):e===V?up(t.stateElement):Ua};function mp(t){$p();const e=kh(t);if(0!==e.size){!function(t){vh.add(t)}(t);for(const n of e.values())gp(t,n)}}function gp(t,e){e.controller?.abort();const n=new AbortController;e.controller=n;const o=function(t,e){const n=e.definition.args;if(null===n)return void e.depAddresses.clear();const o=hp,s=new Set;let r;hp=s;try{t.createState("readonly",t=>{r=n(t)})}finally{hp=o}r instanceof Promise&&Z(`${z} entry "${e.name}" args must be synchronous (it returned a Promise).`);const i=`${G}${a}${e.name}`,l=`${V}${a}${e.name}`;for(const n of s){const o=n.absolutePathInfo.pathInfo;n.absolutePathInfo.stateElement!==t||o.path!==e.name&&o.path!==i&&o.path!==l||Z(`${z} entry "${e.name}" args must not read the stream itself ("${o.path}"): a self-dependency would restart the stream on its own writes (infinite loop).`),o.wildcardCount>0&&Z(`${z} entry "${e.name}" args must not read wildcard paths ("${o.path}"): wildcard dependencies are out of scope.`)}return e.depAddresses=s,r}(t,e);!function(t,e){const n=Jd(t);if(void 0!==n&&0!==e.depAddresses.size)for(const o of n.entries){if("path"!==o.source.kind||o.source.pathInfo.segments[0]!==e.name)continue;const s=op(t,n,o.name);for(const t of e.depAddresses){const n=t.absolutePathInfo.pathInfo.path;s.has(n)&&Z(`[wcs/scan-feedback-loop] ${z} entry "${e.name}" args read "${n}", which is derived from the ${F} output "${o.name}" that this stream feeds. Every landing would restart the stream on its own result. Advance the cursor from an event ($on) and keep it a plain property instead of deriving it from the accumulator.`)}}}(t,e),t.createState("writable",t=>{t[e.name]=e.definition.initial}),yp(t,e,"active",null);const s=e.definition,r={fold(n){t.createState("writable",t=>{t[e.name]=s.fold(t[e.name],n)})},done(){yp(t,e,"done",null)},fail(o){yp(t,e,"error",o),n.abort()}};!async function(t,e,n,o){let s=null,r=null;const i=()=>{if(s&&s!==r){r=s;try{s.return?.()?.then?.(void 0,()=>{})}catch{}}};n.addEventListener("abort",i,{once:!0});try{const r=await t(e,n);if(s=function(t,e){if("function"==typeof t?.getReader)return async function*(t,e){const n=t.getReader(),o=()=>{n.cancel().catch(()=>{})};e.addEventListener("abort",o,{once:!0});try{for(;;){const{done:t,value:e}=await n.read();if(t)return;yield e}}finally{e.removeEventListener("abort",o),n.releaseLock()}}(t,e);if("function"==typeof t?.[Symbol.asyncIterator])return t;throw new TypeError("[@wcstack/state] $streams: source must return an AsyncIterable or a ReadableStream (got neither).")}(r,n)[Symbol.asyncIterator](),n.aborted)return void i();for(;;){const t=await s.next();if(t.done)break;if(n.aborted)return;o.fold(t.value)}if(n.aborted)return;o.done()}catch(t){if(n.aborted)return;o.fail(t)}finally{n.removeEventListener("abort",i)}}(s.source,o,n.signal,r)}function yp(t,e,n,o){e.status=n,e.error=o;const s=function(t,e){return Sh.get(t)?.get(e)??{status:"idle",error:null}}(t,e.name),r=s.status!==n,i=!Object.is(s.error,o);(r||i)&&(function(t,e,n,o){let s=Sh.get(t);void 0===s&&(s=new Map,Sh.set(t,s)),s.set(e,{status:n,error:o})}(t,e.name,n,o),t.createState("writable",t=>{r&&t.$postUpdate(`${G}${a}${e.name}`),i&&t.$postUpdate(`${V}${a}${e.name}`)}))}function bp(t){const e=vh;if(0===e.size)return;const n=[];for(const o of e)for(const e of kh(o).values())for(const s of e.depAddresses)if(t.has(s)){n.push({stateElement:o,entry:e});break}for(const{stateElement:t,entry:o}of n)if(e.has(t)&&kh(t).get(o.name)===o)try{gp(t,o)}catch(n){o.controller?.abort(),e.has(t)&&kh(t).get(o.name)===o&&yp(t,o,"error",n)}}let wp=!1;const vp=new WeakMap,_p={order:20,apply(t,e){var n;dp(t),Ih(n=t),_h(n),Nh.delete(n),function(t,e){za(e);const n=e[z];if(void 0===n)return void xh(t,rp);"object"==typeof n&&null!==n||Z(`${z} must be an object mapping stream names to stream definitions.`);const o=new Map;for(const[s,r]of Object.entries(n)){0===s.length&&Z(`${z} entry name must be a non-empty string.`),s.includes(a)&&Z(`${z} entry "${s}" must be a flat property name ("${a}" is not allowed).`),s.includes(l)&&Z(`${z} entry "${s}" must be a flat property name ("${l}" is not allowed).`),s.startsWith("$")&&Z(`${z} entry "${s}" must not start with "$" (reserved namespace).`),s in Object.prototype&&Z(`${z} entry "${s}" must not be a property name inherited from Object.prototype (e.g. "__proto__", "constructor").`),t.getterPaths.has(s)&&Z(`${z} entry "${s}" conflicts with a getter declared on the state.`),t.setterPaths.has(s)&&Z(`${z} entry "${s}" conflicts with a setter declared on the state.`),"object"==typeof r&&null!==r||Z(`${z} entry "${s}" must be an object ({ args?, source, fold?, initial? }).`);const n=r;"function"!=typeof n.source&&Z(`${z} entry "${s}" source must be a function.`);const i=void 0!==n.fold;i&&"function"!=typeof n.fold&&Z(`${z} entry "${s}" fold must be a function.`),i&&!("initial"in n)&&Z(`${z} entry "${s}" requires "initial" when fold is specified (reduce needs a seed value).`),void 0!==n.args&&"function"!=typeof n.args&&Z(`${z} entry "${s}" args must be a function.`);const c={name:s,definition:{args:n.args??null,source:n.source,fold:n.fold??sp,initial:n.initial},status:"idle",error:null,controller:null,depAddresses:new Set};s in e||(e[s]=c.definition.initial),o.set(s,c)}!function(t,e){Nh.set(t,e)}(t,o),xh(t,new Set(o.keys()))}(t,e),void 0!==e[z]&&t.attachAddressHooks?.("streams",z)},activate(t,n){if(!e()&&null!=t.connectedRootNode){if(null===n){if(!0!==t.initialized)return;return mp(t),void vp.set(t,t.connectGeneration??0)}n===t.connectGeneration&&vp.get(t)!==n&&mp(t)}},deactivate(t){Ih(t),dp(t)}};function $p(){wp||(wp=!0,Ka("streams",pp),Ya("streams",_p),Bs(bp,20))}const Sp=[lu,{name:"temporal",install(){yf(),tp||(tp=!0,Ya("scan",Zf),zs(Th)),$p()}},Tu,Pf,zf,zc,Qc];await(function(t){for(let e=0;e<t.length;e++)t[e].install()}(Sp),void nc(void 0,void 0));const xp={route:"wcs-route",router:"wcs-router",outlet:"wcs-outlet",layout:"wcs-layout",layoutOutlet:"wcs-layout-outlet",link:"wcs-link",head:"wcs-head",guardHandler:"wcs-guard-handler"},Pp=!1,Np=[".html"];function kp(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function Ip(t,e){if(e&&"cause"in e)throw new Error(`[@wcstack/router] ${t}`,{cause:e.cause});throw new Error(`[@wcstack/router] ${t}`)}let Ap=class extends Error{fallbackPath;constructor(t,e){super(t),this.fallbackPath=e}};const Ep={int:{typeName:"int",pattern:/^-?\d+$/,parse(t){if(this.pattern.test(t))return parseInt(t,10)}},float:{typeName:"float",pattern:/^-?\d+(?:\.\d+)?$/,parse(t){if(this.pattern.test(t))return parseFloat(t)}},bool:{typeName:"bool",pattern:/^(true|false|0|1)$/,parse(t){if(this.pattern.test(t))return"true"===t||"1"===t}},uuid:{typeName:"uuid",pattern:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,parse(t){if(this.pattern.test(t))return t}},slug:{typeName:"slug",pattern:/^[a-z0-9]+(?:-[a-z0-9]+)*$/,parse(t){if(this.pattern.test(t))return t}},isoDate:{typeName:"isoDate",pattern:/^\d{4}-\d{2}-\d{2}$/,parse(t){if(!this.pattern.test(t))return;const[e,n,o]=t.split("-").map(Number),s=new Date(e,n-1,o);return s.getFullYear()===e&&s.getMonth()===n-1&&s.getDate()===o?s:void 0}},any:{typeName:"any",pattern:/^.+$/,parse(t){if(this.pattern.test(t))return t}}};function Cp(t){const e={};for(const[n,o]of new URLSearchParams(t))e[n]=o;return Object.freeze(e)}function Tp(t,e){const n=Object.keys(t),o=Object.keys(e);if(n.length!==o.length)return!1;for(const o of n){if(!Object.prototype.hasOwnProperty.call(e,o))return!1;if(t[o]!==e[o])return!1}return!0}const Mp={static:2,param:1,"catch-all":0};let Op=class extends EventTarget{_target;_parentCore=null;_path="";_name="";_isFallbackRoute=!1;_segmentInfos=[];_absoluteSegmentInfos;_paramNames;_absoluteParamNames;_weight;_absoluteWeight;_segmentCount;_params={};_typedParams={};_active=!1;_hasGuard=!1;_guardHandler=null;_guardFallbackPath="";_waitForSetGuardHandler=null;_resolveSetGuardHandler=null;_guardHandlerLoadFailed=!1;constructor(t){super(),this._target=t??this}get parentCore(){return this._parentCore}set parentCore(t){this._parentCore=t}get path(){return this._path}get name(){return this._name}get isFallbackRoute(){return this._isFallbackRoute}get isRelative(){return!this._path.startsWith("/")}get segmentInfos(){return this._segmentInfos}_checkParentCore(t,e){return this._isFallbackRoute||(this.isRelative&&!this._parentCore&&Ip(`${xp.route} is relative but has no parent route.`),!this.isRelative&&this._parentCore&&Ip(`${xp.route} is absolute but has a parent route.`)),this.isRelative&&this._parentCore?t(this._parentCore):e()}get absolutePath(){return this._checkParentCore(t=>{const e=t.absolutePath;return e.endsWith("/")?e+this._path:e+"/"+this._path},()=>this._path)}get absoluteSegmentInfos(){return void 0===this._absoluteSegmentInfos&&(this._absoluteSegmentInfos=this._checkParentCore(t=>[...t.absoluteSegmentInfos,...this._segmentInfos],()=>[...this._segmentInfos])),this._absoluteSegmentInfos}get params(){return this._params}get typedParams(){return this._typedParams}get active(){return this._active}get paramNames(){if(void 0===this._paramNames){const t=[];for(const e of this._segmentInfos)e.paramName&&t.push(e.paramName);this._paramNames=t}return this._paramNames}get absoluteParamNames(){return void 0===this._absoluteParamNames&&(this._absoluteParamNames=this._checkParentCore(t=>[...t.absoluteParamNames,...this.paramNames],()=>[...this.paramNames])),this._absoluteParamNames}get weight(){if(void 0===this._weight){let t=0;for(const e of this._segmentInfos)t+=Mp[e.type];this._weight=t}return this._weight}get absoluteWeight(){return void 0===this._absoluteWeight&&(this._absoluteWeight=this._checkParentCore(t=>t.absoluteWeight+this.weight,()=>this.weight)),this._absoluteWeight}get segmentCount(){if(void 0===this._segmentCount){let t=0;for(const e of this._segmentInfos)"catch-all"!==e.type&&t++;this._segmentCount=""===this._path?0:t}return this._segmentCount}get absoluteSegmentCount(){return this._checkParentCore(t=>t.absoluteSegmentCount+this.segmentCount,()=>this.segmentCount)}parsePath(t,e={}){this._segmentInfos=[],this._absoluteSegmentInfos=void 0,this._paramNames=void 0,this._absoluteParamNames=void 0,this._weight=void 0,this._absoluteWeight=void 0,this._segmentCount=void 0,this._path=t,this._name=e.name||"",this._isFallbackRoute=e.isFallback||!1,e.isIndex&&this._segmentInfos.push({type:"static",segmentText:"",paramName:null,pattern:/^$/,isIndex:!0});const n=t.split("/");for(let t=0;t<n.length;t++){const o=n[t];if(!(""===o&&t===n.length-1&&t>0)){if("*"===o){this._segmentInfos.push({type:"catch-all",segmentText:o,paramName:"*",pattern:new RegExp("^(.*)$")});break}if(o.startsWith(":")){const t=o.match(/^:([^()]+)(\(([^)]+)\))?$/);let e,n="any";t?(e=t[1],t[3]&&Object.keys(Ep).includes(t[3])&&(n=t[3])):e=o.substring(1),this._segmentInfos.push({type:"param",segmentText:o,paramName:e,pattern:new RegExp("^([^\\/]+)$"),paramType:n})}else""===o&&e.isIndex||this._segmentInfos.push({type:"static",segmentText:o,paramName:null,pattern:new RegExp(`^${o}$`)})}}this._hasGuard=e.hasGuard||!1,this._hasGuard&&(this._guardFallbackPath=e.guardFallback||"/",this._waitForSetGuardHandler=new Promise(t=>{this._resolveSetGuardHandler=t}))}setParams(t,e){const n=this._active;this._params=t,this._typedParams=e,this._active=!0,this._target.dispatchEvent(new CustomEvent("wcs-route:params-changed",{detail:{params:t,typedParams:e},bubbles:!0})),n||this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!0,bubbles:!0}))}clearParams(){const t=this._active;this._params={},this._typedParams={},this._active=!1,t&&this._target.dispatchEvent(new CustomEvent("wcs-route:active-changed",{detail:!1,bubbles:!0}))}shouldChange(t){for(const e of this.paramNames)if(this._params[e]!==t[e])return!0;return!1}get hasGuard(){return this._hasGuard}get guardHandler(){return this._guardHandler||Ip(`${xp.route} has no guardHandler.`),this._guardHandler}set guardHandler(t){this._guardHandler=t,this._resolveSetGuardHandler?.()}notifyGuardHandlerLoadFailed(){this._guardHandlerLoadFailed=!0,this._resolveSetGuardHandler?.()}async guardCheck(t){if(this._hasGuard&&this._waitForSetGuardHandler&&await this._waitForSetGuardHandler,this._guardHandler){const e=t.path,n=t.lastPath,o=await this._guardHandler(e,n,function(t){return Object.freeze({params:Object.freeze({...t.params}),typedParams:Object.freeze({...t.typedParams}),searchParams:Cp(t.search??""),routeName:t.routes[t.routes.length-1]?.name??""})}(t));if("string"==typeof o&&""!==o)throw new Ap("Navigation cancelled by guard.",o);if(!o)throw new Ap("Navigation cancelled by guard.",this._guardFallbackPath);return"object"==typeof o?o:null}if(this._hasGuard&&this._guardHandlerLoadFailed)throw new Ap("Navigation cancelled: guard handler failed to load.",this._guardFallbackPath);return null}},Lp=class extends HTMLElement{_core;_routeParentNode=null;_routeChildNodes=[];_routerNode=null;_uuid=kp();_placeHolder=document.createComment(`@@route:${this._uuid}`);_childNodeArray;_childIndex=0;_initialized=!1;_routes;constructor(){super(),this._core=new Op(this)}get routeParentNode(){return this._routeParentNode}get routeChildNodes(){return this._routeChildNodes}get routerNode(){return this._routerNode||Ip(`${xp.route} has no routerNode.`),this._routerNode}get uuid(){return this._uuid}get placeHolder(){return this._placeHolder}get childNodeArray(){return void 0===this._childNodeArray&&(this._childNodeArray=Array.from(this.childNodes)),this._childNodeArray}adoptChildNodes(t){for(this._childNodeArray=[...t];this.firstChild;)this.removeChild(this.firstChild)}get routes(){return void 0===this._routes&&(this._routes=this.routeParentNode?this.routeParentNode.routes.concat(this):[this]),this._routes}get childIndex(){return this._childIndex}get path(){return this._core.path}get name(){return this._core.name}get isRelative(){return this._core.isRelative}get absolutePath(){return this._core.absolutePath}get segmentInfos(){return this._core.segmentInfos}get absoluteSegmentInfos(){return this._core.absoluteSegmentInfos}get params(){return this._core.params}get typedParams(){return this._core.typedParams}get paramNames(){return this._core.paramNames}get absoluteParamNames(){return this._core.absoluteParamNames}get weight(){return this._core.weight}get absoluteWeight(){return this._core.absoluteWeight}get segmentCount(){return this._core.segmentCount}get absoluteSegmentCount(){return this._core.absoluteSegmentCount}get fullpath(){return this.absolutePath}get hasGuard(){return this._core.hasGuard}get guardHandler(){return this._core.guardHandler}set guardHandler(t){this._core.guardHandler=t}setParams(t,e){this._core.setParams(t,e)}clearParams(){this._core.clearParams()}shouldChange(t){return this._core.shouldChange(t)}async guardCheck(t){return this._core.guardCheck(t)}notifyGuardHandlerLoadFailed(){this._core.notifyGuardHandlerLoadFailed()}testAncestorNode(t){let e=this._routeParentNode;for(;e;){if(e===t)return!0;e=e.routeParentNode}return!1}initialize(t,e){if(this._initialized)return;let n;this._initialized=!0;let o=!1,s=!1;this.hasAttribute("path")?n=this.getAttribute("path")||"":this.hasAttribute("index")?(n="",o=!0):this.hasAttribute("fallback")?(n="",s=!0):Ip(`${xp.route} should have a "path" or "index" attribute.`),this._routerNode=t,this._routeParentNode=e;const r=e||t;r.routeChildNodes.push(this),this._childIndex=r.routeChildNodes.length-1,s&&(e&&Ip(`${xp.route} with fallback attribute must be a direct child of ${xp.router}.`),t.fallbackRoute&&Ip(`${xp.router} can have only one fallback route.`),t.fallbackRoute=this),e&&(this._core.parentCore=e._core),this._core.parsePath(n,{isIndex:o,isFallback:s,hasGuard:this.hasAttribute("guard"),guardFallback:this.getAttribute("guard"),name:this.getAttribute("name")||""}),this.setAttribute("fullpath",this.absolutePath)}};const Rp=Symbol.for("wcstack.trustedTypes.policy"),jp=Symbol.for("wcstack.trustedTypes.internal"),Wp="wcstack";function Dp(){const t=globalThis[Rp];return null===t||"object"!=typeof t?null:t}let zp=!1;function Bp(t){const e=function(){const t=globalThis,e=t[jp];if(void 0!==e)return e;const n=globalThis.trustedTypes;let o=null;if(n&&"function"==typeof n.createPolicy)try{o=n.createPolicy(Wp,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){"function"!=typeof Dp()?.createHTML&&console.error(`[@wcstack/router] Could not create the Trusted Types policy "${Wp}". Allow it in the CSP (\`trusted-types ${Wp};\`), or inject your own policy at globalThis[Symbol.for("wcstack.trustedTypes.policy")]. See docs/csp.md section 7.`,t)}return t[jp]=o,o}(),n=e?.createHTML;if("function"==typeof n)return n.call(e,t);if(!("trustedTypes"in globalThis))return t;const o=Dp(),s=o?.createHTML;return"function"==typeof s?(zp||(zp=!0,console.warn(`[@wcstack/router] Falling back to the injected Trusted Types policy to expand a layout template, because the "${Wp}" policy could not be created. If that policy sanitizes (e.g. DOMPurify), custom elements in the layout may be stripped. Allow \`trusted-types ${Wp};\` in the CSP to avoid this. See docs/csp.md section 7.`)),s.call(o,t)):t}const Fp=new Map;let Hp=class extends HTMLElement{_uuid=kp();constructor(){super()}async _loadTemplateFromSource(t){try{const e=await fetch(t);e.ok||Ip(`${xp.layout} failed to fetch layout from source: ${t}, status: ${e.status}`);const n=await e.text();return Fp.set(t,n),n}catch(e){Ip(`${xp.layout} failed to load layout from source: ${t}, error: ${e}`,{cause:e})}}_loadTemplateFromDocument(t){const e=document.getElementById(`${t}`);return e&&e instanceof HTMLTemplateElement?e.innerHTML:null}async loadTemplate(){const t=this.getAttribute("src"),e=this.getAttribute("layout");t&&e&&console.warn(`${xp.layout} have both "src" and "layout" attributes.`);const n=document.createElement("template");if(t)Fp.has(t)?n.innerHTML=Bp(Fp.get(t)||""):n.innerHTML=Bp(await this._loadTemplateFromSource(t)||"");else if(e){const t=this._loadTemplateFromDocument(e);t?n.innerHTML=Bp(t):console.warn(`${xp.layout} could not find template with id "${e}".`)}return n}get uuid(){return this._uuid}get enableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Pp}get name(){return this.getAttribute("name")||""}},qp=class extends HTMLElement{_routesNode=null;_lastRoutes=[];_initialized=!1;constructor(){super()}get routesNode(){return this._routesNode||Ip(`${xp.outlet} has no routesNode.`),this._routesNode}set routesNode(t){this._routesNode=t}get rootNode(){return this.shadowRoot?this.shadowRoot:this}get lastRoutes(){return this._lastRoutes}set lastRoutes(t){this._lastRoutes=[...t]}_resolveEnableShadowRoot(){return!!this.hasAttribute("enable-shadow-root")||!this.hasAttribute("disable-shadow-root")&&Pp}_initialize(){this._resolveEnableShadowRoot()&&this.attachShadow({mode:"open"}),this._initialized=!0}connectedCallback(){this._initialized||this._initialize()}disconnectedCallback(){this._lastRoutes=[]}};const Up=new Set(["props","states","attr",""]);function Gp(t,e,n){for(const[o,s]of Object.entries(e))switch(n){case"props":t.props={...t.props,[o]:s};break;case"states":t.states={...t.states,[o]:s};break;case"attr":null==s?t.removeAttribute(o):t.setAttribute(o,String(s));break;case"":t[o]=s}}function Vp(t,e){t.hasAttribute("data-bind")||Ip(`${t.tagName} has no 'data-bind' attribute.`);const n=t.getAttribute("data-bind")||"";Up.has(n)||Ip(`${t.tagName} has invalid 'data-bind' attribute: ${n}`);const o=n,s=function(t){const e=t.tagName.toLowerCase();if(e.includes("-"))return e;const n=t.getAttribute("is");return n&&n.includes("-")?n:null}(t);s&&void 0===customElements.get(s)?customElements.whenDefined(s).then(()=>{t.isConnected&&Gp(t,e,o)}).catch(()=>{Ip(`Failed to define custom element: ${s}`)}):Gp(t,e,o)}let Kp=class extends HTMLElement{_layout=null;_initialized=!1;_initializing=!1;_disconnectedDuringInit=!1;_layoutChildNodes=[];constructor(){super()}get layout(){return this._layout||Ip(`${xp.layoutOutlet} has no layout.`),this._layout}set layout(t){this._layout=t,this.setAttribute("name",t.name)}get name(){return this.layout.name}async _initialize(){this._initializing=!0;try{this._initialized=!0,this.layout.enableShadowRoot&&!this.shadowRoot&&this.attachShadow({mode:"open"});const t=await this.layout.loadTemplate();if(!this.isConnected)return void(this._initialized=!1);if(this.shadowRoot){this.shadowRoot.appendChild(t.content.cloneNode(!0));for(const t of Array.from(this.layout.childNodes))this._layoutChildNodes.push(t),this.appendChild(t)}else{const e=t.content.cloneNode(!0),n=new Map;e.querySelectorAll("slot").forEach(t=>{const e=t.getAttribute("name")||"";n.has(e)?console.warn(`${xp.layoutOutlet} duplicate slot name "${e}" in layout template.`):n.set(e,t)});const o=new Map,s=document.createDocumentFragment();for(const t of Array.from(this.layout.childNodes)){if(this._layoutChildNodes.push(t),t instanceof Element){const e=t.getAttribute("slot")||"";if(e.length>0&&n.has(e)){o.has(e)||o.set(e,document.createDocumentFragment()),o.get(e)?.appendChild(t);continue}}s.appendChild(t)}for(const[t,e]of n){const n=o.get(t);n&&e.replaceWith(n)}const r=n.get("");r&&r.replaceWith(s),this.appendChild(e)}}finally{this._initializing=!1}}async connectedCallback(){this._initialized||(this._disconnectedDuringInit=!1,await this._initialize(),!this._disconnectedDuringInit&&this.isConnected)}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0)}assignParams(t){for(const e of this._layoutChildNodes)e instanceof Element&&(e.querySelectorAll("[data-bind]").forEach(e=>{Vp(e,t)}),e.hasAttribute("data-bind")&&Vp(e,t))}};function Jp(){return document.createElement(xp.layoutOutlet)}const Qp="https://github.com/wcstack/wcstack/blob/main/docs/csp.md";function Xp(t,e){(async function(t,e){let n=null,o=null;const s=e.uuid||"",r=`\n//# sourceURL=${s?`wcs-guard-handler:${s}`:"wcs-guard-handler"}\n`,i=t.text+r;let a=!1;const l=t=>{t.effectiveDirective.startsWith("script-src")&&(a=!0)};document.addEventListener("securitypolicyviolation",l);try{if("function"==typeof URL.createObjectURL){const e=new Blob([i],{type:"application/javascript"}),s=URL.createObjectURL(e);try{n=await(import(s))}catch(t){o=t}finally{URL.revokeObjectURL(s)}}if(!n){const e=btoa(String.fromCodePoint(...(new TextEncoder).encode(i)));try{n=await(import(`data:application/javascript;base64,${e}`))}catch(t){Ip(function(t,e,n){return n?`The guard <script> was blocked by Content-Security-Policy. Guard scripts are inline-only and are evaluated through a blob: URL, so script-src must allow blob:. See ${Qp}`:`loadGuardHandler: failed to import guard script. data: URL error: ${t?.message??String(t)}`+(e?`. Blob URL error: ${e?.message??String(e)}`:"")+`. If this page sets a Content-Security-Policy, see ${Qp}`}(t,o,a),{cause:o??t})}}}finally{document.removeEventListener("securitypolicyviolation",l)}return n&&"function"==typeof n.default?n.default:null})(t,e).then(t=>{t?e.guardHandler=t:e.notifyGuardHandlerLoadFailed()}).catch(t=>{console.error("loadGuardHandler failed:",t),e.notifyGuardHandlerLoadFailed()})}function Yp(t,e){let n=t.get(e.absolutePath);n||(n=[]);for(const t of n)if(!e.testAncestorNode(t)){console.warn(`Duplicate route path detected: '${e.absolutePath}' (defined as '${e.path}')`);break}n.push(e),1===n.length&&t.set(e.absolutePath,n)}async function Zp(t,e,n,o){const s=n.length>0?n[n.length-1]:null,r=document.createDocumentFragment(),i=Array.from(e.childNodes);for(const e of i)if(e.nodeType===Node.ELEMENT_NODE){let i=e,a=e;const l=a.tagName.toLowerCase();if(l===xp.route){const e=document.createDocumentFragment();for(const t of Array.from(a.childNodes))e.appendChild(t);const r=document.importNode(a,!0);customElements.upgrade(r),r.appendChild(e);const l=r;l.initialize(t,s),Yp(o,l),n.push(l),i=l.placeHolder,a=l}else{if(l===xp.guardHandler){if(n.length>0){const t=n[n.length-1],e=a.querySelector('script[type="module"]');e&&Xp(e,t)}continue}if("template"===l){r.appendChild(a);continue}if(l===xp.layout){const t=document.createDocumentFragment();for(const e of Array.from(a.childNodes))t.appendChild(e);const e=document.importNode(a,!0);customElements.upgrade(e),e.appendChild(t);const n=e,o=Jp();o.layout=n,i=o,a=e}}const c=await Zp(t,a,n,o);a.replaceChildren(),a.appendChild(c),r.appendChild(i)}else r.appendChild(e);return r}async function tm(t){const e=new Map;return await Zp(t,t.template.content,[],e)}function em(t){return!1!==t.checkVisibility?.()}function nm(t,e,n,o){const s=function(t,e,n){const o={},s={};let r=!0,i=!1,a=0,l=0;for(;a<t.absoluteSegmentInfos.length;){const e=t.absoluteSegmentInfos[a];if(e.isIndex){a++;continue}if(0===a&&""===e.segmentText&&"static"===e.type){a++;continue}const c=n[l];if(void 0===c){r=!1;break}let u=!1;if("param"===e.type){const t=e.paramType||"any",n=Ep[t].parse(c);void 0!==n&&(e.paramName&&(o[e.paramName]=c,s[e.paramName]=n),u=!0)}else u=null!==e.pattern.exec(c);if(!u){r=!1;break}if("catch-all"===e.type){const t=n.slice(l).join("/");o["*"]=t,s["*"]=t,i=!0;break}a++,l++}let c=!1;return r&&(i||a===t.absoluteSegmentInfos.length&&l===n.length)&&(c=!0),c?{path:e,routes:t.routes,params:o,typedParams:s,lastPath:""}:null}(t,e,n);s&&o.push(s);for(const s of t.routeChildNodes)nm(s,e,n,o)}function om(t,e){const n=t.routeChildNodes,o=[],s=e.split("/"),r=s.filter((t,e)=>!(0===e&&""===t||e===s.length-1&&""===t&&s.length>1));for(const t of n)nm(t,e,r,o);return o.sort((t,e)=>{const n=t.routes.at(-1),o=e.routes.at(-1),s=n.absoluteSegmentCount-o.absoluteSegmentCount;if(0!==s)return-s;const r=n.absoluteWeight-o.absoluteWeight;return 0!==r?-r:n.childIndex-o.childIndex}),o.length>0?o[0]:null}let sm=null,rm=null;function im(){const t=Np;return 0===t.length?null:(sm===t&&rm||(sm=t,rm=new RegExp(`\\/[^/]+(?:${t.map(t=>t.replace(/\./g,"\\.")).join("|")})$`,"i")),rm)}function am(t){let e=t||"/";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=im();return n&&(e=e.replace(n,"")),""===e&&(e="/"),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),e}function lm(t,e){let n=t;return""!==e&&(t===e?n="":t.startsWith(e+"/")&&(n=t.slice(e.length))),""===n?"/":n}function cm(t){let e=t||"";if(!e)return"";e.startsWith("/")||(e="/"+e),e=e.replace(/\/{2,}/g,"/");const n=im();return n&&(e=e.replace(n,"")),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1)),"/"===e?"":e}function um(t){t.clearParams();for(const e of t.childNodeArray)e.parentNode?.removeChild(e)}function dm(t,e){const n={},o={};for(const s of t.paramNames)n[s]=e.params[s],o[s]=e.typedParams[s];t.setParams(n,o);for(const e of t.childNodeArray)if(e.nodeType===Node.ELEMENT_NODE){const n=e;n.querySelectorAll("[data-bind]").forEach(e=>{Vp(e,t.typedParams)}),n.hasAttribute("data-bind")&&Vp(n,t.typedParams),n.querySelectorAll(xp.layoutOutlet).forEach(e=>{e.assignParams(t.typedParams)}),n.tagName.toLowerCase()===xp.layoutOutlet&&n.assignParams(t.typedParams)}}function hm(t,e){dm(t,e);const n=t.placeHolder.parentNode,o=t.placeHolder.nextSibling;for(const e of t.childNodeArray)o?n?.insertBefore(e,o):n?.appendChild(e);return!0}const fm=Symbol.for("wcstack.transition-runner");const pm=Symbol.for("wcstack.binder");function mm(){const t=globalThis[pm];return null==t||"wcs-binder"!==t.protocol||"number"!=typeof t.version||t.version<1||"function"!=typeof t.bind?null:t}const gm=Symbol.for("wcstack.binder.pending"),ym=Symbol.for("wcstack.binder.taken");function bm(){const t=globalThis;let e=t[ym];return void 0===e&&(e=new WeakSet,t[ym]=e),e}function wm(t){const e=mm();return null===e?(function(){const t=globalThis;let e=t[gm];return void 0===e&&(e=[],t[gm]=e),e}().push(t),!1):(bm().add(t),e.bind(t),!0)}const vm=new WeakSet,_m="data-wcs";function $m(t,e,n){!vm.has(t)&&function(t){return t.hasAttribute(_m)||null!==t.querySelector(`[${_m}]`)}(t)&&(vm.add(t),function(t){"complete"===document.readyState?t():window.addEventListener("load",t,{once:!0})}(()=>{var o;null!==mm()||(o=t,bm().has(o))||console.warn(`[@wcstack/router] ${e} contains ${_m} bindings that will never be applied. A binding exists only for nodes that were in the document when @wcstack/state built its bindings, and these nodes were not. They will render empty. ${n}`)}))}function Sm(t){for(const e of t.childNodeArray)1===e.nodeType&&(wm(e)||$m(e,`<${e.tagName.toLowerCase()}> inside a route`,'Load @wcstack/state on this page, or render data-driven markup outside <wcs-router> — bind the router\'s `path` into state and gate the markup with <template data-wcs="if: …">. See examples/router-i18n.'))}async function xm(t,e){try{let t=null;for(const n of e.routes){const o=await n.guardCheck(e);o&&(t=null===t?o:Object.assign({},t,o))}e.data=t}catch(e){if(e instanceof Ap)return console.warn(`Navigation cancelled: ${e.message}. Redirecting to ${e.fallbackPath}`),queueMicrotask(()=>{t.navigate(e.fallbackPath).catch(t=>{console.error("Fallback navigation failed:",t)})}),!1;throw e}return!0}async function Pm(t,e,n,o,s=""){const r=lm(n,t.basename);if(t.isSameMatch(r))return t.commitNavigation({params:t.params,typedParams:t.typedParams,routeName:t.routeName,data:t.data,search:s,path:r}),!0;let i=om(t,r);i||(t.fallbackRoute?i={routes:[t.fallbackRoute],params:{},typedParams:{},path:r,lastPath:o}:Ip(`${xp.router} No route matched for path: ${r}`)),i.lastPath=o,i.search=s;const a=e.lastRoutes,l=await async function(t,e,n){if(!await xm(t,e))return!1;const o=new Set(e.routes),s=new Set(n),r=()=>{for(const t of n)o.has(t)||um(t);let t=!1;for(const o of e.routes)(!s.has(o)||o.shouldChange(e.params)||t)&&(t=hm(o,e),n.length>0&&!s.has(o)&&Sm(o))};let i;return 0===n.length?r():i=function(t,e,n){const o=function(t){const e=globalThis[fm];return null==e||"wcs-transition-runner"!==e.protocol||"number"!=typeof e.version||e.version<1||"function"!=typeof e.run?null:"function"==typeof e.accepts&&e.accepts(t)?e:null}(t);if(null!==o)return o.run(e,{source:t,types:n});e()}("router",r),void 0!==i&&await i,!0}(t,i,a);return!!l&&(t.commitNavigation({params:i.params,typedParams:i.typedParams,routeName:i.routes[i.routes.length-1]?.name??"",data:i.data??null,search:s,path:r}),e.lastRoutes=i.routes,a.length>0&&function(t,e){if("title"===t.announcePolicy){const e=t.a11yRegion;null!==e&&(e.textContent=document.title)}if("heading"===t.focusPolicy){const t=function(t){for(const e of t){if(e.nodeType!==Node.ELEMENT_NODE)continue;const t=e;if(/^H[1-6]$/.test(t.tagName)){if(em(t))return t}else for(const e of t.querySelectorAll("h1,h2,h3,h4,h5,h6"))if(em(e))return e}return null}(e.routes[e.routes.length-1].childNodeArray);if(null!==t)t.hasAttribute("tabindex")||t.setAttribute("tabindex","-1"),t.focus();else{const t=document.querySelector("[autofocus]");null!==t?t.focus():document.activeElement instanceof HTMLElement&&document.activeElement.blur()}}}(t,i),!0)}function Nm(){const t=window.navigation;return t?"function"!=typeof t.addEventListener||"function"!=typeof t.removeEventListener?null:t:null}function km(t){let e=t,n="";const o=e.indexOf("#");o>=0&&(n=e.slice(o),e=e.slice(0,o));let s="";const r=e.indexOf("?");return r>=0&&(s=e.slice(r),e=e.slice(0,r)),{pathname:e,search:s,hash:n}}function Im(t){return"?"===t?"":t}function Am(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}function Em(){const t=document.documentElement;return!!t&&t.hasAttribute("data-wcs-server")}const Cm="data-wcs-ssr",Tm="data-wcs-ssr-link",Mm="@@wcs-route-ph:",Om="@@wcs-route-start:",Lm="@@wcs-route-end:",Rm=Object.freeze({});class jm extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"navigateUrl",event:"wcs-router:navigate-url-changed",semantics:"state"},{name:"replaceUrl",event:"wcs-router:replace-url-changed",semantics:"state"},{name:"path",event:"wcs-router:path-changed",semantics:"state"},{name:"params",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.params},{name:"typedParams",event:"wcs-router:params-changed",semantics:"state",getter:t=>t.detail.typedParams},{name:"searchParams",event:"wcs-router:search-changed",semantics:"state"},{name:"routeName",event:"wcs-router:route-name-changed",semantics:"state"},{name:"data",event:"wcs-router:data-changed",semantics:"state"}],inputs:[{name:"basename",attribute:"basename"},{name:"navigateUrl"},{name:"replaceUrl"}],commands:[{name:"navigate",async:!0},{name:"replace",async:!0}]};_outlet=null;_template=null;_routeChildNodes=[];_basename="";_path="";_initialized=!1;_fallbackRoute=null;_listeningPopState=!1;_listeningNavigate=!1;_navigateUrl=null;_replaceUrl=null;_disconnectedDuringInit=!1;_initializing=!1;_a11yRegion=null;_params=Rm;_typedParams=Rm;_searchParams=Rm;_routeName="";_data=null;_hasCommitted=!1;_connectedCallbackPromise;_resolveConnectedCallback=null;_rejectConnectedCallback=null;constructor(){super(),this._connectedCallbackPromise=new Promise((t,e)=>{this._resolveConnectedCallback=t,this._rejectConnectedCallback=e}),this._connectedCallbackPromise.catch(()=>{})}get connectedCallbackPromise(){return this._connectedCallbackPromise}get a11yRegion(){return this._a11yRegion}get focusPolicy(){return"heading"===this.getAttribute("focus")?"heading":null}get announcePolicy(){return"title"===this.getAttribute("announce")?"title":null}_ensureA11yRegion(){if(null!==this._a11yRegion)return;const t=document.createElement("div");t.setAttribute("role","status"),t.style.position="absolute",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",t.style.clipPath="inset(50%)",t.style.whiteSpace="nowrap",this.appendChild(t),this._a11yRegion=t}_normalizePathname(t){return am(t)}_normalizeBasename(t){return cm(t)}_joinInternalPath(t,e){const n=this._normalizeBasename(t);let o=e.startsWith("/")?e:"/"+e;return o=this._normalizePathname(o),n?"/"===o?n+"/":n+o:o}_notifyLocationChange(){window.dispatchEvent(new CustomEvent("wcs:navigate"))}_getBasename(){let t=new URL(document.baseURI).pathname||"/";return"/"===t?"":this._normalizeBasename(t)}get basename(){return this._basename}_getOutlet(){const t=this.nextElementSibling;if(t&&t.matches(xp.outlet))return t;const e=document.createElement(xp.outlet);return this.parentNode?this.parentNode.insertBefore(e,this.nextSibling):document.body.appendChild(e),e}_getTemplate(){return this.querySelector("template")}get outlet(){return this._outlet||Ip(`${xp.router} has no outlet.`),this._outlet}get template(){return this._template||Ip(`${xp.router} has no template.`),this._template}get routeChildNodes(){return this._routeChildNodes}get path(){return this._path}set path(t){const e=this._path!==t;this._path=t,e&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t,bubbles:!0}))}get params(){return this._params}get typedParams(){return this._typedParams}get searchParams(){return this._searchParams}get routeName(){return this._routeName}get data(){return this._data}isSameMatch(t){return!!this._hasCommitted&&this._path===t}commitNavigation(t){const e=Object.freeze({...t.params}),n=Object.freeze({...t.typedParams}),o=Cp(t.search),s=t.data??null,r=this._data!==s,i=!Tp(this._params,e),a=this._routeName!==t.routeName,l=!Tp(this._searchParams,o),c=this._path!==t.path;r&&(this._data=s),i&&(this._params=e,this._typedParams=n),a&&(this._routeName=t.routeName),l&&(this._searchParams=o),this._path=t.path,this._hasCommitted=!0,r&&this.dispatchEvent(new CustomEvent("wcs-router:data-changed",{detail:this._data,bubbles:!0})),i&&this.dispatchEvent(new CustomEvent("wcs-router:params-changed",{detail:{params:this._params,typedParams:this._typedParams},bubbles:!0})),a&&this.dispatchEvent(new CustomEvent("wcs-router:route-name-changed",{detail:this._routeName,bubbles:!0})),l&&this.dispatchEvent(new CustomEvent("wcs-router:search-changed",{detail:this._searchParams,bubbles:!0})),c&&this.dispatchEvent(new CustomEvent("wcs-router:path-changed",{detail:t.path,bubbles:!0}))}get fallbackRoute(){return this._fallbackRoute}set fallbackRoute(t){this._fallbackRoute=t}get navigateUrl(){return this._navigateUrl}set navigateUrl(t){null!=t&&""!==t&&this._navigateUrl!==t&&(this._navigateUrl=t,this.navigate(t).catch(t=>{console.error(`${xp.router} navigate failed:`,t)}).finally(()=>{this._navigateUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:navigate-url-changed",{detail:null,bubbles:!0}))}))}get replaceUrl(){return this._replaceUrl}set replaceUrl(t){null!=t&&""!==t&&this._replaceUrl!==t&&(this._replaceUrl=t,this.replace(t).catch(t=>{console.error(`${xp.router} replace failed:`,t)}).finally(()=>{this._replaceUrl=null,this.dispatchEvent(new CustomEvent("wcs-router:replace-url-changed",{detail:null,bubbles:!0}))}))}async navigate(t){await this._performNavigation(t,!1)}async replace(t){await this._performNavigation(t,!0)}async _performNavigation(t,e){const n=km(t),o=""!==n.pathname||""===n.search&&""===n.hash?this._joinInternalPath(this._basename,n.pathname):window.location.pathname,s=o+Im(n.search)+n.hash,r=Nm();if(r?.navigate){const t=e?r.navigate(s,{history:"replace"}):r.navigate(s);await(t?.finished)}else{e?history.replaceState(null,"",s):history.pushState(null,"",s);const t=this._normalizePathname(o),r=this.isSameMatch(lm(t,this._basename));await Pm(this,this.outlet,t,this._path,Im(n.search))&&!r&&window.scrollTo(0,0),this._notifyLocationChange()}}_isOwnPath(t){return""===this._basename||t===this._basename||t.startsWith(this._basename+"/")}_onNavigateFunc(t){if(!t.canIntercept||t.hashChange||null!==t.downloadRequest)return;const e=new URL(t.destination.url),n=this._normalizePathname(e.pathname);if(!this._isOwnPath(n))return;const o=this.isSameMatch(lm(n,this._basename)),s=o&&("push"===t.navigationType||"replace"===t.navigationType),r=e.search,i=this;t.intercept({handler:async()=>{try{await Pm(i,i.outlet,n,i.path,r)}catch(t){throw console.error(`${xp.router} applyRoute failed:`,t),t}},scroll:s?"manual":"after-transition",focusReset:o||null!==i.focusPolicy?"manual":"after-transition"})}_onNavigate=this._onNavigateFunc.bind(this);_onPopState=async()=>{const t=this._normalizePathname(window.location.pathname);this._isOwnPath(t)&&(await Pm(this,this.outlet,t,this._path,window.location.search||""),this._notifyLocationChange())};async _initialize(){this._initializing=!0;try{const t=Em();this._basename=this._normalizeBasename(this.getAttribute("basename")||this._getBasename()||"");const e=null!==document.querySelector("base[href]"),n=new URL(window.location.href);""!==this._basename||e||"/"===n.pathname||Ip(`${xp.router} basename is empty, but current path is not "/".`),this._outlet=this._getOutlet(),this._outlet.routesNode=this,this._template=this._getTemplate(),this._template||Ip(`${xp.router} should have a <template> child element.`);const o=t?this._template.content.cloneNode(!0):null,s=await tm(this),r=!t&&this._outlet.hasAttribute(Cm);if(r||this._outlet.rootNode.appendChild(s),null!==o){const t=this._template.content;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(o)}0===this.routeChildNodes.length&&Ip(`${xp.router} has no route definitions.`),t||this._ensureA11yRegion();const i=this._normalizePathname(window.location.pathname);if(t)return await this._renderForSsr(i),void(this._initialized=!0);if(r){if(await this._hydrateFromSsr(i))return this._notifyLocationChange(),void(this._initialized=!0);this._outlet.removeAttribute(Cm);const t=this._outlet.rootNode;for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s)}await Pm(this,this.outlet,i,this._path,window.location.search||""),(r||null!==mm())&&this._offerInitialContentToBinder(),this._notifyLocationChange(),this._initialized=!0}finally{this._initializing=!1}}async _hydrateFromSsr(t){const e=this.outlet.rootNode,n=new Map;let o=!1;if(this._forEachRoute(t=>{n.has(t.absolutePath)?o=!0:n.set(t.absolutePath,t)}),o)return!1;if(null!==e.querySelector(xp.layoutOutlet))return!1;const s=new Map,r=new Map,i=new Map,a=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);let l=0;for(;a.nextNode();){const t=a.currentNode,e=t.data;if(l++,e.startsWith(Mm)){const o=e.slice(15);if(s.has(o)||!n.has(o))return!1;s.set(o,t)}else if(e.startsWith(Om)){const o=e.slice(18);if(r.has(o)||!n.has(o))return!1;r.set(o,{comment:t,index:l})}else if(e.startsWith(Lm)){const o=e.slice(16);if(i.has(o)||!n.has(o))return!1;i.set(o,{comment:t,index:l})}}if(r.size!==i.size)return!1;const c=[];for(const[t,e]of r){const n=i.get(t);if(!n)return!1;if(n.comment.parentNode!==e.comment.parentNode)return!1;if(n.index<=e.index)return!1;c.push({start:e.index,end:n.index})}for(const t of c)for(const e of c)if(t.start<e.start&&e.start<t.end&&t.end<e.end)return!1;const u=lm(t,this._basename);let d=om(this,u);if(!d){if(null===this._fallbackRoute)return!1;d={routes:[this._fallbackRoute],params:{},typedParams:{},path:u,lastPath:this._path}}if(d.lastPath=this._path,d.routes.length!==r.size)return!1;for(const t of d.routes)if(!r.has(t.absolutePath))return!1;const h=new Set;for(const t of this.routeChildNodes)h.add(t.absolutePath);for(const t of d.routes)for(const e of t.routeChildNodes)h.add(e.absolutePath);if(s.size!==h.size)return!1;for(const t of h)if(!s.has(t))return!1;for(const[t,e]of s){const o=n.get(t);e.parentNode.replaceChild(o.placeHolder,e)}for(const t of d.routes){const e=r.get(t.absolutePath).comment,n=i.get(t.absolutePath).comment,o=[],s=new Set;let a=e.nextSibling;for(;null!==a&&a!==n;){if(a.nodeType===Node.COMMENT_NODE){const t=a.data;if(t.startsWith(Om)){const e=t.slice(18);a=i.get(e).comment.nextSibling;continue}}if(s.has(a))a=a.nextSibling;else{if(a.nodeType===Node.ELEMENT_NODE&&a.tagName.toLowerCase()===xp.link){const t=a.anchorElement;null!==t&&s.add(t)}o.push(a),a=a.nextSibling}}t.adoptChildNodes(o)}for(const{comment:t}of r.values())t.remove();for(const{comment:t}of i.values())t.remove();this.outlet.removeAttribute(Cm);for(const t of d.routes)dm(t,d);return this.outlet.lastRoutes=d.routes,!await xm(this,d)||(this.commitNavigation({params:d.params,typedParams:d.typedParams,routeName:d.routes[d.routes.length-1].name,data:d.data??null,search:window.location.search||"",path:u}),!0)}async _renderForSsr(t){const e=lm(t,this._basename),n=om(this,e),o=n?.routes??(null!==this._fallbackRoute?[this._fallbackRoute]:[]);if(0===o.length&&Ip(`${xp.router} No route matched for path: ${e}`),!o.some(t=>t.hasGuard)){await Pm(this,this.outlet,t,this._path,window.location.search||""),this._offerInitialContentToBinder(),this._forEachRoute(t=>{t.placeHolder.data=`${Mm}${t.absolutePath}`}),this.outlet.setAttribute(Cm,"");for(const t of this.outlet.lastRoutes){const e=t.placeHolder.parentNode,n=t.childNodeArray,o=document.createComment(`${Om}${t.absolutePath}`),s=document.createComment(`${Lm}${t.absolutePath}`);e.insertBefore(o,n[0]??t.placeHolder.nextSibling);const r=n[n.length-1];e.insertBefore(s,r?r.nextSibling:o.nextSibling)}}}_offerInitialContentToBinder(){for(const t of this.outlet.lastRoutes)for(const e of t.childNodeArray)e.nodeType===Node.ELEMENT_NODE&&wm(e)}_forEachRoute(t,e=this){for(const n of e.routeChildNodes)t(n),this._forEachRoute(t,n)}async connectedCallback(){if(function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Am(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),Em()){try{await Promise.resolve(),this.hasAttribute("enable-ssr")&&!this._initialized&&await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}return void this._resolveConnectedCallback?.()}if(!this._initialized){this._disconnectedDuringInit=!1;try{null===this._getTemplate()&&await Promise.resolve(),await this._initialize()}catch(t){throw this._rejectConnectedCallback?.(t),t}if(this._disconnectedDuringInit)return void this._resolveConnectedCallback?.()}this._initialized&&this._ensureA11yRegion();const t=Nm();t&&!this._listeningNavigate&&(t.addEventListener("navigate",this._onNavigate),this._listeningNavigate=!0),t||this._listeningPopState||(window.addEventListener("popstate",this._onPopState),this._listeningPopState=!0),this._resolveConnectedCallback?.()}disconnectedCallback(){this._initializing&&(this._disconnectedDuringInit=!0),this._listeningNavigate&&(Nm()?.removeEventListener("navigate",this._onNavigate),this._listeningNavigate=!1),this._listeningPopState&&(window.removeEventListener("popstate",this._onPopState),this._listeningPopState=!1),null!==this._a11yRegion&&(this._a11yRegion.remove(),this._a11yRegion=null)}}const Wm=["title","rel","target","download","hreflang","lang","dir"];class Dm extends HTMLElement{static get observedAttributes(){return["to",...Wm]}_childNodeArray=[];_uuid=kp();_path="";_router=null;_anchorElement=null;_initialized=!1;_onClick;constructor(){super()}get uuid(){return this._uuid}get router(){if(this._router)return this._router;const t=this.closest(xp.router);if(t)return this._router=t;const e=this.getRootNode(),n=e.querySelector?.(xp.router);if(n)return this._router=n;Ip(`${xp.link} is not connected to a router.`)}_initialize(){this.style.display="none",this._childNodeArray=Array.from(this.childNodes),this._path=this.getAttribute("to")||"",this._initialized=!0}_normalizePathname(t){return am(t)}_joinInternalPath(t,e){const n=cm(t),o=e.startsWith("/")?e:"/"+e,s=this._normalizePathname(o);return n?"/"===s?n+"/":n+s:s}_isInternalTarget(t){return t.startsWith("/")||t.startsWith("?")}_setAnchorHref(t,e){if(this._isInternalTarget(e)){const{pathname:n,search:o,hash:s}=km(e),r=""===n?window.location.pathname:this._joinInternalPath(this.router.basename,n);t.href=r+Im(o)+s}else try{t.href=new URL(e).toString()}catch{Ip(`[${xp.link}] Invalid URL in 'to' attribute: ${e}`)}}connectedCallback(){Em()?queueMicrotask(()=>{this.isConnected&&this._connect()}):this._connect()}_findSsrAnchor(){const t=this.nextElementSibling;return null!==t&&"A"===t.tagName&&t.hasAttribute(Tm)?t:null}_connect(){this._initialized||this._initialize();const t=this.parentNode;if(!t)return;const e=this._findSsrAnchor();let n;if(null!==e)n=e,n.removeAttribute(Tm),this._childNodeArray=Array.from(n.childNodes),this._setAnchorHref(n,this._path);else{const e=this.nextSibling;n=document.createElement("a"),this._setAnchorHref(n,this._path);for(const t of Array.from(this.attributes))(t.name.startsWith("aria-")||Wm.includes(t.name))&&n.setAttribute(t.name,t.value);for(const t of this._childNodeArray)n.appendChild(t);e?t.insertBefore(n,e):t.appendChild(n)}if(this._anchorElement=n,Em())return this._updateActiveState(),void n.setAttribute(Tm,"");Nm()?.addEventListener("currententrychange",this._updateActiveState),window.addEventListener("wcs:navigate",this._updateActiveState),window.addEventListener("popstate",this._updateActiveState),this._isInternalTarget(this._path)&&!Nm()?.navigate&&(this._onClick=async t=>{t.defaultPrevented||0===t.button&&(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||this._isInternalTarget(this._path)&&(t.preventDefault(),await this.router.navigate(this._path),this._updateActiveState()))},n.addEventListener("click",this._onClick)),this._updateActiveState()}disconnectedCallback(){Nm()?.removeEventListener("currententrychange",this._updateActiveState),window.removeEventListener("wcs:navigate",this._updateActiveState),window.removeEventListener("popstate",this._updateActiveState);const t=this._anchorElement;t&&(this._onClick&&(t.removeEventListener("click",this._onClick),this._onClick=void 0),t.remove(),this._anchorElement=null);for(const e of this._childNodeArray)t&&e.parentNode===t&&t.removeChild(e);this._router=null}attributeChangedCallback(t,e,n){if("to"===t&&e!==n)this._path=n||"",this._anchorElement&&(this._setAnchorHref(this._anchorElement,this._path),this._updateActiveState());else if(Wm.includes(t)){const e=this._anchorElement;e&&(null===n?e.removeAttribute(t):e.setAttribute(t,n))}}_updateActiveState=()=>{this._path.startsWith("?")&&this._anchorElement&&this._setAnchorHref(this._anchorElement,this._path);const t=this._normalizePathname(new URL(window.location.href).pathname),{pathname:e}=km(this._path),n=this._normalizePathname(this._isInternalTarget(this._path)?""===e?window.location.pathname:this._joinInternalPath(this.router.basename,e):e);this._anchorElement&&(t===n?(this._anchorElement.classList.add("active"),this._anchorElement.setAttribute("aria-current","page")):(this._anchorElement.classList.remove("active"),this._anchorElement.removeAttribute("aria-current")))};get anchorElement(){return this._anchorElement}}const zm=[],Bm=new Map;let Fm=!1;const Hm=new WeakMap;class qm extends HTMLElement{_initialized=!1;_childElementArray=[];constructor(){super(),this.style.display="none"}_initialize(){if(!this._initialized){this._initialized=!0,this._childElementArray=Array.from(this.children);for(const t of this._childElementArray)this.removeChild(t)}}connectedCallback(){this._initialize(),Fm||(this._captureInitialHead(),Fm=!0),zm.push(this),this._reapplyHead()}disconnectedCallback(){const t=zm.indexOf(this);-1!==t&&zm.splice(t,1),this._reapplyHead()}get childElementArray(){return this._initialized||Ip("Head component is not initialized yet."),this._childElementArray}_getKey(t){const e=Hm.get(t);if(void 0!==e)return e;const n=this._computeKey(t);return Hm.set(t,n),n}_computeKey(t){const e=t.tagName.toLowerCase();if("title"===e)return"title";if("meta"===e)return`meta:${t.getAttribute("name")||""}:${t.getAttribute("property")||""}:${t.getAttribute("http-equiv")||""}:${t.hasAttribute("charset")?"charset":""}:${t.getAttribute("media")||""}`;if("link"===e)return`link:${t.getAttribute("rel")||""}:${t.getAttribute("href")||""}:${t.getAttribute("media")||""}:${t.getAttribute("hreflang")||""}`;if("base"===e)return"base";if("script"===e){const e=t.getAttribute("src")||"",n=t.getAttribute("id")||"",o=t.getAttribute("type")||"";return e||n?`script:${e}:${n}:${o}`:`script::${o}:${t.outerHTML.slice(0,100)}`}if("style"===e){const e=t.getAttribute("id")||"",n=t.getAttribute("media")||"";return e?`style:${e}:${n}`:`style::${n}:${t.outerHTML.slice(0,100)}`}return`${e}:${t.outerHTML.slice(0,100)}`}_buildHeadElementMap(){const t=new Map;for(const e of Array.from(document.head.children)){const n=this._getKey(e);t.has(n)||t.set(n,e)}return t}_captureInitialHead(){const t=document.head;for(const e of Array.from(t.children)){const t=this._getKey(e);Bm.has(t)||Bm.set(t,e.cloneNode(!0))}}_reapplyHead(){const t=new Set;for(const e of zm)for(const n of e._childElementArray)t.add(this._getKey(n));for(const e of Bm.keys())t.add(e);const e=this._buildHeadElementMap();for(const n of e.keys())t.add(n);for(const n of t){let t=null;for(let e=zm.length-1;e>=0;e--){const o=zm[e];for(const e of o._childElementArray)if(this._getKey(e)===n){t=e.cloneNode(!0);break}if(t)break}!t&&Bm.has(n)&&(t=Bm.get(n).cloneNode(!0));const o=e.get(n)??null;t?(o?o.replaceWith(t):document.head.appendChild(t),e.set(n,t),wm(t)||$m(t,`<${t.tagName.toLowerCase()}> inside <${xp.head}>`,`<${xp.head}> reflects its children into <head> with cloneNode, so the clone is not the node that was bound. Load @wcstack/state on this page, or write the value statically here.`)):(o?.remove(),e.delete(n))}}}await void function(t=customElements){t.get(xp.layout)||t.define(xp.layout,Hp),t.get(xp.layoutOutlet)||t.define(xp.layoutOutlet,Kp),t.get(xp.outlet)||t.define(xp.outlet,qp),t.get(xp.route)||t.define(xp.route,Lp),t.get(xp.router)||t.define(xp.router,jm),t.get(xp.link)||t.define(xp.link,Dm),t.get(xp.head)||t.define(xp.head,qm)}(void 0);const Um="data-fetchtarget",Gm={fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"};let Vm=class{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,n={}){this.laneKey=t,this.policy=e,this._withSignal=n.withSignal??!1,this._trace=n.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,n={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(n),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const o=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:n,attempt:o}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const n=e+1;this._attempts.set(t.operationId,n),this._releaseController(t.operationId);const o=this._makeAttempt(t.operationId,n);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:n}),o}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&!this._terminal.has(t.operationId)&&!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,n=this._terminal.get(e);if(void 0!==n&&"committing"!==n)return;let o;o="committing"===n?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,o),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===o?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:o}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let n;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),n=e.signal}return{operationId:t,attempt:e,signal:n}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}};function Km(t,e){return e.every(e=>"available"===t.availability.get(e))}const Jm=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);let Qm=class t extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new Vm("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return Km(this.platformAssessment,t.REQUIRED_CAPABILITIES)}get platformAssessment(){return function(t,e){const n=new Map,o=e=>{const n=t.get(e);return void 0===n?"unknown":n.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=o(t);n.set(t,e),"available"!==e&&(s=!1)}let r=!0;for(const t of e.optional??[]){const e=o(t);n.set(t,e),"available"!==e&&(r=!1)}const i=s?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),u=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",d=c?"required":"not-applicable";return{availability:n,permission:e.permission??"not-applicable",readiness:i,activity:e.activity??"inactive",preconditions:{secureContext:u,userActivation:d},epoch:e.epoch??0,lastError:e.lastError}}(Jm,{required:t.REQUIRED_CAPABILITIES,optional:t.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,n,o,s){this._commitErrorInfo({code:t,phase:e,recoverable:n,message:o,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,n=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=n,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:n},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(e,n={}){if(!e)return this._setErrorInfo("invalid-argument","start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const o=this.platformAssessment;if(!Km(o,t.REQUIRED_CAPABILITIES)){const e=t.REQUIRED_CAPABILITIES.find(t=>"available"!==o.availability.get(t));return this._setErrorInfo("capability-missing","start",!1,`Required capability "${e}" is unavailable.`,e),this._setError({message:`Required capability "${e}" is unavailable.`}),null}const s=this._doFetch(e,n);return this._promise=s,s}async _doFetch(t,e){const n=this._lane.begin(),{ticket:o,attempt:s}=n,r=s.signal;this._commitStep(o,()=>this._setLoading(!0)),this._commitStep(o,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:i="GET",body:a=null,contentType:l=null,forceText:c=!1,responseType:u="auto",timeout:d=0}=e;let h=null;d>0&&(h=setTimeout(()=>{if(!this._lane.claimTerminal(o,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(o,()=>{this._setErrorInfo("timeout","execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),this._lane.abort(o),this._lane.finalize(o)},d));const f={...e.headers??{}};try{l&&!f["Content-Type"]&&(f["Content-Type"]=l);const e={method:i,headers:f,signal:r};"GET"!==i&&"HEAD"!==i&&null!==a&&(e.body=a);const n=await globalThis.fetch(t,e);let s=null;if("HEAD"===i);else if(n.ok)if(c)s=await n.text();else if("blob"===u)s=await n.blob();else if("arrayBuffer"===u)s=await n.arrayBuffer();else if("text"===u)s=await n.text();else if("json"===u)s=await n.json();else{const t=n.headers.get("Content-Type")||"";s=t.includes("application/json")?await n.json():await n.text()}if(!n.ok){const t=await n.text().catch(()=>""),e={status:n.status,statusText:n.statusText,body:t};return this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{this._setErrorInfo("http-error","execute",!0,`HTTP ${n.status} ${n.statusText}`),this._setError(e)}),this._commitStep(o,()=>this._setResponse(null,n.status)),this._commitStep(o,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(o,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(o,()=>this._setResponse(s,n.status,d)),this._commitStep(o,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(o,"aborted")&&this._commitStep(o,()=>this._setLoading(!1)),null):this._lane.claimTerminal(o,"error")?(this._commitStep(o,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo("network","execute",!0,e),this._setError(t??{message:e})}),this._commitStep(o,()=>this._setResponse(null,0)),this._commitStep(o,()=>this._setLoading(!1)),null):null}finally{null!==h&&clearTimeout(h),this._lane.finalize(o)}}},Xm=!1;function Ym(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${Um}]`);if(!n)return;const o=n.getAttribute(Um);if(!o)return;const s=customElements.get(Gm.fetch),r=document.getElementById(o);if(!(s&&r instanceof s))return;const i=r;i.url&&(t.preventDefault(),i.fetch())}function Zm(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}const tg=Symbol.for("wcstack.trustedTypes.policy");function eg(){const t=globalThis[tg];return null===t||"object"!=typeof t?null:t}let ng,og=!1;let sg=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...Qm.wcBindable,properties:[...Qm.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new Qm(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(Gm.fetchHeader);for(const n of e){const e=n.headerName,o=n.headerValue;e&&(t[e]=o)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(Gm.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:n,contentType:o}=this._collectBody(e);n instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:n,contentType:o,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&function(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=eg(),n=e?.createHTML;return"function"!=typeof n?t:n.call(e,t)}(e)}catch(t){if(function(){if(void 0!==ng)return ng;if(!("trustedTypes"in globalThis))return ng=!1,ng;try{document.createElement("div").innerHTML="<i></i>",ng=!1}catch{ng=!0}return ng}())return void function(){if(og)return;og=!0;const t="function"==typeof eg()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}(t,s)}return s}attributeChangedCallback(t,e,n){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!Zm(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",Xm||(Xm=!0,document.addEventListener("click",Ym)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}};class rg extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class ig extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}let ag=class extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof sg&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}};!function(t=customElements){t.get(Gm.fetch)||t.define(Gm.fetch,sg),t.get(Gm.fetchHeader)||t.define(Gm.fetchHeader,rg),t.get(Gm.fetchBody)||t.define(Gm.fetchBody,ig),t.get(Gm.infiniteScroll)||t.define(Gm.infiniteScroll,ag)}(void 0);const lg="data-storagetarget",cg={storage:"wcs-storage"},ug="wcs-storage:value-changed",dg="wcs-storage:loading-changed",hg="wcs-storage:error",fg="wcs-storage:error-info-changed",pg="wcs-storage:trigger-changed";let mg=class extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:ug,semantics:"state",getter:t=>t.detail},{name:"loading",event:dg,semantics:"state"},{name:"error",event:hg,semantics:"state"},{name:"errorInfo",event:fg,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(t){Object.is(t,this._value)||this._setValue(t)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(t){this._key=String(t)}get type(){return this._type}set type(t){"local"===t||"session"===t?this._type=t:this._setError({operation:"type",message:`Invalid storage type: "${t}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent(dg,{detail:t,bubbles:!0}))}_setError(t,e){this._error!==t&&(this._error=t,this._commitErrorInfo(null===t?null:function(t,e){return void 0===e?{code:"invalid-argument",phase:"start",recoverable:!1,message:t.message}:"QuotaExceededError"===e?{code:"quota-exceeded",phase:"execute",recoverable:!0,message:t.message}:"SecurityError"===e?{code:"not-allowed",phase:"execute",recoverable:!1,message:t.message}:{code:"storage-error",phase:"execute",recoverable:!0,message:t.message}}(t,e)),this._target.dispatchEvent(new CustomEvent(hg,{detail:t,bubbles:!0})))}_commitErrorInfo(t){this._errorInfo=t,this._target.dispatchEvent(new CustomEvent(fg,{detail:t,bubbles:!0}))}_toStorageError(t,e){return{operation:t,message:e instanceof Error?e.message:String(e)}}_errName(t){return t instanceof Error?t.name:""}_setValue(t){this._value=t,this._target.dispatchEvent(new CustomEvent(ug,{detail:t,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const t=this._getStorage().getItem(this._key);if(null===t)this._setValue(null);else try{this._setValue(JSON.parse(t))}catch{this._setValue(t)}return this._setLoading(!1),this._value}catch(t){return this._setError(this._toStorageError("load",t),this._errName(t)),this._setLoading(!1),null}}save(t){if(this._key){this._setLoading(!0),this._setError(null);try{const e=this._getStorage();null==t?(e.removeItem(this._key),this._setValue(null)):"string"==typeof t?(e.setItem(this._key,t),this._setValue(t)):(e.setItem(this._key,JSON.stringify(t)),this._setValue(t)),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("save",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(t){this._setError(this._toStorageError("remove",t),this._errName(t)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const t=++this._gen;this._storageListener=e=>{if(t===this._gen&&e.key===this._key&&"session"!==this._type)if(this._setError(null),null===e.newValue)this._setValue(null);else try{this._setValue(JSON.parse(e.newValue))}catch{this._setValue(e.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}},gg=!1;function yg(t){const e=t.target;if(!(e instanceof Element))return;const n=e.closest(`[${lg}]`);if(!n)return;const o=n.getAttribute(lg);if(!o)return;const s=customElements.get(cg.storage),r=document.getElementById(o);s&&r instanceof s&&(t.preventDefault(),r.save())}function bg(t,e){let n=Object.getPrototypeOf(t);for(;null!==n;){const t=Object.getOwnPropertyDescriptor(n,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;n=Object.getPrototypeOf(n)}return!1}let wg=class extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...mg.wcBindable,properties:[...mg.wcBindable.properties,{name:"trigger",event:pg,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new mg(this),this._internals=this._initInternals(),this._wireStates({[dg]:t=>({loading:!0===t}),[hg]:t=>({error:null!=t})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[n,o]of Object.entries(t))this.addEventListener(n,t=>{const n=this.hasAttribute("debug-states");for(const[s,r]of Object.entries(o(t.detail))){try{r?e.add(s):e.delete(s)}catch{}n&&this.toggleAttribute(`data-wcs-state-${s}`,r)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(t){this.setAttribute("key",t)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(t){this.setAttribute("type",t)}get value(){return this._core.value}set value(t){this.manual?this._core.value=t:(this._syncCore(),this._core.save(t))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(t){if(t){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(pg,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(t,e,n){this.isConnected&&("key"===t&&(this._syncCore(),n&&!this.manual&&this.load()),"type"===t&&this._syncCore())}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,n=e?.inputs;if(void 0!==n)for(const e of n){const n=e.name;if(!Object.prototype.hasOwnProperty.call(t,n))continue;if(!bg(t,n))continue;const o=t,s=o[n];delete o[n],o[n]=s}}(this),this.style.display="none",gg||(gg=!0,document.addEventListener("click",yg)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}};!function(t=customElements){t.get(cg.storage)||t.define(cg.storage,wg)}(void 0);const vg="*",_g="vanilla",$g={scanImportmap:!0,loaders:{[_g]:{postfix:".js",loader:async function(t){return(await(import(`${t}`))).default}},[vg]:_g},observable:!0,tagNames:{autoloader:"wcs-autoloader"}};function Sg(t){if(t.startsWith("@components/")){if(t.endsWith("/")){const e=t.slice(12,t.length-1),[n,o]=e.split("|",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,prefix:n.replaceAll("/","-").toLowerCase(),loaderKey:o??null,isNameSpaced:!0}}{const e=t.slice(12),[n,o]=e.split("|",2),[s,r]=(o??"").split(",",2);if(""===n)throw new Error("Invalid importmap key: "+t);return{key:t,tagName:n.replaceAll("/","-").toLowerCase(),loaderKey:s||null,extends:r||null,isNameSpaced:!1}}}return null}function xg(t,e,n){let o;if(null===e||e===vg||""===e){let e=null;const s=[];for(const[t,e]of Object.entries(n)){if(t===vg)continue;const o="string"==typeof e?n[e]:e;"string"!=typeof o&&s.push(o)}s.sort((t,e)=>e.postfix.length-t.postfix.length);for(const n of s)if(t.endsWith(n.postfix)){e=n;break}e?o=e:(o=n[vg],"string"==typeof o&&(o=n[o]))}else if(o=n[e],!o)throw new Error("Loader not found: "+e);if("string"==typeof o)throw new Error("Loader redirection is not supported here");return o}const Pg=new Set,Ng=new Map;let kg=new WeakMap;function Ig(t){if(t===globalThis.customElements)return Ng;let e=kg.get(t);return void 0===e&&(e=new Map,kg.set(t,e)),e}const Ag=new Map;async function Eg(t,e,n){try{if(customElements.get(e))return;const o=await n.loader(t.key);if(null!==o){let n=t.extends;if(null===n&&(n=function(t){for(const[e,n]of Ag)if(t.prototype instanceof e)return n;return null}(o)),customElements.get(e))return;null===n?customElements.define(e,o):customElements.define(e,o,{extends:n})}}catch(t){Pg.has(e)||(console.error(`Failed to eager load component '${e}':`,t),Pg.add(e))}}function Cg(t){if("object"!=typeof t||null===t)return null;const e=t;return"function"!=typeof e.get||"function"!=typeof e.whenDefined||"function"!=typeof e.define?null:e}function Tg(t){const e=t.tagName.toLowerCase();let n,o;if(e.includes("-"))n=e,o=null;else{const s=t.getAttribute("is");if(null===s)throw new Error("Custom element without a dash or 'is' attribute found: "+e);if(!s.includes("-"))throw new Error("Custom element 'is' attribute without a dash found: "+e);n=s,o=e}return{name:n,extends:o}}"undefined"!=typeof window&&[[HTMLButtonElement,"button"],[HTMLInputElement,"input"],[HTMLAnchorElement,"a"],[HTMLImageElement,"img"],[HTMLDivElement,"div"],[HTMLSpanElement,"span"],[HTMLParagraphElement,"p"],[HTMLUListElement,"ul"],[HTMLOListElement,"ol"],[HTMLLIElement,"li"],[HTMLTableElement,"table"],[HTMLFormElement,"form"],[HTMLLabelElement,"label"],[HTMLSelectElement,"select"],[HTMLTextAreaElement,"textarea"],[HTMLHeadingElement,"h1"],[HTMLQuoteElement,"blockquote"],[HTMLPreElement,"pre"],[HTMLBRElement,"br"],[HTMLHRElement,"hr"],[HTMLModElement,"ins"],[HTMLTableCaptionElement,"caption"],[HTMLTableColElement,"col"],[HTMLTableSectionElement,"tbody"],[HTMLTableRowElement,"tr"],[HTMLTableCellElement,"td"],[HTMLFieldSetElement,"fieldset"],[HTMLLegendElement,"legend"],[HTMLDListElement,"dl"],[HTMLOptGroupElement,"optgroup"],[HTMLOptionElement,"option"],[HTMLStyleElement,"style"],[HTMLScriptElement,"script"],[HTMLTemplateElement,"template"],[HTMLCanvasElement,"canvas"],[HTMLIFrameElement,"iframe"],[HTMLObjectElement,"object"],[HTMLEmbedElement,"embed"],[HTMLVideoElement,"video"],[HTMLAudioElement,"audio"],[HTMLTrackElement,"track"],[HTMLMapElement,"map"],[HTMLAreaElement,"area"],[HTMLSourceElement,"source"],[HTMLParamElement,"param"],[HTMLMeterElement,"meter"],[HTMLProgressElement,"progress"],[HTMLOutputElement,"output"],[HTMLDetailsElement,"details"],[HTMLDialogElement,"dialog"],[HTMLMenuElement,"menu"],[HTMLSlotElement,"slot"],[HTMLTimeElement,"time"],[HTMLDataElement,"data"],[HTMLPictureElement,"picture"]].forEach(([t,e])=>{void 0!==t&&Ag.set(t,e)});const Mg=new WeakSet,Og=new WeakSet;async function Lg(t,e,n){t.shadowRoot&&(Mg.has(t)||await async function(t,e,n){Mg.add(t),await Dg(t.shadowRoot,e,n)}(t,e,n))}async function Rg(t,e,n,o){const s=function(t,e){for(const[n,o]of Object.entries(e))if(t.startsWith(n+"-"))return o;return null}(t.name,n);if(null===s)throw new Error("No matching namespace found for lazy loaded component: "+t.name);const r=Ig(o),i=r.get(t.name);if(void 0!==i)return void await i;const a=async function(t,e,n,o){try{let s;try{s=xg("",n.loaderKey,e.loaders)}catch(e){throw new Error("Loader redirection is not supported for lazy loaded components: "+t.name)}const r=t.name.slice(n.prefix.length+1);if(""===r)throw new Error("Invalid component name for lazy loaded component: "+t.name);const i=n.key+r+s.postfix;if(o.get(t.name))return;const a=await s.loader(i);if(null===a)throw new Error("Loader returned null for component: "+t.name);if(o.get(t.name))return;null===t.extends?o.define(t.name,a):o.define(t.name,a,{extends:t.extends})}catch(e){console.error(`Failed to lazy load component '${t.name}':`,e),Pg.add(t.name)}}(t,e,s,o);r.set(t.name,a);try{await a}finally{r.delete(t.name)}}async function jg(t,e,n,o){const s=[],r=(t.ownerDocument??t).createTreeWalker(t,NodeFilter.SHOW_ELEMENT,t=>(t=>(t instanceof Element&&(t.tagName.includes("-")||t.getAttribute("is")?.includes("-")))??!1)(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP);for(;r.nextNode();)s.push(r.currentNode);const i=[],a=new Set;for(const t of s){const s=Tg(t);void 0===o.get(s.name)?(Og.has(t)||(Og.add(t),o.whenDefined(s.name).then(async()=>{await Lg(t,e,n)})),a.has(s.name)||Pg.has(s.name)||(a.add(s.name),i.push(s))):await Lg(t,e,n)}let l=0;for(const t of i)await Rg(t,e,n,o),l++;return l}async function Wg(t,e,n,o){for(;await jg(t,e,n,o)>0;);}async function Dg(t,e,n){if(0===Object.keys(n).length)return null;const o=function(t=null){if(null!=t){const e=t.customElementRegistry;if(null===e)return null;if(void 0!==e)return Cg(e)}return Cg(globalThis.customElements)}(t);if(null===o)return console.error("Cannot autoload components: the root has a null custom element registry."),null;try{await Wg(t,e,n,o)}catch(t){throw new Error("Failed to lazy load components: "+t)}if(!e.observable)return null;const s=new MutationObserver(async()=>{try{await Wg(t,e,n,o)}catch(t){console.error("Failed to lazy load components: "+t)}});return s.observe(t,{childList:!0,subtree:!0}),s}class zg extends HTMLElement{static _instance=null;_initialized=!1;_prefixMap=null;_observer=null;constructor(){if(super(),zg._instance)throw new Error(`${$g.tagNames.autoloader} can only be instantiated once.`);zg._instance=this;const t=function(){const t={imports:{}};return document.querySelectorAll('script[type="importmap"]').forEach(e=>{try{const n=JSON.parse(e.innerHTML);n.imports&&(t.imports=Object.assign(t.imports,n.imports))}catch(t){throw new Error("Failed to parse importmap JSON: "+t)}}),Object.keys(t.imports).length>0?t:null}();if(t){const{prefixMap:e,loadMap:n}=function(t){const e={},n={};for(const[o,s]of Object.entries(t.imports)){const t=Sg(o);null!==t&&(t.isNameSpaced?e[t.prefix]=t:n[t.tagName]=t)}return{prefixMap:e,loadMap:n}}(t);this._prefixMap=e,async function(t,e){const n=[];for(const[o,s]of Object.entries(t)){let r;try{r=xg(s.key,s.loaderKey,e)}catch(t){throw new Error("Loader redirection is not supported for eager loaded components: "+o)}n.push(Eg(s,o,r))}await Promise.all(n)}(n,$g.loaders).catch(t=>{console.error("Failed to eager load components:",t)})}}async connectedCallback(){this._initialized||(this._initialized=!0,this._prefixMap&&("loading"===document.readyState&&await new Promise(t=>document.addEventListener("DOMContentLoaded",()=>t(),{once:!0})),this._observer=await Dg(document,$g,this._prefixMap)))}disconnectedCallback(){this._observer?.disconnect(),this._observer=null,zg._instance===this&&(zg._instance=null)}}!function(t=customElements){t.get($g.tagNames.autoloader)||t.define($g.tagNames.autoloader,zg)}(void 0);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|